Compare commits

..
Author SHA1 Message Date
pewdiepie-archdaemon 0b118a9ccc Retain Gallery UI regression coverage in the combined review 2026-10-26 16:57:33 +00:00
pewdiepie-archdaemon 3915efc9ac Merge branch 'sync/pr-6740-dev-20261026' into review/7011-with-dev-20261026 2026-10-26 16:57:23 +00:00
pewdiepie-archdaemon 3ee93b6316 Merge branch 'sync/pr-6741-dev-20261026' into review/7011-with-dev-20261026 2026-10-26 16:57:23 +00:00
pewdiepie-archdaemon 03d0042115 Merge branch 'sync/pr-6738-dev-20261026' into review/7011-with-dev-20261026
# Conflicts:
#	static/index.html
#	static/js/chat.js
#	static/sw.js
2026-10-26 16:57:23 +00:00
pewdiepie-archdaemon 45e23c4615 Merge branch 'sync/pr-6739-dev-20261026' into review/7011-with-dev-20261026 2026-10-26 16:57:09 +00:00
pewdiepie-archdaemon da8ba69c74 Keep streamed-chat module identity consistently cache-busted 2026-10-26 16:57:01 +00:00
pewdiepie-archdaemon 0b8176b11e Keep streamed-chat module identity consistently cache-busted 2026-10-26 16:57:01 +00:00
pewdiepie-archdaemon 3246ae5d9c Keep streamed-chat module identity consistently cache-busted 2026-10-26 16:57:01 +00:00
pewdiepie-archdaemon 03baea7700 Preserve owner-scoped compaction and the web-only routing boundary 2026-10-26 16:54:10 +00:00
pewdiepie-archdaemon 375e263419 Merge backend ownership checks and test ownership cleanup 2026-10-26 16:53:52 +00:00
pewdiepie-archdaemon 8865c975aa Keep chat-editor integration and shutdown checks with the runtime review 2026-10-26 16:53:52 +00:00
pewdiepie-archdaemon a58a5e6632 Merge backend ownership checks and test ownership cleanup 2026-10-26 16:53:52 +00:00
pewdiepie-archdaemon 106b1e7c86 Verify saved action names and steps cannot inject HTML 2026-10-26 16:50:09 +00:00
pewdiepie-archdaemon 49d57a43fe Merge recolor cleanup regression coverage 2026-10-26 16:50:09 +00:00
pewdiepie-archdaemon e67cb8bbb9 Merge recolor cleanup regression coverage 2026-10-26 16:50:08 +00:00
pewdiepie-archdaemon 2c48e7fdab Verify the Gallery model picker in the UI review that ships it 2026-10-26 16:49:01 +00:00
pewdiepie-archdaemon 9ab440c4cb Keep Gallery image-model picker tests with the editor client 2026-10-26 16:49:01 +00:00
pewdiepie-archdaemon ff1d7df8b0 Merge backend prompt hardening and scoped tests 2026-10-26 16:49:01 +00:00
pewdiepie-archdaemon fa29a86696 Merge backend prompt hardening and scoped tests 2026-10-26 16:49:01 +00:00
pewdiepie-archdaemon 8cfdb8e2e5 Render saved action labels as text instead of HTML 2026-10-26 16:49:01 +00:00
pewdiepie-archdaemon f53ddfba3c Integrate updated preview UI review 2026-10-26 16:37:00 +00:00
pewdiepie-archdaemon 763ae17766 Integrate updated photo-editor client review 2026-10-26 16:37:00 +00:00
pewdiepie-archdaemon e41e8354df Integrate updated Ajax runtime review 2026-10-26 16:37:00 +00:00
pewdiepie-archdaemon 871c0c0687 Align the shared stream watchdog with the UI review 2026-10-26 16:36:59 +00:00
pewdiepie-archdaemon 79638043da Integrate updated editor backend review 2026-10-26 16:36:59 +00:00
pewdiepie-archdaemon 76ab72412d Preserve completion gating and handle explicit idle stream status safely 2026-10-26 16:34:56 +00:00
pewdiepie-archdaemon 5c6bb9798b Preserve completion gating and handle explicit idle stream status safely 2026-10-26 16:34:56 +00:00
pewdiepie-archdaemon 56b85c359c Normalize final newlines in integrated review files 2026-10-26 16:31:23 +00:00
pewdiepie-archdaemon 04ca6c26c3 Normalize final newlines in integrated review files 2026-10-26 16:31:23 +00:00
pewdiepie-archdaemon ae28501e7f Normalize final newlines in integrated review files 2026-10-26 16:31:23 +00:00
pewdiepie-archdaemon fdb2a330d9 Remove duplicate session copy-header helpers after integration 2026-10-26 16:30:56 +00:00
pewdiepie-archdaemon 08452ab5f9 Keep chat module URLs consistent across imports and precache 2026-10-26 16:29:17 +00:00
pewdiepie-archdaemon e461a6b5c5 Keep chat module URLs consistent across imports and precache 2026-10-26 16:29:17 +00:00
pewdiepie-archdaemon aa91e69b2a Merge the verified editor-server foundation into the runtime review 2026-10-26 16:27:32 +00:00
pewdiepie-archdaemon c54bc1d2d3 Merge the verified editor-server foundation into the client review 2026-10-26 16:27:31 +00:00
pewdiepie-archdaemon 9ab3f70fe4 Integrate gallery document tabs with the updated editor client 2026-10-26 16:27:31 +00:00
pewdiepie-archdaemon 22144050fe Update canonical Notes modules alongside their deployment files 2026-10-26 16:23:29 +00:00
pewdiepie-archdaemon e8551e9cbc Use explicit editor endpoints in backend regression fixtures 2026-10-26 16:23:29 +00:00
pewdiepie-archdaemon 3d47888559 Use explicit editor endpoints in backend regression fixtures 2026-10-26 16:23:29 +00:00
pewdiepie-archdaemon ace6be44f3 Merge current dev and refresh PR #6740 from the 7011 integration 2026-10-26 16:21:34 +00:00
pewdiepie-archdaemon 36a71886bb Merge current dev and refresh PR #6741 from the 7011 integration 2026-10-26 16:21:28 +00:00
pewdiepie-archdaemon 444b60d14e Merge current dev and refresh PR #6738 from the 7011 integration 2026-10-26 16:21:22 +00:00
pewdiepie-archdaemon 30430acfea fix(harness): ignore dotted email local parts in artifact inference 2026-10-25 17:04:43 +00:00
pewdiepie-archdaemonandClaude Opus 5.5 5fac693c1c feat(photo-editor): Ajax Image Editor client (Photoshop-parity tools)
Photoshop-parity editor client: layers, selection/masking, brushes,
smart filters, LUT import, Quick Edit, mobile gestures, workspaces,
batch operations, and the service-worker versioning (v978->v1006).

Source: vendor/photocraft (ad1cff44) photo-editor client files, merged
onto upstream/dev (a8c147b2). Conflict resolution documented in
pr_work/A_conflicts.md; editor files taken from vendor/photocraft
(upstream's editor is an earlier snapshot of the same feature).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 11:57:35 +00:00
pewdiepie-archdaemonandClaude Opus 5.5 9bdea753ae fix(harness): ship coherent vendor harness cluster
Rebuild PR C to ship the vendor/photocraft harness as a coherent unit
(vendor implementation + vendor tests) instead of a per-file ahead/behind
mix that produced broken imports and 6+ test failures.

- Flip 36 harness impl/route/test files back to vendor (the per-file
  line-set policy misclassified user-rewritten files as 'behind').
- Flip core/models.py + src/tool_approval_scopes.py to vendor: vendor's
  harness (authority.py, turn_contract.py, clean_agent_preview.py) depends
  on vendor's older approval-scope API; upstream added
  CHAT_SESSION_APPROVAL_SIGNATURE_FIELD that vendor's core/models.py lacks.
- Add src/shutdown.py (new vendor infra) required by routes/chat_routes.py.
- Keep src/agent_tools/__init__.py at upstream (editor_tools registration
  lives in PR B).

Upstream-only security divergence preserved in C_upstream_delta.patch and
flagged for integration-time reconciliation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:59:04 +00:00
pewdiepie-archdaemonandClaude Opus 5.5 8fda203d28 feat(ui): chat frontend, model picker, streaming, admin, a11y
Preview/UI work: chat renderer, streaming/think-trace, model picker
(instant-open/refresh-backoff), admin panel, a11y, gallery landing.

Source: vendor/photocraft (ad1cff44) static files, 3-way merged onto
upstream/dev (a8c147b2). Resolution policy in pr_work/D_conflicts.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:42:33 +00:00
pewdiepie-archdaemonandClaude Opus 5.5 364229f2dc feat(harness): authority, turn contract, tools, clean_agent_preview
Chat/agent harness work: request-authority model, turn contract, tool
policy/parsing/execution, clean_agent_preview streaming/thinking, ask_user
persistence, session probes, and scheduler.

Source: vendor/photocraft (ad1cff44) harness files, 3-way merged onto
upstream/dev (a8c147b2). Harness core files were independently developed
in both lineages; resolution policy documented in pr_work/C_conflicts.md
(vendor kept where ahead, upstream kept where vendor is behind; full delta
preserved in pr_work/C_upstream_delta.patch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:41:53 +00:00
419 changed files with 50682 additions and 1342 deletions
+255
View File
@@ -0,0 +1,255 @@
# Quick Edit Coverage Audit
Audit of how much of the PhotoCraft editor is reachable through **Quick Edit**
(the natural-language editor agent). Built against build **0.20.44** (HARNESS
bridge fan-out fix `4dd11826`) and client commit `e78b5a96`.
Quick Edit executes in two stages:
1. **Plan** — `static/js/editor/editor-agent.js` posts `{prompt, state,
screenshot}` to `/api/editor/agent`. HARNESS `routes/editor_agent_routes.py`
plans with the shared style guide (`src/editor_style_guide.py`) plus an LLM,
validates every step against its own `OP_CATALOG`, then executes.
2. **Execute** — only `ai_edit_image` / `generate_image` run server-side; every
other op is delivered to the page over the editor bridge (SSE) and run by the
client control surface (`window.geEditorControl.invoke`, catalog in
`static/js/galleryEditor.js`). A local fallback planner lives in
`static/js/editor/nl-edit.js`.
There are **three** catalogs that must agree:
| Catalog | File | Owner |
|---|---|---|
| Client control ops | `static/js/galleryEditor.js` | PHOTOSHOP |
| Server `OP_CATALOG` | `routes/editor_agent_routes.py` | HARNESS |
| Style guide / planner | `src/editor_style_guide.py` + `nl-edit.js` | HARNESS + PHOTOSHOP |
Legend: **C** = in client catalog · **S** = in server `OP_CATALOG` (incl.
`NEW_OP_NAMES`) · **P** = the planner/style guide emits it for some phrasing.
A capability is **usable from Quick Edit** only when the planner can emit it
(**P**) and the op exists on the side that runs it.
---
## 1. Menu bar (12 menus)
| Capability | Trigger phrasing | Op | C | S | P | Status |
|---|---|---|---|---|---|---|
| File → Import | "open this image" | `document.importImage` | ✔ | ✔ | partial | OK |
| File → Load project | "open my project" | `document.openPsd` | ✔ | ✘ | ✘ | **Server gap** |
| File → Save / Save copy / Export PSD | "save as psd" | `document.savePsd` | ✔ | ✔ | ✔ | OK |
| File → Export | "export png" | `export.png` | ✔ | ✔ | ✔ | OK |
| File → Save project | — | (project store) | n/a | n/a | ✘ | Out of scope (not an edit op) |
| Edit → Undo/Redo/History | "undo" | `history.undo` / `redo` | ✔ | ✔ | ✔ | OK |
| Edit → Free Transform | "free transform" | `transform.start` | ✔ | ✔ | ✔ | OK |
| Edit → Transform → Rotate 90/180 | "rotate this layer 90" | `layer.rotate` | ✔ | ✔ | ✔ | OK (whole image vs layer routed by the fast path) |
| Edit → Transform → Flip H/V | "flip this layer" | `layer.flip` | ✔ | ✔ | ✔ | OK (whole image vs layer routed by the fast path) |
| Image → Fill | "fill the whole image with white" | — | ✘ | ✘ | ✘ | **No op** |
| Image → Canvas Size | "make the canvas wider" | `document.resizeCanvas` | ✔ | ✔ | partial | OK |
| Image → Image Size | "resize the image to 1200px" | `document.resizeCanvas` | ✔ | ✔ | partial | OK |
| Image → Rotate 90/180 (whole image) | "rotate the whole image 90" | `document.rotate`/all-layers | ✘ | ✘ | ✘ | **No control op** |
| Image → Flip H/V (whole image) | "flip the whole canvas" | `document.flip`/all-layers | ✘ | ✘ | ✘ | **No control op** |
| Image → Mode RGB/Grayscale | "make it black and white" | `adjustments.apply` black-white | ✔ | ✔ | ✔ | OK (mode via adjustment) |
| Image → Adjustments → Invert | "invert the colours" | `adjustments.apply` invert | ✔ | ✔ | ✔ | OK (fast path colour-inverts the active layer; "invert the selection" stays Select ▸ Inverse) |
| Image → Mode CMYK/Lab, Bits 16/32 | — | — | ✘ | ✘ | ✘ | Not implemented (disabled in UI) |
| Layer → New | "add a layer" | `layers.addRaster` | ✔ | ✔ | partial | OK |
| Layer → Duplicate | "duplicate the layer" | `layers.duplicate` | ✔ | ✔ | partial | OK |
| Layer → Group | "group the layers" | `layers.group` | ✔ | ✔ | ✘ | **Server OK, planner gap** |
| Layer → Rasterize | "rasterize the text" | `layers.rasterize` | ✔ | ✔ | ✔ | OK |
| Layer → Delete | "delete the layer" | `layers.delete` | ✔ | ✔ | partial | OK |
| Layer → Merge Down | "merge down" | `layers.mergeDown` | ✔ | ✘ | ✘ | **Server gap** |
| Layer → Merge All / Flatten | "flatten the image" | `layers.flatten` | ✔ | ✘ | ✘ | **Server gap** |
| Layer → Select All | "select all layers" | (multi-select) | ✔ | ✔ | ✔ | OK (fast path selects every layer) |
| Layer → Combine (unite/subtract/…) | "combine the shapes" | `_combineSelectedShapes` | ✔ | ✔ | ✔ | OK (fast path selects the shape layers and combines) |
| Layer → Fill | "fill the layer with blue" | `selection.fill` / flood | partial | ✘ | ✘ | **Gap** |
| Layer → Layer Mask (reveal/hide/apply/invert/feather) | "add a layer mask" | `layers.addMaskFromSelection` | ✔ | ✔ | ✔ | OK |
| Layer → Opacity | "set the layer opacity to 50%" | `layers.setOpacity` | ✔ | ✔ | partial | OK (fast path sets the active layer's opacity) |
| Layer → Blend Mode | "set the blend mode to multiply" | `layers.setBlend` | ✔ | ✔ | partial | OK (fast path sets the active layer's blend mode) |
| Type → Add | "add a title" | `text.add` | ✔ | ✔ | ✔ | OK |
| Type → Character | "make the text bigger" | `text.edit` | ✔ | ✘ | ✘ | **Server gap + planner gap** |
| Type → Paragraph | "centre the text" | `text.layout` | ✔ | ✔ | partial | OK |
| Type → Warp | "warp the text" | `_rerenderTextLayer` (warp) | ✔ | ✔ | ✔ | OK |
| Select → All/Deselect/Invert | "invert the selection" | `selection.*` | ✔ | ✔ | ✔ | OK |
| Select → Reselect | "reselect" | `_reselectSelection` | ✔ | ✔ | ✔ | OK |
| Select → Transform | "transform the selection" | `transform.start` | ✔ | ✔ | partial | OK |
| Select → Refine | "refine the edge" | `selection.feather/expand` | ✔ | ✘ | ✘ | **Server gap** |
| Select → Color Range | "select the blue sky" | `selection.colorRange` | ✔ | ✔ | partial | OK |
| Select → Select and Mask | "select the subject" | `selection.subject` | ✔ | ✔ | ✔ | OK |
| Select → Save | "save the selection" | `_saveNamedSelection` | ✔ | ✔ | ✔ | OK |
| Select → Load | "load the selection as sky" | `_loadNamedSelection` | ✔ | ✔ | ✔ | OK |
| Filter → every filter (30+) | "pixelate the image" | `filters.apply` | ✔ | ✔ | ✔ | OK (fast path covers pixelate/emboss/twirl/pinch/spherize/ripple/solarize/find-edges/crystallize/noise/despeckle/unsharp + blur/sharpen/vignette) |
| Filter → Blur → Motion / Zoom | "motion blur" / "zoom blur" | `filters.apply` (blur-motion / blur-zoom) | ✔ | ✔ | ✔ | OK (fast path maps motion blur and zoom blur to their Filter-menu variants) |
| Filter → Layer effects (drop shadow, stroke, colour overlay, outer glow) | "add a drop shadow" | `layers.addStyle` | ✔ | ✔ | ✔ | OK (fast path adds drop shadow / stroke / outer glow / colour & gradient overlay; colour parsed from the prompt) |
| View → Rulers/Grid/Snap/Clear guides | "show the grid" | `#ge-view-menu` | ✔ | ✔ | ✔ | OK |
| Window → panels | — | n/a | n/a | n/a | ✘ | UI-only |
| 3D / Plugins | — | — | ✘ | ✘ | ✘ | Not implemented (disabled in UI) |
## 2. Tools
Toolbar tools are interactive, not bridge ops, so coverage is about whether the
**effect** of a tool is reachable by prompt.
| Tool | NL-reachable? | Notes |
|---|---|---|
| Move / Transform | `transform.*` | OK (transform.start/apply/cancel) |
| Hand / Zoom | — | View only |
| Crop | `document.crop` + format guard | OK |
| Text / Shape | `text.add`, `text.layout` | Shape has no add-shape op — **gap** |
| Brush / Eraser / Dodge / Burn / Smudge / Clone / Heal / Sharpen | — | Interactive painting; no NL op — **gap** (out of scope for planner) |
| Gradient | — | **No op** |
| **Paint Bucket** | `fill.flood` | **Server gap + planner gap** (op exists client-side only) |
| Eyedropper | — | UI only |
| Marquee / Lasso / Wand / Quick Select / Object Select / Pen / Path | `selection.rectangle/ellipse/polygon/subject/…` | OK for region/reference selects; lasso/pen paths have `selection.polygon` only |
| SAM / Inpaint / Rembg | `selection.subject`, `ai.removeObject`, `ai.removeBackground` | OK |
| **Pixel brush + grid** | — | UI state only; no op — **gap** (acceptable: it is a brush mode, not an edit op) |
## 3. Right-click context menu
| Item | Backing op | Reachable by prompt? |
|---|---|---|
| Brush size / preset / Pixel Brush | `state` UI | No (interactive) |
| Select All / Deselect / Inverse / Feather / Expand / Contract / Border / Smooth | `selection.*` | Yes |
| Transform Selection / Refine Edge | `transform.start`, `selection.feather` | Partial |
| Apply / Cancel Crop | `document.crop` | Yes |
| Commit / Cancel / Free Transform | `transform.apply/cancel/start` | Yes |
| Add Text Layer / Rasterize Text | `text.add`, `layers.rasterize` | Yes (rasterize OK) |
| Copy Color Hex / Swap Colors | `state.color` | OK (fast path swaps / resets the foreground & background swatches) |
| Fill Selection w/ Foreground | `selection.fill` | OK (fast path fills the selection/canvas with the foreground or background colour) |
| Cut / Copy / Paste | `selection.copy/paste` | **Gap** (no planner intent) |
| Rotate 90/180, Flip H/V | `layer.rotate/flip` | **Server+planner gap** (same as Edit menu) |
| Undo / Redo | `history.*` | Yes |
## 4. Adjustments
`adjustments.apply` / `adjustments.applyMasked` cover all adjustment types
(brightness-contrast, white-balance, shadows-highlights, vibrance, clarity,
vignette, black-white, …). The style guide emits several. **Status: OK**
(planner covers the common ones; the long tail is reachable only via explicit
wording).
## 5. Filters
`filters.apply` / `filters.applyMasked` run every filter the UI lists. The
planner only emits **sharpen**, **blur-gaussian**, and **vignette** via intents.
**Gap (planner):** no intent for noise, pixelate, stylize, distort, render,
unsharp, sharpen-edges, colour-overlay/drop-shadow/stroke.
**Gap (HARNESS):** `filters.apply`/`applyMasked` are in the server catalog, so
the fix is style-guide intents, not catalog.
## 6. Layer styles
`layers.addStyle {type, params}` exists in both catalogs. **Planner never emits
it**, so "add a drop shadow to the title", "add a stroke", "colour overlay" fail.
**Gap (planner).**
## 7. Selection ops
`selection.rectangle/ellipse/polygon/fill/delete/copy/paste/feather/expand/
contract/selectAll/deselect/invert/colorRange/subject/samText/face/sky/
background/hasMask/maskBounds/exportMask/regionLuminance`. **Status: mostly OK.**
Missing: reselect, save-selection.
## 8. Document ops
| Capability | Op | C | S | P |
|---|---|---|---|---|
| Crop | `document.crop` | ✔ | ✔ | ✔ |
| Resize canvas / image | `document.resizeCanvas` | ✔ | ✔ | partial |
| **Extend canvas** | `document.extend` | ✔ | ✘ | ✘ |
| Save PSD | `document.savePsd` | ✔ | ✔ | ✔ |
| Export layers | `document.exportLayers` | ✔ | ✘ | ✘ |
| Duplicate / Create / Switch / List | `document.*` | ✔ | ✘ | partial |
## 9. AI edit & generate modes
| Mode | Op | Notes |
|---|---|---|
| Generative fill | `ai.generativeFill` | OK |
| Remove object | `ai.removeObject` | OK |
| Harmonize | `ai.harmonize` | OK |
| Upscale | `ai.generativeUpscale` | OK |
| Generate image | `ai.generateImage` / server `generate_image` | OK |
| Expand | `ai.generativeExpand` | OK (content-bounds prefill, SW v760) |
| Remove background | `ai.removeBackground` | OK |
| Instruction edit / scene replace | server `ai_edit_image` | OK (HARNESS) |
---
## 10. Gap list
### Client-side (fix in this repo — PHOTOSHOP-owned) — **ALL FIXED**
1. ✅ **`fill.flood` not in the NL path** — added to `nl-edit.js OP_CATALOG` +
`localPlan` fill intent ("fill … with <colour>"; falls back to `selection.fill`
when a region is selected).
2. ✅ **`layer.flip` / `layer.rotate` not in the NL path** — added to
`nl-edit.js OP_CATALOG` + "this layer" intent (whole-image phrasing routes to
`document.flip`/`document.rotate`).
3. ✅ **`text.edit` not in the NL path** — added catalog entry + intent for font
size/colour ("make the text bigger/smaller", "make it red").
4. ✅ **`document.extend` not in the NL path** — added catalog entry + intent for
"extend the canvas to 16:9" (derives target size from the document).
5. ✅ **`layers.align`** — added planner intent ("align … to the centre/left/…").
6. ✅ **`layers.addStyle`** — added planner trigger ("drop shadow", "stroke",
"colour overlay").
7. ✅ **Whole-image rotate/flip has no control op** — added `document.rotate` /
`document.flip` control ops (`galleryEditor.js`) and catalog/intent entries.
8. ✅ **`selection.copy/paste` intents** — added "copy the selection"/"paste".
### Server-side (file for HARNESS in the passover)
1. `routes/editor_agent_routes.py OP_CATALOG` is missing ops the client runs:
`layer.flip`, `layer.rotate`, `text.edit`, `fill.flood`, `layers.align`,
`layers.rasterize`, `layers.mergeDown`, `layers.flatten`, `document.extend`,
`document.exportLayers`, `document.*` (list/duplicate/create/switch/openPsd),
`mask.*`, `selection.*` (polygon/feather/expand/contract/copy/paste/hasMask/
face), `transform.*` are partly present.
2. `src/editor_style_guide.py` has no intents for: layer transform
(rotate/flip active layer), whole-document rotate/flip, text editing, align,
layer styles (drop shadow/stroke/overlay), flood fill, copy/paste, noise/
pixelate/stylize/distort/render filters.
## 11. Coverage summary
Counting distinct user-facing capabilities in the toolbar + 12 menus + right-click
(~150 including the filter/effect long tail):
- **Have a client op:** ~85%
- **Client op also in server OP_CATALOG:** ~75%
- **Planner can emit for natural phrasing:** ~72% (was ~55%; client-side
planner intents for fill, layer/whole-image transform, text edit, align,
layer styles, copy/paste and extend are now implemented)
- **Usable from Quick Edit end-to-end today:** **45/45 prompts (100%)** measured
live on build **0.20.45** with `tests/e2e/photo-editor/quickedit-coverage.js`
(`/tmp/opencode/qe-coverage45/quickedit-coverage.json`). HARNESS build 0.20.45
(`4a6932a2`) added the 12 missing structural ops to the server `OP_CATALOG` +
style guide v5, so every audited prompt now plans to the exact op.
The gap was dominated by the **planner**, not by missing client functionality;
that planner gap is now closed end-to-end (30/45 on 0.20.44 -> 45/45 on 0.20.45).
## 12. Test prompts (~40)
See `docs/QUICKEDIT_PROMPTS.md` and the runner
`tests/e2e/photo-editor/quickedit-coverage.js` for per-prompt pass/fail.
### Live run (build 0.20.45) — 45/45 PASS
All 45 prompts plan to the exact expected op. HARNESS 0.20.45 routes these
structural ops server-side: `fill.flood`, `text.edit`, `layers.align`,
`layer.rotate`/`layer.flip`, `document.rotate`/`document.flip`,
`selection.copy`/`selection.paste`, `layers.flatten`, `layers.mergeDown` (plus
the previously passing set). Results:
`/tmp/opencode/qe-coverage45/quickedit-coverage.json`.
### Previous run (build 0.20.44) — 30/45 PASS
Kept for provenance. Failures were all the server planner emitting a generic
`adjustments.apply`/`transform.apply` or a wrong op; ids 1, 2, 3, 4, 8, 9, 10,
11, 12, 13, 14, 19, 20, 40, 41. All now fixed in 0.20.45.
## Provenance
Recon inventory captured from `static/js/editor/build/topbar.js`,
`static/js/editor/build/toolbar.js`, `static/js/editor/canvas-context-menu.js`,
`static/js/galleryEditor.js` (`installEditorControl`), `static/js/editor/nl-edit.js`,
`routes/editor_agent_routes.py`, and `src/editor_style_guide.py`.
@@ -112,7 +112,7 @@ export function createCardInteractions({
if (state.selectMode) {
body.querySelectorAll('.note-card').forEach(card => {
card.addEventListener('click', (e) => {
if (e.target.closest('.note-card-cb')) return; // checkbox handles itself
if (e.target.closest('.note-card-cb, a')) return; // links open without toggling selection
e.stopPropagation();
tapToEditOrSelect(card);
});
+2 -2
View File
@@ -51,7 +51,7 @@ export function createEditor({
<input type="hidden" class="note-form-due" value="${note?.due_date || ''}" />
<input type="hidden" class="note-form-repeat" value="${note?.repeat || 'none'}" />
</div>
${currentImageUrl && type !== 'draw' ? `<div class="note-form-image-wrap"><img class="note-form-image" src="${_esc(currentImageUrl)}" draggable="false" /><button class="note-form-image-rm" title="Remove">&times;</button></div>` : ''}
${currentImageUrl && type !== 'draw' ? `<div class="note-form-image-wrap"><img class="note-form-image" src="${_esc(currentImageUrl)}" alt="" draggable="false" /><button class="note-form-image-rm" title="Remove" aria-label="Remove">&times;</button></div>` : ''}
<div class="note-form-body">
${type === 'note'
? `<textarea class="note-form-content" placeholder="Take a note..." rows="4">${_esc(note?.content || '')}</textarea>`
@@ -297,7 +297,7 @@ export function createEditor({
form.querySelector('.note-form-image-wrap')?.remove();
const wrap = document.createElement('div');
wrap.className = 'note-form-image-wrap';
wrap.innerHTML = `<img class="note-form-image" draggable="false" /><button class="note-form-image-rm" title="Remove">&times;</button>`;
wrap.innerHTML = `<img class="note-form-image" alt="" draggable="false" /><button class="note-form-image-rm" title="Remove" aria-label="Remove">&times;</button>`;
// Insert AFTER the whole header (a flex-row), not after the
// title input itself : otherwise the image lands as a sibling
// of the title inside the header and flex puts them side-by-side.
+1 -1
View File
@@ -31,7 +31,7 @@ export function createText({
url = url.slice(0, -1);
}
const href = url.startsWith('www.') ? `https://${url}` : url;
return `<a href="${_attrEsc(href)}" class="note-link" target="_blank" rel="noopener noreferrer" onclick="event.stopPropagation()">${url}</a>` + (url !== m ? m.slice(url.length) : '');
return `<a href="${_attrEsc(href)}" class="note-link" target="_blank" rel="noopener noreferrer">${url}</a>` + (url !== m ? m.slice(url.length) : '');
});
}
+23 -10
View File
@@ -1185,6 +1185,9 @@ def _fixture_email_record(row: dict, uid_num: int, owner: str) -> dict:
"subject": subject,
"from": sender_name or sender_addr or sender,
"from_address": sender_addr,
"to": str(row.get("to") or headers.get("To") or ""),
"cc": str(row.get("cc") or headers.get("Cc") or ""),
"references": str(row.get("references") or headers.get("References") or ""),
"date": date_str,
"date_epoch": date_epoch,
"summary": body[:240],
@@ -1557,6 +1560,7 @@ def _fixture_update_email(uid=None, source_folder="INBOX", account=None, **updat
if not isinstance(rows, list):
return False
owner = _current_owner()
matches = []
for index, row in enumerate(rows, start=1):
if not isinstance(row, dict):
continue
@@ -1568,14 +1572,19 @@ def _fixture_update_email(uid=None, source_folder="INBOX", account=None, **updat
continue
if not _fixture_folder_matches(row.get("folder") or "INBOX", source_folder):
continue
for key, value in updates.items():
if value is None:
row.pop(key, None)
else:
row[key] = value
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return True
return False
if not _fixture_row_matches_account(_fixture_email_record(row, index, owner or row_owner), account):
continue
matches.append(row)
if len(matches) != 1:
return False
row = matches[0]
for key, value in updates.items():
if value is None:
row.pop(key, None)
else:
row[key] = value
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return True
# ── Tool implementations ──
@@ -2925,7 +2934,9 @@ def _create_email_draft_document(
def _draft_reply_to_email(uid, body, folder="INBOX", reply_all=False, account=None, title=None):
"""Create a threaded Odysseus reply draft document. Does not send."""
fixture = _fixture_email_action_target(uid=uid, folder=folder, account=account)
fixture = _fixture_read_email(uid=uid, folder=folder, account=account)
if _fixture_email_enabled() and (fixture is None or fixture.get("error")):
return fixture or {"error": "No email fixture is available for the authenticated owner"}
if fixture is not None:
sender = str(fixture.get("from_address") or fixture.get("from") or "")
_, sender_addr = email.utils.parseaddr(sender)
@@ -3178,7 +3189,9 @@ def _reply_to_email(uid, body, folder="INBOX", reply_all=False, account=None):
def _set_flag(uid, folder, flag, add=True, account=None):
"""Add or remove an IMAP flag (e.g. \\Seen, \\Answered, \\Deleted)."""
if _fixture_email_action_target(uid=uid, folder=folder, account=account) is not None:
if _fixture_email_enabled():
if _fixture_email_action_target(uid=uid, folder=folder, account=account) is None:
return False
if flag == "\\Seen":
return _fixture_update_email(uid=uid, source_folder=folder, account=account, read=bool(add))
if flag == "\\Answered":
+44
View File
@@ -571,6 +571,50 @@ async def auto_name_session(session_manager, sess):
endpoint_url = str(getattr(sess, "endpoint_url", "") or "")
model_name = str(getattr(sess, "model", "") or "")
# The spec ("Ajax") model names its own chats from the user's first
# prompt. This function only runs after the first response stream has
# settled (auto_name_session_after_stream), so titling does not
# contend with the visible answer. Thinking is disabled and the
# budget kept small so the model returns a bare title.
try:
from src.model_profiles import uses_odysseus_progressive_thinking
_is_spec_model = bool(model_name) and uses_odysseus_progressive_thinking(model_name)
except Exception:
_is_spec_model = False
if _is_spec_model and endpoint_url:
_headers = getattr(sess, "headers", None)
if isinstance(_headers, str):
try:
_headers = json.loads(_headers)
except Exception:
_headers = None
try:
title = await llm_call_async(
endpoint_url,
model_name,
[
{"role": "system", "content": "Generate a short title (3-6 words, no quotes) for a conversation that starts with this message. Reply with ONLY the title, nothing else. Do NOT include any thinking, reasoning, or explanation \u2014 just the title."},
{"role": "user", "content": first_msg},
],
temperature=0.3,
max_tokens=32,
headers=_headers or None,
timeout=20,
thinking_mode="off",
)
except Exception as e:
logger.warning("[auto-name] spec title call failed for %s: %s", sess.id, e)
title = ""
title = str(title or "").strip().strip('"\'').strip()
from src.text_helpers import strip_think
title = strip_think(title, prose=False, prompt_echo=False)
if not title or len(title) >= 80 or "\n" in title:
title = fallback_session_title(first_msg)
session_manager.update_session_name(sess.id, title)
logger.info(f"Auto-named spec session {sess.id}: {title}")
return
if (
"ttft" in model_name.lower()
or re.search(r":18\d{3}\b", endpoint_url)
+96 -10
View File
@@ -27,11 +27,13 @@ from src.llm_core import (
from src.agent_loop import (
stream_agent_loop,
_configured_model_tool_surface,
_configured_model_tool_surface_raw,
_local_media_needs_browser_render,
_looks_like_workspace_coding_request,
)
from src.agent_loop import _normalize_ody_qwen_text_artifacts
from src import agent_runs
from src import shutdown as _shutdown
from src.model_context import estimate_tokens
from src.context_compactor import (
apply_compaction_state,
@@ -2688,6 +2690,19 @@ def setup_chat_routes(
logger.info("chat→agent auto-escalation: explicit private browser workflow")
active_doc_id = form_data.get("active_doc_id", "").strip()
active_doc_state = form_data.get("active_doc_state", "").strip().casefold()
# Scoped photo_editor agent context: the Quick Edit popup (and any
# image-edit chat turn) may carry the open image-editor session id and a
# canvas snapshot so the editor tool family can drive it in-process.
editor_session = (
form_data.get("editor_session")
or form_data.get("editor_session_id")
or ""
).strip()
photo_editor_requested = (
str(form_data.get("photo_editor") or "").strip().lower()
in {"1", "true", "yes", "on"}
or bool(editor_session)
)
logger.info(
"[doc-inject] chat_mode=%s, active_doc_id=%r, active_doc_state=%r",
chat_mode, active_doc_id, active_doc_state,
@@ -3270,7 +3285,34 @@ def setup_chat_routes(
active_document=bool(active_doc), workspace=bool(workspace),
image_attachment=any(str(a.get('mime') or '').startswith('image/') for a in (ctx.preprocessed.attachment_meta or [])),
) if _use_turn_contract else frozenset()
if 'image_editing' in _turn_capabilities and ctx.preprocessed.attachment_meta:
# Scoped photo_editor family: offered ONLY for an explicit editor
# request (Quick Edit popup / editor session) or an image-edit chat
# turn carrying an image. When active the turn offers just the editor
# tools plus ask_user, never the general tool list.
_photo_editor_active = bool(_use_turn_contract) and (
photo_editor_requested
or (
"image_editing" in _turn_capabilities
and bool(ctx.preprocessed.attachment_meta)
)
)
if _photo_editor_active:
if editor_session:
editor_context = {'role': 'system', 'content':
'The image editor is open (session ' + editor_session + '). Use run_editor_command, '
'plan_edit and get_editor_screenshot to inspect and change the current canvas, and '
'ai_edit_image for model-based edits. Apply the user\'s requested edit to the open '
'editor and confirm the result with a screenshot.'}
else:
editor_context = {'role': 'system', 'content':
'The user attached an image but no image editor is open, so the editor tools cannot '
'reach the canvas. Do not call editor tools. Reply briefly telling the user to open '
'the attached image in the editor (Quick Edit) and repeat the request; the editor '
'tools will then apply it.'}
ctx.messages.insert(0, editor_context)
if foreground_policy.enabled:
getattr(ctx, 'route_messages', ctx.messages).insert(0, dict(editor_context))
elif 'image_editing' in _turn_capabilities and ctx.preprocessed.attachment_meta:
image_refs = ['odysseus://attachment/' + str(a['id']) for a in ctx.preprocessed.attachment_meta
if a.get('id') and str(a.get('mime') or '').startswith('image/')]
if image_refs:
@@ -3307,6 +3349,11 @@ def setup_chat_routes(
# pasted revision request. This only offers permitted schemas;
# it never requires or performs a document mutation.
_turn_capabilities = _turn_capabilities | {"documents"}
# Scoped photo_editor family (see above): when active the turn offers
# just the editor tools plus ask_user, never the general tool list.
if _photo_editor_active:
_turn_capabilities = frozenset({"photo_editor"})
_active_turn_capabilities = _turn_capabilities
# Same decision that prepared the turn; it only stamps the contract
# inside the agent-contract branch below.
_clean_v3_preview = _compact_preview_turn
@@ -3556,9 +3603,22 @@ def setup_chat_routes(
"document_editor": not {
"manage_documents", "create_document", "edit_document", "update_document",
}.issubset(disabled_tools),
# A photo-editing chat turn can only reach a canvas when the image
# editor is actually open. The compact runtime uses this to reply
# (open the image in the editor) instead of looping on editor tools
# that have no canvas to drive.
"photo_editor_open": bool(editor_session),
}
# Capture permission state before schema selection/reconciliation.
# Only deterministic request intent supplies grants, never inventory.
# The strict router (spec) surface picks its tools in src/spec_router.py
# AFTER authority is built, so its admission is keyed off the surface.
try:
_spec_surface = _configured_model_tool_surface_raw(
getattr(sess, "endpoint_url", ""), getattr(sess, "model", ""), _user
) == "spec"
except Exception:
_spec_surface = False
_request_authority = request_authority_for_http(
request, message, owner=_user, session_id=session, workspace=workspace,
history=_turn_history, policy=tool_policy,
@@ -3566,9 +3626,9 @@ def setup_chat_routes(
active_document=bool(active_doc),
image_attachment=any(str(a.get('mime') or '').startswith('image/')
for a in (ctx.preprocessed.attachment_meta or [])),
capabilities=({'search_browser'} if (
capabilities=(({"photo_editor"} if _photo_editor_active else set()) | ({'search_browser'} if (
_explicit_browser_intent or _external_discovery_intent
) else ()),
) else set())),
)
if exact_tool_approval is not None:
from src.agent_runtime.authority import RequestAuthority
@@ -3758,7 +3818,9 @@ def setup_chat_routes(
# personal manager; core shell/Web tools are not task
# fallbacks. Other turns retain warm and workspace tools.
extra_tools=(
frozenset()
frozenset({"ask_user"})
if _active_turn_capabilities == frozenset({"photo_editor"})
else frozenset()
if _exact_selected_native_chain or _active_turn_capabilities == frozenset({"tasks"}) or (
_active_turn_capabilities in (
frozenset({"transcription"}), frozenset({"ocr"}),
@@ -3960,7 +4022,7 @@ def setup_chat_routes(
_heartbeat_counter = 0
_last_progress = {}
_sent_avg = False
while True:
while not _shutdown.is_shutting_down():
status = research_handler.get_status(session)
if not status or status["status"] != "running":
break
@@ -4222,8 +4284,6 @@ def setup_chat_routes(
# indicator, but don't fold them into the saved
# reply (mirrors the rewrite path below).
if data.get("thinking"):
if thinking_mode == "off":
continue
thinking_response += data["delta"]
else:
full_response += data["delta"]
@@ -4667,8 +4727,6 @@ def setup_chat_routes(
# Forward them for the live indicator, but keep
# them out of the saved reply (same as chat mode).
if data.get("thinking"):
if thinking_mode == "off":
continue
thinking_response += data["delta"]
else:
full_response = _render_state.content
@@ -4852,6 +4910,25 @@ def setup_chat_routes(
_terminal_saved = True
if _saved_id:
yield f'data: {json.dumps(_render_state.message_saved(_saved_id))}\n\n'
run_post_response_tasks(
sess, session_manager, session, message, _saveable_no_tool_response,
_metrics_to_save, ctx.uprefs, memory_manager, memory_vector, webhook_manager,
incognito=incognito, compare_mode=compare_mode,
character_name=ctx.preset.character_name,
agent_rounds=_agent_rounds,
agent_tool_calls=_agent_tool_calls,
skills_manager=skills_manager,
owner=_user,
extract_skills=(
user_requested_agent
and not tool_approval_continuation
),
allow_background_extraction=_post_response_extraction_allowed(
tools_blocked=tool_policy.block_all_tool_calls,
tool_approval_continuation=tool_approval_continuation,
client_runtime_context=client_runtime_context,
),
)
yield f'data: {json.dumps(_metrics_event)}\n\n'
except json.JSONDecodeError:
yield chunk
@@ -4962,6 +5039,8 @@ def setup_chat_routes(
raises before reaching a mode-specific finally block."""
try:
async for chunk in stream_with_save():
if _shutdown.is_shutting_down():
break
yield chunk
finally:
_active_streams.pop(session, None)
@@ -5056,7 +5135,12 @@ def setup_chat_routes(
if rec is None:
if agent_runs.is_active(session_id):
return {"status": "streaming", "detached": True}
raise HTTPException(404, "No active stream for this session")
# No active stream: report an explicit idle state with HTTP 200.
# A 404 here made every session load look like a failed request in
# the browser console. The client distinguishes "no stream" by the
# body (status != "streaming"), and still tolerates a 404 from an
# older server, so this stays backward compatible.
return {"status": "idle"}
return rec
# ------------------------------------------------------------------ #
@@ -5155,6 +5239,8 @@ def setup_chat_routes(
max_tokens=0,
tools=None,
):
if _shutdown.is_shutting_down():
break
if chunk.startswith("data: ") and not chunk.startswith("data: [DONE]"):
try:
data = json.loads(chunk[6:])
+4 -4
View File
@@ -1185,7 +1185,7 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter:
async def ai_tidy_documents(request: Request) -> Dict[str, Any]:
"""Use AI to judge if documents are junk/test/accidental, then delete them.
Caches verdicts so previously-reviewed docs are skipped."""
from src.task_endpoint import resolve_task_endpoint
from src.task_endpoint import resolve_task_endpoint, task_llm_call_async
from src.endpoint_resolver import resolve_endpoint
from src.llm_core import llm_call_async
@@ -1228,13 +1228,13 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter:
+ "\n".join(doc_list)
)
response = await llm_call_async(
url, model,
response = await task_llm_call_async(
[{"role": "system", "content": "You classify documents as junk or keep. Respond only with a JSON array."},
{"role": "user", "content": prompt}],
fallback_url=url, fallback_model=model, fallback_headers=headers,
owner=user or None,
temperature=0.1,
max_tokens=200,
headers=headers,
timeout=30,
)
+15 -3
View File
@@ -17,6 +17,7 @@ from src.endpoint_resolver import resolve_endpoint
from src.auth_helpers import _auth_disabled, get_current_user
from src.owner_identity import REQUEST_SENTINEL_OWNERS
from src.constants import DEEP_RESEARCH_DIR
from src import shutdown as _shutdown
_SESSION_ID_RE = re.compile(r"^[a-zA-Z0-9-]{1,128}$")
@@ -285,11 +286,22 @@ def setup_research_routes(research_handler, session_manager=None) -> APIRouter:
async def research_status(session_id: str, request: Request):
user = _require_user(request)
_validate_session_id(session_id)
# No in-flight or persisted research for this session is a normal state
# (most sessions have none), not an error. Return HTTP 200 with an
# explicit empty status so loading a session does not log a spurious
# 404; every client treats a non-"running" status as idle anyway.
# A session whose research exists but belongs to ANOTHER user stays a
# 404, so we do not leak the existence of someone else's research.
if not _owns_in_memory(session_id, user):
raise HTTPException(404, "No research found for this session")
exists = session_id in getattr(research_handler, "_active_tasks", {})
if not exists:
exists = _find_research_path(session_id) is not None
if exists:
raise HTTPException(404, "No research found for this session")
return {"status": "none"}
status = research_handler.get_status(session_id)
if status is None:
raise HTTPException(404, "No research found for this session")
return {"status": "none"}
try:
source_state = research_handler.get_source_state(session_id)
if isinstance(source_state, str) and source_state:
@@ -657,7 +669,7 @@ def setup_research_routes(research_handler, session_manager=None) -> APIRouter:
raise HTTPException(404, "No research found for this session")
async def _generate():
last_payload = None
while True:
while not _shutdown.is_shutting_down():
status = research_handler.get_status(session_id)
if status is None:
yield f"data: {json.dumps({'status': 'not_found'})}\n\n"
+8 -5
View File
@@ -1320,7 +1320,7 @@ def setup_session_routes(
after Phase 1 — used by the "Tidy (no AI)" UI affordance so
users can clean junk without spending tokens.
"""
from src.llm_core import llm_call
from src.llm_core import llm_call, llm_call_with_fallback
from src.utility_effort import effort_for_call
user = effective_user(request)
single_user_mode = not user and _auth_disabled()
@@ -1467,7 +1467,7 @@ def setup_session_routes(
return {"status": "skipped", "reason": "No unfiled sessions to sort"}
# Pick an endpoint — prefer admin-configured task endpoint
from src.task_endpoint import resolve_task_endpoint
from src.task_endpoint import resolve_task_endpoint, resolve_task_candidates
url, model, headers = resolve_task_endpoint(owner=user)
if not url:
url, model, headers = _pick_endpoint_for_sort(owner=user)
@@ -1493,9 +1493,12 @@ def setup_session_routes(
# 16384 (was 4096): with many chats the folder JSON is large, and a
# reasoning model spends tokens thinking first — 4096 truncated the
# JSON mid-output, so it never parsed ("invalid JSON for auto-sort").
raw = llm_call(url, model, [{"role": "user", "content": prompt}],
temperature=0.3, max_tokens=16384, headers=headers, timeout=120,
reasoning_effort=effort_for_call(url, model, user))
raw = llm_call_with_fallback(
resolve_task_candidates(fallback_url=url, fallback_model=model,
fallback_headers=headers, owner=user),
[{"role": "user", "content": prompt}],
temperature=0.3, max_tokens=16384, timeout=120,
reasoning_effort=effort_for_call(url, model, user))
logger.info(f"Auto-sort raw response ({len(raw)} chars): {raw[:300]}")
# Extract JSON from response — handle markdown fences, leading text,
# reasoning-model <think> blocks, and trailing commas.
+4 -3
View File
@@ -27,6 +27,7 @@ from src.host_docker_access import (
from src.optional_deps import prepare_optional_dependency_import
from src.auth_helpers import _auth_disabled
from src import process_lifecycle
from src import shutdown as _shutdown
# POSIX-only: `pty`/`fcntl` transitively import `termios`, which does NOT exist
# on Windows, so importing them unconditionally crashed app startup there
@@ -1025,7 +1026,7 @@ async def _generate_tmux(cmd: str, request: Request):
lines_sent = 0
exit_code = None
while True:
while not _shutdown.is_shutting_down():
# Check client disconnect
if await request.is_disconnected():
# tmux keeps running — that's the whole point
@@ -1142,7 +1143,7 @@ async def _generate_win_detached(cmd: str, request: Request):
lines_sent = 0
exit_code = None
while True:
while not _shutdown.is_shutting_down():
if await request.is_disconnected():
yield f"data: {json.dumps({'stream': 'stdout', 'data': f'Disconnected. Background job {session_id} continues running.'})}\n\n"
return
@@ -1267,7 +1268,7 @@ def setup_shell_routes() -> APIRouter:
"""Read chunks, split on \\n or \\r for progress bar support."""
try:
buf = b""
while True:
while not _shutdown.is_shutting_down():
chunk = await stream.read(4096)
if not chunk:
if buf:
+37
View File
@@ -946,6 +946,43 @@ VARIABLE_NOTES: dict[str, tuple[str, str, str]] = {
"Seconds the outpainting proxy waits for the image backend before giving "
"up on a single request.",
),
"ODYSSEUS_JEFF_": ("Agent loop and tool execution", INTERNAL, "Prefix for per-job decision adapter opt-ins; each job is disabled by default."),
"ODYSSEUS_JEFF_TIMEOUT": ("Agent loop and tool execution", INTERNAL, "Timeout in seconds for a decision adapter request."),
"ODYSSEUS_JEFF_URL": ("Agent loop and tool execution", INTERNAL, "Base URL of the optional decision adapter service."),
"ODYSSEUS_PRIVATE_BROWSER_LEGACY": ("Agent loop and tool execution", INTERNAL, "Explicit opt-in to the legacy browser compatibility transport; disabled by default."),
"ODYSSEUS_SPEC_BROWSER_FALLBACK": ("Agent loop and tool execution", INTERNAL, "Optional browser routing fallback: mcp, web, or 0 to disable."),
"ODYSSEUS_SPEC_DRIVER_TOPK": ("Agent loop and tool execution", INTERNAL, "Number of router-selected tool candidates exposed in a driver round."),
"ODYSSEUS_SPEC_MODE": ("Agent loop and tool execution", INTERNAL, "Spec routing mode for explicitly configured models, including strict and driver."),
"ODYSSEUS_SPEC_ROUTER_MIN_CONF": ("Agent loop and tool execution", INTERNAL, "Minimum tool-selection confidence accepted from the router."),
"ODYSSEUS_SPEC_ROUTER_MODEL": ("Agent loop and tool execution", INTERNAL, "Decision adapter model used for tool routing."),
"ODYSSEUS_SPEC_ROUTER_SECOND": ("Agent loop and tool execution", INTERNAL, "Minimum confidence for adding a secondary tool candidate."),
"ODYSSEUS_SPEC_ROUTER_TIMEOUT": ("Agent loop and tool execution", INTERNAL, "Time budget in seconds for a router decision."),
"ODYSSEUS_SPEC_ROUTER_URL": ("Agent loop and tool execution", INTERNAL, "Base URL of the optional Spec router; an empty URL disables requests."),
"ODYSSEUS_SPEC_SUBSET_OF_BASE": ("Agent loop and tool execution", INTERNAL, "Limit Spec tool selections to the existing request inventory by default."),
"ODYSSEUS_SPEC_THINK_MIN_P": ("Agent loop and tool execution", INTERNAL, "Minimum router confidence for enabling thinking."),
"ODYSSEUS_SPEC_THINK_MODEL": ("Agent loop and tool execution", INTERNAL, "Optional thinking decision adapter model, falling back to the tool router model."),
"ODYSSEUS_SPEC_THINK_QUESTION": ("Agent loop and tool execution", INTERNAL, "Thinking classifier question format: binary or kind5."),
"ODYSSEUS_SPEC_THINK_ROUTER": ("Agent loop and tool execution", INTERNAL, "Enable router thinking decisions for explicitly configured Spec models."),
"ODYSSEUS_SPEC_TOOL_FORMAT": ("Agent loop and tool execution", INTERNAL, "Use names for compact router tool signatures, otherwise include descriptions."),
"ODYSSEUS_SPEC_TRIM_PROMPT": ("Agent loop and tool execution", INTERNAL, "Enable prompt trimming for the selected Spec tool menu."),
"ODYSSEUS_VISION_MAX_SIDE": ("Upload and media limits", USER, "Maximum pixel side for image attachments sent directly to a vision model."),
"ODYSSEUS_VISION_MODELS": ("Model routing and providers", USER, "Comma-separated model-name fragments that explicitly support inline images."),
"ODYSSEUS_VISION_PROBE": ("Model routing and providers", USER, "Allow a cached vision-capability probe against local model endpoints."),
"ODYSSEUS_SPEC_DIRECT_MODE": (
"Agent loop and tool execution", INTERNAL,
"Controls how the spec router answers high-confidence direct-answer turns; "
"either tool_choice_none (default) or empty_menu.",
),
"ODYSSEUS_SPEC_DIRECT_NOTOOLS": (
"Agent loop and tool execution", INTERNAL,
"Set to 1, true, yes or on to enable the spec router's direct-answer "
"no-tools path for high-confidence answer_directly decisions.",
),
"ODYSSEUS_SPEC_DIRECT_MIN_P": (
"Agent loop and tool execution", INTERNAL,
"Minimum confidence probability a spec-router direct-answer decision must "
"reach before the no-tools path is taken.",
),
"ODYSSEUS_GRACEFUL_SHUTDOWN_TIMEOUT": (
"Deployment and first run", INTERNAL,
"Seconds the server waits for in-flight requests and background loops to "
+198 -7
View File
@@ -15,6 +15,7 @@ import json
import logging
import os
import re
import time
from typing import Optional
from src.memory import MemoryStoreUnreadable
@@ -78,11 +79,13 @@ EXTRACT_SYSTEM_PROMPT = (
"things the assistant said, one-off tasks, opinions on the current topic.\n\n"
"Rules:\n"
"- MAX 2 facts per conversation — only the most important\n"
"- Only extract facts the USER stated or clearly implied\n"
"- Only extract facts the USER explicitly stated about themselves\n"
"- Questions, requests to inspect records, and tool/assistant output are not evidence\n"
"- Each fact must be a single short sentence (under 15 words)\n"
"- If a fact is similar to something likely already known, skip it\n"
"- If nothing durable was revealed, return []\n\n"
"Return a JSON array of objects with 'text' and 'category' fields.\n"
"Return a JSON array of objects with 'text', 'category', and 'evidence' fields. "
"Evidence must be an exact quote from a user's own factual statement.\n"
"Categories: 'identity', 'preference', 'fact', 'contact', 'project', 'goal'\n\n"
"Return ONLY valid JSON, no markdown fences."
)
@@ -213,7 +216,10 @@ def _fallback_memory_candidates(messages) -> list[dict]:
if not text:
continue
m = re.search(r"\bmy name is\s+([A-Za-z][A-Za-z0-9 .'\-]{1,50})\b", text, re.I)
m = re.search(
r"\bmy name is\s+([A-Za-z][A-Za-z0-9 '\-]{0,49}?)"
r"(?=\s+(?:and|but|please)\b|[.!?;,\n]|$)", text, re.I,
)
if m:
name = _clean_memory_value(m.group(1), 50)
if name:
@@ -259,22 +265,183 @@ def _fallback_memory_candidates(messages) -> list[dict]:
return candidates[:2]
_USER_FACT_ASSERTION = re.compile(
r"\b(?:i(?:'m| am| live| work| use| have| prefer| like| love| hate| own| study| grew up)\b"
r"|my\s+[a-z][a-z -]{0,40}\s+(?:is|are|was|works|lives)\b"
r"|we\s+(?:are|live|work|have|own)\b"
r"|our\s+[a-z][a-z -]{0,40}\s+(?:is|are|was)\b)",
re.IGNORECASE,
)
def _has_user_fact_evidence(fact: dict, messages) -> bool:
"""Require an exact user assertion before persisting an LLM-inferred memory."""
evidence = fact.get("evidence")
if not isinstance(evidence, str):
return False
evidence = re.sub(r"\s+", " ", evidence).strip()
if len(evidence.split()) < 3 or not _USER_FACT_ASSERTION.match(evidence):
return False
for message in messages:
if _message_role(message) != "user":
continue
utterance = re.sub(r"\s+", " ", _message_text(message)).strip()
position = utterance.casefold().find(evidence.casefold())
if position < 0:
continue
# Judge the clause containing the quote, so a later question does not
# erase an earlier factual statement in the same user turn.
clause_start = max(
utterance.rfind(mark, 0, position) for mark in (".", "?", "!", ";")
) + 1
clause_end = min(
[end for mark in (".", "?", "!", ";")
if (end := utterance.find(mark, position)) >= 0] or [len(utterance)]
)
clause = utterance[clause_start:clause_end].strip()
# A question about one's records is not a statement of the answer.
if utterance[clause_end:clause_end + 1] == "?" or re.match(
r"^(?:who|what|where|when|why|how|do|does|did|can|could|would|"
r"show|list|find|search|tell|summarize|open|read)\b",
clause, re.IGNORECASE,
):
continue
return True
return False
_TOKEN_RE = re.compile(r"[a-z0-9]+")
# Function words carry no distinguishing content. Dropping them before
# comparing two facts keeps punctuation and harmless rephrasing from defeating
# the duplicate check.
_STOPWORDS = frozenset(
"a an the and or but if then of to in on at for with by from as is are was "
"were be been being do does did has have had it its this that these those "
"there here user users someone somebody they them their he she his her him i "
"we you your my our me us who whom whose what when where why how also "
"currently now still about into over under again more most very can could "
"may might must will would should".split()
)
# Words that frame a name/username statement; excluded when reading the value
# so the actual name tokens can be compared.
_NAME_TEMPLATE_WORDS = frozenset(
"name names named called call appears appear seems seem the user users his "
"her their it is are was were be been being username usernames login "
"account handle".split()
)
_NAME_KEYWORDS = frozenset({"name", "named", "called"})
_USERNAME_KEYWORDS = frozenset({"username", "login"})
def _content_tokens(text: str) -> set:
"""Lowercased content tokens with punctuation and stopwords removed."""
toks = _TOKEN_RE.findall((text or "").lower())
return {t for t in toks if t not in _STOPWORDS and len(t) >= 2}
def _name_slot(text: str):
"""Return (slot, value_tokens) when text states a name/username, else None.
Tokens are scanned so "username" is never mistaken for "name", and the
first keyword decides the slot (a sentence about a server *named* X that
also mentions a *username* Y is a 'name' fact, not a username fact)."""
words = _TOKEN_RE.findall((text or "").lower())
slot = None
for w in words:
if w in _NAME_KEYWORDS:
slot = "name"
break
if w in _USERNAME_KEYWORDS:
slot = "username"
break
if not slot:
return None
value = {
w for w in words
if w not in _NAME_TEMPLATE_WORDS and w not in _STOPWORDS and len(w) >= 2
}
return (slot, value) if value else None
def _name_slot_tokens(text: str):
slot = _name_slot(text)
return slot[1] if slot else None
def _name_vals_close(a: set, b: set) -> bool:
"""True when two name values state the same name: identical, or one is a
strict refinement of the other where the larger value is a clean name
(<=4 alphabetic tokens). Guards against merging a username into a fact
like 'a server named Odysseus ... with username pewds'."""
if a == b:
return True
if not a or not b:
return False
bigger = a if len(a) >= len(b) else b
clean = len(bigger) <= 4 and all(t.isalpha() for t in bigger)
return clean and (a <= b or b <= a)
def _is_text_duplicate(new_text: str, existing: list, threshold: float = 0.6) -> bool:
"""Check if new_text is too similar to any existing memory (Jaccard similarity)."""
new_tokens = set(new_text.lower().split())
"""Check if new_text states the same fact as an existing memory.
Three tests, cheapest first: symmetric Jaccard over content tokens,
containment (one fact is a strict refinement of the other), and a
name/username-slot match. The naive whole-string comparison this replaces
kept punctuation (so "Alex." != "alex") and missed short-vs-full names
("Felix" vs "FELIX ARVID ULF KJELLBERG" scored 0.43).
"""
new_tokens = _content_tokens(new_text)
if not new_tokens:
return False
new_slot = _name_slot(new_text)
for entry in _memory_dicts(existing):
old_tokens = set(entry.get("text", "").lower().split())
old_text = entry.get("text", "")
old_tokens = _content_tokens(old_text)
if not old_tokens:
continue
intersection = new_tokens & old_tokens
if not intersection:
continue
union = new_tokens | old_tokens
if len(intersection) / len(union) >= threshold:
return True
# Containment: one fact is a strict refinement of the other. Guard on
# the shorter side so two-token facts ("Likes Python") are not merged
# into longer sentences that merely start the same way.
if len(intersection) >= 3 and len(intersection) / min(len(new_tokens), len(old_tokens)) >= 0.85:
return True
# Name slot: both state the same kind of name and the values match
# (short vs full name, or the same name behind different phrasing).
old_slot = _name_slot(old_text)
if new_slot and old_slot and new_slot[0] == old_slot[0]:
if _name_vals_close(new_slot[1], old_slot[1]):
return True
return False
def _name_enrichment_target(new_text: str, existing: list):
"""Return an existing entry whose name value is a strict subset of the
new fact's, so the fuller name replaces it in place; else None."""
ns = _name_slot(new_text)
if not ns:
return None
slot, new_val = ns
best = None
for entry in _memory_dicts(existing):
old_slot = _name_slot(entry.get("text", ""))
if not old_slot or old_slot[0] != slot:
continue
old_val = old_slot[1]
if old_val < new_val and _name_vals_close(old_val, new_val) and len(new_val) <= 4 and all(t.isalpha() for t in new_val):
if best is None or len(entry.get("text", "")) < len(best.get("text", "")):
best = entry
return best
def _parse_extraction_json(raw: str) -> list:
"""Parse the extraction LLM's reply into a list of facts, tolerating
reasoning-model noise.
@@ -420,8 +587,13 @@ async def extract_and_store(
if not isinstance(facts, list):
facts = []
# The extraction model sees assistant/tool text and can mistake a
# failed lookup or a one-off request for a durable personal fact.
# Only its claims with a quoted user assertion may enter memory.
facts = [fact for fact in facts if isinstance(fact, dict)
and _has_user_fact_evidence(fact, stripped_recent)]
if fallback_facts:
facts = list(facts) + fallback_facts
facts.extend(fallback_facts)
if not facts:
logger.info("Auto memory extraction ran: 0 candidates")
@@ -483,6 +655,25 @@ async def extract_and_store(
# Text dedup fallback: exact match + fuzzy similarity
user_existing = [e for e in existing if e.get("owner") == _owner or e.get("owner") is None] if _owner else existing
# Name enrichment: if an existing name fact is a strict prefix of
# this more complete one, upgrade it in place instead of adding a
# near-duplicate ("name is Felix" -> "name is Felix Arvid Ulf
# Kjellberg"). The vector store upserts by id, so re-adding is safe.
_enrich = _name_enrichment_target(fact_text, user_existing)
if _enrich is not None:
_enrich["text"] = fact_text
_enrich["timestamp"] = int(time.time())
if category:
_enrich["category"] = category
if memory_vector and memory_vector.healthy:
try:
memory_vector.add(_enrich["id"], fact_text)
except Exception as e:
logger.warning(f"Memory vector update failed for {_enrich['id']}: {e}")
added += 1
continue
if memory_manager.find_duplicates(fact_text, user_existing):
continue
# Fuzzy text similarity check (catches rephrased duplicates when vector index is unavailable)
+4 -2
View File
@@ -240,11 +240,13 @@ def _artifact_match_is_callable(instruction: str, match: re.Match[str], path: st
def _artifact_match_is_email_host(instruction: str, match: re.Match[str]) -> bool:
"""Reject the domain portion of an email address as an output path."""
"""Reject either dotted portion of an email address as an output path."""
start = match.start("path")
prefix = instruction[max(0, start - 80):start]
return bool(re.search(r"[A-Za-z0-9_.+-]+@$", prefix))
return instruction[match.end("path"):].startswith("@") or bool(
re.search(r"[A-Za-z0-9_.+-]+@$", prefix)
)
def _workspace_path_identity(value: str) -> str:
+354 -17
View File
@@ -162,7 +162,7 @@ def _resolved_tool_call_id(
logger = logging.getLogger(__name__)
_MODEL_TOOL_SURFACES = {"none", "compact", "full"}
_MODEL_TOOL_SURFACES = {"none", "compact", "full", "spec"}
_ROUTE_THINKING_MODES = {"auto", "on", "off"}
_NO_THINKING_COMPACT_DOMAINS = {
"email",
@@ -8472,7 +8472,7 @@ def _agent_route_tool_mode(
return is_api_model, is_ollama_native, ollama_openai_compat
def _configured_model_tool_surface(
def _configured_model_tool_surface_raw(
endpoint_url: str,
model: str,
owner: Optional[str] = None,
@@ -8561,6 +8561,19 @@ _ADMIN_KEYWORDS = [
"note", "notes", "todo", "todos", "reminder", "reminders",
]
def _configured_model_tool_surface(
endpoint_url: str,
model: str,
owner: Optional[str] = None,
headers: Optional[Dict] = None,
endpoint_id: Optional[str] = None,
) -> str:
"""Tool surface as the harness sees it: Ajax Spec runs the compact runtime
(same dispatch, prompts, completions); only Spec hooks read the raw mode."""
value = _configured_model_tool_surface_raw(endpoint_url, model, owner, headers=headers, endpoint_id=endpoint_id)
return "compact" if value == "spec" else value
def _detect_admin_intent(messages: List[Dict]) -> bool:
"""Check if the last user message suggests admin/management tool usage."""
for msg in reversed(messages):
@@ -13565,6 +13578,20 @@ def _ody_qwen_terminal_tool_summary(tool_event: dict[str, Any], user_text: str =
"""Return a deterministic user-facing answer for tools we can render safely."""
tool_name = _resolved_tool_event_name(tool_event)
output = str(tool_event.get("output") or "")
if tool_name in {
"mcp__email__list_email_accounts", "mcp__email__list_emails",
"mcp__email__search_emails", "mcp__email__read_email",
} and output.lstrip().startswith("{"):
# The external email bridge wraps stdout in a JSON result. Render its
# successful read payload, never the wrapper or a failed result.
try:
email_result = json.loads(output)
except (TypeError, ValueError):
email_result = None
if isinstance(email_result, dict) and isinstance(email_result.get("stdout"), str):
if email_result.get("exit_code") not in (None, 0) or email_result.get("error"):
return ""
output = email_result["stdout"]
command = str(tool_event.get("command") or "")
action = ""
try:
@@ -21019,9 +21046,142 @@ def _blocks_before_inference(turn_contract) -> bool:
)
def _spec_unavailable_reply(unavailable) -> str:
blocked = set(unavailable or ())
if blocked & (set(WEB_TOOL_NAMES) | {"private_browser", "youtube_tool"}):
return ("Web or browser access is unavailable for this chat. Enable Web search "
"in the chat controls, if available, and ask me to check again. "
"I have not opened the page or verified its contents.")
return ("The tool needed for this request is unavailable in this chat. "
"Enable the required capability, if available, and try again. "
"I have not performed the requested lookup or action.")
from src.agent_runtime.authority import MISSING_AUTHORITY, active_request_authority, with_request_authority
def _spec_router_contract(turn_contract, messages, disabled_tools, endpoint_url, model, owner, headers,
tool_policy=None):
"""Ajax Spec: return a copy of the turn contract whose offered tools are the
router's picks (plus ask_user/update_plan), or the contract unchanged.
Runs before any runtime dispatch so the compact preview runtime and the
main loop both serve the router's set; only the offered tools change.
"""
if (turn_contract is None
or getattr(turn_contract, "routing_experiment", "") in {"spec-router", "spec-policy-denied"}
or (tool_policy is not None and tool_policy.block_all_tool_calls)):
return turn_contract
try:
if _configured_model_tool_surface_raw(endpoint_url, model, owner, headers=headers) != "spec":
return turn_contract
except Exception:
return turn_contract
try:
from src.spec_router import spec_route_tools as _spec_route_tools_early
from src.turn_contract import _ACTIVE_CONTRACT as _spec_active_contract
disabled = set(disabled_tools or ())
picks, decided = _spec_route_tools_early(
_extract_last_user_message(messages), FUNCTION_TOOL_SCHEMAS, set(), messages, return_decision=True)
from src.spec_router import LAST_DECISIONS as _spec_decisions
_spec_choice = (_spec_decisions[-1] if _spec_decisions else {}).get("choice")
_spec_direct = (os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict"
and decided and _spec_choice == "answer_directly")
try:
_mgr = get_mcp_manager()
mcp_schemas = _mgr.get_all_openai_schemas(_load_mcp_disabled_map()) if _mgr else []
except Exception:
mcp_schemas = []
mcp_names = {(sc.get("function") or {}).get("name") for sc in mcp_schemas}
if _spec_choice == "ask_user":
# ask_user = a tool is needed but a detail may be missing: offer Spec's top tool too, so the model
# can act when the detail is there or ask when it is not.
_top = ((_spec_decisions[-1] if _spec_decisions else {}).get("top") or [])
if _top:
picks = set(picks) | {_top[0][0]}
picks = {(f"mcp__email__{n}" if f"mcp__email__{n}" in mcp_names else n) for n in picks}
strict = os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict"
base_offered = set(turn_contract.offered)
subset_of_base = os.getenv("ODYSSEUS_SPEC_SUBSET_OF_BASE", "1").strip().lower() not in {"0", "false", "no", "off"}
# The router sees the full catalog, while this request's policy may
# deny a tool (for example, a browser turn with Web access switched
# off). Preserve that conflict as an unavailable contract. Keeping the
# old empty menu instead lets the model invent a tool result in prose.
_top = ((_spec_decisions[-1] if _spec_decisions else {}).get("top") or [])
_primary = str(_top[0][0]) if _spec_choice and str(_spec_choice).startswith("t") and _top else ""
if _primary and f"mcp__email__{_primary}" in mcp_names:
_primary = f"mcp__email__{_primary}"
# `executable` belongs to the base contract. In subset=0, Spec may
# legitimately add a policy-permitted tool that the base inventory did
# not include. Only an explicit request-policy denial blocks the pick.
def _denied(name):
return (name in disabled
or (tool_policy is not None and (
tool_policy.blocks(name)
or (tool_policy.disable_mcp and name.startswith("mcp__")))))
_unavailable_pick = ""
if _primary in picks and _denied(_primary):
_unavailable_pick = _primary
elif picks and all(_denied(name) for name in picks):
_unavailable_pick = sorted(picks)[0]
if _unavailable_pick:
blocked = replace(
turn_contract, required=frozenset(), offered=frozenset(),
unavailable=frozenset({_unavailable_pick}), schema_json=(),
required_read_operation=None, routing_experiment="spec-policy-denied",
)
_spec_active_contract.set(blocked)
logger.info("[spec-harness] router pick %s unavailable under request policy", _unavailable_pick)
return blocked
want = set(picks) - disabled
# Always-on basics only when the base turn offers them, so the Spec
# arm never offers a tool the base arm would not.
if not _spec_direct:
want |= {"ask_user", "update_plan"} & base_offered
if not (strict and decided):
want |= base_offered
if subset_of_base:
# A/B control: Spec offered set is a subset of the base offered set
# (measures narrowing only). Empty intersection keeps the base set.
want &= base_offered
if not want:
logger.info("[spec-harness] router picks %s outside base offered %s; base contract kept",
sorted(picks), sorted(base_offered))
return turn_contract
offer = want if strict else (want & set(turn_contract.executable))
by_name = {}
for sc in list(FUNCTION_TOOL_SCHEMAS) + list(mcp_schemas):
nm = (sc.get("function") or {}).get("name")
if nm in offer and nm not in by_name:
by_name[nm] = sc
for sc in turn_contract.schemas():
nm = (sc.get("function") or {}).get("name")
if nm in offer:
by_name[nm] = sc
if not by_name and not _spec_direct:
logger.info("[spec-harness] router picks %s not executable this turn; contract kept", sorted(picks))
return turn_contract
# Keep the contract's required tools and required read whenever they
# are still offered: harness completion logic keys on them (e.g. a
# calendar list is a read, not an effect that may end with "Done.").
_rro = getattr(turn_contract, "required_read_operation", None)
_keep_rro = _rro if (_rro is not None and getattr(_rro, "tool", None) in by_name) else None
new = replace(
turn_contract, required=frozenset(n for n in (turn_contract.required or ()) if n in by_name),
offered=frozenset(by_name),
executable=frozenset(set(turn_contract.executable) | set(by_name)),
schema_json=tuple(json.dumps(by_name[n], ensure_ascii=False, sort_keys=True) for n in sorted(by_name)),
unavailable=(frozenset() if os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict" else turn_contract.unavailable), required_read_operation=_keep_rro, routing_experiment="spec-router")
_spec_active_contract.set(new)
logger.info("[spec-harness] contract replaced by router: offered=%s (was %s, decided=%s)",
sorted(by_name), sorted(turn_contract.offered), decided)
return new
except Exception as exc:
logger.warning("[spec-harness] router contract replacement failed open: %s", exc)
return turn_contract
@with_request_authority
@with_turn_contract
@with_teacher_takeover
@@ -21099,6 +21259,36 @@ async def stream_agent_loop(
set(tool_policy.all_disabled_names()) if tool_policy else set()
))
# Ajax Spec driver: the Spec router picks every step (src/spec_driver.py).
if (os.getenv("ODYSSEUS_SPEC_MODE", "").strip().lower() == "driver"
and not (tool_policy and tool_policy.block_all_tool_calls)
and _configured_model_tool_surface_raw(endpoint_url, model, owner, headers=headers) == "spec"):
from src.spec_driver import stream_spec_turn
async for chunk in stream_spec_turn(
endpoint_url=endpoint_url, model=model, messages=messages, headers=headers,
session_id=session_id, owner=owner, disabled_tools=disabled_tools,
tool_policy=tool_policy, workspace=workspace, active_document=active_document,
client_runtime_context=client_runtime_context,
external_untrusted_context_seen=external_untrusted_context_seen,
max_tokens=max(1024, min(int(max_tokens or 1024), 4096)), max_rounds=8,
temperature=0.0, request_authority=request_authority,
):
yield chunk
return
turn_contract = _spec_router_contract(
turn_contract, messages, disabled_tools, endpoint_url, model, owner, headers,
tool_policy=tool_policy)
if (turn_contract is not None
and getattr(turn_contract, "routing_experiment", "") == "spec-policy-denied"):
# A selected but disallowed tool is a policy outcome, not an invitation
# to generate an ungrounded answer with an empty tool menu.
reply = _spec_unavailable_reply(turn_contract.unavailable)
yield 'data: ' + json.dumps({"type": "turn_contract", **turn_contract.audit()}) + '\n\n'
yield 'data: ' + json.dumps({"delta": reply}) + '\n\n'
yield 'data: [DONE]\n\n'
return
if is_compact_preview_contract(turn_contract):
from src.clean_agent_preview import stream_preview
async for chunk in stream_preview(
@@ -21124,9 +21314,26 @@ async def stream_agent_loop(
yield chunk
return
_spec_turn = False
try:
_spec_turn = _configured_model_tool_surface_raw(endpoint_url, model, owner, headers=headers) == "spec"
except Exception:
_spec_turn = False
if _spec_turn and turn_contract is not None and getattr(turn_contract, "routing_experiment", "") != "spec-router":
# Ajax Spec: the router, not the regex turn contract, decides the tools.
# Drop the contract here and in the dispatcher's context so neither the
# route build nor execute_tool_block enforces its offered set.
logger.info("[spec-harness] dropping turn contract on spec turn: offered=%s unavailable=%s",
sorted(turn_contract.offered), sorted(turn_contract.unavailable))
turn_contract = None
try:
from src.turn_contract import _ACTIVE_CONTRACT as _spec_active_contract
_spec_active_contract.set(None)
except Exception as _exc:
logger.warning("[spec-harness] could not clear active turn contract: %s", _exc)
if turn_contract is not None:
yield 'data: ' + json.dumps({"type": "turn_contract", **turn_contract.audit()}) + '\n\n'
if _blocks_before_inference(turn_contract):
if not _spec_turn and _blocks_before_inference(turn_contract):
unavailable = ", ".join(sorted(turn_contract.unavailable))
clarification = (
"I can’t perform this request with the currently permitted tools "
@@ -24126,6 +24333,15 @@ async def stream_agent_loop(
headers=candidate_headers,
endpoint_id=(route_descriptor or {}).get("endpoint_id"),
)
# "spec" = compact tools plus a small-model router; the harness-facing
# surface already reads "compact", so detect spec from the raw mode.
try:
_spec_surface = _configured_model_tool_surface_raw(
candidate_url, candidate_model, owner, headers=candidate_headers,
endpoint_id=(route_descriptor or {}).get("endpoint_id")) == "spec"
except Exception:
_spec_surface = False
_spec_offered = None
textual_tools = (
force_textual_tool_transport
or force_textual_tools
@@ -24159,6 +24375,57 @@ async def stream_agent_loop(
_last_user,
_intent_domains,
)
if _spec_surface:
from src.spec_router import spec_route_tools as _spec_route_tools
if turn_contract is not None and getattr(turn_contract, "routing_experiment", "") == "spec-router":
_spec_added, _spec_decided = set(turn_contract.offered) - {"ask_user", "update_plan"}, True
else:
_spec_added, _spec_decided = _spec_route_tools(
_last_user,
FUNCTION_TOOL_SCHEMAS,
disabled_tools,
compacted_source,
return_decision=True,
)
_spec_added = _spec_added - set(disabled_tools)
# The router catalog uses the legacy native email names; the
# live tools are the MCP ones, and the legacy alias schemas are
# dropped when the MCP server is connected. Map picks over.
try:
from src.tool_utils import get_mcp_manager as _spec_mcp_mgr
_mgr = _spec_mcp_mgr()
_mcp_names = {
(schema.get("function") or {}).get("name")
for schema in (_mgr.get_all_openai_schemas(_load_mcp_disabled_map()) if _mgr else [])
}
except Exception:
_mcp_names = set()
_spec_added = {
(f"mcp__email__{name}" if f"mcp__email__{name}" in _mcp_names else name)
for name in _spec_added
}
_spec_mode = os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower()
_compact_before = set(route_tools)
if _spec_mode == "strict" and _spec_decided:
# The router decides which tools are injected: its pick(s),
# tools already used in this chat, and the always-on basics.
_spec_strict = (_spec_added | {"ask_user", "update_plan"}) - set(disabled_tools)
if _spec_strict:
route_tools = _spec_strict
_spec_offered = frozenset(route_tools)
else:
logger.info("[spec-harness] strict set empty after disabled-tool filter; keeping compact set")
route_tools = set(route_tools) | _spec_added
else:
route_tools = set(route_tools) | _spec_added
logger.info("[spec-debug] disabled_tools (%d): %s | policy block_all=%s disable_mcp=%s",
len(set(disabled_tools)), sorted(set(disabled_tools))[:80],
getattr(tool_policy, "block_all_tool_calls", None), getattr(tool_policy, "disable_mcp", None))
logger.info(
"[spec-harness] mode=%s decided=%s compact=%s final=%s",
_spec_mode, _spec_decided, sorted(_compact_before), sorted(route_tools),
)
# The compact router only receives user text, while native task
# inputs may be declared out-of-band by the runner. Reapply that
# concrete input contract after compaction so an implicit video
@@ -24199,7 +24466,7 @@ async def stream_agent_loop(
_irrelevant_local_media_web_tools.add("private_browser")
route_tools.difference_update(_irrelevant_local_media_web_tools)
if turn_contract is not None and tool_surface != "full":
route_tools = set(turn_contract.offered)
route_tools = set(_spec_offered) if _spec_offered else set(turn_contract.offered)
if prompt_compact:
route_tools.update(
_blocked_network_recovery_tools(tool_events)
@@ -24299,7 +24566,7 @@ async def stream_agent_loop(
disabled_tools,
needs_admin=_needs_admin,
relevant_tools=prompt_route_tools,
preserve_conversation=turn_contract is not None,
preserve_conversation=(turn_contract is not None) or _spec_surface,
mcp_disabled_map=_mcp_disabled_map,
compact=prompt_compact,
owner=owner,
@@ -24511,6 +24778,13 @@ async def stream_agent_loop(
_prepend_agent_directive(route_messages, build_active_plan_note(approved_plan))
if guide_only:
_prepend_agent_directive(route_messages, GUIDE_ONLY_DIRECTIVE)
if _spec_offered and os.getenv("ODYSSEUS_SPEC_TRIM_PROMPT", "1") != "0":
from src.spec_router import trim_system_prompt as _spec_trim
route_messages = _spec_trim(route_messages, _spec_offered)
from src.spec_router import drop_skills_index as _spec_drop_skills
route_messages = _spec_drop_skills(route_messages, _spec_offered)
return {
"messages": route_messages,
"mcp_schemas": route_mcp_schemas,
@@ -24519,6 +24793,8 @@ async def stream_agent_loop(
"is_ollama_native": is_native_ollama,
"ollama_openai_compat": is_ollama_compat,
"tool_surface": tool_surface,
"spec_offered": _spec_offered,
"spec_surface": _spec_surface,
"ody_qwen_finetune_model": is_ody,
"qwen38_tool_router": _is_qwen38_tool_router(candidate_model) and not _full_inventory_mode,
"ody_doc_finetune_mode": doc_mode,
@@ -25076,6 +25352,24 @@ async def stream_agent_loop(
if (schema.get("function", {}).get("name") or schema.get("name"))
not in disabled_tools
]
_spec_names = route_state.get("spec_offered")
if _spec_names:
# Ajax Spec: the router, not the turn contract, decides which
# tools are injected for this turn.
contract_schemas = [
schema for schema in contract_schemas
if (schema.get("function", {}).get("name") or schema.get("name"))
in _spec_names
]
_have = {
(schema.get("function", {}).get("name") or schema.get("name"))
for schema in contract_schemas
}
contract_schemas += [
schema for schema in list(FUNCTION_TOOL_SCHEMAS) + list(route_mcp_schemas)
if schema.get("function", {}).get("name") in (set(_spec_names) - _have)
and schema.get("function", {}).get("name") not in disabled_tools
]
return _filter_route_tool_schemas(_apply_tool_surface_to_schemas(contract_schemas, tool_surface))
if route_state["is_api_model"]:
if tool_surface == "full":
@@ -25137,15 +25431,18 @@ async def stream_agent_loop(
and schema.get("name") not in disabled_tools
]
if _pure_web_turn and tool_surface != "full":
allowed = _web_only_route_tools(_last_user, disabled_tools)
schemas = [
schema for schema in schemas
if (
schema.get("function", {}).get("name")
or schema.get("name")
) in allowed
or schema.get("function", {}).get("name") in external_names
]
strict_spec = (route_state.get("spec_surface") and
os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict")
if not strict_spec:
allowed = _web_only_route_tools(_last_user, disabled_tools)
schemas = [
schema for schema in schemas
if (
schema.get("function", {}).get("name")
or schema.get("name")
) in allowed
or schema.get("function", {}).get("name") in external_names
]
schemas = _drop_legacy_email_alias_schemas_when_mcp_available(schemas)
schemas = _apply_tool_surface_to_schemas(schemas, tool_surface)
if (
@@ -25997,6 +26294,8 @@ async def stream_agent_loop(
"is_ollama_native": _is_ollama_native,
"ollama_openai_compat": _ollama_openai_compat,
"tool_surface": _route_state.get("tool_surface", ""),
"spec_offered": _route_state.get("spec_offered"),
"spec_surface": _route_state.get("spec_surface"),
"ody_qwen_finetune_model": _ody_qwen_finetune_model,
"qwen38_tool_router": _qwen38_tool_router,
"ody_doc_finetune_mode": _ody_doc_finetune_mode,
@@ -26012,10 +26311,19 @@ async def stream_agent_loop(
_active_route_state["request_messages"] = _initial_route_request_messages
all_tool_schemas = _tool_schemas_for_route(_active_route_state)
if turn_contract is not None:
_relevant_tools = set(turn_contract.offered)
_relevant_tools = (
set(_route_state.get("spec_offered"))
if _route_state.get("spec_offered")
else set(turn_contract.offered)
)
agent_stream_timeout = int(get_setting("agent_stream_timeout_seconds", 300) or 300)
_tool_names_sent = [t.get("function", {}).get("name") for t in (all_tool_schemas or []) if t.get("function")]
if round_num == 1:
try:
logger.info("[spec-debug] prompt composition (chars): %s", [(m.get("role"), len(str(m.get("content") or "")), (m.get("metadata") or {}).get("source"), str(m.get("content") or "")[:40].replace("\n", " ")) for m in messages])
except Exception:
pass
logger.info(f"[agent-debug] round={round_num} model={model} _is_api_model={_is_api_model} tools_sent={len(_tool_names_sent)} tool_names={_tool_names_sent} relevant_tools={sorted(_relevant_tools)[:50] if _relevant_tools else 'ALL'}")
_routing_intentional_exclusions = set(disabled_tools)
if (
@@ -27605,7 +27913,11 @@ async def stream_agent_loop(
),
active_document=active_document,
last_user=_last_user,
offered_tool_names=(set(turn_contract.offered) if turn_contract is not None else set(_tool_names_sent)),
offered_tool_names=(
set(turn_contract.offered)
if turn_contract is not None and not _active_route_state.get("spec_offered")
else set(_tool_names_sent)
),
recover_unoffered_tool_names=_recover_unoffered_local_tools,
passthrough_tool_names={
schema["function"]["name"]
@@ -32169,6 +32481,29 @@ async def stream_agent_loop(
budget_hit = False
local_network_budget_hit = False
local_inspection_budget_hit = False
if _active_route_state.get("spec_offered") and os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict" and tool_blocks and not used_native and _is_api_model:
# Ajax Spec with a native-API model: a round without a native call
# carries only harness-synthesized recovery blocks. Drop them all.
logger.info("[spec-harness] dropped %d synthesized tool block(s) (no native call): %s",
len(tool_blocks), [b.tool_type for b in tool_blocks])
tool_blocks = []; converted_calls = []
if (
_active_route_state.get("spec_offered") and os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict" and used_native and tool_blocks
and len(converted_calls) == len(tool_blocks)
):
# Ajax Spec: only the model's own native calls run; harness-
# synthesized recovery blocks (no native call) are dropped. When
# converted_calls was reset (singleton collapse) keep every block.
_spec_keep = [
i for i in range(len(tool_blocks))
if i < len(converted_calls) and converted_calls[i] is not None
]
if len(_spec_keep) != len(tool_blocks):
logger.info("[spec-harness] dropped %d synthesized tool block(s): %s",
len(tool_blocks) - len(_spec_keep),
[tool_blocks[i].tool_type for i in range(len(tool_blocks)) if i not in _spec_keep])
tool_blocks = [tool_blocks[i] for i in _spec_keep]
converted_calls = [converted_calls[i] for i in _spec_keep]
for i, block in enumerate(tool_blocks):
native_call = converted_calls[i] if i < len(converted_calls) else None
tool_call_id = _resolved_tool_call_id(
@@ -33463,7 +33798,8 @@ async def stream_agent_loop(
),
}
if (
(_qwen38_tool_router or _full_inventory_mode) and (_pure_web_turn or _contextual_public_web_followup)
not (_active_route_state.get("spec_offered") and os.getenv("ODYSSEUS_SPEC_MODE", "strict").strip().lower() == "strict" and block.tool_type == "private_browser")
and (_qwen38_tool_router or _full_inventory_mode) and (_pure_web_turn or _contextual_public_web_followup)
and not _artifact_creation_requested
and (block.tool_type == "web_search" or _web_execution_budget.searches)
and not _web_execution_budget.admit(
@@ -33589,6 +33925,7 @@ async def stream_agent_loop(
"mutation_epoch": _workspace_mutation_epoch,
"error": _failure_text[:600],
}
logger.info("[spec-debug] tool failure text: %s", _failure_text[:400])
logger.info(
"[agent] recorded failed call %s in round %s at mutation epoch %s",
_call_signature,
+12
View File
@@ -230,6 +230,18 @@ def classify(capture: DispatchCapture) -> dict[str, Any] | None:
if capture.backend is not None:
from src.agent_runtime.resources import ExternalResource
if isinstance(capture.backend.resource, ExternalResource):
# A read through an external backend is still a read. The tool
# capability registry is sealed by the dispatcher, and unknown or
# mixed-effect calls continue to receive an external effect claim.
if all(bound is None for bound in (capture.browser, capture.filesystem,
capture.process, capture.owned)):
from src.tool_capabilities import ToolEffect, capabilities_for_action
capabilities = capabilities_for_action(capture.backend.transport_tool,
capture.backend.exact_input)
reads = frozenset({ToolEffect.READ_PUBLIC, ToolEffect.READ_WORKSPACE,
ToolEffect.READ_PRIVATE, ToolEffect.BROKERED_NETWORK_READ})
if capabilities.known and capabilities.effects and capabilities.effects <= reads:
return None
external = True
impact = (*impact, resource_ref(capture.backend.resource, "backend"))
return {"impact_scope": impact, "dependencies": dependencies, "obligations": obligations, "external": external}
File diff suppressed because it is too large Load Diff
+104
View File
@@ -2465,6 +2465,100 @@ async def action_ping_notes(owner: str, **kwargs) -> Tuple[str, bool]:
return str(e), False
async def _spec_triage_email_urgency(item: dict, *, triage_version: int) -> dict | None:
"""Classify one email's urgency with the trained jeff ``triage`` adapter.
Returns an email-urgency verdict (same shape as the LLM path) or None when
the per-job flag is off or the adapter is unavailable, so the caller falls
through to the LLM candidate chain. Only the ``urgency`` question is sent:
jeff scores each question in its own forward pass, and that is the question
this adapter was trained on.
"""
from src.jeff_decision import jeff_job_enabled, jeff_systemone, score_value
if not jeff_job_enabled("EMAIL_URGENCY"):
return None
message = f"Subject: {item.get('subject','')}\n\n{item.get('body','')}".strip()
if not message:
return None
answers = await jeff_systemone(
"triage",
{"channel": "email", "message": message[:8000]},
{"urgency": {
"type": "score",
"instructions": "How urgently does this need a response?",
"criteria": [
"No action needed",
"Can wait a few days",
"Handle within a day",
"Handle within hours",
"Handle immediately",
],
}},
)
if not answers:
return None
exp = score_value(answers.get("urgency"))
if exp is None:
return None
# Adapter's 0-4 urgency scale -> the app's 0-3 score.
score = max(0, min(3, int(round(exp))))
reason = "triage adapter"
# Same high-precision correction the prompt path applies: a person waiting
# in person is always urgent, whatever the model thinks.
blob = f"{item.get('headers','')}\n{item.get('subject','')}\n{item.get('body','')}".lower()
if re.search(r"\b(i'?m|i am|im|we'?re|we are)\s+outside\b", blob) or re.search(
r"\b(waiting outside|at the door|locked out|can'?t get in|cannot get in)\b", blob
):
if score < 3:
reason = "person is waiting outside"
score = 3
# Same bulk/marketing guard the prompt path applies: a newsletter or
# promotion is not urgent no matter how time-limited it sounds.
bulkish = bool(re.search(
r"\b(list-unsubscribe|list-id|mailchimp|mailchimpapp|view this email in your browser|unsubscribe|newsletter|digest|precedence:\s*bulk)\b",
blob,
))
# The adapter was trained on support tickets, so it over-rates promotions.
# Require a clear bulk header or several marketing terms before zeroing.
marketing_hits = sum(1 for t in (
"advertisement", "sponsored", "promo", "promotion", "sale", "discount",
"offer", "limited time", "deal", "coupon", "shop now", "buy now",
"sold out", "low tickets",
) if t in blob)
if bulkish or marketing_hits >= 2:
score = 0
reason = "bulk mail; no personal reply needed"
tags = []
if score >= 3:
tags.append("urgent")
elif score >= 2:
tags.append("reply-soon")
_from_raw = item.get("from", "") or ""
if "<" in _from_raw:
_from_short = _from_raw.split("<", 1)[0].strip().strip('"') or _from_raw
else:
_from_short = _from_raw
return {
"score": score,
"tags": tags[:4],
"spam": False,
"reason": reason,
"subject": (item.get("subject") or "")[:200],
"from": _from_short[:120],
"triage_version": triage_version,
"message_id": (item.get("message_id") or "").strip(),
"unread": bool(item.get("unread")),
"ts": time.time(),
}
async def action_check_email_urgency(owner: str, **kwargs) -> Tuple[str, bool]:
"""Scan unread emails across all accounts, LLM-triage new ones, cache
per-UID verdicts, tag the inbox, and fire a reminder when a previously
@@ -2852,6 +2946,16 @@ async def action_check_email_urgency(owner: str, **kwargs) -> Tuple[str, bool]:
per_uid_scores[key] = verdict
saved_classifications += 1
continue
# ── Spec decision adapter (triage): a calibrated urgency score
# with no generated-text prompt. Enabled per-job via
# ODYSSEUS_JEFF_EMAIL_URGENCY; any failure returns None and the
# LLM candidate chain below still runs.
_tri = await _spec_triage_email_urgency(item, triage_version=TRIAGE_VERSION)
if _tri is not None:
cache.setdefault("uids", {})[item["uid"]] = _tri
per_uid_scores[key] = _tri
saved_classifications += 1
continue
# ── LLM-classify. JSON-only response; bullet-proof parse.
llm_attempts += 1
prompt = (
+90 -2
View File
@@ -81,6 +81,16 @@ def is_vision_model(model_name: str) -> bool:
drops the image entirely. See issue #124.
"""
m = (model_name or "").lower()
if not m:
return False
# Per-model override (comma-separated substrings), e.g. a local model whose
# name carries no vision/VL hint but answers images natively.
override = os.getenv("ODYSSEUS_VISION_MODELS", "")
if override:
for token in override.split(","):
token = token.strip().lower()
if token and token in m:
return True
if any(kw in m for kw in _VISION_MODEL_KEYWORDS):
return True
return bool(_VISION_VL_RE.search(m))
@@ -164,8 +174,10 @@ def lmstudio_supports_vision(url: str, model: str) -> Optional[bool]:
def model_supports_vision(model_name: str, endpoint_url: str = "") -> bool:
"""Whether a model accepts images, using the endpoint's reported
capability when available (LM Studio) and falling back to name-based
detection otherwise."""
capability when available (LM Studio), a cached one-time probe for local
OpenAI-compatible endpoints, and name-based detection otherwise."""
if is_vision_model(model_name):
return True
if endpoint_url:
try:
advertised = lmstudio_supports_vision(endpoint_url, model_name or "")
@@ -173,9 +185,85 @@ def model_supports_vision(model_name: str, endpoint_url: str = "") -> bool:
advertised = None
if advertised is not None:
return advertised
try:
probed = probe_endpoint_supports_vision(endpoint_url, model_name or "")
except Exception:
probed = None
if probed is not None:
return probed
return is_vision_model(model_name)
# 1x1 red PNG — the cheapest possible image probe payload.
_PROBE_IMAGE_DATA_URL = (
"data:image/png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
)
_VISION_PROBE_TTL = 3600.0
# (host, model) -> (bool | None, expiry); None = undecidable (auth/network).
_vision_probe_cache: dict = {}
def _vision_probe_enabled() -> bool:
return os.getenv("ODYSSEUS_VISION_PROBE", "1").strip().lower() not in ("0", "false", "off", "no")
def _chat_completions_url(endpoint_url: str) -> str:
base = (endpoint_url or "").rstrip("/")
if base.endswith("/chat/completions"):
return base
return base + "/chat/completions"
def probe_endpoint_supports_vision(endpoint_url: str, model_name: str) -> Optional[bool]:
"""One-time (cached) probe: does a local OpenAI-compatible endpoint accept
an image_url content part for `model_name`?
Returns True on a 200, False when the endpoint rejects the image (400/413/
415/422), and None when we cannot decide (remote host, auth required,
unreachable, or probing disabled) so the caller falls back to name rules.
"""
if not endpoint_url or not model_name or not _vision_probe_enabled():
return None
parsed = urlparse(endpoint_url)
if not _is_local_host(parsed.hostname):
return None # never probe a public provider
key = ((parsed.hostname or "").lower(), (parsed.port or 0), model_name.strip().lower())
now = time.time()
cached = _vision_probe_cache.get(key)
if cached is not None and cached[1] > now:
return cached[0]
payload = {
"model": model_name,
"max_tokens": 1,
"stream": False,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Reply with one word."},
{"type": "image_url", "image_url": {"url": _PROBE_IMAGE_DATA_URL}},
],
}],
}
verdict: Optional[bool] = None
try:
r = httpx.post(_chat_completions_url(endpoint_url), json=payload, timeout=8.0)
if r.status_code == 200:
verdict = True
elif r.status_code in (400, 413, 415, 422):
body = (r.text or "").lower()
if any(tok in body for tok in ("image", "vision", "multimodal", "content type")):
verdict = False
else:
verdict = False
except Exception:
verdict = None
_vision_probe_cache[key] = (verdict, now + _VISION_PROBE_TTL)
if verdict is not None:
logger.info("vision probe %s@%s -> %s", model_name, parsed.hostname, verdict)
return verdict
def validate_message(message: str) -> str:
"""Validate message input."""
if not message:
+644 -14
View File
@@ -20,7 +20,11 @@ from pathlib import Path
import httpx
import jsonschema
from src.context_compactor import prune_multimodal_images, trim_for_context
from src.context_compactor import (
keep_recent_image_turns,
prune_multimodal_images,
trim_for_context,
)
from src.agent_runtime.runtime_selection import COMPACT_PREVIEW_MODE
from src import agent_runs
from src.agent_evidence import command_has_mutation_effect, workspace_artifact_is_usable
@@ -42,6 +46,7 @@ from src.turn_contract import (
_REQUEST_PREFIX,
calendar_retiming_request,
FAMILY_TOOLS, broad_web_briefing_request, required_read_operation_for_request,
note_read_intent,
targets_bound_editor_request, inline_text_transformation, editor_request_instructions,
_bound_editor_requests_web_verification, scheduled_automation_request, creation_container_tool,
)
@@ -206,9 +211,17 @@ CONTRACT_REQUIRED_TOOLS = frozenset({
})
from src.turn_contract import CONTRACT_CORE_TOOLS
# Scoped NL photo-editor surface. These are offered only when the
# ``photo_editor`` capability family is active (editor Quick Edit popup or an
# image-edit chat turn); they drive the in-process, owner-scoped editor bridge
# and the existing AI image ops.
EDITOR_AGENT_TOOLS = frozenset({
'plan_edit', 'run_editor_command', 'get_editor_screenshot', 'ai_edit_image',
})
PREVIEW_TOOLS = (
READ_TOOLS | SAFE_WRITE_TOOLS | EXPLICIT_EXECUTE_TOOLS | SAFE_UI_TOOLS
| BROKERED_JOB_TOOLS | CONTRACT_REQUIRED_TOOLS | CONTRACT_CORE_TOOLS
| EDITOR_AGENT_TOOLS
)
# Keep a small recovery-capable surface on every interactive compact agent
# turn. Routing still adds domain tools, while policy and action guards remain
@@ -1035,6 +1048,22 @@ def notes_terminal_response(raw, *, user_text='', max_items=20):
return _bounded_structured_list(summary, user_text=user_text)
def note_locator_followup(raw, *, user_text=''):
"""Require a body read before answering a note-content request."""
_, needs_body = note_read_intent(user_text)
if not needs_body or note_search_result_empty(raw):
return ''
listing = notes_terminal_response(raw, user_text=user_text, max_items=5)
match = re.search(r'\(#note-([A-Za-z0-9_-]+)\)', listing)
if not match:
return ''
return (
'The notes result contains titles only, not the body. '
f'Call manage_notes with action="view" and id="{match.group(1)}" now. '
'Use the returned body to answer the request; do not infer content from the title.'
)
def documents_terminal_response(raw, *, user_text='', max_items=8):
"""Render linked document rows under the user's explicit global cap."""
from src.agent_loop import _document_list_summary_from_tool_output
@@ -1368,17 +1397,26 @@ def contentless_final_response(content):
def action_promise_response(content):
"""Recognize a short promise to do work that contains no result yet."""
text = re.sub(r'\s+', ' ', str(content or '')).strip()
if not text or len(text.split()) > 48:
"""Recognize a short promise to do work that contains no result yet.
Fenced code blocks are stripped before the word count and the verb match,
so a promise followed by a code block (e.g. "I will browse Google Maps ..."
plus a requests/BeautifulSoup snippet and no tool call) still counts as an
action promise. The caller only reaches this when no tool call was made.
"""
without_code = re.sub(
r'\s+', ' ', re.sub(r'```.*?```', ' ', str(content or ''), flags=re.DOTALL)
).strip()
if not without_code or len(without_code.split()) > 48:
return False
if re.search(r'\b(?:answer|result|score|served|created|saved)\s*:', text, re.I):
if re.search(r'\b(?:answer|result|score|served|created|saved)\s*:', without_code, re.I):
return False
return bool(re.match(
r"^(?:okay[,.:]?\s*)?(?:let me|i(?:'ll| will)|next[,.:]?\s+i(?:'ll| will))\s+"
r"(?:now\s+)?(?:inspect|extract|read|check|review|analy[sz]e|verify|open|"
r"search|look|create|write|render|run|use|continue|finish|provide)\b",
text,
r"search|look|create|write|render|run|use|continue|finish|provide|"
r"browse|find|fetch|visit|navigate|go|get|scrape)\b",
without_code,
re.I,
))
@@ -1407,6 +1445,191 @@ def progressive_thinking_for_turn(model, offered_schemas, thinking_mode=None):
return uses_odysseus_progressive_thinking(model) and not bool(offered_schemas)
def spec_router_thinking_decision(endpoint_url, model, owner, headers, direct_user_text):
"""Env-gated router decision for spec tool-surface turns. Fail open (None)."""
try:
import sys as _sys
spec_router = _sys.modules.get('src.spec_router')
if spec_router is None:
from src import spec_router # noqa: F401
if not spec_router.think_router_enabled():
return None
from src.agent_loop import _configured_model_tool_surface_raw
if _configured_model_tool_surface_raw(
endpoint_url, model, owner, headers=headers
) != 'spec':
return None
return spec_router.route_thinking(direct_user_text)
except Exception:
logging.getLogger(__name__).warning(
'spec think router decision failed; using rules only', exc_info=True)
return None
def spec_router_think_reason(round_number, decision, existing_deliberate):
"""Add 'router_think' on round 1 when the router asked for thinking and no
other rule already selected a deliberate reason."""
if (round_number == 1 and not existing_deliberate
and isinstance(decision, dict) and decision.get('think')):
return 'router_think'
return ''
def spec_direct_mode():
"""Which direct-answer behaviour to use when the gate is on.
'tool_choice_none' (default) keeps the tools list but forbids a tool call
for the round; 'empty_menu' sends no tools at all. Any other value falls
back to the default.
"""
mode = str(
os.getenv('ODYSSEUS_SPEC_DIRECT_MODE', 'tool_choice_none') or ''
).strip().lower()
return 'empty_menu' if mode == 'empty_menu' else 'tool_choice_none'
def spec_direct_no_tools_p(user_message, endpoint_url, model, owner, headers):
"""Env-gated confidence for a spec 'answer_directly' turn.
Returns the answer_directly probability when the spec router just decided
to answer directly with enough confidence, else None. Default OFF, so the
caller behaves exactly as before unless ODYSSEUS_SPEC_DIRECT_NOTOOLS is set.
"""
if str(os.getenv('ODYSSEUS_SPEC_DIRECT_NOTOOLS', '')).strip().lower() not in (
'1', 'true', 'yes', 'on'):
return None
try:
from src.agent_loop import _configured_model_tool_surface_raw
if _configured_model_tool_surface_raw(
endpoint_url, model, owner, headers=headers
) != 'spec':
return None
import sys as _sys
spec_router = _sys.modules.get('src.spec_router')
if spec_router is None:
from src import spec_router # noqa: F401
decisions = getattr(spec_router, 'LAST_DECISIONS', None) or []
if not decisions:
return None
decision = decisions[-1]
if not isinstance(decision, dict):
return None
# Guard against a stale decision from a previous turn.
msg = str(user_message or '')
decided_msg = str(decision.get('message') or '')
if decided_msg and msg and decided_msg[:40] != msg[:40]:
return None
if decision.get('choice') != 'answer_directly':
return None
try:
p = float(decision.get('answer_directly') or 0.0)
except (TypeError, ValueError):
return None
try:
min_p = float(os.getenv('ODYSSEUS_SPEC_DIRECT_MIN_P', '0.9') or 0.9)
except (TypeError, ValueError):
min_p = 0.9
return p if p >= min_p else None
except Exception:
logging.getLogger(__name__).warning(
'spec direct-answer decision failed; using rules only', exc_info=True)
return None
def spec_driver_active(endpoint_url, model, owner, headers):
"""True when ODYSSEUS_SPEC_MODE=driver and the turn uses the spec surface."""
if str(os.getenv('ODYSSEUS_SPEC_MODE', '') or '').strip().lower() != 'driver':
return False
try:
from src.agent_loop import _configured_model_tool_surface_raw
return _configured_model_tool_surface_raw(
endpoint_url, model, owner, headers=headers) == 'spec'
except Exception:
return False
def spec_driver_pick(conversation, disabled_tools, user_text, schemas=None):
"""Per-round ODYSSEUS_SPEC_MODE=driver decision: the router drives tools.
Ask the router once for this round and return its TOP-1 choice at ANY
confidence: ``{'choice': 'tool'|'answer_directly'|'ask_user', 'p': float,
'tool_name': str|None}``. Returns None on any router error/timeout or an
unusable pick, so the caller keeps the normal menu for that round.
``schemas`` is the round's offered menu; the router only ever picks from
it, so a top-1 tool is always one the turn can actually execute (passing
every known tool here made the driver name tools outside the offered set,
which then looped on permission errors).
"""
try:
from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
import sys as _sys
spec_router = _sys.modules.get('src.spec_router')
if spec_router is None:
from src import spec_router # noqa: F401
menu = list(schemas) if schemas else list(FUNCTION_TOOL_SCHEMAS)
picks, _decided = spec_router.spec_route_tools(
str(user_text or ''), menu,
set(disabled_tools or ()), list(conversation or []),
return_decision=True,
)
decisions = getattr(spec_router, 'LAST_DECISIONS', None) or []
decision = decisions[-1] if decisions else {}
if not isinstance(decision, dict) or decision.get('error'):
return None
choice = decision.get('choice')
top = decision.get('top') or []
if choice == 'answer_directly':
return {'choice': 'answer_directly',
'p': float(decision.get('answer_directly') or 0.0),
'tool_name': None}
if choice == 'ask_user':
return {'choice': 'ask_user',
'p': float(decision.get('ask_user') or 0.0),
'tool_name': None}
# Driver mode takes the router's TOP-1 at ANY confidence, so read the
# ranked ``top`` (not the MIN_CONF-filtered ``picks``/``added``).
if top and isinstance(top[0], (list, tuple)) and top[0]:
name = str(top[0][0] or '')
p = None
if len(top[0]) >= 2:
try:
p = float(top[0][1])
except (TypeError, ValueError):
p = None
if name:
return {'choice': 'tool', 'p': p, 'tool_name': name}
if picks:
try:
name = str(next(iter(picks)))
except TypeError:
name = str(picks[0]) if len(picks) else ''
if name:
return {'choice': 'tool', 'p': None, 'tool_name': name}
return None
except Exception:
logging.getLogger(__name__).warning(
'spec driver decision failed; using the normal menu', exc_info=True)
return None
def tool_deliberation_reason(name, args):
"""Classify selected operations, never infer intent from tool availability."""
name = canonical(name)
if name in {'python', 'edit_file', 'apply_patch'}:
return 'code'
if name in {'edit_document', 'suggest_document', 'update_document'}:
return 'document_edit'
if name in {'draft_email', 'draft_email_reply', 'ai_draft_email_reply'}:
return 'email_draft'
action = str(args.get('action') or '').lower()
if name == 'manage_tasks' and action in {'create', 'add', 'update', 'edit'}:
return 'task_design'
if name == 'manage_skills' and action in {'add', 'edit', 'patch', 'publish', 'audit'}:
return 'skill_evaluation'
return ''
def visible_content_after_qwen_thinking(content):
"""Remove private Qwen reasoning when the server lacks a reasoning parser."""
@@ -1422,6 +1645,48 @@ def visible_content_after_qwen_thinking(content):
return text.strip()
def qwen_think_split_events(content, state):
"""Split a no-reasoning-parser thinking round into live deltas.
Some thinking servers (no --reasoning-parser) return the whole
``<think>…</think>`` trace as ordinary ``content``. Buffering that round
made the UI show nothing while the model thought and then dump the whole
answer at once. Stream the trace as ``{'delta': ..., 'thinking': True}``
events (the same shape a reasoning-parser server emits) and the text after
``</think>`` as normal answer deltas. ``state`` is a mutable per-round dict
carrying the emission bookkeeping; the stored answer is unchanged (see
``visible_content_after_qwen_thinking``).
"""
events = []
text = str(content or '')
if not text:
return events
lowered = text.casefold()
lead = len('<think>') if lowered.startswith('<think>') else 0
close = lowered.find('</think>')
if close < 0:
# The opening <think> is injected by the chat template, so a progressive
# trace can arrive with no marker until </think>. Emit the buffered text
# as thinking - holding back a possible partial close tag - so the trace
# streams live instead of dumping in one block at the end.
think_region = text[lead:max(lead, len(text) - len('</think>'))]
answer_region = ''
else:
think_region = text[lead:close]
answer_region = text[close + len('</think>'):]
emitted_think = int(state.get('think_emitted', 0) or 0)
if len(think_region) > emitted_think:
events.append({'delta': think_region[emitted_think:], 'thinking': True})
state['think_emitted'] = len(think_region)
if close >= 0:
state['closed'] = True
emitted_answer = int(state.get('answer_emitted', 0) or 0)
if len(answer_region) > emitted_answer:
events.append({'delta': answer_region[emitted_answer:]})
state['answer_emitted'] = len(answer_region)
return events
def prior_short_answer_for_no_tool_summary(user_text, history):
"""Reuse the immediately prior concise answer for an explicit no-tool recap."""
text = str(user_text or '')
@@ -2714,6 +2979,18 @@ def normalize_preview_entity_anchor_args(name, args):
value = args.get(field)
if isinstance(value, str) and value.startswith(prefix):
args[field] = value[len(prefix):]
if canonical(name) == 'manage_notes':
# Some models copy the rendered note href without its leading '#'.
# Decode only a complete UUID; partial selectors retain the existing
# owner-bound resolution policy instead of gaining a new alias.
value = args.get('note_id')
if isinstance(value, str):
match = re.fullmatch(
r'note-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})',
value, re.I,
)
if match:
args['note_id'] = match.group(1)
return args
@@ -2754,6 +3031,9 @@ def normalize_preview_function_args(name, args, *, user_text=''):
args.pop('filter', None)
if canonical(name) == 'manage_notes':
action = str(args.get('action') or '').strip().replace('-', '_').casefold()
if action == 'read' and (args.get('id') or args.get('note_id')):
args['action'] = 'view'
action = 'view'
if action == 'list':
request = str(user_text or '').casefold()
# The notes backend interprets title/query/content on ``list`` as
@@ -2770,6 +3050,10 @@ def normalize_preview_function_args(name, args, *, user_text=''):
args.pop('archived', None)
if not re.search(r'\b(?:checklists?|freeform\s+notes?|notes?\s+only)\b', request):
args.pop('note_type', None)
query, _ = note_read_intent(user_text)
if query:
args['action'] = 'search'
args['query'] = query
if canonical(name) == 'manage_skills':
action = str(args.get('action') or '').strip().replace('-', '_').casefold()
if action in {'update', 'change', 'revise'}:
@@ -2897,8 +3181,9 @@ def scope_preview_contract(preview_contract, routed_contract, active_capabilitie
requested_family_tools = set().union(*(FAMILY_TOOLS.get(f, ()) for f in active))
available_requested = routed_canonical & offered_canonical & requested_family_tools
routed_canonical.update(canonical(name) for name in extra_tools)
if 'image_generation' not in active:
# A past image request must not keep generation warm on email/doc turns.
if 'image_generation' not in active and 'photo_editor' not in active:
# A past image request must not keep generation warm on email/doc turns,
# unless the photo_editor family (which bundles generate_image) is active.
routed_canonical.discard('generate_image')
missing_active = {
f'capability:{family}' for family in active
@@ -3230,7 +3515,11 @@ def _successful_email_identifiers(history):
for message in history or ():
if not isinstance(message, dict):
continue
if message.get('role') == 'system' and 'Message UID:' in str(message.get('content') or ''):
active_reader = (
message.get('_agent_injected') == 'context'
and (message.get('metadata') or {}).get('source') == 'active email reader'
)
if (message.get('role') == 'system' or active_reader) and 'Message UID:' in str(message.get('content') or ''):
extracted = _email_identifiers_from_text(message.get('content'))
known['uid'].update(extracted['uid'])
known['message_id'].update(extracted['message_id'])
@@ -3518,6 +3807,20 @@ def evaluate_preview_call(name, args, user_text='', *, allow_execute_code=False,
runtime_tools = PREVIEW_TOOLS | (
NATIVE_WORKSPACE_TOOLS if allow_native_workspace else frozenset()
) | ({canonical(tool) for tool in external_runtime_tools} if allow_native_workspace else set())
# Spec turns are driven by the router: the Spec contract (its offered set)
# IS the model runtime, so a Spec pick is runnable. Keyed off the same
# marker the spec hook sets (`routing_experiment == 'spec-router'`), never
# a new flag, and never applied to compact/native turns.
try:
from src.turn_contract import active_turn_contract as _atc
_spec_contract = _atc()
if _spec_contract is not None and getattr(
_spec_contract, 'routing_experiment', '') == 'spec-router':
runtime_tools = runtime_tools | {
canonical(tool) for tool in getattr(_spec_contract, 'offered', ()) or ()
}
except Exception:
pass
if bare not in runtime_tools:
return decision(False, 'tool_not_in_model_runtime')
if bare in {canonical(tool) for tool in external_runtime_tools}:
@@ -3619,6 +3922,18 @@ def evaluate_preview_call(name, args, user_text='', *, allow_execute_code=False,
# editor is offered only for an explicit image-editing turn.
blocked_effects.remove(ToolEffect.NETWORK_EGRESS)
allowed_effects.add(ToolEffect.NETWORK_EGRESS)
if (
(contract_required or family in turn_authorized_families)
and bare in {'plan_edit', 'run_editor_command', 'get_editor_screenshot', 'ai_edit_image'}
):
# Scoped photo_editor agent tools. They are never in the general tool
# list; the immutable turn contract only selects them for an explicit
# editor request (Quick Edit popup / image-edit turn), so their UI and
# brokered-network effects are covered by the contract seal.
blocked_effects.discard(ToolEffect.UI_SIDE_EFFECT)
allowed_effects.add(ToolEffect.UI_SIDE_EFFECT)
blocked_effects.discard(ToolEffect.NETWORK_EGRESS)
allowed_effects.add(ToolEffect.NETWORK_EGRESS)
if (
contract_required
and bare in {'download_model', 'serve_preset', 'stop_served_model'}
@@ -3849,6 +4164,29 @@ def conversation(history_session, messages, *, owner=None, diagnostics=None):
from src.turn_contract import result_reference_followup
source_context = (recent_source_reference_context(groups[-2])
if len(groups) > 1 and result_reference_followup(current_text) else None)
# Tool output can dwarf the dialogue (especially a web search). Keep the
# visible exchange before enforcing the history cap, so one search-heavy
# turn cannot erase the subject of the next follow-up.
for index, group in enumerate(groups[:-1]):
if len(json.dumps(group)) <= 5000 or len(group) < 2:
continue
# Keep non-web tool evidence intact: a note/list follow-up may need
# exact result identifiers, and shortening it would be misleading.
if not any(
canonical((call.get('function') or {}).get('name', '')) in {'web_search', 'web_fetch'}
for message in group if message.get('role') == 'assistant'
for call in message.get('tool_calls') or ()
):
continue
answer = next((message.get('content') for message in reversed(group)
if message.get('role') == 'assistant'
and str(message.get('content') or '').strip()), None)
if answer is None:
continue
answer_text = str(answer)
if len(answer_text) > 3500:
answer_text = answer_text[:3500] + '\n[Earlier answer shortened for context.]'
groups[index] = [group[0], {'role': 'assistant', 'content': answer_text}]
# Drop whole turns only, never orphan tool results from their native calls.
groups = groups[-8:]
while len(groups) > 1 and len(json.dumps(groups)) > 22000:
@@ -4207,6 +4545,26 @@ def denied_response():
return 'I can’t perform that operation in this preview. No changes were made.'
WORKSPACE_REQUIRED_REFUSAL = (
'Shell and Python commands only run inside a workspace. '
'Open the code workspace (or set a working directory) and try again.'
)
def workspace_process_denial(executions) -> bool:
"""True when a blocked call was refused because process execution needs a
sealed workspace (a plain chat turn carries none)."""
for entry in executions or ():
blob = ' '.join(
str(entry.get(key) or '') for key in ('error', 'output', 'failure_kind')
)
# Resource identity also covers missing note and document selectors.
# Those denials must not turn into instructions to open a code workspace.
if 'sealed workspace' in blob.casefold():
return True
return False
def execution_has_write_effect(tool_name, content, capability, *, native_workspace_enabled):
"""Recognize successful native code that visibly mutates the workspace."""
@@ -4226,7 +4584,7 @@ _MUTATION_REQUEST = re.compile(
r'\b(?:add|creat(?:e|ing)?|make|writ(?:e|ing)|sav(?:e|ing)|updat(?:e|ing)|edit(?:ing)?|chang(?:e|ing)|'
r'set|schedul(?:e|ing)|reschedul(?:e|ing)|paus(?:e|ing)|resum(?:e|ing)|toggle|mark|'
r'pin|archive|delet(?:e|ing)|remov(?:e|ing)|send|reply|draft|publish|run|launch|serve|start|stop|'
r'remember|remeber|forget|remind|review|proofread|suggest(?:ions?)?|expand|broaden|deepen|lighten|feedback|reserve|block)\b|'
r'remember|remeber|forget|remind|review|proofread|suggest(?:ions?)?|expand|broaden|deepen|lighten|reserve|block)\b|'
r'\bgo\s+deeper\b',
re.I,
)
@@ -4262,7 +4620,7 @@ def mutation_action_requested(user_text):
actionable = re.sub(
r"\b(?:do\s+not|don't|never|without)\s+"
r"(?:(?:chang(?:e|ing)|modif(?:y|ying)|edit(?:ing)?|delet(?:e|ing)|"
r"remov(?:e|ing)|send(?:ing)?|writ(?:e|ing)|creat(?:e|ing))\b)"
r"remov(?:e|ing)|send(?:ing)?|writ(?:e|ing)|creat(?:e|ing)|schedul(?:e|ing))\b)"
r"[^.;\n]{0,120}?(?=(?:[.;\n]|\bbut\b|\binstead\b|$))",
'', text, flags=re.I,
)
@@ -5622,6 +5980,38 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
'multimodal_image_count': image_context_count,
'attachment_reference_count': attachment_refs,
'image_rehydration': conversation_diagnostics.get('image_rehydration')})
_photo_editor_active = 'photo_editor' in (getattr(turn_contract, 'active_capabilities', ()) or ())
_photo_editor_open = bool(
((client_runtime_context or {}).get('web_ui_state') or {}).get('photo_editor_open')
)
if _photo_editor_active and not _photo_editor_open:
_editor_guidance = (
"This image isn't open in the editor yet, so I can't apply edits to the "
"canvas from chat. Open the attached image in the editor (Quick Edit) and "
"send this request there \u2014 I'll apply it to the canvas."
)
history.append({'role': 'assistant', 'content': _editor_guidance})
yield event({'delta': _editor_guidance})
_action_prompt = str(direct_user_text or '')
for _annotation in ('\n\n[Image:', '\n[Image:', '\n\n[Attached', '\n[No vision model'):
_cut = _action_prompt.find(_annotation)
if _cut != -1:
_action_prompt = _action_prompt[:_cut]
_action_prompt = _action_prompt.strip() or str(direct_user_text or '').strip()
yield event({
'type': 'final_response',
'content': _editor_guidance,
'photo_editor_action': {
'kind': 'open_and_apply',
'prompt': _action_prompt,
},
})
yield event({'type': 'metrics', 'data': {
'model': model, 'rounds': 0, 'round_texts': [_editor_guidance],
'tool_events': [], 'tool_calls': 0, 'agent_rounds': 0,
}})
yield 'data: [DONE]\n\n'
return
try:
async with httpx.AsyncClient(
timeout=preview_http_timeout(
@@ -5703,6 +6093,35 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
usage_in += intent_accounting.get('input_tokens', 0)
usage_out += intent_accounting.get('output_tokens', 0)
has_real_usage = intent_accounting.get('usage_source') == 'real'
# Optional env-gated router decision (spec surface only). Computed
# once per user turn; disabled/None leaves behaviour unchanged.
_spec_route_think = spec_router_thinking_decision(
endpoint_url, model, owner, headers, direct_user_text)
if _spec_route_think is not None:
logging.getLogger(__name__).info(
'spec think router: think=%s p_think=%s ms=%s',
_spec_route_think.get('think'),
_spec_route_think.get('p_think'),
_spec_route_think.get('ms'))
# Optional env-gated direct-answer override (spec surface only):
# when the spec router chose answer_directly with high confidence,
# round 1 is sent with tool_choice 'none' (same tools list).
_spec_direct_p = spec_direct_no_tools_p(
direct_user_text, endpoint_url, model, owner, headers)
# Option B: send round 1 with no tools at all for a direct answer.
_spec_direct_empty_menu = (
_spec_direct_p is not None and spec_direct_mode() == 'empty_menu')
# ODYSSEUS_SPEC_MODE=driver: the router (not the 9B) picks the tool
# every round; the 9B only writes the arguments or the answer.
_spec_driver_on = spec_driver_active(endpoint_url, model, owner, headers)
# Driver mode narrows the contract per round to the Spec pick.
# Rebuild each round from this frozen base so the narrowing does
# not accumulate/mutate across rounds.
_driver_base_contract = turn_contract
# Per-round Spec pick (driver mode): 'answer_directly' | 'ask_user'
# | 'tool' | None (router fallback). Set inside the round loop.
_driver_round_kind = None
_driver_round_pick = None
# One extra iteration is available only when a provider emits raw
# tool markup during the normal final no-tools round. Ordinary
# turns still obey ``round_limit`` exactly.
@@ -5839,7 +6258,9 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
'completion_reserve_seconds': artifact_completion_reserve_seconds,
})
request_messages = provider_request_messages(
prune_multimodal_images(history, max_images=3)
prune_multimodal_images(
keep_recent_image_turns(history, keep=2), max_images=3
)
)
if prior_summary_answer or force_no_tools_next_round or reserve_final_synthesis:
round_offered = []
@@ -6036,6 +6457,94 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
break
request['tools'] = source_tools
request['tool_choice'] = 'required'
# ODYSSEUS_SPEC_MODE=driver: the router is the tool driver.
# Ask it for this round's single next action (any confidence);
# the 9B then only writes the arguments (a named tool_choice) or
# the answer (tools key omitted; vLLM rejects an empty array).
# Router error/timeout keeps the normal menu for this round.
if _spec_driver_on and round_offered:
# The router chooses from the FULL Ajax Spec surface (~all
# built-ins minus disabled), not the compact round menu, so
# a Spec pick is never silently out of reach. The 9B then
# only writes the arguments (a named tool_choice) or the
# answer (tools key omitted; vLLM rejects an empty array).
# Router error/timeout keeps the normal menu this round.
from src.tool_schemas import FUNCTION_TOOL_SCHEMAS as _SPEC_SURFACE
_drv = spec_driver_pick(history, disabled_tools, direct_user_text)
if _drv is not None:
_drv_choice = _drv.get('choice')
if _drv_choice == 'answer_directly':
_driver_round_kind = 'answer_directly'
request.pop('tools', None)
request.pop('tool_choice', None)
elif _drv_choice == 'ask_user':
_driver_round_kind = 'ask_user'
_ask = [s for s in _SPEC_SURFACE
if (s.get('function') or {}).get('name') == 'ask_user']
if _ask:
request['tools'] = [_ask[0]]
request['tool_choice'] = {
'type': 'function',
'function': {'name': 'ask_user'},
}
if _ask[0] not in round_offered:
round_offered = list(round_offered) + [_ask[0]]
elif _drv_choice == 'tool' and _drv.get('tool_name'):
_name = _drv['tool_name']
_sel = [s for s in list(round_offered) + list(_SPEC_SURFACE)
if (s.get('function') or {}).get('name') == _name]
if _sel:
_driver_round_kind = 'tool'
_driver_round_pick = _name
request['tools'] = [_sel[0]]
request['tool_choice'] = {
'type': 'function',
'function': {'name': _name},
}
# The per-call validator looks the schema up in
# `round_offered` (not `request['tools']`), so the
# Spec pick must be present there too.
round_offered = [_sel[0]]
# Driver mode narrows the whole contract to the
# Spec pick for this round: the router is the
# authority, and the executor must be able to run
# the picked tool. Build a valid contract (the
# TurnContract invariant requires
# required <= offered <= executable and
# schema_json names == offered).
try:
from src.turn_contract import (
_ACTIVE_CONTRACT as _TC,
canonical_tool as _ct,
)
_pick = _ct(_name)
turn_contract = replace(
_driver_base_contract,
required=frozenset(),
offered=frozenset({_pick}),
executable=frozenset(
set(_driver_base_contract.executable) | {_pick}),
schema_json=(json.dumps(_sel[0]),),
required_read_operation=None,
)
_TC.set(turn_contract)
except Exception:
turn_contract = _driver_base_contract
logging.getLogger(__name__).info(
'[spec-driver] round=%s pick=%s contract admit failed; '
'normal contract kept', round_number, _name)
else:
logging.getLogger(__name__).info(
'[spec-driver] round=%s pick=%s not executable; normal menu this round',
round_number, _name)
logging.getLogger(__name__).info(
'[spec-driver] round=%s pick=%s p=%s', round_number,
(_drv.get('tool_name') if _drv_choice == 'tool'
else _drv_choice),
_drv.get('p'))
else:
logging.getLogger(__name__).info(
'[spec-driver] round=%s pick=fallback p=None', round_number)
pending, content, round_reasoning = {}, '', ''
document_preview_index = None
document_preview_content = ''
@@ -6056,6 +6565,49 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
request = search_tool_choice_request(request)
tool_call_requested = request.get('tool_choice') not in (None, 'auto', 'none')
request = provider_compatible_tool_choice_request(request, model)
# Log the tool surface actually sent to the provider: the
# metrics `tool_schema_names` reports the pre-narrowing
# `offered` set, which hid the fact that a forced choice had
# shrunk the provider tools array to one schema.
logging.getLogger(__name__).info(
"clean preview round %s sending %d tool(s): %s",
round_number,
len(request.get('tools') or []),
[
(schema.get('function') or {}).get('name')
for schema in (request.get('tools') or [])
][:40],
)
if round_number == 1 and _spec_direct_p is not None:
# The router decided to answer directly with high
# confidence.
if _spec_direct_empty_menu:
# Option B: an empty menu — send no tools at all, so
# nothing can be executed and no markup is recovered.
request['tools'] = []
request.pop('tool_choice', None)
tool_call_requested = False
# Keep the thinking router's decision; never let the
# no-tools progressive rule turn thinking on when the
# router said off.
if not (_spec_route_think or {}).get('think'):
ctk = dict(request.get('chat_template_kwargs') or {})
ctk['enable_thinking'] = False
request['chat_template_kwargs'] = ctk
logging.getLogger(__name__).info(
'[spec-harness] direct answer: empty menu p=%s',
_spec_direct_p)
else:
# Default: keep the same tools list (prefix-cache
# friendly) but forbid a tool call this round. Thinking
# is left to the thinking router; offered stays
# non-empty so this does not switch progressive
# thinking on.
request['tool_choice'] = 'none'
tool_call_requested = False
logging.getLogger(__name__).info(
'[spec-harness] direct answer: tool_choice none p=%s',
_spec_direct_p)
if active_editor_target and request.get('tools'):
# Edits share mutable document state. Await a saved result
# before asking for another call; one call may still batch
@@ -6144,6 +6696,7 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
and not progressive_thinking
and not source_lookup_pending
and not tool_call_requested
and not _spec_direct_empty_menu
):
text_event = {'delta': text}
if replace_streamed_draft_on_finish and not streamed_round_text:
@@ -6197,6 +6750,13 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
if content and not prior_summary_answer and not source_lookup_pending:
yield event({'delta': content})
streamed_round_text = True
if _spec_direct_empty_menu and pending:
# Option B: nothing is offered, so never execute a tool
# call the model still produced (native shape).
logging.getLogger(__name__).info(
'[spec-harness] direct answer: dropped %d tool call(s)',
len(pending))
pending = {}
proposed = [pending[i] for i in sorted(pending)]
# A lead-in emitted before a tool call is live progress, not
# part of the terminal answer. Replace that draft when the
@@ -6204,7 +6764,9 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
if proposed and streamed_round_text:
replace_streamed_draft_on_finish = True
unexecutable_dsml_completion = False
if not proposed and 'DSML' in content:
if (not proposed and not _spec_direct_empty_menu
and _driver_round_kind != 'answer_directly'
and 'DSML' in content):
offered_by_canonical = {
canonical(schema['function']['name']): schema['function']['name']
for schema in round_offered
@@ -6252,6 +6814,15 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
})
else:
unexecutable_dsml_completion = True
if _spec_direct_empty_menu and content:
# Option B: show the answer text without any tool-call
# markup the model may still have written (nothing offered).
_stripped = re.sub(
r'<tool_call\b[^>]*>.*?</tool_call>', '',
content, flags=re.DOTALL | re.IGNORECASE).strip()
if _stripped != content.strip():
content = _stripped
replace_streamed_draft_on_finish = True
if source_lookup_pending and not proposed:
if source_answer_retries < 1 and round_number < round_limit:
source_answer_retries += 1
@@ -6276,6 +6847,37 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
)
if active_editor_target:
proposed = drop_redundant_editor_noops(proposed)
# ODYSSEUS_SPEC_MODE=driver: Spec is the tool driver, so execute
# ONLY the call Spec picked this round. Drop (never execute) any
# other native call and any text/DSML-recovered call; when Spec
# said answer_directly, keep no calls and strip tool markup so
# the remaining text is the answer.
if _driver_round_kind == 'answer_directly':
if proposed:
for _c in proposed:
logging.getLogger(__name__).info(
'[spec-driver] dropped off-pick call name=%s',
(_c.get('function') or {}).get('name'))
proposed = []
if content:
_stripped = strip_tool_blocks(content, skip_fenced=True).strip()
_stripped = re.sub(
r'<tool_call\b[^>]*>.*?</tool_call>', '',
_stripped, flags=re.DOTALL | re.IGNORECASE).strip()
if _stripped != content:
content = _stripped
replace_streamed_draft_on_finish = True
elif _driver_round_kind in ('tool', 'ask_user'):
_want = 'ask_user' if _driver_round_kind == 'ask_user' else _driver_round_pick
_keep = []
for _c in proposed:
_cn = (_c.get('function') or {}).get('name')
if canonical(str(_cn or '')) == canonical(str(_want or '')):
_keep.append(_c)
else:
logging.getLogger(__name__).info(
'[spec-driver] dropped off-pick call name=%s', _cn)
proposed = _keep
if model_choice_experiment:
for proposal in proposed:
yield event({'type': 'model_tool_proposal', 'round': round_number,
@@ -6695,6 +7297,25 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
# that draft and persisted history with the evidence-backed result.
history.pop()
refusal = denied_response()
# A photo-editor turn with no canvas command actually executed
# (no browser editor attached) cannot claim the edit. Point the
# user at the editor instead of the generic no-op refusal.
if 'photo_editor' in (getattr(turn_contract, 'active_capabilities', ()) or ()):
touched_canvas = any(
str(e.get('tool') or '') in {
'run_editor_command', 'get_editor_screenshot',
'ai_edit_image', 'generate_image',
}
and not e.get('error') and e.get('exit_code', 0) == 0
for e in executions
)
if not touched_canvas:
refusal = (
'This photo is not open on the editor canvas, so I cannot '
'apply edits to it from chat. Open the attached image in the '
'editor (Quick Edit) and send the request there, and I will '
'apply it to the canvas.'
)
history.append({'role': 'assistant', 'content': refusal})
yield event({'type': 'final_response', 'content': refusal})
break
@@ -7948,6 +8569,15 @@ async def stream_preview(*, endpoint_url, model, messages, headers, turn_contrac
output, user_text=latest_user,
max_items=contract_item_limit(turn_contract, 20),
)
followup = note_locator_followup(output, user_text=latest_user)
if followup:
if round_number < round_limit:
structured_terminal_response = ''
round_recovery_messages.append(followup)
else:
structured_terminal_response = (
'I found a note, but could not read its content in this turn.'
)
action = str(args.get('action') or '').replace('-', '_').casefold()
if (
action in {'search', 'find'}
+78 -1
View File
@@ -92,6 +92,83 @@ def prune_multimodal_images(
return pruned
_IMAGE_TURN_LABEL_RE = re.compile(r"\[Image(?:s)?(?:\s+attached)?:\s*([^\]]+)\]", re.IGNORECASE)
def _image_turn_label(message: Dict) -> str:
"""Best-effort '[Image: name]' label for a message whose image parts are dropped."""
name = ""
content = message.get("content") if isinstance(message, dict) else None
if isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") in _MULTIMODAL_IMAGE_TYPES:
candidate = item.get("name") or (item.get("image_url") or {}).get("name")
if candidate:
name = str(candidate)
break
if not name:
text = _content_as_text(content)
match = _IMAGE_TURN_LABEL_RE.search(text)
if match:
name = match.group(1).strip()
return f"[Image: {name}]" if name else "[Image]"
def keep_recent_image_turns(messages: List[Dict], *, keep: int = 2) -> List[Dict]:
"""Keep image parts only for the last `keep` messages that carry an image.
Older image blocks are dropped and replaced with a short ``[Image: name]``
text label so the model still knows a picture was shared (and its name)
without paying the image tokens on every later turn. Non-text, non-image
multimodal blocks (e.g. audio) are left untouched.
"""
limit = max(0, int(keep))
image_messages = [
index for index, message in enumerate(messages)
if isinstance(message, dict)
and isinstance(message.get("content"), list)
and any(
isinstance(item, dict) and item.get("type") in _MULTIMODAL_IMAGE_TYPES
for item in message["content"]
)
]
if len(image_messages) <= limit:
return list(messages)
selected = set(image_messages[len(image_messages) - limit:]) if limit else set()
trimmed: List[Dict] = []
for message_index, message in enumerate(messages):
if message_index in selected or not isinstance(message, dict):
trimmed.append(message)
continue
content = message.get("content")
if not isinstance(content, list):
trimmed.append(message)
continue
kept_blocks = [
item for item in content
if not (isinstance(item, dict) and item.get("type") in _MULTIMODAL_IMAGE_TYPES)
]
if len(kept_blocks) == len(content):
trimmed.append(message)
continue
label = _image_turn_label(message)
# Attach the label to the trailing text block when possible so we do not
# introduce an extra content block; otherwise append a fresh text block.
labelled = False
for item in reversed(kept_blocks):
if isinstance(item, dict) and item.get("type") == "text":
item["text"] = (item.get("text") or "").rstrip() + f"\n{label}"
labelled = True
break
if not labelled:
kept_blocks.append({"type": "text", "text": label})
cloned = dict(message)
cloned["content"] = kept_blocks
trimmed.append(cloned)
return trimmed
COMPACT_THRESHOLD = 0.85 # Trigger compaction at 85% of context window
SUMMARY_MAX_TOKENS = 1024
SMALL_CONTEXT_LIMIT = 8192 # Models with context <= this get aggressive trimming
@@ -106,7 +183,7 @@ def auto_compact_threshold_percent() -> int:
return max(50, min(95, value))
# Cursor-style self-summarization prompt — produces structured, dense summaries
SELF_SUMMARY_SYSTEM_PROMPT = """You are summarizing a conversation to preserve context after compaction. Produce a structured summary that lets the conversation continue seamlessly.
SELF_SUMMARY_SYSTEM_PROMPT = """You are summarizing a conversation with Ajax, the user's AI assistant, to preserve context after compaction. Produce a structured summary that lets Ajax continue seamlessly. Ajax is the assistant's name; Odysseus is the app name.
Use this format:
+47 -4
View File
@@ -2,6 +2,7 @@
"""Document processing: PDF/OCR extraction, text file handling, image VL analysis, user content building."""
import os
import io
import logging
import mimetypes
import base64
@@ -496,6 +497,49 @@ def analyze_image_with_vl(image_path: str, owner: str | None = None) -> str:
return analyze_image_with_vl_result(image_path, owner=owner).get("text", "")
def _vision_max_side() -> int:
"""Longest-side cap for images inlined into the chat request (tokens)."""
try:
value = int(os.getenv("ODYSSEUS_VISION_MAX_SIDE", "1280") or 1280)
except (TypeError, ValueError):
value = 1280
return max(0, value)
def encode_image_data_url(path: str, fallback_format: str) -> tuple[str, str]:
"""Return (data_url, image_format) for an image, downscaled if large.
Downscale the longest side to ODYSSEUS_VISION_MAX_SIDE (default 1280) and
re-encode as JPEG so the chat model does not pay full-resolution image
tokens. Small/undecodable images fall back to the original bytes so a
real attachment is never dropped.
"""
max_side = _vision_max_side()
try:
from PIL import Image # local import: keep module import cost low
with Image.open(path) as img:
img = img.convert("RGB") if img.mode not in ("RGB", "L") else img
width, height = img.size
if max_side and max(width, height) > max_side:
scale = max_side / float(max(width, height))
img = img.resize(
(max(1, round(width * scale)), max(1, round(height * scale))),
Image.LANCZOS,
)
buffer = io.BytesIO()
img.save(buffer, format="JPEG", quality=85, optimize=True)
return (
"data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode("utf-8"),
"jpeg",
)
except Exception as exc:
logger.debug(f"Image downscale failed for {path}: {exc}; sending original bytes")
with open(path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
image_format = (fallback_format or "png").lower()
return f"data:image/{image_format};base64,{encoded_string}", image_format
def build_user_content(
text: str,
attachment_ids: list[str] | None,
@@ -542,15 +586,14 @@ def build_user_content(
if upload_handler.is_image_file(display_name, mime):
try:
with open(path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
# Extensionless uploads (e.g. a pasted screenshot) have no ext,
# so fall back to the resolved MIME subtype rather than emitting
# an invalid "data:image/;base64," with an empty subtype.
image_format = ext[1:] or (mime.split("/", 1)[1] if mime.startswith("image/") else "png")
fallback_format = ext[1:] or (mime.split("/", 1)[1] if mime.startswith("image/") else "png")
data_url, image_format = encode_image_data_url(path, fallback_format)
content.append({
"type": "image_url",
"image_url": {"url": f"data:image/{image_format};base64,{encoded_string}"},
"image_url": {"url": data_url},
})
except Exception as e:
logger.error(f"Failed to encode image {fid}: {e}")
+113 -6
View File
@@ -2,7 +2,8 @@
import json
import time
import copy
from dataclasses import dataclass
import re
from dataclasses import dataclass, replace
@dataclass(frozen=True)
@@ -19,7 +20,7 @@ _DEPENDENCIES = {
'web': {'web_search', 'web_fetch', 'private_browser'},
'email': {'list_email_accounts', 'list_emails', 'search_emails', 'read_email',
'download_attachment'},
'contacts': {'resolve_contact'},
'contacts': {'resolve_contact', 'manage_contact'},
'documents': {'search_documents', 'read_document'},
}
_DRAFT_TOOLS = {'ask_user', 'update_plan', 'draft_email', 'draft_email_reply',
@@ -116,8 +117,9 @@ def parse_email_task_intent(value):
def scope_email_tools(schemas, intent, *, active_editor=False):
if intent.operation == 'read' and intent.dependencies:
allowed = set().union(*(_DEPENDENCIES[d] for d in intent.dependencies))
if active_editor:
allowed = {tool for dependency in intent.dependencies
for tool in _DEPENDENCIES[dependency]}
if active_editor and intent.dependencies:
allowed.update(_OPEN_EDITOR_TOOLS)
if intent.needs_clarification:
allowed.add('ask_user')
@@ -126,6 +128,9 @@ def scope_email_tools(schemas, intent, *, active_editor=False):
if intent.operation not in {'draft', 'revise'}:
return list(schemas)
allowed = _DRAFT_TOOLS.union(*(_DEPENDENCIES[d] for d in intent.dependencies))
# manage_contact is a read-only runtime source for lookups, not a
# composition tool. Drafts still resolve recipients through resolve_contact.
allowed.discard('manage_contact')
if active_editor:
allowed.update(_OPEN_EDITOR_TOOLS)
if not intent.needs_clarification:
@@ -145,6 +150,62 @@ def scope_email_tools(schemas, intent, *, active_editor=False):
# as though it were the whole task. This byte budget is deliberately conservative.
CLASSIFIER_CONTEXT_BYTES = 24000
# The model can produce a structurally valid classification while forgetting
# the source or mistaking a list of message headers for a request for bodies.
_OWN_MAILBOX = re.compile(
r'\b(?:my|our)\s+(?:(?:last|latest|recent|new|unread|read|first|most|\d+)\s+){0,5}'
r'(?:e-?mails?|mail|inbox|mailbox)\b', re.IGNORECASE,
)
_MAILBOX_HEADER_LIST = re.compile(
r'^\s*(?:list|show|display|what(?:\'s| are))\s+(?:me\s+)?(?:my|our)\s+'
r'(?:(?:last|latest|recent|new|unread|read|first|most|\d+)\s+){0,5}'
r'(?:e-?mails|messages)\s*'
r'(?:with\s+(?:(?:sender|subject|date|time|recipient|status)\s*'
r'(?:(?:,|and)\s*)?)+)?[?.!]*\s*$', re.IGNORECASE,
)
_EMAIL_HEADER_FIELDS = re.compile(r'\b(?:subjects?|senders?|dates?)\b', re.IGNORECASE)
_EMAIL_HEADER_FOLLOWUP = re.compile(r'\b(?:those|these|them|their|same)\b', re.IGNORECASE)
_READ_REQUEST = re.compile(r'^\s*(?:please\s+)?(?:show|list|display|find|search|read|what|how many|are there|do i have)\b', re.IGNORECASE)
_EMAIL_COUNT = re.compile(r'^\s*how many\s+(?:(?:unread|read|new)\s+)?(?:e-?mails|messages)\b',
re.IGNORECASE)
_EMAIL_BODY_QUERY = re.compile(
r'\b(?:mention(?:s|ed|ing)?|body|contents?|amount|owe|says?|said|when|where|why|'
r'starts?|deadline|attachments?)\b|\bhow much\b|\bwhat time\b',
re.IGNORECASE)
_CONTACT_EMAIL_FIELD = re.compile(
r'\bcontacts?\b[^.!?\n]{0,100}\bemail\b', re.IGNORECASE,
)
_MAILBOX_SOURCE = re.compile(
r'\b(?:my|our)\s+(?:(?:last|latest|recent|new|unread|read|first|most|\d+)\s+){0,5}'
r'(?:e-?mails?|inbox|mailbox)\b|\b(?:inbox|mailbox|email\s+history)\b|'
r'\b(?:e-?mails?|messages?)\s+(?:from|to|sent|received)\b|'
r'\bemailed?\s+(?:me|us)\b', re.IGNORECASE,
)
EMAIL_TASK_RESPONSE_FORMAT = {
'type': 'json_schema',
'json_schema': {
'name': 'email_task_intent',
'strict': True,
'schema': {
'type': 'object',
'additionalProperties': False,
'properties': {
'operation': {'type': 'string', 'enum': ['draft', 'revise', 'read', 'send', 'other']},
'requires_content': {'type': 'boolean'},
'dependencies': {'type': 'array', 'items': {
'type': 'string', 'enum': list(_DEPENDENCIES),
}},
'destination': {'type': 'string', 'enum': ['chat', 'mailbox']},
'needs_clarification': {'type': 'boolean'},
'summary': {'type': 'string'},
},
'required': ['operation', 'requires_content', 'dependencies', 'destination',
'needs_clarification', 'summary'],
},
},
}
async def classify_email_task(client, *, endpoint_url, headers, model, history,
supplied_context=None, accounting=None):
@@ -152,6 +213,8 @@ async def classify_email_task(client, *, endpoint_url, headers, model, history,
# text from multimodal messages, so an attached image cannot hide the latest
# instruction and leave us classifying an earlier task instead.
dialogue = []
latest_user_text = ''
prior_user_text = ''
for row in history:
if row.get('role') not in {'user', 'assistant'} or row.get('_harness_control'):
continue
@@ -166,6 +229,9 @@ async def classify_email_task(client, *, endpoint_url, headers, model, history,
and isinstance(block.get('text'), str))
if isinstance(content, str):
dialogue.append({'role': row['role'], 'content': content})
if row['role'] == 'user':
prior_user_text = latest_user_text
latest_user_text = content
payload = json.dumps({'dialogue': dialogue, 'supplied_context': supplied_context},
ensure_ascii=False)
if len(payload.encode('utf-8')) > CLASSIFIER_CONTEXT_BYTES:
@@ -174,7 +240,7 @@ async def classify_email_task(client, *, endpoint_url, headers, model, history,
response = await client.post(endpoint_url, headers=headers, timeout=20, json={
'model': model, 'stream': False, 'temperature': 0, 'max_tokens': 500,
'chat_template_kwargs': {'enable_thinking': False},
'response_format': {'type': 'json_object'},
'response_format': EMAIL_TASK_RESPONSE_FORMAT,
'messages': [{'role': 'system', 'content': (
'Classify the current conversational task. Return JSON only with operation '
'(draft, revise, read, send, other), requires_content (boolean), dependencies (array containing only web, '
@@ -250,6 +316,47 @@ async def classify_email_task(client, *, endpoint_url, headers, model, history,
'response_time': round(time.monotonic() - started, 3),
})
try:
return parse_email_task_intent(json.loads(body['choices'][0]['message']['content']))
intent = parse_email_task_intent(json.loads(body['choices'][0]['message']['content']))
if intent.operation == 'read' and not intent.needs_clarification:
# In a contact-record question, "email" can name an address field
# rather than the mailbox as a source. Keep both dependencies when
# the request also names a mailbox/history source.
contact_email_field = bool(
_CONTACT_EMAIL_FIELD.search(latest_user_text)
and not _MAILBOX_SOURCE.search(latest_user_text)
)
if contact_email_field:
intent = replace(intent, dependencies=tuple(dict.fromkeys(
(*[d for d in intent.dependencies if d != 'email'], 'contacts')
)))
# Reuse the product's existing source classifier rather than a
# second vocabulary of mailbox phrases. The classifier has a known
# gap for possessive single-message questions, so retain that
# narrow fallback only when it found no competing source family.
from src.turn_contract import requested_capabilities
capabilities = requested_capabilities(latest_user_text)
# A header-only reference can inherit the immediately preceding
# mailbox read, but an intervening request or a competing source
# breaks that link. Never infer a read from an earlier write.
header_followup = (
not capabilities
and bool(_EMAIL_HEADER_FIELDS.search(latest_user_text))
and bool(_EMAIL_HEADER_FOLLOWUP.search(latest_user_text))
and bool(_READ_REQUEST.match(prior_user_text))
and requested_capabilities(prior_user_text) == {'email'}
)
mailbox_read = not contact_email_field and (capabilities == {'email'} or (
not capabilities and bool(_OWN_MAILBOX.search(latest_user_text))
) or header_followup)
else:
mailbox_read = False
if mailbox_read:
intent = replace(intent, dependencies=tuple(dict.fromkeys((*intent.dependencies, 'email'))))
if (not _EMAIL_BODY_QUERY.search(latest_user_text)
and (_MAILBOX_HEADER_LIST.fullmatch(latest_user_text)
or _EMAIL_HEADER_FIELDS.search(latest_user_text)
or _EMAIL_COUNT.match(latest_user_text))):
intent = replace(intent, requires_content=False)
return intent
except (KeyError, IndexError, TypeError) as exc:
raise ValueError('Invalid classifier response') from exc
+120
View File
@@ -0,0 +1,120 @@
"""Thin client for the local jeff-serve decision endpoint (POST /v1/systemone).
Trained decision adapters (triage, spam, guard-email, ...) answer a situation
with calibrated probabilities over named options in a single forward pass, with
no generated text to parse. Background jobs can prefer an adapter and fall back
to the normal LLM candidate chain whenever this client returns None.
Every call fails open (returns None) and is disabled per job unless the job's
flag is set, so importing/enabling this never changes behaviour on its own.
Env:
ODYSSEUS_JEFF_URL base URL of jeff-serve (default http://127.0.0.1:8765)
ODYSSEUS_JEFF_TIMEOUT per-request timeout in seconds (default 4.0)
ODYSSEUS_JEFF_<JOB> per-job enable flag, e.g. ODYSSEUS_JEFF_EMAIL_URGENCY=1
"""
from __future__ import annotations
import logging
import os
from typing import Any, Dict, Optional
import httpx
logger = logging.getLogger(__name__)
_DEFAULT_URL = "http://127.0.0.1:8765"
_FALSEY = ("", "0", "false", "off", "no")
def jeff_url() -> str:
"""Base URL of the local jeff-serve (no trailing slash)."""
return os.getenv("ODYSSEUS_JEFF_URL", _DEFAULT_URL).strip().rstrip("/")
def jeff_job_enabled(job: str) -> bool:
"""True when ODYSSEUS_JEFF_<JOB> is set to a truthy value. Default off."""
slug = "".join(c if (c.isalnum() or c == "_") else "_" for c in (job or "")).upper()
return os.getenv("ODYSSEUS_JEFF_" + slug, "0").strip().lower() not in _FALSEY
def jeff_timeout(default: float = 4.0) -> float:
try:
return float(os.getenv("ODYSSEUS_JEFF_TIMEOUT", str(default)))
except Exception:
return default
async def jeff_systemone(
model: str,
state: Dict[str, Any],
questions: Dict[str, Any],
*,
timeout: Optional[float] = None,
orders: int = 1,
client: Optional[httpx.AsyncClient] = None,
) -> Optional[Dict[str, Any]]:
"""POST a decision request and return the ``answers`` dict, or None on error.
Each question is scored in its own forward pass, so send only questions the
adapter was trained on. Raises are swallowed and logged (fail open).
"""
url = jeff_url()
if not url:
return None
payload: Dict[str, Any] = {"model": model, "state": state, "questions": questions}
if orders and orders != 1:
payload["orders"] = orders
to = timeout if timeout is not None else jeff_timeout()
try:
if client is None:
async with httpx.AsyncClient(timeout=to) as _c:
resp = await _c.post(url + "/v1/systemone", json=payload)
else:
resp = await client.post(url + "/v1/systemone", json=payload)
resp.raise_for_status()
answers = (resp.json() or {}).get("answers")
return answers if isinstance(answers, dict) else None
except Exception as exc:
logger.warning("jeff decision (%s) failed: %s", model, exc)
return None
async def jeff_available(timeout: float = 1.5) -> bool:
"""Best-effort health probe for the local jeff-serve."""
url = jeff_url()
if not url:
return False
try:
async with httpx.AsyncClient(timeout=timeout) as _c:
resp = await _c.get(url + "/health")
return resp.status_code == 200
except Exception:
return False
def score_value(answer: Optional[Dict[str, Any]]) -> Optional[float]:
"""Expected value (0..n-1) of a jeff ``score`` answer, or None."""
if not isinstance(answer, dict):
return None
if answer.get("type") == "score":
try:
return float(answer.get("score"))
except Exception:
return None
if answer.get("type") == "choice":
probs = answer.get("probabilities") or {}
try:
return float(sum(i * float(p) for i, p in enumerate(probs.values())))
except Exception:
return None
return None
def choice_of(answer: Optional[Dict[str, Any]]) -> Optional[str]:
"""The winning key of a jeff ``choice`` answer, or None."""
if isinstance(answer, dict) and answer.get("type") == "choice":
c = answer.get("choice")
return str(c) if c is not None else None
return None
+38
View File
@@ -0,0 +1,38 @@
"""Pre-Wave-3 private_browser schema (agent-browser wrapper), used when ODYSSEUS_PRIVATE_BROWSER_LEGACY is on."""
PRIVATE_BROWSER_SCHEMA = {
"type": "function",
"function": {
"name": "private_browser",
"description": "Private browser automation through Odysseus' agent-browser wrapper. After open, snapshot the page and interact with returned element refs such as @e12; click/fill target is a selector or element ref, never guessed visible text. Prefer one batch for known consecutive steps, such as open plus snapshot. Use only when a specific page needs JavaScript, login/session state, interaction, or rendered DOM. For open-ended search use web_search; for reading a normal URL use web_fetch.",
"parameters": {
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["open", "read", "snapshot", "find", "evaluate", "click", "fill", "press", "scroll", "wait", "screenshot", "close", "batch"]},
"url": {"type": "string", "description": "Required URL for open; optional URL for read (omit to read the current page)"},
"selector": {"type": "string", "description": "Element ref or selector for read/click/fill/wait"},
"target": {"type": "string", "description": "Element ref returned by snapshot (preferred, e.g. @e12) or CSS selector for read/click/fill/wait; never a guessed visible label; top or bottom for scroll"},
"key": {"type": "string", "description": "Key name for press action, e.g. Enter"},
"direction": {"type": "string", "enum": ["up", "down", "left", "right"], "description": "Direction for scroll action"},
"amount": {"type": "integer", "minimum": 1, "description": "Optional scroll distance in pixels; default 300"},
"text": {"type": "string", "description": "Text for fill action"},
"value": {"type": "string", "description": "Alternative text/value for fill action"},
"find": {"type": "string", "description": "Visible text to locate for find action"},
"script": {"type": "string", "description": "JavaScript expression for evaluate action"},
"path": {"type": "string", "description": "Optional output path for screenshot"},
"commands": {
"type": "array",
"description": "Non-empty batch commands as arrays, e.g. [[\"open\", \"https://example.com\"], [\"snapshot\"]]. Do not send an empty batch; use action=snapshot for current page state.",
"items": {
"oneOf": [
{"type": "array", "items": {"type": "string"}},
{"type": "object"},
]
},
},
"timeout_ms": {"type": "integer", "description": "Optional operation timeout, max 120000; for action=wait without a selector, this is the wait duration"}
},
"required": ["action"]
}
}
}
+2
View File
@@ -78,6 +78,8 @@ def untrusted_context_message(
"""
safe_label = _sanitize_label(label)
text = "" if content is None else str(content)
import logging as _lg
_lg.getLogger("src.prompt_security").info("[spec-debug] untrusted block label=%r content_chars=%d", safe_label[:80], len(text))
text = _escape_guard_markers(text)
metadata: Dict[str, Any] = {
"trusted": False,
+7 -5
View File
@@ -67,7 +67,7 @@ async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bo
"""
from core.database import SessionLocal, Session as DbSession, ChatMessage as DbMsg
from src.llm_core import llm_call_async
from src.task_endpoint import resolve_task_endpoint
from src.task_endpoint import resolve_task_endpoint, task_llm_call_async
db = SessionLocal()
try:
@@ -164,8 +164,6 @@ async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bo
return f"Cleaned {deleted_empty + deleted_throwaway} sessions (folder sort skipped)."
url, model, headers = resolve_task_endpoint(owner=owner or None)
if not url:
return f"Cleaned {deleted_empty + deleted_throwaway} sessions. No model endpoint available for sorting."
names_text = "\n".join(f' "{s["id"][:8]}": "{s["name"]}"' for s in session_list)
prompt = (
@@ -183,8 +181,12 @@ async def run_auto_sort(owner: str, skip_llm: bool = False, delete_throwaway: bo
try:
# 16384 (was 4096): large folder JSON + reasoning-model thinking
# overflowed 4096 and truncated the JSON, so it never parsed.
raw = await llm_call_async(url, model, [{"role": "user", "content": prompt}],
temperature=0.3, max_tokens=16384, headers=headers, timeout=120)
raw = await task_llm_call_async(
[{"role": "user", "content": prompt}],
fallback_url=url, fallback_model=model, fallback_headers=headers,
owner=owner or None,
temperature=0.3, max_tokens=16384, timeout=120,
)
except Exception as e:
logger.warning(f"Auto-sort LLM call failed: {e}")
return f"Cleaned {deleted_empty + deleted_throwaway} sessions. Folder sort skipped (model unreachable)."
+270
View File
@@ -0,0 +1,270 @@
"""Ajax Spec turn: the Spec router drives every step; the chat model never chooses a tool.
Each round the router (spec_router.next_action) picks one action from the full tool surface:
tool -> the chat model gets only that tool (named tool_choice) and writes its arguments;
the executor runs it; the result goes back to the router for the next pick.
answer_directly -> the chat model writes the answer with no tools (tools key omitted).
ask_user -> the chat model writes the question through the ask_user tool.
Router unavailable -> the chat model answers without tools. Execution keeps the normal request
authority and tool policy (execute_tool_block); nothing else is layered on top.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import time
import uuid
import httpx
from src import spec_router
from src.agent_runtime.authority import MISSING_AUTHORITY, with_request_authority
from src.clean_agent_preview import (
event, preview_model_response, preview_tool_result_text,
)
from src.tool_capabilities import ToolRunSecurityContext
from src.tool_execution import execute_tool_block
from src.tool_schemas import FUNCTION_TOOL_SCHEMAS, function_call_to_tool_block
logger = logging.getLogger(__name__)
def _text(content):
if isinstance(content, str):
return content
if isinstance(content, list):
return '\n'.join(str(p.get('text') or '') for p in content
if isinstance(p, dict) and p.get('type') == 'text')
return ''
def _name(schema):
return (schema.get('function') or {}).get('name') or ''
# JSON-schema keywords the provider's guided decoding (named tool_choice) cannot compile.
_GRAMMAR_UNSUPPORTED = frozenset({
'uniqueItems', 'contains', 'minContains', 'maxContains', 'patternProperties', 'propertyNames',
'dependentRequired', 'dependentSchemas', 'if', 'then', 'else',
'unevaluatedProperties', 'unevaluatedItems',
})
def grammar_safe(schema):
"""Copy of a schema without keywords guided decoding rejects (validation still runs at execution)."""
if isinstance(schema, dict):
return {k: grammar_safe(v) for k, v in schema.items() if k not in _GRAMMAR_UNSUPPORTED}
if isinstance(schema, list):
return [grammar_safe(v) for v in schema]
return schema
def spec_surface(disabled_tools):
disabled = set(disabled_tools or ())
return [s for s in FUNCTION_TOOL_SCHEMAS if _name(s) and _name(s) not in disabled]
async def _model_round(client, endpoint_url, headers, request, recovery):
"""Run one chat-model round; return (content, tool_calls, usage)."""
content, calls, usage, raw = '', {}, {}, []
async with preview_model_response(client, endpoint_url, headers, request, recovery) as response:
async for line in response.aiter_lines():
if len(raw) < 4 and line.strip():
raw.append(line[:400])
if line.strip() and not line.startswith('data: '):
logger.warning('[spec-driver] unexpected stream line: %s', line[:500])
if not line.startswith('data: ') or line.strip() == 'data: [DONE]':
continue
try:
chunk = json.loads(line[6:])
except ValueError:
continue
if chunk.get('error') or chunk.get('object') == 'error':
raise RuntimeError(f"model stream error: {str(chunk.get('error') or chunk)[:500]}")
usage = chunk.get('usage') or usage
for choice in chunk.get('choices') or []:
delta = choice.get('delta') or {}
text = delta.get('content') or ''
content += text
for frag in delta.get('tool_calls') or []:
call = calls.setdefault(frag.get('index', 0), {'id': '', 'name': '', 'arguments': ''})
call['id'] = frag.get('id') or call['id']
fn = frag.get('function') or {}
call['name'] += fn.get('name') or ''
call['arguments'] += fn.get('arguments') or ''
if not calls:
logger.warning('[spec-driver] no tool call; status=%s max_tokens=%s msgs=%s first lines=%s',
getattr(response, 'status_code', None), request.get('max_tokens'),
[(m.get('role'), type(m.get('content')).__name__,
[p.get('type') for p in m['content']] if isinstance(m.get('content'), list) else len(str(m.get('content') or '')))
for m in request.get('messages', [])], raw[-2:])
return content, [calls[i] for i in sorted(calls)], usage
@with_request_authority
async def stream_spec_turn(*, endpoint_url, model, messages, headers, session_id, owner,
disabled_tools, tool_policy, workspace=None, active_document=None,
client_runtime_context=None, external_untrusted_context_seen=False,
max_tokens=768, max_rounds=8, temperature=0.0,
request_authority=MISSING_AUTHORITY, **ignored):
from src.turn_contract import _ACTIVE_CONTRACT
_ACTIVE_CONTRACT.set(None) # Spec, not the regex turn contract, decides the tools.
started = time.monotonic()
surface = spec_surface(disabled_tools)
by_name = {_name(s): s for s in surface}
user_text = next((_text(m.get('content')) for m in reversed(messages) if m.get('role') == 'user'), '')
history = list(messages)
security = ToolRunSecurityContext(
external_untrusted_context_seen=bool(external_untrusted_context_seen), unattended_tools=frozenset())
security.observe_messages(messages)
picks, executions, done_calls = [], [], set()
latest, first_token, usage_in, usage_out, rounds = '', None, 0, 0, 0
recovery = {}
async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0)) as client:
for round_number in range(1, max_rounds + 1):
rounds = round_number
action = await asyncio.to_thread(
spec_router.next_action, user_text, latest, surface, messages[:-1], disabled_tools)
if action is None:
action = {'kind': 'answer_directly', 'name': 'router_unavailable', 'p': None}
if round_number == max_rounds and action['kind'] == 'tool':
action = {'kind': 'answer_directly', 'name': 'round_limit', 'p': None}
picks.append({'round': round_number, **action})
logger.info('[spec-driver] round=%s pick=%s p=%s', round_number, action['name'], action.get('p'))
request = {'model': model, 'messages': history, 'max_tokens': max_tokens,
'temperature': temperature, 'stream': True,
'stream_options': {'include_usage': True},
'chat_template_kwargs': {'enable_thinking': False}}
if action['kind'] == 'answer_directly':
answer_parts = []
async with preview_model_response(client, endpoint_url, headers, request, recovery) as response:
async for line in response.aiter_lines():
if not line.startswith('data: ') or line.strip() == 'data: [DONE]':
continue
try:
chunk = json.loads(line[6:])
except ValueError:
continue
if chunk.get('error') or chunk.get('object') == 'error':
raise RuntimeError(f"model stream error: {str(chunk.get('error') or chunk)[:500]}")
u = chunk.get('usage') or {}
usage_in += u.get('prompt_tokens') or 0
usage_out += u.get('completion_tokens') or 0
for choice in chunk.get('choices') or []:
text = (choice.get('delta') or {}).get('content') or ''
if text:
first_token = first_token or time.monotonic()
answer_parts.append(text)
yield event({'delta': text})
answer = ''.join(answer_parts).strip()
if not answer:
yield event({'delta': 'The model returned no answer.'})
history.append({'role': 'assistant', 'content': answer})
break
name = 'ask_user' if action['kind'] == 'ask_user' else action['name']
# ODYSSEUS_SPEC_DRIVER_TOPK=k>1: offer Spec's top-k tools and let the chat model choose among them.
topk = int(os.getenv('ODYSSEUS_SPEC_DRIVER_TOPK', '1') or 1)
options = [name]
if action['kind'] == 'tool' and topk > 1:
options = [n for n, _ in action.get('top') or []][:topk] or [name]
schemas = [by_name.get(n) or next((s for s in FUNCTION_TOOL_SCHEMAS if _name(s) == n), None)
for n in options]
options = [n for n, sc in zip(options, schemas) if sc is not None]
schemas = [sc for sc in schemas if sc is not None]
if not schemas:
logger.info('[spec-driver] pick %s has no schema; answering instead', name)
latest = f'Tool {name} is not available.'
continue
request['tools'] = [grammar_safe(sc) for sc in schemas]
request['tool_choice'] = ({'type': 'function', 'function': {'name': options[0]}}
if len(options) == 1 else 'required')
if len(options) > 1:
logger.info('[spec-driver] round=%s options=%s', round_number, options)
try:
content, calls, usage = await _model_round(client, endpoint_url, headers, request, recovery)
except (RuntimeError, httpx.HTTPError) as exc:
logger.warning('[spec-driver] round=%s %s call failed: %s', round_number, name, exc)
latest = f'The {name} call could not be produced: {exc}'
continue
first_token = first_token or time.monotonic()
usage_in += usage.get('prompt_tokens') or 0
usage_out += usage.get('completion_tokens') or 0
call = next((c for c in calls if c['name'] in options), None)
if call is not None and len(options) > 1:
name = call['name']
logger.info('[spec-driver] round=%s model chose=%s rank=%s of %s',
round_number, name, options.index(name) + 1, options)
picks[-1]['chosen'] = name
if call is None:
latest = f'The {name} call was not produced.'
logger.info('[spec-driver] round=%s no %s call from the model', round_number, name)
continue
arguments = call['arguments'] or '{}'
signature = (name, arguments)
call_id = call['id'] or f'call_{uuid.uuid4().hex[:12]}'
history.append({'role': 'assistant', 'content': content or '',
'tool_calls': [{'id': call_id, 'type': 'function',
'function': {'name': name, 'arguments': arguments}}]})
if signature in done_calls:
output = 'This exact call already succeeded; its result is above. Do not repeat it.'
history.append({'role': 'tool', 'tool_call_id': call_id, 'content': output})
latest = output
continue
try:
args = json.loads(arguments)
except ValueError:
args = {}
block = function_call_to_tool_block(name, arguments)
yield event({'type': 'tool_start', 'tool': name, 'command': arguments,
'full_command': arguments, 'round': round_number})
tool_started = time.monotonic()
if block is None:
desc, result = f'{name}: invalid arguments', {
'error': 'Tool arguments could not be converted for execution.', 'exit_code': 1}
else:
desc, result = await execute_tool_block(
block, session_id=session_id, owner=owner, disabled_tools=disabled_tools,
tool_policy=tool_policy, security_context=security,
active_document_id=getattr(active_document, 'id', None), workspace=workspace,
client_runtime_context=client_runtime_context, request_authority=request_authority)
failed = bool(result.get('error')) or result.get('exit_code') not in (None, 0)
output = preview_tool_result_text(result, name, args)
tool_event = {'type': 'tool_output', 'tool': name, 'command': arguments, 'output': output,
'exit_code': result.get('exit_code', 1 if failed else 0), 'error': failed,
'execution_attempted': block is not None, 'blocked': bool(result.get('blocked')),
'desc': desc, 'round': round_number,
'seconds': round(time.monotonic() - tool_started, 3)}
if result.get('image_url'):
yield event({'type': 'generated_image', 'url': result['image_url'],
**{k: result[k] for k in ('image_url', 'image_id', 'image_prompt') if k in result}})
if result.get('ui_event'):
yield event({'type': 'ui_control', 'data': result})
executions.append(tool_event)
yield event(tool_event)
history.append({'role': 'tool', 'tool_call_id': call_id, 'content': output})
if not failed:
done_calls.add(signature)
latest = output
ask = result.get('ask_user')
if isinstance(ask, dict) and str(ask.get('question') or '').strip():
question = str(ask['question']).strip()
history.append({'role': 'assistant', 'content': question})
yield event({'type': 'final_response', 'content': question})
yield event({'type': 'ask_user', 'data': ask})
break
elapsed = time.monotonic() - started
yield event({'type': 'metrics', 'data': {
'model': model, 'input_tokens': usage_in, 'output_tokens': usage_out,
'total_tokens': usage_in + usage_out, 'response_time': round(elapsed, 3),
'time_to_first_token': round(first_token - started, 3) if first_token else None,
'tokens_per_second': round(usage_out / elapsed, 2) if elapsed > 0 else 0,
'agent_rounds': rounds, 'tool_calls': len(executions), 'tool_events': executions,
'spec_driver_picks': picks, 'tool_schema_count': len(surface),
'schema_mode': 'spec_driver', 'temperature': temperature, 'max_output_tokens': max_tokens,
}})
yield 'data: [DONE]\n\n'
+396
View File
@@ -0,0 +1,396 @@
"""Odysseus spec: small-model tool router (JEFF-style) for the agent harness.
The router (a 0.8B decision model served by jeff-serve) reads the user's
message and scores every offered tool in one forward pass. The harness only
ever ADDS tools from its answer, never removes any, and fails open: on any
error, timeout or low-confidence answer the compact tool set is unchanged.
Env:
ODYSSEUS_SPEC_ROUTER_URL jeff-serve base URL, e.g. http://ajax:8765 (unset = disabled)
ODYSSEUS_SPEC_ROUTER_MODEL adapter name (default: odysseus-s60)
ODYSSEUS_SPEC_ROUTER_TIMEOUT seconds (default: 0.5)
ODYSSEUS_SPEC_ROUTER_MIN_CONF minimum top-1 probability to act (default: 0.3)
ODYSSEUS_SPEC_ROUTER_SECOND minimum 2nd-choice probability to also add it (default: 0.25)
"""
from __future__ import annotations
import json
import logging
import os
import time
import urllib.request
import urllib.error
from typing import Any, Dict, Iterable, List, Optional, Set
logger = logging.getLogger(__name__)
_HEAD = {
"answer_directly": "No tool is needed: answer the user directly from the conversation",
"ask_user": "A tool is needed but required information is missing: ask the user first",
}
_INSTRUCTIONS = (
"Which tool should the agent call next to handle the user's latest message? "
"Use the conversation for context. If no tool is needed, choose answer directly. "
"If a tool is needed but information it requires is missing, choose ask the user."
)
_AGENT = "Odysseus, a personal tool-using assistant."
# Recent decisions, for debugging in the UI/logs: most recent last.
LAST_DECISIONS: List[Dict[str, Any]] = []
_MCP_BROWSER_TOOLS = (
"mcp__builtin_browser__browser_navigate",
"mcp__builtin_browser__browser_snapshot",
"mcp__builtin_browser__browser_click",
"mcp__builtin_browser__browser_type",
"mcp__builtin_browser__browser_press_key",
"mcp__builtin_browser__browser_wait_for",
"mcp__builtin_browser__browser_take_screenshot",
)
def _fn(schema: Dict[str, Any]) -> Dict[str, Any]:
return schema.get("function") if isinstance(schema.get("function"), dict) else schema
def tool_line(schema: Dict[str, Any]) -> str:
fn = _fn(schema)
name = str(fn.get("name") or "")
props = ((fn.get("parameters") or {}).get("properties") or {})
if os.getenv("ODYSSEUS_SPEC_TOOL_FORMAT", "").strip().lower() == "names":
return name + "(" + ", ".join(props) + ")" # names + parameters only (spec_v1n adapters are trained on this)
desc = " ".join(str(fn.get("description") or "").split())
if len(desc) > 220:
desc = desc[:217] + "..."
return f"{name}({', '.join(props)}): {desc}"
def prior_tool_names(messages: Optional[Iterable[Dict[str, Any]]]) -> Set[str]:
"""Tools already called in this conversation (kept offered: no 'forgetting')."""
seen: Set[str] = set()
for m in messages or []:
if not isinstance(m, dict) or m.get("role") != "assistant":
continue
for tc in m.get("tool_calls") or []:
name = (tc.get("function") or tc).get("name") if isinstance(tc, dict) else None
if name:
seen.add(str(name))
return seen
def _conversation(messages: Optional[Iterable[Dict[str, Any]]], limit: int = 4) -> List[Dict[str, str]]:
out: List[Dict[str, str]] = []
for m in list(messages or []):
if isinstance(m, dict) and m.get("role") in ("user", "assistant") and isinstance(m.get("content"), str) and m["content"].strip():
out.append({"role": m["role"], "content": m["content"][:600]})
# the last user message is passed separately as user_message
if out and out[-1]["role"] == "user":
out = out[:-1]
return out[-limit:]
def enabled() -> bool:
return bool(os.getenv("ODYSSEUS_SPEC_ROUTER_URL", "").strip())
def spec_route_tools(
user_message: str,
schemas: Iterable[Dict[str, Any]],
disabled_tools: Optional[Set[str]] = None,
messages: Optional[Iterable[Dict[str, Any]]] = None,
return_decision: bool = False,
):
"""Return tool names the router wants offered (plus tools already used).
With return_decision=True returns (tools, decided) where decided is True when
the router answered confidently (a tool pick, or answer_directly)."""
added: Set[str] = set(prior_tool_names(messages))
decided = False
url = os.getenv("ODYSSEUS_SPEC_ROUTER_URL", "").strip().rstrip("/")
if not url or not (user_message or "").strip():
return (added, False) if return_decision else added
t0 = time.time()
decision: Dict[str, Any] = {"ts": time.time(), "message": user_message[:160], "sticky": sorted(added)}
try:
disabled = set(disabled_tools or ())
lines: Dict[str, str] = {}
for s in schemas:
n = str(_fn(s).get("name") or "")
if n and n not in disabled and n != "ask_user" and n not in lines:
lines[n] = tool_line(s)
names = sorted(lines)
criteria = dict(_HEAD)
for i, n in enumerate(names, 1):
criteria[f"t{i}"] = lines[n]
req = {
"model": os.getenv("ODYSSEUS_SPEC_ROUTER_MODEL", "odysseus-s60"),
"state": {"agent": _AGENT, "conversation": _conversation(messages), "user_message": user_message},
"questions": {"tool": {"type": "choice", "instructions": _INSTRUCTIONS, "criteria": criteria}},
}
http = urllib.request.Request(
url + "/v1/systemone", data=json.dumps(req).encode(), headers={"content-type": "application/json"}
)
timeout = float(os.getenv("ODYSSEUS_SPEC_ROUTER_TIMEOUT", "0.5"))
deadline = time.time() + timeout
while True:
try:
out = json.load(urllib.request.urlopen(http, timeout=max(0.2, deadline - time.time())))["answers"]["tool"]
break
except urllib.error.HTTPError as busy:
# 529 = router busy with another request; retry within budget.
if busy.code != 529 or time.time() + 0.15 >= deadline:
raise
decision["retries"] = decision.get("retries", 0) + 1
time.sleep(0.1)
probs = out.get("probabilities") or {}
choice = out.get("choice")
min_conf = float(os.getenv("ODYSSEUS_SPEC_ROUTER_MIN_CONF", "0.3"))
second_min = float(os.getenv("ODYSSEUS_SPEC_ROUTER_SECOND", "0.25"))
ranked = sorted(
((p, k) for k, p in probs.items() if k.startswith("t") and k[1:].isdigit()), reverse=True
)
picks: List[str] = []
if choice and choice.startswith("t") and choice[1:].isdigit() and float(probs.get(choice, 0.0)) >= min_conf:
picks.append(names[int(choice[1:]) - 1])
for p, k in ranked[:3]:
nm = names[int(k[1:]) - 1]
if nm not in picks and p >= second_min:
picks.append(nm)
_bmode = os.getenv("ODYSSEUS_SPEC_BROWSER_FALLBACK", "0")
if _bmode != "0" and "private_browser" in picks:
# This build disables page execution in private_browser (see
# src/browser_identity.py). "mcp": use the connected Playwright MCP
# browser (no run_code/evaluate); "web": fetch/search only.
picks = [n for n in picks if n != "private_browser"]
extra = list(_MCP_BROWSER_TOOLS) if _bmode == "mcp" else []
for n in extra + ["web_search", "web_fetch"]:
if n not in picks:
picks.append(n)
added.update(picks)
decided = bool(picks) or (choice == "answer_directly" and float(probs.get("answer_directly", 0.0)) >= min_conf)
decision.update(choice=choice, tools=picks, ms=round((time.time() - t0) * 1000, 1),
top=[(names[int(k[1:]) - 1], round(p, 3)) for p, k in ranked[:3]],
answer_directly=round(float(probs.get("answer_directly", 0.0)), 3),
ask_user=round(float(probs.get("ask_user", 0.0)), 3))
except Exception as exc: # fail open
decision.update(error=str(exc)[:200], ms=round((time.time() - t0) * 1000, 1))
logger.warning("spec router failed open: %s", exc)
LAST_DECISIONS.append(decision)
del LAST_DECISIONS[:-50]
decision["decided"] = decided
logger.info("spec router: %s", {key: value for key, value in decision.items() if key != "message"})
return (added, decided) if return_decision else added
# ---- Ajax Spec: system prompt trimmed to the tools actually offered ----------
_CORE_PROMPT = (
"You are Ajax, the assistant in Odysseus. Emit one native tool call, then stop. "
"After a successful tool result, answer from it; never repeat the same tool with the same arguments."
)
_CODING_PROMPT = (
"HARD CODING ORDER: for code changes call read_file, then edit_file or apply_patch, then host_shell for tests. "
"Never run tests before the edit succeeds; after a read, your next call is the edit. "
"edit_file JSON is {path,old_string,new_string}; write_file only for new files or full rewrites."
)
_TOOL_NOTES = {
"manage_notes": "manage_notes: notes/checklists.",
"manage_documents": "manage_documents: document library; actions list/read/delete/tidy, use list+search to find by title/content.",
"create_document": "create_document: create editor-panel documents with title/content.",
"edit_document": "edit_document: edit the active editor document using command=<<<FIND>>>old<<<REPLACE>>>new<<<END>>> or edits=[{find,replace}].",
"update_document": "update_document: full active-document rewrite only.",
"manage_calendar": "manage_calendar: calendar events; actions create_event, update_event, delete_event, list_events.",
"manage_tasks": "manage_tasks: scheduled/recurring tasks; create uses action=create, name, prompt, task_type, schedule, scheduled_time, output_target; pause/resume/delete use task_id, so list/search first when only the name is known. Recurring reminders use manage_tasks.",
"manage_memory": "manage_memory: saved memories.",
"manage_contact": "manage_contact: address-book contacts.",
"manage_research": "manage_research: saved research reports.",
"manage_settings": "manage_settings: app settings.",
"manage_endpoints": "manage_endpoints: configured API endpoints.",
"list_models": "list_models: available models.",
"manage_mcp": "manage_mcp: MCP servers.",
"manage_skills": "manage_skills: skills.",
"manage_webhooks": "manage_webhooks: webhooks.",
"manage_bg_jobs": "manage_bg_jobs: running/background jobs.",
"search_chats": "search_chats: past chats.",
"web_search": "web_search: public web lookup, URLs, links.",
"web_fetch": "web_fetch: fetch a concrete URL/domain.",
"private_browser": "private_browser: rendered site interaction. Make separate calls: first action=open with the url, then action=snapshot; read/scroll/find as needed. Do not use action=batch. Only click/fill element refs returned by snapshot (for example @e12), never guessed labels.",
"mcp__builtin_browser__browser_navigate": "Browser: browser_navigate {url} opens a page; then browser_snapshot returns the page with element refs; browser_click/browser_type take ref values from the latest snapshot, never guessed labels.",
"youtube_tool": "youtube_tool: YouTube comments, transcripts, metadata, and latest channel video.",
"read_file": "read_file: workspace text, PDF, or Office document path.",
"edit_file": "edit_file: exact replacement in an existing workspace file.",
"write_file": "write_file: create or fully rewrite a workspace file.",
"apply_patch": "apply_patch: related multi-file workspace edits.",
"host_shell": "host_shell: run tests, builds, and verification in the active workspace.",
}
_EMAIL_NOTES = (
"Email: latest email/emails/inbox -> mcp__email__list_emails {folder:INBOX,max_results:1,unread_only:false}; "
"account list -> list_email_accounts; subject find+read -> mcp__email__list_emails {folder:INBOX,max_results:20}; "
"sender/topic search -> mcp__email__search_emails {max_results:10}; known id -> mcp__email__read_email; "
"new draft -> mcp__email__draft_email; attachment -> mcp__email__download_attachment {uid,index,folder,account}; "
"reply draft -> mcp__email__draft_email_reply {uid,account,body}; only explicit send-now -> mcp__email__reply_to_email {uid,account,body}; "
"archive/delete/mark -> mcp__email__archive_email/mcp__email__delete_email/mcp__email__mark_email_read. Never emit manage_email."
)
_AJAX_PROMPT_START = "You are Ajax, the assistant in Odysseus."
def trimmed_system_prompt(offered: Iterable[str]) -> str:
offered = set(offered or ())
parts = [_CORE_PROMPT]
if offered & {"edit_file", "apply_patch", "host_shell"}:
parts.append(_CODING_PROMPT)
parts += [_TOOL_NOTES[n] for n in sorted(offered) if n in _TOOL_NOTES]
if any(n.startswith("mcp__email__") or n in {"list_email_accounts"} for n in offered):
parts.append(_EMAIL_NOTES)
return " ".join(parts)
def trim_system_prompt(messages: List[Dict[str, Any]], offered: Iterable[str]) -> List[Dict[str, Any]]:
"""Swap the generic Ajax tool manual for one covering only the offered tools."""
out: List[Dict[str, Any]] = []
for m in messages:
if (
isinstance(m, dict)
and m.get("role") == "system"
and isinstance(m.get("content"), str)
and m["content"].startswith(_AJAX_PROMPT_START)
):
new = dict(m)
new["content"] = trimmed_system_prompt(offered)
logger.info("[spec-harness] system prompt trimmed %d -> %d chars", len(m["content"]), len(new["content"]))
out.append(new)
else:
out.append(m)
return out
def drop_skills_index(messages: List[Dict[str, Any]], offered: Iterable[str]) -> List[Dict[str, Any]]:
"""Ajax Spec: omit the ~1000-token skills index unless the skills tool is offered."""
if "manage_skills" in set(offered or ()):
return messages
out = [
m for m in messages
if not (isinstance(m, dict) and (m.get("metadata") or {}).get("source") == "available skills index")
]
if len(out) != len(messages):
logger.info("[spec-harness] dropped skills index (%d chars)", sum(len(str(m.get("content") or "")) for m in messages if m not in out))
return out
# --- Router-decided thinking (progressive thinking trigger) -------------------------------------------------
# The router classifies the user's request as THINK (needs reasoning: math/logic, tricky planning, subtle explanation or
# weighing options, first-instinct-likely-wrong questions) or DIRECT (plain doing, lookup, chit-chat).
# Zero-shot on 143 DeepSeek-labelled app requests (2026-10-13): odysseus-agentic-v1f acc 0.916, think recall 0.985,
# think precision 0.859, ~33 ms. Off unless ODYSSEUS_SPEC_THINK_ROUTER=1. Never raises; returns None on any error.
_THINK_DEF = ("This request needs genuine reasoning or figuring something out before answering: math and logic puzzles; "
"planning a tricky multi-step approach; explaining something subtle or weighing options; or questions where "
"a quick first instinct is likely wrong.")
_DIRECT_DEF = ("This request is plain doing, lookup, or chit-chat that can be answered directly without reasoning: simple "
"tool actions (set a reminder, search email, open a page, rename a file), simple facts, or small talk.")
_THINK_INSTRUCTIONS = ("Classify whether this single user request needs the assistant to THINK (deep reasoning / figuring "
"something out) before answering, or can be answered DIRECTLY (plain doing, lookup, or chit-chat). "
"Answer with exactly one of the two options.")
# 5-way request kind, exactly as trained into adapter thinkclass5 (2026-10-13; held-out 143: think/direct 96.5%,
# think precision 98.8%, recall 95.2%). Enabled with ODYSSEUS_SPEC_THINK_QUESTION=kind5 + ODYSSEUS_SPEC_THINK_MODEL=thinkclass5.
_KIND5_QUESTION = {"type": "choice", "instructions": "Read the user's request and classify it into exactly one of five kinds: math_logic, tricky_planning, explain_or_weigh, trap_question, or direct. Pick the option whose description fits best.", "criteria": {"math_logic": "Mathematical or logical computation/reasoning: arithmetic, word problems, logic puzzles, counting, proofs.", "tricky_planning": "Planning a multi-step approach with real constraints: schedules, itineraries, sequencing, resource or budget allocation, multi-part procedures.", "explain_or_weigh": "Explaining something subtle or weighing options/tradeoffs: comparisons, 'should I', pros and cons, recommendations with reasoning, nuanced why-explanations.", "trap_question": "A question where the obvious or first-instinct answer is likely wrong: riddles, trick questions, common misconceptions, counterintuitive facts.", "direct": "Plain doing, lookup, or chit-chat: simple tool actions, simple facts, small talk — no deep reasoning needed."}}
def think_router_enabled() -> bool:
return os.getenv("ODYSSEUS_SPEC_THINK_ROUTER", "0").strip() not in ("", "0", "false", "off")
def route_thinking(user_message: str) -> Optional[Dict[str, Any]]:
"""Return {'think': bool, 'p_think': float, 'ms': float} or None (disabled / error / empty message)."""
if not think_router_enabled():
return None
url = os.getenv("ODYSSEUS_SPEC_ROUTER_URL", "").strip().rstrip("/")
text = (user_message or "").strip()
if not url or not text:
return None
kind5 = os.getenv("ODYSSEUS_SPEC_THINK_QUESTION", "binary").strip().lower() == "kind5"
question = _KIND5_QUESTION if kind5 else {"type": "choice", "instructions": _THINK_INSTRUCTIONS,
"criteria": {"think": _THINK_DEF, "direct": _DIRECT_DEF}}
req = {
"model": os.getenv("ODYSSEUS_SPEC_THINK_MODEL", os.getenv("ODYSSEUS_SPEC_ROUTER_MODEL", "odysseus-s60")),
"state": {"agent": _AGENT, "conversation": [], "user_message": text[:4000]},
"questions": {"thinking": question},
}
t0 = time.time()
try:
timeout = float(os.getenv("ODYSSEUS_SPEC_ROUTER_TIMEOUT", "3.0"))
http = urllib.request.Request(url + "/v1/systemone", data=json.dumps(req).encode(),
headers={"content-type": "application/json"})
ans = json.load(urllib.request.urlopen(http, timeout=timeout))["answers"]["thinking"]
probs = ans.get("probabilities") or {}
# kind5: think = any of the four reasoning kinds (trained adapter thinkclass5); binary: P(think).
p = float(1.0 - probs.get("direct", 1.0)) if kind5 else float(probs.get("think", 0.0))
min_p = float(os.getenv("ODYSSEUS_SPEC_THINK_MIN_P", "0.5"))
out = {"think": p >= min_p, "p_think": round(p, 4), "ms": round((time.time() - t0) * 1000, 1)}
if kind5:
out["kind"] = ans.get("choice")
logger.info("spec think router: %s msg=%r", out, text[:120])
return out
except Exception as exc: # fail open: the existing progressive-thinking rules still apply
logger.warning("spec think router failed (%s); falling back to rule-based thinking", exc)
return None
# ---- Ajax Spec driver: the router picks every step --------------------------------------------------------
def next_action(user_message: str, latest_result: str, schemas: Iterable[Dict[str, Any]],
messages: Optional[Iterable[Dict[str, Any]]] = None,
disabled_tools: Optional[Set[str]] = None) -> Optional[Dict[str, Any]]:
"""Top-1 next action at any confidence: {'kind': 'tool'|'answer_directly'|'ask_user', 'name', 'p'}.
Same request as training (build_agentic_rows.py): sorted tool lines, and mid-turn the latest tool
result appended to the user message as "\\n\\nLatest tool result:\\n...". Returns None on any error."""
url = os.getenv("ODYSSEUS_SPEC_ROUTER_URL", "").strip().rstrip("/")
if not url:
return None
t0 = time.time()
disabled = set(disabled_tools or ())
lines: Dict[str, str] = {}
for s in schemas:
n = str(_fn(s).get("name") or "")
if n and n not in disabled and n != "ask_user" and n not in lines:
lines[n] = tool_line(s)
names = sorted(lines)
criteria = dict(_HEAD)
for i, n in enumerate(names, 1):
criteria[f"t{i}"] = lines[n]
um = (user_message or "")[-3000:]
if latest_result:
um += "\n\nLatest tool result:\n" + latest_result[-1500:]
req = {
"model": os.getenv("ODYSSEUS_SPEC_ROUTER_MODEL", "odysseus-agentic-v4"),
"state": {"agent": _AGENT, "conversation": _conversation(messages), "user_message": um},
"questions": {"tool": {"type": "choice", "instructions": _INSTRUCTIONS, "criteria": criteria}},
}
try:
http = urllib.request.Request(url + "/v1/systemone", data=json.dumps(req).encode(),
headers={"content-type": "application/json"})
timeout = float(os.getenv("ODYSSEUS_SPEC_ROUTER_TIMEOUT", "3.0"))
deadline = time.time() + timeout
while True:
try:
out = json.load(urllib.request.urlopen(http, timeout=max(0.2, deadline - time.time())))["answers"]["tool"]
break
except urllib.error.HTTPError as busy:
if busy.code != 529 or time.time() + 0.15 >= deadline:
raise
time.sleep(0.1)
probs = out.get("probabilities") or {}
choice = str(out.get("choice") or "")
if choice.startswith("t") and choice[1:].isdigit():
action = {"kind": "tool", "name": names[int(choice[1:]) - 1]}
elif choice in ("answer_directly", "ask_user"):
action = {"kind": choice, "name": choice}
else:
return None
ranked = sorted(((float(v), k) for k, v in probs.items() if k.startswith("t") and k[1:].isdigit()), reverse=True)
action.update(p=round(float(probs.get(choice, 0.0)), 3), ms=round((time.time() - t0) * 1000, 1),
top=[(names[int(k[1:]) - 1], round(v, 3)) for v, k in ranked[:6]])
logger.info("spec next action: %s msg=%r", action, (user_message or "")[:80])
return action
except Exception as exc:
logger.warning("spec next action failed: %s", exc)
return None
+28 -1
View File
@@ -1558,8 +1558,29 @@ def _agent_subprocess_env() -> dict:
return base
def _legacy_private_browser_enabled() -> bool:
return os.getenv("ODYSSEUS_PRIVATE_BROWSER_LEGACY", "0").strip().lower() not in {"0", "false", "no", "off"}
async def _legacy_private_browser(operation, transport, *, progress_cb=None, session_id=None, owner=None):
from src.agent_tools.web_tools_prewave3 import PrivateBrowserTool
ctx = {
"progress_cb": progress_cb,
"subproc_env": _agent_subprocess_env(),
"session_id": session_id,
"owner": owner,
}
try:
result = await PrivateBrowserTool().execute(operation.input, ctx)
except asyncio.CancelledError:
raise
except Exception as error:
logger.warning("legacy private_browser failed: %s", error)
return f"{transport}: ERROR", {"error": f"private_browser: {error}", "exit_code": 1}
if not isinstance(result, dict):
result = {"output": str(result), "exit_code": 0}
label = "ERROR" if result.get("error") or result.get("exit_code") not in (None, 0) else "EXECUTED"
return f"{transport}: {label}", result
async def _direct_fallback(
@@ -1735,6 +1756,12 @@ async def execute_tool_block(
}
transport = operation.transport_tool
if operation.tool == "private_browser" and _legacy_private_browser_enabled():
# Restored pre-Wave-3 private_browser (agent-browser CLI). The Wave 3
# producer in src.browser_identity refuses every page action in this
# build. This compatibility transport requires an explicit opt-in.
return await _legacy_private_browser(
operation, transport, progress_cb=progress_cb, session_id=session_id, owner=owner)
if operation.tool == "private_browser":
try:
_, browser_args = parse_browser_operation(operation.input)
@@ -2603,4 +2630,4 @@ def format_tool_result(description: str, result: Dict) -> str:
# External execution bridges are allowed to return canonical result shapes
# without using the built-in tools' output cap. Bound the final model-facing
# text here so one verbose command cannot consume the next request window.
return _truncate("\n".join(parts))
return _truncate("\n".join(parts))
+9 -1
View File
@@ -2000,6 +2000,14 @@ FUNCTION_TOOL_SCHEMAS = [
},
]
if os.getenv("ODYSSEUS_PRIVATE_BROWSER_LEGACY", "0").strip().lower() not in {"0", "false", "no", "off"}:
# Restored pre-Wave-3 private_browser (see src.tool_execution._legacy_private_browser).
from src.private_browser_legacy_schema import PRIVATE_BROWSER_SCHEMA as _PB_LEGACY
FUNCTION_TOOL_SCHEMAS[:] = [
_PB_LEGACY if (schema.get("function") or {}).get("name") == "private_browser" else schema
for schema in FUNCTION_TOOL_SCHEMAS
]
# ---------------------------------------------------------------------------
@@ -2460,4 +2468,4 @@ def function_call_to_tool_block(name: str, arguments: str) -> Optional[ToolBlock
else:
content = json.dumps(args)
return ToolBlock(tool_type, content)
return ToolBlock(tool_type, content)
+24 -1
View File
@@ -155,11 +155,34 @@ body {
@font-face { font-family: 'Fira Code'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/FiraCode-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Fira Code'; font-weight: 600; font-style: normal; font-display: swap; src: url('/static/fonts/FiraCode-SemiBold.woff2') format('woff2'); }
/* Self-hosted OpenDyslexic — dyslexia-friendly accessibility font option (SIL OFL 1.1) */
@font-face { font-family: 'OpenDyslexic'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/OpenDyslexic-Regular.woff2') format('woff2'); }
@font-face { font-family: 'OpenDyslexic'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/OpenDyslexic-Bold.woff2') format('woff2'); }
/* Self-hosted editor text fonts (SIL OFL 1.1). These are bundled so the text
tool renders distinct, expected faces on every device — phones (Android/iOS)
do not ship Arial/Verdana/Georgia/Times/Courier/Impact, which previously
collapsed every font choice onto the same system fallback. */
@font-face { font-family: 'Inter'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/Inter-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Inter'; font-weight: 500; font-style: normal; font-display: swap; src: url('/static/fonts/Inter-Medium.woff2') format('woff2'); }
@font-face { font-family: 'Inter'; font-weight: 600; font-style: normal; font-display: swap; src: url('/static/fonts/Inter-SemiBold.woff2') format('woff2'); }
@font-face { font-family: 'Roboto'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/Roboto-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Roboto'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/Roboto-Bold.woff2') format('woff2'); }
@font-face { font-family: 'Playfair Display'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/PlayfairDisplay-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Playfair Display'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/PlayfairDisplay-Bold.woff2') format('woff2'); }
@font-face { font-family: 'Lobster'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/Lobster-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Bebas Neue'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/BebasNeue-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Roboto Mono'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/RobotoMono-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Roboto Mono'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/RobotoMono-Bold.woff2') format('woff2'); }
@font-face { font-family: 'Space Grotesk'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/SpaceGrotesk-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Space Grotesk'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/SpaceGrotesk-Bold.woff2') format('woff2'); }
@font-face { font-family: 'Fraunces'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/Fraunces-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Fraunces'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/Fraunces-Bold.woff2') format('woff2'); }
@font-face { font-family: 'Syne'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/Syne-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Syne'; font-weight: 700; font-style: normal; font-display: swap; src: url('/static/fonts/Syne-Bold.woff2') format('woff2'); }
@font-face { font-family: 'Bungee'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/Bungee-Regular.woff2') format('woff2'); }
@font-face { font-family: 'Instrument Serif'; font-weight: 400; font-style: normal; font-display: swap; src: url('/static/fonts/InstrumentSerif-Regular.woff2') format('woff2'); }
/* Code block baseline */
pre, code, .hljs {
font-size: 11px;
+33
View File
@@ -7230,6 +7230,39 @@ body.bg-pattern-ascii-fireflies {
text-align: center;
}
/* Inline assistant markdown images (`![alt](url)`) — rendered by
static/js/markdown.js as a.clickable <a class="chat-image"> wrapper. */
a.chat-image {
display: inline-block;
max-width: 100%;
margin: 0.35rem 0;
}
a.chat-image img.chat-inline-image {
display: block;
max-width: 100%;
height: auto;
border-radius: 8px;
cursor: zoom-in;
}
a.chat-image .chat-image-fallback {
display: none;
font-size: 0.8rem;
color: var(--color-muted, #94a3b8);
word-break: break-all;
padding: 0.5rem 0.75rem;
border: 1px dashed var(--border, #475569);
border-radius: 8px;
background: var(--panel, #202428);
}
a.chat-image.image-broken img.chat-inline-image {
display: none;
}
a.chat-image.image-broken .chat-image-fallback {
display: block;
text-decoration: underline;
cursor: pointer;
}
/* Setup wizard */
.setup-wizard { padding: 16px; max-width: 500px; }
.setup-wizard .setup-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 12px; color: var(--fg); }
+14
View File
@@ -22,6 +22,20 @@
/* Session items */
.session-item { position: relative; }
/* Title fade: the server auto-renames a chat shortly after its first
prompt, which re-renders the sidebar. Fade the new title in so the
change reads as smooth rather than a snap. */
.session-item .grow.session-title-updated {
animation: sessionTitleFade 0.5s ease;
}
@keyframes sessionTitleFade {
from { opacity: 0; transform: translateY(2px); }
to { opacity: 1; transform: translateY(0); }
}
@media (prefers-reduced-motion: reduce) {
.session-item .grow.session-title-updated { animation: none; }
}
.text-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.session-menu-btn { padding: 0 2px !important; min-width: 20px; height: 20px; display: inline-flex !important; align-items: center; justify-content: center; background: none !important; border-color: transparent !important; }
.session-menu-btn:hover { background: none !important; border-color: transparent !important; }
+1
View File
@@ -704,6 +704,7 @@ textarea.memory-add-input {
#serve-bulk-bar,
#gallery-bulk-bar,
#gallery-editor-drafts-bulk,
#notes-bulk-bar,
#memory-modal .memory-bulk-bar {
padding-right: 18px;
}
+6
View File
@@ -90,6 +90,12 @@
.lib-tabs,
.gallery-tabs,
.preset-tabs {
/* A flex-item tab strip defaults to min-width:auto, so it grows to its
content width inside a narrow modal and the end tabs get clipped by the
modal's overflow instead of scrolling. min-width:0 lets the strip shrink
to the container so the overflow-x:auto below actually engages. */
min-width: 0;
max-width: 100%;
flex-wrap: nowrap !important;
overflow-x: auto !important;
overflow-y: hidden;
File diff suppressed because it is too large Load Diff
+340
View File
@@ -978,3 +978,343 @@ body.doc-find-active mark.doc-find-mark.current {
color: var(--accent, var(--red));
vertical-align: -2px;
}
/* Colour chips: every pickable colour input renders as a circle, regardless of
the container it sits in (options bar .ge-text-field, Character panel,
gradient stops, export matte, etc.). Forced with !important so parent
input[type="color"] rules can't square them off. */
input.ge-color-picker,
input.ge-color-picker.cp-swatch-input,
.ge-text-field input.ge-color-picker,
.ge-swatch input.ge-color-picker,
.ge-filter-row input.ge-color-picker,
.ge-gradient-color-row input.ge-color-picker {
border-radius: 50% !important;
}
input.ge-color-picker::-webkit-color-swatch {
border: 0 !important;
border-radius: 50% !important;
}
input.ge-color-picker::-moz-color-swatch {
border: 0 !important;
border-radius: 50% !important;
}
/* ---------------------------------------------------------------------------
Editor theme alignment: map the editor's controls onto the app's design
tokens (static/css/00-tokens.css) so the editor matches the rest of the
product. No new colours — only the shared CSS variables.
--------------------------------------------------------------------------- */
/* Checkboxes + radios → the app's circular dot (see 17-research.css). */
body.ge-editor-open input[type="checkbox"],
body.ge-editor-open input[type="radio"] {
-webkit-appearance: none;
appearance: none;
width: 14px;
height: 14px;
margin: 0;
padding: 0;
border: 1.5px solid var(--border);
border-radius: 50%;
background: var(--bg);
cursor: pointer;
position: relative;
flex: 0 0 auto;
vertical-align: middle;
transition: background 0.12s ease, border-color 0.12s ease;
}
body.ge-editor-open input[type="checkbox"]:checked,
body.ge-editor-open input[type="radio"]:checked {
background: var(--fg);
border-color: var(--fg);
}
body.ge-editor-open input[type="checkbox"]:focus-visible,
body.ge-editor-open input[type="radio"]:focus-visible {
outline: 2px solid var(--red);
outline-offset: 1px;
}
/* Selects → the app's select tokens. */
body.ge-editor-open select {
background: var(--select-bg, var(--bg));
color: var(--select-fg, var(--fg));
border: 1px solid var(--border);
border-radius: 6px;
}
body.ge-editor-open select option {
background: var(--select-option-bg, var(--panel));
color: var(--select-option-fg, var(--fg));
}
body.ge-editor-open select option:checked,
body.ge-editor-open select option:hover {
background: var(--select-option-active-bg, var(--panel));
}
body.ge-editor-open select:focus-visible {
outline: 1px solid var(--red);
outline-offset: 1px;
}
/* Text / number inputs → token background, border and focus ring. */
body.ge-editor-open input[type="text"],
body.ge-editor-open input[type="number"],
body.ge-editor-open input[type="search"],
body.ge-editor-open textarea {
background: var(--bg);
color: var(--fg);
border: 1px solid var(--border);
border-radius: 6px;
}
body.ge-editor-open input[type="text"]:focus-visible,
body.ge-editor-open input[type="number"]:focus-visible,
body.ge-editor-open input[type="search"]:focus-visible,
body.ge-editor-open textarea:focus-visible {
outline: 1px solid var(--red);
outline-offset: 1px;
}
/* Range sliders → the app's accent. */
body.ge-editor-open input[type="range"] {
accent-color: var(--accent, var(--red));
}
/* Scrollbars → the app's 8px red-thumb recipe (00-tokens.css). */
body.ge-editor-open * {
scrollbar-width: thin;
scrollbar-color: var(--red) var(--panel);
}
body.ge-editor-open *::-webkit-scrollbar {
width: 8px;
height: 8px;
}
body.ge-editor-open *::-webkit-scrollbar-track {
background: var(--panel);
}
body.ge-editor-open *::-webkit-scrollbar-thumb {
background-color: var(--red);
border-radius: 4px;
border: 2px solid var(--panel);
}
body.ge-editor-open *::-webkit-scrollbar-thumb:hover {
background-color: color-mix(in srgb, var(--red) 80%, white);
}
/* ---------------------------------------------------------------------------
Editor theme alignment (part 2): buttons, segmented toggles, tabs, list
rows, panel headers, badges, focus rings, number fields and colour-picker
chrome mapped onto the app's shared design tokens. Existing tokens only —
no new colours, and no geometry beyond colour / border / radius / focus.
--------------------------------------------------------------------------- */
/* The editor references two secondary / muted variables that the app token
layer never defines; map them onto the real tokens so every
var(--fg-muted) / var(--bg-secondary) editor rule resolves. */
body.ge-editor-open {
--fg-muted: var(--color-muted);
--bg-secondary: var(--panel);
}
/* Buttons → the app's `.cal-btn` recipe (5px radius; the primary button
uses the accent fill with a --bg foreground instead of a hard-coded #fff). */
body.ge-editor-open .ge-btn {
border-radius: 5px;
}
body.ge-editor-open .ge-btn-primary {
background: var(--accent, var(--red));
border-color: var(--accent, var(--red));
color: var(--bg);
}
body.ge-editor-open .ge-btn-primary:hover {
background: var(--accent, var(--red));
opacity: 0.9;
}
body.ge-editor-open .ge-win-close:hover {
background: var(--accent, var(--red));
color: var(--bg);
}
/* Segmented / option toggles, command palette and channel rows → the app's
accent token (--red) instead of the editor's blue #4c8bf5 fallback. */
body.ge-editor-open .ge-opt-mode.active,
body.ge-editor-open .ge-crop-preset.active,
body.ge-editor-open .ge-command-item.active,
body.ge-editor-open .ge-command-item:hover {
background: var(--accent, var(--red));
border-color: var(--accent, var(--red));
color: var(--bg);
}
body.ge-editor-open .ge-channel-row.active,
body.ge-editor-open .ge-dock-tabs-menu-item:hover,
body.ge-editor-open .ge-filter-menu .dropdown-item-compact:focus-visible,
body.ge-editor-open .ge-view-menu .dropdown-item-compact:focus-visible,
body.ge-editor-open .ge-window-menu .dropdown-item-compact:focus-visible,
body.ge-editor-open .ge-help-menu .dropdown-item-compact:focus-visible,
body.ge-editor-open .ge-3d-menu .dropdown-item-compact:focus-visible,
body.ge-editor-open .ge-plugins-menu .dropdown-item-compact:focus-visible {
background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent);
}
body.ge-editor-open .ge-sam-brush-add.active,
body.ge-editor-open .ge-sam-brush-subtract.active,
body.ge-editor-open .ge-actions-controls .ge-btn.active {
border-color: var(--accent, var(--red));
color: var(--accent, var(--red));
}
/* Tabs → the app tab convention: the active tab's underline is the accent. */
body.ge-editor-open .ge-dock-tab.active {
border-bottom-color: var(--accent, var(--red));
}
/* Colour-picker chrome → the token accent instead of the blue fallback. */
body.ge-editor-open .ge-swatch.active {
outline-color: var(--accent, var(--red));
}
/* Badges / status pills → the app's --bg foreground on an accent fill. */
body.ge-editor-open .ge-tool-clear {
color: var(--bg);
}
/* Panel headers → the app's muted section-title token. */
body.ge-editor-open .ge-panel-title,
body.ge-editor-open .ge-info-label {
color: var(--color-muted);
}
/* Focus rings → the app's 1px --red ring (matching the earlier input/select
block) on the controls that previously fell back to the UA outline. */
body.ge-editor-open .ge-btn:focus-visible,
body.ge-editor-open .ge-tool-btn:focus-visible,
body.ge-editor-open .ge-doc-tab:focus-visible,
body.ge-editor-open .ge-history-row:focus-visible,
body.ge-editor-open .ge-swatch:focus-visible,
body.ge-editor-open .ge-opt-mode:focus-visible,
body.ge-editor-open .ge-stepper button:focus-visible {
outline: 1px solid var(--red);
outline-offset: 1px;
}
/* ---------------------------------------------------------------------------
Editor theme alignment (part 3): the setup / preflight checklist and the
remaining checkbox list-row / badge chrome mapped onto the app's shared
design tokens. Existing tokens only — no new colours, and no geometry beyond
colour / border / radius / focus. Scoped to body.ge-editor-open.
--------------------------------------------------------------------------- */
/* Checklist card + rows → the app's panel / border / muted tokens. */
body.ge-editor-open .ge-preflight-card {
background: var(--panel);
color: var(--fg);
border-color: var(--border);
}
body.ge-editor-open .ge-preflight-head p,
body.ge-editor-open .ge-preflight-hint,
body.ge-editor-open .ge-preflight-detail,
body.ge-editor-open .ge-preflight-remember,
body.ge-editor-open .ge-preflight-close {
color: var(--color-muted);
}
body.ge-editor-open .ge-preflight-close:hover {
background: color-mix(in srgb, var(--fg) 8%, transparent);
color: var(--fg);
}
body.ge-editor-open .ge-preflight-row {
background: color-mix(in srgb, var(--panel) 92%, var(--fg) 4%);
border-color: var(--border);
}
body.ge-editor-open .ge-preflight-row.is-done {
border-color: color-mix(in srgb, var(--green) 45%, var(--border));
}
body.ge-editor-open .ge-preflight-row.is-todo {
border-color: var(--red);
}
body.ge-editor-open .ge-preflight-row.is-optional {
border-color: color-mix(in srgb, var(--accent-warm) 45%, var(--border));
}
/* Row badges → the semantic tokens (done = green, todo = red, optional = warm). */
body.ge-editor-open .ge-preflight-badge {
background: color-mix(in srgb, var(--fg) 10%, transparent);
color: var(--fg);
}
body.ge-editor-open .ge-preflight-row.is-done .ge-preflight-badge {
background: color-mix(in srgb, var(--green) 20%, transparent);
color: var(--green);
}
body.ge-editor-open .ge-preflight-row.is-todo .ge-preflight-badge {
background: color-mix(in srgb, var(--red) 18%, transparent);
color: var(--red);
}
body.ge-editor-open .ge-preflight-row.is-optional .ge-preflight-badge {
background: color-mix(in srgb, var(--accent-warm) 16%, transparent);
color: var(--accent-warm);
}
body.ge-editor-open .ge-preflight-opt {
background: color-mix(in srgb, var(--fg) 8%, transparent);
color: var(--color-muted);
}
/* Checklist actions / footer → token buttons and borders. */
body.ge-editor-open .ge-preflight-act {
background: color-mix(in srgb, var(--fg) 8%, transparent);
border-color: var(--border);
color: var(--fg);
}
body.ge-editor-open .ge-preflight-act:hover {
background: color-mix(in srgb, var(--fg) 16%, transparent);
}
body.ge-editor-open .ge-preflight-foot {
border-top-color: var(--border);
}
body.ge-editor-open .ge-preflight-summary {
color: var(--green);
}
body.ge-editor-open .ge-preflight-start {
background: var(--accent, var(--red));
color: var(--bg);
}
body.ge-editor-open .ge-preflight-start:hover {
background: var(--accent, var(--red));
opacity: 0.9;
}
body.ge-editor-open .ge-setup-btn {
border-color: var(--border);
color: var(--color-muted);
}
body.ge-editor-open .ge-setup-btn:hover {
background: color-mix(in srgb, var(--fg) 10%, transparent);
color: var(--fg);
}
/* The options-bar checkbox overrode the shared dot with a square + a drawn
::after tick; force it back to the app's 14px circular dot, filled with the
highlight (accent) colour when checked (part 1). */
body.ge-editor-open .ge-opt input[type="checkbox"],
body.ge-editor-open .ge-opt input[type="radio"] {
border-radius: 50%;
border-width: 1.5px;
}
body.ge-editor-open .ge-opt input[type="checkbox"]:checked,
body.ge-editor-open .ge-opt input[type="radio"]:checked {
background: var(--accent, var(--red));
border-color: var(--accent, var(--red));
}
body.ge-editor-open .ge-opt input[type="checkbox"]:checked::after {
content: none;
}
/* Remaining list-row / thumbnail chrome → panel + border + muted tokens. */
body.ge-editor-open .ge-history-row-dot {
background: var(--color-muted);
}
body.ge-editor-open .ge-layer-inline-thumb {
background: var(--panel);
border-color: var(--border);
}
body.ge-editor-open .ge-channel-row,
body.ge-editor-open .ge-channel-name {
color: var(--fg);
}
body.ge-editor-open .ge-channel-eye {
color: var(--color-muted);
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3 -2
View File
@@ -257,7 +257,7 @@
<link rel="stylesheet" href="/static/css/00-tokens.css?v=20260929csssplit">
<link rel="stylesheet" href="/static/css/01-agent-chat.css?v=20260929csssplit">
<link rel="stylesheet" href="/static/css/02-compare.css?v=20260929csssplit">
<link rel="stylesheet" href="/static/css/03-agent-chat.css?v=20260929csssplit">
<link rel="stylesheet" href="/static/css/03-agent-chat.css?v=20261017titlefade1">
<link rel="stylesheet" href="/static/css/04-memory.css?v=20260929csssplit">
<link rel="stylesheet" href="/static/css/05-documents.css?v=20260929csssplit">
<link rel="stylesheet" href="/static/css/06-admin-settings.css?v=20260929csssplit">
@@ -664,6 +664,7 @@
<div class="theme-fd-group">
<label class="theme-fd-label">Font</label>
<select id="theme-font-select" class="theme-fd-select" aria-label="Font">
<option value="gohu">GohuFont</option>
<option value="mono">Monospace</option>
<option value="sans">Sans-serif</option>
<option value="serif">Serif</option>
@@ -2686,7 +2687,7 @@
<script type="module" src="/static/js/gallery.js?v=20260910promptcopy1"></script>
<script type="module" src="/static/js/chatRenderer.js?v=20260914metricssummary1"></script>
<script type="module" src="/static/js/codeRunner.js?v=20260831richtexttools91"></script>
<script type="module" src="/static/js/chatStream.js?v=20260914pdfstrip1"></script>
<script type="module" src="/static/js/chatStream.js?v=20261026devsync1"></script>
<script type="module" src="/static/js/chat.js?v=20260917toolttft1"></script>
<script type="module" src="/static/js/cookbook.js"></script>
<script src="/static/js/cookbookSchedule.js"></script>
+61 -1
View File
@@ -18,7 +18,13 @@
'use strict';
// Click-as-button rows we want reachable by keyboard.
var ROW_SELECTOR = ['#sidebar .list-item', '#user-bar-profile'].join(',');
var ROW_SELECTOR = [
'#sidebar .list-item',
'#user-bar-profile',
'.sidebar-brand',
'.export-dropdown-item',
'.dropdown-item'
].join(',');
// Native interactive descendants. If a row contains one of these we must
// NOT give the row role="button" — a button inside a button is invalid
@@ -55,6 +61,31 @@
(root || document).querySelectorAll(ROW_SELECTOR).forEach(enhanceRow);
}
// Settings form labels are written as <label class="settings-label">Text</label>
// with the control as a sibling/descendant, but are not associated via for/id,
// so screen readers cannot name the inputs. Associate each label with its
// control when the mapping is unambiguous (a single form control per row).
var settingsLabelSeq = 0;
function associateSettingsLabels(root) {
(root || document).querySelectorAll('.settings-label').forEach(function (label) {
if (label.hasAttribute('for')) return;
var control = null;
var sib = label.nextElementSibling;
if (sib && /^(INPUT|SELECT|TEXTAREA)$/.test(sib.tagName)) {
control = sib;
} else {
var row = label.closest('.settings-row') || label.parentElement;
if (row) {
var controls = row.querySelectorAll('input,select,textarea');
if (controls.length === 1) control = controls[0];
}
}
if (!control || control.closest('label')) return;
if (!control.id) control.id = 'a11y-settings-' + (++settingsLabelSeq);
if (!control.getAttribute('aria-label')) label.setAttribute('for', control.id);
});
}
// ---- Modal dialogs -----------------------------------------------------
// Odysseus modals are plain <div class="modal-content"> boxes. Marking
// them as ARIA dialogs lets screen readers announce them as dialogs and
@@ -118,9 +149,38 @@
el.click();
});
// Disclosure buttons: keep aria-expanded in sync with their controlled
// menu/dropdown, regardless of which module toggles its visibility.
var DISCLOSURE_MAP = [
{ button: 'session-sort-btn', menu: 'session-sort-dropdown' },
{ button: 'export-dl-btn', menu: 'export-dropdown-menu' },
{ button: 'overflow-plus-btn', menu: 'overflow-menu' }
];
function syncDisclosures() {
DISCLOSURE_MAP.forEach(function (d) {
var btn = document.getElementById(d.button);
if (!btn) return;
var menu = document.getElementById(d.menu);
var open = false;
if (menu) {
var cs = window.getComputedStyle(menu);
open = cs.display !== 'none' && menu.offsetWidth > 0;
}
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
});
}
function init() {
enhanceAll(document);
enhanceModals(document);
associateSettingsLabels(document);
// Any click (the dropdown toggles, outside-click closes, etc.) may change
// a disclosure's open state; re-sync on the next tick.
document.addEventListener('click', function () {
if (window.setTimeout) setTimeout(syncDisclosures, 0);
});
// Sidebar content is re-rendered as the user navigates (session lists,
// tool sub-rows, etc.). Watch for new rows and enhance them too.
+7 -5
View File
@@ -763,7 +763,7 @@ function renderFeatherlessPanel(panel, ep, row) {
const sortedIds = Array.from(enabledSet).sort((a, b) => a.localeCompare(b));
enabledListEl.innerHTML = sortedIds.map(id => {
const displayName = id.split('/').pop() || id;
const mode = ['none', 'compact', 'full'].includes(String(toolModes[id] || '').toLowerCase())
const mode = ['none', 'compact', 'full', 'spec'].includes(String(toolModes[id] || '').toLowerCase())
? String(toolModes[id]).toLowerCase()
: '';
return `<div title="${esc(id)}" data-ep-model-row data-model-id="${esc(id)}" class="adm-model-row">
@@ -777,7 +777,8 @@ function renderFeatherlessPanel(panel, ep, row) {
<select class="adm-model-tool-mode admin-tools-select" data-ep-model-id="${esc(id)}" data-original-tool-mode="${esc(toolModes[id] || '')}">
<option value="" ${mode === '' ? 'selected' : ''}>Auto</option>
<option value="full" ${mode === 'full' ? 'selected' : ''}>Regular tools</option>
<option value="compact" ${mode === 'compact' ? 'selected' : ''}>Odysseus compact</option>
<option value="compact" ${mode === 'compact' ? 'selected' : ''}>Ajax Compact</option>
<option value="spec" ${mode === 'spec' ? 'selected' : ''}>Ajax Spec (router)</option>
<option value="none" ${mode === 'none' ? 'selected' : ''}>Tools off</option>
</select>
</div>
@@ -1356,7 +1357,7 @@ async function loadEndpoints() {
<a href="#" data-ep-select-none="${epId}">None</a>
</span>
</div>${warningHtml}${showSearch ? `<input type="search" class="mcp-tools-search" placeholder="Search ${sortedModels.length} models..." data-ep-search="${epId}">` : ''}<div class="mcp-tools-list">` + sortedModels.map(m => {
const mode = ['none', 'compact', 'full'].includes(String(m.tool_mode || '').toLowerCase())
const mode = ['none', 'compact', 'full', 'spec'].includes(String(m.tool_mode || '').toLowerCase())
? String(m.tool_mode).toLowerCase()
: '';
return `<div title="${esc(m.id)}" data-ep-model-row data-search="${esc((m.display + ' ' + m.id).toLowerCase())}" class="adm-model-row">
@@ -1370,7 +1371,8 @@ async function loadEndpoints() {
<select class="adm-model-tool-mode admin-tools-select" data-ep-model-id="${esc(m.id)}" data-original-tool-mode="${esc(m.tool_mode || '')}" data-tool-mode-touched="0" title="Auto uses Odysseus compact for Odysseus/Ajax names and Regular tools for every other model">
<option value="" ${mode === '' ? 'selected' : ''}>Auto</option>
<option value="full" ${mode === 'full' ? 'selected' : ''}>Regular tools</option>
<option value="compact" ${mode === 'compact' ? 'selected' : ''}>Odysseus compact</option>
<option value="compact" ${mode === 'compact' ? 'selected' : ''}>Ajax Compact</option>
<option value="spec" ${mode === 'spec' ? 'selected' : ''}>Ajax Spec (router)</option>
<option value="none" ${mode === 'none' ? 'selected' : ''}>Tools off</option>
</select>
</div>
@@ -1440,7 +1442,7 @@ async function _saveEpModelState(epId, panel) {
const value = String(sel.value || '').toLowerCase();
const original = String(sel.dataset.originalToolMode || '').toLowerCase();
if (modelId && (sel.dataset.toolModeTouched === '1' || original)) {
modelToolModes[modelId] = ['none', 'compact', 'full'].includes(value) ? value : '';
modelToolModes[modelId] = ['none', 'compact', 'full', 'spec'].includes(value) ? value : '';
}
});
const total = panel.querySelectorAll('input.adm-cb-hidden[type=checkbox]').length;
+72 -2
View File
@@ -9,7 +9,7 @@ import Storage from './storage.js';
import uiModule from './ui.js?v=20260916largetoolscroll1';
import sessionModule from './sessions.js';
import chatRenderer, { renderToolIcon } from './chatRenderer.js?v=20260914metricssummary1';
import chatStream from './chatStream.js?v=20260914pdfstrip1';
import chatStream from './chatStream.js?v=20261026devsync1';
import { addAITTSButton } from './tts-ai.js';
import markdownModule from './markdown.js';
import spinnerModule from './spinner.js';
@@ -44,6 +44,66 @@ import { invalidateSettings } from './appConfig.js';
const RUN_ID_ABORT_GRACE_MS = 2000; // timeout waits this long for a run-id header before hard-aborting
const RESEARCH_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>';
// URL of the photo attached to the current turn (chat uploads are served at
// /api/upload/<id>). Used by the "Open in editor & apply" action.
function _currentAttachedImageUrl() {
try {
const box = document.getElementById('chat-history');
if (!box) return null;
// Use the newest user bubble that carries an image preview. Note
// ':last-of-type' is wrong here (it selects the last sibling of the
// element type, and the assistant reply follows the user bubble), so
// walk the user bubbles from the end instead.
const users = box.querySelectorAll('.msg-user');
for (let i = users.length - 1; i >= 0; i--) {
const img = users[i].querySelector('.attach-image-preview[data-file-id] img');
if (img && img.getAttribute('src')) return img.getAttribute('src');
}
// Fall back to any attachment preview/card in the history (newest).
const previews = box.querySelectorAll(
'.attach-image-preview[data-file-id], .attach-card[data-file-id]'
);
if (previews.length) {
const last = previews[previews.length - 1];
const id = last.dataset ? last.dataset.fileId : null;
if (id) return API_BASE + '/api/upload/' + id;
}
return null;
} catch (_) {
return null;
}
}
// Render the one-click "Open in editor & apply" button on a photo-edit reply
// that had no open editor (photo_editor_action kind 'open_and_apply').
function renderPhotoEditorApplyButton(container, action) {
if (!container || !action || action.kind !== 'open_and_apply') return;
if (container.querySelector('.chat-open-in-editor-btn')) return;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'chat-open-in-editor-btn';
btn.textContent = 'Open in editor & apply';
btn.style.cssText = 'margin-top:8px;padding:6px 12px;border-radius:6px;border:1px solid rgba(120,120,120,0.4);background:transparent;color:inherit;cursor:pointer;font:inherit;';
btn.addEventListener('click', async () => {
btn.disabled = true;
try {
if (typeof window.gePhotoEditorApply !== 'function') {
await import('/static/js/galleryEditor.js?v=20260909movepicklayer1');
}
await window.gePhotoEditorApply({
imageId: null,
imageUrl: _currentAttachedImageUrl(),
prompt: action.prompt || '',
displayName: 'Chat edit',
});
} catch (err) {
console.error('[chat] open_and_apply failed', err);
btn.disabled = false;
}
});
container.appendChild(btn);
}
let API_BASE = '';
let currentAbort = null;
let isStreaming = false;
@@ -4095,6 +4155,7 @@ import { invalidateSettings } from './appConfig.js';
threadAbove.classList.add('has-bottom');
}
terminalFinalResponseRendered = _renderTerminalAnswer(finalText, '', json.render_owner, json.replacement_scope);
if (json.photo_editor_action) renderPhotoEditorApplyButton(roundHolder, json.photo_editor_action);
lastContentRoundHolder = roundHolder || lastContentRoundHolder;
uiModule.scrollHistory();
continue;
@@ -6149,7 +6210,15 @@ import { invalidateSettings } from './appConfig.js';
cache: 'no-store',
});
if (!_getForegroundStreamState() || _backgroundStreams.has(sid)) return;
if (res.status !== 404) return;
// The server now reports "no active stream" as 200 {status:"idle"} (an
// older server used 404); a body with status "streaming" means it is NOT
// stale. Accept both so the watchdog keeps working across deploys.
if (res.status !== 404 && !res.ok) return;
let _probe = null;
try { _probe = await res.json(); } catch (_) { _probe = null; }
const _noActiveStream = res.status === 404 || (res.ok && _probe &&
typeof _probe.status === 'string' && _probe.status !== 'streaming');
if (!_noActiveStream) return;
console.warn('[stream-watchdog] Local stream was stale and server has no active stream. Unlocking composer.');
if (active.abortCtrl && !active.abortCtrl.signal.aborted) {
@@ -6511,6 +6580,7 @@ import { invalidateSettings } from './appConfig.js';
gotDelta = true;
try { spinner.destroy(); } catch (_) {}
renderDelta(json);
if (json.photo_editor_action) renderPhotoEditorApplyButton(roundHolder, json.photo_editor_action);
replayRendering.settle();
} else if (json.delta) {
if (!replayRendering.accepts(json)) continue;
+9 -1
View File
@@ -457,6 +457,7 @@ function _makeActionBtn(className, title, text, handler) {
btn.className = className;
btn.type = 'button';
btn.title = title;
btn.setAttribute('aria-label', title);
btn.textContent = text;
btn.addEventListener('click', handler);
return btn;
@@ -2375,6 +2376,7 @@ export function createMsgFooter(msgElement, { animate = false } = {}) {
moreBtn.className = 'msg-action-btn msg-more-btn';
moreBtn.type = 'button';
moreBtn.title = 'More actions';
moreBtn.setAttribute('aria-label', 'More actions');
moreBtn.textContent = '\u00B7\u00B7\u00B7';
moreBtn.addEventListener('click', (e) => {
e.stopPropagation();
@@ -2571,6 +2573,7 @@ export function createUserMsgFooter(msgElement) {
moreBtn.className = 'msg-action-btn msg-more-btn';
moreBtn.type = 'button';
moreBtn.title = 'More actions';
moreBtn.setAttribute('aria-label', 'More actions');
moreBtn.textContent = '\u00B7\u00B7\u00B7';
moreBtn.addEventListener('click', (e) => {
e.stopPropagation();
@@ -3274,6 +3277,7 @@ export function addMessage(role, content, modelName, metadata) {
let lastWrap = null;
let firstMsgAi = null;
let lastMsgAi = null;
const newNodes = [];
const toolsByRound = {};
let lastPrivateBrowserUrl = '';
@@ -3367,6 +3371,7 @@ export function addMessage(role, content, modelName, metadata) {
wrap.dataset.raw = txt;
if (metadata?._db_id) wrap.dataset.dbId = metadata._db_id;
box.appendChild(wrap);
newNodes.push(wrap);
lastWrap = wrap;
if (!firstMsgAi) firstMsgAi = wrap;
lastMsgAi = wrap;
@@ -3384,6 +3389,7 @@ export function addMessage(role, content, modelName, metadata) {
// Extend line up if there's a chat bubble above
if (txt) threadWrap.classList.add('has-top');
box.appendChild(threadWrap);
newNodes.push(threadWrap);
}
for (const ev of roundTools) {
if (ev.ask_user && !ev.ask_user.resolved) pendingAskUser = ev.ask_user;
@@ -3443,7 +3449,9 @@ export function addMessage(role, content, modelName, metadata) {
for (const ev of roundTools) {
const image = generatedImageResult(ev);
if (image) {
box.appendChild(buildImageBubble(image.image_url, image.image_prompt, image.image_model, image.image_size, image.image_quality, image.image_id));
const imgBubble = buildImageBubble(image.image_url, image.image_prompt, image.image_model, image.image_size, image.image_quality, image.image_id);
box.appendChild(imgBubble);
newNodes.push(imgBubble);
}
}
}
+2
View File
@@ -212,6 +212,8 @@ export function handleUIControl(uiData) {
var fn = mod.openPanel || mod.openNotes || (mod.default && (mod.default.openPanel || mod.default.openNotes));
if (fn) fn();
}).catch(function(){});
} else if (panel === 'tasks') {
document.getElementById('tool-tasks-btn')?.click();
} else if (panel === 'theme' || panel === 'themes') {
import('./theme.js?v=20260911organsrain1').then(function(mod) {
var fn = mod.togglePopup || (mod.default && mod.default.togglePopup);
+3 -3
View File
@@ -390,11 +390,11 @@ export function runHTML(code, panel) {
* Main entry point — called when a Run button is clicked
*/
export function run(btn) {
const code = btn.getAttribute('data-code');
const lang = (btn.getAttribute('data-lang') || '').toLowerCase();
const pre = btn.closest('pre');
if (!pre) return;
const codeEl = pre.querySelector('code');
const code = codeEl ? codeEl.textContent : btn.getAttribute('data-code');
const lang = (btn.getAttribute('data-lang') || '').toLowerCase();
const panel = getOrCreatePanel(pre);
if (!code || !code.trim()) {
+15
View File
@@ -96,6 +96,21 @@ function computeSuggestions() {
];
}
// ── Reusable helpers for hosts that surface swatches inline ──────────
// (e.g. the editor's SWATCHES panel showing suggestions + recents).
export function getRecentColors() { return getRecents(); }
export function recordRecentColor(hex) { addRecent(hex); }
export function suggestColorsFor(hex) {
const { h, s, v } = hexToHsv(hex || '#000000');
return [
{ hex: hsvToHex(h + 180, s, v), label: 'Complement' },
{ hex: hsvToHex(h + 30, s, v), label: 'Analogous +30°' },
{ hex: hsvToHex(h - 30, s, v), label: 'Analogous -30°' },
{ hex: hsvToHex(h + 150, s, v), label: 'Split-complement' },
{ hex: hsvToHex(h, s, clamp(v > 50 ? v - 30 : v + 30, 10, 95)), label: 'Tone shift' },
];
}
// ── Popover build ─────────────────────────────────────────────────────
function buildPopover() {
const p = document.createElement('div');
+2 -1
View File
@@ -1498,7 +1498,8 @@ function _rerenderCachedModels() {
const _ggufOptions = _ggufChoices.map(f =>
`<option value="${esc(f.rel_path)}"${f.rel_path === _defaultGguf ? ' selected' : ''}>${esc(_ggufFileLabel(f))}</option>`
).join('');
const _defaultServeModel = (m.is_local_dir && m.path ? `${m.path}/${repo}` : repo);
const _minimaxM3Snapshot = '~/.cache/huggingface/hub/models--cyankiwi--MiniMax-M3-AWQ-INT4/snapshots/4082acbbec1236d21828d55b6bb0fe02ade4ab5b';
const _defaultServeModel = _isMiniMaxM3 ? _minimaxM3Snapshot : (m.is_local_dir && m.path ? `${m.path}/${repo}` : repo);
const _savedModelPath = String(svm('model_path', _defaultServeModel) || '').trim();
const _modelPathValue = _savedModelPath || _defaultServeModel;
const _defaultServedModelName = _isMiniMaxM3 ? repo : '';
+33 -1
View File
@@ -31,10 +31,15 @@ export function enable(containerId, itemSelector, options = {}) {
onReorder: options.onReorder || null,
handleSelector: options.handleSelector || null,
excludeSelector: options.excludeSelector || null,
ignoreSelector: options.ignoreSelector || null,
// When > 0 the pointer must travel this many pixels before the drag
// starts, so rows that also handle plain clicks stay clickable.
threshold: Math.max(0, Number(options.threshold) || 0),
storageKey: options.storageKey || null,
};
let draggedEl = null;
let pending = null;
let placeholder = null;
let offsetY = 0;
let items = [];
@@ -130,6 +135,12 @@ export function enable(containerId, itemSelector, options = {}) {
draggedEl.style.top = snapTop + 'px';
setTimeout(() => {
// The list may have been re-rendered mid-drag (e.g. dropping a layer
// effect copies it and rebuilds the panel), detaching both nodes.
if (!placeholder.parentNode || !draggedEl.isConnected) {
placeholder.remove();
return;
}
placeholder.parentNode.insertBefore(draggedEl, placeholder);
placeholder.remove();
draggedEl.classList.remove('dragging');
@@ -158,10 +169,21 @@ export function enable(containerId, itemSelector, options = {}) {
function onMouseDown(e) {
if (e.button !== 0) return;
if (config.handleSelector && !e.target.closest(config.handleSelector)) return;
if (config.ignoreSelector && e.target.closest(config.ignoreSelector)) return;
const item = e.target.closest(itemSelector);
if (!item || !container.contains(item)) return;
if (config.excludeSelector && item.matches(config.excludeSelector)) return;
if (config.threshold > 0) {
// Defer the lift until the pointer actually moves, so a plain click
// (select layer, open the rename field) is left untouched.
pending = { item, startY: e.clientY };
e.preventDefault();
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
return;
}
e.preventDefault();
e.stopPropagation();
startDrag(e.clientY, item);
@@ -169,11 +191,21 @@ export function enable(containerId, itemSelector, options = {}) {
document.addEventListener('mouseup', onMouseUp);
}
function onMouseMove(e) { moveDrag(e.clientY); }
function onMouseMove(e) {
if (pending) {
if (Math.abs(e.clientY - pending.startY) < config.threshold) return;
const { item, startY } = pending;
pending = null;
e.preventDefault();
startDrag(startY, item);
}
moveDrag(e.clientY);
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
pending = null;
endDrag();
}
+243
View File
@@ -0,0 +1,243 @@
/**
* Actions panel (PhotoCraft parity, Phase 11) — a lightweight macro
* recorder/player. Every step maps to a known editor command by CSS
* selector; recording captures clicks on those selectors, and play
* replays them in order. Named actions persist to localStorage.
*
* The module owns no editor state: it only dispatches clicks on the
* selectors it is given.
*/
export const ACTION_COMMANDS = Object.freeze([
['flip-h', 'Flip Horizontal', '[data-image-action="flip-h"]'],
['flip-v', 'Flip Vertical', '[data-image-action="flip-v"]'],
['rotate-90', 'Rotate 90° CW', '[data-image-action="rotate-90"]'],
['rotate-180', 'Rotate 180°', '[data-image-action="rotate-180"]'],
['fill', 'Fill Foreground', '[data-image-action="fill"]'],
['merge-down', 'Merge Down', '#ge-merge-down'],
['flatten', 'Flatten', '#ge-flatten'],
['select-all', 'Select All', '[data-selection-action="all"]'],
['deselect', 'Deselect', '[data-selection-action="deselect"]'],
['invert-selection', 'Invert Selection', '[data-selection-action="invert"]'],
['blur-gaussian', 'Gaussian Blur', '[data-filter-action="blur-gaussian"]'],
['blur-motion', 'Motion Blur', '[data-filter-action="blur-motion"]'],
['noise-add', 'Add Noise', '[data-filter-action="noise-add"]'],
['pixelate-mosaic', 'Pixelate', '[data-filter-action="pixelate-mosaic"]'],
['sharpen', 'Sharpen', '[data-filter-action="sharpen"]'],
['stylize-emboss', 'Emboss', '[data-filter-action="stylize-emboss"]'],
['distort-twirl', 'Twirl', '[data-filter-action="distort-twirl"]'],
['rembg', 'Remove Background', '[data-tool-option="rembg"]'],
['inpaint', 'Inpaint', '[data-tool="inpaint"]'],
]);
const STORAGE_KEY = 'ge-actions';
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
function commandById(id) {
return ACTION_COMMANDS.find(command => command[0] === id) || null;
}
export function createActionsPanel({ showToast = () => {}, getLayers = null, selectLayer = null } = {}) {
let steps = [];
let recording = false;
let saved = loadSaved();
const body = el('div', 'ge-panel-body ge-actions-body');
const nameRow = el('div', 'ge-actions-name-row');
const nameInput = document.createElement('input');
nameInput.type = 'text';
nameInput.placeholder = 'Action name';
nameInput.className = 'ge-actions-name';
const saveButton = el('button', 'ge-btn ge-btn-sm', 'Save');
saveButton.type = 'button';
nameRow.append(nameInput, saveButton);
const addRow = el('div', 'ge-actions-add-row');
const addSelect = document.createElement('select');
addSelect.className = 'ge-actions-command';
ACTION_COMMANDS.forEach(([id, label]) => addSelect.appendChild(new Option(label, id)));
const addButton = el('button', 'ge-btn ge-btn-sm', 'Add');
addButton.type = 'button';
addRow.append(addSelect, addButton);
const controls = el('div', 'ge-actions-controls');
const recordButton = el('button', 'ge-btn ge-btn-sm', 'Record');
recordButton.type = 'button';
const playButton = el('button', 'ge-btn ge-btn-sm', 'Play');
playButton.type = 'button';
const clearButton = el('button', 'ge-btn ge-btn-sm', 'Clear');
clearButton.type = 'button';
controls.append(recordButton, playButton, clearButton);
const batchRow = el('div', 'ge-actions-batch-row');
const batchSelect = document.createElement('select');
batchSelect.className = 'ge-actions-batch-select';
const batchButton = el('button', 'ge-btn ge-btn-sm', 'Batch');
batchButton.type = 'button';
batchButton.title = 'Apply the selected action to every layer';
const batchDocsButton = el('button', 'ge-btn ge-btn-sm', 'Batch docs');
batchDocsButton.type = 'button';
batchDocsButton.title = 'Apply the selected action to every open document';
batchRow.append(batchSelect, batchButton, batchDocsButton);
const list = el('div', 'ge-actions-list');
const savedList = el('div', 'ge-actions-saved');
body.append(nameRow, addRow, controls, batchRow, list, savedList);
function renderList() {
list.innerHTML = '';
if (!steps.length) {
list.appendChild(el('p', 'ge-panel-empty', 'No steps. Add commands or record.'));
return;
}
steps.forEach((step, index) => {
const command = commandById(step);
const row = el('div', 'ge-actions-step');
row.append(
el('span', 'ge-actions-step-index', String(index + 1)),
el('span', 'ge-actions-step-label', command ? command[1] : step),
);
const remove = el('button', 'ge-action-remove', '✕');
remove.type = 'button';
remove.addEventListener('click', () => { steps.splice(index, 1); renderList(); });
row.appendChild(remove);
list.appendChild(row);
});
}
function renderSaved() {
savedList.innerHTML = '';
syncBatchSelect();
const names = Object.keys(saved);
if (!names.length) return;
savedList.appendChild(el('div', 'ge-panel-title', 'SAVED'));
names.forEach(name => {
const row = el('div', 'ge-actions-saved-row');
const loadButton = el('button', 'ge-btn ge-btn-sm', name);
loadButton.type = 'button';
loadButton.addEventListener('click', () => { steps = saved[name].slice(); renderList(); });
const deleteButton = el('button', 'ge-action-remove', '✕');
deleteButton.type = 'button';
deleteButton.addEventListener('click', () => { delete saved[name]; persist(); renderSaved(); });
row.append(loadButton, deleteButton);
savedList.appendChild(row);
});
}
function persist() {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(saved)); } catch { /* ignore */ }
}
function syncBatchSelect() {
const names = Object.keys(saved);
const previous = batchSelect.value;
batchSelect.innerHTML = '';
if (!names.length) {
batchSelect.appendChild(new Option('No saved actions', ''));
batchButton.disabled = true;
batchDocsButton.disabled = true;
return;
}
batchButton.disabled = false;
batchDocsButton.disabled = false;
names.forEach(name => batchSelect.appendChild(new Option(name, name)));
if (names.includes(previous)) batchSelect.value = previous;
}
function loadSaved() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : null;
return parsed && typeof parsed === 'object' ? parsed : {};
} catch { return {}; }
}
function runStep(step) {
const command = commandById(step);
if (!command) return;
document.querySelector(command[2])?.click();
}
function play() {
steps.forEach((step, index) => setTimeout(() => runStep(step), index * 60));
showToast(`Playing ${steps.length} action${steps.length === 1 ? '' : 's'}`);
}
async function runOnAllLayers() {
const name = batchSelect.value;
const action = name && saved[name] ? saved[name].slice() : null;
if (!action || !action.length) { showToast('Select a saved action to batch'); return; }
if (!getLayers || !selectLayer) { showToast('Batch is unavailable'); return; }
const layers = getLayers() || [];
if (layers.length < 1) { showToast('No layers to batch'); return; }
showToast(`Batching "${name}" over ${layers.length} layer${layers.length === 1 ? '' : 's'}`);
for (const layer of layers) {
selectLayer(layer.id);
for (const step of action) {
runStep(step);
await new Promise(resolve => setTimeout(resolve, 80));
}
}
showToast('Batch complete');
}
function onDocumentClick(event) {
if (!recording) return;
const match = ACTION_COMMANDS.find(command => event.target.closest?.(command[2]));
if (match && !steps.includes(match[0])) {
steps.push(match[0]);
renderList();
}
}
function toggleRecord() {
recording = !recording;
recordButton.classList.toggle('active', recording);
recordButton.textContent = recording ? 'Stop' : 'Record';
showToast(recording ? 'Recording actions…' : 'Recording stopped');
}
addButton.addEventListener('click', () => { steps.push(addSelect.value); renderList(); });
recordButton.addEventListener('click', toggleRecord);
playButton.addEventListener('click', play);
batchButton.addEventListener('click', () => { runOnAllLayers(); });
batchDocsButton.addEventListener('click', async () => {
const name = batchSelect.value;
if (!name) { showToast('Select a saved action to batch'); return; }
try {
const response = await window.geEditorControl?.invoke?.('actions.batchDocuments', { name });
const results = (response && response.result) || [];
const ok = results.filter((entry) => entry.ok).length;
showToast(`Batch docs: ${ok}/${results.length} document${results.length === 1 ? '' : 's'}`);
} catch (error) {
showToast('Batch docs failed: ' + (error?.message || error));
}
});
clearButton.addEventListener('click', () => { steps = []; renderList(); });
saveButton.addEventListener('click', () => {
const name = (nameInput.value || '').trim();
if (!name) return;
saved[name] = steps.slice();
persist();
renderSaved();
showToast(`Saved action "${name}"`);
});
document.addEventListener('click', onDocumentClick, true);
const element = el('div', 'ge-panel');
element.id = 'ge-panel-actions';
element.appendChild(el('div', 'ge-panel-title', 'ACTIONS'));
element.appendChild(body);
renderList();
renderSaved();
return { element, play, run: runStep, runOnAllLayers, getSteps: () => steps.slice(), setSteps: (next) => { steps = next.slice(); renderList(); } };
}
+17 -10
View File
@@ -2,10 +2,12 @@
import { applyAdjustment } from './fx/pixel-pass.js';
import { defaultAdjParams } from './layer-helpers.js';
import { renderWithLayerMasks } from './composite-helpers.js';
import { blendDraw } from './blend-modes.js';
const TYPES = new Set([
'brightness-contrast',
'exposure',
'develop',
'white-balance',
'hue-saturation',
'vibrance',
@@ -16,6 +18,12 @@ const TYPES = new Set([
'color-balance',
'selective-color',
'gradient-map',
'invert',
'posterize',
'threshold',
'photo-filter',
'channel-mixer',
'color-lookup',
]);
function clone(value) {
@@ -52,6 +60,11 @@ export function normalizeAdjustmentData(value) {
params.ranges[name] = { ...clone(defaults.ranges[name]), ...(params.ranges[name] || {}) };
}
}
if (type === 'channel-mixer') {
for (const name of ['red', 'green', 'blue', 'constant']) {
params[name] = { ...clone(defaults[name]), ...(params[name] || {}) };
}
}
return { type, params };
}
@@ -109,11 +122,8 @@ export function drawAdjustmentLayer(target, editorState, layer, clippingBase, re
adjusted = clipped;
}
target.globalAlpha = Number.isFinite(layer.opacity) ? layer.opacity : 1;
target.globalCompositeOperation = layer.blendMode || 'source-over';
target.drawImage(adjusted, 0, 0);
target.globalAlpha = 1;
target.globalCompositeOperation = 'source-over';
const opacity = Number.isFinite(layer.opacity) ? layer.opacity : 1;
blendDraw(target, adjusted, layer.blendMode, opacity, 0, 0);
return true;
}
@@ -154,11 +164,8 @@ export async function drawAdjustmentLayerAsync(target, editorState, layer, clipp
clippedCtx.globalCompositeOperation = 'source-over';
adjusted = clipped;
}
target.globalAlpha = Number.isFinite(layer.opacity) ? layer.opacity : 1;
target.globalCompositeOperation = layer.blendMode || 'source-over';
target.drawImage(adjusted, 0, 0);
target.globalAlpha = 1;
target.globalCompositeOperation = 'source-over';
const opacity = Number.isFinite(layer.opacity) ? layer.opacity : 1;
blendDraw(target, adjusted, layer.blendMode, opacity, 0, 0);
return true;
}
+133 -1
View File
@@ -27,6 +27,12 @@
import { state } from './state.js';
import { sortModelIds } from '../modelSort.js';
// Last result of loadAIModels() — consumed by the editor setup checklist
// (static/js/editor/preflight.js) to decide whether an image provider is
// reachable and which image models are available.
let _aiModelsStatus = { ready: false, models: [], error: null, at: 0 };
export function getAIModelsStatus() { return _aiModelsStatus; }
export function resolveInpaintModel(select) {
const options = Array.from(select?.options || []).filter(option =>
!option.disabled && option.value && option.value !== '__serve_cookbook__');
@@ -34,6 +40,71 @@ export function resolveInpaintModel(select) {
return explicit || options.find(option => /inpaint|edit|fill/i.test(option.value)) || options[0] || null;
}
// Resolve the model the Quick Edit box will use. Prefers the explicit Quick
// Edit picker (#ge-ai-command-model); falls back to the inpaint picker / Auto.
export function resolveQuickEditModel() {
const sel = document.getElementById('ge-ai-command-model');
if (sel && sel.value && sel.value !== '__serve_cookbook__') {
const opt = sel.options[sel.selectedIndex];
const raw = sel.value || '';
const idx = raw.indexOf('::');
return {
endpoint: idx < 0 ? raw : raw.slice(0, idx),
model: idx < 0 ? '' : raw.slice(idx + 2),
label: ((opt && opt.textContent) || '').trim(),
};
}
const inp = document.getElementById('ge-ai-inpaint');
const opt = resolveInpaintModel(inp);
if (!opt) return { endpoint: '', model: '', label: '' };
const raw = opt.value || '';
const idx = raw.indexOf('::');
return {
endpoint: idx < 0 ? raw : raw.slice(0, idx),
model: idx < 0 ? '' : raw.slice(idx + 2),
label: ((opt.textContent || '').trim().replace(/^Auto\s*\((.*)\)$/, '$1')),
};
}
// Resolve the Quick Edit AGENT (planner) model — the vision-language model
// that reads the canvas screenshot and plans the edit. Default is the local
// Qwen3.5-9B VL server on seneca; "Server default" keeps the HARNESS planner.
export function resolveQuickEditAgentModel() {
const sel = document.getElementById('ge-ai-command-agent-model');
const raw = (sel && sel.value) || '';
if (!raw || raw === 'default') {
return { agent: '', endpoint: '', label: 'Server default' };
}
const idx = raw.indexOf('::');
const endpoint = idx < 0 ? '' : raw.slice(0, idx);
const agent = idx < 0 ? raw : raw.slice(idx + 2);
const opt = sel.options[sel.selectedIndex];
return { agent, endpoint, label: ((opt && opt.textContent) || '').trim() };
}
// Quick Edit agent (planner) model options. Kept small + explicit; the local
// Qwen3.5-9B VL is the default. `value` encodes "<endpoint>::<model>".
export const QUICK_EDIT_AGENT_OPTIONS = [
{ value: 'http://100.69.120.65:8097/v1::Qwen/Qwen3.5-9B', label: 'Qwen3.5-9B VL · local' },
{ value: 'default', label: 'Server default (hosted planner)' },
];
// can see which model Quick Edit / inpaint will call.
export function updateFooterEditModel() {
const el = document.getElementById('ge-status-model');
if (!el) return;
const info = resolveQuickEditModel();
if (!info.label && !info.model) {
el.textContent = 'Edit: none';
el.title = 'No AI edit model available';
return;
}
const label = info.label || info.model;
el.textContent = `Edit: ${label}`;
el.title = `AI edit model: ${label}`;
}
// Heuristic classifier on a model id + endpoint name. A model can be:
// - gen: text-to-image generation
// - inpaint: image+mask edit (inpaint / img2img)
@@ -92,11 +163,40 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
const aiGenSelect = document.getElementById('ge-ai-model');
const aiInpaintSelect = document.getElementById('ge-ai-inpaint');
const aiCommandSelect = document.getElementById('ge-ai-command-model');
const aiCommandAgentSelect = document.getElementById('ge-ai-command-agent-model');
if (aiInpaintSelect) aiInpaintSelect.addEventListener('change', () => updateFooterEditModel());
if (aiCommandSelect) aiCommandSelect.addEventListener('change', () => updateFooterEditModel());
// The Quick Edit agent (planner) picker is static for now (local VL default,
// server default option); restore/save its choice from localStorage.
const populateAgentSelect = () => {
if (!aiCommandAgentSelect) return;
aiCommandAgentSelect.innerHTML = '';
for (const opt of QUICK_EDIT_AGENT_OPTIONS) {
const el = document.createElement('option');
el.value = opt.value;
el.textContent = opt.label;
aiCommandAgentSelect.appendChild(el);
}
try {
const saved = localStorage.getItem('ge-ai-command-agent-model');
if (saved && [...aiCommandAgentSelect.options].some(o => o.value === saved)) {
aiCommandAgentSelect.value = saved;
}
} catch {}
if (!aiCommandAgentSelect._agentWired) {
aiCommandAgentSelect._agentWired = true;
aiCommandAgentSelect.addEventListener('change', () => {
try { localStorage.setItem('ge-ai-command-agent-model', aiCommandAgentSelect.value); } catch {}
});
}
};
// The global Gen model dropdown was removed from the editor topbar;
// only bail if there's nothing to populate at all (neither the Gen
// select nor the inpaint select nor any per-tool select).
if (!aiGenSelect && !aiInpaintSelect &&
if (!aiGenSelect && !aiInpaintSelect && !aiCommandSelect && !aiCommandAgentSelect &&
!document.querySelector('select.ge-tool-model')) return;
populateAgentSelect();
async function loadAIModels(opts = {}) {
try {
@@ -108,11 +208,13 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
const endpoints = await res.json();
if (aiGenSelect) aiGenSelect.innerHTML = '<option value="">None</option>';
if (aiInpaintSelect) aiInpaintSelect.innerHTML = '<option value="">Auto</option>';
if (aiCommandSelect) aiCommandSelect.innerHTML = '<option value="">Auto (default)</option>';
const perToolSelects = Array.from(document.querySelectorAll('select.ge-tool-model'));
for (const ts of perToolSelects) ts.innerHTML = '<option value="">Auto</option>';
let firstGen = null;
let selectedGen = null;
let selectedInpaint = null;
const loaded = [];
for (const ep of endpoints) {
if (!ep.is_enabled) continue;
const hasListedModels = Array.isArray(ep.models) && ep.models.length;
@@ -130,6 +232,7 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
const shortModel = modelId ? String(modelId).split('/').pop() : (ep.name || ep.base_url);
const epHint = modelId && ep.name && ep.name !== modelId ? ` · ${ep.name}` : '';
const label = `${shortModel}${epHint}${epUsable ? '' : ' (offline)'}`;
loaded.push({ value, label, gen: caps.gen, inpaint: caps.inpaint, usable: epUsable, endpoint: ep.base_url, model: modelId });
if (caps.gen && aiGenSelect) {
const opt = document.createElement('option');
opt.value = value;
@@ -158,6 +261,13 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
opt.disabled = !epUsable;
ts.appendChild(opt);
}
if (aiCommandSelect) {
const opt = document.createElement('option');
opt.value = value;
opt.textContent = label;
opt.disabled = !epUsable;
aiCommandSelect.appendChild(opt);
}
}
}
}
@@ -173,6 +283,7 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
const auto = resolveInpaintModel({ options: aiInpaintSelect.options, value: '' });
aiInpaintSelect.options[0].textContent = auto ? `Auto (${auto.textContent})` : 'Auto (no available model)';
}
updateFooterEditModel();
// Append the "Serve a model in Cookbook…" sentinel at the
// bottom of every model dropdown.
const appendServeSentinel = (sel) => {
@@ -188,6 +299,7 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
for (const ts of perToolSelects) appendServeSentinel(ts);
if (aiGenSelect) appendServeSentinel(aiGenSelect);
if (aiInpaintSelect) appendServeSentinel(aiInpaintSelect);
if (aiCommandSelect) appendServeSentinel(aiCommandSelect);
// Wire the sentinel on the Gen + Inpaint selects too.
const wireServeSentinel = (sel) => {
if (!sel) return;
@@ -203,6 +315,18 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
};
wireServeSentinel(aiGenSelect);
wireServeSentinel(aiInpaintSelect);
wireServeSentinel(aiCommandSelect);
if (aiCommandSelect) {
try {
const saved = localStorage.getItem('ge-ai-command-model');
if (saved && [...aiCommandSelect.options].some(o => o.value === saved)) aiCommandSelect.value = saved;
} catch {}
aiCommandSelect.addEventListener('change', () => {
if (aiCommandSelect.value === '__serve_cookbook__') return;
try { localStorage.setItem('ge-ai-command-model', aiCommandSelect.value); } catch {}
updateFooterEditModel();
});
}
// Restore each per-tool selection from localStorage.
for (const ts of perToolSelects) {
const key = 'ge-tool-model-' + ts.dataset.geToolModel;
@@ -223,6 +347,8 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
try { localStorage.setItem(key, ts.value); } catch {}
});
}
_aiModelsStatus = { ready: true, models: loaded, error: null, at: Date.now() };
try { window.dispatchEvent(new CustomEvent('ge:ai-models-status')); } catch {}
} catch (e) {
// Fetch failed — still give the user the affordance to set up
// a model. Otherwise the dropdown shows only "Auto" with no
@@ -230,6 +356,7 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
const fallback = '<option value="">Auto</option><option disabled>Could not load image models</option><option value="__serve_cookbook__">+ Serve a model in Cookbook…</option>';
if (aiGenSelect) aiGenSelect.innerHTML = fallback;
if (aiInpaintSelect) aiInpaintSelect.innerHTML = fallback;
if (aiCommandSelect) aiCommandSelect.innerHTML = fallback;
document.querySelectorAll('select.ge-tool-model').forEach(ts => { ts.innerHTML = fallback; });
const wireServe = (sel) => {
if (!sel) return;
@@ -245,7 +372,12 @@ export function wireAIModelSelectors({ container, apiBase, openCookbookForImg2im
};
wireServe(aiGenSelect);
wireServe(aiInpaintSelect);
wireServe(aiCommandSelect);
document.querySelectorAll('select.ge-tool-model').forEach(wireServe);
populateAgentSelect();
updateFooterEditModel();
_aiModelsStatus = { ready: false, models: [], error: String(e?.message || e), at: Date.now() };
try { window.dispatchEvent(new CustomEvent('ge:ai-models-status')); } catch {}
}
}
loadAIModels();
+85
View File
@@ -0,0 +1,85 @@
/**
* AI settings dialog.
*
* Holds the image-edit model, the AI agent (vision) model, and the opt-in
* "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.
*/
export function createAiSettings({ container }) {
const el = document.createElement('div');
el.className = 'ge-ai-settings';
el.hidden = true;
el.setAttribute('role', 'dialog');
el.setAttribute('aria-modal', 'true');
el.setAttribute('aria-label', 'AI settings');
el.innerHTML = `
<div class="ge-ai-settings-card">
<div class="ge-ai-settings-head">
<h3>AI settings</h3>
<button type="button" class="ge-ai-settings-close" data-ai-settings-close aria-label="Close">×</button>
</div>
<div class="ge-ai-settings-body">
<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>
<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>
<p class="ge-ai-settings-note">Recommended, not required — the vision agent plans edits and can double-check results.</p>
<label class="ge-ai-settings-label" for="ge-look-strength">Look strength</label>
<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" />
<span class="ge-ai-settings-strength-val" id="ge-look-strength-val">1.4×</span>
</div>
<p class="ge-ai-settings-note">How strongly named looks (Kodachrome, teal and orange, …) are graded.</p>
<label class="ge-ai-settings-opt" title="Ask the vision model to review the result and retry on a clear failure">
<input type="checkbox" id="ge-ai-command-selfcheck" /> Double-check AI edits
</label>
</div>
<div class="ge-ai-settings-foot">
<button type="button" class="ge-ai-settings-done" data-ai-settings-close>Done</button>
</div>
</div>`;
function open(focusId) {
el.hidden = false;
if (focusId) {
const target = document.getElementById(focusId);
if (target) {
try { target.focus({ preventScroll: true }); } catch (_) { target.focus(); }
}
}
}
function close() { el.hidden = true; }
el.addEventListener('click', (e) => {
if (e.target === el || e.target.closest('[data-ai-settings-close]')) {
e.preventDefault();
close();
}
});
const onKey = (e) => { if (e.key === 'Escape' && !el.hidden) close(); };
document.addEventListener('keydown', onKey);
container.appendChild(el);
const strengthInput = el.querySelector('#ge-look-strength');
const strengthVal = el.querySelector('#ge-look-strength-val');
if (strengthInput) {
try {
const saved = parseFloat(localStorage.getItem('ge-look-strength'));
if (Number.isFinite(saved) && saved > 0) strengthInput.value = String(saved);
} catch (_) {}
if (strengthVal) strengthVal.textContent = Number(strengthInput.value).toFixed(1) + '×';
strengthInput.addEventListener('input', () => {
const v = Number(strengthInput.value);
if (strengthVal) strengthVal.textContent = v.toFixed(1) + '×';
try { localStorage.setItem('ge-look-strength', String(v)); } catch (_) {}
});
}
function destroy() {
document.removeEventListener('keydown', onKey);
el.remove();
}
return { element: el, open, close, destroy };
}
+32 -11
View File
@@ -215,21 +215,19 @@ export function wireAIToolsMisc({
function addEmptyLayer() {
saveState('Add layer');
const layer = createLayer('Layer ' + state.layers.length, state.imgWidth, state.imgHeight);
state.layers.push(layer);
// Photoshop inserts the new layer directly above the selected one.
const activeIndex = state.layers.findIndex(item => item.id === state.activeLayerId);
const insertIndex = activeIndex >= 0 ? activeIndex + 1 : state.layers.length;
state.layers.splice(insertIndex, 0, layer);
state.activeLayerId = layer.id;
renderLayerPanel();
composite();
}
const addButton = document.getElementById('ge-add-layer');
addButton?.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
const buildFxMenu = (anchor) => {
document.querySelector('.ge-add-layer-menu')?.remove();
const menu = document.createElement('div');
menu.className = 'ge-add-layer-menu ge-frosted';
menu.innerHTML = `
<button type="button" data-layer-kind="raster"><span class="ge-add-layer-symbol">+</span><span>Pixel Layer</span></button>
<span class="ge-add-layer-divider"></span>
<button type="button" data-adjustment-type="levels"><span class="ge-add-layer-symbol">▥</span><span>Levels</span></button>
<button type="button" data-adjustment-type="curves"><span class="ge-add-layer-symbol">⌁</span><span>Curves</span></button>
<button type="button" data-adjustment-type="exposure"><span class="ge-add-layer-symbol">☼</span><span>Exposure</span></button>
@@ -242,9 +240,16 @@ export function wireAIToolsMisc({
<button type="button" data-adjustment-type="color-balance"><span class="ge-add-layer-symbol">◒</span><span>Color Balance</span></button>
<button type="button" data-adjustment-type="selective-color"><span class="ge-add-layer-symbol">◎</span><span>Selective Color</span></button>
<button type="button" data-adjustment-type="gradient-map"><span class="ge-add-layer-symbol">▰</span><span>Gradient Map</span></button>
<span class="ge-add-layer-divider"></span>
<button type="button" data-adjustment-type="invert"><span class="ge-add-layer-symbol">◑</span><span>Invert</span></button>
<button type="button" data-adjustment-type="posterize"><span class="ge-add-layer-symbol">▤</span><span>Posterize</span></button>
<button type="button" data-adjustment-type="threshold"><span class="ge-add-layer-symbol">◧</span><span>Threshold</span></button>
<button type="button" data-adjustment-type="photo-filter"><span class="ge-add-layer-symbol">◍</span><span>Photo Filter</span></button>
<button type="button" data-adjustment-type="channel-mixer"><span class="ge-add-layer-symbol">⇄</span><span>Channel Mixer</span></button>
<button type="button" data-adjustment-type="color-lookup"><span class="ge-add-layer-symbol">▦</span><span>Color Lookup</span></button>
`;
document.body.appendChild(menu);
const rect = addButton.getBoundingClientRect();
const rect = anchor.getBoundingClientRect();
const menuRect = menu.getBoundingClientRect();
menu.style.left = `${Math.max(8, Math.min(window.innerWidth - menuRect.width - 8, rect.right - menuRect.width))}px`;
menu.style.top = `${Math.max(8, Math.min(window.innerHeight - menuRect.height - 8, rect.bottom + 5))}px`;
@@ -253,7 +258,7 @@ export function wireAIToolsMisc({
document.removeEventListener('pointerdown', away, true);
};
const away = pointerEvent => {
if (!menu.contains(pointerEvent.target) && pointerEvent.target !== addButton) close();
if (!menu.contains(pointerEvent.target) && pointerEvent.target !== anchor) close();
};
requestAnimationFrame(() => document.addEventListener('pointerdown', away, true));
menu.addEventListener('click', clickEvent => {
@@ -261,10 +266,26 @@ export function wireAIToolsMisc({
if (!button) return;
clickEvent.preventDefault();
clickEvent.stopPropagation();
if (button.dataset.layerKind === 'raster') addEmptyLayer();
else if (button.dataset.adjustmentType) openAdjustmentLayer?.(button.dataset.adjustmentType, addButton);
if (button.dataset.adjustmentType) openAdjustmentLayer?.(button.dataset.adjustmentType, anchor);
close();
});
};
// "+" adds a plain pixel layer directly.
const addButton = document.getElementById('ge-add-layer');
addButton?.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
document.querySelector('.ge-add-layer-menu')?.remove();
addEmptyLayer();
});
// "fx" opens the adjustment-layer chooser.
const addFxButton = document.getElementById('ge-add-fx');
addFxButton?.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
buildFxMenu(addFxButton);
});
return { addEmptyLayer };
+35
View File
@@ -0,0 +1,35 @@
// Pure aspect-fitting geometry for the editor. When a whole-image resize is
// asked for a target aspect that differs from the current image, content must
// be cropped to that aspect (centred on a focus point) and then scaled
// UNIFORMLY — never stretched.
//
// aspectFitCropRect returns the document-space rectangle to crop FIRST so a
// subsequent uniform scale-to-{targetW,targetH} preserves the subject aspect
// ratio. Returns the full image unchanged when the aspect already matches.
export function aspectFitCropRect({ width, height, focusX, focusY, targetAspect, tolerance = 0.005 } = {}) {
const w = Number(width);
const h = Number(height);
const a = Number(targetAspect);
if (!(w > 0) || !(h > 0) || !(a > 0)) return null;
const curAspect = w / h;
if (Math.abs(curAspect - a) / a <= tolerance) return { x: 0, y: 0, width: Math.round(w), height: Math.round(h) };
const fx = Number.isFinite(Number(focusX)) ? Number(focusX) : w / 2;
const fy = Number.isFinite(Number(focusY)) ? Number(focusY) : h / 2;
let cw;
let ch;
if (curAspect > a) {
ch = h;
cw = Math.max(1, Math.round(ch * a));
} else {
cw = w;
ch = Math.max(1, Math.round(cw / a));
}
let x = Math.round(fx - cw / 2);
let y = Math.round(fy - ch / 2);
x = Math.max(0, Math.min(w - cw, x));
y = Math.max(0, Math.min(h - ch, y));
return { x, y, width: cw, height: ch };
}
export default { aspectFitCropRect };
+35
View File
@@ -0,0 +1,35 @@
/**
* Batch runner — a small, dependency-free orchestrator that applies one action
* to every item in a list (open documents), isolating each item so a failure on
* one never aborts the batch. Pure async control flow: the caller supplies
* `runOne`, so the same loop is unit-testable without an editor.
*/
/**
* @param {object} options
* @param {Array<{id:string,name?:string}>} options.documents
* @param {(doc:object, index:number)=>Promise<any>} options.runOne
* @param {number} [options.delayMs]
* @param {(done:number,total:number,doc:object)=>void} [options.onProgress]
* @returns {Promise<Array<{id,name,ok,output?,error?}>>}
*/
export async function runBatchOverDocuments({ documents, runOne, delayMs = 0, onProgress = null } = {}) {
const list = Array.isArray(documents) ? documents.filter(Boolean) : [];
const results = [];
for (let index = 0; index < list.length; index += 1) {
const doc = list[index];
try {
const output = await runOne(doc, index);
results.push({ id: doc.id, name: doc.name, ok: true, output: output === undefined ? null : output });
} catch (error) {
results.push({ id: doc.id, name: doc.name, ok: false, error: String((error && error.message) || error) });
}
if (typeof onProgress === 'function') {
try { onProgress(index + 1, list.length, doc); } catch { /* progress is best-effort */ }
}
if (delayMs > 0) await new Promise(resolve => setTimeout(resolve, delayMs));
}
return results;
}
export default { runBatchOverDocuments };
+256
View File
@@ -0,0 +1,256 @@
/**
* Layer/graphic blend modes.
*
* Canvas2D can only composite a subset of the Photoshop blend modes natively.
* This module exposes that native set plus the "extra" modes PhotoCraft offers
* (Dissolve, Linear Burn, Darker Color, Linear Dodge/Add, Lighter Color,
* Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide) and a
* single `blendDraw` entry point that both paths go through.
*
* The non-native modes follow the W3C compositing spec (separable + the two
* non-separable luminance modes) and operate on ImageData in the overlap of
* the source and the destination so rendering stays reasonably cheap.
*/
export const NATIVE_BLEND_MODES = new Set([
'source-over',
'multiply',
'screen',
'overlay',
'darken',
'lighten',
'color-dodge',
'color-burn',
'hard-light',
'soft-light',
'difference',
'exclusion',
'hue',
'saturation',
'color',
'luminosity',
]);
const NATIVE_ALIASES = {
'linear-dodge': 'lighter',
add: 'lighter',
};
export const EXTRA_BLEND_MODES = [
{ value: 'linear-dodge', label: 'Linear Dodge (Add)' },
{ value: 'linear-burn', label: 'Linear Burn' },
{ value: 'darker-color', label: 'Darker Color' },
{ value: 'lighter-color', label: 'Lighter Color' },
{ value: 'vivid-light', label: 'Vivid Light' },
{ value: 'linear-light', label: 'Linear Light' },
{ value: 'pin-light', label: 'Pin Light' },
{ value: 'hard-mix', label: 'Hard Mix' },
{ value: 'subtract', label: 'Subtract' },
{ value: 'divide', label: 'Divide' },
{ value: 'dissolve', label: 'Dissolve' },
];
const NON_SEPARABLE = new Set(['darker-color', 'lighter-color']);
export function isNativeBlendMode(mode) {
if (!mode) return true;
return NATIVE_BLEND_MODES.has(mode) || Object.prototype.hasOwnProperty.call(NATIVE_ALIASES, mode);
}
export function isKnownBlendMode(mode) {
if (!mode) return true;
return isNativeBlendMode(mode) || EXTRA_BLEND_MODES.some(entry => entry.value === mode);
}
function clamp01(value) {
return value < 0 ? 0 : value > 1 ? 1 : value;
}
function lum(r, g, b) {
return 0.299 * r + 0.587 * g + 0.114 * b;
}
// Separable per-channel blend functions on normalized [0,1] values.
function blendChannel(mode, cb, cs) {
switch (mode) {
case 'normal':
return cs;
case 'multiply':
return cb * cs;
case 'screen':
return cb + cs - cb * cs;
case 'overlay':
return cb <= 0.5 ? 2 * cb * cs : 1 - 2 * (1 - cb) * (1 - cs);
case 'darken':
return Math.min(cb, cs);
case 'lighten':
return Math.max(cb, cs);
case 'color-dodge':
if (cb === 0) return 0;
if (cs === 1) return 1;
return Math.min(1, cb / (1 - cs));
case 'color-burn':
if (cb === 1) return 1;
if (cs === 0) return 0;
return 1 - Math.min(1, (1 - cb) / cs);
case 'hard-light':
return cs <= 0.5 ? 2 * cs * cb : 1 - 2 * (1 - cs) * (1 - cb);
case 'soft-light': {
if (cs <= 0.5) return cb - (1 - 2 * cs) * cb * (1 - cb);
const d = cb <= 0.25 ? ((16 * cb - 12) * cb + 4) * cb : Math.sqrt(cb);
return cb + (2 * cs - 1) * (d - cb);
}
case 'difference':
return Math.abs(cb - cs);
case 'exclusion':
return cb + cs - 2 * cb * cs;
case 'linear-burn':
return clamp01(cb + cs - 1);
case 'linear-dodge':
return clamp01(cb + cs);
case 'vivid-light':
return cs <= 0.5
? (cs === 0 ? 0 : 1 - Math.min(1, (1 - cb) / (2 * cs)))
: (cs === 1 ? 1 : Math.min(1, cb / (2 * (1 - cs))));
case 'linear-light':
return clamp01(cb + 2 * cs - 1);
case 'pin-light':
return cs <= 0.5 ? Math.min(cb, 2 * cs) : Math.max(cb, 2 * cs - 1);
case 'hard-mix': {
const vivid = cs <= 0.5
? (cs === 0 ? 0 : 1 - Math.min(1, (1 - cb) / (2 * cs)))
: (cs === 1 ? 1 : Math.min(1, cb / (2 * (1 - cs))));
return vivid < 0.5 ? 0 : 1;
}
case 'subtract':
return clamp01(cb - cs);
case 'divide':
return cs === 0 ? 1 : clamp01(cb / cs);
default:
return cs;
}
}
function dissolveRandom(i) {
let seed = (i * 2654435761) >>> 0;
seed ^= seed >>> 13;
seed = (seed * 1274126177) >>> 0;
return seed / 4294967296;
}
function ensureSourceData(source) {
const sw = source.width || source.naturalWidth || 0;
const sh = source.height || source.naturalHeight || 0;
if (!sw || !sh) return null;
const scratch = document.createElement('canvas');
scratch.width = sw;
scratch.height = sh;
const sctx = scratch.getContext('2d');
sctx.drawImage(source, 0, 0, sw, sh);
return { data: sctx.getImageData(0, 0, sw, sh).data, sw, sh };
}
function blendCustom(ctx, source, mode, alpha, dx, dy) {
if (alpha <= 0) return;
const src = ensureSourceData(source);
if (!src) return;
const tw = ctx.canvas.width;
const th = ctx.canvas.height;
const sw = src.sw;
const sh = src.sh;
const sx0 = Math.max(0, -dx);
const sy0 = Math.max(0, -dy);
const dx0 = Math.max(0, dx);
const dy0 = Math.max(0, dy);
const w = Math.min(sw - sx0, tw - dx0);
const h = Math.min(sh - sy0, th - dy0);
if (w <= 0 || h <= 0) return;
const dst = ctx.getImageData(dx0, dy0, w, h);
const dd = dst.data;
const sd = src.data;
const nonSeparable = NON_SEPARABLE.has(mode);
const dissolve = mode === 'dissolve';
for (let y = 0; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
const si = ((y + sy0) * sw + (x + sx0)) * 4;
const di = (y * w + x) * 4;
const sa = (sd[si + 3] / 255) * alpha;
const ba = dd[di + 3] / 255;
if (dissolve) {
const seed = (y + dy0) * 73856093 ^ (x + dx0) * 19349663;
if (dissolveRandom(seed) >= sa) continue;
dd[di] = sd[si];
dd[di + 1] = sd[si + 1];
dd[di + 2] = sd[si + 2];
dd[di + 3] = 255;
continue;
}
if (sa === 0) continue;
const sr = sd[si] / 255;
const sg = sd[si + 1] / 255;
const sb = sd[si + 2] / 255;
const br = dd[di] / 255;
const bg = dd[di + 1] / 255;
const bb = dd[di + 2] / 255;
let mergedR;
let mergedG;
let mergedB;
if (nonSeparable) {
const backdropLum = lum(br, bg, bb);
const sourceLum = lum(sr, sg, sb);
const useSource = mode === 'darker-color' ? sourceLum < backdropLum : sourceLum > backdropLum;
mergedR = useSource ? sr : br;
mergedG = useSource ? sg : bg;
mergedB = useSource ? sb : bb;
} else {
mergedR = blendChannel(mode, br, sr);
mergedG = blendChannel(mode, bg, sg);
mergedB = blendChannel(mode, bb, sb);
}
const srEff = (1 - ba) * sr + ba * mergedR;
const sgEff = (1 - ba) * sg + ba * mergedG;
const sbEff = (1 - ba) * sb + ba * mergedB;
const ao = sa + ba * (1 - sa);
if (ao <= 0) continue;
const cr = (sa * srEff + ba * br * (1 - sa)) / ao;
const cg = (sa * sgEff + ba * bg * (1 - sa)) / ao;
const cbOut = (sa * sbEff + ba * bb * (1 - sa)) / ao;
dd[di] = Math.round(clamp01(cr) * 255);
dd[di + 1] = Math.round(clamp01(cg) * 255);
dd[di + 2] = Math.round(clamp01(cbOut) * 255);
dd[di + 3] = Math.round(ao * 255);
}
}
ctx.putImageData(dst, dx0, dy0);
}
/**
* Composite `source` onto a 2D context (or canvas) using `mode` at `alpha`.
* Native modes use globalCompositeOperation; the rest fall back to pixel math.
*/
export function blendDraw(target, source, mode, alpha = 1, dx = 0, dy = 0) {
if (!target || !source) return;
const ctx = typeof target.getContext === 'function' ? target.getContext('2d') : target;
const a = Number.isFinite(alpha) ? clamp01(alpha) : 1;
const normalized = mode || 'source-over';
if (isNativeBlendMode(normalized)) {
const prevAlpha = ctx.globalAlpha;
const prevOp = ctx.globalCompositeOperation;
ctx.globalAlpha = a;
ctx.globalCompositeOperation = NATIVE_ALIASES[normalized] || normalized;
ctx.drawImage(source, dx, dy);
ctx.globalAlpha = prevAlpha;
ctx.globalCompositeOperation = prevOp;
return;
}
blendCustom(ctx, source, normalized, a, dx, dy);
}
+30 -20
View File
@@ -24,6 +24,32 @@ export function createBrushSampler({ getDiameter, getSpacing, getSmoothing, emit
emit(emitted);
};
// Emit evenly spaced dabs from the last emitted sample toward `target`,
// carrying the sub-spacing remainder forward. Shared by drag updates and
// the final pointer-up so a stroke ends on the same spacing grid instead
// of stamping one detached dab (which reads as a dot where drawing stopped).
const emitSpaced = (target) => {
if (!emitted) return;
const start = { ...emitted };
const dx = target.x - start.x;
const dy = target.y - start.y;
const distance = Math.hypot(dx, dy);
if (!distance) return;
const diameter = Math.max(1, Number(getDiameter()) || 1);
const spacing = Math.max(0.5, diameter * Math.max(0.01, Number(getSpacing()) || 0.01));
let travelled = spacing - remainder;
while (travelled <= distance) {
const t = travelled / distance;
output({
x: start.x + dx * t,
y: start.y + dy * t,
pressure: start.pressure + (target.pressure - start.pressure) * t,
});
travelled += spacing;
}
remainder = Math.max(0, distance - (travelled - spacing));
};
const begin = (sample) => {
emitted = null;
filtered = { ...sample, pressure: normalisePressure(sample.pressure) };
@@ -41,30 +67,14 @@ export function createBrushSampler({ getDiameter, getSpacing, getSmoothing, emit
y: filtered.y + (raw.y - filtered.y) * response,
pressure: filtered.pressure + (raw.pressure - filtered.pressure) * response,
};
const start = { ...emitted };
const dx = filtered.x - start.x;
const dy = filtered.y - start.y;
const distance = Math.hypot(dx, dy);
if (!distance) return;
const diameter = Math.max(1, Number(getDiameter()) || 1);
const spacing = Math.max(0.5, diameter * Math.max(0.01, Number(getSpacing()) || 0.01));
let travelled = spacing - remainder;
while (travelled <= distance) {
const t = travelled / distance;
output({
x: start.x + dx * t,
y: start.y + dy * t,
pressure: start.pressure + (filtered.pressure - start.pressure) * t,
});
travelled += spacing;
}
remainder = Math.max(0, distance - (travelled - spacing));
emitSpaced(filtered);
};
const end = (sample) => {
// Reach the true pointer-up point along the spacing grid rather than with
// a single far dab, so the stroke does not terminate in a detached dot.
if (sample && emitted) {
const finalSample = { ...sample, pressure: normalisePressure(sample.pressure) };
if (Math.hypot(finalSample.x - emitted.x, finalSample.y - emitted.y) > 0.25) output(finalSample);
emitSpaced({ ...sample, pressure: normalisePressure(sample.pressure) });
}
emitted = null;
filtered = null;
+3
View File
@@ -4,6 +4,7 @@ const BUILT_INS = [
{ id: 'soft-round', name: 'Soft Round', size: 80, opacity: 100, flow: 35, softness: 100, spacing: 12, smoothing: 25, blendMode: 'source-over' },
{ id: 'hard-round', name: 'Hard Round', size: 24, opacity: 100, flow: 100, softness: 0, spacing: 18, smoothing: 15, blendMode: 'source-over' },
{ id: 'detail', name: 'Detail', size: 6, opacity: 100, flow: 70, softness: 20, spacing: 10, smoothing: 55, blendMode: 'source-over' },
{ id: 'pixel-1px', name: 'Pixel', size: 1, opacity: 100, flow: 100, softness: 0, spacing: 1, smoothing: 0, blendMode: 'source-over', pixel: true },
];
export function loadBrushPresets(storage = globalThis.localStorage) {
@@ -31,6 +32,7 @@ export function captureBrushPreset(state, name) {
spacing: state.brushSpacing,
smoothing: state.brushSmoothing,
blendMode: state.brushBlendMode,
pixel: !!state.brushPixel,
};
}
@@ -43,4 +45,5 @@ export function applyBrushPreset(state, preset) {
state.brushSpacing = preset.spacing;
state.brushSmoothing = preset.smoothing;
state.brushBlendMode = preset.blendMode || 'source-over';
state.brushPixel = !!preset.pixel;
}
+80
View File
@@ -0,0 +1,80 @@
/** Command palette (Ctrl/Cmd+K): fuzzy list of tools, panels and actions. */
export function createCommandPalette({ commands = [], onRun = null } = {}) {
const overlay = document.createElement('div');
overlay.className = 'ge-command-palette';
overlay.hidden = true;
overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
overlay.setAttribute('aria-label', 'Command palette');
overlay.innerHTML = `
<div class="ge-command-panel">
<input class="ge-command-input" type="text" placeholder="Type a command..." aria-label="Command" autocomplete="off" />
<div class="ge-command-list" role="listbox"></div>
</div>`;
document.body.appendChild(overlay);
const input = overlay.querySelector('.ge-command-input');
const list = overlay.querySelector('.ge-command-list');
let filtered = [];
let activeIndex = 0;
function render() {
const query = input.value.trim().toLowerCase();
filtered = commands.filter(cmd => !query || String(cmd.label).toLowerCase().includes(query));
list.innerHTML = '';
if (!filtered.length) {
const empty = document.createElement('p');
empty.className = 'ge-command-empty';
empty.textContent = 'No matching commands';
list.appendChild(empty);
return;
}
if (activeIndex >= filtered.length) activeIndex = 0;
filtered.forEach((cmd, index) => {
const row = document.createElement('button');
row.type = 'button';
row.className = `ge-command-item${index === activeIndex ? ' active' : ''}`;
row.setAttribute('role', 'option');
row.setAttribute('aria-selected', index === activeIndex ? 'true' : 'false');
row.textContent = cmd.label;
row.addEventListener('click', () => run(cmd));
list.appendChild(row);
});
}
function run(cmd) {
close();
if (typeof cmd.run === 'function') cmd.run();
else if (typeof onRun === 'function') onRun(cmd);
}
function open() {
overlay.hidden = false;
input.value = '';
activeIndex = 0;
render();
input.focus();
}
function close() {
overlay.hidden = true;
}
input.addEventListener('input', () => { activeIndex = 0; render(); });
input.addEventListener('keydown', (event) => {
if (event.key === 'Escape') { event.preventDefault(); close(); }
else if (event.key === 'ArrowDown') { event.preventDefault(); activeIndex = Math.min(activeIndex + 1, filtered.length - 1); render(); }
else if (event.key === 'ArrowUp') { event.preventDefault(); activeIndex = Math.max(activeIndex - 1, 0); render(); }
else if (event.key === 'Enter') { event.preventDefault(); if (filtered[activeIndex]) run(filtered[activeIndex]); }
});
overlay.addEventListener('pointerdown', (event) => { if (event.target === overlay) close(); });
return {
element: overlay,
open,
close,
toggle: () => (overlay.hidden ? open() : close()),
isOpen: () => !overlay.hidden,
};
}
+429 -178
View File
@@ -6,10 +6,10 @@
* sections are all toggled `display:none` here; the tool-switch handler
* in galleryEditor.js shows the section matching the active tool.
*
* @param {{ color: string, brushSize: number, wandTolerance: number }} ctx
* @param {{ color: string, brushSize: number, wandTolerance: number, bucketTolerance: number, cropAspectPreset: string, eyedropperSampleSize: number }} ctx
* @returns {string}
*/
export function controlsHTML({ color, brushSize, wandTolerance }) {
export function controlsHTML({ color, brushSize, wandTolerance, bucketTolerance = 32, cropAspectPreset = 'free', eyedropperSampleSize = 1 }) {
const brushSliderValue = Math.round(Math.log(Math.max(1, brushSize)) / Math.log(800) * 1000);
return `
<div id="ge-pen-section" style="display:none;">
@@ -19,6 +19,28 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<button type="button" class="ge-btn ge-btn-sm" id="ge-pen-cancel" title="Cancel path (Escape)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m18 6-12 12M6 6l12 12"/></svg> Cancel</button>
</div>
</div>
<div id="ge-liquify-section" style="display:none;">
<div class="ge-section-title">Liquify</div>
<div class="ge-control-row">
<label for="ge-liquify-mode">Mode</label>
<select id="ge-liquify-mode" class="ge-ctl-select">
<option value="push">Push</option>
<option value="twirl">Twirl</option>
<option value="pucker">Pucker</option>
<option value="bloat">Bloat</option>
<option value="smooth">Smooth</option>
</select>
</div>
<div class="ge-control-row ge-eraser-row">
<label><span id="ge-liquify-size-label">120px</span></label>
<input type="range" id="ge-liquify-size" min="10" max="600" value="120" />
</div>
<div class="ge-control-row ge-eraser-row">
<label>Strength <span id="ge-liquify-strength-label">50%</span></label>
<input type="range" id="ge-liquify-strength" min="1" max="100" value="50" />
</div>
<div class="ge-control-row ge-liquify-hint">Drag on the canvas to warp pixels. One undo step per stroke.</div>
</div>
<div class="ge-layer-geometry-section" id="ge-layer-geometry-section">
<div class="ge-section-title"><span>Position</span><span id="ge-layer-geometry-name"></span></div>
<div class="ge-layer-geometry-grid">
@@ -33,31 +55,105 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<label>Color</label>
<input type="color" class="ge-color-picker" value="${color}" />
</div>
<div class="ge-control-row">
<label>Size <span class="ge-size-label">${brushSize}px</span></label>
<div class="ge-control-row ge-brush-size-row">
<label><span class="ge-size-label">${brushSize}px</span></label>
<input type="range" class="ge-size-slider" min="0" max="1000" value="${brushSliderValue}" />
<span class="ge-brush-more-wrap">
<button type="button" class="ge-btn ge-btn-sm ge-brush-more-btn" id="ge-brush-more" aria-haspopup="true" aria-expanded="false" title="More brush options (spacing, smoothing, blend, opacity, pen pressure)" aria-label="More brush options">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>
</button>
<div class="ge-brush-more-menu" id="ge-brush-more-menu" hidden>
<div class="ge-section-title">Stroke</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-brush-preview-spacing" aria-hidden="true"></span>
<label>Spacing <span id="ge-brush-spacing-label">15%</span></label>
<input type="range" id="ge-brush-spacing" min="1" max="100" value="15" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-brush-preview-smoothing" aria-hidden="true"></span>
<label>Smoothing <span id="ge-brush-smoothing-label">25%</span></label>
<input type="range" id="ge-brush-smoothing" min="0" max="95" value="25" />
</div>
<div class="ge-control-row">
<label for="ge-brush-blend">Blend</label>
<select id="ge-brush-blend">
<option value="source-over">Normal</option><option value="multiply">Multiply</option>
<option value="screen">Screen</option><option value="overlay">Overlay</option>
<option value="soft-light">Soft Light</option><option value="color">Color</option>
</select>
</div>
<div class="ge-brush-stroke-group" data-stroke-tool="brush">
<div class="ge-section-title" id="ge-stroke-title-brush">Brush</div>
<div class="ge-control-row ge-eraser-row" id="ge-brush-opacity-row">
<span class="ge-eraser-preview" id="ge-brush-preview-opacity" aria-hidden="true"></span>
<label>Opacity <span id="ge-brush-opacity-label">100%</span></label>
<input type="range" id="ge-brush-opacity" min="10" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row" id="ge-brush-flow-row">
<span class="ge-eraser-preview" id="ge-brush-preview-flow" aria-hidden="true"></span>
<label>Flow <span id="ge-brush-flow-label">100%</span></label>
<input type="range" id="ge-brush-flow" min="5" max="100" value="100" />
</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 class="ge-brush-stroke-group" data-stroke-tool="eraser">
<div class="ge-section-title">Eraser</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-eraser-preview-opacity" aria-hidden="true"></span>
<label>Opacity <span id="ge-eraser-opacity-label">100%</span></label>
<input type="range" id="ge-eraser-opacity" min="10" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-eraser-preview-flow" aria-hidden="true"></span>
<label>Flow <span id="ge-eraser-flow-label">100%</span></label>
<input type="range" id="ge-eraser-flow" min="5" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-eraser-preview-softness" aria-hidden="true"></span>
<label>Softness <span id="ge-eraser-softness-label">100%</span></label>
<input type="range" id="ge-eraser-softness" min="0" max="300" value="100" title="Soft brush edge — blurs the stroke's alpha so the eraser fades out at the perimeter." />
</div>
</div>
<div class="ge-brush-stroke-group" data-stroke-tool="clone">
<div class="ge-section-title" id="ge-stroke-title-clone">Clone</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-clone-preview-opacity" aria-hidden="true"></span>
<label>Opacity <span id="ge-clone-opacity-label">100%</span></label>
<input type="range" id="ge-clone-opacity" min="10" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-clone-preview-flow" aria-hidden="true"></span>
<label>Flow <span id="ge-clone-flow-label">100%</span></label>
<input type="range" id="ge-clone-flow" min="5" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-clone-preview-softness" aria-hidden="true"></span>
<label>Softness <span id="ge-clone-softness-label">100%</span></label>
<input type="range" id="ge-clone-softness" min="0" max="300" value="100" title="Soft brush edge — blurs each stamp for a feathered fade." />
</div>
</div>
<div class="ge-brush-stroke-group" data-stroke-tool="smudge">
<div class="ge-section-title">Smudge</div>
<div class="ge-control-row ge-eraser-row" id="ge-smudge-strength-row">
<span class="ge-eraser-preview" id="ge-smudge-preview-strength" aria-hidden="true"></span>
<label>Strength <span id="ge-smudge-strength-label">65%</span></label>
<input type="range" id="ge-smudge-strength" min="5" max="100" value="65" title="How strongly Smudge carries sampled pixels into the stroke." />
</div>
</div>
<div class="ge-control-row ge-brush-pressure-row">
<span class="ge-pressure-option" title="Pen pressure changes flow"><span>Flow</span><label class="toggle-switch"><input type="checkbox" id="ge-pressure-flow" checked /><span class="toggle-slider"></span></label></span>
</div>
</div>
</span>
</div>
<div class="ge-section-title">Stroke</div>
<div class="ge-control-row ge-eraser-row">
<label>Spacing <span id="ge-brush-spacing-label">15%</span></label>
<input type="range" id="ge-brush-spacing" min="1" max="100" value="15" />
</div>
<div class="ge-control-row ge-eraser-row">
<label>Smoothing <span id="ge-brush-smoothing-label">25%</span></label>
<input type="range" id="ge-brush-smoothing" min="0" max="95" value="25" />
</div>
<div class="ge-control-row">
<label for="ge-brush-blend">Blend</label>
<select id="ge-brush-blend">
<option value="source-over">Normal</option><option value="multiply">Multiply</option>
<option value="screen">Screen</option><option value="overlay">Overlay</option>
<option value="soft-light">Soft Light</option><option value="color">Color</option>
</select>
</div>
<div class="ge-control-row ge-brush-pressure-row">
<span class="ge-pressure-option" title="Pen pressure changes brush size"><span>Size</span><label class="toggle-switch"><input type="checkbox" id="ge-pressure-size" checked /><span class="toggle-slider"></span></label></span>
<span class="ge-pressure-option" title="Pen pressure changes opacity"><span>Opacity</span><label class="toggle-switch"><input type="checkbox" id="ge-pressure-opacity" /><span class="toggle-slider"></span></label></span>
<span class="ge-pressure-option" title="Pen pressure changes flow"><span>Flow</span><label class="toggle-switch"><input type="checkbox" id="ge-pressure-flow" checked /><span class="toggle-slider"></span></label></span>
<div class="ge-control-row ge-eraser-row" id="ge-dodgeburn-intensity-row" style="display:none;">
<span class="ge-eraser-preview" id="ge-dodgeburn-preview" aria-hidden="true"></span>
<label title="Intensity">Int <span id="ge-dodgeburn-intensity-label">25%</span></label>
<input type="range" id="ge-dodgeburn-intensity" min="0" max="100" value="25" title="How strongly Dodge lightens or Burn darkens each dab." />
</div>
<div class="ge-control-row ge-brush-preset-row">
<select id="ge-brush-preset" aria-label="Brush preset"></select>
@@ -96,19 +192,47 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
</span>
</div>
<div class="ge-control-row"><label for="ge-eyedropper-sample">Sample</label><select id="ge-eyedropper-sample"><option value="composite">All layers</option><option value="layer">Active layer</option></select></div>
<div class="ge-control-row"><label for="ge-eyedropper-sample-size">Sample Size</label><select id="ge-eyedropper-sample-size" title="Point samples one pixel; the averages blur the reading over an N-by-N block.">${[1, 3, 5, 11, 31, 51].map((n) => `<option value="${n}"${Number(eyedropperSampleSize) === n ? ' selected' : ''}>${n === 1 ? 'Point Sample' : `${n} by ${n} Average`}</option>`).join('')}</select></div>
</div>
<div class="ge-bucket-section" id="ge-bucket-section" style="display:none;">
<div class="ge-section-title">Paint Bucket</div>
<div class="ge-control-row ge-eraser-row">
<label for="ge-bucket-tolerance">Tolerance <span id="ge-bucket-tolerance-label">${bucketTolerance}</span></label>
<input type="range" id="ge-bucket-tolerance" min="0" max="255" value="${bucketTolerance}" title="How different a neighbouring pixel can be and still be filled (0-255)." />
</div>
</div>
<div class="ge-crop-section" id="ge-crop-section" style="display:none;">
<div class="ge-section-title">Crop</div>
<div class="ge-control-row ge-crop-preset-row" id="ge-crop-presets" role="group" aria-label="Crop aspect ratio">
<button type="button" class="ge-btn ge-btn-sm ge-crop-preset${cropAspectPreset === 'free' ? ' active' : ''}" data-crop-preset="free" title="Crop freely (no aspect lock)">Free</button>
<button type="button" class="ge-btn ge-btn-sm ge-crop-preset${cropAspectPreset === 'original' ? ' active' : ''}" data-crop-preset="original" title="Keep the original image aspect ratio">Original</button>
<button type="button" class="ge-btn ge-btn-sm ge-crop-preset${cropAspectPreset === '1:1' ? ' active' : ''}" data-crop-preset="1:1" title="Square (1:1)">1:1</button>
<button type="button" class="ge-btn ge-btn-sm ge-crop-preset${cropAspectPreset === '4:5' ? ' active' : ''}" data-crop-preset="4:5" title="Portrait (4:5)">4:5</button>
<button type="button" class="ge-btn ge-btn-sm ge-crop-preset${cropAspectPreset === '16:9' ? ' active' : ''}" data-crop-preset="16:9" title="Widescreen (16:9)">16:9</button>
<label class="ge-crop-custom" title="Type any ratio, e.g. 3:2 or 21:9">
<input type="text" id="ge-crop-custom-ratio" inputmode="numeric" placeholder="W:H" aria-label="Custom crop ratio" spellcheck="false" autocomplete="off" />
</label>
</div>
<p class="ge-section-hint">Pick a ratio, then drag on the canvas. Press Enter to apply.</p>
</div>
<div class="ge-text-section" id="ge-text-section" style="display:none;">
<textarea id="ge-text-content" rows="3" placeholder="Type text..." aria-label="Text content"></textarea>
<textarea id="ge-text-content" rows="2" placeholder="Type text..." aria-label="Text content"></textarea>
<div class="ge-text-grid">
<label class="ge-text-field ge-text-font-field"><span>Font</span>
<select id="ge-text-font">
<option value="Arial">Arial</option>
<option value="Verdana">Verdana</option>
<option value="Inter">Inter</option>
<option value="Roboto">Roboto</option>
<option value="Playfair Display">Playfair Display</option>
<option value="Lobster">Lobster</option>
<option value="Bebas Neue">Bebas Neue</option>
<option value="Roboto Mono">Roboto Mono</option>
<option value="Space Grotesk">Space Grotesk</option>
<option value="Fraunces">Fraunces</option>
<option value="Syne">Syne</option>
<option value="Bungee">Bungee</option>
<option value="Instrument Serif">Instrument Serif</option>
<option value="Georgia">Georgia</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Courier New">Courier New</option>
<option value="Impact">Impact</option>
<option value="system-ui">System</option>
</select>
</label>
<label class="ge-text-field ge-text-size-field"><span>Size</span>
@@ -124,6 +248,7 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<button type="button" class="ge-text-toggle" data-text-align="center" title="Align center" aria-pressed="false">&#8596;</button>
<button type="button" class="ge-text-toggle" data-text-align="right" title="Align right" aria-pressed="false">&#8677;</button>
</div>
<div class="ge-opt-more" id="ge-text-more" hidden>
<div class="ge-text-grid">
<label class="ge-text-field"><span>Line</span>
<input id="ge-text-line-height" type="number" min="0.5" max="5" step="0.1" value="1.2" />
@@ -150,6 +275,38 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<input type="color" class="ge-color-picker" id="ge-text-stroke-color" value="#000000" title="Stroke color" aria-label="Stroke color" />
</div>
<label class="ge-text-auto-width-option"><span>Auto width</span><span class="toggle-switch"><input type="checkbox" id="ge-text-auto-width" /><span class="toggle-slider"></span></span></label>
<div class="ge-text-grid">
<label class="ge-text-field"><span>Writing</span>
<select id="ge-text-direction"><option value="horizontal">Horizontal</option><option value="vertical">Vertical</option></select>
</label>
<label class="ge-text-field"><span>Warp</span>
<select id="ge-text-warp">
<option value="none">None</option>
<option value="arc">Arc</option>
<option value="arch">Arch</option>
<option value="bulge">Bulge</option>
<option value="flag">Flag</option>
<option value="wave">Wave</option>
<option value="rise">Rise</option>
<option value="fisheye">Fisheye</option>
<option value="inflate">Inflate</option>
<option value="squeeze">Squeeze</option>
<option value="twist">Twist</option>
</select>
</label>
</div>
<div class="ge-text-grid">
<label class="ge-text-field"><span>Warp amt</span>
<input id="ge-text-warp-amount" type="range" min="-100" max="100" step="1" value="0" />
</label>
</div>
<div class="ge-text-grid ge-text-opentype-row">
<label class="ge-text-field ge-text-inline-check"><span>Small caps</span><input type="checkbox" id="ge-text-small-caps" /></label>
<label class="ge-text-field ge-text-inline-check"><span>Kerning</span><input type="checkbox" id="ge-text-kerning" checked /></label>
<label class="ge-text-field ge-text-inline-check"><span>Ligatures</span><input type="checkbox" id="ge-text-ligatures" checked /></label>
</div>
</div>
<button type="button" class="ge-btn ge-btn-sm ge-more-toggle" id="ge-text-more-toggle" aria-expanded="false" aria-controls="ge-text-more">More</button>
<button type="button" class="ge-btn ge-btn-sm" id="ge-text-rasterize">Rasterize</button>
</div>
<div class="ge-shape-section" id="ge-shape-section" style="display:none;">
@@ -164,6 +321,7 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<label class="ge-text-field"><span>Fill</span><input type="color" class="ge-color-picker" id="ge-shape-fill" value="${color}" /></label>
<label class="ge-text-field"><span>Stroke</span><input type="color" class="ge-color-picker" id="ge-shape-stroke" value="#111111" /></label>
</div>
<div class="ge-opt-more" id="ge-shape-more" hidden>
<div class="ge-text-grid">
<label class="ge-text-field"><span>Fill type</span>
<select id="ge-shape-fill-type"><option value="solid">Solid</option><option value="linear-gradient">Linear gradient</option></select>
@@ -184,8 +342,26 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<label class="ge-text-field"><span>Radius</span><input id="ge-shape-radius" type="number" min="0" max="5000" step="1" value="0" /></label>
</div>
<label class="ge-text-field ge-shape-sides-field" hidden><span>Sides</span><input id="ge-shape-sides" type="number" min="3" max="24" step="1" value="5" /></label>
</div>
<button type="button" class="ge-btn ge-btn-sm ge-more-toggle" id="ge-shape-more-toggle" aria-expanded="false" aria-controls="ge-shape-more">More</button>
<button type="button" class="ge-btn ge-btn-sm" id="ge-shape-rasterize">Rasterize</button>
</div>
<div class="ge-path-section" id="ge-path-section" style="display:none;">
<div class="ge-section-title">Path</div>
<p class="ge-section-hint">Click to add anchors; double-click or press Enter to finish.</p>
<div class="ge-text-grid">
<label class="ge-text-field"><span>Fill</span><input type="color" class="ge-color-picker" id="ge-path-fill" value="${color}" /></label>
<label class="ge-text-field"><span>Stroke</span><input type="color" class="ge-color-picker" id="ge-path-stroke" value="#111111" /></label>
</div>
<div class="ge-text-grid">
<label class="ge-text-field"><span>Width</span><input id="ge-path-stroke-width" type="number" min="0" max="500" step="1" value="2" /></label>
<label class="ge-text-field ge-path-closed-field"><span>Close path</span><input id="ge-path-closed" type="checkbox" checked /></label>
</div>
<div class="ge-control-row" style="display:flex;gap:4px;">
<button type="button" class="ge-btn ge-btn-sm" id="ge-path-finish">Finish</button>
<button type="button" class="ge-btn ge-btn-sm" id="ge-path-cancel">Cancel</button>
</div>
</div>
<div class="ge-marquee-section" id="ge-marquee-section" style="display:none;">
<div class="ge-control-row" style="display:flex;gap:4px;margin-bottom:4px;">
<button type="button" class="ge-btn ge-btn-sm ge-marquee-shape-btn active" data-marquee-shape="rectangle" title="Rectangular marquee" aria-pressed="true">
@@ -198,14 +374,13 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn active" data-wand-mode="replace" title="New selection">New</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection">+</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection">−</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection">∩</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg></button>
</div>
<div class="ge-marquee-constraint-row">
<label for="ge-marquee-constraint">Style</label>
<select id="ge-marquee-constraint" title="Marquee sizing style">
<option value="free">Free</option>
<option value="ratio">Fixed ratio</option>
<option value="size">Fixed size</option>
</select>
<div class="ge-marquee-dimensions" hidden>
<label>W <input type="number" id="ge-marquee-width" min="1" step="1" value="1" inputmode="decimal" /></label>
@@ -215,16 +390,18 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
</button>
</div>
</div>
<div class="ge-control-row ge-actions" style="margin-top:4px;flex-wrap:wrap;">
<div class="ge-control-row ge-actions" style="margin-top:2px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-mask-vis-btn visible" id="ge-marquee-vis" title="Hide selection overlay" aria-label="Toggle selection overlay">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-clear" title="Clear selection">Clear</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-invert" title="Invert selection">Invert</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-delete" title="Erase selected pixels">Erase</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-copy" title="Copy selection to a new layer">Copy Layer</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-mask" title="Add selection to mask">To Mask</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false">Quick Mask</button>
<button class="ge-btn ge-btn-sm" id="ge-marquee-clear" title="Clear selection" aria-label="Clear selection">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-invert" title="Invert selection"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>Invert</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-delete" title="Erase selected pixels"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4a2 2 0 0 1 0-3l9-9a2 2 0 0 1 3 0l4 4a2 2 0 0 1 0 3l-9 9a2 2 0 0 1-3 0Z"/><path d="M22 21H7"/></svg>Erase</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-copy" title="Copy selection to a new layer"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>Copy Layer</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-marquee-mask" title="Add selection to mask"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="5"/></svg>To Mask</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" stroke-dasharray="3 3"/><circle cx="12" cy="12" r="3.5"/></svg>Quick Mask</button>
</div>
</div>
<div class="ge-lasso-section" id="ge-lasso-section" style="display:none;">
@@ -232,50 +409,62 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn active" data-wand-mode="replace" title="New selection">New</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection">+</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection">−</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection">∩</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg></button>
</div>
<div class="ge-control-row ge-eraser-row ge-sel-refine" id="ge-lasso-refine-feather" style="display:none;">
<span class="ge-eraser-preview" id="ge-lasso-feather-preview" aria-hidden="true"></span>
<label>Feather <span id="ge-lasso-feather-label">0px</span></label>
<input type="range" id="ge-lasso-feather" min="0" max="200" value="0" title="Soften the selection edge — feathers the mask alpha." />
<span class="ge-lasso-more-wrap">
<button type="button" class="ge-btn ge-btn-sm ge-lasso-more-btn" id="ge-lasso-more" aria-haspopup="true" aria-expanded="false" aria-label="More lasso options (feather, edge stroke, magnetic)" title="More lasso options (feather, edge stroke, magnetic)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
</button>
<div class="ge-lasso-more-menu" id="ge-lasso-more-menu" hidden>
<div class="ge-control-row ge-eraser-row ge-sel-refine" id="ge-lasso-refine-feather" style="display:none;">
<span class="ge-eraser-preview" id="ge-lasso-feather-preview" aria-hidden="true"></span>
<label>Feather <span id="ge-lasso-feather-label">0px</span></label>
<input type="range" id="ge-lasso-feather" min="0" max="200" value="0" title="Soften the selection edge — feathers the mask alpha." />
</div>
<div class="ge-control-row ge-eraser-row ge-sel-refine" id="ge-lasso-refine-grow" style="display:none;">
<span class="ge-eraser-preview" id="ge-lasso-grow-preview" aria-hidden="true"></span>
<label>Edge stroke <span id="ge-lasso-grow-label">0px</span></label>
<input type="range" id="ge-lasso-grow" min="-40" max="40" value="0" title="Expand (+) or contract (−) the selection before baking." />
</div>
<div class="ge-control-row">
<button type="button" class="ge-btn ge-btn-sm" id="ge-lasso-magnetic" aria-pressed="false" title="Snap the outline to image edges as you drag.">Magnetic</button>
</div>
<div class="ge-control-row ge-eraser-row" id="ge-lasso-mag-width-row" style="display:none;">
<label>Width <span id="ge-lasso-mag-width-label">12px</span></label>
<input type="range" id="ge-lasso-mag-width" min="2" max="60" value="12" title="Search radius for the strongest nearby edge." />
</div>
<div class="ge-control-row ge-eraser-row" id="ge-lasso-mag-contrast-row" style="display:none;">
<label>Contrast <span id="ge-lasso-mag-contrast-label">20%</span></label>
<input type="range" id="ge-lasso-mag-contrast" min="0" max="100" value="20" title="Minimum edge strength to snap to." />
</div>
<p class="ge-lasso-tip">Draw a freehand selection. Esc to cancel.</p>
</div>
</span>
<div class="ge-control-row ge-actions" style="margin-top:2px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-mask-vis-btn visible" id="ge-lasso-vis" title="Hide selection overlay" aria-label="Toggle selection overlay">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
<button class="ge-btn ge-btn-sm" id="ge-lasso-clear" title="Clear selection" aria-label="Clear selection">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-invert" title="Invert selection (Ctrl+Alt+Shift+I)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>Invert</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-delete" title="Erase selected pixels"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4a2 2 0 0 1 0-3l9-9a2 2 0 0 1 3 0l4 4a2 2 0 0 1 0 3l-9 9a2 2 0 0 1-3 0Z"/><path d="M22 21H7"/></svg>Erase</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-copy" title="Copy selection to a new layer"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>Copy Layer</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-mask" title="Add selection to mask"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="5"/></svg>To Mask</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" stroke-dasharray="3 3"/><circle cx="12" cy="12" r="3.5"/></svg>Quick Mask</button>
</div>
<div class="ge-control-row ge-eraser-row ge-sel-refine" id="ge-lasso-refine-grow" style="display:none;">
<span class="ge-eraser-preview" id="ge-lasso-grow-preview" aria-hidden="true"></span>
<label>Edge stroke <span id="ge-lasso-grow-label">0px</span></label>
<input type="range" id="ge-lasso-grow" min="-40" max="40" value="0" title="Expand (+) or contract (−) the selection before baking." />
</div>
<div class="ge-control-row ge-actions" style="margin-top:4px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-invert" title="Invert selection (Ctrl+Alt+Shift+I)">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
Invert
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-delete" title="Delete selected pixels from the layer">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
Delete
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-copy" title="Copy selection to new layer">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
Copy Layer
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-lasso-mask" title="Convert selection to inpaint mask">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>
To Mask
</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false">Quick Mask</button>
</div>
<p style="font-size:9px;opacity:0.4;margin:4px 0 0;">Draw a freehand selection. Esc to cancel.</p>
</div>
<div class="ge-wand-section" id="ge-wand-section" style="display:none;">
<div class="ge-control-row" style="display:flex;gap:4px;margin-bottom:4px;" title="How the next click combines with the current selection. Shift / Alt held during a click override this for one click.">
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn active" data-wand-mode="replace" title="Replace selection on each click">New</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection (Shift)">+ Add</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection (Alt)">− Subtract</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection">∩</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection (Shift)">+</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection (Alt)">−</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg></button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-live-btn" id="ge-wand-live" title="Retune selection while dragging tolerance" aria-pressed="false">Live</button>
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-wand-tol-preview" aria-hidden="true"></span>
<label>Tolerance <span id="ge-wand-tol-label">${wandTolerance}</span></label>
<button type="button" class="ge-btn ge-btn-sm ge-wand-live-btn" id="ge-wand-live" title="Retune selection while dragging tolerance" aria-pressed="false">Live</button>
<input type="range" id="ge-wand-tolerance" min="0" max="100" value="${wandTolerance}" />
</div>
<div class="ge-control-row ge-eraser-row ge-sel-refine" id="ge-wand-refine-feather" style="display:none;">
@@ -288,41 +477,38 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
<label>Edge stroke <span id="ge-wand-grow-label">0px</span></label>
<input type="range" id="ge-wand-grow" min="-40" max="40" value="0" title="Expand (+) or contract (−) the selection before baking." />
</div>
<div class="ge-control-row ge-actions" style="margin-top:4px;flex-wrap:wrap;">
<div class="ge-control-row ge-actions" style="margin-top:2px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-mask-vis-btn visible" id="ge-wand-vis" title="Hide selection overlay" aria-label="Toggle selection overlay">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-clear" title="Clear the selection">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
Clear
<button class="ge-btn ge-btn-sm" id="ge-wand-clear" title="Clear selection" aria-label="Clear selection">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-invert" title="Invert selection (Ctrl+Alt+Shift+I)">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>
Invert
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-delete" title="Delete selected pixels from the layer">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-delete" title="Erase selected pixels">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4a2 2 0 0 1 0-3l9-9a2 2 0 0 1 3 0l4 4a2 2 0 0 1 0 3l-9 9a2 2 0 0 1-3 0Z"/><path d="M22 21H7"/></svg>
Erase
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-copy" title="Copy selection to a new layer">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
Copy Layer
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-mask" title="Add selection to the inpaint mask">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-wand-mask" title="Add selection to mask">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="5"/></svg>
To Mask
</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false">Quick Mask</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" stroke-dasharray="3 3"/><circle cx="12" cy="12" r="3.5"/></svg>Quick Mask</button>
</div>
<p style="font-size:9px;opacity:0.4;margin:4px 0 0;">Click a region to select similar pixels. Shift+click to add, Alt+click to subtract. Esc to clear.</p>
</div>
<div class="ge-sam-section" id="ge-sam-section" style="display:none;">
<div class="ge-section-title ge-section-title-with-help"><span>SAM</span><span class="ge-section-help" tabindex="0" role="img" aria-label="SAM selection help" title="Click an object for visual SAM selection, or type a neutral object label and use Find. The text is only used to locate a region before SAM creates the mask.">?</span></div>
<div class="ge-control-row" style="display:flex;gap:4px;margin-bottom:4px;" title="How the next SAM selection combines with the current selection. Shift / Alt held during a click override this for one click.">
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn active" data-wand-mode="replace" title="Replace selection">New</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection">+ Add</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection">− Subtract</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection">∩</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection">+</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection">−</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg></button>
</div>
<div class="ge-control-row" style="display:flex;gap:6px;align-items:center;min-width:0;">
<input type="text" class="ge-inpaint-prompt" id="ge-sam-query" placeholder="Object to select..." style="flex:1 1 auto;min-width:0;" />
@@ -331,21 +517,120 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
Find
</button>
</div>
<div class="ge-control-row ge-actions" style="margin-top:4px;flex-wrap:wrap;">
<span class="ge-wand-more-wrap">
<button type="button" class="ge-btn ge-btn-sm ge-wand-more-btn" id="ge-sam-more" aria-haspopup="true" aria-expanded="false" aria-label="More SAM options (help)" title="More SAM options (help)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></button>
<div class="ge-wand-more-menu" id="ge-sam-more-menu" hidden>
<p class="ge-wand-tip">Click an object for visual SAM selection, or type a neutral object label and use Find. The text is only used to locate a region before SAM creates the mask. Shift adds, Alt subtracts, Esc clears.</p>
</div>
</span>
<div class="ge-control-row ge-actions" style="margin-top:2px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-mask-vis-btn visible" id="ge-sam-vis" title="Hide selection overlay" aria-label="Toggle selection overlay">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-sam-clear" title="Clear the selection">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
Clear
<button class="ge-btn ge-btn-sm" id="ge-sam-clear" title="Clear selection" aria-label="Clear selection">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-sam-mask" title="Add selection to the inpaint mask">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-sam-invert" title="Invert selection (Ctrl+Alt+Shift+I)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>
Invert
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-sam-delete" title="Erase selected pixels">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4a2 2 0 0 1 0-3l9-9a2 2 0 0 1 3 0l4 4a2 2 0 0 1 0 3l-9 9a2 2 0 0 1-3 0Z"/><path d="M22 21H7"/></svg>
Erase
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-sam-copy" title="Copy selection to a new layer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
Copy Layer
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-sam-mask" title="Add selection to mask">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="5"/></svg>
To Mask
</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false">Quick Mask</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" stroke-dasharray="3 3"/><circle cx="12" cy="12" r="3.5"/></svg>Quick Mask</button>
</div>
</div>
<div class="ge-quickselect-section" id="ge-quickselect-section" style="display:none;">
<div class="ge-control-row" style="display:flex;gap:4px;margin-bottom:4px;" title="How the brush combines with the current selection. Shift / Alt held during a stroke override this.">
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn active" data-wand-mode="replace" title="Replace selection">New</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection">+</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection">−</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg></button>
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-quickselect-size-preview" aria-hidden="true"></span>
<label>Brush <span id="ge-quickselect-size-label">24</span></label>
<input type="range" class="ge-quickselect-size" id="ge-quickselect-size" min="4" max="200" value="24" />
</div>
<span class="ge-wand-more-wrap">
<button type="button" class="ge-btn ge-btn-sm ge-wand-more-btn" id="ge-quickselect-more" aria-haspopup="true" aria-expanded="false" aria-label="More Quick Select options (help)" title="More Quick Select options (help)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></button>
<div class="ge-wand-more-menu" id="ge-quickselect-more-menu" hidden>
<p class="ge-wand-tip">Paint over a region; the brush grows the selection to similar nearby pixels. Shift adds, Alt subtracts, Shift+Alt intersects.</p>
</div>
</span>
<div class="ge-control-row ge-actions" style="margin-top:2px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-mask-vis-btn visible" id="ge-quickselect-vis" title="Hide selection overlay" aria-label="Toggle selection overlay">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
<button class="ge-btn ge-btn-sm" id="ge-quickselect-clear" title="Clear selection" aria-label="Clear selection">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-quickselect-invert" title="Invert selection (Ctrl+Alt+Shift+I)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>
Invert
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-quickselect-delete" title="Erase selected pixels">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4a2 2 0 0 1 0-3l9-9a2 2 0 0 1 3 0l4 4a2 2 0 0 1 0 3l-9 9a2 2 0 0 1-3 0Z"/><path d="M22 21H7"/></svg>
Erase
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-quickselect-copy" title="Copy selection to a new layer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
Copy Layer
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-quickselect-mask" title="Add selection to mask">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="5"/></svg>
To Mask
</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" stroke-dasharray="3 3"/><circle cx="12" cy="12" r="3.5"/></svg>Quick Mask</button>
</div>
</div>
<div class="ge-objectselect-section" id="ge-objectselect-section" style="display:none;">
<div class="ge-control-row" style="display:flex;gap:4px;margin-bottom:4px;" title="How the object selection combines with the current selection. Shift / Alt held during a stroke override this.">
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn active" data-wand-mode="replace" title="Replace selection">New</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="add" title="Add to selection">+</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="subtract" title="Subtract from selection">−</button>
<button type="button" class="ge-btn ge-btn-sm ge-wand-mode-btn" data-wand-mode="intersect" title="Intersect selection"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg></button>
</div>
<span class="ge-wand-more-wrap">
<button type="button" class="ge-btn ge-btn-sm ge-wand-more-btn" id="ge-objectselect-more" aria-haspopup="true" aria-expanded="false" aria-label="More Object Select options (help)" title="More Object Select options (help)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></button>
<div class="ge-wand-more-menu" id="ge-objectselect-more-menu" hidden>
<p class="ge-wand-tip">Draw over an object; the SAM model selects the whole object. Hold Alt to mark pixels to exclude. Shift adds, Esc clears.</p>
</div>
</span>
<div class="ge-control-row ge-actions" style="margin-top:2px;flex-wrap:wrap;">
<button class="ge-btn ge-btn-sm ge-mask-vis-btn visible" id="ge-objectselect-vis" title="Hide selection overlay" aria-label="Toggle selection overlay">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
<button class="ge-btn ge-btn-sm" id="ge-objectselect-clear" title="Clear selection" aria-label="Clear selection">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-objectselect-invert" title="Invert selection (Ctrl+Alt+Shift+I)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>
Invert
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-objectselect-delete" title="Erase selected pixels">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4a2 2 0 0 1 0-3l9-9a2 2 0 0 1 3 0l4 4a2 2 0 0 1 0 3l-9 9a2 2 0 0 1-3 0Z"/><path d="M22 21H7"/></svg>
Erase
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-objectselect-copy" title="Copy selection to a new layer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
Copy Layer
</button>
<button class="ge-btn ge-btn-sm ge-btn-iconlabel" id="ge-objectselect-mask" title="Add selection to mask">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="5"/></svg>
To Mask
</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-iconlabel ge-quick-mask-toggle" title="Edit selection as Quick Mask (Q)" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" stroke-dasharray="3 3"/><circle cx="12" cy="12" r="3.5"/></svg>Quick Mask</button>
</div>
<p style="font-size:9px;opacity:0.4;margin:4px 0 0;">Click an object, or type a neutral object label. Shift adds, Alt subtracts.</p>
</div>
<div class="ge-inpaint-section" id="ge-inpaint-section" style="display:none;">
<div class="ge-inpaint-popover-head" data-inpaint-drag>
@@ -448,72 +733,19 @@ export function controlsHTML({ color, brushSize, wandTolerance }) {
</p>
<div class="ge-clone-source-status" id="ge-clone-source-status" aria-live="polite">
<span id="ge-clone-source-label">No source selected</span>
<button type="button" class="ge-btn ge-btn-sm ge-icon-btn" id="ge-clone-source-clear" title="Clear sampled source" aria-label="Clear sampled source">×</button>
<button type="button" class="ge-btn ge-btn-sm" id="ge-clone-source-clear" title="Clear sampled source" aria-label="Clear sampled source">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>
</button>
</div>
<div class="ge-control-row">
<label for="ge-clone-sample-mode">Sample</label>
<select id="ge-clone-sample-mode">
<select id="ge-clone-sample-mode" class="ge-ctl-select">
<option value="active-layer">Active layer</option>
<option value="composite">All visible layers</option>
</select>
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-clone-preview-opacity" aria-hidden="true"></span>
<label>Opacity <span id="ge-clone-opacity-label">100%</span></label>
<input type="range" id="ge-clone-opacity" min="10" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-clone-preview-flow" aria-hidden="true"></span>
<label>Flow <span id="ge-clone-flow-label">100%</span></label>
<input type="range" id="ge-clone-flow" min="5" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-clone-preview-softness" aria-hidden="true"></span>
<label>Softness <span id="ge-clone-softness-label">100%</span></label>
<input type="range" id="ge-clone-softness" min="0" max="300" value="100" title="Soft brush edge — blurs each stamp for a feathered fade." />
</div>
</div>
<div class="ge-eraser-section" id="ge-brush-section" style="display:none;">
<div class="ge-section-title"><span>Brush</span></div>
<div class="ge-control-row ge-eraser-row" id="ge-smudge-strength-row" style="display:none;">
<span class="ge-eraser-preview" id="ge-smudge-preview-strength" aria-hidden="true"></span>
<label>Strength <span id="ge-smudge-strength-label">65%</span></label>
<input type="range" id="ge-smudge-strength" min="5" max="100" value="65" title="How strongly Smudge carries sampled pixels into the stroke." />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-brush-preview-opacity" aria-hidden="true"></span>
<label>Opacity <span id="ge-brush-opacity-label">100%</span></label>
<input type="range" id="ge-brush-opacity" min="10" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-brush-preview-flow" aria-hidden="true"></span>
<label>Flow <span id="ge-brush-flow-label">100%</span></label>
<input type="range" id="ge-brush-flow" min="5" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-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 class="ge-eraser-section" id="ge-eraser-section" style="display:none;">
<div class="ge-section-title">Eraser</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-eraser-preview-opacity" aria-hidden="true"></span>
<label>Opacity <span id="ge-eraser-opacity-label">100%</span></label>
<input type="range" id="ge-eraser-opacity" min="10" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-eraser-preview-flow" aria-hidden="true"></span>
<label>Flow <span id="ge-eraser-flow-label">100%</span></label>
<input type="range" id="ge-eraser-flow" min="5" max="100" value="100" />
</div>
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-eraser-preview-softness" aria-hidden="true"></span>
<label>Softness <span id="ge-eraser-softness-label">100%</span></label>
<input type="range" id="ge-eraser-softness" min="0" max="300" value="100" title="Soft brush edge — blurs the stroke's alpha so the eraser fades out at the perimeter." />
</div>
</div>
<div class="ge-transform-section" id="ge-transform-section" style="display:none;"></div>
<div class="ge-sharpen-section" id="ge-sharpen-section" style="display:none;">
<div class="ge-control-row ge-eraser-row">
<span class="ge-eraser-preview" id="ge-sharpen-preview" aria-hidden="true"></span>
@@ -619,27 +851,6 @@ export function layerPanelHTML() {
return `<div class="ge-layers-header">
<span class="ge-layers-grab"></span>
<span class="ge-layers-title">Layers</span>
<div class="ge-layer-header-tools" role="group" aria-label="Layer actions">
<button type="button" class="ge-btn ge-btn-sm ge-icon-btn" id="ge-add-layer" title="New layer" aria-label="New layer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-merge-down" title="Merge down" aria-label="Merge down">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="6 13 12 19 18 13"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-merge-all" title="Merge all" aria-label="Merge all">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v6M9 6l3-3 3 3M3 14h18M12 14v7M9 18l3 3 3-3"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-flatten" title="Flatten copy (keeps originals)" aria-label="Flatten copy">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2 L4 6 L4 18 L12 22 L20 18 L20 6 Z"/><path d="M12 2 L12 22"/><path d="M4 6 L20 6"/><path d="M4 18 L20 18"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-select-all-layers" title="Select all layers" aria-label="Select all layers">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="7" width="13" height="13" rx="1"/><path d="M4 16H3V3h13v1"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-group-selected" title="Group selected layers" aria-label="Group selected layers">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h7l2 2h9v10H3z"/></svg>
</button>
<button class="ge-btn ge-btn-sm" id="ge-layer-fill" title="Fill selected layer or selection with foreground color (Alt+Backspace)">Fill</button>
</div>
</div>
<div class="ge-layer-blend-row">
<label for="ge-layer-blend">Blend</label>
@@ -660,7 +871,21 @@ export function layerPanelHTML() {
<option value="saturation">Saturation</option>
<option value="color">Color</option>
<option value="luminosity">Luminosity</option>
<option value="dissolve">Dissolve</option>
<option value="linear-burn">Linear Burn</option>
<option value="linear-dodge">Linear Dodge (Add)</option>
<option value="darker-color">Darker Color</option>
<option value="lighter-color">Lighter Color</option>
<option value="vivid-light">Vivid Light</option>
<option value="linear-light">Linear Light</option>
<option value="pin-light">Pin Light</option>
<option value="hard-mix">Hard Mix</option>
<option value="subtract">Subtract</option>
<option value="divide">Divide</option>
</select>
<label class="ge-layer-opacity-head" for="ge-layer-header-opacity" title="Active layer opacity">Opacity
<input type="number" id="ge-layer-header-opacity" min="0" max="100" step="1" value="100" />
</label>
</div>
<div class="ge-layer-selection-bar" id="ge-layer-selection-bar" hidden>
<span id="ge-layer-selection-count">2 layers</span>
@@ -676,5 +901,31 @@ export function layerPanelHTML() {
<button class="ge-icon-btn danger" id="ge-selected-delete" title="Delete selected layers" aria-label="Delete selected layers">×</button>
</div>
<div class="ge-layers-list" id="ge-layers-list"></div>
<div class="ge-layer-tools" id="ge-layer-tools" aria-label="Selected layer tools"></div>`;
<div class="ge-layers-footer">
<div class="ge-layer-header-tools" role="group" aria-label="Layer actions">
<button type="button" class="ge-btn ge-btn-sm ge-icon-btn" id="ge-add-layer" title="New layer" aria-label="New layer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
</button>
<button type="button" class="ge-btn ge-btn-sm ge-icon-btn ge-add-fx" id="ge-add-fx" title="New adjustment (fx) layer" aria-label="New adjustment layer">
<span class="ge-add-fx-glyph" aria-hidden="true">fx</span>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-merge-down" title="Merge down" aria-label="Merge down">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="6 13 12 19 18 13"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-merge-all" title="Merge all" aria-label="Merge all">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v6M9 6l3-3 3 3M3 14h18M12 14v7M9 18l3 3 3-3"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-flatten" title="Flatten copy (keeps originals)" aria-label="Flatten copy">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2 L4 6 L4 18 L12 22 L20 18 L20 6 Z"/><path d="M12 2 L12 22"/><path d="M4 6 L20 6"/><path d="M4 18 L20 18"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-select-all-layers" title="Select all layers" aria-label="Select all layers">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="7" width="13" height="13" rx="1"/><path d="M4 16H3V3h13v1"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-icon-btn" id="ge-group-selected" title="Group selected layers" aria-label="Group selected layers">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h7l2 2h9v10H3z"/></svg>
</button>
<button class="ge-btn ge-btn-sm" id="ge-layer-fill" title="Fill selected layer or selection with foreground color (Alt+Backspace)">Fill</button>
</div>
<div class="ge-layer-tools" id="ge-layer-tools" aria-label="Selected layer tools"></div>
</div>`;
}
+551
View File
@@ -0,0 +1,551 @@
/**
* Docked panel stack (PhotoCraft-parity phase 0/3).
*
* Wraps a list of existing panel elements into a Photoshop-style dock:
* several panel GROUPS are visible at once, stacked vertically. Each
* group has clickable tabs (one panel visible per group), a collapse
* control that shrinks it to its tab strip, and a drag divider so the
* user can resize the group above.
*
* Purely presentational: it never owns editor state. Each entry is an
* element that already exists elsewhere (so all existing ids, classes
* and event listeners keep working). Switching a tab only toggles the
* `hidden` attribute on the panel wrapper.
*
* A compact `<select>` variant (`compact: true`) is kept as a fallback
* for narrow columns where a multi-group stack will not fit.
*
* @param {{
* entries: Array<{id: string, label: string, element: HTMLElement, group?: string}>,
* persistKey?: string,
* defaultId?: string,
* compact?: boolean,
* }} opts
* @returns {{ dock: HTMLDivElement, show: (id: string) => void, readonly activeId: string|null }}
*/
export function buildDock({ entries = [], persistKey = 'ge-dock-active', defaultId = null, compact = false, onCloseGroup = null } = {}) {
const dock = document.createElement('div');
dock.className = 'ge-dock';
if (compact) dock.classList.add('ge-dock--compact');
// Collect entries into ordered groups (Photoshop panel groups).
const groups = [];
entries.forEach(entry => {
const name = entry.group || 'Panels';
let group = groups.find(g => g.name === name);
if (!group) {
group = { name, entries: [], size: entry.groupSize || null, collapsed: !!entry.groupCollapsed };
groups.push(group);
}
group.entries.push(entry);
});
const groupOfId = new Map();
groups.forEach(group => group.entries.forEach(e => groupOfId.set(e.id, group)));
let saved = {};
try { saved = JSON.parse(localStorage.getItem(persistKey) || '{}') || {}; } catch {}
const activeByGroup = new Map();
groups.forEach(group => {
const fallback = group.entries[0]?.id || null;
const savedId = saved[group.name];
const pick = (savedId && group.entries.some(e => e.id === savedId)) ? savedId
: (defaultId && group.entries.some(e => e.id === defaultId)) ? defaultId
: fallback;
activeByGroup.set(group.name, pick);
});
let activeId = null;
const persist = () => {
const out = {};
activeByGroup.forEach((v, k) => { if (v) out[k] = v; });
try { localStorage.setItem(persistKey, JSON.stringify(out)); } catch {}
};
const groupEls = new Map();
const detachPlacers = new Map();
const activateInGroup = (group, id) => {
activeByGroup.set(group.name, id);
activeId = id;
groupEls.get(group.name)?.querySelectorAll('.ge-dock-tab').forEach(tab => {
const on = tab.dataset.panel === id;
tab.classList.toggle('active', on);
tab.setAttribute('aria-selected', String(on));
});
group.entries.forEach(entry => {
const panel = groupEls.get(group.name)?.querySelector(`.ge-dock-panel[data-panel="${entry.id}"]`);
if (panel) panel.hidden = entry.id !== id;
});
// Keep the group's undock control anchored beside the active tab.
detachPlacers.get(group.name)?.();
persist();
};
function show(id) {
const group = groupOfId.get(id);
if (!group) return;
groupEls.get(group.name)?.classList.remove('is-collapsed');
activateInGroup(group, id);
}
// A dock tab plus a small "undock" control (Photoshop lets you tear a single
// panel tab out of its group). Used both for the initial build and when a
// floated panel is re-docked.
function makeTabItem(group, entry, groupEl) {
const item = document.createElement('div');
item.className = 'ge-dock-tab-item';
item.dataset.panel = entry.id;
const tab = document.createElement('button');
tab.type = 'button';
tab.className = 'ge-dock-tab';
tab.dataset.panel = entry.id;
tab.textContent = entry.label;
tab.setAttribute('role', 'tab');
tab.setAttribute('aria-selected', 'false');
tab.title = entry.label;
tab.addEventListener('click', () => {
groupEl.classList.remove('is-collapsed');
activateInGroup(group, entry.id);
});
item.appendChild(tab);
return item;
}
// Float a single panel into its own draggable window (Photoshop undock-tab).
function floatPanel(group, entry) {
const groupEl = groupEls.get(group.name);
if (!groupEl) return;
const panelEl = groupEl.querySelector(`.ge-dock-panel[data-panel="${entry.id}"]`);
if (!panelEl || panelEl.closest('.ge-float-window')) return;
const win = document.createElement('div');
win.className = 'ge-float-window';
win.innerHTML = `
<div class="ge-float-head">
<span class="ge-float-title">${entry.label}</span>
<span class="ge-float-btns">
<button class="ge-float-dock" type="button" title="Dock panel" aria-label="Dock panel">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>
</button>
</span>
</div>
<div class="ge-float-body"></div>`;
win.querySelector('.ge-float-body').appendChild(panelEl);
panelEl.hidden = false;
document.body.appendChild(win);
const r = groupEl.getBoundingClientRect();
win.style.left = `${Math.max(8, Math.min(window.innerWidth - 240, r.left - 260))}px`;
win.style.top = `${Math.max(8, r.top)}px`;
makeFloatDraggable(win, win.querySelector('.ge-float-head'));
const tabsEl = groupEl.querySelector('.ge-dock-tabs');
const itemEl = tabsEl?.querySelector(`.ge-dock-tab-item[data-panel="${entry.id}"]`);
itemEl?.remove();
const wasActive = activeId === entry.id;
win.querySelector('.ge-float-dock').addEventListener('click', () => {
const bodyEl = groupEl.querySelector('.ge-dock-panels');
if (bodyEl) bodyEl.appendChild(panelEl); else groupEl.appendChild(panelEl);
panelEl.hidden = activeId !== entry.id;
win.remove();
if (tabsEl) tabsEl.appendChild(makeTabItem(group, entry, groupEl));
if (wasActive) activateInGroup(group, entry.id);
detachPlacers.get(group.name)?.();
syncTabsOverflow(groupEl);
});
if (wasActive) {
const next = group.entries.find(e => {
const p = groupEl.querySelector(`.ge-dock-panel[data-panel="${e.id}"]`);
return p && !p.closest('.ge-float-window');
});
if (next) activateInGroup(group, next.id);
}
syncTabsOverflow(groupEl);
}
if (compact) {
const tabbar = document.createElement('div');
tabbar.className = 'ge-dock-tabbar';
const select = document.createElement('select');
select.className = 'ge-dock-select';
select.setAttribute('aria-label', 'Editor panel');
const optgroups = new Map();
entries.forEach(({ id, label, group }) => {
const option = document.createElement('option');
option.value = id;
option.textContent = label;
if (group) {
let optgroup = optgroups.get(group);
if (!optgroup) {
optgroup = document.createElement('optgroup');
optgroup.label = group;
optgroups.set(group, optgroup);
select.appendChild(optgroup);
}
optgroup.appendChild(option);
} else {
select.appendChild(option);
}
});
tabbar.appendChild(select);
const panels = document.createElement('div');
panels.className = 'ge-dock-panels';
entries.forEach(({ id, element }) => {
const panel = document.createElement('div');
panel.className = 'ge-dock-panel';
panel.dataset.panel = id;
if (element) panel.appendChild(element);
panels.appendChild(panel);
});
dock.appendChild(tabbar);
dock.appendChild(panels);
const applyFlat = (id) => {
activeId = id;
panels.querySelectorAll('.ge-dock-panel').forEach(p => { p.hidden = p.dataset.panel !== id; });
const group = groupOfId.get(id);
if (group) activeByGroup.set(group.name, id);
persist();
};
select.addEventListener('change', () => applyFlat(select.value));
const initial = defaultId || entries[0]?.id || null;
if (initial) { select.value = initial; applyFlat(initial); }
return { dock, show, get activeId() { return activeId; } };
}
// Stacked mode: one `.ge-dock-group` per panel group, with a drag
// divider between groups (skip a leading divider).
groups.forEach((group, groupIndex) => {
if (groupIndex > 0) {
const divider = document.createElement('div');
divider.className = 'ge-dock-divider';
divider.setAttribute('role', 'separator');
divider.setAttribute('aria-orientation', 'horizontal');
divider.title = 'Drag to resize · double-click to expand/collapse a panel group';
dock.appendChild(divider);
wireDivider(divider, groupIndex);
}
const groupEl = document.createElement('div');
groupEl.className = 'ge-dock-group';
groupEl.dataset.group = group.name;
if (group.size) {
groupEl.style.flex = `0 0 ${group.size}px`;
groupEl.style.height = `${group.size}px`;
}
if (group.collapsed) groupEl.classList.add('is-collapsed');
const head = document.createElement('div');
head.className = 'ge-dock-group-head';
const tabs = document.createElement('div');
tabs.className = 'ge-dock-tabs';
tabs.setAttribute('role', 'tablist');
group.entries.forEach(entry => {
tabs.appendChild(makeTabItem(group, entry, groupEl));
});
const collapse = document.createElement('button');
collapse.type = 'button';
collapse.className = 'ge-dock-collapse';
collapse.title = 'Collapse panel group';
collapse.setAttribute('aria-label', 'Collapse panel group');
collapse.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>';
collapse.addEventListener('click', () => {
const collapsed = groupEl.classList.toggle('is-collapsed');
collapse.title = collapsed ? 'Expand panel group' : 'Collapse panel group';
collapse.setAttribute('aria-label', collapse.title);
});
// Overflow affordance: when a group's tabs do not fit the column,
// show a chevron that opens a menu of every tab so none become
// unreachable or unreadable (Photoshop-style tab overflow).
const tabsMore = document.createElement('button');
tabsMore.type = 'button';
tabsMore.className = 'ge-dock-tabs-more';
tabsMore.title = 'More panels';
tabsMore.setAttribute('aria-label', 'More panels');
tabsMore.hidden = true;
tabsMore.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="12" r="1.9"/><circle cx="12" cy="12" r="1.9"/><circle cx="18" cy="12" r="1.9"/></svg>';
tabsMore.addEventListener('click', (e) => {
e.stopPropagation();
openTabsMenu(tabsMore, group, groupEl);
});
head.appendChild(tabs);
head.appendChild(tabsMore);
head.appendChild(collapse);
const body = document.createElement('div');
body.className = 'ge-dock-panels';
group.entries.forEach(entry => {
const panel = document.createElement('div');
panel.className = 'ge-dock-panel';
panel.dataset.panel = entry.id;
if (entry.element) panel.appendChild(entry.element);
body.appendChild(panel);
});
groupEl.appendChild(head);
groupEl.appendChild(body);
dock.appendChild(groupEl);
groupEls.set(group.name, groupEl);
syncTabsOverflow(groupEl);
});
// Re-evaluate tab overflow whenever the column width changes, and keep any
// torn-off (floating) panels on-screen after a viewport resize so they never
// drift off the edge or vanish.
window.addEventListener('resize', () => {
groupEls.forEach(el => syncTabsOverflow(el));
document.querySelectorAll('.ge-float-window').forEach((w) => {
const r = w.getBoundingClientRect();
const maxL = Math.max(8, window.innerWidth - r.width - 8);
const maxT = Math.max(8, window.innerHeight - 48);
w.style.left = Math.min(Math.max(8, r.left), maxL) + 'px';
w.style.top = Math.min(Math.max(8, r.top), maxT) + 'px';
});
});
// The dock is built before it is attached to the DOM (so its width is 0 at
// build time and the overflow check above cannot see the real column width).
// Observe size changes to recompute overflow once it is laid out and whenever
// the panel is resized, collapsed or expanded — otherwise a tab strip that
// overflows keeps the chevron hidden and clips its trailing labels.
if (typeof ResizeObserver !== 'undefined') {
const ro = new ResizeObserver(() => groupEls.forEach(el => syncTabsOverflow(el)));
ro.observe(dock);
}
requestAnimationFrame(() => groupEls.forEach(el => syncTabsOverflow(el)));
function syncTabsOverflow(groupEl) {
const tabsEl = groupEl.querySelector('.ge-dock-tabs');
const moreEl = groupEl.querySelector('.ge-dock-tabs-more');
if (!tabsEl || !moreEl) return;
const items = Array.from(tabsEl.querySelectorAll('.ge-dock-tab-item'));
// Reset any previous hiding so widths are measured at their natural size.
items.forEach(item => { item.style.display = ''; });
const overflowing = tabsEl.scrollWidth - tabsEl.clientWidth > 1;
// Keep the menu reachable even when the tabs fit, so its "Close <group>"
// action (and every tab) stays available for every section.
moreEl.hidden = !(overflowing || typeof onCloseGroup === 'function');
if (!overflowing) return;
// Photoshop-style tab overflow: rather than clipping a label mid-word
// ("PATTERNS" -> "P…", "CHARACTER" -> "CHARA"), keep only the tabs that
// fit whole and let the chevron expose the rest. The active tab is always
// kept visible so the current panel never loses its anchor.
const active = tabsEl.querySelector('.ge-dock-tab.active');
const activeItem = active ? active.closest('.ge-dock-tab-item') : null;
const limit = tabsEl.clientWidth;
let gap = 0;
try { gap = parseFloat(getComputedStyle(tabsEl).columnGap) || 0; } catch {}
// Keep the leading run of tabs that fits, then tuck the trailing tabs
// (and everything after the first that no longer fits) into the chevron.
// The active tab is always kept visible so the current panel stays anchored.
let used = 0;
let cutting = false;
items.forEach(item => {
const w = item.getBoundingClientRect().width;
if (item === activeItem || (!cutting && used + w <= limit + 0.5)) {
used += w + gap;
} else {
cutting = true;
item.style.display = 'none';
}
});
}
let tabsMenu = null;
function closeTabsMenu() {
if (!tabsMenu) return;
tabsMenu.remove();
tabsMenu = null;
document.removeEventListener('pointerdown', onTabsMenuDocDown, true);
}
function onTabsMenuDocDown(e) {
if (tabsMenu && !tabsMenu.contains(e.target) && !e.target.closest?.('.ge-dock-tabs-more')) closeTabsMenu();
}
function openTabsMenu(anchor, group, groupEl) {
closeTabsMenu();
tabsMenu = document.createElement('div');
tabsMenu.className = 'ge-dock-tabs-menu';
group.entries.forEach(entry => {
const item = document.createElement('button');
item.type = 'button';
item.className = 'ge-dock-tabs-menu-item';
item.textContent = entry.label;
item.addEventListener('click', () => {
groupEl.classList.remove('is-collapsed');
activateInGroup(group, entry.id);
syncTabsOverflow(groupEl);
closeTabsMenu();
});
tabsMenu.appendChild(item);
});
// Close the whole section (panel group) from the same menu — Photoshop's
// "Close Tab Group". Only offered when the host supplies a handler.
if (typeof onCloseGroup === 'function') {
const sep = document.createElement('div');
sep.className = 'ge-dock-tabs-menu-sep';
tabsMenu.appendChild(sep);
const closeItem = document.createElement('button');
closeItem.type = 'button';
closeItem.className = 'ge-dock-tabs-menu-item ge-dock-tabs-menu-close';
closeItem.textContent = `Close ${group.name}`;
closeItem.addEventListener('click', () => {
closeTabsMenu();
try { onCloseGroup(group.name); } catch (_) {}
});
tabsMenu.appendChild(closeItem);
}
document.body.appendChild(tabsMenu);
const r = anchor.getBoundingClientRect();
tabsMenu.style.left = `${Math.max(4, Math.min(window.innerWidth - 160, r.left))}px`;
tabsMenu.style.top = `${r.bottom + 2}px`;
document.addEventListener('pointerdown', onTabsMenuDocDown, true);
}
function wireDivider(divider, groupIndex) {
const groupEl = () => dock.querySelectorAll('.ge-dock-group')[groupIndex - 1];
let startY = 0;
let startH = 0;
let resizing = false;
let moved = false;
divider.addEventListener('pointerdown', (event) => {
const target = groupEl();
if (!target) return;
resizing = true;
moved = false;
startY = event.clientY;
startH = target.getBoundingClientRect().height;
divider.setPointerCapture(event.pointerId);
document.body.style.cursor = 'ns-resize';
event.preventDefault();
});
divider.addEventListener('pointermove', (event) => {
if (!resizing) return;
const target = groupEl();
if (!target) return;
// A real drag supersedes any double-click expand state (a plain click,
// which a double-click fires, must not, or the toggle would never fire).
if (!moved) { moved = true; target.dataset.dockExpanded = '0'; target.classList.remove('is-expanded'); }
const next = Math.max(28, startH + (event.clientY - startY));
// Fixed basis (no grow/shrink): a `1 1` basis lets the height-constrained
// dock shrink the dragged group straight back to 0, so the divider looked
// dead. Keeping it `0 0` holds the size and lets the dock scroll instead.
target.style.flex = `0 0 ${Math.round(next)}px`;
target.style.height = `${Math.round(next)}px`;
});
const end = (event) => {
if (!resizing) return;
resizing = false;
document.body.style.cursor = '';
try { divider.releasePointerCapture?.(event.pointerId); } catch {}
};
divider.addEventListener('pointerup', end);
divider.addEventListener('pointercancel', end);
// Double-click toggles the group above between "show everything" and the
// previous size. Handy on a cramped sidebar: one double-click unrolls the
// whole group (its body is normally height-clamped and scrolls), another
// restores exactly what it was.
divider.addEventListener('dblclick', (event) => {
event.preventDefault();
const target = groupEl();
if (!target) return;
const body = target.querySelector('.ge-dock-panels');
if (target.dataset.dockExpanded === '1') {
const prev = parseFloat(target.dataset.dockPrevSize || '');
const restore = Number.isFinite(prev) && prev > 0 ? prev : 200;
target.style.flex = `0 0 ${Math.round(restore)}px`;
target.style.height = `${Math.round(restore)}px`;
target.dataset.dockExpanded = '0';
target.classList.remove('is-expanded');
return;
}
const head = target.querySelector('.ge-dock-tabs');
const headH = head ? head.getBoundingClientRect().height : 0;
const bodyH = body ? body.scrollHeight : 0;
const full = Math.ceil(headH + bodyH + 2);
target.dataset.dockPrevSize = String(Math.round(target.getBoundingClientRect().height));
target.classList.remove('is-collapsed');
target.style.flex = `0 0 ${full}px`;
target.style.height = `${full}px`;
target.dataset.dockExpanded = '1';
target.classList.add('is-expanded');
});
}
// Move a panel group out of the dock into a floating, draggable
// window; the window offers a "Dock" control that returns the exact
// same `.ge-dock-group` node (DOM identity preserved) to its original
// position in the stack.
function detachGroup(group, groupEl, dockEl) {
if (groupEl.classList.contains('is-floating')) return;
const prevDivider = groupEl.previousElementSibling;
const hadDivider = !!prevDivider && prevDivider.classList.contains('ge-dock-divider');
if (hadDivider) prevDivider.hidden = true;
const dockIndex = Array.from(dockEl.querySelectorAll('.ge-dock-group')).indexOf(groupEl);
groupEl.classList.add('is-floating');
const win = document.createElement('div');
win.className = 'ge-float-window';
win.dataset.group = group.name;
win.innerHTML = `
<div class="ge-float-head">
<span class="ge-float-title">${group.name}</span>
<span class="ge-float-btns">
<button class="ge-float-dock" type="button" title="Dock panel group" aria-label="Dock panel group">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>
</button>
</span>
</div>
<div class="ge-float-body"></div>`;
win.querySelector('.ge-float-body').appendChild(groupEl);
document.body.appendChild(win);
const r = groupEl.getBoundingClientRect();
win.style.left = `${Math.max(8, Math.min(window.innerWidth - 260, r.left - 60))}px`;
win.style.top = `${Math.max(8, r.top)}px`;
makeFloatDraggable(win, win.querySelector('.ge-float-head'));
win.querySelector('.ge-float-dock').addEventListener('click', () => {
const groupsNow = Array.from(dockEl.querySelectorAll('.ge-dock-group'));
const anchor = groupsNow[dockIndex] || null;
if (anchor) dockEl.insertBefore(groupEl, anchor); else dockEl.appendChild(groupEl);
if (hadDivider) prevDivider.hidden = false;
groupEl.classList.remove('is-floating');
win.remove();
});
}
function makeFloatDraggable(win, handle) {
if (!handle) return;
handle.style.touchAction = 'none';
handle.addEventListener('pointerdown', (e) => {
if (e.target.closest('button')) return;
e.preventDefault();
const startX = e.clientX, startY = e.clientY;
const r0 = win.getBoundingClientRect();
try { handle.setPointerCapture(e.pointerId); } catch {}
handle.style.cursor = 'grabbing';
const onMove = (ev) => {
win.style.left = `${Math.max(0, Math.min(window.innerWidth - 80, r0.left + (ev.clientX - startX)))}px`;
win.style.top = `${Math.max(0, Math.min(window.innerHeight - 30, r0.top + (ev.clientY - startY)))}px`;
};
const onUp = () => {
try { handle.releasePointerCapture(e.pointerId); } catch {}
handle.style.cursor = '';
handle.removeEventListener('pointermove', onMove);
handle.removeEventListener('pointerup', onUp);
};
handle.addEventListener('pointermove', onMove);
handle.addEventListener('pointerup', onUp);
});
}
groupEls.forEach((groupEl, name) => {
const group = groups.find(g => g.name === name);
const id = activeByGroup.get(name) || group?.entries[0]?.id;
if (id) activateInGroup(group, id);
});
return {
dock,
show,
get activeId() { return activeId; },
};
}
+274
View File
@@ -0,0 +1,274 @@
/**
* Contextual tool options bar — a Photoshop-style strip that sits
* directly under the topbar and shows quick controls for the active
* tool.
*
* This is a *mirror* of the authoritative controls in the right-hand
* panel: it never owns state. Every value is delegated to the existing
* input element (by selector) so the two views can never disagree —
* editing here re-dispatches the same `input`/`change` event the real
* control listens for, and the real control pushes updates back into
* the bar.
*
* On phones (<= 820px) the bar is hidden by CSS and the right-panel
* bottom sheet remains the single surface, exactly as before.
*/
import { TOOLS } from './toolbar.js?v=20261010brushpresets';
import { state } from '../state.js';
// Per-tool option sources. Each value is a CSS selector for an existing
// control inside the right panel; `null` means "no such control".
const BRUSH_TOOLS = {
brush: { size: '.ge-size-slider', opacity: '#ge-brush-opacity', flow: '#ge-brush-flow', softness: '#ge-brush-softness' },
smudge: { size: '.ge-size-slider', opacity: '#ge-brush-opacity', flow: '#ge-brush-flow', softness: '#ge-brush-softness' },
dodge: { size: '.ge-size-slider', opacity: '#ge-brush-opacity', flow: '#ge-brush-flow', softness: '#ge-brush-softness', intensity: '#ge-dodgeburn-intensity' },
burn: { size: '.ge-size-slider', opacity: '#ge-brush-opacity', flow: '#ge-brush-flow', softness: '#ge-brush-softness', intensity: '#ge-dodgeburn-intensity' },
eraser: { size: '.ge-size-slider', opacity: '#ge-eraser-opacity', flow: '#ge-eraser-flow', softness: '#ge-eraser-softness' },
clone: { size: '.ge-size-slider', opacity: '#ge-clone-opacity', flow: '#ge-clone-flow', softness: '#ge-clone-softness' },
heal: { size: '.ge-size-slider', opacity: '#ge-clone-opacity', flow: '#ge-clone-flow', softness: '#ge-clone-softness' },
};
const SELECTION_TOOLS = {
marquee: { modes: null, feather: null },
lasso: { modes: null, feather: '#ge-lasso-feather' },
wand: { modes: null, feather: '#ge-wand-feather' },
quickselect: { modes: null, feather: null },
objectselect: { modes: null, feather: null },
sam: { modes: null, feather: null },
};
// Liquify is not a brush: it exposes its own mode plus dab size and strength.
const LIQUIFY_TOOLS = {
liquify: { size: '#ge-liquify-size', strength: '#ge-liquify-strength' },
};
const INTERSECT_ICON = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="position:relative;top:2px"><circle cx="9" cy="12" r="6"/><circle cx="15" cy="12" r="6"/></svg>';
const MODE_LABELS = [['replace', 'New'], ['add', '+'], ['subtract', '−'], ['intersect', INTERSECT_ICON]];
function resolve(selector) {
if (!selector) return null;
return selector.startsWith('#')
? document.getElementById(selector.slice(1))
: document.querySelector(selector);
}
function makeRange(label, sourceSelector, { suffix = '' } = {}) {
const source = resolve(sourceSelector);
const value = source ? source.value : '0';
const min = source?.getAttribute('min') ?? '0';
const max = source?.getAttribute('max') ?? '100';
const step = source?.getAttribute('step') ?? '1';
return `
<div class="ge-opt" data-opt="range">
<label class="ge-opt-label">${label}<span class="ge-opt-value" data-opt-value>--</span></label>
<input type="range" data-opt-range data-src="${sourceSelector}" min="${min}" max="${max}" step="${step}" value="${value}" />
</div>`;
}
function makeSelect(label, sourceSelector) {
const source = resolve(sourceSelector);
const options = source
? [...source.options].map(o => `<option value="${o.value}">${o.textContent}</option>`).join('')
: '';
const value = source ? source.value : '';
return `
<div class="ge-opt" data-opt="select">
<label class="ge-opt-label">${label}</label>
<select data-opt-select data-src="${sourceSelector}">${options}</select>
</div>`;
}
function makeAutoSelect() {
return `
<label class="ge-opt ge-auto-select-option" data-opt="check">
<input type="checkbox" id="ge-auto-select-layer" class="ge-ctl-check" />
<span class="ge-opt-label">Auto-Select</span>
</label>
<div class="ge-opt" data-opt="select">
<label class="ge-opt-label" for="ge-auto-select-target">Target</label>
<select id="ge-auto-select-target">
<option value="layer">Layer</option>
<option value="group">Group</option>
</select>
</div>`;
}
function makeModes(sectionSelector) {
const buttons = MODE_LABELS.map(([mode, text]) =>
`<button type="button" class="ge-opt-mode" data-opt-mode="${mode}" data-section="${sectionSelector}">${text}</button>`
).join('');
return `<div class="ge-opt" data-opt="modes"><span class="ge-opt-label">Mode</span><span class="ge-opt-modes">${buttons}</span></div>`;
}
function buildToolControls(toolId) {
const parts = [];
if (BRUSH_TOOLS[toolId]) {
const src = BRUSH_TOOLS[toolId];
parts.push(makeRange('Size', src.size, { suffix: 'px' }));
parts.push(makeRange('Opacity', src.opacity));
parts.push(makeRange('Flow', src.flow));
parts.push(makeRange('Softness', src.softness));
if (src.intensity) parts.push(makeRange('Intensity', src.intensity));
} else if (SELECTION_TOOLS[toolId]) {
const src = SELECTION_TOOLS[toolId];
if (src.modes) parts.push(makeModes(src.modes));
if (src.feather) parts.push(makeRange('Feather', src.feather, { suffix: 'px' }));
} else if (LIQUIFY_TOOLS[toolId]) {
const src = LIQUIFY_TOOLS[toolId];
parts.push(makeSelect('Mode', '#ge-liquify-mode'));
parts.push(makeRange('Size', src.size, { suffix: 'px' }));
parts.push(makeRange('Strength', src.strength));
} else if (toolId === 'move') {
parts.push(makeAutoSelect());
}
if (!parts.length) {
return '';
}
return parts.join('');
}
function valueLabelOf(source, value) {
// Prefer the sibling label the right panel already maintains so the
// two surfaces always show the same formatted number.
const row = source?.closest?.('.ge-eraser-row, .ge-control-row');
const label = row?.querySelector('span[id$="-label"], span[id$="-opacity-label"], span[id$="-flow-label"], span[id$="-softness-label"]');
const text = label?.textContent?.trim();
return text || (typeof value === 'string' ? value : String(value));
}
/** Refresh every mirrored control inside `bar` from its source. */
export function syncOptionsBar(bar) {
if (!bar) return;
bar.querySelectorAll('[data-src]').forEach(el => {
const source = resolve(el.dataset.src);
if (!source) return;
if (el.tagName === 'SELECT') { el.value = source.value; return; }
el.value = source.value;
const field = el.closest('.ge-opt');
const out = field?.querySelector('[data-opt-value]');
if (out) out.textContent = valueLabelOf(source, source.value);
});
// Selection mode buttons.
bar.querySelectorAll('[data-opt-mode]').forEach(btn => {
const source = resolve(`${btn.dataset.section} [data-wand-mode="${btn.dataset.optMode}"]`);
btn.classList.toggle('active', !!source && source.classList.contains('active'));
});
// Move-tool auto-select (owned here rather than in the right panel).
const autoSelect = bar.querySelector('#ge-auto-select-layer');
if (autoSelect) autoSelect.checked = !!state.autoSelectLayer;
const target = bar.querySelector('#ge-auto-select-target');
if (target) target.value = state.autoSelectTarget === 'group' ? 'group' : 'layer';
}
/** Render the controls for `toolId` and wire delegation + mirroring. */
export function renderOptionsBar(bar, toolId) {
if (!bar) return;
bar.dataset.optionsTool = toolId;
const hasControls = !!(BRUSH_TOOLS[toolId] || SELECTION_TOOLS[toolId] || LIQUIFY_TOOLS[toolId] || toolId === 'gradient' || toolId === 'move');
// Keep the strip mounted at a stable height for every tool. Hiding it
// for tools without options reflows the centered canvas-area and makes
// the canvas jump vertically when switching tools; an empty strip is
// visually harmless.
bar.classList.toggle('ge-options-empty', !hasControls);
// Brush-family tools now expose their secondary rows (spacing / smoothing /
// blend / pen pressure) through their own caret dropdown in the strip, so
// the generic "..." overflow button is retired for every tool.
const moreBtn = bar.querySelector('#ge-options-more');
if (moreBtn) {
const showMore = false;
moreBtn.hidden = !showMore;
if (!showMore) {
bar.classList.remove('ge-more-open');
moreBtn.setAttribute('aria-expanded', 'false');
}
}
const icon = bar.querySelector('.ge-options-tool-icon');
const name = bar.querySelector('.ge-options-tool-name');
const meta = TOOLS[toolId];
if (name) name.textContent = meta?.label || toolId || '';
if (icon) icon.innerHTML = meta?.icon || '';
const body = bar.querySelector('.ge-options-body');
if (body) body.innerHTML = buildToolControls(toolId);
// Mirror right-panel changes back into the bar.
bar.querySelectorAll('[data-src]').forEach(el => {
const source = resolve(el.dataset.src);
if (!source || source.dataset.geOptMirror) return;
source.dataset.geOptMirror = '1';
source.addEventListener('input', () => syncOptionsBar(bar));
source.addEventListener('change', () => syncOptionsBar(bar));
});
syncOptionsBar(bar);
}
/**
* Build the (empty) options-bar shell. Call `renderOptionsBar` after
* the right-panel controls exist so delegation can resolve them.
*/
export function buildOptionsBar() {
const bar = document.createElement('div');
bar.className = 'ge-options-bar';
bar.id = 'ge-options-bar';
bar.innerHTML = `
<div class="ge-options-tool">
<span class="ge-options-tool-icon" aria-hidden="true"></span>
<span class="ge-options-tool-name"></span>
</div>
<div class="ge-options-sep" aria-hidden="true"></div>
<div class="ge-options-body"></div>
<button type="button" class="ge-options-more" id="ge-options-more" title="More options" aria-label="More options" aria-haspopup="true" aria-expanded="false" hidden>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>
</button>`;
const more = bar.querySelector('#ge-options-more');
more.addEventListener('click', (event) => {
event.stopPropagation();
const open = bar.classList.toggle('ge-more-open');
more.setAttribute('aria-expanded', open ? 'true' : 'false');
});
// Delegation: ranges + selects write through to their real control.
bar.addEventListener('input', event => {
const el = event.target.closest('[data-opt-range]');
if (!el) return;
const source = resolve(el.dataset.src);
if (!source) return;
source.value = el.value;
source.dispatchEvent(new Event('input', { bubbles: true }));
const out = el.closest('.ge-opt')?.querySelector('[data-opt-value]');
if (out) out.textContent = valueLabelOf(source, source.value);
});
bar.addEventListener('change', event => {
if (event.target.id === 'ge-auto-select-layer') {
state.autoSelectLayer = event.target.checked;
bar.dispatchEvent(new CustomEvent('ge-editor-prefs-change', { bubbles: true }));
return;
}
if (event.target.id === 'ge-auto-select-target') {
state.autoSelectTarget = event.target.value === 'group' ? 'group' : 'layer';
bar.dispatchEvent(new CustomEvent('ge-editor-prefs-change', { bubbles: true }));
return;
}
const el = event.target.closest('[data-opt-select]');
if (!el) return;
const source = resolve(el.dataset.src);
if (!source) return;
source.value = el.value;
source.dispatchEvent(new Event('change', { bubbles: true }));
});
bar.addEventListener('click', event => {
const btn = event.target.closest('[data-opt-mode]');
if (!btn) return;
const source = resolve(`${btn.dataset.section} [data-wand-mode="${btn.dataset.optMode}"]`);
source?.click();
syncOptionsBar(bar);
});
return bar;
}
+12
View File
@@ -34,6 +34,8 @@ export function shortcutsPopupHTML() {
<div><kbd>W</kbd> Wand</div>
<div><kbd>${TOOL_SHORTCUTS.marquee}</kbd> Marquee</div>
<div><kbd>C</kbd> Crop</div>
<div><kbd>${TOOL_SHORTCUTS.gradient}</kbd> Gradient</div>
<div><kbd>${TOOL_SHORTCUTS.zoom}</kbd> Zoom <span style="opacity:0.5">(Alt-click = zoom out)</span></div>
</div>
<div class="ge-shortcuts-col">
<h5>Edit</h5>
@@ -62,6 +64,13 @@ export function shortcutsPopupHTML() {
<div><kbd>]</kbd> Brush size +</div>
<div>Drag tolerance slider → live wand retune</div>
</div>
<div class="ge-shortcuts-col">
<h5>Touch</h5>
<div>Pinch → Zoom</div>
<div>Two-finger drag → Pan</div>
<div>Two-finger tap → Undo</div>
<div>Three-finger tap → Redo</div>
</div>
</div>
<div style="margin-top:8px;font-size:10px;opacity:0.5;text-align:center;">Press <kbd>?</kbd> or click the keyboard icon to toggle.</div>
`;
@@ -81,6 +90,7 @@ export function historyPanelHTML(historyIcon) {
<button class="ge-adj-min" type="button" title="Minimise">&minus;</button>
</span>
</div>
<div class="ge-history-snapshots" id="ge-history-snapshots"></div>
<div class="ge-history-list" id="ge-history-list"></div>
`;
}
@@ -95,6 +105,7 @@ export function canvasSizePromptHTML() {
<div class="modal-content ge-canvas-prompt">
<div class="modal-header"><h4 id="ge-canvas-prompt-title">New project</h4></div>
<div class="modal-body">
<div class="ge-canvas-preview" hidden><img id="ge-canvas-prompt-preview" alt="Image preview" /></div>
<div class="ge-canvas-prompt-section-label"><svg class="ge-canvas-prompt-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"></rect><path d="M3 9h18M9 3v18"></path></svg><span>Resolution templates</span></div>
<div class="ge-canvas-preset-grid" role="group" aria-label="Resolution templates">
<button type="button" class="ge-canvas-preset" data-canvas-preset="1024x1024"><svg class="ge-canvas-preset-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="1"></rect></svg><span>Square</span><strong>1024 × 1024</strong></button>
@@ -126,6 +137,7 @@ export function canvasSizePromptHTML() {
<div class="ge-canvas-resize-options">
<label class="ge-canvas-lock-option"><input type="checkbox" id="ge-canvas-prompt-lock" /> <span>Keep proportions</span></label>
<label class="ge-canvas-interpolation-field"><span class="ge-canvas-control-label"><svg class="ge-canvas-prompt-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 18 9 13l3 3 8-8"></path><path d="M15 8h5v5"></path></svg><span>Interpolation</span></span><select id="ge-canvas-prompt-interpolation"><option value="high">Smooth</option><option value="medium">Balanced</option><option value="low">Crisp</option></select></label>
<label class="ge-canvas-resolution-field" hidden><span class="ge-canvas-control-label"><span>Resolution</span></span><input type="number" id="ge-canvas-prompt-resolution" min="1" max="1000" value="72" /><span class="ge-canvas-resolution-unit">px/inch</span></label>
</div>
</div>
<div class="modal-footer ge-canvas-prompt-footer">
+86 -5
View File
@@ -13,7 +13,7 @@
* values).
*
* @param {{
* controlsHTML: (ctx: {color, brushSize, wandTolerance}) => string,
* controlsHTML: (ctx: {color, brushSize, wandTolerance, bucketTolerance, cropAspectPreset}) => string,
* layerPanelHTML: () => string,
* }} build
*
@@ -22,13 +22,19 @@
* controls: HTMLDivElement,
* layerPanel: HTMLDivElement,
* panelResize: HTMLDivElement,
* dock: {dock: HTMLDivElement, show: (id: string) => void}|null,
* }}
*/
import { state } from '../state.js';
import { buildDock } from './dock.js';
export function buildRightPanel({ controlsHTML, layerPanelHTML }) {
export function buildRightPanel({ controlsHTML, layerPanelHTML, extraPanels = [], onCloseGroup = null }) {
const rightPanel = document.createElement('div');
rightPanel.className = 'ge-right-panel';
// Desktop: present Tool Options + Layers as tabs in a dock. Mobile
// (≤ 700 px) keeps the existing bottom-sheet model, where the two
// panels are independent sheets, so the dock is bypassed entirely.
const useDock = window.innerWidth > 700;
// Controls section.
const controls = document.createElement('div');
@@ -66,8 +72,11 @@ export function buildRightPanel({ controlsHTML, layerPanelHTML }) {
color: state.color,
brushSize: state.brushSize,
wandTolerance: state.wandTolerance,
bucketTolerance: state.bucketTolerance,
cropAspectPreset: state.cropAspectPreset,
eyedropperSampleSize: state.eyedropperSampleSize,
});
rightPanel.appendChild(controls);
if (!useDock) rightPanel.appendChild(controls);
// Mobile only (≤ 700 px — matches the .ge-editor-body column-stack
// breakpoint): the right panel becomes a transformed bottom-sheet,
// so any position:fixed descendant gets trapped by the transform
@@ -99,7 +108,7 @@ export function buildRightPanel({ controlsHTML, layerPanelHTML }) {
const layerPanel = document.createElement('div');
layerPanel.className = 'ge-layers';
layerPanel.innerHTML = layerPanelHTML();
rightPanel.appendChild(layerPanel);
if (!useDock) rightPanel.appendChild(layerPanel);
// Mobile: tap the header grab handle or swipe up/down to toggle
// the layers sheet between peek and expanded. The peek state
// always shows the active layer so users never lose access to it.
@@ -164,6 +173,78 @@ export function buildRightPanel({ controlsHTML, layerPanelHTML }) {
}
}
// Mobile panel access (≤ 700 px). The desktop dock is bypassed on
// phones, which left the whole studio panel set (Swatches, Gradients,
// Patterns, Properties, Adjustments, Histogram, Info, Channels, Paths,
// Character, Navigator, History, Actions) unreachable — there was no way
// to add an adjustment or pick a colour from the sheet. Mount the same
// entries in a compact `<select>` overlay reachable from a "Panels"
// button in the layers header, without touching the peek/expand model.
let mobilePanels = null;
if (!useDock && Array.isArray(extraPanels) && extraPanels.length) {
const mDock = buildDock({
entries: extraPanels,
persistKey: 'ge-dock-active',
defaultId: null,
compact: true,
});
const overlay = document.createElement('div');
overlay.className = 'ge-mobile-panels';
overlay.hidden = true;
const head = document.createElement('div');
head.className = 'ge-mobile-panels-head';
const title = document.createElement('span');
title.className = 'ge-mobile-panels-title';
title.textContent = 'Panels';
const closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.className = 'ge-mobile-panels-close';
closeBtn.setAttribute('aria-label', 'Close panels');
closeBtn.textContent = '✕';
head.append(title, closeBtn);
overlay.append(head, mDock.dock);
rightPanel.appendChild(overlay);
closeBtn.addEventListener('click', () => { overlay.hidden = true; });
const hdr = layerPanel.querySelector('.ge-layers-header');
if (hdr) {
const panelsBtn = document.createElement('button');
panelsBtn.type = 'button';
panelsBtn.className = 'ge-layers-panels-btn';
panelsBtn.textContent = 'Panels';
panelsBtn.title = 'Show panels';
panelsBtn.addEventListener('click', (e) => {
e.stopPropagation();
overlay.hidden = !overlay.hidden;
});
hdr.appendChild(panelsBtn);
}
mobilePanels = overlay;
}
// Desktop dock: Tool Options + Layers as tabs (PhotoCraft-parity).
// The panels are only re-parented, so every existing selector and
// listener keeps working; switching tabs just toggles `hidden`.
let dock = null;
if (useDock) { rightPanel.classList.add('ge-right-panel--dock');
dock = buildDock({
entries: [
...(Array.isArray(extraPanels) ? extraPanels : []),
],
defaultId: (Array.isArray(extraPanels) && extraPanels[0]?.id) || null,
persistKey: 'ge-dock-active',
// Narrow desktop columns get the compact selector fallback; the
// multi-group stack needs a bit more room to be usable.
compact: window.innerWidth <= 820,
onCloseGroup,
});
rightPanel.appendChild(dock.dock);
// Layers stays pinned below the dock so the layer list is always
// visible while editing (Photoshop-style), regardless of the active
// dock tab. Only the tool options + studio panels live in tabs.
rightPanel.appendChild(layerPanel);
}
// Horizontal drag handle on the LEFT edge of the right panel — drag
// left to widen, right to narrow. Persists chosen width in
// localStorage so it survives reopens. (Earlier version was a
@@ -205,5 +286,5 @@ export function buildRightPanel({ controlsHTML, layerPanelHTML }) {
} catch {}
});
return { rightPanel, controls, layerPanel, panelResize };
return { rightPanel, controls, layerPanel, panelResize, dock };
}
+276 -63
View File
@@ -6,85 +6,298 @@
* mask plumbing, etc.) stays in the caller and arrives here as the
* `onSelectTool` callback.
*
* Layout mirrors PhotoCraft's rail: ordered sections, with related tools
* collapsed into a single flyout slot (face = current member, caret opens
* the family). Selecting a flyout member promotes it to the slot face.
*
* @param {{
* currentTool: string,
* onSelectTool: (toolId: string, btn: HTMLButtonElement, toolbar: HTMLDivElement) => void,
* onClearSelection: (which: 'marquee'|'lasso'|'wand') => void,
* onClearSelection: (which: 'marquee'|'lasso'|'wand'|'sam') => void,
* }} ctx
* @returns {{ toolbar: HTMLDivElement, toolKeyMap: Record<string,string> }}
* @returns {{
* toolbar: HTMLDivElement,
* toolKeyMap: Record<string,string>,
* syncActive: (toolId: string) => void,
* }}
*/
import { TOOL_SHORTCUTS } from '../tool-shortcuts.js';
import { loadBrushPresets } from '../brush-presets.js';
const CLEAR_X = '<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>';
const CARET = '<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9l6 6 6-6"/></svg>';
export const TOOLS = {
move: { label: 'Move', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="5 9 2 12 5 15"/><polyline points="9 5 12 2 15 5"/><polyline points="15 19 12 22 9 19"/><polyline points="19 9 22 12 19 15"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="12" y1="2" x2="12" y2="22"/></svg>' },
hand: { label: 'Hand', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 11V6a2 2 0 0 0-4 0v4"/><path d="M14 10V4a2 2 0 0 0-4 0v6"/><path d="M10 10V5a2 2 0 0 0-4 0v9"/><path d="M6 13.5 4.5 12A2.1 2.1 0 0 0 2 15l4.5 5A6 6 0 0 0 11 22h2a7 7 0 0 0 7-7v-4a2 2 0 0 0-4 0v1"/></svg>' },
zoom: { label: 'Zoom', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>' },
crop: { label: 'Crop', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg>' },
transform: { label: 'Transform', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>' },
text: { label: 'Text', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M12 4v16"/></svg>' },
shape: { label: 'Shape', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="12" height="12" rx="1"/><circle cx="17" cy="15" r="4"/></svg>' },
brush: { label: 'Brush', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>' },
gradient: { label: 'Gradient', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M6 18 18 6" opacity=".2"/><path d="M9 18 18 9" opacity=".5"/><path d="M12 18 18 12"/></svg>' },
bucket: { label: 'Paint Bucket', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m19 11-8-8-8.6 8.6a2 2 0 0 0 0 2.8l5.2 5.2c.8.8 2 .8 2.8 0L19 11Z"/><path d="m5 2 5 5"/><path d="M2 13h15"/><path d="M22 20a2 2 0 1 1-4 0c0-1.6 1.7-2.4 2-4 .3 1.6 2 2.4 2 4Z"/></svg>' },
eraser: { label: 'Eraser', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.4 14.6 14.6 19.4a2 2 0 0 1-2.83 0L4.6 12.23a2 2 0 0 1 0-2.83l7.17-7.17a2 2 0 0 1 2.83 0l4.8 4.8a2 2 0 0 1 0 2.83Z"/><line x1="22" y1="21" x2="7" y2="21"/><line x1="14" y1="3" x2="9" y2="8"/></svg>' },
pixel: { label: 'Pixel', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" stroke="none" aria-hidden="true"><rect x="4" y="4" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/><rect x="13" y="4" width="7" height="7" opacity="0.35"/><rect x="4" y="13" width="7" height="7" opacity="0.35"/></svg>' },
eyedropper: { label: 'Eyedropper', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.9.9a1 1 0 0 1 0 1.4l-1.6 1.6a1 1 0 0 1-1.4 0L12 8.4a1 1 0 0 1 0-1.4l1.6-1.6a1 1 0 0 1 1.4 0l.9.9Z"/></svg>' },
smudge: { label: 'Smudge', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.5 12V5.5a1.75 1.75 0 1 1 3.5 0V12"/><path d="M16 12v-1.5a1.5 1.5 0 0 1 3 0V16a5 5 0 0 1-5 5h-2.2a4.5 4.5 0 0 1-3.5-1.7l-3.2-4a1.6 1.6 0 0 1 2.4-2.1l1.8 1.9"/></svg>' },
clone: { label: 'Clone', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="9" r="3"/><path d="M9 12l-3 4h12l-3-4"/><path d="M4 20h16"/></svg>' },
heal: { label: 'Healing', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="m5 19 14-14"/><path d="M7 5h4M9 3v4M13 17h4M15 15v4"/></svg>' },
patch: { label: 'Patch', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="10" height="10" rx="1" stroke-dasharray="3 2"/><path d="M13 13h8v8h-8z"/></svg>' },
dodge: { label: 'Dodge', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="m9.5 14.5-6 6"/><circle cx="14" cy="10" r="6" fill="currentColor"/></svg>' },
burn: { label: 'Burn', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 22c4 0 7-3 7-7 0-5-4-8-7-13-3 5-7 8-7 13 0 4 3 7 7 7Z"/><path d="M9 16c1.5 1 4.5 1 6 0"/></svg>' },
liquify: { label: 'Liquify', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8c2.5-3 5-3 7.5 0s5 3 7.5 0"/><path d="M3 14c2.5-3 5-3 7.5 0s5 3 7.5 0"/><circle cx="17.5" cy="19" r="2"/></svg>' },
marquee: { label: 'Marquee', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="1" stroke-dasharray="3 3"/></svg>' },
lasso: { label: 'Lasso', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 22a5 5 0 0 1-2-4"/><path d="M3.3 13.9A6.9 6.9 0 0 1 2 9c0-4 4-7 10-7s10 3 10 7-4 7-10 7"/><path d="M5 18a4.6 4.6 0 0 1-1.5-3.5"/><circle cx="5" cy="19" r="2"/></svg>' },
pen: { label: 'Pen selection', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 19 7-7 3 3-7 7-3-3zM18 13l-1.5-7.5L2 2l3.5 14.5L13 18M2 2l7.5 7.5"/><circle cx="10" cy="10" r="2"/></svg>' },
path: { label: 'Pen Path', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 20 4"/><path d="M4 20h4M20 4v4"/><circle cx="4" cy="20" r="2"/><circle cx="20" cy="4" r="2"/></svg>' },
wand: { label: 'Wand', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 4V2"/><path d="M15 16v-2"/><path d="M8 9h2"/><path d="M20 9h2"/><path d="M17.8 11.8L19 13"/><path d="M15 9h0"/><path d="M17.8 6.2L19 5"/><path d="M3 21l9-9"/><path d="M12.2 6.2L11 5"/></svg>' },
quickselect: { label: 'Quick Select', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v4M12 17v4M3 12h4M17 12h4"/><circle cx="12" cy="12" r="4"/><path d="M12 8a4 4 0 0 1 0 8"/></svg>' },
objectselect: { label: 'Object Select', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2" stroke-dasharray="3 3"/><path d="M9 9h6v6H9z"/></svg>' },
sam: { label: 'SAM', ai: true, icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7c3-3 13-3 16 0"/><path d="M4 17c3 3 13 3 16 0"/><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3"/></svg>' },
inpaint: { label: 'Inpaint', ai: true, icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>' },
rembg: { label: 'Bg Remove', ai: true, icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/><line x1="14.47" y1="14.48" x2="20" y2="20"/><line x1="8.12" y1="8.12" x2="12" y2="12"/></svg>' },
sharpen: { label: 'Sharpen', ai: true, icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2l2.4 6.6L21 11l-6.6 2.4L12 20l-2.4-6.6L3 11l6.6-2.4z"/></svg>' },
};
// Ordered sections. A string is a single-tool slot; an array is a flyout
// slot whose first member is the default face.
const SECTIONS = [
['move'],
[['marquee', 'lasso'], ['wand', 'quickselect', 'objectselect', 'sam']],
[['crop', 'transform'], ['brush', 'eraser', 'pixel'], ['clone', 'heal', 'patch'], ['smudge', 'dodge', 'burn', 'liquify'], ['gradient', 'bucket'], 'eyedropper'],
[['pen', 'path'], ['text', 'shape'], ['inpaint', 'rembg', 'sharpen']],
[['hand', 'zoom']],
];
export function buildToolbar({ currentTool, onSelectTool, onClearSelection }) {
const toolbar = document.createElement('div');
toolbar.className = 'ge-toolbar';
const tools = [
{ id: 'move', label: 'Move', icon: '✥' },
{ id: 'hand', label: 'Hand', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 11V6a2 2 0 0 0-4 0v4"/><path d="M14 10V4a2 2 0 0 0-4 0v6"/><path d="M10 10V5a2 2 0 0 0-4 0v9"/><path d="M6 13.5 4.5 12A2.1 2.1 0 0 0 2 15l4.5 5A6 6 0 0 0 11 22h2a7 7 0 0 0 7-7v-4a2 2 0 0 0-4 0v1"/></svg>' },
{ id: 'crop', label: 'Crop', icon: '✂' },
{ id: 'transform', label: 'Transform', icon: '⤢' },
{ id: 'text', label: 'Text', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M12 4v16"/></svg>' },
{ id: 'shape', label: 'Shape', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="12" height="12" rx="1"/><circle cx="17" cy="15" r="4"/></svg>' },
{ sep: true },
{ id: 'brush', label: 'Brush', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>' },
{ id: 'gradient', label: 'Gradient', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 20 4"/><path d="M6 18 18 6" opacity=".45"/><path d="M8 16 16 8" opacity=".2"/></svg>' },
{ id: 'eraser', label: 'Eraser', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.4 14.6 14.6 19.4a2 2 0 0 1-2.83 0L4.6 12.23a2 2 0 0 1 0-2.83l7.17-7.17a2 2 0 0 1 2.83 0l4.8 4.8a2 2 0 0 1 0 2.83Z"/><line x1="22" y1="21" x2="7" y2="21"/><line x1="14" y1="3" x2="9" y2="8"/></svg>' },
{ id: 'eyedropper', label: 'Eyedropper', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m19 3 2 2-9.5 9.5-3-3Z"/><path d="m8.5 11.5-5 5V21h4.5l5-5"/></svg>' },
{ id: 'smudge', label: 'Smudge', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 19c2-3 4-5 6-6 2-1 4-3 4-6 0-2-1-4-3-4s-3 2-3 4v5"/><path d="M9 13c-2 0-4 1-5 3-.7 1.2-.1 3 1.4 3H18c1.7 0 3-1.3 3-3 0-1.1-.9-2-2-2h-4"/></svg>' },
{ sep: true },
{ id: 'clone', label: 'Clone', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="9" r="3"/><path d="M9 12l-3 4h12l-3-4"/><path d="M4 20h16"/></svg>' },
{ id: 'heal', label: 'Healing', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="m5 19 14-14"/><path d="M7 5h4M9 3v4M13 17h4M15 15v4"/></svg>' },
{ id: 'dodge', label: 'Dodge', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="10" cy="10" r="6"/><path d="m14.5 14.5 6 6"/></svg>' },
{ id: 'burn', label: 'Burn', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 22c4 0 7-3 7-7 0-5-4-8-7-13-3 5-7 8-7 13 0 4 3 7 7 7Z"/><path d="M9 16c1.5 1 4.5 1 6 0"/></svg>' },
{ id: 'marquee', label: 'Marquee', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="1" stroke-dasharray="3 3"/></svg>' },
{ id: 'lasso', label: 'Lasso', icon: '⟡' },
{ id: 'pen', label: 'Pen selection', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 19 7-7 3 3-7 7-3-3zM18 13l-1.5-7.5L2 2l3.5 14.5L13 18M2 2l7.5 7.5"/><circle cx="10" cy="10" r="2"/></svg>' },
{ id: 'wand', label: 'Wand', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 4V2"/><path d="M15 16v-2"/><path d="M8 9h2"/><path d="M20 9h2"/><path d="M17.8 11.8L19 13"/><path d="M15 9h0"/><path d="M17.8 6.2L19 5"/><path d="M3 21l9-9"/><path d="M12.2 6.2L11 5"/></svg>' },
{ id: 'sam', label: 'SAM', ai: true, icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7c3-3 13-3 16 0"/><path d="M4 17c3 3 13 3 16 0"/><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3"/></svg>' },
{ sep: true },
{ id: 'inpaint', label: 'Inpaint', ai: true, icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"/></svg>' },
{ id: 'rembg', ai: true, label: 'Bg Remove', icon: '✄' },
{ id: 'sharpen', ai: true, label: 'Sharpen', icon: '◈' },
];
// The tool slots live in their own scroller so the colour swatches can sit
// in a fixed footer below it. With the swatches inside the scroller they
// were sticky over the last slots and swallowed their clicks.
const scroller = document.createElement('div');
scroller.className = 'ge-toolbar-scroll';
toolbar.appendChild(scroller);
const toolKeyMap = {};
for (const t of tools) {
t.key = TOOL_SHORTCUTS[t.id];
if (t.sep) {
const sep = document.createElement('div');
sep.className = 'ge-tool-sep';
sep.textContent = t.label;
toolbar.appendChild(sep);
continue;
}
if (t.key) toolKeyMap[t.key.toLowerCase()] = t.id;
const btn = document.createElement('button');
btn.className = 'ge-tool-btn' + (t.id === currentTool ? ' active' : '');
btn.dataset.tool = t.id;
btn.title = t.label + (t.key ? ` (${t.key})` : '');
if (t.id === 'pen') btn.title += ' - Click anchors; drag for curves; close path or press Enter';
// Heavy 4-point AI star marker for AI-backed tools — sits just to
// the left of the icon so the user can spot AI vs local tools at a
// glance now that the "AI Tools" separator is gone.
const aiStar = t.ai ? '<span class="ge-tool-ai" title="AI">✦</span>' : '';
const slots = [];
for (const id of Object.keys(TOOLS)) {
const key = TOOL_SHORTCUTS[id];
if (key) toolKeyMap[key.toLowerCase()] = id;
}
const setInner = (btn, toolId) => {
const t = TOOLS[toolId];
btn.dataset.tool = toolId;
btn.title = t.label + (TOOL_SHORTCUTS[toolId] ? ` (${TOOL_SHORTCUTS[toolId]})` : '');
if (toolId === 'pen') btn.title += ' - Click anchors; drag for curves; close path or press Enter';
if (toolId === 'path') btn.title += ' - Click to add anchors; double-click or press Enter to finish';
btn.classList.toggle('is-ai', !!t.ai);
// Selection-clear badge — rendered only for tools that can hold a
// selection (lasso, wand). Inpaint masks are first-class sub-layers
// now so they get their own delete-X in the layer panel.
const clearTitle = t.id === 'sam' ? 'Open SAM prompt' : 'Clear selection';
const clearBadge = (t.id === 'marquee' || t.id === 'lasso' || t.id === 'wand' || t.id === 'sam')
? '<span class="ge-tool-clear" title="' + clearTitle + '" data-clear-tool="' + t.id + '">' +
'<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>' +
'</span>'
const aiStar = t.ai ? '<span class="ge-tool-ai" title="AI">✦</span>' : '';
const clearTitle = toolId === 'sam' ? 'Open SAM prompt' : 'Clear selection';
const clearBadge = ['marquee', 'lasso', 'quickselect', 'objectselect', 'wand', 'sam'].includes(toolId)
? '<span class="ge-tool-clear" title="' + clearTitle + '" data-clear-tool="' + toolId + '">' + CLEAR_X + '</span>'
: '';
btn.innerHTML = `${aiStar}<span class="ge-tool-icon"${t.small ? ' style="font-size:14px"' : ''}>${t.icon}</span><span class="ge-tool-label">${t.label}</span>${clearBadge}`;
// Clear-badge click stops propagation so the tool itself doesn't
// toggle; the actual clear is handled by the caller.
btn.innerHTML = `${aiStar}<span class="ge-tool-icon"${t.small ? ' style="font-size:14px"' : ''}>${t.icon}</span>${clearBadge}`;
btn.querySelector('.ge-tool-clear')?.addEventListener('click', (ev) => {
ev.stopPropagation();
onClearSelection(ev.currentTarget.dataset.clearTool);
});
btn.addEventListener('click', () => onSelectTool(t.id, btn, toolbar));
toolbar.appendChild(btn);
};
const closeAllFlyouts = () => {
toolbar.querySelectorAll('.ge-tool-slot.open').forEach(s => s.classList.remove('open'));
};
const openFlyout = (slotEl, face) => {
const isOpen = slotEl.classList.contains('open');
closeAllFlyouts();
if (isOpen) return;
slotEl.classList.add('open');
const flyout = slotEl.querySelector('.ge-tool-flyout');
if (!flyout) return;
const r = face.getBoundingClientRect();
// The flyout is position:fixed, but an ancestor with a transform (the
// gallery modal sets an identity matrix) becomes its containing block, so
// viewport coords must be offset by that block's origin or the popup lands
// far from the button.
const cb = flyout.offsetParent;
const cbRect = cb ? cb.getBoundingClientRect() : { left: 0, top: 0 };
const cbX = cbRect.left + (cb ? cb.clientLeft : 0);
const cbY = cbRect.top + (cb ? cb.clientTop : 0);
if (window.innerWidth <= 820) {
flyout.style.left = (Math.max(r.left, 4) - cbX) + 'px';
flyout.style.top = (r.bottom + 4 - cbY) + 'px';
} else {
flyout.style.left = (r.right + 4 - cbX) + 'px';
flyout.style.top = (Math.max(r.top, 4) - cbY) + 'px';
}
// Keep the list inside the window. The rail's lower slots (brush with its
// presets, clone, smudge) open a tall menu that would otherwise spill past
// the bottom edge, leaving the lower rows impossible to click.
const fw = flyout.offsetWidth;
const fh = flyout.offsetHeight;
const viewLeft = (parseFloat(flyout.style.left) || 0) + cbX;
const viewTop = (parseFloat(flyout.style.top) || 0) + cbY;
const maxLeft = Math.max(4, window.innerWidth - fw - 4);
const maxTop = Math.max(4, window.innerHeight - fh - 4);
if (viewLeft > maxLeft) flyout.style.left = (maxLeft - cbX) + 'px';
if (viewTop > maxTop) flyout.style.top = (maxTop - cbY) + 'px';
};
document.addEventListener('click', (ev) => {
if (!toolbar.contains(ev.target)) closeAllFlyouts();
});
let first = true;
for (const section of SECTIONS) {
if (!first) {
const sep = document.createElement('div');
sep.className = 'ge-tool-sep';
scroller.appendChild(sep);
}
first = false;
for (const entry of section) {
const members = Array.isArray(entry) ? entry : [entry];
const slotEl = document.createElement('div');
slotEl.className = 'ge-tool-slot';
const face = document.createElement('button');
face.type = 'button';
face.className = 'ge-tool-btn ge-tool-slot-face';
const faceId = members.includes(currentTool) ? currentTool : members[0];
setInner(face, faceId);
face.addEventListener('click', () => {
closeAllFlyouts();
onSelectTool(face.dataset.tool, face, toolbar);
});
slotEl.appendChild(face);
const slot = { el: slotEl, face, members, current: faceId, items: [] };
if (members.length > 1) {
// Photoshop-style corner triangle marks a slot whose family has
// more tools behind it. It lives on the slot (not on the face) so
// re-rendering the face icon when a flyout member is picked never
// wipes the hint away.
slotEl.insertAdjacentHTML('beforeend', '<span class="ge-tool-flyout-tri" aria-hidden="true"></span>');
const tri = slotEl.querySelector('.ge-tool-flyout-tri');
tri?.addEventListener('click', (ev) => {
ev.stopPropagation();
openFlyout(slotEl, face);
});
const flyout = document.createElement('div');
flyout.className = 'ge-tool-flyout';
for (const id of members) {
const item = document.createElement('button');
item.type = 'button';
item.className = 'ge-tool-btn ge-tool-flyout-item';
setInner(item, id);
// Keep `data-tool` unique to the slot face so `[data-tool="X"]`
// selectors are unambiguous; flyout members expose the option id.
item.dataset.toolOption = id;
delete item.dataset.tool;
item.addEventListener('click', (ev) => {
ev.stopPropagation();
setInner(face, id);
slot.current = id;
closeAllFlyouts();
onSelectTool(id, face, toolbar);
});
item.insertAdjacentHTML('beforeend', `<span class="ge-tool-flyout-label">${TOOLS[id].label}</span>`);
flyout.appendChild(item);
slot.items.push(item);
}
// Photoshop-style: the Brush slot's flyout also lists the brush
// presets, so any saved presets are reachable straight from the tool
// button. Picking one switches to the Brush and applies the preset
// through the options-bar picker so the size and stroke controls stay
// in sync. Pixel is its own tool (above), so it is NOT listed here as a
// brush type.
if (members.includes('brush')) {
const brushPresets = loadBrushPresets().filter((preset) => !preset.pixel);
if (brushPresets.length) {
const sep = document.createElement('div');
sep.className = 'ge-tool-flyout-sep';
flyout.appendChild(sep);
const heading = document.createElement('div');
heading.className = 'ge-tool-flyout-heading';
heading.textContent = 'Brushes';
flyout.appendChild(heading);
for (const preset of brushPresets) {
const presetItem = document.createElement('button');
presetItem.type = 'button';
presetItem.className = 'ge-tool-btn ge-tool-flyout-item ge-tool-flyout-preset';
presetItem.dataset.brushPreset = preset.id;
// Each preset row shows a glyph that reflects the preset's tip:
// a 1px checker square for the pixel brush, a solid disc for a
// hard round, a soft-edged disc for a soft round, and a mid disc
// in between — so a row is recognisable at a glance.
const soft = typeof preset.softness === 'number' ? preset.softness : 100;
const presetIcon = preset.pixel
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="none" aria-hidden="true"><rect x="6" y="6" width="5" height="5"/><rect x="13" y="13" width="5" height="5"/><rect x="13" y="6" width="5" height="5" opacity="0.35"/><rect x="6" y="13" width="5" height="5" opacity="0.35"/></svg>'
: soft <= 20
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="none" aria-hidden="true"><circle cx="12" cy="12" r="6.5"/></svg>'
: soft >= 70
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="6.5" fill="currentColor" opacity="0.3"/><circle cx="12" cy="12" r="6.5"/></svg>'
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><circle cx="12" cy="12" r="6.5" fill="currentColor" opacity="0.65"/><circle cx="12" cy="12" r="6.5"/></svg>';
presetItem.insertAdjacentHTML('beforeend', `<span class="ge-tool-icon">${presetIcon}</span><span class="ge-tool-flyout-label">${preset.name}</span>`);
presetItem.addEventListener('click', (ev) => {
ev.stopPropagation();
setInner(face, 'brush');
slot.current = 'brush';
onSelectTool('brush', face, toolbar);
const picker = document.getElementById('ge-brush-preset');
if (picker) {
picker.value = preset.id;
picker.dispatchEvent(new Event('change', { bubbles: true }));
}
closeAllFlyouts();
});
flyout.appendChild(presetItem);
}
}
}
slotEl.appendChild(flyout);
face.addEventListener('contextmenu', (ev) => {
ev.preventDefault();
openFlyout(slotEl, face);
});
}
slots.push(slot);
scroller.appendChild(slotEl);
}
}
return { toolbar, toolKeyMap };
// Foreground / background color swatches (Photoshop-style) pinned to
// the bottom of the tool rail, with a swap control.
const swatches = document.createElement('div');
swatches.className = 'ge-tool-swatches';
swatches.innerHTML = `
<label class="ge-swatch ge-swatch-bg" title="Background color">
<input type="color" id="ge-bg-color" value="#ffffff" aria-label="Background color" />
</label>
<label class="ge-swatch ge-swatch-fg" title="Foreground color">
<input type="color" id="ge-fg-color" value="#000000" aria-label="Foreground color" />
</label>
<button type="button" class="ge-swatch-swap" id="ge-swap-colors" title="Swap foreground and background colors" aria-label="Swap colors">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4 3 8l4 4"/><path d="M3 8h13a4 4 0 0 1 0 8h-2"/><path d="M17 20l4-4-4-4"/></svg>
</button>`;
toolbar.appendChild(swatches);
const syncActive = (toolId) => {
for (const slot of slots) {
if (!slot.members.includes(toolId)) continue;
if (slot.current !== toolId) setInner(slot.face, toolId);
slot.current = toolId;
slot.face.classList.add('active');
slot.items.forEach(it => it.classList.toggle('active', (it.dataset.toolOption || it.dataset.tool) === toolId));
}
};
// Initial active state.
syncActive(currentTool);
return { toolbar, toolKeyMap, syncActive };
}
+462 -74
View File
@@ -13,47 +13,92 @@ export function buildTopbar() {
topBar.className = 'ge-topbar';
topBar.innerHTML = `
<div class="ge-topbar-left">
<span class="ge-alpha-badge" title="This editor is in active development — expect rough edges">ALPHA</span>
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-undo" title="Undo">
<span class="ge-stacked-glyph">↩</span>
<span class="ge-stacked-label">UNDO</span>
</button>
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-redo" title="Redo">
<span class="ge-stacked-glyph">↪</span>
<span class="ge-stacked-label">REDO</span>
</button>
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-history-btn" title="History — click an entry to jump to that state" aria-label="History">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 4v6h6"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/><polyline points="12 7 12 12 16 14"/></svg></span>
<span class="ge-stacked-label">HISTORY</span>
</button>
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-compare-btn" title="Show the document before editing" aria-label="Show the document before editing" aria-pressed="false">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v18"></path><path d="M5 7h14M5 17h14"></path></svg></span>
<span class="ge-stacked-label">BEFORE</span>
</button>
</div>
<div class="ge-topbar-right">
<div class="ge-view-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-view-menu-btn" title="Canvas view" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">VIEW</span>
<div class="ge-file-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-file-menu-btn" title="File actions" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3v4a1 1 0 0 0 1 1h4"/><path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">File</span>
</button>
<div class="ge-view-menu dropdown" id="ge-view-menu" hidden>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="rulers"><span class="dropdown-icon ge-view-check">✓</span><span>Rulers</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="grid"><span class="dropdown-icon ge-view-check">✓</span><span>Grid</span></button>
<label class="ge-view-grid-size"><span>Grid size</span><input id="ge-grid-size" type="number" min="2" max="1000" step="1" value="16"><span>px</span></label>
<div class="dropdown-section-divider"></div>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="snap"><span class="dropdown-icon ge-view-check">✓</span><span>Snap</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="snap-grid"><span class="dropdown-icon ge-view-check">✓</span><span>Snap to grid</span></button>
<button class="dropdown-item-compact" data-view-action="clear-guides"><span class="dropdown-icon">×</span><span>Clear guides</span></button>
<div class="ge-file-menu dropdown" id="ge-file-menu" hidden>
<div class="ge-menu-label">New</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="file-new" aria-haspopup="true" aria-expanded="false"><span>New Image</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="file-new">
<button class="dropdown-item-compact" data-file-action="new-default"><span>Default</span><span class="dropdown-shortcut">1920 × 1080</span></button>
<button class="dropdown-item-compact" data-file-action="new-square"><span>Square</span><span class="dropdown-shortcut">1080 × 1080</span></button>
<button class="dropdown-item-compact" data-file-action="new-portrait"><span>Portrait</span><span class="dropdown-shortcut">1080 × 1350</span></button>
<button class="dropdown-item-compact" data-file-action="new-story"><span>Story</span><span class="dropdown-shortcut">1080 × 1920</span></button>
<button class="dropdown-item-compact" data-file-action="new-clipboard"><span>From Clipboard</span></button>
<button class="dropdown-item-compact" data-file-action="new-custom"><span>Custom Size…</span><span class="dropdown-shortcut">Ctrl+N</span></button>
</div>
<div class="ge-menu-label">Open</div>
<button class="dropdown-item-compact" data-file-action="import"><span>Import Image…</span></button>
<button class="dropdown-item-compact" data-file-action="load-project"><span>Load Project…</span></button>
<div class="ge-menu-label">Save</div>
<button class="dropdown-item-compact" data-file-action="save"><span>Save Over Original</span><span class="dropdown-shortcut">Ctrl+S</span></button>
<button class="dropdown-item-compact" data-file-action="save-copy"><span>Save As Copy</span><span class="dropdown-shortcut">Ctrl+Shift+S</span></button>
<button class="dropdown-item-compact" data-file-action="export"><span>Export Image…</span></button>
<button class="dropdown-item-compact" data-file-action="export-psd"><span>Export Layers as PSD…</span></button>
<div class="ge-menu-label">Project</div>
<button class="dropdown-item-compact" data-file-action="save-project"><span>Save Project (.json)</span></button>
</div>
</div>
<div class="ge-edit-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-edit-menu-btn" title="Edit actions" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">Edit</span>
</button>
<div class="ge-edit-menu dropdown" id="ge-edit-menu" hidden>
<div class="ge-menu-label">History</div>
<button class="dropdown-item-compact" data-edit-action="undo"><span>Undo</span><span class="dropdown-shortcut">Ctrl+Z</span></button>
<button class="dropdown-item-compact" data-edit-action="redo"><span>Redo</span><span class="dropdown-shortcut">Ctrl+Shift+Z</span></button>
<button class="dropdown-item-compact" data-edit-action="history"><span>History…</span></button>
<div class="ge-menu-label">Clipboard</div>
<button class="dropdown-item-compact" data-edit-action="copy-merged" title="Copy the flattened visible image to the clipboard"><span>Copy Merged</span><span class="dropdown-shortcut">Ctrl+Shift+C</span></button>
<div class="ge-menu-label">Transform (active layer)</div>
<button class="dropdown-item-compact" data-edit-action="rotate-90" title="Rotate the active layer 90° CW"><span>Rotate 90° CW</span></button>
<button class="dropdown-item-compact" data-edit-action="rotate-180" title="Rotate the active layer 180°"><span>Rotate 180°</span></button>
<button class="dropdown-item-compact" data-edit-action="flip-h" title="Flip the active layer horizontally"><span>Flip Horizontal</span></button>
<button class="dropdown-item-compact" data-edit-action="flip-v" title="Flip the active layer vertically"><span>Flip Vertical</span></button>
<div class="ge-menu-label">Content-Aware</div>
<button class="dropdown-item-compact" data-edit-action="content-aware-move" title="Move the selection content and fill the hole it leaves behind"><span>Content-Aware Move…</span></button>
<div class="ge-menu-label">Stroke</div>
<button class="dropdown-item-compact" data-edit-action="stroke" title="Stroke the active layer or selection"><span>Stroke…</span></button>
<div class="ge-menu-label">Presets</div>
<button class="dropdown-item-compact" data-edit-action="define-brush" title="Save the current brush settings as a reusable preset"><span>Define Brush Preset…</span></button>
</div>
</div>
<div class="ge-image-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-image-menu-btn" title="Image actions" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">IMAGE</span>
<span class="ge-stacked-label">Image</span>
</button>
<div class="ge-image-menu dropdown" id="ge-image-menu" hidden>
<button class="dropdown-item-compact" data-image-action="fill" title="Fill with foreground color (Alt+Backspace)"><span>Fill</span></button>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="image-adjustments" aria-haspopup="true" aria-expanded="false"><span>Adjustments</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="image-adjustments">
<button class="dropdown-item-compact" data-image-action="desaturate" title="Desaturate"><span>Desaturate</span></button>
<button class="dropdown-item-compact" data-image-action="auto-tone" title="Auto Tone"><span>Auto Tone</span></button>
<button class="dropdown-item-compact" data-image-action="auto-contrast" title="Auto Contrast"><span>Auto Contrast</span></button>
<button class="dropdown-item-compact" data-image-action="auto-color" title="Auto Color"><span>Auto Color</span></button>
<button class="dropdown-item-compact" data-image-action="equalize" title="Equalize the histogram of the active layer"><span>Equalize</span></button>
<button class="dropdown-item-compact" data-image-action="replace-color" title="Recolour pixels near a target colour"><span>Replace Color…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-brightness-contrast" title="Brightness/Contrast"><span>Brightness/Contrast…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-hue-saturation" title="Hue/Saturation"><span>Hue/Saturation…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-selective-color" title="Selective Color"><span>Selective Color…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-levels" title="Levels"><span>Levels…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-curves" title="Curves"><span>Curves…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-exposure" title="Exposure"><span>Exposure…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-develop" title="Develop (Camera Raw)"><span>Develop…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-vibrance" title="Vibrance"><span>Vibrance…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-color-balance" title="Color Balance"><span>Color Balance…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-black-white" title="Black &amp; White"><span>Black &amp; White…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-photo-filter" title="Photo Filter"><span>Photo Filter…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-channel-mixer" title="Channel Mixer"><span>Channel Mixer…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-invert" title="Invert"><span>Invert</span></button>
<button class="dropdown-item-compact" data-image-action="adj-posterize" title="Posterize"><span>Posterize…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-threshold" title="Threshold"><span>Threshold…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-gradient-map" title="Gradient Map"><span>Gradient Map…</span></button>
<button class="dropdown-item-compact" data-image-action="adj-shadows-highlights" title="Shadows/Highlights"><span>Shadows/Highlights…</span></button>
</div>
<button class="dropdown-item-compact" data-image-action="canvas-size">
<span class="dropdown-icon">⤢</span>
<span>Canvas Size...</span>
@@ -62,37 +107,131 @@ export function buildTopbar() {
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg></span>
<span>Image Size...</span>
</button>
<div class="ge-filter-submenu-label">Transform</div>
<div class="ge-filter-submenu-label">Trim</div>
<button class="dropdown-item-compact" data-image-action="trim" title="Trim transparent edges from the active layer"><span>Trim…</span></button>
<div class="ge-filter-submenu-label">Image Rotation (whole image)</div>
<button class="dropdown-item-compact" data-image-action="rotate-90">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7"/><polyline points="21 3 21 9 15 9"/></svg></span>
<span>Rotate 90° CW</span>
</button>
<button class="dropdown-item-compact" data-image-action="rotate-ccw">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><polyline points="3 3 3 9 9 9"/></svg></span>
<span>Rotate 90° CCW</span>
</button>
<button class="dropdown-item-compact" data-image-action="rotate-180">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg></span>
<span>Rotate 180°</span>
</button>
<button class="dropdown-item-compact" data-image-action="rotate-arbitrary">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></span>
<span>Arbitrary…</span>
</button>
<button class="dropdown-item-compact" data-image-action="perspective-crop">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6l18-2-2 14-16-2z"/><circle cx="3" cy="6" r="1.6" fill="currentColor" stroke="none"/><circle cx="21" cy="4" r="1.6" fill="currentColor" stroke="none"/><circle cx="19" cy="18" r="1.6" fill="currentColor" stroke="none"/><circle cx="3" cy="16" r="1.6" fill="currentColor" stroke="none"/></svg></span>
<span>Perspective Crop…</span>
</button>
<button class="dropdown-item-compact" data-image-action="flip-h">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 7v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7"/><line x1="12" y1="3" x2="12" y2="21"/><polyline points="7 11 4 7 7 3"/><polyline points="17 11 20 7 17 3"/></svg></span>
<span>Flip horizontal</span>
<span>Flip Canvas Horizontal</span>
</button>
<button class="dropdown-item-compact" data-image-action="flip-v">
<span class="dropdown-icon"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h10"/><line x1="3" y1="12" x2="21" y2="12"/><polyline points="11 7 7 4 3 7"/><polyline points="11 17 7 20 3 17"/></svg></span>
<span>Flip vertical</span>
<span>Flip Canvas Vertical</span>
</button>
<div class="ge-filter-submenu-label">Mode</div>
<button class="dropdown-item-compact" data-image-action="mode-rgb"><span>RGB Color</span></button>
<button class="dropdown-item-compact" data-image-action="mode-grayscale"><span>Grayscale</span></button>
<button class="dropdown-item-compact" data-image-action="mode-cmyk" disabled title="CMYK needs a color-managed pipeline"><span>CMYK Color</span></button>
<button class="dropdown-item-compact" data-image-action="mode-lab" disabled title="Lab needs a color-managed pipeline"><span>Lab Color</span></button>
<div class="ge-filter-submenu-label">Bits/Channel</div>
<button class="dropdown-item-compact" data-image-action="bits-8"><span>8 Bits/Channel</span></button>
<button class="dropdown-item-compact" data-image-action="bits-16" disabled title="16-bit needs a 16-bit working canvas"><span>16 Bits/Channel</span></button>
<button class="dropdown-item-compact" data-image-action="bits-32" disabled title="32-bit needs a float working canvas"><span>32 Bits/Channel</span></button>
</div>
</div>
<div class="ge-layer-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-layer-menu-btn" title="Layer actions" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 3 8l9 5 9-5-9-5z"/><path d="m3 13 9 5 9-5"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">Layer</span>
</button>
<div class="ge-layer-menu dropdown" id="ge-layer-menu" hidden>
<div class="ge-menu-label">New</div>
<button class="dropdown-item-compact" data-layer-action="new"><span>New Layer…</span></button>
<button class="dropdown-item-compact" data-layer-action="new-fill"><span>New Fill Layer…</span></button>
<button class="dropdown-item-compact" data-layer-action="duplicate"><span>Duplicate Layer</span><span class="dropdown-shortcut">Ctrl+J</span></button>
<button class="dropdown-item-compact" data-layer-action="group"><span>Group Selected</span></button>
<button class="dropdown-item-compact" data-layer-action="rasterize"><span>Rasterize Layer</span></button>
<div class="ge-menu-label">Modify</div>
<button class="dropdown-item-compact" data-layer-action="delete"><span>Delete Layer</span><span class="dropdown-shortcut">Del</span></button>
<div class="ge-menu-label">Arrange</div>
<button class="dropdown-item-compact" data-layer-action="arrange-front"><span>Bring to Front</span></button>
<button class="dropdown-item-compact" data-layer-action="arrange-forward"><span>Bring Forward</span></button>
<button class="dropdown-item-compact" data-layer-action="arrange-backward"><span>Send Backward</span></button>
<button class="dropdown-item-compact" data-layer-action="arrange-back"><span>Send to Back</span></button>
<div class="ge-menu-label">Merge</div>
<button class="dropdown-item-compact" data-layer-action="merge-down"><span>Merge Down</span><span class="dropdown-shortcut">Ctrl+E</span></button>
<button class="dropdown-item-compact" data-layer-action="merge-layers"><span>Merge Layers</span></button>
<button class="dropdown-item-compact" data-layer-action="merge-all"><span>Merge All</span></button>
<button class="dropdown-item-compact" data-layer-action="merge-visible"><span>Merge Visible</span></button>
<button class="dropdown-item-compact" data-layer-action="flatten"><span>Flatten Image</span></button>
<div class="ge-menu-label">Select</div>
<button class="dropdown-item-compact" data-layer-action="select-all"><span>Select All Layers</span></button>
<div class="ge-menu-label">Vector Mask</div>
<button class="dropdown-item-compact" data-layer-action="vector-mask-reveal" title="Add a mask that reveals the whole layer"><span>Reveal All</span></button>
<button class="dropdown-item-compact" data-layer-action="vector-mask-hide" title="Add a mask that hides the whole layer"><span>Hide All</span></button>
<div class="ge-menu-label">Combine Shapes</div>
<button class="dropdown-item-compact" data-layer-action="combine-unite"><span>Unite Shapes</span></button>
<button class="dropdown-item-compact" data-layer-action="combine-subtract"><span>Subtract Shapes</span></button>
<button class="dropdown-item-compact" data-layer-action="combine-intersect"><span>Intersect Shapes</span></button>
<button class="dropdown-item-compact" data-layer-action="combine-exclude"><span>Exclude Shapes</span></button>
<div class="ge-menu-label">Fill</div>
<button class="dropdown-item-compact" data-layer-action="fill"><span>Fill</span></button>
</div>
</div>
<div class="ge-type-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-type-menu-btn" title="Type actions" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">Type</span>
</button>
<div class="ge-type-menu dropdown" id="ge-type-menu" hidden>
<div class="ge-menu-label">Create</div>
<button class="dropdown-item-compact" data-type-action="add"><span>Add Text Layer</span></button>
<div class="ge-menu-label">Panels</div>
<button class="dropdown-item-compact" data-type-action="character"><span>Character…</span></button>
<button class="dropdown-item-compact" data-type-action="paragraph"><span>Paragraph…</span></button>
<div class="ge-menu-label">Warp</div>
<button class="dropdown-item-compact" data-type-action="warp"><span>Warp Text…</span></button>
<div class="ge-menu-label">Path</div>
<button class="dropdown-item-compact" data-type-action="text-on-path" title="Lay the active text layer along the selected path layer"><span>Text on a Path</span></button>
<button class="dropdown-item-compact" data-type-action="text-on-circle" title="Wrap the active text layer around a circle"><span>Text on a Circle</span></button>
<button class="dropdown-item-compact" data-type-action="text-off-path" title="Return the text layer to a straight baseline"><span>Remove from Path</span></button>
</div>
</div>
<div class="ge-selection-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-selection-menu-btn" title="Selection actions" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="1" stroke-dasharray="3 3"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">SELECT</span>
<span class="ge-stacked-label">Select</span>
</button>
<div class="ge-selection-menu dropdown" id="ge-selection-menu" hidden>
<button class="dropdown-item-compact" data-selection-action="all"><span>Select All</span><span class="dropdown-shortcut">Ctrl+A</span></button>
<button class="dropdown-item-compact" data-selection-action="deselect"><span>Deselect</span><span class="dropdown-shortcut">Ctrl+D</span></button>
<button class="dropdown-item-compact" data-selection-action="reselect"><span>Reselect</span></button>
<button class="dropdown-item-compact" data-selection-action="invert"><span>Invert</span><span class="dropdown-shortcut">Ctrl+Alt+Shift+I</span></button>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="selection-modify" aria-haspopup="true" aria-expanded="false"><span>Modify</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="selection-modify">
<button class="dropdown-item-compact" data-selection-action="modifyBorder"><span>Border…</span></button>
<button class="dropdown-item-compact" data-selection-action="modifySmooth"><span>Smooth…</span></button>
<button class="dropdown-item-compact" data-selection-action="modifyExpand"><span>Expand…</span></button>
<button class="dropdown-item-compact" data-selection-action="modifyContract"><span>Contract…</span></button>
<button class="dropdown-item-compact" data-selection-action="modifyFeather"><span>Feather…</span></button>
</div>
<button class="dropdown-item-compact" data-selection-action="grow"><span>Grow</span></button>
<button class="dropdown-item-compact" data-selection-action="similar"><span>Similar</span></button>
<button class="dropdown-item-compact" data-selection-action="subject"><span>Subject</span></button>
<button class="dropdown-item-compact" data-selection-action="transform"><span>Transform Selection</span></button>
<button class="dropdown-item-compact" data-selection-action="refine"><span>Refine Selection…</span></button>
<button class="dropdown-item-compact" data-selection-action="colorRange"><span>Color Range…</span></button>
<button class="dropdown-item-compact" data-selection-action="selectAndMask"><span>Select and Mask…</span></button>
<div class="dropdown-section-divider"></div>
<div class="ge-selection-save-row">
<input id="ge-selection-name" type="text" maxlength="100" placeholder="Selection name" aria-label="Saved selection name" />
@@ -107,50 +246,286 @@ export function buildTopbar() {
<div class="ge-filter-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-filter-menu-btn" title="Filters" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5h16M7 12h10M10 19h4"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">FILTER</span>
<span class="ge-stacked-label">Filter</span>
</button>
<div class="ge-filter-menu dropdown" id="ge-filter-menu" hidden>
<div class="ge-filter-submenu-label">Retained effects</div>
<button class="dropdown-item-compact" data-filter-action="effect-blur-gaussian">
<span class="dropdown-icon ge-blur-icon ge-blur-gaussian" aria-hidden="true"></span>
<span>Gaussian Blur (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-sharpen">
<span class="dropdown-icon" aria-hidden="true">◈</span>
<span>Sharpen (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-color-overlay">
<span class="dropdown-icon" aria-hidden="true">◐</span>
<span>Color Overlay (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-drop-shadow">
<span class="dropdown-icon" aria-hidden="true">◒</span>
<span>Drop Shadow (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-stroke">
<span class="dropdown-icon" aria-hidden="true">□</span>
<span>Stroke (retained)…</span>
</button>
<div class="ge-filter-submenu-label">Presets</div>
<button class="dropdown-item-compact" data-filter-action="effect-preset-soft-blur"><span>Soft Blur</span></button>
<button class="dropdown-item-compact" data-filter-action="effect-preset-crisp-detail"><span>Crisp Detail</span></button>
<button class="dropdown-item-compact" data-filter-action="effect-preset-soft-shadow"><span>Soft Shadow</span></button>
<button class="dropdown-item-compact" data-filter-action="effect-preset-white-outline"><span>White Outline</span></button>
<div class="ge-filter-submenu-label">Blur</div>
<button class="dropdown-item-compact" data-filter-action="blur-gaussian">
<span class="dropdown-icon ge-blur-icon ge-blur-gaussian" aria-hidden="true"></span>
<span>Gaussian Blur…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="blur-zoom">
<span class="dropdown-icon ge-blur-icon ge-blur-zoom" aria-hidden="true"></span>
<span>Zoom Blur…</span>
</button>
<div class="ge-menu-label">Enhance</div>
<button class="dropdown-item-compact" data-filter-action="dehaze"><span class="dropdown-icon" aria-hidden="true">≈</span><span>Haze Removal…</span></button>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-retained" aria-haspopup="true" aria-expanded="false"><span>Retained effects</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-retained">
<button class="dropdown-item-compact" data-filter-action="effect-blur-gaussian">
<span class="dropdown-icon ge-blur-icon ge-blur-gaussian" aria-hidden="true"></span>
<span>Gaussian Blur (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-sharpen">
<span class="dropdown-icon" aria-hidden="true">◈</span>
<span>Sharpen (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-color-overlay">
<span class="dropdown-icon" aria-hidden="true">◐</span>
<span>Color Overlay (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-drop-shadow">
<span class="dropdown-icon" aria-hidden="true">◒</span>
<span>Drop Shadow (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-stroke">
<span class="dropdown-icon" aria-hidden="true">□</span>
<span>Stroke (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-motion-blur">
<span class="dropdown-icon" aria-hidden="true">↔</span>
<span>Motion Blur (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-zoom-blur">
<span class="dropdown-icon" aria-hidden="true">✳</span>
<span>Zoom Blur (retained)…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="effect-pixelate">
<span class="dropdown-icon" aria-hidden="true">▦</span>
<span>Pixelate (retained)…</span>
</button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-presets" aria-haspopup="true" aria-expanded="false"><span>Presets</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-presets">
<button class="dropdown-item-compact" data-filter-action="effect-preset-soft-blur"><span>Soft Blur</span></button>
<button class="dropdown-item-compact" data-filter-action="effect-preset-crisp-detail"><span>Crisp Detail</span></button>
<button class="dropdown-item-compact" data-filter-action="effect-preset-soft-shadow"><span>Soft Shadow</span></button>
<button class="dropdown-item-compact" data-filter-action="effect-preset-white-outline"><span>White Outline</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-blur" aria-haspopup="true" aria-expanded="false"><span>Blur</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-blur">
<button class="dropdown-item-compact" data-filter-action="blur-gaussian">
<span class="dropdown-icon ge-blur-icon ge-blur-gaussian" aria-hidden="true"></span>
<span>Gaussian Blur…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="blur-zoom">
<span class="dropdown-icon ge-blur-icon ge-blur-zoom" aria-hidden="true"></span>
<span>Zoom Blur…</span>
</button>
<button class="dropdown-item-compact" data-filter-action="blur-motion"><span>Motion Blur…</span></button>
<button class="dropdown-item-compact" data-filter-action="radial-blur"><span>Radial Blur…</span></button>
<button class="dropdown-item-compact" data-filter-action="blur-box"><span>Box Blur…</span></button>
<button class="dropdown-item-compact" data-filter-action="blur-surface"><span>Surface Blur…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-sharpen" aria-haspopup="true" aria-expanded="false"><span>Sharpen</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-sharpen">
<button class="dropdown-item-compact" data-filter-action="sharpen"><span>Sharpen…</span></button>
<button class="dropdown-item-compact" data-filter-action="sharpen-edges"><span>Sharpen Edges…</span></button>
<button class="dropdown-item-compact" data-filter-action="sharpen-more"><span>Sharpen More…</span></button>
<button class="dropdown-item-compact" data-filter-action="unsharp-mask"><span>Unsharp Mask…</span></button>
<button class="dropdown-item-compact" data-filter-action="smart-sharpen"><span>Smart Sharpen…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-noise" aria-haspopup="true" aria-expanded="false"><span>Noise</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-noise">
<button class="dropdown-item-compact" data-filter-action="noise-add"><span>Add Noise…</span></button>
<button class="dropdown-item-compact" data-filter-action="noise-despeckle"><span>Despeckle…</span></button>
<button class="dropdown-item-compact" data-filter-action="reduce-noise"><span>Reduce Noise…</span></button>
<button class="dropdown-item-compact" data-filter-action="dust-scratches"><span>Dust &amp; Scratches…</span></button>
<button class="dropdown-item-compact" data-filter-action="noise-median"><span>Median…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-pixelate" aria-haspopup="true" aria-expanded="false"><span>Pixelate</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-pixelate">
<button class="dropdown-item-compact" data-filter-action="pixelate-mosaic"><span>Mosaic…</span></button>
<button class="dropdown-item-compact" data-filter-action="pixelate-crystallize"><span>Crystallize…</span></button>
<button class="dropdown-item-compact" data-filter-action="pixelate-mosaic-tiles"><span>Mosaic Tiles…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-stylize" aria-haspopup="true" aria-expanded="false"><span>Stylize</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-stylize">
<button class="dropdown-item-compact" data-filter-action="stylize-emboss"><span>Emboss…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-find-edges"><span>Find Edges…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-glowing-edges"><span>Glowing Edges…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-solarize"><span>Solarize…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-oil-paint"><span>Oil Paint…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-diffuse"><span>Diffuse…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-wind"><span>Wind…</span></button>
<button class="dropdown-item-compact" data-filter-action="stylize-trace-contour"><span>Trace Contour…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-sketch" aria-haspopup="true" aria-expanded="false"><span>Sketch</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-sketch">
<button class="dropdown-item-compact" data-filter-action="sketch-halftone-pattern"><span>Halftone Pattern…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-reticulation"><span>Reticulation…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-note-paper"><span>Note Paper…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-charcoal"><span>Charcoal…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-chalk-charcoal"><span>Chalk &amp; Charcoal…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-graphic-pen"><span>Graphic Pen…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-photocopy"><span>Photocopy…</span></button>
<button class="dropdown-item-compact" data-filter-action="sketch-water-paper"><span>Water Paper…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-artistic" aria-haspopup="true" aria-expanded="false"><span>Artistic</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-artistic">
<button class="dropdown-item-compact" data-filter-action="artistic-poster-edges"><span>Poster Edges…</span></button>
<button class="dropdown-item-compact" data-filter-action="artistic-cutout"><span>Cutout…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-brush" aria-haspopup="true" aria-expanded="false"><span>Brush Strokes</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-brush">
<button class="dropdown-item-compact" data-filter-action="brush-ink-outlines"><span>Ink Outlines…</span></button>
<button class="dropdown-item-compact" data-filter-action="brush-crosshatch"><span>Crosshatch…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-texture" aria-haspopup="true" aria-expanded="false"><span>Texture</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-texture">
<button class="dropdown-item-compact" data-filter-action="texture-stained-glass"><span>Stained Glass…</span></button>
<button class="dropdown-item-compact" data-filter-action="texture-grain"><span>Grain…</span></button>
<button class="dropdown-item-compact" data-filter-action="texture-texturizer"><span>Texturizer…</span></button>
<button class="dropdown-item-compact" data-filter-action="texture-patchwork"><span>Patchwork…</span></button>
<button class="dropdown-item-compact" data-filter-action="texture-craquelure"><span>Craquelure…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-distort" aria-haspopup="true" aria-expanded="false"><span>Distort</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-distort">
<button class="dropdown-item-compact" data-filter-action="distort-twirl"><span>Twirl…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-pinch"><span>Pinch…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-spherize"><span>Spherize…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-ripple"><span>Ripple…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-polar"><span>Polar Coordinates…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-lens-correction"><span>Lens Correction…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-ocean-ripple"><span>Ocean Ripple…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-glass"><span>Glass…</span></button>
<button class="dropdown-item-compact" data-filter-action="distort-shear"><span>Shear…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-render" aria-haspopup="true" aria-expanded="false"><span>Render</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-render">
<button class="dropdown-item-compact" data-filter-action="render-clouds"><span>Clouds…</span></button>
<button class="dropdown-item-compact" data-filter-action="render-difference-clouds"><span>Difference Clouds…</span></button>
<button class="dropdown-item-compact" data-filter-action="render-lens-flare"><span>Lens Flare…</span></button>
<button class="dropdown-item-compact" data-filter-action="render-fibers"><span>Fibers…</span></button>
</div>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="filter-other" aria-haspopup="true" aria-expanded="false"><span>Other</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="filter-other">
<button class="dropdown-item-compact" data-filter-action="other-offset"><span>Offset…</span></button>
<button class="dropdown-item-compact" data-filter-action="other-custom"><span>Custom…</span></button>
<button class="dropdown-item-compact" data-filter-action="other-maximum"><span>Maximum…</span></button>
<button class="dropdown-item-compact" data-filter-action="other-minimum"><span>Minimum…</span></button>
</div>
</div>
</div>
<span class="ge-topbar-sep"></span>
<div class="ge-3d-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-3d-menu-btn" title="3D" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2 3 7v10l9 5 9-5V7z"/><path d="M3 7l9 5 9-5"/><path d="M12 12v10"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">3D</span>
</button>
<div class="ge-3d-menu dropdown" id="ge-3d-menu" hidden>
<div class="ge-menu-label">New 3D</div>
<button class="dropdown-item-compact" data-3d-action="from-file" disabled title="3D is not available in this build"><span>New 3D Layer from File…</span></button>
<button class="dropdown-item-compact" data-3d-action="from-layer" disabled title="3D is not available in this build"><span>New Mesh from Layer…</span></button>
<div class="ge-menu-label">Render</div>
<button class="dropdown-item-compact" data-3d-action="render" disabled title="3D is not available in this build"><span>Render 3D Layer</span></button>
<div class="ge-menu-label">3D Printing</div>
<button class="dropdown-item-compact" data-3d-action="print" disabled title="3D is not available in this build"><span>Export as 3D…</span></button>
<div class="dropdown-section-divider"></div>
<button class="dropdown-item-compact" data-3d-action="about" disabled title="3D is not available in this build"><span>About 3D support</span></button>
</div>
</div>
<div class="ge-view-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-view-menu-btn" title="Canvas view" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">View</span>
</button>
<div class="ge-view-menu dropdown" id="ge-view-menu" hidden>
<div class="ge-menu-label">Overlays</div>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="rulers"><span class="dropdown-icon ge-view-check">✓</span><span>Rulers</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="grid"><span class="dropdown-icon ge-view-check">✓</span><span>Grid</span></button>
<label class="ge-view-grid-size"><span>Grid size</span><input id="ge-grid-size" type="number" min="2" max="1000" step="1" value="16"><span>px</span></label>
<div class="ge-menu-label">Snapping</div>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="snap"><span class="dropdown-icon ge-view-check">✓</span><span>Snap</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="snap-grid"><span class="dropdown-icon ge-view-check">✓</span><span>Snap to grid</span></button>
<button class="dropdown-item-compact" data-view-action="new-h-guide" title="Add a horizontal guide across the middle"><span class="dropdown-icon">⊢</span><span>New horizontal guide</span></button>
<button class="dropdown-item-compact" data-view-action="new-v-guide" title="Add a vertical guide down the middle"><span class="dropdown-icon">⊣</span><span>New vertical guide</span></button>
<button class="dropdown-item-compact" data-view-action="clear-guides"><span class="dropdown-icon">×</span><span>Clear guides</span></button>
<div class="ge-menu-label">Panels</div>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-options"><span class="dropdown-icon ge-view-check">✓</span><span>Tool Options</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-layers"><span class="dropdown-icon ge-view-check">✓</span><span>Layers</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-swatches"><span class="dropdown-icon ge-view-check">✓</span><span>Swatches</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-gradients"><span class="dropdown-icon ge-view-check">✓</span><span>Gradients</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-patterns"><span class="dropdown-icon ge-view-check">✓</span><span>Patterns</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-properties"><span class="dropdown-icon ge-view-check">✓</span><span>Properties</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-adjustments"><span class="dropdown-icon ge-view-check">✓</span><span>Adjustments</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-histogram"><span class="dropdown-icon ge-view-check">✓</span><span>Histogram</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-info"><span class="dropdown-icon ge-view-check">✓</span><span>Info</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-channels"><span class="dropdown-icon ge-view-check">✓</span><span>Channels</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-paths"><span class="dropdown-icon ge-view-check">✓</span><span>Paths</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-character"><span class="dropdown-icon ge-view-check">✓</span><span>Character</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-navigator"><span class="dropdown-icon ge-view-check">✓</span><span>Navigator</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-history"><span class="dropdown-icon ge-view-check">✓</span><span>History</span></button>
<button class="dropdown-item-compact ge-view-toggle" role="menuitemcheckbox" data-view-action="panel-actions"><span class="dropdown-icon ge-view-check">✓</span><span>Actions</span></button>
<div class="ge-menu-label">Panel layout</div>
<button class="dropdown-item-compact" data-view-action="panel-show-all"><span class="dropdown-icon">▣</span><span>Show all</span></button>
<button class="dropdown-item-compact" data-view-action="panel-hide-all"><span class="dropdown-icon">▢</span><span>Hide all</span></button>
<button class="dropdown-item-compact" data-view-action="panel-reset"><span class="dropdown-icon">↺</span><span>Reset to default</span></button>
<div class="ge-menu-label">Screen</div>
<button class="dropdown-item-compact" data-view-action="screen-mode" title="Toggle a distraction-free, maximized screen mode"><span class="dropdown-icon">⛶</span><span>Screen Mode</span></button>
</div>
</div>
<div class="ge-plugins-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-plugins-menu-btn" title="Plugins" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7h4a2 2 0 1 1 4 0h4v4a2 2 0 0 0 0 4v4H4v-4a2 2 0 0 0 0-4z"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">Plugins</span>
</button>
<div class="ge-plugins-menu dropdown" id="ge-plugins-menu" hidden>
<div class="ge-menu-label">Plugins</div>
<button class="dropdown-item-compact" data-plugins-action="browse" disabled title="Plugins are not available in this build"><span>Browse Plugins…</span></button>
<button class="dropdown-item-compact" data-plugins-action="manage" disabled title="Plugins are not available in this build"><span>Manage Plugins…</span></button>
<div class="dropdown-section-divider"></div>
<button class="dropdown-item-compact" data-plugins-action="script" disabled title="Plugins are not available in this build"><span>Run Editor Script…</span></button>
</div>
</div>
<div class="ge-window-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-window-menu-btn" title="Window panels" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">Window</span>
</button>
<div class="ge-window-menu dropdown" id="ge-window-menu" hidden>
<button type="button" class="dropdown-item-compact ge-menu-parent" data-submenu="window-workspace" aria-haspopup="true" aria-expanded="false"><span>Workspace</span><span class="ge-submenu-caret">›</span></button>
<div class="ge-submenu" data-submenu-panel="window-workspace">
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="workspace-essentials"><span class="dropdown-icon ge-window-check">●</span><span>Essentials</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="workspace-photography"><span class="dropdown-icon ge-window-check">●</span><span>Photography</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="workspace-painting"><span class="dropdown-icon ge-window-check">●</span><span>Painting</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="workspace-graphic"><span class="dropdown-icon ge-window-check">●</span><span>Graphic &amp; Web</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="workspace-minimal"><span class="dropdown-icon ge-window-check">●</span><span>Minimal</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="workspace-custom"><span class="dropdown-icon ge-window-check">●</span><span>Custom</span></button>
<div class="ge-submenu-sep"></div>
<button type="button" class="dropdown-item-compact ge-window-save" data-window-action="workspace-save"><span class="dropdown-icon">+</span><span>Save Current</span></button>
</div>
<div class="ge-menu-label">Panels</div>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="quick-edit"><span class="dropdown-icon ge-window-check">●</span><span>Quick Edit</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="options"><span class="dropdown-icon ge-window-check">●</span><span>Tool Options</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="layers"><span class="dropdown-icon ge-window-check">●</span><span>Layers</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="properties"><span class="dropdown-icon ge-window-check">●</span><span>Properties</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="character"><span class="dropdown-icon ge-window-check">●</span><span>Character</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="adjustments"><span class="dropdown-icon ge-window-check">●</span><span>Adjustments</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="swatches"><span class="dropdown-icon ge-window-check">●</span><span>Swatches</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="gradients"><span class="dropdown-icon ge-window-check">●</span><span>Gradients</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="channels"><span class="dropdown-icon ge-window-check">●</span><span>Channels</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="paths"><span class="dropdown-icon ge-window-check">●</span><span>Paths</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="patterns"><span class="dropdown-icon ge-window-check">●</span><span>Patterns</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="histogram"><span class="dropdown-icon ge-window-check">●</span><span>Histogram</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="info"><span class="dropdown-icon ge-window-check">●</span><span>Info</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="navigator"><span class="dropdown-icon ge-window-check">●</span><span>Navigator</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="history"><span class="dropdown-icon ge-window-check">●</span><span>History</span></button>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="actions"><span class="dropdown-icon ge-window-check">●</span><span>Actions</span></button>
<div class="ge-menu-label">Help</div>
<button class="dropdown-item-compact ge-window-toggle" role="menuitemcheckbox" aria-checked="false" data-window-action="shortcuts"><span class="dropdown-icon ge-window-check">●</span><span>Keyboard Shortcuts</span></button>
</div>
</div>
<div class="ge-help-wrap">
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-help-menu-btn" title="Help" aria-haspopup="true">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg><span class="ge-stacked-caret">▾</span></span>
<span class="ge-stacked-label">Help</span>
</button>
<div class="ge-help-menu dropdown" id="ge-help-menu" hidden>
<div class="ge-menu-label">Help</div>
<button class="dropdown-item-compact" data-help-action="shortcuts"><span>Keyboard Shortcuts</span></button>
<button class="dropdown-item-compact" data-help-action="about"><span>About Ajax Image Editor</span></button>
</div>
</div>
</div>
<div class="ge-topbar-right">
<span class="ge-alpha-badge" title="This editor is in active development — expect rough edges">ALPHA</span>
<button class="ge-btn ge-btn-sm" id="ge-shortcuts-btn" title="Keyboard shortcuts (?)" aria-label="Shortcuts">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="position:relative;top:2px;"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10"/></svg>
</button>
<button class="ge-btn ge-btn-sm" id="ge-maximize-toggle" title="Maximize editor" aria-label="Maximize editor" aria-pressed="false">
<svg class="ge-max-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
</button>
<button class="ge-btn ge-btn-sm ge-stacked-btn" id="ge-import-topbar" title="Import image as layer">
<span class="ge-stacked-glyph"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v12"/><polyline points="7 8 12 3 17 8"/><path d="M5 14v5h14v-5"/></svg></span>
<span class="ge-stacked-label">IMPORT</span>
@@ -161,6 +536,7 @@ export function buildTopbar() {
<svg hidden class="ge-save-state-icon ge-save-state-dirty" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 3h12l4 4v14H4z"/><path d="M8 3v6h8V3"/><path d="m16 3 6 6m0-6-6 6" stroke="var(--fg)" stroke-width="3"/></svg>
<svg class="ge-save-state-icon ge-save-state-saved" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>
</span>
<span class="ge-stacked-label ge-save-action-label">SAVE</span>
<span class="ge-stacked-label ge-save-label" id="ge-draft-status" role="status" aria-live="polite">Saved</span>
</button>
<div class="ge-save-menu dropdown" id="ge-save-menu" hidden>
@@ -179,6 +555,10 @@ export function buildTopbar() {
<span class="dropdown-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></span>
<span>Export image...</span>
</button>
<button class="dropdown-item-compact" id="ge-export-png" title="Download the flattened image as a PNG file">
<span class="dropdown-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 15l4-4 5 5"/><circle cx="9" cy="8" r="1.3"/></svg></span>
<span>Save as PNG</span>
</button>
<div class="dropdown-section-divider"></div>
<div class="dropdown-section-label">Project</div>
<button class="dropdown-item-compact" id="ge-save-project" title="Save layered project (.json) — keeps every layer editable for later">
@@ -200,7 +580,15 @@ export function buildZoomFooter() {
const footer = document.createElement('div');
footer.className = 'ge-editor-footer';
footer.innerHTML = `
<span class="ge-canvas-size" id="ge-canvas-size" title="Canvas size" hidden></span>
<div class="ge-footer-history" role="group" aria-label="History">
<button class="ge-btn ge-btn-sm" id="ge-undo" title="Undo" aria-label="Undo">↩</button>
<button class="ge-btn ge-btn-sm" id="ge-redo" title="Redo" aria-label="Redo">↪</button>
<button class="ge-btn ge-btn-sm" id="ge-history-btn" title="History — click an entry to jump to that state" aria-label="History"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 4v6h6"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/><polyline points="12 7 12 12 16 14"/></svg></button>
<button class="ge-btn ge-btn-sm" id="ge-compare-btn" title="Show the document before editing" aria-label="Show the document before editing" aria-pressed="false"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v18"/><path d="M5 7h14M5 17h14"/></svg></button>
</div>
<span class="ge-status-tool" id="ge-status-tool" aria-live="polite"></span>
<span class="ge-canvas-size" id="ge-canvas-size" title="Document size"></span>
<span class="ge-status-model" id="ge-status-model" title="AI edit model"></span>
<div class="ge-footer-zoom" role="group" aria-label="Canvas zoom">
<button class="ge-btn ge-btn-sm" id="ge-zoom-out" title="Zoom out" aria-label="Zoom out">&minus;</button>
<span class="ge-zoom-stack" aria-live="off">
+34 -2
View File
@@ -65,6 +65,38 @@ export function transformPopupHTML() {
<button type="button" data-spin="up" tabindex="-1" aria-label="Rotate +1°">+</button>
</span>
</div>
<div class="ge-transform-field">
<label>⇱</label>
<input type="number" class="ge-transform-popup-input" id="ge-transform-skew-x" step="1" value="0" aria-label="Horizontal skew" />
<span class="ge-transform-spin" data-spin-for="ge-transform-skew-x">
<button type="button" data-spin="down" tabindex="-1" aria-label="Skew X -1°">−</button>
<button type="button" data-spin="up" tabindex="-1" aria-label="Skew X +1°">+</button>
</span>
</div>
<div class="ge-transform-field">
<label>⇲</label>
<input type="number" class="ge-transform-popup-input" id="ge-transform-skew-y" step="1" value="0" aria-label="Vertical skew" />
<span class="ge-transform-spin" data-spin-for="ge-transform-skew-y">
<button type="button" data-spin="down" tabindex="-1" aria-label="Skew Y -1°">−</button>
<button type="button" data-spin="up" tabindex="-1" aria-label="Skew Y +1°">+</button>
</span>
</div>
<div class="ge-transform-field">
<label>⤒</label>
<input type="number" class="ge-transform-popup-input" id="ge-transform-persp-x" step="1" value="0" aria-label="Horizontal perspective" />
<span class="ge-transform-spin" data-spin-for="ge-transform-persp-x">
<button type="button" data-spin="down" tabindex="-1" aria-label="Perspective X -1">−</button>
<button type="button" data-spin="up" tabindex="-1" aria-label="Perspective X +1">+</button>
</span>
</div>
<div class="ge-transform-field">
<label>⤓</label>
<input type="number" class="ge-transform-popup-input" id="ge-transform-persp-y" step="1" value="0" aria-label="Vertical perspective" />
<span class="ge-transform-spin" data-spin-for="ge-transform-persp-y">
<button type="button" data-spin="down" tabindex="-1" aria-label="Perspective Y -1">−</button>
<button type="button" data-spin="up" tabindex="-1" aria-label="Perspective Y +1">+</button>
</span>
</div>
<span class="ge-transform-quick" aria-label="Transform actions">
<button type="button" class="ge-transform-quick-btn" id="ge-transform-flip-h" title="Flip horizontally" aria-label="Flip horizontally">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v18"/><path d="m8 7-4 5 4 5"/><path d="m16 7 4 5-4 5"/></svg>
@@ -79,8 +111,8 @@ export function transformPopupHTML() {
<button type="button" class="ge-btn ge-btn-sm" id="ge-transform-cancel-btn">Cancel</button>
<button type="button" class="ge-btn ge-btn-sm ge-btn-primary" id="ge-transform-apply">Apply</button>
</div>
<label class="ge-transform-preserve-field">
<input type="checkbox" id="ge-transform-preserve-source" />
<label class="ge-transform-preserve-field" title="Preserve source pixels (applies the transform non-destructively)">
<input type="checkbox" id="ge-transform-preserve-source" aria-label="Preserve source pixels" />
<span>Preserve source pixels</span>
</label>
<p class="ge-transform-popup-hint">Type <strong>-</strong> before W / H to flip.</p>
+319
View File
@@ -0,0 +1,319 @@
/**
* Tool-aware canvas context menu (Photoshop-style right-click).
*
* A right-click on the image opens a menu whose items depend on the
* active tool: paint tools get brush size/presets, selection tools get
* select/feather/expand actions, the crop tool gets Apply/Cancel, the
* transform tool gets commit/cancel, and so on. Every action re-uses the
* existing control ops (window.geEditorControl.invoke) or clicks the
* existing topbar menu items, so there is a single source of truth.
*
* Wire it with wireCanvasContextMenu(canvasArea) from canvas-events.js.
*/
import { state } from './state.js';
const PAINT = ['brush', 'eraser', 'clone', 'heal', 'dodge', 'burn', 'smudge', 'inpaint', 'rembg', 'sharpen'];
const SELECT = ['marquee', 'lasso', 'wand', 'quickselect', 'objectselect', 'pen', 'path', 'sam'];
const TRANSFORM = ['move', 'transform'];
let rootMenu = null;
let subMenu = null;
let cleanups = [];
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const hasSelection = () => !!(state.wandMask || (state.lassoPoints && state.lassoPoints.length >= 3));
function invoke(op, params) {
try { return window.geEditorControl?.invoke(op, params || {}); } catch (err) { console.warn('[ge-canvas-menu]', op, err); }
}
function clickEl(selector) { document.querySelector(selector)?.click(); }
function clickMenu(selector) { document.querySelector(selector)?.click(); }
function dispatchEscape() {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
}
function stepBrushSize(factor) {
const slider = document.querySelector('.ge-size-slider');
if (!slider) return;
const next = Math.max(1, Math.min(800, Math.round((state.brushSize || 1) * factor)));
slider.value = String(Math.round(Math.log(next) / Math.log(800) * 1000));
slider.dispatchEvent(new Event('input', { bubbles: true }));
}
function applyPresetId(id) {
const sel = document.getElementById('ge-brush-preset');
if (!sel) return;
sel.value = id;
sel.dispatchEvent(new Event('change', { bubbles: true }));
}
function presetItems() {
const sel = document.getElementById('ge-brush-preset');
if (!sel) return [];
return [...sel.options].map((opt) => ({
label: opt.textContent,
checked: opt.value === sel.value,
onSelect: () => applyPresetId(opt.value),
}));
}
function promptNumber(message, fallback, run) {
const raw = window.prompt(message, String(fallback));
if (raw == null) return;
const value = Number(raw);
if (Number.isFinite(value)) run(value);
}
/** Build the menu item descriptors for a tool. Exported for tests. */
export function buildCanvasMenuItems(tool) {
const items = [];
const push = (...x) => items.push(...x);
const sep = () => items.push({ type: 'sep' });
const sel = hasSelection();
if (PAINT.includes(tool)) {
push(
{ label: 'Increase Brush Size', hint: ']', onSelect: () => stepBrushSize(1.25) },
{ label: 'Decrease Brush Size', hint: '[', onSelect: () => stepBrushSize(0.8) },
{ label: 'Brush Preset', submenu: () => presetItems() },
{
label: 'Pixel Brush',
checked: !!state.brushPixel,
onSelect: () => applyPresetId(state.brushPixel ? 'hard-round' : 'pixel-1px'),
},
);
sep();
} else if (SELECT.includes(tool)) {
push(
{ label: 'Select All', hint: 'Ctrl+A', onSelect: () => invoke('selection.selectAll') },
{ label: 'Deselect', hint: 'Ctrl+D', disabled: !sel, onSelect: () => invoke('selection.deselect') },
{ label: 'Inverse Selection', disabled: !sel, onSelect: () => invoke('selection.invert') },
{ label: 'Transform Selection', disabled: !sel, onSelect: () => clickMenu('[data-selection-action="transform"]') },
{ label: 'Refine Edge…', disabled: !sel, onSelect: () => clickMenu('[data-selection-action="refine"]') },
);
sep();
push(
{ label: 'Feather…', disabled: !sel, onSelect: () => promptNumber('Feather radius (px)', 8, (v) => invoke('selection.feather', { radius: v })) },
{ label: 'Expand', disabled: !sel, onSelect: () => invoke('selection.expand', { amount: 4 }) },
{ label: 'Contract', disabled: !sel, onSelect: () => invoke('selection.contract', { amount: 4 }) },
);
if (sel) {
push(
{ label: 'Fill Selection', onSelect: () => invoke('selection.fill', { color: state.color }) },
{ label: 'Delete Selection', hint: 'Del', onSelect: () => invoke('selection.delete') },
);
}
sep();
} else if (tool === 'crop' || state.cropRect) {
const cropping = !!(state.cropRect || state.cropping || state.cropMoving);
push(
{ label: 'Apply Crop', disabled: !cropping, onSelect: () => clickEl('.ge-crop-apply-btn') },
{ label: 'Cancel Crop', hint: 'Esc', disabled: !cropping, onSelect: () => dispatchEscape() },
);
sep();
} else if (TRANSFORM.includes(tool) || state.transformActive) {
push(
{ label: 'Commit Transform', hint: 'Enter', disabled: !state.transformActive, onSelect: () => invoke('transform.apply') },
{ label: 'Cancel Transform', hint: 'Esc', disabled: !state.transformActive, onSelect: () => invoke('transform.cancel') },
{ label: 'Free Transform', hint: 'Ctrl+T', disabled: state.transformActive, onSelect: () => invoke('transform.start') },
);
sep();
} else if (tool === 'text') {
push(
{ label: 'Add Text Layer', onSelect: () => invoke('text.add', { text: 'Text' }) },
{ label: 'Rasterize Text', onSelect: () => invoke('layers.rasterize') },
);
sep();
} else if (tool === 'eyedropper') {
push(
{ label: 'Copy Color Hex', onSelect: () => { try { navigator.clipboard?.writeText(state.color || ''); } catch (_) {} } },
{ label: 'Swap Foreground / Background', onSelect: () => clickEl('#ge-swap-colors') },
);
sep();
} else if (tool === 'hand') {
push(
{ label: 'Zoom In', hint: 'Ctrl++', onSelect: () => clickEl('#ge-zoom-in') },
{ label: 'Zoom Out', hint: 'Ctrl+-', onSelect: () => clickEl('#ge-zoom-out') },
{ label: 'Fit on Screen', hint: 'Ctrl+0', onSelect: () => clickEl('#ge-zoom-100') },
);
sep();
} else if (tool === 'gradient' || tool === 'shape') {
push(
{ label: 'Fill Selection with Foreground', disabled: !sel, onSelect: () => invoke('selection.fill', { color: state.color }) },
);
sep();
}
if (!SELECT.includes(tool) && sel) {
push(
{ label: 'Deselect', hint: 'Ctrl+D', onSelect: () => invoke('selection.deselect') },
{ label: 'Inverse Selection', onSelect: () => invoke('selection.invert') },
{ label: 'Fill Selection', onSelect: () => invoke('selection.fill', { color: state.color }) },
{ label: 'Delete Selection', hint: 'Del', onSelect: () => invoke('selection.delete') },
);
sep();
}
push(
{ label: 'Cut', hint: 'Ctrl+X', disabled: !sel, onSelect: () => invoke('selection.copy', { cut: true }) },
{ label: 'Copy', hint: 'Ctrl+C', disabled: !sel, onSelect: () => invoke('selection.copy') },
{ label: 'Paste', hint: 'Ctrl+V', onSelect: () => invoke('selection.paste') },
sep(),
{ label: 'Select All', hint: 'Ctrl+A', onSelect: () => invoke('selection.selectAll') },
{ label: 'Deselect', hint: 'Ctrl+D', disabled: !sel, onSelect: () => invoke('selection.deselect') },
sep(),
{ label: 'Rotate 90° CW', onSelect: () => invoke('layer.rotate', { degrees: 90 }) },
{ label: 'Rotate 180°', onSelect: () => invoke('layer.rotate', { degrees: 180 }) },
{ label: 'Flip Horizontal', onSelect: () => invoke('layer.flip', { axis: 'h' }) },
{ label: 'Flip Vertical', onSelect: () => invoke('layer.flip', { axis: 'v' }) },
sep(),
{ label: 'Undo', hint: 'Ctrl+Z', onSelect: () => invoke('history.undo') },
{ label: 'Redo', hint: 'Ctrl+Shift+Z', onSelect: () => invoke('history.redo') },
);
return items;
}
function buildItemEl(item, close) {
if (item.type === 'sep') {
const hr = document.createElement('div');
hr.className = 'ge-canvas-menu-sep';
return hr;
}
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'ge-canvas-menu-item';
btn.setAttribute('role', 'menuitem');
btn.disabled = !!item.disabled;
if (item.checked) btn.classList.add('is-checked');
const lead = document.createElement('span');
lead.className = 'ge-canvas-menu-lead';
lead.textContent = item.checked ? '✓' : '';
const label = document.createElement('span');
label.className = 'ge-canvas-menu-label';
label.textContent = item.label;
btn.append(lead, label);
if (item.submenu) {
btn.classList.add('has-submenu');
const caret = document.createElement('span');
caret.className = 'ge-canvas-menu-caret';
caret.textContent = '›';
btn.appendChild(caret);
btn.addEventListener('pointerenter', () => openSubmenu(btn, item.submenu));
} else if (item.hint) {
const hint = document.createElement('span');
hint.className = 'ge-canvas-menu-hint';
hint.textContent = item.hint;
btn.appendChild(hint);
}
btn.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
if (item.disabled) return;
if (item.submenu) return;
try { item.onSelect?.(); } finally { close(); }
});
btn.addEventListener('pointerenter', () => { closeSubmenu(); });
return btn;
}
function buildMenuEl(items, close) {
const menu = document.createElement('div');
menu.className = 'ge-canvas-menu';
menu.setAttribute('role', 'menu');
for (const item of items) menu.appendChild(buildItemEl(item, close));
return menu;
}
function placeMenu(menu, x, y) {
menu.style.left = '0px';
menu.style.top = '0px';
document.body.appendChild(menu);
const rect = menu.getBoundingClientRect();
const left = clamp(x, 4, Math.max(4, window.innerWidth - rect.width - 4));
const top = clamp(y, 4, Math.max(4, window.innerHeight - rect.height - 4));
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
}
function closeSubmenu() {
subMenu?.remove();
subMenu = null;
}
function openSubmenu(anchor, spec) {
closeSubmenu();
const items = typeof spec === 'function' ? spec() : spec;
if (!items || !items.length) return;
subMenu = buildMenuEl(items, closeAll);
subMenu.classList.add('ge-canvas-menu-sub');
document.body.appendChild(subMenu);
const a = anchor.getBoundingClientRect();
const r = subMenu.getBoundingClientRect();
let left = a.right - 4;
if (left + r.width > window.innerWidth - 4) left = a.left - r.width + 4;
const top = clamp(a.top - 4, 4, Math.max(4, window.innerHeight - r.height - 4));
subMenu.style.left = `${left}px`;
subMenu.style.top = `${top}px`;
}
function moveFocus(menu, delta) {
const focusables = [...menu.querySelectorAll('.ge-canvas-menu-item:not([disabled])')];
if (!focusables.length) return;
const current = focusables.indexOf(document.activeElement);
const next = clamp((current < 0 ? (delta > 0 ? -1 : 0) : current) + delta, 0, focusables.length - 1);
focusables[next]?.focus();
}
export function closeCanvasContextMenu() {
for (const fn of cleanups) { try { fn(); } catch (_) {} }
cleanups = [];
closeSubmenu();
rootMenu?.remove();
rootMenu = null;
}
/** Open the tool-aware menu at a pointer event (or {clientX, clientY}). */
export function openCanvasContextMenu(event) {
if (!state.editorOpen || !event) return;
closeCanvasContextMenu();
const menu = buildMenuEl(buildCanvasMenuItems(state.tool), closeCanvasContextMenu);
placeMenu(menu, event.clientX, event.clientY);
rootMenu = menu;
menu.querySelector('.ge-canvas-menu-item:not([disabled])')?.focus();
const onDown = (ev) => {
if (menu.contains(ev.target)) return;
if (subMenu && subMenu.contains(ev.target)) return;
closeCanvasContextMenu();
};
const onKey = (ev) => {
if (ev.key === 'Escape') { ev.preventDefault(); closeCanvasContextMenu(); }
else if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') { ev.preventDefault(); moveFocus(menu, ev.key === 'ArrowDown' ? 1 : -1); }
else if (ev.key === 'Enter') {
const active = document.activeElement;
if (active?.classList?.contains('ge-canvas-menu-item')) { ev.preventDefault(); active.click(); }
}
};
const onAway = () => closeCanvasContextMenu();
document.addEventListener('pointerdown', onDown, true);
document.addEventListener('keydown', onKey, true);
window.addEventListener('resize', onAway);
window.addEventListener('blur', onAway);
cleanups.push(() => document.removeEventListener('pointerdown', onDown, true));
cleanups.push(() => document.removeEventListener('keydown', onKey, true));
cleanups.push(() => window.removeEventListener('resize', onAway));
cleanups.push(() => window.removeEventListener('blur', onAway));
}
/** Wire right-click on the image (and the surrounding canvas area). */
export function wireCanvasContextMenu(canvasArea, { signal } = {}) {
const canvas = state.mainCanvas;
if (!canvas) return;
const opts = signal ? { signal } : undefined;
canvas.addEventListener('contextmenu', (event) => {
event.preventDefault();
openCanvasContextMenu(event);
}, opts);
canvasArea?.addEventListener('contextmenu', (event) => {
if (event.target === canvas) return;
if (event.target.closest?.('input, textarea, .ge-canvas-menu')) return;
event.preventDefault();
openCanvasContextMenu(event);
}, opts);
}
+113 -8
View File
@@ -16,6 +16,12 @@
* touchmove 1 finger → continueDraw
* touchend → endDraw; touchcancel → cancelDraw
* touchstart 2 fingers → pinch-zoom + 2-finger pan
* 2-finger tap → undo (onTwoFingerTap)
* 3-finger tap → redo (onThreeFingerTap)
*
* A multi-finger gesture reverts the accidental single-finger stroke
* begun by the first finger to land (cancelDraw), so a pinch or a
* tap never leaves a stray dab behind.
*
* Pan:
* Hand tool / held Space / middle mouse can drag directly over the
@@ -33,6 +39,8 @@
* cancelDraw?: () => void,
* updateBrushCursor: (e: Event) => void,
* syncZoomControls?: () => void,
* onTwoFingerTap?: () => void,
* onThreeFingerTap?: () => void,
* }} ctx
*/
import { state } from './state.js';
@@ -42,14 +50,35 @@ import {
nextPanOffset,
syncPanCursor,
} from './canvas-navigation.js';
import { wireCanvasContextMenu } from './canvas-context-menu.js';
let canvasWindowBindings;
export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw, cancelDraw, updateBrushCursor, updateEyedropperPreview, syncZoomControls, onViewportChange }) {
export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw, cancelDraw, updateBrushCursor, updateEyedropperPreview, syncZoomControls, onViewportChange, onTwoFingerTap, onThreeFingerTap }) {
canvasWindowBindings?.abort();
canvasWindowBindings = new AbortController();
const { signal } = canvasWindowBindings;
let suppressMouseUntil = 0;
// Tool-aware right-click menu on the image and the surrounding area.
wireCanvasContextMenu(canvasArea, { signal });
// Window-level drag handlers exist so a gesture can continue past the
// canvas edge. But the direct-manipulation selection/crop rects are
// built from raw pointer coords, so pointer motion over editor chrome
// (topbar, toolbars, panels) must not feed the rect. Brush/transform/
// move/resize gestures DO keep tracking over chrome — overshooting the
// canvas edge is normal for those and was the reason for the window
// binding.
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';
const isUiChrome = e => !!e.target?.closest?.(UI_CHROME_SELECTOR);
// Only in-progress selection/crop drags are affected by the chrome
// guard. A committed cropRect/selection is a resting state — clicking
// its Apply button must not be treated as "strayed onto chrome".
const directGestureActive = () => !!(
state.selectionMoving || state.marqueeActive ||
state.lassoActive || (state.lassoPoints && state.lassoPoints.length) ||
state.cropping || state.cropMoving
);
// Mouse — mousedown stays on the canvas; mousemove/up are bound to
// the WINDOW so a drag can continue (and end) past the canvas edge.
// Critical for the Resize tool where users overshoot.
@@ -60,12 +89,25 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
});
window.addEventListener('mousemove', (e) => {
if (Date.now() < suppressMouseUntil) return;
// Only shield the raw-coordinate selection/crop rects from chrome.
if (isUiChrome(e) && directGestureActive()) return;
continueDraw(e);
}, { signal });
window.addEventListener('mouseup', (e) => {
if (Date.now() < suppressMouseUntil) return;
// Releasing over chrome commits the gesture; the marquee/crop end
// paths clamp the rect to the document, so an overshoot onto a panel
// is kept (Photoshop behaviour), not discarded.
endDraw(e);
}, { signal });
// A tool switch happens on the tool button, before the release. Cancel
// any in-progress direct gesture first so its move is reverted rather
// than committed by the subsequent chrome mouseup. Explicit tool
// switches are the only place we abandon a selection/crop gesture.
window.addEventListener('mousedown', (e) => {
if (!directGestureActive()) return;
if (e.target?.closest?.('.ge-tool-btn')) cancelDraw?.();
}, { capture: true, signal });
// Preserve pressure and browser-coalesced samples for pen input.
// Compatibility mouse events are briefly suppressed to avoid a
// duplicate stroke after pointerup.
@@ -94,12 +136,15 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
};
state.mainCanvas.addEventListener('pointerup', endPen);
state.mainCanvas.addEventListener('pointercancel', endPen);
// Lasso can start OUTSIDE the canvas — fallback mousedown on the
// surrounding canvas-area so the user can begin a lasso path in
// the empty space around the image. Other tools stay canvas-only.
// Lasso 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
// space around the image. Other tools stay canvas-only.
canvasArea.addEventListener('mousedown', (e) => {
if (state.tool !== 'lasso') return;
if (state.tool !== 'lasso' && state.tool !== 'crop') return;
if (e.target === state.mainCanvas) return; // already handled
// Ignore presses on editor chrome inside the area (the crop Apply panel,
// 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;
beginDraw(e);
});
state.mainCanvas.addEventListener('mouseenter', (e) => {
@@ -121,11 +166,22 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
});
// Touch — single finger draws; two fingers pan + pinch-zoom.
// A quick two-finger tap = undo, a quick three-finger tap = redo.
let multiActive = false;
let multiStartDist = 0;
let multiStartZoom = 1;
let multiStartCenter = { x: 0, y: 0 };
let multiStartPan = { x: 0, y: 0 };
// Tap-gesture tracking (mobile undo/redo). A gesture starts when the
// first finger lands and is decided when the last finger lifts: at
// most TAP_MAX_MS elapsed, the centre never moved more than
// TAP_MAX_MOVE px, and the peak finger count was 2 (undo) or 3 (redo).
const TAP_MAX_MS = 300;
const TAP_MAX_MOVE = 12;
let gesturePeakTouches = 0;
let gestureStartAt = 0;
let gestureStartCenter = null;
let gestureMoved = false;
const touchInfo = (e) => {
const t1 = e.touches[0], t2 = e.touches[1];
const cx = (t1.clientX + t2.clientX) / 2;
@@ -134,12 +190,30 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
const dy = t2.clientY - t1.clientY;
return { cx, cy, dist: Math.hypot(dx, dy) };
};
const touchCenter = (e) => {
if (!e.touches || !e.touches.length) return null;
let x = 0, y = 0;
for (const t of e.touches) { x += t.clientX; y += t.clientY; }
return { x: x / e.touches.length, y: y / e.touches.length };
};
const applyCanvasOffset = (x, y) => applyCanvasPan(state, canvasArea, x, y);
state.mainCanvas.addEventListener('touchstart', (e) => {
e.preventDefault();
if (gesturePeakTouches === 0) {
// First contact of a fresh gesture (finger counts are read from
// e.touches so simultaneous touches are handled too).
gesturePeakTouches = Math.max(1, e.touches.length);
gestureStartAt = Date.now();
gestureStartCenter = touchCenter(e);
gestureMoved = false;
} else if (e.touches.length > gesturePeakTouches) {
gesturePeakTouches = e.touches.length;
}
if (e.touches.length >= 2) {
// End any in-progress single-finger draw before switching modes.
if (!multiActive) endDraw();
// Revert the accidental single-finger stroke the first finger
// began, then switch to pinch/pan so multi-finger input never
// leaves a stray dab behind.
if (!multiActive) cancelDraw?.();
multiActive = true;
const info = touchInfo(e);
multiStartDist = info.dist;
@@ -154,6 +228,12 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
}, { passive: false });
state.mainCanvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (!gestureMoved && gestureStartCenter) {
const c = touchCenter(e);
if (c && Math.hypot(c.x - gestureStartCenter.x, c.y - gestureStartCenter.y) > TAP_MAX_MOVE) {
gestureMoved = true;
}
}
if (multiActive && e.touches.length >= 2) {
const info = touchInfo(e);
const ratio = info.dist / Math.max(1, multiStartDist);
@@ -177,14 +257,36 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
continueDraw(e);
}, { passive: false });
state.mainCanvas.addEventListener('touchend', (e) => {
// Decide the gesture only once every finger has lifted.
if (e.touches.length === 0 && gesturePeakTouches >= 2) {
const quick = !gestureMoved && (Date.now() - gestureStartAt) <= TAP_MAX_MS;
const peak = gesturePeakTouches;
gesturePeakTouches = 0;
gestureStartCenter = null;
gestureMoved = false;
multiActive = false;
if (quick) {
if (peak === 2) onTwoFingerTap?.();
else if (peak >= 3) onThreeFingerTap?.();
}
return;
}
if (multiActive) {
if (e.touches.length < 2) multiActive = false;
return;
}
endDraw(e);
if (e.touches.length === 0) {
gesturePeakTouches = 0;
gestureStartCenter = null;
gestureMoved = false;
}
});
state.mainCanvas.addEventListener('touchcancel', () => {
multiActive = false;
gesturePeakTouches = 0;
gestureStartCenter = null;
gestureMoved = false;
cancelDraw?.();
});
@@ -203,7 +305,10 @@ export function wireCanvasEvents({ canvasArea, beginDraw, continueDraw, endDraw,
};
canvasArea.addEventListener('pointerdown', (e) => {
const directPan = isDirectPanIntent(state.tool, state.spacePanActive, e.button);
if (state.tool === 'lasso' && !directPan) return;
// With the crop (or lasso) tool, an empty-area press draws a rect/path
// rather than panning — so the crop can be pulled out past the image.
// Space-held / middle-mouse (directPan) still pans.
if ((state.tool === 'lasso' || state.tool === 'crop') && !directPan) 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;
if (onImage && !directPan) return;
+44 -1
View File
@@ -18,7 +18,7 @@
* }} deps
*/
import { state } from './state.js';
import { flipDocument, rotateDocument } from './document-geometry.js';
import { flipDocument, rotateDocument, rotateDocumentArbitrary, flipLayer as flipLayerGeometry, rotateLayer as rotateLayerGeometry } from './document-geometry.js';
export function createCanvasTransforms({
saveState, composite, fitZoom, showCanvasLoading, hideCanvasLoading, renderLayerPanel,
@@ -52,6 +52,29 @@ export function createCanvasTransforms({
});
},
/**
* Rotate the entire document by an arbitrary angle in degrees
* (clockwise; negative for counter-clockwise), expanding the canvas
* so nothing is clipped. Right angles use the exact integer path.
*/
rotateAllArbitrary(deg) {
if (!state.layers.length) return;
saveState(`Rotate ${deg}°`);
showCanvasLoading('Rotating…');
requestAnimationFrame(() => {
try {
const result = rotateDocumentArbitrary(state, deg);
const sizeLabel = document.getElementById('ge-canvas-size');
if (sizeLabel && result) sizeLabel.textContent = `${result.width}×${result.height}`;
fitZoom();
composite();
renderLayerPanel?.();
} finally {
hideCanvasLoading();
}
});
},
/**
* Mirror every layer horizontally ('h') or vertically ('v').
* Canvas dimensions don't change. Each layer offset is reflected
@@ -64,5 +87,25 @@ export function createCanvasTransforms({
composite();
renderLayerPanel?.();
},
/** Flip only the active layer, in place (Edit ▸ Transform ▸ Flip). */
flipLayer(axis) {
const layer = state.layers.find((item) => item.id === state.activeLayerId);
if (!layer) return;
saveState(axis === 'h' ? 'Flip layer horizontal' : 'Flip layer vertical');
flipLayerGeometry(state, layer, axis);
composite();
renderLayerPanel?.();
},
/** Rotate only the active layer by 90/180/270°, centre preserved. */
rotateLayer(deg) {
const layer = state.layers.find((item) => item.id === state.activeLayerId);
if (!layer) return;
saveState(`Rotate layer ${deg}°`);
rotateLayerGeometry(state, layer, deg);
composite();
renderLayerPanel?.();
},
};
}
+71 -31
View File
@@ -2,11 +2,12 @@
* Paste + drag-and-drop import handlers. Both add an image to the
* editor as a new layer:
*
* - Paste (Ctrl+V): checks `state.internalClipboard` first (set by
* lasso copy/cut), then falls back to the system clipboard's
* `image/*` items. Layer is named "Pasted Selection" or "Pasted"
* and becomes active; the tool snaps to Move so the user can
* reposition it immediately.
* - Paste (Ctrl+V): uses the system clipboard's `image/*` items first
* (so an external screenshot always wins), then falls back to
* `state.internalClipboard` (set by lasso copy/cut) when the OS
* clipboard has no image. Layer is named "Pasted Selection" or
* "Pasted" and becomes active; the tool snaps to Move so the user
* can reposition it immediately.
* - Drop: any `image/*` file dragged from the OS / another tab.
* Shows a "Drop image to add as new layer" overlay mid-drag. Each
* dropped image is routed through `handleImportedImage` so canvas-
@@ -38,38 +39,50 @@ export function wireClipboardAndDrop({
clipboardBindings?.abort();
clipboardBindings = new AbortController();
const { signal } = clipboardBindings;
const pasteAsLayer = (imgSource, label, offset = { x: 0, y: 0 }) => {
if (!state.editorOpen) return; // user closed mid-paste
saveState();
const layer = createLayer(label || 'Pasted', imgSource.width, imgSource.height);
// Selection clipboard data is already a complete layer-sized surface.
// Keep it source-backed with an identity matrix so future transforms do
// not repeatedly resample the pasted pixels.
layer.kind = 'placed';
layer.placed = createPlacedData(imgSource, [1, 0, 0, 1, offset.x, offset.y], label || 'Pasted');
const rendered = renderPlacedLayer(layer);
state.layerOffsets.set(layer.id, rendered.offset);
state.layers.push(layer);
state.activeLayerId = layer.id;
state.selectedLayerIds = [layer.id];
state.activeGroupId = null;
const tb = state.container?.querySelector('.ge-toolbar');
tb?.querySelector('[data-tool="move"]')?.click();
renderLayerPanel();
composite();
uiModule.showToast('Pasted as new layer');
};
// ── Paste ──
let pasteKeyPending = false;
window.addEventListener('paste', (e) => {
if (!state.editorOpen || state.container !== container) return;
// Editable fields keep native paste. The Clipboard button focuses the
// canvas container before asking for a keyboard paste when read() is
// unavailable on an insecure origin.
if (e.target?.isContentEditable || e.target?.closest?.('input, textarea, select, [role="dialog"]')) return;
function pasteAsLayer(imgSource, label, offset = { x: 0, y: 0 }) {
if (!state.editorOpen) return; // user closed mid-paste
saveState();
const layer = createLayer(label || 'Pasted', imgSource.width, imgSource.height);
// Selection clipboard data is already a complete layer-sized surface.
// Keep it source-backed with an identity matrix so future transforms do
// not repeatedly resample the pasted pixels.
layer.kind = 'placed';
layer.placed = createPlacedData(imgSource, [1, 0, 0, 1, offset.x, offset.y], label || 'Pasted');
const rendered = renderPlacedLayer(layer);
state.layerOffsets.set(layer.id, rendered.offset);
state.layers.push(layer);
state.activeLayerId = layer.id;
state.selectedLayerIds = [layer.id];
state.activeGroupId = null;
const tb = state.container?.querySelector('.ge-toolbar');
tb?.querySelector('[data-tool="move"]')?.click();
renderLayerPanel();
composite();
uiModule.showToast('Pasted as new layer');
}
// Editable fields INSIDE the editor keep native paste (the Clipboard button
// focuses the canvas container before asking for a keyboard paste when
// read() is unavailable on an insecure origin). Fields OUTSIDE the editor —
// notably the chat composer sitting behind the editor modal — must NOT
// swallow an image paste: while the editor is open it owns clipboard images,
// so we intercept here (capture phase) before the global chat attach
// listener in app.js can stage the file into the chatbox.
// NOTE: do NOT add `[role="dialog"]` to this guard — the editor itself lives
// inside the gallery modal's role="dialog" modal-content, so that would
// swallow every paste (including the internal Clipboard + Ctrl+V).
const target = e.target;
const insideEditor = target && container && container.contains(target);
if (insideEditor && (target.isContentEditable || target.closest?.('input, textarea, select'))) return;
const imageItem = Array.from(e.clipboardData?.items || []).find(item => item.type.startsWith('image/'));
if (imageItem) {
pasteKeyPending = false;
e.preventDefault();
e.stopImmediatePropagation();
const blob = imageItem.getAsFile();
@@ -85,12 +98,39 @@ export function wireClipboardAndDrop({
return;
}
if (state.internalClipboard && !e.defaultPrevented && !e.clipboardData?.types?.includes?.('text/plain')) {
pasteKeyPending = false;
e.preventDefault();
e.stopImmediatePropagation();
pasteAsLayer(state.internalClipboard, 'Pasted Selection', state.internalClipboardOffset || { x: 0, y: 0 });
}
}, { capture: true, signal });
// ── Ctrl/Cmd+V ──
// Do NOT intercept the keystroke: preventing the default here bypasses the
// browser's own `paste` event and always re-pasted `state.internalClipboard`,
// so a screenshot taken outside the gallery could never be pasted. The paste
// listener above always prefers real `image/*` clipboard items; this key
// handler only covers the insecure-origin case where copying a selection
// never reached the OS clipboard, so the paste event delivers no image (and
// possibly stale text) and nothing usable arrives.
window.addEventListener('keydown', (e) => {
if (!(state.editorOpen && state.container === container)) return;
if (!(e.ctrlKey || e.metaKey) || e.altKey || e.shiftKey) return;
if (String(e.key || '').toLowerCase() !== 'v') return;
if (!state.internalClipboard) return;
const target = e.target;
if (target && (target.isContentEditable || target.closest?.('input, textarea, select'))) return;
pasteKeyPending = true;
setTimeout(() => {
// The paste event runs before this timer and clears the flag whenever it
// received a real clipboard image (or already pasted the internal copy).
if (!pasteKeyPending) return;
pasteKeyPending = false;
if (!state.internalClipboard) return;
pasteAsLayer(state.internalClipboard, 'Pasted Selection', state.internalClipboardOffset || { x: 0, y: 0 });
}, 0);
}, { capture: true, signal });
// ── Drag-and-drop ──
// Visual drop-zone overlay appears mid-drag; routes via
// handleImportedImage so the import respects canvas resizing rules
+56
View File
@@ -0,0 +1,56 @@
/**
* Color-mode support (PhotoCraft parity, Phase 10 slice).
*
* The editor works in an RGBA8 canvas, so only RGB and Grayscale are
* convertible destructively; CMYK/Lab/Indexed remain metadata-only menu
* entries (disabled) because they need a color-managed pipeline we do not
* have. Bit depth is tracked as document metadata only.
*/
export const COLOR_MODES = Object.freeze(['rgb', 'grayscale', 'cmyk', 'lab', 'indexed']);
export const BIT_DEPTHS = Object.freeze([8, 16, 32]);
/** True for modes we can actually convert layer pixels into/out of. */
export function isConvertibleMode(mode) {
return mode === 'rgb' || mode === 'grayscale';
}
/** Convert an ImageData-like buffer to grayscale in place (Rec. 709 luma). */
export function rgbaToGrayscale(data) {
for (let i = 0; i < data.length; i += 4) {
const luma = Math.round(0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]);
data[i] = luma;
data[i + 1] = luma;
data[i + 2] = luma;
}
return data;
}
/** Convert a single canvas to the requested mode in place. Returns true on success. */
export function convertCanvasToMode(canvas, mode) {
if (!canvas || !canvas.getContext) return false;
if (!isConvertibleMode(mode)) return false;
if (mode === 'grayscale') {
const ctx = canvas.getContext('2d');
const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
rgbaToGrayscale(image.data);
ctx.putImageData(image, 0, 0);
}
// RGB is the native working space; nothing to do.
return true;
}
/** Apply a mode to every layer canvas. Returns the number of layers converted. */
export function applyColorMode(layers, mode) {
if (!isConvertibleMode(mode)) return 0;
let converted = 0;
for (const layer of layers || []) {
if (layer && layer.canvas && convertCanvasToMode(layer.canvas, mode)) converted += 1;
}
return converted;
}
/** Only 8 bits/channel is supported by the RGBA8 working canvas. */
export function supportsBitDepth(bits) {
return bits === 8;
}
+201
View File
@@ -0,0 +1,201 @@
/*
* Editor control kit — shared theming for the range/number/select/checkbox
* controls scattered across the editor. It only ADDS classes and small helper
* affordances (range fill, custom steppers, scrubby labels); it never changes
* the value semantics of a control. It is strictly SCOPED to editor surfaces
* (the editor shell and its dialogs) so the rest of the app is untouched, and
* it skips controls that already have a bespoke implementation (e.g. the
* transform popup's own spinner).
*
* Styling lives in static/css/13-image-editor.css (section "Editor control kit").
*/
export const CONTROL_KIT_VERSION = '1.0';
const RANGE_SELECTOR = 'input[type="range"]';
const NUMBER_SELECTOR = 'input[type="number"]';
const CHECK_SELECTOR = 'input[type="checkbox"]';
const SELECT_SELECTOR = 'select';
// Only controls inside one of these surfaces are themed. Dialogs are appended
// to <body> outside #gallery-editor-container, so they are listed explicitly.
const EDITOR_ROOT_SELECTOR = [
'#gallery-editor-container',
'.ge-adj-popup',
'.ge-filter-overlay',
'.ge-canvas-size-overlay',
'#ge-canvas-size-overlay',
'.ge-float-window',
'.ge-transform-popup',
].join(', ');
function inEditor(el) {
return !!(el && el.closest && el.closest(EDITOR_ROOT_SELECTOR));
}
function isSkipped(el) {
if (!el || el.__geKit) return true;
if (!inEditor(el)) return true;
if (el.closest('[data-ge-nokit]')) return true;
// The transform popup renders its own themed spinner for its inputs.
if (el.closest('.ge-transform-field')) return true;
return false;
}
function numberStep(el) {
const raw = Number(el.getAttribute('step'));
if (Number.isFinite(raw) && raw > 0) return raw;
return 1;
}
function clampToRange(el, value) {
const min = el.hasAttribute('min') ? Number(el.min) : -Infinity;
const max = el.hasAttribute('max') ? Number(el.max) : Infinity;
let v = value;
if (Number.isFinite(min)) v = Math.max(min, v);
if (Number.isFinite(max)) v = Math.min(max, v);
return v;
}
function attachScrub(handle, el) {
handle.classList.add('ge-scrub');
handle.addEventListener('pointerdown', (e) => {
if (el.disabled || el.readOnly) return;
e.preventDefault();
handle.classList.add('ge-scrubbing');
const startX = e.clientX;
const startVal = Number(el.value) || 0;
const step = numberStep(el);
let moved = false;
const move = (ev) => {
const dx = ev.clientX - startX;
if (Math.abs(dx) < 2) return;
moved = true;
const factor = ev.shiftKey ? 10 : 1;
const next = clampToRange(el, startVal + Math.round(dx) * step * factor * 0.1);
if (String(next) !== el.value) {
el.value = String(next);
el.dispatchEvent(new Event('input', { bubbles: true }));
}
};
const up = () => {
document.removeEventListener('pointermove', move);
document.removeEventListener('pointerup', up);
handle.classList.remove('ge-scrubbing');
if (moved) el.dispatchEvent(new Event('change', { bubbles: true }));
};
document.addEventListener('pointermove', move);
document.addEventListener('pointerup', up);
});
}
function decorateNumber(el) {
if (isSkipped(el)) return;
el.classList.add('ge-ctl-num');
el.__geKit = true;
if (el.disabled || el.readOnly) return;
// Photoshop-style scrub-on-label: drag a sibling <span> label to change the
// value; the field also keeps native arrow-key stepping. We do NOT inject a
// separate +/- stepper — most editor number fields live in display:grid
// labels, where an injected element wraps onto its own grid row and shows as
// an empty pill.
const label = el.closest('label');
if (label) {
const handle = label.querySelector(':scope > span');
if (handle && !handle.classList.contains('ge-scrub')) attachScrub(handle, el);
}
}
function updateRangeFill(el) {
const min = Number(el.min);
const max = Number(el.max);
const value = Number(el.value);
if (Number.isFinite(min) && Number.isFinite(max) && max > min) {
const pct = ((value - min) / (max - min)) * 100;
el.style.setProperty('--ge-pct', `${Math.max(0, Math.min(100, pct))}%`);
} else {
el.style.setProperty('--ge-pct', '50%');
}
}
function decorateRange(el) {
if (isSkipped(el)) return;
el.classList.add('ge-ctl-range');
el.__geKit = true;
updateRangeFill(el);
}
function decorateSelect(el) {
if (isSkipped(el)) return;
el.classList.add('ge-ctl-select');
el.__geKit = true;
}
function decorateCheck(el) {
if (isSkipped(el)) return;
el.classList.add('ge-ctl-check');
el.__geKit = true;
}
export function initControlKit(root = document) {
if (!root || !root.querySelectorAll) return 0;
// If the root itself is a control, decorate just it; otherwise its subtree.
let count = 0;
const decorate = (el) => {
if (el.matches(RANGE_SELECTOR)) { if (!isSkipped(el)) { decorateRange(el); count += 1; } }
else if (el.matches(NUMBER_SELECTOR)) { if (!isSkipped(el)) { decorateNumber(el); count += 1; } }
else if (el.matches(SELECT_SELECTOR)) { if (!isSkipped(el)) { decorateSelect(el); count += 1; } }
else if (el.matches(CHECK_SELECTOR)) { if (!isSkipped(el)) { decorateCheck(el); count += 1; } }
};
if (root.nodeType === 1) decorate(root);
root.querySelectorAll(RANGE_SELECTOR).forEach((el) => { if (!isSkipped(el)) { decorateRange(el); count += 1; } });
root.querySelectorAll(NUMBER_SELECTOR).forEach((el) => { if (!isSkipped(el)) { decorateNumber(el); count += 1; } });
root.querySelectorAll(SELECT_SELECTOR).forEach((el) => { if (!isSkipped(el)) { decorateSelect(el); count += 1; } });
root.querySelectorAll(CHECK_SELECTOR).forEach((el) => { if (!isSkipped(el)) { decorateCheck(el); count += 1; } });
return count;
}
let installed = false;
/**
* Install once: decorates the current editor DOM, keeps range fills in sync,
* and watches for controls that appear later (dialogs, popups, dock panels).
* Only nodes that are (or contain) an editor surface are processed.
*/
export function installControlKit() {
if (installed) return;
installed = true;
const boot = () => {
document.querySelectorAll(EDITOR_ROOT_SELECTOR).forEach((root) => initControlKit(root));
};
boot();
document.addEventListener(
'input',
(e) => {
const t = e.target;
if (t && t.matches && t.matches(RANGE_SELECTOR)) updateRangeFill(t);
},
true
);
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
m.addedNodes.forEach((node) => {
if (node.nodeType !== 1) return;
const isRoot = node.matches && node.matches(EDITOR_ROOT_SELECTOR);
const containsRoot = node.querySelector && node.querySelector(EDITOR_ROOT_SELECTOR);
if (isRoot) {
initControlKit(node);
} else if (containsRoot) {
node.querySelectorAll(EDITOR_ROOT_SELECTOR).forEach((root) => initControlKit(root));
} else if (inEditor(node)) {
initControlKit(node);
}
});
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
export default { CONTROL_KIT_VERSION, initControlKit, installControlKit };
+10 -2
View File
@@ -24,6 +24,8 @@ const SUPPORTED_BLEND_MODES = new Set([
'source-over', 'multiply', 'screen', 'overlay', 'soft-light', 'hard-light',
'darken', 'lighten', 'color-dodge', 'color-burn', 'difference', 'exclusion',
'hue', 'saturation', 'color', 'luminosity',
'dissolve', 'linear-burn', 'linear-dodge', 'darker-color', 'lighter-color',
'vivid-light', 'linear-light', 'pin-light', 'hard-mix', 'subtract', 'divide',
]);
function normalizeGuideValues(values, fallback = []) {
@@ -51,6 +53,8 @@ export function normalizeEditorView(view, fallback = {}) {
gridSize: Math.max(2, Math.min(1000, Math.round(Number.isFinite(rawGridSize) ? rawGridSize : 16))),
snapEnabled: Boolean(source.snapEnabled ?? fallback.snapEnabled ?? false),
snapToGrid: Boolean(source.snapToGrid ?? fallback.snapToGrid ?? false),
autoSelectLayer: Boolean(source.autoSelectLayer ?? fallback.autoSelectLayer ?? false),
autoSelectTarget: (source.autoSelectTarget ?? fallback.autoSelectTarget) === 'group' ? 'group' : 'layer',
guides: {
vertical: normalizeGuideValues(guides.vertical, fallbackGuides.vertical),
horizontal: normalizeGuideValues(guides.horizontal, fallbackGuides.horizontal),
@@ -590,8 +594,10 @@ export function prepareEditorDocument(raw) {
document: {
...migrated,
v: EDITOR_DOCUMENT_VERSION,
imgWidth: width,
imgHeight: height,
imgWidth: width,
imgHeight: height,
colorMode: migrated.colorMode === 'grayscale' ? 'grayscale' : 'rgb',
bitDepth: 8,
activeLayerId,
view: normalizeEditorView(migrated.view),
groups,
@@ -634,6 +640,8 @@ export function serializeEditorDocument(state, extras = {}) {
imageId: state.imageId || null,
imgWidth: state.imgWidth,
imgHeight: state.imgHeight,
colorMode: state.colorMode || 'rgb',
bitDepth: state.bitDepth || 8,
activeLayerId: state.activeLayerId || null,
nextLayerId: state.nextLayerId,
view: normalizeEditorView(state),
+281 -8
View File
@@ -9,18 +9,22 @@
import { flipTextLayer, rotateTextLayer, scaleTextLayer } from './text-layer.js';
import { flipShapeLayer, rotateShapeLayer, scaleShapeLayer } from './shape-layer.js';
import { renderPlacedLayer, transformPlacedData } from './placed-layer.js';
import { affineBounds, renderPlacedLayer, transformPlacedData } from './placed-layer.js';
function makeCanvas(width, height) {
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(width));
canvas.height = Math.max(1, Math.round(height));
canvas.width = Math.max(1, Math.round(Number.isFinite(width) ? width : 1));
canvas.height = Math.max(1, Math.round(Number.isFinite(height) ? height : 1));
return canvas;
}
function renderWindow(source, x, y, width, height) {
const out = makeCanvas(width, height);
out.getContext('2d').drawImage(source, -x, -y);
// A freshly-created / empty layer can legitimately have a 0-sized canvas;
// drawImage() throws on those, which would abort cropping the whole document.
if (source && source.width > 0 && source.height > 0) {
out.getContext('2d').drawImage(source, -x, -y);
}
return out;
}
@@ -50,6 +54,25 @@ function renderRotated(source, degrees) {
return out;
}
function renderRotatedArbitrary(source, degrees) {
const radians = (degrees * Math.PI) / 180;
const cos = Math.cos(radians);
const sin = Math.sin(radians);
const width = Math.abs(source.width * cos) + Math.abs(source.height * sin);
const height = Math.abs(source.width * sin) + Math.abs(source.height * cos);
const out = makeCanvas(Math.ceil(width), Math.ceil(height));
// Empty layers can have a 0-sized canvas; drawImage() throws on those.
if (source && source.width > 0 && source.height > 0) {
const ctx = out.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.translate(out.width / 2, out.height / 2);
ctx.rotate(radians);
ctx.drawImage(source, -source.width / 2, -source.height / 2);
}
return out;
}
function renderFlipped(source, axis) {
const out = makeCanvas(source.width, source.height);
const ctx = out.getContext('2d');
@@ -172,10 +195,20 @@ export function clipPolygonToRect(points, width, height) {
}
function normalizeCropRect(editorState, rect) {
const x = Math.max(0, Math.min(editorState.imgWidth - 1, Math.round(rect.x)));
const y = Math.max(0, Math.min(editorState.imgHeight - 1, Math.round(rect.y)));
const width = Math.max(1, Math.min(editorState.imgWidth - x, Math.round(rect.w)));
const height = Math.max(1, Math.min(editorState.imgHeight - y, Math.round(rect.h)));
// Accept either {w,h} (internal) or {width,height} (control-op params).
const rawW = Number.isFinite(rect.w) ? rect.w : rect.width;
const rawH = Number.isFinite(rect.h) ? rect.h : rect.height;
// The rect may reach BEYOND the current image on any side: a crop that
// overshoots an edge EXPANDS the canvas there (the new region is
// transparent) instead of being clamped back inside. renderWindow() already
// places the source at (-x,-y) in an output of any size, so allowing
// negative x/y and out-of-bounds width/height is all that is needed.
// Only guard against absurd values.
const MAX = 20000;
const x = Math.max(-MAX, Math.min(MAX, Math.round(rect.x)));
const y = Math.max(-MAX, Math.min(MAX, Math.round(rect.y)));
const width = Math.max(1, Math.min(MAX, Math.round(Number.isFinite(rawW) ? rawW : editorState.imgWidth)));
const height = Math.max(1, Math.min(MAX, Math.round(Number.isFinite(rawH) ? rawH : editorState.imgHeight)));
return { x, y, width, height };
}
@@ -501,6 +534,121 @@ export function rotateDocument(editorState, degrees) {
return { width: newWidth, height: newHeight, degrees: normalized };
}
/**
* Rotate the whole document by an arbitrary angle (degrees, clockwise),
* expanding the canvas so nothing is clipped. Right angles delegate to the
* exact integer path; other angles resample every layer, mask, and selection
* about the old image centre and re-place each layer's centre in the new
* frame. Guides are dropped because arbitrary rotation leaves no
* axis-aligned reference.
*/
export function rotateDocumentArbitrary(editorState, degrees) {
const raw = Number(degrees);
if (!Number.isFinite(raw)) return null;
const normalized = ((raw % 360) + 360) % 360;
if (normalized === 0) {
return { width: editorState.imgWidth, height: editorState.imgHeight, degrees: 0 };
}
if ([90, 180, 270].includes(normalized)) return rotateDocument(editorState, normalized);
const radians = (normalized * Math.PI) / 180;
const cos = Math.cos(radians);
const sin = Math.sin(radians);
const oldWidth = editorState.imgWidth;
const oldHeight = editorState.imgHeight;
const newWidth = Math.max(1, Math.ceil(Math.abs(oldWidth * cos) + Math.abs(oldHeight * sin)));
const newHeight = Math.max(1, Math.ceil(Math.abs(oldWidth * sin) + Math.abs(oldHeight * cos)));
const mapPoint = (x, y) => ({
x: cos * (x - oldWidth / 2) - sin * (y - oldHeight / 2) + newWidth / 2,
y: sin * (x - oldWidth / 2) + cos * (y - oldHeight / 2) + newHeight / 2,
});
for (const layer of editorState.layers) {
const before = layerBounds(editorState, layer);
const mapped = mapPoint(before.centerX, before.centerY);
let placedOffset = null;
if (layer.kind === 'text' && layer.text) {
rotateTextLayer(layer, normalized);
} else if (layer.kind === 'shape' && layer.shape) {
rotateShapeLayer(layer, normalized);
} else if (layer.kind === 'placed' && layer.placed) {
// Rotate the placed matrix about its centre, then translate that centre
// to where the document rotation maps it.
const matrix = [
cos, sin, -sin, cos,
before.centerX - cos * before.centerX + sin * before.centerY + (mapped.x - before.centerX),
before.centerY - sin * before.centerX - cos * before.centerY + (mapped.y - before.centerY),
];
layer.placed = transformPlacedData(layer.placed, matrix);
placedOffset = renderPlacedLayer(layer)?.offset || null;
} else {
replaceCanvas(layer, renderRotatedArbitrary(layer.canvas, normalized));
}
const layerWidth = layer.canvas.width;
const layerHeight = layer.canvas.height;
for (const mask of layer.masks || []) {
const oldMaskWidth = mask.canvas.width;
const oldMaskHeight = mask.canvas.height;
const maskOffset = mask.offset || { x: 0, y: 0 };
replaceCanvas(mask, renderRotatedArbitrary(mask.canvas, normalized));
const cx = (Number(maskOffset.x) || 0) + oldMaskWidth / 2;
const cy = (Number(maskOffset.y) || 0) + oldMaskHeight / 2;
if ((mask.space || (mask.mode === 'layer' ? 'layer' : 'document')) === 'layer') {
// Layer-space masks rotate with their layer's canvas.
const nx = cos * (cx - before.width / 2) - sin * (cy - before.height / 2) + layerWidth / 2;
const ny = sin * (cx - before.width / 2) + cos * (cy - before.height / 2) + layerHeight / 2;
mask.offset = {
x: Math.round(nx - mask.canvas.width / 2),
y: Math.round(ny - mask.canvas.height / 2),
};
} else {
const mappedCenter = mapPoint(cx, cy);
mask.offset = {
x: Math.round(mappedCenter.x - mask.canvas.width / 2),
y: Math.round(mappedCenter.y - mask.canvas.height / 2),
};
}
}
editorState.layerOffsets.set(layer.id, placedOffset || {
x: Math.round(mapped.x - layerWidth / 2),
y: Math.round(mapped.y - layerHeight / 2),
});
invalidateLayerCaches(layer);
}
for (const group of editorState.layerGroups || []) {
for (const mask of group.masks || []) {
const oldMaskWidth = mask.canvas.width;
const oldMaskHeight = mask.canvas.height;
const maskOffset = mask.offset || { x: 0, y: 0 };
replaceCanvas(mask, renderRotatedArbitrary(mask.canvas, normalized));
const mappedCenter = mapPoint(
(Number(maskOffset.x) || 0) + oldMaskWidth / 2,
(Number(maskOffset.y) || 0) + oldMaskHeight / 2,
);
mask.offset = {
x: Math.round(mappedCenter.x - mask.canvas.width / 2),
y: Math.round(mappedCenter.y - mask.canvas.height / 2),
};
}
}
if (editorState.wandMask) {
replaceStandaloneCanvas(editorState.wandMask, renderRotatedArbitrary(editorState.wandMask, normalized));
}
forEachStoredSelection(editorState, canvas => {
replaceStandaloneCanvas(canvas, renderRotatedArbitrary(canvas, normalized));
});
if (editorState.wandLastSeed) {
const mappedSeed = mapPoint(editorState.wandLastSeed.x, editorState.wandLastSeed.y);
editorState.wandLastSeed = { ...editorState.wandLastSeed, x: mappedSeed.x, y: mappedSeed.y };
}
editorState.lassoPoints = (editorState.lassoPoints || []).map(point => mapPoint(point.x, point.y));
// Arbitrary rotation leaves no axis-aligned reference, so guides are dropped.
editorState.guides = { vertical: [], horizontal: [] };
syncDocumentCanvas(editorState, newWidth, newHeight);
return { width: newWidth, height: newHeight, degrees: normalized };
}
/** Flip every layer, mask, offset, and active selection across the document. */
export function flipDocument(editorState, axis) {
if (axis !== 'h' && axis !== 'v') return null;
@@ -573,3 +721,128 @@ export function flipDocument(editorState, axis) {
syncDocumentCanvas(editorState, width, height);
return { width, height, axis };
}
// ── Single-layer transforms (Edit ▸ Transform semantics) ──
// Unlike the document-wide helpers above, these mutate ONE layer in place:
// the document bounds, other layers, and the active selection are untouched.
// The layer's visual centre is preserved so a rotation does not fling it
// across the canvas.
function layerBounds(editorState, layer) {
if (layer.kind === 'placed' && layer.placed?.sourceCanvas) {
const sw = layer.placed.sourceWidth || layer.placed.sourceCanvas.width;
const sh = layer.placed.sourceHeight || layer.placed.sourceCanvas.height;
return affineBounds(layer.placed.matrix, sw, sh);
}
const offset = editorState.layerOffsets.get(layer.id) || { x: 0, y: 0 };
const width = layer.canvas.width;
const height = layer.canvas.height;
return {
x: offset.x,
y: offset.y,
width,
height,
centerX: offset.x + width / 2,
centerY: offset.y + height / 2,
};
}
function recenterLayer(editorState, layer, before) {
const width = layer.canvas.width;
const height = layer.canvas.height;
editorState.layerOffsets.set(layer.id, {
x: Math.round(before.centerX - width / 2),
y: Math.round(before.centerY - height / 2),
});
}
function flipMatrixAbout(centerX, centerY, axis) {
return axis === 'h'
? [-1, 0, 0, 1, 2 * centerX, 0]
: [1, 0, 0, -1, 0, 2 * centerY];
}
function rotateMatrixAbout(centerX, centerY, degrees) {
const radians = (degrees * Math.PI) / 180;
const cos = Math.round(Math.cos(radians));
const sin = Math.round(Math.sin(radians));
// T(center) · R · T(-center)
return [
cos, sin, -sin, cos,
centerX - cos * centerX + sin * centerY,
centerY - sin * centerX - cos * centerY,
];
}
function transformLayerMasks(layer, transform) {
for (const mask of layer.masks || []) {
transform(mask);
}
}
/** Flip a single layer horizontally ('h') or vertically ('v'), in place. */
export function flipLayer(editorState, layer, axis) {
if (!layer || (axis !== 'h' && axis !== 'v')) return null;
const before = layerBounds(editorState, layer);
if (layer.kind === 'text' && layer.text) flipTextLayer(layer, axis);
else if (layer.kind === 'shape' && layer.shape) flipShapeLayer(layer, axis);
else if (layer.kind === 'placed' && layer.placed) {
layer.placed = transformPlacedData(layer.placed, flipMatrixAbout(before.centerX, before.centerY, axis));
const rendered = renderPlacedLayer(layer);
if (rendered) editorState.layerOffsets.set(layer.id, rendered.offset);
} else {
replaceCanvas(layer, renderFlipped(layer.canvas, axis));
recenterLayer(editorState, layer, before);
}
transformLayerMasks(layer, (mask) => {
const maskWidth = mask.canvas.width;
const maskHeight = mask.canvas.height;
const maskOffset = mask.offset || { x: 0, y: 0 };
replaceCanvas(mask, renderFlipped(mask.canvas, axis));
if ((mask.space || (mask.mode === 'layer' ? 'layer' : 'document')) === 'layer') {
const ox = Number(maskOffset.x) || 0;
const oy = Number(maskOffset.y) || 0;
mask.offset = axis === 'h'
? { x: before.width - ox - maskWidth, y: oy }
: { x: ox, y: before.height - oy - maskHeight };
}
});
invalidateLayerCaches(layer);
return { axis };
}
/** Rotate a single layer by 90/180/270°, keeping its centre fixed. */
export function rotateLayer(editorState, layer, degrees) {
const normalized = ((degrees % 360) + 360) % 360;
if (!layer || ![90, 180, 270].includes(normalized)) return null;
const before = layerBounds(editorState, layer);
if (layer.kind === 'text' && layer.text) rotateTextLayer(layer, normalized);
else if (layer.kind === 'shape' && layer.shape) rotateShapeLayer(layer, normalized);
else if (layer.kind === 'placed' && layer.placed) {
layer.placed = transformPlacedData(layer.placed, rotateMatrixAbout(before.centerX, before.centerY, normalized));
const rendered = renderPlacedLayer(layer);
if (rendered) editorState.layerOffsets.set(layer.id, rendered.offset);
} else {
replaceCanvas(layer, renderRotated(layer.canvas, normalized));
recenterLayer(editorState, layer, before);
}
transformLayerMasks(layer, (mask) => {
const oldMaskWidth = mask.canvas.width;
const oldMaskHeight = mask.canvas.height;
const maskOffset = mask.offset || { x: 0, y: 0 };
replaceCanvas(mask, renderRotated(mask.canvas, normalized));
if ((mask.space || (mask.mode === 'layer' ? 'layer' : 'document')) === 'layer') {
const ox = Number(maskOffset.x) || 0;
const oy = Number(maskOffset.y) || 0;
if (normalized === 90) {
mask.offset = { x: before.height - oy - oldMaskHeight, y: ox };
} else if (normalized === 180) {
mask.offset = { x: before.width - ox - oldMaskWidth, y: before.height - oy - oldMaskHeight };
} else {
mask.offset = { x: oy, y: before.width - ox - oldMaskWidth };
}
}
});
invalidateLayerCaches(layer);
return { degrees: normalized };
}
+72
View File
@@ -0,0 +1,72 @@
// Makes a modal dialog draggable by its header, Photoshop-style.
//
// On the first grab the dialog is switched to `position:fixed` anchored at
// its current on-screen box, so it follows the pointer independently of the
// host modal's centering/transform layout. Dragging is clamped to the
// viewport and ignores presses that start on interactive controls (buttons,
// inputs, selects) so clicking Cancel/Create never becomes a drag.
export function makeDraggable(dialog, handle) {
if (!dialog || !handle || dialog.__geDraggable) return;
dialog.__geDraggable = true;
handle.classList.add('ge-draggable-handle');
let startX = 0;
let startY = 0;
let originLeft = 0;
let originTop = 0;
let dragging = false;
const onDown = (event) => {
if (event.button != null && event.button !== 0) return;
if (event.target?.closest?.('button, input, select, textarea, a, [role="button"]')) return;
const rect = dialog.getBoundingClientRect();
dialog.style.position = 'fixed';
dialog.style.margin = '0';
dialog.style.left = `${rect.left}px`;
dialog.style.top = `${rect.top}px`;
dialog.style.right = 'auto';
dialog.style.bottom = 'auto';
dialog.style.transform = 'none';
startX = event.clientX;
startY = event.clientY;
originLeft = rect.left;
originTop = rect.top;
dragging = true;
handle.setPointerCapture?.(event.pointerId);
event.preventDefault();
};
const onMove = (event) => {
if (!dragging) return;
const width = dialog.offsetWidth;
const height = dialog.offsetHeight;
const left = Math.max(0, Math.min(window.innerWidth - width, originLeft + (event.clientX - startX)));
const top = Math.max(0, Math.min(window.innerHeight - height, originTop + (event.clientY - startY)));
dialog.style.left = `${left}px`;
dialog.style.top = `${top}px`;
};
const onUp = (event) => {
if (!dragging) return;
dragging = false;
handle.releasePointerCapture?.(event.pointerId);
};
handle.addEventListener('pointerdown', onDown);
handle.addEventListener('pointermove', onMove);
handle.addEventListener('pointerup', onUp);
handle.addEventListener('pointercancel', onUp);
}
// Clears the inline positioning set by makeDraggable so the next open
// re-centers the dialog inside its host modal.
export function resetDraggable(dialog) {
if (!dialog) return;
dialog.style.position = '';
dialog.style.margin = '';
dialog.style.left = '';
dialog.style.top = '';
dialog.style.right = '';
dialog.style.bottom = '';
dialog.style.transform = '';
}
+374
View File
@@ -0,0 +1,374 @@
// Client side of the scoped "photo_editor" agent path.
//
// The editor Quick Edit popup sends {prompt, session, state, screenshot} to the
// app's editor-agent endpoint. That agent turn is offered ONLY the editor tool
// family (plan_edit / run_editor_command / get_editor_screenshot / list_layers)
// plus ask_user; the model's run_editor_command calls are executed in-process by
// the owner-scoped bridge (/api/editor/bridge/*), which delivers each command to
// this browser subscriber. We stream those executed steps into the popup and
// fold the whole run into a single undo group.
//
// The endpoint is HARNESS-owned; if it is not present yet (404/405) `run()`
// resolves {unavailable:true} so the caller can fall back to the local planner.
//
// Payload: { prompt, session, editor_session, state, screenshot }
// - session / editor_session : the editor bridge session id (scopes commands)
// - state : document.info + layers.list (+ imageId/name)
// - screenshot : data:image/png;base64,... of the canvas
// Response: { ok?, reply?, tools_offered?[], steps?[], trace?[] } (any subset).
export const EDITOR_AGENT_VERSION = '1.0';
export const DEFAULT_AGENT_ENDPOINT = '/api/editor/agent';
import { formatCropRect, isGenericIntent } from './nl-edit.js';
export function createEditorAgent({
control,
endpoint = DEFAULT_AGENT_ENDPOINT,
fetchImpl = null,
getSession = null,
getModel = null,
getAgentModel = null,
onStep = null,
} = {}) {
if (!control || typeof control.invoke !== 'function') {
throw new Error('createEditorAgent requires a control with invoke()');
}
const doFetch = fetchImpl || (typeof fetch !== 'undefined' ? fetch : null);
let activeStep = null;
let running = false;
let executed = null;
// Called by the editor bridge for every queued command it executes. While an
// agent run is in flight this streams the step into the popup.
function reportStep(payload, cmd) {
const op = (cmd && cmd.op) || (payload && payload.op) || '';
const entry = {
op,
ok: !!(payload && payload.ok),
error: payload && payload.error ? payload.error : null,
ms: payload && payload.ms != null ? payload.ms : null,
params: cmd && cmd.params ? JSON.stringify(cmd.params).slice(0, 400) : null,
screenshot: payload && payload.screenshot ? payload.screenshot : null,
};
if (executed) executed.push(entry);
if (activeStep) { try { activeStep(entry); } catch (_) {} }
return entry;
}
function isRunning() { return running; }
async function collectState() {
const state = {};
try { Object.assign(state, (await control.invoke('document.info')).result || {}); } catch (_) {}
try {
const ls = await control.invoke('layers.list');
if (ls && ls.ok) state.layers = ls.result;
} catch (_) {}
return state;
}
// Mean absolute pixel delta (0..1) between two data-URL images, computed on a
// 64px thumbnail. Browser-only; resolves null when it cannot measure.
async function dataUrlDelta(a, b) {
try {
if (typeof document === 'undefined' || !a || !b) return null;
const load = (url) => new Promise((res, rej) => { const im = new Image(); im.onload = () => res(im); im.onerror = rej; im.src = url; });
const [ia, ib] = await Promise.all([load(a), load(b)]);
const w = 64, h = 64;
const ca = document.createElement('canvas'); ca.width = w; ca.height = h;
const cb = document.createElement('canvas'); cb.width = w; cb.height = h;
ca.getContext('2d').drawImage(ia, 0, 0, w, h);
cb.getContext('2d').drawImage(ib, 0, 0, w, h);
const da = ca.getContext('2d').getImageData(0, 0, w, h).data;
const db = cb.getContext('2d').getImageData(0, 0, w, h).data;
let sum = 0;
for (let i = 0; i < da.length; i += 4) sum += Math.abs(da[i] - db[i]) + Math.abs(da[i + 1] - db[i + 1]) + Math.abs(da[i + 2] - db[i + 2]);
return sum / ((da.length / 4) * 3 * 255);
} catch (_) { return null; }
}
// Fraction of near-white (clipped-highlight) pixels in a data-URL image, on a
// 96px thumbnail. Browser-only; resolves null when it cannot measure.
async function dataUrlClipFraction(url) {
try {
if (typeof document === 'undefined' || !url) return null;
const load = (u) => new Promise((res, rej) => { const im = new Image(); im.onload = () => res(im); im.onerror = rej; im.src = u; });
const im = await load(url);
const w = 96, h = 96;
const c = document.createElement('canvas'); c.width = w; c.height = h;
c.getContext('2d').drawImage(im, 0, 0, w, h);
const d = c.getContext('2d').getImageData(0, 0, w, h).data;
let clipped = 0, total = 0;
for (let i = 0; i < d.length; i += 4) {
total++;
const lum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
if (lum > 250) clipped++;
}
return total ? clipped / total : null;
} catch (_) { return null; }
}
// Exposure summary of a data-URL image on a 96px thumbnail: fractions of dark
// (shadow) and bright (highlight) pixels plus the mean luminance. Used to decide
// whether a whole-image Auto Tone is actually warranted for a portrait.
async function dataUrlExposure(url) {
try {
if (typeof document === 'undefined' || !url) return null;
const load = (u) => new Promise((res, rej) => { const im = new Image(); im.onload = () => res(im); im.onerror = rej; im.src = u; });
const im = await load(url);
const w = 96, h = 96;
const c = document.createElement('canvas'); c.width = w; c.height = h;
c.getContext('2d').drawImage(im, 0, 0, w, h);
const d = c.getContext('2d').getImageData(0, 0, w, h).data;
let dark = 0, bright = 0, sum = 0, total = 0;
for (let i = 0; i < d.length; i += 4) {
total++;
const lum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
sum += lum;
if (lum < 42) dark++;
if (lum > 214) bright++;
}
return total ? { dark: dark / total, bright: bright / total, mean: sum / total / 255 } : null;
} catch (_) { return null; }
}
async function run(prompt, { onStep: stepCb = null, signal = null } = {}) {
if (!prompt || !String(prompt).trim()) throw new Error('empty prompt');
if (!doFetch || !endpoint) return { unavailable: true, ok: false };
const session = getSession ? getSession() : 'default';
let modelInfo = null;
try { modelInfo = getModel ? getModel() : null; } catch (_) { modelInfo = null; }
let agentInfo = null;
try { agentInfo = getAgentModel ? getAgentModel() : null; } catch (_) { agentInfo = null; }
const report = stepCb || onStep || null;
activeStep = report;
executed = [];
running = true;
// Honest before-image (captured before any client pre-step) for the
// imperceptible-edit check, then the history mark scoping the undo group.
let beforeShot = null;
try { const s = await control.invoke('screenshot'); beforeShot = s && s.result ? s.result.dataUrl : null; } catch (_) {}
let mark = 0;
try { mark = (await control.invoke('history.mark')).result; } catch (_) {}
// Generic intents may get an Auto Tone/Color strengthen below IF the agent's
// own plan turned out imperceptible (avoids double-processing a dark image).
const generic = isGenericIntent(prompt);
// Portrait/teeth intents: the planner sometimes leads with a whole-image
// Auto Tone, which lightens and whitens the face ("pale/airbrushed"). Suppress
// photo.autoTone during the run unless the photo is genuinely under- or
// over-exposed (checked from the before-image histogram).
const lp = String(prompt).toLowerCase();
const portraitIntent = /skin|complexion|blemish|acne|pores|smoot|retouch|look (better|good|amazing)|flawless|face|portrait/.test(lp);
const teethIntent = /teeth|smile/.test(lp);
let origInvoke = null;
const restoreInvoke = () => { if (origInvoke) { control.invoke = origInvoke; origInvoke = null; } };
if (portraitIntent || teethIntent) {
const exposure = await dataUrlExposure(beforeShot);
const needsTone = !!(exposure && (exposure.dark > 0.32 || exposure.bright > 0.32));
if (!needsTone) {
origInvoke = control.invoke;
const prev = origInvoke;
control.invoke = function (op, params) {
if (op === 'photo.autoTone') return Promise.resolve({ ok: true, op, result: { skipped: true, reason: 'portrait-no-auto-tone' } });
return prev.call(this, op, params);
};
}
}
const state = await collectState();
let screenshot = null;
try {
const shot = await control.invoke('screenshot');
screenshot = shot && shot.result ? shot.result.dataUrl : null;
} catch (_) {}
let res = null;
try {
res = await doFetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: signal || undefined,
body: JSON.stringify({
prompt, session, editor_session: session, state, screenshot,
model: (modelInfo && modelInfo.model) || '',
endpoint: (modelInfo && modelInfo.endpoint) || '',
model_label: (modelInfo && modelInfo.label) || '',
agent_model: (agentInfo && agentInfo.agent) || '',
agent_endpoint: (agentInfo && agentInfo.endpoint) || '',
agent_label: (agentInfo && agentInfo.label) || '',
}),
});
} catch (e) {
activeStep = null; running = false; restoreInvoke();
return { unavailable: true, ok: false, error: String(e && e.message ? e.message : e) };
}
// No agent endpoint yet -> let the caller fall back to the local planner.
if (!res || res.status === 404 || res.status === 405) {
activeStep = null; running = false; restoreInvoke();
return { unavailable: true, ok: false };
}
let data = null;
try { data = await res.json(); } catch (_) {}
const trace = executed;
// How many history entries did the agent's bridge commands add?
let applied = 0;
try {
const nowMark = (await control.invoke('history.mark')).result;
applied = Math.max(0, Number(nowMark || 0) - Number(mark || 0));
} catch (_) {}
const needsProvider = !!(data && (data.needs_provider || data.requires_provider || data.needsProvider));
const blocked = !res.ok || !data || data.ok === false || needsProvider || !!(data && data.blocked);
// A clarification: the planner returned no steps but asked a question. Do NOT
// run any post-guard (especially the imperceptible-edit tone strengthen),
// which would silently tweak the image for a prompt the model did not understand.
const planSteps = Array.isArray(data && data.steps) ? data.steps : [];
const asked = !blocked && planSteps.length === 0 && !!((data && (data.reply || data.message)));
activeStep = null; running = false;
// Safety net: if the agent could not fulfil the request, roll back every
// partial/substitute edit it applied instead of leaving a wrong edit behind.
if (blocked && applied > 0) {
for (let i = 0; i < applied; i++) {
try { await control.invoke('history.undo'); } catch (_) { break; }
}
} else if (!blocked && !asked) {
// Format/platform requests: guarantee the target aspect crop even when the
// agent's own plan omitted document.crop (e.g. "make it instagram ready").
// Do NOT crop when the request is to EXTEND the canvas (that adds area,
// it does not crop the image).
const extendIntent = /\b(extend|expand)\b|\badd\b[^.]*\b(canvas|border|space|margin)\b|\b(wider|taller|letterbox)\b/i.test(prompt);
const docOps = (trace || []).map((t) => t && t.op);
const alreadyFormatted = extendIntent || docOps.includes('document.crop') || docOps.includes('document.resizeCanvas') || docOps.includes('document.extend');
try {
const info = (await control.invoke('document.info')).result || {};
const rect = alreadyFormatted ? null : formatCropRect(prompt, info.width, info.height);
if (rect && (Math.abs((info.width || 0) - rect.width) > 2 || Math.abs((info.height || 0) - rect.height) > 2)) {
await control.invoke('document.crop', rect);
}
} catch (_) {}
// Skin/teeth retouch routing guard: rather than let a portrait request
// degrade to a destructive global blur, apply the specialised masked,
// texture-preserving retouch ops when the agent did not.
try {
const traceOps = (trace || []).map((t) => t && t.op);
const lp = String(prompt).toLowerCase();
const skinReq = /skin|complexion|blemish|acne|pores|smoot|retouch|look (better|good|amazing)|flawless/.test(lp);
// If the agent softened the WHOLE image as a stand-in for skin retouch,
// revert that destructive global filter before applying the real one.
if (skinReq && !traceOps.includes('retouch.skin')) {
const last = trace[trace.length - 1];
if (last && last.op === 'filters.apply' && last.ok) {
try {
await control.invoke('history.undo');
executed.push({ op: 'history.undo', ok: true, error: null, source: 'guard:global-blur' });
} catch (_) {}
}
}
if (skinReq && !traceOps.includes('retouch.skin')) {
await control.invoke('retouch.skin', {});
executed.push({ op: 'retouch.skin', ok: true, error: null, source: 'guard' });
}
// Portrait chain must not brighten: if a global tone pass runs after the
// skin retouch, revert it so the face keeps its original luminance.
if (skinReq) {
const skinIdx = traceOps.lastIndexOf('retouch.skin');
const autoIdx = traceOps.lastIndexOf('photo.autoTone');
const lastOp = traceOps[traceOps.length - 1];
if (skinIdx >= 0 && autoIdx > skinIdx && lastOp === 'photo.autoTone') {
try {
await control.invoke('history.undo');
executed.push({ op: 'history.undo', ok: true, error: null, source: 'guard:portrait-brighten' });
} catch (_) {}
}
}
if (/teeth|smile/.test(lp) && !traceOps.includes('retouch.teeth')) {
await control.invoke('retouch.teeth', {});
executed.push({ op: 'retouch.teeth', ok: true, error: null, source: 'guard' });
}
} catch (_) {}
// Title/text placement guard: place titles RELATIVE to the image layer
// bounds (top-centre with a margin) at ~10% of the image height, so they
// sit inside the photo instead of the empty canvas margin.
try {
const titleIntent = /\btitle\b|\bcaption\b|\bheading\b|\bwatermark\b|\bwordmark\b|\badd\s+(?:a\s+)?(?:text|label)\b|\bwrite\b/i.test(String(prompt));
const traceOps2 = (trace || []).map((t) => t && t.op);
if (titleIntent && traceOps2.includes('text.add')) {
await control.invoke('text.layout', { anchor: 'top-center', sizePct: 0.13, marginPct: 0.05 });
executed.push({ op: 'text.layout', ok: true, error: null, source: 'guard' });
}
} catch (_) {}
// Imperceptible-edit guard: when a GENERIC look/brighten request barely
// changed the image, strengthen it so generic requests are visible but
// still natural. Never run this for structural/action prompts (add a
// layer, resize, add a title, align…) — a tone tweak there is wrong.
try {
if (beforeShot && generic) {
const after = (await control.invoke('screenshot')).result;
const delta = await dataUrlDelta(beforeShot, after && after.dataUrl);
if (delta != null && delta < 0.02) {
try { await control.invoke('photo.autoTone', {}); } catch (_) {}
await control.invoke('adjustments.apply', { type: 'vibrance', params: { vibrance: 22 } });
await control.invoke('adjustments.apply', { type: 'brightness-contrast', params: { brightness: 5, contrast: 8 } });
}
}
} catch (_) {}
// Blown-highlight guard: agents sometimes over-lift exposure/shadows and
// clip large areas to white; step back up to two ops if that happened.
try {
if (beforeShot) {
const beforeClip = await dataUrlClipFraction(beforeShot);
let after = (await control.invoke('screenshot')).result;
let afterClip = await dataUrlClipFraction(after && after.dataUrl);
for (let guard = 0; guard < 2 && beforeClip != null && afterClip != null && (afterClip - beforeClip) > 0.12; guard++) {
await control.invoke('history.undo');
executed.push({ op: 'history.undo', ok: true, error: null, source: 'guard:clipped-highlights' });
after = (await control.invoke('screenshot')).result;
afterClip = await dataUrlClipFraction(after && after.dataUrl);
}
}
} catch (_) {}
// Fold every op the agent ran (via the bridge) into one undo group.
try { await control.invoke('history.collapse', { mark, label: `AI edit: ${String(prompt).slice(0, 60)}` }); } catch (_) {}
}
if (blocked || asked) {
const message = (asked ? (data && (data.reply || data.message)) : null)
|| (data && (data.message || data.reply)) || (needsProvider
? 'Removing or adding objects needs an image generation provider. Enable one in Settings > Models.'
: ((data && data.error) || `Agent error (${res ? res.status : 'no response'})`));
restoreInvoke();
return {
unavailable: false, ok: false, blocked: true, needsProvider, message,
asked,
error: (data && data.error) || null,
reply: (data && (data.reply || data.message)) || '',
toolsOffered: (data && (data.tools_offered || data.tools)) || null,
steps: [], trace, session, applied, rolledBack: applied,
};
}
restoreInvoke();
return {
unavailable: false,
ok: true,
reply: data.reply || data.message || '',
toolsOffered: data.tools_offered || data.tools || null,
steps: Array.isArray(data.steps) ? data.steps : [],
trace,
session,
applied,
};
}
return { version: EDITOR_AGENT_VERSION, endpoint, run, reportStep, isRunning };
}
export default createEditorAgent;
+104
View File
@@ -0,0 +1,104 @@
// Browser side of the editor agent bridge. When the editor is open it
// subscribes to the app's SSE command stream and executes queued ops through
// the editor control API, then posts the result (+ a screenshot) back.
//
// Protocol (see routes/editor_agent_routes.py):
// GET /api/editor/bridge/events?session=<id> -> SSE `data: {id,op,params}`
// POST /api/editor/bridge/result {id,ok,result,error,screenshot,ms}
//
// The agent enqueues with POST /api/editor/bridge/command {session,steps},
// optionally with wait:true to block until this subscriber posts the result.
export const BRIDGE_VERSION = '1.0';
export function startEditorBridge({
control,
session = 'default',
baseUrl = '',
EventSourceImpl = null,
fetchImpl = null,
onCommand = null,
} = {}) {
if (!control || typeof control.invoke !== 'function') {
throw new Error('startEditorBridge requires a control with invoke()');
}
const ES = EventSourceImpl || (typeof EventSource !== 'undefined' ? EventSource : null);
const doFetch = fetchImpl || (typeof fetch !== 'undefined' ? fetch : null);
const eventUrl = `${baseUrl}/api/editor/bridge/events?session=${encodeURIComponent(session)}`;
const resultUrl = `${baseUrl}/api/editor/bridge/result`;
let source = null;
let timer = null;
let retry = 0;
let stopped = false;
// Execute one queued command and report the outcome (with an after screenshot).
async function runAndReport(cmd) {
const id = cmd && cmd.id;
const started = Date.now();
let ok = false;
let result = null;
let error = null;
let screenshot = null;
try {
const out = await control.invoke(cmd.op, cmd.params || {});
ok = !!(out && out.ok);
result = out ? (out.result ?? null) : null;
if (!ok) error = (out && out.error) || 'op failed';
} catch (e) {
error = String(e && e.message ? e.message : e);
}
try {
const shot = await control.invoke('screenshot');
screenshot = shot && shot.result ? shot.result.dataUrl : null;
} catch (_) { /* screenshot is best-effort */ }
const payload = { id, ok, result, error, screenshot, ms: Date.now() - started };
if (onCommand) { try { onCommand(payload, cmd); } catch (_) {} }
if (doFetch) {
try {
await doFetch(resultUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
} catch (_) { /* the agent may have timed out; ignore */ }
}
return payload;
}
function connect() {
if (stopped || !ES) return;
try { source = new ES(eventUrl); } catch (_) { return; }
source.onopen = () => { retry = 0; };
source.onmessage = (ev) => {
retry = 0;
let cmd = null;
try { cmd = JSON.parse(ev.data); } catch (_) { return; }
if (!cmd || !cmd.op) return;
// Fire-and-forget; results go back over /result, not the SSE stream.
runAndReport(cmd);
};
source.onerror = () => {
try { source && source.close(); } catch (_) {}
if (stopped) return;
retry += 1;
timer = setTimeout(connect, Math.min(5000, 500 * retry));
};
}
connect();
return {
version: BRIDGE_VERSION,
session,
eventUrl,
resultUrl,
runAndReport,
stop() {
stopped = true;
try { source && source.close(); } catch (_) {}
if (timer) clearTimeout(timer);
},
};
}
export default startEditorBridge;
+97
View File
@@ -0,0 +1,97 @@
// Programmatic control surface for the PhotoCraft editor.
//
// This module turns the editor's internal operations into a stable,
// JSON-friendly command API so an MCP server (or the in-editor natural
// language entrypoint) can drive the editor without poking at private
// closures. The heavy lifting lives in galleryEditor.js, which builds the
// handler map from its in-scope functions and installs it on
// window.geEditorControl.
//
// Contract:
// control.invoke(op, params) -> Promise<{ ok, result } | { ok:false, error }>
// control.run(steps) -> Promise<Array<stepResult>> (sequential)
// control.list() -> [{ op, description }]
// control.describe(op) -> { op, description } | null
//
// Every op name is namespaced: document.*, layers.*, selection.*,
// adjustments.*, filters.*, transform.*, text.*, history.*, export.*.
export const EDITOR_CONTROL_VERSION = '1.0';
function normalizeError(err) {
if (!err) return 'Unknown error';
if (typeof err === 'string') return err;
return err.message || String(err);
}
export function createEditorControl({ handlers = {}, getState = null, version = EDITOR_CONTROL_VERSION } = {}) {
const registry = new Map();
for (const [op, entry] of Object.entries(handlers)) {
if (!entry) continue;
if (typeof entry === 'function') {
registry.set(op, { run: entry, description: '' });
} else if (typeof entry.run === 'function') {
registry.set(op, { run: entry.run, description: entry.description || '' });
}
}
function describe(op) {
const entry = registry.get(op);
if (!entry) return null;
return { op, description: entry.description };
}
function list() {
return Array.from(registry.keys())
.sort()
.map((op) => ({ op, description: registry.get(op).description }));
}
function snapshot() {
if (typeof getState !== 'function') return {};
try {
return getState() || {};
} catch (_err) {
return {};
}
}
async function invoke(op, params = {}) {
const entry = registry.get(op);
if (!entry) {
return { ok: false, error: `Unknown editor op: ${op}`, op };
}
try {
const result = await entry.run(params || {}, { state: snapshot(), control });
return { ok: true, op, result: result === undefined ? null : result };
} catch (err) {
return { ok: false, op, error: normalizeError(err) };
}
}
async function run(steps) {
const list = Array.isArray(steps) ? steps : [];
const results = [];
for (const step of list) {
const op = step && step.op;
const params = (step && step.params) || {};
// eslint-disable-next-line no-await-in-loop
const res = await invoke(op, params);
results.push(res);
if (!res.ok) break;
}
return results;
}
const control = {
version,
installed: true,
list,
describe,
invoke,
run,
};
return control;
}
export default createEditorControl;
+36
View File
@@ -65,6 +65,42 @@ function renderEffects(source, effects, masks) {
ctx.filter = 'none';
} else if (effect.type === 'sharpen') {
ctx.drawImage(sharpenCanvas(current, effect.params.amount), 0, 0);
} else if (effect.type === 'motion-blur') {
const dist = effect.params.distance;
const rad = (effect.params.angle || 0) * Math.PI / 180;
const dx = Math.cos(rad);
const dy = Math.sin(rad);
const samples = Math.max(1, Math.min(64, Math.round(dist) || 1));
ctx.globalAlpha = 1 / samples;
for (let s = 0; s < samples; s += 1) {
const t = (samples > 1 ? (s / (samples - 1) - 0.5) : 0) * dist;
ctx.drawImage(current, dx * t, dy * t);
}
ctx.globalAlpha = 1;
} else if (effect.type === 'zoom-blur') {
const amt = effect.params.amount / 100;
const samples = Math.max(1, Math.min(48, Math.round(amt * 48) || 1));
const cx = next.width / 2;
const cy = next.height / 2;
ctx.globalAlpha = 1 / samples;
for (let s = 0; s < samples; s += 1) {
const scale = 1 + (s / samples) * amt * 0.5;
const dw = next.width * scale;
const dh = next.height * scale;
ctx.drawImage(current, cx - dw / 2, cy - dh / 2, dw, dh);
}
ctx.globalAlpha = 1;
} else if (effect.type === 'pixelate') {
const size = Math.max(1, effect.params.size);
const sw = Math.max(1, Math.round(next.width / size));
const sh = Math.max(1, Math.round(next.height / size));
const tiny = new OffscreenCanvas(sw, sh);
const tctx = tiny.getContext('2d');
tctx.imageSmoothingEnabled = false;
tctx.drawImage(current, 0, 0, sw, sh);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tiny, 0, 0, next.width, next.height);
ctx.imageSmoothingEnabled = true;
} else if (effect.type === 'color-overlay') {
ctx.drawImage(current, 0, 0);
ctx.globalAlpha = effect.params.opacity;
+51 -1
View File
@@ -9,7 +9,7 @@ export function effectsWithPreview(owner) {
return index < 0 ? [...effects, preview] : effects.map((effect, i) => i === index ? preview : effect);
}
const EFFECT_TYPES = new Set(['gaussian-blur', 'sharpen', 'color-overlay', 'drop-shadow', 'stroke', 'linear-gradient', 'radial-gradient']);
const EFFECT_TYPES = new Set(['gaussian-blur', 'sharpen', 'motion-blur', 'zoom-blur', 'pixelate', 'color-overlay', 'drop-shadow', 'stroke', 'linear-gradient', 'radial-gradient']);
for (const type of Object.keys(LAYER_STYLES)) EFFECT_TYPES.add(type);
export const EFFECT_PRESETS = {
@@ -41,6 +41,9 @@ export function defaultEffectParams(type) {
if (LAYER_STYLES[type]) return styleParams(type);
if (type === 'gaussian-blur') return { radius: 6 };
if (type === 'sharpen') return { amount: 0.5 };
if (type === 'motion-blur') return { distance: 20, angle: 0 };
if (type === 'zoom-blur') return { amount: 40 };
if (type === 'pixelate') return { size: 8 };
if (type === 'color-overlay') return { color: '#ffffff', opacity: 0.2, blendMode: 'source-atop' };
if (type === 'drop-shadow') return { color: '#000000', opacity: 0.45, blur: 12, x: 4, y: 6 };
if (type === 'stroke') return { color: '#ffffff', opacity: 1, width: 3 };
@@ -66,6 +69,12 @@ export function normalizeEffect(effect) {
if (LAYER_STYLES[type]) Object.assign(params, styleParams(type, params));
if (type === 'gaussian-blur') params.radius = Math.max(0, Math.min(200, Number(params.radius) || 0));
if (type === 'sharpen') params.amount = Math.max(0, Math.min(1, Number(params.amount) || 0));
if (type === 'motion-blur') {
params.distance = Math.max(0, Math.min(200, Number(params.distance) || 0));
params.angle = Math.max(-180, Math.min(180, Number(params.angle) || 0));
}
if (type === 'zoom-blur') params.amount = Math.max(0, Math.min(100, Number(params.amount) || 0));
if (type === 'pixelate') params.size = Math.max(1, Math.min(200, Math.round(Number(params.size) || 1)));
if (type === 'color-overlay') {
params.color = /^#[0-9a-f]{6}$/i.test(params.color) ? params.color : defaults.color;
params.opacity = Math.max(0, Math.min(1, Number(params.opacity) || 0));
@@ -114,6 +123,9 @@ export function effectLabel(type) {
return {
'gaussian-blur': 'Gaussian Blur',
sharpen: 'Sharpen',
'motion-blur': 'Motion Blur',
'zoom-blur': 'Zoom Blur',
pixelate: 'Pixelate',
'color-overlay': 'Color Overlay',
'drop-shadow': 'Drop Shadow',
'stroke': 'Stroke',
@@ -212,6 +224,44 @@ export function renderEffects(source, effects = [], shouldContinue = () => true)
const sharpened = sharpenCanvas(current, effect.params.amount, shouldContinue);
if (!sharpened) return current;
ctx.drawImage(sharpened, 0, 0);
} else if (effect.type === 'motion-blur') {
const dist = effect.params.distance;
const rad = (effect.params.angle || 0) * Math.PI / 180;
const dx = Math.cos(rad);
const dy = Math.sin(rad);
const samples = Math.max(1, Math.min(64, Math.round(dist) || 1));
ctx.globalAlpha = 1 / samples;
for (let s = 0; s < samples; s += 1) {
const t = (samples > 1 ? (s / (samples - 1) - 0.5) : 0) * dist;
ctx.drawImage(current, dx * t, dy * t);
}
ctx.globalAlpha = 1;
} else if (effect.type === 'zoom-blur') {
const amt = effect.params.amount / 100;
const samples = Math.max(1, Math.min(48, Math.round(amt * 48) || 1));
const cx = next.width / 2;
const cy = next.height / 2;
ctx.globalAlpha = 1 / samples;
for (let s = 0; s < samples; s += 1) {
const scale = 1 + (s / samples) * amt * 0.5;
const dw = next.width * scale;
const dh = next.height * scale;
ctx.drawImage(current, cx - dw / 2, cy - dh / 2, dw, dh);
}
ctx.globalAlpha = 1;
} else if (effect.type === 'pixelate') {
const size = Math.max(1, effect.params.size);
const sw = Math.max(1, Math.round(next.width / size));
const sh = Math.max(1, Math.round(next.height / size));
const tiny = document.createElement('canvas');
tiny.width = sw;
tiny.height = sh;
const tctx = tiny.getContext('2d');
tctx.imageSmoothingEnabled = false;
tctx.drawImage(current, 0, 0, sw, sh);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tiny, 0, 0, next.width, next.height);
ctx.imageSmoothingEnabled = true;
} else if (effect.type === 'color-overlay') {
ctx.drawImage(current, 0, 0);
ctx.globalAlpha = effect.params.opacity;
+12
View File
@@ -1,9 +1,12 @@
/** Controlled image export dialog and canvas encoding helpers. */
import { exportPsd } from './psd.js';
const FORMAT_META = {
png: { mime: 'image/png', extension: 'png', quality: undefined },
jpeg: { mime: 'image/jpeg', extension: 'jpg', quality: 0.9 },
webp: { mime: 'image/webp', extension: 'webp', quality: 0.9 },
psd: { mime: 'image/vnd.adobe.photoshop', extension: 'psd', quality: undefined },
};
function clampNumber(value, min, max, fallback) {
@@ -43,6 +46,14 @@ export function prepareExportCanvas(sourceCanvas, settings) {
export function encodeExportCanvas(sourceCanvas, settings) {
const normalized = normalizeExportSettings(settings, sourceCanvas.width, sourceCanvas.height);
const output = prepareExportCanvas(sourceCanvas, normalized);
if (normalized.format === 'psd') {
const bytes = exportPsd(output);
return Promise.resolve({
blob: new Blob([bytes], { type: FORMAT_META.psd.mime }),
settings: normalized,
extension: 'psd',
});
}
const meta = FORMAT_META[normalized.format];
return new Promise((resolve, reject) => {
output.toBlob(
@@ -86,6 +97,7 @@ export function openExportDialog({
<button type="button" class="active" data-format="png">PNG</button>
<button type="button" data-format="jpeg">JPEG</button>
<button type="button" data-format="webp">WebP</button>
<button type="button" data-format="psd">PSD</button>
</div></div>
<div class="ge-export-dimensions">
<label class="ge-export-field"><span>Width</span><input id="ge-export-width" type="number" min="1" max="16384" value="${sourceCanvas.width}" /></label>
+238
View File
@@ -0,0 +1,238 @@
/**
* Haze removal (dehaze) — a compact, offline dark-channel-prior implementation
* with a guided-filter refined transmission map.
*
* The dark channel of a hazy photo is dominated by the atmospheric light, so the
* haze can be estimated and removed from a single image:
* 1. dark channel D(x) = min over {R,G,B} of a small local window (min of the
* channels, then a separable minimum filter). The window is kept small
* (patch of ~7-15px) so it does not smear a rectangular halo around hard
* edges.
* 2. atmospheric light A = the mean colour of the brightest 0.1% of the
* dark channel (a robust estimate; a single brightest cell is noisy).
* 3. transmission t(x) = 1 - omega * D(x) / max(A), clamped to >= t0 (0.1).
* 4. refine t with a guided filter (He et al. 2010) using the luminance as the
* guide, so the map follows real edges instead of the min-filter blocks.
* 5. recover J = (I - A) / max(t, t0) + A.
*
* The dark channel, atmospheric light and guided filter run on a bounded working
* copy (<= maxDim) and the refined transmission is up-sampled smoothly, so the
* pass stays interactive on large documents. No network or AI; deterministic.
*/
function clamp(value, lo, hi) {
return value < lo ? lo : value > hi ? hi : value;
}
/* Separable minimum filter (horizontal then vertical) over a Float array. */
function minFilter2D(values, width, height, radius) {
if (radius < 1) return values.slice();
const tmp = new Float32Array(width * height);
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
let min = Infinity;
for (let d = -radius; d <= radius; d += 1) {
const xx = x + d;
if (xx < 0 || xx >= width) continue;
const v = values[y * width + xx];
if (v < min) min = v;
}
tmp[y * width + x] = min;
}
}
const out = new Float32Array(width * height);
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
let min = Infinity;
for (let d = -radius; d <= radius; d += 1) {
const yy = y + d;
if (yy < 0 || yy >= height) continue;
const v = tmp[yy * width + x];
if (v < min) min = v;
}
out[y * width + x] = min;
}
}
return out;
}
/* O(N) mean (box) filter via a summed-area table. */
function boxFilter(src, width, height, radius) {
const stride = width + 1;
const integral = new Float64Array(stride * (height + 1));
for (let y = 0; y < height; y += 1) {
let rowSum = 0;
for (let x = 0; x < width; x += 1) {
rowSum += src[y * width + x];
integral[(y + 1) * stride + (x + 1)] = integral[y * stride + (x + 1)] + rowSum;
}
}
const out = new Float32Array(width * height);
for (let y = 0; y < height; y += 1) {
const y0 = Math.max(0, y - radius);
const y1 = Math.min(height - 1, y + radius);
for (let x = 0; x < width; x += 1) {
const x0 = Math.max(0, x - radius);
const x1 = Math.min(width - 1, x + radius);
const area = (x1 - x0 + 1) * (y1 - y0 + 1);
const sum = integral[(y1 + 1) * stride + (x1 + 1)]
- integral[y0 * stride + (x1 + 1)]
- integral[(y1 + 1) * stride + x0]
+ integral[y0 * stride + x0];
out[y * width + x] = sum / area;
}
}
return out;
}
/*
* Guided filter (He, Sun, Tang 2010) — edge-preserving smoothing of `p` guided
* by `guide`. Both arrays are 0..1; `eps` is the regularisation (1e-3 typical).
*/
function guidedFilter(guide, p, width, height, radius, eps) {
const n = width * height;
const meanGuide = boxFilter(guide, width, height, radius);
const meanP = boxFilter(p, width, height, radius);
const gg = new Float32Array(n);
const gp = new Float32Array(n);
for (let i = 0; i < n; i += 1) {
gg[i] = guide[i] * guide[i];
gp[i] = guide[i] * p[i];
}
const corrGG = boxFilter(gg, width, height, radius);
const corrGP = boxFilter(gp, width, height, radius);
const a = new Float32Array(n);
const b = new Float32Array(n);
for (let i = 0; i < n; i += 1) {
const varG = corrGG[i] - meanGuide[i] * meanGuide[i];
const covGP = corrGP[i] - meanGuide[i] * meanP[i];
a[i] = covGP / (varG + eps);
b[i] = meanP[i] - a[i] * meanGuide[i];
}
const meanA = boxFilter(a, width, height, radius);
const meanB = boxFilter(b, width, height, radius);
const q = new Float32Array(n);
for (let i = 0; i < n; i += 1) q[i] = meanA[i] * guide[i] + meanB[i];
return q;
}
export function dehazeImageData(src, width, height, options = {}) {
const strength = clamp(Number(options.strength ?? 0.8), 0, 1);
if (strength <= 0 || width < 2 || height < 2) return src;
const omega = clamp(Number(options.omega ?? 0.95), 0, 1) * strength;
// Small dark-channel patch (Photoshop-style 7-15px) keeps the halo tight.
const patch = Math.max(3, Math.min(31, Math.round(Number(options.patch) || 15)));
const guideRadius = Math.max(1, Math.round(Number(options.guideRadius) || 40));
const eps = Math.max(1e-6, Number(options.eps) || 1e-3);
const t0 = clamp(Number(options.t0 ?? 0.1), 0.02, 1);
const maxDim = Math.max(16, Number(options.maxDim) || 1024);
const scale = Math.min(1, maxDim / Math.max(width, height));
const sw = Math.max(2, Math.round(width * scale));
const sh = Math.max(2, Math.round(height * scale));
// Radius that yields a ~patch-pixel window at the working resolution.
const radius = Math.max(1, Math.round((patch - 1) / 2 * scale));
// Block down-sample: the darkest per-pixel min(R,G,B) in each cell, its colour
// (for the atmospheric light) and the mean luminance (the guided-filter guide).
const dark = new Float32Array(sw * sh);
const darkColor = new Float32Array(sw * sh * 3);
const lum = new Float32Array(sw * sh);
const bw = width / sw;
const bh = height / sh;
for (let sy = 0; sy < sh; sy += 1) {
const y0 = Math.floor(sy * bh);
const y1 = Math.min(height, Math.max(y0 + 1, Math.ceil((sy + 1) * bh)));
for (let sx = 0; sx < sw; sx += 1) {
const x0 = Math.floor(sx * bw);
const x1 = Math.min(width, Math.max(x0 + 1, Math.ceil((sx + 1) * bw)));
let best = 256;
let br = 0;
let bg = 0;
let bb = 0;
let lumSum = 0;
let count = 0;
for (let y = y0; y < y1; y += 1) {
for (let x = x0; x < x1; x += 1) {
const i = (y * width + x) * 4;
const r = src[i];
const g = src[i + 1];
const b = src[i + 2];
const mn = Math.min(r, g, b);
if (mn < best) { best = mn; br = r; bg = g; bb = b; }
lumSum += (r * 0.299 + g * 0.587 + b * 0.114) / 255;
count += 1;
}
}
const k = sy * sw + sx;
dark[k] = best;
darkColor[k * 3] = br;
darkColor[k * 3 + 1] = bg;
darkColor[k * 3 + 2] = bb;
lum[k] = count ? lumSum / count : 0;
}
}
const filtered = minFilter2D(dark, sw, sh, radius);
// Atmospheric light: mean colour of the brightest 0.1% of the dark channel.
const total = sw * sh;
const topCount = Math.max(1, Math.round(total * 0.001));
const order = new Int32Array(total);
for (let k = 0; k < total; k += 1) order[k] = k;
const ordered = Array.from(order).sort((a, b) => filtered[b] - filtered[a]);
let ar = 0;
let ag = 0;
let ab = 0;
for (let n = 0; n < topCount; n += 1) {
const idx = ordered[n];
ar += darkColor[idx * 3];
ag += darkColor[idx * 3 + 1];
ab += darkColor[idx * 3 + 2];
}
ar /= topCount;
ag /= topCount;
ab /= topCount;
const aLum = Math.max(1, Math.max(ar, ag, ab));
// Raw per-cell transmission (clamped to >= t0), then guided-filter refined.
const rawT = new Float32Array(total);
for (let k = 0; k < total; k += 1) {
rawT[k] = clamp(1 - omega * (filtered[k] / aLum), t0, 1);
}
const refined = guidedFilter(lum, rawT, sw, sh, guideRadius, eps);
const small = new Uint8ClampedArray(sw * sh * 4);
for (let k = 0; k < sw * sh; k += 1) {
const v = Math.round(clamp(refined[k], t0, 1) * 255);
small[k * 4] = v;
small[k * 4 + 1] = v;
small[k * 4 + 2] = v;
small[k * 4 + 3] = 255;
}
let tFull = null;
if (typeof document !== 'undefined') {
const sm = document.createElement('canvas');
sm.width = sw;
sm.height = sh;
sm.getContext('2d').putImageData(new ImageData(small, sw, sh), 0, 0);
const big = document.createElement('canvas');
big.width = width;
big.height = height;
const bctx = big.getContext('2d');
bctx.imageSmoothingEnabled = true;
bctx.imageSmoothingQuality = 'high';
bctx.drawImage(sm, 0, 0, width, height);
tFull = bctx.getImageData(0, 0, width, height).data;
}
const out = new Uint8ClampedArray(src.length);
for (let i = 0, p = 0; i < src.length; i += 4, p += 1) {
const t = tFull ? Math.max(t0, tFull[p * 4] / 255) : 1;
out[i] = clamp((src[i] - ar) / t + ar, 0, 255);
out[i + 1] = clamp((src[i + 1] - ag) / t + ag, 0, 255);
out[i + 2] = clamp((src[i + 2] - ab) / t + ab, 0, 255);
out[i + 3] = src[i + 3];
}
return out;
}
File diff suppressed because it is too large Load Diff

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