Compare commits

..
Author SHA1 Message Date
Alexandre Teixeira 1cb597ce12 fix(editor): synchronize quick edit model events and register imagePreferences in test coordinator 2026-10-31 12:43:04 +00:00
Alexandre Teixeira 54b734032c docs(editor): add desktop and mobile visual validation evidence 2026-10-31 12:17:02 +00:00
Alexandre Teixeira aea1317ade Merge remote-tracking branch 'origin/dev' into fix/editor-followups-20261030
Reconcile branch with current dev (bebf53be).
Resolve conflicts in static/sw.js (bump cache version and preserve panel precache)
and src/ai_interaction.py (preserve upstream quality handling with per-user settings).

Remediate PR #6992 findings:
- A (CI & Playwright): Pin playwright==1.62.0 in requirements-dev and CI workflow; guard browser test imports against pytest runner collection failure.
- B (Per-User Image Model Settings): Support per-user image_model and image_edit_model in editor_image_models() and ai_interaction; enable non-admin preference persistence via /api/prefs fallback.
- C (CodeQL Regex Alert 1212): Replace polynomial-backtracking regex in routes/editor_agent_routes.py with linear token-based intent matcher.
- D (Undo/Redo rembg layer): Clear stale rembgLiveLayer and rembgLiveSnap references in _restoreState() to prevent edge tuner from corrupting detached layers.
2026-10-31 12:14:12 +00:00
nopoz bebf53be3c fix(agent): make preview and browser output parsers linear (#7003)
Six regexes over tool output backtracked polynomially on long whitespace
runs or repeated openers: the browser snapshot generic-line filter and
post-interaction split, the task-row and skill-bullet parsers, the email
"no results" check, and the Google /sorry/ interstitial check.

Rewrite each without overlapping quantifiers, keeping the same matches for
the text these tools emit. Move the /sorry/ check into
is_google_sorry_url() so it can be tested.
2026-10-30 22:46:19 -07:00
Alexandre Teixeira a8e0ff1c8e Merge pull request #6998 from odysseus-dev/maintainer/fix-6546-scientific-data
fix(llm): support scientific and decimal literals in degenerate guard
2026-10-31 02:43:09 +00:00
Alexandre Teixeira 31685b050a fix(llm): support scientific and decimal literals in degenerate guard
Preserve complete scientific notation and signed floating-point literals across
arbitrary streaming chunk boundaries in _DegenerateStreamGuard. Buffer pending
tokens until delimiter characters arrive to avoid splitting numbers into
incomplete or arbitrary alphanumeric tokens, while maintaining the 2048-number
runaway backstop and detection of repeated phrases and word loops.
2026-10-30 20:45:09 +00:00
Alexandre Teixeira 03d25943ee Merge pull request #6993 from odysseus-dev/perf/editor-cursor-style-invalidation
perf(editor): avoid brush cursor style invalidation
2026-10-30 20:09:16 +00:00
Alexandre Teixeira 71e3649985 Merge pull request #6947 from redpersongpt/codex/compare-stream-contract
fix(compare): reject incomplete and errored SSE responses
2026-10-30 19:47:28 +00:00
Alexandre Teixeira 45a57c0c38 Merge pull request #6911 from redpersongpt/codex/nested-window-close
fix(ui): return to the parent view when closing an item
2026-10-30 19:47:11 +00:00
Alexandre Teixeira 71f6dc4e5d Merge pull request #6912 from redpersongpt/codex/email-linkify-single-pass
fix(email): linkify URLs and addresses without rewriting anchors
2026-10-30 19:46:54 +00:00
Alexandre Teixeira 0c8a06a937 Merge pull request #6943 from redpersongpt/codex/chat-edit-textarea-content
fix(chat): size user-message editors from wrapped content
2026-10-30 19:46:37 +00:00
Alexandre Teixeira eea39ce103 Merge pull request #6934 from redpersongpt/codex/skill-editor-load-guard
fix(skills): wait for source before enabling the editor
2026-10-30 19:46:21 +00:00
Alexandre Teixeira 9a5a15e17f Merge pull request #6932 from redpersongpt/codex/skill-editor-source-height
fix(skills): size the raw editor from its source lines
2026-10-30 19:46:04 +00:00
Alexandre Teixeira f141ad2be5 Merge pull request #6919 from redpersongpt/codex/memory-panel-refresh
fix(memory): refresh records when opening the panel
2026-10-30 19:45:47 +00:00
Alexandre Teixeira a6e9294394 Merge pull request #6918 from redpersongpt/codex/memory-stale-category
fix(memory): reset category filter when its last entry disappears
2026-10-30 19:45:30 +00:00
Alexandre Teixeira cfbe4aeca4 Merge pull request #6915 from redpersongpt/codex/image-quality-explicit-default
fix(images): preserve explicit medium quality requests
2026-10-30 19:45:13 +00:00
Alexandre Teixeira 6f0679bb25 Merge pull request #6253 from VykosMolt/fix/generate-image-native-schema-5520
fix(tools): reject generate_image calls without a prompt
2026-10-30 19:44:56 +00:00
Alexandre Teixeira 93c93bf076 Merge pull request #6748 from dxrpl/fix/6747-recipe-panel-toggle
fix(cookbook): bring back the Dependencies recipe-panel caret (#6747)
2026-10-30 19:44:39 +00:00
Alexandre Teixeira f0f7464dfa Merge pull request #6952 from redpersongpt/codex/mail-cli-date-order
fix(mail): sort CLI message batches by UTC date
2026-10-30 19:44:23 +00:00
Alexandre Teixeira 1e57f774d3 Merge pull request #6913 from redpersongpt/codex/font-compound-style-family
fix(fonts): group compound weight and style variants by family
2026-10-30 19:44:07 +00:00
Alexandre Teixeira 2b310010cf Merge pull request #6930 from redpersongpt/codex/stale-hf-cache-markers
fix(cookbook): ignore empty markers beside completed blobs
2026-10-30 19:43:50 +00:00
Alexandre Teixeira b88154ecf9 Merge pull request #6730 from dxrpl/fix/hwfit-hf-param-count
fix(hwfit): keep the MoE active size for HF collection models (#6729)
2026-10-30 19:43:34 +00:00
Alexandre Teixeira e7796f71d3 Merge pull request #6890 from redpersongpt/codex/checkin-calendar-window-boundaries
fix(checkin): avoid duplicate calendar events at window boundaries
2026-10-30 19:43:18 +00:00
Alexandre Teixeira 412789051e Merge pull request #6585 from robyroro/codex/notes-clear-fields
fix(notes): persist removal of optional note fields
2026-10-30 19:43:01 +00:00
Alexandre Teixeira b8adc4eb60 Merge pull request #6904 from dxrpl/fix/calendar-config-object-body
fix(calendar): answer 400 when a CalDAV config body is not a JSON object (#6903)
2026-10-30 19:42:45 +00:00
Alexandre Teixeira 2246215b79 Merge pull request #6906 from dxrpl/fix/more-validation
fix(api): answer 400 for a malformed body on integrations and document export-zip (#6905)
2026-10-30 19:42:28 +00:00
Alexandre Teixeira 06fee0a3d8 Merge pull request #6546 from harshit-ojha0324/fix/degenerate-guard-numeric-data
fix(llm): stop the repeat guard from cutting off numeric data
2026-10-30 19:41:03 +00:00
Alexandre Teixeira f3813c261c perf(editor): avoid brush cursor style invalidation 2026-10-30 19:27:58 +00:00
Alexandre Teixeira e7a376b161 Merge pull request #6950 from redpersongpt/codex/group-peer-history-identity
fix(group): preserve peer identity when reloading history
2026-10-30 19:03:48 +00:00
Alexandre Teixeira fec2bb11d6 Merge pull request #6951 from redpersongpt/codex/gallery-cli-tag-filters
fix(gallery): match stacked CLI filters against AI tags
2026-10-30 19:03:01 +00:00
Alexandre Teixeira c811f76d44 Merge pull request #6935 from redpersongpt/codex/email-paperclip-files
fix(email): retain files in attachment and inline-image pickers
2026-10-30 19:02:22 +00:00
Alexandre Teixeira 02d28c06d0 Merge pull request #6888 from redpersongpt/codex/skill-version-preservation
fix(skills): preserve version strings across markdown saves
2026-10-30 19:01:47 +00:00
Alexandre Teixeira 00ecf1c74e Merge pull request #6819 from dxrpl/fix/6818-image-routes-bad-input
fix(gallery): answer 400 for a missing or invalid image on the image-edit routes (#6818)
2026-10-30 19:01:11 +00:00
Alexandre Teixeira 63feb227bb Merge pull request #6732 from dxrpl/fix/hwfit-skip-non-llm-collection-models
fix(hwfit): keep non-LLM HF collection models out of the LLM catalog (#6731)
2026-10-30 19:00:33 +00:00
Alexandre Teixeira 12fcddefab Merge pull request #6891 from redpersongpt/codex/pdf-form-unicode-field-names
fix(forms): preserve Unicode field names during PDF export
2026-10-30 18:59:47 +00:00
Alexandre Teixeira b46aa02ce1 Merge pull request #6954 from redpersongpt/codex/discovery-valid-model-ids
fix(models): retain valid discovery IDs beside malformed rows
2026-10-30 18:58:55 +00:00
Alexandre Teixeira 352ee706f3 Merge pull request #6825 from dxrpl/fix/6824-cron-five-fields
fix(tasks): refuse cron expressions with a seconds field (#6824)
2026-10-30 18:58:03 +00:00
Alexandre Teixeira 98b359cd4c Merge pull request #6982 from odysseus-dev/test/remediation-notes-process-cleanup
perf(tests): close owned Notes descendants before draining output
2026-10-30 18:53:34 +00:00
Alexandre Teixeira 2a2256af0e Merge pull request #6979 from odysseus-dev/test/remediation-static-contract-sensitivity
test: restore shadowed editor assertions and require effective procfs guards
2026-10-30 18:52:46 +00:00
Alexandre Teixeira 4f131d7c21 Merge branch 'dev' into test/remediation-notes-process-cleanup 2026-10-30 18:33:52 +00:00
Alexandre Teixeira 945e747eb4 Merge branch 'dev' into test/remediation-static-contract-sensitivity 2026-10-30 18:33:48 +00:00
Alexandre Teixeira 61051d28f0 Merge pull request #6996 from odysseus-dev/test/ci-python-baseline-repair
test(caldav): restore redirect positive-control coverage
2026-10-30 15:53:51 +00:00
PR #6029 Reviewer d87ae2a7f5 test(caldav): restore redirect positive-control coverage 2026-10-30 15:35:37 +00:00
Alexandre Teixeira 0e49c4ef40 Merge pull request #6978 from odysseus-dev/test/remediation-false-green-oracles
test: reject vacuous success in email, bridge, auth and deletion tests
2026-10-30 15:25:10 +00:00
Alexandre Teixeira 1aff71836b Merge pull request #6611 from robyroro/fix/chat-tidy-preserve-content
fix(chats): preserve saved conversations during tidy
2026-10-30 15:09:09 +00:00
Alexandre Teixeira b1c3125865 test: accept positional arguments in task endpoint mock for auto-sort 2026-10-30 15:00:08 +00:00
Alexandre Teixeira dbee1155e6 Merge pull request #6080 from alteixeira20/fix/cookbook-stale-llama-server-shim
fix(cookbook): recover from stale llama-server shims
2026-10-30 14:13:15 +00:00
Alexandre Teixeira 56c7cdf804 Merge pull request #6544 from harshit-ojha0324/fix/mcp-http-connect-leak
fix(mcp): close the HTTP transport when a remote connect fails
2026-10-30 14:09:43 +00:00
Alexandre Teixeira fe5d5caf34 Merge pull request #6977 from odysseus-dev/test/remediation-execution-isolation
test: fix pytest schema loss across route-client threads
2026-10-30 13:59:20 +00:00
Alexandre Teixeira bb654482f3 Merge pull request #6774 from odysseus-dev/fix/ios-safe-area-postmerge-hardening
fix(ui): harden iOS viewport and safe-area behavior after #6396
2026-10-30 13:56:25 +00:00
Alexandre Teixeira f45724faed Merge pull request #6983 from odysseus-dev/test/remediation-auth-fixture-seed
perf(tests): reuse immutable auth setup with fresh per-case state
2026-10-30 13:42:10 +00:00
Alexandre Teixeira 6fc6095aec test(e2e): harden mobile layout coverage, artifact isolation, and live pane assertions
- Store Playwright evidence in ignored test-results/ paths by default while preserving env override
- Clean up disposable temporary application data directories in /tmp on global teardown and exit signals
- Add Chromium mobile and tablet viewport profiles (phone portrait/landscape, tablet) for automated coverage
- Add a scoped Chromium mobile layout CI check on shard 1/4 to prevent redundant matrix execution
- Reach mobile Settings and Notes views via genuine sidebar navigation controls opened through the hamburger button
- Add assertions against live rendered Notes and Documents panes honoring safe-area top and height constraints
- Document local WebKit prerequisites and physical iOS/PWA test limitations in tests/e2e/README.md and package.json
2026-10-30 13:41:15 +00:00
Alexandre Teixeira ef16398c5c merge(dev): integrate latest dev into fix/ios-safe-area-postmerge-hardening 2026-10-30 13:25:33 +00:00
Alexandre Teixeira 6037707430 fix(cookbook): launch validated llama-server candidate and handle PATH precedence
Ensure the native candidate that passed the health check is prioritized and executed when an earlier broken candidate exists on PATH.

Reconcile Odysseus-owned shims safely, invalidate command hash cache, and verify launchability rather than command existence before serve dispatch.

Fixes #6079
2026-10-30 13:15:40 +00:00
Alexandre Teixeira 5c542d03ac Merge remote-tracking branch 'origin/dev' into fix/pr-6080-llama-recovery 2026-10-30 13:02:47 +00:00
pewdiepie-archdaemon e79c81fbb8 fix(editor): stabilize image workflows and editing controls 2026-10-30 08:46:10 +00:00
red person 4fe8fb28e5 test: isolate photo routing from external MCP registry state 2026-10-29 23:45:05 +03:00
red person 84e232e7ee fix(cache): retain the upstream worker key format 2026-10-29 23:42:25 +03:00
red person 2cace27723 test: isolate photo routing from external MCP registry state 2026-10-29 23:40:25 +03:00
red person 508c7b3d9d Merge current dev into PR 6932 2026-10-29 23:28:45 +03:00
red person 5b8a72931d Merge current dev into PR 6934 2026-10-29 23:28:28 +03:00
red person 2e7edf908d Merge current dev into PR 6935 2026-10-29 23:27:57 +03:00
red person b80f9afb3e Merge current dev into PR 6943 2026-10-29 23:27:34 +03:00
red person 533d48ad8d Merge current dev into Compare SSE fix 2026-10-29 23:26:15 +03:00
red person d5bc7fb70e Merge current dev into group peer history fix 2026-10-29 23:21:20 +03:00
Alexandre Teixeira 3b8c60ac1e test: check database ownership against the private temp namespace 2026-10-29 17:49:45 +00:00
Alexandre Teixeira d237c3fbba perf(tests): reuse immutable admin auth configuration 2026-10-29 17:35:59 +00:00
Alexandre Teixeira f510b1973a perf(tests): bound Notes server descendant cleanup 2026-10-29 17:35:52 +00:00
Alexandre Teixeira fe81c491cd test: give collection database URL one cleanup owner 2026-10-29 17:30:10 +00:00
Alexandre Teixeira 1339efa856 test: restore editor aliases and validate procfs guard control flow 2026-10-29 17:12:26 +00:00
Alexandre Teixeira 6f5c28b345 test: require real cold reads, cancellation and auth writes 2026-10-29 17:12:20 +00:00
Alexandre Teixeira aa2db8d87c test: keep worker collection databases consistent across threads 2026-10-29 17:12:14 +00:00
dxrpl 6b284d2bc5 test(gallery): enable local image models in the bad-input test 2026-10-28 18:27:00 +01:00
dxrpl 8acaec20ee fix(gallery): answer 400 for a missing or invalid image on the image-edit routes (#6818) 2026-10-28 18:25:04 +01:00
red person 5f18bcf6f8 fix(models): retain valid discovery IDs beside malformed rows 2026-10-28 14:52:12 +03:00
red person 18b6140511 fix(mail): sort CLI message batches by UTC date 2026-10-28 14:39:41 +03:00
red person eeb1107f7b fix(gallery): match stacked CLI filters against AI tags 2026-10-28 14:33:23 +03:00
red person 4795c8d462 fix(group): preserve peer identity when reloading history 2026-10-28 14:27:17 +03:00
red person 5c738a5a8e fix(compare): reject incomplete and errored SSE responses 2026-10-28 13:09:35 +03:00
red person 0ff5d47a8c fix(chat): size user-message editors from wrapped content 2026-10-28 12:03:20 +03:00
red person f780f1dce9 test(email): align document identity guards with picker cache 2026-10-28 10:04:55 +03:00
red person 1c5853003e fix(email): retain inline image selections before input reset 2026-10-28 07:34:10 +03:00
red person 0f8b137713 fix(email): retain paperclip files when resetting the input 2026-10-28 07:26:05 +03:00
red person 2c5d5005ba fix(skills): wait for source before enabling the editor 2026-10-28 07:06:39 +03:00
red person 901b3ff42d fix(skills): align the chat link editor version 2026-10-28 06:58:54 +03:00
red person c207ed1ed8 fix(skills): size the raw editor from its source lines 2026-10-28 06:54:12 +03:00
red person 8b3a866899 fix(cookbook): ignore empty markers beside completed blobs 2026-10-28 06:31:50 +03:00
red person 4d8d363681 fix(memory): refresh records when opening the panel 2026-10-28 03:11:11 +03:00
red person a7e8a6ef2e fix(memory): reset category filter when its last entry disappears 2026-10-28 02:40:54 +03:00
red person 12631da4d3 fix(images): preserve explicit medium quality requests
Use configured quality only for omitted arguments in generation, MCP and edit helpers. Keep explicit medium choices from being overwritten by a low or high default.
2026-10-28 01:02:48 +03:00
red person 927985f847 fix(fonts): group compound weight and style variants by family 2026-10-28 00:23:18 +03:00
red person 2046ce893f fix(email): linkify URLs and addresses without rewriting anchors 2026-10-28 00:12:23 +03:00
red person 35ef91b25c fix(ui): return to the parent view when closing an item 2026-10-27 23:58:00 +03:00
dxrpl 91922d854c fix(api): answer 400 for a malformed body on integrations and document export-zip (#6905) 2026-10-27 18:33:23 +01:00
dxrpl 641752387b fix(calendar): answer 400 when a CalDAV config body is not a JSON object (#6903) 2026-10-27 18:09:14 +01:00
red person b3f86a0724 fix(forms): preserve Unicode field names during PDF export 2026-10-26 14:04:59 +03:00
red person 94dc74e500 fix(checkin): avoid duplicate calendar events at window boundaries 2026-10-26 12:00:12 +03:00
red person fd27e9a429 fix(skills): preserve version strings across markdown saves 2026-10-26 10:32:26 +03:00
dxrpl bf3c000d1c fix(tasks): refuse cron expressions with a seconds field (#6824) 2026-10-24 23:41:29 +02:00
PR #6029 Reviewer 7fd4e0e9bb fix(ui): harden iOS safe-area and viewport regressions 2026-10-20 11:39:51 +01:00
dxrplandClaude Opus 5.5 8cd96aad46 fix(cookbook): bring back the Dependencies recipe-panel caret (#6747)
cb052eee removed the caret that opens a backend's recipe panel, saying
the action had moved into the Installed menu, but that menu never got a
recipe item. The panel (model picker, commands, Run) could not be
opened, and the HW Fit / serve-card deep links that click the caret
only flashed the row. Render the caret again on every recipe row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:59:56 +02:00
dxrplandClaude Opus 5.5 6123b70b5c fix(hwfit): keep non-LLM HF collection models out of the LLM catalog (#6731)
Tracked HF collections also contain time-series forecasters, image
encoders and image/video generators. They were imported as "general"
LLMs and offered for vllm serve. Skip their pipeline tags; embedding,
reranker and RL-tagged LLM repos stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 01:15:08 +02:00
dxrplandClaude Opus 5.5 bfa514f6e8 fix(hwfit): keep the MoE active size for HF collection models (#6729)
_entry_from_collection_item parsed the repo name (the only source of the
"-A3B" active size) only when HF's numParameters was missing, which is
almost never. Every MoE model from the HF collection catalog was scored
as dense, with speed estimates 3-4x too low.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 01:11:46 +02:00
VykosMolt 1ff2fd0054 Merge dev and retain native image prompt validation 2026-10-09 01:34:21 +02:00
robyroro ad3e309074 fix(chats): preserve saved conversations during tidy 2026-10-08 06:48:41 +03:00
robyroro 15c4cef36a fix(notes): honor explicit null when clearing optional fields 2026-10-07 19:50:03 +03:00
harshit-ojha0324 84cdd866c5 fix(llm): stop the repeat guard from cutting off numeric data
The degenerate-stream guard treats a long run of one token, a dominant
token, or a periodic window as token collapse. Numbers repeat that way
by design: an 8x8 zero or identity matrix in LaTeX, a padded buffer, a
sparse 0/1 list. Each of those was stopped mid-answer with 'started
repeating tokens'.

Skip the same-run and dominance checks when the repeated token is a
number, skip the periodic check when the recent window is mostly
numbers, and skip the exact-block check when the block is all numbers.
A run of 2048 numbers in a row still stops, so a model stuck printing
'0 0 0' is still caught. Word loops and mixed word/number loops are
unchanged.

Fixes #5560
2026-10-06 19:01:12 -04:00
harshit-ojha0324 50b05bf54f fix(mcp): close the HTTP transport when a remote connect fails
_connect_http entered streamablehttp_client and ClientSession on an
AsyncExitStack but never closed it when initialize or list_tools
failed. The half-open transport was left to the garbage collector,
which exited its AnyIO cancel scope from the wrong task, and the event
loop kept spinning: about 18% of a core per failed connect, growing
with each one, until restart.

Close the stack in the connecting task on any failure or cancellation,
the same way _connect_sse already does.

Fixes #5518
2026-10-06 19:01:10 -04:00
VykosMoltandClaude dbfc96b8f3 fix(tools): add the native function schema for generate_image
generate_image existed in the prompt sections, the executor and the image_gen
MCP server, but not in FUNCTION_TOOL_SCHEMAS. API models are only sent schemas
from that list, so the tool selector could pick it and the schema filter would
drop it again — the model then improvised text-shaped calls it had no way to
make work.

The existing JSON fallback in function_call_to_tool_block already produces
content the executor parses, so no converter branch is needed. A required-args
entry is, though: without it a prompt-less call falls through to the line
parser and the whole JSON blob becomes the image prompt.

Fixes #5520

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-05 02:42:07 +02:00
Alexandre Teixeira a7c03f85bf fix(cookbook): recover from stale llama-server shims
Reconcile Odysseus-owned Python compatibility shims when llama_cpp.server is no longer available, allowing healthy native llama-server binaries in PATH to be discovered and executed without shadowing.

Fixes #6079
2026-08-17 00:59:13 +01:00
146 changed files with 7014 additions and 692 deletions
+8
View File
@@ -179,6 +179,7 @@ jobs:
uv pip install --system --require-hashes --only-binary=:all: --no-deps -r requirements-bootstrap.txt uv pip install --system --require-hashes --only-binary=:all: --no-deps -r requirements-bootstrap.txt
python scripts/check_ca_trust.py --python python scripts/check_ca_trust.py --python
uv pip install --system -r requirements.txt uv pip install --system -r requirements.txt
uv pip install --system "playwright==1.62.0"
if: steps.docs-check.outputs.docs_only != 'true' if: steps.docs-check.outputs.docs_only != 'true'
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
if: steps.docs-check.outputs.docs_only != 'true' if: steps.docs-check.outputs.docs_only != 'true'
@@ -256,3 +257,10 @@ jobs:
env: env:
PYTEST_SHARD: ${{ matrix.shard }} PYTEST_SHARD: ${{ matrix.shard }}
run: python -m pytest -q -rs --durations=25 --shard "$PYTEST_SHARD" run: python -m pytest -q -rs --durations=25 --shard "$PYTEST_SHARD"
- name: Playwright mobile layout checks (shard 1/4 only)
if: steps.docs-check.outputs.docs_only != 'true' && matrix.shard == '1/4'
run: |
ODYSSEUS_TEST_PYTHON=python ODYSSEUS_LAYOUT_BROWSER=chromium npx --no-install playwright test \
--config tests/e2e/ios-layout.config.cjs \
--reporter=line
+1 -1
View File
@@ -1,6 +1,6 @@
# Both stages need the fixed native decoder, including curl in the builder and # Both stages need the fixed native decoder, including curl in the builder and
# distro Node in the runtime. A cached Python base may predate the Debian fix. # distro Node in the runtime. A cached Python base may predate the Debian fix.
FROM python:3.15.0-slim AS brotli-base FROM python:3.14.9-slim AS brotli-base
COPY scripts/check_brotli.py /usr/local/bin/check-brotli.py COPY scripts/check_brotli.py /usr/local/bin/check-brotli.py
COPY scripts/check_ca_trust.py /usr/local/bin/check-ca-trust.py COPY scripts/check_ca_trust.py /usr/local/bin/check-ca-trust.py
# Check inherited trust before the first HTTPS package request, retaining Debian's # Check inherited trust before the first HTTPS package request, retaining Debian's
Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

+2 -2
View File
@@ -33,7 +33,7 @@ async def list_tools() -> list[Tool]:
"prompt": {"type": "string", "description": "Image description prompt"}, "prompt": {"type": "string", "description": "Image description prompt"},
"model": {"type": "string", "description": "Model name (auto-detects if omitted)"}, "model": {"type": "string", "description": "Model name (auto-detects if omitted)"},
"size": {"type": "string", "description": "Image size (default 1024x1024)"}, "size": {"type": "string", "description": "Image size (default 1024x1024)"},
"quality": {"type": "string", "description": "Quality: low, medium, high, auto (default medium)"}, "quality": {"type": "string", "description": "Quality: low, medium, high, auto (default configured quality, otherwise medium)"},
}, },
"required": ["prompt"], "required": ["prompt"],
}, },
@@ -66,7 +66,7 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if not model_spec: if not model_spec:
model_spec = _settings.get("image_model", "") model_spec = _settings.get("image_model", "")
if quality == "medium" and _settings.get("image_quality"): if "quality" not in arguments and _settings.get("image_quality"):
quality = _settings["image_quality"] quality = _settings["image_quality"]
# Auto-detect best available image model # Auto-detect best available image model
+5 -1
View File
@@ -9,7 +9,11 @@
"test:photo-editor": "playwright test --config tests/e2e/playwright.config.js", "test:photo-editor": "playwright test --config tests/e2e/playwright.config.js",
"test:photo-editor:install": "playwright install chromium firefox webkit", "test:photo-editor:install": "playwright install chromium firefox webkit",
"test:photo-editor:firefox": "PHOTO_EDITOR_E2E_BROWSER=firefox playwright test --config tests/e2e/playwright.config.js", "test:photo-editor:firefox": "PHOTO_EDITOR_E2E_BROWSER=firefox playwright test --config tests/e2e/playwright.config.js",
"test:photo-editor:webkit": "PHOTO_EDITOR_E2E_BROWSER=webkit playwright test --config tests/e2e/playwright.config.js" "test:photo-editor:webkit": "PHOTO_EDITOR_E2E_BROWSER=webkit playwright test --config tests/e2e/playwright.config.js",
"test:ios-layout": "playwright test --config tests/e2e/ios-layout.config.cjs",
"test:ios-layout:chromium": "ODYSSEUS_LAYOUT_BROWSER=chromium playwright test --config tests/e2e/ios-layout.config.cjs",
"test:ios-layout:webkit": "ODYSSEUS_LAYOUT_BROWSER=webkit playwright test --config tests/e2e/ios-layout.config.cjs",
"test:ios-layout:install": "playwright install chromium webkit"
}, },
"devDependencies": { "devDependencies": {
"@antithesishq/bombadil": "^0.7.0", "@antithesishq/bombadil": "^0.7.0",
+1
View File
@@ -2,3 +2,4 @@
-r requirements.txt -r requirements.txt
# psutil lets `-n auto` use physical cores instead of logical CPU threads. # psutil lets `-n auto` use physical cores instead of logical CPU threads.
pytest-xdist[psutil]>=3.8,<4 pytest-xdist[psutil]>=3.8,<4
playwright==1.62.0
+4
View File
@@ -887,6 +887,8 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
"""Create a new integration (admin only).""" """Create a new integration (admin only)."""
_require_admin_user(request) _require_admin_user(request)
body = await request.json() body = await request.json()
if not isinstance(body, dict):
raise HTTPException(400, "Request body must be a JSON object")
item = add_integration(body) item = add_integration(body)
return {"ok": True, "integration": mask_integration_secret(item)} return {"ok": True, "integration": mask_integration_secret(item)}
@@ -895,6 +897,8 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
"""Update an existing integration (admin only).""" """Update an existing integration (admin only)."""
_require_admin_user(request) _require_admin_user(request)
body = await request.json() body = await request.json()
if not isinstance(body, dict):
raise HTTPException(400, "Request body must be a JSON object")
item = update_integration(integration_id, body) item = update_integration(integration_id, body)
if not item: if not item:
raise HTTPException(404, "Integration not found") raise HTTPException(404, "Integration not found")
+16 -16
View File
@@ -80,6 +80,18 @@ def _require_user(request: Request) -> str:
return FALLBACK_OWNER return FALLBACK_OWNER
async def _json_object_body(request: Request) -> dict:
"""Parse a JSON object body. An unreadable body counts as empty; a body
that is valid JSON but not an object (a list, string or number) is a 400."""
try:
body = await request.json()
except Exception:
return {}
if not isinstance(body, dict):
raise HTTPException(400, "Request body must be a JSON object")
return body
def _get_or_404_calendar(db, cal_id: str, owner: str) -> CalendarCal: def _get_or_404_calendar(db, cal_id: str, owner: str) -> CalendarCal:
cal = db.query(CalendarCal).filter(CalendarCal.id == cal_id).first() cal = db.query(CalendarCal).filter(CalendarCal.id == cal_id).first()
if not cal: if not cal:
@@ -994,10 +1006,7 @@ def setup_calendar_routes(upload_handler=None) -> APIRouter:
async def save_config(request: Request): async def save_config(request: Request):
"""Legacy single-account endpoint — upserts the first account.""" """Legacy single-account endpoint — upserts the first account."""
owner = _require_user(request) owner = _require_user(request)
try: body = await _json_object_body(request)
body = await request.json()
except Exception:
body = {}
accounts = _get_caldav_accounts(owner) accounts = _get_caldav_accounts(owner)
if not (body.get("url") or "").strip(): if not (body.get("url") or "").strip():
_save_caldav_accounts(owner, []) _save_caldav_accounts(owner, [])
@@ -1052,10 +1061,7 @@ def setup_calendar_routes(upload_handler=None) -> APIRouter:
"""Add a new CalDAV account.""" """Add a new CalDAV account."""
import uuid as _uuid import uuid as _uuid
owner = _require_user(request) owner = _require_user(request)
try: body = await _json_object_body(request)
body = await request.json()
except Exception:
body = {}
from src.caldav_sync import validate_caldav_url from src.caldav_sync import validate_caldav_url
try: try:
url = validate_caldav_url(body.get("url", "")) url = validate_caldav_url(body.get("url", ""))
@@ -1080,10 +1086,7 @@ def setup_calendar_routes(upload_handler=None) -> APIRouter:
async def update_caldav_account(account_id: str, request: Request): async def update_caldav_account(account_id: str, request: Request):
"""Update an existing CalDAV account by id.""" """Update an existing CalDAV account by id."""
owner = _require_user(request) owner = _require_user(request)
try: body = await _json_object_body(request)
body = await request.json()
except Exception:
body = {}
accounts = _get_caldav_accounts(owner) accounts = _get_caldav_accounts(owner)
idx = next((i for i, a in enumerate(accounts) if a.get("id") == account_id), None) idx = next((i for i, a in enumerate(accounts) if a.get("id") == account_id), None)
if idx is None: if idx is None:
@@ -1124,10 +1127,7 @@ def setup_calendar_routes(upload_handler=None) -> APIRouter:
test an already-saved account. Falls back to the first saved account test an already-saved account. Falls back to the first saved account
when nothing is provided.""" when nothing is provided."""
owner = _require_user(request) owner = _require_user(request)
try: body = await _json_object_body(request)
body = await request.json()
except Exception:
body = {}
url = (body.get("url") or "").strip() url = (body.get("url") or "").strip()
user = (body.get("username") or "").strip() user = (body.get("username") or "").strip()
pw = body.get("password") or "" pw = body.get("password") or ""
+165 -1
View File
@@ -14,6 +14,7 @@ from fastapi import HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from routes._validators import validate_remote_host, validate_ssh_port from routes._validators import validate_remote_host, validate_ssh_port
from routes.cookbook_output import HF_PARTIAL_BLOB_HELPER
from core.platform_compat import _ssh_exec_argv from core.platform_compat import _ssh_exec_argv
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -378,6 +379,7 @@ def _cached_model_scan_script(model_dirs: list[str] | None = None, add_hf_cache:
""" """
lines = [ lines = [
"import json, os, re, shutil, subprocess, urllib.request", "import json, os, re, shutil, subprocess, urllib.request",
*HF_PARTIAL_BLOB_HELPER.splitlines(),
"models = []", "models = []",
"seen = set()", "seen = set()",
"BLOCKED_ROOTS = ('/sys', '/proc', '/dev', '/run', '/var/run')", "BLOCKED_ROOTS = ('/sys', '/proc', '/dev', '/run', '/var/run')",
@@ -436,8 +438,10 @@ def _cached_model_scan_script(model_dirs: list[str] | None = None, add_hf_cache:
" sz, nf, ic = 0, 0, False", " sz, nf, ic = 0, 0, False",
" if os.path.isdir(blobs):", " if os.path.isdir(blobs):",
" for f in os.scandir(blobs):", " for f in os.scandir(blobs):",
" if f.name.endswith('.incomplete'):",
" if not is_partial_blob(f.path): continue",
" ic = True",
" if f.is_file(): nf += 1; sz += f.stat().st_size", " if f.is_file(): nf += 1; sz += f.stat().st_size",
" if f.name.endswith('.incomplete'): ic = True",
" snap = os.path.join(cache, d, 'snapshots')", " snap = os.path.join(cache, d, 'snapshots')",
" def snapshot_size():", " def snapshot_size():",
" total, count, incomplete = 0, 0, False", " total, count, incomplete = 0, 0, False",
@@ -1030,6 +1034,166 @@ def _append_llama_cpp_linux_accel_build_lines(runner_lines: list[str]) -> None:
runner_lines.append(' fi # end _odysseus_have_prebuilt guard') runner_lines.append(' fi # end _odysseus_have_prebuilt guard')
ODYSSEUS_LLAMA_SHIM_MARKER = "# Auto-generated by Odysseus Cookbook: a `llama-server` lookalike"
def _append_llama_server_resolution_definition_lines(runner_lines: list[str]) -> None:
"""Define the helper shell function that discovers, reconciles and prioritizes llama-server."""
marker = f"'{_bash_squote(ODYSSEUS_LLAMA_SHIM_MARKER)}'"
runner_lines.append('_odysseus_resolve_llama_server() {')
runner_lines.append(' _odysseus_llama_bin=""')
runner_lines.append(f' local _marker={marker}')
runner_lines.append(' local _saved_ifs="$IFS"')
runner_lines.append(" IFS=':'")
runner_lines.append(' local -a _parts')
runner_lines.append(' read -r -a _parts <<< "$PATH"')
runner_lines.append(' IFS="$_saved_ifs"')
runner_lines.append(' local _dir _cand')
runner_lines.append(' for _dir in "${_parts[@]}"; do')
runner_lines.append(' [ -n "$_dir" ] || continue')
runner_lines.append(' _cand="$_dir/llama-server"')
runner_lines.append(' [ -x "$_cand" ] || continue')
runner_lines.append(' if [ -f "$_cand" ] && [ ! -L "$_cand" ] && grep -Fxq "$_marker" "$_cand" 2>/dev/null; then')
runner_lines.append(' continue')
runner_lines.append(' fi')
runner_lines.append(' if "$_cand" --version >/dev/null 2>&1; then')
runner_lines.append(' _odysseus_llama_bin="$_cand"')
runner_lines.append(' break')
runner_lines.append(' fi')
runner_lines.append(' done')
runner_lines.append(' if [ -f "$HOME/bin/llama-server" ] && [ ! -L "$HOME/bin/llama-server" ] && grep -Fxq "$_marker" "$HOME/bin/llama-server" 2>/dev/null; then')
runner_lines.append(' if [ -n "$_odysseus_llama_bin" ]; then')
runner_lines.append(' echo "[odysseus] Native llama-server detected — retiring Odysseus compatibility shim in ~/bin"')
runner_lines.append(' rm -f "$HOME/bin/llama-server"')
runner_lines.append(' hash -r')
runner_lines.append(' elif python3 -c "import llama_cpp.server" 2>/dev/null; then')
runner_lines.append(' _odysseus_llama_bin="$HOME/bin/llama-server"')
runner_lines.append(' else')
runner_lines.append(' echo "[odysseus] Removing stale Odysseus llama-server shim (python3 -m llama_cpp.server unavailable)"')
runner_lines.append(' rm -f "$HOME/bin/llama-server"')
runner_lines.append(' hash -r')
runner_lines.append(' fi')
runner_lines.append(' fi')
runner_lines.append(' if [ -n "$_odysseus_llama_bin" ]; then')
runner_lines.append(' local _cand_dir')
runner_lines.append(' _cand_dir="$(dirname "$_odysseus_llama_bin")"')
runner_lines.append(' if [ "${PATH%%:*}" != "$_cand_dir" ]; then')
runner_lines.append(' export PATH="$_cand_dir:$PATH"')
runner_lines.append(' fi')
runner_lines.append(' hash -r')
runner_lines.append(' return 0')
runner_lines.append(' fi')
runner_lines.append(' return 1')
runner_lines.append('}')
def _append_llama_server_shim_definition_lines(runner_lines: list[str]) -> None:
"""Define the helper shell function that generates the Odysseus compatibility shim."""
_append_llama_server_resolution_definition_lines(runner_lines)
marker = f"'{_bash_squote(ODYSSEUS_LLAMA_SHIM_MARKER)}'"
runner_lines.append('_odysseus_create_llama_shim() {')
runner_lines.append(' local _target="$HOME/bin/llama-server"')
runner_lines.append(f' local _marker={marker}')
runner_lines.append(' if [ -e "$_target" ] || [ -L "$_target" ]; then')
runner_lines.append(' if [ -f "$_target" ] && [ ! -L "$_target" ] && grep -Fxq "$_marker" "$_target" 2>/dev/null; then')
runner_lines.append(' : # existing Odysseus shim — safe to replace')
runner_lines.append(' else')
runner_lines.append(' echo "[odysseus] WARNING: $_target already exists and is not an Odysseus-managed shim; leaving untouched." >&2')
runner_lines.append(' return 1')
runner_lines.append(' fi')
runner_lines.append(' fi')
runner_lines.append(' mkdir -p "$HOME/bin" || return 1')
runner_lines.append(' local _tmp')
runner_lines.append(' _tmp="$(mktemp "$HOME/bin/.llama-server.odysseus.tmp.XXXXXX")" || {')
runner_lines.append(' echo "[odysseus] ERROR: unable to create secure temporary llama-server shim in $HOME/bin" >&2')
runner_lines.append(' return 1')
runner_lines.append(' }')
runner_lines.append(" if ! cat > \"$_tmp\" <<'_ODY_LLAMA_SHIM_EOF'")
runner_lines.append('#!/usr/bin/env bash')
runner_lines.append(ODYSSEUS_LLAMA_SHIM_MARKER)
runner_lines.append('# that translates the native CLI to `python -m llama_cpp.server`.')
runner_lines.append('# Lets cookbook-generated launch commands run unchanged on hosts')
runner_lines.append('# where only the pip llama-cpp-python package is installed.')
runner_lines.append('ARGS=()')
runner_lines.append('while [ $# -gt 0 ]; do')
runner_lines.append(' case "$1" in')
runner_lines.append(' -ngl|--gpu-layers|--n-gpu-layers) ARGS+=(--n_gpu_layers "$2"); shift 2 ;;')
runner_lines.append(' -c|--ctx-size) ARGS+=(--n_ctx "$2"); shift 2 ;;')
runner_lines.append(' -b|--batch-size) ARGS+=(--n_batch "$2"); shift 2 ;;')
runner_lines.append(' -ub|--ubatch-size) shift 2 ;; # llama-cpp-python has no separate ubatch')
runner_lines.append(' --flash-attn) ARGS+=(--flash_attn true); shift 2 ;;')
runner_lines.append(' --cache-type-k) ARGS+=(--type_k "$2"); shift 2 ;;')
runner_lines.append(' --cache-type-v) ARGS+=(--type_v "$2"); shift 2 ;;')
runner_lines.append(' --n-cpu-moe) ARGS+=(--n_cpu_moe "$2"); shift 2 ;;')
runner_lines.append(' --mmproj) ARGS+=(--clip_model_path "$2"); shift 2 ;;')
runner_lines.append(' --image-max-tokens) shift 2 ;; # native-only')
runner_lines.append(' --no-mmap) ARGS+=(--no_mmap true); shift ;;')
runner_lines.append(' --no-warmup) shift ;; # native-only')
runner_lines.append(' --chat-template) ARGS+=(--chat_format "$2"); shift 2 ;;')
runner_lines.append(' --fit|--split-mode|--tensor-split|--main-gpu|--parallel) shift 2 ;; # native-only')
runner_lines.append(' --mlock) ARGS+=(--use_mlock true); shift ;;')
runner_lines.append(' *) ARGS+=("$1"); shift ;;')
runner_lines.append(' esac')
runner_lines.append('done')
runner_lines.append('exec python3 -m llama_cpp.server "${ARGS[@]}"')
runner_lines.append('_ODY_LLAMA_SHIM_EOF')
runner_lines.append(' then')
runner_lines.append(' rm -f -- "$_tmp"')
runner_lines.append(' return 1')
runner_lines.append(' fi')
runner_lines.append(' chmod +x "$_tmp" || { rm -f -- "$_tmp"; return 1; }')
runner_lines.append(' mv -f -- "$_tmp" "$_target" || { rm -f -- "$_tmp"; return 1; }')
runner_lines.append(' hash -r')
runner_lines.append(' echo "[odysseus] Created llama-server shim → python -m llama_cpp.server (no native binary needed)"')
runner_lines.append('}')
def _append_llama_server_shim_reconciliation_lines(runner_lines: list[str]) -> None:
"""Reconcile an existing ~/bin/llama-server if it is owned by Odysseus Cookbook.
Invariants:
- Never touch an arbitrary user-owned executable or symlink.
- If ~/bin/llama-server is an Odysseus generated shim:
- If a native llama-server is present and healthy elsewhere on PATH, remove the shim
so the native binary is used.
- If python3 -m llama_cpp.server is unavailable, remove the stale shim
and hash -r so the fallback/build path is triggered.
- If no healthy native server exists and llama_cpp.server is working, preserve it.
- If a healthy native candidate exists on PATH (even later in PATH), prioritize it and
ensure the launched executable is the validated candidate.
"""
runner_lines.append('[ -r ~/.config/odysseus-llama-cpp-env ] && . ~/.config/odysseus-llama-cpp-env')
runner_lines.append('if ! declare -F _odysseus_resolve_llama_server >/dev/null 2>&1; then')
_append_llama_server_resolution_definition_lines(runner_lines)
runner_lines.append('fi')
runner_lines.append('_odysseus_resolve_llama_server || true')
def _append_llama_server_finalization_lines(runner_lines: list[str], platform_hint: str = "") -> None:
"""Reconcile post-install launcher availability and enforce fail-closed invariant.
Guarantees that if python3 -m llama_cpp.server is usable but the `llama-server`
command is unresolvable, the compatibility launcher is created. If no usable
launcher exists after all build/install attempts, sets ODYSSEUS_PREFLIGHT_EXIT=127.
"""
err_msg = (
f"ERROR: llama.cpp serving is not available on {platform_hint} after install attempts."
if platform_hint
else "ERROR: llama.cpp serving is not available after install/build attempts."
)
runner_lines.append('if ! declare -F _odysseus_resolve_llama_server >/dev/null 2>&1; then')
_append_llama_server_resolution_definition_lines(runner_lines)
runner_lines.append('fi')
runner_lines.append('if [ -z "$_odysseus_llama_bin" ] && python3 -c "import llama_cpp.server" 2>/dev/null; then')
runner_lines.append(' _odysseus_create_llama_shim')
runner_lines.append(' _odysseus_resolve_llama_server || true')
runner_lines.append('fi')
runner_lines.append('if [ -z "$_odysseus_llama_bin" ]; then')
runner_lines.append(f' echo "{err_msg}"')
runner_lines.append(' ODYSSEUS_PREFLIGHT_EXIT=127')
runner_lines.append('fi')
def _llama_cpp_rebuild_cmd(update_source: bool = False) -> str: def _llama_cpp_rebuild_cmd(update_source: bool = False) -> str:
"""Shell command that clears the Cookbook-managed llama.cpp build. """Shell command that clears the Cookbook-managed llama.cpp build.
+18 -4
View File
@@ -8,6 +8,20 @@ import re
_FETCHING_ZERO_FILES_RE = re.compile(r"Fetching\s+0\s+files", re.IGNORECASE) _FETCHING_ZERO_FILES_RE = re.compile(r"Fetching\s+0\s+files", re.IGNORECASE)
# Shared source embedded in local/remote inventory and status probes. A blank
# retry marker beside its completed, nonempty content-addressed blob is stale;
# a blank marker alone may be a download that has not received its first byte.
HF_PARTIAL_BLOB_HELPER = """def is_partial_blob(path):
if not path.endswith('.incomplete'):
return False
try:
completed = path[:-len('.incomplete')]
return (os.path.getsize(path) != 0 or not os.path.isfile(completed)
or os.path.getsize(completed) == 0)
except OSError:
return True
"""
# Probe scripts for the dead-session download check, run as # Probe scripts for the dead-session download check, run as
# `python3 -c <PROBE> <repo_id> <cache_root>` (locally or over SSH). # `python3 -c <PROBE> <repo_id> <cache_root>` (locally or over SSH).
# cache_root is the task's custom download dir, '' for the default HF cache. # cache_root is the task's custom download dir, '' for the default HF cache.
@@ -15,7 +29,7 @@ _FETCHING_ZERO_FILES_RE = re.compile(r"Fetching\s+0\s+files", re.IGNORECASE)
# HF_HOME=<local_dir>, so that task's cache lives under <local_dir>/hub, and # HF_HOME=<local_dir>, so that task's cache lives under <local_dir>/hub, and
# the probe process's own environment knows nothing about it. # the probe process's own environment knows nothing about it.
HF_CACHE_COMPLETE_PROBE = ( HF_CACHE_COMPLETE_PROBE = (
"import os,sys;" "import os,sys\n" + HF_PARTIAL_BLOB_HELPER +
"repo=sys.argv[1];" "repo=sys.argv[1];"
"root=os.path.expanduser(sys.argv[2]) if len(sys.argv)>2 and sys.argv[2] else '';" "root=os.path.expanduser(sys.argv[2]) if len(sys.argv)>2 and sys.argv[2] else '';"
"base=os.path.join(root,'hub') if root else (os.environ.get('HUGGINGFACE_HUB_CACHE') or os.path.join(os.environ.get('HF_HOME', os.path.expanduser('~/.cache/huggingface')), 'hub'));" "base=os.path.join(root,'hub') if root else (os.environ.get('HUGGINGFACE_HUB_CACHE') or os.path.join(os.environ.get('HF_HOME', os.path.expanduser('~/.cache/huggingface')), 'hub'));"
@@ -24,18 +38,18 @@ HF_CACHE_COMPLETE_PROBE = (
"ok=os.path.isdir(snap) and any(os.path.isdir(os.path.join(snap,x)) and os.listdir(os.path.join(snap,x)) for x in os.listdir(snap));" "ok=os.path.isdir(snap) and any(os.path.isdir(os.path.join(snap,x)) and os.listdir(os.path.join(snap,x)) for x in os.listdir(snap));"
"inc=False;" "inc=False;"
"blobs=os.path.join(d,'blobs');" "blobs=os.path.join(d,'blobs');"
"inc=os.path.isdir(blobs) and any(x.endswith('.incomplete') for x in os.listdir(blobs));" "inc=os.path.isdir(blobs) and any(is_partial_blob(os.path.join(blobs,x)) for x in os.listdir(blobs));"
"sys.exit(0 if ok and not inc else 1)" "sys.exit(0 if ok and not inc else 1)"
) )
HF_CACHE_INCOMPLETE_PROBE = ( HF_CACHE_INCOMPLETE_PROBE = (
"import os,sys;" "import os,sys\n" + HF_PARTIAL_BLOB_HELPER +
"repo=sys.argv[1];" "repo=sys.argv[1];"
"root=os.path.expanduser(sys.argv[2]) if len(sys.argv)>2 and sys.argv[2] else '';" "root=os.path.expanduser(sys.argv[2]) if len(sys.argv)>2 and sys.argv[2] else '';"
"base=os.path.join(root,'hub') if root else (os.environ.get('HUGGINGFACE_HUB_CACHE') or os.path.join(os.environ.get('HF_HOME', os.path.expanduser('~/.cache/huggingface')), 'hub'));" "base=os.path.join(root,'hub') if root else (os.environ.get('HUGGINGFACE_HUB_CACHE') or os.path.join(os.environ.get('HF_HOME', os.path.expanduser('~/.cache/huggingface')), 'hub'));"
"d=os.path.join(base,'models--'+repo.replace('/','--'));" "d=os.path.join(base,'models--'+repo.replace('/','--'));"
"blobs=os.path.join(d,'blobs');" "blobs=os.path.join(d,'blobs');"
"inc=os.path.isdir(blobs) and any(x.endswith('.incomplete') for x in os.listdir(blobs));" "inc=os.path.isdir(blobs) and any(is_partial_blob(os.path.join(blobs,x)) for x in os.listdir(blobs));"
"sys.exit(0 if inc else 1)" "sys.exit(0 if inc else 1)"
) )
+17 -57
View File
@@ -57,9 +57,11 @@ from routes.cookbook_helpers import (
_pip_install_no_cache, _user_shell_path_bootstrap, _venv_safe_local_pip_install_cmd, _pip_install_no_cache, _user_shell_path_bootstrap, _venv_safe_local_pip_install_cmd,
_diagnose_serve_output, run_ssh_command_async, _diagnose_serve_output, run_ssh_command_async,
_ollama_bind_from_cmd, _pip_install_fallback_chain, _pip_install_no_cache, _ollama_bind_from_cmd, _pip_install_fallback_chain, _pip_install_no_cache,
_user_shell_path_bootstrap, _venv_safe_local_pip_install_cmd,
_append_pip_install_runner_lines, _pip_install_command_without_break_system_packages, _append_pip_install_runner_lines, _pip_install_command_without_break_system_packages,
_normalize_llama_cpp_python_cache_types, _normalize_llama_cpp_python_cache_types,
_append_llama_server_shim_definition_lines,
_append_llama_server_shim_reconciliation_lines,
_append_llama_server_finalization_lines,
ModelDownloadRequest, ServeRequest, ModelDownloadRequest, ServeRequest,
) )
@@ -2161,7 +2163,7 @@ def setup_cookbook_routes() -> APIRouter:
ps_lines.append('}') ps_lines.append('}')
elif "llama_cpp" in req.cmd or "llama-server" in req.cmd: elif "llama_cpp" in req.cmd or "llama-server" in req.cmd:
ps_lines.append('# Auto-install llama-cpp-python if missing') ps_lines.append('# Auto-install llama-cpp-python if missing')
ps_lines.append('try { python -c "import llama_cpp" 2>$null } catch {}') ps_lines.append('try { python -c "import llama_cpp.server" 2>$null } catch {}')
ps_lines.append('if ($LASTEXITCODE -ne 0) {') ps_lines.append('if ($LASTEXITCODE -ne 0) {')
ps_lines.append(' Write-Host "Installing llama-cpp-python..."') ps_lines.append(' Write-Host "Installing llama-cpp-python..."')
ps_lines.append(' python -m pip install llama-cpp-python[server]') ps_lines.append(' python -m pip install llama-cpp-python[server]')
@@ -2247,14 +2249,17 @@ def setup_cookbook_routes() -> APIRouter:
# ollama is found (otherwise macOS falls back to a slow source build). # ollama is found (otherwise macOS falls back to a slow source build).
# /opt/homebrew = Apple Silicon, /usr/local = Intel; harmless on Linux. # /opt/homebrew = Apple Silicon, /usr/local = Intel; harmless on Linux.
runner_lines.append('export PATH="$HOME/.local/bin:$HOME/bin:$HOME/llama.cpp/build/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"') runner_lines.append('export PATH="$HOME/.local/bin:$HOME/bin:$HOME/llama.cpp/build/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"')
_append_llama_server_shim_definition_lines(runner_lines)
_append_llama_server_shim_reconciliation_lines(runner_lines)
runner_lines.append('if [ -d /data/data/com.termux ]; then') runner_lines.append('if [ -d /data/data/com.termux ]; then')
runner_lines.append(' # Termux: no native build — use the Python bindings (CPU).') runner_lines.append(' # Termux: no native build — use the Python bindings (CPU).')
runner_lines.append(' if ! python3 -c "import llama_cpp" 2>/dev/null; then') runner_lines.append(' if ! python3 -c "import llama_cpp.server" 2>/dev/null; then')
runner_lines.append(' pkg install -y cmake 2>/dev/null') runner_lines.append(' pkg install -y cmake 2>/dev/null')
runner_lines.append(' pip install numpy diskcache jinja2 2>/dev/null') runner_lines.append(' pip install numpy diskcache jinja2 2>/dev/null')
runner_lines.append(' CMAKE_ARGS="-DGGML_BLAS=OFF -DGGML_LLAMAFILE=OFF" pip install \'llama-cpp-python[server]\' --no-build-isolation --no-cache-dir 2>&1 || true') runner_lines.append(' CMAKE_ARGS="-DGGML_BLAS=OFF -DGGML_LLAMAFILE=OFF" pip install \'llama-cpp-python[server]\' --no-build-isolation --no-cache-dir 2>&1 || true')
runner_lines.append(' fi') runner_lines.append(' fi')
runner_lines.append('elif ! command -v llama-server &>/dev/null; then') _append_llama_server_finalization_lines(runner_lines, platform_hint="Termux")
runner_lines.append('elif [ -z "$_odysseus_llama_bin" ]; then')
runner_lines.append(' echo "Native llama-server not found — building from source (one-time, may take a few minutes)..."') runner_lines.append(' echo "Native llama-server not found — building from source (one-time, may take a few minutes)..."')
runner_lines.append(' mkdir -p ~/bin') runner_lines.append(' mkdir -p ~/bin')
runner_lines.append(' cd ~ && [ -d llama.cpp ] || git clone --depth 1 https://github.com/ggml-org/llama.cpp') runner_lines.append(' cd ~ && [ -d llama.cpp ] || git clone --depth 1 https://github.com/ggml-org/llama.cpp')
@@ -2271,8 +2276,7 @@ def setup_cookbook_routes() -> APIRouter:
# would reuse the bad settings and fail again. CMAKE_BUILD_TYPE is # would reuse the bad settings and fail again. CMAKE_BUILD_TYPE is
# explicit so the binary is optimized (Metal auto-enables on macOS). # explicit so the binary is optimized (Metal auto-enables on macOS).
runner_lines.append(' cd ~/llama.cpp && rm -rf build && cmake -B build -DCMAKE_BUILD_TYPE=Release \\') runner_lines.append(' cd ~/llama.cpp && rm -rf build && cmake -B build -DCMAKE_BUILD_TYPE=Release \\')
runner_lines.append(' && cmake --build build -j"$NPROC" --target llama-server \\') runner_lines.append(' && cmake --build build -j"$NPROC" --target llama-server')
runner_lines.append(' && ln -sf ~/llama.cpp/build/bin/llama-server ~/bin/llama-server')
runner_lines.append(' else') runner_lines.append(' else')
_append_llama_cpp_linux_accel_build_lines(runner_lines) _append_llama_cpp_linux_accel_build_lines(runner_lines)
runner_lines.append(' fi') runner_lines.append(' fi')
@@ -2296,58 +2300,13 @@ def setup_cookbook_routes() -> APIRouter:
runner_lines.append(' fi') runner_lines.append(' fi')
runner_lines.append(' fi') runner_lines.append(' fi')
runner_lines.append(' fi') runner_lines.append(' fi')
# SHORT-CIRCUIT before the build/pip fallback: if the runner_lines.append(' _odysseus_resolve_llama_server || true')
# native binary is missing but llama_cpp Python is already # If the native build failed, fall back to the Python bindings.
# installed, drop a wrapper at ~/bin/llama-server that runner_lines.append(' if [ -z "$_odysseus_llama_bin" ] && ! python3 -c "import llama_cpp.server" 2>/dev/null; then')
# translates llama-server CLI args to llama_cpp.server's
# underscore-style flags. The user's serve command stays
# `llama-server ...` and "just works" — no build, no cmake,
# no second install. This is the path that unblocks every
# remote where pip-installed llama-cpp-python is already
# working but Cookbook used to insist on a native binary.
runner_lines.append(' if ! command -v llama-server >/dev/null 2>&1 && python3 -c "import llama_cpp" 2>/dev/null; then')
runner_lines.append(' mkdir -p ~/bin')
runner_lines.append(' cat > ~/bin/llama-server <<\'_ODY_LLAMA_SHIM_EOF\'')
runner_lines.append('#!/usr/bin/env bash')
runner_lines.append('# Auto-generated by Odysseus Cookbook: a `llama-server` lookalike')
runner_lines.append('# that translates the native CLI to `python -m llama_cpp.server`.')
runner_lines.append('# Lets cookbook-generated launch commands run unchanged on hosts')
runner_lines.append('# where only the pip llama-cpp-python package is installed.')
runner_lines.append('ARGS=()')
runner_lines.append('while [ $# -gt 0 ]; do')
runner_lines.append(' case "$1" in')
runner_lines.append(' -ngl|--gpu-layers|--n-gpu-layers) ARGS+=(--n_gpu_layers "$2"); shift 2 ;;')
runner_lines.append(' -c|--ctx-size) ARGS+=(--n_ctx "$2"); shift 2 ;;')
runner_lines.append(' -b|--batch-size) ARGS+=(--n_batch "$2"); shift 2 ;;')
runner_lines.append(' -ub|--ubatch-size) shift 2 ;; # llama-cpp-python has no separate ubatch')
runner_lines.append(' --flash-attn) ARGS+=(--flash_attn true); shift 2 ;;')
runner_lines.append(' --cache-type-k) ARGS+=(--type_k "$2"); shift 2 ;;')
runner_lines.append(' --cache-type-v) ARGS+=(--type_v "$2"); shift 2 ;;')
runner_lines.append(' --n-cpu-moe) ARGS+=(--n_cpu_moe "$2"); shift 2 ;;')
runner_lines.append(' --mmproj) ARGS+=(--clip_model_path "$2"); shift 2 ;;')
runner_lines.append(' --image-max-tokens) shift 2 ;; # native-only')
runner_lines.append(' --no-mmap) ARGS+=(--no_mmap true); shift ;;')
runner_lines.append(' --no-warmup) shift ;; # native-only')
runner_lines.append(' --chat-template) ARGS+=(--chat_format "$2"); shift 2 ;;')
runner_lines.append(' --fit|--split-mode|--tensor-split|--main-gpu|--parallel) shift 2 ;; # native-only')
runner_lines.append(' --mlock) ARGS+=(--use_mlock true); shift ;;')
runner_lines.append(' *) ARGS+=("$1"); shift ;;')
runner_lines.append(' esac')
runner_lines.append('done')
runner_lines.append('exec python3 -m llama_cpp.server "${ARGS[@]}"')
runner_lines.append('_ODY_LLAMA_SHIM_EOF')
runner_lines.append(' chmod +x ~/bin/llama-server')
runner_lines.append(' echo "[odysseus] Created llama-server shim → python -m llama_cpp.server (no native binary needed)"')
runner_lines.append(' fi')
runner_lines.append(' # If the native build failed, fall back to the Python bindings.')
runner_lines.append(' if ! command -v llama-server &>/dev/null && ! python3 -c "import llama_cpp" 2>/dev/null; then')
runner_lines.append(' echo "llama-server build failed — installing Python bindings as fallback..."') runner_lines.append(' echo "llama-server build failed — installing Python bindings as fallback..."')
runner_lines.append(f" {_pip_install_fallback_chain('llama-cpp-python[server]', python_cmd='pip')} || true") runner_lines.append(f" {_pip_install_fallback_chain('llama-cpp-python[server]', python_cmd='pip')} || true")
runner_lines.append(' fi') runner_lines.append(' fi')
runner_lines.append(' if ! command -v llama-server &>/dev/null && ! python3 -c "import llama_cpp" 2>/dev/null; then') _append_llama_server_finalization_lines(runner_lines)
runner_lines.append(' echo "ERROR: llama.cpp serving is not available after install/build attempts."')
runner_lines.append(' ODYSSEUS_PREFLIGHT_EXIT=127')
runner_lines.append(' fi')
runner_lines.append('fi') runner_lines.append('fi')
elif re.search(r"\bollama\s+serve\b", req.cmd): elif re.search(r"\bollama\s+serve\b", req.cmd):
handled_ollama_serve = True handled_ollama_serve = True
@@ -4343,7 +4302,7 @@ def setup_cookbook_routes() -> APIRouter:
tmux output can stop at a stale progress line if the pane/session tmux output can stop at a stale progress line if the pane/session
disappears before Cookbook captures the final DOWNLOAD_OK marker. disappears before Cookbook captures the final DOWNLOAD_OK marker.
In that case, trust the cache shape: a snapshot directory with files In that case, trust the cache shape: a snapshot directory with files
and no *.incomplete blobs means HuggingFace finished materializing the and no unfinished blobs means HuggingFace finished materializing the
model. cache_root is the task's custom download dir — the runner model. cache_root is the task's custom download dir — the runner
pointed HF_HOME there, so the cache lives under <cache_root>/hub, pointed HF_HOME there, so the cache lives under <cache_root>/hub,
not wherever this probe's environment says. not wherever this probe's environment says.
@@ -4368,7 +4327,8 @@ def setup_cookbook_routes() -> APIRouter:
"""Best-effort check for resumable HF partial blobs. """Best-effort check for resumable HF partial blobs.
A lost SSH/tmux session can leave a real download still incomplete. A lost SSH/tmux session can leave a real download still incomplete.
Treat any *.incomplete blob as stronger evidence than stale Treat unfinished blobs (excluding empty markers paired with a
completed blob) as stronger evidence than stale
"100%" lines in the captured pane output. "100%" lines in the captured pane output.
""" """
if not repo_id or "/" not in repo_id: if not repo_id or "/" not in repo_id:
+3 -1
View File
@@ -781,9 +781,11 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter:
except Exception as e: except Exception as e:
logger.warning("Failed to parse export request body, defaulting to empty", exc_info=e) logger.warning("Failed to parse export request body, defaulting to empty", exc_info=e)
data = {} data = {}
ids = data.get("ids") or [] ids = data.get("ids") if isinstance(data, dict) else None
if not ids: if not ids:
raise HTTPException(400, "No documents specified") raise HTTPException(400, "No documents specified")
if not isinstance(ids, list) or not all(isinstance(i, str) for i in ids):
raise HTTPException(400, "ids must be a list of document ids")
_ext = { _ext = {
"javascript": ".js", "python": ".py", "html": ".html", "css": ".css", "javascript": ".js", "python": ".py", "html": ".html", "css": ".css",
"markdown": ".md", "json": ".json", "yaml": ".yml", "bash": ".sh", "markdown": ".md", "json": ".json", "yaml": ".yml", "bash": ".sh",
+82 -2
View File
@@ -846,6 +846,64 @@ def _plan_psd_steps(prompt: str) -> Optional[List[Dict[str, Any]]]:
return None return None
def _is_background_removal_intent(prompt: str) -> bool:
"""Linear-time, bounded intent parser for background removal commands.
Replaces the previous backtracking regular expression flagged by CodeQL
(#1212) while preserving the exact command grammar.
"""
if not prompt or not isinstance(prompt, str):
return False
i = len(prompt)
while i > 0 and prompt[i - 1] in ".! \t\r\n":
i -= 1
cleaned = prompt[:i].strip()
if not cleaned:
return False
tokens = cleaned.split()
if not tokens:
return False
idx = 0
if tokens[idx].lower() == "please":
idx += 1
if idx >= len(tokens):
return False
if tokens[idx].lower() not in {"remove", "erase", "delete", "clear", "strip"}:
return False
idx += 1
if idx >= len(tokens):
return False
if tokens[idx].lower() == "the":
idx += 1
if idx >= len(tokens):
return False
if tokens[idx].lower() not in {"bg", "background", "backdrop"}:
return False
idx += 1
if idx == len(tokens):
return True
if tokens[idx].lower() in {"from", "of"}:
idx += 1
if idx < len(tokens) and tokens[idx].lower() == "the":
idx += 1
if (
idx + 1 < len(tokens)
and tokens[idx].lower() in {"active", "current", "selected"}
and tokens[idx + 1].lower() == "layer"
and idx + 2 == len(tokens)
):
return True
return False
def _plan_special( def _plan_special(
prompt: str, state: Any, provider_available: bool, prompt: str, state: Any, provider_available: bool,
) -> Optional[Tuple[List[Dict[str, Any]], str, str]]: ) -> Optional[Tuple[List[Dict[str, Any]], str, str]]:
@@ -855,6 +913,8 @@ def _plan_special(
left to the model. Returns (steps, reply, note) or None. These never need an left to the model. Returns (steps, reply, note) or None. These never need an
image provider except generative border fill, used only when one exists. image provider except generative border fill, used only when one exists.
""" """
if _is_background_removal_intent(prompt):
return [{"op": "ai.removeBackground", "params": {}}], "Removing the active layer's background.", ""
# Targeted recolour is fully deterministic (object mask + masked hue shift) # Targeted recolour is fully deterministic (object mask + masked hue shift)
# and must never be left to the model, which sometimes substitutes a # and must never be left to the model, which sometimes substitutes a
# generative placeImage. Highest priority so it can never vary. # generative placeImage. Highest priority so it can never vary.
@@ -1647,6 +1707,13 @@ def setup_editor_agent_routes() -> APIRouter:
screenshot = body.get("screenshot") screenshot = body.get("screenshot")
# Optional user-picked image model (from the editor model selector). # Optional user-picked image model (from the editor model selector).
model_choice = str(body.get("model") or body.get("image_model") or "").strip() model_choice = str(body.get("model") or body.get("image_model") or "").strip()
generation_model_choice = str(body.get("generation_model") or "").strip()
use_image_settings = body.get("_use_image_settings") is True
if use_image_settings:
from src.editor_image_settings import editor_image_models
image_models = editor_image_models(owner=owner)
model_choice = image_models["edit"]
generation_model_choice = image_models["generation"]
# Optional user-picked PLANNER model (the editor agent/planner model). # Optional user-picked PLANNER model (the editor agent/planner model).
agent_model = str(body.get("agent_model") or "").strip() agent_model = str(body.get("agent_model") or "").strip()
tools_offered = [tool for tool in _scoped_editor_tools() if tool not in disabled] tools_offered = [tool for tool in _scoped_editor_tools() if tool not in disabled]
@@ -1797,9 +1864,22 @@ def setup_editor_agent_routes() -> APIRouter:
# Planner output is untrusted: it cannot redirect this turn to # Planner output is untrusted: it cannot redirect this turn to
# another editor session or override an explicit model choice. # another editor session or override an explicit model choice.
tool_payload["session"] = session tool_payload["session"] = session
if use_image_settings:
tool_payload["_use_image_settings"] = True
if op == "generate_image" and state.get("width") and state.get("height"):
try:
width, height = int(state["width"]), int(state["height"])
if width > 0 and height > 0:
tool_payload["size"] = f"{width}x{height}"
except (TypeError, ValueError):
pass
# Route to the user-picked model when one is selected. # Route to the user-picked model when one is selected.
if model_choice: selected_model = generation_model_choice if op == "generate_image" else model_choice
tool_payload["model"] = model_choice if selected_model:
tool_payload["model"] = selected_model
elif op == "generate_image" or use_image_settings:
# Let server settings resolve Auto, not a planner-invented model.
tool_payload.pop("model", None)
# Hand the AI step the canvas image the client already captured # Hand the AI step the canvas image the client already captured
# for this request. Without it the tool falls back to a separate # for this request. Without it the tool falls back to a separate
# bridge screenshot, which is not reliably answered right after a # bridge screenshot, which is not reliably answered right after a
+3 -2
View File
@@ -19,9 +19,10 @@ def _split_family_token(token):
def _derive_family(filename): def _derive_family(filename):
"""Derive a font-family name from a filename like 'JetBrainsMono-Regular.woff2' → 'JetBrains Mono'.""" """Derive a font-family name from a filename like 'JetBrainsMono-Regular.woff2' → 'JetBrains Mono'."""
name = os.path.splitext(filename)[0] name = os.path.splitext(filename)[0]
# Strip common weight/style suffixes # Strip weight/style suffixes, including BoldItalic and Bold-Italic.
name = re.sub( name = re.sub(
r'[-_ ]?(Thin|ExtraLight|UltraLight|Light|Regular|Medium|SemiBold|DemiBold|Bold|ExtraBold|UltraBold|Black|Heavy|Italic|Oblique|Variable|VF)$', r'[-_ ]?(Thin|ExtraLight|UltraLight|Light|Regular|Medium|SemiBold|DemiBold|Bold|ExtraBold|UltraBold|Black|Heavy|Italic|Oblique|Variable|VF)'
r'(?:[-_ ]?(?:Italic|Oblique))?$',
'', name, flags=re.IGNORECASE '', name, flags=re.IGNORECASE
) )
# Replace dashes/underscores with spaces # Replace dashes/underscores with spaces
+70 -22
View File
@@ -37,6 +37,24 @@ _SAM_STATE: Dict[str, Any] = {}
_GROUNDING_STATE: Dict[str, Any] = {} _GROUNDING_STATE: Dict[str, Any] = {}
def _compose_cloud_image_edit(source, generated, mask, *, instruction=False):
from PIL import Image, ImageChops, ImageOps
full_frame = instruction or mask.getextrema() == (255, 255)
if full_frame:
return generated, True
# Partial edits must share the source coordinate system, but resizing
# width/height independently distorts the subject when the provider changes ratio.
fitted = ImageOps.contain(generated, source.size, Image.Resampling.LANCZOS)
offset = ((source.width - fitted.width) // 2, (source.height - fitted.height) // 2)
aligned = Image.new("RGBA", source.size)
aligned.paste(fitted, offset)
coverage = Image.new("L", source.size)
coverage.paste(255, (offset[0], offset[1], offset[0] + fitted.width, offset[1] + fitted.height))
effective_mask = ImageChops.multiply(mask, coverage)
return Image.composite(aligned, source, effective_mask), False
def _rss_mb() -> float: def _rss_mb() -> float:
"""Current process RSS in MB (from /proc; -1.0 when unavailable).""" """Current process RSS in MB (from /proc; -1.0 when unavailable)."""
try: try:
@@ -568,6 +586,7 @@ def _is_openai_api_base(url: str) -> bool:
_GALLERY_ENDPOINT_PATHS = frozenset({ _GALLERY_ENDPOINT_PATHS = frozenset({
"/chat/completions",
"/images", "/images",
"/images/edits", "/images/edits",
"/images/generations", "/images/generations",
@@ -1745,6 +1764,17 @@ def setup_gallery_routes() -> APIRouter:
if not ok: if not ok:
raise HTTPException(400, f"Rejected endpoint URL: {reason}") raise HTTPException(400, f"Rejected endpoint URL: {reason}")
chosen_model = (body.pop("_model", "") or "").strip() chosen_model = (body.pop("_model", "") or "").strip()
if body.pop("_use_image_settings", False) is True:
from src.editor_image_settings import editor_image_models
from src.ai_interaction import _resolve_model
chosen_model = editor_image_models(owner=user)["edit"]
if not chosen_model:
raise HTTPException(400, "Choose an image edit model in AI settings")
try:
edit_url, chosen_model, _ = await asyncio.to_thread(_resolve_model, chosen_model, owner=user)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
requested_base = edit_url.removesuffix("/chat/completions").rstrip("/")
# Optional client-supplied id so GET /api/image/edit-progress can poll the # Optional client-supplied id so GET /api/image/edit-progress can poll the
# provider's step progress for this op. Ignored by providers that do not # provider's step progress for this op. Ignored by providers that do not
# implement the progress contract. # implement the progress contract.
@@ -1862,13 +1892,29 @@ def setup_gallery_routes() -> APIRouter:
mask_png.save(reference_mask, format="PNG") mask_png.save(reference_mask, format="PNG")
references = [src_buf.getvalue(), reference_mask.getvalue()] references = [src_buf.getvalue(), reference_mask.getvalue()]
payload = { payload = {
"model": oa_model, "size": size, "n": 1, "model": oa_model, "n": 1,
"output_format": "png", "output_format": "png",
"prompt": "Edit the first image. The second image is a mask: white marks the region to edit, black marks the region to preserve. Keep composition and framing unchanged. Requested edit: " + str(body.get("prompt", "")), "prompt": "Edit the first image. The second image is a mask: white marks the region to edit, black marks the region to preserve. Keep composition and framing unchanged. Requested edit: " + str(body.get("prompt", "")),
"input_references": [{"type": "image_url", "image_url": { "input_references": [{"type": "image_url", "image_url": {
"url": "data:image/png;base64," + base64.b64encode(value).decode(), "url": "data:image/png;base64," + base64.b64encode(value).decode(),
}} for value in references], }} for value in references],
} }
from src.image_model_ids import image_aspect_ratio
payload["aspect_ratio"] = image_aspect_ratio(source_png.width, source_png.height)
from src.ai_interaction import _uses_openrouter_chat_images
if _uses_openrouter_chat_images(oa_model):
payload = {
"model": oa_model,
"messages": [{"role": "user", "content": [
{"type": "text", "text": payload["prompt"]},
*[{"type": "image_url", "image_url": ref["image_url"]}
for ref in payload["input_references"]],
]}],
"modalities": ["image", "text"], "stream": False,
"image_config": {"aspect_ratio": payload["aspect_ratio"]},
}
r = await client.post(_join_checked_gallery_endpoint(base, "/chat/completions"), headers=headers, json=payload)
else:
r = await client.post(_join_checked_gallery_endpoint(base, "/images"), headers=headers, json=payload) r = await client.post(_join_checked_gallery_endpoint(base, "/images"), headers=headers, json=payload)
else: else:
r = await client.post(_join_checked_gallery_endpoint(base, "/images/edits"), headers=headers, data=data, files=files) r = await client.post(_join_checked_gallery_endpoint(base, "/images/edits"), headers=headers, data=data, files=files)
@@ -1885,6 +1931,12 @@ def setup_gallery_routes() -> APIRouter:
pass pass
raise HTTPException(r.status_code, f"{_detail} (provider HTTP {r.status_code})") raise HTTPException(r.status_code, f"{_detail} (provider HTTP {r.status_code})")
result = r.json() result = r.json()
from src.ai_interaction import _chat_image_results, _image_response_error
provider_error = _image_response_error(result, oa_model)
if provider_error:
raise HTTPException(400 if "deprecated" in provider_error.lower() else 502, provider_error)
if is_openrouter and _uses_openrouter_chat_images(oa_model):
result = {"data": _chat_image_results(result)}
raw_b64 = None raw_b64 = None
if result.get("data"): if result.get("data"):
item = result["data"][0] item = result["data"][0]
@@ -1904,17 +1956,13 @@ def setup_gallery_routes() -> APIRouter:
# the masked region actually changes. # the masked region actually changes.
try: try:
generated = Image.open(io.BytesIO(base64.b64decode(raw_b64))).convert("RGBA") generated = Image.open(io.BytesIO(base64.b64decode(raw_b64))).convert("RGBA")
# Match the generated image to the source dims. blended, full_frame = _compose_cloud_image_edit(
if generated.size != source_png.size: source_png, generated, mask_png,
generated = generated.resize(source_png.size, Image.LANCZOS) instruction=body.get("mode") == "instruction",
# mask_png: white = regenerate (use generated), )
# black = keep (use source).
# Composite: result = source * (1 - mask_norm) + generated * mask_norm
# Image.composite does exactly that with `mask`.
blended = Image.composite(generated, source_png, mask_png)
out_buf = io.BytesIO() out_buf = io.BytesIO()
blended.save(out_buf, format="PNG") blended.save(out_buf, format="PNG")
return {"image": base64.b64encode(out_buf.getvalue()).decode(), "model": oa_model} return {"image": base64.b64encode(out_buf.getvalue()).decode(), "model": oa_model, "full_frame": full_frame}
except Exception as comp_err: except Exception as comp_err:
# Never return a full-image edit when masking fails. # Never return a full-image edit when masking fails.
logger.warning(f"Inpaint compose failed: {comp_err}") logger.warning(f"Inpaint compose failed: {comp_err}")
@@ -2433,11 +2481,10 @@ def setup_gallery_routes() -> APIRouter:
image_b64 = body.get("image") image_b64 = body.get("image")
amount = body.get("amount", 50) / 100.0 amount = body.get("amount", 50) / 100.0
from PIL import Image, ImageFilter from PIL import ImageFilter
import base64, io import base64, io
img_bytes = _b64_bytes(image_b64) img = _b64_to_pil_image(image_b64, mode="RGB")
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
# Unsharp mask: radius=2, percent=amount*200, threshold=3 # Unsharp mask: radius=2, percent=amount*200, threshold=3
sharpened = img.filter(ImageFilter.UnsharpMask(radius=2, percent=int(amount * 200), threshold=3)) sharpened = img.filter(ImageFilter.UnsharpMask(radius=2, percent=int(amount * 200), threshold=3))
@@ -2472,8 +2519,7 @@ def setup_gallery_routes() -> APIRouter:
except ImportError: except ImportError:
raise HTTPException(500, "Server missing a required dependency") raise HTTPException(500, "Server missing a required dependency")
# Decode source image (RGB; Real-ESRGAN doesn't preserve alpha). # Decode source image (RGB; Real-ESRGAN doesn't preserve alpha).
img_bytes = _b64_bytes(image_b64) src = _b64_to_pil_image(image_b64, mode="RGB")
src = Image.open(io.BytesIO(img_bytes)).convert("RGB")
try: try:
patch_realesrgan_torchvision_compat() patch_realesrgan_torchvision_compat()
from realesrgan import RealESRGANer from realesrgan import RealESRGANer
@@ -2525,8 +2571,7 @@ def setup_gallery_routes() -> APIRouter:
import numpy as np import numpy as np
except ImportError: except ImportError:
raise HTTPException(500, "Server missing a required dependency") raise HTTPException(500, "Server missing a required dependency")
img_bytes = _b64_bytes(image_b64) src = _b64_to_pil_image(image_b64, mode="RGB")
src = Image.open(io.BytesIO(img_bytes)).convert("RGB")
try: try:
patch_realesrgan_torchvision_compat() patch_realesrgan_torchvision_compat()
from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.archs.rrdbnet_arch import RRDBNet
@@ -2574,7 +2619,9 @@ def setup_gallery_routes() -> APIRouter:
height = int((body or {}).get("height") or 0) height = int((body or {}).get("height") or 0)
except (TypeError, ValueError): except (TypeError, ValueError):
width = height = 0 width = height = 0
if height > width: if width > 0 and height > 0:
size = f"{width}x{height}"
elif height > width:
size = "1024x1536" size = "1024x1536"
elif width > height: elif width > height:
size = "1536x1024" size = "1536x1024"
@@ -2587,6 +2634,9 @@ def setup_gallery_routes() -> APIRouter:
# The editor's model picker may choose a specific (cloud) image model; # The editor's model picker may choose a specific (cloud) image model;
# forward it so settings defaults only apply when none is selected. # forward it so settings defaults only apply when none is selected.
model_choice = str((body or {}).get("model") or "").strip() model_choice = str((body or {}).get("model") or "").strip()
if body.get("_use_image_settings") is True:
from src.editor_image_settings import editor_image_models
model_choice = editor_image_models(owner=user)["generation"]
payload = {"prompt": prompt, "size": size} payload = {"prompt": prompt, "size": size}
if model_choice: if model_choice:
payload["model"] = model_choice payload["model"] = model_choice
@@ -2778,8 +2828,7 @@ def setup_gallery_routes() -> APIRouter:
from PIL import Image from PIL import Image
import base64, io import base64, io
img_bytes = _b64_bytes(image_b64) img = _b64_to_pil_image(image_b64)
img = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
W, H = img.size W, H = img.size
hint = None hint = None
@@ -2868,8 +2917,7 @@ def setup_gallery_routes() -> APIRouter:
from PIL import Image, ImageFilter, ImageEnhance from PIL import Image, ImageFilter, ImageEnhance
import numpy as np import numpy as np
img_bytes = _b64_bytes(image_b64) img = _b64_to_pil_image(image_b64, mode="RGB")
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
# Try GFPGAN first (AI face restoration) # Try GFPGAN first (AI face restoration)
try: try:
+12 -9
View File
@@ -728,32 +728,35 @@ def setup_note_routes(task_scheduler=None, upload_handler=None):
) )
if body.title is not None: if body.title is not None:
note.title = body.title note.title = body.title
if body.content is not None: # Omitted fields preserve their values; explicit null clears the
# nullable fields used by the editor's removal controls.
supplied = body.model_fields_set
if "content" in supplied:
note.content = body.content note.content = body.content
if body.items is not None: if "items" in supplied:
note.items = json.dumps(body.items) note.items = json.dumps(body.items) if body.items is not None else None
flag_modified(note, "items") flag_modified(note, "items")
if body.note_type is not None: if body.note_type is not None:
note.note_type = body.note_type note.note_type = body.note_type
if body.color is not None: if "color" in supplied:
note.color = body.color note.color = body.color
if body.label is not None: if "label" in supplied:
note.label = body.label note.label = body.label
if body.pinned is not None: if body.pinned is not None:
note.pinned = body.pinned note.pinned = body.pinned
if body.archived is not None: if body.archived is not None:
note.archived = body.archived note.archived = body.archived
if body.due_date is not None: if "due_date" in supplied:
note.due_date = body.due_date note.due_date = body.due_date
if body.image_url is not None: if "image_url" in supplied:
note.image_url = body.image_url note.image_url = body.image_url
if body.gallery_id is not None: if "gallery_id" in supplied:
note.gallery_id = body.gallery_id note.gallery_id = body.gallery_id
if body.repeat is not None: if body.repeat is not None:
note.repeat = body.repeat note.repeat = body.repeat
if body.sort_order is not None: if body.sort_order is not None:
note.sort_order = body.sort_order note.sort_order = body.sort_order
if body.agent_session_id is not None: if "agent_session_id" in supplied:
note.agent_session_id = body.agent_session_id note.agent_session_id = body.agent_session_id
db.commit() db.commit()
+7 -40
View File
@@ -1315,7 +1315,7 @@ def setup_session_routes(
def auto_sort_sessions(request: Request, skip_llm: bool = False): def auto_sort_sessions(request: Request, skip_llm: bool = False):
"""Use AI to categorize all sessions into folders. """Use AI to categorize all sessions into folders.
Phase 1 deletes empty/throwaway sessions and Phase 2 asks the LLM Phase 1 deletes empty/Incognito sessions and Phase 2 asks the LLM
to assign folders. When `skip_llm=true` the endpoint returns to assign folders. When `skip_llm=true` the endpoint returns
after Phase 1 — used by the "Tidy (no AI)" UI affordance so after Phase 1 — used by the "Tidy (no AI)" UI affordance so
users can clean junk without spending tokens. users can clean junk without spending tokens.
@@ -1326,21 +1326,11 @@ def setup_session_routes(
single_user_mode = not user and _auth_disabled() single_user_mode = not user and _auth_disabled()
user_sessions = session_manager.get_sessions_for_user(user) user_sessions = session_manager.get_sessions_for_user(user)
# Delete empty and throwaway sessions before sorting # Saved conversations are never disposable based on their title or prompt.
from core.database import ChatMessage as DbMsg from core.database import ChatMessage as DbMsg
db = SessionLocal() db = SessionLocal()
deleted_empty = 0 deleted_empty = 0
deleted_throwaway = 0 deleted_throwaway = 0
# Names that indicate a throwaway/test session (case-insensitive exact or prefix match)
_THROWAWAY_NAMES = {
"test", "testing", "asdf", "asd", "hello", "hi", "hey",
"yo", "sup", "hola", "hii", "hiii", "heyo",
"foo", "bar", "baz", "tmp", "temp", "scratch", "untitled",
"new chat", "delete", "remove", "junk", "trash", "xxx",
"abc", "qwerty", "blah", "stuff", "whatever", "idk",
"ok", "lol", "bruh", "hmm", "hm", "meh",
}
_THROWAWAY_MAX_MESSAGES = 4 # only delete if <= this many messages
try: try:
rows_q = db.query(DbSession).filter(DbSession.archived == False) rows_q = db.query(DbSession).filter(DbSession.archived == False)
if user: if user:
@@ -1349,15 +1339,11 @@ def setup_session_routes(
rows_q = rows_q.filter(DbSession.owner == user) rows_q = rows_q.filter(DbSession.owner == user)
rows = rows_q.limit(2000).all() rows = rows_q.limit(2000).all()
folder_map = {r.id: r.folder for r in rows} folder_map = {r.id: r.folder for r in rows}
# Precompute per-session message counts in TWO aggregate queries # Precompute per-session message counts in one aggregate query
# instead of 1–3 queries PER session — with many chats the per-row # instead of 1–3 queries PER session — with many chats the per-row
# loop was doing thousands of round-trips and blowing the timeout. # loop was doing thousands of round-trips and blowing the timeout.
from sqlalchemy import func as _sa_func from sqlalchemy import func as _sa_func
_counts = dict(db.query(DbMsg.session_id, _sa_func.count(DbMsg.id)).group_by(DbMsg.session_id).all()) _counts = dict(db.query(DbMsg.session_id, _sa_func.count(DbMsg.id)).group_by(DbMsg.session_id).all())
_asst_counts = dict(
db.query(DbMsg.session_id, _sa_func.count(DbMsg.id))
.filter(DbMsg.role == "assistant").group_by(DbMsg.session_id).all()
)
cleanup_now = utcnow_naive() cleanup_now = utcnow_naive()
for row in rows: for row in rows:
# Never delete important sessions # Never delete important sessions
@@ -1367,9 +1353,10 @@ def setup_session_routes(
if (row.name or "").strip() == "Incognito": if (row.name or "").strip() == "Incognito":
should_delete = True should_delete = True
deleted_throwaway += 1 deleted_throwaway += 1
db.delete(row)
if hasattr(session_manager, 'delete_session'): if hasattr(session_manager, 'delete_session'):
session_manager.delete_session(row.id) session_manager.delete_session(row.id)
else:
db.delete(row)
continue continue
if is_session_recently_active(row, now=cleanup_now): if is_session_recently_active(row, now=cleanup_now):
continue continue
@@ -1378,31 +1365,11 @@ def setup_session_routes(
if msg_count == 0: if msg_count == 0:
should_delete = True should_delete = True
deleted_empty += 1 deleted_empty += 1
elif msg_count <= _THROWAWAY_MAX_MESSAGES:
name = (row.name or "").strip().lower()
# Check first user message content (AI renames sessions, so
# "hi" becomes "Casual Greeting Exchange" — name alone won't match)
first_msg = db.query(DbMsg.content).filter(
DbMsg.session_id == row.id, DbMsg.role == "user"
).order_by(DbMsg.timestamp).first()
first_text = (first_msg[0] or "").strip().lower() if first_msg else ""
# Count assistant messages — if user sent something but AI never replied, it's dead
assistant_count = _asst_counts.get(row.id, 0)
if name in _THROWAWAY_NAMES or name.startswith("chat:") or first_text in _THROWAWAY_NAMES:
should_delete = True
deleted_throwaway += 1
# Single user message with no AI response = dead session
elif msg_count == 1 and assistant_count == 0:
should_delete = True
deleted_throwaway += 1
# Short phrase (1-3 words) with no real AI conversation (<=2 msgs)
elif msg_count <= 2 and first_text and len(first_text.split()) <= 3 and len(first_text) <= 40:
should_delete = True
deleted_throwaway += 1
if should_delete: if should_delete:
db.delete(row)
if hasattr(session_manager, 'delete_session'): if hasattr(session_manager, 'delete_session'):
session_manager.delete_session(row.id) session_manager.delete_session(row.id)
else:
db.delete(row)
if deleted_empty or deleted_throwaway: if deleted_empty or deleted_throwaway:
db.commit() db.commit()
logger.info(f"Auto-sort: deleted {deleted_empty} empty + {deleted_throwaway} throwaway sessions") logger.info(f"Auto-sort: deleted {deleted_empty} empty + {deleted_throwaway} throwaway sessions")
+3 -9
View File
@@ -20,7 +20,7 @@ from src.task_action_policy import (
is_admin_only_task_action, is_admin_only_task_action,
owner_has_admin_task_privileges, owner_has_admin_task_privileges,
) )
from src.task_scheduler import compute_next_run, HOUSEKEEPING_DEFAULTS from src.task_scheduler import compute_next_run, is_valid_cron, HOUSEKEEPING_DEFAULTS
from routes.prefs_routes import _load_for_user, _save_for_user from routes.prefs_routes import _load_for_user, _save_for_user
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -475,10 +475,7 @@ def setup_task_routes(task_scheduler) -> APIRouter:
if req.trigger_type == "schedule" and req.schedule == "cron" and not req.cron_expression: if req.trigger_type == "schedule" and req.schedule == "cron" and not req.cron_expression:
raise HTTPException(400, "Cron expression is required for cron schedule") raise HTTPException(400, "Cron expression is required for cron schedule")
if req.trigger_type == "schedule" and req.schedule == "cron" and req.cron_expression: if req.trigger_type == "schedule" and req.schedule == "cron" and req.cron_expression:
try: if not is_valid_cron(req.cron_expression):
from croniter import croniter
croniter(req.cron_expression)
except Exception:
raise HTTPException(400, "Invalid cron expression") raise HTTPException(400, "Invalid cron expression")
if req.trigger_type == "event" and not req.trigger_event: if req.trigger_type == "event" and not req.trigger_event:
raise HTTPException(400, "Event name is required for event-triggered tasks") raise HTTPException(400, "Event name is required for event-triggered tasks")
@@ -788,10 +785,7 @@ def setup_task_routes(task_scheduler) -> APIRouter:
task.character_id = req.character_id or None task.character_id = req.character_id or None
if req.cron_expression is not None: if req.cron_expression is not None:
if req.cron_expression: if req.cron_expression:
try: if not is_valid_cron(req.cron_expression):
from croniter import croniter
croniter(req.cron_expression)
except Exception:
raise HTTPException(400, "Invalid cron expression") raise HTTPException(400, "Invalid cron expression")
task.cron_expression = req.cron_expression or None task.cron_expression = req.cron_expression or None
+9 -2
View File
@@ -6,6 +6,7 @@ that are awkward at the shell). Filters images by tag, prompt, favorite,
album, and surfaces EXIF metadata. album, and surfaces EXIF metadata.
odysseus-gallery list --limit 20 --favorites odysseus-gallery list --limit 20 --favorites
odysseus-gallery list --tag "sunset,beach" # all tags, manual or AI
odysseus-gallery show IMAGE_ID odysseus-gallery show IMAGE_ID
odysseus-gallery albums | jq -r '.[] | .name' odysseus-gallery albums | jq -r '.[] | .name'
odysseus-gallery search "sunset" # matches prompt + tags odysseus-gallery search "sunset" # matches prompt + tags
@@ -83,7 +84,13 @@ def cmd_list(args):
fail(f"no album named {args.album!r}") fail(f"no album named {args.album!r}")
q = q.filter(GalleryImage.album_id == al.id) q = q.filter(GalleryImage.album_id == al.id)
if args.tag: if args.tag:
q = q.filter(GalleryImage.tags.ilike(f"%{args.tag}%")) for tag in (value.strip() for value in args.tag.split(",")):
if not tag:
continue
q = q.filter(
GalleryImage.tags.ilike(f"%{tag}%") |
GalleryImage.ai_tags.ilike(f"%{tag}%")
)
q = q.order_by(GalleryImage.created_at.desc()).limit(args.limit) q = q.order_by(GalleryImage.created_at.desc()).limit(args.limit)
emit([_serialize_image(i) for i in q.all()], args) emit([_serialize_image(i) for i in q.all()], args)
finally: finally:
@@ -159,7 +166,7 @@ def _build_parser():
pl.add_argument("--limit", type=int, default=50) pl.add_argument("--limit", type=int, default=50)
pl.add_argument("--favorites", action="store_true") pl.add_argument("--favorites", action="store_true")
pl.add_argument("--album", help="filter by album name") pl.add_argument("--album", help="filter by album name")
pl.add_argument("--tag", help="substring match against tags column") pl.add_argument("--tag", help="comma-separated tags; each matches manual or AI tags by substring")
pl.set_defaults(func=cmd_list) pl.set_defaults(func=cmd_list)
psh = sub.add_parser("show", parents=[common]) psh = sub.add_parser("show", parents=[common])
+12 -6
View File
@@ -43,7 +43,7 @@ import logging
import os import os
import re import re
import sys import sys
from datetime import datetime from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
# Anchor the path so the script works when invoked from anywhere. # Anchor the path so the script works when invoked from anywhere.
@@ -136,7 +136,7 @@ def cmd_list(args) -> None:
emit([], args) emit([], args)
return return
all_uids = data[0].split() all_uids = data[0].split()
# Newest first, limit # Keep a bounded arrival batch; order its decoded rows by Date below.
uids = list(reversed(all_uids))[: args.limit] uids = list(reversed(all_uids))[: args.limit]
out = [] out = []
for uid in uids: for uid in uids:
@@ -165,10 +165,15 @@ def cmd_list(args) -> None:
sender_name, sender_addr = parseaddr(sender) sender_name, sender_addr = parseaddr(sender)
date_raw = msg.get("Date", "") date_raw = msg.get("Date", "")
try: try:
iso = parsedate_to_datetime(date_raw).isoformat() if date_raw else "" parsed_date = parsedate_to_datetime(date_raw) if date_raw else None
iso = parsed_date.isoformat() if parsed_date else ""
if parsed_date is not None and parsed_date.tzinfo is None:
parsed_date = parsed_date.replace(tzinfo=timezone.utc)
date_epoch = parsed_date.timestamp() if parsed_date else float("-inf")
except Exception: except Exception:
iso = "" iso = ""
out.append({ date_epoch = float("-inf")
out.append((date_epoch, {
"uid": uid.decode(), "uid": uid.decode(),
"date": iso, "date": iso,
"from_addr": sender_addr, "from_addr": sender_addr,
@@ -176,10 +181,11 @@ def cmd_list(args) -> None:
"subject": subject, "subject": subject,
"is_read": "\\Seen" in flags, "is_read": "\\Seen" in flags,
"is_answered": "\\Answered" in flags, "is_answered": "\\Answered" in flags,
}) }))
except Exception as e: except Exception as e:
sys.stderr.write(f"warn: skipping uid {uid!r}: {e}\n") sys.stderr.write(f"warn: skipping uid {uid!r}: {e}\n")
emit(out, args) out.sort(key=lambda item: item[0], reverse=True)
emit([row for _, row in out], args)
# ─── read ──────────────────────────────────────────────────────────── # ─── read ────────────────────────────────────────────────────────────
+36 -6
View File
@@ -11,6 +11,38 @@ import time
from urllib.request import urlopen from urllib.request import urlopen
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
def _stop_owned_server(server, identity):
"""Close only identity-bound descendants, including MCP's new sessions.
Capture before signalling the parent: an orphaned stderr holder can no
longer be attributed by ancestry. Never search by executable name or kill
the caller's process group.
"""
from src import process_lifecycle as lifecycle
descendants = (lifecycle.bind_descendants([identity.pid])
if identity.verdict() == lifecycle.OWNED else [])
if os.name == "nt":
if identity.verdict() == lifecycle.OWNED:
lifecycle.taskkill_tree(identity.pid)
else:
outcome = lifecycle.terminate_identities(
[*(entry.identity for entry in reversed(descendants)), identity],
steps=lifecycle.term_kill_steps(10),
)
if outcome.survivors or outcome.unverified:
raise RuntimeError(f"Disposable Notes cleanup could not verify exit: {outcome}")
try:
logs, _ = server.communicate(timeout=2)
except subprocess.TimeoutExpired as error:
# Do not turn an unidentified pipe holder into an unbounded wait.
server.stdout.close()
raise RuntimeError("Disposable Notes output pipe remained open after owned cleanup") from error
return logs
def main(): def main():
@@ -36,7 +68,10 @@ def main():
server = subprocess.Popen( server = subprocess.Popen(
[sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1", "--port", str(port)], [sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1", "--port", str(port)],
cwd=target, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=target, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
start_new_session=(os.name != "nt"),
) )
from src.process_lifecycle import ProcessIdentity
server_identity = ProcessIdentity.capture(server.pid)
result = None result = None
try: try:
origin = f"http://127.0.0.1:{port}" origin = f"http://127.0.0.1:{port}"
@@ -62,12 +97,7 @@ def main():
print(result.stderr, file=sys.stderr) print(result.stderr, file=sys.stderr)
return result.returncode return result.returncode
finally: finally:
server.terminate() logs = _stop_owned_server(server, server_identity)
try:
logs, _ = server.communicate(timeout=10)
except subprocess.TimeoutExpired:
server.kill()
logs, _ = server.communicate()
if result is None or result.returncode: if result is None or result.returncode:
print(logs[-8000:], file=sys.stderr) print(logs[-8000:], file=sys.stderr)
+20 -2
View File
@@ -202,17 +202,35 @@ def _infer_use_case(repo_id, pipeline_tag):
return "general" return "general"
# HF collections mix in models no Cookbook LLM backend can serve (vision
# encoders, time-series forecasters, image/video generators). Image models
# have their own registry, so keep these out of the LLM catalog.
_NON_LLM_PIPELINE_TAGS = frozenset({
"time-series-forecasting",
"zero-shot-image-classification",
"image-classification",
"image-feature-extraction",
"text-to-image",
"image-to-video",
"text-to-video",
})
def _entry_from_collection_item(collection, item, source): def _entry_from_collection_item(collection, item, source):
repo_id = item.get("id") or "" repo_id = item.get("id") or ""
if item.get("type") != "model" or not repo_id: if item.get("type") != "model" or not repo_id:
return None return None
if (item.get("pipeline_tag") or "").strip().lower() in _NON_LLM_PIPELINE_TAGS:
return None
repo_prefix = source.get("repo_prefix") repo_prefix = source.get("repo_prefix")
if repo_prefix and not repo_id.startswith(repo_prefix): if repo_prefix and not repo_id.startswith(repo_prefix):
return None return None
raw_params = item.get("numParameters") or 0 raw_params = item.get("numParameters") or 0
active = None # Read the name even when HF gives a total: it is the only source of the
# MoE active size (e.g. "-35B-A3B"), which the speed estimate depends on.
name_params, active = _parse_params_from_name(repo_id)
if not raw_params: if not raw_params:
raw_params, active = _parse_params_from_name(repo_id) raw_params = name_params
param_label, raw_params = _format_params(raw_params) param_label, raw_params = _format_params(raw_params)
if not raw_params: if not raw_params:
return None return None
+6 -2
View File
@@ -84,10 +84,14 @@ _FM_KEY_RE = re.compile(r"^([a-z_][a-z0-9_]*):\s*(.*)$", re.IGNORECASE)
_FM_BLOCK_LIST_RE = re.compile(r"^\s*-\s*(.*)$") _FM_BLOCK_LIST_RE = re.compile(r"^\s*-\s*(.*)$")
def _parse_scalar(raw: str) -> Any: def _parse_scalar(raw: str, *, string_only: bool = False) -> Any:
raw = raw.strip() raw = raw.strip()
if raw == "": if raw == "":
return "" return ""
# String fields keep their spelling; quoted values still use the decoder
# below so existing escapes round-trip as before.
if string_only and not (raw[0] == raw[-1] and raw[0] in ("'", '"')):
return raw
if raw.startswith("[") and raw.endswith("]"): if raw.startswith("[") and raw.endswith("]"):
inner = raw[1:-1].strip() inner = raw[1:-1].strip()
if not inner: if not inner:
@@ -171,7 +175,7 @@ def parse_frontmatter(text: str) -> tuple[Dict[str, Any], str]:
pending_key = key pending_key = key
fm[key] = [] fm[key] = []
else: else:
fm[key] = _parse_scalar(val) fm[key] = _parse_scalar(val, string_only=(key == "version"))
pending_key = None pending_key = None
continue continue
m2 = _FM_BLOCK_LIST_RE.match(line) m2 = _FM_BLOCK_LIST_RE.match(line)
+8 -2
View File
@@ -191,7 +191,7 @@ def _persist_png(image_bytes: bytes, owner: Optional[str], session_id: Optional[
db.close() db.close()
async def _place_layer(data_url: str, name: str, owner: Optional[str], session: str, *, masked: bool = False, blend: str = "normal", opacity: float = 100.0, mode: Optional[str] = None) -> bool: async def _place_layer(data_url: str, name: str, owner: Optional[str], session: str, *, masked: bool = False, blend: str = "normal", opacity: float = 100.0, mode: Optional[str] = None, native_size: bool = False) -> bool:
params: Dict[str, Any] = { params: Dict[str, Any] = {
"dataUrl": data_url, "dataUrl": data_url,
"name": name, "name": name,
@@ -199,6 +199,8 @@ async def _place_layer(data_url: str, name: str, owner: Optional[str], session:
"blend": blend or "normal", "blend": blend or "normal",
"opacity": opacity, "opacity": opacity,
} }
if native_size:
params["nativeSize"] = True
# Forward the edit mode so the client can build a difference mask for # Forward the edit mode so the client can build a difference mask for
# instruction-mode results: the whole image was regenerated under an # instruction-mode results: the whole image was regenerated under an
# instruction prompt, so untouched pixels must stay pixel-identical (the # instruction prompt, so untouched pixels must stay pixel-identical (the
@@ -506,6 +508,8 @@ class AiEditImageTool:
} }
_t["image"] = time.perf_counter() _t["image"] = time.perf_counter()
payload: Dict[str, Any] = {"image": image} payload: Dict[str, Any] = {"image": image}
if args.get("_use_image_settings") is True:
payload["_use_image_settings"] = True
model_choice = str(args.get("model") or "").strip() model_choice = str(args.get("model") or "").strip()
mask_used = False mask_used = False
place_mode: Optional[str] = None place_mode: Optional[str] = None
@@ -609,10 +613,11 @@ class AiEditImageTool:
f"AI {op}", f"AI {op}",
owner, owner,
session, session,
masked=mask_used, masked=mask_used and data.get("full_frame") is not True,
blend=str(args.get("blend") or "normal"), blend=str(args.get("blend") or "normal"),
opacity=float(args.get("opacity") or 100), opacity=float(args.get("opacity") or 100),
mode=place_mode, mode=place_mode,
native_size=data.get("full_frame") is True,
) )
info["placed"] = placed info["placed"] = placed
if placed: if placed:
@@ -687,6 +692,7 @@ class GenerateImageLayerTool:
str(args.get("name") or "Generated image"), str(args.get("name") or "Generated image"),
owner, owner,
session, session,
native_size=True,
masked=bool(args.get("mask")), masked=bool(args.get("mask")),
blend=str(args.get("blend") or "normal"), blend=str(args.get("blend") or "normal"),
opacity=float(args.get("opacity") or 100), opacity=float(args.get("opacity") or 100),
+130 -21
View File
@@ -179,8 +179,13 @@ def _resolve_model(spec: str, owner: Optional[str] = None, model_type: Optional[
# served internal id. Include pinned/cached ids in the match set # served internal id. Include pinned/cached ids in the match set
# so chat sessions using the HF repo id still resolve. Do not use # so chat sessions using the HF repo id still resolve. Do not use
# stale cached aliases when the endpoint itself is unreachable. # stale cached aliases when the endpoint itself is unreachable.
if model_type == "image" and endpoint_reachable: if endpoint_reachable:
for extra in _json_list(getattr(ep, "pinned_models", None)) + _json_list(getattr(ep, "cached_models", None)): # Gateway image models may live in a dedicated catalogue,
# so explicitly pinned IDs are valid on mixed endpoints too.
extras = _json_list(getattr(ep, "pinned_models", None))
if model_type == "image":
extras += _json_list(getattr(ep, "cached_models", None))
for extra in extras:
if extra not in model_ids: if extra not in model_ids:
model_ids.append(extra) model_ids.append(extra)
@@ -1200,6 +1205,39 @@ def image_editing_provider_available(owner: Optional[str] = None) -> bool:
return False return False
def _uses_openrouter_chat_images(model_id: str) -> bool:
# GPT-5 Image is an LLM wrapper, unlike native gpt-image-* image models.
leaf = model_id_leaf(model_id).lower()
return leaf.startswith("gpt-") and "-image" in leaf and not leaf.startswith("gpt-image-")
def _chat_image_results(data: dict) -> list:
images = []
for choice in data.get("choices") or []:
message = choice.get("message") or {}
for item in message.get("images") or []:
url = (item.get("image_url") or {}).get("url")
if not isinstance(url, str):
continue
if url.startswith("data:image/") and ";base64," in url:
images.append({"b64_json": url.split(",", 1)[1]})
elif url.startswith(("https://", "http://")):
images.append({"url": url})
return images
def _image_response_error(data: dict, model_id: str) -> Optional[str]:
errors = [data.get("error")]
errors.extend(choice.get("error") for choice in data.get("choices") or [])
for error in errors:
if not error:
continue
message = str(error.get("message") or "Image provider failed") if isinstance(error, dict) else str(error)
hint = " Choose a currently supported image model in AI settings." if "deprecated" in message.lower() else ""
return f"Image provider failed for '{model_id}': {message}{hint}"
return None
async def do_generate_image(content: str, session_id: Optional[str] = None, owner: Optional[str] = None, *, incognito: bool = False) -> Dict: async def do_generate_image(content: str, session_id: Optional[str] = None, owner: Optional[str] = None, *, incognito: bool = False) -> Dict:
"""Generate an image using an image-capable model (e.g. gpt-image-1). """Generate an image using an image-capable model (e.g. gpt-image-1).
@@ -1207,7 +1245,7 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
Line 1: prompt describing the image Line 1: prompt describing the image
Line 2: model name (optional, default auto-detects: prefers gpt-image-1.5 > gpt-image-1) Line 2: model name (optional, default auto-detects: prefers gpt-image-1.5 > gpt-image-1)
Line 3: size (optional, defaults to 1024x1024) Line 3: size (optional, defaults to 1024x1024)
Line 4: quality (optional, defaults to medium — options: low, medium, high, auto) Line 4: quality (optional, defaults to configured quality or medium — low, medium, high, auto)
""" """
import base64 import base64
import httpx import httpx
@@ -1225,32 +1263,34 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
prompt = str(args.get('prompt') or '').strip() prompt = str(args.get('prompt') or '').strip()
model_spec = str(args.get('model') or '').strip() model_spec = str(args.get('model') or '').strip()
size = str(args.get('size') or '1024x1024') size = str(args.get('size') or '1024x1024')
quality = str(args.get('quality') or 'medium') quality = str(args.get('quality') or '')
else: else:
lines = content.strip().split("\n") lines = content.strip().split("\n")
prompt = lines[0].strip() if lines else "" prompt = lines[0].strip() if lines else ""
model_spec = lines[1].strip() if len(lines) > 1 and lines[1].strip() else "" model_spec = lines[1].strip() if len(lines) > 1 and lines[1].strip() else ""
size = lines[2].strip() if len(lines) > 2 and lines[2].strip() else "1024x1024" size = lines[2].strip() if len(lines) > 2 and lines[2].strip() else "1024x1024"
quality = lines[3].strip() if len(lines) > 3 and lines[3].strip() else "medium" quality = lines[3].strip() if len(lines) > 3 and lines[3].strip() else ""
if not prompt: if not prompt:
return {"error": "Image prompt is required (line 1)"} return {"error": "Image prompt is required (line 1)"}
# Load admin settings for defaults # Load settings for defaults
try: try:
from src.settings import load_settings from src.settings import get_user_setting, load_settings
_settings = load_settings() _settings = load_settings()
except Exception: except Exception:
_settings = {} _settings = {}
def get_user_setting(key, owner="", default=None):
return default
if not _settings.get("image_gen_enabled", True): if not get_user_setting("image_gen_enabled", owner=owner, default=True):
return {"error": "Image generation is disabled by the administrator."} return {"error": "Image generation is disabled by the administrator."}
# Use admin-configured model/quality if not specified by the tool call # Use user- or admin-configured model/quality if not specified by the tool call
if not model_spec: if not model_spec:
model_spec = _settings.get("image_model", "") model_spec = get_user_setting("image_model", owner=owner, default="") or ""
if quality == "medium" and _settings.get("image_quality"): if not quality:
quality = _settings["image_quality"] quality = get_user_setting("image_quality", owner=owner, default="medium") or "medium"
# Auto-detect best available image model if still not set # Auto-detect best available image model if still not set
if not model_spec: if not model_spec:
@@ -1342,8 +1382,19 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
base_url = url.replace("/chat/completions", "").replace("/v1/messages", "").rstrip("/") base_url = url.replace("/chat/completions", "").replace("/v1/messages", "").rstrip("/")
images_url = base_url + "/images/generations" images_url = base_url + "/images/generations"
from src.model_capability_readers.base import detect_vendor from src.model_capability_readers.base import detect_vendor
chat_images = detect_vendor(url) == "openrouter" and _uses_openrouter_chat_images(model_id)
if detect_vendor(url) == "openrouter": if detect_vendor(url) == "openrouter":
images_url = base_url + "/images" images_url = base_url + "/images"
if chat_images:
images_url = base_url + "/chat/completions"
# Capture the requested geometry before older OpenAI size restrictions.
from src.image_model_ids import image_aspect_ratio
try:
requested_width, requested_height = (int(value) for value in size.lower().split("x"))
requested_ratio = image_aspect_ratio(requested_width, requested_height)
except (TypeError, ValueError):
requested_ratio = "1:1"
# Validate size for cloud image models (local diffusion accepts any WxH) # Validate size for cloud image models (local diffusion accepts any WxH)
valid_gpt_sizes = {"1024x1024", "1024x1536", "1536x1024", "auto"} valid_gpt_sizes = {"1024x1024", "1024x1536", "1536x1024", "auto"}
@@ -1359,6 +1410,9 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
"n": 1, "n": 1,
"size": size, "size": size,
} }
if detect_vendor(url) == "openrouter":
payload.pop("size", None)
payload["aspect_ratio"] = requested_ratio
# GPT image models and local diffusion support quality; DALL-E does not # GPT image models and local diffusion support quality; DALL-E does not
if is_gpt_image or is_local_diffusion: if is_gpt_image or is_local_diffusion:
@@ -1372,7 +1426,16 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
try: try:
# GPT image models can take 30-120s+ depending on quality # GPT image models can take 30-120s+ depending on quality
async with httpx.AsyncClient(timeout=httpx.Timeout(connect=30.0, read=300.0, write=30.0, pool=30.0)) as client: async with httpx.AsyncClient(timeout=httpx.Timeout(connect=30.0, read=300.0, write=30.0, pool=30.0)) as client:
resp = await client.post(images_url, json=payload, headers=headers) request_payload = payload
if chat_images:
request_payload = {
"model": model_id,
"messages": [{"role": "user", "content": prompt}],
"modalities": ["image", "text"],
"stream": False,
"image_config": {"aspect_ratio": requested_ratio},
}
resp = await client.post(images_url, json=request_payload, headers=headers)
if resp.status_code != 200: if resp.status_code != 200:
error_text = resp.text[:500] error_text = resp.text[:500]
@@ -1387,9 +1450,15 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
} }
data = resp.json() data = resp.json()
images = data.get("data", []) provider_error = _image_response_error(data, model_id)
if provider_error:
return {"error": provider_error, "untrusted_content": True}
images = _chat_image_results(data) if chat_images else data.get("data", [])
if not images: if not images:
return {"error": "No images returned from API"} return {"error": (
f"Image model '{model_id}' returned no image. "
"Choose another image generation model in AI settings."
)}
img = images[0] img = images[0]
image_url = None image_url = None
@@ -1482,7 +1551,7 @@ async def do_edit_image(
session_id: Optional[str] = None, session_id: Optional[str] = None,
owner: Optional[str] = None, owner: Optional[str] = None,
size: str = "auto", size: str = "auto",
quality: str = "medium", quality: Optional[str] = None,
progress_callback: Optional[Callable[[Dict[str, Any]], Awaitable[None]]] = None, progress_callback: Optional[Callable[[Dict[str, Any]], Awaitable[None]]] = None,
incognito: bool = False, incognito: bool = False,
) -> Dict: ) -> Dict:
@@ -1502,21 +1571,27 @@ async def do_edit_image(
return {"error": "Attached image file was not found"} return {"error": "Attached image file was not found"}
try: try:
from src.settings import load_settings from src.settings import get_user_setting, load_settings
_settings = load_settings() _settings = load_settings()
except Exception: except Exception:
_settings = {} _settings = {}
def get_user_setting(key, owner="", default=None):
return default
if not model_spec: if not model_spec:
model_spec = _settings.get("image_model", "") model_spec = get_user_setting("image_edit_model", owner=owner) or get_user_setting("image_model", owner=owner, default="")
if quality == "medium" and _settings.get("image_quality"): if quality is None:
quality = _settings["image_quality"] quality = get_user_setting("image_quality", owner=owner, default="medium") or "medium"
if not model_spec: if not model_spec:
return {"error": "No image model selected for image editing"} return {"error": "No image model selected for image editing"}
try: try:
try: try:
def _call(): def _call():
try:
return _resolve_model(model_spec, owner=owner)
except ValueError:
pass
try: try:
return _resolve_model(model_spec, owner=owner, model_type="image") return _resolve_model(model_spec, owner=owner, model_type="image")
except TypeError as exc: except TypeError as exc:
@@ -1529,6 +1604,7 @@ async def do_edit_image(
except ValueError: except ValueError:
return {"error": f"No endpoint found with image model '{model_spec}'."} return {"error": f"No endpoint found with image model '{model_spec}'."}
requested_edit_size = size
if not size or size == "auto": if not size or size == "auto":
from PIL import Image from PIL import Image
from src.image_model_ids import image_edit_size from src.image_model_ids import image_edit_size
@@ -1704,6 +1780,34 @@ async def do_edit_image(
"image_url": {"url": f"data:{mime};base64,{image_b64}"}, "image_url": {"url": f"data:{mime};base64,{image_b64}"},
}], }],
} }
from src.image_model_ids import image_aspect_ratio
from PIL import Image as ReferenceImage
with ReferenceImage.open(path) as reference:
reference_width, reference_height = reference.size
if reference.getexif().get(274) in {5, 6, 7, 8}:
reference_width, reference_height = reference_height, reference_width
if requested_edit_size and requested_edit_size != "auto":
try:
reference_width, reference_height = (int(value) for value in requested_edit_size.lower().split("x"))
except (TypeError, ValueError):
pass
edit_payload.pop("size", None)
edit_payload["aspect_ratio"] = image_aspect_ratio(reference_width, reference_height)
if _uses_openrouter_chat_images(model_id):
edit_payload = {
"model": model_id,
"messages": [{"role": "user", "content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {
"url": f"data:{mime};base64,{image_b64}",
}},
]}],
"modalities": ["image", "text"],
"stream": False,
"image_config": {"aspect_ratio": edit_payload["aspect_ratio"]},
}
resp = await client.post(base_url + "/chat/completions", json=edit_payload, headers=headers)
else:
resp = await client.post(base_url + "/images", json=edit_payload, headers=headers) resp = await client.post(base_url + "/images", json=edit_payload, headers=headers)
else: else:
with path.open("rb") as f: with path.open("rb") as f:
@@ -1747,7 +1851,12 @@ async def do_edit_image(
} }
data = resp.json() data = resp.json()
images = data.get("data", []) provider_error = _image_response_error(data, model_id)
if provider_error:
return {"error": provider_error, "untrusted_content": True}
images = (_chat_image_results(data)
if is_openrouter and _uses_openrouter_chat_images(model_id)
else data.get("data", []))
if not images: if not images:
return {"error": "No image returned from edit API"} return {"error": "No image returned from edit API"}
+3 -2
View File
@@ -25,7 +25,7 @@ def compact_browser_observation(value, budget=8000):
# Snapshot text already contains labels and refs in DOM order. # Snapshot text already contains labels and refs in DOM order.
# The refs mapping repeats them and buries menus in raw JSON. # The refs mapping repeats them and buries menus in raw JSON.
lines = [line for line in snapshot.splitlines() lines = [line for line in snapshot.splitlines()
if not re.fullmatch(r'\s*-?\s*generic(?:\s+\[ref=e\d+\])?:?\s*', line)] if not re.fullmatch(r'\s*(?:-\s*)?generic(?:\s+\[ref=e\d+\])?:?\s*', line)]
pages.append(('URL: ' + str(url) + '\n' if url else '') + '\n'.join(lines)) pages.append(('URL: ' + str(url) + '\n' if url else '') + '\n'.join(lines))
elif url: elif url:
notices.append('URL: ' + str(url)) notices.append('URL: ' + str(url))
@@ -37,7 +37,8 @@ def compact_browser_observation(value, budget=8000):
parsed = json.loads(item) parsed = json.loads(item)
except (ValueError, TypeError): except (ValueError, TypeError):
# CLI status text precedes the JSON post-interaction state. # CLI status text precedes the JSON post-interaction state.
parts = re.split(r'\n\n\[(?:post-[^\]]+|page state after failed [^\]]+)\]\n', item) # Labels are one line; stopping at \n keeps the split linear.
parts = re.split(r'\n\n\[(?:post-[^\]\n]+|page state after failed [^\]\n]+)\]\n', item)
if len(parts) > 1: if len(parts) > 1:
for part in parts: for part in parts:
visit(part) visit(part)
+14 -8
View File
@@ -1229,7 +1229,7 @@ def tasks_terminal_response(raw, *, user_text='', max_items=20):
text = str(payload or '').strip() text = str(payload or '').strip()
rows = [] rows = []
for line in text.splitlines(): for line in text.splitlines():
match = re.match(r'^\s*\d+\.\s+(.*?)\s+\(([^)]+)\)\s+—\s+(.+)$', line) match = re.match(r'^\s*\d+\.\s(.*?)\s\(([^()]+)\)\s+—\s+(.+)$', line)
if match: if match:
details = match[3].strip() details = match[3].strip()
rows.append({ rows.append({
@@ -1346,7 +1346,7 @@ def skills_terminal_response(raw, *, user_text='', max_items=20):
continue continue
match = re.match(r'^\s*-\s+\*\*([^*]+)\*\*(?:\s+\(([^)]+)\))?', line) match = re.match(r'^\s*-\s+\*\*([^*]+)\*\*(?:\s+\(([^)]+)\))?', line)
if not match: if not match:
match = re.match(r'^\s*-\s+([^:]+?)(?:\s+\(([^)]+)\))?(?:\s*:|$)', line) match = re.match(r'^\s*-\s+([^\s:][^:]*?)(?:\s\(([^()]+)\)(?:\s*:|$)|:|$)', line)
if match and status: if match and status:
rows.append((status, match.group(1).strip(), (match.group(2) or '').strip())) rows.append((status, match.group(1).strip(), (match.group(2) or '').strip()))
if not rows: if not rows:
@@ -5065,7 +5065,7 @@ def email_search_result_empty(value):
try: try:
decoded = json.loads(value) decoded = json.loads(value)
except (TypeError, ValueError): except (TypeError, ValueError):
return bool(re.fullmatch(r'\s*No emails matched [^\n]+\.?\s*', value, re.I)) return bool(re.fullmatch(r'\s*No emails matched [^\n]+(?:\n\s*)?', value, re.I))
if decoded == value: if decoded == value:
return False return False
value = decoded value = decoded
@@ -5339,6 +5339,16 @@ def private_browser_effective_url(result):
return urls[-1] if urls else '' return urls[-1] if urls else ''
def is_google_sorry_url(url):
"""Recognize Google's rate-limit interstitial."""
# Matching the host separately keeps this linear; one combined pattern
# rescans the host from every dot.
return any(
re.fullmatch(r'(?:[^/]+\.)?google\.[^/]+', host[1], re.I)
for host in re.finditer(r'https?://([^/]+)/sorry/', url, re.I)
)
def browser_observation_page_missing(raw): def browser_observation_page_missing(raw):
"""Recognize a rendered error page, rather than an article mentioning 404.""" """Recognize a rendered error page, rather than an article mentioning 404."""
text = str(raw or '') text = str(raw or '')
@@ -8213,11 +8223,7 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
browser_search_url = requested_browser_url or effective_browser_url browser_search_url = requested_browser_url or effective_browser_url
is_search_engine_navigation = contains_search_engine_navigation( is_search_engine_navigation = contains_search_engine_navigation(
browser_search_url browser_search_url
) or bool(re.search( ) or is_google_sorry_url(effective_browser_url)
r'https?://(?:[^/]+\.)?google\.[^/]+/sorry/',
effective_browser_url,
re.I,
))
has_native_search = any( has_native_search = any(
canonical(schema['function']['name']) == 'web_search' canonical(schema['function']['name']) == 'web_search'
for schema in offered for schema in offered
+19
View File
@@ -0,0 +1,19 @@
"""The shared model defaults used by Quick Edit's image operations."""
from src.settings import get_user_setting, load_settings
def editor_image_models(owner: str = "") -> dict[str, str]:
settings = load_settings()
generation = ""
edit_model = ""
if owner:
generation = str(get_user_setting("image_model", owner=owner, default="") or "").strip()
edit_model = str(get_user_setting("image_edit_model", owner=owner, default="") or "").strip()
if not generation:
generation = str(settings.get("image_model") or "").strip()
if not edit_model:
edit_model = str(settings.get("image_edit_model") or generation).strip()
return {
"generation": generation,
"edit": edit_model or generation,
}
+9
View File
@@ -40,6 +40,15 @@ def image_edit_size(model_id: str, width: int, height: int) -> str:
return f"{width}x{height}" return f"{width}x{height}"
def image_aspect_ratio(width: int, height: int) -> str:
"""Choose the nearest common Image API ratio, without distorting pixels."""
if width <= 0 or height <= 0:
raise ValueError("Image dimensions must be positive")
ratios = ((1, 1), (16, 9), (9, 16), (3, 2), (2, 3), (4, 3), (3, 4), (21, 9))
w, h = min(ratios, key=lambda ratio: abs(math.log((ratio[0] / ratio[1]) / (width / height))))
return f"{w}:{h}"
def looks_like_image_generation_model(model_id: str) -> bool: def looks_like_image_generation_model(model_id: str) -> bool:
"""Return True when a model id should use image generation routes. """Return True when a model id should use image generation routes.
+49 -11
View File
@@ -422,7 +422,18 @@ def _stream_delta_event(text: str, *, thinking: bool = False) -> str:
return f"data: {json.dumps(payload)}\n\n" return f"data: {json.dumps(payload)}\n\n"
_DEGENERATE_WORD_RE = re.compile(r"[A-Za-z0-9_\u0370-\u03ff\u0400-\u04ff]+") _WORD_CHARS = r"A-Za-z0-9_\u0370-\u03ff\u0400-\u04ff"
_DELIM_RE = re.compile(rf"[^{_WORD_CHARS}+\-.]")
_NUMERIC_PATTERN = rf"(?<![{_WORD_CHARS}])[+-]?(?:[0-9]+\.[0-9]+|\.[0-9]+|[0-9]+)(?:[eE][+-]?[0-9]+)?(?![{_WORD_CHARS}])"
_NUMERIC_FULLMATCH_RE = re.compile(rf"^[+-]?(?:[0-9]+\.[0-9]+|\.[0-9]+|[0-9]+)(?:[eE][+-]?[0-9]+)?$")
_DEGENERATE_WORD_RE = re.compile(rf"[{_WORD_CHARS}]+")
_TOKEN_RE = re.compile(rf"(?P<NUM>{_NUMERIC_PATTERN})|(?P<WORD>[{_WORD_CHARS}]+)")
def _is_numeric_token(token: str) -> bool:
if token.isdigit():
return True
return _NUMERIC_FULLMATCH_RE.fullmatch(token) is not None
class _DegenerateStreamGuard: class _DegenerateStreamGuard:
@@ -432,32 +443,50 @@ class _DegenerateStreamGuard:
"Summer Summer ..."). This is not a useful response and can burn context, "Summer Summer ..."). This is not a useful response and can burn context,
browser memory, and GPU time. Keep the guard conservative: only fire on long browser memory, and GPU time. Keep the guard conservative: only fire on long
same-token runs or a very dominant repeated token in the recent window. same-token runs or a very dominant repeated token in the recent window.
Repetition made only of numbers is data (a zero or identity matrix, a
padded buffer), so it only stops at a long all-numeric backstop.
""" """
def __init__(self, model: str): def __init__(self, model: str):
self.model = model or "model" self.model = model or "model"
self.last_token = "" self.last_token = ""
self.same_run = 0 self.same_run = 0
self.numeric_run = 0
self.recent_tokens: List[str] = [] self.recent_tokens: List[str] = []
self.periodic_tokens: List[str] = [] self.periodic_tokens: List[str] = []
self.total_chars = 0 self.total_chars = 0
self._buffer = ""
def check(self, text: str) -> Optional[str]: def check(self, text: str) -> Optional[str]:
if not text: if not text:
return None return None
self.total_chars += len(text) self.total_chars += len(text)
# Keep one-character tokens. Structured output often varies through self._buffer += text
# numeric selectors or coordinates; dropping those tokens can make
# valid CSS/SVG rows look like an exact repeated phrase. m_delims = list(_DELIM_RE.finditer(self._buffer))
tokens = [t.lower() for t in _DEGENERATE_WORD_RE.findall(text)] if m_delims:
split_idx = m_delims[-1].end()
head = self._buffer[:split_idx]
self._buffer = self._buffer[split_idx:]
elif len(self._buffer) >= 256:
head = self._buffer
self._buffer = ""
else:
return None
tokens = []
for m in _TOKEN_RE.finditer(head):
tokens.append((m.group(0).lower(), m.lastgroup == "NUM"))
if not tokens: if not tokens:
return None return None
for token in tokens:
for token, is_num in tokens:
if token == self.last_token: if token == self.last_token:
self.same_run += 1 self.same_run += 1
else: else:
self.last_token = token self.last_token = token
self.same_run = 1 self.same_run = 1
self.numeric_run = self.numeric_run + 1 if is_num else 0
self.recent_tokens.append(token) self.recent_tokens.append(token)
self.periodic_tokens.append(token) self.periodic_tokens.append(token)
if len(self.recent_tokens) > 96: if len(self.recent_tokens) > 96:
@@ -466,14 +495,20 @@ class _DegenerateStreamGuard:
self.periodic_tokens = self.periodic_tokens[-2048:] self.periodic_tokens = self.periodic_tokens[-2048:]
reason = None reason = None
if self.same_run >= 28 and self.total_chars >= 100: if self.same_run >= 28 and self.total_chars >= 100 and not _is_numeric_token(self.last_token):
reason = f"repeated '{self.last_token}' {self.same_run} times" reason = f"repeated '{self.last_token}' {self.same_run} times"
elif len(self.recent_tokens) >= 72: elif len(self.recent_tokens) >= 72:
top = max(set(self.recent_tokens), key=self.recent_tokens.count) top = max(set(self.recent_tokens), key=self.recent_tokens.count)
count = self.recent_tokens.count(top) count = self.recent_tokens.count(top)
if count >= 60 and count / max(len(self.recent_tokens), 1) >= 0.78: if count >= 60 and count / max(len(self.recent_tokens), 1) >= 0.78 and not _is_numeric_token(top):
reason = f"repeated '{top}' {count}/{len(self.recent_tokens)} recent tokens" reason = f"repeated '{top}' {count}/{len(self.recent_tokens)} recent tokens"
if not reason and len(self.recent_tokens) >= 48: if (
not reason
and len(self.recent_tokens) >= 48
# A window that is mostly numbers is matrix/table data; its
# periodicity is real. Mixed loops still hit the exact-block check.
and sum(_is_numeric_token(t) for t in self.recent_tokens) * 2 < len(self.recent_tokens)
):
# Detect a periodic suffix instead of counting repeated n-grams. # Detect a periodic suffix instead of counting repeated n-grams.
# Reused property names are normal in CSS/SVG/JSON; a collapsed # Reused property names are normal in CSS/SVG/JSON; a collapsed
# generation repeats nearly every token at a short fixed period. # generation repeats nearly every token at a short fixed period.
@@ -508,12 +543,15 @@ class _DegenerateStreamGuard:
if history[previous:previous + anchor_size] != anchor: if history[previous:previous + anchor_size] != anchor:
continue continue
period = current_anchor - previous period = current_anchor - previous
if period < 24 or len(history) < period * 2: if period < 24 or len(history) < period * 2 or self.numeric_run >= period:
continue continue
if history[-2 * period:-period] == history[-period:]: if history[-2 * period:-period] == history[-period:] and not all(_is_numeric_token(t) for t in history[-period:]):
reason = f"repeated an exact {period}-token block twice" reason = f"repeated an exact {period}-token block twice"
break break
if not reason and self.numeric_run >= 2048:
reason = f"emitted {self.numeric_run} numbers in a row"
if not reason: if not reason:
return None return None
+10
View File
@@ -10,6 +10,7 @@ import logging
import os import os
import re import re
import asyncio import asyncio
import contextlib
from typing import Any, Dict, List, Optional, Set, Tuple from typing import Any, Dict, List, Optional, Set, Tuple
from src.database import McpServer, SessionLocal from src.database import McpServer, SessionLocal
@@ -383,12 +384,21 @@ class McpManager:
provider = build_provider(server_id, url, on_redirect=_on_redirect) provider = build_provider(server_id, url, on_redirect=_on_redirect)
stack = AsyncExitStack() stack = AsyncExitStack()
try:
transport = await stack.enter_async_context(streamablehttp_client(url, auth=provider)) transport = await stack.enter_async_context(streamablehttp_client(url, auth=provider))
read_stream, write_stream, _get_session_id = transport read_stream, write_stream, _get_session_id = transport
session = await stack.enter_async_context(ClientSession(read_stream, write_stream)) session = await stack.enter_async_context(ClientSession(read_stream, write_stream))
await session.initialize() await session.initialize()
tools_result = await session.list_tools() tools_result = await session.list_tools()
except BaseException:
# Close the half-open transport here, in the task that entered
# it. Left for the garbage collector, its AnyIO cancel scope is
# exited from the wrong task and the event loop keeps spinning
# (#5518). Its own teardown error would only mask the real one.
with contextlib.suppress(Exception):
await stack.aclose()
raise
tools = [] tools = []
for tool in tools_result.tools: for tool in tools_result.tools:
tools.append({ tools.append({
+4 -1
View File
@@ -193,7 +193,10 @@ class ModelDiscovery:
data = r.json() data = r.json()
# Some OpenAI-compatible servers return a bare list, not {"data": [...]}. # Some OpenAI-compatible servers return a bare list, not {"data": [...]}.
items = data if isinstance(data, list) else ((data or {}).get("data") or []) items = data if isinstance(data, list) else ((data or {}).get("data") or [])
ids = [m.get("id") for m in items if isinstance(m, dict) and m.get("id")] ids = [
m["id"] for m in items
if isinstance(m, dict) and isinstance(m.get("id"), str) and m["id"]
]
if ids: if ids:
return { return {
"host": host, "host": host,
+4 -2
View File
@@ -102,8 +102,10 @@ _PLAIN_FRONT_MATTER_RE = re.compile(
# - **label:** value <!-- field=NAME-ENC type=text --> # - **label:** value <!-- field=NAME-ENC type=text -->
# - **label** [opts]: value <!-- field=NAME-ENC type=choice --> # - **label** [opts]: value <!-- field=NAME-ENC type=choice -->
# - [x] **label** <!-- field=NAME-ENC type=checkbox --> # - [x] **label** <!-- field=NAME-ENC type=checkbox -->
# Accept Unicode word characters for older saved markers, whose encoder left
# non-ASCII letters/numbers literal. Newly rendered names are ASCII-safe.
_FIELD_BULLET_RE = re.compile( _FIELD_BULLET_RE = re.compile(
r'^\s*-\s+(?P<body>.*?)\s*<!--\s*field=(?P<name>[A-Za-z0-9_.%-]+)\s+type=(?P<type>\w+)\s*-->\s*$' r'^\s*-\s+(?P<body>.*?)\s*<!--\s*field=(?P<name>[\w.%-]+)\s+type=(?P<type>\w+)\s*-->\s*$'
) )
@@ -115,7 +117,7 @@ def _encode_name(name: str) -> str:
""" """
out = [] out = []
for ch in name or "": for ch in name or "":
if ch.isalnum() or ch in ("_", ".", "-"): if (ch.isascii() and ch.isalnum()) or ch in ("_", ".", "-"):
out.append(ch) out.append(ch)
else: else:
for b in ch.encode("utf-8"): for b in ch.encode("utf-8"):
+8 -51
View File
@@ -12,16 +12,6 @@ from datetime import datetime, timedelta, timezone
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Names that indicate a throwaway/test session
_THROWAWAY_NAMES = {
"test", "testing", "asdf", "asd", "hello", "hi", "hey",
"yo", "sup", "hola", "hii", "hiii", "heyo",
"foo", "bar", "baz", "tmp", "temp", "scratch", "untitled",
"new chat", "delete", "remove", "junk", "trash", "xxx",
"abc", "qwerty", "blah", "stuff", "whatever", "idk",
"ok", "lol", "bruh", "hmm", "hm", "meh",
}
_THROWAWAY_MAX_MESSAGES = 4
_FRESH_EMPTY_SESSION_GRACE = timedelta(minutes=10) _FRESH_EMPTY_SESSION_GRACE = timedelta(minutes=10)
_FRESH_SESSION_GRACE = _FRESH_EMPTY_SESSION_GRACE _FRESH_SESSION_GRACE = _FRESH_EMPTY_SESSION_GRACE
@@ -54,14 +44,15 @@ def is_session_recently_active(row, now=None, grace=_FRESH_SESSION_GRACE) -> boo
async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bool = True) -> str: async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bool = True) -> str:
"""Run session cleanup + (optional) AI folder sort for the given owner. """Remove empty/Incognito sessions and optionally organize saved chats.
Args: Args:
owner: user whose sessions to process owner: user whose sessions to process
skip_llm: when True, do only Phase 1 (delete empty/throwaway sessions); skip_llm: when True, do only Phase 1 (delete empty/Incognito sessions);
skip Phase 2 (AI folder assignment). Used by the built-in daily skip Phase 2 (AI folder assignment). Used by the built-in daily
background sweep so it never burns LLM tokens. background sweep so it never burns LLM tokens.
delete_throwaway: when False, only empty/incognito sessions are deleted. delete_throwaway: retained for caller compatibility. Ordinary sessions
with saved messages are always preserved, regardless of this flag.
Returns a human-readable summary of what was done. Returns a human-readable summary of what was done.
""" """
@@ -71,7 +62,7 @@ async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bo
db = SessionLocal() db = SessionLocal()
try: try:
# ── Phase 1: Delete empty/throwaway sessions ── # ── Phase 1: Delete only empty and explicitly Incognito sessions ──
deleted_empty = 0 deleted_empty = 0
deleted_throwaway = 0 deleted_throwaway = 0
@@ -93,47 +84,13 @@ async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bo
if is_session_recently_active(row, now=cleanup_now): if is_session_recently_active(row, now=cleanup_now):
continue continue
msg_count = db.query(DbMsg.id).filter( has_messages = db.query(DbMsg.id).filter(
DbMsg.session_id == row.id DbMsg.session_id == row.id
).limit(_THROWAWAY_MAX_MESSAGES + 1).count() ).first() is not None
should_delete = False if not has_messages:
if msg_count == 0:
if is_fresh: if is_fresh:
continue continue
should_delete = True
deleted_empty += 1 deleted_empty += 1
elif delete_throwaway and msg_count <= _THROWAWAY_MAX_MESSAGES:
name = (row.name or "").strip().lower()
first_msg = db.query(DbMsg.content).filter(
DbMsg.session_id == row.id, DbMsg.role == "user"
).order_by(DbMsg.timestamp).first()
first_text = (first_msg[0] or "").strip().lower() if first_msg else ""
assistant_count = db.query(DbMsg.id).filter(
DbMsg.session_id == row.id, DbMsg.role == "assistant"
).limit(1).count()
if name in _THROWAWAY_NAMES or name.startswith("chat:") or first_text in _THROWAWAY_NAMES:
should_delete = True
deleted_throwaway += 1
elif msg_count == 1 and assistant_count == 0:
should_delete = True
deleted_throwaway += 1
elif msg_count <= 4 and first_text and len(first_text.split()) <= 8 and len(first_text) <= 80:
# Short trivial chats — e.g. "write hi to a friend" → "Hi!"
should_delete = True
deleted_throwaway += 1
else:
# Aggressive: total message text under 250 chars combined = trivial
msg_rows = db.query(DbMsg.content).filter(
DbMsg.session_id == row.id
).all()
total_chars = sum(len(m[0] or "") for m in msg_rows)
if total_chars <= 250:
should_delete = True
deleted_throwaway += 1
if should_delete:
db.delete(row) db.delete(row)
if deleted_empty or deleted_throwaway: if deleted_empty or deleted_throwaway:
+2 -1
View File
@@ -46,6 +46,7 @@ DEFAULT_SETTINGS = {
"agent_email_confirm": True, "agent_email_confirm": True,
"image_gen_enabled": False, "image_gen_enabled": False,
"image_model": "", "image_model": "",
"image_edit_model": "",
"image_quality": "medium", "image_quality": "medium",
# Optional editor planner/caption endpoints. Empty uses configured chat # Optional editor planner/caption endpoints. Empty uses configured chat
# fallback without probing a developer-specific host. # fallback without probing a developer-specific host.
@@ -294,7 +295,7 @@ def is_setting_overridden(key: str) -> bool:
# resolved by FastAPI deps; an empty/None owner falls through to the global. # resolved by FastAPI deps; an empty/None owner falls through to the global.
_PER_USER_KEYS = { _PER_USER_KEYS = {
"vision_model", "vision_enabled", "vision_model_fallbacks", "vision_model", "vision_enabled", "vision_model_fallbacks",
"image_model", "image_gen_enabled", "image_quality", "image_model", "image_edit_model", "image_gen_enabled", "image_quality",
# Default chat endpoint / model — without per-user resolution every new # Default chat endpoint / model — without per-user resolution every new
# account inherited whatever the most-recent admin picked, which then # account inherited whatever the most-recent admin picked, which then
# got injected into the chat composer on first open. # got injected into the chat composer on first open.
+22 -2
View File
@@ -132,6 +132,23 @@ async def _cached(key: Tuple, ttl: float, fetch: Callable[[], Awaitable[Any]]) -
_shared_cache_pending.pop(key, None) _shared_cache_pending.pop(key, None)
def is_valid_cron(cron_expression: str) -> bool:
"""True for a standard 5-field cron expression that croniter can parse.
croniter also accepts 6- and 7-field expressions with a seconds field, but
the scheduler works at one-minute resolution and would run such a task
every second.
"""
if len((cron_expression or "").split()) != 5:
return False
try:
from croniter import croniter
croniter(cron_expression)
except Exception:
return False
return True
def compute_next_run(schedule: str, scheduled_time: str, def compute_next_run(schedule: str, scheduled_time: str,
scheduled_day: int = None, scheduled_day: int = None,
scheduled_date: datetime = None, scheduled_date: datetime = None,
@@ -175,6 +192,9 @@ def compute_next_run(schedule: str, scheduled_time: str,
return dt.astimezone(timezone.utc).replace(tzinfo=None) return dt.astimezone(timezone.utc).replace(tzinfo=None)
if schedule == "cron" and cron_expression: if schedule == "cron" and cron_expression:
if not is_valid_cron(cron_expression):
logger.warning(f"Invalid cron expression '{cron_expression}'")
return None
try: try:
from croniter import croniter from croniter import croniter
cron = croniter(cron_expression, now) cron = croniter(cron_expression, now)
@@ -306,7 +326,7 @@ def _digest_windows(now):
def _checkin_calendar_events(db, owner, start, end): def _checkin_calendar_events(db, owner, start, end):
"""Calendar events in [start, end] for ONE owner, for the check-in digest. """Calendar events in [start, end) for ONE owner, for the check-in digest.
Ownership lives on CalendarCal.owner; events inherit it via calendar_id. Ownership lives on CalendarCal.owner; events inherit it via calendar_id.
The digest query had no owner scope, so it pulled EVERY user's events into The digest query had no owner scope, so it pulled EVERY user's events into
@@ -320,7 +340,7 @@ def _checkin_calendar_events(db, owner, start, end):
.filter( .filter(
_CC.owner == owner, _CC.owner == owner,
_CE.dtstart >= start, _CE.dtstart >= start,
_CE.dtstart <= end, _CE.dtstart < end,
_CE.status != "cancelled", _CE.status != "cancelled",
) )
.order_by(_CE.dtstart) .order_by(_CE.dtstart)
+1
View File
@@ -41,6 +41,7 @@ _REQUIRED_NATIVE_TOOL_ARGS = {
"write_file": ("path",), "write_file": ("path",),
"edit_file": ("path",), "edit_file": ("path",),
"apply_patch": ("patch_text", "patchText", "patch"), "apply_patch": ("patch_text", "patchText", "patch"),
"generate_image": ("prompt",),
"host_shell": ("command",), "host_shell": ("command",),
} }
+3 -1
View File
@@ -4592,7 +4592,9 @@ body.bg-pattern-ascii-fireflies {
width:100%; background:var(--bg); color:var(--fg); width:100%; background:var(--bg); color:var(--fg);
border:1px solid var(--border); border-radius:6px; border:1px solid var(--border); border-radius:6px;
padding:8px; font-family:inherit; font-size:0.95rem; padding:8px; font-family:inherit; font-size:0.95rem;
resize:vertical; outline:none; resize:both; outline:none;
field-sizing:content;
max-width:100%; box-sizing:border-box;
min-height:80px; min-height:80px;
} }
.edit-textarea:focus { border-color:var(--red); } .edit-textarea:focus { border-color:var(--red); }
+63 -1
View File
@@ -264,7 +264,42 @@
/* The brush controls (Color/Size/preset/caret) hug their content; only the /* The brush controls (Color/Size/preset/caret) hug their content; only the
trailing slider section grows, so the Opacity/Flow/Softness group sits trailing slider section grows, so the Opacity/Flow/Softness group sits
right after the caret instead of leaving a wide gap. */ right after the caret instead of leaving a wide gap. */
.ge-controls--in-options #ge-brush-controls { flex: 0 0 auto; } .ge-controls--in-options #ge-brush-controls { flex: 0 0 auto; flex-direction: row; align-items: center; gap: 8px; }
.ge-controls--in-options #ge-brush-softness-row input[type="range"] { width: 88px; flex: 0 0 88px; }
#ge-brush-softness-row {
display: grid !important;
grid-template-columns: 14px max-content 88px;
column-gap: 8px;
align-items: center;
}
#ge-brush-softness-row:has(> .ge-slider-value) {
grid-template-columns: 14px max-content 88px 6ch;
}
#ge-brush-softness-row label {
flex: 0 0 auto;
min-width: max-content;
gap: 6px;
}
#ge-brush-softness-row #ge-brush-softness-label {
position: static;
min-width: 6ch;
margin: 0;
padding: 0;
white-space: nowrap;
text-align: right;
font-variant-numeric: tabular-nums;
}
.ge-controls--in-options #ge-brush-controls .ge-brush-size-row {
display: grid;
grid-template-columns: minmax(6ch, max-content) 96px auto;
column-gap: 8px;
}
.ge-controls--in-options .ge-brush-size-row label,
.ge-controls--in-options .ge-brush-size-row .ge-size-label {
min-width: 6ch;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.ge-controls--in-options .ge-control-row { .ge-controls--in-options .ge-control-row {
margin: 0 !important; margin: 0 !important;
flex: 0 0 auto; flex: 0 0 auto;
@@ -4607,6 +4642,8 @@ body.ge-editor-open textarea.ge-direct-text-editor {
pointer-events: auto; pointer-events: auto;
} }
.ge-filter-modal { .ge-filter-modal {
max-height: calc(100dvh - 40px);
overflow-y: auto;
width: 240px; width: 240px;
background: color-mix(in srgb, var(--panel) 95%, transparent); background: color-mix(in srgb, var(--panel) 95%, transparent);
border: 1px solid var(--border); border: 1px solid var(--border);
@@ -4631,6 +4668,9 @@ body.ge-editor-open textarea.ge-direct-text-editor {
gap: 2px; gap: 2px;
} }
.ge-filter-row label { .ge-filter-row label {
flex: 0 0 auto;
min-width: 0;
width: 100%;
font-size: 10px; font-size: 10px;
opacity: 0.7; opacity: 0.7;
display: flex; display: flex;
@@ -9732,6 +9772,28 @@ body.ge-editor-open .tour-hint {
margin-left: auto; margin-left: auto;
color: var(--color-muted); color: var(--color-muted);
} }
.ge-submenu .dropdown-item-compact {
box-sizing: border-box;
display: flex;
align-items: center;
height: 28px;
min-height: 28px;
max-height: 28px;
padding: 0 10px;
line-height: 1.2;
white-space: nowrap;
}
.ge-submenu .dropdown-item-compact svg {
flex-shrink: 0;
max-height: 16px;
}
@media (max-width: 820px) {
.ge-submenu .dropdown-item-compact {
height: 32px;
min-height: 32px;
max-height: 32px;
}
}
.ge-submenu { .ge-submenu {
display: none; display: none;
position: absolute; position: absolute;
+6 -3
View File
@@ -2690,11 +2690,14 @@ body.theme-frosted .modal {
max-height: 95dvh !important; max-height: 95dvh !important;
} }
/* Notes and Documents must respect the same viewport and safe-area
top as other mobile full-height sheets. Keep these authoritative rules
consistent with 05-documents.css and 14-email.css. */
body.doc-view .doc-editor-pane, body.doc-view .doc-editor-pane,
body.notes-view .notes-pane { body.notes-view .notes-pane {
inset: auto 0 0 !important; inset: var(--sheet-top) 0 0 !important;
height: 95dvh !important; height: calc(var(--app-height) - var(--sheet-top)) !important;
max-height: 95dvh !important; max-height: calc(var(--app-height) - var(--sheet-top)) !important;
} }
} }
+4 -7
View File
@@ -16,13 +16,6 @@
<link rel="apple-touch-icon" href="/static/icons/icon-192.png"> <link rel="apple-touch-icon" href="/static/icons/icon-192.png">
<script nonce="{{CSP_NONCE}}"> <script nonce="{{CSP_NONCE}}">
window._odysseusLoadTime = Date.now(); window._odysseusLoadTime = Date.now();
// Stops iOS focus-zoom on every field; iOS still allows pinch-zoom, other platforms would not.
(function(){
var ua = navigator.userAgent || '';
var isIOS = /iPad|iPhone|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);
var vp = document.querySelector('meta[name="viewport"]');
if (isIOS && vp) vp.setAttribute('content', vp.getAttribute('content') + ', maximum-scale=1');
})();
(function(){ (function(){
try { try {
var t = JSON.parse(localStorage.getItem('odysseus-theme')); var t = JSON.parse(localStorage.getItem('odysseus-theme'));
@@ -1684,6 +1677,10 @@
<label class="settings-label">Model</label> <label class="settings-label">Model</label>
<select id="set-imgModelSelect" class="settings-select"><option value="">Auto-detect</option></select> <select id="set-imgModelSelect" class="settings-select"><option value="">Auto-detect</option></select>
</div> </div>
<div style="display:flex;align-items:center;gap:0.75rem;">
<label class="settings-label" for="set-imgEditModelSelect">Image edit model</label>
<select id="set-imgEditModelSelect" class="settings-select"><option value="">Same as generation</option></select>
</div>
<div style="display:flex;align-items:center;gap:0.75rem;"> <div style="display:flex;align-items:center;gap:0.75rem;">
<label class="settings-label">Quality</label> <label class="settings-label">Quality</label>
<select id="set-imgQualitySelect" class="settings-select"> <select id="set-imgQualitySelect" class="settings-select">
+7 -1
View File
@@ -771,7 +771,13 @@ function _getModal() {
<button class="cal-side-nav cal-side-nav-next" id="cal-side-next" title="Next" aria-label="Next">&rsaquo;</button> <button class="cal-side-nav cal-side-nav-next" id="cal-side-next" title="Next" aria-label="Next">&rsaquo;</button>
</div>`; </div>`;
document.body.appendChild(_modal); document.body.appendChild(_modal);
_modal.querySelector('#cal-close').addEventListener('click', closeCalendar); _modal.querySelector('#cal-close').addEventListener('click', () => {
if (_modal.querySelector('.cal-form')) {
_render();
return;
}
closeCalendar();
});
_modal.querySelector('#cal-side-prev')?.addEventListener('click', (e) => { _modal.querySelector('#cal-side-prev')?.addEventListener('click', (e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
+65
View File
@@ -0,0 +1,65 @@
function streamError(payload) {
const detail = payload?.data ?? payload;
const candidates = [detail?.message, detail?.text, detail?.error?.message,
detail?.error, payload?.message, payload?.text, payload?.error?.message,
payload?.error, typeof payload === 'string' ? payload : null];
const message = candidates.find(value => typeof value === 'string' && value.trim());
return new Error(message || 'Model request failed.');
}
/** Decode complete SSE frames, requiring the backend's terminal DONE event. */
export async function consumeCompareEvents(response, onEvent, onActivity) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let line = '', event = 'message', data = [], skipLF = false;
try {
while (true) {
const { done, value } = await reader.read();
if (!done) onActivity?.();
let chunk = decoder.decode(value, { stream: !done });
if (skipLF && chunk.length) {
if (chunk.startsWith('\n')) chunk = chunk.slice(1);
skipLF = false;
}
const separators = /\r\n|\r|\n/g;
let start = 0, separator;
while ((separator = separators.exec(chunk))) {
line += chunk.slice(start, separator.index);
start = separator.index + separator[0].length;
skipLF = separator[0] === '\r' && start === chunk.length;
if (!line) {
if (data.length || event === 'error') {
const raw = data.join('\n');
if (event !== 'error' && raw === '[DONE]') return;
let payload;
try { payload = JSON.parse(raw); }
catch (_) {
if (event === 'error') throw streamError(raw);
throw new Error('Invalid model stream data.');
}
if (event === 'error' || payload?.type === 'error') throw streamError(payload);
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
throw new Error('Invalid model stream data.');
}
await onEvent(payload);
}
event = 'message';
data = [];
} else if (!line.startsWith(':')) {
const colon = line.indexOf(':');
const field = colon < 0 ? line : line.slice(0, colon);
let value = colon < 0 ? '' : line.slice(colon + 1);
if (value.startsWith(' ')) value = value.slice(1);
if (field === 'data') data.push(value);
else if (field === 'event') event = value || 'message';
}
line = '';
}
line += chunk.slice(start);
if (done) throw new Error('Stream ended before completion.');
}
} finally {
try { await reader.cancel(); } catch (_) {}
reader.releaseLock();
}
}
+12 -22
View File
@@ -1,5 +1,6 @@
// compare/stream.js — SSE streaming to panes // compare/stream.js — SSE streaming to panes
import state from './state.js'; import state from './state.js';
import { consumeCompareEvents } from './sse.js';
import { addFinishBadge } from './vote.js?v=20260828resendcaldrag1'; import { addFinishBadge } from './vote.js?v=20260828resendcaldrag1';
import { getModelCost, renderAskUserCard, safeDisplayImageSrc } from '../chatRenderer.js?v=20260914metricssummary1'; import { getModelCost, renderAskUserCard, safeDisplayImageSrc } from '../chatRenderer.js?v=20260914metricssummary1';
import markdownModule from '../markdown.js'; import markdownModule from '../markdown.js';
@@ -472,25 +473,9 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
}); });
if (!response.ok) throw new Error(`HTTP ${response.status}`); if (!response.ok) throw new Error(`HTTP ${response.status}`);
const reader = response.body.getReader(); await consumeCompareEvents(response,
const decoder = new TextDecoder(); (json) => {
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
_resetIdleTimeout(); // any chunk = stream is alive
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6);
if (data === '[DONE]') break;
try { try {
const json = JSON.parse(data);
if (json.type === 'metrics') { if (json.type === 'metrics') {
metrics = json.data; metrics = json.data;
@@ -672,7 +657,7 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
if (hist) hist.scrollTop = hist.scrollHeight; if (hist) hist.scrollTop = hist.scrollHeight;
} else if (json.delta) { } else if (json.delta) {
// Skip text deltas if we already rendered an image // Skip text deltas if we already rendered an image
if (aiMsgEl._imageData) continue; if (aiMsgEl._imageData) return;
// Capture TTFT on very first text delta // Capture TTFT on very first text delta
if (!accumulated && !_ttft) _ttft = performance.now() - _timerStart; if (!accumulated && !_ttft) _ttft = performance.now() - _timerStart;
// On first delta, destroy spinner and prepare text area // On first delta, destroy spinner and prepare text area
@@ -701,8 +686,7 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
_scheduleLiveRender(target); _scheduleLiveRender(target);
} }
} catch (e) { console.warn('Compare stream render error:', e); } } catch (e) { console.warn('Compare stream render error:', e); }
} }, _resetIdleTimeout);
}
streamOk = true; streamOk = true;
// Destroy any remaining spinner // Destroy any remaining spinner
@@ -900,9 +884,15 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
} }
} else { } else {
console.error('Compare stream error:', error); console.error('Compare stream error:', error);
aiBody.innerHTML = '<span style="color:var(--color-error);">Error: ' + escapeHtml(error.message) + '</span>'; awaitingChoice = false;
const message = state._blindMode ? 'Model request failed. Try again.' : error.message;
aiBody.innerHTML = '<span style="color:var(--color-error);">Error: ' + escapeHtml(message) + '</span>';
} }
} finally { } finally {
if (aiMsgEl._spinner) {
aiMsgEl._spinner.destroy();
aiMsgEl._spinner = null;
}
clearTimeout(timeoutId); clearTimeout(timeoutId);
_timerDone = true; _timerDone = true;
cancelAnimationFrame(_rafId); cancelAnimationFrame(_rafId);
+6 -5
View File
@@ -1195,11 +1195,12 @@ async function _fetchDependencies() {
// For backends with a recipe catalog (vllm / sglang / llama_cpp), // For backends with a recipe catalog (vllm / sglang / llama_cpp),
// append a caret button that toggles a per-row recipe panel below. // append a caret button that toggles a per-row recipe panel below.
const hasRecipe = RECIPE_BACKENDS.has(pkg.name); const hasRecipe = RECIPE_BACKENDS.has(pkg.name);
// Standalone recipe-caret button removed — the "Pick install // The caret is the only way to open the recipe panel (the Installed ▾
// command" action lives inside the Installed ▾ dropdown menu // menu has no recipe item), and the HW Fit / serve-card deep links
// (see _showDepMenu) so each row only has ONE caret to click. // open it by clicking this caret (#6747).
// Kept the variable so downstream concat code stays the same. const recipeCaret = hasRecipe
const recipeCaret = ''; ? `<button class="cookbook-dep-tag cookbook-dep-recipe-caret" data-dep-recipe-toggle="${esc(pkg.name)}" title="Pick a model to see the exact install commands" aria-expanded="false" style="background:none;border:1px solid var(--border);padding:2px 6px;display:inline-flex;align-items:center;cursor:pointer;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="transition:transform 0.15s"><polyline points="6 9 12 15 18 9"/></svg></button>`
: '';
const recipePanel = hasRecipe ? _recipePanelHtml(pkg.name) : ''; const recipePanel = hasRecipe ? _recipePanelHtml(pkg.name) : '';
// When llama_cpp (or any future engine) reports build_deps_missing // When llama_cpp (or any future engine) reports build_deps_missing
// from its system_prereqs probe, surface a one-tap install button // from its system_prereqs probe, surface a one-tap install button
+2 -2
View File
@@ -5232,7 +5232,7 @@ import { attachColorPicker } from './colorPicker.js?v=20260910eyedropper1';
} }
async function _handleAttachUpload(e) { async function _handleAttachUpload(e) {
const files = e.target.files; const files = Array.from(e.target.files || []);
e.target.value = ''; // reset for next upload e.target.value = ''; // reset for next upload
await _uploadComposeFiles(files); await _uploadComposeFiles(files);
} }
@@ -5963,7 +5963,7 @@ import { attachColorPicker } from './colorPicker.js?v=20260910eyedropper1';
} }
async function _handleMarkdownImageUpload(e) { async function _handleMarkdownImageUpload(e) {
const files = e.target.files; const files = Array.from(e.target.files || []);
e.target.value = ''; e.target.value = '';
await _uploadMarkdownImages(files); await _uploadMarkdownImages(files);
} }
+25 -6
View File
@@ -41,6 +41,7 @@
* }} deps * }} deps
*/ */
import { state } from './state.js'; import { state } from './state.js';
import { imageResultGeometry } from './image-result-geometry.js';
import { beginAIOperation, decodeAIImage } from './ai-operation.js'; import { beginAIOperation, decodeAIImage } from './ai-operation.js';
export function wireInpaintButtons({ export function wireInpaintButtons({
@@ -184,17 +185,30 @@ export function wireInpaintButtons({
if (!state.editorOpen) return; // user closed mid-decode if (!state.editorOpen) return; // user closed mid-decode
try { try {
saveState('Inpaint result'); saveState('Inpaint result');
// OpenAI returns at one of its allowed sizes (1024², // Whole-image edits keep the provider's native frame; only masked
// 1024×1536, 1536×1024) which often differs from our // edits need registration with the source document's coordinates.
// canvas. Scale to canvas size with smoothing so the
// inpaint blends in regardless of source dims.
const shortPrompt = (prompt || '').trim().replace(/\s+/g, ' ').slice(0, 40); const shortPrompt = (prompt || '').trim().replace(/\s+/g, ' ').slice(0, 40);
const layerName = shortPrompt ? `Inpaint: ${shortPrompt}` : 'Inpaint Result'; const layerName = shortPrompt ? `Inpaint: ${shortPrompt}` : 'Inpaint Result';
const resultLayer = createLayer(layerName, state.imgWidth, state.imgHeight); const fullFrame = data.full_frame === true;
const geometry = imageResultGeometry(resultImg.naturalWidth, resultImg.naturalHeight, state.imgWidth, state.imgHeight);
const resultLayer = createLayer(layerName,
fullFrame ? geometry.width : state.imgWidth,
fullFrame ? geometry.height : state.imgHeight);
resultLayer.ctx.imageSmoothingEnabled = true; resultLayer.ctx.imageSmoothingEnabled = true;
resultLayer.ctx.imageSmoothingQuality = 'high'; resultLayer.ctx.imageSmoothingQuality = 'high';
resultLayer.ctx.drawImage(resultImg, 0, 0, state.imgWidth, state.imgHeight); if (fullFrame) {
resultLayer.ctx.drawImage(resultImg, geometry.drawX, geometry.drawY, geometry.drawWidth, geometry.drawHeight);
state.layerOffsets.set(resultLayer.id, {
x: geometry.offsetX,
y: geometry.offsetY,
});
} else {
const scale = Math.min(state.imgWidth / resultImg.naturalWidth, state.imgHeight / resultImg.naturalHeight);
const width = resultImg.naturalWidth * scale, height = resultImg.naturalHeight * scale;
resultLayer.ctx.drawImage(resultImg, (state.imgWidth - width) / 2, (state.imgHeight - height) / 2, width, height);
}
// Snapshot the AI result + hard mask used for this run. // Snapshot the AI result + hard mask used for this run.
if (!fullFrame) {
const aiSnap = document.createElement('canvas'); const aiSnap = document.createElement('canvas');
aiSnap.width = state.imgWidth; aiSnap.height = state.imgHeight; aiSnap.width = state.imgWidth; aiSnap.height = state.imgHeight;
aiSnap.getContext('2d').drawImage(resultLayer.canvas, 0, 0); aiSnap.getContext('2d').drawImage(resultLayer.canvas, 0, 0);
@@ -205,6 +219,7 @@ export function wireInpaintButtons({
resultLayer.inpaintSource = { ai: aiSnap, mask: maskSnap, base: baseSnap, padPx }; resultLayer.inpaintSource = { ai: aiSnap, mask: maskSnap, base: baseSnap, padPx };
// Apply initial alpha = hard mask (no feather, no edge shift). // Apply initial alpha = hard mask (no feather, no edge shift).
applyInpaintFeather(resultLayer, 0, 0); applyInpaintFeather(resultLayer, 0, 0);
}
state.layers.push(resultLayer); state.layers.push(resultLayer);
state.activeLayerId = resultLayer.id; state.activeLayerId = resultLayer.id;
state.lastInpaintLayerId = resultLayer.id; state.lastInpaintLayerId = resultLayer.id;
@@ -220,6 +235,10 @@ export function wireInpaintButtons({
} }
composite(); composite();
renderLayerPanel(); renderLayerPanel();
if (fullFrame) {
if (uiModule) uiModule.showToast('Image edit complete', 4500);
return;
}
// Reveal post-generation Feather + Edge Stroke sliders. // Reveal post-generation Feather + Edge Stroke sliders.
// Cap Edge Stroke at ±padPx so the slider can't ask for // Cap Edge Stroke at ±padPx so the slider can't ask for
// more AI buffer than we generated. // more AI buffer than we generated.
+20 -51
View File
@@ -54,16 +54,16 @@ export function resolveQuickEditModel() {
label: ((opt && opt.textContent) || '').trim(), label: ((opt && opt.textContent) || '').trim(),
}; };
} }
const inp = document.getElementById('ge-ai-inpaint'); const generation = document.getElementById('ge-ai-model');
const opt = resolveInpaintModel(inp); if (generation?.value && generation.value !== '__serve_cookbook__') {
if (!opt) return { endpoint: '', model: '', label: '' }; const index = generation.value.indexOf('::');
const raw = opt.value || ''; const model = index < 0 ? '' : generation.value.slice(index + 2);
const idx = raw.indexOf('::'); if (model && modelCaps(model, '', '').inpaint) {
return { return { endpoint: generation.value.slice(0, index), model,
endpoint: idx < 0 ? raw : raw.slice(0, idx), label: generation.options[generation.selectedIndex]?.textContent?.trim() || model };
model: idx < 0 ? '' : raw.slice(idx + 2), }
label: ((opt.textContent || '').trim().replace(/^Auto\s*\((.*)\)$/, '$1')), }
}; return { endpoint: '', model: '', label: 'Auto (saved settings)' };
} }
// Resolve the Quick Edit AGENT (planner) model — the vision-language model // Resolve the Quick Edit AGENT (planner) model — the vision-language model
@@ -144,21 +144,19 @@ export function modelCaps(modelId, endpointName, endpointType) {
function syncCommandModel(value) { function syncCommandModel(value) {
const select = document.getElementById('ge-ai-command-model'); const select = document.getElementById('ge-ai-command-model');
if (!select || !select._modelsReady) return; if (!select || !select._modelsReady) return;
if (value && ![...select.options].some(o => !o.disabled && o.value === value && value !== '__serve_cookbook__')) {
if (localStorage.getItem('ge-ai-command-model') === value) localStorage.removeItem('ge-ai-command-model');
value = '';
}
if (select.value !== value) { if (select.value !== value) {
select.value = value; select.value = value;
if (select.value !== value) select.value = ''; if (select.value !== value) select.value = '';
updateFooterEditModel(); updateFooterEditModel();
} }
} }
if (typeof window !== 'undefined') {
window.addEventListener('ge-ai-command-model-change', e => syncCommandModel(e.detail?.value || '')); window.addEventListener('ge-ai-command-model-change', e => syncCommandModel(e.detail?.value || ''));
window.addEventListener('storage', e => { window.addEventListener('storage', e => {
if (e.key === 'ge-ai-command-model') syncCommandModel(e.newValue || ''); if (e.key === 'ge-ai-command-model') syncCommandModel(e.newValue || '');
}); });
window.addEventListener('ge:model-endpoints-updated', e => { }
globalThis.window?.addEventListener('ge:model-endpoints-updated', e => {
document.getElementById('ge-ai-command-model')?._refreshAIModels?.(e.detail?.baseUrl || ''); document.getElementById('ge-ai-command-model')?._refreshAIModels?.(e.detail?.baseUrl || '');
}); });
@@ -256,9 +254,9 @@ export function wireAIModelSelectors({ container, apiBase = '', openCookbookForI
const data = await res.json(); const data = await res.json();
if (listeners.signal.aborted || !root.isConnected) return; if (listeners.signal.aborted || !root.isConnected) return;
const modelsList = data.models || []; const modelsList = data.models || [];
if (aiGenSelect) aiGenSelect.innerHTML = '<option value="">None</option>'; if (aiGenSelect) aiGenSelect.innerHTML = '<option value="">Auto-detect</option>';
if (aiInpaintSelect) aiInpaintSelect.innerHTML = '<option value="">Auto</option>'; if (aiInpaintSelect) aiInpaintSelect.innerHTML = '<option value="">Auto</option>';
if (aiCommandSelect) aiCommandSelect.innerHTML = '<option value="">Auto (default)</option>'; if (aiCommandSelect) aiCommandSelect.innerHTML = '<option value="">Same as generation</option>';
const perToolSelects = Array.from(document.querySelectorAll('select.ge-tool-model')); const perToolSelects = Array.from(document.querySelectorAll('select.ge-tool-model'));
for (const ts of perToolSelects) ts.innerHTML = '<option value="">Auto</option>'; for (const ts of perToolSelects) ts.innerHTML = '<option value="">Auto</option>';
let firstGen = null; let firstGen = null;
@@ -346,45 +344,15 @@ export function wireAIModelSelectors({ container, apiBase = '', openCookbookForI
// Sentinel changes are handled by the component's delegated listener. // Sentinel changes are handled by the component's delegated listener.
if (aiCommandSelect) { if (aiCommandSelect) {
aiCommandSelect._modelsReady = true; aiCommandSelect._modelsReady = true;
try { // Legacy URL migration check: legacy endpoints with raw URLs are scrubbed.
const rawSaved = localStorage.getItem('ge-ai-command-model') || ''; const scrubModelUrl = (saved) => (saved && saved.startsWith('http://') ? '' : saved);
let saved = rawSaved;
if (saved.startsWith('http://') || saved.startsWith('https://') || saved.includes('://') || saved.startsWith('::')) {
const modelPart = saved.includes('::') ? saved.split('::').pop() : '';
const matching = loaded.filter(l => l.model === modelPart);
if (matching.length === 1) {
saved = matching[0].value;
} else {
saved = '';
}
try {
if (saved) localStorage.setItem('ge-ai-command-model', saved);
else localStorage.removeItem('ge-ai-command-model');
} catch {}
}
if (saved && [...aiCommandSelect.options].some(o => o.value === saved)) {
aiCommandSelect.value = saved;
} else {
aiCommandSelect.value = '';
}
if (aiCommandSelect.value !== rawSaved) {
if (aiCommandSelect.value) localStorage.setItem('ge-ai-command-model', aiCommandSelect.value);
else localStorage.removeItem('ge-ai-command-model');
window.dispatchEvent(new CustomEvent('ge-ai-command-model-change', { detail: { value: aiCommandSelect.value } }));
}
} catch {}
if (aiCommandSelect._commandWired !== listeners) { if (aiCommandSelect._commandWired !== listeners) {
aiCommandSelect._commandWired = listeners; aiCommandSelect._commandWired = listeners;
listen(aiCommandSelect, 'change', () => { listen(aiCommandSelect, 'change', () => {
if (aiCommandSelect.value === '__serve_cookbook__') return; if (aiCommandSelect.value === '__serve_cookbook__') return;
const val = aiCommandSelect.value || ''; const val = scrubModelUrl(aiCommandSelect.value) || '';
try {
if (val) localStorage.setItem('ge-ai-command-model', aiCommandSelect.value);
else localStorage.removeItem('ge-ai-command-model');
} catch {}
updateFooterEditModel(); updateFooterEditModel();
window.dispatchEvent(new CustomEvent('ge-ai-command-model-change', { detail: { value: val } })); globalThis.window?.dispatchEvent?.(new CustomEvent('ge-ai-command-model-change', { detail: { value: val } }));
}); });
} }
} }
@@ -409,6 +377,7 @@ export function wireAIModelSelectors({ container, apiBase = '', openCookbookForI
}); });
} }
_aiModelsStatus = { ready: true, models: loaded, error: null, at: Date.now() }; _aiModelsStatus = { ready: true, models: loaded, error: null, at: Date.now() };
container.dispatchEvent(new Event('ge-image-models-ready'));
try { window.dispatchEvent(new CustomEvent('ge:ai-models-status')); } catch {} try { window.dispatchEvent(new CustomEvent('ge:ai-models-status')); } catch {}
} catch (e) { } catch (e) {
if (listeners.signal.aborted || !root.isConnected) return; if (listeners.signal.aborted || !root.isConnected) return;
+5 -30
View File
@@ -2,11 +2,10 @@
* Background Remove (rembg) + Sharpen wiring + the live edge-cleanup * Background Remove (rembg) + Sharpen wiring + the live edge-cleanup
* tuner that runs on the most-recent rembg cutout. * tuner that runs on the most-recent rembg cutout.
* *
* rembg-run button: flatten + POST to /api/image/remove-bg with an * rembg-run button: active layer + POST to /api/image/remove-bg with an
* optional hint_mask if the user has a wand/lasso selection * optional hint_mask if the user has a wand/lasso selection
* active. After the new layer lands, hides every previously- * active. Updates only that layer and binds its live edge tuner;
* visible layer so the cutout reads cleanly, and binds the * other layers and their visibility remain unchanged.
* live-tuner to the new layer.
* *
* Live edge-cleanup tuner: snapshots the pristine cutout the * Live edge-cleanup tuner: snapshots the pristine cutout the
* moment it lands; subsequent feather/grow slider tweaks * moment it lands; subsequent feather/grow slider tweaks
@@ -65,37 +64,13 @@ export function wireRembgAndSharpen({
// NB: edge_feather / edge_grow are applied CLIENT-side so the // NB: edge_feather / edge_grow are applied CLIENT-side so the
// sliders can re-tune the cutout without re-running the model. // sliders can re-tune the cutout without re-running the model.
const btn = document.getElementById('ge-rembg-run'); const btn = document.getElementById('ge-rembg-run');
const before = state.layers.length; const editedLayer = await applyImageTool('/api/image/remove-bg', payload, 'BG Removed', btn);
// Snapshot which layers were visible BEFORE the run so we know
// which to hide after a successful cutout.
const prevVisible = state.layers.filter(l => l.visible).map(l => l.id);
await applyImageTool('/api/image/remove-bg', payload, 'BG Removed', btn);
// applyImageTool resolves after the returned image is decoded and the
// new layer is inserted. Keep a short poll for defensive compatibility
// with alternate runners that may still commit on the next frame.
let frames = 0;
while (state.layers.length <= before && frames < 60) {
await new Promise(r => requestAnimationFrame(r));
frames++;
}
if (state.layers.length > before) {
const newLayer = state.layers[state.layers.length - 1];
bindRembgLiveTuner(newLayer);
// Auto-hide underlying layers so the user sees just the
// cutout — the eye toggles back on if they re-enable manually.
for (const layer of state.layers) {
if (prevVisible.includes(layer.id) && layer.id !== newLayer.id) {
layer.visible = false;
}
}
composite();
renderLayerPanel();
}
// Reset sliders so the new cutout starts clean. // Reset sliders so the new cutout starts clean.
const f = document.getElementById('ge-rembg-feather'); const f = document.getElementById('ge-rembg-feather');
const g = document.getElementById('ge-rembg-grow'); const g = document.getElementById('ge-rembg-grow');
if (f) { f.value = 0; document.getElementById('ge-rembg-feather-label').textContent = '0px'; syncRembgFeather(0); } if (f) { f.value = 0; document.getElementById('ge-rembg-feather-label').textContent = '0px'; syncRembgFeather(0); }
if (g) { g.value = 0; document.getElementById('ge-rembg-grow-label').textContent = '0px'; syncRembgGrow(0); } if (g) { g.value = 0; document.getElementById('ge-rembg-grow-label').textContent = '0px'; syncRembgGrow(0); }
if (editedLayer) bindRembgLiveTuner(editedLayer);
}); });
// ── Live edge-cleanup tuner ── // ── Live edge-cleanup tuner ──
+61 -3
View File
@@ -5,6 +5,9 @@
* "Double-check AI edits" toggle. Opened from the Quick Edit gear button and * "Double-check AI edits" toggle. Opened from the Quick Edit gear button and
* from the editor setup checklist; keeps the Quick Edit box itself uncluttered. * from the editor setup checklist; keeps the Quick Edit box itself uncluttered.
*/ */
import { readImagePreferences, saveImagePreferences } from '../settings/imagePreferences.js';
import { updateFooterEditModel } from './ai-models.js';
export function createAiSettings({ container }) { export function createAiSettings({ container }) {
const el = document.createElement('div'); const el = document.createElement('div');
el.className = 'ge-ai-settings'; el.className = 'ge-ai-settings';
@@ -19,11 +22,14 @@ export function createAiSettings({ container }) {
<button type="button" class="ge-ai-settings-close" data-ai-settings-close aria-label="Close">×</button> <button type="button" class="ge-ai-settings-close" data-ai-settings-close aria-label="Close">×</button>
</div> </div>
<div class="ge-ai-settings-body"> <div class="ge-ai-settings-body">
<label class="ge-ai-settings-label" for="ge-ai-model">Image generation model</label>
<select class="ge-ai-command-model" id="ge-ai-model" title="Image generation model" aria-label="Image generation model"></select>
<label class="ge-ai-settings-label" for="ge-ai-command-model">Image edit model</label> <label class="ge-ai-settings-label" for="ge-ai-command-model">Image edit model</label>
<select class="ge-ai-command-model" id="ge-ai-command-model" title="Image edit model" aria-label="Image edit model"></select> <select class="ge-ai-command-model" id="ge-ai-command-model" title="Image edit model" aria-label="Image edit model"></select>
<label class="ge-ai-settings-label" for="ge-ai-command-agent-model">AI agent (vision) model</label> <label class="ge-ai-settings-label" for="ge-ai-command-agent-model">AI agent (vision) model</label>
<select class="ge-ai-command-model" id="ge-ai-command-agent-model" title="Quick Edit agent model" aria-label="Quick Edit agent model"></select> <select class="ge-ai-command-model" id="ge-ai-command-agent-model" title="Quick Edit agent model" aria-label="Quick Edit agent model"></select>
<p class="ge-ai-settings-note">Recommended, not required — the vision agent plans edits and can double-check results.</p> <p class="ge-ai-settings-note">Recommended, not required — the vision agent plans edits and can double-check results.</p>
<p class="ge-ai-settings-note" id="ge-ai-settings-save-status" role="status"></p>
<label class="ge-ai-settings-label" for="ge-look-strength">Look strength</label> <label class="ge-ai-settings-label" for="ge-look-strength">Look strength</label>
<div class="ge-ai-settings-strength"> <div class="ge-ai-settings-strength">
<input type="range" id="ge-look-strength" min="0.5" max="2" step="0.1" value="1.4" aria-label="Look grade strength" /> <input type="range" id="ge-look-strength" min="0.5" max="2" step="0.1" value="1.4" aria-label="Look grade strength" />
@@ -41,6 +47,7 @@ export function createAiSettings({ container }) {
function open(focusId) { function open(focusId) {
el.hidden = false; el.hidden = false;
syncModels();
if (focusId) { if (focusId) {
const target = document.getElementById(focusId); const target = document.getElementById(focusId);
if (target) { if (target) {
@@ -56,10 +63,59 @@ export function createAiSettings({ container }) {
close(); close();
} }
}); });
const onKey = (e) => { if (e.key === 'Escape' && !el.hidden) close(); }; const onKey = (e) => {
document.addEventListener('keydown', onKey); if (e.key !== 'Escape' || el.hidden) return;
e.preventDefault();
e.stopImmediatePropagation();
close();
};
window.addEventListener('keydown', onKey, true);
container.appendChild(el); container.appendChild(el);
const status = el.querySelector('#ge-ai-settings-save-status');
const modelFields = [['ge-ai-model', 'image_model'], ['ge-ai-command-model', 'image_edit_model']];
function applyModels(settings) {
for (const [id, key] of modelFields) {
if (!(key in settings)) continue;
const select = el.querySelector(`#${id}`);
const model = settings[key] || '';
let option = [...select.options].find(option => {
const value = option.value;
return model ? value.slice(value.indexOf('::') + 2) === model : value === '';
});
if (!option && model && select.options.length) {
option = document.createElement('option');
option.value = `::${model}`;
option.textContent = `${model} (unavailable)`;
option.disabled = true;
select.append(option);
}
if (option) select.value = option.value;
}
updateFooterEditModel();
}
async function syncModels() {
try { applyModels(await readImagePreferences()); }
catch (error) { status.textContent = error.message; }
}
for (const [id, key] of modelFields) {
el.querySelector(`#${id}`).addEventListener('change', async (event) => {
const raw = event.target.value;
if (raw === '__serve_cookbook__') return;
const model = raw.includes('::') ? raw.slice(raw.indexOf('::') + 2) : '';
try {
status.textContent = 'Saving…';
await saveImagePreferences({ [key]: model });
status.textContent = 'Saved';
} catch (error) {
await syncModels();
status.textContent = error.message;
}
});
}
const onPreferencesChanged = event => applyModels(event.detail);
window.addEventListener('image-preferences-changed', onPreferencesChanged);
container.addEventListener('ge-image-models-ready', syncModels);
const strengthInput = el.querySelector('#ge-look-strength'); const strengthInput = el.querySelector('#ge-look-strength');
const strengthVal = el.querySelector('#ge-look-strength-val'); const strengthVal = el.querySelector('#ge-look-strength-val');
@@ -77,7 +133,9 @@ export function createAiSettings({ container }) {
} }
function destroy() { function destroy() {
document.removeEventListener('keydown', onKey); window.removeEventListener('keydown', onKey, true);
window.removeEventListener('image-preferences-changed', onPreferencesChanged);
container.removeEventListener('ge-image-models-ready', syncModels);
el.remove(); el.remove();
} }
+23 -1
View File
@@ -76,7 +76,12 @@ export function createApplyImageTool({
if (sel.endpoint) extraPayload._endpoint = sel.endpoint; if (sel.endpoint) extraPayload._endpoint = sel.endpoint;
if (sel.model && !extraPayload._model) extraPayload._model = sel.model; if (sel.model && !extraPayload._model) extraPayload._model = sel.model;
} }
const flatCanvas = flatten(); const removeBackground = endpoint === '/api/image/remove-bg';
const targetLayer = removeBackground ? state.layers.find(layer => layer.id === state.activeLayerId) : null;
if (removeBackground && (!targetLayer?.canvas || targetLayer.kind === 'adjustment' || targetLayer.locks?.pixels)) {
throw new Error('Select an unlocked image layer first');
}
const flatCanvas = removeBackground ? targetLayer.canvas : flatten();
const imageB64 = flatCanvas.toDataURL('image/png').split(',')[1]; const imageB64 = flatCanvas.toDataURL('image/png').split(',')[1];
const body = { image: imageB64, ...extraPayload }; const body = { image: imageB64, ...extraPayload };
const res = await fetch(endpoint, { const res = await fetch(endpoint, {
@@ -96,6 +101,23 @@ export function createApplyImageTool({
const img = await decodeAIImage(data.image, operation.signal); const img = await decodeAIImage(data.image, operation.signal);
operation.signal.throwIfAborted(); operation.signal.throwIfAborted();
if (!state.editorOpen) return; // user closed mid-decode (v2 review HIGH-4) if (!state.editorOpen) return; // user closed mid-decode (v2 review HIGH-4)
if (removeBackground) {
if (!state.layers.includes(targetLayer)) return;
saveState('Remove background');
// The returned pixels replace the editable source, not just its preview.
targetLayer.kind = 'raster';
targetLayer.placed = null;
targetLayer.text = null;
targetLayer.shape = null;
targetLayer.ctx.clearRect(0, 0, targetLayer.canvas.width, targetLayer.canvas.height);
targetLayer.ctx.drawImage(img, 0, 0, targetLayer.canvas.width, targetLayer.canvas.height);
targetLayer._adjCacheKey = null;
targetLayer._adjFinalKey = null;
composite();
renderLayerPanel();
uiModule?.showToast('Background removed');
return targetLayer;
}
{ {
saveState(); saveState();
const layer = createLayer(layerName, state.imgWidth, state.imgHeight); const layer = createLayer(layerName, state.imgWidth, state.imgHeight);
+5 -5
View File
@@ -55,6 +55,11 @@ export function controlsHTML({ color, brushSize, wandTolerance, bucketTolerance
<label>Color</label> <label>Color</label>
<input type="color" class="ge-color-picker" value="${color}" /> <input type="color" class="ge-color-picker" value="${color}" />
</div> </div>
<div class="ge-control-row ge-eraser-row" id="ge-brush-softness-row">
<span class="ge-eraser-preview" id="ge-brush-preview-softness" aria-hidden="true"></span>
<label>Softness <span id="ge-brush-softness-label">100%</span></label>
<input type="range" id="ge-brush-softness" min="0" max="1200" value="100" title="Brush edge softness and feathered falloff" />
</div>
<div class="ge-control-row ge-brush-size-row"> <div class="ge-control-row ge-brush-size-row">
<label><span class="ge-size-label">${brushSize}px</span></label> <label><span class="ge-size-label">${brushSize}px</span></label>
<input type="range" class="ge-size-slider" min="0" max="1000" value="${brushSliderValue}" /> <input type="range" class="ge-size-slider" min="0" max="1000" value="${brushSliderValue}" />
@@ -94,11 +99,6 @@ export function controlsHTML({ color, brushSize, wandTolerance, bucketTolerance
<label>Flow <span id="ge-brush-flow-label">100%</span></label> <label>Flow <span id="ge-brush-flow-label">100%</span></label>
<input type="range" id="ge-brush-flow" min="5" max="100" value="100" /> <input type="range" id="ge-brush-flow" min="5" max="100" value="100" />
</div> </div>
<div class="ge-control-row ge-eraser-row" id="ge-brush-softness-row">
<span class="ge-eraser-preview" id="ge-brush-preview-softness" aria-hidden="true"></span>
<label>Softness <span id="ge-brush-softness-label">100%</span></label>
<input type="range" id="ge-brush-softness" min="0" max="300" value="100" title="Soft brush edge — blurs the stroke's alpha for a feathered fade at the perimeter." />
</div>
</div> </div>
<div class="ge-brush-stroke-group" data-stroke-tool="eraser"> <div class="ge-brush-stroke-group" data-stroke-tool="eraser">
<div class="ge-section-title">Eraser</div> <div class="ge-section-title">Eraser</div>
+35 -5
View File
@@ -78,6 +78,7 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
const UI_CHROME_SELECTOR = '.ge-topbar, .ge-toolbar, .ge-controls, .ge-right-panel, ' const UI_CHROME_SELECTOR = '.ge-topbar, .ge-toolbar, .ge-controls, .ge-right-panel, '
+ '.ge-dock, .ge-options-bar, .ge-canvas-toolbar, button, input, select, textarea'; + '.ge-dock, .ge-options-bar, .ge-canvas-toolbar, button, input, select, textarea';
const isUiChrome = e => !!e.target?.closest?.(UI_CHROME_SELECTOR); const isUiChrome = e => !!e.target?.closest?.(UI_CHROME_SELECTOR);
const canStartOutside = () => ['marquee', 'lasso', 'crop'].includes(state.tool);
// Only in-progress selection/crop drags are affected by the chrome // Only in-progress selection/crop drags are affected by the chrome
// guard. A committed cropRect/selection is a resting state — clicking // guard. A committed cropRect/selection is a resting state — clicking
// its Apply button must not be treated as "strayed onto chrome". // its Apply button must not be treated as "strayed onto chrome".
@@ -143,15 +144,16 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
}; };
state.mainCanvas.addEventListener('pointerup', endPen); state.mainCanvas.addEventListener('pointerup', endPen);
state.mainCanvas.addEventListener('pointercancel', endPen); state.mainCanvas.addEventListener('pointercancel', endPen);
// Lasso and Crop can start OUTSIDE the canvas — fallback mousedown on the // Selection and Crop can start OUTSIDE the canvas — fallback mousedown on the
// surrounding canvas-area so the user can begin a path/rect in the empty // surrounding canvas-area so the user can begin a path/rect in the empty
// space around the image. Other tools stay canvas-only. // space around the image. Other tools stay canvas-only.
canvasArea.addEventListener('mousedown', (e) => { canvasArea.addEventListener('mousedown', (e) => {
if (state.tool !== 'lasso' && state.tool !== 'crop') return; if (!canStartOutside() || Date.now() < suppressMouseUntil) return;
if (e.button !== 0 || isDirectPanIntent(state.tool, state.spacePanActive, e.button)) return;
if (e.target === state.mainCanvas) return; // already handled if (e.target === state.mainCanvas) return; // already handled
// Ignore presses on editor chrome inside the area (the crop Apply panel, // Ignore presses on editor chrome inside the area (the crop Apply panel,
// popups, buttons) so clicking Apply does not start a fresh crop. // popups, buttons) so clicking Apply does not start a fresh crop.
if (e.target.closest?.('button, input, select, textarea, .ge-crop-apply, .ge-adj-popup, .ge-transform-popup, .ge-fx-popup, .ge-inpaint-popup, .ge-controls, .ge-right-panel, .ge-fx-menu')) return; if (isUiChrome(e) || e.target.closest?.('.ge-crop-apply, .ge-adj-popup, .ge-transform-popup, .ge-fx-popup, .ge-inpaint-popup, .ge-fx-menu')) return;
beginDraw(e); beginDraw(e);
}); });
state.mainCanvas.addEventListener('mouseenter', (e) => { state.mainCanvas.addEventListener('mouseenter', (e) => {
@@ -305,6 +307,7 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
let panning = false; let panning = false;
let pid = null; let pid = null;
let transformPointerId = null; let transformPointerId = null;
let outsideDrawPointerId = null;
let startX = 0, startY = 0; let startX = 0, startY = 0;
let startPanX = 0, startPanY = 0; let startPanX = 0, startPanY = 0;
const getOffset = () => ({ x: state.panX || 0, y: state.panY || 0 }); const getOffset = () => ({ x: state.panX || 0, y: state.panY || 0 });
@@ -315,10 +318,23 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
}; };
canvasArea.addEventListener('pointerdown', (e) => { canvasArea.addEventListener('pointerdown', (e) => {
const directPan = isDirectPanIntent(state.tool, state.spacePanActive, e.button); const directPan = isDirectPanIntent(state.tool, state.spacePanActive, e.button);
// With the crop (or lasso) tool, an empty-area press draws a rect/path // With a selection or crop tool, an empty-area press draws a rect/path
// rather than panning — so the crop can be pulled out past the image. // rather than panning — so the crop can be pulled out past the image.
// Space-held / middle-mouse (directPan) still pans. // Space-held / middle-mouse (directPan) still pans.
if ((state.tool === 'lasso' || state.tool === 'crop') && !directPan) return; if (canStartOutside() && !directPan) {
if (e.target === state.mainCanvas || isUiChrome(e) ||
e.target.closest?.('.ge-crop-apply, .ge-adj-popup, .ge-transform-popup, .ge-fx-popup, .ge-inpaint-popup, .ge-fx-menu')) return;
// Mouse starts through mousedown; pen/touch need their own captured path.
if (e.pointerType === 'pen' || e.pointerType === 'touch') {
if (outsideDrawPointerId !== null || e.button !== 0) return;
outsideDrawPointerId = e.pointerId;
suppressMouseUntil = Date.now() + 500;
try { canvasArea.setPointerCapture(e.pointerId); } catch {}
beginDraw(e);
e.preventDefault();
}
return;
}
if (e.target.closest('button, input, .ge-adj-popup, .ge-transform-popup, .ge-fx-popup, .ge-inpaint-popup, .ge-controls, .ge-right-panel, .ge-fx-menu')) return; if (e.target.closest('button, input, .ge-adj-popup, .ge-transform-popup, .ge-fx-popup, .ge-inpaint-popup, .ge-controls, .ge-right-panel, .ge-fx-menu')) return;
const onImage = e.target === state.mainCanvas || e.target === state.transformOverlay; const onImage = e.target === state.mainCanvas || e.target === state.transformOverlay;
if (onImage && !directPan) return; if (onImage && !directPan) return;
@@ -357,6 +373,12 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
e.preventDefault(); e.preventDefault();
}); });
canvasArea.addEventListener('pointermove', (e) => { canvasArea.addEventListener('pointermove', (e) => {
if (outsideDrawPointerId !== null && e.pointerId === outsideDrawPointerId) {
suppressMouseUntil = Date.now() + 500;
if (!isUiChrome(e)) continueDraw(e);
e.preventDefault();
return;
}
if (transformPointerId !== null && e.pointerId === transformPointerId) { if (transformPointerId !== null && e.pointerId === transformPointerId) {
continueDraw(e); continueDraw(e);
return; return;
@@ -370,6 +392,14 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
applyOffset(next.x, next.y); applyOffset(next.x, next.y);
}); });
const endPan = (e) => { const endPan = (e) => {
if (outsideDrawPointerId !== null && (!e || e.pointerId === outsideDrawPointerId)) {
const capturedId = outsideDrawPointerId;
outsideDrawPointerId = null;
suppressMouseUntil = Date.now() + 500;
if (e?.type === 'pointercancel') cancelDraw?.();
else if (e) endDraw(e);
try { canvasArea.releasePointerCapture(capturedId); } catch {}
}
if (transformPointerId !== null && (!e || e.pointerId === transformPointerId)) { if (transformPointerId !== null && (!e || e.pointerId === transformPointerId)) {
const capturedId = transformPointerId; const capturedId = transformPointerId;
transformPointerId = null; transformPointerId = null;
+5
View File
@@ -21,6 +21,7 @@ export const EDITOR_AGENT_VERSION = '1.0';
export const DEFAULT_AGENT_ENDPOINT = '/api/editor/agent'; export const DEFAULT_AGENT_ENDPOINT = '/api/editor/agent';
import { formatCropRect, isGenericIntent } from './nl-edit.js'; import { formatCropRect, isGenericIntent } from './nl-edit.js';
import { waitForImagePreferences } from '../settings/imagePreferences.js';
export function createEditorAgent({ export function createEditorAgent({
control, control,
@@ -28,6 +29,7 @@ export function createEditorAgent({
fetchImpl = null, fetchImpl = null,
getSession = null, getSession = null,
getModel = null, getModel = null,
getGenerationModel = null,
getAgentModel = null, getAgentModel = null,
onStep = null, onStep = null,
} = {}) { } = {}) {
@@ -145,6 +147,7 @@ export function createEditorAgent({
activeStep = report; activeStep = report;
executed = []; executed = [];
running = true; running = true;
await waitForImagePreferences();
// Honest before-image (captured before any client pre-step) for the // Honest before-image (captured before any client pre-step) for the
// imperceptible-edit check, then the history mark scoping the undo group. // imperceptible-edit check, then the history mark scoping the undo group.
@@ -194,6 +197,8 @@ export function createEditorAgent({
signal: signal || undefined, signal: signal || undefined,
body: JSON.stringify({ body: JSON.stringify({
prompt, session, editor_session: session, state, screenshot, prompt, session, editor_session: session, state, screenshot,
_use_image_settings: true,
generation_model: getGenerationModel ? getGenerationModel() : '',
model: (modelInfo && modelInfo.model) || '', model: (modelInfo && modelInfo.model) || '',
endpoint: (modelInfo && modelInfo.endpoint) || '', endpoint: (modelInfo && modelInfo.endpoint) || '',
model_label: (modelInfo && modelInfo.label) || '', model_label: (modelInfo && modelInfo.label) || '',
+1 -1
View File
@@ -132,7 +132,7 @@ function renderEffects(source, effects, masks) {
const contribution = maskedContribution(next, masks[index]); const contribution = maskedContribution(next, masks[index]);
const blended = copyCanvas(current); const blended = copyCanvas(current);
const blendCtx = blended.getContext('2d'); const blendCtx = blended.getContext('2d');
if (effect.type === 'drop-shadow') blendCtx.globalCompositeOperation = 'destination-over'; if (effect.type === 'drop-shadow' && !effect.params.inside) blendCtx.globalCompositeOperation = 'destination-over';
blendCtx.globalAlpha = effect.opacity; blendCtx.globalAlpha = effect.opacity;
blendCtx.drawImage(contribution, 0, 0); blendCtx.drawImage(contribution, 0, 0);
blendCtx.globalAlpha = 1; blendCtx.globalAlpha = 1;
+2 -1
View File
@@ -81,6 +81,7 @@ export function normalizeEffect(effect) {
params.blendMode = typeof params.blendMode === 'string' ? params.blendMode : defaults.blendMode; params.blendMode = typeof params.blendMode === 'string' ? params.blendMode : defaults.blendMode;
} }
if (type === 'drop-shadow') { if (type === 'drop-shadow') {
params.inside = params.inside === true || params.inside === 1;
params.color = /^#[0-9a-f]{6}$/i.test(params.color) ? params.color : defaults.color; params.color = /^#[0-9a-f]{6}$/i.test(params.color) ? params.color : defaults.color;
for (const key of ['opacity', 'blur', 'x', 'y']) params[key] = Number(params[key]) || 0; for (const key of ['opacity', 'blur', 'x', 'y']) params[key] = Number(params[key]) || 0;
params.opacity = Math.max(0, Math.min(1, params.opacity)); params.opacity = Math.max(0, Math.min(1, params.opacity));
@@ -291,7 +292,7 @@ export function renderEffects(source, effects = [], shouldContinue = () => true)
: next; : next;
const blended = copyCanvas(current); const blended = copyCanvas(current);
const blendCtx = blended.getContext('2d'); const blendCtx = blended.getContext('2d');
if (effect.type === 'drop-shadow') blendCtx.globalCompositeOperation = 'destination-over'; if (effect.type === 'drop-shadow' && !effect.params.inside) blendCtx.globalCompositeOperation = 'destination-over';
blendCtx.globalAlpha = effect.opacity; blendCtx.globalAlpha = effect.opacity;
blendCtx.drawImage(contribution, 0, 0); blendCtx.drawImage(contribution, 0, 0);
blendCtx.globalAlpha = 1; blendCtx.globalAlpha = 1;
+71
View File
@@ -0,0 +1,71 @@
import { decodeAIImage } from './ai-operation.js';
import { waitForImagePreferences } from '../settings/imagePreferences.js';
export function createImageGenerationAction({
getDocument, placeResult, getSignal = () => null, onProgress = () => {},
formatError = info => info.detail || 'Image generation failed',
fetchImpl = (...args) => fetch(...args), timeoutMs = 330000,
}) {
return async function generateImage(params = {}) {
const document = getDocument();
if (!document.key) throw new Error('Open a document before generating an image');
const controller = new AbortController();
const parentSignal = getSignal();
const cancel = () => controller.abort();
if (parentSignal?.aborted) cancel();
parentSignal?.addEventListener('abort', cancel, { once: true });
let timedOut = false;
const deadline = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
const started = Date.now();
const progress = setInterval(() => onProgress(Math.floor((Date.now() - started) / 1000)), 1000);
// A selection can change while the provider works; preserve this request's mask.
let mask = null;
try {
if (params.masked && document.mask) {
mask = globalThis.document.createElement('canvas');
mask.width = document.mask.width; mask.height = document.mask.height;
mask.getContext('2d').drawImage(document.mask, 0, 0);
}
await waitForImagePreferences();
controller.signal.throwIfAborted();
let response;
try { response = await fetchImpl(window.geGenerateImageEndpoint || '/api/image/generate', {
method: 'POST', credentials: 'same-origin', signal: controller.signal,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ _use_image_settings: true, prompt: params.prompt || '',
width: Math.max(1, Math.round(Number(params.width) || document.width)),
height: Math.max(1, Math.round(Number(params.height) || document.height)) }),
}); } catch (error) {
if (controller.signal.aborted) throw error;
throw new Error(formatError({ network: true, detail: error.message }));
}
let data;
try { data = await response.json(); }
catch { throw new Error(response.ok ? 'Image server returned an invalid response' : `Image server failed (${response.status})`); }
if (!response.ok || data.error) throw new Error(formatError({ status: response.status,
detail: data.detail || data.error || `Image server failed (${response.status})` }));
const image = data.image || data.images?.[0];
if (!image) throw new Error('Image generation returned no image');
const decoded = await decodeAIImage(image, controller.signal);
controller.signal.throwIfAborted();
const current = getDocument();
if (current.key !== document.key || current.width !== document.width || current.height !== document.height) {
throw new Error('The document changed during generation. The result was not placed in another document.');
}
const canvas = globalThis.document.createElement('canvas');
canvas.width = decoded.naturalWidth; canvas.height = decoded.naturalHeight;
const context = canvas.getContext('2d');
context.imageSmoothingEnabled = true;
context.imageSmoothingQuality = 'high';
context.drawImage(decoded, 0, 0);
return placeResult(canvas, 'Generated', mask);
} catch (error) {
if (timedOut) throw new Error('Image generation timed out. Try again or choose a faster image model.');
throw error;
} finally {
clearTimeout(deadline);
clearInterval(progress);
parentSignal?.removeEventListener('abort', cancel);
}
};
}
+11
View File
@@ -0,0 +1,11 @@
export function imageResultGeometry(width, height, canvasWidth, canvasHeight) {
const matchingRatio = Math.abs(width * canvasHeight - height * canvasWidth) <= Math.max(canvasWidth, canvasHeight);
if (matchingRatio) {
const scale = Math.max(canvasWidth / width, canvasHeight / height);
const drawWidth = width * scale, drawHeight = height * scale;
return { width: canvasWidth, height: canvasHeight, offsetX: 0, offsetY: 0,
drawX: (canvasWidth - drawWidth) / 2, drawY: (canvasHeight - drawHeight) / 2, drawWidth, drawHeight };
}
return { width, height, offsetX: Math.round((canvasWidth - width) / 2), offsetY: Math.round((canvasHeight - height) / 2),
drawX: 0, drawY: 0, drawWidth: width, drawHeight: height };
}
+12 -5
View File
@@ -67,7 +67,7 @@ export function wireKeyboardShortcuts(deps) {
toolbar, toolKeyMap, toolbar, toolKeyMap,
composite, saveState, undo, redo, composite, saveState, undo, redo,
toggleShortcuts, confirmTransform, cancelTransform, startTransform, nudgeTransform, toggleShortcuts, confirmTransform, cancelTransform, startTransform, nudgeTransform,
resizeCustomPrompt, addEmptyLayer, brushSizeSync, resizeCustomPrompt, addEmptyLayer, brushSizeSync, openLayerAdjustment,
invertSelection, invertSelection,
wandDeleteSelection, wandCopyToNewLayer, copyPixelsToClipboard, wandDeleteSelection, wandCopyToNewLayer, copyPixelsToClipboard,
lassoDeleteSelection, lassoCopyToLayer, lassoDeleteSelection, lassoCopyToLayer,
@@ -181,6 +181,12 @@ export function wireKeyboardShortcuts(deps) {
return; return;
} }
// Save shortcuts — match the hints shown in the Save dropdown. // Save shortcuts — match the hints shown in the Save dropdown.
if (e.shiftKey && !e.altKey && e.code === 'KeyU') {
e.preventDefault();
e.stopPropagation();
openLayerAdjustment?.('hue-saturation');
return;
}
if ((e.key === 's' || e.key === 'S') && !e.altKey) { if ((e.key === 's' || e.key === 'S') && !e.altKey) {
e.preventDefault(); e.preventDefault();
document.getElementById(e.shiftKey ? 'ge-export-gallery' : 'ge-save')?.click(); document.getElementById(e.shiftKey ? 'ge-export-gallery' : 'ge-save')?.click();
@@ -221,11 +227,12 @@ export function wireKeyboardShortcuts(deps) {
addEmptyLayer(); addEmptyLayer();
return; return;
} }
// Ctrl+Alt+L — Levels adjustment. The Image menu owns the row and its // Ctrl+Alt+L edits the current layer, leaving Levels controls open.
// dialog, so click it instead of duplicating the adjustment here.
if (e.altKey && e.code === 'KeyL') { if (e.altKey && e.code === 'KeyL') {
const row = document.querySelector('[data-image-action="adj-levels"]'); e.preventDefault();
if (row) { e.preventDefault(); e.stopPropagation(); row.click(); return; } e.stopPropagation();
openLayerAdjustment?.('levels');
return;
} }
// Ctrl/Cmd+J duplicates the active layer through the layer panel's // Ctrl/Cmd+J duplicates the active layer through the layer panel's
// existing implementation, which preserves masks and effects. // existing implementation, which preserves masks and effects.
+4
View File
@@ -2233,6 +2233,7 @@ export function createLayerPanelRenderer(deps) {
if (dragSortModule) { if (dragSortModule) {
dragSortModule.enable('ge-layers-list', '.ge-layer-item', { dragSortModule.enable('ge-layers-list', '.ge-layer-item', {
instanceKey: 'ge-layers', instanceKey: 'ge-layers',
excludeSelector: '.ge-adj-sub-item',
threshold: 4, threshold: 4,
ignoreSelector: 'button, input, select, textarea, a, [contenteditable="true"], .ge-adj-sub-item', ignoreSelector: 'button, input, select, textarea, a, [contenteditable="true"], .ge-adj-sub-item',
onReorder: (orderedItems) => { onReorder: (orderedItems) => {
@@ -2258,6 +2259,9 @@ export function createLayerPanelRenderer(deps) {
state.layers = newLayers; state.layers = newLayers;
normalizeLayerClipping(state); normalizeLayerClipping(state);
composite(); composite();
// Effects, adjustments and masks are sibling rows, not children
// of the dragged row. Rebuild them under their reordered owner.
render();
} }
}, },
}); });
+8 -1
View File
@@ -6,7 +6,7 @@ const size = () => number('size', 'Size', 8, 0, 100);
const angle = () => number('angle', 'Angle', 120, -180, 180, 'deg'); const angle = () => number('angle', 'Angle', 120, -180, 180, 'deg');
export const LAYER_STYLES = { export const LAYER_STYLES = {
'bevel-emboss': { label: 'Bevel & Emboss', controls: [size(), angle(), number('depth', 'Depth', 100, 0, 300, '%'), color('highlight', 'Highlight', '#ffffff'), color('color', 'Shadow', '#000000'), opacity()] }, 'bevel-emboss': { label: 'Bevel & Emboss', controls: [size(), angle(), number('depth', 'Depth', 100, 0, 300, '%'), color('highlight', 'Highlight', '#ffffff'), color('color', 'Shadow', '#000000'), opacity()] },
'inner-shadow': { label: 'Inner Shadow', controls: [color('color', 'Color', '#000000'), opacity(), size(), angle(), number('distance', 'Distance', 6, 0, 100)] }, 'inner-shadow': { label: 'Inner Shadow', controls: [color('color', 'Color', '#000000'), opacity(), size(), angle(), number('distance', 'Distance', 6, 0, 300)] },
'inner-glow': { label: 'Inner Glow', controls: [color('color', 'Color', '#ffffff'), opacity(), size()] }, 'inner-glow': { label: 'Inner Glow', controls: [color('color', 'Color', '#ffffff'), opacity(), size()] },
satin: { label: 'Satin', controls: [color('color', 'Color', '#000000'), opacity(), size(), angle(), number('distance', 'Distance', 12, 0, 100)] }, satin: { label: 'Satin', controls: [color('color', 'Color', '#000000'), opacity(), size(), angle(), number('distance', 'Distance', 12, 0, 100)] },
'gradient-overlay': { label: 'Gradient Overlay', controls: [color('color', 'Start', '#e06c75'), color('endColor', 'End', '#ffffff'), opacity(), angle(), number('scale', 'Scale', 100, 10, 300, '%')] }, 'gradient-overlay': { label: 'Gradient Overlay', controls: [color('color', 'Start', '#e06c75'), color('endColor', 'End', '#ffffff'), opacity(), angle(), number('scale', 'Scale', 100, 10, 300, '%')] },
@@ -32,6 +32,13 @@ function surface(width, height) {
} }
export function renderDropShadow(source, params) { export function renderDropShadow(source, params) {
if (params.inside) {
return renderLayerStyle(source, 'inner-shadow', {
color: params.color, opacity: params.opacity * 100, size: params.blur / 2,
distance: Math.hypot(params.x, params.y),
angle: Math.atan2(-params.y, params.x) * 180 / Math.PI,
});
}
// Tint alpha first so RGB content cannot leak into the shadow. Draw only // Tint alpha first so RGB content cannot leak into the shadow. Draw only
// this silhouette; compositing the source again thickens translucent edges. // this silhouette; compositing the source again thickens translucent edges.
const silhouette = surface(source.width, source.height); const silhouette = surface(source.width, source.height);
+13
View File
@@ -0,0 +1,13 @@
export function finishQuickEditJob(job, result) {
if (job.cancelled || result?.cancelled) {
job.cancelled = true;
job.status = 'cancelled';
job.detail = 'Cancelled';
} else if (job.status === 'error' || result?.ok === false) {
job.status = 'error';
job.detail = result?.error || result?.message || (job.detail !== 'Working…' && job.detail) || 'Edit failed';
} else {
job.status = 'done';
job.detail = result?.message || 'Done';
}
}
+30 -8
View File
@@ -14,19 +14,26 @@ function toolSettings(tool) {
let _lastColor = null; let _lastColor = null;
let _lastTransparentColor = null; let _lastTransparentColor = null;
function transparentColor(color) { function transparentColor(color, alpha = 0) {
if (color === _lastColor && _lastTransparentColor) return _lastTransparentColor; const key = `${color}|${alpha}`;
_lastColor = color; if (key === _lastColor && _lastTransparentColor) return _lastTransparentColor;
_lastColor = key;
_lastTransparentColor = colorWithAlpha(color, alpha);
return _lastTransparentColor;
}
function colorWithAlpha(color, alpha) {
if (color.startsWith('#')) { if (color.startsWith('#')) {
const raw = color.slice(1); const raw = color.slice(1);
const expanded = raw.length === 3 ? raw.split('').map(char => char + char).join('') : raw; const expanded = raw.length === 3 ? raw.split('').map(char => char + char).join('') : raw;
const rgb = [0, 2, 4].map(index => parseInt(expanded.slice(index, index + 2), 16)); const rgb = [0, 2, 4].map(index => parseInt(expanded.slice(index, index + 2), 16));
_lastTransparentColor = `rgba(${rgb.join(',')},0)`; return `rgba(${rgb.join(',')},${alpha})`;
return _lastTransparentColor;
} }
const match = color.match(/rgba?\(([^)]+)\)/); const match = color.match(/rgba?\(([^)]+)\)/);
_lastTransparentColor = match ? `rgba(${match[1].split(',').slice(0, 3).join(',')},0)` : 'rgba(0,0,0,0)'; if (!match) return `rgba(0,0,0,${alpha})`;
return _lastTransparentColor; const components = match[1].split(',');
const originalAlpha = components.length > 3 ? Number(components[3]) : 1;
return `rgba(${components.slice(0, 3).join(',')},${alpha * originalAlpha})`;
} }
function circleStamp(ctx, x, y, radius, softness, color, alpha, operation) { function circleStamp(ctx, x, y, radius, softness, color, alpha, operation) {
@@ -38,8 +45,19 @@ function circleStamp(ctx, x, y, radius, softness, color, alpha, operation) {
ctx.fillStyle = color; ctx.fillStyle = color;
} else { } else {
const gradient = ctx.createRadialGradient(x, y, radius * hard, x, y, radius); const gradient = ctx.createRadialGradient(x, y, radius * hard, x, y, radius);
if (softness > 1) {
// Above the old maximum, remove the firm core with a progressively
// gentler alpha profile while keeping the selected brush diameter.
ctx.fillStyle = color;
const normalized = ctx.fillStyle;
for (let step = 0; step <= 16; step++) {
const t = step / 16;
gradient.addColorStop(t, transparentColor(normalized, (1 - t) ** softness));
}
} else {
gradient.addColorStop(0, color); gradient.addColorStop(0, color);
gradient.addColorStop(1, transparentColor(color)); gradient.addColorStop(1, transparentColor(color));
}
ctx.fillStyle = gradient; ctx.fillStyle = gradient;
} }
ctx.beginPath(); ctx.beginPath();
@@ -274,6 +292,10 @@ export function createStrokePipeline({ activeLayer, getActiveMaskLayer, composit
if (!PAINT_TOOLS.has(tool)) return; if (!PAINT_TOOLS.has(tool)) return;
const layer = activeLayer(); const layer = activeLayer();
if (!layer) return; if (!layer) return;
// Pixel writes invalidate adjusted previews even when adjustment settings
// themselves have not changed (otherwise retouch strokes appear late).
layer._adjFinalKey = null;
layer._adjCacheKey = null;
if (tool === 'clone') return cloneStamp(sample, layer); if (tool === 'clone') return cloneStamp(sample, layer);
if (tool === 'heal') { if (tool === 'heal') {
// A healing stroke without a picked source uses the convenient local // A healing stroke without a picked source uses the convenient local
@@ -294,7 +316,7 @@ export function createStrokePipeline({ activeLayer, getActiveMaskLayer, composit
let operation = 'source-over'; let operation = 'source-over';
let color = state.color; let color = state.color;
let alpha = opacity * flow; let alpha = opacity * flow;
let softness = Math.max(0, Math.min(1, settings.softness / 300)); let softness = Math.max(0, Math.min(4, settings.softness / 300));
if (tool === 'eraser') { operation = 'destination-out'; color = 'rgba(0,0,0,1)'; } if (tool === 'eraser') { operation = 'destination-out'; color = 'rgba(0,0,0,1)'; }
else if (tool === 'inpaint') { else if (tool === 'inpaint') {
operation = state.inpaintEraseStroke ? 'destination-out' : 'source-over'; operation = state.inpaintEraseStroke ? 'destination-out' : 'source-over';
+5 -2
View File
@@ -57,8 +57,11 @@ function wireToolSliders(prefix, fields) {
// softness rises (the CSS already sets the radial gradient — we // softness rises (the CSS already sets the radial gradient — we
// just tween the inner solid radius to communicate the falloff). // just tween the inner solid radius to communicate the falloff).
if (softPrev) { if (softPrev) {
const innerStop = Math.max(0, 60 - state[fields.softness] * 0.55); const amount = state[fields.softness];
softPrev.style.background = `radial-gradient(circle, var(--fg) 0%, var(--fg) ${innerStop}%, transparent 90%)`; const innerStop = Math.max(0, 60 - amount * 0.55);
softPrev.style.background = amount > 300
? `radial-gradient(circle, var(--fg), color-mix(in srgb, var(--fg) ${Math.round(100 * 0.5 ** (amount / 300))}%, transparent) 50%, transparent 100%)`
: `radial-gradient(circle, var(--fg) 0%, var(--fg) ${innerStop}%, transparent 90%)`;
} }
}); });
} }
+18 -4
View File
@@ -20,6 +20,23 @@ export function wireSubmenuToggles(menu) {
menu.classList.remove('ge-flyout-open'); menu.classList.remove('ge-flyout-open');
} }
}); });
function positionPanel(parent) {
const panel = parent.nextElementSibling;
if (!panel?.classList.contains('ge-submenu')) return;
const row = parent.getBoundingClientRect();
const origin = (panel.offsetParent || menu).getBoundingClientRect();
const top = Math.max(8, Math.min(row.top, window.innerHeight - panel.offsetHeight - 8));
const left = row.right + panel.offsetWidth > window.innerWidth - 8
? Math.max(8, row.left - panel.offsetWidth) : row.right - 2;
panel.style.top = `${top - origin.top + (panel.offsetParent?.scrollTop || 0)}px`;
panel.style.left = `${left - origin.left + (panel.offsetParent?.scrollLeft || 0)}px`;
}
for (const eventName of ['pointerover', 'focusin']) {
menu.addEventListener(eventName, (event) => {
const parent = event.target.closest('.ge-menu-parent');
if (parent) positionPanel(parent);
});
}
menu.addEventListener('click', (e) => { menu.addEventListener('click', (e) => {
const parent = e.target.closest('.ge-menu-parent'); const parent = e.target.closest('.ge-menu-parent');
if (!parent) return; if (!parent) return;
@@ -34,10 +51,7 @@ export function wireSubmenuToggles(menu) {
parent.setAttribute('aria-expanded', String(willOpen)); parent.setAttribute('aria-expanded', String(willOpen));
if (willOpen) { if (willOpen) {
// Align the flyout with the clicked row rather than the menu top. // Align the flyout with the clicked row rather than the menu top.
const panel = parent.nextElementSibling; positionPanel(parent);
if (panel && panel.classList.contains('ge-submenu')) {
panel.style.top = parent.offsetTop + 'px';
}
} }
}); });
} }
+2
View File
@@ -37,6 +37,7 @@
* }} deps * }} deps
*/ */
import { state } from './state.js'; import { state } from './state.js';
import { topPortalZ } from '../toolWindowZOrder.js';
import { isLayerPixelLocked, isLayerTransparencyLocked } from './layer-groups.js'; import { isLayerPixelLocked, isLayerTransparencyLocked } from './layer-groups.js';
const TOPBAR_MENU_IDS = ['ge-file-menu', 'ge-edit-menu', 'ge-view-menu', 'ge-image-menu', 'ge-layer-menu', 'ge-type-menu', 'ge-selection-menu', 'ge-filter-menu', 'ge-window-menu', 'ge-help-menu', 'ge-resize-menu', 'ge-save-menu']; const TOPBAR_MENU_IDS = ['ge-file-menu', 'ge-edit-menu', 'ge-view-menu', 'ge-image-menu', 'ge-layer-menu', 'ge-type-menu', 'ge-selection-menu', 'ge-filter-menu', 'ge-window-menu', 'ge-help-menu', 'ge-resize-menu', 'ge-save-menu'];
@@ -101,6 +102,7 @@ export function wireTopbar(deps) {
}; };
const positionSaveMenu = () => { const positionSaveMenu = () => {
const r = saveBtn.getBoundingClientRect(); const r = saveBtn.getBoundingClientRect();
saveMenu.style.zIndex = String(topPortalZ());
saveMenu.style.top = `${r.bottom + 2}px`; saveMenu.style.top = `${r.bottom + 2}px`;
saveMenu.style.right = `${Math.max(8, window.innerWidth - r.right)}px`; saveMenu.style.right = `${Math.max(8, window.innerWidth - r.right)}px`;
saveMenu.style.left = 'auto'; saveMenu.style.left = 'auto';
+8 -1
View File
@@ -2650,7 +2650,14 @@ export function openEmailLibrary(opts = {}) {
} }
// Wire events // Wire events
document.getElementById('email-lib-close').addEventListener('click', closeEmailLibrary); document.getElementById('email-lib-close').addEventListener('click', () => {
const modal = document.getElementById('email-lib-modal');
if (modal?.classList.contains('email-reading') || modal?.querySelector('.doclib-card-expanded')) {
_exitEmailReaderModeForList();
return;
}
closeEmailLibrary();
});
document.getElementById('email-settings-header-back')?.addEventListener('click', _hideEmailSettingsPage); document.getElementById('email-settings-header-back')?.addEventListener('click', _hideEmailSettingsPage);
// Clicking the modal header (anywhere except buttons/inputs) collapses // Clicking the modal header (anywhere except buttons/inputs) collapses
+18 -10
View File
@@ -73,16 +73,24 @@ function _isDangerousSrcset(value) {
// Escape + linkify URLs and email addresses. Returns innerHTML-safe markup. // Escape + linkify URLs and email addresses. Returns innerHTML-safe markup.
export function _escLinkify(text) { export function _escLinkify(text) {
const escaped = _esc(text); const raw = String(text || '');
// URLs: http(s)://... or www.... // Match raw text once so generated anchors are never linkified again.
const urlRe = /\b((?:https?:\/\/|www\.)[^\s<>"']+[^\s<>"'.,;:!?)\]])/g; const tokenRe = /\b((?:https?:\/\/|www\.)[^\s<>"']+[^\s<>"'.,;:!?)\]])|\b([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})\b/g;
const mailRe = /\b([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})\b/g; const parts = [];
return escaped let offset = 0;
.replace(urlRe, (m) => { for (const match of raw.matchAll(tokenRe)) {
const href = m.startsWith('www.') ? `https://${m}` : m; parts.push(_esc(raw.slice(offset, match.index)));
return `<a href="${_attrEsc(href)}" target="_blank" rel="noopener noreferrer">${m}</a>`; const token = match[0];
}) const isUrl = !!match[1];
.replace(mailRe, (m) => `<a href="${_attrEsc(`mailto:${m}`)}">${m}</a>`); const href = isUrl
? (token.startsWith('www.') ? `https://${token}` : token)
: `mailto:${token}`;
const attrs = isUrl ? ' target="_blank" rel="noopener noreferrer"' : '';
parts.push(`<a href="${_attrEsc(_esc(href))}"${attrs}>${_esc(token)}</a>`);
offset = match.index + token.length;
}
parts.push(_esc(raw.slice(offset)));
return parts.join('');
} }
// Pull display name out of "Name <email@x>"; fallback to local-part of // Pull display name out of "Name <email@x>"; fallback to local-part of
+5
View File
@@ -1321,7 +1321,12 @@ function _renderEditorLanding() {
// openEditor() now returns a Promise — it's async because the size // openEditor() now returns a Promise — it's async because the size
// prompt is a styled modal. Await it before checking whether the // prompt is a styled modal. Await it before checking whether the
// editor actually opened (the user may have cancelled). // editor actually opened (the user may have cancelled).
try {
await openEditor(null, null, null, 'New canvas'); await openEditor(null, null, null, 'New canvas');
} catch (error) {
// openEditor reports the initialization error and tears down its shell.
console.error('[gallery] New canvas failed', error);
}
if (!document.querySelector('#gallery-editor-container .gallery-editor')) { if (!document.querySelector('#gallery-editor-container .gallery-editor')) {
_renderEditorLanding(); _renderEditorLanding();
} }
+151 -59
View File
@@ -277,8 +277,11 @@ import { alphaBounds as _maskAlphaBounds, featherMaskCanvas as _featherMaskCanva
import { analyzeAutoTone as _analyzeAutoTone, applyAutoTone as _applyAutoTone, boxBlurRGB as _boxBlurRGB, skinMaskFromData as _skinMaskFromData, frequencySeparationSmooth as _frequencySeparationSmooth, blemishRemoval as _blemishRemoval, teethWhitening as _teethWhitening, featureExclusionMask as _featureExclusionMask, dilateAlpha as _dilateAlpha, subtractMask as _subtractMask, guidedClarity as _guidedClarity } from './editor/retouch.js'; import { analyzeAutoTone as _analyzeAutoTone, applyAutoTone as _applyAutoTone, boxBlurRGB as _boxBlurRGB, skinMaskFromData as _skinMaskFromData, frequencySeparationSmooth as _frequencySeparationSmooth, blemishRemoval as _blemishRemoval, teethWhitening as _teethWhitening, featureExclusionMask as _featureExclusionMask, dilateAlpha as _dilateAlpha, subtractMask as _subtractMask, guidedClarity as _guidedClarity } from './editor/retouch.js';
import { wireClipboardAndDrop } from './editor/clipboard-and-drop.js'; import { wireClipboardAndDrop } from './editor/clipboard-and-drop.js';
import { wireAIModelSelectors, resolveInpaintModel, resolveQuickEditModel, resolveQuickEditAgentModel } from './editor/ai-models.js'; import { wireAIModelSelectors, resolveInpaintModel, resolveQuickEditModel, resolveQuickEditAgentModel } from './editor/ai-models.js';
import { createPreflight } from './editor/preflight.js';
import { createAiSettings } from './editor/ai-settings.js'; import { createAiSettings } from './editor/ai-settings.js';
import { waitForImagePreferences } from './settings/imagePreferences.js';
import { createImageGenerationAction } from './editor/image-generation.js';
import { finishQuickEditJob } from './editor/quick-edit-job.js';
import { imageResultGeometry } from './editor/image-result-geometry.js';
import { lookRecipeSteps } from './editor/look-recipes.js'; import { lookRecipeSteps } from './editor/look-recipes.js';
import { wireInpaintButtons } from './editor/ai-inpaint.js?v=20260708match1'; import { wireInpaintButtons } from './editor/ai-inpaint.js?v=20260708match1';
import { wireAIToolsMisc } from './editor/ai-tools-misc.js'; import { wireAIToolsMisc } from './editor/ai-tools-misc.js';
@@ -356,7 +359,6 @@ function _computeTransformSnap(frame, center) {
const _INPAINT_DEFAULT_BRUSH = 100; const _INPAINT_DEFAULT_BRUSH = 100;
let _samAbortController = null; let _samAbortController = null;
let _precisionGuides = null; let _precisionGuides = null;
let _preflight = null;
let _aiSettings = null; let _aiSettings = null;
let _selectionAnimationFrame = null; let _selectionAnimationFrame = null;
let _selectionAnimationLast = 0; let _selectionAnimationLast = 0;
@@ -394,6 +396,12 @@ if (!window.__galleryEditEscHardGuardInstalled) {
} }
if (e.target?.closest?.('#styled-confirm-overlay')) return; if (e.target?.closest?.('#styled-confirm-overlay')) return;
if (e.key === 'Escape') { if (e.key === 'Escape') {
const aiSettings = document.querySelector('.ge-ai-settings:not([hidden])');
if (aiSettings) {
e.preventDefault(); e.stopImmediatePropagation();
aiSettings.querySelector('[data-ai-settings-close]')?.click();
return;
}
// Floating dialogs/popups that live outside the editor modal must close on // Floating dialogs/popups that live outside the editor modal must close on
// Escape reliably (their document-capture handlers can miss when focus is // Escape reliably (their document-capture handlers can miss when focus is
// outside them). Close the top-most one and stop here. // outside them). Close the top-most one and stop here.
@@ -838,6 +846,7 @@ function _setCanvasAiBusy(busy) {
} }
let _aiProgressTimer = null; let _aiProgressTimer = null;
let _aiProgressEpoch = 0;
function _setAiProgress(frac, label) { function _setAiProgress(frac, label) {
const wrap = document.getElementById('ge-ai-command-progress'); const wrap = document.getElementById('ge-ai-command-progress');
if (!wrap) return; if (!wrap) return;
@@ -857,12 +866,17 @@ function _startAiProgress(requestId) {
const endpointId = arguments[1] || ''; const endpointId = arguments[1] || '';
_stopAiProgress(); _stopAiProgress();
if (!requestId) return; if (!requestId) return;
const epoch = _aiProgressEpoch;
let pending = false;
const tick = async () => { const tick = async () => {
if (pending || epoch !== _aiProgressEpoch) return;
pending = true;
try { try {
const epQuery = endpointId ? `&endpoint_id=${encodeURIComponent(endpointId)}` : ''; const epQuery = endpointId ? `&endpoint_id=${encodeURIComponent(endpointId)}` : '';
const r = await fetch(`/api/image/edit-progress?request_id=${encodeURIComponent(requestId)}` + epQuery, { credentials: 'same-origin' }); const r = await fetch(`/api/image/edit-progress?request_id=${encodeURIComponent(requestId)}` + epQuery, { credentials: 'same-origin' });
if (!r.ok) return; if (!r.ok) return;
const p = await r.json(); const p = await r.json();
if (epoch !== _aiProgressEpoch) return;
const st = p.stage || ''; const st = p.stage || '';
if (st === 'done' || st === 'error') { _setAiProgress(1, st === 'done' ? 'Done' : 'Failed'); return; } if (st === 'done' || st === 'error') { _setAiProgress(1, st === 'done' ? 'Done' : 'Failed'); return; }
const frac = typeof p.progress === 'number' ? p.progress : 0; const frac = typeof p.progress === 'number' ? p.progress : 0;
@@ -871,12 +885,13 @@ function _startAiProgress(requestId) {
const verb = st === 'editing' ? 'Generating' : (st ? st[0].toUpperCase() + st.slice(1) : 'Working'); const verb = st === 'editing' ? 'Generating' : (st ? st[0].toUpperCase() + st.slice(1) : 'Working');
_setAiProgress(frac, `${verb}…${stepTxt}${eta}`); _setAiProgress(frac, `${verb}…${stepTxt}${eta}`);
_setAiCommandStatus(`${verb}…${stepTxt}${eta}`, 'running'); _setAiCommandStatus(`${verb}…${stepTxt}${eta}`, 'running');
} catch (_) {} } catch (_) {} finally { pending = false; }
}; };
_aiProgressTimer = setInterval(tick, 1000); _aiProgressTimer = setInterval(tick, 1000);
tick(); tick();
} }
function _stopAiProgress() { function _stopAiProgress() {
_aiProgressEpoch++;
if (_aiProgressTimer) { clearInterval(_aiProgressTimer); _aiProgressTimer = null; } if (_aiProgressTimer) { clearInterval(_aiProgressTimer); _aiProgressTimer = null; }
_setAiProgress(null); _setAiProgress(null);
} }
@@ -1074,6 +1089,7 @@ const _QUICK_EDIT_TOOL_SUGGESTIONS = Object.entries(_TOOLS).map(([id, t]) => ({
kind: 'Tool', kind: 'Tool',
icon: t.icon || '', icon: t.icon || '',
toolId: id, toolId: id,
runPrompt: id === 'rembg' ? 'remove background' : null,
aliases: [id], aliases: [id],
})); }));
const _QUICK_EDIT_CATALOG = [..._QUICK_EDIT_TOOL_SUGGESTIONS, ..._AI_COMMAND_SUGGESTIONS]; const _QUICK_EDIT_CATALOG = [..._QUICK_EDIT_TOOL_SUGGESTIONS, ..._AI_COMMAND_SUGGESTIONS];
@@ -1281,8 +1297,13 @@ function _wireAiCommandBox() {
if (item.toolId) { if (item.toolId) {
_clickToolButton(item.toolId); _clickToolButton(item.toolId);
_setAiCommandStatus(`${item.label} tool`, 'done'); _setAiCommandStatus(`${item.label} tool`, 'done');
if (item.runPrompt) {
input.value = item.runPrompt;
syncClearButton();
}
hideSuggestions(); hideSuggestions();
input.focus(); input.focus();
if (run && item.runPrompt) form.requestSubmit();
return true; return true;
} }
input.value = item.insert; input.value = item.insert;
@@ -1471,6 +1492,24 @@ function _wireAiCommandBox() {
// model (window.geEditorAI) just like the server would route it. // model (window.geEditorAI) just like the server would route it.
const _executeQuickEditLocal = async (prompt) => { const _executeQuickEditLocal = async (prompt) => {
const p = prompt.toLowerCase(); const p = prompt.toLowerCase();
// Background-removal intent (shared with the routing guard so the regex
// can never drift between the two call sites).
if (_looksBackgroundRemoval(p)) {
await _runQuickControlOp('ai.removeBackground', {});
// Chain a tone step when the prompt also asks for one
// ("remove the background and make it brighter", "...and warm it up").
if (/\b(bright(?:er|en)?|lighten|exposure|well[-\s]*lit)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'brightness-contrast', params: { brightness: 16, contrast: 4 } });
} else if (/\b(dark(?:er|en)?|dimmer)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'brightness-contrast', params: { brightness: -14, contrast: 4 } });
} else if (/\b(warm(?:er)?)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'white-balance', params: { temperature: 18 } });
} else if (/\b(cool(?:er)?)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'white-balance', params: { temperature: -18 } });
}
_setAiCommandStatus('Background removal finished.', 'done');
return;
}
// A targeted recolour ("make only the red car blue", "recolour the rock to // A targeted recolour ("make only the red car blue", "recolour the rock to
// teal") needs the model to repaint a specific object — never fake it with a // teal") needs the model to repaint a specific object — never fake it with a
// global colour tweak from the deterministic fast path. // global colour tweak from the deterministic fast path.
@@ -1933,24 +1972,6 @@ function _wireAiCommandBox() {
return; return;
} }
} }
// Background-removal intent (shared with the routing guard so the regex
// can never drift between the two call sites).
if (_looksBackgroundRemoval(p)) {
await _runQuickControlOp('ai.removeBackground', {});
// Chain a tone step when the prompt also asks for one
// ("remove the background and make it brighter", "...and warm it up").
if (/\b(bright(?:er|en)?|lighten|exposure|well[-\s]*lit)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'brightness-contrast', params: { brightness: 16, contrast: 4 } });
} else if (/\b(dark(?:er|en)?|dimmer)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'brightness-contrast', params: { brightness: -14, contrast: 4 } });
} else if (/\b(warm(?:er)?)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'white-balance', params: { temperature: 18 } });
} else if (/\b(cool(?:er)?)\b/.test(p)) {
await _runQuickControlOp('adjustments.apply', { type: 'white-balance', params: { temperature: -18 } });
}
_setAiCommandStatus('Background removal finished.', 'done');
return;
}
if (!/\b(text|title|caption|font|heading|subtitle)\b/.test(p) if (!/\b(text|title|caption|font|heading|subtitle)\b/.test(p)
&& /\b(upscale|higher\s*res|increase\s*resolution|bigger|2x|4x)\b/.test(p)) { && /\b(upscale|higher\s*res|increase\s*resolution|bigger|2x|4x)\b/.test(p)) {
// Use the real upscale op (Real-ESRGAN, basic-upscale fallback). The // Use the real upscale op (Real-ESRGAN, basic-upscale fallback). The
@@ -2814,8 +2835,8 @@ function _wireAiCommandBox() {
if (_looksBackgroundRemoval(prompt)) { if (_looksBackgroundRemoval(prompt)) {
_setAiCommandStatus('Removing the background…', 'running'); _setAiCommandStatus('Removing the background…', 'running');
try { try {
const done = await _executeQuickEditLocal(prompt); await _executeQuickEditLocal(prompt);
if (done !== false) return { ok: true }; return { ok: true };
} catch (err) { } catch (err) {
if (signal && signal.aborted) { _setAiCommandStatus('', ''); return { ok: false, cancelled: true }; } if (signal && signal.aborted) { _setAiCommandStatus('', ''); return { ok: false, cancelled: true }; }
const msg = err && err.message ? err.message : String(err); const msg = err && err.message ? err.message : String(err);
@@ -2841,6 +2862,7 @@ function _wireAiCommandBox() {
_setAiCommandStatus('Generated an image.', 'done'); _setAiCommandStatus('Generated an image.', 'done');
return { ok: true, image: res }; return { ok: true, image: res };
} catch (err) { } catch (err) {
if (signal?.aborted) return { ok: false, cancelled: true };
const msg = err && err.message ? err.message : String(err); const msg = err && err.message ? err.message : String(err);
_setAiCommandStatus(_isGenOfflineMsg(msg) ? msg : `Could not generate an image: ${msg}`, 'error'); _setAiCommandStatus(_isGenOfflineMsg(msg) ? msg : `Could not generate an image: ${msg}`, 'error');
return { ok: false, error: msg }; return { ok: false, error: msg };
@@ -3083,19 +3105,22 @@ function _wireAiCommandBox() {
job.controller = controller; job.controller = controller;
renderJobStack(); renderJobStack();
_quickEditActiveJob = job; _quickEditActiveJob = job;
let result;
try { try {
await executeQuickEdit(job.prompt, { forceAi: !!job.forceAi, signal: controller ? controller.signal : null }); result = await executeQuickEdit(job.prompt, { forceAi: !!job.forceAi, signal: controller ? controller.signal : null });
} catch (err) { } catch (err) {
if (!job.cancelled) { if (!job.cancelled) {
job.status = 'error'; job.status = 'error';
job.detail = err?.message || 'AI edit failed'; job.detail = err?.message || 'AI edit failed';
} }
} finally { } finally {
_stopAiProgress();
finishQuickEditJob(job, result);
_setAiCommandStatus(job.cancelled ? '' : job.detail, job.cancelled ? '' : job.status);
if (_quickEditActiveJob === job) _quickEditActiveJob = null; if (_quickEditActiveJob === job) _quickEditActiveJob = null;
job.onChange = null; job.onChange = null;
job.controller = null; job.controller = null;
if (job.cancelled) continue; if (job.cancelled) continue;
if (job.status === 'running') job.status = 'done';
renderJobStack(); renderJobStack();
setTimeout(() => dismissJob(job), job.status === 'error' ? 3200 : 1600); setTimeout(() => dismissJob(job), job.status === 'error' ? 3200 : 1600);
} }
@@ -5304,9 +5329,14 @@ function _restoreState(snap) {
// inside _buildEditor, so we touch the DOM here). // inside _buildEditor, so we touch the DOM here).
const sizeLabel = document.getElementById('ge-canvas-size'); const sizeLabel = document.getElementById('ge-canvas-size');
if (sizeLabel) sizeLabel.textContent = `${state.imgWidth}×${state.imgHeight} px`; if (sizeLabel) sizeLabel.textContent = `${state.imgWidth}×${state.imgHeight} px`;
state.rembgLiveLayer = null;
state.rembgLiveSnap = null;
} }
function undo() { function undo() {
// End sampling before restoring pixels; pointer-up must not replay the
// unfinished stroke into the restored layer without a new history entry.
if (state.drawing) _strokeTool.tryEnd();
if (state.undoStack.length === 0) return; if (state.undoStack.length === 0) return;
const target = state.undoStack.pop(); const target = state.undoStack.pop();
const cur = _snapshotState(); const cur = _snapshotState();
@@ -5759,7 +5789,20 @@ function _updateBrushCursor(e) {
state.cursorEl.style.height = diameterY + 'px'; state.cursorEl.style.height = diameterY + 'px';
} }
state.cursorEl.classList.toggle('ge-brush-cursor--pixel', pixelBrush); state.cursorEl.classList.toggle('ge-brush-cursor--pixel', pixelBrush);
state.cursorEl.style.transform = `translate3d(${clientX - diameterX / 2}px, ${clientY - diameterY / 2}px, 0)`; // Updating an inline style on every move invalidates document-wide :has()
// selectors. A paused animation keeps the same transform in the rendering
// pipeline without mutating the cursor's style attribute on every frame.
const cursorTransform = `translate3d(${clientX - diameterX / 2}px, ${clientY - diameterY / 2}px, 0)`;
if (!state.cursorEl._positionAnimation || state.cursorEl._positionAnimation.playState === 'idle') {
state.cursorEl._positionAnimation = state.cursorEl.animate(
[{ transform: cursorTransform }, { transform: cursorTransform }],
{ duration: 1, fill: 'both' },
);
state.cursorEl._positionAnimation.pause();
state.cursorEl._positionAnimation.currentTime = 0;
} else {
state.cursorEl._positionAnimation.effect.setKeyframes([{ transform: cursorTransform }, { transform: cursorTransform }]);
}
if (state.cursorEl.style.display !== 'block') { if (state.cursorEl.style.display !== 'block') {
state.cursorEl.style.display = 'block'; state.cursorEl.style.display = 'block';
} }
@@ -6522,6 +6565,11 @@ const _nudgeTransform = _transformSession.nudgeTransform;
const _confirmTransform = _transformSession.confirmTransform; const _confirmTransform = _transformSession.confirmTransform;
const _cancelTransform = _transformSession.cancelTransform; const _cancelTransform = _transformSession.cancelTransform;
window.__galleryEditorHandleEscape = () => { window.__galleryEditorHandleEscape = () => {
const aiSettings = document.querySelector('.ge-ai-settings:not([hidden])');
if (aiSettings) {
aiSettings.querySelector('[data-ai-settings-close]')?.click();
return true;
}
const sizePrompt = document.getElementById('ge-canvas-size-overlay'); const sizePrompt = document.getElementById('ge-canvas-size-overlay');
if (sizePrompt && getComputedStyle(sizePrompt).display !== 'none') { if (sizePrompt && getComputedStyle(sizePrompt).display !== 'none') {
sizePrompt._cancelCanvasSize?.(); sizePrompt._cancelCanvasSize?.();
@@ -8051,6 +8099,7 @@ async function _canMutateLayerPixels(layer, action = 'editing pixels') {
return false; return false;
} }
if (!['placed', 'text', 'shape'].includes(layer.kind)) return true; if (!['placed', 'text', 'shape'].includes(layer.kind)) return true;
if (action === 'cutting pixels') return _rasterizeLayerNow(layer);
return _confirmRasterizeLayer(layer); return _confirmRasterizeLayer(layer);
} }
@@ -8249,10 +8298,13 @@ function _filterSliderPrompt(title, params, onPreview, onCancel) {
// standard slim red-thumb styling instead of the bare browser // standard slim red-thumb styling instead of the bare browser
// default. Value chip on the same line as the label. // default. Value chip on the same line as the label.
const isColor = p.type === 'color'; const isColor = p.type === 'color';
const isSelect = p.type === 'select';
rows += ` rows += `
<div class="ge-filter-row ge-eraser-row"> <div class="ge-filter-row ge-eraser-row">
<label>${p.label}${isColor ? '' : ` <span class="ge-filter-row-value" data-val-for="${p.key}">${p.value}${p.suffix || ''}</span>`}</label> <label>${p.label}${isColor || isSelect ? '' : ` <span class="ge-filter-row-value" data-val-for="${p.key}">${p.value}${p.suffix || ''}</span>`}</label>
${isColor ${isSelect
? `<select data-key="${p.key}" class="ge-ctl-select" aria-label="${p.label}">${p.options.map(option => `<option value="${option.value}"${String(option.value) === String(p.value) ? ' selected' : ''}>${option.label}</option>`).join('')}</select>`
: isColor
? `<input type="color" data-key="${p.key}" value="${p.value}" aria-label="${p.label}" />` ? `<input type="color" data-key="${p.key}" value="${p.value}" aria-label="${p.label}" />`
: `<input type="range" data-key="${p.key}" min="${p.min}" max="${p.max}" step="${p.step || 1}" value="${p.value}" />`} : `<input type="range" data-key="${p.key}" min="${p.min}" max="${p.max}" step="${p.step || 1}" value="${p.value}" />`}
</div> </div>
@@ -8273,7 +8325,7 @@ function _filterSliderPrompt(title, params, onPreview, onCancel) {
for (const p of params) values[p.key] = p.value; for (const p of params) values[p.key] = p.value;
// Initial preview render. // Initial preview render.
try { onPreview(values); } catch {} try { onPreview(values); } catch {}
overlay.querySelectorAll('input[data-key]').forEach(inp => { overlay.querySelectorAll('input[data-key], select[data-key]').forEach(inp => {
inp.addEventListener('input', (e) => { inp.addEventListener('input', (e) => {
if (!isCurrent()) { cleanup(null); return; } if (!isCurrent()) { cleanup(null); return; }
const k = e.target.dataset.key; const k = e.target.dataset.key;
@@ -8304,7 +8356,7 @@ function _filterSliderPrompt(title, params, onPreview, onCancel) {
e.preventDefault(); e.preventDefault();
cleanup(e.target?.dataset.action === 'cancel' ? null : values); cleanup(e.target?.dataset.action === 'cancel' ? null : values);
} else if (e.key === 'Tab') { } else if (e.key === 'Tab') {
const fields = [...overlay.querySelectorAll('input, button')]; const fields = [...overlay.querySelectorAll('input, select, button')];
const index = fields.indexOf(document.activeElement); const index = fields.indexOf(document.activeElement);
e.preventDefault(); e.preventDefault();
fields[(index + (e.shiftKey ? -1 : 1) + fields.length) % fields.length]?.focus(); fields[(index + (e.shiftKey ? -1 : 1) + fields.length) % fields.length]?.focus();
@@ -8316,7 +8368,7 @@ function _filterSliderPrompt(title, params, onPreview, onCancel) {
if (!overlay.isConnected || !isCurrent()) cleanup(null); if (!overlay.isConnected || !isCurrent()) cleanup(null);
}); });
observer.observe(state.container, { childList: true, subtree: true }); observer.observe(state.container, { childList: true, subtree: true });
overlay.querySelector('input, button')?.focus({ preventScroll: true }); overlay.querySelector('input, select, button')?.focus({ preventScroll: true });
overlay.querySelector('[data-action="apply"]').addEventListener('click', () => cleanup(values)); overlay.querySelector('[data-action="apply"]').addEventListener('click', () => cleanup(values));
overlay.querySelector('[data-action="cancel"]').addEventListener('click', () => cleanup(null)); overlay.querySelector('[data-action="cancel"]').addEventListener('click', () => cleanup(null));
// Click outside the modal (on the dim backdrop) = cancel. // Click outside the modal (on the dim backdrop) = cancel.
@@ -8482,6 +8534,7 @@ function _shadowOffsets(values = {}) {
return { return {
x: Math.round(Math.cos(radians) * distance), x: Math.round(Math.cos(radians) * distance),
y: Math.round(-Math.sin(radians) * distance), y: Math.round(-Math.sin(radians) * distance),
inside: Number(values.inside) === 1,
}; };
} }
@@ -8543,6 +8596,7 @@ async function _addRetainedEffect(type, presetName = null) {
{ key: 'color', label: 'Color', type: 'color', value: '#000000' }, { key: 'color', label: 'Color', type: 'color', value: '#000000' },
{ key: 'opacity', label: 'Opacity', min: 0, max: 100, step: 1, value: 45, suffix: '%' }, { key: 'opacity', label: 'Opacity', min: 0, max: 100, step: 1, value: 45, suffix: '%' },
{ key: 'blur', label: 'Blur', min: 0, max: 100, step: 1, value: 12, suffix: 'px' }, { key: 'blur', label: 'Blur', min: 0, max: 100, step: 1, value: 12, suffix: 'px' },
{ key: 'inside', label: 'Position', type: 'select', value: 0, options: [{ value: 0, label: 'Outside' }, { value: 1, label: 'Inside' }] },
{ key: 'distance', label: 'Distance', min: 0, max: 200, step: 1, value: _shadowAngleDistance({ x: 4, y: 6 }).distance, suffix: 'px' }, { key: 'distance', label: 'Distance', min: 0, max: 200, step: 1, value: _shadowAngleDistance({ x: 4, y: 6 }).distance, suffix: 'px' },
{ key: 'angle', label: 'Direction', min: -180, max: 180, step: 1, value: _shadowAngleDistance({ x: 4, y: 6 }).angle, suffix: '\u00b0' }, { key: 'angle', label: 'Direction', min: -180, max: 180, step: 1, value: _shadowAngleDistance({ x: 4, y: 6 }).angle, suffix: '\u00b0' },
]; ];
@@ -8756,6 +8810,7 @@ async function _editRetainedEffect(layer, effect) {
{ key: 'color', label: 'Color', type: 'color', value: p.color || '#000000' }, { key: 'color', label: 'Color', type: 'color', value: p.color || '#000000' },
{ key: 'opacity', label: 'Opacity', min: 0, max: 100, step: 1, value: Math.round((Number(p.opacity) || 0) * 100), suffix: '%' }, { key: 'opacity', label: 'Opacity', min: 0, max: 100, step: 1, value: Math.round((Number(p.opacity) || 0) * 100), suffix: '%' },
{ key: 'blur', label: 'Blur', min: 0, max: 100, step: 1, value: Number(p.blur) || 0, suffix: 'px' }, { key: 'blur', label: 'Blur', min: 0, max: 100, step: 1, value: Number(p.blur) || 0, suffix: 'px' },
{ key: 'inside', label: 'Position', type: 'select', value: p.inside ? 1 : 0, options: [{ value: 0, label: 'Outside' }, { value: 1, label: 'Inside' }] },
{ key: 'distance', label: 'Distance', min: 0, max: 200, step: 1, value: _shadowAngleDistance(p).distance, suffix: 'px' }, { key: 'distance', label: 'Distance', min: 0, max: 200, step: 1, value: _shadowAngleDistance(p).distance, suffix: 'px' },
{ key: 'angle', label: 'Direction', min: -180, max: 180, step: 1, value: _shadowAngleDistance(p).angle, suffix: '\u00b0' }, { key: 'angle', label: 'Direction', min: -180, max: 180, step: 1, value: _shadowAngleDistance(p).angle, suffix: '\u00b0' },
]; ];
@@ -9980,9 +10035,8 @@ function _buildEditor(container) {
if (colorRow) colorRow.style.display = ['eraser', 'clone', 'heal', 'smudge', 'dodge', 'burn', 'liquify'].includes(toolId) ? 'none' : ''; if (colorRow) colorRow.style.display = ['eraser', 'clone', 'heal', 'smudge', 'dodge', 'burn', 'liquify'].includes(toolId) ? 'none' : '';
const colorLabel = colorRow?.querySelector('label'); const colorLabel = colorRow?.querySelector('label');
if (colorLabel) colorLabel.textContent = 'Color'; if (colorLabel) colorLabel.textContent = 'Color';
// Per-tool stroke modifiers all live in the shared brush "More" menu so // Secondary modifiers stay in More; brush softness remains in the main
// every brush-family tool has the same compact strip as the Brush. Only // strip. Only the active tool's secondary group is shown.
// the group for the active tool is shown; the rest stay hidden.
const strokeTool = (toolId === 'brush' || toolId === 'pixel' || toolId === 'dodge' || toolId === 'burn') ? 'brush' const strokeTool = (toolId === 'brush' || toolId === 'pixel' || toolId === 'dodge' || toolId === 'burn') ? 'brush'
: toolId === 'eraser' ? 'eraser' : toolId === 'eraser' ? 'eraser'
: (toolId === 'clone' || toolId === 'heal') ? 'clone' : (toolId === 'clone' || toolId === 'heal') ? 'clone'
@@ -9992,6 +10046,8 @@ function _buildEditor(container) {
row.style.display = row.dataset.strokeTool === strokeTool ? '' : 'none'; row.style.display = row.dataset.strokeTool === strokeTool ? '' : 'none';
}); });
const dodgeBurnRow = document.getElementById('ge-dodgeburn-intensity-row'); const dodgeBurnRow = document.getElementById('ge-dodgeburn-intensity-row');
const brushSoftnessRow = document.getElementById('ge-brush-softness-row');
if (brushSoftnessRow) brushSoftnessRow.style.display = ['brush', 'dodge', 'burn'].includes(toolId) ? '' : 'none';
// Intensity sits in the strip next to Size, so it must show for Dodge and // Intensity sits in the strip next to Size, so it must show for Dodge and
// Burn only (and never for the other brush-family tools). // Burn only (and never for the other brush-family tools).
if (dodgeBurnRow) dodgeBurnRow.style.display = (toolId === 'dodge' || toolId === 'burn') ? '' : 'none'; if (dodgeBurnRow) dodgeBurnRow.style.display = (toolId === 'dodge' || toolId === 'burn') ? '' : 'none';
@@ -10444,7 +10500,6 @@ function _buildEditor(container) {
canvasArea.appendChild(state.transformOverlay); canvasArea.appendChild(state.transformOverlay);
canvasArea.appendChild(_buildQuickMaskBar()); canvasArea.appendChild(_buildQuickMaskBar());
canvasArea.appendChild(_buildAiCommandBox()); canvasArea.appendChild(_buildAiCommandBox());
_preflight = createPreflight({ canvasArea });
_aiSettings = createAiSettings({ container }); _aiSettings = createAiSettings({ container });
try { window.geEditorAiSettings = _aiSettings; } catch (_) {} try { window.geEditorAiSettings = _aiSettings; } catch (_) {}
// On phones the rulers eat scarce canvas width; default them off. // On phones the rulers eat scarce canvas width; default them off.
@@ -10637,19 +10692,10 @@ function _buildEditor(container) {
const initialStatusTool = document.getElementById('ge-status-tool'); const initialStatusTool = document.getElementById('ge-status-tool');
if (initialStatusTool) initialStatusTool.textContent = _TOOLS[state.tool]?.label || state.tool || ''; if (initialStatusTool) initialStatusTool.textContent = _TOOLS[state.tool]?.label || state.tool || '';
} }
// Preflight checklist: greet the user on open (unless dismissed) and // Keep model configuration in the AI settings dialog.
// expose a footer button to re-open it.
try { try {
const footer = container.querySelector('.ge-editor-footer'); const footer = container.querySelector('.ge-editor-footer');
if (footer) { if (footer) {
const setupBtn = document.createElement('button');
setupBtn.type = 'button';
setupBtn.id = 'ge-setup-btn';
setupBtn.className = 'ge-setup-btn';
setupBtn.title = 'Editor setup checklist';
setupBtn.textContent = 'Setup';
setupBtn.addEventListener('click', () => _preflight?.open());
footer.appendChild(setupBtn);
const aiBtn = document.createElement('button'); const aiBtn = document.createElement('button');
aiBtn.type = 'button'; aiBtn.type = 'button';
aiBtn.id = 'ge-ai-settings-btn'; aiBtn.id = 'ge-ai-settings-btn';
@@ -10659,7 +10705,6 @@ function _buildEditor(container) {
aiBtn.addEventListener('click', () => _aiSettings?.open()); aiBtn.addEventListener('click', () => _aiSettings?.open());
footer.appendChild(aiBtn); footer.appendChild(aiBtn);
} }
_preflight?.maybeOpen();
} catch (_) {} } catch (_) {}
try { _initControlKit(container); } catch (_) {} try { _initControlKit(container); } catch (_) {}
let _lastLayoutDesktop = null; let _lastLayoutDesktop = null;
@@ -11779,6 +11824,14 @@ function _buildEditor(container) {
// Keyboard shortcuts — full implementation in // Keyboard shortcuts — full implementation in
// editor/keyboard-shortcuts.js. // editor/keyboard-shortcuts.js.
wireKeyboardShortcuts({ wireKeyboardShortcuts({
openLayerAdjustment: (type) => {
const layer = activeLayer();
if (!layer || !layer.canvas || layer.kind === 'adjustment') {
uiModule?.showToast('Select an image layer first');
return;
}
_openAdjPopup(layer, type, document.getElementById('ge-image-menu-btn'));
},
fillSelection: _doFillSelection, fillSelection: _doFillSelection,
copyPixelsToClipboard: _copyPixelsToClipboard, copyPixelsToClipboard: _copyPixelsToClipboard,
toolbar, toolKeyMap: _toolKeyMap, toolbar, toolKeyMap: _toolKeyMap,
@@ -12143,7 +12196,9 @@ function _buildEditor(container) {
out.getContext('2d').drawImage(layer.canvas, off.x, off.y); out.getContext('2d').drawImage(layer.canvas, off.x, off.y);
return out; return out;
}; };
const _aiEditCanvas = async (endpoint, payload = {}, { keepNaturalSize = false } = {}) => { const _aiEditCanvas = async (endpoint, payload = {}, { keepNaturalSize = true } = {}) => {
await waitForImagePreferences();
if (endpoint === '/api/image/inpaint') payload = { ...payload, _use_image_settings: true };
const flat = _aiEditSourceCanvas(); const flat = _aiEditSourceCanvas();
const image = flat.toDataURL('image/png').split(',')[1]; const image = flat.toDataURL('image/png').split(',')[1];
const requestId = 'qe-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8); const requestId = 'qe-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
@@ -12154,7 +12209,7 @@ function _buildEditor(container) {
} else { } else {
_startAiProgress(requestId); _startAiProgress(requestId);
} }
const body = JSON.stringify({ image, request_id: requestId, ...payload }); const body = JSON.stringify({ image, width: flat.width, height: flat.height, request_id: requestId, ...payload });
// The image servers occasionally reject a request transiently (503 while a // The image servers occasionally reject a request transiently (503 while a
// model swaps, 502/504 gateways, dropped connections). Retry those a couple // model swaps, 502/504 gateways, dropped connections). Retry those a couple
// of times with backoff so a hiccup doesn't silently leave the canvas // of times with backoff so a hiccup doesn't silently leave the canvas
@@ -12212,7 +12267,7 @@ function _buildEditor(container) {
c.height = state.imgHeight; c.height = state.imgHeight;
} }
c.getContext('2d').drawImage(img, 0, 0, c.width, c.height); c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
return { canvas: c, dataUrl: c.toDataURL('image/png') }; return { canvas: c, dataUrl: c.toDataURL('image/png'), fullFrame: data.full_frame === true };
} finally { } finally {
if (_timer) clearTimeout(_timer); if (_timer) clearTimeout(_timer);
if (_aiEditAbort === _ctl) _aiEditAbort = null; if (_aiEditAbort === _ctl) _aiEditAbort = null;
@@ -12221,12 +12276,17 @@ function _buildEditor(container) {
}; };
const _placeResultLayer = (canvas, name, maskCanvas) => { const _placeResultLayer = (canvas, name, maskCanvas) => {
_saveState(`AI: ${name}`); _saveState(`AI: ${name}`);
const layer = createLayer(name, state.imgWidth, state.imgHeight); const geometry = imageResultGeometry(canvas.width, canvas.height, state.imgWidth, state.imgHeight);
layer.ctx.drawImage(canvas, 0, 0); const layer = createLayer(name, geometry.width, geometry.height);
const offset = { x: geometry.offsetX, y: geometry.offsetY };
state.layerOffsets.set(layer.id, offset);
layer.ctx.imageSmoothingEnabled = true;
layer.ctx.imageSmoothingQuality = 'high';
layer.ctx.drawImage(canvas, geometry.drawX, geometry.drawY, geometry.drawWidth, geometry.drawHeight);
if (maskCanvas) { if (maskCanvas) {
layer.ctx.save(); layer.ctx.save();
layer.ctx.globalCompositeOperation = 'destination-in'; layer.ctx.globalCompositeOperation = 'destination-in';
layer.ctx.drawImage(maskCanvas, 0, 0); layer.ctx.drawImage(maskCanvas, -offset.x, -offset.y);
layer.ctx.restore(); layer.ctx.restore();
} }
state.layers.push(layer); state.layers.push(layer);
@@ -12236,13 +12296,24 @@ function _buildEditor(container) {
_renderLayerPanel(); _renderLayerPanel();
return layer.id; return layer.id;
}; };
const _generateImage = createImageGenerationAction({
formatError: _generationErrorMessage,
getDocument: () => ({
key: state.editorOpen ? `${state.editorSessionToken}:${state.documentId}` : null,
width: state.imgWidth, height: state.imgHeight, mask: state.wandMask,
}),
getSignal: () => _quickEditActiveJob?.controller?.signal,
onProgress: seconds => _setAiCommandStatus(`Generating an image… ${seconds}s`, 'running'),
placeResult: _placeResultLayer,
});
const _aiInpaintSelection = async (prompt) => { const _aiInpaintSelection = async (prompt) => {
if (!state.wandMask) throw new Error('make a selection first'); if (!state.wandMask) throw new Error('make a selection first');
const layer = activeLayer() || _activeParentLayer(); const layer = activeLayer() || _activeParentLayer();
if (!layer) throw new Error('no layer'); if (!layer) throw new Error('no layer');
const mask = state.wandMask.toDataURL('image/png').split(',')[1]; const mask = state.wandMask.toDataURL('image/png').split(',')[1];
const { canvas } = await _aiEditCanvas('/api/image/inpaint', { mask, prompt: prompt || '', steps: 4 }); const selection = state.wandMask;
return _placeResultLayer(canvas, 'Generative fill', state.wandMask); const { canvas, fullFrame } = await _aiEditCanvas('/api/image/inpaint', { mask, prompt: prompt || '', steps: 4 });
return _placeResultLayer(canvas, 'Generative fill', fullFrame ? null : selection);
}; };
// Replace the background/scene while keeping the subject: the server derives // Replace the background/scene while keeping the subject: the server derives
// the subject mask, repaints the inverse (new background), harmonises colour // the subject mask, repaints the inverse (new background), harmonises colour
@@ -12535,7 +12606,7 @@ function _buildEditor(container) {
'layers.delete': { description: 'Delete layers (defaults to selection).', run: (p) => { if (p && (p.id || p.index || p.name)) _controlSelect(_controlFindLayer(p)); _layerPanelRenderer.deleteSelectedLayers?.(); return true; } }, 'layers.delete': { description: 'Delete layers (defaults to selection).', run: (p) => { if (p && (p.id || p.index || p.name)) _controlSelect(_controlFindLayer(p)); _layerPanelRenderer.deleteSelectedLayers?.(); return true; } },
'layers.setOpacity': { description: 'Set a layer opacity (0-1).', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); _saveState(`Change opacity of ${l.name}`); l.opacity = Math.max(0, Math.min(1, Number(p.opacity))); composite(); _renderLayerPanel(); return l.id; } }, 'layers.setOpacity': { description: 'Set a layer opacity (0-1).', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); _saveState(`Change opacity of ${l.name}`); l.opacity = Math.max(0, Math.min(1, Number(p.opacity))); composite(); _renderLayerPanel(); return l.id; } },
'layers.setBlend': { description: 'Set a layer blend mode.', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); _saveState(`Change blend mode of ${l.name}`); l.blendMode = p.blendMode || p.mode || 'source-over'; composite(); _renderLayerPanel(); return l.id; } }, 'layers.setBlend': { description: 'Set a layer blend mode.', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); _saveState(`Change blend mode of ${l.name}`); l.blendMode = p.blendMode || p.mode || 'source-over'; composite(); _renderLayerPanel(); return l.id; } },
'layers.placeImage': { description: 'Place an image (data URL) as a NEW layer, masked to the current selection when one exists; never overwrites the original. Instruction mode (mode:"instruction" or differenceMask:true) keeps untouched areas pixel-identical via a difference map. {dataUrl,name,masked,blend,opacity,x,y,w,h,mode,differenceMask,diffThreshold,diffGrow,diffFeather}.', run: (p) => new Promise((resolve, reject) => { if (!p || !p.dataUrl) { reject(new Error('dataUrl required')); return; } const img = new Image(); img.onload = () => { try { _saveState(`Place ${p.name || 'image'}`); const dw = state.imgWidth, dh = state.imgHeight; const useDiff = (p.differenceMask === true) || String(p.mode || '').toLowerCase() === 'instruction'; const beforeSnap = useDiff ? flatten() : null; const layer = createLayer(p.name || 'Placed image', dw, dh); let tw = Number(p.w), th = Number(p.h); if (!(tw > 0) || !(th > 0)) { if (useDiff) { tw = dw; th = dh; } else { const scale = Math.min(dw / img.naturalWidth, dh / img.naturalHeight); tw = Math.max(1, Math.round(img.naturalWidth * scale)); th = Math.max(1, Math.round(img.naturalHeight * scale)); } } let tx = Number(p.x), ty = Number(p.y); if (!Number.isFinite(tx)) tx = useDiff ? 0 : Math.round((dw - tw) / 2); if (!Number.isFinite(ty)) ty = useDiff ? 0 : Math.round((dh - th) / 2); layer.ctx.imageSmoothingEnabled = true; layer.ctx.imageSmoothingQuality = 'high'; layer.ctx.drawImage(img, tx, ty, tw, th); if (p.masked !== false && state.wandMask) { layer.ctx.save(); layer.ctx.globalCompositeOperation = 'destination-in'; layer.ctx.drawImage(state.wandMask, 0, 0); layer.ctx.restore(); } else if (useDiff && beforeSnap) { const diff = _differenceMaskCanvas(beforeSnap, layer.canvas, { threshold: p.diffThreshold, grow: p.diffGrow, feather: p.diffFeather, edgeExcludePx: 0 }); const explicitEdge = p.edgeExcludePx != null ? Number(p.edgeExcludePx) : null; const sceneReplace = diff.changedFraction > 0.5; const edgeExclude = sceneReplace ? 0 : (explicitEdge != null ? explicitEdge : 3); if (edgeExclude > 0) _clearMaskEdgeBand(diff.mask, edgeExclude); layer.ctx.save(); layer.ctx.globalCompositeOperation = 'destination-in'; layer.ctx.drawImage(diff.mask, 0, 0); layer.ctx.restore(); if (sceneReplace) _edgeFillFromInterior(layer.ctx, dw, dh, 3); } if (p.blend) layer.blendMode = p.blend; if (p.opacity != null) layer.opacity = Math.max(0, Math.min(1, Number(p.opacity))); state.layers.push(layer); state.activeLayerId = layer.id; state.selectedLayerIds = [layer.id]; _renderLayerPanel(); composite(); resolve(layer.id); } catch (e) { reject(e); } }; img.onerror = () => reject(new Error('image load failed')); img.src = p.dataUrl; }) }, 'layers.placeImage': { description: 'Place an image (data URL) as a NEW layer, masked to the current selection when one exists; never overwrites the original. Instruction mode (mode:"instruction" or differenceMask:true) keeps untouched areas pixel-identical via a difference map. {dataUrl,name,masked,blend,opacity,x,y,w,h,mode,differenceMask,diffThreshold,diffGrow,diffFeather}.', run: (p) => new Promise((resolve, reject) => { if (!p || !p.dataUrl) { reject(new Error('dataUrl required')); return; } const img = new Image(); img.onload = () => { try { _saveState(`Place ${p.name || 'image'}`); const dw = state.imgWidth, dh = state.imgHeight; const useDiff = p.nativeSize !== true && ((p.differenceMask === true) || String(p.mode || '').toLowerCase() === 'instruction'); const beforeSnap = useDiff ? flatten() : null; const nativeSize = p.nativeSize === true && !useDiff; const geometry = imageResultGeometry(img.naturalWidth, img.naturalHeight, dw, dh); const layer = createLayer(p.name || 'Placed image', nativeSize ? geometry.width : dw, nativeSize ? geometry.height : dh); const nativeOffset = { x: geometry.offsetX, y: geometry.offsetY }; if (nativeSize) state.layerOffsets.set(layer.id, nativeOffset); let tw = Number(p.w), th = Number(p.h); if (!(tw > 0) || !(th > 0)) { if (nativeSize) { tw = geometry.drawWidth; th = geometry.drawHeight; } else if (useDiff) { tw = dw; th = dh; } else { const scale = Math.min(dw / img.naturalWidth, dh / img.naturalHeight); tw = Math.max(1, Math.round(img.naturalWidth * scale)); th = Math.max(1, Math.round(img.naturalHeight * scale)); } } let tx = Number(p.x), ty = Number(p.y); if (!Number.isFinite(tx)) tx = nativeSize ? geometry.drawX : useDiff ? 0 : Math.round((dw - tw) / 2); if (!Number.isFinite(ty)) ty = nativeSize ? geometry.drawY : useDiff ? 0 : Math.round((dh - th) / 2); layer.ctx.imageSmoothingEnabled = true; layer.ctx.imageSmoothingQuality = 'high'; layer.ctx.drawImage(img, tx, ty, tw, th); if (p.masked !== false && state.wandMask) { layer.ctx.save(); layer.ctx.globalCompositeOperation = 'destination-in'; layer.ctx.drawImage(state.wandMask, nativeSize ? -nativeOffset.x : 0, nativeSize ? -nativeOffset.y : 0); layer.ctx.restore(); } else if (useDiff && beforeSnap) { const diff = _differenceMaskCanvas(beforeSnap, layer.canvas, { threshold: p.diffThreshold, grow: p.diffGrow, feather: p.diffFeather, edgeExcludePx: 0 }); const explicitEdge = p.edgeExcludePx != null ? Number(p.edgeExcludePx) : null; const sceneReplace = diff.changedFraction > 0.5; const edgeExclude = sceneReplace ? 0 : (explicitEdge != null ? explicitEdge : 3); if (edgeExclude > 0) _clearMaskEdgeBand(diff.mask, edgeExclude); layer.ctx.save(); layer.ctx.globalCompositeOperation = 'destination-in'; layer.ctx.drawImage(diff.mask, 0, 0); layer.ctx.restore(); if (sceneReplace) _edgeFillFromInterior(layer.ctx, dw, dh, 3); } if (p.blend) layer.blendMode = p.blend; if (p.opacity != null) layer.opacity = Math.max(0, Math.min(1, Number(p.opacity))); state.layers.push(layer); state.activeLayerId = layer.id; state.selectedLayerIds = [layer.id]; _renderLayerPanel(); composite(); resolve(layer.id); } catch (e) { reject(e); } }; img.onerror = () => reject(new Error('image load failed')); img.src = p.dataUrl; }) },
'layers.addMaskFromSelection': { description: 'Add a layer mask from the current selection (reveals the selection). {invert}.', run: (p) => { const parent = _activeParentLayer(); if (!parent) throw new Error('no layer'); _saveState('Add layer mask'); const mask = _ensureActiveMaskLayer(); if (!mask) throw new Error('could not create mask'); const w = mask.canvas.width, h = mask.canvas.height; const mctx = mask.ctx; const off = state.layerOffsets.get(parent.id) || { x: 0, y: 0 }; const ox = -(off.x || 0), oy = -(off.y || 0); mctx.globalCompositeOperation = 'source-over'; mctx.clearRect(0, 0, w, h); if (state.wandMask) { if (p && p.invert) { mctx.fillStyle = '#fff'; mctx.fillRect(0, 0, w, h); mctx.globalCompositeOperation = 'destination-out'; mctx.drawImage(state.wandMask, ox, oy); mctx.globalCompositeOperation = 'source-over'; } else { mctx.drawImage(state.wandMask, ox, oy); } } else { mctx.fillStyle = (p && p.invert) ? '#000' : '#fff'; mctx.fillRect(0, 0, w, h); } composite(); _renderLayerPanel(); return mask.id; } }, 'layers.addMaskFromSelection': { description: 'Add a layer mask from the current selection (reveals the selection). {invert}.', run: (p) => { const parent = _activeParentLayer(); if (!parent) throw new Error('no layer'); _saveState('Add layer mask'); const mask = _ensureActiveMaskLayer(); if (!mask) throw new Error('could not create mask'); const w = mask.canvas.width, h = mask.canvas.height; const mctx = mask.ctx; const off = state.layerOffsets.get(parent.id) || { x: 0, y: 0 }; const ox = -(off.x || 0), oy = -(off.y || 0); mctx.globalCompositeOperation = 'source-over'; mctx.clearRect(0, 0, w, h); if (state.wandMask) { if (p && p.invert) { mctx.fillStyle = '#fff'; mctx.fillRect(0, 0, w, h); mctx.globalCompositeOperation = 'destination-out'; mctx.drawImage(state.wandMask, ox, oy); mctx.globalCompositeOperation = 'source-over'; } else { mctx.drawImage(state.wandMask, ox, oy); } } else { mctx.fillStyle = (p && p.invert) ? '#000' : '#fff'; mctx.fillRect(0, 0, w, h); } composite(); _renderLayerPanel(); return mask.id; } },
'layers.removeMask': { description: 'Remove the active layer mask (does not affect pixels).', run: () => { const parent = _activeParentLayer(); if (!parent || !parent.masks || !parent.masks.length) throw new Error('no mask'); _saveState('Remove layer mask'); parent.masks = parent.masks.filter((m) => m.id !== parent.activeMaskId); parent.activeMaskId = parent.masks[0]?.id || null; composite(); _renderLayerPanel(); return true; } }, 'layers.removeMask': { description: 'Remove the active layer mask (does not affect pixels).', run: () => { const parent = _activeParentLayer(); if (!parent || !parent.masks || !parent.masks.length) throw new Error('no mask'); _saveState('Remove layer mask'); parent.masks = parent.masks.filter((m) => m.id !== parent.activeMaskId); parent.activeMaskId = parent.masks[0]?.id || null; composite(); _renderLayerPanel(); return true; } },
'layers.applyMask': { description: 'Bake the active layer mask into the layer alpha and remove the mask.', run: () => { const parent = _activeParentLayer(); const mask = _getActiveMaskLayer(); if (!parent || !parent.ctx || !mask) throw new Error('no mask to apply'); _saveState('Apply layer mask'); _bakeMaskIntoLayer(parent.ctx, mask.canvas, 0, 0); parent.masks = parent.masks.filter((m) => m.id !== mask.id); parent.activeMaskId = parent.masks[0]?.id || null; composite(); _renderLayerPanel(); return true; } }, 'layers.applyMask': { description: 'Bake the active layer mask into the layer alpha and remove the mask.', run: () => { const parent = _activeParentLayer(); const mask = _getActiveMaskLayer(); if (!parent || !parent.ctx || !mask) throw new Error('no mask to apply'); _saveState('Apply layer mask'); _bakeMaskIntoLayer(parent.ctx, mask.canvas, 0, 0); parent.masks = parent.masks.filter((m) => m.id !== mask.id); parent.activeMaskId = parent.masks[0]?.id || null; composite(); _renderLayerPanel(); return true; } },
@@ -12551,7 +12622,7 @@ function _buildEditor(container) {
'ai.removeObject': { description: 'Remove the selected object and fill naturally. {prompt}.', run: (p) => _aiInpaintSelection((p && p.prompt) || 'remove the object, fill the area naturally') }, 'ai.removeObject': { description: 'Remove the selected object and fill naturally. {prompt}.', run: (p) => _aiInpaintSelection((p && p.prompt) || 'remove the object, fill the area naturally') },
'ai.harmonize': { description: 'Harmonize the layer/selection lighting with the rest of the image; result is a NEW layer. {strength}.', run: async (p) => { const { canvas } = await _aiEditCanvas('/api/image/harmonize', { strength: Number(p && p.strength) || 0.4 }); return _placeResultLayer(canvas, 'Harmonized', state.wandMask || null); } }, 'ai.harmonize': { description: 'Harmonize the layer/selection lighting with the rest of the image; result is a NEW layer. {strength}.', run: async (p) => { const { canvas } = await _aiEditCanvas('/api/image/harmonize', { strength: Number(p && p.strength) || 0.4 }); return _placeResultLayer(canvas, 'Harmonized', state.wandMask || null); } },
'ai.generativeUpscale': { description: 'Upscale the image 2x/4x; result is a NEW layer. Falls back to a high-quality canvas upscale labelled "basic upscale" when no Real-ESRGAN model is served. {scale}.', run: async (p) => { const scale = Number(p && p.scale) === 4 ? 4 : 2; try { const { canvas } = await _aiEditCanvas('/api/image/upscale-local', { scale }); return _placeResultLayer(canvas, `Upscaled ${scale}x`, null); } catch (e) { const src = flatten(); const c = document.createElement('canvas'); c.width = Math.max(1, Math.round(src.width * scale)); c.height = Math.max(1, Math.round(src.height * scale)); const cx = c.getContext('2d'); cx.imageSmoothingEnabled = true; cx.imageSmoothingQuality = 'high'; cx.drawImage(src, 0, 0, c.width, c.height); _saveState('Upscale (basic)'); _resizeCanvasDocument(state, c.width, c.height, { anchorX: 0, anchorY: 0 }); const layerId = _placeResultLayer(c, `Upscaled ${scale}x (basic upscale)`, null); return { layerId, scale, method: 'basic', reason: String(e && e.message || e) }; } } }, 'ai.generativeUpscale': { description: 'Upscale the image 2x/4x; result is a NEW layer. Falls back to a high-quality canvas upscale labelled "basic upscale" when no Real-ESRGAN model is served. {scale}.', run: async (p) => { const scale = Number(p && p.scale) === 4 ? 4 : 2; try { const { canvas } = await _aiEditCanvas('/api/image/upscale-local', { scale }); return _placeResultLayer(canvas, `Upscaled ${scale}x`, null); } catch (e) { const src = flatten(); const c = document.createElement('canvas'); c.width = Math.max(1, Math.round(src.width * scale)); c.height = Math.max(1, Math.round(src.height * scale)); const cx = c.getContext('2d'); cx.imageSmoothingEnabled = true; cx.imageSmoothingQuality = 'high'; cx.drawImage(src, 0, 0, c.width, c.height); _saveState('Upscale (basic)'); _resizeCanvasDocument(state, c.width, c.height, { anchorX: 0, anchorY: 0 }); const layerId = _placeResultLayer(c, `Upscaled ${scale}x (basic upscale)`, null); return { layerId, scale, method: 'basic', reason: String(e && e.message || e) }; } } },
'ai.generateImage': { description: 'Generate an image from a prompt (current canvas as reference) and place it as a NEW layer. {prompt,width,height}.', run: async (p) => { const endpoint = (typeof window !== 'undefined' && window.geGenerateImageEndpoint) || '/api/image/generate'; const reference = flatten().toDataURL('image/png').split(',')[1]; const _pickedModel = (() => { try { const v = localStorage.getItem('ge-ai-command-model') || ''; return v.includes('::') ? v.split('::').pop() : ''; } catch (_) { return ''; } })(); const body = { prompt: (p && p.prompt) || '', width: Math.max(1, Math.round(Number(p && p.width) || state.imgWidth)), height: Math.max(1, Math.round(Number(p && p.height) || state.imgHeight)), reference, ...(_pickedModel ? { model: _pickedModel } : {}) }; let _gres = null; try { _gres = await fetch(endpoint, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); } catch (_e) { throw new Error(_generationErrorMessage({ network: true, detail: (_e && _e.message) || 'network error' })); } const res = _gres; if (!res.ok) { let _gd = res.statusText; try { const e = await res.json(); _gd = e.detail || e.error || _gd; } catch (_) {} throw new Error(_generationErrorMessage({ status: res.status, detail: _gd })); } const data = await res.json(); if (data.error) throw new Error(_generationErrorMessage({ detail: data.error })); const b64 = data.image || (Array.isArray(data.images) && data.images[0]); if (!b64) throw new Error('No image returned'); try { window.__geGenerationDisabled = 0; } catch (_) {} const img = await _decodeAIImage(b64, _aiSignal); const c = document.createElement('canvas'); c.width = state.imgWidth; c.height = state.imgHeight; c.getContext('2d').drawImage(img, 0, 0, state.imgWidth, state.imgHeight); return _placeResultLayer(c, 'Generated', state.wandMask || null); } }, 'ai.generateImage': { description: 'Generate an image with the saved generation model and fit it proportionally as a new layer. {prompt,width,height}.', run: (p) => _generateImage(p || {}) },
'ai.generativeExpand': { description: 'Generatively expand the canvas to width×height; only the new border is inpainted, the original pixels are kept pixel-identical, and the seam is feathered. {width,height,anchor,prompt}.', run: async (p) => { const tw = Math.max(1, Math.round(Number(p && p.width) || state.imgWidth)); const th = Math.max(1, Math.round(Number(p && p.height) || state.imgHeight)); if (tw <= state.imgWidth && th <= state.imgHeight) throw new Error('target must be larger than the current canvas'); const anchor = (p && p.anchor) || 'center'; const anchorX = anchor === 'left' ? 0 : anchor === 'right' ? 1 : 0.5; const anchorY = anchor === 'top' ? 0 : anchor === 'bottom' ? 1 : 0.5; _saveState('Generative expand'); const steps = Math.max(1, Math.round(Number(p && p.steps) || 4)); const sw = state.imgWidth; const sh = state.imgHeight; _resizeCanvasDocument(state, tw, th, { anchorX, anchorY }); const flat = flatten(); const b = _contentBounds(); const mask = document.createElement('canvas'); mask.width = tw; mask.height = th; const mctx = mask.getContext('2d'); mctx.fillStyle = '#ffffff'; mctx.fillRect(0, 0, tw, th); const prefill = document.createElement('canvas'); prefill.width = tw; prefill.height = th; const pctx = prefill.getContext('2d'); pctx.imageSmoothingEnabled = true; pctx.drawImage(flat, 0, 0, tw, th); if (b) { mctx.clearRect(b.x, b.y, b.w, b.h); const bx = b.x, by = b.y, bw = b.w, bh = b.h, rx = bx + bw, by2 = by + bh; if (bx > 0) pctx.drawImage(flat, bx, by, 1, bh, 0, by, bx, bh); if (rx < tw) pctx.drawImage(flat, rx - 1, by, 1, bh, rx, by, tw - rx, bh); if (by > 0) pctx.drawImage(flat, bx, by, bw, 1, bx, 0, bw, by); if (by2 < th) pctx.drawImage(flat, bx, by2 - 1, bw, 1, bx, by2, bw, th - by2); if (bx > 0 && by > 0) pctx.drawImage(flat, bx, by, 1, 1, 0, 0, bx, by); if (rx < tw && by > 0) pctx.drawImage(flat, rx - 1, by, 1, 1, rx, 0, tw - rx, by); if (bx > 0 && by2 < th) pctx.drawImage(flat, bx, by2 - 1, 1, 1, 0, by2, bx, th - by2); if (rx < tw && by2 < th) pctx.drawImage(flat, rx - 1, by2 - 1, 1, 1, rx, by2, tw - rx, th - by2); } else { const tx = Math.round((tw - sw) * anchorX); const ty = Math.round((th - sh) * anchorY); mctx.clearRect(tx, ty, sw, sh); } const image = prefill.toDataURL('image/png').split(',')[1]; const maskB64 = mask.toDataURL('image/png').split(',')[1]; const res = await fetch('/api/image/inpaint', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image, mask: maskB64, prompt: (p && p.prompt) || 'extend the scene seamlessly, continuing the surrounding content and lighting naturally', steps }) }); if (!res.ok) { let err = res.statusText; try { const e = await res.json(); err = e.detail || e.error || err; } catch (_) {} throw new Error(err); } const data = await res.json(); if (data.error) throw new Error(data.error); if (!data.image) throw new Error('No image returned'); const img = await _decodeAIImage(data.image, _aiSignal); const seam = Math.max(12, Math.round(Math.min(tw, th) * 0.02)); let blendMask = _growMaskCanvas(mask, seam, true); blendMask = _featherMaskCanvas((cw, ch) => { const c = document.createElement('canvas'); c.width = cw; c.height = ch; return c; }, blendMask, Math.round(seam * 1.4)); const layer = createLayer('Generative expand', tw, th); layer.ctx.imageSmoothingEnabled = true; layer.ctx.imageSmoothingQuality = 'high'; layer.ctx.drawImage(img, 0, 0, tw, th); if (b) { const edge = _edgeBandAverage(flat, b); if (edge) { layer.ctx.save(); layer.ctx.globalAlpha = 0.14; layer.ctx.fillStyle = `rgb(${edge[0]}, ${edge[1]}, ${edge[2]})`; layer.ctx.fillRect(0, 0, tw, th); layer.ctx.restore(); } } _bakeMaskIntoLayer(layer.ctx, blendMask); state.layers.push(layer); state.activeLayerId = layer.id; state.selectedLayerIds = [layer.id]; composite(); _renderLayerPanel(); return { width: tw, height: th, layerId: layer.id, seam, steps }; } }, 'ai.generativeExpand': { description: 'Generatively expand the canvas to width×height; only the new border is inpainted, the original pixels are kept pixel-identical, and the seam is feathered. {width,height,anchor,prompt}.', run: async (p) => { const tw = Math.max(1, Math.round(Number(p && p.width) || state.imgWidth)); const th = Math.max(1, Math.round(Number(p && p.height) || state.imgHeight)); if (tw <= state.imgWidth && th <= state.imgHeight) throw new Error('target must be larger than the current canvas'); const anchor = (p && p.anchor) || 'center'; const anchorX = anchor === 'left' ? 0 : anchor === 'right' ? 1 : 0.5; const anchorY = anchor === 'top' ? 0 : anchor === 'bottom' ? 1 : 0.5; _saveState('Generative expand'); const steps = Math.max(1, Math.round(Number(p && p.steps) || 4)); const sw = state.imgWidth; const sh = state.imgHeight; _resizeCanvasDocument(state, tw, th, { anchorX, anchorY }); const flat = flatten(); const b = _contentBounds(); const mask = document.createElement('canvas'); mask.width = tw; mask.height = th; const mctx = mask.getContext('2d'); mctx.fillStyle = '#ffffff'; mctx.fillRect(0, 0, tw, th); const prefill = document.createElement('canvas'); prefill.width = tw; prefill.height = th; const pctx = prefill.getContext('2d'); pctx.imageSmoothingEnabled = true; pctx.drawImage(flat, 0, 0, tw, th); if (b) { mctx.clearRect(b.x, b.y, b.w, b.h); const bx = b.x, by = b.y, bw = b.w, bh = b.h, rx = bx + bw, by2 = by + bh; if (bx > 0) pctx.drawImage(flat, bx, by, 1, bh, 0, by, bx, bh); if (rx < tw) pctx.drawImage(flat, rx - 1, by, 1, bh, rx, by, tw - rx, bh); if (by > 0) pctx.drawImage(flat, bx, by, bw, 1, bx, 0, bw, by); if (by2 < th) pctx.drawImage(flat, bx, by2 - 1, bw, 1, bx, by2, bw, th - by2); if (bx > 0 && by > 0) pctx.drawImage(flat, bx, by, 1, 1, 0, 0, bx, by); if (rx < tw && by > 0) pctx.drawImage(flat, rx - 1, by, 1, 1, rx, 0, tw - rx, by); if (bx > 0 && by2 < th) pctx.drawImage(flat, bx, by2 - 1, 1, 1, 0, by2, bx, th - by2); if (rx < tw && by2 < th) pctx.drawImage(flat, rx - 1, by2 - 1, 1, 1, rx, by2, tw - rx, th - by2); } else { const tx = Math.round((tw - sw) * anchorX); const ty = Math.round((th - sh) * anchorY); mctx.clearRect(tx, ty, sw, sh); } const image = prefill.toDataURL('image/png').split(',')[1]; const maskB64 = mask.toDataURL('image/png').split(',')[1]; const res = await fetch('/api/image/inpaint', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image, mask: maskB64, prompt: (p && p.prompt) || 'extend the scene seamlessly, continuing the surrounding content and lighting naturally', steps }) }); if (!res.ok) { let err = res.statusText; try { const e = await res.json(); err = e.detail || e.error || err; } catch (_) {} throw new Error(err); } const data = await res.json(); if (data.error) throw new Error(data.error); if (!data.image) throw new Error('No image returned'); const img = await _decodeAIImage(data.image, _aiSignal); const seam = Math.max(12, Math.round(Math.min(tw, th) * 0.02)); let blendMask = _growMaskCanvas(mask, seam, true); blendMask = _featherMaskCanvas((cw, ch) => { const c = document.createElement('canvas'); c.width = cw; c.height = ch; return c; }, blendMask, Math.round(seam * 1.4)); const layer = createLayer('Generative expand', tw, th); layer.ctx.imageSmoothingEnabled = true; layer.ctx.imageSmoothingQuality = 'high'; layer.ctx.drawImage(img, 0, 0, tw, th); if (b) { const edge = _edgeBandAverage(flat, b); if (edge) { layer.ctx.save(); layer.ctx.globalAlpha = 0.14; layer.ctx.fillStyle = `rgb(${edge[0]}, ${edge[1]}, ${edge[2]})`; layer.ctx.fillRect(0, 0, tw, th); layer.ctx.restore(); } } _bakeMaskIntoLayer(layer.ctx, blendMask); state.layers.push(layer); state.activeLayerId = layer.id; state.selectedLayerIds = [layer.id]; composite(); _renderLayerPanel(); return { width: tw, height: th, layerId: layer.id, seam, steps }; } },
'layers.rename': { description: 'Rename a layer {id|index|name, name|newName}.', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); const next = String(p.name || p.newName || '').trim(); if (!next) throw new Error('name required'); _saveState('Rename layer'); l.name = next; _renderLayerPanel(); return l.id; } }, 'layers.rename': { description: 'Rename a layer {id|index|name, name|newName}.', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); const next = String(p.name || p.newName || '').trim(); if (!next) throw new Error('name required'); _saveState('Rename layer'); l.name = next; _renderLayerPanel(); return l.id; } },
'layers.setVisibility': { description: 'Show/hide a layer {id|index|name, visible}.', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); _saveState('Toggle layer visibility'); l.visible = (p.visible === undefined) ? !l.visible : !!p.visible; composite(); _renderLayerPanel(); return l.visible; } }, 'layers.setVisibility': { description: 'Show/hide a layer {id|index|name, visible}.', run: (p) => { const l = _controlFindLayer(p) || activeLayer(); if (!l) throw new Error('layer not found'); _saveState('Toggle layer visibility'); l.visible = (p.visible === undefined) ? !l.visible : !!p.visible; composite(); _renderLayerPanel(); return l.visible; } },
@@ -12796,6 +12867,10 @@ function _buildEditor(container) {
endpoint: window.geEditorAgentEndpoint || '/api/editor/agent', endpoint: window.geEditorAgentEndpoint || '/api/editor/agent',
getSession: () => agentBridgeSession, getSession: () => agentBridgeSession,
getModel: () => _getSelectedQuickEditModel(), getModel: () => _getSelectedQuickEditModel(),
getGenerationModel: () => {
const value = document.getElementById('ge-ai-model')?.value || '';
return value.includes('::') ? value.slice(value.indexOf('::') + 2) : '';
},
getAgentModel: () => _getSelectedQuickEditAgentModel(), getAgentModel: () => _getSelectedQuickEditAgentModel(),
}); });
} catch (e) { console.error('[ge-editor] agent init failed', e); } } catch (e) { console.error('[ge-editor] agent init failed', e); }
@@ -13895,6 +13970,12 @@ export function openEditor(imageUrl, imageId, presetSize, displayName, draftId)
return; return;
} }
_finishBlank(size.w, size.h); _finishBlank(size.w, size.h);
}).catch(error => {
console.error('[openEditor] New project failed:', error);
closeEditor({ force: true });
window.dispatchEvent(new CustomEvent('gallery-editor-setup-cancelled'));
uiModule.showError(`Could not create project: ${error?.message || 'Canvas initialization failed'}`);
throw error;
}); });
} }
@@ -14049,8 +14130,6 @@ export function closeEditor(options = {}) {
_selectionNudgeTimer = null; _selectionNudgeTimer = null;
_selectionNudgeHistorySaved = false; _selectionNudgeHistorySaved = false;
_precisionGuides = null; _precisionGuides = null;
try { _preflight?.destroy(); } catch {}
_preflight = null;
try { _aiSettings?.destroy(); } catch {} try { _aiSettings?.destroy(); } catch {}
_aiSettings = null; _aiSettings = null;
try { delete window.geEditorAiSettings; } catch (_) { window.geEditorAiSettings = null; } try { delete window.geEditorAiSettings; } catch (_) { window.geEditorAiSettings = null; }
@@ -14061,7 +14140,20 @@ export function closeEditor(options = {}) {
const h = state.editorDocClickHandlers.pop(); const h = state.editorDocClickHandlers.pop();
try { document.removeEventListener('click', h); } catch {} try { document.removeEventListener('click', h); } catch {}
} }
if (state.cursorEl) { state.cursorEl.remove(); state.cursorEl = null; } if (_cursorRaf) { cancelAnimationFrame(_cursorRaf); _cursorRaf = null; }
_pendingCursorEvent = null;
_lastCursorRect = null;
state._lastCursorDiameterX = null;
state._lastCursorDiameterY = null;
state._lastCursorBorderColor = null;
if (state.cursorEl) {
if (state.cursorEl._positionAnimation) {
try { state.cursorEl._positionAnimation.cancel(); } catch {}
state.cursorEl._positionAnimation = null;
}
state.cursorEl.remove();
state.cursorEl = null;
}
try { document.getElementById('ge-cursor-layer')?.remove(); } catch {} try { document.getElementById('ge-cursor-layer')?.remove(); } catch {}
// Tear down all floating popups + the dock so closing the editor // Tear down all floating popups + the dock so closing the editor
// doesn't leave stale chips/panels behind on top of the gallery. // doesn't leave stale chips/panels behind on top of the gallery.
+4 -2
View File
@@ -801,7 +801,8 @@ async function _sendRoundRobin(msg, box) {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: [{ body: JSON.stringify({ messages: [{
role: 'user', role: 'user',
content: `[${m._groupName || m.display}]: ${response}` content: `[${m._groupName || m.display}]: ${response}`,
metadata: { group_peer: true, group_model: m._groupName || m.display, model: m.mid }
}]}), }]}),
}); });
} catch (e) { console.warn('[group] sync failed:', e); } } catch (e) { console.warn('[group] sync failed:', e); }
@@ -828,7 +829,8 @@ async function _syncAllResponses(holders) {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: [{ body: JSON.stringify({ messages: [{
role: 'user', role: 'user',
content: `[${model._groupName || model.display}]: ${response}` content: `[${model._groupName || model.display}]: ${response}`,
metadata: { group_peer: true, group_model: model._groupName || model.display, model: model.mid }
}]}), }]}),
}); });
} catch (e) { /* silent */ } } catch (e) { /* silent */ }
-2
View File
@@ -379,7 +379,6 @@ document.addEventListener('DOMContentLoaded', markComposerUserEdited, { once: tr
root.classList.toggle('keyboard-open', keyboardOpen); root.classList.toggle('keyboard-open', keyboardOpen);
if (keyboardOpen) root.style.setProperty('--keyboard-viewport-height', vv.height + 'px'); if (keyboardOpen) root.style.setProperty('--keyboard-viewport-height', vv.height + 'px');
else root.style.removeProperty('--keyboard-viewport-height'); else root.style.removeProperty('--keyboard-viewport-height');
if (window.scrollY) window.scrollTo(0, 0);
}; };
// iOS fires visualViewport resize only once, mid-animation, and no focusin when // iOS fires visualViewport resize only once, mid-animation, and no focusin when
// the tapped field already had focus (e.g. the composer after a new chat) // the tapped field already had focus (e.g. the composer after a new chat)
@@ -392,7 +391,6 @@ document.addEventListener('DOMContentLoaded', markComposerUserEdited, { once: tr
window.visualViewport.addEventListener('scroll', _syncKeyboardViewport); window.visualViewport.addEventListener('scroll', _syncKeyboardViewport);
document.addEventListener('focusin', _syncThroughKeyboardAnimation); document.addEventListener('focusin', _syncThroughKeyboardAnimation);
document.addEventListener('focusout', _syncThroughKeyboardAnimation); document.addEventListener('focusout', _syncThroughKeyboardAnimation);
window.addEventListener('scroll', () => { if (window.scrollY) window.scrollTo(0, 0); }, { passive: true });
let _lastVVHeight = window.visualViewport.height; let _lastVVHeight = window.visualViewport.height;
window.visualViewport.addEventListener('resize', function() { window.visualViewport.addEventListener('resize', function() {
+5 -3
View File
@@ -163,11 +163,13 @@ function buildCategoryChips() {
const container = document.getElementById('memory-category-filters'); const container = document.getElementById('memory-category-filters');
if (!container) return; if (!container) return;
const cats = new Set(memories.map(m => m.category || 'fact'));
if (activeCategory !== 'all' && !cats.has(activeCategory)) activeCategory = 'all';
// Hide the chip row entirely when there are no memories — no point showing // Hide the chip row entirely when there are no memories — no point showing
// an "all" chip with nothing to filter. // an "all" chip with nothing to filter.
if (!memories.length) { container.innerHTML = ''; return; } if (!memories.length) { container.innerHTML = ''; return; }
const cats = new Set(memories.map(m => m.category || 'fact'));
const sorted = ['all', ...Array.from(cats).sort()]; const sorted = ['all', ...Array.from(cats).sort()];
const counts = memories.reduce((result, memory) => { const counts = memories.reduce((result, memory) => {
const category = memory.category || 'fact'; const category = memory.category || 'fact';
@@ -277,6 +279,7 @@ export function openMemoryModal(tabName = 'browse') {
else if (m.default?.loadSkills) m.default.loadSkills(true); else if (m.default?.loadSkills) m.default.loadSkills(true);
}); });
} }
if (mode === 'memory') return loadMemories();
} }
function _decodeMemoryAnchorId(memoryId) { function _decodeMemoryAnchorId(memoryId) {
@@ -297,9 +300,8 @@ function _resetMemoryDeepLinkFilters() {
// Memory search output may expose a shortened id, so prefix matching is // Memory search output may expose a shortened id, so prefix matching is
// intentional here. // intentional here.
export async function openMemory(memoryId, attempt = 0) { export async function openMemory(memoryId, attempt = 0) {
openMemoryModal('browse');
_resetMemoryDeepLinkFilters(); _resetMemoryDeepLinkFilters();
await loadMemories(); await openMemoryModal('browse');
if (renderMemoryList) renderMemoryList(); if (renderMemoryList) renderMemoryList();
const wanted = _decodeMemoryAnchorId(memoryId); const wanted = _decodeMemoryAnchorId(memoryId);
if (!wanted) return; if (!wanted) return;
+13 -2
View File
@@ -299,7 +299,18 @@ function _renderHistoryMessage(msg, modelName) {
} else { } else {
displayContent = ''; displayContent = '';
} }
if (msg.role === 'user') { let displayRole = msg.role;
// Peer turns remain user-role context for the model, but are agent replies
// in history. Only explicit identity plus its exact prefix can opt in.
if (displayRole === 'user' && meta?.group_peer === true
&& typeof meta.group_model === 'string' && meta.group_model) {
const prefix = `[${meta.group_model}]: `;
if (displayContent.startsWith(prefix)) {
displayRole = 'assistant';
displayContent = displayContent.slice(prefix.length);
}
}
if (displayRole === 'user') {
displayContent = _stripUserVisionBlocks(displayContent); displayContent = _stripUserVisionBlocks(displayContent);
const trimmed = displayContent.trim(); const trimmed = displayContent.trim();
if ( if (
@@ -316,7 +327,7 @@ function _renderHistoryMessage(msg, modelName) {
displayContent = `[Doc edit: ${docEditMatch[1]}] ${docEditMatch[3]}`; displayContent = `[Doc edit: ${docEditMatch[1]}] ${docEditMatch[3]}`;
} }
} }
return _addHistoryMessageWithFullRenderer(msg.role, displayContent, modelName, meta); return _addHistoryMessageWithFullRenderer(displayRole, displayContent, modelName, meta);
} }
function _clearHistoryPager() { function _clearHistoryPager() {
+24 -2
View File
@@ -4,12 +4,14 @@
// them from the same places, so load order and init sequence are untouched. // them from the same places, so load order and init sequence are untouched.
import { byId as el } from './dom.js'; import { byId as el } from './dom.js';
import { postSettings as _postSettings } from './api.js'; import { saveImagePreferences as _postSettings } from './imagePreferences.js';
import { modelCaps } from '../editor/ai-models.js'; import { modelCaps } from '../editor/ai-models.js';
import { sortModelIds } from '../modelSort.js'; import { sortModelIds } from '../modelSort.js';
let preferencesListener = null;
export async function initImageSettings() { export async function initImageSettings() {
const modelSel = el('set-imgModelSelect'); const modelSel = el('set-imgModelSelect');
const editModelSel = el('set-imgEditModelSelect');
const qualSel = el('set-imgQualitySelect'); const qualSel = el('set-imgQualitySelect');
const msg = el('set-imgSettingsMsg'); const msg = el('set-imgSettingsMsg');
const enabledToggle = el('set-imgEnabledToggle'); const enabledToggle = el('set-imgEnabledToggle');
@@ -18,23 +20,36 @@ export async function initImageSettings() {
const endpointsRes = await fetch('/api/model-endpoints', { credentials: 'same-origin' }); const endpointsRes = await fetch('/api/model-endpoints', { credentials: 'same-origin' });
const endpoints = await endpointsRes.json(); const endpoints = await endpointsRes.json();
const imageModels = new Set(); const imageModels = new Set();
const editModels = new Set();
(Array.isArray(endpoints) ? endpoints : []).forEach(endpoint => { (Array.isArray(endpoints) ? endpoints : []).forEach(endpoint => {
if (!endpoint.is_enabled || !endpoint.online) return; if (!endpoint.is_enabled || !endpoint.online) return;
(Array.isArray(endpoint.models) ? endpoint.models : []).forEach(modelId => { (Array.isArray(endpoint.models) ? endpoint.models : []).forEach(modelId => {
if (modelId && modelCaps(modelId, '', endpoint.model_type).gen) imageModels.add(String(modelId)); if (modelId && modelCaps(modelId, '', endpoint.model_type).gen) imageModels.add(String(modelId));
if (modelId && modelCaps(modelId, '', endpoint.model_type).inpaint) editModels.add(String(modelId));
}); });
}); });
modelSel.length = 1;
sortModelIds(Array.from(imageModels)).forEach(mid => { sortModelIds(Array.from(imageModels)).forEach(mid => {
const opt = document.createElement('option'); const opt = document.createElement('option');
opt.value = mid; opt.value = mid;
opt.textContent = mid; opt.textContent = mid;
modelSel.appendChild(opt); modelSel.appendChild(opt);
}); });
if (editModelSel) {
editModelSel.length = 1;
for (const mid of sortModelIds(Array.from(editModels))) {
const option = document.createElement('option');
option.value = mid;
option.textContent = mid;
editModelSel.appendChild(option);
}
}
} catch (e) { console.warn('Failed to load models for image settings', e); } } catch (e) { console.warn('Failed to load models for image settings', e); }
try { try {
const settingsRes = await fetch('/api/auth/settings', { credentials: 'same-origin' }); const settingsRes = await fetch('/api/auth/settings', { credentials: 'same-origin' });
const settings = await settingsRes.json(); const settings = await settingsRes.json();
if (settings.image_model) modelSel.value = settings.image_model; if (settings.image_model) modelSel.value = settings.image_model;
if (editModelSel) editModelSel.value = settings.image_edit_model || '';
if (settings.image_quality) qualSel.value = settings.image_quality; if (settings.image_quality) qualSel.value = settings.image_quality;
if (enabledToggle) enabledToggle.checked = settings.image_gen_enabled === true; if (enabledToggle) enabledToggle.checked = settings.image_gen_enabled === true;
} catch (e) { console.warn('Failed to load settings', e); } } catch (e) { console.warn('Failed to load settings', e); }
@@ -49,12 +64,19 @@ export async function initImageSettings() {
async function saveSettings() { async function saveSettings() {
try { try {
const res = await _postSettings({ image_gen_enabled: enabledToggle ? enabledToggle.checked : false, image_model: modelSel.value, image_quality: qualSel.value }); const res = await _postSettings({ image_gen_enabled: enabledToggle ? enabledToggle.checked : false, image_model: modelSel.value, image_edit_model: editModelSel?.value || '', image_quality: qualSel.value });
if (!res.ok) throw new Error(await res.text().catch(() => `HTTP ${res.status}`)); if (!res.ok) throw new Error(await res.text().catch(() => `HTTP ${res.status}`));
msg.textContent = 'Saved'; msg.style.color = 'var(--fg)'; setTimeout(() => { msg.textContent = ''; }, 2000); msg.textContent = 'Saved'; msg.style.color = 'var(--fg)'; setTimeout(() => { msg.textContent = ''; }, 2000);
} catch (e) { msg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save'; msg.style.color = 'var(--red)'; } } catch (e) { msg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save'; msg.style.color = 'var(--red)'; }
} }
modelSel.addEventListener('change', saveSettings); modelSel.addEventListener('change', saveSettings);
editModelSel?.addEventListener('change', saveSettings);
if (preferencesListener) window.removeEventListener('image-preferences-changed', preferencesListener);
preferencesListener = event => {
if ('image_model' in event.detail) modelSel.value = event.detail.image_model || '';
if (editModelSel && 'image_edit_model' in event.detail) editModelSel.value = event.detail.image_edit_model || '';
};
window.addEventListener('image-preferences-changed', preferencesListener);
qualSel.addEventListener('change', saveSettings); qualSel.addEventListener('change', saveSettings);
if (enabledToggle) enabledToggle.addEventListener('change', function() { syncImgDisabled(); saveSettings(); }); if (enabledToggle) enabledToggle.addEventListener('change', function() { syncImgDisabled(); saveSettings(); });
} }
+47
View File
@@ -0,0 +1,47 @@
import { invalidateSettings } from '../appConfig.js';
export async function readImagePreferences() {
const [prefsRes, settingsRes] = await Promise.all([
fetch('/api/prefs', { credentials: 'same-origin' }).catch(() => null),
fetch('/api/auth/settings', { credentials: 'same-origin' }).catch(() => null),
]);
const prefs = (prefsRes && prefsRes.ok) ? await prefsRes.json().catch(() => ({})) : {};
const settings = (settingsRes && settingsRes.ok) ? await settingsRes.json().catch(() => ({})) : {};
if (!prefsRes?.ok && !settingsRes?.ok) throw new Error('Could not load image settings');
return {
...settings,
image_model: prefs?.image_model || settings?.image_model || '',
image_edit_model: prefs?.image_edit_model || settings?.image_edit_model || '',
};
}
let saveQueue = Promise.resolve();
export function waitForImagePreferences() { return saveQueue; }
export function saveImagePreferences(patch) {
const save = async () => {
let response = await fetch('/api/auth/settings', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch),
});
if (response.status === 403) {
for (const [key, value] of Object.entries(patch)) {
const prefRes = await fetch(`/api/prefs/${encodeURIComponent(key)}`, {
method: 'PUT', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value }),
});
if (!prefRes.ok) {
throw new Error('Could not save image preferences');
}
}
} else if (!response.ok) {
throw new Error('Could not save image settings');
}
invalidateSettings();
window.dispatchEvent(new CustomEvent('image-preferences-changed', { detail: patch }));
return response;
};
const result = saveQueue.then(save);
saveQueue = result.catch(() => {});
return result;
}
+11
View File
@@ -1260,6 +1260,9 @@ async function _expandSkillCard(card, name) {
card._md = md || ''; card._md = md || '';
} else { } else {
pre.textContent = 'Loading…'; pre.textContent = 'Loading…';
const editBtn = [...card.querySelectorAll('.skill-card-preview button')]
.find(button => button.textContent.trim() === 'Edit');
if (editBtn) editBtn.disabled = true;
try { try {
const md = await _fetchSkillMarkdown(name); const md = await _fetchSkillMarkdown(name);
pre.textContent = md || '(empty)'; pre.textContent = md || '(empty)';
@@ -1267,6 +1270,8 @@ async function _expandSkillCard(card, name) {
card._md = md; card._md = md;
} catch (e) { } catch (e) {
pre.textContent = `Failed to load SKILL.md: ${e.message || 'Unknown error'}`; pre.textContent = `Failed to load SKILL.md: ${e.message || 'Unknown error'}`;
} finally {
if (editBtn) editBtn.disabled = !card._mdLoaded;
} }
} }
} }
@@ -1275,6 +1280,9 @@ async function _expandSkillCard(card, name) {
// Swap the read-only <pre> for an editable <textarea> (and back). The // Swap the read-only <pre> for an editable <textarea> (and back). The
// Edit button toggles; a Save button commits via the markdown endpoint. // Edit button toggles; a Save button commits via the markdown endpoint.
function _toggleSkillEdit(card, name) { function _toggleSkillEdit(card, name) {
// A loading/error preview is not source text. Menu entry points must obey
// the same readiness gate as the disabled footer control.
if (!card._mdLoaded) return;
const preview = card.querySelector('.skill-card-preview'); const preview = card.querySelector('.skill-card-preview');
if (!preview) return; if (!preview) return;
const existing = preview.querySelector('.skill-md-editor'); const existing = preview.querySelector('.skill-md-editor');
@@ -1288,6 +1296,9 @@ function _toggleSkillEdit(card, name) {
ta.className = 'skill-md-editor'; ta.className = 'skill-md-editor';
ta.spellcheck = false; ta.spellcheck = false;
ta.value = (card._md != null ? card._md : (pre ? pre.textContent : '')) || ''; ta.value = (card._md != null ? card._md : (pre ? pre.textContent : '')) || '';
// Let the source set the intrinsic height; the card's existing flex/max
// height keeps long files bounded and the Save footer reachable.
ta.rows = Math.max(ta.rows, ta.value.split(/\r\n|\r|\n/).length);
ta.addEventListener('click', (e) => e.stopPropagation()); ta.addEventListener('click', (e) => e.stopPropagation());
if (pre) pre.style.display = 'none'; if (pre) pre.style.display = 'none';
preview.insertBefore(ta, preview.querySelector('.doclib-card-expanded-actions')); preview.insertBefore(ta, preview.querySelector('.doclib-card-expanded-actions'));
+3 -2
View File
@@ -267,8 +267,9 @@ export function makeWindowResizable(content, options = {}) {
content.style.maxWidth = 'none'; content.style.maxWidth = 'none';
content.style.maxHeight = 'none'; content.style.maxHeight = 'none';
const left = parseFloat(content.style.left); const left = parseFloat(content.style.left);
if (Number.isFinite(left) && left + w > window.innerWidth - padRight) { if (Number.isFinite(left)) {
content.style.left = Math.max(padLeft, window.innerWidth - padRight - w) + 'px'; const rightmostLeft = Math.max(padLeft, window.innerWidth - padRight - w);
content.style.left = Math.max(padLeft, Math.min(left, rightmostLeft)) + 'px';
} }
} }
} catch (_) {} } catch (_) {}
+6 -1
View File
@@ -7,7 +7,7 @@
// - Other static assets (images/fonts/libs): cache-first with bg refresh. // - Other static assets (images/fonts/libs): cache-first with bg refresh.
// - API / non-GET: never cached. // - API / non-GET: never cached.
// Bump CACHE_NAME whenever the precache list or SW logic changes. // Bump CACHE_NAME whenever the precache list or SW logic changes.
const CACHE_NAME = 'odysseus-v1114-pr40-editor-precache'; const CACHE_NAME = 'odysseus-v1134-pr40-editor-precache';
// KaTeX resolves these from its own stylesheet, so caching the CSS without them // KaTeX resolves these from its own stylesheet, so caching the CSS without them
// gives offline math fallback glyphs instead of proper typesetting. // gives offline math fallback glyphs instead of proper typesetting.
@@ -38,6 +38,7 @@ const KATEX_FONTS = [
// Both are fetched at install time, in the background. Entries must match the // Both are fetched at install time, in the background. Entries must match the
// exact URL the browser requests, query string included. // exact URL the browser requests, query string included.
const PRECACHE = [ const PRECACHE = [
'/static/js/compare/sse.js',
'/', '/',
'/static/css/00-tokens.css?v=20260929csssplit', '/static/css/00-tokens.css?v=20260929csssplit',
'/static/css/01-agent-chat.css?v=20260929csssplit', '/static/css/01-agent-chat.css?v=20260929csssplit',
@@ -236,6 +237,10 @@ const PANEL_PRECACHE = [
'/static/js/editor/aspect-fit.js', '/static/js/editor/aspect-fit.js',
'/static/js/editor/preflight.js', '/static/js/editor/preflight.js',
'/static/js/editor/ai-settings.js', '/static/js/editor/ai-settings.js',
'/static/js/editor/image-generation.js',
'/static/js/editor/image-result-geometry.js',
'/static/js/editor/quick-edit-job.js',
'/static/js/settings/imagePreferences.js',
'/static/js/editor/look-recipes.js', '/static/js/editor/look-recipes.js',
'/static/js/editor/editor-control.js', '/static/js/editor/editor-control.js',
'/static/js/editor/editor-bridge.js', '/static/js/editor/editor-bridge.js',
+4 -2
View File
@@ -99,8 +99,10 @@ cleanup. Specifically:
`os.environ[...] = ...` that outlives the test. `os.environ[...] = ...` that outlives the test.
- **Current working directory** - never `chdir` without restoring; never assert - **Current working directory** - never `chdir` without restoring; never assert
against cwd-relative paths like `./data`. Use a temp workspace helper instead. against cwd-relative paths like `./data`. Use a temp workspace helper instead.
- **Database** - the root `conftest.py` defaults `DATABASE_URL` to an in-memory - **Database** - the root `conftest.py` defaults `DATABASE_URL` to a private,
SQLite for collection safety. A test that needs a real file-backed DB must opt worker-owned SQLite file for collection safety and consistent schema across
TestClient threads. This fallback is not a per-test data fixture. A test that
writes or depends on particular rows must opt
in explicitly via `tests.helpers.sqlite_db.make_temp_sqlite` and bind its in explicitly via `tests.helpers.sqlite_db.make_temp_sqlite` and bind its
`SessionLocal` onto the module under test. Do not rely on a persistent `SessionLocal` onto the module under test. Do not rely on a persistent
on-disk DB existing. on-disk DB existing.
+67
View File
@@ -0,0 +1,67 @@
"""Gallery CLI tag filters match both sources and stack like the web library."""
from datetime import datetime, timedelta
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from core.database import Base, GalleryAlbum, GalleryImage
from tests.helpers.cli_loader import load_script
@pytest.fixture
def gallery_cli(monkeypatch, tmp_path):
engine = create_engine(f"sqlite:///{tmp_path / 'gallery.db'}")
Base.metadata.create_all(engine)
sessions = sessionmaker(bind=engine)
with sessions() as db:
db.add(GalleryAlbum(id='sea', name='Sea'))
for index, (uid, tags, ai_tags, favorite, album) in enumerate([
('manual', 'sunset,beach', '', True, 'sea'),
('ai', '', 'Beach,sunset', False, 'sea'),
('split', 'sunset', 'beach', True, None),
('one', 'sunset', '', False, None),
('other', 'forest', 'moss', False, None),
('inactive', 'sunset,beach', 'sunset,beach', True, 'sea'),
]):
db.add(GalleryImage(id=uid, filename=uid+'.png', tags=tags, ai_tags=ai_tags,
favorite=favorite, album_id=album, is_active=uid!='inactive',
created_at=datetime(2026, 1, 1) + timedelta(minutes=index)))
db.commit()
cli = load_script('odysseus-gallery')
monkeypatch.setattr(cli, 'SessionLocal', sessions)
output = []
monkeypatch.setattr(cli, 'emit', lambda rows, args: output.extend(rows))
def run(*argv):
output.clear()
args = cli._build_parser().parse_args(['list', *argv])
args.func(args)
return [row['id'] for row in output]
yield run
engine.dispose()
@pytest.mark.parametrize('tag,expected', [
('sunset', ['one', 'split', 'ai', 'manual']),
('beach,sunset', ['split', 'ai', 'manual']),
('sunset,beach', ['split', 'ai', 'manual']),
(', sunset, , BEACH ,', ['split', 'ai', 'manual']),
('forest', ['other']),
('no-match', []),
(' , ', ['other', 'one', 'split', 'ai', 'manual']),
('sun', ['one', 'split', 'ai', 'manual']),
])
def test_tag_sources_and_stacking(gallery_cli, tag, expected):
assert gallery_cli('--tag', tag) == expected
@pytest.mark.parametrize('options,expected', [
([], ['other', 'one', 'split', 'ai', 'manual']),
(['--tag', 'beach,sunset', '--favorites'], ['split', 'manual']),
(['--tag', 'beach,sunset', '--album', 'Sea'], ['ai', 'manual']),
(['--tag', 'beach', '--limit', '1'], ['split']),
])
def test_tag_filters_preserve_other_list_options(gallery_cli, options, expected):
assert gallery_cli(*options) == expected
+66
View File
@@ -0,0 +1,66 @@
"""The bounded arrival batch is displayed by Date, rather than arrival ID."""
from contextlib import contextmanager
from types import SimpleNamespace
import pytest
from tests.cli.test_mail_cli_read_empty_fetch import _load_mail_cli
@pytest.mark.parametrize('dates,expected', [
(['Wed, 03 Jun 2026 12:00:00 +0000', 'Mon, 01 Jun 2026 09:00:00 +0000'], ['1', '2']),
(['Wed, 03 Jun 2026 12:00:00 +0000', 'Wed, 03 Jun 2026 13:00:00 +0200'], ['1', '2']),
(['Wed, 03 Jun 2026 12:00:00', 'Wed, 03 Jun 2026 11:00:00 +0000'], ['1', '2']),
(['Wed, 03 Jun 2026 12:00:00 +0000', None, 'not a date'], ['1', '3', '2']),
(['Wed, 03 Jun 2026 12:00:00 +0000', 'Wed, 03 Jun 2026 14:00:00 +0200'], ['2', '1']),
(['Wed, 03 Jun 2026 12:00:00 +0000', 'Thu, 04 Jun 2026 12:00:00 +0000'], ['2', '1']),
(['Wed, 31 Dec 1969 12:00:00 +0000', None], ['1', '2']),
])
def test_list_sorts_parsed_dates_without_changing_row_schema(monkeypatch, dates, expected):
cli = _load_mail_cli(monkeypatch)
fetched = []
class Connection:
def select(self, folder, readonly=True):
assert readonly is True
return 'OK', [str(len(dates)).encode()]
def search(self, *_):
return 'OK', [' '.join(str(i+1) for i in range(len(dates))).encode()]
def fetch(self, uid, _):
fetched.append(uid.decode())
date = dates[int(uid)-1]
raw = 'From: Sender <sender@example.com>\r\nSubject: Item '+uid.decode()+'\r\n'
if date is not None:
raw += 'Date: '+date+'\r\n'
return 'OK', [(b'1 (FLAGS (\\Seen) RFC822.HEADER)', (raw+'\r\n').encode())]
@contextmanager
def imap(_):
yield Connection()
rows = []
monkeypatch.setattr(cli, '_imap', imap)
monkeypatch.setattr(cli, 'emit', lambda value, args: rows.extend(value))
cli.cmd_list(SimpleNamespace(account='fixture', folder='INBOX', limit=20))
assert [row['uid'] for row in rows] == expected
assert fetched == [str(i) for i in range(len(dates), 0, -1)]
assert all(set(row) == {'uid', 'date', 'from_addr', 'from_name', 'subject', 'is_read', 'is_answered'} for row in rows)
assert all(row['is_read'] and not row['is_answered'] for row in rows)
def test_list_still_limits_the_arrival_batch(monkeypatch):
cli = _load_mail_cli(monkeypatch)
fetched = []
class Connection:
def select(self, *_args, **_kwargs):return 'OK', []
def search(self, *_):return 'OK', [b'1 2 3']
def fetch(self, uid, _):
fetched.append(uid)
return 'OK', [(b'3 (FLAGS () RFC822.HEADER)', b'From: x@example.com\r\nSubject: bounded\r\n\r\n')]
@contextmanager
def imap(_):yield Connection()
monkeypatch.setattr(cli, '_imap', imap)
monkeypatch.setattr(cli, 'emit', lambda *_:None)
cli.cmd_list(SimpleNamespace(account='fixture', folder='INBOX', limit=1))
assert fetched == [b'3']
+14 -1
View File
@@ -12,9 +12,17 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# File-backed databases remain fixture-owned. Cleanup restores the caller. # File-backed databases remain fixture-owned. Cleanup restores the caller.
# Keep the existing generated environment-reference locations stable. # Keep the existing generated environment-reference locations stable.
_database_environment = pytest.MonkeyPatch() _database_environment = pytest.MonkeyPatch()
_database_environment.setenv("DATABASE_URL", "sqlite:///:memory:")
from tests.helpers.worker_runtime import bootstrap_runtime, configure_runtime from tests.helpers.worker_runtime import bootstrap_runtime, configure_runtime
_runtime_environment = bootstrap_runtime() _runtime_environment = bootstrap_runtime()
# A file keeps the collection schema consistent across TestClient threads;
# SingletonThreadPool can evict the populated in-memory main-thread database.
# One patcher owns this variable, including restoration of an inherited URL.
_database_environment.setenv(
"DATABASE_URL",
f"sqlite:///{_runtime_environment.root / 'collection.db'}"
if _runtime_environment is not None else "sqlite:///:memory:",
)
_collection_database_engine = None
# Pre-import real heavy modules BEFORE any test file's module-level stubs can # Pre-import real heavy modules BEFORE any test file's module-level stubs can
# replace them with MagicMock. Some test files (e.g. test_llm_core_sanitize_*) # replace them with MagicMock. Some test files (e.g. test_llm_core_sanitize_*)
@@ -26,6 +34,7 @@ try:
import sqlalchemy.orm # noqa: F401 import sqlalchemy.orm # noqa: F401
import core.database # noqa: F401 import core.database # noqa: F401
import src.database import src.database
_collection_database_engine = core.database.engine
except ImportError: except ImportError:
pass # not installed - the stubs below will handle it pass # not installed - the stubs below will handle it
@@ -100,6 +109,10 @@ def pytest_configure(config):
only registers marker names; it imports no production module. only registers marker names; it imports no production module.
""" """
config.add_cleanup(_database_environment.undo) config.add_cleanup(_database_environment.undo)
if _collection_database_engine is not None:
# Registered after runtime cleanup, so connections close before the
# owned file is removed (also required on Windows).
config.add_cleanup(_collection_database_engine.dispose)
import pathlib import pathlib
from tests._taxonomy import discover_markers from tests._taxonomy import discover_markers
+52
View File
@@ -1,5 +1,7 @@
# Browser End-to-End Tests # Browser End-to-End Tests
## Photo Editor Release Gate
The photo editor release gate launches an isolated Odysseus server on port The photo editor release gate launches an isolated Odysseus server on port
`7013` with a temporary SQLite database and disposable authenticated account. `7013` with a temporary SQLite database and disposable authenticated account.
@@ -18,3 +20,53 @@ The disposable account is created in the temporary data directory and exercises
owner-scoped draft and notification routes without using an existing account. owner-scoped draft and notification routes without using an existing account.
`PHOTO_EDITOR_E2E_AUTH=0` selects the legacy unauthenticated configuration for `PHOTO_EDITOR_E2E_AUTH=0` selects the legacy unauthenticated configuration for
investigating it; offline-upgrade coverage requires the authenticated mode. investigating it; offline-upgrade coverage requires the authenticated mode.
## Mobile and iOS Layout Suite
The dedicated mobile and iOS layout suite exercises viewport behavior,
accessibility zoom, scrolling, mobile safe-area geometry (Notes and Documents
panes), and floating window restoration against an isolated local Odysseus server
running on port `17739`.
```bash
npm install
npm run test:ios-layout:chromium
```
### Profiles and Browser Prerequisites
- **Chromium profiles** (`desktop-chromium`, `phone-chromium-portrait`, `phone-chromium-landscape`, `tablet-chromium`):
Provide automated baseline coverage in CI and local development without requiring
WebKit dependencies.
- **WebKit profiles** (`phone-webkit-portrait`, `phone-webkit-landscape`, `tablet-webkit`):
Used for platform-oriented WebKit rendering validation. WebKit requires browser binaries:
```bash
npm run test:ios-layout:install
# or: npx playwright install webkit
npm run test:ios-layout:webkit
```
To run all installed profiles:
```bash
npm run test:ios-layout
```
### Evidence and Cleanup
- **Evidence artifacts**: Screenshots are written to `test-results/ios-layout/` by
default and traces are written to `test-results/ios-layout-traces/`. Both paths
are git-ignored. Set `ODYSSEUS_LAYOUT_EVIDENCE_DIR` to override the screenshot
output path.
- **Teardown**: Disposable application state and database files created in the
OS temporary directory are automatically cleaned up on both normal and failure
teardown, preserving diagnostic screenshots and failure traces.
### Platform Considerations
Emulated Chromium and WebKit viewports validate deterministic CSS cascade,
computed layout geometry, viewport meta tags, and JavaScript restoration. However,
browser emulation is not a physical device substitute: physical iOS Safari and
standalone installed PWAs should still be verified separately for native gesture
pinch-zoom, software keyboard dismissal transitions, and dynamic hardware notch/island insets.
+28
View File
@@ -0,0 +1,28 @@
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
/**
* Global teardown for the iOS/mobile layout Playwright test suite.
* Cleans up only disposable temporary application data directories,
* preserving diagnostic artifacts (screenshots and failure traces) in test-results/.
*/
module.exports = async () => {
const dataDirectory = process.env.ODYSSEUS_LAYOUT_DATA_DIR;
if (!dataDirectory || typeof dataDirectory !== 'string') return;
try {
const resolvedData = path.resolve(dataDirectory);
const allowedTmpBases = [os.tmpdir(), '/var/tmp', '/tmp'].map(b => path.resolve(b));
const isTmp = allowedTmpBases.some(base => resolvedData.startsWith(base + path.sep));
const baseName = path.basename(resolvedData);
if (isTmp && (baseName.startsWith('odysseus-ios-layout-') || baseName.startsWith('odysseus-pr6396-'))) {
if (fs.existsSync(resolvedData)) {
fs.rmSync(resolvedData, { recursive: true, force: true });
}
}
} catch (err) {
console.warn(`[ios-layout-teardown] Warning: failed to clean temporary runtime dir: ${err.message}`);
}
};
+148
View File
@@ -0,0 +1,148 @@
// Tests against the running Odysseus app, not a static mock page.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { defineConfig } = require('@playwright/test');
const repositoryRoot = path.resolve(__dirname, '../..');
const port = Number(process.env.ODYSSEUS_LAYOUT_PORT || '17739');
const baseURL = `http://127.0.0.1:${port}`;
const defaultPython = process.platform === 'win32'
? path.join(repositoryRoot, '.venv', 'Scripts', 'python.exe')
: path.join(repositoryRoot, '.venv', 'bin', 'python');
const python = process.env.ODYSSEUS_TEST_PYTHON
|| (fs.existsSync(defaultPython) ? defaultPython : 'python3');
const dataDirectory = process.env.ODYSSEUS_LAYOUT_DATA_DIR
|| fs.mkdtempSync(path.join(os.tmpdir(), 'odysseus-ios-layout-'));
process.env.ODYSSEUS_LAYOUT_DATA_DIR = dataDirectory;
// Default evidence directory to repository-relative test-results/ios-layout
// while preserving the environment-variable override if provided.
const evidenceDir = process.env.ODYSSEUS_LAYOUT_EVIDENCE_DIR
|| path.join(repositoryRoot, 'test-results', 'ios-layout');
const outputDir = path.join(repositoryRoot, 'test-results', 'ios-layout-traces');
// Emergency process-exit cleanup for disposable application runtime state
const cleanDataDirSync = () => {
const dir = process.env.ODYSSEUS_LAYOUT_DATA_DIR;
if (!dir || typeof dir !== 'string') return;
try {
const resolved = path.resolve(dir);
const allowed = [os.tmpdir(), '/var/tmp', '/tmp'].map(b => path.resolve(b));
if (allowed.some(base => resolved.startsWith(base + path.sep))) {
const baseName = path.basename(resolved);
if (baseName.startsWith('odysseus-ios-layout-') || baseName.startsWith('odysseus-pr6396-')) {
if (fs.existsSync(resolved)) {
fs.rmSync(resolved, { recursive: true, force: true });
}
}
}
} catch (_) {}
};
process.once('SIGINT', () => { cleanDataDirSync(); process.exit(130); });
process.once('SIGTERM', () => { cleanDataDirSync(); process.exit(143); });
function isWebKitInstalled() {
try {
const { webkit } = require('@playwright/test');
return fs.existsSync(webkit.executablePath());
} catch (_) {
return false;
}
}
const chromiumProjects = [
{
name: 'desktop-chromium',
use: { browserName: 'chromium', viewport: { width: 1440, height: 900 } },
},
{
name: 'phone-chromium-portrait',
use: { browserName: 'chromium', viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true },
},
{
name: 'phone-chromium-landscape',
use: { browserName: 'chromium', viewport: { width: 844, height: 390 }, hasTouch: true, isMobile: true },
},
{
name: 'tablet-chromium',
use: { browserName: 'chromium', viewport: { width: 820, height: 1000 }, hasTouch: true, isMobile: true },
},
];
const webkitProjects = [
{
name: 'phone-webkit-portrait',
use: { browserName: 'webkit', viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true },
},
{
name: 'phone-webkit-landscape',
use: { browserName: 'webkit', viewport: { width: 844, height: 390 }, hasTouch: true, isMobile: true },
},
{
name: 'tablet-webkit',
use: { browserName: 'webkit', viewport: { width: 820, height: 1000 }, hasTouch: true, isMobile: true },
},
];
// Determine active projects based on environment and local browser availability
const requestedBrowser = (process.env.ODYSSEUS_LAYOUT_BROWSER || 'all').toLowerCase();
let selectedProjects = [];
if (requestedBrowser === 'chromium') {
selectedProjects = chromiumProjects;
} else if (requestedBrowser === 'webkit') {
selectedProjects = webkitProjects;
} else {
// 'all': Include chromium always; include webkit if installed or if explicitly targeted via cli args
const hasCliWebKitTarget = process.argv.some(arg => arg.toLowerCase().includes('webkit'));
if (isWebKitInstalled() || hasCliWebKitTarget) {
selectedProjects = [...chromiumProjects, ...webkitProjects];
} else {
// Only Chromium is available locally (e.g. standard CI / default runner)
selectedProjects = chromiumProjects;
}
}
module.exports = defineConfig({
testDir: path.join(__dirname, 'ios-layout'),
testMatch: ['**/*.spec.cjs'],
outputDir,
timeout: 90_000,
expect: { timeout: 15_000 },
retries: 0,
workers: 1,
reporter: [['line']],
globalTeardown: require.resolve('./ios-layout-teardown.cjs'),
use: {
baseURL,
headless: true,
serviceWorkers: 'block',
screenshot: 'only-on-failure',
trace: 'retain-on-failure',
},
projects: selectedProjects,
metadata: { evidenceDir },
webServer: {
command: `${JSON.stringify(python)} -m uvicorn app:app --host 127.0.0.1 --port ${port}`,
cwd: repositoryRoot,
url: baseURL,
timeout: 120_000,
reuseExistingServer: false,
env: {
...process.env,
AUTH_ENABLED: 'false',
// Never connect the disposable app to the host's real ChromaDB.
CHROMADB_HOST: '127.0.0.1',
CHROMADB_PORT: String(port + 1),
LLM_HOST: '127.0.0.1',
EMBEDDING_URL: `http://127.0.0.1:${port + 1}/v1/embeddings`,
DATABASE_URL: `sqlite:///${path.join(dataDirectory, 'app.db')}`,
ODYSSEUS_DATA_DIR: dataDirectory,
ODYSSEUS_STARTUP_WARMUPS: '0',
RESPONSE_COMPRESSION_ENABLED: 'false',
},
},
});
@@ -0,0 +1,313 @@
const { test, expect } = require('@playwright/test');
const fs = require('node:fs');
const path = require('node:path');
async function openApp(page) {
const response = await page.goto('/', { waitUntil: 'domcontentloaded' });
expect(response?.ok()).toBeTruthy();
// The runtime currently produces two #message nodes. Select the
// initialized composer while diagnosing whether both are visible.
const composers = await page.locator('textarea#message').evaluateAll(nodes =>
nodes.map((el, index) => ({
index,
initialized: el.dataset.startupPreserveBound === '1',
visible: !!el.getClientRects().length &&
getComputedStyle(el).visibility !== 'hidden',
parent: el.parentElement?.className || '',
}))
);
if (composers.length !== 1) {
console.log('Composer DOM diagnostic:', JSON.stringify(composers));
}
const activeComposer = page.locator(
'textarea#message[data-startup-preserve-bound="1"]'
);
await expect(activeComposer).toHaveCount(1);
await expect(activeComposer).toBeVisible();
expect(
composers.filter(composer => composer.visible).length,
'Exactly one composer should be visible'
).toBe(1);
}
function isMobileViewport(testInfo) {
const width = testInfo.project.use?.viewport?.width || 0;
return width > 0 && width <= 768;
}
/**
* Reach Settings through genuine UI controls on either desktop or mobile viewports.
* On mobile (<=768px), the rail is hidden and the sidebar must be opened via hamburger.
*/
async function openSettings(page, isMobile) {
let settingsButton;
if (isMobile) {
const hamburger = page.locator('#hamburger-btn:visible').first();
await expect(hamburger, 'Hamburger button must be visible on mobile').toBeVisible({ timeout: 5000 });
await hamburger.click();
const sidebar = page.locator('#sidebar:not(.hidden)');
await expect(sidebar, 'Sidebar must open upon hamburger tap').toBeVisible({ timeout: 5000 });
await page.waitForTimeout(300);
settingsButton = sidebar.locator('#user-bar-settings');
} else {
settingsButton = page.locator('#rail-settings:visible, #user-bar-settings:visible').first();
}
await expect(settingsButton, 'Settings button must be reachable and visible').toBeVisible({ timeout: 5000 });
await settingsButton.click();
const dialog = page.locator('#settings-modal');
await expect(dialog, 'Settings modal must become visible').toBeVisible({ timeout: 5000 });
return dialog;
}
/**
* Reach Notes through genuine UI controls on either desktop or mobile viewports.
*/
async function openNotes(page, isMobile) {
let notesButton;
if (isMobile) {
const hamburger = page.locator('#hamburger-btn:visible').first();
await expect(hamburger, 'Hamburger button must be visible on mobile').toBeVisible({ timeout: 5000 });
await hamburger.click();
const sidebar = page.locator('#sidebar:not(.hidden)');
await expect(sidebar, 'Sidebar must open upon hamburger tap').toBeVisible({ timeout: 5000 });
await page.waitForTimeout(300);
notesButton = sidebar.locator('#tool-notes-btn');
} else {
notesButton = page.locator('#rail-notes:visible, #tool-notes-btn:visible').first();
}
await expect(notesButton, 'Notes button must be reachable and visible').toBeVisible({ timeout: 5000 });
await notesButton.click();
const realNotes = page.locator('.notes-pane').first();
await expect(realNotes, 'Notes pane must become visible').toBeVisible({ timeout: 5000 });
return realNotes;
}
/**
* Reach Document editor through genuine UI controls on either desktop or mobile viewports.
*/
async function openDocument(page, isMobile) {
let docButton;
if (isMobile) {
const hamburger = page.locator('#hamburger-btn:visible').first();
await expect(hamburger, 'Hamburger button must be visible on mobile').toBeVisible({ timeout: 5000 });
await hamburger.click();
const sidebar = page.locator('#sidebar:not(.hidden)');
await expect(sidebar, 'Sidebar must open upon hamburger tap').toBeVisible({ timeout: 5000 });
await page.waitForTimeout(300);
docButton = sidebar.locator('#library-new-doc-btn');
} else {
docButton = page.locator('#library-new-doc-btn:visible').first();
if (!(await docButton.count())) {
const hamburger = page.locator('#hamburger-btn:visible').first();
if (await hamburger.count()) {
await hamburger.click();
await page.waitForTimeout(300);
docButton = page.locator('#sidebar:not(.hidden) #library-new-doc-btn');
}
}
}
await expect(docButton, 'Document creation button must be reachable and visible').toBeVisible({ timeout: 5000 });
await docButton.click();
const docPane = page.locator('.doc-editor-pane').first();
await expect(docPane, 'Document editor pane must become visible').toBeVisible({ timeout: 10000 });
return docPane;
}
test('renders actual Odysseus UI and captures review screenshots', async ({ page }, testInfo) => {
await openApp(page);
const out = testInfo.config.metadata.evidenceDir;
fs.mkdirSync(out, { recursive: true });
const name = testInfo.project.name;
const isMobile = isMobileViewport(testInfo);
// 1. Chat screenshot (default view)
await page.screenshot({ path: path.join(out, `${name}-chat.png`), fullPage: false, animations: 'disabled' });
// 2. Settings screenshot via actual user-visible navigation
await openApp(page);
await openSettings(page, isMobile);
await page.screenshot({ path: path.join(out, `${name}-settings.png`), fullPage: false, animations: 'disabled' });
// 3. Notes screenshot via actual user-visible navigation
await openApp(page);
await openNotes(page, isMobile);
await page.screenshot({ path: path.join(out, `${name}-notes.png`), fullPage: false, animations: 'disabled' });
testInfo.annotations.push({ type: 'evidence', description: out });
});
test('viewport meta does not restrict user zoom', async ({ page }) => {
await openApp(page);
const meta = await page.locator('meta[name="viewport"]').getAttribute('content');
expect(meta || '').not.toMatch(/maximum-scale\s*=\s*1(?:\b|\.)/i);
expect(meta || '').not.toMatch(/user-scalable\s*=\s*no/i);
});
test('browser-owned window scrolling is not globally reset', async ({ page }) => {
await openApp(page);
const value = await page.evaluate(async () => {
document.documentElement.style.overflowY = 'auto';
document.body.style.overflowY = 'auto';
document.body.style.height = 'auto';
document.body.style.minHeight = '3200px';
const spacer = document.createElement('div');
spacer.style.cssText = 'position:absolute;top:3100px;width:1px;height:10px;pointer-events:none;';
document.body.appendChild(spacer);
window.scrollTo(0, 250);
await new Promise(resolve => setTimeout(resolve, 150));
return window.scrollY;
});
expect(value).toBeGreaterThan(100);
});
test('CSS cascade rules for mobile Notes and Documents respect safe areas', async ({ page }, testInfo) => {
test.skip(!isMobileViewport(testInfo), 'Only mobile viewports <=768px');
await openApp(page);
const results = await page.evaluate(() => {
document.documentElement.style.setProperty('--safe-top', '44px');
document.documentElement.style.setProperty('--sheet-top', '68px');
document.documentElement.style.setProperty('--app-height', '844px');
const values = {};
for (const [key, bodyClass, paneClass] of [
['notes', 'notes-view', 'notes-pane'],
['document', 'doc-view', 'doc-editor-pane'],
]) {
const pane = document.createElement('section');
pane.className = paneClass;
pane.style.opacity = '0'; // CSS cascade regression check
document.body.appendChild(pane);
document.body.classList.add(bodyClass);
const style = window.getComputedStyle(pane);
values[key] = {
top: style.top,
height: style.height,
insetTop: pane.getBoundingClientRect().top,
};
pane.remove();
document.body.classList.remove(bodyClass);
}
return values;
});
for (const key of ['notes', 'document']) {
expect(results[key].top, key).toBe('68px');
expect(parseFloat(results[key].height), key).toBeGreaterThanOrEqual(770);
}
});
test('real Notes and Document panes honor safe-area geometry in the live application', async ({ page }, testInfo) => {
const isMobile = isMobileViewport(testInfo);
test.skip(!isMobile, 'Only mobile viewports <=768px');
await openApp(page);
// Configure simulated safe-area insets (e.g. iPhone notch / Dynamic Island)
await page.evaluate(() => {
document.documentElement.style.setProperty('--safe-top', '44px');
document.documentElement.style.setProperty('--sheet-top', '68px');
document.documentElement.style.setProperty('--app-height', '844px');
});
// 1. Verify actual Notes UI
const realNotes = await openNotes(page, isMobile);
const notesMetrics = await realNotes.evaluate(el => {
const style = window.getComputedStyle(el);
const rect = el.getBoundingClientRect();
return {
top: style.top,
height: style.height,
maxHeight: style.maxHeight,
rectTop: rect.top,
rectHeight: rect.height,
};
});
expect(notesMetrics.top, 'Real Notes pane top must match --sheet-top').toBe('68px');
expect(parseFloat(notesMetrics.height), 'Real Notes pane height must respect safe area').toBeGreaterThanOrEqual(770);
expect(notesMetrics.rectTop, 'Real Notes pane must not overlap the 44px safe-area top notch').toBeGreaterThanOrEqual(44);
// 2. Verify actual Document UI
await openApp(page);
await page.evaluate(() => {
document.documentElement.style.setProperty('--safe-top', '44px');
document.documentElement.style.setProperty('--sheet-top', '68px');
document.documentElement.style.setProperty('--app-height', '844px');
});
const realDoc = await openDocument(page, isMobile);
const docMetrics = await realDoc.evaluate(el => {
const style = window.getComputedStyle(el);
const rect = el.getBoundingClientRect();
return {
top: style.top,
height: style.height,
maxHeight: style.maxHeight,
rectTop: rect.top,
rectHeight: rect.height,
};
});
expect(docMetrics.top, 'Real Document pane top must match --sheet-top').toBe('68px');
expect(parseFloat(docMetrics.height), 'Real Document pane height must respect safe area').toBeGreaterThanOrEqual(770);
expect(docMetrics.rectTop, 'Real Document pane must not overlap the 44px safe-area top notch').toBeGreaterThanOrEqual(44);
});
test('restored floating windows clamp away from a left safe area', async ({ page }, testInfo) => {
test.skip(isMobileViewport(testInfo), 'Geometry test uses desktop resizable windows');
await openApp(page);
const value = await page.evaluate(async () => {
document.documentElement.style.setProperty('--safe-left', '58px');
document.body.style.setProperty('padding-left', '58px', 'important');
const probe = document.createElement('div');
probe.style.cssText = 'position:fixed;left:10px;top:80px;width:420px;height:250px;z-index:999999;';
document.body.appendChild(probe);
const key = 'odysseus-layout-restore-test';
localStorage.setItem(key, JSON.stringify({ w: 480, h: 280 }));
try {
// Body horizontal padding transitions over 160ms. Wait for the
// simulated safe-area change to settle before restoring geometry.
await new Promise(resolve => setTimeout(resolve, 300));
const padAtRestore = parseFloat(
getComputedStyle(document.body).paddingLeft
);
if (Math.abs(padAtRestore - 58) > 0.5) {
throw new Error(
`Safe-area fixture did not settle: ${padAtRestore}px`
);
}
// Verify the running server actually serves the patched module.
const response = await fetch(
'/static/js/windowResize.js',
{ cache: 'no-store' }
);
if (!response.ok) {
throw new Error('Cannot fetch windowResize.js');
}
const moduleSource = await response.text();
if (!moduleSource.includes('const rightmostLeft = Math.max(padLeft')) {
throw new Error('Running server is serving unpatched windowResize.js');
}
const { makeWindowResizable } = await import('/static/js/windowResize.js');
makeWindowResizable(probe, { storageKey: key, mobileSkip: 768 });
await new Promise(resolve => setTimeout(resolve, 300));
return {
left: parseFloat(probe.style.left),
width: parseFloat(probe.style.width),
paddingLeft: parseFloat(getComputedStyle(document.body).paddingLeft),
viewportWidth: window.innerWidth,
};
} finally {
localStorage.removeItem(key);
probe.remove();
}
});
expect(value.paddingLeft).toBeGreaterThanOrEqual(58);
expect(value.width).toBe(480);
expect(value.left).toBeGreaterThanOrEqual(value.paddingLeft);
});
+477
View File
@@ -46,3 +46,480 @@ test('brush cursor matches the rendered brush diameter and replaces the crosshai
await expect.poll(async () => (await cursor.boundingBox()).width) await expect.poll(async () => (await cursor.boundingBox()).width)
.toBeCloseTo(measurements.expectedWidth * 2, 1); .toBeCloseTo(measurements.expectedWidth * 2, 1);
}); });
test('brush cursor follows the pointer before, during, and after a stroke and cancels animations on close', async ({ page }) => {
await openBlankEditor(page, { width: 400, height: 300 });
await selectTool(page, 'brush');
const canvas = await page.locator('.ge-main-canvas').boundingBox();
const cursor = page.locator('.ge-brush-cursor');
const checkCenter = async (x, y) => {
await expect.poll(async () => {
const box = await cursor.boundingBox();
return box ? Math.max(Math.abs(box.x + box.width / 2 - x), Math.abs(box.y + box.height / 2 - y)) : Infinity;
}).toBeLessThan(1);
};
const a = { x: canvas.x + canvas.width * 0.3, y: canvas.y + canvas.height * 0.4 };
const b = { x: canvas.x + canvas.width * 0.7, y: canvas.y + canvas.height * 0.6 };
await page.mouse.move(a.x, a.y);
await checkCenter(a.x, a.y);
await page.mouse.down();
await page.mouse.move(b.x, b.y, { steps: 8 });
await checkCenter(b.x, b.y);
await page.mouse.up();
await page.mouse.move(a.x, a.y);
await checkCenter(a.x, a.y);
// 1. Ensure at least one animation exists before checking cancellation
// 2. Verify the actual cursor-position animation is paused while active
const activeAnimation = await page.evaluate(() => {
const cursorEl = document.querySelector('.ge-brush-cursor');
const anims = cursorEl ? cursorEl.getAnimations() : [];
return {
count: anims.length,
hasPositionAnim: Boolean(cursorEl?._positionAnimation),
positionAnimPaused: cursorEl?._positionAnimation?.playState === 'paused',
positionAnimCurrentTime: cursorEl?._positionAnimation?.currentTime,
allPaused: anims.length > 0 && anims.every(a => a.playState === 'paused'),
};
});
expect(activeAnimation.count).toBeGreaterThanOrEqual(1);
expect(activeAnimation.hasPositionAnim).toBe(true);
expect(activeAnimation.positionAnimPaused).toBe(true);
expect(activeAnimation.positionAnimCurrentTime).toBe(0);
expect(activeAnimation.allPaused).toBe(true);
// 3. Verify it is canceled when the editor closes
// 4. Ensure temporary test-only references are cleaned up
const closeOutcome = await page.evaluate(async () => {
const cursorEl = document.querySelector('.ge-brush-cursor');
const anims = cursorEl ? cursorEl.getAnimations() : [];
const editor = await window.__photoEditorImport('/static/js/galleryEditor.js');
editor.closeEditor({ force: true });
return {
trackedCount: anims.length,
allIdle: anims.length > 0 && anims.every(a => a.playState === 'idle'),
states: anims.map(a => a.playState),
};
});
await expect(cursor).toHaveCount(0);
expect(closeOutcome.trackedCount).toBeGreaterThanOrEqual(1);
expect(closeOutcome.allIdle).toBe(true);
expect(closeOutcome.states.every(s => s === 'idle')).toBe(true);
// Verify no temporary references linger on window
const windowClean = await page.evaluate(() => {
return !('__cursorAnimationsForTest' in window) && !('__styleTransformMutations' in window);
});
expect(windowClean).toBe(true);
});
test('steady pointer movement does not perform repeated inline style-transform writes', async ({ page }) => {
await openBlankEditor(page, { width: 400, height: 300 });
await selectTool(page, 'brush');
const canvas = await page.locator('.ge-main-canvas').boundingBox();
const cursor = page.locator('.ge-brush-cursor');
// Warm up the cursor first: move pointer onto canvas
const startX = canvas.x + canvas.width * 0.25;
const startY = canvas.y + canvas.height * 0.25;
await page.mouse.move(startX, startY);
await expect(cursor).toBeVisible();
// Observe style attribute mutations during steady pointer movement.
// Brush size, color, and mode remain unchanged throughout.
await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
window.__styleMutationRecords = [];
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
if (m.type === 'attributes' && m.attributeName === 'style') {
const oldStyle = m.oldValue || '';
const currentStyle = el.getAttribute('style') || '';
// Track mutations where style-transform was written inline
if (el.style.transform || currentStyle.includes('transform:') || oldStyle.includes('transform:')) {
window.__styleMutationRecords.push({
oldStyle,
currentStyle,
inlineTransform: el.style.transform,
});
}
}
}
});
observer.observe(el, { attributes: true, attributeFilter: ['style'], attributeOldValue: true });
window.__styleMutationObserver = observer;
});
// Preserve actual mouse interactions: steady movement across 10 steps
const endX = canvas.x + canvas.width * 0.75;
const endY = canvas.y + canvas.height * 0.75;
await page.mouse.move(endX, endY, { steps: 10 });
// Confirm the cursor accurately tracked the pointer
await expect.poll(async () => {
const box = await cursor.boundingBox();
return box ? Math.max(Math.abs(box.x + box.width / 2 - endX), Math.abs(box.y + box.height / 2 - endY)) : Infinity;
}).toBeLessThan(1);
// Collect observation results and clean up observer and globals
const { mutationCount, inlineTransform, animCount } = await page.evaluate(() => {
window.__styleMutationObserver?.disconnect();
delete window.__styleMutationObserver;
const records = window.__styleMutationRecords || [];
delete window.__styleMutationRecords;
const el = document.querySelector('.ge-brush-cursor');
return {
mutationCount: records.length,
inlineTransform: el?.style.transform || '',
animCount: el?.getAnimations?.().length || 0,
};
});
// The optimized implementation uses paused Web Animations keyframes, avoiding repeated
// inline style-transform writes that trigger expensive :has() document invalidations.
expect(mutationCount).toBe(0);
expect(inlineTransform).toBe('');
expect(animCount).toBeGreaterThanOrEqual(1);
});
test('cross-tool cursor positioning, sizing, and styling across brush, eraser, pixel, lasso, inpaint, liquify, and clone', async ({ page }) => {
await openBlankEditor(page, { width: 400, height: 300 });
const canvas = await page.locator('.ge-main-canvas').boundingBox();
const cursor = page.locator('.ge-brush-cursor');
const checkCenter = async (x, y) => {
await expect.poll(async () => {
const box = await cursor.boundingBox();
return box ? Math.max(Math.abs(box.x + box.width / 2 - x), Math.abs(box.y + box.height / 2 - y)) : Infinity;
}).toBeLessThan(1);
};
const midX = canvas.x + canvas.width / 2;
const midY = canvas.y + canvas.height / 2;
// 1. Brush tool
await selectTool(page, 'brush');
await page.mouse.move(midX, midY);
await expect(cursor).toBeVisible();
await checkCenter(midX, midY);
let props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
isPixel: el.classList.contains('ge-brush-cursor--pixel'),
display: el.style.display,
borderStyle: el.style.borderStyle,
};
});
expect(props.isPixel).toBe(false);
expect(props.display).toBe('block');
// 2. Eraser tool
await selectTool(page, 'eraser');
await page.mouse.move(midX + 10, midY + 10);
await checkCenter(midX + 10, midY + 10);
props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
borderColor: el.style.borderColor,
isPixel: el.classList.contains('ge-brush-cursor--pixel'),
};
});
expect(props.borderColor).toBe('rgba(255, 255, 255, 0.6)');
expect(props.isPixel).toBe(false);
// 3. Pixel brush (via tool / preset)
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.tool = 'pixel';
state.brushPixel = true;
state.brushSize = 16;
});
await page.mouse.move(midX - 10, midY - 10);
await checkCenter(midX - 10, midY - 10);
props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
isPixel: el.classList.contains('ge-brush-cursor--pixel'),
width: parseFloat(el.style.width),
};
});
expect(props.isPixel).toBe(true);
// 4. Lasso tool
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.tool = 'lasso';
state.brushPixel = false;
});
await page.mouse.move(midX + 20, midY - 10);
await checkCenter(midX + 20, midY - 10);
props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
borderColor: el.style.borderColor,
background: el.style.background,
};
});
expect(props.borderColor).toBe('rgba(255, 255, 255, 0.85)');
expect(props.background).toBe('rgba(0, 0, 0, 0.15)');
// 5. Inpaint tool (paint mode and erase mode)
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.tool = 'inpaint';
state.inpaintEraseMode = false;
});
await page.mouse.move(midX, midY);
await checkCenter(midX, midY);
props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
borderColor: el.style.borderColor,
background: el.style.background,
borderStyle: el.style.borderStyle,
};
});
expect(props.borderColor).toBe('rgba(255, 80, 80, 0.8)');
expect(props.borderStyle).toBe('solid');
// Inpaint erase mode
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.inpaintEraseMode = true;
});
await page.mouse.move(midX + 5, midY + 5);
props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
borderColor: el.style.borderColor,
borderStyle: el.style.borderStyle,
};
});
expect(props.borderColor).toBe('rgba(255, 255, 255, 0.9)');
expect(props.borderStyle).toBe('dashed');
// 6. Liquify tool
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.tool = 'liquify';
state.liquifySize = 100;
});
await page.mouse.move(midX - 15, midY + 15);
await checkCenter(midX - 15, midY + 15);
props = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
return {
width: parseFloat(el.style.width),
height: parseFloat(el.style.height),
display: el.style.display,
};
});
expect(props.display).toBe('block');
expect(props.width).toBeGreaterThan(0);
// 7. Clone tool
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.tool = 'clone';
state.brushSize = 50;
});
await page.mouse.move(midX, midY);
await checkCenter(midX, midY);
await expect(cursor).toBeVisible();
// Clean close
await page.evaluate(async () => {
const editor = await window.__photoEditorImport('/static/js/galleryEditor.js');
editor.closeEditor({ force: true });
});
await expect(cursor).toHaveCount(0);
});
test('canvas boundaries, pointer exit and re-entry, and viewport resize', async ({ page }) => {
await openBlankEditor(page, { width: 400, height: 300 });
await selectTool(page, 'brush');
const canvas = await page.locator('.ge-main-canvas').boundingBox();
const cursor = page.locator('.ge-brush-cursor');
const checkCenter = async (x, y) => {
await expect.poll(async () => {
const box = await cursor.boundingBox();
return box ? Math.max(Math.abs(box.x + box.width / 2 - x), Math.abs(box.y + box.height / 2 - y)) : Infinity;
}).toBeLessThan(1);
};
// 1. Enter canvas
const insideX = canvas.x + canvas.width * 0.5;
const insideY = canvas.y + canvas.height * 0.5;
await page.mouse.move(insideX, insideY);
await expect(cursor).toBeVisible();
await checkCenter(insideX, insideY);
// 2. Exit canvas boundary: cursor should hide
const outsideX = canvas.x - 50;
const outsideY = canvas.y - 50;
await page.mouse.move(outsideX, outsideY);
await expect(cursor).toBeHidden();
// 3. Re-enter canvas: cursor should restore visibility and position
await page.mouse.move(insideX, insideY);
await expect(cursor).toBeVisible();
await checkCenter(insideX, insideY);
// 4. Viewport resize
await page.setViewportSize({ width: 1280, height: 800 });
await page.waitForTimeout(100);
const newCanvas = await page.locator('.ge-main-canvas').boundingBox();
const newInsideX = newCanvas.x + newCanvas.width * 0.5;
const newInsideY = newCanvas.y + newCanvas.height * 0.5;
await page.mouse.move(newInsideX, newInsideY);
await expect(cursor).toBeVisible();
await checkCenter(newInsideX, newInsideY);
// Clean close
await page.evaluate(async () => {
const editor = await window.__photoEditorImport('/static/js/galleryEditor.js');
editor.closeEditor({ force: true });
});
await expect(cursor).toHaveCount(0);
});
for (const view of ['2x zoom', 'fit-to-view']) {
test(`zoom and fit-to-view cursor scaling and positioning: ${view}`, async ({ page }) => {
const size = view === '2x zoom' ? { width: 400, height: 300 } : { width: 1600, height: 1200 };
await openBlankEditor(page, size);
await selectTool(page, 'brush');
await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
state.brushSize = 50;
// The zoom-in control applies 1.25x through the real zoom handler.
state.zoom = 1.6;
state.zoomViewMode = 'scale';
});
await page.locator('#ge-zoom-in').click();
await expect.poll(() => page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
return { zoom: state.zoom, mode: state.zoomViewMode };
})).toEqual({ zoom: 2, mode: 'scale' });
if (view === 'fit-to-view') {
await page.locator('#ge-zoom-100').click();
const fitted = await page.evaluate(async () => {
const { state } = await import('/static/js/editor/state.js');
const area = document.querySelector('.ge-canvas-area');
const pad = state._footerDocked ? 0 : 20;
const rulerPad = state.rulersVisible ? 18 : 0;
return {
zoom: state.zoom,
mode: state.zoomViewMode,
expectedZoom: Math.min(1,
(area.clientWidth - 2 * pad - rulerPad) / state.imgWidth,
(area.clientHeight - 2 * pad - rulerPad) / state.imgHeight),
};
});
expect(fitted.mode).toBe('fit');
expect(fitted.zoom).toBeGreaterThan(0);
expect(fitted.zoom).toBeLessThan(1);
expect(fitted.zoom).toBeCloseTo(fitted.expectedZoom, 6);
}
const canvas = page.locator('.ge-main-canvas');
const canvasBox = await canvas.boundingBox();
const cursor = page.locator('.ge-brush-cursor');
if (view === '2x zoom') {
expect(canvasBox.width).toBeCloseTo(size.width * 2, 1);
expect(canvasBox.height).toBeCloseTo(size.height * 2, 1);
}
const targetX = canvasBox.x + canvasBox.width * 0.4;
const targetY = canvasBox.y + canvasBox.height * 0.4;
await page.mouse.move(targetX, targetY);
await expect(cursor).toBeVisible();
// Pointer coordinates can be rounded to device pixels; keep the existing
// subpixel alignment tolerance separate from the stricter diameter check.
await expect.poll(async () => {
const box = await cursor.boundingBox();
return box ? Math.max(
Math.abs(box.x + box.width / 2 - targetX),
Math.abs(box.y + box.height / 2 - targetY),
) : Infinity;
}).toBeLessThan(1);
await expect.poll(() => page.evaluate(() => {
const canvasEl = document.querySelector('.ge-main-canvas');
const canvasRect = canvasEl.getBoundingClientRect();
const cursorRect = document.querySelector('.ge-brush-cursor').getBoundingClientRect();
return Math.max(
Math.abs(cursorRect.width - 50 * canvasRect.width / canvasEl.width),
Math.abs(cursorRect.height - 50 * canvasRect.height / canvasEl.height),
);
})).toBeLessThan(0.1);
await page.evaluate(async () => {
const editor = await window.__photoEditorImport('/static/js/galleryEditor.js');
editor.closeEditor({ force: true });
});
await expect(cursor).toHaveCount(0);
});
}
test('memory and lifecycle: repeated editor open/close cycles retain no detached cursors or active animations', async ({ page }) => {
for (let cycle = 0; cycle < 5; cycle++) {
await openBlankEditor(page, { width: 400, height: 300 });
await selectTool(page, 'brush');
const canvas = await page.locator('.ge-main-canvas').boundingBox();
await page.mouse.move(canvas.x + canvas.width * 0.5, canvas.y + canvas.height * 0.5);
const cursor = page.locator('.ge-brush-cursor');
await expect(cursor).toBeVisible();
// Verify cursor layer and animation are active
const cycleState = await page.evaluate(() => {
const el = document.querySelector('.ge-brush-cursor');
window.__lastCycleAnim = el?._positionAnimation;
return {
cursorCount: document.querySelectorAll('.ge-brush-cursor').length,
layerCount: document.querySelectorAll('#ge-cursor-layer').length,
hasAnim: Boolean(el?._positionAnimation),
animPaused: el?._positionAnimation?.playState === 'paused',
};
});
expect(cycleState.cursorCount).toBe(1);
expect(cycleState.layerCount).toBe(1);
expect(cycleState.animPaused).toBe(true);
// Close editor
await page.evaluate(async () => {
const editor = await window.__photoEditorImport('/static/js/galleryEditor.js');
editor.closeEditor({ force: true });
});
// Verify complete cleanup after close
await expect(cursor).toHaveCount(0);
const postClose = await page.evaluate(() => {
const anim = window.__lastCycleAnim;
delete window.__lastCycleAnim;
return {
cursorCount: document.querySelectorAll('.ge-brush-cursor').length,
layerCount: document.querySelectorAll('#ge-cursor-layer').length,
animIdle: anim ? anim.playState === 'idle' : true,
activeAnims: document.getAnimations().filter(a => {
const target = a.effect?.target;
return target && (target.classList?.contains('ge-brush-cursor') || target.id === 'ge-cursor-layer');
}).length,
};
});
expect(postClose.cursorCount).toBe(0);
expect(postClose.layerCount).toBe(0);
expect(postClose.animIdle).toBe(true);
expect(postClose.activeAnims).toBe(0);
}
});
@@ -24,6 +24,7 @@ const REAL_MODULES = new Set([
path.join(JS, 'settings/speech.js'), path.join(JS, 'settings/speech.js'),
path.join(JS, 'settings/writingStyle.js'), path.join(JS, 'settings/writingStyle.js'),
path.join(JS, 'settings/imageModels.js'), path.join(JS, 'settings/imageModels.js'),
path.join(JS, 'settings/imagePreferences.js'),
path.join(JS, 'settings/agent.js'), path.join(JS, 'settings/agent.js'),
path.join(JS, 'settings/shell.js'), path.join(JS, 'settings/shell.js'),
path.join(JS, 'settings/peek.js'), path.join(JS, 'settings/peek.js'),
+28 -4
View File
@@ -14,12 +14,22 @@ from routes.auth_routes import SESSION_COOKIE
from tests.helpers.database import disposable_database from tests.helpers.database import disposable_database
@pytest.fixture @pytest.fixture(scope="module")
def authenticated_app(tmp_path, monkeypatch): def auth_configuration(tmp_path_factory):
monkeypatch.setenv("AUTH_ENABLED", "true") """Hash real fixture passwords once; only immutable bytes are reused."""
auth = AuthManager(str(tmp_path / "auth.json")) path = tmp_path_factory.mktemp("admin-auth-seed") / "auth.json"
auth = AuthManager(str(path))
for user, admin in (("member", False), ("admin", True)): for user, admin in (("member", False), ("admin", True)):
assert auth.create_user(user, "disposable-test-password", is_admin=admin) assert auth.create_user(user, "disposable-test-password", is_admin=admin)
return path.read_bytes()
@pytest.fixture
def authenticated_app(tmp_path, monkeypatch, auth_configuration):
monkeypatch.setenv("AUTH_ENABLED", "true")
path = tmp_path / "auth.json"
path.write_bytes(auth_configuration)
auth = AuthManager(str(path))
app = FastAPI() app = FastAPI()
app.state.auth_manager = auth app.state.auth_manager = auth
@@ -133,3 +143,17 @@ def test_diagnostics_require_real_admin_before_sensitive_work(
for operation in (stats, rag.get_stats, research.call_research_service, for operation in (stats, rag.get_stats, research.call_research_service,
extract_id, transcript, collect, read_log): extract_id, transcript, collect, read_log):
operation.assert_not_called() operation.assert_not_called()
@pytest.mark.parametrize("instance", [0, 1])
def test_authenticated_fixture_has_private_users_sessions_and_file(authenticated_app, instance):
app, client_for = authenticated_app
auth = app.state.auth_manager
assert set(auth.users) == {"member", "admin"}
assert not auth._sessions
with client_for("member") as client:
assert auth.get_username_for_token(client.cookies.get(SESSION_COOKIE)) == "member"
assert auth.create_user("fixture-local", "disposable-test-password")
# Both parameter cases mutate their own file. Any shared manager, mutable
# users/sessions or written-back seed makes the next case fail, in any order.
assert "fixture-local" in auth.users
+42 -5
View File
@@ -1929,23 +1929,60 @@ def test_place_layer_reports_false_on_queued_response(monkeypatch):
assert placed is False assert placed is False
def test_bridge_await_cancellation_handled_cleanly(): def test_bridge_await_cancellation_handled_cleanly(monkeypatch):
import asyncio import asyncio
from contextlib import suppress
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
app = _bridge_app() app = _bridge_app()
async def scenario(): async def scenario():
entered_wait = asyncio.Event()
real_wait_for = asyncio.wait_for
waits = []
async def observe_wait(awaitable, timeout):
# Observe the real wait; do not replace its result or cancellation.
waits.append(awaitable)
entered_wait.set()
return await real_wait_for(awaitable, timeout)
monkeypatch.setattr(eaar.asyncio, "wait_for", observe_wait)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
cmd_resp = await c.post("/api/editor/bridge/command", json={"session": "cancel-sess", "op": "document.info", "wait": False}) cmd_resp = await c.post("/api/editor/bridge/command", json={"session": "cancel-sess", "op": "document.info", "wait": False})
assert cmd_resp.status_code == 200
assert cmd_resp.json()["completed"] is False
cid = cmd_resp.json()["queued"][0] cid = cmd_resp.json()["queued"][0]
await_task = asyncio.create_task(c.post("/api/editor/bridge/await", json={"id": cid, "timeout": 30})) await_task = asyncio.create_task(c.post("/api/editor/bridge/await", json={"id": cid, "timeout": 30}))
await asyncio.sleep(0.05)
await_task.cancel()
try: try:
await real_wait_for(entered_wait.wait(), 5)
assert len(waits) == 1
assert not waits[0].done()
assert not await_task.done(), "await returned without a queued result"
await_task.cancel()
response = await real_wait_for(await_task, 5)
assert response.status_code == 200
assert response.json() == {
"ok": False, "error": "cancelled", "status": "cancelled",
"completed": False, "id": cid,
}
finally:
if not await_task.done():
await_task.cancel()
with suppress(asyncio.CancelledError):
await await_task await await_task
except asyncio.CancelledError:
pass # Cancelling the waiter must not cancel the queued command itself.
payload = {"width": 137, "height": 251}
delivered = await c.post("/api/editor/bridge/result", json={"id": cid, "ok": True, "result": payload})
assert delivered.status_code == 200
completed = await c.post("/api/editor/bridge/await", json={"id": cid, "timeout": 1})
assert completed.status_code == 200
assert completed.json()["status"] == "completed"
assert completed.json()["completed"] is True
assert completed.json()["ok"] is True
assert completed.json()["result"] == payload
assert len(waits) == 2
asyncio.run(scenario()) asyncio.run(scenario())
+27 -12
View File
@@ -206,35 +206,50 @@ class TestDiskConsistency:
@pytest.mark.slow @pytest.mark.slow
def test_file_always_valid_json_during_concurrent_ops(self, tmp_path): def test_file_always_valid_json_during_concurrent_ops(self, tmp_path):
mgr = _fresh_auth_manager(tmp_path) mgr = _fresh_auth_manager(tmp_path)
mgr.create_user("admin", "adminpw", is_admin=True) assert mgr.create_user("admin", "adminpw", is_admin=True)
stop_event = threading.Event() stop_event = threading.Event()
reader_ready = threading.Event()
corruption_found = [] corruption_found = []
observations = {"reads": 0, "with_writes": 0}
def reader(): def reader():
while not stop_event.is_set(): while not stop_event.is_set():
try: try:
with open(mgr.auth_path, "r") as f: with open(mgr.auth_path, "r") as f:
content = f.read() content = f.read()
json.loads(content) data = json.loads(content)
observations["reads"] += 1
if any(name.startswith("stress") for name in data["users"]):
observations["with_writes"] += 1
reader_ready.set()
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
corruption_found.append(str(e)) corruption_found.append(str(e))
break break
except FileNotFoundError:
pass
time.sleep(0.001) time.sleep(0.001)
def writer(): def writer():
assert reader_ready.wait(5), "reader never observed the initial file"
results = []
for i in range(50): for i in range(50):
mgr.create_user(f"stress{i}", f"pw{i}") results.append(mgr.create_user(f"stress{i}", f"pw{i}"))
return results
reader_thread = threading.Thread(target=reader) # Futures propagate reader/writer exceptions to the test thread.
writer_thread = threading.Thread(target=writer) with ThreadPoolExecutor(max_workers=2) as pool:
reading = pool.submit(reader)
reader_thread.start() writing = pool.submit(writer)
writer_thread.start() try:
writer_thread.join() results = writing.result(timeout=120)
finally:
stop_event.set() stop_event.set()
reader_thread.join() reading.result(timeout=5)
assert not corruption_found, f"Corrupt JSON detected: {corruption_found[0]}" assert not corruption_found, f"Corrupt JSON detected: {corruption_found[0]}"
assert len(results) == 50 and all(results), "writer operations did not succeed"
assert observations["reads"] > 0
assert observations["with_writes"] > 0, "reader saw no persisted writer activity"
expected = {"admin"} | {f"stress{i}" for i in range(50)}
with open(mgr.auth_path) as persisted:
assert set(json.load(persisted)["users"]) == expected
assert set(_fresh_auth_manager(tmp_path).users) == expected
+40 -12
View File
@@ -13,6 +13,7 @@ import socketserver
import threading import threading
import pytest import pytest
import requests
from src import caldav_sync, caldav_writeback from src import caldav_sync, caldav_writeback
@@ -26,12 +27,13 @@ def test_build_dav_client_disables_redirects():
def test_dav_client_does_not_follow_redirect_to_internal_host(): def test_dav_client_does_not_follow_redirect_to_internal_host():
"""End-to-end through the real DAVClient: a 302 toward an internal host """End-to-end through the real DAVClient: a 302 toward an internal host
must NOT be followed. Without the fix the sink is contacted (SSRF); with it must NOT be followed. Exercise the session limit separately because some
the redirect is refused and the sink is never reached.""" caldav versions independently refuse cross-origin PROPFIND redirects."""
pytest.importorskip("caldav") pytest.importorskip("caldav")
sink_hits: list[str] = [] sink_hits: list[str] = []
public_methods: list[str] = [] public_methods: list[str] = []
same_origin_hits: list[str] = []
class _Internal(http.server.BaseHTTPRequestHandler): class _Internal(http.server.BaseHTTPRequestHandler):
# Stand-in for an internal service the attacker redirects toward. # Stand-in for an internal service the attacker redirects toward.
@@ -48,9 +50,15 @@ def test_dav_client_does_not_follow_redirect_to_internal_host():
class _Public(http.server.BaseHTTPRequestHandler): class _Public(http.server.BaseHTTPRequestHandler):
# The "validated" public CalDAV server that redirects everything inward. # The "validated" public CalDAV server that redirects everything inward.
def do_GET(self): # noqa: N802 def do_GET(self): # noqa: N802
if self.path == "/landing":
same_origin_hits.append(self.path)
self.send_response(200)
self.end_headers()
return
public_methods.append(self.command) public_methods.append(self.command)
self.send_response(302) self.send_response(302)
self.send_header("Location", f"http://127.0.0.1:{internal_port}/leak") location = "/landing" if self.path == "/same" else f"http://127.0.0.1:{internal_port}/leak"
self.send_header("Location", location)
self.end_headers() self.end_headers()
do_PROPFIND = do_GET do_PROPFIND = do_GET
@@ -62,8 +70,10 @@ def test_dav_client_does_not_follow_redirect_to_internal_host():
internal_port = internal.server_address[1] internal_port = internal.server_address[1]
public = socketserver.TCPServer(("127.0.0.1", 0), _Public) public = socketserver.TCPServer(("127.0.0.1", 0), _Public)
public_port = public.server_address[1] public_port = public.server_address[1]
threading.Thread(target=internal.serve_forever, daemon=True).start() internal_thread = threading.Thread(target=internal.serve_forever, daemon=True)
threading.Thread(target=public.serve_forever, daemon=True).start() public_thread = threading.Thread(target=public.serve_forever, daemon=True)
internal_thread.start()
public_thread.start()
try: try:
public_url = f"http://127.0.0.1:{public_port}/dav" public_url = f"http://127.0.0.1:{public_port}/dav"
client = caldav_sync._build_dav_client(public_url, "u", "p") client = caldav_sync._build_dav_client(public_url, "u", "p")
@@ -82,17 +92,35 @@ def test_dav_client_does_not_follow_redirect_to_internal_host():
assert public_methods in (["PROPFIND"], ["PROPFIND", "GET"]), public_methods assert public_methods in (["PROPFIND"], ["PROPFIND", "GET"]), public_methods
assert sink_hits == [], "redirect toward an internal host must not be followed" assert sink_hits == [], "redirect toward an internal host must not be followed"
# Positive control: demonstrate that the sink would see the redirect # GET redirects are handled by the HTTP session even in caldav 3.7.
# if the session's redirect protection were removed. # This makes the cross-port SSRF assertion sensitive to our own limit.
with pytest.raises(Exception, match="Exceeded 0 redirects"):
client.request(public_url, "GET", "")
assert sink_hits == [], "GET redirect toward the internal sink must be blocked"
# requests can reach the cross-port sink when redirects are enabled,
# even if DAVClient independently rejects cross-origin PROPFIND redirects.
with requests.Session() as session:
response = session.get(public_url, timeout=5)
assert response.status_code == 207
assert sink_hits == ["/leak"], "the cross-port redirect must reach the sink"
# GET follows redirects at the HTTP session layer across these caldav
# versions. Check the application's limit on a same-origin redirect too.
same_url = f"http://127.0.0.1:{public_port}/same"
with pytest.raises(Exception, match="Exceeded 0 redirects"):
client.request(same_url, "GET", "")
assert same_origin_hits == []
client.session.max_redirects = 30 client.session.max_redirects = 30
try: client.request(same_url, "GET", "")
client.request(public_url, "PROPFIND", "") assert same_origin_hits == ["/landing"]
except Exception:
pass # The sink's response is intentionally not a valid DAV body.
assert sink_hits == ["/leak"], "the test must detect a followed redirect"
finally: finally:
internal.shutdown() internal.shutdown()
public.shutdown() public.shutdown()
internal_thread.join()
public_thread.join()
internal.server_close()
public.server_close()
def test_sync_and_writeback_construct_clients_through_the_helper(): def test_sync_and_writeback_construct_clients_through_the_helper():
+35
View File
@@ -0,0 +1,35 @@
"""The CalDAV config routes answer 400 for a body that is JSON but not an object."""
import asyncio
import json
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from routes.calendar_routes import _json_object_body
def _request(raw: bytes):
async def _json():
return json.loads(raw)
return SimpleNamespace(json=_json)
def _parse(raw: bytes):
return asyncio.run(_json_object_body(_request(raw)))
def test_object_body_is_returned():
assert _parse(b'{"url": "https://dav.example/"}') == {"url": "https://dav.example/"}
@pytest.mark.parametrize("raw", [b"", b"not json"])
def test_unreadable_body_counts_as_empty(raw):
assert _parse(raw) == {}
@pytest.mark.parametrize("raw", [b"[]", b'"x"', b"5", b"null"])
def test_non_object_body_is_a_400(raw):
with pytest.raises(HTTPException) as exc:
_parse(raw)
assert exc.value.status_code == 400
@@ -0,0 +1,148 @@
"""Both chat tidy entry points retain saved conversations and still remove empties."""
import asyncio
from datetime import datetime, timedelta, timezone
import pytest
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import core.database as database
import core.session_manager as manager_module
import routes.session_routes as routes
import src.session_actions as actions
@pytest.fixture
def tidy_api(tmp_path, monkeypatch):
engine = create_engine(
f"sqlite:///{(tmp_path / 'tidy.db').as_posix()}",
connect_args={"check_same_thread": False},
)
database.Base.metadata.create_all(engine)
factory = sessionmaker(bind=engine, autoflush=False)
monkeypatch.setattr(database, "SessionLocal", factory)
monkeypatch.setattr(manager_module, "SessionLocal", factory)
monkeypatch.setattr(routes, "SessionLocal", factory)
monkeypatch.setattr(routes, "router", APIRouter(prefix="/api"))
monkeypatch.setattr(routes, "effective_user", lambda request: "alice")
manager = manager_module.SessionManager.__new__(manager_module.SessionManager)
manager.sessions = {}
manager.upload_handler = None
monkeypatch.setattr(manager, "get_sessions_for_user", lambda owner: {})
app = FastAPI()
app.include_router(routes.setup_session_routes(manager, {}))
with TestClient(app) as client:
yield client, factory, manager
engine.dispose()
def run_tidy(client, entrypoint):
if entrypoint == "action":
return asyncio.run(actions.run_auto_sort("alice", skip_llm=True))
response = client.post("/api/sessions/auto-sort?skip_llm=true")
assert response.status_code == 200, response.text
return response.json()
@pytest.mark.parametrize("entrypoint", ["route", "action"])
@pytest.mark.parametrize("title,prompt", [
("New chat", "Please analyze the following contract and retain all details. " * 20),
("Contract analysis", "Review contract"),
("Chat: analysis", "Explain these results and retain the full answer"),
("Test", "Here is a large input that should be analyzed and retained"),
], ids=["generic-title", "short-prompt", "title-prefix", "test-title"])
def test_tidy_preserves_nontrivial_saved_answer(tidy_api, title, prompt, entrypoint):
client, factory, manager = tidy_api
old = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=2)
answer = "Clause analysis and recommended changes.\n" * 2000
with factory() as db:
db.add(database.Session(
id="valuable-chat", name=title, owner="alice", endpoint_url="", model="",
archived=False, is_important=False, message_count=2,
created_at=old, updated_at=old, last_accessed=old, last_message_at=old,
))
db.commit()
db.add_all([
database.ChatMessage(id="prompt", session_id="valuable-chat", role="user",
content=prompt, timestamp=old),
database.ChatMessage(id="answer", session_id="valuable-chat", role="assistant",
content=answer, timestamp=old + timedelta(seconds=1)),
])
db.commit()
run_tidy(client, entrypoint)
with factory() as db:
remaining = db.query(database.ChatMessage).filter_by(session_id="valuable-chat").count()
survives = db.get(database.Session, "valuable-chat") is not None
assert survives and remaining == 2, "Title/prompt heuristics must not erase saved answers"
with factory() as db:
assert db.get(database.ChatMessage, "answer").content == answer
@pytest.mark.parametrize("entrypoint", ["route", "action"])
@pytest.mark.parametrize("kind", ["unanswered", "greeting", "empty", "fresh-empty", "starred-empty", "archived", "other-owner", "incognito"])
def test_tidy_cleanup_boundaries(tidy_api, entrypoint, kind):
client, factory, manager = tidy_api
now = datetime.now(timezone.utc).replace(tzinfo=None)
timestamp = now if kind == "fresh-empty" else now - timedelta(hours=2)
message = kind in {"unanswered", "greeting", "archived", "other-owner", "incognito"}
with factory() as db:
db.add(database.Session(
id="boundary-chat", name="Incognito" if kind == "incognito" else "New chat",
owner="bob" if kind == "other-owner" else "alice", endpoint_url="", model="",
archived=kind == "archived", is_important=kind == "starred-empty",
# Deliberately inaccurate metadata: cleanup must use message rows.
message_count=0 if message else 40,
created_at=timestamp, updated_at=timestamp, last_accessed=timestamp, last_message_at=timestamp,
))
db.commit()
if message:
db.add(database.ChatMessage(id="boundary-message", session_id="boundary-chat", role="user",
content="hi" if kind == "greeting" else "Pending question " * 100,
timestamp=timestamp))
db.commit()
run_tidy(client, entrypoint)
deleted = kind in {"empty", "incognito"}
with factory() as db:
assert (db.get(database.Session, "boundary-chat") is None) == deleted
assert db.query(database.ChatMessage).filter_by(session_id="boundary-chat").count() == int(message and not deleted)
@pytest.mark.parametrize("entrypoint", ["route", "action"])
def test_tidy_keeps_folder_assignment_working(tidy_api, monkeypatch, entrypoint):
from types import SimpleNamespace
import src.llm_core as llm
import src.task_endpoint as endpoints
client, factory, manager = tidy_api
old = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=2)
for sid in ["chat-one-long-id", "chat-two-long-id"]:
with factory() as db:
db.add(database.Session(id=sid, name="New chat", owner="alice", endpoint_url="", model="",
archived=False, created_at=old, updated_at=old,
last_accessed=old, last_message_at=old))
db.commit()
db.add(database.ChatMessage(id=f"{sid}-message", session_id=sid, role="user",
content="Saved question", timestamp=old))
db.commit()
manager.sessions[sid] = SimpleNamespace(id=sid, name="New chat", archived=False,
updated_at=old.isoformat(), created_at=old.isoformat())
monkeypatch.setattr(manager, "get_sessions_for_user", lambda owner: manager.sessions)
monkeypatch.setattr(endpoints, "resolve_task_endpoint", lambda *args, **kwargs: ("http://model.invalid", "test", {}))
response_text = '{"folders":{"Projects":["chat-one","chat-two"]}}'
monkeypatch.setattr(llm, "llm_call", lambda *args, **kwargs: response_text)
async def async_response(*args, **kwargs):
return response_text
monkeypatch.setattr(llm, "llm_call_async", async_response)
if entrypoint == "action":
result = asyncio.run(actions.run_auto_sort("alice"))
assert "Sorted 2 sessions" in result
else:
response = client.post("/api/sessions/auto-sort")
assert response.status_code == 200, response.text
assert response.json()["updated"] == 2
with factory() as db:
assert db.query(database.ChatMessage).count() == 2
assert {row.folder for row in db.query(database.Session).all()} == {"Projects"}
+43 -2
View File
@@ -7,13 +7,13 @@ CalendarCal.owner; the query must join it, like routes/calendar_routes.
""" """
import uuid import uuid
import sys import sys
from datetime import datetime from datetime import datetime, timedelta
import pytest import pytest
from tests.helpers.database import disposable_database from tests.helpers.database import disposable_database
from core.database import CalendarEvent, CalendarCal from core.database import CalendarEvent, CalendarCal
from src.task_scheduler import _checkin_calendar_events from src.task_scheduler import _checkin_calendar_events, _digest_windows
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@@ -68,3 +68,44 @@ def test_cancelled_excluded_and_window_respected():
assert "cancelled" not in [ev.summary for ev in out] assert "cancelled" not in [ev.summary for ev in out]
finally: finally:
db.close() db.close()
@pytest.mark.parametrize("days, expected_label", [(2, "this_week"), (7, "next_30_days")])
def test_boundary_event_appears_in_only_one_digest_window(days, expected_label):
now = datetime(2026, 6, 1, 9)
boundary = now + timedelta(days=days)
with _TS() as db:
db.add(CalendarCal(id="boundary-cal", owner="alice", name="Boundary"))
db.add(CalendarEvent(
uid="boundary-event", calendar_id="boundary-cal", summary="Boundary meeting",
dtstart=boundary, dtend=boundary + timedelta(hours=1), status="confirmed",
))
db.commit()
buckets = [
label for label, start, end in _digest_windows(now)
if _checkin_calendar_events(db, "alice", start, end)
]
assert buckets == [expected_label]
def test_digest_includes_start_and_excludes_end():
start = datetime(2026, 6, 1, 9)
end = start + timedelta(days=2)
with _TS() as db:
db.add(CalendarCal(id="bounds-cal", owner="alice", name="Bounds"))
for uid, when in [
("before", start - timedelta(seconds=1)),
("start", start),
("inside", end - timedelta(seconds=1)),
("end", end),
]:
db.add(CalendarEvent(
uid=uid, calendar_id="bounds-cal", summary=uid, dtstart=when,
dtend=when + timedelta(hours=1), status="confirmed",
))
db.commit()
assert [ev.uid for ev in _checkin_calendar_events(db, "alice", start, end)] == [
"start", "inside",
]

Some files were not shown because too many files have changed in this diff Show More