mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 20:49:41 +02:00
Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9df310c30a | ||
|
|
50b8f1d9a0 | ||
|
|
1255e28f6f | ||
|
|
9d12fc7f94 | ||
|
|
5d406c9705 | ||
|
|
a8782b364f | ||
|
|
d8da1bd3ff | ||
|
|
06871eb7e3 | ||
|
|
5d59c1764d | ||
|
|
cfcd9d288b | ||
|
|
9c22114b5a | ||
|
|
98b2124d7e | ||
|
|
bdaec320f5 | ||
|
|
dfe20a3742 | ||
|
|
de5216b83f | ||
|
|
57eefd7aa5 | ||
|
|
2c81bbc08b | ||
|
|
b374121c18 | ||
|
|
b1c4330680 | ||
|
|
47359e4002 | ||
|
|
a8e7d60db4 | ||
|
|
8dc70a5f1d | ||
|
|
4d129086d1 | ||
|
|
566c65c3c9 | ||
|
|
cd7d8c7329 | ||
|
|
c55af9ec39 | ||
|
|
1a54217bfb | ||
|
|
70742d400a | ||
|
|
d5809d1808 | ||
|
|
a0ac10a07c | ||
|
|
f7814ad364 | ||
|
|
3172befd5d | ||
|
|
29ffc62536 | ||
|
|
4cb3a4aac8 | ||
|
|
b6531cbf79 | ||
|
|
d16bf34e34 | ||
|
|
e6989bdb40 | ||
|
|
6ab6bbbbd4 | ||
|
|
c15c19fab7 | ||
|
|
f6a30d7335 | ||
|
|
db93491dd1 | ||
|
|
b7ff54b2ec | ||
|
|
dc63d1f1a6 | ||
|
|
7c5920d3b9 | ||
|
|
e1e670594b | ||
|
|
2e28e17834 | ||
|
|
90f18438ff | ||
|
|
5b62f397ec | ||
|
|
1e54ebcdf4 | ||
|
|
0364bea166 | ||
|
|
c7e8ff616f | ||
|
|
21fbff4d8a | ||
|
|
8ffb2b0644 | ||
|
|
80ebf8b549 | ||
|
|
c101cc8716 | ||
|
|
cceb24ed8f | ||
|
|
60dab7ce3f | ||
|
|
a5263b3252 | ||
|
|
90cd481b9f | ||
|
|
787e5e2a03 | ||
|
|
097433c86f | ||
|
|
e738c776c1 | ||
|
|
e10f0dabdb | ||
|
|
661c89cefd | ||
|
|
a122e867ef | ||
|
|
a68f23e647 | ||
|
|
f0f43ddbad | ||
|
|
ea53916adc | ||
|
|
585127deb2 | ||
|
|
e742d00c98 | ||
|
|
1a363a3e62 | ||
|
|
577b6d7384 | ||
|
|
5eacb1cf03 | ||
|
|
5fbe451c26 | ||
|
|
99e537ef1a | ||
|
|
67c7973aa5 | ||
|
|
534712e50f | ||
|
|
f69cd4874c | ||
|
|
1ac3c09054 | ||
|
|
95fb5fc226 | ||
|
|
eae225bf9a | ||
|
|
4d9d93dfff | ||
|
|
c82f6c802e | ||
|
|
0809f59f0f | ||
|
|
eda95adaa9 | ||
|
|
41a209e96d | ||
|
|
7102fdb23a | ||
|
|
49c92e4723 | ||
|
|
3f2c23cb0f | ||
|
|
f7ce8e4767 | ||
|
|
f1c64994ad | ||
|
|
12c8e080c1 | ||
|
|
9893a7f64a | ||
|
|
5b2da424a1 | ||
|
|
aa84447899 | ||
|
|
a0e1a2e33b | ||
|
|
6da22f0db0 | ||
|
|
dc9c4b3bda | ||
|
|
1cf5c8c8ad | ||
|
|
7eda39e7f7 | ||
|
|
f0db5f827f | ||
|
|
aa4e1ce9cf | ||
|
|
b8cb4670dd | ||
|
|
4a33b91107 | ||
|
|
28b531fa5b | ||
|
|
68310619a7 | ||
|
|
fe821fb679 | ||
|
|
d7606366a2 | ||
|
|
42f0b28c75 | ||
|
|
055f18fb66 | ||
|
|
cf2a7f54bf | ||
|
|
beeec63f72 | ||
|
|
fad32eeaab | ||
|
|
c1458d8ab8 |
+262
@@ -1,5 +1,267 @@
|
||||
# aicodeman
|
||||
|
||||
## 1.1.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Mobile image uploads, reliable input delivery, and gesture window dragging.
|
||||
|
||||
**Mobile image uploads (camera-roll picker / drag-drop / paste).** The "🖼 Image" button now handles real photo batches: up to 20 images per batch uploaded with bounded concurrency and a live "Uploading N/M…" progress toast (with a summary of successes, failures, and whether the 20-cap trimmed the selection). The per-file limit is raised from 10MB to 50MB (`MAX_PASTE_IMAGE_BYTES`, env-overridable via `CODEMAN_MAX_PASTE_IMAGE_BYTES`) so full-resolution phone photos and large screenshots are accepted. Very large images are downscaled to ≤4096px on the longest edge before upload, fixing iOS Safari's ~16.7M-px `<canvas>` limit that previously made huge photos fail to re-encode. Also fixes a latent concurrency bug the batch path exposed where the first parallel uploads to a session raced on creating `.claude-images/` and failed with EEXIST.
|
||||
|
||||
**Reliable, exactly-once input delivery.** A "sent" prompt could be silently lost on a flaky connection (e.g. a train): a half-open WebSocket accepts `ws.send()` without error while discarding the frame, and nothing was queued or resent. Input is now recorded durably (localStorage) with a stable clientId + monotonic per-session sequence before delivery, and only dropped once the server ACKs it — delivered over the WebSocket (acked via `{t:'ia',seq}`) or, when the socket is down, over POST in order. A 2s sweep force-reconnects a half-open socket; pending input survives reconnects and page reloads. The server applies each `(clientId, seq)` at most once (`Session.shouldApplyInput`), so an at-least-once resend can never type the prompt twice. Untagged input (curl/legacy) is unchanged. See `docs/reliable-input-delivery.md`.
|
||||
|
||||
**Gesture beta: drag agent windows.** With the camera hand-tracking overlay, you can now pinch and move the floating subagent and ultracode run/transcript windows. They keep their glowing connector line to the session tab while moving and can travel across a multi-monitor seam.
|
||||
|
||||
## 1.1.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Security: harden all frontend inline `onclick`/`ondblclick` handlers against a stored-XSS double-context bug.
|
||||
|
||||
Many inline handlers interpolated values as `'${escapeHtml(value)}'` — a JavaScript string literal sitting inside an HTML attribute. The browser HTML-decodes the attribute value _before_ parsing the handler source, so `escapeHtml`'s `'` reverts to a literal `'` and a quote-bearing id/name/path/URL breaks out of the JS string into executable code. `escapeHtml` alone is insufficient for this JS-string-within-HTML-attribute context.
|
||||
|
||||
All affected handlers now use `escapeHtml(JSON.stringify(value))`: `JSON.stringify` JS-encodes and quote-wraps the value, then `escapeHtml` handles the HTML-attribute layer, so the value round-trips as a single inert string argument.
|
||||
- ultracode run/agent cards and minimized-tab badges (`ultracode-panel.js`, `ultracode-windows.js`) — PR #132.
|
||||
- Session tabs (click/rename/gear/detach/close), notifications, subagent windows + dropdowns, the agents/tools/log-viewer/image-popup panels, mux-session monitor rows, and case-management buttons (`app.js`, `notification-manager.js`, `subagent-windows.js`, `panels-ui.js`, `session-ui.js`).
|
||||
- Two non-`escapeHtml` variants of the same class: a pre-escaped mux-session id in `panels-ui.js` (`selectSession`/`killMuxSession`) and a fully raw, unescaped `phase.id` in `orchestrator-panel.js` (`orchestratorSkipPhase`/`orchestratorRetryPhase`).
|
||||
|
||||
The most realistic exploitation vector was file paths in the project-insights log-viewer link, since filenames can legally contain a single quote. Purely numeric interpolations and developer-literal handler strings were left unchanged.
|
||||
|
||||
## 1.1.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Ultracode (Workflow-tool) floating windows — agent transcripts in-page, and minimize-to-tab.
|
||||
- **Agent transcripts open in-page, connected, instead of a detached browser popup.** Clicking an agent card (in a run window or the dock panel) now opens the agent's live transcript as its own draggable floating window, tied by a connector line to its parent run window (falling back to the run's session tab if that window has since closed) — the same line idiom the run windows use. Re-clicking a card focuses the existing window; closing it removes the window and its line. (Previously this spawned a separate `window.open` browser popup.)
|
||||
- **The window "−" button now minimizes into the originating session tab**, mirroring the subagent-window idiom. The window genie-animates into its tab and is tracked there; the tab shows an `ULTRA` badge whose hover/click dropdown lists each minimized item (🧬 run windows, 📄 agent transcripts). Click an item to restore its floating window, or dismiss it with ×. A run minimized while still active keeps tracking in the background and its badge auto-clears shortly after the run finishes. Both run windows and agent-transcript windows minimize into the same merged badge.
|
||||
- Removed the old collapse-to-header behavior that the "−" button previously triggered (now superseded by minimize-to-tab).
|
||||
|
||||
## 1.1.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Keep the `/compact` button in the extended (full) mobile keyboard accessory bar; only the simple bar drops it. (1.1.12 had removed it from both.)
|
||||
|
||||
## 1.1.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Remove the `/compact` button from the mobile keyboard accessory bar. It had been reintroduced in 1.1.10; this removes the button from both the simple and full accessory-bar layouts (the underlying command handler is left in place as inert plumbing).
|
||||
|
||||
## 1.1.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Ultracode (Workflow-tool) run visualization — much better live tracking.
|
||||
|
||||
While a run is in flight, the watcher previously showed empty agent slots ("agent N", 0 tokens, raw `wf_…` id as the title) because the detailed completion JSON only lands when the run finishes. The live path now enriches in-flight runs directly from the on-disk transcript tree:
|
||||
- **Real per-agent stats mid-run** — tokens and tool-call counts are parsed from each `agent-<id>.jsonl` transcript (tool counts match the final accounting exactly; token totals land within ~1% of the completion value), with model and a prompt preview. All mtime-cached (transcripts, journal, and script meta) so idle polls do no extra reads.
|
||||
- **Readable window/run title** — workflow name, summary, and phases are derived from the persisted `workflows/scripts/<name>-<runId>.js` instead of showing the raw run id.
|
||||
- **Agent status colors** — done agents show green, working agents show yellow (this also fixes the run/agent status badges, which referenced undefined `--success`/`--warning` CSS variables and were rendering with no color).
|
||||
- **Connector line** — the floating-window → session-tab line now uses the session-tab accent blue (was purple).
|
||||
- **Click a run to open its floating window** — clicking a workflow in the dock panel opens (or focuses) its floating window with the connector line, in addition to the auto-popped windows.
|
||||
- Agents are ordered by journal launch order; concurrent run-detail fetches are de-duplicated.
|
||||
|
||||
## 1.1.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Mobile CJK input, iPad keyboard accessory bar, and terminal touch interaction fixes (PRs #130, #131).
|
||||
|
||||
Mobile / CJK (#130):
|
||||
- Restore reliable real-time CJK (e.g. Pinyin) composition in the always-visible textarea, and refocus input when the terminal is tapped.
|
||||
- Stop clearing the textarea during `compositionstart` — some IMEs include existing text in the composition region, and clearing it mid-composition corrupted input.
|
||||
- iPad-specific fixes: `#cjkInput` positioning, paste-dialog placement, and duplicated voice-dictation output.
|
||||
- Split CJK keyboard positioning by device size (phones vs iPad use different keyboard offsets).
|
||||
- iPad accessory-bar styling/positioning: moved the accessory-bar and paste-overlay base styles out of the `max-width:1023px`-gated mobile stylesheet so iPad landscape (≥1024px) renders them correctly.
|
||||
- Raise the toolbar stacking context while the case-settings popover is open so the popover is no longer hidden behind the toolbar.
|
||||
- Restore the `/compact` button to the keyboard accessory bar (with double-tap confirmation, like `/clear`); the paste dialog now submits pasted text on "Send".
|
||||
|
||||
Terminal touch + forced redraw (#131):
|
||||
- Enable terminal touch interaction on all touch devices and show the stop button on touch devices.
|
||||
- Add an 8px tap threshold so micro-drift is treated as a tap, not a scroll, fixing cases where a tap failed to register.
|
||||
- Tap-to-position the cursor via a synthesized mouse report, gated on the live mouse-tracking mode so it never triggers local text selection when tracking is off; let SGR mouse reports through to the PTY even while the CJK input field owns focus.
|
||||
- Suppress the cursor/momentum side effects of a sub-threshold tap so a jittery tap no longer both positions the cursor and starts a momentum fling.
|
||||
- New opt-in, per-device "Redraw Terminal" header button (`showRedrawButton`, default off) that forces an xterm redraw via a resize jitter to clear occasional rendering glitches; the resize path now accepts a `force` flag (threaded through the session, HTTP, and WebSocket resize routes) that guarantees a SIGWINCH/redraw at the current device's size without bypassing multi-client resize arbitration.
|
||||
|
||||
## 1.1.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Two welcome-screen tunnel changes:
|
||||
- **UI (Daylight Blue skin):** the **Cloudflare Tunnel** button is now purple (was orange/yellow), keeping the three welcome buttons visually distinct — Claude blue, Tunnel purple, OpenCode green.
|
||||
- **Enable a tunnel without `CODEMAN_PASSWORD`, with a warning.** Previously enabling the Cloudflare tunnel with no password set was hard-refused unless you set `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1`. Now you can opt in straight from the browser: clicking the tunnel toggle without a password pops a **security confirm dialog** ("publishes this machine to a public URL with no login — effectively remote code execution; set CODEMAN_PASSWORD instead"), and only on confirm does it enable, sending an explicit per-request `acknowledgeUnauthTunnel:true`. The server logs a loud warning whenever a passwordless public tunnel starts. curl/API/CLI callers are unchanged — still refused unless they set a password, set the env var, or pass `acknowledgeUnauthTunnel:true` — so nothing gets exposed accidentally. The acknowledgment is an action field and is never persisted to settings.json.
|
||||
|
||||
## 1.1.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- UI (Daylight Blue skin): give the welcome-screen action buttons distinct colors instead of all reading blue. **Run Claude Code** keeps the blue accent, **Cloudflare Tunnel** now uses Cloudflare's brand orange, and **Run OpenCode** uses an emerald green — so the three are visually distinguishable at a glance. Scoped to the default `daylight-blue` skin only (daylight-green and OG are unchanged), with matching hover/active states and dark ink for contrast. Verified in a real browser: the three buttons compute to blue / orange / green gradients on the welcome overlay.
|
||||
|
||||
## 1.1.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix: terminal scroll-up (scrollback) intermittently breaking for **Claude** sessions — most visible on iPhone, where you suddenly "can't scroll up the Claude console."
|
||||
|
||||
Root cause: Claude Code periodically emits alternate-screen switches (`\x1b[?1049h`/`\x1b[?47h`/`\x1b[?1047h`), scrollback-erase (`\x1b[3J`), and mouse-tracking enables — typically when it draws a full-screen UI (pickers/dialogs, the boot welcome). xterm.js obeys these by moving to the scrollback-less alternate buffer (or wiping saved lines / hijacking the wheel), so the conversation history becomes unreachable until Claude returns to its normal view. Codeman already stripped these sequences so history stays scrollable, but the strip was gated to **Codex mode only** — Claude (and the equivalent buffer-replay path) let them through.
|
||||
|
||||
The strip is now shared via a single `isAltScreenStripMode(mode)` predicate (`codex || claude`) applied at BOTH sites that were Codex-only: the live PTY stream (`Session._handleTerminalOutput`, including the split-across-chunks carry reassembly) and the `/terminal` buffer replay used on tab-switch/reconnect. `shell` is deliberately excluded so full-screen TUIs run from a shell (vim/less/htop) keep their alternate screen; `opencode` is also unchanged.
|
||||
|
||||
Verified end-to-end on an isolated instance against a real Claude session: the replayed buffer and live stream now carry zero alt-screen/scrollback-erase/mouse sequences, the terminal stays in the normal buffer with scrollback intact, and touch swipe-up scrolls correctly. Covered by new unit tests (`test/claude-scrollback-strip.test.ts`); the existing Codex strip tests are unchanged.
|
||||
|
||||
## 1.1.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix: ultracode floating run windows now pop on a fresh device/browser that loads while a run is already active.
|
||||
|
||||
`ultracodeFloatingWindows` syncs from the server (it's a non-display setting), but on a first-time device the SSE `getLightState` run snapshot can seed the run list BEFORE the async settings load resolves — so the floating-window gate read `false` at that instant and skipped any already-active run, leaving the window un-popped until the next ~10s watcher tick. The app now re-runs `syncAllUltracodeFloatingWindows()` once server settings finish loading (in the `loadAppSettingsFromServer().then()` callback), so an in-flight run pops its window immediately. Idempotent: open windows are left as-is, and if the setting is off any premature windows are torn down. Verified end-to-end against a real in-flight run on an isolated instance — a pristine browser (empty localStorage) seeds the setting from the server and pops the active run's window ~0.4s after first paint.
|
||||
|
||||
Also corrected a stale `@fileoverview` comment in `ultracode-windows.js` that claimed the floating windows are gated on `showUltracodeAgents`; they are gated on the dedicated `ultracodeFloatingWindows` toggle (only the docked "Ultracode Agents" panel uses `showUltracodeAgents`).
|
||||
|
||||
## 1.1.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix: the Ultracode Agents panel's (×) Close button now fully hides the panel.
|
||||
|
||||
`closeUltracodeAgentsPanel()` only removed the `open` class, which drops the bottom-docked drawer to its collapsed _peek_ state (the 36px header strip stays visible) rather than closing it — so clicking (×) looked like it did nothing. It now also adds the `hidden` class (`display:none`), mirroring `closeSubagentsPanel()`. It deliberately does NOT flip the `showUltracodeAgents` setting (that also gates the run watcher and floating windows); the header launcher button reopens the panel. Verified in a real browser: after (×) the panel computes `display:none`.
|
||||
|
||||
## 1.1.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix: ultracode floating run windows (and the live dock panel) now appear DURING an in-flight Workflow/ultracode run, not only after it finishes.
|
||||
|
||||
The Workflow runtime writes the run-state file `…/workflows/wf_<id>.json` only at completion (always a terminal status); while a run is live, its only on-disk state is the sibling `…/subagents/workflows/wf_<id>/` transcript tree. `workflow-run-watcher` previously scanned only the completion file, so it never observed a run until it was already terminal — and the floating-window auto-pop is gated on an ACTIVE run, so it never fired for a live run (the feature was effectively dead for in-flight runs).
|
||||
|
||||
The watcher now ALSO scans the `subagents/workflows/wf_<id>/` transcript tree and synthesizes a minimal ACTIVE run (status `running`, agent slots keyed by their `agentId` so the agent-card → live-transcript click still works, `lastActivityAt` from the newest agent/journal mtime, per-agent done/running derived from the run journal's `result` events) when no completion file exists yet. When the run finishes, the real `wf_<id>.json` supersedes the synthesized record (same runId), restoring full phase/token detail and the normal finish → 8s-grace auto-close flow. The watcher stays standalone (it never imports subagent-watcher). Verified end-to-end against a real in-flight run; adds unit coverage for live synthesis, agentId preservation, journal-derived state, empty-dir skipping, and completion-file precedence.
|
||||
|
||||
## 1.1.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Ultracode floating run windows + a dedicated toggle to control them.
|
||||
- **New: floating ultracode run windows.** When enabled, each active ultracode / Workflow run pops a small draggable window (like the file browser) connected by a glowing line to its originating session tab — the same connector-line idiom as subagent windows. The tab is resolved by matching the run's `sessionUuid` to a session's `claudeSessionId`. The window mirrors the live agent grid (phases, per-agent model / tokens burned / tool calls / state), auto-closes a few seconds after its run finishes, and remembers windows you explicitly dismiss so they don't re-pop. These windows are **additional to** the existing docked "Ultracode Agents" master-detail panel, which is unchanged.
|
||||
- **New setting "Ultracode Floating Windows"** (App Settings → Display), **default OFF**, independent of the "Ultracode Agents" panel toggle. Either toggle now starts the server-side workflow-run watcher (at boot and on live settings change), so the floating windows work even with the docked panel off.
|
||||
- Internals: new frontend module `ultracode-windows.js` (load order 15.5); ultracode connector lines are appended into the shared `#connectionLines` SVG within the existing batched read/write reflow pass in `subagent-windows.js`; new `ultracodeFloatingWindows` app-settings key in `schemas.ts`; watcher gating in `server.ts` + `system-routes.ts` now ORs both ultracode toggles.
|
||||
- Docs: `CLAUDE.md` brought up to date for the 1.1.2 ultracode/workflow-run subsystem (Agents / Frontend / Types / Config inventories, JS load order, a Key Patterns entry) and the new floating-windows feature.
|
||||
|
||||
## 1.1.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Ultracode/Workflow run visualization + subagent discovery fixes.
|
||||
- **Ultracode / Workflow run visualization** (new, opt-in): App Settings → Display → "Ultracode Agents" (`showUltracodeAgents`, default OFF) adds a master-detail tab that shows ultracode / Workflow-tool runs like Claude Code's "working agents" view — the LEFT pane lists runs and their phases (selectable tasks), the RIGHT pane shows each run's agents with model, live state, tokens burned, and tool calls. Clicking an agent opens its live transcript. Backed by a new standalone workflow-run watcher that reads the per-run state JSON (stripping the heavy embedded script/result/logs so payloads stay small), exposes `GET /api/workflows` and `GET /api/workflows/:runId`, and broadcasts `workflow:run_discovered/updated/removed` SSE events. The header launcher and panel stay hidden until the setting is enabled (the setting is synced across devices, not per-device).
|
||||
- **Subagent tracking discovery fix**: restored subagent tracking after Claude Code changed the on-disk format from `agent-*.jsonl` to `agent-*.meta.json` (background agents were showing 0). Also discovers workflow-nested subagents under `subagents/workflows/<wf>/` and hardens the meta→transcript upgrade path so an agent re-points to its `.jsonl` transcript once it appears.
|
||||
- **File viewer**: opens audio, SVG, and other binary files the same way the attachments viewer does.
|
||||
- **Tooling**: hardened the real-overview screenshot capture script and documented the `deviceScaleFactor` / static-cache gotchas.
|
||||
|
||||
## 1.1.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Six reviewed contributor PRs (all adversarially reviewed and fixed before merge):
|
||||
- **Markdown sanitizer hardened against mutation-XSS (#126).** The denylist `_sanitizeHtml` is replaced with vendored DOMPurify 3.4.8 (authentic, byte-matched to the official dist) wired via a new `sanitize-html.js` allowlist, with a fail-closed escape fallback. The curated allowlist is genuinely enforced (no `USE_PROFILES` override) so non-markdown tags and svg/math/style/script/event-handler/`javascript:` vectors are stripped while legitimate markdown survives.
|
||||
- **Hook-event secret now required unconditionally (#127).** The `/api/hook-event` + `/api/status-telemetry` localhost bypass requires the per-instance hook secret whether or not a managed tunnel is running, closing the own-loopback-reverse-proxy gap. A self-heal refreshes pre-secret hook configs in existing cases on spawn so password-protected installs don't silently 401 their hooks. No-password loopback installs are unaffected.
|
||||
- **`codeman doctor` dependency checker (#125).** New `doctor`/`check-deps` command probes Node, the agent CLIs, tmux, and document converters per environment (linux/darwin/win32/wsl), with grouped or `--json` output and a non-zero exit when a required tool is missing. Requires Node 22+, reports `pdftoppm` (used for PDF/Office thumbnails), and validates `--category`.
|
||||
- **macOS Option / physical-key session shortcuts (#129).** Tab switching matches physical key codes (`e.code`) so Option+1–9 works on macOS layouts that remap Option, plus Option/Alt+`[`/`]` for previous/next session — without leaking escape sequences into the focused terminal.
|
||||
- **Desktop session tabs auto-wrap to a second row on overflow (#128)** instead of horizontal scrolling (off when the manual two-row layout is pinned; mobile/tablet unchanged), re-evaluated on window resize.
|
||||
- **CJK input textarea hidden on the welcome screen (#123)** so it no longer floats over the welcome overlay, and re-shown on session entry; vertical centering fixed.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- **Plan Usage Limits chip (new).** A header chip now shows your live Claude plan usage — the 5-hour and weekly windows as a percentage — parsed from Claude Code's statusLine telemetry (CLI v2.1.80+). It's opt-in via **App Settings → Display → "Plan Usage Limits"** (default OFF). The toggle is **per-device**: turn it on at your desk without it appearing on your phone. Telemetry collection is decoupled from display, so one device's preference never affects another's, and the last-known value replays instantly on reconnect. Distinct from auto-resume (which reacts to the limit _message_) — this proactively shows the live %.
|
||||
|
||||
**Attachments.** New attachment history drawer to browse files referenced by a session (COD-39), plus document previews and thumbnails on attachment cards (COD-38). The header **Attachments button is now opt-in** (default OFF) via **App Settings → Display → "Attachments Button"**, per-device like the Response Viewer button.
|
||||
|
||||
**Settings & models.** Added Opus 4.6 options to the Claude Model picker. Removed the legacy Token Count / Show Cost header toggles and moved Plan Usage Limits to the top of the Display settings. Slimmed the Skin picker control to match its row.
|
||||
|
||||
**Mobile & header polish.** Restored the response-viewer (eye) button on phones; kept the phone header minimal (settings gear + lifecycle log stay in the toolbar). Added two regression guards so header controls can't silently leak onto the mobile header again — a CI-runnable static policy check plus a real-browser E2E test.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
### Major Changes
|
||||
|
||||
- # Codeman 1.0.0 🎉
|
||||
|
||||
The first stable release of Codeman — and it comes with a fresh new look.
|
||||
|
||||
**New: theme skins.** Codeman now ships a built-in skin switcher (App Settings → Display → Appearance):
|
||||
- **OG Codeman** — the original look, preserved exactly.
|
||||
- **Daylight Green** — a fresh emerald-on-slate theme.
|
||||
- **Daylight Blue** — bright sky-blue on lifted slate (the new default).
|
||||
|
||||
Skins apply instantly, persist per device (with a pre-paint script so there's no flash on load), and re-theme any open terminals live. The system is built on `html[data-skin]` design tokens and self-hosted Manrope (UI) + JetBrains Mono (terminal) fonts — no external CDN, CSP-safe.
|
||||
|
||||
**1.0.0 milestone.** This marks the start of the stable 1.x line: the CLI, documented environment variables, and the `{ success, data }` HTTP/SSE API envelope follow semantic versioning (see `docs/versioning-policy.md`).
|
||||
|
||||
**Thank you to everyone who helped build Codeman.** This release is dedicated to all of our contributors for their work on the project: Ark0N, Aamer Akhter (@aakhter), Tenggan Zhang (@TeigenZhang), zhouyuan / @sunnyzhouy, jaypark, Marco Migozzi, Skúli Arnlaugsson, Aaron Fields, Loïc Sculier, and Noah Waldner (@noahwaldner). 💙
|
||||
|
||||
## 0.9.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Security hardening for the tunnel exposure path, Codex terminal rendering fixes, and a mobile modal fix.
|
||||
|
||||
**Security (PR #115, COD-54/COD-55):**
|
||||
- `/api/hook-event` localhost bypass is now gated while the managed Cloudflare tunnel is running: tunneled traffic arrives with a loopback source IP, so the bypass additionally requires a per-instance shared secret (`X-Codeman-Hook-Secret`, 256-bit, `~/.codeman/hook-secret`, mode 0600). Locally generated hook commands read the secret file at execution time via `$CODEMAN_HOOK_SECRET_FILE` (exported into every managed session's environment), so the value never lands on command lines or in case configs, and running sessions pick up a new secret without respawn. Failed presentations rate-limit in a dedicated per-IP bucket so misfiring legacy hooks can never lock out the Basic-Auth login path. With no tunnel running, behavior is unchanged.
|
||||
- Enabling the Cloudflare tunnel now **refuses with 403** when no `CODEMAN_PASSWORD` is set (a public tunnel URL with no auth is effectively public RCE), unless `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1` explicitly acknowledges the exposure. The settings UI surfaces the refusal as an error toast and reverts the toggle.
|
||||
|
||||
**Codex rendering (PRs #116, #117):**
|
||||
- Alt-screen toggles (`?47/?1047/?1049`), scrollback-erase (`CSI 3 J`), and mouse-tracking enables (`?1000`–`?1007`) are stripped from the Codex byte stream (live + replay), so conversation history survives tab switches and the scroll wheel scrolls the viewport instead of being hijacked. Sequences split across PTY chunk boundaries are reassembled via a small carry before stripping, so a split `?1049h` can no longer trap xterm in the scrollback-less alt buffer.
|
||||
- Smaller 32KB first-frame write budget for Codex sessions keeps dense synchronized redraws from stalling the renderer; a 1.5s grace window after a manual scroll-up suppresses sticky-scroll so high-frequency `• Working (Ns)` status ticks no longer snap the viewport back to the bottom while reading earlier output.
|
||||
|
||||
**Mobile:** session-options modal raised above the fixed mobile/tablet header (z-index 1300 vs 1200) so the close button is reachable on phones; Respawn tab controls regrouped.
|
||||
|
||||
**Docs:** security-architecture.md updated for the secret-gated hook bypass (including the external-proxy caveat) and the tunnel password guard; README documents auto-resume on usage limit.
|
||||
|
||||
## 0.9.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Auto-resume on usage limit ("token pause" control) plus a set of mobile-view fixes for regressions introduced in 0.9.8.
|
||||
|
||||
**Auto-resume on usage limit** — new opt-in checkbox at the top of the session Respawn tab (off by default). When Claude stops because a usage limit was reached, Codeman parses the reset time from the limit message, waits until the limit lifts (plus a 2-minute safety buffer), then dismisses the rate-limit dialog (Esc) and sends "continue" so the session picks its work back up automatically. All Claude Code message formats from 1.0.x through 2.1.x are recognized ("5-hour limit reached ∙ resets 8pm", "Limit reached · resets 1pm (America/Chicago) · /upgrade…", "You've hit your weekly limit · resets Mon 12:00am", weekly date forms, and the raw API `usage limit reached|<epoch>` form). Still-limited responses re-arm the scheduler (5-minute retry loop); a pending schedule persists across Codeman restarts and re-arms on boot; respawn cycles are blocked while a limit pause is active so the cycle's `/clear` cannot wipe the paused conversation. New endpoint `POST /api/sessions/:id/auto-resume`; new SSE events `session:limitPauseScheduled`, `session:limitResume`, `session:limitResumeCancelled`; toast/notification on pause and resume, plus a live "resumes at HH:MM" status line in the modal. The Respawn tab layout was also tidied: compact single-row Update/Kickstart prompt fields and a merged options row.
|
||||
|
||||
**Mobile fixes (0.9.8 regressions)**:
|
||||
- **Activity-based resize arbitration** — a desktop sizing claim now only blocks a phone's resize while that desktop has actually typed within the last 90 seconds. Previously any connected desktop tab (even one abandoned hours ago) silently discarded the phone's resize with no fallback, leaving the phone rendering a desktop-width stream in a narrow terminal: mid-word wraps, tmux dot-fill rows, overdrawn garbled text, and misplaced keyboard echo. Now an idle desktop yields the pane to the phone, and the next desktop keystroke automatically restores the desktop layout ("whoever is actively using the session wins"). Phones also re-send their dimensions every 30 seconds (visible tab only, skipped while the virtual keyboard is open) so attaching under a momentarily-active desktop self-corrects.
|
||||
- **Keyboard accessory bar and toolbar restored on iOS** — the lift offset is measured against the layout viewport (`window.innerHeight`) again instead of the keyboard-shrunken app element; on iOS the offset computed to 0, leaving both bars hidden behind the OS keyboard with a dead black gap above it.
|
||||
- **Removed the mobile header utility ("three dots") toggle** — the header-utilities tray stays collapsed on small viewports.
|
||||
|
||||
## 0.9.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Documentation refresh — README catches up with the Codex run mode, plus a CLAUDE.md correction.
|
||||
|
||||
**README (en + zh-CN)**: Codex is now listed as a third supported AI coding CLI everywhere the docs previously said "Claude Code or OpenCode": the install requirement in Quick Start (now "any combination works", linking to the official Codex CLI docs), the Windows/WSL setup note, the renamed **Multi-CLI** feature bullet (env-prefix gating now reads `CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*`), the Zod schema-validation security bullet, and the architecture mermaid diagram. The header tagline was also finalized to "Claude Code • OpenCode • Codex — One Dashboard • Any Device" in both languages.
|
||||
|
||||
**CLAUDE.md**: fixed a stale "Local packages" line that claimed the xterm-zerolag-input local-echo overlay had a copy embedded in `app.js` — it is single-source in `packages/xterm-zerolag-input/`, bundled to the gitignored vendor file, and only consumed by `app.js`, matching the existing single-source gotcha.
|
||||
|
||||
## 0.9.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix a terminal freeze on hover (catastrophic regex backtracking) and a CSP violation that disabled the terminal's anti-throttling worker.
|
||||
|
||||
**Tab-freezing hover bug**: the terminal link provider's `cmdPattern` (which turns `tail -f /path`-style text into clickable links) used an empty-matchable, unbounded arg group — `(?:[^\s\/]*\s+)*` — that backtracks exponentially on real Claude output, e.g. wrapped `git commit -m "$(cat <<'EOF'` heredoc lines or aligned table rows. Hovering the mouse over such a line hung the page's main thread for minutes ("page unresponsive"). The pattern now uses non-empty tokens with bounded repetition (linear time); all intended command+path link forms still match. New `test/link-provider-regex.test.ts` extracts the shipped patterns from source and pins linear-time behavior on the killer line shapes.
|
||||
|
||||
**Blob worker CSP fix**: `worker-src 'self' blob:` is now always present in the CSP (previously only with `CODEMAN_GESTURE=1`). The terminal's `_safeYield` anti-throttling tick worker is created from a Blob URL and was silently blocked on every install, logging a CSP violation on each page load and disabling the worker leg of the render-yield fallback chain.
|
||||
|
||||
## 0.9.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Self-update now restarts automatically on headless Macs supervised by a system LaunchDaemon.
|
||||
|
||||
New `launchd-daemon` supervisor kind: when Codeman runs under a bootstrapped, KeepAlive system-level LaunchDaemon (`/Library/LaunchDaemons/com.codeman.web.plist` — the right setup for headless Macs, where LaunchAgents never start because there is no GUI login), the updater no longer ends with "Update staged — restart Codeman to apply". It restarts rootlessly: the update script kills the server PID (passed via `--server-pid`) and launchd respawns it on the freshly built `dist/`. Detection is conservative — the daemon must be bootstrapped in the system domain AND have `KeepAlive` enabled.
|
||||
|
||||
Also fixed: a lingering "restart Codeman to apply" status. After a manual restart of a staged update, boot reconciliation now flips `completed-needs-manual-restart` to `completed` once the running version matches the staged target, so the Updates tab stops showing the stale instruction.
|
||||
|
||||
## 0.9.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -56,7 +56,7 @@ When user says "COM":
|
||||
|
||||
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
|
||||
|
||||
**Version**: 0.9.9 (must match `package.json`)
|
||||
**Version**: 1.1.16 (must match `package.json`)
|
||||
|
||||
## Project Overview
|
||||
|
||||
@@ -102,11 +102,13 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
- **Global regex `lastIndex`** — Shared `g`-flag patterns in loops must reset `lastIndex = 0` first, or use the `execPattern()` helper in `utils/regex-patterns.ts` (resets automatically)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` env vars** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift
|
||||
- **Effort is NOT an env var** — never carry effort as `CLAUDE_CODE_EFFORT_LEVEL`: the env var hard-locks effort and blocks in-session `/effort` switching (incl. ultracode). It flows as the dedicated `effort` payload field → `Session._effort` → `claude --effort <level>` for regular levels incl. `max` (the settings `effortLevel` key is `enum(["low","medium","high","xhigh"]).catch(undefined)` — `max` gets SILENTLY dropped there), or `claude --settings '{"ultracode":true}'` for ultracode (rejected by `--effort`). Both are soft defaults the user can override anytime. Legacy env-var entries are auto-migrated by the Session constructor and unset from tmux sessions in `applyEnvOverrides()`. See `buildEffortCliArgs()` in `session-cli-builder.ts`, tests in `test/effort-injection.test.ts`
|
||||
- **Model choice flows via `settings.local.json`, NOT `--model` or env** — the App Settings **Claude Model** picker (`claudeModel` in `settings.json`) is read by `session-ui.js` at session create (wins over the legacy 1M-Opus toggles `opusContext1m`/`opusContext1mEnabled`), sent as the `modelOverride` payload field, and `updateCaseModel()` (`hooks-config.ts`) writes/deletes the `model` key in `<case>/.claude/settings.local.json`. This is the intended exception to the envOverrides rule above: model legitimately lives in `settings.local.json` (a soft default — in-session `/model` still works); env vars do not
|
||||
- **Multi-CLI prefix discipline** — Codeman supports Claude Code, OpenCode, and Codex (`claude-cli-resolver.ts` / `opencode-cli-resolver.ts` / `codex-cli-resolver.ts`); env-var prefix is CLI-specific (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*`) and the allowlist in `schemas.ts` enforces this. When adding settings, decide which CLI(s) it applies to and gate the env export accordingly — don't blindly forward all prefixes. See `docs/opencode-integration.md` for the OpenCode resolver design
|
||||
- **Zod `.optional()` rejects `null`** — accepts `undefined` only. When the frontend builds a request body with `JSON.stringify`, an explicit `null` field is preserved on the wire and fails validation with `INVALID_INPUT`. Convert `null` → `undefined` before stringifying (e.g. `field: value ?? undefined`), or declare the schema `.nullish()`. Real bugs caused: 0.6.4 (`durationMinutes` for ∞ respawn), and the same shape pattern hit `opusContext1mEnabled` in 0.6.3
|
||||
- **`xterm-zerolag-input` is single-source — edit the package, then rebuild the bundle** — the local-echo overlay source lives ONLY in `packages/xterm-zerolag-input/src/` (`zerolag-input-addon.ts`; also published to npm as a standalone library — see README "Published Packages"). It is bundled (esbuild → IIFE, with appended `window.LocalEchoOverlay` aliases) into the **gitignored** `src/web/public/vendor/xterm-zerolag-input.js` by `scripts/postinstall.js` (for dev/`tsx`) and into `dist/.../vendor/` by `scripts/build.mjs:50` (for prod). `app.js` only **consumes** it via `new LocalEchoOverlay(terminal)` — there is NO inline copy to keep in sync. So: change behavior in the package source, then re-run the bundle step (`npm install` reruns postinstall; `npm run build` for prod); **never hand-edit `app.js` for overlay behavior or commit the gitignored vendor bundle**. A public-API break in the package still warrants a separate `xterm-zerolag-input` version bump in the changeset. Always test on mobile after touching it. See `docs/local-echo-overlay-plan.md`.
|
||||
- **Default bind is loopback-only; non-loopback without a password starts but warns** — since COD-29 (PR #107) the web server defaults to `--host 127.0.0.1` (was `0.0.0.0`). As of **0.9.0** binding a non-loopback host (`--host`/`-H`/`CODEMAN_HOST`) without `CODEMAN_PASSWORD` **no longer refuses to start — it starts and prints a loud warning** listing the fixes (set `CODEMAN_PASSWORD`, bind loopback + tunnel/`tailscale serve`, or `--allow-unauthenticated-network` / `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1` to acknowledge → terser note). Host classification is `isLoopbackBindHost()` in `network-auth-policy.ts`; the warn-vs-start logic is in `server.ts` `start()`; flags wired in `cli.ts`. ⚠️ Operational note: the production systemd unit runs `node dist/index.js web --https` with no `--host`, so it binds **localhost only** — reach it remotely via `tailscale serve`/tunnel to `127.0.0.1`, or add `Environment=CODEMAN_HOST=0.0.0.0` + `Environment=CODEMAN_PASSWORD=…` to `~/.config/systemd/user/codeman-web.service`. A loopback bind is reachable through a same-host tunnel (cloudflared/tailscale → `127.0.0.1`) but NOT by a browser hitting the box's LAN IP. Auth user defaults to `admin`. **Full model: `docs/security-architecture.md`.**
|
||||
- **Instance isolation / multi-instance attach danger** — data dir (`~/.codeman`) and tmux socket (`tmux -L codeman`) are PROCESS-WIDE and shared by every Codeman on the machine, derived from `CODEMAN_INSTANCE` via `src/config/instance.ts` (`getDataDir()`/`dataPath()`/`DEFAULT_TMUX_SOCKET`). ⚠️ A 2nd instance on the SAME socket **discovers and attaches PTYs to the first instance's live sessions** (`tmux -L codeman attach-session …`), resizing/mutating them — `$HOME` isolation is NOT enough (tmux is system-global). To run two instances, give each a distinct `CODEMAN_INSTANCE` (scopes BOTH dir+socket: `~/.codeman-<name>` + `-L codeman-<name>`), or set `CODEMAN_TMUX_SOCKET` + `CODEMAN_DATA_DIR` individually. **`CODEMAN_INSTANCE` defaults to empty = the production layout (`~/.codeman`, `-L codeman`, port 3000)**, so this branch is safe to ship to master without disturbing existing installs. To run THIS beta alongside prod, launch with `scripts/run-beta.sh` (`CODEMAN_INSTANCE=beta` + `CODEMAN_PORT=5000`) — it never collides with prod's data dir/socket/port. Any new `~/.codeman/...` path MUST go through `dataPath()`, never `join(homedir(), '.codeman', …)`.
|
||||
- **Headless screenshots: `deviceScaleFactor` MUST be 1, and write unique filenames** — `scripts/capture-real-overview.mjs` (drives a live session in headless Chromium → overview PNG). Two traps, both observed 2026-06-14: **(1) DSF=2 doubles the console font.** xterm's WebGL renderer draws terminal glyphs at ~2× their nominal size under `deviceScaleFactor: 2`, while STILL reporting nominal cell dims (`terminal.cols`/`_renderService.dimensions.css.cell` say 8px/187cols — they lie), so it's invisible to any internal measurement and only the pixels reveal it. The HTML chrome (header/toolbar) is unaffected → ONLY the console font looks comically large. Default to **DSF=1** (script does); the image is 1× res but the font is true-to-browser. **(2) Stable filenames → stale renders.** Overwriting a fixed path (`claude-overview.png`) in place leaves OS image viewers (eog/feh) — and any HTTP client behind a long/`immutable` cache — showing the OLD render; the user reads it as "the fix didn't work". The script now mints a timestamped `claude-overview-<ts>.png` per run. ⚠️ This was a LOCAL image-viewer cache, NOT a Codeman serving bug: `file-routes` previews send `Cache-Control: no-cache` and `/api/screenshots/:name` sends none. The one real Codeman-side footgun: `server.ts` serves non-content-hashed static assets `public, max-age=31536000, immutable`, and `cacheBustAssets()` only rewrites `.js`/`.css` refs — a stable-named **image** referenced from public/ would go stale on overwrite. Reflect the per-device UI to match a real device when capturing: seed `localStorage` `codeman:skin`, `codeman-font-size`, and the desktop `codeman-app-settings` blob (the plan-usage chip is a per-device display key deleted from the server payload — a fresh browser hides it unless seeded; close side panels for a full-width terminal).
|
||||
|
||||
**Import conventions**: Utils from `./utils`, types from `./types` (barrel), config from specific `./config/*` files.
|
||||
|
||||
@@ -117,26 +119,27 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
| Domain | Key files | Notes |
|
||||
|--------|-----------|-------|
|
||||
| **Entry** | `src/index.ts`, `src/cli.ts` | |
|
||||
| **Session** | `src/session.ts` ★, `src/session-manager.ts`, `src/session-auto-ops.ts`, `src/session-cli-builder.ts`, `src/session-lifecycle-log.ts`, `src/session-task-cache.ts` | |
|
||||
| **Session** | `src/session.ts` ★, `src/session-manager.ts`, `src/session-auto-ops.ts`, `src/session-cli-builder.ts`, `src/session-lifecycle-log.ts`, `src/session-task-cache.ts`, `src/usage-limit-patterns.ts`, `src/usage-telemetry.ts` | |
|
||||
| **Mux** | `src/mux-interface.ts`, `src/mux-factory.ts`, `src/tmux-manager.ts` ★ | |
|
||||
| **Respawn** | `src/respawn-controller.ts` ★ + 4 helpers (`-adaptive-timing`, `-health`, `-metrics`, `-patterns`) | Read `docs/respawn-state-machine.md` first |
|
||||
| **Ralph** | `src/ralph-tracker.ts` ★, `src/ralph-loop.ts` + 5 helpers (`-config`, `-fix-plan-watcher`, `-plan-tracker`, `-stall-detector`, `-status-parser`) | Read `docs/ralph-wiggum-guide.md` first |
|
||||
| **Orchestrator** | `src/orchestrator-loop.ts`, `src/orchestrator-planner.ts`, `src/orchestrator-verifier.ts` | Read `docs/orchestrator-loop-architecture.md` first |
|
||||
| **Agents** | `src/subagent-watcher.ts` ★, `src/team-watcher.ts`, `src/bash-tool-parser.ts`, `src/transcript-watcher.ts` | |
|
||||
| **Agents** | `src/subagent-watcher.ts` ★, `src/team-watcher.ts`, `src/bash-tool-parser.ts`, `src/transcript-watcher.ts`, `src/workflow-run-watcher.ts` | `workflow-run-watcher` is STANDALONE (never touches `subagent-watcher`) — see Key Patterns |
|
||||
| **AI** | `src/ai-checker-base.ts`, `src/ai-idle-checker.ts`, `src/ai-plan-checker.ts` | |
|
||||
| **Tasks** | `src/task.ts`, `src/task-queue.ts`, `src/task-tracker.ts` | |
|
||||
| **State** | `src/state-store.ts`, `src/run-summary.ts`, `src/session-lifecycle-log.ts` | |
|
||||
| **Infra** | `src/hooks-config.ts`, `src/push-store.ts`, `src/tunnel-manager.ts`, `src/image-watcher.ts`, `src/file-stream-manager.ts` | |
|
||||
| **Plan** | `src/plan-orchestrator.ts`, `src/prompts/*.ts`, `src/templates/claude-md.ts` | |
|
||||
| **Web** | `src/web/server.ts` ★, `src/web/sse-events.ts`, `src/web/routes/*.ts` (15 route modules + barrel; `session-routes.ts` ★), `src/web/route-helpers.ts`, `src/web/ports/*.ts`, `src/web/middleware/auth.ts`, `src/web/schemas.ts`, `src/web/self-update.ts` | |
|
||||
| **Frontend** | `src/web/public/app.js` (~3.6K lines, core) + 5 infra modules (`constants.js`, `mobile-handlers.js`, `voice-input.js`, `notification-manager.js`, `keyboard-accessory.js`) + 7 domain modules (`terminal-ui.js`, `respawn-ui.js`, `ralph-panel.js`, `orchestrator-panel.js`, `settings-ui.js`, `panels-ui.js`, `session-ui.js`) + 5 feature modules (`ralph-wizard.js`, `api-client.js`, `subagent-windows.js`, `input-cjk.js`, `image-input.js`) + `sw.js` | |
|
||||
| **Types** | `src/types/index.ts` (barrel) → 15 domain files; also `src/types.ts` root re-export | See `@fileoverview` in index.ts |
|
||||
| **Attachments** | `src/attachment-registry.ts`, `src/attachment-magic.ts`, `src/session-attachment-history.ts`, `src/document-preview-cache.ts`, `src/document-thumbnailer.ts`, `src/document-conversion-limiter.ts`, `src/config/attachment-guard.ts` | See Key Patterns |
|
||||
| **Plan** | `src/plan-orchestrator.ts`, `src/prompts/*.ts`, `src/templates/` (`claude-md.ts` + `case-template.md`, the CLAUDE.md scaffold generated into new cases) | |
|
||||
| **Web** | `src/web/server.ts` ★, `src/web/sse-events.ts`, `src/web/routes/*.ts` (16 route modules + barrel; `session-routes.ts` ★), `src/web/route-helpers.ts`, `src/web/ports/*.ts`, `src/web/middleware/auth.ts`, `src/web/schemas.ts`, `src/web/self-update.ts`, `src/web/plan-usage-latest.ts` | |
|
||||
| **Frontend** | `src/web/public/app.js` (~4K lines, core) + 6 infra modules (`constants.js`, `mobile-handlers.js`, `voice-input.js`, `notification-manager.js`, `keyboard-accessory.js`, `sanitize-html.js` — DOMPurify mXSS allowlist, COD-56) + 8 domain modules (`terminal-ui.js`, `respawn-ui.js`, `ralph-panel.js`, `orchestrator-panel.js`, `ultracode-panel.js`, `settings-ui.js`, `panels-ui.js`, `session-ui.js`) + 6 feature modules (`ralph-wizard.js`, `api-client.js`, `subagent-windows.js`, `ultracode-windows.js`, `input-cjk.js`, `image-input.js`) + `sw.js` | `ultracode-windows.js` = floating run windows w/ tab connector lines (additional to the dock panel) |
|
||||
| **Types** | `src/types/index.ts` (barrel) → 16 domain files (incl. `workflow-run.ts`); also `src/types.ts` root re-export | See `@fileoverview` in index.ts |
|
||||
|
||||
★ = Large, central file (>50KB) — read its `@fileoverview` first. All files have `@fileoverview` JSDoc — read that before diving in. Discovery aid: `grep -l '@fileoverview' src/web/routes/*.ts` lists all route modules; same grep works for `src/types/`, `src/web/public/*.js`.
|
||||
|
||||
**Local packages**: `packages/xterm-zerolag-input/` — local echo overlay for xterm.js; copy embedded in `app.js`. `packages/gesture-control/` (`codeman-gesture-control`) — hand-tracking overlay source; built to `src/web/public/gesture/gesture-codeman.js` via `npm run build:gesture` (see Frontend → Gesture control).
|
||||
**Local packages**: `packages/xterm-zerolag-input/` — local echo overlay for xterm.js; single-source, bundled to the gitignored `vendor/xterm-zerolag-input.js` and consumed by `app.js` (see Gotchas). `packages/gesture-control/` (`codeman-gesture-control`) — hand-tracking overlay source; built to `src/web/public/gesture/gesture-codeman.js` via `npm run build:gesture` (see Frontend → Gesture control).
|
||||
|
||||
**Config**: `src/config/` — 10 files, no barrel (`index.ts`) exists; import from the specific file.
|
||||
**Config**: `src/config/` — 14 files, no barrel (`index.ts`) exists; import from the specific file.
|
||||
|
||||
**Utilities**: `src/utils/` — re-exported via index. Key: `CleanupManager`, `LRUMap`, `StaleExpirationMap`, `BufferAccumulator`, `stripAnsi`, `Debouncer`, `KeyedDebouncer`. Also: `claude-cli-resolver`/`opencode-cli-resolver`/`codex-cli-resolver` (CLI path resolution), `string-similarity` (fuzzy matching), `regex-patterns` (ANSI/token/spinner patterns), `assertNever` (exhaustive checks), `token-validation` (auth tokens), `nice-wrapper` (process priority).
|
||||
|
||||
@@ -153,25 +156,33 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Idle detection**: Multi-layer (completion message → AI check → output silence → token stability). See `docs/respawn-state-machine.md`.
|
||||
|
||||
**Auto-resume on usage limit** ("token pause" control, opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit ("5-hour limit reached ∙ resets 8pm" and all 1.0.x–2.1.x variants), `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time from cleaned output; `SessionAutoOps` arms a timer for reset+2min, then sends Esc (dismisses the rate-limit dialog) + `continue`. Still-limited responses re-arm the loop (5-min retry on stale times); a `working` transition cancels it. Claude-mode only (detection rides `_processExpensiveParsers`). Persists/recovers via `SessionState.autoResumeEnabled`/`autoResumeAt`; respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected` — prevents `/clear` from wiping the paused conversation). Endpoint: `POST /api/sessions/:id/auto-resume`; SSE: `session:limitPauseScheduled`/`limitResume`/`limitResumeCancelled`. Tests: `test/usage-limit-patterns.test.ts`, `test/session-auto-resume.test.ts`.
|
||||
|
||||
**Plan-usage chip** (statusLine telemetry, opt-in `showPlanUsageLimits`, default OFF): Claude Code (v2.1.80+) pipes a JSON blob to a configured `statusLine.command` on each render; on Pro/Max it carries a `rate_limits` object (`five_hour`/`seven_day` windows only — no Opus weekly field — each `{used_percentage 0-100, resets_at epoch-SECONDS}`). Codeman injects its OWN statusLine exporter (`generateStatusLineCommand()` in `hooks-config.ts`, identified by the `/api/status-telemetry` marker — it only ever adds/updates/removes a statusLine that is *ours*, never a user's hand-authored one) that POSTs the blob to `POST /api/status-telemetry`. That route (auth-exempt like `/api/hook-event` — localhost-only, hook-secret-gated under a tunnel) parses via `usage-telemetry.ts` (pure, unit-tested), broadcasts SSE `session:statusTelemetry` (de-duped per session by `telemetrySignature` since the statusline fires on every assistant message), and returns a compact plain-text footer for the exporter to **print-through** (so injecting our statusLine doesn't blank the in-terminal footer). `plan-usage-latest.ts` holds the process-wide last value, replayed in the SSE init snapshot (`getLightState`) so the header chip (`#planUsageChip`, toggled by `showPlanUsageLimits` in settings-ui.js) renders immediately on page load / reconnect without per-browser localStorage. Claude-mode only. **Distinct from auto-resume** (which reacts to the limit *message*; this proactively shows the live %). Design: `docs/usage-limits-display-plan.md`. Tests: `test/usage-telemetry.test.ts`.
|
||||
|
||||
**Orchestrator**: State machine that turns a user goal into a phased plan and drives it to completion: `idle → planning → approval → executing → verifying → (replanning) → completed/failed`. `OrchestratorLoop` (engine) delegates plan generation to `orchestrator-planner` and per-phase verification gates to `orchestrator-verifier`, executing phases via team agents/`task-queue`. State persists under the `orchestrator` key in `state.json`. Distinct from Ralph (single-session autonomous loop) — orchestrator coordinates multi-phase, multi-agent execution. See `docs/orchestrator-loop-architecture.md`.
|
||||
|
||||
**External CLI modes (OpenCode, Codex)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior — Ralph tracker, BashToolParser, token/CLI-info parsing, and ❯-prompt readiness detection are all skipped (these CLIs render their own TUIs; readiness = output stabilization instead). Both modes **require tmux — no direct PTY fallback** — because secrets are injected via `tmux setenv`, never on the spawn command line: OpenCode gets `OPENCODE_CONFIG_CONTENT` etc., Codex gets `OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` (`setCodexEnvVars` in `tmux-manager.ts`). Codex specifics: command built by `buildCodexCommand()` (`--model`, `resume <id>`, `--dangerously-bypass-approvals-and-sandbox` from the `codexConfig` payload / `codexDangerouslyBypassApprovals` app setting; `renderMode` is schema-coerced to `'hybrid'`, the only supported mode); tmux exports `COLORTERM=truecolor` + unsets `NO_COLOR` (other modes unset `COLORTERM`); availability via `GET /api/codex/status` — session/quick-start routes fail with `OPERATION_FAILED` and an install hint (`npm install -g @openai/codex`) when the binary is missing. Frontend: run-mode dropdown → `runCodex()` in `session-ui.js` ("Run CX" label), App Settings → Codex CLI tab; Respawn/Ralph options are Claude-only, so session options open on the Summary tab for external CLI sessions. Tests: `test/run-mode-ui.test.ts` (vm-sandbox harness, no real DOM).
|
||||
|
||||
**Hook events**: Claude Code hooks trigger via `/api/hook-event`. Key events: `permission_prompt`, `elicitation_dialog`, `idle_prompt`, `stop`, `teammate_idle`, `task_completed`. See `src/hooks-config.ts`.
|
||||
**Hook events**: Claude Code hooks trigger via `/api/hook-event`. Key events: `permission_prompt`, `elicitation_dialog`, `idle_prompt`, `stop`, `teammate_idle`, `task_completed`. See `src/hooks-config.ts`; upstream hook semantics mirrored in `docs/claude-code-hooks-reference.md`.
|
||||
|
||||
**Agent Teams**: `TeamWatcher` polls `~/.claude/teams/`, matches to sessions via `leadSessionId`. Teammates are in-process threads appearing as subagents. Enable: `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`. See `docs/agent-teams/`.
|
||||
|
||||
**Circuit breaker**: Prevents respawn thrashing. States: `CLOSED` → `HALF_OPEN` → `OPEN`. Reset: `/api/sessions/:id/ralph-circuit-breaker/reset`.
|
||||
|
||||
**Self-update** (App Settings → Updates): in-app updater for **git-clone installs** supervised by systemd/launchd. The update restarts the very process running it, so the real work runs in a DETACHED `scripts/self-update.sh` (`git checkout <release tag> && npm install && npm run build && restart`) that outlives the restart; it writes progress to `dataPath('update-status.json')`, which the browser polls across the connection drop. Channel = latest `codeman@X.Y.Z` release tag; dirty trees are auto-stashed. `src/web/self-update.ts` splits PURE helpers (semver/tag parsing, reconcile decision — unit-tested) from IO wrappers (`getInstallInfo`/`checkForUpdate`/`startUpdate`/`reconcileUpdateOnBoot`). Routes: `GET /api/system/update/check`, `POST /api/system/update`, `GET /api/system/update/status`. Types: `src/types/update.ts`. npm installs report as non-updatable.
|
||||
**Self-update** (App Settings → Updates): in-app updater for **git-clone installs** supervised by systemd/launchd. Supervisors: `systemd` (user unit), `launchd` (GUI LaunchAgent, gui-domain kickstart), `launchd-daemon` (KeepAlive system LaunchDaemon on headless Macs — restarts rootlessly by killing the server PID and letting launchd respawn it; detected only when the daemon is bootstrapped AND KeepAlive), else `none` → "restart manually" message; on next boot a manual-restart status auto-completes when the running version matches the target. The update restarts the very process running it, so the real work runs in a DETACHED `scripts/self-update.sh` (`git checkout <release tag> && npm install && npm run build && restart`) that outlives the restart; it writes progress to `dataPath('update-status.json')`, which the browser polls across the connection drop. Channel = latest `codeman@X.Y.Z` release tag; dirty trees are auto-stashed. `src/web/self-update.ts` splits PURE helpers (semver/tag parsing, reconcile decision — unit-tested) from IO wrappers (`getInstallInfo`/`checkForUpdate`/`startUpdate`/`reconcileUpdateOnBoot`). Routes: `GET /api/system/update/check`, `POST /api/system/update`, `GET /api/system/update/status`. Types: `src/types/update.ts`. npm installs report as non-updatable.
|
||||
|
||||
**Attachments** (live external document references; COD-37/#119 core, COD-38/#120 previews, COD-39/#121 history): all wiring in `file-routes.ts`. **Registry** (`attachment-registry.ts`): an **in-memory** map of a stable `attachmentId` → an absolute, `realpath`-resolved, extension-allowlisted file path, so browser requests (`GET /api/sessions/:id/attachments/:attachmentId/raw`) never carry arbitrary absolute paths; `POST /api/sessions/:id/attachments` registers one. **Magic links** (`attachment-magic.ts`): parses `codeman://attach?...` out of terminal output — ⚠️ this scanner is prompt-injectable, so the scan path is **force-confined to the session workspace** (a hostile prompt could otherwise make it read arbitrary host files over SSE); emits the `attachment:detected` SSE event. Security gate is an extension **allowlist** (`isSupportedAttachmentExtension`, in the registry/magic modules), not a blocklist; a separate path layer (`config/attachment-guard.ts`) confines reads to the workspace (`attachmentConfineToWorkspace`) and blocks sensitive trees (`/root`, `/etc`). **Previews + thumbnails** (COD-38): `:attachmentId/preview` + `:attachmentId/thumbnail` (and the workspace-file equivalents `file-preview`/`file-thumbnail`) render Office docs/PDFs via external converters (`pdftoppm` / LibreOffice `soffice` / Word-COM `powershell`); `document-preview-cache.ts` is a shared disk cache (de-dups *identical* in-flight inputs), `document-thumbnailer.ts` does best-effort first-page images, and `document-conversion-limiter.ts` is a **global converter-spawn concurrency cap** (`runWithConversionLimit`) — without it, N distinct large docs detected at once fork N multi-minute converter processes = a localhost fork-bomb-shaped resource-exhaustion vector. **History drawer** (COD-39): `session-attachment-history.ts` tracks the last `ATTACHMENT_HISTORY_LIMIT` (100) attachments per session (`Session._attachmentHistory`, persisted via `SessionState.attachmentHistory`, replayed so externals re-register on reconnect); `GET /api/sessions/:id/attachments` is the list endpoint. ⚠️ The history drawer's launcher button is desktop-only — hidden on phones (regression-guarded; see `mobile-header-buttons-policy` test). Session-local files keep using the existing workspace-scoped `file-routes` paths; the registry is only for explicit live externals.
|
||||
|
||||
**Ultracode / Workflow-run visualization** (opt-in `showUltracodeAgents`, default OFF; released 1.1.2): the Workflow tool ("ultracode") writes a run-state JSON per run at `~/.claude/projects/<projHash>/<sessionUuid>/workflows/wf_*.json`. `workflow-run-watcher.ts` (STANDALONE — deliberately never imports/touches `subagent-watcher.ts`; disjoint directory tree, separate singleton) globs that tree via periodic poll + per-run chokidar watcher with per-file mtime skip, and broadcasts SSE `workflow:run_discovered`/`run_updated`/`run_removed`. The watcher is only started when the setting is on (`server.ts` gates on `showUltracodeAgents`). Served via `GET /api/workflows` (optional `?minutes=` filter) and `GET /api/workflows/:runId`. Frontend `ultracode-panel.js` renders a docked master-detail view (LEFT: runs + phases; RIGHT: per-agent tokens + tool-calls; click an agent card → its live transcript via client-side `agentId` join). **Additionally**, `ultracode-windows.js` auto-pops a draggable **floating window per active run** (gated on the same `showUltracodeAgents` setting), connected by a glowing line to the originating session tab (resolved by `session.claudeSessionId === run.sessionUuid`) — same line idiom as subagent windows, drawn into the shared `#connectionLines` SVG from the tail of `_updateConnectionLinesImmediate`. The window auto-closes ~8s after its run finishes; explicit dismissals are remembered. Types: `src/types/workflow-run.ts`. Config: `src/config/workflow-config.ts`.
|
||||
|
||||
**Port interfaces**: Routes declare dependencies via port interfaces (`src/web/ports/`). Routes use intersection types (e.g., `SessionPort & EventPort`).
|
||||
|
||||
### Frontend
|
||||
|
||||
Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order: `constants.js`(1) → `mobile-handlers.js`(2) → `voice-input.js`(3) → `notification-manager.js`(4) → `keyboard-accessory.js`(5) → `input-cjk.js`(5.5) → `app.js`(6) → `terminal-ui.js`(7) → `respawn-ui.js`(8) → `ralph-panel.js`(9) → `orchestrator-panel.js`(9.5) → `settings-ui.js`(10) → `panels-ui.js`(11) → `session-ui.js`(12) → `ralph-wizard.js`(13) → `api-client.js`(14) → `subagent-windows.js`(15) → `image-input.js`(16). `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData).
|
||||
Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order: `constants.js`(1) → `mobile-handlers.js`(2) → `voice-input.js`(3) → `notification-manager.js`(4) → `keyboard-accessory.js`(5) → `input-cjk.js`(5.5) → `sanitize-html.js`(5.6) → `app.js`(6) → `terminal-ui.js`(7) → `respawn-ui.js`(8) → `ralph-panel.js`(9) → `orchestrator-panel.js`(9.5) → `settings-ui.js`(10) → `panels-ui.js`(11) → `ultracode-panel.js`(11.5) → `session-ui.js`(12) → `ralph-wizard.js`(13) → `api-client.js`(14) → `subagent-windows.js`(15) → `ultracode-windows.js`(15.5) → `image-input.js`(16). `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData).
|
||||
|
||||
**Z-index layers**: subagent windows (1000), plan agents (1100), log viewers (2000), image popups (3000), local echo overlay (7).
|
||||
**Z-index layers**: subagent windows (1000), plan agents (1100), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried; bug fixed in `b8cb467`), log viewers (2000), image popups (3000), local echo overlay (7).
|
||||
|
||||
**Multi-monitor button** (header, top-right; the notification bell it sits beside stays hidden — notifications live in Settings → Notifications). `app.launchMultiMonitor()` (in `panels-ui.js`) POSTs `/api/system/span-displays`, which spawns `scripts/span-codeman.sh` — a fresh, maximized browser `--app` window sized to the union of all displays (macOS; needs "Displays have separate Spaces" OFF). Supports the gesture layer's in-page floating session panels dragging across the physical monitor seam. **Opt-in:** hidden by default; enable under App Settings → Display → **Header Displays** ("Multi-monitor Button", `showMultiMonitorButton`). The button carries a `btn-multimonitor--hidden` class in the template; `renderIndexHtml` strips that class at render when the setting is on (a unique class token, not a brittle match on the aria-label/style copy), and `applyHeaderVisibilitySettings()` toggles the same class live on save. Solo (detached) windows hide it via `body.solo-mode`.
|
||||
|
||||
@@ -181,6 +192,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Gesture-control source lives in-repo** at `packages/gesture-control/` (workspace package `codeman-gesture-control`, was the standalone `Ark0N/codeman-gesture-control` repo). The transport-agnostic core is `src/gesture/*` (MediaPipe GestureRecognizer → One-Euro-filtered cursor → pinch state machine); `src/codeman/entry.ts` is the Codeman *consumer* that maps grab/drag/drop onto real `.session-tab`/toolbar buttons and is the bundle entry. **Edit there, then run `npm run build:gesture`** (`scripts/build-gesture-bundle.mjs` → esbuild bundles `entry.ts`, MediaPipe JS included, into `src/web/public/gesture/gesture-codeman.js`) and **commit the regenerated bundle** — the committed bundle is what dev/`tsx` serves (no bundler at runtime), and `scripts/build.mjs` reruns the same step so prod always reflects current source. The MediaPipe **wasm + model** are NOT bundled — loaded at runtime from same-origin `/gesture/wasm` + `/gesture/gesture_recognizer.task`, fetched by `scripts/fetch-gesture-assets.mjs` (gitignored, see Gotchas). `entry.ts` mounts `window.__codemanGesture = new GestureBridge()` idempotently at module-eval. A standalone vite playground (`npm run dev` in the package — fake tabs, no Codeman) lets you iterate on gesture *feel* in isolation. ⚠️ Keep `MP_VERSION` in `fetch-gesture-assets.mjs` in sync with `@mediapipe/tasks-vision` in `packages/gesture-control/package.json`.
|
||||
|
||||
**Theme skins** (App Settings → Display): the `skin` setting selects a palette via a `data-skin` attribute on `<html>`. Values: `daylight-blue` (default), `daylight-green`, `og` (OG Codeman). CSS lives under `[data-skin="…"]` blocks in `styles.css`. To avoid a flash-of-wrong-theme, an **inline pre-paint script** in `index.html` (`<head>`) reads `localStorage['codeman:skin']` and sets `data-skin` before first paint; `settings-ui.js` `applyTheme()`/`applyTerminalSkin()` apply it live on save and keep the standalone `codeman:skin` key + the settings object in sync. `skin` is a **per-device/client-only** setting — it's destructured OUT of the server payload (settings-ui.js, alongside `localEchoEnabled`/`cjkInputEnabled`/`extendedKeyboardBar`), so it does NOT sync across devices.
|
||||
|
||||
**Respawn presets**: `solo-work` (3s/60min), `subagent-workflow` (45s/240min), `team-lead` (90s/480min), `ralph-todo` (8s/480min), `overnight-autonomous` (10s/480min).
|
||||
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (help), Ctrl+W (kill), Ctrl+Tab (next), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter (newline), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font).
|
||||
@@ -198,20 +211,20 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
| **QR Auth** | Single-use 6-char tokens (60s TTL) for tunnel login. See `docs/qr-auth-plan.md` |
|
||||
| **Sessions** | 24h cookie (`codeman_session`), auto-extend, device context audit |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). QR has separate limiter |
|
||||
| **Hook bypass** | `/api/hook-event` exempt from auth (localhost-only, schema-validated) |
|
||||
| **Hook bypass** | `/api/hook-event` (and `/api/status-telemetry`, the statusLine exporter) exempt from auth (localhost-only, schema-validated). While the **managed tunnel** runs, the bypass additionally requires the per-instance `X-Codeman-Hook-Secret` header (COD-54, `config/hook-secret.ts`): hook curls cat the secret file at exec time via `$CODEMAN_HOOK_SECRET_FILE` (session env), failures rate-limit in a dedicated bucket (never lock out login). External loopback proxies (own cloudflared/`tailscale serve`) aren't detected — plain bypass still applies there. Tunnel enable **refuses** without `CODEMAN_PASSWORD` unless exposure is acknowledged — via `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1` (env, COD-55) **or** the per-request `acknowledgeUnauthTunnel:true` action field (1.1.9): the welcome/settings tunnel toggle pops a security confirm dialog and, on confirm, resends with that flag (server logs a loud warning on every passwordless tunnel start; curl/API stay refused without password/env/flag). The flag is an action field, never persisted |
|
||||
| **Env vars** | `CODEMAN_MUX` (managed session), `CODEMAN_API_URL` (auto-set for hooks), `CODEMAN_ALLOWED_HOSTS` (extra Host/Origin allowlist entries for reverse proxies, comma-separated; bare `.suffix` matches subdomains) |
|
||||
| **Validation** | Zod schemas, path allowlist regex, env prefix allowlist (`CLAUDE_CODE_*`/`OPENCODE_*`/`CODEX_*`) |
|
||||
| **Headers** | CORS localhost-only, CSP, X-Frame-Options, HSTS if HTTPS |
|
||||
|
||||
### SSE Event Registry
|
||||
|
||||
~120 event types in `src/web/sse-events.ts` (backend) and `SSE_EVENTS` in `constants.js` (frontend). Both must be kept in sync.
|
||||
~127 event types in `src/web/sse-events.ts` (backend) and `SSE_EVENTS` in `constants.js` (frontend). Both must be kept in sync.
|
||||
|
||||
### API Routes
|
||||
|
||||
~135 handlers across 15 route files in `src/web/routes/`: system (41, incl. self-update `check`/`status`/`POST /api/system/update`, `POST /api/system/span-displays` → spawns `scripts/span-codeman.sh`, and `GET /api/codex/status`), sessions (28), orchestrator (10), cases (9), ralph (9), plan (8), respawn (7), files (6), mux (5), push (4), scheduled (4), teams (2), hooks (1), clipboard (1), ws (1 WebSocket). Each file has `@fileoverview` with endpoint details.
|
||||
~147 handlers across 16 route files in `src/web/routes/`: system (41, incl. self-update `check`/`status`/`POST /api/system/update`, `POST /api/system/span-displays` → spawns `scripts/span-codeman.sh`, and `GET /api/codex/status`), sessions (29), orchestrator (10), cases (9), ralph (9), plan (8), files (14, incl. attachment register + list/history + `:attachmentId/raw`/`preview`/`thumbnail` + workspace `file-preview`/`file-thumbnail`), respawn (7), mux (5), push (4), scheduled (4), teams (2), hooks (1), clipboard (1), status-telemetry (1, `POST /api/status-telemetry` ← statusLine exporter), ws (1 WebSocket). Each file has `@fileoverview` with endpoint details.
|
||||
|
||||
**HTTP contract** (stable since 0.9.x, see `docs/versioning-policy.md`): responses use the `ApiResponse<T>` envelope — `{ success: true, data? }` or `{ success: false, error, errorCode }` (`src/types/api.ts`). `/api/v1/*` is a versioned alias of `/api/*` (URL rewrite in `server.ts`).
|
||||
**HTTP contract** (stable since 0.9.x, see `docs/versioning-policy.md`; full envelope/status/error-code/SSE spec in `docs/api-reference.md`): responses use the `ApiResponse<T>` envelope — `{ success: true, data? }` or `{ success: false, error, errorCode }` (`src/types/api.ts`). `/api/v1/*` is a versioned alias of `/api/*` (URL rewrite in `server.ts`).
|
||||
|
||||
## Adding Features
|
||||
|
||||
@@ -249,7 +262,7 @@ Raw `npx vitest` skips `config/vitest.config.ts`; always use `npm test --` or pa
|
||||
|
||||
**Ports**: Pick unique ports manually. Search `const PORT =` before adding new tests.
|
||||
|
||||
**Respawn tests**: Use `MockSession` from `test/respawn-test-utils.ts`. **Route tests**: `app.inject({ method, url, payload })` in `test/routes/` — no live port needed. **Mobile tests**: Playwright suite in `test/mobile/` (135 device profiles).
|
||||
**Respawn tests**: Use `MockSession` from `test/respawn-test-utils.ts`. **Route tests**: `app.inject({ method, url, payload })` in `test/routes/` — no live port needed. **Mobile tests**: Playwright suite in `test/mobile/` (135 device profiles). Browser-testing infra and practices: `docs/browser-testing-guide.md`.
|
||||
|
||||
## Debugging
|
||||
|
||||
|
||||
@@ -2,14 +2,10 @@
|
||||
<img src="docs/images/codeman-title.svg" alt="Codeman" height="60">
|
||||
</p>
|
||||
|
||||
<h2 align="center">The missing control plane for AI coding agents</h2>
|
||||
<h2 align="center">Mission control for AI coding agents</h2>
|
||||
|
||||
<p align="center">
|
||||
<em>Agent Visualization • Zero-Lag Input • Mobile-First UI • Hardened Security</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> • <a href="README.zh-CN.md">简体中文</a>
|
||||
<em>Claude Code • OpenCode • Codex • Terminal - One Dashboard • Any Device</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -20,6 +16,10 @@
|
||||
<img src="https://img.shields.io/badge/Tests-2861%20total-22c55e?style=flat-square" alt="Tests">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> • <a href="README.zh-CN.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/subagent-demo.gif" alt="Codeman — parallel subagent visualization" width="900">
|
||||
</p>
|
||||
@@ -34,7 +34,7 @@ curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | b
|
||||
|
||||
This installs Node.js and tmux if missing, clones Codeman to `~/.codeman/app`, and builds it.
|
||||
|
||||
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code) or [OpenCode](https://opencode.ai) (or both). After install:
|
||||
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), or [Codex](https://developers.openai.com/codex/cli) (any combination works). After install:
|
||||
|
||||
```bash
|
||||
codeman web
|
||||
@@ -103,7 +103,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
|
||||
wsl bash -c "curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | bash"
|
||||
```
|
||||
|
||||
Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code) or [OpenCode](https://opencode.ai)). After installing, `http://localhost:3000` is accessible from your Windows browser.
|
||||
Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), or [Codex](https://developers.openai.com/codex/cli)). After installing, `http://localhost:3000` is accessible from your Windows browser.
|
||||
</details>
|
||||
|
||||
---
|
||||
@@ -214,6 +214,7 @@ WATCHING → IDLE DETECTED → SEND UPDATE → /clear → /init → CONTINUE →
|
||||
```
|
||||
|
||||
- **Multi-layer idle detection** — completion messages, AI-powered idle check, output silence, token stability
|
||||
- **Auto-resume on usage limit** *(opt-in, off by default)* — when Claude halts on a subscription limit ("You've hit your limit · resets 3pm"), Codeman parses the reset time, waits it out plus a 2-minute safety buffer, then dismisses the rate-limit dialog and sends `continue` — so an overnight run survives the 5-hour window instead of stalling until morning. Recognizes every Claude Code limit-message format, retries if still limited, survives Codeman restarts, and holds respawn cycles while paused so `/clear` can't wipe the waiting conversation. Enable per session at the top of the Respawn tab
|
||||
- **Circuit breaker** — prevents respawn thrashing when Claude is stuck (CLOSED -> HALF_OPEN -> OPEN states, tracks consecutive no-progress and repeated errors)
|
||||
- **Health scoring** — 0-100 health score with component scores for cycle success, circuit breaker state, iteration progress, and stuck recovery
|
||||
- **Built-in presets** — `solo-work` (3s idle, 60min), `subagent-workflow` (45s, 240min), `team-lead` (90s, 480min), `ralph-todo` (8s, 480min), `overnight-autonomous` (10s, 480min)
|
||||
@@ -293,7 +294,7 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt
|
||||
## More Features
|
||||
|
||||
- **Self-update** — git-clone installs under systemd/launchd update in place from **App Settings → Updates**: it detects the latest release, auto-stashes a dirty tree, and streams build progress across the service restart (npm installs report as non-updatable)
|
||||
- **Dual-CLI** — run **Claude Code** or **OpenCode** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Multi-CLI** — run **Claude Code**, **OpenCode**, or **Codex** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Effort & Ultracode** — set a per-session default effort (`low`–`max`) or enable **ultracode** (dynamic multi-agent workflows). Soft defaults only — switchable anytime with `/effort` in-session. Extended-thinking budget is configurable too
|
||||
- **Voice input** — dictate prompts with Deepgram Nova-3 (Web Speech API fallback): toggle recording, auto-silence stop, live level meter (`Ctrl+Shift+V`)
|
||||
- **Image input** — paste or drag-and-drop images straight into a session
|
||||
@@ -447,7 +448,7 @@ These run for **every** request — before auth, even on the default no-password
|
||||
|
||||
### Input, files & headers
|
||||
|
||||
- **Schema-validated inputs** — every API body is checked with Zod v4 schemas; a `CLAUDE_CODE_*` / `OPENCODE_*` env-prefix allowlist gates which settings each CLI can receive
|
||||
- **Schema-validated inputs** — every API body is checked with Zod v4 schemas; a `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` env-prefix allowlist gates which settings each CLI can receive
|
||||
- **Path containment** — file routes `realpath` before boundary checks (no TOCTOU); `..`, absolute paths, and symlinks resolving outside the working dir are rejected. Caps: 10 MB text preview / 50 MB raw & download; `/api/download` blocklists sensitive paths (`.env`, `*credentials*`, `~/.ssh/`, `.aws/credentials`). SVG/HTML is served `octet-stream` + `nosniff` + attachment so it downloads rather than executes
|
||||
- **Security headers** — `Content-Security-Policy` (`default-src 'self'`, every exception enumerated), `X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, HSTS over HTTPS, and CORS reflected **only** for `localhost` / `127.0.0.1` / `::1`
|
||||
|
||||
@@ -482,7 +483,8 @@ Single-digit selection (1-9), color-coded status, token counts, auto-refresh. De
|
||||
|----------|--------|
|
||||
| `Ctrl/Cmd+W` | Kill active session |
|
||||
| `Ctrl/Cmd+Tab` | Next session |
|
||||
| `Alt+1`–`Alt+9` | Switch to tab N |
|
||||
| `Alt/Option+[` / `Alt/Option+]` | Previous / next session |
|
||||
| `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) |
|
||||
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right |
|
||||
| `Ctrl/Cmd+L` | Clear terminal |
|
||||
| `Ctrl+Shift+R` | Restore terminal size |
|
||||
@@ -579,7 +581,7 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["External"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode</small>"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex</small>"]
|
||||
BG["Background Agents<br/><small>(Task tool)</small>"]
|
||||
end
|
||||
end
|
||||
|
||||
+8
-7
@@ -2,10 +2,10 @@
|
||||
<img src="docs/images/codeman-title.svg" alt="Codeman" height="60">
|
||||
</p>
|
||||
|
||||
<h2 align="center">为 AI 编程智能体而生的「控制平面」</h2>
|
||||
<h2 align="center">AI 编程智能体的任务控制中心</h2>
|
||||
|
||||
<p align="center">
|
||||
<em>智能体可视化 • 零延迟输入 • 自主编排器 • 重生控制器 • 移动优先 UI • 安全加固</em>
|
||||
<em>Claude Code • OpenCode • Codex —— 统一仪表盘 • 任意设备</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -36,7 +36,7 @@ curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | b
|
||||
|
||||
该脚本会在缺失时自动安装 Node.js 和 tmux,把 Codeman 克隆到 `~/.codeman/app` 并完成构建。
|
||||
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [OpenCode](https://opencode.ai)(两个都装也可以)。安装完成后:
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai) 或 [Codex](https://developers.openai.com/codex/cli)(任意组合均可)。安装完成后:
|
||||
|
||||
```bash
|
||||
codeman web
|
||||
@@ -105,7 +105,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
|
||||
wsl bash -c "curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | bash"
|
||||
```
|
||||
|
||||
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [OpenCode](https://opencode.ai))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
|
||||
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai) 或 [Codex](https://developers.openai.com/codex/cli))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
|
||||
</details>
|
||||
|
||||
---
|
||||
@@ -216,6 +216,7 @@ WATCHING → IDLE DETECTED → SEND UPDATE → /clear → /init → CONTINUE →
|
||||
```
|
||||
|
||||
- **多层空闲检测** —— 完成消息、AI 驱动的空闲检查、输出静默、token 稳定性
|
||||
- **用量限额自动恢复**(*可选,默认关闭*)—— 当 Claude 因订阅用量限额而停止("You've hit your limit · resets 3pm")时,Codeman 会解析重置时间,等到限额刷新(外加 2 分钟安全缓冲)后自动关闭限额对话框并发送 `continue`,让通宵任务平稳跨过 5 小时窗口而不是停摆到早晨。可识别 Claude Code 各版本的全部限额消息格式;若仍受限会自动重试;计划在 Codeman 重启后依然生效;暂停期间会阻止重生循环,避免 `/clear` 清掉等待中的对话。在会话 Respawn 标签页顶部按会话启用
|
||||
- **熔断器** —— 当 Claude 卡住时防止重生抖动(CLOSED → HALF_OPEN → OPEN 状态,跟踪连续无进展与重复错误)
|
||||
- **健康评分** —— 0–100 健康分,分项涵盖循环成功率、熔断器状态、迭代进展与卡死恢复
|
||||
- **内置预设** —— `solo-work`(3s 空闲,60min)、`subagent-workflow`(45s,240min)、`team-lead`(90s,480min)、`ralph-todo`(8s,480min)、`overnight-autonomous`(10s,480min)
|
||||
@@ -295,7 +296,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
## 更多特性
|
||||
|
||||
- **自更新** —— systemd/launchd 管理下的 git-clone 安装可在 **App Settings → Updates** 中原地更新:它会检测最新发行版,自动暂存(stash)脏工作树,并在服务重启期间流式展示构建进度(npm 安装会被报告为不可更新)
|
||||
- **双 CLI** —— 每个会话可选 **Claude Code** 或 **OpenCode**;环境变量前缀自动隔离(`CLAUDE_CODE_*` 与 `OPENCODE_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode** 或 **Codex**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*` 与 `CODEX_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Effort 与 Ultracode** —— 设置每会话的默认 effort(`low`–`max`),或启用 **ultracode**(动态多智能体工作流)。这些都只是软默认值 —— 会话中可随时用 `/effort` 切换。扩展思考预算也可配置
|
||||
- **语音输入** —— 用 Deepgram Nova-3 口述提示(带 Web Speech API 回退):切换录音、自动静音停止、实时音量表(`Ctrl+Shift+V`)
|
||||
- **图像输入** —— 直接把图片粘贴或拖放进会话
|
||||
@@ -449,7 +450,7 @@ Codeman 用 `--dangerously-skip-permissions` 启动会话,因此 Web UI 在设
|
||||
|
||||
### 输入、文件与响应头
|
||||
|
||||
- **模式校验的输入** —— 每个 API 请求体都用 Zod v4 模式检查;一个 `CLAUDE_CODE_*` / `OPENCODE_*` 环境变量前缀允许列表把控每个 CLI 能接收哪些设置
|
||||
- **模式校验的输入** —— 每个 API 请求体都用 Zod v4 模式检查;一个 `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` 环境变量前缀允许列表把控每个 CLI 能接收哪些设置
|
||||
- **路径限定** —— 文件路由在边界检查前先 `realpath`(无 TOCTOU);`..`、绝对路径、以及解析到工作目录之外的符号链接都会被拒绝。上限:10 MB 文本预览 / 50 MB 原始与下载;`/api/download` 对敏感路径(`.env`、`*credentials*`、`~/.ssh/`、`.aws/credentials`)做黑名单。SVG/HTML 以 `octet-stream` + `nosniff` + attachment 提供,因此会被下载而非执行
|
||||
- **安全响应头** —— `Content-Security-Policy`(`default-src 'self'`,每个例外都逐条列举)、`X-Content-Type-Options: nosniff`、`X-Frame-Options: SAMEORIGIN`、HTTPS 下的 HSTS,以及**仅**对 `localhost` / `127.0.0.1` / `::1` 反射的 CORS
|
||||
|
||||
@@ -581,7 +582,7 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["外部"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode</small>"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex</small>"]
|
||||
BG["后台智能体<br/><small>(Task 工具)</small>"]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Reliable input delivery (exactly-once, durable)
|
||||
|
||||
## The bug this fixes
|
||||
|
||||
With local echo on, pressing Enter cleared the overlay and then sent the prompt
|
||||
over the WebSocket **fire-and-forget** (`ws.send({t:'i',d})`). On a flaky link
|
||||
(e.g. a moving train) the socket is frequently *half-open*: `readyState === OPEN`
|
||||
so `ws.send()` does **not** throw, but the underlying TCP is dead, so the frame is
|
||||
silently discarded. Nothing was enqueued (the send "succeeded"), the on-screen
|
||||
prompt was already wiped, and `navigator.onLine` stays `true` — so a long typed
|
||||
prompt vanished with no trace and no resend.
|
||||
|
||||
## The guarantee
|
||||
|
||||
Every byte of user input is **recorded durably before delivery** and **only
|
||||
dropped once the server ACKs it** — so a half-open socket, a reconnect, or a page
|
||||
reload can never lose input. Redelivery is **exactly-once**: the server applies
|
||||
each `(clientId, seq)` at most once, so a resend can't type the prompt twice.
|
||||
|
||||
## How it works
|
||||
|
||||
### Client (`app.js`)
|
||||
|
||||
- A stable **`clientId`** (`localStorage['codeman:clientId']`) identifies this
|
||||
browser to the server's dedup across reconnects and reloads.
|
||||
- Each input frame gets a **monotonic per-session `seq`**. Frame records
|
||||
(`{seq,data,useMux,ts,tries,sentAt}`) live in `_pendingDeliveries`
|
||||
(`Map<sessionId, record[]>`), persisted (debounced, + flushed on `pagehide`/
|
||||
`visibilitychange`) to `localStorage['codeman:pendingInput']`. The seq counters
|
||||
persist too, so seqs stay monotonic across reloads (never reset — a reset would
|
||||
let the server treat fresh input as an already-applied duplicate).
|
||||
- **Delivery** (`_drainSession`):
|
||||
- **WS path** — when the socket is `OPEN` for the session, send each not-yet-sent
|
||||
record (`sentAt === 0`) in seq order over the single ordered stream. Records
|
||||
stay pending until the server's `{t:'ia',seq}` ACK removes them.
|
||||
- **POST path** — when no WS, POST records in order, awaiting each (the HTTP 2xx
|
||||
*is* the ACK). A 404/410 (session gone) drops the record rather than retry
|
||||
forever.
|
||||
- **Half-open recovery** (`_redeliverSweep`, every 2s): if the active WS session's
|
||||
oldest record is unacked past `_reliableAckTimeoutMs` (4s), the socket is assumed
|
||||
dead — `ws.close()` forces a fast reconnect; `onopen` (`_onWsReady`) resets
|
||||
`sentAt = 0` and re-sends everything pending. Also re-drains background sessions
|
||||
over POST, and fires on SSE-reconnect / `online`.
|
||||
- The connection indicator shows pending count/bytes (`_pendingBytes`).
|
||||
|
||||
### Server
|
||||
|
||||
- **`Session.shouldApplyInput(clientId, seq)`** — returns `true` exactly once per
|
||||
`(clientId, seq)`: the first time a seq strictly greater than that client's
|
||||
last-applied is seen. A replayed/lower seq returns `false`. Bounded MRU map
|
||||
(`MAX_INPUT_DEDUP_CLIENTS = 256`).
|
||||
- **WS route** (`ws-routes.ts`) — parses optional `cid`/`seq` on `{t:'i'}`; applies
|
||||
via `shouldApplyInput` (skips a duplicate, still ACKs with `{t:'ia',seq}` so the
|
||||
client drops it). Untagged frames apply unconditionally (no behavior change).
|
||||
- **POST route** (`/api/sessions/:id/input`) — optional `seq`/`clientId` in
|
||||
`SessionInputWithLimitSchema`; a deduped duplicate returns 200 without writing
|
||||
(the 200 is the client's ACK). `curl`/legacy callers omit the fields and always
|
||||
apply.
|
||||
|
||||
## Known limitation
|
||||
|
||||
Dedup state is in-memory on the server. A **server restart** between a write and
|
||||
the client's redelivery of that same seq could re-apply it (a rare duplicate).
|
||||
This is a deliberate trade-off: favor *never losing input* over a rare duplicate
|
||||
across the narrow restart window.
|
||||
|
||||
## Tests
|
||||
|
||||
- `test/reliable-input-dedup.test.ts` — `Session.shouldApplyInput` exactly-once
|
||||
semantics (monotonic, per-client, gap-tolerant, eviction-safe).
|
||||
- `test/routes/session-routes.test.ts` — POST `/input` applies a tagged
|
||||
`(clientId, seq)` once on redelivery; untagged input always applies.
|
||||
@@ -124,7 +124,11 @@ loopback bind matters. The auth pipeline (`src/web/middleware/auth.ts`,
|
||||
`onRequest` hook) runs in this order:
|
||||
|
||||
1. **Localhost‑only exemptions** (always first): `POST /api/hook-event` and the QR
|
||||
`/q/` short‑code path are exempt when `req.ip` is loopback (see §3).
|
||||
`/q/` short‑code path are exempt when `req.ip` is loopback (see §3). While the
|
||||
**managed tunnel is running**, the hook‑event exemption additionally requires
|
||||
the per‑instance `X-Codeman-Hook-Secret` header (COD‑54); failed presentations
|
||||
are rate‑limited in a **dedicated bucket** (separate from Basic‑Auth failures)
|
||||
so misfiring hooks can never lock out the login path.
|
||||
2. **Session cookie** check — a valid `codeman_session` cookie short‑circuits to
|
||||
allow.
|
||||
3. **HTTP Basic** check — correct credentials short‑circuit to allow and clear
|
||||
@@ -165,17 +169,29 @@ protection is unchanged.
|
||||
with `req.ip = 127.0.0.1`**. The localhost‑only exemptions then treat those
|
||||
requests as local:
|
||||
|
||||
- `POST /api/hook-event` — auth‑exempt for loopback. Bounded impact: it is
|
||||
- `POST /api/hook-event` — auth‑exempt for loopback **only while no managed tunnel
|
||||
is running**. When Codeman's own tunnel is up, the exemption requires the
|
||||
per‑instance shared secret (`X-Codeman-Hook-Secret`, 256‑bit hex in
|
||||
`~/.codeman/hook-secret`, mode 0600, COD‑54). Local hook commands read the
|
||||
secret file at execution time (`$CODEMAN_HOOK_SECRET_FILE`, exported into every
|
||||
managed session), so they keep working — tunneled internet traffic can't know
|
||||
it. Even without the secret the impact is bounded: the route is
|
||||
`HookEventSchema`‑validated and requires a valid in‑memory `sessionId`; it can
|
||||
drive respawn signals, SSE broadcasts, push notifications, and transcript
|
||||
watching — **not** arbitrary terminal input or file reads. It is a
|
||||
session‑disruption / notification‑spoofing surface, not RCE.
|
||||
watching — **not** arbitrary terminal input or file reads. ⚠️ The gate keys off
|
||||
the **managed** tunnel — an externally run loopback proxy (your own
|
||||
`cloudflared`, `tailscale serve`) is invisible to it, so the plain loopback
|
||||
exemption still applies there (prefer `tailscale serve`, which authenticates at
|
||||
the tailnet layer). Hook configs regenerated since COD‑54 always present the
|
||||
header, so a future release can require the secret unconditionally.
|
||||
- QR `/q/` — still protected by its own short‑code brute‑force limiter
|
||||
(10 failures / 60s against a 62⁶ space).
|
||||
|
||||
**Mitigation:** set `CODEMAN_PASSWORD` whenever a loopback‑connecting tunnel is
|
||||
up (it does not gate the hook‑event exemption, but it gates everything else and
|
||||
is the documented practice). Prefer `tailscale serve` (below), which authenticates
|
||||
up — it gates everything except the (secret‑gated) hook exemption and is the
|
||||
documented practice; since COD‑55 enabling the managed tunnel **refuses** to start
|
||||
without it unless `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1` explicitly
|
||||
acknowledges the exposure. Prefer `tailscale serve` (below), which authenticates
|
||||
at the tailnet layer so untrusted clients never reach the loopback port at all.
|
||||
|
||||
### Host‑header & Origin allowlist (DNS‑rebinding & CSRF defense)
|
||||
@@ -304,7 +320,37 @@ injected from API JSON (`innerHTML`), not via `file-raw`, so they are unaffected
|
||||
`/api/download` additionally refuses a blocklist of sensitive paths
|
||||
(`/etc/shadow`, `~/.ssh/`, `.env`, `*credentials*`, `.aws/credentials`, …). This
|
||||
is **defense‑in‑depth, not the primary boundary** — the realpath containment is
|
||||
the control.
|
||||
the control. The blocklist patterns are shared (`src/web/sensitive-path.ts`) with
|
||||
the attachment guard below.
|
||||
|
||||
### External attachments (registry) & the magic‑link trust boundary
|
||||
|
||||
Live external attachments (`src/attachment-registry.ts`) mint an `att_<uuid>` id
|
||||
for a host file so browser requests carry the id, never an absolute path. Serving
|
||||
is by id (`GET /api/sessions/:id/attachments/:attachmentId/raw`, 50 MB cap,
|
||||
`nosniff`) and re‑resolves the symlink + re‑checks the **attachment guard**
|
||||
(`src/config/attachment-guard.ts`: the shared sensitive‑path blocklist **plus**
|
||||
the `/root` and `/etc` trees, extendable via `attachmentBlockedPaths` /
|
||||
`CODEMAN_ATTACHMENT_BLOCKED_PATHS`) on every request. Unlike the workspace file
|
||||
routes, attachments are intentionally **cross‑workspace** — so the effective gate
|
||||
is the blocklist + a 6‑extension allowlist (`png/pdf/docx/pptx/md/txt`), not
|
||||
realpath containment.
|
||||
|
||||
Two registration paths, with **different trust**:
|
||||
|
||||
- **Explicit `POST /api/sessions/:id/attachments`** (and `codeman attach`, which
|
||||
POSTs directly inside a managed session) — a deliberate, Origin‑guarded HTTP
|
||||
request. Allowed cross‑workspace (subject to the guard). This is the supported
|
||||
path for codeman‑publish and the `~/.codeman` review‑card loop.
|
||||
- **Terminal `codeman://attach?path=…` magic links** — scanned passively from
|
||||
session output. Terminal output is **attacker‑influenceable** (a prompt‑injected
|
||||
session can print an arbitrary path), and registration here is server‑side with
|
||||
no Origin gate and broadcasts the `rawUrl` over SSE to all clients. This path is
|
||||
therefore **force‑confined to the session workspace** (`forceWorkspaceConfinement`
|
||||
in `registerExternalAttachment`, wired in `WebServer.registerAttachment`),
|
||||
regardless of the global confine setting — a passive magic link cannot expose a
|
||||
file outside the session's own workspace. Cross‑workspace attach must go through
|
||||
the explicit POST path above.
|
||||
|
||||
### SSE log‑tail route — intentional extra read roots
|
||||
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
# Ultracode / Workflow Agent Visualization — Design & Implementation Plan
|
||||
|
||||
> **Status: IMPLEMENTED (2026-06-15, rev. 3) — Phases 1–3 shipped & verified; Phase 4 (live-transcript link) deferred.** A dedicated, opt-in **master-detail tab** (`showUltracodeAgents`, default OFF) shows ultracode/Workflow runs as Claude Code's "working agents" TUI: LEFT = runs + phases (selectable tasks), RIGHT = each run's agents with model, live state, **tokens burned**, and **tool calls**.
|
||||
>
|
||||
> ### What rev. 3 changed vs. rev. 2 (decided during implementation against on-disk truth)
|
||||
> 1. **UI is a master-detail TAB, not grouped floating subagent windows.** The user asked for the CC "working agents" view (left task picker, right agent stats). Built as a new docked panel `#ultracodeAgentsPanel` (clones `.subagents-panel` master-detail CSS) + `src/web/public/ultracode-panel.js` — NOT via `openSubagentWindow`/grouped windows.
|
||||
> 2. **STANDALONE — zero edits to `subagent-watcher.ts`.** w16-claudeman's commit `f6a30d7` already discovers the per-agent workflow *transcripts* (`watchWorkflowDirs`). The data the view needs (run/phase/per-agent tokens+toolCalls) lives in the *run-state* JSON, read by a brand-new `src/workflow-run-watcher.ts` (globs the disjoint `…/workflows/wf_*.json` tree). No shared files with w16.
|
||||
> 3. **No per-agent transcript streaming needed for v1.** The run-state JSON already carries `tokens`/`toolCalls`/`state`/`label`/`phase` per agent, so the whole view reads from `wf_<runId>.json` alone. (Phase 4 will optionally link a card to its already-tracked transcript via `agentId` — no watcher edits.)
|
||||
> 4. **Agent states are `start | progress | done`** (verified on disk) — NOT running/queued. `start`=queued (no agentId/tokens/toolCalls yet), `done` has `durationMs`/`resultPreview`.
|
||||
> 5. **The run JSON's `script` (15–660KB embedded JS), `scriptPath`, `result`, `logs` are STRIPPED in the watcher** before caching/broadcast (a 28-agent run drops 174KB → ~25KB; `promptPreview`/`resultPreview` truncated).
|
||||
> 6. **SSE/snapshot ship lightweight run SUMMARIES (no `agents[]`); the RIGHT pane fetches the full run** via `GET /api/workflows/:runId` on selection. (A 25-run snapshot is ~20KB vs ~900KB if it carried every agent.) The LEFT list shows ALL cached runs (LRU-bounded), not a recency window — a run browser must show past runs.
|
||||
>
|
||||
> _Original rev. 2 proposal (grouped floating windows, extending subagent-watcher) preserved below for context; superseded by the above._
|
||||
|
||||
### What changed in rev. 2 (vs. the first draft)
|
||||
|
||||
1. **No backend cross-watcher coupling.** The per-agent label/phase/agentType/state **join moves to the frontend at render time** — the run object already carries every agent's entry keyed by `agentId`. This deletes `subagent-watcher`'s backward dependency on `workflow-run-watcher` (`getAgentLabel()` + its TTL cache), removes the registration-vs-run-state **race** (labels always track the latest `workflow:run_updated`), and drops the per-agent `meta.json` read from the hot path.
|
||||
2. **`SubagentInfo` grows by 2 fields, not 4** (`isWorkflowAgent`, `workflowRunId`) — both derivable from the file path alone at registration, zero extra I/O. `agentType`/`label`/`phase`/`state` come from the run object on the frontend.
|
||||
3. **The `isInternalAgent` bypass covers BOTH drop sites** — `registerAgentFile` *and* the late re-resolution in `processEntry`. The first draft named only one.
|
||||
4. **De-duplicated.** Each trap (`journal.jsonl`, the `projects/*/*/workflows` depth, the gate-mismatch lesson, reuse-not-rebuild) is stated once in its owning section.
|
||||
|
||||
### Code-reuse verified against the tree (2026-06-14)
|
||||
|
||||
Confirmed present and shaped as assumed: `subagent-watcher.ts` — `watchSubagentDir`/`registerAgentFile`/`tailFile`/`processEntry`, `getRecentSubagents`, `isInternalAgent` (drops on `MIN_DESCRIPTION_LENGTH=5`), `STARTUP_MAX_FILE_AGE_MS=4h`, `MAX_TRACKED_AGENTS`, `knownSubagentDirs`/`dirWatchers`. `team-watcher.ts` — `configMtimes` mtime-skip + chokidar + `setInterval` poll. `server.ts` — `setupSubagentWatcherListeners`, `getLightState()` (`subagents: getRecentSubagents(15)`, `LIGHT_STATE_CACHE_TTL_MS=1000`), `isSubagentTrackingEnabled()` (`settings.subagentTrackingEnabled ?? true`). Frontend — `_SSE_HANDLER_MAP`, `this.subagents` Map, `handleInit`/`cleanupAllFloatingWindows`, `renderSubagentPanel`/`_renderSubagentPanelImmediate`, `getTeammateBadgeHtml`, `openSubagentWindow` + `.subagent-window-parent` sub-header.
|
||||
|
||||
## 1. The enabling fact: on-disk artifacts
|
||||
|
||||
The Workflow tool (what `ultracode` drives) persists each workflow agent as a transcript under the **same `subagents/` directory Codeman already watches**, one level deeper. Empirically verified against a real run (`wf_a8e09f2c-550`); **re-confirm the shape against a fresh run at implementation time** (§8 mandates a live e2e pass anyway):
|
||||
|
||||
```
|
||||
~/.claude/projects/<projHash>/<sessionUuid>/
|
||||
├─ subagents/
|
||||
│ ├─ agent-XX.jsonl ← regular Task subagent (tracked today)
|
||||
│ └─ workflows/wf_<runId>/
|
||||
│ ├─ agent-YY.jsonl ← WORKFLOW agent — IDENTICAL line format
|
||||
│ ├─ agent-YY.meta.json ← {"agentType":"workflow-subagent"} (optional enrichment)
|
||||
│ └─ journal.jsonl ← run journal {type:"started",...} — MUST be skipped
|
||||
└─ workflows/wf_<runId>.json ← run state: runId, workflowName, summary, status,
|
||||
phases[], workflowProgress[], totals (DIFFERENT tree)
|
||||
```
|
||||
|
||||
The per-agent `.jsonl` line shape is identical to a regular subagent transcript:
|
||||
|
||||
```jsonc
|
||||
{ "parentUuid": null, "isSidechain": true, "agentId": "ac6a1d27012a64e38",
|
||||
"type": "user" | "assistant", "message": { "role": "...", "content": "..." }, ... }
|
||||
```
|
||||
|
||||
Because the line shape is identical, the entire existing parse→event→render pipeline works unchanged once discovery reaches those files. The only new data is the **run-level metadata** in `workflows/wf_<runId>.json` (name, summary, phases, and `workflowProgress[]` — the per-agent labels/state/tools), which supplies the group header and per-agent labels.
|
||||
|
||||
**Can show:** per-agent live transcript (tool calls, messages, results); per-agent status (active/idle/completed via the existing mtime/PID/pgrep liveness); per-agent model + running token totals (from each agent's JSONL `message.usage`, exactly as today); the run's `workflowName`/`summary`/`phases[]`; per-agent `label`/`phaseTitle`/`state`/`lastToolName` (from `workflowProgress[]`); grouping under `wf_<runId>`.
|
||||
|
||||
**Cannot show:** anything absent from the artifacts — a live phase cursor beyond `workflowProgress[].state`; an authoritative **budget/cost ceiling** (only consumed totals exist — `usage` + run-state `totalTokens`, no remaining-budget field); runs older than `STARTUP_MAX_FILE_AGE_MS` (4h) after a server restart (live monitoring only).
|
||||
|
||||
## 2. Architecture
|
||||
|
||||
**Decision: EXTEND `subagent-watcher.ts` for per-agent discovery/streaming; ADD a thin `workflow-run-watcher.ts` (modeled on `team-watcher.ts`) for the group-header metadata ONLY. The agent→run-metadata join happens on the FRONTEND, so the two watchers stay decoupled.**
|
||||
|
||||
- The per-agent JSONL is identical in shape, so re-running it through `registerAgentFile()` → `tailFile()` → `processEntry()` and the existing `subagent:*` events is free and reconnect-safe (those agents land in `agentInfo`, replayed by `getRecentSubagents(15)`). A parallel per-agent watcher would duplicate the liveness/token/tool-call/SSE machinery for zero benefit.
|
||||
- Run metadata lives in a *different* file under a *different* tree (`workflows/wf_<runId>.json`, sibling to `subagents/`). A small `WorkflowRunWatcher` watching `projects/*/*/workflows/wf_*.json` (mtime-skip, like `team-watcher`'s `configMtimes`) is the clean home; folding it into `subagent-watcher` would entangle two unrelated watch roots and put a JSON re-read in the hot per-line path.
|
||||
- **The two watchers never call each other.** The frontend receives both streams and joins agent→label by `agentId` at render time (the run object carries every agent's entry). This removes the timing coupling entirely.
|
||||
|
||||
```
|
||||
~/.claude/projects/<projHash>/<sessionUuid>/
|
||||
├─ subagents/
|
||||
│ ├─ agent-XX.jsonl ──────────────► SubagentWatcher (EXTENDED: also descends
|
||||
│ └─ workflows/wf_<runId>/ workflows/wf_<runId>/, tags isWorkflowAgent+runId)
|
||||
│ ├─ agent-YY.jsonl ─┐ reuse registerAgentFile/tailFile/processEntry
|
||||
│ └─ journal.jsonl (SKIP) emits subagent:* (now w/ 2 workflow fields)
|
||||
└─ workflows/wf_<runId>.json ──────► WorkflowRunWatcher (NEW, team-watcher-shaped)
|
||||
{workflowName,phases,workflowProgress[]} emits workflow:run_discovered|updated|removed
|
||||
|
||||
server.ts
|
||||
setupSubagentWatcherListeners() ──► broadcast(subagent:*) ─┐
|
||||
setupWorkflowRunWatcherListeners() ──► broadcast(workflow:run_*) │ SSE
|
||||
getLightState(): subagents + workflowRuns ───────────────────────┘
|
||||
│
|
||||
▼ app.js dispatch table
|
||||
panels-ui: partition this.subagents by workflowRunId; header + per-agent
|
||||
labels JOINED from this.workflowRuns.get(runId).agents (by agentId)
|
||||
```
|
||||
|
||||
## 3. Backend changes (ordered, file-by-file)
|
||||
|
||||
### 3a. `src/subagent-watcher.ts` — nested discovery + 2 tag fields
|
||||
|
||||
**(1) Extend `SubagentInfo` with exactly two optional fields** (optional → regular subagents and the wire shape are unaffected):
|
||||
|
||||
```ts
|
||||
isWorkflowAgent?: boolean; // true when discovered under subagents/workflows/<wf_runId>/
|
||||
workflowRunId?: string; // e.g. "wf_23dbeab2-152" (parent dir name)
|
||||
```
|
||||
|
||||
Both are derived from the **file path alone** at registration — no extra reads. They ride existing `subagent:discovered|updated|completed` payloads (no new per-agent event). Do **not** add `agentType`/`label`/`phase`/`workflowName` here — those come from the run object on the frontend (§4c).
|
||||
|
||||
**(2) Constant.** `const WORKFLOWS_SUBDIR = 'workflows';` near the existing dir constants.
|
||||
|
||||
**(3) `watchSubagentDir()` — descend into `workflows/<wf_runId>/`.** After the existing direct-child registration loop:
|
||||
|
||||
```ts
|
||||
// Workflow agents live one level deeper: subagents/workflows/<wf_runId>/agent-*.jsonl
|
||||
const wfRoot = join(dir, WORKFLOWS_SUBDIR);
|
||||
try {
|
||||
for (const runId of await readdir(wfRoot)) {
|
||||
if (!runId.startsWith('wf_')) continue;
|
||||
await this.watchWorkflowRunDir(join(wfRoot, runId), projectHash, sessionId, runId);
|
||||
}
|
||||
} catch { /* no workflows subdir — normal for most sessions */ }
|
||||
```
|
||||
|
||||
The existing `fs.watch(dir, …)` on `subagents/` is **non-recursive on Linux** and won't fire for writes inside `workflows/<runId>/`, so each run dir needs its own watcher.
|
||||
|
||||
**(4) New private `watchWorkflowRunDir(runDir, projectHash, sessionId, runId)`** — clone `watchSubagentDir`'s structure, but:
|
||||
- Register only files matching `^agent-.*\.jsonl$`, **explicitly skipping `journal.jsonl`** (it ends in `.jsonl` but is `{type:'started',…}`, not a transcript — registering it would create a phantom agent).
|
||||
- Call `registerAgentFile(filePath, projectHash, sessionId, isInitialScan, runId)` so the agent is tagged.
|
||||
- Install one `watch(runDir, …)` per run dir; on `error` and `stop()`, reuse the existing teardown (close + delete from `dirWatchers`/`knownSubagentDirs`/`dirWatcherErrorHandlers`).
|
||||
- Guard re-registration **per run dir** in `knownSubagentDirs`, **not** `wfRoot` — the 5s full scan must still re-`readdir(wfRoot)` to pick up *new* `wf_<runId>` dirs created mid-session.
|
||||
|
||||
**(5) `registerAgentFile()` — accept + apply `runId`.** Add a trailing optional `runId?: string`. When set, the whole change is:
|
||||
|
||||
```ts
|
||||
if (runId) { info.isWorkflowAgent = true; info.workflowRunId = runId; }
|
||||
```
|
||||
|
||||
No `meta.json` read, no run-state lookup, no description override. `agentId`s are globally unique `a<16hex>` (verified: 0 collisions across a 370-agent corpus), so keep the flat `agentInfo` map keyed by `agentId` — do **not** switch to a composite key. Add a one-line dev-assert log if `agentInfo.has(agentId)` with a *different* `workflowRunId`, so a future collision is observable.
|
||||
|
||||
**(6) `isInternalAgent` bypass — BOTH drop sites.** Workflow agents have no Task-tool spawn record, so `_resolveDescription` yields only the first-user-message fallback (often a long phase prompt) or empty → `isInternalAgent` (`length < MIN_DESCRIPTION_LENGTH`) would wrongly drop them. They are real by construction (the `subagents/workflows/wf_*/` path is the discriminator). Gate the drop on `!info.isWorkflowAgent` at **both** places:
|
||||
- `registerAgentFile` initial check (`isInternalAgent(description)`),
|
||||
- `processEntry`'s late re-resolution (the second `isInternalAgent` call).
|
||||
|
||||
**(7) `stop()` teardown.** Per-run watchers live in `dirWatchers`, so the existing close-all loop covers them — verify no separate map was introduced (24h runs spawn many `wf_<runId>` dirs → FSWatcher leak risk).
|
||||
|
||||
### 3b. NEW `src/workflow-run-watcher.ts` (singleton, EventEmitter — model on `team-watcher.ts`)
|
||||
|
||||
- **Watch root:** `~/.claude/projects/<projHash>/<sessionUuid>/workflows/wf_*.json` — **two** levels under `projects` (verified: `projects/*/workflows` is empty; must be `projects/*/*/workflows/`). chokidar `depth:3` + a poll fallback, mirroring `team-watcher`'s dual discovery + interval.
|
||||
- **mtime-skip:** `runMtimes: Map<absPath, number>` (mirror `team-watcher.configMtimes`).
|
||||
- **Parse:** read `wf_<runId>.json`, take the **top-level structured keys** (`runId`, `workflowName`, `summary`, `status`, `phases:[{title,detail}]`, `agentCount`, `defaultModel`, `durationMs`, `totalTokens`, `totalToolCalls`, `workflowProgress[]`). **Do NOT parse the embedded `script` string** — name/phases/summary are already top-level; the script's `export const meta` is redundant and costly. Derive `sessionUuid` from the dir name, `projectHash` from the dir above; expose `getProjectHash(workingDir)` for Codeman-session correlation.
|
||||
- **`workflowProgress[] → agents[]`:** filter `type === 'workflow_agent'`, map each to a `WorkflowAgentEntry` (§3c) keyed by `agentId`. **This array is the join source the frontend uses** — no backend `getAgentLabel()` API, no TTL cache, no import from `subagent-watcher`.
|
||||
- **Emit** `workflow:run_discovered|updated|removed` carrying `WorkflowRunInfo`; removal by set-diff (mirror `team-watcher`).
|
||||
- **Lifecycle:** `start()`/`stop()` with `CleanupManager` teardown of chokidar + interval + caches; `LRUMap`-bounded run cache (24h memory rule).
|
||||
|
||||
### 3c. `src/types/` — workflow run types
|
||||
|
||||
```ts
|
||||
export interface WorkflowAgentEntry { // one workflowProgress[type==='workflow_agent']
|
||||
agentId: string; label: string; phaseIndex?: number; phaseTitle?: string;
|
||||
agentType?: string; model?: string; state?: string; // 'done'|'running'|'queued'|...
|
||||
lastToolName?: string; lastToolSummary?: string; tokens?: number; toolCalls?: number;
|
||||
}
|
||||
export interface WorkflowRunInfo {
|
||||
runId: string; sessionUuid: string; projectHash: string;
|
||||
workflowName?: string; summary?: string; status?: string; // 'running'|'completed'|...
|
||||
phases: Array<{ title: string; detail?: string }>;
|
||||
agentCount?: number; defaultModel?: string;
|
||||
agents: WorkflowAgentEntry[]; // workflowProgress filtered to workflow_agent, keyed by agentId
|
||||
startedAt?: number; durationMs?: number; totalTokens?: number; totalToolCalls?: number;
|
||||
}
|
||||
```
|
||||
|
||||
The two `SubagentInfo` workflow fields stay inline in `subagent-watcher.ts` (matching the existing convention).
|
||||
|
||||
### 3d. `src/web/sse-events.ts` — register run events
|
||||
|
||||
Add `workflow:run_discovered`, `workflow:run_updated`, `workflow:run_removed` after the `subagent:*` block and to the `SseEvent` union. **No new per-agent event** — workflow agents reuse `subagent:*`.
|
||||
|
||||
### 3e. `src/web/server.ts` — bridge, snapshot, gating
|
||||
|
||||
- **`setupWorkflowRunWatcherListeners()`** (beside `setupSubagentWatcherListeners`): map the three run events → `this.broadcast(...)`. Add `cleanupWorkflowRunWatcherListeners()` (store handler refs).
|
||||
- **Start/stop:** call `workflowRunWatcher.start()`/`.stop()` beside `subagentWatcher`, **gated on the same enable condition** (§3f).
|
||||
- **`getLightState()`:** add `workflowRuns: workflowRunWatcher.getRecentRuns(15)` beside `subagents: subagentWatcher.getRecentSubagents(15)` so headers replay on reconnect (agents already replay via `subagents`). Keep the `LIGHT_STATE_CACHE_TTL_MS` memoization.
|
||||
- **Gating read:** add `isWorkflowAgentTrackingEnabled()` mirroring `isSubagentTrackingEnabled()` (boot-time `dataPath('settings.json')` read). Gate `workflowRunWatcher.start()` **and** the subagent-watcher `workflows/` descent (§3a-3) on `showUltracodeAgents` so non-opted-in users never register historical workflow agents.
|
||||
|
||||
### 3f. `src/web/schemas.ts` — settings key
|
||||
|
||||
Add `showUltracodeAgents: z.boolean().optional()` to the `.strict()` settings update schema near `showPlanUsageLimits` (required — `.strict()` 400s the whole PUT on an unknown key).
|
||||
|
||||
### 3g. `src/web/routes/system-routes.ts` — poll API
|
||||
|
||||
- `GET /api/subagents` and `GET /api/sessions/:id/subagents` include workflow agents once registered — **no change** (they carry `isWorkflowAgent`/`workflowRunId`; a consumer joins to `/api/workflows/:runId` for labels).
|
||||
- Add `GET /api/workflows` → `workflowRunWatcher.getRecentRuns()` and `GET /api/workflows/:runId` (uniform `ApiResponse` contract; headers are also in `getLightState`).
|
||||
- `GET /api/subagents/:agentId/transcript` works for workflow agents (they're in `agentInfo`) — no new route.
|
||||
|
||||
## 4. Frontend changes (file-by-file)
|
||||
|
||||
### 4a. `src/web/public/constants.js`
|
||||
- Add the three SSE strings to `SSE_EVENTS`, matching §3d exactly (`WORKFLOW_RUN_DISCOVERED: 'workflow:run_discovered'`, etc.).
|
||||
- Reuse `ZINDEX_SUBAGENT_BASE=1000` for the agent windows (they ARE subagent windows). The group **header/cluster** is in-flow panel DOM, not a floating window — no new z-index (1100 is plan-subagent).
|
||||
|
||||
### 4b. `src/web/public/app.js`
|
||||
- Constructor: `this.workflowRuns = new Map(); // runId -> WorkflowRunInfo` beside `this.subagents`.
|
||||
- `_SSE_HANDLER_MAP`: add three rows → `_onWorkflowRunDiscovered/Updated/Removed` (must exist before `connectSSE` builds the wrappers).
|
||||
- `handleInit`: after seeding `data.subagents`, seed `this.workflowRuns` from `data.workflowRuns` (clear-then-set). **Clear `this.workflowRuns` everywhere the subagent Maps are cleared** (incl. `cleanupAllFloatingWindows`) — 24h leak guard.
|
||||
|
||||
### 4c. `src/web/public/panels-ui.js` — the join lives here
|
||||
- `_onWorkflowRunDiscovered/Updated(data)` → `this.workflowRuns.set(data.runId, data)` + debounced re-render; `_onWorkflowRunRemoved` → delete + re-render.
|
||||
- **No change to `_onSubagentDiscovered/Updated`** — they already store the whole payload, so the 2 new fields ride along.
|
||||
- `renderSubagentPanel`/`_renderSubagentPanelImmediate`: when `showUltracodeAgents` is on, **partition `this.subagents` into flat (no `workflowRunId`) vs grouped-by-`workflowRunId`**. Flat agents render exactly as today. For each group: build the header from `this.workflowRuns.get(runId)` (`workflowName` + phase/status chip from `phases[]`), then render that run's agents reusing the existing per-agent row markup. **Per-agent label/phase/agentType come from the JOIN** — build `Map(agentId → entry)` from `this.workflowRuns.get(runId).agents` and look each agent up by `agent.agentId`; render the small chip via the `getTeammateBadgeHtml` pattern. (If the run object hasn't arrived yet, fall back to the agent's own `description` — the run `:updated` event will fill it in on the next render.)
|
||||
- `findParentSessionForSubagent` is unchanged — workflow agent `sessionId === session.claudeSessionId`. **Do not conflate `workflowRunId` with `sessionId`.**
|
||||
|
||||
### 4d. `src/web/public/subagent-windows.js`
|
||||
**Decision: REUSE `.subagent-window` per agent + a group sub-header — do NOT build a cluster class.** A cluster path duplicates Map/z-index/drag/cleanup/persistence for no functional gain; reuse keeps connection lines, minimize-to-tab, and `localStorage` persistence. In `openSubagentWindow`, where the optional `.subagent-window-parent` sub-header is built: when `agent.workflowRunId` is set, inject a `.subagent-workflow-header` showing `this.workflowRuns.get(runId)?.workflowName` + the joined agent's `label`/phase (look up by `agentId`), mirroring the `from <session>` sub-header. Respect the existing skip guards (teammate-terminal windows, minimized/`_lazyTerminal`).
|
||||
|
||||
**Do NOT auto-open windows** for workflow agents — a multi-phase run can spawn many, against the 50-window/60fps budget + `MAX_TRACKED_AGENTS=500`. They render collapsed in the grouped panel; the user expands via the existing panel buttons.
|
||||
|
||||
### 4e. `src/web/public/settings-ui.js` + `index.html`
|
||||
- `index.html` Panels block: add a `settings-item` checkbox `id="appSettingsShowUltracodeAgents"` ("Show ULTRACODE / Workflow Agents").
|
||||
- `openAppSettings`: load `settings.showUltracodeAgents` with `false` fallback (mirror `showPlanUsageLimits`).
|
||||
- `saveAppSettings`: collect `showUltracodeAgents` into the fresh settings literal (uncollected keys reset to default every save).
|
||||
- Live-apply on toggle: re-run `renderSubagentPanel()` (show/hide group sections) — a panel re-render, not a CSS-class strip.
|
||||
- **SYNCED, not per-device:** do NOT add `showUltracodeAgents` to `displayKeys` and do NOT strip it in the per-device block. A synced value gives the server-side gate (`isWorkflowAgentTrackingEnabled`, §3e) one canonical truth to decide whether to run the watcher; a per-device value can't gate a process-wide watcher. (Contrast `showResponseViewer`, pure client display.)
|
||||
- `styles.css` + `mobile.css`: add `.subagent-workflow-header` and `.subagent-group-badge` next to `.subagent-window-parent`; mirror device overrides in `mobile.css`.
|
||||
|
||||
## 5. Settings / opt-in wiring
|
||||
|
||||
- **Key:** `showUltracodeAgents` (boolean, **default OFF**). Fallback `false` in `openAppSettings`; "absent ⇒ off" in `isWorkflowAgentTrackingEnabled()`. Schema `z.boolean().optional()` in the `.strict()` update schema, kept OUT of `displayKeys` (synced).
|
||||
- **Runtime gating:** `workflowRunWatcher.start()` and the subagent-watcher `workflows/` descent run only when the boot-time `settings.json` read reports `showUltracodeAgents === true` (mirroring `isSubagentTrackingEnabled`). The frontend additionally gates display. Toggling at runtime gates **display** immediately (panel re-render); the **watcher branch** picks up on next boot — matches existing `subagentTrackingEnabled` semantics. (Optional polish: restart just the workflow watcher on toggle for instant on/off.)
|
||||
|
||||
## 6. SSE events
|
||||
|
||||
**Reused (no change):** `subagent:discovered|updated|tool_call|tool_result|progress|message|completed`. Workflow agents flow through these; payloads now carry the optional `isWorkflowAgent`/`workflowRunId` fields on `SubagentInfo`. SSE payloads aren't schema-gated (typed only at `broadcast()` call sites), so the new fields propagate with zero friction.
|
||||
|
||||
**New (3 events, run-level metadata):**
|
||||
|
||||
| Event (backend const / frontend key) | Payload |
|
||||
|---|---|
|
||||
| `workflow:run_discovered` / `WORKFLOW_RUN_DISCOVERED` | `WorkflowRunInfo` |
|
||||
| `workflow:run_updated` / `WORKFLOW_RUN_UPDATED` | `WorkflowRunInfo` |
|
||||
| `workflow:run_removed` / `WORKFLOW_RUN_REMOVED` | `{ runId: string }` |
|
||||
|
||||
Sync requirement (CLAUDE.md): each must appear in **both** `sse-events.ts` (§3d) and `constants.js` `SSE_EVENTS` (§4a), be emitted via `broadcast()` in `setupWorkflowRunWatcherListeners()` (§3e), and have a dispatch-table row + `_on*` handler (§4b/§4c).
|
||||
|
||||
## 7. Edge cases & cleanup
|
||||
|
||||
- **`journal.jsonl` phantom-agent trap** — owned by §3a-4: run-dir registration requires the `agent-` prefix and excludes `journal.jsonl`.
|
||||
- **`isInternalAgent` over-filtering** — owned by §3a-6: bypass at BOTH drop sites; titled from the frontend join (or the description fallback).
|
||||
- **No workflow agents in the flat list** — `renderSubagentPanel` partitions on `agent.workflowRunId` (§4c). When the toggle is OFF, the descent never ran, so they aren't in `this.subagents` at all.
|
||||
- **Completion/idle** — keep the existing per-agent mtime/PID/pgrep liveness as the per-card source of truth. Optionally render a group-level "workflow done" badge from run-state `status==='completed'`.
|
||||
- **Limits** — `MAX_TRACKED_AGENTS=500` LRU-evicts workflow agents in the same flat map; no auto-open (50-window budget); the 4h `STARTUP_MAX_FILE_AGE_MS` skip means a run completed >4h ago won't reload after restart (acceptable — live monitoring).
|
||||
- **Reconnect/replay** — agents via `getRecentSubagents(15)`; headers via `workflowRuns: getRecentRuns(15)` in `getLightState`. `handleInit` clears `this.workflowRuns` alongside the subagent Maps.
|
||||
- **Watcher teardown** — every per-run `fs.watch` and the chokidar watcher closes in `stop()` and on `error`; `CleanupManager` for the new watcher (24h runs create many run dirs).
|
||||
- **CLAUDE.md discipline** — read-only `~/.claude/...` artifacts; no new `~/.codeman/...` paths, no env-var prefixes touched. Claude-mode-only by nature (external CLIs don't write workflow transcripts).
|
||||
|
||||
## 8. Testing & verification
|
||||
|
||||
- **Unit (pure):**
|
||||
- `test/workflow-run-watcher.test.ts`: feed a scrubbed fixture `wf_<runId>.json` → assert `WorkflowRunInfo` extraction (name/summary/phases, `workflowProgress`→`agents[]` keyed by `agentId`), mtime-skip, removal-by-set-diff.
|
||||
- Extend `subagent-watcher` coverage: temp `subagents/workflows/wf_X/agent-Y.jsonl` + a stray `journal.jsonl` → assert `agent-Y` registered with `isWorkflowAgent`/`workflowRunId` and `journal.jsonl` NOT registered; assert a short-description workflow agent is NOT dropped at **either** `isInternalAgent` site.
|
||||
- **Route/inject (`app.inject`):** `GET /api/workflows` + `:runId` return the `ApiResponse` envelope; `GET /api/subagents` includes a tagged agent.
|
||||
- **Frontend (vm-sandbox, like `test/run-mode-ui.test.ts`):** dispatch `subagent:discovered` with `workflowRunId` + `workflow:run_discovered` → assert `renderSubagentPanel` produces a group section under the workflow name with the agent inside it (label sourced from the **join**, not flat); assert order-independence (agent before run, and run before agent both resolve); assert OFF hides the section.
|
||||
- **REQUIRED real end-to-end** (the always-end-to-end-test rule — the plan-usage chip shipped *dead* from a gate mismatch): on dev/beta with `showUltracodeAgents` ON, **drive a real ultracode/workflow run**, then (1) `curl …/api/workflows | jq` shows the live run with `agents[]`; (2) `curl …/api/subagents | jq '.data[]|select(.isWorkflowAgent)'` shows tagged agents; (3) watch `/api/events` for `workflow:run_discovered` + `subagent:discovered` with the workflow fields; (4) Playwright (`waitUntil:'domcontentloaded'`, wait 3–4s) asserts the grouped DOM cluster renders with the workflow-name header and live status. Verify path gates against `GET /api/sessions` `workingDir`. **Test against a LIVE run** — all at-rest runs are `completed`/`done`; `running`/`queued` states only exist mid-run.
|
||||
|
||||
## 9. Phased rollout
|
||||
|
||||
| Phase | Scope | Done-check | Size |
|
||||
|---|---|---|---|
|
||||
| **P1 — Backend discovery + tagging (gated, no UI)** | §3a (nested descent, `journal.jsonl` skip, 2 `SubagentInfo` fields, `isInternalAgent` bypass ×2) + §3f schema key + §3e gate read. No run watcher yet. | With `showUltracodeAgents` forced on, `curl /api/subagents \| jq '.data[]\|select(.isWorkflowAgent)'` lists real workflow agents during a live run; flat subagents unchanged; `tsc --noEmit` + targeted watcher test green. | S–M |
|
||||
| **P2 — Run-state metadata + SSE** | §3b (`workflow-run-watcher.ts`) + §3c types + §3d/§3e (SSE, bridge, `getLightState` replay) + §3g routes. | `curl /api/workflows \| jq` returns runs with `agents[]`/`phases`; SSE emits `workflow:run_discovered`; reconnect snapshot carries `workflowRuns`. | M |
|
||||
| **P3 — Frontend grouped UI** | §4a–§4d (constants, app.js state/dispatch/init, panels-ui grouped render + **agent→label join**, subagent-windows group sub-header). Reuse `.subagent-window`; no auto-open. | Playwright: live run renders a group section under the workflow name with per-agent rows + live status + joined labels; flat subagents stay flat; expand opens a window with the workflow sub-header. | M |
|
||||
| **P4 — Settings toggle + polish + docs** | §4e (checkbox, settings-ui load/save/live-apply, SYNCED), styles/mobile, phase chips, CLAUDE.md "Key Patterns" entry + this doc's status → SHIPPED. | Toggling the checkbox shows/hides the cluster live (no reload for display); OFF by default on a fresh install; CI green. | S |
|
||||
|
||||
Each phase is independently shippable: P1 is invisible (gated, no UI), P2 adds an API with no UI dependency, P3 lights up the UI for flag-enablers, P4 exposes the toggle and finalizes defaults/docs.
|
||||
|
||||
## 10. Effort & risk
|
||||
|
||||
**Size:** P1 = S–M, P2 = M, P3 = M, P4 = S. Total ≈ **M** (one focused engineer, ~2–4 days incl. the real end-to-end run — down from the first draft's M-L now that the backend join/coupling is gone).
|
||||
|
||||
**Top 3 risks:**
|
||||
|
||||
1. **Non-recursive watch on Linux misses live writes.** `fs.watch` is non-recursive and `{recursive:true}` is unreliable on Linux → per-`wf_<runId>` watchers (§3a-4) are correct, but the 5s full scan must re-`readdir(wfRoot)` to catch *new* run dirs mid-session, and each watcher must be torn down to avoid FSWatcher leaks in 24h runs. Mitigation: explicit per-run-dir registration + verified `dirWatchers` teardown; chokidar (with `CleanupManager`) only in the new run watcher, where `team-watcher` already proves the pattern.
|
||||
2. **Discovery cost / over-registration.** A user with hundreds of historical workflow agents could flood `agentInfo` on boot. Mitigation: the 4h `STARTUP_MAX_FILE_AGE_MS` skip drops old files on the initial scan, the descent only runs when the toggle is on, and `MAX_TRACKED_AGENTS=500` LRU-evicts. Verify boot scan time doesn't regress with the corpus present.
|
||||
3. **Shipping-dead-on-a-gate** (the repo's recurring failure mode — the plan-usage chip shipped dead because injection was gated on `CASES_DIR` while real sessions ran elsewhere). Same trap here if the path/mode gate is wrong (e.g. `projects/*/workflows` instead of `projects/*/*/workflows`, or correlation via the wrong session key). Mitigation: the **mandatory live ultracode end-to-end run** in §8 against a real session's `workingDir`, observing the real SSE event + real DOM cluster — not the at-rest corpus, not unit tests alone.
|
||||
@@ -0,0 +1,169 @@
|
||||
# Plan Usage Limits Display — Design & As-Built
|
||||
|
||||
> **Status: SHIPPED — deployed to prod + pushed to master, not yet released (2026-06-14).** Opt-in via App Settings → Display → **Plan Usage Limits** (`showPlanUsageLimits`, default OFF). Commits `c82f6c8` (feature) → `4d9d93d` (end-to-end fixes) → `eae225b` (per-user reconcile) → `95fb5fc` (init-snapshot replay). Full suite green (2869), CI green. No changeset/version bump yet.
|
||||
>
|
||||
> Two surfaces from one `statusLine` callback:
|
||||
> - **Header chip** (top-right) — account-wide **plan limits**: `5h 35% · 7d 38%`, per-window green/yellow/red.
|
||||
> - **In-terminal statusline footer** — the **current session's** status: `Opus 4.8 (1M context) in:562,411 out:1,188 ctx:56%`.
|
||||
>
|
||||
> The `rate_limits` JSON schema below was **empirically confirmed** against Claude Code 2.1.177 on a Claude Max account; see the Verification appendix to reproduce.
|
||||
|
||||
## Problem
|
||||
|
||||
Codeman had no proactive view of how much of the Claude subscription is left. It only learned about limits **reactively**: `usage-limit-patterns.ts` regex-scrapes ANSI-stripped terminal output for footer strings like `5-hour limit reached ∙ resets 8pm`, extracting only the **reset time**, and only *after* Claude has already stalled. There was no "73% of your 5-hour limit used" anywhere.
|
||||
|
||||
We wanted a live, always-visible gauge so the operator can see a wall coming and pace overnight/autonomous runs — without hijacking the in-terminal statusline, which should keep showing the current session's status.
|
||||
|
||||
## Data source: the statusline `rate_limits` JSON
|
||||
|
||||
Claude Code (**v2.1.80+**; prod box runs **2.1.177**) pipes a JSON blob to a configured `statusLine.command` on stdin after each render. On Pro/Max subscriptions that blob includes `rate_limits`. **This is the only channel that exposes plan-limit data** (see rejected alternatives) — so the feature *must* set a statusLine command, which is why the footer is also reconstructed by it (below).
|
||||
|
||||
### Confirmed schema (real captured payload)
|
||||
|
||||
```jsonc
|
||||
"rate_limits": {
|
||||
"five_hour": { "used_percentage": 15, "resets_at": 1781409000 }, // → 2026-06-14T03:50:00Z
|
||||
"seven_day": { "used_percentage": 34, "resets_at": 1781827200 } // → 2026-06-19T00:00:00Z
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Notes |
|
||||
|-------|------|-------|
|
||||
| `rate_limits.five_hour.used_percentage` | `number` 0–100 | Integer-valued in practice; treat as `number`, don't assume decimals. |
|
||||
| `rate_limits.five_hour.resets_at` | `number` | **Epoch SECONDS** (10 digits). `×1000` for a JS `Date`. |
|
||||
| `rate_limits.seven_day.{used_percentage,resets_at}` | same | |
|
||||
|
||||
**Confirmed facts & gotchas:**
|
||||
|
||||
- **Only two windows exist: `five_hour` and `seven_day`.** There is **no separate Opus-weekly field**, even on a Max/Opus account.
|
||||
- `rate_limits` is **absent on the first render**, **present after the first API response**. UI degrades to "no chip yet."
|
||||
- statusLine fires **only in interactive TUI mode**, never `--print`. Fine — Codeman sessions are interactive TUIs (and so are Codeman-spawned ones in tmux).
|
||||
- **Subscriber-gated.** Absent for API-key / non-subscriber auth.
|
||||
|
||||
### Bonus telemetry in the same payload — used for the footer
|
||||
|
||||
The same stdin object also carries `model.display_name`, `context_window.{used_percentage, total_input_tokens, total_output_tokens, …}`, `cost.total_cost_usd`, `effort.level`, etc. The shipped feature uses **model + token totals + context %** to build the in-terminal footer (so the statusline stays useful even though we own it). The endpoint also broadcasts `contextUsedPercentage`/`costUsd`/`modelDisplayName` alongside the limits for future chip tooltips.
|
||||
|
||||
### Alternatives considered & rejected
|
||||
|
||||
| Source | Why not |
|
||||
|--------|---------|
|
||||
| OAuth endpoint `api.anthropic.com/api/oauth/usage` | Undocumented, aggressively rate-limited, needs the **encrypted** OAuth token. Only worth it for *dollar spend*. |
|
||||
| `/usage` slash command | Interactive-only, no programmatic output. |
|
||||
| On-disk `~/.claude/` files | No usage state persisted (only `daemon.status.json` = auto-updater supervisor). |
|
||||
| CLI flag (`claude usage` / `--check-usage`) | Does not exist. |
|
||||
| `StopFailure` hook | Carries only an `error_type` on *failure* — no live percentages. |
|
||||
|
||||
## As-built architecture
|
||||
|
||||
```
|
||||
Claude TUI (any Claude session, incl. linked-case/real-repo sessions)
|
||||
│ renders statusline after each assistant msg (+ /compact, mode change)
|
||||
▼
|
||||
statusLine.command (settings.local.json) ──reads stdin JSON──▶
|
||||
curl -sk POST $CODEMAN_API_URL/api/status-telemetry {sessionId, data}
|
||||
(X-Codeman-Hook-Secret: $(cat $CODEMAN_HOOK_SECRET_FILE))
|
||||
│ ◀── HTTP 200 text/plain = current-SESSION status string ──┘
|
||||
▼
|
||||
printf '%s' "$body" → in-terminal footer: "Opus 4.8 (1M context) in:… out:… ctx:…%"
|
||||
|
||||
server (status-telemetry-routes.ts):
|
||||
parse rate_limits → (if changed) store last-known + broadcast SSE session:statusTelemetry → header chip
|
||||
parse model/tokens/ctx → return the session-status footer string
|
||||
▼
|
||||
app.js: _onSessionStatusTelemetry → chip (per-window colors) + localStorage save
|
||||
handleInit → chip from init-snapshot planUsage (fresh-load replay)
|
||||
```
|
||||
|
||||
### 1. The exporter — `generateStatusLineCommand()` in `hooks-config.ts`
|
||||
|
||||
Mirrors the hook `curlCmd()`. Reads the stdin JSON, POSTs `{sessionId, data}` to a **fixed** loopback path, and prints the response body back to stdout (print-through, so the footer stays useful). The managed-session env carries `$CODEMAN_SESSION_ID` / `$CODEMAN_API_URL` / `$CODEMAN_HOOK_SECRET_FILE` (from `tmux-manager.buildEnvExports()`).
|
||||
|
||||
```bash
|
||||
INPUT=$(cat 2>/dev/null || echo '{}'); \
|
||||
printf '{"sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$INPUT" | \
|
||||
curl -sk -X POST "$CODEMAN_API_URL/api/status-telemetry" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" \
|
||||
--data @- 2>/dev/null || echo codeman
|
||||
```
|
||||
|
||||
⚠️ **`curl -sk`, not `curl -s`.** Prod is loopback **HTTPS with a self-signed cert**; without `-k`, curl returns `000` and the statusline silently shows nothing. `-k` is safe (loopback only). *(The existing hook curls use `-s` without `-k` and have the same latent issue on HTTPS installs — a known, separate follow-up.)*
|
||||
|
||||
### 2. Endpoint — `POST /api/status-telemetry` (`status-telemetry-routes.ts`)
|
||||
|
||||
Fixed path (sessionId in the **body**, not the URL) so the auth exemption is an exact-match like `/api/hook-event` (`middleware/auth.ts`: loopback-only; `X-Codeman-Hook-Secret`-gated while a tunnel runs). Schema `StatusTelemetrySchema` in `schemas.ts` validates the subset; unknown keys are stripped. Pure parsing/formatting in `usage-telemetry.ts`:
|
||||
|
||||
- `parseStatusTelemetry(data)` → `{ fiveHour, sevenDay, … }` or `null`. On change (signature dedup; statusline fires often), store last-known (`plan-usage-latest.ts`) and `broadcast('session:statusTelemetry', { sessionId, …telemetry })`.
|
||||
- `parseSessionStatus(data)` + `formatSessionStatusText()` → the **footer** string `Opus 4.8 (1M context) in:562,411 out:1,188 ctx:56%` (returned as `text/plain`). Available from the first render, even before `rate_limits` appears.
|
||||
|
||||
### 3. SSE + frontend chip
|
||||
|
||||
`session:statusTelemetry` registered in `sse-events.ts` + `constants.js`. `app.js`:
|
||||
- `_onSessionStatusTelemetry` → `updatePlanUsageChip(data)` + save to `localStorage['codeman:planUsage']`.
|
||||
- `updatePlanUsageChip` renders two `5h`/`7d` windows; **per-window color by usage** — green `<60%`, yellow `60–84%`, red `≥85%` (`pu-green/pu-yellow/pu-red`); bold labels/values; reset times in the tooltip. `resets_at*1000 → Date`.
|
||||
- Chip element ships hidden (`header-plan-usage--hidden`); `applyHeaderVisibilitySettings()` reveals it client-side when the setting is on (response-viewer pattern — **no `renderIndexHtml` strip**, which kept the "title-only" render contract intact).
|
||||
|
||||
### 4. Chip data robustness — three layers
|
||||
|
||||
1. **Live:** `session:statusTelemetry` SSE on every distinct render.
|
||||
2. **Fresh load / reconnect:** server stores the latest in `plan-usage-latest.ts`; `getLightState()` includes it as `planUsage`; the per-connection **init snapshot** replays it; `handleInit` paints the chip immediately (authoritative over localStorage). Null until the first telemetry of the process.
|
||||
3. **Offline / cross-restart:** `restorePlanUsageChip()` reads `localStorage` on load (12h freshness guard).
|
||||
|
||||
### 5. Injection lifecycle — works for *any* user, never self-destructs
|
||||
|
||||
The setting `showPlanUsageLimits` is **synced** (in `settings.json`, not a per-device `displayKey`).
|
||||
|
||||
- **On toggle** (`PUT /api/settings`, `system-routes.ts`): reconcile the exporter across **all active Claude sessions' working dirs** — inject on enable, remove on disable. Server-side and authoritative, so existing sessions get the footer + feed the chip *immediately*, no new session needed, no dependency on a client's synced localStorage.
|
||||
- **On session create** (`session-routes.ts`): **ADD-ONLY** — inject when `statusLineTelemetry` is true; **never remove**. Sessions in a repo share one `settings.local.json`, so a single create-with-false (e.g. a client whose synced setting hadn't loaded) must not yank the statusLine out from under other live sessions. Removal happens only via the explicit toggle.
|
||||
- `applyStatusLineConfig()` is **`isOurs`-guarded** (matches `/api/status-telemetry`), so a user's own hand-authored statusLine is never touched, and it **updates an out-of-date ours-command** so fixes (e.g. `-k`) propagate. **No `CASES_DIR` gate** — runs for linked cases / real repos (where sessions actually run), mirroring `updateCaseModel`.
|
||||
|
||||
## Codeman-specific considerations
|
||||
|
||||
1. **Account-global limits.** The 5h/7d pools are shared across all sessions on the account → one shared header chip (freshest sample wins), not a per-tab bar.
|
||||
2. **The footer is owned, by necessity.** A statusLine command always replaces Claude's default footer. Since `rate_limits` *only* arrives via statusLine, we reconstruct a useful **session-status** footer (model · tokens · ctx %) from the same payload rather than showing the limits there.
|
||||
3. **`isOurs`-guarded.** Never removes/overwrites a user's own statusLine on disable; only manages the Codeman exporter.
|
||||
4. **Security envelope unchanged.** The exporter runs arbitrary shell every render — same trust model as the hook curls (localhost + `$CODEMAN_HOOK_SECRET_FILE`); reuses the hook-secret gate.
|
||||
5. **Claude-only.** OpenCode/Codex emit no `rate_limits` JSON; injection is gated to `mode === 'claude'`.
|
||||
6. **Future — auto-resume synergy.** Live percentages would let `SessionAutoOps` pre-arm *before* the wall instead of reacting to the stall footer. Not built.
|
||||
|
||||
## Files shipped
|
||||
|
||||
- `src/usage-telemetry.ts` — pure parse/format (`parseStatusTelemetry`, `parseSessionStatus`, `formatSessionStatusText`, `telemetrySignature`) + `test/usage-telemetry.test.ts`.
|
||||
- `src/hooks-config.ts` — `generateStatusLineCommand()` (`curl -sk`), `applyStatusLineConfig()` (add/update/remove, `isOurs`-guarded).
|
||||
- `src/web/routes/status-telemetry-routes.ts` — `POST /api/status-telemetry`.
|
||||
- `src/web/plan-usage-latest.ts` — process-wide last-known store for init replay.
|
||||
- `src/web/schemas.ts` — `StatusTelemetrySchema` + `showPlanUsageLimits` + create-payload `statusLineTelemetry`.
|
||||
- `src/web/middleware/auth.ts` — exemption extended to `/api/status-telemetry`.
|
||||
- `src/web/routes/session-routes.ts` — add-only create-time injection.
|
||||
- `src/web/routes/system-routes.ts` — settings-toggle reconcile.
|
||||
- `src/web/server.ts` — `getLightState().planUsage` (init snapshot).
|
||||
- `src/web/sse-events.ts` + `constants.js` — `session:statusTelemetry`.
|
||||
- Frontend: `app.js` (`_onSessionStatusTelemetry`, `updatePlanUsageChip`, `restorePlanUsageChip`, `handleInit`), `settings-ui.js` (toggle + `applyHeaderVisibilitySettings`), `index.html` (chip + toggle row), `styles.css` (chip + colors), `session-ui.js` (create payload).
|
||||
|
||||
## Bugs E2E testing caught (that unit tests didn't)
|
||||
|
||||
The first "shipped" build passed every test and was broken in practice. End-to-end testing on the real install (the lesson: drive a REAL session, observe the REAL output) surfaced:
|
||||
|
||||
1. **`CASES_DIR` injection gate** excluded the user's whole workflow — sessions run in linked cases / real repos, not under `~/codeman-cases`. → dropped the gate.
|
||||
2. **`curl -s` → `000`** on the loopback self-signed HTTPS cert; statusline silently empty. → `curl -sk`.
|
||||
3. **Remove-on-create-false + shared `settings.local.json`** let a single stale client yank the statusLine out from under all sessions in a repo. → add-only on create; removal only via the toggle reconcile.
|
||||
4. **Chip blank after reload** (localStorage-only, lost on restart/fresh browser). → server-side last-known in the init snapshot.
|
||||
|
||||
## Open questions / future
|
||||
|
||||
- **Schema stability.** `rate_limits` is officially shipped but undocumented in exact shape; the parser is tolerant (renders whatever windows exist, ignores unknown).
|
||||
- **Hook `curl -s` parity.** Hooks share the no-`-k` issue on HTTPS installs — worth fixing the hook curl too (separate change; covered by `cod54` tests).
|
||||
- **Disable cleanliness.** Disabling removes the statusLine from active sessions; a brand-new session created by a *stale* client could re-add it (chip still hidden, footer benign). Fully server-authoritative create-time injection (read the setting server-side instead of the payload flag) would close this — deferred.
|
||||
|
||||
## Verification appendix — how the schema was captured (reproducible)
|
||||
|
||||
Captured without touching global settings or any real session:
|
||||
|
||||
1. Throwaway dir `/tmp/sl-capture` with an exporter `dump.sh` that appends stdin to `payloads.jsonl` and prints `cap`; a `settings.json` pointing `statusLine.command` at it.
|
||||
2. `--print` mode does **not** render a statusline → no capture (confirms TUI-only). Must use interactive.
|
||||
3. Launch interactive Claude in an **isolated tmux socket** (`tmux -L slcap`, never `-L codeman`) inside the temp dir, `--settings /tmp/sl-capture/settings.json` (no global mutation). Confirm the workspace-trust dialog (appears even with `--dangerously-skip-permissions`), then send a one-line prompt (literal text + Enter separately, Ink-style).
|
||||
4. After the first response, `rate_limits` appears in the **second** captured record (absent in the first). Inspect with `jq '.rate_limits'`.
|
||||
5. Tear down: `tmux -L slcap kill-server` + `rm -rf /tmp/sl-capture`; verify the `codeman` socket is untouched.
|
||||
|
||||
Related: `docs/claude-code-hooks-reference.md` (hook callback pattern), `src/usage-limit-patterns.ts` (reactive fallback), `docs/respawn-state-machine.md` (auto-resume interplay).
|
||||
Generated
+9
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "0.9.9",
|
||||
"version": "1.1.16",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "0.9.9",
|
||||
"version": "1.1.16",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
@@ -20,6 +20,7 @@
|
||||
"@fastify/static": "^9.1.3",
|
||||
"@fastify/websocket": "^11.2.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/addon-unicode11": "^0.9.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
@@ -4525,6 +4526,12 @@
|
||||
"integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@xterm/addon-serialize": {
|
||||
"version": "0.14.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/addon-serialize/-/addon-serialize-0.14.0.tgz",
|
||||
"integrity": "sha512-uteyTU1EkrQa2Ux6P/uFl2fzmXI46jy5uoQMKEOM0fKTyiW7cSn0WrFenHm5vO5uEXX/GpwW/FgILvv3r0WbkA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@xterm/addon-unicode11": {
|
||||
"version": "0.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz",
|
||||
|
||||
+3
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "0.9.9",
|
||||
"description": "The missing control plane for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"version": "1.1.16",
|
||||
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@@ -61,6 +61,7 @@
|
||||
"@fastify/static": "^9.1.3",
|
||||
"@fastify/websocket": "^11.2.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/addon-unicode11": "^0.9.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
|
||||
@@ -17,6 +17,13 @@
|
||||
// • Panel "re-grab" — pinch an existing floating panel and move it anywhere;
|
||||
// release over the tab strip to re-dock it (panel goes away, the tab stays).
|
||||
// This is the capability the old OS-window detach lost.
|
||||
// • Agent-window "grab-to-move" — pinch any floating *subagent* or *ultracode*
|
||||
// run/transcript window (the dashboard's own `.subagent-window` /
|
||||
// `.ultracode-window` floats) and move it anywhere. These windows stay owned
|
||||
// by app.js — we only nudge their `style.left/top` and ask app.js to redraw
|
||||
// the glowing connector line back to their session tab (its redraw reads live
|
||||
// rects, so the line tracks without us touching app.js internals). This is the
|
||||
// multi-monitor verb that lets these windows cross the physical monitor seam.
|
||||
// • Button "tap" — pinch over a toolbar button (Run / Run Shell) and release
|
||||
// in place → fires the button's real click handler. Drift too far first and
|
||||
// it's treated as a stray move, not a tap.
|
||||
@@ -36,12 +43,29 @@ import type { HandState } from '../gesture/types.ts';
|
||||
declare global {
|
||||
interface Window {
|
||||
__codemanGesture?: GestureBridge;
|
||||
/** The Codeman dashboard singleton (app.js, `window.app`). The gesture layer
|
||||
* reaches into it to redraw the floating-window connector lines and bump a
|
||||
* grabbed window's z-order while moving the subagent / ultracode windows.
|
||||
* Loosely typed — only the few members we touch. */
|
||||
app?: {
|
||||
updateConnectionLines?: () => void;
|
||||
saveSubagentWindowStates?: () => void;
|
||||
subagentWindowZIndex?: number;
|
||||
ultracodeWindowZIndex?: number;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const TAB_SELECTOR = '.session-tab';
|
||||
/** An in-page floating session panel this layer spawned — re-grabbable to move. */
|
||||
const PANEL_SELECTOR = '.cg-float';
|
||||
/** The dashboard's own floating agent windows (subagent runs + ultracode run and
|
||||
* transcript windows). All three carry one of these classes, position via
|
||||
* `style.left/top`, and redraw their connector line from
|
||||
* `window.app.updateConnectionLines()` — so the hand can pick one up and move it
|
||||
* without app.js knowing. (`.ultracode-agent-window` also carries
|
||||
* `.ultracode-window`, so this matches it too.) */
|
||||
const WINDOW_SELECTOR = '.subagent-window, .ultracode-window';
|
||||
/** The session-tab strip; dropping a moved panel over it re-docks the session. */
|
||||
const DOCK_SELECTOR = '.session-tabs';
|
||||
/** Toolbar buttons a pinch can "tap": Run (#runBtn → app.run()) and Run Shell
|
||||
@@ -93,6 +117,17 @@ type Grab =
|
||||
dy: number;
|
||||
/** Cursor currently over the tab strip → releasing re-docks. */
|
||||
overDock: boolean;
|
||||
}
|
||||
| {
|
||||
/** A dashboard-owned floating agent window (subagent / ultracode) being
|
||||
* moved. We never remove or re-parent it — just reposition + redraw its
|
||||
* connector. The element ref can go stale mid-grab (SSE reconnect tears
|
||||
* ultracode windows down), so every move guards on `el.isConnected`. */
|
||||
kind: 'window';
|
||||
el: HTMLElement;
|
||||
/** Cursor→window-top-left offset at grab, so it doesn't snap. */
|
||||
dx: number;
|
||||
dy: number;
|
||||
};
|
||||
|
||||
/** Live state for one hand pinching a toolbar button (Run / Run Shell). */
|
||||
@@ -122,6 +157,8 @@ class GestureBridge {
|
||||
private taps = new Map<string, Tap>();
|
||||
/** Live floating panels, keyed by session id (idempotent per id). */
|
||||
private floats = new Map<string, FloatingPanel>();
|
||||
/** rAF coalescing for connector-line redraws while dragging an agent window. */
|
||||
private connectorRedrawScheduled = false;
|
||||
|
||||
constructor() {
|
||||
injectStyles();
|
||||
@@ -187,7 +224,7 @@ class GestureBridge {
|
||||
await this.gc.start();
|
||||
this.running = true;
|
||||
this.button.classList.add('on');
|
||||
this.status.textContent = 'on — pinch a tab or button';
|
||||
this.status.textContent = 'on — pinch a tab, window, or button';
|
||||
} catch (err) {
|
||||
// Surface the *real* cause: MediaPipe/Emscripten can throw a non-Error
|
||||
// (number/string), so `(err as Error).message` was logging "undefined".
|
||||
@@ -242,6 +279,22 @@ class GestureBridge {
|
||||
}
|
||||
}
|
||||
|
||||
// A dashboard-owned floating agent window (subagent / ultracode run or
|
||||
// transcript) → pick it up and move it. Priority below cg-float panels
|
||||
// (which sit far above), above tabs/buttons. We grab anywhere on the window
|
||||
// (not just its titlebar) since the hand is choosing the whole window.
|
||||
const win = this.hitClosest(x, y, WINDOW_SELECTOR);
|
||||
if (win) {
|
||||
const rect = win.getBoundingClientRect();
|
||||
// Match app.js's own drag: drop any bottom-anchor so left/top take effect.
|
||||
win.style.bottom = 'auto';
|
||||
win.classList.add('cg-win-grabbed');
|
||||
this.bringWindowToFront(win);
|
||||
this.grabs.set(hand, { kind: 'window', el: win, dx: x - rect.left, dy: y - rect.top });
|
||||
this.status.textContent = 'moving window';
|
||||
return;
|
||||
}
|
||||
|
||||
// A session tab → grab-and-pull-out into a floating panel (ghost follows).
|
||||
const tab = this.hitClosest(x, y, TAB_SELECTOR);
|
||||
const id = tab?.dataset.id;
|
||||
@@ -292,12 +345,16 @@ class GestureBridge {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (grab?.kind === 'window') {
|
||||
this.moveWindow(grab.el, x - grab.dx, y - grab.dy);
|
||||
return;
|
||||
}
|
||||
// A button pinch that drifts too far is a stray move, not a tap — cancel it.
|
||||
const tap = this.taps.get(hand);
|
||||
if (tap && Math.hypot(x - tap.ox, y - tap.oy) > TAP_CANCEL_PX) {
|
||||
tap.el.classList.remove('cg-tap-armed');
|
||||
this.taps.delete(hand);
|
||||
this.status.textContent = 'on — pinch a tab or button';
|
||||
this.status.textContent = 'on — pinch a tab, window, or button';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,6 +376,23 @@ class GestureBridge {
|
||||
else this.flash('placed');
|
||||
return;
|
||||
}
|
||||
if (grab?.kind === 'window') {
|
||||
this.grabs.delete(hand);
|
||||
grab.el.classList.remove('cg-win-grabbed');
|
||||
// Clear the coalescer so the final placement always redraws, even if a
|
||||
// mid-drag rAF was throttled (tab briefly backgrounded) and left it latched.
|
||||
this.connectorRedrawScheduled = false;
|
||||
this.redrawWindowConnectors();
|
||||
// Persist subagent-window positions like app.js's own drag end does
|
||||
// (a no-op for ultracode windows, which aren't position-persisted).
|
||||
try {
|
||||
window.app?.saveSubagentWindowStates?.();
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
this.flash('placed window');
|
||||
return;
|
||||
}
|
||||
// Release over the same button → fire its real click handler.
|
||||
const tap = this.taps.get(hand);
|
||||
if (tap) {
|
||||
@@ -373,6 +447,59 @@ class GestureBridge {
|
||||
float.el.style.top = `${t}px`;
|
||||
}
|
||||
|
||||
/** Move a dashboard-owned agent window by its top-left, clamped on-screen, then
|
||||
* redraw its connector line. The window self-positions via `style.left/top` and
|
||||
* app.js's connector redraw reads live rects, so this tracks without touching
|
||||
* app.js internals. Guards on `isConnected`: ultracode windows can be torn down
|
||||
* (SSE reconnect / auto-close) while still held. Clamps to `innerWidth/Height`,
|
||||
* which equals the *spanned* viewport in a multi-monitor window — so the window
|
||||
* can still travel across the physical monitor seam, just not off-screen. */
|
||||
private moveWindow(el: HTMLElement, left: number, top: number): void {
|
||||
if (!el.isConnected) return;
|
||||
const w = el.offsetWidth || 380;
|
||||
const h = el.offsetHeight || 320;
|
||||
const l = Math.min(Math.max(4, left), Math.max(4, window.innerWidth - w - 4));
|
||||
const t = Math.min(Math.max(4, top), Math.max(4, window.innerHeight - h - 4));
|
||||
el.style.left = `${l}px`;
|
||||
el.style.top = `${t}px`;
|
||||
this.redrawWindowConnectors();
|
||||
}
|
||||
|
||||
/** Ask app.js to redraw all connector lines (subagent + ultracode), coalesced to
|
||||
* one per frame so per-frame drags don't thrash. `updateConnectionLines()` is
|
||||
* itself debounced in app.js, but we rAF-gate too in case an older dashboard
|
||||
* build isn't, and to no-op cleanly when app.js isn't present (standalone). */
|
||||
private redrawWindowConnectors(): void {
|
||||
if (this.connectorRedrawScheduled) return;
|
||||
this.connectorRedrawScheduled = true;
|
||||
requestAnimationFrame(() => {
|
||||
this.connectorRedrawScheduled = false;
|
||||
try {
|
||||
window.app?.updateConnectionLines?.();
|
||||
} catch {
|
||||
/* app.js may not expose it (standalone playground) */
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Pop a grabbed window above its siblings using app.js's own z-counter, so a
|
||||
* picked-up window comes to the front like a real focus. Cosmetic + best-effort. */
|
||||
private bringWindowToFront(el: HTMLElement): void {
|
||||
const app = window.app;
|
||||
if (!app) return;
|
||||
try {
|
||||
if (el.classList.contains('ultracode-window')) {
|
||||
app.ultracodeWindowZIndex = (app.ultracodeWindowZIndex ?? 1000) + 1;
|
||||
el.style.zIndex = String(app.ultracodeWindowZIndex);
|
||||
} else {
|
||||
app.subagentWindowZIndex = (app.subagentWindowZIndex ?? 1000) + 1;
|
||||
el.style.zIndex = String(app.subagentWindowZIndex);
|
||||
}
|
||||
} catch {
|
||||
/* cosmetic only */
|
||||
}
|
||||
}
|
||||
|
||||
private positionGhost(ghost: HTMLElement, x: number, y: number): void {
|
||||
ghost.style.left = `${x}px`;
|
||||
ghost.style.top = `${y}px`;
|
||||
@@ -385,17 +512,19 @@ class GestureBridge {
|
||||
if (grab.kind === 'tab') {
|
||||
grab.ghost.remove();
|
||||
grab.tab.classList.remove('cg-grabbed');
|
||||
} else {
|
||||
} else if (grab.kind === 'panel') {
|
||||
grab.panel.el.style.pointerEvents = '';
|
||||
grab.panel.el.classList.remove('cg-float-grabbed', 'cg-redock');
|
||||
} else {
|
||||
grab.el.classList.remove('cg-win-grabbed');
|
||||
}
|
||||
}
|
||||
this.grabs.clear();
|
||||
for (const tap of this.taps.values()) tap.el.classList.remove('cg-tap-armed');
|
||||
this.taps.clear();
|
||||
document
|
||||
.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed`)
|
||||
.forEach((t) => t.classList.remove('cg-grabbed', 'cg-tap-armed'));
|
||||
.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed, .cg-win-grabbed`)
|
||||
.forEach((t) => t.classList.remove('cg-grabbed', 'cg-tap-armed', 'cg-win-grabbed'));
|
||||
}
|
||||
|
||||
private onStatus(fps: number, hands: HandState[]): void {
|
||||
@@ -491,6 +620,10 @@ function injectStyles(): void {
|
||||
.cg-status { color: #9aa0a6; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.session-tab.cg-grabbed { opacity: .35; outline: 2px dashed #4ade80; outline-offset: -2px; }
|
||||
.cg-tap-armed { outline: 2px solid #4ade80 !important; outline-offset: 2px; box-shadow: 0 0 0 4px rgba(74,222,128,.25) !important; }
|
||||
.subagent-window.cg-win-grabbed, .ultracode-window.cg-win-grabbed {
|
||||
outline: 2px solid #4ade80 !important; outline-offset: -2px;
|
||||
box-shadow: 0 12px 48px rgba(74,222,128,.5) !important;
|
||||
}
|
||||
.cg-float {
|
||||
position: fixed; left: 0; top: 0; width: ${FLOAT_W}px; height: ${FLOAT_H}px;
|
||||
z-index: ${Z}; display: flex; flex-direction: column; overflow: hidden;
|
||||
|
||||
@@ -39,7 +39,7 @@ Server echoes 'h' ←───────────────────
|
||||
|
||||
## Origin
|
||||
|
||||
This library was extracted from [Codeman](https://github.com/Ark0N/Codeman), the missing control plane for AI coding agents — multi-session management, real-time agent visualization, autonomous respawn loops, and a mobile-first web UI for Claude Code and OpenCode. The local echo system was built to make mobile and remote access feel instant, then battle-tested across thousands of hours of real usage. After 3 deep code audits, it was extracted into this standalone library with 78 tests covering every state transition.
|
||||
This library was extracted from [Codeman](https://github.com/Ark0N/Codeman), mission control for AI coding agents — multi-session management, real-time agent visualization, autonomous respawn loops, and a mobile-first web UI for Claude Code, OpenCode, and Codex. The local echo system was built to make mobile and remote access feel instant, then battle-tested across thousands of hours of real usage. After 3 deep code audits, it was extracted into this standalone library with 78 tests covering every state transition.
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ run('copy template', 'cp src/templates/case-template.md dist/templates/');
|
||||
run('xterm css', 'cp node_modules/@xterm/xterm/css/xterm.css dist/web/public/vendor/');
|
||||
run('xterm js', 'npx esbuild node_modules/@xterm/xterm/lib/xterm.js --minify --outfile=dist/web/public/vendor/xterm.min.js');
|
||||
run('xterm-addon-fit', 'npx esbuild node_modules/@xterm/addon-fit/lib/addon-fit.js --minify --outfile=dist/web/public/vendor/xterm-addon-fit.min.js');
|
||||
run('xterm-addon-serialize', 'npx esbuild node_modules/@xterm/addon-serialize/lib/addon-serialize.js --minify --outfile=dist/web/public/vendor/xterm-addon-serialize.min.js');
|
||||
run('xterm-addon-webgl', 'cp node_modules/@xterm/addon-webgl/lib/addon-webgl.js dist/web/public/vendor/xterm-addon-webgl.min.js');
|
||||
run('xterm-addon-unicode11', 'npx esbuild node_modules/@xterm/addon-unicode11/lib/addon-unicode11.js --minify --outfile=dist/web/public/vendor/xterm-addon-unicode11.min.js');
|
||||
run('xterm-zerolag-input', 'npx esbuild packages/xterm-zerolag-input/src/zerolag-input-addon.ts --bundle --minify --format=iife --global-name=XtermZerolagInput --outfile=dist/web/public/vendor/xterm-zerolag-input.js');
|
||||
@@ -66,6 +67,7 @@ appendFileSync(
|
||||
|
||||
// 4. Minify frontend assets
|
||||
run('minify input-cjk.js', 'npx esbuild dist/web/public/input-cjk.js --minify --outfile=dist/web/public/input-cjk.js --allow-overwrite');
|
||||
run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --minify --outfile=dist/web/public/sanitize-html.js --allow-overwrite');
|
||||
run('minify app.js', 'npx esbuild dist/web/public/app.js --minify --outfile=dist/web/public/app.js --allow-overwrite');
|
||||
run('minify terminal-ui.js', 'npx esbuild dist/web/public/terminal-ui.js --minify --outfile=dist/web/public/terminal-ui.js --allow-overwrite');
|
||||
run('minify respawn-ui.js', 'npx esbuild dist/web/public/respawn-ui.js --minify --outfile=dist/web/public/respawn-ui.js --allow-overwrite');
|
||||
@@ -89,6 +91,7 @@ console.log('\n[build] content-hash cache busting');
|
||||
'notification-manager.js',
|
||||
'keyboard-accessory.js',
|
||||
'input-cjk.js',
|
||||
'sanitize-html.js',
|
||||
'app.js',
|
||||
'terminal-ui.js',
|
||||
'respawn-ui.js',
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* capture-readme-real.mjs
|
||||
*
|
||||
* Captures README desktop scenes (multi-session dashboard, monitor, subagent
|
||||
* windows) from a REAL Codeman instance — intended to run against an ISOLATED
|
||||
* dev/beta instance (CODEMAN_INSTANCE=beta on :5000) seeded from prod's settings,
|
||||
* NOT prod itself (never touch prod's live sessions).
|
||||
*
|
||||
* Reuses the high-quality capture recipe proven in capture-real-overview.mjs:
|
||||
* - DSF=2 + ?nowebgl → crisp retina at the TRUE font size (WebGL doubles
|
||||
* glyphs under DSF=2; the DOM renderer respects devicePixelRatio).
|
||||
* - per-device localStorage seeding so the capture matches a real device.
|
||||
*
|
||||
* SCENE=dashboard|monitor|subagent|all BASE=http://localhost:5000 \
|
||||
* OUT=screenshots-readme-real/desktop node scripts/capture-readme-real.mjs
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { mkdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const BASE = process.env.BASE || 'http://localhost:5000';
|
||||
const OUT = process.env.OUT || 'screenshots-readme-real/desktop';
|
||||
const SKIN = process.env.SKIN || 'daylight-blue';
|
||||
const SCENE = process.env.SCENE || 'all';
|
||||
const FONT = Math.max(10, Math.min(24, Number(process.env.FONT || 13)));
|
||||
const VIEWPORT = { width: Number(process.env.VW || 1280), height: Number(process.env.VH || 720) };
|
||||
const DSF = Number(process.env.DSF || 2);
|
||||
const PLAN_USAGE = process.env.PLAN_USAGE !== '0';
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const url = (extra = '') => {
|
||||
const sep = BASE.includes('?') ? '&' : '?';
|
||||
const params = [];
|
||||
if (DSF > 1) params.push('nowebgl'); // DOM renderer → correct font size at DSF>1
|
||||
if (extra) params.push(extra);
|
||||
return params.length ? `${BASE}${sep}${params.join('&')}` : BASE;
|
||||
};
|
||||
|
||||
async function newCtx(browser) {
|
||||
const context = await browser.newContext({
|
||||
viewport: VIEWPORT,
|
||||
deviceScaleFactor: DSF,
|
||||
ignoreHTTPSErrors: BASE.startsWith('https'),
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
await page.addInitScript(
|
||||
([skin, planUsage, font]) => {
|
||||
try {
|
||||
localStorage.setItem('codeman:skin', skin);
|
||||
localStorage.setItem('codeman-font-size', String(font));
|
||||
const blob = { skin, showFileBrowser: false, showProjectInsights: false };
|
||||
if (planUsage) blob.showPlanUsageLimits = true;
|
||||
localStorage.setItem('codeman-app-settings', JSON.stringify(blob));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
[SKIN, PLAN_USAGE, FONT]
|
||||
);
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
async function bootstrap(page) {
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 20000 });
|
||||
await sleep(1200);
|
||||
}
|
||||
|
||||
async function listSessions(page) {
|
||||
return page.evaluate(() =>
|
||||
Array.from(window.app.sessions.values()).map((s) => ({ id: s.id, name: s.name, mode: s.mode }))
|
||||
);
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const out = join(OUT, name);
|
||||
await page.evaluate((f) => {
|
||||
try {
|
||||
if (window.app.setFontSize) window.app.setFontSize(f);
|
||||
} catch {}
|
||||
try {
|
||||
window.app.fitAddon && window.app.fitAddon.fit();
|
||||
} catch {}
|
||||
try {
|
||||
window.app.applyHeaderVisibilitySettings && window.app.applyHeaderVisibilitySettings();
|
||||
} catch {}
|
||||
}, FONT);
|
||||
await sleep(1500);
|
||||
await page.screenshot({ path: out, fullPage: false });
|
||||
console.log(' Saved: ' + out);
|
||||
}
|
||||
|
||||
async function sceneDashboard(browser) {
|
||||
console.log('Scene: dashboard');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
const sessions = await listSessions(page);
|
||||
// Select a claude session so the active terminal shows rich content; all tabs render.
|
||||
const target = sessions.find((s) => s.mode === 'claude') || sessions[0];
|
||||
if (target) await page.evaluate((id) => window.app.selectSession(id), target.id);
|
||||
await sleep(4000);
|
||||
await shoot(page, 'multi-session-dashboard.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function sceneMonitor(browser) {
|
||||
console.log('Scene: monitor');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
const sessions = await listSessions(page);
|
||||
const target = sessions.find((s) => s.mode === 'claude') || sessions[0];
|
||||
if (target) await page.evaluate((id) => window.app.selectSession(id), target.id);
|
||||
await sleep(2500);
|
||||
// toggleMonitorPanel() opens the panel, clears the hidden state, loads REAL
|
||||
// mux sessions (/api/mux), starts stats, and renders the task panel.
|
||||
await page.evaluate(async () => {
|
||||
try {
|
||||
await window.app.toggleMonitorPanel();
|
||||
} catch {}
|
||||
});
|
||||
await sleep(3000);
|
||||
await shoot(page, 'multi-session-monitor.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function sceneSubagent(browser) {
|
||||
console.log('Scene: subagent');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
// Select the session whose subagents we want (subagentActiveTabOnly means
|
||||
// app.subagents only fills for the active tab). Prefer SUBAGENT_SID env.
|
||||
const sessions = await listSessions(page);
|
||||
const targetId = process.env.SUBAGENT_SID || (sessions.find((s) => s.mode === 'claude') || sessions[0])?.id;
|
||||
if (targetId) await page.evaluate((id) => window.app.selectSession(id), targetId);
|
||||
// Wait (up to ~25s) for live subagents to arrive via SSE into app.subagents.
|
||||
let agents = [];
|
||||
for (let i = 0; i < 25; i++) {
|
||||
agents = await page.evaluate(() =>
|
||||
Array.from(window.app.subagents?.entries?.() || []).map(([id, a]) => ({ id, name: a.name ?? a.agentType ?? '' }))
|
||||
);
|
||||
if (agents.length >= 1) break;
|
||||
await sleep(1000);
|
||||
}
|
||||
console.log(' live in-browser subagents:', JSON.stringify(agents));
|
||||
if (agents.length === 0) {
|
||||
console.log(' NO live subagents — skipping (stage a longer subagent task and run this while it runs).');
|
||||
await context.close();
|
||||
return;
|
||||
}
|
||||
await page.evaluate(
|
||||
(ids) => {
|
||||
ids.slice(0, 2).forEach((id) => {
|
||||
try {
|
||||
window.app.openSubagentWindow(id);
|
||||
} catch {}
|
||||
});
|
||||
},
|
||||
agents.map((a) => a.id)
|
||||
);
|
||||
await sleep(2000);
|
||||
await page.evaluate(() => {
|
||||
const wins = Array.from(window.app.subagentWindows.values());
|
||||
const place = [
|
||||
{ left: 360, top: 60, w: 430, h: 330 },
|
||||
{ left: 810, top: 60, w: 430, h: 330 },
|
||||
];
|
||||
wins.slice(0, 2).forEach((win, i) => {
|
||||
const el = win.element;
|
||||
const p = place[i];
|
||||
el.style.left = p.left + 'px';
|
||||
el.style.top = p.top + 'px';
|
||||
el.style.width = p.w + 'px';
|
||||
el.style.height = p.h + 'px';
|
||||
});
|
||||
});
|
||||
await sleep(1500);
|
||||
await shoot(page, 'subagent-spawn.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function main() {
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
||||
});
|
||||
console.log(`BASE=${BASE} SKIN=${SKIN} DSF=${DSF} VIEWPORT=${VIEWPORT.width}x${VIEWPORT.height} SCENE=${SCENE}`);
|
||||
if (SCENE === 'dashboard' || SCENE === 'all') await sceneDashboard(browser);
|
||||
if (SCENE === 'monitor' || SCENE === 'all') await sceneMonitor(browser);
|
||||
if (SCENE === 'subagent' || SCENE === 'all') await sceneSubagent(browser);
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('FATAL', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* capture-real-overview.mjs
|
||||
*
|
||||
* Captures a REAL claude-overview screenshot from a LIVE Codeman server
|
||||
* (no mock injection). Drive a real session to do real work, then run:
|
||||
*
|
||||
* SID=<sessionId> BASE=http://localhost:5000 OUT=screenshots-real \
|
||||
* node scripts/capture-real-overview.mjs
|
||||
*
|
||||
* Skin defaults to daylight-blue (prod default) via the localStorage pre-paint
|
||||
* contract in index.html. Output: <OUT>/claude-overview.png at 1280x720 (DSF 2).
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { mkdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const SID = process.env.SID;
|
||||
const BASE = process.env.BASE || 'http://localhost:5000';
|
||||
const OUT = process.env.OUT || 'screenshots-real';
|
||||
const SKIN = process.env.SKIN || 'daylight-blue';
|
||||
// Unique filename per run (timestamped) so a viewer holding an old render of a
|
||||
// fixed path can never shadow a fresh capture. Override with NAME=… if needed.
|
||||
const STAMP = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19);
|
||||
const NAME = process.env.NAME || `claude-overview-${STAMP}.png`;
|
||||
const VIEWPORT = { width: Number(process.env.VW || 1512), height: Number(process.env.VH || 812) };
|
||||
// IMPORTANT: default deviceScaleFactor is 1, NOT 2. xterm's WebGL renderer in
|
||||
// headless Chromium draws terminal glyphs at ~2× their nominal size when DSF=2
|
||||
// (while still reporting nominal 8px cell dims internally, so it can't be caught
|
||||
// by measuring terminal.cols/cell — only the pixels reveal it). The HTML chrome
|
||||
// is unaffected, so DSF=2 makes ONLY the console font look comically large. DSF=1
|
||||
// renders the console at its true size, matching a real (non-headless) browser.
|
||||
const DSF = Number(process.env.DSF || 1);
|
||||
|
||||
if (!SID) {
|
||||
console.error('SID env var required (the live session id to screenshot)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const main = async () => {
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
||||
});
|
||||
const context = await browser.newContext({
|
||||
viewport: VIEWPORT,
|
||||
deviceScaleFactor: DSF,
|
||||
ignoreHTTPSErrors: BASE.startsWith('https'),
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
// Force the skin before any page script runs (pre-paint <head> contract), and
|
||||
// seed the PER-DEVICE display blob so the capture reflects what prod actually
|
||||
// shows on the user's real device — notably the plan-usage chip, which is a
|
||||
// per-device setting (default OFF) deleted from the server payload, so a fresh
|
||||
// browser would otherwise hide it. PLAN_USAGE=0 disables.
|
||||
const PLAN_USAGE = process.env.PLAN_USAGE !== '0';
|
||||
// Terminal console font size. App default is 14px; a fresh headless browser has
|
||||
// no saved codeman-font-size, so it renders at 14 — much larger than a real
|
||||
// device where the console has been zoomed down. Seed a smaller value (clamped
|
||||
// to the app's [10,24] range) so the console font looks normal in the capture.
|
||||
const FONT = Math.max(10, Math.min(24, Number(process.env.FONT || 14)));
|
||||
await page.addInitScript(
|
||||
([skin, planUsage, font]) => {
|
||||
try {
|
||||
localStorage.setItem('codeman:skin', skin);
|
||||
localStorage.setItem('codeman-font-size', String(font));
|
||||
// Desktop app-settings blob (settings-ui.js getSettingsStorageKey()).
|
||||
// Present these display keys explicitly so the server merge won't seed
|
||||
// side panels open (display keys only seed from server when absent from
|
||||
// localStorage). Matches the clean full-width-terminal reference look.
|
||||
const blob = {
|
||||
skin,
|
||||
showFileBrowser: false,
|
||||
showMonitor: false,
|
||||
showSubagents: false,
|
||||
showProjectInsights: false,
|
||||
};
|
||||
if (planUsage) blob.showPlanUsageLimits = true;
|
||||
localStorage.setItem('codeman-app-settings', JSON.stringify(blob));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
[SKIN, PLAN_USAGE, FONT]
|
||||
);
|
||||
|
||||
// At DSF>1, xterm's WebGL renderer draws glyphs at ~2x (see DSF comment above).
|
||||
// The app honors a `?nowebgl` URL param that switches to xterm's DOM renderer,
|
||||
// which respects devicePixelRatio correctly — so DSF=2 + nowebgl yields a crisp
|
||||
// 2x (retina) capture at the TRUE font size. Auto-enable it whenever DSF>1.
|
||||
const url = DSF > 1 ? `${BASE}${BASE.includes('?') ? '&' : '?'}nowebgl` : BASE;
|
||||
console.log(`Loading ${url} (DSF=${DSF}) ...`);
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 20000 });
|
||||
await sleep(1500);
|
||||
|
||||
console.log(`Selecting session ${SID} ...`);
|
||||
await page.evaluate((sid) => window.app.selectSession(sid), SID);
|
||||
|
||||
// Let the terminal buffer stream in + xterm render + any Ink redraw settle.
|
||||
await sleep(2000);
|
||||
|
||||
// Force a clean fit (avoids capturing a transient pre-fit frame where the
|
||||
// terminal renders at the wrong column count) and re-apply per-device header
|
||||
// visibility so the seeded plan-usage chip is shown.
|
||||
await page.evaluate((font) => {
|
||||
// Force the console font explicitly (setFontSize also re-fits) in case
|
||||
// loadFontSize didn't pick up the seeded value before the session rendered.
|
||||
try {
|
||||
if (window.app.setFontSize) window.app.setFontSize(font);
|
||||
else window.app.terminal.options.fontSize = font;
|
||||
} catch {}
|
||||
try {
|
||||
window.app.fitAddon && window.app.fitAddon.fit();
|
||||
} catch {}
|
||||
try {
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
} catch {}
|
||||
try {
|
||||
window.app.applyHeaderVisibilitySettings && window.app.applyHeaderVisibilitySettings();
|
||||
} catch {}
|
||||
}, FONT);
|
||||
await sleep(3000);
|
||||
|
||||
// Optionally scroll the terminal up to frame the rich tool-call region
|
||||
// (Read/Write/Bash + green test results) instead of the trailing summary.
|
||||
const SCROLL = Number(process.env.SCROLL || 0);
|
||||
if (SCROLL) {
|
||||
await page.evaluate((n) => {
|
||||
const t = window.app && window.app.terminal;
|
||||
if (t && t.scrollLines) t.scrollLines(-n);
|
||||
}, SCROLL);
|
||||
await sleep(800);
|
||||
}
|
||||
|
||||
const outPath = join(OUT, NAME);
|
||||
await page.screenshot({ path: outPath, fullPage: false });
|
||||
console.log(`Saved: ${outPath}`);
|
||||
|
||||
await context.close();
|
||||
await browser.close();
|
||||
};
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('FATAL', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -252,6 +252,7 @@ if (isGlobalInstall) {
|
||||
const require = createRequire(import.meta.url);
|
||||
const xtermDir = join(require.resolve('@xterm/xterm'), '..', '..');
|
||||
const fitDir = join(require.resolve('@xterm/addon-fit'), '..', '..');
|
||||
const serializeDir = join(require.resolve('@xterm/addon-serialize'), '..', '..');
|
||||
const webglDir = join(require.resolve('@xterm/addon-webgl'), '..', '..');
|
||||
const unicode11Dir = join(require.resolve('@xterm/addon-unicode11'), '..', '..');
|
||||
const vendorDir = join(srcDir, 'web', 'public', 'vendor');
|
||||
@@ -264,12 +265,14 @@ if (isGlobalInstall) {
|
||||
try {
|
||||
execSync(`npx esbuild "${join(xtermDir, 'lib', 'xterm.js')}" --minify --outfile="${join(vendorDir, 'xterm.min.js')}"`, { stdio: 'pipe' });
|
||||
execSync(`npx esbuild "${join(fitDir, 'lib', 'addon-fit.js')}" --minify --outfile="${join(vendorDir, 'xterm-addon-fit.min.js')}"`, { stdio: 'pipe' });
|
||||
execSync(`npx esbuild "${join(serializeDir, 'lib', 'addon-serialize.js')}" --minify --outfile="${join(vendorDir, 'xterm-addon-serialize.min.js')}"`, { stdio: 'pipe' });
|
||||
execSync(`npx esbuild "${join(unicode11Dir, 'lib', 'addon-unicode11.js')}" --minify --outfile="${join(vendorDir, 'xterm-addon-unicode11.min.js')}"`, { stdio: 'pipe' });
|
||||
console.log(colors.green('✓ xterm vendor files copied to src/web/public/vendor/'));
|
||||
} catch {
|
||||
// Fallback: copy unminified
|
||||
copyFileSync(join(xtermDir, 'lib', 'xterm.js'), join(vendorDir, 'xterm.min.js'));
|
||||
copyFileSync(join(fitDir, 'lib', 'addon-fit.js'), join(vendorDir, 'xterm-addon-fit.min.js'));
|
||||
copyFileSync(join(serializeDir, 'lib', 'addon-serialize.js'), join(vendorDir, 'xterm-addon-serialize.min.js'));
|
||||
copyFileSync(join(unicode11Dir, 'lib', 'addon-unicode11.js'), join(vendorDir, 'xterm-addon-unicode11.min.js'));
|
||||
console.log(colors.green('✓ xterm vendor files copied') + colors.dim(' (unminified — esbuild not available)'));
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export PUPPETEER_SKIP_DOWNLOAD="${PUPPETEER_SKIP_DOWNLOAD:-1}"
|
||||
REPO=""
|
||||
TAG=""
|
||||
SUPERVISOR="none"
|
||||
SERVER_PID=""
|
||||
STATUS_FILE=""
|
||||
UPDATE_ID=""
|
||||
FROM_VERSION=""
|
||||
@@ -50,6 +51,7 @@ while [[ $# -gt 0 ]]; do
|
||||
--node) NODE="$2"; shift 2 ;;
|
||||
--log) LOG="$2"; shift 2 ;;
|
||||
--prev-sha) PREV_SHA="$2"; shift 2 ;;
|
||||
--server-pid) SERVER_PID="$2"; shift 2 ;;
|
||||
--stash) DO_STASH=1; shift ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
@@ -198,6 +200,19 @@ case "$SUPERVISOR" in
|
||||
|| fail "Build succeeded but launchd restart failed" "launchctl"
|
||||
}
|
||||
;;
|
||||
launchd-daemon)
|
||||
# System-level KeepAlive LaunchDaemon (headless Mac): kickstarting the system
|
||||
# domain needs root, but we don't need it — kill the server and launchd
|
||||
# respawns it on the new dist/ within ThrottleInterval seconds.
|
||||
if [[ -n "$SERVER_PID" ]] && kill "$SERVER_PID" 2>/dev/null; then
|
||||
: # respawn is launchd's job from here
|
||||
else
|
||||
MANUAL_CMD="sudo launchctl kickstart -k system/com.codeman.web"
|
||||
write_status "completed-needs-manual-restart" "Update staged — restart Codeman to apply v$TO_VERSION."
|
||||
echo "[self-update] launchd-daemon: could not signal server pid '$SERVER_PID' — manual restart required"
|
||||
exit 0
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
MANUAL_CMD="pkill -f 'codeman.*web'; codeman web &"
|
||||
write_status "completed-needs-manual-restart" "Update staged — restart Codeman to apply v$TO_VERSION."
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @fileoverview Parses terminal magic links that request attachment cards.
|
||||
*/
|
||||
|
||||
import { isAbsolute } from 'node:path';
|
||||
import { isSupportedAttachmentExtension } from './attachment-registry.js';
|
||||
|
||||
const MAGIC_LINK_RE = /codeman:\/\/attach\?([^\s<>"']+)/g;
|
||||
|
||||
export function parseAttachmentMagicLinks(data: string): string[] {
|
||||
const results: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const match of data.matchAll(MAGIC_LINK_RE)) {
|
||||
const query = trimTrailingPunctuation(match[1] || '');
|
||||
try {
|
||||
const params = new URLSearchParams(query);
|
||||
const filePath = params.get('path');
|
||||
if (!filePath || !isAbsolute(filePath)) continue;
|
||||
const extension = filePath.split('.').pop()?.toLowerCase() || '';
|
||||
if (!isSupportedAttachmentExtension(extension)) continue;
|
||||
if (seen.has(filePath)) continue;
|
||||
seen.add(filePath);
|
||||
results.push(filePath);
|
||||
} catch {
|
||||
// Ignore malformed terminal text. Magic links are advisory.
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function trimTrailingPunctuation(value: string): string {
|
||||
return value.replace(/[),.;:]+$/g, '');
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* @fileoverview In-memory attachment registry for live external document references.
|
||||
*
|
||||
* Session-local files keep using the existing workspace-scoped file routes. This
|
||||
* registry is only for explicit, live external attachments that need a stable ID
|
||||
* so browser requests never contain arbitrary absolute paths.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { basename, extname, isAbsolute } from 'node:path';
|
||||
import { isBlockedAttachmentPath, loadAttachmentGuardConfig } from './config/attachment-guard.js';
|
||||
import { validateSessionFilePath } from './web/route-helpers.js';
|
||||
import type { AttachmentDetectedEvent, AttachmentDetectedType } from './types.js';
|
||||
|
||||
const SUPPORTED_ATTACHMENT_EXTENSIONS = new Set(['png', 'pdf', 'docx', 'pptx', 'md', 'txt']);
|
||||
|
||||
export type AttachmentSource = 'detected' | 'external';
|
||||
|
||||
export interface AttachmentRecord {
|
||||
attachmentId: string;
|
||||
sessionId: string;
|
||||
filePath: string;
|
||||
fileName: string;
|
||||
extension: string;
|
||||
attachmentType: AttachmentDetectedType;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
timestamp: number;
|
||||
source: AttachmentSource;
|
||||
}
|
||||
|
||||
export interface AttachmentRegistrationResult extends AttachmentDetectedEvent {
|
||||
attachmentId: string;
|
||||
source: AttachmentSource;
|
||||
rawUrl: string;
|
||||
previewUrl: string;
|
||||
thumbnailUrl: string;
|
||||
}
|
||||
|
||||
export class AttachmentRegistrationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly statusCode: number = 400
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Per-session attachment cap. Bounds memory against a client (or a
|
||||
* prompt-injected magic-link flood) registering unbounded distinct paths. */
|
||||
const MAX_ATTACHMENTS_PER_SESSION = 200;
|
||||
|
||||
class AttachmentRegistry {
|
||||
private recordsBySession = new Map<string, Map<string, AttachmentRecord>>();
|
||||
|
||||
register(record: AttachmentRecord): void {
|
||||
let records = this.recordsBySession.get(record.sessionId);
|
||||
if (!records) {
|
||||
records = new Map();
|
||||
this.recordsBySession.set(record.sessionId, records);
|
||||
}
|
||||
records.set(record.attachmentId, record);
|
||||
// Evict oldest (insertion-order) entries beyond the cap.
|
||||
while (records.size > MAX_ATTACHMENTS_PER_SESSION) {
|
||||
const oldest = records.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
records.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
get(sessionId: string, attachmentId: string): AttachmentRecord | undefined {
|
||||
return this.recordsBySession.get(sessionId)?.get(attachmentId);
|
||||
}
|
||||
|
||||
findByFilePath(sessionId: string, filePath: string): AttachmentRecord | undefined {
|
||||
const records = this.recordsBySession.get(sessionId);
|
||||
if (!records) return undefined;
|
||||
for (const record of records.values()) {
|
||||
if (record.filePath === filePath) return record;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
clearSession(sessionId: string): void {
|
||||
this.recordsBySession.delete(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
export const attachmentRegistry = new AttachmentRegistry();
|
||||
|
||||
export function isSupportedAttachmentExtension(extension: string): boolean {
|
||||
return SUPPORTED_ATTACHMENT_EXTENSIONS.has(extension.toLowerCase().replace(/^\./, ''));
|
||||
}
|
||||
|
||||
export function getAttachmentType(extension: string): AttachmentDetectedType {
|
||||
const normalized = extension.toLowerCase().replace(/^\./, '');
|
||||
if (normalized === 'png') return 'image';
|
||||
if (normalized === 'pdf') return 'pdf';
|
||||
if (normalized === 'pptx') return 'presentation';
|
||||
if (normalized === 'md') return 'markdown';
|
||||
if (normalized === 'txt') return 'text';
|
||||
return 'document';
|
||||
}
|
||||
|
||||
export function buildAttachmentRoutes(
|
||||
sessionId: string,
|
||||
attachmentId: string
|
||||
): {
|
||||
rawUrl: string;
|
||||
previewUrl: string;
|
||||
thumbnailUrl: string;
|
||||
} {
|
||||
const encodedId = encodeURIComponent(attachmentId);
|
||||
return {
|
||||
rawUrl: `/api/sessions/${sessionId}/attachments/${encodedId}/raw`,
|
||||
previewUrl: `/api/sessions/${sessionId}/attachments/${encodedId}/preview`,
|
||||
thumbnailUrl: `/api/sessions/${sessionId}/attachments/${encodedId}/thumbnail`,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildFileThumbnailRoute(sessionId: string, relativePath: string): string {
|
||||
return `/api/sessions/${sessionId}/file-thumbnail?path=${encodeURIComponent(relativePath)}`;
|
||||
}
|
||||
|
||||
export function attachmentRecordToEvent(record: AttachmentRecord): AttachmentRegistrationResult {
|
||||
const routes = buildAttachmentRoutes(record.sessionId, record.attachmentId);
|
||||
return {
|
||||
sessionId: record.sessionId,
|
||||
filePath: record.fileName,
|
||||
relativePath: '',
|
||||
fileName: record.fileName,
|
||||
extension: record.extension,
|
||||
attachmentType: record.attachmentType,
|
||||
timestamp: record.timestamp,
|
||||
size: record.size,
|
||||
attachmentId: record.attachmentId,
|
||||
source: record.source,
|
||||
...routes,
|
||||
};
|
||||
}
|
||||
|
||||
/** Options for {@link registerExternalAttachment}. */
|
||||
export interface RegisterExternalAttachmentOptions {
|
||||
/**
|
||||
* The registering session's working directory. Required to enforce workspace
|
||||
* confinement — either when the global mode is enabled
|
||||
* (`attachmentConfineToWorkspace` / `CODEMAN_ATTACHMENT_CONFINE`) or when
|
||||
* {@link forceWorkspaceConfinement} is set for this call.
|
||||
*/
|
||||
sessionWorkingDir?: string;
|
||||
/**
|
||||
* Force workspace confinement for THIS registration regardless of the global
|
||||
* setting. Used by the terminal-output `codeman://attach` magic-link scanner:
|
||||
* terminal output is attacker-influenceable (a prompt-injected session can
|
||||
* print an arbitrary path), so passive magic links may only reference files
|
||||
* inside the session workspace. Deliberate cross-workspace attachment still
|
||||
* works through the explicit, Origin-guarded `POST /attachments` route and the
|
||||
* `codeman attach` CLI (which POSTs directly when a session id is known).
|
||||
*/
|
||||
forceWorkspaceConfinement?: boolean;
|
||||
}
|
||||
|
||||
export async function registerExternalAttachment(
|
||||
sessionId: string,
|
||||
requestedPath: string,
|
||||
options: RegisterExternalAttachmentOptions = {}
|
||||
): Promise<AttachmentRegistrationResult> {
|
||||
if (!requestedPath || !isAbsolute(requestedPath)) {
|
||||
throw new AttachmentRegistrationError('Attachment path must be an absolute local path');
|
||||
}
|
||||
|
||||
let resolvedPath: string;
|
||||
try {
|
||||
resolvedPath = realpathSync(requestedPath);
|
||||
} catch {
|
||||
throw new AttachmentRegistrationError('Attachment file not found', 404);
|
||||
}
|
||||
|
||||
// COD-53: enforce the active attachment-guard policy on the symlink-resolved
|
||||
// path before doing anything else.
|
||||
const guard = await loadAttachmentGuardConfig();
|
||||
|
||||
if (guard.confineToWorkspace || options.forceWorkspaceConfinement) {
|
||||
// Workspace-confined: the file MUST resolve inside the session's workspace.
|
||||
// Applies when the global strict mode is on (opt-in, default OFF) OR when
|
||||
// the caller forces it for this registration (the magic-link scanner — see
|
||||
// forceWorkspaceConfinement). Strictly more restrictive than the blocklist.
|
||||
const workingDir = options.sessionWorkingDir;
|
||||
if (!workingDir || !validateSessionFilePath(workingDir, resolvedPath)) {
|
||||
throw new AttachmentRegistrationError('Access to this file is blocked', 403);
|
||||
}
|
||||
}
|
||||
|
||||
// Blocklist (DEFAULT, also applied alongside confinement as defense in
|
||||
// depth): pre-populated secret locations + the /root and /etc trees + any
|
||||
// operator-configured extra trees. Symlinks are already resolved above.
|
||||
// Cross-workspace attachment of non-blocked files stays allowed, so
|
||||
// codeman-publish and the ~/.codeman review loop keep working.
|
||||
if (isBlockedAttachmentPath(resolvedPath, guard.blockedTrees)) {
|
||||
throw new AttachmentRegistrationError('Access to this file is blocked', 403);
|
||||
}
|
||||
|
||||
const extension = extname(resolvedPath).toLowerCase().replace(/^\./, '');
|
||||
if (!isSupportedAttachmentExtension(extension)) {
|
||||
throw new AttachmentRegistrationError('Unsupported attachment type');
|
||||
}
|
||||
|
||||
const stat = await fs.stat(resolvedPath);
|
||||
if (typeof stat.isFile === 'function' && !stat.isFile()) {
|
||||
throw new AttachmentRegistrationError('Attachment path is not a file');
|
||||
}
|
||||
|
||||
const existing = attachmentRegistry.findByFilePath(sessionId, resolvedPath);
|
||||
if (existing) {
|
||||
existing.size = stat.size;
|
||||
existing.mtimeMs = stat.mtimeMs ?? 0;
|
||||
existing.timestamp = Date.now();
|
||||
return attachmentRecordToEvent(existing);
|
||||
}
|
||||
|
||||
const record: AttachmentRecord = {
|
||||
attachmentId: `att_${randomUUID()}`,
|
||||
sessionId,
|
||||
filePath: resolvedPath,
|
||||
fileName: basename(resolvedPath),
|
||||
extension,
|
||||
attachmentType: getAttachmentType(extension),
|
||||
size: stat.size,
|
||||
mtimeMs: stat.mtimeMs ?? 0,
|
||||
timestamp: Date.now(),
|
||||
source: 'external',
|
||||
};
|
||||
attachmentRegistry.register(record);
|
||||
return attachmentRecordToEvent(record);
|
||||
}
|
||||
+123
@@ -10,11 +10,17 @@
|
||||
import { Command } from 'commander';
|
||||
import chalk from 'chalk';
|
||||
import { createRequire } from 'module';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { isAbsolute } from 'node:path';
|
||||
import { dataPath } from './config/instance.js';
|
||||
import { getSessionManager } from './session-manager.js';
|
||||
import { getTaskQueue } from './task-queue.js';
|
||||
import { getRalphLoop } from './ralph-loop.js';
|
||||
import { getStore } from './state-store.js';
|
||||
import { getErrorMessage } from './types.js';
|
||||
import { isSupportedAttachmentExtension } from './attachment-registry.js';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const pkg = require('../package.json') as { version: string };
|
||||
@@ -23,6 +29,93 @@ const program = new Command();
|
||||
|
||||
program.name('codeman').description('Claude Code session manager with autonomous Ralph Loop').version(pkg.version);
|
||||
|
||||
function makeAttachmentMagicLink(filePath: string): string {
|
||||
return `codeman://attach?path=${encodeURIComponent(filePath)}`;
|
||||
}
|
||||
|
||||
function readCodemanEnv(): Record<string, string> {
|
||||
const envPath = dataPath('.env');
|
||||
try {
|
||||
const text = readFileSync(envPath, 'utf-8');
|
||||
const result: Record<string, string> = {};
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
|
||||
if (!match) continue;
|
||||
let value = match[2].trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
result[match[1]] = value;
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function postAttachment(apiUrl: string, sessionId: string, filePath: string): Promise<boolean> {
|
||||
const envFile = readCodemanEnv();
|
||||
const username = process.env.CODEMAN_USERNAME || envFile.CODEMAN_USERNAME || 'admin';
|
||||
const password = process.env.CODEMAN_PASSWORD || envFile.CODEMAN_PASSWORD;
|
||||
const url = new URL(`/api/sessions/${encodeURIComponent(sessionId)}/attachments`, apiUrl);
|
||||
const body = JSON.stringify({ path: filePath });
|
||||
const transport = url.protocol === 'https:' ? https : http;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const headers: Record<string, string | number> = {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
};
|
||||
if (password) {
|
||||
headers.Authorization = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
const req = transport.request(
|
||||
{
|
||||
protocol: url.protocol,
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
method: 'POST',
|
||||
path: `${url.pathname}${url.search}`,
|
||||
rejectUnauthorized: false,
|
||||
headers,
|
||||
},
|
||||
(res) => {
|
||||
res.resume();
|
||||
res.on('end', () => resolve(Boolean(res.statusCode && res.statusCode >= 200 && res.statusCode < 300)));
|
||||
}
|
||||
);
|
||||
req.on('error', () => resolve(false));
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
program
|
||||
.command('attach <path>')
|
||||
.description('Show an attachment card for a local file')
|
||||
.option('-s, --session <id>', 'Codeman session ID (defaults to CODEMAN_SESSION_ID)')
|
||||
.option('--url <url>', 'Codeman API URL (defaults to CODEMAN_API_URL or https://127.0.0.1:3000)')
|
||||
.action(async (filePath, options) => {
|
||||
const extension = String(filePath).split('.').pop()?.toLowerCase() || '';
|
||||
if (!isAbsolute(filePath) || !isSupportedAttachmentExtension(extension)) {
|
||||
console.error(chalk.red('✗ attach requires an absolute path to a png, pdf, docx, pptx, md, or txt file'));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const sessionId = options.session || process.env.CODEMAN_SESSION_ID;
|
||||
const apiUrl = options.url || process.env.CODEMAN_API_URL || 'https://127.0.0.1:3000';
|
||||
if (sessionId && (await postAttachment(apiUrl, sessionId, filePath))) {
|
||||
console.log(chalk.green('✓ Attachment card requested'));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(makeAttachmentMagicLink(filePath));
|
||||
});
|
||||
|
||||
// ============ Session Commands ============
|
||||
|
||||
const sessionCmd = program.command('session').alias('s').description('Manage Claude sessions');
|
||||
@@ -533,4 +626,34 @@ program
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command('doctor')
|
||||
.alias('check-deps')
|
||||
.description('Check Codeman tool dependencies (Node, Claude CLI, tmux, LibreOffice, MS Office)')
|
||||
.option('--json', 'Output structured JSON instead of a table')
|
||||
.option('--category <name>', 'Only check one category (core|office|other)')
|
||||
.action(async (options) => {
|
||||
const { createRealHost, checkAll } = await import('./utils/dependency-checker.js');
|
||||
const { renderTable, renderJson, computeExitCode } = await import('./utils/dependency-report.js');
|
||||
const { DEPENDENCY_REGISTRY, TOOL_CATEGORIES } = await import('./config/dependency-registry.js');
|
||||
|
||||
if (options.category && !(TOOL_CATEGORIES as readonly string[]).includes(options.category)) {
|
||||
console.error(`Unknown category "${options.category}". Valid categories: ${TOOL_CATEGORIES.join(', ')}`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const host = createRealHost();
|
||||
const registry = options.category
|
||||
? DEPENDENCY_REGISTRY.filter((t) => t.category === options.category)
|
||||
: DEPENDENCY_REGISTRY;
|
||||
const results = checkAll(registry, host);
|
||||
|
||||
if (options.json) {
|
||||
console.log(JSON.stringify(renderJson(results, host.environment), null, 2));
|
||||
} else {
|
||||
console.log(renderTable(results, host.environment));
|
||||
}
|
||||
process.exit(computeExitCode(results));
|
||||
});
|
||||
|
||||
export { program };
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* @fileoverview Attachment path-guard configuration (COD-53).
|
||||
*
|
||||
* Governs which host files may be registered as cross-workspace attachments
|
||||
* and served to the browser. Two operator-facing knobs, both with safe
|
||||
* defaults:
|
||||
*
|
||||
* 1. **Blocked-path blocklist (DEFAULT, configurable).** Pre-populated with the
|
||||
* shared secret-location blocklist (`isSensitivePath`) PLUS the directory
|
||||
* trees `/root` and `/etc` (anything under them is blocked). The operator
|
||||
* EXTENDS — never shrinks — this set with additional absolute directory
|
||||
* trees via the settings key `attachmentBlockedPaths: string[]` and/or the
|
||||
* env var `CODEMAN_ATTACHMENT_BLOCKED_PATHS` (comma-separated).
|
||||
*
|
||||
* 2. **Workspace confinement (OPTIONAL, default OFF).** When enabled, an
|
||||
* attachment must resolve INSIDE the registering session's workingDir
|
||||
* (reusing `validateSessionFilePath` containment semantics). This is
|
||||
* strictly more restrictive than the blocklist and breaks intentional
|
||||
* cross-workspace attachment (codeman-publish, the ~/.codeman review-card
|
||||
* loop), so it is OFF by default. Toggle via settings
|
||||
* `attachmentConfineToWorkspace: boolean` and/or env
|
||||
* `CODEMAN_ATTACHMENT_CONFINE` (`1`/`true`).
|
||||
*
|
||||
* All paths passed to the predicates here MUST be absolute and symlink-resolved
|
||||
* (realpath) by the caller, mirroring `isSensitivePath`'s contract.
|
||||
*
|
||||
* @module config/attachment-guard
|
||||
*/
|
||||
|
||||
import { sep } from 'node:path';
|
||||
import { isSensitivePath } from '../web/sensitive-path.js';
|
||||
import { readJsonConfig, SETTINGS_PATH } from '../web/route-helpers.js';
|
||||
|
||||
/**
|
||||
* Directory trees blocked by default, IN ADDITION to the secret-location
|
||||
* blocklist in `isSensitivePath`. Anything resolving under one of these trees
|
||||
* is rejected. Pre-populated with the root account home and the system config
|
||||
* tree (which already partially overlaps `isSensitivePath`'s `/etc/shadow`
|
||||
* etc., but here we block the WHOLE tree).
|
||||
*/
|
||||
export const DEFAULT_BLOCKED_TREES: readonly string[] = ['/root', '/etc'];
|
||||
|
||||
/** Settings key carrying extra blocked directory trees (extends the defaults). */
|
||||
export const ATTACHMENT_BLOCKED_PATHS_SETTING = 'attachmentBlockedPaths';
|
||||
|
||||
/** Settings key carrying the workspace-confinement toggle. */
|
||||
export const ATTACHMENT_CONFINE_SETTING = 'attachmentConfineToWorkspace';
|
||||
|
||||
/** Resolved attachment-guard configuration. */
|
||||
export interface AttachmentGuardConfig {
|
||||
/** Pre-populated default trees PLUS any operator extras. */
|
||||
blockedTrees: string[];
|
||||
/** Whether attachments must resolve inside the session workspace. */
|
||||
confineToWorkspace: boolean;
|
||||
}
|
||||
|
||||
/** Normalizes a tree prefix: trim, drop trailing separators (but keep root). */
|
||||
function normalizeTree(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return '';
|
||||
// Strip trailing slashes so '/etc/' and '/etc' behave the same; never reduce
|
||||
// a bare separator to empty.
|
||||
const stripped = trimmed.replace(/[/\\]+$/, '');
|
||||
return stripped || trimmed[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if `absPath` (absolute, symlink-resolved) is the tree itself or
|
||||
* lives under it. Uses path-separator-aware matching so `/etc` does NOT block
|
||||
* an unrelated `/etcetera/notes.md`.
|
||||
*/
|
||||
export function isUnderTree(absPath: string, tree: string): boolean {
|
||||
const t = normalizeTree(tree);
|
||||
if (!t) return false;
|
||||
if (absPath === t) return true;
|
||||
return absPath.startsWith(t.endsWith(sep) ? t : t + sep);
|
||||
}
|
||||
|
||||
/** Parses the comma-separated env override into a list of normalized trees. */
|
||||
function parseEnvBlockedTrees(): string[] {
|
||||
const raw = process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS;
|
||||
if (!raw) return [];
|
||||
return raw
|
||||
.split(',')
|
||||
.map(normalizeTree)
|
||||
.filter((t) => t.length > 0);
|
||||
}
|
||||
|
||||
/** Parses the env confinement toggle (`1`/`true`/`yes`/`on`, case-insensitive). */
|
||||
function parseEnvConfine(): boolean | undefined {
|
||||
const raw = process.env.CODEMAN_ATTACHMENT_CONFINE;
|
||||
if (raw === undefined) return undefined;
|
||||
return /^(1|true|yes|on)$/i.test(raw.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the effective attachment-guard config by merging the pre-populated
|
||||
* defaults with settings.json and env overrides. Env wins over settings for the
|
||||
* confinement toggle; blocked-tree extras from BOTH sources are unioned on top
|
||||
* of the defaults (operators can only EXTEND, never shrink, the blocked set).
|
||||
*/
|
||||
export async function loadAttachmentGuardConfig(): Promise<AttachmentGuardConfig> {
|
||||
const settings = await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {});
|
||||
|
||||
const settingsTrees = Array.isArray(settings[ATTACHMENT_BLOCKED_PATHS_SETTING])
|
||||
? (settings[ATTACHMENT_BLOCKED_PATHS_SETTING] as unknown[])
|
||||
.filter((v): v is string => typeof v === 'string')
|
||||
.map(normalizeTree)
|
||||
.filter((t) => t.length > 0)
|
||||
: [];
|
||||
|
||||
const blockedTrees = Array.from(new Set([...DEFAULT_BLOCKED_TREES, ...settingsTrees, ...parseEnvBlockedTrees()]));
|
||||
|
||||
const envConfine = parseEnvConfine();
|
||||
const settingsConfine = settings[ATTACHMENT_CONFINE_SETTING] === true;
|
||||
const confineToWorkspace = envConfine ?? settingsConfine;
|
||||
|
||||
return { blockedTrees, confineToWorkspace };
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachment-specific blocklist check. Builds on the shared `isSensitivePath`
|
||||
* base (secret locations, shared with `/api/download`) and ADDS the configured
|
||||
* directory trees (`/root`, `/etc`, plus operator extras). `absPath` must be
|
||||
* absolute and symlink-resolved.
|
||||
*
|
||||
* NOTE: this is intentionally a SUPERSET of `isSensitivePath` so `/api/download`
|
||||
* behavior is NOT changed — only attachment registration/serving uses this.
|
||||
*/
|
||||
export function isBlockedAttachmentPath(absPath: string, blockedTrees: readonly string[]): boolean {
|
||||
if (isSensitivePath(absPath)) return true;
|
||||
return blockedTrees.some((tree) => isUnderTree(absPath, tree));
|
||||
}
|
||||
@@ -96,3 +96,18 @@ export const TRIM_RESPAWN_BUFFER_TO = 512 * 1024; // 512KB
|
||||
* which is enough to extract metadata from the first few JSONL lines.
|
||||
*/
|
||||
export const FILE_PEEK_BYTES = 8 * 1024 - 1; // 8KB (inclusive end offset)
|
||||
|
||||
// ============================================================================
|
||||
// Paste-Image Upload Limits
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Maximum size (bytes) of a single image uploaded via POST
|
||||
* /api/sessions/:id/paste-image. The mobile picker / drag-drop / paste paths
|
||||
* send one file per request (the client uploads up to MAX_PASTE_IMAGES of them
|
||||
* per batch), so this caps each individual file, not the batch. Generous enough
|
||||
* for full-resolution phone photos and large screenshots; the client downscales
|
||||
* very large images before upload, so legitimate uploads land well under this.
|
||||
* Override: CODEMAN_MAX_PASTE_IMAGE_BYTES (bytes)
|
||||
*/
|
||||
export const MAX_PASTE_IMAGE_BYTES = parseInt(process.env.CODEMAN_MAX_PASTE_IMAGE_BYTES || '') || 50 * 1024 * 1024; // 50MB
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* @fileoverview Static registry of downstream tool dependencies probed by
|
||||
* `codeman doctor`. Each entry declares per-environment resolvers and the
|
||||
* skills that use it. EXTENSION POINT: skill-manifest-driven discovery
|
||||
* (COD follow-up) will merge dynamically-found entries into this list.
|
||||
*
|
||||
* @module config/dependency-registry
|
||||
*/
|
||||
|
||||
export type ProbeEnvironment = 'linux' | 'darwin' | 'win32' | 'wsl';
|
||||
|
||||
/** The valid `--category` filter values; single source of truth for the type, the CLI
|
||||
* help text, and CLI input validation. */
|
||||
export const TOOL_CATEGORIES = ['core', 'office', 'other'] as const;
|
||||
export type ToolCategory = (typeof TOOL_CATEGORIES)[number];
|
||||
|
||||
/** Resolve a binary on the PATH and read its version. */
|
||||
export interface PathResolver {
|
||||
kind: 'path';
|
||||
bins: string[];
|
||||
versionArg?: string; // default '--version'
|
||||
versionRegex?: RegExp; // default matches first \d+.\d+(.\d+)?
|
||||
}
|
||||
|
||||
/** Resolve a Windows-installed app reachable from win32 or WSL. */
|
||||
export interface WindowsSideResolver {
|
||||
kind: 'windows-side';
|
||||
appDirs: string[]; // relative to a Program Files root
|
||||
exes: string[]; // candidate executables; first found wins
|
||||
}
|
||||
|
||||
export interface ResolverSpec {
|
||||
match: ProbeEnvironment[];
|
||||
resolver: PathResolver | WindowsSideResolver;
|
||||
}
|
||||
|
||||
export interface ToolDependency {
|
||||
id: string;
|
||||
label: string;
|
||||
category: ToolCategory;
|
||||
required: boolean;
|
||||
usedBy?: string[];
|
||||
minVersion?: string;
|
||||
resolvers: ResolverSpec[];
|
||||
installHint?: Partial<Record<ProbeEnvironment, string>>;
|
||||
}
|
||||
|
||||
const ALL: ProbeEnvironment[] = ['linux', 'darwin', 'wsl', 'win32'];
|
||||
|
||||
export const DEPENDENCY_REGISTRY: ToolDependency[] = [
|
||||
{
|
||||
id: 'node',
|
||||
label: 'Node.js',
|
||||
category: 'core',
|
||||
required: true,
|
||||
minVersion: '22.0.0',
|
||||
resolvers: [{ match: ALL, resolver: { kind: 'path', bins: ['node'], versionArg: '--version' } }],
|
||||
installHint: { linux: 'https://nodejs.org', darwin: 'brew install node', wsl: 'https://nodejs.org' },
|
||||
},
|
||||
{
|
||||
id: 'claude',
|
||||
label: 'Claude CLI',
|
||||
category: 'core',
|
||||
required: false,
|
||||
usedBy: ['Claude Code sessions (default backend)'],
|
||||
resolvers: [{ match: ALL, resolver: { kind: 'path', bins: ['claude'], versionArg: '--version' } }],
|
||||
installHint: { linux: 'https://docs.claude.com/claude-code', darwin: 'https://docs.claude.com/claude-code' },
|
||||
},
|
||||
{
|
||||
id: 'tmux',
|
||||
label: 'tmux',
|
||||
category: 'core',
|
||||
required: true,
|
||||
resolvers: [{ match: ['linux', 'darwin', 'wsl'], resolver: { kind: 'path', bins: ['tmux'], versionArg: '-V' } }],
|
||||
installHint: { linux: 'sudo apt install tmux', darwin: 'brew install tmux', wsl: 'sudo apt install tmux' },
|
||||
},
|
||||
{
|
||||
id: 'opencode',
|
||||
label: 'OpenCode CLI',
|
||||
category: 'core',
|
||||
required: false,
|
||||
usedBy: ['OpenCode sessions'],
|
||||
resolvers: [{ match: ALL, resolver: { kind: 'path', bins: ['opencode'], versionArg: '--version' } }],
|
||||
},
|
||||
{
|
||||
id: 'codex',
|
||||
label: 'Codex CLI',
|
||||
category: 'core',
|
||||
required: false,
|
||||
usedBy: ['Codex sessions'],
|
||||
resolvers: [{ match: ALL, resolver: { kind: 'path', bins: ['codex'], versionArg: '--version' } }],
|
||||
},
|
||||
{
|
||||
id: 'libreoffice',
|
||||
label: 'LibreOffice',
|
||||
category: 'office',
|
||||
required: false,
|
||||
usedBy: ['document preview', 'thumbnails'],
|
||||
resolvers: [
|
||||
{
|
||||
match: ['linux', 'darwin', 'wsl'],
|
||||
resolver: { kind: 'path', bins: ['libreoffice', 'soffice'], versionArg: '--version' },
|
||||
},
|
||||
],
|
||||
installHint: { linux: 'sudo apt install libreoffice', darwin: 'brew install --cask libreoffice' },
|
||||
},
|
||||
{
|
||||
id: 'pdftoppm',
|
||||
label: 'pdftoppm',
|
||||
category: 'office',
|
||||
required: false,
|
||||
usedBy: ['document preview', 'PDF/Office first-page thumbnails'],
|
||||
// poppler's pdftoppm prints its version to stderr; presence is what matters here.
|
||||
resolvers: [
|
||||
{ match: ['linux', 'darwin', 'wsl'], resolver: { kind: 'path', bins: ['pdftoppm'], versionArg: '-v' } },
|
||||
],
|
||||
installHint: {
|
||||
linux: 'sudo apt install poppler-utils',
|
||||
darwin: 'brew install poppler',
|
||||
wsl: 'sudo apt install poppler-utils',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'msoffice',
|
||||
label: 'MS Office',
|
||||
category: 'office',
|
||||
required: false,
|
||||
usedBy: ['document preview', 'thumbnails'],
|
||||
resolvers: [
|
||||
{
|
||||
match: ['wsl', 'win32'],
|
||||
resolver: {
|
||||
kind: 'windows-side',
|
||||
appDirs: ['Microsoft Office/root/Office16'],
|
||||
exes: ['WINWORD.EXE', 'POWERPNT.EXE', 'EXCEL.EXE'],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* @fileoverview Per-instance shared hook secret (COD-54).
|
||||
*
|
||||
* Claude Code hooks POST to `/api/hook-event` with no Basic-Auth credentials,
|
||||
* relying on a localhost bypass in `web/middleware/auth.ts`. That bypass is safe
|
||||
* for loopback-only deploys, but a `cloudflared --url http://127.0.0.1:port`
|
||||
* tunnel proxies internet traffic INTO the loopback origin, so tunneled requests
|
||||
* arrive with `req.ip === 127.0.0.1` and would otherwise pass the bypass and
|
||||
* drive respawn/Ralph signals unauthenticated.
|
||||
*
|
||||
* To close that hole WITHOUT breaking the loop's own (credential-less) hook
|
||||
* channel, every locally-generated hook command now presents a per-instance
|
||||
* shared secret in the `X-Codeman-Hook-Secret` header. The middleware requires
|
||||
* a matching secret for the bypass WHEN A TUNNEL IS RUNNING. Tunneled internet
|
||||
* traffic can't know the secret; local hooks (which we generate) do.
|
||||
*
|
||||
* Storage mirrors the VAPID-key pattern in `push-store.ts`: a small file under
|
||||
* the instance data dir (`dataPath('hook-secret')`), read-if-present /
|
||||
* generate-if-missing, stable across restarts. 256 bits of hex.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { getDataDir, dataPath } from './instance.js';
|
||||
|
||||
/** HTTP header local hooks use to present the shared secret. */
|
||||
export const HOOK_SECRET_HEADER = 'X-Codeman-Hook-Secret';
|
||||
|
||||
/** Number of random bytes in the secret (256 bits → 64 hex chars). */
|
||||
const SECRET_BYTES = 32;
|
||||
|
||||
let cachedSecret: string | null = null;
|
||||
|
||||
/**
|
||||
* Return this instance's hook secret, generating and persisting it on first use.
|
||||
* Stable across restarts. Cached in-process after the first read.
|
||||
*/
|
||||
export function getHookSecret(): string {
|
||||
if (cachedSecret) return cachedSecret;
|
||||
|
||||
const secretFile = dataPath('hook-secret');
|
||||
|
||||
if (existsSync(secretFile)) {
|
||||
try {
|
||||
const raw = readFileSync(secretFile, 'utf-8').trim();
|
||||
if (raw) {
|
||||
cachedSecret = raw;
|
||||
return cachedSecret;
|
||||
}
|
||||
// Empty/whitespace file — fall through and regenerate.
|
||||
} catch {
|
||||
// Unreadable — fall through and regenerate.
|
||||
}
|
||||
}
|
||||
|
||||
const secret = randomBytes(SECRET_BYTES).toString('hex');
|
||||
try {
|
||||
mkdirSync(getDataDir(), { recursive: true });
|
||||
// Owner-only perms — the secret gates the hook bypass.
|
||||
writeFileSync(secretFile, secret, { mode: 0o600 });
|
||||
} catch {
|
||||
// Best-effort persistence: even if the write fails we still return a usable
|
||||
// secret for this process so hooks/middleware agree within this run.
|
||||
}
|
||||
cachedSecret = secret;
|
||||
return cachedSecret;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* @fileoverview Workflow (ultracode) run-watcher polling and cache configuration.
|
||||
*
|
||||
* Controls how frequently WorkflowRunWatcher polls
|
||||
* ~/.claude/projects/<projHash>/<sessionUuid>/workflows/wf_*.json
|
||||
* and how many runs are cached in memory.
|
||||
*
|
||||
* Distinct from the Agent-Teams config (team-config.ts). The run-state JSON is
|
||||
* rewritten on every agent tick across a whole run (28+ agents), so the watcher
|
||||
* relies on a per-file mtime skip; the poll itself is just N stat() calls.
|
||||
*
|
||||
* @module config/workflow-config
|
||||
*/
|
||||
|
||||
/** Workflow run-state poll interval (ms). Short because a poll is just N mtime stats. */
|
||||
export const WORKFLOW_RUN_POLL_INTERVAL_MS = 10_000;
|
||||
|
||||
/** Max cached workflow runs (LRU eviction). */
|
||||
export const MAX_CACHED_WORKFLOW_RUNS = 100;
|
||||
|
||||
/**
|
||||
* Default recency window (minutes) for getRecentRuns(). Generous enough that a
|
||||
* recently-finished long run still appears in the LEFT-pane list — filtered on
|
||||
* last-activity, not start time, so multi-hour runs don't vanish.
|
||||
*/
|
||||
export const WORKFLOW_RUN_RECENT_WINDOW_MIN = 240;
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* @fileoverview Global concurrency limiter for spawning external document
|
||||
* converters (pdftoppm / LibreOffice `soffice` / Word-COM `powershell.exe`).
|
||||
*
|
||||
* Without a cap, N simultaneous thumbnail/preview requests for *distinct*
|
||||
* documents fork N converter processes at once — each held open for up to the
|
||||
* multi-minute conversion timeout. That is a localhost resource-exhaustion
|
||||
* (fork-bomb-shaped) vector: a handful of large PDFs detected at once can pin
|
||||
* CPU and RAM. This module serializes converter spawns down to a small fixed
|
||||
* pool; excess spawns queue (FIFO) until a slot frees. The in-flight cache in
|
||||
* `document-preview-cache.ts` already de-dups *identical* inputs; this bounds
|
||||
* the *distinct* case the cache can't.
|
||||
*
|
||||
* Permit accounting transfers the slot directly to the next waiter on release
|
||||
* (rather than decrement-then-reacquire) so the active count can never exceed
|
||||
* the cap even under interleaved async resumption.
|
||||
*
|
||||
* NOT re-entrant: never call `runWithConversionLimit` from inside a task that is
|
||||
* already holding a slot — a nested acquire under a full pool would deadlock.
|
||||
* The converter call sites only ever acquire once per request (the office path
|
||||
* acquires for `soffice` and `pdftoppm` sequentially, not nested).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Max converter processes allowed to run concurrently across the whole process.
|
||||
* Override with CODEMAN_MAX_DOCUMENT_CONVERSIONS (clamped to >= 1).
|
||||
*/
|
||||
const MAX_CONCURRENT_DOCUMENT_CONVERSIONS = (() => {
|
||||
const raw = Number(process.env.CODEMAN_MAX_DOCUMENT_CONVERSIONS);
|
||||
return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : 3;
|
||||
})();
|
||||
|
||||
let active = 0;
|
||||
const waiters: Array<() => void> = [];
|
||||
|
||||
/** Test/diagnostic hook: converters currently holding a slot. */
|
||||
export function getActiveConversionCount(): number {
|
||||
return active;
|
||||
}
|
||||
|
||||
function acquire(): Promise<void> {
|
||||
if (active < MAX_CONCURRENT_DOCUMENT_CONVERSIONS) {
|
||||
active++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise<void>((resolve) => waiters.push(resolve));
|
||||
}
|
||||
|
||||
function release(): void {
|
||||
const next = waiters.shift();
|
||||
if (next) {
|
||||
// Hand the slot straight to the next waiter — `active` stays at the cap.
|
||||
next();
|
||||
} else {
|
||||
active--;
|
||||
}
|
||||
}
|
||||
|
||||
/** Run `task` once a converter slot is free, releasing the slot afterward. */
|
||||
export async function runWithConversionLimit<T>(task: () => Promise<T>): Promise<T> {
|
||||
await acquire();
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* @fileoverview Shared disk cache for expensive Office document previews.
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { basename, dirname, extname, join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import { runWithConversionLimit } from './document-conversion-limiter.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const OFFICE_CONVERSION_TIMEOUT_MS = 5 * 60_000;
|
||||
const DOCUMENT_PREVIEW_CACHE_DIR = join(tmpdir(), 'codeman-document-preview-cache');
|
||||
/**
|
||||
* Cap on persistent converted-PDF files kept in DOCUMENT_PREVIEW_CACHE_DIR.
|
||||
* The cache key embeds the source mtime, so every edit to a doc orphans its
|
||||
* prior PDF; without a cap the dir grows unbounded across long-running sessions.
|
||||
* Override with CODEMAN_MAX_PREVIEW_CACHE_FILES (clamped to >= 1).
|
||||
*/
|
||||
const MAX_PREVIEW_CACHE_FILES = (() => {
|
||||
const raw = Number(process.env.CODEMAN_MAX_PREVIEW_CACHE_FILES);
|
||||
return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : 100;
|
||||
})();
|
||||
function buildWordExportPdfScript(sourcePath: string, outputPath: string): string {
|
||||
return `
|
||||
$ErrorActionPreference = "Stop"
|
||||
$source = ${toPowerShellSingleQuotedString(sourcePath)}
|
||||
$output = ${toPowerShellSingleQuotedString(outputPath)}
|
||||
$word = $null
|
||||
$doc = $null
|
||||
try {
|
||||
$word = New-Object -ComObject Word.Application
|
||||
$word.Visible = $false
|
||||
$word.DisplayAlerts = 0
|
||||
$doc = $word.Documents.Open($source)
|
||||
$doc.ExportAsFixedFormat($output, 17)
|
||||
} finally {
|
||||
if ($null -ne $doc) {
|
||||
$doc.Close($false) | Out-Null
|
||||
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($doc) | Out-Null
|
||||
}
|
||||
if ($null -ne $word) {
|
||||
$word.Quit() | Out-Null
|
||||
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($word) | Out-Null
|
||||
}
|
||||
[System.GC]::Collect()
|
||||
[System.GC]::WaitForPendingFinalizers()
|
||||
}
|
||||
`.trim();
|
||||
}
|
||||
|
||||
type OfficePreviewConverter = 'msword' | 'libreoffice';
|
||||
|
||||
const inFlightOfficeConversions = new Map<string, Promise<string | null>>();
|
||||
|
||||
export function clearDocumentPreviewCache(): void {
|
||||
inFlightOfficeConversions.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort LRU-ish eviction for the persistent converted-PDF cache: keeps at
|
||||
* most MAX_PREVIEW_CACHE_FILES `*.pdf` files in `cacheDir`, deleting the oldest
|
||||
* by mtime once over the cap. Never throws — a pruning failure must not fail the
|
||||
* conversion that triggered it. Only `*.pdf` files are considered, so the
|
||||
* transient `work-*` mkdtemp dirs are ignored.
|
||||
*/
|
||||
export async function pruneDocumentPreviewCache(cacheDir: string): Promise<void> {
|
||||
try {
|
||||
const entries = await fs.readdir(cacheDir);
|
||||
const pdfs = entries.filter((name) => name.toLowerCase().endsWith('.pdf'));
|
||||
if (pdfs.length <= MAX_PREVIEW_CACHE_FILES) return;
|
||||
|
||||
const stats = await Promise.all(
|
||||
pdfs.map(async (name) => {
|
||||
const fullPath = join(cacheDir, name);
|
||||
try {
|
||||
const stat = await fs.stat(fullPath);
|
||||
return { fullPath, mtimeMs: stat.mtimeMs ?? 0 };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const sorted = stats.filter((s): s is { fullPath: string; mtimeMs: number } => s !== null);
|
||||
sorted.sort((a, b) => a.mtimeMs - b.mtimeMs); // oldest first
|
||||
const toRemove = sorted.slice(0, Math.max(0, sorted.length - MAX_PREVIEW_CACHE_FILES));
|
||||
await Promise.all(toRemove.map((entry) => fs.rm(entry.fullPath, { force: true }).catch(() => {})));
|
||||
} catch {
|
||||
// Best-effort: pruning must never break a conversion.
|
||||
}
|
||||
}
|
||||
|
||||
export async function getOfficePreviewPdfPath(filePath: string, extension: string): Promise<string | null> {
|
||||
const ext = extension.toLowerCase().replace(/^\./, '');
|
||||
if (ext !== 'docx' && ext !== 'pptx') return null;
|
||||
|
||||
let sourceStat;
|
||||
try {
|
||||
sourceStat = await fs.stat(filePath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const converter of getOfficePreviewConverters(filePath, ext)) {
|
||||
const cacheKey = createDocumentPreviewCacheKey(filePath, ext, sourceStat.size, sourceStat.mtimeMs ?? 0, converter);
|
||||
const cachePath = getOfficePreviewCachePath(filePath, cacheKey, converter);
|
||||
|
||||
if (await fileExists(cachePath)) {
|
||||
return cachePath;
|
||||
}
|
||||
|
||||
const inFlightKey = `${converter}:${cacheKey}`;
|
||||
const inFlight = inFlightOfficeConversions.get(inFlightKey);
|
||||
if (inFlight) {
|
||||
const converted = await inFlight;
|
||||
if (converted) return converted;
|
||||
continue;
|
||||
}
|
||||
|
||||
const conversion =
|
||||
converter === 'msword'
|
||||
? convertWordDocumentToCachedPdf(filePath, cachePath)
|
||||
: convertLibreOfficeDocumentToCachedPdf(filePath, cachePath);
|
||||
inFlightOfficeConversions.set(inFlightKey, conversion);
|
||||
try {
|
||||
const converted = await conversion;
|
||||
if (converted) return converted;
|
||||
} finally {
|
||||
inFlightOfficeConversions.delete(inFlightKey);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getOfficePreviewConverters(filePath: string, extension: string): OfficePreviewConverter[] {
|
||||
if (extension === 'docx' && wslMountPathToWindowsPath(filePath)) {
|
||||
return ['msword', 'libreoffice'];
|
||||
}
|
||||
return ['libreoffice'];
|
||||
}
|
||||
|
||||
function createDocumentPreviewCacheKey(
|
||||
filePath: string,
|
||||
extension: string,
|
||||
size: number,
|
||||
mtimeMs: number,
|
||||
converter: OfficePreviewConverter
|
||||
): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify({ cacheVersion: 2, converter, filePath, extension, size, mtimeMs }))
|
||||
.digest('hex')
|
||||
.slice(0, 32);
|
||||
}
|
||||
|
||||
function getOfficePreviewCachePath(filePath: string, cacheKey: string, converter: OfficePreviewConverter): string {
|
||||
if (converter === 'msword') {
|
||||
const windowsCacheDir = getWindowsUserTempCacheDir(filePath);
|
||||
if (windowsCacheDir) {
|
||||
return join(windowsCacheDir, `${cacheKey}.pdf`);
|
||||
}
|
||||
}
|
||||
|
||||
return join(DOCUMENT_PREVIEW_CACHE_DIR, `${cacheKey}.pdf`);
|
||||
}
|
||||
|
||||
async function fileExists(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await fs.stat(filePath);
|
||||
return typeof stat.isFile !== 'function' || stat.isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function convertWordDocumentToCachedPdf(filePath: string, cachePath: string): Promise<string | null> {
|
||||
const outputPath = wslMountPathToWindowsPath(cachePath);
|
||||
if (!outputPath) return null;
|
||||
|
||||
let sourceCopyPath: string | undefined;
|
||||
|
||||
try {
|
||||
await fs.mkdir(dirname(cachePath), { recursive: true });
|
||||
sourceCopyPath = join(dirname(cachePath), `${basename(cachePath, '.pdf')}.docx`);
|
||||
await fs.copyFile(filePath, sourceCopyPath);
|
||||
|
||||
const sourcePath = wslMountPathToWindowsPath(sourceCopyPath);
|
||||
if (!sourcePath) return null;
|
||||
|
||||
await runWithConversionLimit(() =>
|
||||
execFileAsync(
|
||||
'powershell.exe',
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-ExecutionPolicy',
|
||||
'Bypass',
|
||||
'-EncodedCommand',
|
||||
encodePowerShellCommand(buildWordExportPdfScript(sourcePath, outputPath)),
|
||||
],
|
||||
{
|
||||
timeout: OFFICE_CONVERSION_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
if (await fileExists(cachePath)) {
|
||||
await pruneDocumentPreviewCache(dirname(cachePath));
|
||||
return cachePath;
|
||||
}
|
||||
|
||||
console.warn(`[DocumentPreviewCache] Microsoft Word did not produce PDF output for ${filePath}`);
|
||||
return null;
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[DocumentPreviewCache] Failed to convert DOCX with Microsoft Word (${filePath}):`,
|
||||
getCacheErrorMessage(err)
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
if (sourceCopyPath) {
|
||||
await fs.rm(sourceCopyPath, { force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function convertLibreOfficeDocumentToCachedPdf(filePath: string, cachePath: string): Promise<string | null> {
|
||||
let workDir: string | undefined;
|
||||
try {
|
||||
await fs.mkdir(DOCUMENT_PREVIEW_CACHE_DIR, { recursive: true });
|
||||
const outDir = await fs.mkdtemp(join(DOCUMENT_PREVIEW_CACHE_DIR, 'work-'));
|
||||
workDir = outDir;
|
||||
const profileDir = join(outDir, 'profile');
|
||||
await fs.mkdir(profileDir, { recursive: true });
|
||||
|
||||
await runWithConversionLimit(() =>
|
||||
execFileAsync(
|
||||
'soffice',
|
||||
[
|
||||
'--headless',
|
||||
'--nologo',
|
||||
'--nofirststartwizard',
|
||||
`-env:UserInstallation=${pathToFileURL(profileDir).href}`,
|
||||
'--convert-to',
|
||||
'pdf',
|
||||
'--outdir',
|
||||
outDir,
|
||||
filePath,
|
||||
],
|
||||
{
|
||||
timeout: OFFICE_CONVERSION_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const converted = (await fs.readdir(outDir)).find((name) => name.toLowerCase().endsWith('.pdf'));
|
||||
if (!converted) return null;
|
||||
|
||||
await fs.rename(join(workDir, converted), cachePath);
|
||||
await pruneDocumentPreviewCache(DOCUMENT_PREVIEW_CACHE_DIR);
|
||||
return cachePath;
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[DocumentPreviewCache] Failed to convert Office file to PDF (${filePath}):`,
|
||||
getCacheErrorMessage(err)
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
if (workDir) {
|
||||
await fs.rm(workDir, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function wslMountPathToWindowsPath(filePath: string): string | null {
|
||||
const match = filePath.match(/^\/mnt\/([a-zA-Z])\/(.+)$/);
|
||||
if (!match) return null;
|
||||
return `${match[1].toUpperCase()}:\\${match[2].replace(/\//g, '\\')}`;
|
||||
}
|
||||
|
||||
function getWindowsUserTempCacheDir(filePath: string): string | null {
|
||||
const match = filePath.match(/^\/mnt\/([a-zA-Z])\/Users\/([^/]+)\//);
|
||||
if (!match) return null;
|
||||
return `/mnt/${match[1].toLowerCase()}/Users/${match[2]}/AppData/Local/Temp/codeman-document-preview-cache`;
|
||||
}
|
||||
|
||||
function toPowerShellSingleQuotedString(value: string): string {
|
||||
return `'${value.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
function encodePowerShellCommand(script: string): string {
|
||||
return Buffer.from(script, 'utf16le').toString('base64');
|
||||
}
|
||||
|
||||
export function getPreviewPdfDownloadName(fileName: string, extension: string): string {
|
||||
return `${basename(fileName, extname(fileName) || `.${extension}`)}.pdf`;
|
||||
}
|
||||
|
||||
function getCacheErrorMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* @fileoverview Best-effort first-page thumbnails for attachment cards.
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { basename, extname, join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { getOfficePreviewPdfPath } from './document-preview-cache.js';
|
||||
import { runWithConversionLimit } from './document-conversion-limiter.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const THUMBNAIL_CONVERSION_TIMEOUT_MS = 5 * 60_000;
|
||||
|
||||
export interface ThumbnailResult {
|
||||
content: Buffer;
|
||||
contentType: 'image/png';
|
||||
}
|
||||
|
||||
export async function generateFirstPageThumbnail(filePath: string, extension: string): Promise<ThumbnailResult | null> {
|
||||
const ext = extension.toLowerCase().replace(/^\./, '');
|
||||
|
||||
try {
|
||||
await fs.stat(filePath);
|
||||
|
||||
if (ext === 'png') {
|
||||
return { content: await fs.readFile(filePath), contentType: 'image/png' };
|
||||
}
|
||||
|
||||
if (ext === 'pdf') {
|
||||
return renderPdfFirstPage(filePath);
|
||||
}
|
||||
|
||||
if (ext === 'docx' || ext === 'pptx') {
|
||||
return renderOfficeFirstPage(filePath);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`[Thumbnailer] Failed to generate ${ext} thumbnail for ${filePath}:`, getThumbnailErrorMessage(err));
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function renderOfficeFirstPage(filePath: string): Promise<ThumbnailResult | null> {
|
||||
try {
|
||||
const previewPdfPath = await getOfficePreviewPdfPath(filePath, extname(filePath).toLowerCase().replace(/^\./, ''));
|
||||
if (!previewPdfPath) return null;
|
||||
return await renderPdfFirstPage(previewPdfPath);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[Thumbnailer] Failed to convert Office file to PDF for thumbnail (${filePath}):`,
|
||||
getThumbnailErrorMessage(err)
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function renderPdfFirstPage(filePath: string): Promise<ThumbnailResult | null> {
|
||||
let previewDir: string | undefined;
|
||||
try {
|
||||
previewDir = await fs.mkdtemp(join(tmpdir(), 'codeman-thumb-pdf-'));
|
||||
const prefix = join(previewDir, basename(filePath, extname(filePath)));
|
||||
await runWithConversionLimit(() =>
|
||||
execFileAsync('pdftoppm', ['-png', '-singlefile', '-f', '1', '-l', '1', '-scale-to', '520', filePath, prefix], {
|
||||
timeout: THUMBNAIL_CONVERSION_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
})
|
||||
);
|
||||
const content = await fs.readFile(`${prefix}.png`);
|
||||
return { content, contentType: 'image/png' };
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[Thumbnailer] Failed to render PDF first page for thumbnail (${filePath}):`,
|
||||
getThumbnailErrorMessage(err)
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
if (previewDir) {
|
||||
await fs.rm(previewDir, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getThumbnailErrorMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
+212
-73
@@ -3,8 +3,9 @@
|
||||
*
|
||||
* Generates `.claude/settings.local.json` with hook definitions that POST
|
||||
* to Codeman's `/api/hook-event` endpoint when Claude Code fires hooks.
|
||||
* Uses `$CODEMAN_API_URL` and `$CODEMAN_SESSION_ID` env vars (set on every
|
||||
* managed session) so the config is static per case directory.
|
||||
* Uses `$CODEMAN_API_URL`, `$CODEMAN_SESSION_ID`, and `$CODEMAN_HOOK_SECRET_FILE`
|
||||
* env vars (set on every managed session) so the config is static per case
|
||||
* directory and free of secret values.
|
||||
*
|
||||
* Key exports:
|
||||
* - `generateHooksConfig()` — returns hooks object for settings.local.json
|
||||
@@ -30,6 +31,30 @@ import { join } from 'node:path';
|
||||
import type { HookEventType } from './types.js';
|
||||
import { HOOK_TIMEOUT_MS } from './config/auth-config.js';
|
||||
|
||||
/**
|
||||
* Serializes read-modify-write access to a `settings.local.json` path. Every
|
||||
* writer in this module (hooks, env, model, statusLine) shares this map, so
|
||||
* concurrent updates to the SAME file — e.g. session-create writing hooks/model
|
||||
* while an App-Settings toggle injects the statusLine into the same repo — can't
|
||||
* lose each other's changes through interleaved read-then-write. Per-path chains
|
||||
* are independent; the map self-prunes when a path's chain goes idle.
|
||||
*/
|
||||
const settingsWriteLocks = new Map<string, Promise<unknown>>();
|
||||
function withSettingsLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
||||
const prev = settingsWriteLocks.get(path) ?? Promise.resolve();
|
||||
const run = prev.then(fn, fn); // run after the prior writer, regardless of its outcome
|
||||
// Tail never rejects, so a failed write doesn't poison subsequent writers.
|
||||
const tail = run.then(
|
||||
() => {},
|
||||
() => {}
|
||||
);
|
||||
settingsWriteLocks.set(path, tail);
|
||||
void tail.then(() => {
|
||||
if (settingsWriteLocks.get(path) === tail) settingsWriteLocks.delete(path);
|
||||
});
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the hooks section for .claude/settings.local.json
|
||||
*
|
||||
@@ -41,11 +66,18 @@ import { HOOK_TIMEOUT_MS } from './config/auth-config.js';
|
||||
export function generateHooksConfig(): { hooks: Record<string, unknown[]> } {
|
||||
// Read Claude Code's stdin JSON and forward it as the data field.
|
||||
// Falls back to empty object if stdin is unavailable or malformed.
|
||||
// COD-54: present the per-instance hook secret so the bypass keeps working while
|
||||
// a tunnel is running. The value is read from the secret file AT EXECUTION TIME
|
||||
// (path via $CODEMAN_HOOK_SECRET_FILE, set in every managed session's env), so it
|
||||
// never lands in this config and rotation needs no respawn. If the var/file is
|
||||
// missing the header is empty — the middleware then allows the request only on
|
||||
// the plain loopback bypass (tunnel down), same as pre-secret behavior.
|
||||
const curlCmd = (event: HookEventType) =>
|
||||
`HOOK_DATA=$(cat 2>/dev/null || echo '{}'); ` +
|
||||
`printf '{"event":"${event}","sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$HOOK_DATA" | ` +
|
||||
`curl -s -X POST "$CODEMAN_API_URL/api/hook-event" ` +
|
||||
`-H 'Content-Type: application/json' ` +
|
||||
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
|
||||
`--data @- ` +
|
||||
`2>/dev/null || true`;
|
||||
|
||||
@@ -95,29 +127,31 @@ export async function stripCaseEnvKeys(casePath: string, keysToRemove: readonly
|
||||
if (keysToRemove.length === 0) return;
|
||||
|
||||
const settingsPath = join(casePath, '.claude', 'settings.local.json');
|
||||
if (!existsSync(settingsPath)) return;
|
||||
await withSettingsLock(settingsPath, async () => {
|
||||
if (!existsSync(settingsPath)) return;
|
||||
|
||||
let existing: Record<string, unknown>;
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
return; // Malformed — don't rewrite it
|
||||
}
|
||||
|
||||
const env = existing.env as Record<string, string> | undefined;
|
||||
if (!env) return;
|
||||
|
||||
let changed = false;
|
||||
for (const key of keysToRemove) {
|
||||
if (key in env) {
|
||||
delete env[key];
|
||||
changed = true;
|
||||
let existing: Record<string, unknown>;
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
return; // Malformed — don't rewrite it
|
||||
}
|
||||
}
|
||||
if (!changed) return;
|
||||
|
||||
existing.env = env;
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
const env = existing.env as Record<string, string> | undefined;
|
||||
if (!env) return;
|
||||
|
||||
let changed = false;
|
||||
for (const key of keysToRemove) {
|
||||
if (key in env) {
|
||||
delete env[key];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) return;
|
||||
|
||||
existing.env = env;
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,30 +160,31 @@ export async function stripCaseEnvKeys(casePath: string, keysToRemove: readonly
|
||||
*/
|
||||
export async function updateCaseEnvVars(casePath: string, envVars: Record<string, string>): Promise<void> {
|
||||
const claudeDir = join(casePath, '.claude');
|
||||
if (!existsSync(claudeDir)) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
const settingsPath = join(claudeDir, 'settings.local.json');
|
||||
let existing: Record<string, unknown> = {};
|
||||
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
|
||||
const currentEnv = (existing.env as Record<string, string>) || {};
|
||||
for (const [key, value] of Object.entries(envVars)) {
|
||||
if (value) {
|
||||
currentEnv[key] = value;
|
||||
} else {
|
||||
delete currentEnv[key];
|
||||
await withSettingsLock(settingsPath, async () => {
|
||||
if (!existsSync(claudeDir)) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
}
|
||||
existing.env = currentEnv;
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
let existing: Record<string, unknown> = {};
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
|
||||
const currentEnv = (existing.env as Record<string, string>) || {};
|
||||
for (const [key, value] of Object.entries(envVars)) {
|
||||
if (value) {
|
||||
currentEnv[key] = value;
|
||||
} else {
|
||||
delete currentEnv[key];
|
||||
}
|
||||
}
|
||||
existing.env = currentEnv;
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,26 +193,27 @@ export async function updateCaseEnvVars(casePath: string, envVars: Record<string
|
||||
*/
|
||||
export async function updateCaseModel(casePath: string, model: string | null): Promise<void> {
|
||||
const claudeDir = join(casePath, '.claude');
|
||||
if (!existsSync(claudeDir)) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
const settingsPath = join(claudeDir, 'settings.local.json');
|
||||
let existing: Record<string, unknown> = {};
|
||||
await withSettingsLock(settingsPath, async () => {
|
||||
if (!existsSync(claudeDir)) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
let existing: Record<string, unknown> = {};
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
|
||||
if (model) {
|
||||
existing.model = model;
|
||||
} else {
|
||||
delete existing.model;
|
||||
}
|
||||
if (model) {
|
||||
existing.model = model;
|
||||
} else {
|
||||
delete existing.model;
|
||||
}
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,22 +222,125 @@ export async function updateCaseModel(casePath: string, model: string | null): P
|
||||
*/
|
||||
export async function writeHooksConfig(casePath: string): Promise<void> {
|
||||
const claudeDir = join(casePath, '.claude');
|
||||
if (!existsSync(claudeDir)) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
const settingsPath = join(claudeDir, 'settings.local.json');
|
||||
let existing: Record<string, unknown> = {};
|
||||
await withSettingsLock(settingsPath, async () => {
|
||||
if (!existsSync(claudeDir)) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
// If file is malformed or doesn't exist, start fresh
|
||||
existing = {};
|
||||
}
|
||||
let existing: Record<string, unknown> = {};
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
// If file is malformed or doesn't exist, start fresh
|
||||
existing = {};
|
||||
}
|
||||
|
||||
const hooksConfig = generateHooksConfig();
|
||||
const merged = { ...existing, ...hooksConfig };
|
||||
const hooksConfig = generateHooksConfig();
|
||||
const merged = { ...existing, ...hooksConfig };
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n');
|
||||
await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-heal a case's hooks block so the COD-91 unconditional hook-secret gate keeps
|
||||
* accepting its hook events.
|
||||
*
|
||||
* `writeHooksConfig` only runs when a case is first CREATED. Cases created before the
|
||||
* X-Codeman-Hook-Secret header was added (COD-54, 2026-06-10) keep hook curls in their
|
||||
* settings.local.json that POST to /api/hook-event WITHOUT the secret — which, once the
|
||||
* gate requires it unconditionally (COD-91), silently 401 on a password-protected
|
||||
* install. This refreshes the hooks block so those stale curls regain the header.
|
||||
*
|
||||
* Deliberately surgical: regenerates ONLY when settings.local.json already contains
|
||||
* Codeman's own hook curls (they target `/api/hook-event`) that lack the secret header.
|
||||
* No-op when the file/hooks are absent (we never impose hooks on a user who removed
|
||||
* them), when the hooks aren't ours, or when the secret is already present — so it never
|
||||
* clobbers a user's customizations and is cheap enough to call on every Claude spawn.
|
||||
*/
|
||||
export async function refreshStaleHookSecret(casePath: string): Promise<void> {
|
||||
const settingsPath = join(casePath, '.claude', 'settings.local.json');
|
||||
if (!existsSync(settingsPath)) return;
|
||||
await withSettingsLock(settingsPath, async () => {
|
||||
let existing: Record<string, unknown>;
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
return; // malformed — leave it untouched (case-create owns the happy path)
|
||||
}
|
||||
const hooksJson = JSON.stringify(existing.hooks ?? null);
|
||||
const isOurs = hooksJson.includes('/api/hook-event');
|
||||
// The generated curl carries this header literal (see generateHooksConfig); its
|
||||
// absence on our own hooks means they predate COD-54 and need regenerating.
|
||||
const hasSecret = hooksJson.includes('X-Codeman-Hook-Secret');
|
||||
if (!isOurs || hasSecret) return;
|
||||
const merged = { ...existing, ...generateHooksConfig() };
|
||||
await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/** Unique marker identifying Codeman's own statusLine command (vs a user's). */
|
||||
const STATUSLINE_MARKER = '/api/status-telemetry';
|
||||
|
||||
/**
|
||||
* The plan-usage statusLine exporter command. Mirrors the hook `curlCmd` pattern:
|
||||
* reads Claude Code's statusline stdin JSON, POSTs `{sessionId,data}` to Codeman,
|
||||
* and prints the response body (a compact "⟳ 5h 15% · 7d 34%" footer) back to
|
||||
* stdout so the in-terminal statusline stays useful. Env vars resolve at runtime
|
||||
* (present in every managed session via tmux setenv), so the config is static.
|
||||
*/
|
||||
export function generateStatusLineCommand(): string {
|
||||
// `curl -sk`: CODEMAN_API_URL is loopback HTTPS with a self-signed cert in the
|
||||
// production setup; without -k curl returns 000 and the statusline shows
|
||||
// nothing. -k is safe here (loopback only). Falls back to a brand string so the
|
||||
// footer is never blank if Codeman is unreachable.
|
||||
return (
|
||||
`INPUT=$(cat 2>/dev/null || echo '{}'); ` +
|
||||
`printf '{"sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$INPUT" | ` +
|
||||
`curl -sk -X POST "$CODEMAN_API_URL${STATUSLINE_MARKER}" ` +
|
||||
`-H 'Content-Type: application/json' ` +
|
||||
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
|
||||
`--data @- 2>/dev/null || echo codeman`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add or remove Codeman's plan-usage statusLine exporter in
|
||||
* `.claude/settings.local.json`. Only ever touches a statusLine that is OURS
|
||||
* (command targets `/api/status-telemetry`), so a user's hand-authored
|
||||
* statusLine is never removed OR overwritten — on both the enable and disable
|
||||
* paths we bail out when an existing statusLine isn't ours. Callers gate on
|
||||
* Claude mode. Merges, preserving all other keys (hooks, env, model).
|
||||
*/
|
||||
export async function applyStatusLineConfig(casePath: string, enabled: boolean): Promise<void> {
|
||||
const claudeDir = join(casePath, '.claude');
|
||||
const settingsPath = join(claudeDir, 'settings.local.json');
|
||||
|
||||
await withSettingsLock(settingsPath, async () => {
|
||||
let existing: Record<string, unknown> = {};
|
||||
if (existsSync(settingsPath)) {
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
return; // Malformed — don't rewrite it
|
||||
}
|
||||
}
|
||||
|
||||
const current = existing.statusLine as { command?: unknown } | undefined;
|
||||
const isOurs = !!current && typeof current.command === 'string' && current.command.includes(STATUSLINE_MARKER);
|
||||
|
||||
if (enabled) {
|
||||
const desired = generateStatusLineCommand();
|
||||
if (isOurs && current?.command === desired) return; // already current — skip rewrite
|
||||
if (current && !isOurs) return; // user has their OWN statusLine — never clobber it
|
||||
if (!existsSync(claudeDir)) await mkdir(claudeDir, { recursive: true });
|
||||
existing.statusLine = { type: 'command', command: desired }; // add, or update an out-of-date ours
|
||||
} else {
|
||||
if (!isOurs) return; // nothing of ours to remove (leave a user's own statusLine alone)
|
||||
delete existing.statusLine;
|
||||
}
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
+51
-8
@@ -12,7 +12,7 @@ import { EventEmitter } from 'node:events';
|
||||
import { watch, type FSWatcher } from 'chokidar';
|
||||
import { basename, extname, relative } from 'node:path';
|
||||
import { statSync } from 'node:fs';
|
||||
import type { ImageDetectedEvent } from './types.js';
|
||||
import type { AttachmentDetectedEvent, AttachmentDetectedType, ImageDetectedEvent } from './types.js';
|
||||
import { KeyedDebouncer } from './utils/index.js';
|
||||
|
||||
// ========== Types ==========
|
||||
@@ -20,7 +20,9 @@ import { KeyedDebouncer } from './utils/index.js';
|
||||
// ========== Constants ==========
|
||||
|
||||
/** Supported image file extensions (lowercase) */
|
||||
const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg']);
|
||||
const IMAGE_POPUP_EXTENSIONS = new Set(['.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg']);
|
||||
const ATTACHMENT_EXTENSIONS = new Set(['.png', '.pdf', '.docx', '.pptx']);
|
||||
const DETECTED_FILE_EXTENSIONS = new Set([...IMAGE_POPUP_EXTENSIONS, ...ATTACHMENT_EXTENSIONS]);
|
||||
|
||||
/** Time to wait for file writes to stabilize (ms) */
|
||||
const STABILITY_THRESHOLD_MS = 500;
|
||||
@@ -166,8 +168,8 @@ export class ImageWatcher extends EventEmitter {
|
||||
}
|
||||
const ext = extname(path).toLowerCase();
|
||||
// Don't ignore directories (needed for watching to work)
|
||||
// Ignore files that aren't images
|
||||
return ext !== '' && !IMAGE_EXTENSIONS.has(ext);
|
||||
// Ignore files that aren't previewable images/documents
|
||||
return ext !== '' && !DETECTED_FILE_EXTENSIONS.has(ext);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -229,15 +231,16 @@ export class ImageWatcher extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Handle a new file being detected.
|
||||
* Verifies it's an image and emits the detection event.
|
||||
* Verifies it's a previewable image/document and emits the detection event.
|
||||
*/
|
||||
private handleNewFile(sessionId: string, filePath: string): void {
|
||||
const ext = extname(filePath).toLowerCase();
|
||||
|
||||
// Double-check it's an image extension
|
||||
if (!IMAGE_EXTENSIONS.has(ext)) {
|
||||
// Double-check it's a supported extension
|
||||
if (!DETECTED_FILE_EXTENSIONS.has(ext)) {
|
||||
return;
|
||||
}
|
||||
const isAttachment = ATTACHMENT_EXTENSIONS.has(ext);
|
||||
|
||||
// Burst limit: skip if too many images detected for this session in a short window
|
||||
const now = Date.now();
|
||||
@@ -259,7 +262,11 @@ export class ImageWatcher extends EventEmitter {
|
||||
// Debounce rapid file creation (e.g., multiple screenshots quickly)
|
||||
this.fileDeb.schedule(filePath, () => {
|
||||
this.fileToSession.delete(filePath);
|
||||
this.emitImageDetected(sessionId, filePath);
|
||||
if (isAttachment) {
|
||||
this.emitAttachmentDetected(sessionId, filePath);
|
||||
} else {
|
||||
this.emitImageDetected(sessionId, filePath);
|
||||
}
|
||||
// Increment burst count on actual emission (not on detection)
|
||||
const b = this.burstTrackers.get(sessionId);
|
||||
if (b) b.count++;
|
||||
@@ -294,6 +301,42 @@ export class ImageWatcher extends EventEmitter {
|
||||
this.emit('image:error', error instanceof Error ? error : new Error(String(error)), sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit the attachment:detected event with file metadata.
|
||||
*/
|
||||
private emitAttachmentDetected(sessionId: string, filePath: string): void {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
const fileName = basename(filePath);
|
||||
const workingDir = this.sessionDirs.get(sessionId);
|
||||
const relativePath = workingDir ? relative(workingDir, filePath) : fileName;
|
||||
const extension = extname(fileName).toLowerCase().replace(/^\./, '');
|
||||
|
||||
const event: AttachmentDetectedEvent = {
|
||||
sessionId,
|
||||
filePath,
|
||||
relativePath,
|
||||
fileName,
|
||||
extension,
|
||||
attachmentType: this.getAttachmentType(extension),
|
||||
timestamp: Date.now(),
|
||||
size: stat.size,
|
||||
};
|
||||
|
||||
this.emit('attachment:detected', event);
|
||||
} catch (error) {
|
||||
this.emit('image:error', error instanceof Error ? error : new Error(String(error)), sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
private getAttachmentType(extension: string): AttachmentDetectedType {
|
||||
if (extension === 'png') return 'image';
|
||||
if (extension === 'pdf') return 'pdf';
|
||||
if (extension === 'docx') return 'document';
|
||||
if (extension === 'pptx') return 'presentation';
|
||||
return 'document';
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance for convenience
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
export { RESEARCH_AGENT_PROMPT } from './research-agent.js';
|
||||
export { PLANNER_PROMPT } from './planner.js';
|
||||
export { PHASE_EXECUTION_PROMPT, TEAM_LEAD_PROMPT, REPLAN_PROMPT, SINGLE_TASK_PROMPT } from './orchestrator.js';
|
||||
export { RALPH_STATUS_CONTRACT, buildRalphLoopPrompt, type RalphLoopPromptOptions } from './ralph.js';
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @fileoverview Ralph Loop prompt construction
|
||||
*
|
||||
* Builds the full `@ralph_prompt.md` content written for a new Ralph loop
|
||||
* session, including the RALPH_STATUS block contract. The contract travels
|
||||
* with the loop prompt (not the generated CLAUDE.md) so every Ralph session
|
||||
* emits parseable status blocks regardless of the project's CLAUDE.md.
|
||||
*
|
||||
* @module prompts/ralph
|
||||
*/
|
||||
|
||||
/**
|
||||
* Structured status-reporting contract appended to every Ralph loop prompt.
|
||||
*
|
||||
* `RalphStatusParser` (src/ralph-status-parser.ts) parses this block from
|
||||
* session output — keep the field names and enum values in sync with its
|
||||
* patterns.
|
||||
*/
|
||||
export const RALPH_STATUS_CONTRACT = `## Status Reporting
|
||||
|
||||
End EVERY response with exactly this block — Codeman parses it to track the loop:
|
||||
|
||||
\`\`\`
|
||||
---RALPH_STATUS---
|
||||
STATUS: IN_PROGRESS | COMPLETE | BLOCKED
|
||||
TASKS_COMPLETED_THIS_LOOP: <number>
|
||||
FILES_MODIFIED: <number>
|
||||
TESTS_STATUS: PASSING | FAILING | NOT_RUN
|
||||
WORK_TYPE: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING
|
||||
EXIT_SIGNAL: false | true
|
||||
RECOMMENDATION: <one line: what to do next>
|
||||
---END_RALPH_STATUS---
|
||||
\`\`\`
|
||||
|
||||
Rules:
|
||||
- \`EXIT_SIGNAL: true\` only when ALL tasks are verifiably done — then also output the completion phrase
|
||||
- \`STATUS: BLOCKED\` when you need human input; describe the blocker in RECOMMENDATION
|
||||
- Never set \`EXIT_SIGNAL: true\` while tests are failing
|
||||
`;
|
||||
|
||||
export interface RalphLoopPromptOptions {
|
||||
/** The user's task description (becomes the prompt header) */
|
||||
taskDescription: string;
|
||||
/** Completion phrase the session must emit inside <promise></promise> */
|
||||
completionPhrase: string;
|
||||
/** Whether a @fix_plan.md task plan was generated for this loop */
|
||||
hasPlan: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the full Ralph loop prompt written to `@ralph_prompt.md`.
|
||||
*/
|
||||
export function buildRalphLoopPrompt({ taskDescription, completionPhrase, hasPlan }: RalphLoopPromptOptions): string {
|
||||
let fullPrompt = taskDescription + '\n\n---\n\n';
|
||||
if (hasPlan) {
|
||||
fullPrompt += '## Task Plan\n\n';
|
||||
fullPrompt += 'A task plan has been written to `@fix_plan.md`. Use this to track progress:\n';
|
||||
fullPrompt += '- Reference the plan at the start of each iteration\n';
|
||||
fullPrompt += '- Update task checkboxes as you complete items\n';
|
||||
fullPrompt += '- Work through items in priority order (P0 > P1 > P2)\n\n';
|
||||
}
|
||||
fullPrompt += '## Iteration Protocol\n\n';
|
||||
fullPrompt += 'This is an autonomous loop. Files from previous iterations persist. On each iteration:\n';
|
||||
fullPrompt += '1. Check what work has already been done\n';
|
||||
fullPrompt += '2. Make incremental progress toward completion\n';
|
||||
fullPrompt += '3. Commit meaningful changes with descriptive messages\n\n';
|
||||
fullPrompt += '## Verification\n\n';
|
||||
fullPrompt += 'After each significant change:\n';
|
||||
fullPrompt += '- Run tests to verify (npm test, pytest, etc.)\n';
|
||||
fullPrompt += '- Check for type/lint errors if applicable\n';
|
||||
fullPrompt += '- If tests fail, read the error, fix it, and retry\n\n';
|
||||
fullPrompt += '## Completion Criteria\n\n';
|
||||
fullPrompt += `Output \`<promise>${completionPhrase}</promise>\` when ALL of the following are true:\n`;
|
||||
fullPrompt += '- All requirements from the task description are implemented\n';
|
||||
fullPrompt += '- All tests pass\n';
|
||||
fullPrompt += '- Changes are committed\n\n';
|
||||
fullPrompt += '## If Stuck\n\n';
|
||||
fullPrompt += 'If you encounter the same error for 3+ iterations:\n';
|
||||
fullPrompt += "1. Document what you've tried\n";
|
||||
fullPrompt += '2. Identify the specific blocker\n';
|
||||
fullPrompt += '3. Try an alternative approach\n';
|
||||
fullPrompt += '4. If truly blocked, output `<promise>BLOCKED</promise>` with an explanation\n\n';
|
||||
fullPrompt += RALPH_STATUS_CONTRACT;
|
||||
return fullPrompt;
|
||||
}
|
||||
@@ -2779,6 +2779,19 @@ export class RespawnController extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Usage-limit pause: Claude can't work and the cycle's /clear would wipe
|
||||
// the paused conversation — the auto-resume scheduler owns recovery here.
|
||||
if (this.session.isLimitPaused) {
|
||||
this.log('Skipping respawn cycle - usage-limit pause active (auto-resume armed)');
|
||||
this.logAction('health', 'Respawn skipped: usage-limit pause (auto-resume armed)');
|
||||
this.emit('respawnBlocked', {
|
||||
reason: 'usage_limit',
|
||||
details: 'Usage limit reached — waiting for scheduled auto-resume',
|
||||
});
|
||||
this.setState('watching');
|
||||
return;
|
||||
}
|
||||
|
||||
// Start the respawn cycle
|
||||
this.cycleCount++;
|
||||
this.log(`Starting respawn cycle #${this.cycleCount}`);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { basename, extname } from 'node:path';
|
||||
import type { SessionAttachmentHistoryItem } from './types/session.js';
|
||||
import type { AttachmentDetectedEvent } from './types/tools.js';
|
||||
import { getAttachmentType } from './attachment-registry.js';
|
||||
|
||||
export const ATTACHMENT_HISTORY_LIMIT = 100;
|
||||
|
||||
export interface ExternalAttachmentHistoryInput {
|
||||
sessionId: string;
|
||||
externalPath: string;
|
||||
fileName?: string;
|
||||
extension?: string;
|
||||
size: number;
|
||||
mtimeMs?: number;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export function normalizeAttachmentExtension(extensionOrPath: string): string {
|
||||
const value = extensionOrPath.startsWith('.') ? extensionOrPath : extname(extensionOrPath) || extensionOrPath;
|
||||
return value.toLowerCase().replace(/^\./, '');
|
||||
}
|
||||
|
||||
function historyKey(item: SessionAttachmentHistoryItem): string {
|
||||
if (item.source === 'external' && item.externalPath) {
|
||||
return `external:${item.externalPath}`;
|
||||
}
|
||||
return `detected:${item.relativePath || item.fileName}`;
|
||||
}
|
||||
|
||||
function safeExternalHistoryId(item: SessionAttachmentHistoryItem): string {
|
||||
const source = item.externalPath || item.id || item.fileName;
|
||||
const digest = createHash('sha256').update(source).digest('hex').slice(0, 16);
|
||||
return `external:${digest}:${item.fileName}`;
|
||||
}
|
||||
|
||||
export function sanitizeAttachmentHistoryItem(item: SessionAttachmentHistoryItem): SessionAttachmentHistoryItem {
|
||||
const { externalPath: _externalPath, ...safe } = item;
|
||||
return {
|
||||
...safe,
|
||||
id: item.source === 'external' ? safeExternalHistoryId(item) : item.id,
|
||||
};
|
||||
}
|
||||
|
||||
export function sanitizeAttachmentHistory(
|
||||
history: readonly SessionAttachmentHistoryItem[]
|
||||
): SessionAttachmentHistoryItem[] {
|
||||
return history.map(sanitizeAttachmentHistoryItem);
|
||||
}
|
||||
|
||||
export function upsertAttachmentHistory(
|
||||
history: readonly SessionAttachmentHistoryItem[],
|
||||
item: SessionAttachmentHistoryItem
|
||||
): SessionAttachmentHistoryItem[] {
|
||||
const nextKey = historyKey(item);
|
||||
return [item, ...history.filter((existing) => historyKey(existing) !== nextKey)].slice(0, ATTACHMENT_HISTORY_LIMIT);
|
||||
}
|
||||
|
||||
export function buildDetectedAttachmentHistoryItem(event: AttachmentDetectedEvent): SessionAttachmentHistoryItem {
|
||||
return {
|
||||
id: `detected:${event.relativePath || event.fileName}`,
|
||||
sessionId: event.sessionId,
|
||||
fileName: event.fileName,
|
||||
extension: normalizeAttachmentExtension(event.extension),
|
||||
attachmentType: event.attachmentType,
|
||||
size: event.size,
|
||||
mtimeMs: 0,
|
||||
timestamp: event.timestamp,
|
||||
source: 'detected',
|
||||
relativePath: event.relativePath,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildExternalAttachmentHistoryItem(
|
||||
input: ExternalAttachmentHistoryInput
|
||||
): SessionAttachmentHistoryItem {
|
||||
const extension = normalizeAttachmentExtension(input.extension || input.fileName || input.externalPath);
|
||||
return {
|
||||
id: `external:${createHash('sha256').update(input.externalPath).digest('hex').slice(0, 16)}:${
|
||||
input.fileName || basename(input.externalPath)
|
||||
}`,
|
||||
sessionId: input.sessionId,
|
||||
fileName: input.fileName || basename(input.externalPath),
|
||||
extension,
|
||||
attachmentType: getAttachmentType(extension),
|
||||
size: input.size,
|
||||
mtimeMs: input.mtimeMs ?? 0,
|
||||
timestamp: input.timestamp ?? Date.now(),
|
||||
source: 'external',
|
||||
externalPath: input.externalPath,
|
||||
};
|
||||
}
|
||||
+184
-1
@@ -1,15 +1,25 @@
|
||||
/**
|
||||
* @fileoverview Auto-compact and auto-clear automation for Session.
|
||||
* @fileoverview Auto-compact, auto-clear, and auto-resume automation for Session.
|
||||
*
|
||||
* Monitors token counts and triggers /compact or /clear commands when
|
||||
* configurable thresholds are reached. Waits for Claude to be idle
|
||||
* before sending commands, with retry logic and mutual exclusion
|
||||
* (compact and clear never run simultaneously).
|
||||
*
|
||||
* Also implements auto-resume on usage limit ("token pause" control):
|
||||
* when enabled and Claude stops on a usage-limit message ("5-hour limit
|
||||
* reached ∙ resets 8pm" and friends — see usage-limit-patterns.ts), a timer
|
||||
* is armed for the parsed reset time plus a safety buffer, then Escape
|
||||
* (dismisses the rate-limit options dialog if open) and a "continue" prompt
|
||||
* are sent so work resumes automatically. If the session is still limited,
|
||||
* the fresh limit message re-arms the scheduler — that retry loop is the
|
||||
* safety net for clock skew and parse imprecision.
|
||||
*
|
||||
* @module session-auto-ops
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { detectUsageLimitPause } from './usage-limit-patterns.js';
|
||||
|
||||
// ============================================================================
|
||||
// Timing Constants
|
||||
@@ -78,6 +88,28 @@ async function executeWhenIdle(
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auto-resume (usage-limit pause) constants
|
||||
// ============================================================================
|
||||
|
||||
/** Safety buffer after the stated reset time before resuming (2 minutes) */
|
||||
const RESUME_BUFFER_MS = 2 * 60_000;
|
||||
|
||||
/** Minimum delay before an overdue resume fires (lets output settle) */
|
||||
const RESUME_MIN_DELAY_MS = 5_000;
|
||||
|
||||
/** Retry interval when the reset time is stale/past (5 minutes) */
|
||||
const RESUME_RETRY_MS = 5 * 60_000;
|
||||
|
||||
/** Re-detections scheduling within this window of the current schedule are ignored */
|
||||
const RESUME_DEDUP_TOLERANCE_MS = 90_000;
|
||||
|
||||
/** Delay between Escape (dialog dismiss) and the resume prompt */
|
||||
const RESUME_ESC_DELAY_MS = 600;
|
||||
|
||||
/** Prompt sent to resume work after the limit resets */
|
||||
const RESUME_PROMPT = 'continue';
|
||||
|
||||
/** Minimum valid threshold for auto-clear/compact (1000 tokens) */
|
||||
const MIN_AUTO_THRESHOLD = 1000;
|
||||
|
||||
@@ -131,6 +163,16 @@ export class SessionAutoOps extends EventEmitter {
|
||||
private _isClearing: boolean = false;
|
||||
private _autoClearTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
// Auto-resume (usage-limit pause) state
|
||||
private _autoResumeEnabled: boolean = false;
|
||||
private _autoResumeTimer: NodeJS.Timeout | null = null;
|
||||
/** Esc→continue gap timer; detections must NOT cancel a resume in flight */
|
||||
private _resumeFollowupTimer: NodeJS.Timeout | null = null;
|
||||
/** When the scheduled resume fires (epoch ms), null when not armed */
|
||||
private _autoResumeAt: number | null = null;
|
||||
private _limitPaused: boolean = false;
|
||||
private _resumeAttempts: number = 0;
|
||||
|
||||
private readonly callbacks: AutoOpsCallbacks;
|
||||
|
||||
constructor(callbacks: AutoOpsCallbacks, config?: { compactThreshold?: number; clearThreshold?: number }) {
|
||||
@@ -207,6 +249,145 @@ export class SessionAutoOps extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auto-resume (usage-limit pause) — getters/setters
|
||||
// ============================================================================
|
||||
|
||||
get autoResumeEnabled(): boolean {
|
||||
return this._autoResumeEnabled;
|
||||
}
|
||||
|
||||
/** When the scheduled resume fires (epoch ms), or null when not armed. */
|
||||
get autoResumeAt(): number | null {
|
||||
return this._autoResumeAt;
|
||||
}
|
||||
|
||||
/** True while the session is believed to be paused on a usage limit. */
|
||||
get isLimitPaused(): boolean {
|
||||
return this._limitPaused;
|
||||
}
|
||||
|
||||
setAutoResume(enabled: boolean): void {
|
||||
this._autoResumeEnabled = enabled;
|
||||
if (!enabled) {
|
||||
this._cancelAutoResume('disabled');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore auto-resume state after a Codeman restart. A persisted pending
|
||||
* schedule is re-armed; an overdue one fires shortly after boot (the limit
|
||||
* footer won't reprint on its own, so without this the pause would stall).
|
||||
*/
|
||||
restoreAutoResume(enabled: boolean, resumeAt?: number): void {
|
||||
this._autoResumeEnabled = enabled;
|
||||
if (!enabled || !resumeAt) return;
|
||||
const now = Date.now();
|
||||
this._scheduleResume(Math.max(resumeAt, now + RESUME_MIN_DELAY_MS), resumeAt, 'restored');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auto-resume — detection and scheduling
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Scan cleaned terminal output for a usage-limit pause message and (re)arm
|
||||
* the resume schedule. Called from the session's throttled parser path.
|
||||
*/
|
||||
processCleanData(cleanData: string): void {
|
||||
if (!this._autoResumeEnabled || this.callbacks.isStopped()) return;
|
||||
// A resume is in flight (Esc sent, continue pending): output from our own
|
||||
// Escape can redraw the stale limit footer — don't let it re-arm and
|
||||
// cancel the continue. Fresh evidence arrives after the prompt is sent.
|
||||
if (this._resumeFollowupTimer) return;
|
||||
|
||||
const detection = detectUsageLimitPause(cleanData);
|
||||
if (!detection) return;
|
||||
|
||||
const now = Date.now();
|
||||
const overdue = detection.resetAt <= now;
|
||||
const fireAt = overdue
|
||||
? now + RESUME_RETRY_MS // stale reset time → gentle retry loop
|
||||
: Math.max(detection.resetAt + RESUME_BUFFER_MS, now + RESUME_MIN_DELAY_MS);
|
||||
|
||||
if (this._autoResumeTimer && this._autoResumeAt !== null) {
|
||||
// Already armed: the footer redraws constantly, so ignore re-detections
|
||||
// that land on (or later than) the current schedule. Only an EARLIER
|
||||
// parsed time replaces it — an overdue retry never preempts a real one.
|
||||
if (overdue || fireAt >= this._autoResumeAt - RESUME_DEDUP_TOLERANCE_MS) return;
|
||||
}
|
||||
|
||||
this._scheduleResume(fireAt, detection.resetAt, detection.matched);
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude started working — the limit is lifted (or the user resumed
|
||||
* manually), so any pending auto-resume is obsolete.
|
||||
*/
|
||||
notifyWorking(): void {
|
||||
this._resumeAttempts = 0;
|
||||
if (!this._limitPaused && !this._autoResumeTimer && !this._resumeFollowupTimer) return;
|
||||
this._cancelAutoResume('working');
|
||||
}
|
||||
|
||||
private _scheduleResume(fireAt: number, resetAt: number, matched: string): void {
|
||||
if (this._autoResumeTimer) {
|
||||
clearTimeout(this._autoResumeTimer);
|
||||
this._autoResumeTimer = null;
|
||||
}
|
||||
this._limitPaused = true;
|
||||
this._autoResumeAt = fireAt;
|
||||
const delay = Math.max(fireAt - Date.now(), 0);
|
||||
console.log(
|
||||
`[SessionAutoOps ${this.callbacks.getSessionId()}] Usage-limit pause detected ("${matched.slice(0, 60)}"), auto-resume in ${Math.round(delay / 60000)}min`
|
||||
);
|
||||
this._autoResumeTimer = setTimeout(() => void this._fireResume(), delay);
|
||||
this.emit('limitPauseScheduled', { resetAt, resumeAt: fireAt, matched });
|
||||
}
|
||||
|
||||
private async _fireResume(): Promise<void> {
|
||||
this._autoResumeTimer = null;
|
||||
if (!this._autoResumeEnabled || this.callbacks.isStopped()) return;
|
||||
|
||||
if (this.callbacks.isWorking()) {
|
||||
// Session resumed on its own (or via the user) — nothing to do.
|
||||
this._cancelAutoResume('working');
|
||||
return;
|
||||
}
|
||||
|
||||
this._resumeAttempts++;
|
||||
const attempt = this._resumeAttempts;
|
||||
this._limitPaused = false; // optimistic: a fresh limit message re-arms us
|
||||
this._autoResumeAt = null;
|
||||
|
||||
// Escape first: dismisses the rate-limit options dialog if Claude opened
|
||||
// one (harmless at an idle prompt), then the resume prompt after a beat.
|
||||
await this.callbacks.writeCommand('\x1b');
|
||||
this._resumeFollowupTimer = setTimeout(() => {
|
||||
this._resumeFollowupTimer = null;
|
||||
if (this.callbacks.isStopped()) return;
|
||||
void this.callbacks.writeCommand(`${RESUME_PROMPT}\r`);
|
||||
this.emit('limitResume', { attempt });
|
||||
}, RESUME_ESC_DELAY_MS);
|
||||
}
|
||||
|
||||
private _cancelAutoResume(reason: 'disabled' | 'working' | 'stopped'): void {
|
||||
const wasArmed = this._autoResumeTimer !== null || this._resumeFollowupTimer !== null || this._limitPaused;
|
||||
if (this._autoResumeTimer) {
|
||||
clearTimeout(this._autoResumeTimer);
|
||||
this._autoResumeTimer = null;
|
||||
}
|
||||
if (this._resumeFollowupTimer) {
|
||||
clearTimeout(this._resumeFollowupTimer);
|
||||
this._resumeFollowupTimer = null;
|
||||
}
|
||||
this._limitPaused = false;
|
||||
this._autoResumeAt = null;
|
||||
if (wasArmed && reason !== 'stopped') {
|
||||
this.emit('limitResumeCancelled', { reason });
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Threshold checks
|
||||
// ============================================================================
|
||||
@@ -321,5 +502,7 @@ export class SessionAutoOps extends EventEmitter {
|
||||
this._autoClearTimer = null;
|
||||
}
|
||||
this._isClearing = false;
|
||||
|
||||
this._cancelAutoResume('stopped');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import type { ClaudeMode, EffortLevel } from './types.js';
|
||||
import { isEffortLevel } from './types.js';
|
||||
import { getAugmentedPath } from './utils/index.js';
|
||||
import { dataPath } from './config/instance.js';
|
||||
|
||||
/**
|
||||
* Build Claude CLI permission flags based on the configured mode.
|
||||
@@ -113,6 +114,8 @@ export function buildClaudeEnv(sessionId: string): Record<string, string | undef
|
||||
CODEMAN_MUX: '1',
|
||||
CODEMAN_SESSION_ID: sessionId,
|
||||
CODEMAN_API_URL: process.env.CODEMAN_API_URL || 'http://localhost:3000',
|
||||
// Path only (not the secret value) — hook curls cat it at execution time (COD-54)
|
||||
CODEMAN_HOOK_SECRET_FILE: dataPath('hook-secret'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -149,5 +152,7 @@ export function buildShellEnv(sessionId: string): Record<string, string | undefi
|
||||
CODEMAN_MUX: '1',
|
||||
CODEMAN_SESSION_ID: sessionId,
|
||||
CODEMAN_API_URL: process.env.CODEMAN_API_URL || 'http://localhost:3000',
|
||||
// Path only (not the secret value) — hook curls cat it at execution time (COD-54)
|
||||
CODEMAN_HOOK_SECRET_FILE: dataPath('hook-secret'),
|
||||
};
|
||||
}
|
||||
|
||||
+255
-8
@@ -78,7 +78,14 @@ import {
|
||||
buildShellEnv,
|
||||
} from './session-cli-builder.js';
|
||||
import { SessionAutoOps } from './session-auto-ops.js';
|
||||
import { detectUsageLimitPause } from './usage-limit-patterns.js';
|
||||
import { SessionTaskCache } from './session-task-cache.js';
|
||||
import { parseAttachmentMagicLinks } from './attachment-magic.js';
|
||||
import {
|
||||
sanitizeAttachmentHistory,
|
||||
upsertAttachmentHistory as upsertAttachmentHistoryList,
|
||||
} from './session-attachment-history.js';
|
||||
import type { SessionAttachmentHistoryItem } from './types/session.js';
|
||||
|
||||
export type { BackgroundTask } from './task-tracker.js';
|
||||
export type { RalphTrackerState, RalphTodoItem, ActiveBashTool } from './types.js';
|
||||
@@ -129,6 +136,21 @@ export function isExternalCliMode(mode: SessionMode): boolean {
|
||||
return mode === 'opencode' || mode === 'codex';
|
||||
}
|
||||
|
||||
/**
|
||||
* Modes whose TUI emits alt-screen / scrollback-erase / mouse-tracking sequences
|
||||
* that we strip so the browser keeps everything in the main buffer with scrollback
|
||||
* reachable (the strip runs on both the live stream and the buffer replay).
|
||||
*
|
||||
* Codex and Claude Code are known, controlled TUIs that repaint via cursor
|
||||
* positioning, so dropping the alt-screen switch is safe — content stays in the
|
||||
* normal buffer. Excluded: `shell` (arbitrary programs like vim/less/htop
|
||||
* legitimately need the alt screen) and `opencode` (renders its own TUI that
|
||||
* may rely on it). Keep parity with the replay-side strip in session-routes.ts.
|
||||
*/
|
||||
export function isAltScreenStripMode(mode: SessionMode): boolean {
|
||||
return mode === 'codex' || mode === 'claude';
|
||||
}
|
||||
|
||||
// Note: Claude CLI PATH resolution moved to session-cli-builder.ts (buildClaudeEnv)
|
||||
|
||||
/** PTY fallback geometry when tmux can't be queried (matches pre-#80 hardcoded values). */
|
||||
@@ -258,6 +280,10 @@ export class Session extends EventEmitter {
|
||||
private _messages: ClaudeMessage[] = [];
|
||||
private _lineBuffer: string = '';
|
||||
private _lineBufferFlushTimer: NodeJS.Timeout | null = null;
|
||||
// Alt-screen-strip modes (Codex/Claude): trailing partial CSI held back so
|
||||
// sequences split across PTY chunks can't slip past the alt-screen/scrollback
|
||||
// strip (see _handleTerminalOutput / isAltScreenStripMode)
|
||||
private _altScreenSeqCarry: string = '';
|
||||
private resolvePromise: ((value: { result: string; cost: number }) => void) | null = null;
|
||||
private rejectPromise: ((reason: Error) => void) | null = null;
|
||||
private _promptResolved: boolean = false; // Guard against race conditions in runPrompt
|
||||
@@ -307,6 +333,10 @@ export class Session extends EventEmitter {
|
||||
private _parentAgentId: string | null = null;
|
||||
private _childAgentIds: string[] = [];
|
||||
|
||||
// Bounded dedup set for terminal attachment magic-links already requested.
|
||||
private _attachmentMagicSeen = new Set<string>();
|
||||
private _attachmentHistory: SessionAttachmentHistoryItem[] = [];
|
||||
|
||||
// Nice prioritying configuration
|
||||
private _niceConfig: NiceConfig = { ...DEFAULT_NICE_CONFIG };
|
||||
|
||||
@@ -397,6 +427,8 @@ export class Session extends EventEmitter {
|
||||
envOverrides?: Record<string, string>;
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
effort?: EffortLevel;
|
||||
/** Restored per-session attachment history. May include server-private external paths. */
|
||||
attachmentHistory?: SessionAttachmentHistoryItem[];
|
||||
}
|
||||
) {
|
||||
super();
|
||||
@@ -463,6 +495,9 @@ export class Session extends EventEmitter {
|
||||
if (config.effort && isEffortLevel(config.effort)) {
|
||||
this._effort = config.effort;
|
||||
}
|
||||
if (config.attachmentHistory && config.attachmentHistory.length > 0) {
|
||||
this.restoreAttachmentHistory(config.attachmentHistory);
|
||||
}
|
||||
|
||||
// Initialize task tracker and forward events (store handlers for cleanup)
|
||||
this._taskTracker = new TaskTracker();
|
||||
@@ -520,6 +555,9 @@ export class Session extends EventEmitter {
|
||||
this._totalOutputTokens = 0;
|
||||
this.emit('autoClear', data);
|
||||
});
|
||||
this._autoOps.on('limitPauseScheduled', (data) => this.emit('limitPauseScheduled', data));
|
||||
this._autoOps.on('limitResume', (data) => this.emit('limitResume', data));
|
||||
this._autoOps.on('limitResumeCancelled', (data) => this.emit('limitResumeCancelled', data));
|
||||
}
|
||||
|
||||
get status(): SessionStatus {
|
||||
@@ -825,6 +863,39 @@ export class Session extends EventEmitter {
|
||||
this._autoOps.setAutoCompact(enabled, threshold, prompt);
|
||||
}
|
||||
|
||||
get autoResumeEnabled(): boolean {
|
||||
return this._autoOps.autoResumeEnabled;
|
||||
}
|
||||
|
||||
/** When the scheduled usage-limit auto-resume fires (epoch ms), or null. */
|
||||
get autoResumeAt(): number | null {
|
||||
return this._autoOps.autoResumeAt;
|
||||
}
|
||||
|
||||
/** True while the session is paused on a Claude usage limit (auto-resume armed). */
|
||||
get isLimitPaused(): boolean {
|
||||
return this._autoOps.isLimitPaused;
|
||||
}
|
||||
|
||||
setAutoResume(enabled: boolean): void {
|
||||
this._autoOps.setAutoResume(enabled);
|
||||
// Users typically enable this WHILE a session already sits paused — the
|
||||
// limit footer won't reprint on its own, so scan the recent buffer once.
|
||||
// Only a future reset time counts: stale scrollback must not arm a resume.
|
||||
if (enabled && !isExternalCliMode(this.mode)) {
|
||||
const tail = this._terminalBuffer.value.slice(-8192).replace(ANSI_ESCAPE_PATTERN_FULL, '');
|
||||
const detection = detectUsageLimitPause(tail);
|
||||
if (detection && detection.resetAt > Date.now()) {
|
||||
this._autoOps.processCleanData(tail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Restore auto-resume state (and a pending schedule) after Codeman restart. */
|
||||
restoreAutoResume(enabled: boolean, resumeAt?: number): void {
|
||||
this._autoOps.restoreAutoResume(enabled, resumeAt);
|
||||
}
|
||||
|
||||
get imageWatcherEnabled(): boolean {
|
||||
return this._imageWatcherEnabled;
|
||||
}
|
||||
@@ -853,6 +924,30 @@ export class Session extends EventEmitter {
|
||||
return this._status === 'idle' || this._status === 'busy';
|
||||
}
|
||||
|
||||
get attachmentHistory(): SessionAttachmentHistoryItem[] {
|
||||
return sanitizeAttachmentHistory(this._attachmentHistory);
|
||||
}
|
||||
|
||||
upsertAttachmentHistory(item: SessionAttachmentHistoryItem): void {
|
||||
this._attachmentHistory = upsertAttachmentHistoryList(this._attachmentHistory, item);
|
||||
}
|
||||
|
||||
restoreAttachmentHistory(history: SessionAttachmentHistoryItem[] | undefined): void {
|
||||
this._attachmentHistory = [];
|
||||
for (const item of [...(history ?? [])].reverse()) {
|
||||
// Guard against malformed/legacy on-disk entries (null, non-object, or
|
||||
// missing required fields). historyKey() dereferences source/fileName, so
|
||||
// a bad item would otherwise throw inside the constructor and abort the
|
||||
// entire mux-recovery loop.
|
||||
if (!item || typeof item !== 'object' || !item.source || !item.fileName) continue;
|
||||
this.upsertAttachmentHistory(item);
|
||||
}
|
||||
}
|
||||
|
||||
getAttachmentHistoryForPersist(): SessionAttachmentHistoryItem[] | undefined {
|
||||
return this._attachmentHistory.length > 0 ? this._attachmentHistory.map((item) => ({ ...item })) : undefined;
|
||||
}
|
||||
|
||||
toState(): SessionState {
|
||||
return {
|
||||
id: this.id,
|
||||
@@ -869,6 +964,8 @@ export class Session extends EventEmitter {
|
||||
autoCompactEnabled: this._autoOps.autoCompactEnabled,
|
||||
autoCompactThreshold: this._autoOps.autoCompactThreshold,
|
||||
autoCompactPrompt: this._autoOps.autoCompactPrompt,
|
||||
autoResumeEnabled: this._autoOps.autoResumeEnabled,
|
||||
autoResumeAt: this._autoOps.autoResumeAt ?? undefined,
|
||||
imageWatcherEnabled: this._imageWatcherEnabled,
|
||||
totalCost: this._totalCost,
|
||||
inputTokens: this._totalInputTokens,
|
||||
@@ -890,6 +987,7 @@ export class Session extends EventEmitter {
|
||||
codexConfig: this._codexConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
effort: this._effort,
|
||||
attachmentHistory: this.attachmentHistory.length > 0 ? this.attachmentHistory : undefined,
|
||||
// envOverrides intentionally NOT on the public SessionState type — they must not
|
||||
// leak into SSE / GET /api/sessions broadcasts (schema allows OPENCODE_*, which
|
||||
// can carry secrets). For disk persistence, session-manager calls
|
||||
@@ -1052,6 +1150,66 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
|
||||
private _handleTerminalOutput(data: string): void {
|
||||
// Codex AND Claude Code emit sequences that wipe xterm.js scrollback, plus
|
||||
// mouse-tracking enables that hijack the scroll wheel so the user can't reach
|
||||
// scrollback. Claude Code does this intermittently (e.g. full-screen pickers /
|
||||
// dialogs), which is why terminal scroll-up "randomly" breaks for Claude
|
||||
// sessions on mobile and desktop until the dialog closes:
|
||||
// - \x1b[?1049h / \x1b[?47h / \x1b[?1047h: switch to the alt buffer (no
|
||||
// scrollback) — \x1b[?...l switches back.
|
||||
// - \x1b[3J: erase saved lines (scrollback). (\x1b[2J / \x1b[J — erase
|
||||
// the visible viewport — are left intact; the TUI repaints those rows.)
|
||||
// - \x1b[?1000h / 1002h / 1003h / 1005h / 1006h / 1007h: mouse-tracking
|
||||
// modes (X10, button-event, any-event, UTF-8, SGR, alt-scroll). Once on,
|
||||
// xterm.js forwards wheel events to the CLI instead of scrolling the
|
||||
// viewport, so the conversation is in scrollback but unreachable.
|
||||
// (Focus events at ?1004 are left alone — codeman uses them for
|
||||
// active-tab detection.)
|
||||
// Strip them at the source so neither the persisted buffer nor the live
|
||||
// SSE/WS stream carries them, keeping everything in the main buffer with
|
||||
// scrollback intact. These are controlled TUIs whose cursor-positioned
|
||||
// redraws overwrite only the cells they target, so non-erased rows keep
|
||||
// their content. Gated to Codex/Claude (isAltScreenStripMode) — shell must
|
||||
// keep the alt screen for vim/less/htop.
|
||||
if (isAltScreenStripMode(this.mode)) {
|
||||
// Reassemble sequences split across PTY chunk boundaries first: a chunk
|
||||
// ending mid-sequence ('\x1b[?104' now, '9h' next) would slip past the
|
||||
// strip below and leave xterm stuck in the scrollback-less alt buffer
|
||||
// until the next buffer replay. Hold back an incomplete digit-only CSI
|
||||
// tail (≤7 chars — the longest strippable intro is '\x1b[?1049') and
|
||||
// prepend it to the next chunk; complete sequences are never held.
|
||||
data = this._altScreenSeqCarry + data;
|
||||
this._altScreenSeqCarry = '';
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const splitTail = data.match(/\x1b(?:\[\??[0-9]{0,4})?$/);
|
||||
if (splitTail) {
|
||||
this._altScreenSeqCarry = splitTail[0];
|
||||
data = data.slice(0, -splitTail[0].length);
|
||||
if (!data) return;
|
||||
}
|
||||
data = data
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/\x1b\[\?(?:47|1047|1049)[hl]/g, '')
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/\x1b\[3J/g, '')
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/\x1b\[\?(?:1000|1001|1002|1003|1005|1006|1007)[hl]/g, '');
|
||||
}
|
||||
|
||||
// Scan terminal output for `codeman://attach?path=...` magic links and emit
|
||||
// an attachmentRequested event for each newly-seen absolute path. The web
|
||||
// server turns these into registered attachment cards.
|
||||
const attachmentPaths = parseAttachmentMagicLinks(data);
|
||||
for (const attachmentPath of attachmentPaths) {
|
||||
if (this._attachmentMagicSeen.has(attachmentPath)) continue;
|
||||
this._attachmentMagicSeen.add(attachmentPath);
|
||||
if (this._attachmentMagicSeen.size > 200) {
|
||||
const oldest = this._attachmentMagicSeen.values().next().value;
|
||||
if (oldest) this._attachmentMagicSeen.delete(oldest);
|
||||
}
|
||||
this.emit('attachmentRequested', { sessionId: this.id, path: attachmentPath, timestamp: Date.now() });
|
||||
}
|
||||
|
||||
// BufferAccumulator handles auto-trimming when max size exceeded
|
||||
this._terminalBuffer.append(data);
|
||||
this._lastActivityAt = Date.now();
|
||||
@@ -1250,6 +1408,7 @@ export class Session extends EventEmitter {
|
||||
this._isWorking = true;
|
||||
this._status = 'busy';
|
||||
this.emit('working');
|
||||
this._autoOps.notifyWorking();
|
||||
}
|
||||
this._awaitingIdleConfirmation = false;
|
||||
if (this.activityTimeout) clearTimeout(this.activityTimeout);
|
||||
@@ -1356,6 +1515,11 @@ export class Session extends EventEmitter {
|
||||
this._bashToolParser.processCleanData(getCleanData());
|
||||
}
|
||||
|
||||
// Usage-limit pause detection (auto-resume on usage limit)
|
||||
if (this._autoOps.autoResumeEnabled) {
|
||||
this._autoOps.processCleanData(getCleanData());
|
||||
}
|
||||
|
||||
// Parse token count from status line (e.g., "123.4k tokens" or "5234 tokens")
|
||||
if (rawData.includes('token')) {
|
||||
this.parseTokensFromStatusLine(getCleanData());
|
||||
@@ -1384,6 +1548,7 @@ export class Session extends EventEmitter {
|
||||
this._isWorking = true;
|
||||
this._status = 'busy';
|
||||
this.emit('working');
|
||||
this._autoOps.notifyWorking();
|
||||
this._awaitingIdleConfirmation = false;
|
||||
if (this.activityTimeout) clearTimeout(this.activityTimeout);
|
||||
}
|
||||
@@ -1665,6 +1830,7 @@ export class Session extends EventEmitter {
|
||||
this._errorBuffer = '';
|
||||
this._messages = [];
|
||||
this._lineBuffer = '';
|
||||
this._altScreenSeqCarry = '';
|
||||
this._lastActivityAt = Date.now();
|
||||
}
|
||||
|
||||
@@ -2047,6 +2213,42 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-client highest-applied input sequence, for exactly-once input delivery.
|
||||
* Keyed by the web client's stable `clientId`. Bounded so many devices over a
|
||||
* long-lived session can't grow it without limit (insertion order = MRU, so
|
||||
* eviction drops the least-recently-active client).
|
||||
*/
|
||||
private _appliedInputSeq = new Map<string, number>();
|
||||
private static readonly MAX_INPUT_DEDUP_CLIENTS = 256;
|
||||
|
||||
/**
|
||||
* Decide whether an input frame should be applied to the PTY or skipped as a
|
||||
* duplicate redelivery. Returns true exactly once per (clientId, seq): the
|
||||
* first time a seq strictly greater than the client's last-applied is seen.
|
||||
* A redelivery of an already-applied seq (the client never got our ACK and
|
||||
* resent) returns false. Callers should ACK regardless — a duplicate is, from
|
||||
* the client's view, "delivered" — and only `write()` the PTY when this is
|
||||
* true. Relies on the client delivering one client's frames in seq order over
|
||||
* a single ordered stream, so `seq <= last` ⇒ already applied.
|
||||
*
|
||||
* Without this, the client's at-least-once redelivery (needed because a
|
||||
* half-open socket silently drops frames with no error) would type a prompt
|
||||
* twice whenever an ACK is lost after the write landed.
|
||||
*/
|
||||
shouldApplyInput(clientId: string, seq: number): boolean {
|
||||
const last = this._appliedInputSeq.get(clientId);
|
||||
if (last !== undefined && seq <= last) return false;
|
||||
// Re-insert to move this client to the MRU end for fair eviction.
|
||||
if (last !== undefined) this._appliedInputSeq.delete(clientId);
|
||||
this._appliedInputSeq.set(clientId, seq);
|
||||
if (this._appliedInputSeq.size > Session.MAX_INPUT_DEDUP_CLIENTS) {
|
||||
const oldest = this._appliedInputSeq.keys().next().value;
|
||||
if (oldest !== undefined) this._appliedInputSeq.delete(oldest);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends input via the terminal multiplexer's direct input mechanism.
|
||||
*
|
||||
@@ -2096,9 +2298,29 @@ export class Session extends EventEmitter {
|
||||
*/
|
||||
private _desktopSizeClaims = new Set<symbol>();
|
||||
|
||||
/**
|
||||
* A desktop sizing claim only blocks small-viewport resizes while the
|
||||
* desktop is RECENTLY ACTIVE (claim registration or typed input within this
|
||||
* window). An abandoned-but-connected desktop tab (left open at home, screen
|
||||
* locked) must not hold a phone's view hostage: without this, the phone
|
||||
* renders a desktop-width stream in a narrow xterm — mid-word wraps, tmux
|
||||
* dot-fill, and Ink overdraw soup (the 0.9.8–0.9.12 mobile regression).
|
||||
*/
|
||||
private static readonly DESKTOP_CLAIM_IDLE_MS = 90_000;
|
||||
|
||||
/** Last evidence of a live desktop user (claim registered / typed input). */
|
||||
private _lastDesktopActivityAt = 0;
|
||||
|
||||
/** Last desktop-typed dimensions, for re-asserting after a mobile override. */
|
||||
private _lastDesktopDims: { cols: number; rows: number } | null = null;
|
||||
|
||||
/** True while a small viewport reflowed the pane past an idle desktop claim. */
|
||||
private _mobileSizeOverride = false;
|
||||
|
||||
/** Register a live desktop sizing claim (see _desktopSizeClaims). */
|
||||
claimDesktopSizing(token: symbol): void {
|
||||
this._desktopSizeClaims.add(token);
|
||||
this._lastDesktopActivityAt = Date.now();
|
||||
}
|
||||
|
||||
/** Release a desktop sizing claim when its connection goes away. */
|
||||
@@ -2106,25 +2328,50 @@ export class Session extends EventEmitter {
|
||||
this._desktopSizeClaims.delete(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record desktop user activity (typed input over a claim-holding socket).
|
||||
* If a phone reflowed the pane while the desktop was idle, the desktop
|
||||
* layout is restored — "whoever is actively using the session wins".
|
||||
*/
|
||||
noteDesktopActivity(): void {
|
||||
this._lastDesktopActivityAt = Date.now();
|
||||
if (this._mobileSizeOverride && this._lastDesktopDims) {
|
||||
this._mobileSizeOverride = false;
|
||||
this.resize(this._lastDesktopDims.cols, this._lastDesktopDims.rows, { viewportType: 'desktop' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the PTY terminal dimensions.
|
||||
* Skips the resize if dimensions haven't changed to avoid triggering
|
||||
* unnecessary Ink full-screen redraws (visible flicker on tab switch).
|
||||
*
|
||||
* Arbitration: while a desktop connection holds a sizing claim, resizes from
|
||||
* small viewports (mobile/tablet) are ignored entirely — shrink AND grow
|
||||
* would both reflow the desktop view. Without a desktop connected, small
|
||||
* viewports control the PTY size freely.
|
||||
* Arbitration: while a desktop connection holds a sizing claim AND has been
|
||||
* active within DESKTOP_CLAIM_IDLE_MS, resizes from small viewports
|
||||
* (mobile/tablet) are ignored — shrink AND grow would both reflow the
|
||||
* desktop view. Once the desktop goes idle, a phone may take the pane (the
|
||||
* desktop re-asserts its size on its next typed input via
|
||||
* noteDesktopActivity). Without a desktop connected, small viewports
|
||||
* control the PTY size freely.
|
||||
*
|
||||
* @param cols - Number of columns (width in characters)
|
||||
* @param rows - Number of rows (height in lines)
|
||||
*/
|
||||
resize(cols: number, rows: number, options: { viewportType?: ResizeViewportType } = {}): void {
|
||||
resize(cols: number, rows: number, options: { viewportType?: ResizeViewportType; force?: boolean } = {}): void {
|
||||
const isSmallViewport = options.viewportType === 'mobile' || options.viewportType === 'tablet';
|
||||
if (isSmallViewport && this._desktopSizeClaims.size > 0) {
|
||||
return;
|
||||
if (options.viewportType === 'desktop') {
|
||||
this._lastDesktopDims = { cols, rows };
|
||||
this._lastDesktopActivityAt = Date.now();
|
||||
this._mobileSizeOverride = false;
|
||||
}
|
||||
if (this.ptyProcess && (cols !== this._ptyCols || rows !== this._ptyRows)) {
|
||||
if (isSmallViewport && this._desktopSizeClaims.size > 0) {
|
||||
if (Date.now() - this._lastDesktopActivityAt < Session.DESKTOP_CLAIM_IDLE_MS) {
|
||||
return;
|
||||
}
|
||||
this._mobileSizeOverride = true;
|
||||
}
|
||||
const dimsChanged = cols !== this._ptyCols || rows !== this._ptyRows;
|
||||
if (this.ptyProcess && (dimsChanged || options.force)) {
|
||||
this._ptyCols = cols;
|
||||
this._ptyRows = rows;
|
||||
if (this._mux && this._muxSession) {
|
||||
|
||||
+152
-5
@@ -13,6 +13,8 @@
|
||||
* - `SubagentEvents` — typed event map
|
||||
*
|
||||
* Watched patterns: `~/.claude/projects/{project}/{session}/subagents/agent-{id}.jsonl`
|
||||
* plus the `agent-{id}.meta.json` discovery sidecar (2026-06 format) and nested
|
||||
* workflow agents under `subagents/workflows/{workflowId}/agent-{id}.jsonl`.
|
||||
* Parses JSONL entries: user/assistant messages, tool_use/tool_result blocks, progress events.
|
||||
* Tracks per-agent: status, token counts, model, description, tool call count, liveness (PID).
|
||||
*
|
||||
@@ -30,7 +32,7 @@ import { watch, existsSync, FSWatcher } from 'node:fs';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, basename } from 'node:path';
|
||||
import { join, basename, dirname } from 'node:path';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { readFile, readdir, stat as statAsync } from 'node:fs/promises';
|
||||
import { PENDING_TOOL_CALL_TTL_MS, MAX_PENDING_TOOL_CALLS, MAX_TRACKED_AGENTS } from './config/map-limits.js';
|
||||
@@ -1150,6 +1152,10 @@ export class SubagentWatcher extends EventEmitter {
|
||||
try {
|
||||
await statAsync(subagentDir);
|
||||
await this.watchSubagentDir(subagentDir, project, session);
|
||||
// Workflow agents nest one level deeper under subagents/workflows/{wf}/
|
||||
// (each holds its own agent-{id}.jsonl/.meta.json) — the flat watcher
|
||||
// above never sees them, so discover and watch each workflow dir too.
|
||||
await this.watchWorkflowDirs(subagentDir, project, session);
|
||||
} catch {
|
||||
// subagent dir doesn't exist - skip
|
||||
}
|
||||
@@ -1179,8 +1185,12 @@ export class SubagentWatcher extends EventEmitter {
|
||||
try {
|
||||
const files = await readdir(dir);
|
||||
for (const file of files) {
|
||||
if (file.endsWith('.jsonl')) {
|
||||
if (file.startsWith('agent-') && file.endsWith('.jsonl')) {
|
||||
await this.registerAgentFile(join(dir, file), projectHash, sessionId, true);
|
||||
} else if (file.startsWith('agent-') && file.endsWith('.meta.json')) {
|
||||
// Claude Code (2026-06) writes a `agent-{id}.meta.json` sidecar for TUI
|
||||
// Task subagents and no longer always writes a per-agent `.jsonl` here.
|
||||
await this.registerAgentMeta(join(dir, file), projectHash, sessionId, true);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -1190,13 +1200,26 @@ export class SubagentWatcher extends EventEmitter {
|
||||
// Single directory watcher handles both new files and file content changes
|
||||
try {
|
||||
const watcher = watch(dir, (_eventType, filename) => {
|
||||
if (!filename?.endsWith('.jsonl')) return;
|
||||
const filePath = join(dir, filename);
|
||||
// Only agent-{id}.jsonl / agent-{id}.meta.json — ignore siblings like a
|
||||
// workflow dir's journal.jsonl (would otherwise register a bogus "journal" agent).
|
||||
const isAgent = !!filename && filename.startsWith('agent-');
|
||||
const isJsonl = isAgent && filename.endsWith('.jsonl');
|
||||
const isMeta = isAgent && filename.endsWith('.meta.json');
|
||||
if (!isJsonl && !isMeta) return;
|
||||
const filePath = join(dir, filename as string);
|
||||
|
||||
// Debounce 100ms to batch rapid writes
|
||||
this.fileDeb.schedule(filePath, () => {
|
||||
if (!existsSync(filePath)) return;
|
||||
|
||||
if (isMeta) {
|
||||
// Meta sidecar — discovery only (not a transcript; never tail it).
|
||||
if (!this.fileAgentContext.has(filePath)) {
|
||||
this.registerAgentMeta(filePath, projectHash, sessionId).catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.fileAgentContext.has(filePath)) {
|
||||
// Known file — handle content change
|
||||
this.handleFileChange(filePath).catch(() => {}); // Ignore - errors logged internally, don't crash watcher callback
|
||||
@@ -1225,6 +1248,40 @@ export class SubagentWatcher extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover and watch nested workflow agent directories.
|
||||
*
|
||||
* The Workflow tool runs its subagents under
|
||||
* `subagents/workflows/{workflowId}/agent-{id}.jsonl` (+ `.meta.json`, alongside
|
||||
* a `journal.jsonl` of orchestration events). The flat `subagents/` watcher does
|
||||
* not recurse, and Node's `fs.watch({ recursive: true })` is unsupported on Linux,
|
||||
* so each workflow dir gets its own watcher here. Idempotent via `knownSubagentDirs`
|
||||
* and re-driven by the periodic scan, so newly created workflows are picked up
|
||||
* within one scan cycle (~5s) — the same latency as a new session's `subagents/`.
|
||||
*/
|
||||
private async watchWorkflowDirs(subagentDir: string, projectHash: string, sessionId: string): Promise<void> {
|
||||
const workflowsRoot = join(subagentDir, 'workflows');
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(workflowsRoot);
|
||||
} catch {
|
||||
return; // no workflows for this session
|
||||
}
|
||||
for (const name of names) {
|
||||
// Workflow ids are directories (e.g. `wf_<id>`); skip any stray files that
|
||||
// share the root (a workflow id never carries a file extension).
|
||||
if (name.endsWith('.jsonl') || name.endsWith('.json')) continue;
|
||||
const wfDir = join(workflowsRoot, name);
|
||||
try {
|
||||
const st = await statAsync(wfDir);
|
||||
if (!st.isDirectory()) continue;
|
||||
await this.watchSubagentDir(wfDir, projectHash, sessionId);
|
||||
} catch {
|
||||
// workflow dir vanished mid-scan — skip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a file content change for an already-registered agent file.
|
||||
* Tails from last known position, updates info, retries description if missing.
|
||||
@@ -1291,6 +1348,16 @@ export class SubagentWatcher extends EventEmitter {
|
||||
|
||||
const agentId = basename(filePath).replace('agent-', '').replace('.jsonl', '');
|
||||
|
||||
// Meta→transcript upgrade: the agent may already be registered from its
|
||||
// `.meta.json` sidecar (discovery-only — nothing to tail). Now that the real
|
||||
// `.jsonl` transcript has appeared, re-point to it and drop the stale sidecar
|
||||
// context, emitting `updated` below rather than a duplicate `discovered`.
|
||||
const priorEntry = this.agentInfo.get(agentId);
|
||||
const isMetaUpgrade = !!priorEntry && priorEntry.filePath.endsWith('.meta.json');
|
||||
if (isMetaUpgrade && priorEntry) {
|
||||
this.fileAgentContext.delete(priorEntry.filePath);
|
||||
}
|
||||
|
||||
// Initial info - handle race condition where file may be deleted between discovery and stat
|
||||
let fileStat;
|
||||
try {
|
||||
@@ -1341,7 +1408,7 @@ export class SubagentWatcher extends EventEmitter {
|
||||
// Track file context for directory watcher change handling
|
||||
this.fileAgentContext.set(filePath, { projectHash, sessionId });
|
||||
this.agentInfo.set(agentId, info);
|
||||
this.emit('subagent:discovered', info);
|
||||
this.emit(isMetaUpgrade ? 'subagent:updated' : 'subagent:discovered', info);
|
||||
|
||||
// Read existing content
|
||||
this.tailFile(filePath, agentId, sessionId, 0)
|
||||
@@ -1356,6 +1423,86 @@ export class SubagentWatcher extends EventEmitter {
|
||||
this.resetIdleTimer(agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a subagent discovered via its `agent-{id}.meta.json` sidecar.
|
||||
*
|
||||
* As of the 2026-06 Claude Code format change, TUI Task subagents write the
|
||||
* `agent-{id}.meta.json` sidecar (`{ agentType, description, toolUseId }`) at
|
||||
* spawn, a beat *before* the `agent-{id}.jsonl` transcript appears in the same
|
||||
* dir. The legacy `.jsonl`-only discovery saw nothing in that window ("0
|
||||
* tracked"); this surfaces the agent from the sidecar immediately. The
|
||||
* transcript then lands within ~1s at the standard path and grows incrementally
|
||||
* (empirically verified — it is fully tailable, NOT a dead end), so:
|
||||
* - if the `.jsonl` already exists, defer to registerAgentFile (richer); else
|
||||
* - register meta-only now, and when the sibling `.jsonl` arrives the dir
|
||||
* watcher routes it to registerAgentFile, which detects the prior meta-only
|
||||
* entry and *upgrades* it in place (re-points filePath, starts tailing).
|
||||
*
|
||||
* Edge case: if the transcript never materializes (e.g. an agent that dies
|
||||
* before writing one), the agent stays meta-only — no live feed, status ages
|
||||
* out via the idle timer / stale cleanup.
|
||||
*/
|
||||
private async registerAgentMeta(
|
||||
metaPath: string,
|
||||
projectHash: string,
|
||||
sessionId: string,
|
||||
isInitialScan: boolean = false
|
||||
): Promise<void> {
|
||||
if (this.fileAgentContext.has(metaPath)) return;
|
||||
const agentId = basename(metaPath).replace('agent-', '').replace('.meta.json', '');
|
||||
if (this.agentInfo.has(agentId)) return;
|
||||
|
||||
// Prefer a real transcript if one was written alongside the sidecar.
|
||||
const jsonlPath = join(dirname(metaPath), `agent-${agentId}.jsonl`);
|
||||
if (existsSync(jsonlPath)) {
|
||||
await this.registerAgentFile(jsonlPath, projectHash, sessionId, isInitialScan);
|
||||
return;
|
||||
}
|
||||
|
||||
let fileStat;
|
||||
try {
|
||||
fileStat = await statAsync(metaPath);
|
||||
} catch {
|
||||
return; // deleted between discovery and stat
|
||||
}
|
||||
if (isInitialScan && Date.now() - fileStat.mtime.getTime() > STARTUP_MAX_FILE_AGE_MS) {
|
||||
return; // skip stale historical agents on startup
|
||||
}
|
||||
|
||||
let description: string | undefined;
|
||||
try {
|
||||
const meta = JSON.parse(await readFile(metaPath, 'utf8')) as { agentType?: string; description?: string };
|
||||
description = meta.description || meta.agentType;
|
||||
} catch {
|
||||
return; // unreadable / not yet fully written — a later watch event retries
|
||||
}
|
||||
if (this.isInternalAgent(description)) return;
|
||||
|
||||
const info: SubagentInfo = {
|
||||
agentId,
|
||||
sessionId,
|
||||
projectHash,
|
||||
filePath: metaPath,
|
||||
startedAt: fileStat.birthtime.toISOString(),
|
||||
lastActivityAt: fileStat.mtime.getTime(),
|
||||
status: 'active',
|
||||
toolCallCount: 0,
|
||||
entryCount: 0,
|
||||
fileSize: fileStat.size,
|
||||
description,
|
||||
};
|
||||
|
||||
if (this.agentInfo.size >= MAX_TRACKED_AGENTS) {
|
||||
const oldestId = this.findOldestInactiveAgent();
|
||||
if (oldestId) this.removeAgent(oldestId);
|
||||
}
|
||||
|
||||
this.fileAgentContext.set(metaPath, { projectHash, sessionId });
|
||||
this.agentInfo.set(agentId, info);
|
||||
this.emit('subagent:discovered', info);
|
||||
this.resetIdleTimer(agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tail a file from a specific position
|
||||
*/
|
||||
|
||||
+47
-450
@@ -1,461 +1,58 @@
|
||||
# CLAUDE.md - Project Configuration
|
||||
# CLAUDE.md
|
||||
|
||||
## Setup
|
||||
Copy these files to your new project:
|
||||
- `CLAUDE.md` → project root
|
||||
- `.claude/settings.json` → `.claude/settings.json`
|
||||
<!--
|
||||
Generated by Codeman on [DATE]. This file is loaded into context at the
|
||||
start of every Claude Code session in this project.
|
||||
|
||||
Then update the Project Overview section below.
|
||||
Keep it short (target: under 200 lines). For each line ask: "would removing
|
||||
this cause Claude to make mistakes?" If not, cut it. Don't document what
|
||||
Claude can infer from the code itself (file layout, standard conventions,
|
||||
APIs) — bloat causes Claude to ignore the rules that matter.
|
||||
|
||||
---
|
||||
HTML comments like this one are stripped before loading, so fill-in notes
|
||||
cost no context. If this file grows too big, split into path-scoped rules
|
||||
in .claude/rules/*.md or import other files with @path/to/file syntax.
|
||||
-->
|
||||
|
||||
This file guides Claude Code when working in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
## Project Overview
|
||||
<!-- Update this section with project-specific details -->
|
||||
- **Project Name**: [PROJECT_NAME]
|
||||
- **Description**: [PROJECT_DESCRIPTION]
|
||||
- **Tech Stack**: [TECHNOLOGIES_USED]
|
||||
- **Last Updated**: [DATE]
|
||||
|
||||
---
|
||||
## Commands
|
||||
|
||||
<!-- List the exact commands Claude can't guess — fill in as the project
|
||||
takes shape, then delete this comment:
|
||||
|
||||
| Task | Command |
|
||||
|------|---------|
|
||||
| Dev server | `npm run dev` |
|
||||
| Test (single file) | `npm test -- test/<file>.test.ts` |
|
||||
| Lint | `npm run lint` |
|
||||
| Build | `npm run build` |
|
||||
-->
|
||||
|
||||
## Code Style
|
||||
|
||||
<!-- Only rules that differ from language/framework defaults, one line each:
|
||||
- Use 2-space indentation
|
||||
- ES modules only — never require()
|
||||
-->
|
||||
|
||||
## Workflow
|
||||
|
||||
- Full permissions are granted: read, write, edit, and execute without asking.
|
||||
- Commit after every meaningful change; never batch unrelated work.
|
||||
- Use conventional commits (`feat:` `fix:` `docs:` `refactor:` `test:` `chore:`); the message says what changed and why.
|
||||
- Run the tests and linter before declaring any task done.
|
||||
- Keep README and docs in sync with code changes.
|
||||
|
||||
## Codeman Environment
|
||||
|
||||
This session is managed by **Codeman** and runs within a tmux session.
|
||||
This session is managed by Codeman and runs inside tmux (`CODEMAN_MUX=1` confirms it).
|
||||
|
||||
**Important**: Check for `CODEMAN_MUX=1` environment variable to confirm.
|
||||
- Do NOT attempt to kill your own tmux session
|
||||
- The session persists across disconnects - your work is safe
|
||||
- Token usage, costs, and background tasks are tracked externally
|
||||
|
||||
---
|
||||
|
||||
## Work Principles
|
||||
|
||||
### Autonomy
|
||||
Full permissions granted. Act decisively without asking - read, write, edit, execute freely.
|
||||
|
||||
### Git Discipline
|
||||
- **Commit after every meaningful change** - never batch unrelated work
|
||||
- Use conventional commits: `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`
|
||||
- Commit message = what changed + why (not how)
|
||||
|
||||
### Documentation
|
||||
- Update README.md when adding features or changing setup
|
||||
- Update this file's session log after work sessions
|
||||
- Keep docs in sync with code changes
|
||||
|
||||
### Thinking
|
||||
Extended thinking is enabled. Use deep reasoning for complex architectural decisions, difficult bugs, and multi-file changes.
|
||||
|
||||
### Task Tracking (TodoWrite)
|
||||
**ALWAYS use TodoWrite** to track tasks. This is non-negotiable for anything beyond trivial single-step work.
|
||||
|
||||
**When to use TodoWrite:**
|
||||
- Multi-step tasks (3+ steps)
|
||||
- Bug fixes requiring investigation
|
||||
- Feature implementations
|
||||
- Any work where progress tracking helps
|
||||
- When the user provides multiple requests
|
||||
|
||||
**How to use it:**
|
||||
1. **Before starting**: Break down the work into discrete todos
|
||||
2. **During work**: Mark each todo `in_progress` before starting, `completed` when done
|
||||
3. **One at a time**: Only ONE todo should be `in_progress` at any moment
|
||||
4. **Immediately**: Mark todos complete the moment they're done - don't batch
|
||||
|
||||
**Why this matters:**
|
||||
- Gives the user visibility into your progress
|
||||
- Prevents forgetting tasks mid-work
|
||||
- Creates accountability checkpoints
|
||||
- Makes complex work manageable
|
||||
|
||||
**Example workflow:**
|
||||
```
|
||||
User: "Add user authentication with JWT"
|
||||
|
||||
→ TodoWrite:
|
||||
- [ ] Research existing auth patterns in codebase
|
||||
- [ ] Implement JWT token generation
|
||||
- [ ] Add login endpoint
|
||||
- [ ] Add token validation middleware
|
||||
- [ ] Add protected route example
|
||||
- [ ] Write tests
|
||||
|
||||
→ Mark "Research existing auth patterns" as in_progress
|
||||
→ Do the research
|
||||
→ Mark as completed, mark next as in_progress
|
||||
→ Continue until all done
|
||||
```
|
||||
|
||||
**Anti-patterns to avoid:**
|
||||
- Starting work without creating todos first
|
||||
- Having multiple todos `in_progress` simultaneously
|
||||
- Batching completions at the end
|
||||
- Skipping TodoWrite for "simple" multi-step tasks
|
||||
|
||||
---
|
||||
|
||||
## When to Use Agents
|
||||
|
||||
**Explore agent**: Codebase investigation, finding files, understanding architecture
|
||||
```
|
||||
"Use explore agent to find all authentication-related code"
|
||||
```
|
||||
|
||||
**Parallel agents**: Independent tasks that don't conflict
|
||||
```
|
||||
"Research auth, database, and API modules in parallel using separate agents"
|
||||
```
|
||||
|
||||
**Background execution**: Long-running operations (tests, builds)
|
||||
```
|
||||
"Run the test suite in the background while I continue"
|
||||
```
|
||||
|
||||
**Sequential chaining**: When second task depends on first
|
||||
```
|
||||
"Use code-reviewer to find issues, then use fixer to resolve them"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Planning Mode (Automatic)
|
||||
|
||||
**Automatically enter planning mode** when ANY of these conditions apply:
|
||||
- Multi-file changes (3+ files affected)
|
||||
- Architectural decisions
|
||||
- Unclear or evolving requirements
|
||||
- Risk mitigation on core systems
|
||||
- New feature implementation
|
||||
- Refactoring existing functionality
|
||||
|
||||
**Do NOT ask** whether to enter planning mode - just enter it when conditions are met.
|
||||
|
||||
Planning mode flow: read-only exploration → create plan → get approval → execute.
|
||||
|
||||
**Skip planning mode** only for:
|
||||
- Single-file bug fixes
|
||||
- Typo corrections
|
||||
- Simple config changes
|
||||
- Tasks with explicit step-by-step instructions from user
|
||||
|
||||
---
|
||||
|
||||
## Ralph Wiggum Loop (Autonomous Work Mode)
|
||||
|
||||
Ralph loops enable persistent, autonomous work on large tasks. When active, you continue iterating until completion criteria are met or the loop is cancelled.
|
||||
|
||||
### Starting a Ralph Loop
|
||||
- Start: `/ralph-loop:ralph-loop`
|
||||
- Cancel: `/ralph-loop:cancel-ralph`
|
||||
- Help: `/ralph-loop:help`
|
||||
|
||||
### Time-Aware Loops
|
||||
|
||||
When the user specifies a **minimum duration** (e.g., "optimize for 8 hours", "work on this for 2 hours"), the loop becomes time-aware:
|
||||
|
||||
**At loop start:**
|
||||
```bash
|
||||
# Record start time
|
||||
date +%s > /tmp/ralph_start_time
|
||||
echo "Loop started at $(date)"
|
||||
```
|
||||
|
||||
**Check elapsed time periodically:**
|
||||
```bash
|
||||
START=$(cat /tmp/ralph_start_time)
|
||||
NOW=$(date +%s)
|
||||
ELAPSED_HOURS=$(echo "scale=2; ($NOW - $START) / 3600" | bc)
|
||||
echo "Elapsed: $ELAPSED_HOURS hours"
|
||||
```
|
||||
|
||||
**Time-aware behavior:**
|
||||
1. Complete all primary tasks from the user's prompt
|
||||
2. After primary tasks done, check elapsed time
|
||||
3. If minimum duration NOT reached:
|
||||
- **Do NOT output completion phrase**
|
||||
- Self-generate additional related tasks
|
||||
- Continue working until minimum time elapsed
|
||||
4. Only output completion phrase when:
|
||||
- ALL primary tasks complete AND
|
||||
- Minimum duration reached (or exceeded)
|
||||
|
||||
**Self-generating additional tasks when time remains:**
|
||||
- Code optimization (performance, readability, DRY)
|
||||
- Test coverage improvements
|
||||
- Edge case handling
|
||||
- Error message improvements
|
||||
- Documentation gaps
|
||||
- Security hardening
|
||||
- Accessibility improvements
|
||||
- Code cleanup and dead code removal
|
||||
- Dependency updates
|
||||
- Type safety improvements
|
||||
|
||||
**Example time-aware prompt:**
|
||||
```
|
||||
"Optimize the API endpoints for the next 4 hours. Focus on performance first,
|
||||
then code quality. Minimum runtime: 4 hours."
|
||||
Completion phrase: <promise>TIME_COMPLETE</promise>
|
||||
```
|
||||
|
||||
**Time-aware loop behavior:**
|
||||
```
|
||||
[Start loop, record timestamp]
|
||||
[Complete primary optimization tasks - 2 hours elapsed]
|
||||
[Check time: 2/4 hours - NOT done yet]
|
||||
[Self-generate: "Add caching to database queries"]
|
||||
[Self-generate: "Optimize N+1 queries"]
|
||||
[Self-generate: "Add request batching"]
|
||||
[Continue working... 4.5 hours elapsed]
|
||||
[Check time: 4.5/4 hours - minimum reached]
|
||||
[All tasks complete, tests pass]
|
||||
<promise>TIME_COMPLETE</promise>
|
||||
```
|
||||
|
||||
### How You Know You're in a Ralph Loop
|
||||
|
||||
The user started the loop with a prompt containing:
|
||||
- Clear task requirements
|
||||
- A **completion phrase** (e.g., `<promise>COMPLETE</promise>`)
|
||||
- **Optional: minimum duration** (e.g., "for the next 4 hours")
|
||||
- Iteration limits (handled by the system)
|
||||
|
||||
Your job: Keep working until ALL requirements are verifiably done AND minimum time reached (if specified), then output the exact completion phrase.
|
||||
|
||||
### Core Behaviors During Ralph Loop
|
||||
|
||||
**1. Work Incrementally**
|
||||
- Complete one sub-task at a time
|
||||
- Verify it works before moving to the next
|
||||
- Don't try to do everything in one pass
|
||||
|
||||
**2. Commit Frequently**
|
||||
- Commit after each meaningful completion
|
||||
- Creates recovery points if something breaks
|
||||
- Shows progress in git history
|
||||
```
|
||||
git add . && git commit -m "feat(auth): add token refresh endpoint"
|
||||
```
|
||||
|
||||
**3. Self-Correct Relentlessly**
|
||||
```
|
||||
Loop:
|
||||
1. Implement/fix
|
||||
2. Run tests
|
||||
3. If tests fail → read error, fix, go to 1
|
||||
4. Run linter
|
||||
5. If lint errors → fix, go to 1
|
||||
6. Commit
|
||||
7. Continue to next task
|
||||
```
|
||||
|
||||
**4. Track Progress**
|
||||
Update the session log in this file as you complete tasks:
|
||||
```markdown
|
||||
| Date | Tasks Completed | Files Changed | Notes |
|
||||
|------|-----------------|---------------|-------|
|
||||
| YYYY-MM-DD | Add auth endpoint | auth.ts, routes.ts | Tests passing |
|
||||
```
|
||||
|
||||
**5. Use Git History When Stuck**
|
||||
If something isn't working:
|
||||
```bash
|
||||
git log --oneline -10
|
||||
git diff HEAD~1
|
||||
```
|
||||
See what you already tried. Don't repeat failed approaches.
|
||||
|
||||
**6. Completion Phrase = Contract**
|
||||
Only output the completion phrase (e.g., `<promise>COMPLETE</promise>`) when:
|
||||
- ALL requirements from the original prompt are done
|
||||
- ALL tests pass
|
||||
- ALL linting passes
|
||||
- Changes are committed
|
||||
|
||||
**Never output the completion phrase early.** The loop only ends when you say it's done.
|
||||
|
||||
### What Makes Good Completion Criteria
|
||||
|
||||
The user should provide criteria that are:
|
||||
- **Verifiable**: Tests pass, lint clean, build succeeds
|
||||
- **Measurable**: "5 endpoints", "all files in src/", "zero errors"
|
||||
- **Binary**: Done or not done, no ambiguity
|
||||
|
||||
If the original prompt has vague criteria, ask clarifying questions before starting heavy work.
|
||||
|
||||
### Self-Correction Pattern (Include in Your Work)
|
||||
|
||||
```
|
||||
FOR EACH TASK:
|
||||
1. Implement the change
|
||||
2. Run tests (npm test, pytest, go test, cargo test, etc.)
|
||||
- If fail → read error, fix, retry
|
||||
3. Run linter (npm run lint, ruff, golangci-lint, etc.)
|
||||
- If fail → fix, go to step 2
|
||||
4. Verify manually if needed
|
||||
5. Commit with descriptive message
|
||||
6. Update session log
|
||||
7. Move to next task
|
||||
|
||||
WHEN ALL TASKS DONE:
|
||||
1. Run full test suite
|
||||
2. Run full lint
|
||||
3. Verify build succeeds
|
||||
4. Review all changes: git diff main
|
||||
5. Only then output completion phrase
|
||||
```
|
||||
|
||||
### Example: How to Think During Ralph Loop
|
||||
|
||||
**Original prompt**: "Add CRUD endpoints for todos with validation"
|
||||
|
||||
**Your approach**:
|
||||
```
|
||||
Task breakdown:
|
||||
- [ ] GET /todos (list)
|
||||
- [ ] POST /todos (create with validation)
|
||||
- [ ] GET /todos/:id (single)
|
||||
- [ ] PUT /todos/:id (update with validation)
|
||||
- [ ] DELETE /todos/:id
|
||||
- [ ] Tests for all endpoints
|
||||
|
||||
Starting with GET /todos...
|
||||
[implement]
|
||||
[test - passes]
|
||||
[commit: "feat(todos): add GET /todos endpoint"]
|
||||
[update session log]
|
||||
|
||||
Moving to POST /todos...
|
||||
[implement]
|
||||
[test - fails: validation not working]
|
||||
[fix validation]
|
||||
[test - passes]
|
||||
[commit: "feat(todos): add POST /todos with validation"]
|
||||
[update session log]
|
||||
|
||||
...continue until all done...
|
||||
|
||||
Final verification:
|
||||
[npm test - all pass]
|
||||
[npm run lint - clean]
|
||||
[npm run build - succeeds]
|
||||
|
||||
<promise>COMPLETE</promise>
|
||||
```
|
||||
|
||||
### When to NOT Output Completion Phrase
|
||||
|
||||
- Tests are failing (even one)
|
||||
- Lint errors exist
|
||||
- Build is broken
|
||||
- You skipped a requirement
|
||||
- You're unsure if something works
|
||||
- **Minimum duration not reached** (for time-aware loops)
|
||||
|
||||
Instead: Fix the issue, verify, then complete. For time-aware loops: generate more tasks and keep improving until minimum time elapsed.
|
||||
|
||||
### RALPH_STATUS Block (Required During Ralph Loop)
|
||||
|
||||
At the **END of every response** during a Ralph Loop, output this structured status block:
|
||||
|
||||
```
|
||||
---RALPH_STATUS---
|
||||
STATUS: IN_PROGRESS | COMPLETE | BLOCKED
|
||||
TASKS_COMPLETED_THIS_LOOP: <number>
|
||||
FILES_MODIFIED: <number>
|
||||
TESTS_STATUS: PASSING | FAILING | NOT_RUN
|
||||
WORK_TYPE: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING
|
||||
EXIT_SIGNAL: false | true
|
||||
RECOMMENDATION: <one line summary of what to do next>
|
||||
---END_RALPH_STATUS---
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
- Output this block at the end of **every** response, no exceptions
|
||||
- Set `EXIT_SIGNAL` to `true` ONLY when ALL tasks are verifiably done
|
||||
- Set `STATUS` to `BLOCKED` when you need human intervention
|
||||
- Do NOT continue with busy work when `EXIT_SIGNAL` should be `true`
|
||||
- Do NOT forget the status block — it is required for loop tracking
|
||||
|
||||
### Testing Limits
|
||||
|
||||
- **LIMIT testing to ~20% of total effort** per loop
|
||||
- PRIORITIZE: Implementation > Documentation > Tests
|
||||
- Only write tests for NEW functionality
|
||||
- Do NOT refactor existing tests unless broken
|
||||
- Do NOT run tests repeatedly without implementing new features
|
||||
|
||||
### Exit Scenarios (When to Set EXIT_SIGNAL)
|
||||
|
||||
| Scenario | STATUS | EXIT_SIGNAL | Action |
|
||||
|----------|--------|-------------|--------|
|
||||
| All tasks completed, tests pass | COMPLETE | true | Output completion phrase |
|
||||
| No work remaining, specs done | COMPLETE | true | Output completion phrase |
|
||||
| Making normal progress | IN_PROGRESS | false | Continue to next task |
|
||||
| Test-only loop (no implementation) | IN_PROGRESS | false | Warn and shift to implementation |
|
||||
| Stuck on same error repeatedly | BLOCKED | false | Describe blocker, request help |
|
||||
| Needs human decision/intervention | BLOCKED | false | Describe what's needed |
|
||||
|
||||
**Anti-patterns to avoid:**
|
||||
- Setting `EXIT_SIGNAL: true` when tests are failing
|
||||
- Continuing to work when all tasks are genuinely done (busy work)
|
||||
- Running the same failing test repeatedly without changing approach
|
||||
- Adding features not in the original specifications
|
||||
- Refactoring working code instead of completing assigned tasks
|
||||
|
||||
---
|
||||
|
||||
## Code Standards
|
||||
|
||||
### Before Writing
|
||||
- Read existing code in the area you're modifying
|
||||
- Follow existing patterns and conventions
|
||||
- Check for similar implementations to reference
|
||||
|
||||
### During Implementation
|
||||
- Keep changes focused and minimal
|
||||
- Don't over-engineer
|
||||
- Write tests for new functionality
|
||||
|
||||
### After Implementation
|
||||
- Run tests
|
||||
- Update docs if needed
|
||||
- Commit with descriptive message
|
||||
|
||||
---
|
||||
|
||||
## Hooks Awareness
|
||||
|
||||
This project may have hooks that auto-format code after writes or validate operations. If a tool call behaves unexpectedly, hooks are likely the cause. Continue working - they're intentional.
|
||||
|
||||
---
|
||||
|
||||
## Session Log
|
||||
|
||||
| Date | Tasks Completed | Files Changed | Notes |
|
||||
|------|-----------------|---------------|-------|
|
||||
| [DATE] | Project created | CLAUDE.md | Initial setup |
|
||||
|
||||
---
|
||||
|
||||
## Current Task Queue
|
||||
|
||||
### Active Ralph Loop
|
||||
**Status**: Not Active
|
||||
**Completion Phrase**: -
|
||||
|
||||
### Pending Tasks
|
||||
- [ ] <!-- Add tasks here -->
|
||||
|
||||
---
|
||||
|
||||
## Implementation Plans
|
||||
|
||||
<!-- Document plans before major implementations -->
|
||||
|
||||
---
|
||||
|
||||
## Notes & Decisions
|
||||
|
||||
<!-- Track important decisions and context -->
|
||||
- NEVER kill your own session: no `tmux kill-session`, `pkill tmux`, or `pkill claude`.
|
||||
- The session persists across disconnects — your work is safe.
|
||||
- Hooks may auto-format or validate after writes; unexpected tool behavior usually means a hook ran. Keep working.
|
||||
|
||||
@@ -15,18 +15,17 @@ import { fileURLToPath } from 'node:url';
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const BUNDLED_TEMPLATE_PATH = join(__dirname, 'case-template.md');
|
||||
|
||||
const MINIMAL_FALLBACK = `# CLAUDE.md - Project Configuration
|
||||
const MINIMAL_FALLBACK = `# CLAUDE.md
|
||||
|
||||
<!-- Generated by Codeman on [DATE]. Add the commands, code style rules, and
|
||||
workflow notes Claude can't infer from the code. Keep it short. -->
|
||||
|
||||
This file guides Claude Code when working in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
## Project Overview
|
||||
- **Project Name**: [PROJECT_NAME]
|
||||
- **Description**: [PROJECT_DESCRIPTION]
|
||||
- **Last Updated**: [DATE]
|
||||
|
||||
## Session Log
|
||||
|
||||
| Date | Tasks Completed | Files Changed | Notes |
|
||||
|------|-----------------|---------------|-------|
|
||||
| [DATE] | Project created | CLAUDE.md | Initial setup |
|
||||
`;
|
||||
|
||||
/**
|
||||
|
||||
+9
-1
@@ -426,7 +426,12 @@ export function formatPaneSnapshot(
|
||||
geometry: { cols: number; rows: number; cursorX: number; cursorY: number }
|
||||
): string {
|
||||
const cols = Math.max(1, geometry.cols);
|
||||
const paintCols = Math.max(1, cols - 1);
|
||||
// Paint the full pane width. Earlier this dropped the rightmost column
|
||||
// (cols - 1) out of caution about last-column autowrap, but every painted
|
||||
// row is immediately followed by an absolute cursor-position CSI (the next
|
||||
// row's `\x1b[r;1H`, or the final cursor move), which cancels xterm's
|
||||
// pending-wrap state before any further glyph — so the last column is safe.
|
||||
const paintCols = cols;
|
||||
const rows = Math.max(1, geometry.rows);
|
||||
const parts: string[] = [];
|
||||
for (let row = 0; row < Math.min(lines.length, rows); row++) {
|
||||
@@ -857,6 +862,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
`export CODEMAN_SESSION_ID=${sessionId}`,
|
||||
`export CODEMAN_MUX_NAME=${muxName}`,
|
||||
`export CODEMAN_API_URL=${process.env.CODEMAN_API_URL || 'http://localhost:3000'}`,
|
||||
// Path only (not the secret value): hook curl commands cat the file at
|
||||
// execution time, so the COD-54 hook secret stays off the command line.
|
||||
`export CODEMAN_HOOK_SECRET_FILE="${dataPath('hook-secret')}"`,
|
||||
];
|
||||
// Only unset CLAUDECODE for Claude sessions
|
||||
if (mode === 'claude') exports.splice(2, 0, 'unset CLAUDECODE');
|
||||
|
||||
@@ -67,3 +67,4 @@ export * from './push.js';
|
||||
export * from './plan.js';
|
||||
export * from './orchestrator.js';
|
||||
export * from './update.js';
|
||||
export * from './workflow-run.js';
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
*/
|
||||
|
||||
import type { RespawnConfig } from './respawn.js';
|
||||
import type { AttachmentDetectedType } from './tools.js';
|
||||
|
||||
/** Status of a Claude session */
|
||||
export type SessionStatus = 'idle' | 'busy' | 'stopped' | 'error';
|
||||
@@ -101,6 +102,40 @@ export interface SessionConfig {
|
||||
*/
|
||||
export type SessionColor = 'default' | 'red' | 'orange' | 'yellow' | 'green' | 'blue' | 'purple' | 'pink';
|
||||
|
||||
export type SessionAttachmentHistorySource = 'detected' | 'external';
|
||||
|
||||
/**
|
||||
* Session-scoped attachment history entry.
|
||||
*
|
||||
* `externalPath` is server-private. It may be present in the internal persisted
|
||||
* history copy, but API-bound session state must sanitize it before returning
|
||||
* to the browser.
|
||||
*/
|
||||
export interface SessionAttachmentHistoryItem {
|
||||
/** Stable history identity used for dedupe and list rendering */
|
||||
id: string;
|
||||
/** Codeman session ID this item belongs to */
|
||||
sessionId: string;
|
||||
/** Display filename */
|
||||
fileName: string;
|
||||
/** Lowercase extension without a leading dot */
|
||||
extension: string;
|
||||
/** Viewer category used by the web UI */
|
||||
attachmentType: AttachmentDetectedType;
|
||||
/** File size in bytes */
|
||||
size: number;
|
||||
/** Last modified timestamp in milliseconds, if known */
|
||||
mtimeMs: number;
|
||||
/** Last time this attachment was seen or explicitly published */
|
||||
timestamp: number;
|
||||
/** How the attachment entered the session */
|
||||
source: SessionAttachmentHistorySource;
|
||||
/** Workspace-relative path for detected session files */
|
||||
relativePath?: string;
|
||||
/** Server-private absolute path for explicitly published external files */
|
||||
externalPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current state of a session
|
||||
*/
|
||||
@@ -133,6 +168,10 @@ export interface SessionState {
|
||||
autoCompactThreshold?: number;
|
||||
/** Auto-compact prompt */
|
||||
autoCompactPrompt?: string;
|
||||
/** Auto-resume on usage limit enabled */
|
||||
autoResumeEnabled?: boolean;
|
||||
/** Pending usage-limit auto-resume fire time (epoch ms), if armed */
|
||||
autoResumeAt?: number;
|
||||
/** Image watcher enabled for this session */
|
||||
imageWatcherEnabled?: boolean;
|
||||
/** Total cost in USD */
|
||||
@@ -179,6 +218,8 @@ export interface SessionState {
|
||||
resumeSessionId?: string;
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
effort?: EffortLevel;
|
||||
/** Sanitized per-session attachment history. */
|
||||
attachmentHistory?: SessionAttachmentHistoryItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+37
-1
@@ -7,13 +7,14 @@
|
||||
* - ActiveBashTool — a live bash command with extracted file paths and status
|
||||
* - ActiveBashToolStatus — 'running' | 'completed'
|
||||
* - ImageDetectedEvent — screenshot/image file detection trigger for UI popup
|
||||
* - AttachmentDetectedEvent — document/image file detection trigger for attachment cards
|
||||
*
|
||||
* Cross-domain relationships:
|
||||
* - ActiveBashTool.sessionId links to SessionState.id (session domain)
|
||||
* - ImageDetectedEvent.sessionId links to SessionState.id (session domain)
|
||||
*
|
||||
* Both types are in-memory only (not persisted). Broadcast via SSE events
|
||||
* `subagent:tool_call` and `image:detected`. Parsed by BashToolParser
|
||||
* `subagent:tool_call`, `image:detected`, and `attachment:detected`. Parsed by BashToolParser
|
||||
* (`src/bash-tool-parser.ts`).
|
||||
*/
|
||||
|
||||
@@ -61,3 +62,38 @@ export interface ImageDetectedEvent {
|
||||
/** File size in bytes */
|
||||
size: number;
|
||||
}
|
||||
|
||||
export type AttachmentDetectedType = 'image' | 'pdf' | 'document' | 'presentation' | 'markdown' | 'text';
|
||||
|
||||
/**
|
||||
* Event emitted when a new previewable attachment file is detected in a session's
|
||||
* working directory. Used to render a compact attachment card in the web UI.
|
||||
*/
|
||||
export interface AttachmentDetectedEvent {
|
||||
/** Codeman session ID where the attachment was detected */
|
||||
sessionId: string;
|
||||
/** Full path to the detected attachment file */
|
||||
filePath: string;
|
||||
/** Path relative to the session's working directory (for file-raw/file-preview endpoints) */
|
||||
relativePath: string;
|
||||
/** Attachment file name (basename) */
|
||||
fileName: string;
|
||||
/** Lowercase extension without a leading dot */
|
||||
extension: string;
|
||||
/** Viewer category used by the web UI */
|
||||
attachmentType: AttachmentDetectedType;
|
||||
/** Timestamp when the attachment was detected */
|
||||
timestamp: number;
|
||||
/** File size in bytes */
|
||||
size: number;
|
||||
/** Registered attachment id for explicit live external attachments */
|
||||
attachmentId?: string;
|
||||
/** Source of the attachment card request */
|
||||
source?: 'detected' | 'external';
|
||||
/** Raw file route for explicit attachments */
|
||||
rawUrl?: string;
|
||||
/** Inline preview route for explicit attachments */
|
||||
previewUrl?: string;
|
||||
/** First-page thumbnail route for card previews */
|
||||
thumbnailUrl?: string;
|
||||
}
|
||||
|
||||
+6
-2
@@ -13,8 +13,12 @@
|
||||
* @module types/update
|
||||
*/
|
||||
|
||||
/** Which init system supervises the running server (decides how we restart it). */
|
||||
export type SupervisorKind = 'systemd' | 'launchd' | 'none';
|
||||
/**
|
||||
* Which init system supervises the running server (decides how we restart it).
|
||||
* `launchd-daemon` = a KeepAlive system-level LaunchDaemon (headless Macs, no GUI
|
||||
* login): restart works by killing the server and letting launchd respawn it.
|
||||
*/
|
||||
export type SupervisorKind = 'systemd' | 'launchd' | 'launchd-daemon' | 'none';
|
||||
|
||||
/** How Codeman was installed — only `git` installs can self-update in place. */
|
||||
export type InstallKind = 'git' | 'npm' | 'unknown';
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* @fileoverview Types for ultracode / Workflow-tool run visualization.
|
||||
*
|
||||
* A Workflow run persists its state to
|
||||
* `~/.claude/projects/<projHash>/<sessionUuid>/workflows/wf_<runId>.json`
|
||||
* (a sibling of the deeper `subagents/workflows/wf_<runId>/agent-*.jsonl`
|
||||
* transcript tree that subagent-watcher tracks). This file is the single source
|
||||
* for the master-detail "working agents" view: a run's tasks/phases on the LEFT
|
||||
* and per-agent stats (tokens burned, tool calls) on the RIGHT.
|
||||
*
|
||||
* Field presence is STATE-DRIVEN and verified against real runs on disk:
|
||||
* - state 'start' (queued): no agentId/tokens/toolCalls/startedAt/durationMs/...
|
||||
* - state 'progress' (running): has agentId/tokens/toolCalls, no durationMs/resultPreview
|
||||
* - state 'done' (finished): all fields, incl. durationMs/resultPreview
|
||||
* Absent fields are genuinely ABSENT (never explicit null) — use `?:`, not null.
|
||||
*
|
||||
* @module types/workflow-run
|
||||
*/
|
||||
|
||||
/** One declared phase of a run (from the run JSON's top-level `phases[]`, 0-indexed). */
|
||||
export interface WorkflowRunPhase {
|
||||
/** Phase title; equals each member agent's `phaseTitle`. Always present. */
|
||||
title: string;
|
||||
/** Human description of the phase. Always present in `phases[]`. */
|
||||
detail: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent slot in a run, derived from `workflowProgress[]` entries where
|
||||
* `type === 'workflow_agent'`. Optional fields are absent until the agent
|
||||
* reaches the relevant lifecycle state (see module doc).
|
||||
*/
|
||||
export interface WorkflowAgentInfo {
|
||||
/** 1-based stable slot index, unique within the run. Always present. */
|
||||
index: number;
|
||||
/** Agent label, e.g. "probe:dompurify-config". Always present. */
|
||||
label: string;
|
||||
/** 1-based phase number; join via `run.phases[phaseIndex - 1]`. Always present. */
|
||||
phaseIndex: number;
|
||||
/** Phase title (=== run.phases[phaseIndex-1].title). Always present. */
|
||||
phaseTitle: string;
|
||||
/** Model id, e.g. "claude-opus-4-8[1m]". Always present. */
|
||||
model: string;
|
||||
/** Lifecycle state. Real on-disk values: 'start' | 'progress' | 'done'. Open union. */
|
||||
state: 'start' | 'progress' | 'done' | (string & {});
|
||||
/** Epoch ms the slot was queued. Always present. */
|
||||
queuedAt?: number;
|
||||
/** Epoch ms of the last progress tick. Always present once any progress occurs. */
|
||||
lastProgressAt?: number;
|
||||
/** Truncated prompt the agent was given. Always present. */
|
||||
promptPreview?: string;
|
||||
/**
|
||||
* Globally-unique agent id; equals the `agent-<agentId>.jsonl` transcript stem
|
||||
* (the Phase-4 correlation key). ABSENT while state === 'start'.
|
||||
*/
|
||||
agentId?: string;
|
||||
/** Epoch ms the agent began. Absent while 'start'. */
|
||||
startedAt?: number;
|
||||
/** Attempt counter. Absent while 'start'. */
|
||||
attempt?: number;
|
||||
/** Tokens burned so far (RIGHT pane). Absent while 'start'. */
|
||||
tokens?: number;
|
||||
/** Tool calls made so far (RIGHT pane). Absent while 'start'. */
|
||||
toolCalls?: number;
|
||||
/** Name of the most recent tool. Present for progress/done (occasionally absent). */
|
||||
lastToolName?: string;
|
||||
/** Short summary of the most recent tool call. May be absent even when 'done'. */
|
||||
lastToolSummary?: string;
|
||||
/** Total run time (ms). Present ONLY when 'done' — the live-vs-finished discriminator. */
|
||||
durationMs?: number;
|
||||
/** Truncated final result. Present ONLY when 'done'. */
|
||||
resultPreview?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run-level info shipped to the browser.
|
||||
*
|
||||
* IMPORTANT: the on-disk JSON also carries `script` (15–660KB of embedded JS),
|
||||
* `scriptPath`, `result`, and `logs`. The watcher STRIPS all four before the
|
||||
* object is ever cached/broadcast — never let them reach SSE/getLightState/route.
|
||||
*/
|
||||
export interface WorkflowRunInfo {
|
||||
/** Run id (=== the wf_<runId>.json filename stem). Always present. */
|
||||
runId: string;
|
||||
/** Workflow name from `meta.name`. Always present. */
|
||||
workflowName?: string;
|
||||
/**
|
||||
* Run status. Real on-disk values seen: 'completed' | 'killed'.
|
||||
* 'running' | 'failed' are inferred (parse defensively; keep open union).
|
||||
*/
|
||||
status?: 'completed' | 'killed' | 'running' | 'failed' | (string & {});
|
||||
/** Concise human description (best LEFT-pane label). Always present. */
|
||||
summary?: string;
|
||||
/** Total agent slots, INCLUDING not-yet-started 'start' agents. */
|
||||
agentCount?: number;
|
||||
/** Total tokens across the run (partial mid-run). */
|
||||
totalTokens?: number;
|
||||
/** Total tool calls across the run (partial mid-run). */
|
||||
totalToolCalls?: number;
|
||||
/** Total run duration (ms). */
|
||||
durationMs?: number;
|
||||
/** Run start time (epoch MILLIS). */
|
||||
startTime?: number;
|
||||
/** ISO end/write timestamp. */
|
||||
timestamp?: string;
|
||||
/** Default model for the run. */
|
||||
defaultModel?: string;
|
||||
/** Background-task id that owns the run. */
|
||||
taskId?: string;
|
||||
/** Declared phases (0-indexed). */
|
||||
phases: WorkflowRunPhase[];
|
||||
/** Agents, derived from `workflowProgress` filtered to `type === 'workflow_agent'`. */
|
||||
agents: WorkflowAgentInfo[];
|
||||
/** Error message, present when status is 'killed'/'failed'. */
|
||||
error?: string;
|
||||
|
||||
// ----- Watcher-derived (NOT in the JSON body — captured from the file path) -----
|
||||
/** `<sessionUuid>` path segment (for per-session scoping). */
|
||||
sessionUuid: string;
|
||||
/** `<projHash>` path segment. */
|
||||
projectHash: string;
|
||||
/**
|
||||
* Most recent activity (epoch ms): max agent `lastProgressAt`, else `startTime`.
|
||||
* Drives recency filtering/sorting so finished long runs still surface.
|
||||
*/
|
||||
lastActivityAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight run projection (no `agents[]`) for the LEFT-pane list and the
|
||||
* getLightState reconnect snapshot. A full run with 28 agents serializes to
|
||||
* ~36KB; the snapshot ships dozens of runs, so it carries summaries only and the
|
||||
* RIGHT pane fetches the full run (`GET /api/workflows/:runId`) on selection.
|
||||
*/
|
||||
export type WorkflowRunSummary = Omit<WorkflowRunInfo, 'agents'>;
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* @fileoverview Pure detection of Claude Code usage-limit pause messages.
|
||||
*
|
||||
* When a Claude subscription limit (5-hour rolling window, weekly, Opus weekly,
|
||||
* or extra-usage balance) is hit, the Claude Code TUI stops working and prints a
|
||||
* status line with the reset time. These helpers detect that state in cleaned
|
||||
* (ANSI-stripped) terminal output and parse the reset time, so the session
|
||||
* auto-resume feature (SessionAutoOps) can schedule a "continue" nudge.
|
||||
*
|
||||
* Message shapes covered (observed across Claude Code 1.0.x–2.1.x, 2025–2026):
|
||||
* - `5-hour limit reached ∙ resets 8pm` (v1.0.109+ footer)
|
||||
* - `Session limit reached ∙ resets 8pm`
|
||||
* - `Weekly limit reached ∙ resets 6pm`
|
||||
* - `Opus weekly limit reached ∙ resets Oct 6, 1pm`
|
||||
* - `Limit reached · resets 1pm (America/Chicago) · /upgrade to Max…` (v2.0.55+)
|
||||
* - `You've hit your limit · resets 1:40pm (America/New_York)` (v2.1.x)
|
||||
* - `You've hit your weekly limit · resets Mon 12:00am`
|
||||
* - `You've hit your limit · resets May 5 at 9pm (America/New_York)`
|
||||
* - `You're out of extra usage · resets 1pm (America/Los_Angeles)`
|
||||
* - `Claude usage limit reached. Your limit will reset at 2pm (America/New_York)` (v1.0.x inline)
|
||||
* - `Claude AI usage limit reached|1755309600` (raw API, epoch seconds)
|
||||
*
|
||||
* Deliberately conservative: a limit phrase WITHOUT a parseable reset time is
|
||||
* ignored (returns null) so ordinary conversation text mentioning "limit
|
||||
* reached" can't arm the scheduler. The downstream retry loop (re-detection
|
||||
* after each resume attempt) compensates for any parsing imprecision.
|
||||
*
|
||||
* All functions are pure (caller passes `now`) for testability.
|
||||
*
|
||||
* @module usage-limit-patterns
|
||||
*/
|
||||
|
||||
/** Result of scanning terminal output for a usage-limit pause. */
|
||||
export interface UsageLimitDetection {
|
||||
/**
|
||||
* Epoch ms when the limit resets. May be in the past when the matched
|
||||
* message is stale (caller should treat past values as "retry soon").
|
||||
*/
|
||||
resetAt: number;
|
||||
/** Matched message snippet (for logging and UI). */
|
||||
matched: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit phrases that indicate Claude stopped on a usage limit.
|
||||
* `\blimit reached` covers all "<X> limit reached" footer variants.
|
||||
*/
|
||||
const LIMIT_PHRASE_PATTERN =
|
||||
/(?:\blimit\s+reached\b|you'?ve\s+hit\s+your\s+(?:\w+\s+)?limit\b|you'?re\s+out\s+of\s+extra\s+usage\b)/gi;
|
||||
|
||||
/**
|
||||
* Reset-time spec following a limit phrase. Captures:
|
||||
* 1 month (weekly resets >1 day out: "Oct 6, 1pm" / "May 5 at 9pm")
|
||||
* 2 day-of-month
|
||||
* 3 day-of-week ("Mon 12:00am")
|
||||
* 4 hour (12h) 5 minutes 6 am/pm 7 IANA timezone in parens (optional)
|
||||
* `resets?` + optional `at` also covers the v1.0.x "will reset at 2pm" form.
|
||||
*/
|
||||
const RESET_TIME_PATTERN =
|
||||
/\bresets?\s+(?:at\s+)?(?:(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+(\d{1,2})(?:\s*,\s*|\s+at\s+)|(sun|mon|tue|wed|thu|fri|sat)[a-z]*\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^()\n]{1,64})\))?/i;
|
||||
|
||||
/** Raw API form: `Claude AI usage limit reached|1755309600` (epoch seconds). */
|
||||
const EPOCH_LIMIT_PATTERN = /\busage\s+limit\s+reached\|(\d{9,11})\b/gi;
|
||||
|
||||
/** How far after a limit phrase the reset-time spec may appear (chars). */
|
||||
const RESET_TIME_WINDOW = 160;
|
||||
|
||||
/** Parsed reset spec must not be further out than this (weekly max ≈ 7 days). */
|
||||
const MAX_RESET_HORIZON_MS = 8 * 24 * 60 * 60 * 1000;
|
||||
|
||||
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
|
||||
const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Current UTC offset of an IANA timezone in ms, or null if unresolvable
|
||||
* (e.g. the `(Etc/Unknown)` failure variant Claude Code can print).
|
||||
* DST transitions inside the wait window can skew the result by an hour;
|
||||
* the auto-resume retry loop absorbs that.
|
||||
*/
|
||||
function zoneOffsetMs(timeZone: string, at: number): number | null {
|
||||
try {
|
||||
const dtf = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' });
|
||||
const name = dtf.formatToParts(at).find((p) => p.type === 'timeZoneName')?.value;
|
||||
if (!name) return null;
|
||||
const m = /^GMT(?:([+-])(\d{1,2})(?::(\d{2}))?)?$/.exec(name);
|
||||
if (!m) return null;
|
||||
if (!m[1]) return 0; // plain "GMT"
|
||||
const sign = m[1] === '-' ? -1 : 1;
|
||||
return sign * (parseInt(m[2], 10) * 60 + (m[3] ? parseInt(m[3], 10) : 0)) * 60_000;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface ResetSpec {
|
||||
month?: number; // 0-11
|
||||
dayOfMonth?: number; // 1-31
|
||||
dayOfWeek?: number; // 0-6 (Sun-Sat)
|
||||
hour: number; // 0-23
|
||||
minute: number; // 0-59
|
||||
timeZone?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the epoch ms for a parsed reset spec. Times are wall-clock in the
|
||||
* given IANA timezone when present (and resolvable), otherwise server-local —
|
||||
* Claude CLI runs on the same host as Codeman, so local time is the right
|
||||
* default. Returns null when the spec is implausible (> ~8 days out).
|
||||
*/
|
||||
function resolveResetSpec(spec: ResetSpec, now: number): number | null {
|
||||
const offset = spec.timeZone ? zoneOffsetMs(spec.timeZone, now) : null;
|
||||
|
||||
// Wall-clock view of "now": shifted-UTC when a zone offset is known,
|
||||
// server-local otherwise. Read/build components with the matching API.
|
||||
const useZone = offset !== null;
|
||||
const wallNow = useZone ? new Date(now + offset) : new Date(now);
|
||||
const get = {
|
||||
year: () => (useZone ? wallNow.getUTCFullYear() : wallNow.getFullYear()),
|
||||
month: () => (useZone ? wallNow.getUTCMonth() : wallNow.getMonth()),
|
||||
date: () => (useZone ? wallNow.getUTCDate() : wallNow.getDate()),
|
||||
day: () => (useZone ? wallNow.getUTCDay() : wallNow.getDay()),
|
||||
};
|
||||
const build = (y: number, mo: number, d: number): number => {
|
||||
const wall = useZone
|
||||
? Date.UTC(y, mo, d, spec.hour, spec.minute)
|
||||
: new Date(y, mo, d, spec.hour, spec.minute).getTime();
|
||||
return useZone ? wall - offset : wall;
|
||||
};
|
||||
|
||||
let ts: number;
|
||||
if (spec.month !== undefined && spec.dayOfMonth !== undefined) {
|
||||
// Explicit date ("Oct 6, 1pm"). More than 2 days in the past → assume year
|
||||
// rollover (message seen near New Year); slightly past → stale, keep as-is.
|
||||
ts = build(get.year(), spec.month, spec.dayOfMonth);
|
||||
if (ts < now - 2 * DAY_MS) {
|
||||
ts = build(get.year() + 1, spec.month, spec.dayOfMonth);
|
||||
}
|
||||
} else if (spec.dayOfWeek !== undefined) {
|
||||
// Day-of-week ("Mon 12:00am") → next occurrence.
|
||||
const delta = (spec.dayOfWeek - get.day() + 7) % 7;
|
||||
ts = build(get.year(), get.month(), get.date() + delta);
|
||||
if (ts <= now) ts += 7 * DAY_MS;
|
||||
} else {
|
||||
// Time-only ("resets 8pm") → next occurrence within 24h.
|
||||
ts = build(get.year(), get.month(), get.date());
|
||||
if (ts <= now) ts += DAY_MS;
|
||||
}
|
||||
|
||||
if (ts > now + MAX_RESET_HORIZON_MS) return null;
|
||||
return ts;
|
||||
}
|
||||
|
||||
/** Parse the reset-time spec found within `window`, or null. */
|
||||
function parseResetTime(window: string, now: number): number | null {
|
||||
const m = RESET_TIME_PATTERN.exec(window);
|
||||
if (!m) return null;
|
||||
|
||||
const hour12 = parseInt(m[4], 10);
|
||||
const minute = m[5] ? parseInt(m[5], 10) : 0;
|
||||
if (hour12 < 1 || hour12 > 12 || minute > 59) return null;
|
||||
const pm = m[6].toLowerCase() === 'pm';
|
||||
const hour = (hour12 % 12) + (pm ? 12 : 0);
|
||||
|
||||
const spec: ResetSpec = { hour, minute };
|
||||
if (m[1] && m[2]) {
|
||||
spec.month = MONTHS.indexOf(m[1].toLowerCase());
|
||||
spec.dayOfMonth = parseInt(m[2], 10);
|
||||
if (spec.dayOfMonth < 1 || spec.dayOfMonth > 31) return null;
|
||||
} else if (m[3]) {
|
||||
spec.dayOfWeek = WEEKDAYS.indexOf(m[3].toLowerCase());
|
||||
}
|
||||
if (m[7]) spec.timeZone = m[7].trim();
|
||||
|
||||
return resolveResetSpec(spec, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan cleaned (ANSI-stripped) terminal output for a usage-limit pause message
|
||||
* with a parseable reset time. Returns the LAST parseable occurrence in the
|
||||
* chunk (most recent on screen), or null when none is found.
|
||||
*/
|
||||
export function detectUsageLimitPause(cleanData: string, now: number = Date.now()): UsageLimitDetection | null {
|
||||
if (!cleanData || !/limit|extra usage/i.test(cleanData)) return null;
|
||||
|
||||
let result: UsageLimitDetection | null = null;
|
||||
|
||||
// Raw API epoch form
|
||||
EPOCH_LIMIT_PATTERN.lastIndex = 0;
|
||||
let em: RegExpExecArray | null;
|
||||
while ((em = EPOCH_LIMIT_PATTERN.exec(cleanData)) !== null) {
|
||||
const resetAt = parseInt(em[1], 10) * 1000;
|
||||
if (resetAt > now + MAX_RESET_HORIZON_MS) continue;
|
||||
result = { resetAt, matched: em[0] };
|
||||
}
|
||||
|
||||
// TUI phrase + "resets <time>" forms
|
||||
LIMIT_PHRASE_PATTERN.lastIndex = 0;
|
||||
let pm: RegExpExecArray | null;
|
||||
while ((pm = LIMIT_PHRASE_PATTERN.exec(cleanData)) !== null) {
|
||||
const window = cleanData.slice(pm.index, pm.index + RESET_TIME_WINDOW);
|
||||
const resetAt = parseResetTime(window, now);
|
||||
if (resetAt !== null) {
|
||||
result = { resetAt, matched: window.slice(0, 80).trim() };
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* @fileoverview Pure parsing + formatting of Claude Code statusline telemetry.
|
||||
*
|
||||
* Claude Code (v2.1.80+) pipes a JSON blob to a configured `statusLine.command`
|
||||
* on each render. On Pro/Max subscriptions that blob carries a `rate_limits`
|
||||
* object with the 5-hour rolling and 7-day weekly plan windows. The
|
||||
* Codeman-managed statusLine exporter (see `hooks-config.generateStatusLineCommand`)
|
||||
* POSTs that blob to `/api/status-telemetry`; these helpers normalize the subset
|
||||
* Codeman displays and format the compact in-terminal footer string.
|
||||
*
|
||||
* Confirmed schema (empirically captured, CC 2.1.177, Claude Max — see
|
||||
* `docs/usage-limits-display-plan.md`):
|
||||
* rate_limits.{five_hour,seven_day}.{used_percentage: number 0-100,
|
||||
* resets_at: number EPOCH-SECONDS}
|
||||
* Only those two windows exist (no Opus-weekly field). `rate_limits` is absent
|
||||
* before the first API response and for non-subscriber auth — both yield null.
|
||||
*
|
||||
* All functions are pure for testability. See `test/usage-telemetry.test.ts`.
|
||||
*
|
||||
* @module usage-telemetry
|
||||
*/
|
||||
|
||||
/** A single normalized plan-usage window. */
|
||||
export interface UsageWindow {
|
||||
/** Percent of the window consumed, 0–100. */
|
||||
usedPercentage: number;
|
||||
/** Epoch MILLISECONDS when the window resets (statusline reports seconds). */
|
||||
resetAt: number;
|
||||
}
|
||||
|
||||
/** Normalized telemetry Codeman broadcasts to the UI. */
|
||||
export interface StatusTelemetry {
|
||||
fiveHour?: UsageWindow;
|
||||
sevenDay?: UsageWindow;
|
||||
/** Context-window percent used, 0–100 (bonus field from the same payload). */
|
||||
contextUsedPercentage?: number;
|
||||
/** Session cost in USD (bonus field). */
|
||||
costUsd?: number;
|
||||
/** Model display name, e.g. "Opus 4.8 (1M context)" (bonus field). */
|
||||
modelDisplayName?: string;
|
||||
}
|
||||
|
||||
/** Raw subset of the statusline stdin JSON (snake_case, as Claude emits it). */
|
||||
export interface RawStatuslinePayload {
|
||||
rate_limits?: {
|
||||
five_hour?: { used_percentage?: number; resets_at?: number };
|
||||
seven_day?: { used_percentage?: number; resets_at?: number };
|
||||
};
|
||||
context_window?: { used_percentage?: number; total_input_tokens?: number; total_output_tokens?: number };
|
||||
cost?: { total_cost_usd?: number };
|
||||
model?: { display_name?: string };
|
||||
}
|
||||
|
||||
function clampPct(n: number): number {
|
||||
if (!Number.isFinite(n)) return 0;
|
||||
return Math.max(0, Math.min(100, n));
|
||||
}
|
||||
|
||||
function parseWindow(w?: { used_percentage?: number; resets_at?: number }): UsageWindow | undefined {
|
||||
if (!w || typeof w.used_percentage !== 'number' || typeof w.resets_at !== 'number') return undefined;
|
||||
if (!Number.isFinite(w.resets_at) || w.resets_at <= 0) return undefined;
|
||||
return { usedPercentage: clampPct(w.used_percentage), resetAt: Math.round(w.resets_at * 1000) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a raw statusline payload to the telemetry Codeman displays. Returns
|
||||
* null when there is no plan-limit data to show (pre-first-response or a
|
||||
* non-subscriber account) so the caller can skip broadcasting.
|
||||
*/
|
||||
export function parseStatusTelemetry(data: RawStatuslinePayload | undefined): StatusTelemetry | null {
|
||||
if (!data) return null;
|
||||
const fiveHour = parseWindow(data.rate_limits?.five_hour);
|
||||
const sevenDay = parseWindow(data.rate_limits?.seven_day);
|
||||
if (!fiveHour && !sevenDay) return null;
|
||||
|
||||
const t: StatusTelemetry = {};
|
||||
if (fiveHour) t.fiveHour = fiveHour;
|
||||
if (sevenDay) t.sevenDay = sevenDay;
|
||||
if (typeof data.context_window?.used_percentage === 'number') {
|
||||
t.contextUsedPercentage = clampPct(data.context_window.used_percentage);
|
||||
}
|
||||
if (typeof data.cost?.total_cost_usd === 'number' && Number.isFinite(data.cost.total_cost_usd)) {
|
||||
t.costUsd = data.cost.total_cost_usd;
|
||||
}
|
||||
if (typeof data.model?.display_name === 'string' && data.model.display_name) {
|
||||
t.modelDisplayName = data.model.display_name.slice(0, 60);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current-session status for the in-terminal statusline footer. This is the
|
||||
* "status of the current session" the user sees in Claude's footer — distinct
|
||||
* from the account-wide plan limits, which live ONLY in the Codeman header chip.
|
||||
*/
|
||||
export interface SessionStatus {
|
||||
modelDisplayName?: string;
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
contextUsedPercentage?: number;
|
||||
}
|
||||
|
||||
/** Group a non-negative integer with thousands separators: 562411 → "562,411". */
|
||||
function withCommas(n: number): string {
|
||||
return Math.max(0, Math.round(n))
|
||||
.toString()
|
||||
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
}
|
||||
|
||||
/** Extract current-session status (footer) from the raw payload. */
|
||||
export function parseSessionStatus(data: RawStatuslinePayload | undefined): SessionStatus | null {
|
||||
if (!data) return null;
|
||||
const s: SessionStatus = {};
|
||||
if (typeof data.model?.display_name === 'string' && data.model.display_name) {
|
||||
s.modelDisplayName = data.model.display_name.slice(0, 60);
|
||||
}
|
||||
const cw = data.context_window;
|
||||
if (typeof cw?.total_input_tokens === 'number' && Number.isFinite(cw.total_input_tokens)) {
|
||||
s.inputTokens = Math.max(0, cw.total_input_tokens);
|
||||
}
|
||||
if (typeof cw?.total_output_tokens === 'number' && Number.isFinite(cw.total_output_tokens)) {
|
||||
s.outputTokens = Math.max(0, cw.total_output_tokens);
|
||||
}
|
||||
if (typeof cw?.used_percentage === 'number') {
|
||||
s.contextUsedPercentage = clampPct(cw.used_percentage);
|
||||
}
|
||||
return Object.keys(s).length ? s : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the in-terminal statusline footer: the CURRENT SESSION's status —
|
||||
* `Opus 4.8 (1M context) in:562,411 out:1,188 ctx:56%` — NOT the plan limits,
|
||||
* which live in the Codeman header chip. Claude requires a statusLine command to
|
||||
* emit the rate_limits JSON at all, so this is what that command prints back.
|
||||
*/
|
||||
export function formatSessionStatusText(s: SessionStatus | null): string {
|
||||
if (!s) return 'codeman';
|
||||
const groups: string[] = [];
|
||||
if (s.modelDisplayName) groups.push(s.modelDisplayName);
|
||||
const tok: string[] = [];
|
||||
if (s.inputTokens != null) tok.push(`in:${withCommas(s.inputTokens)}`);
|
||||
if (s.outputTokens != null) tok.push(`out:${withCommas(s.outputTokens)}`);
|
||||
if (tok.length) groups.push(tok.join(' '));
|
||||
if (s.contextUsedPercentage != null) groups.push(`ctx:${Math.round(clampPct(s.contextUsedPercentage))}%`);
|
||||
return groups.length ? groups.join(' ') : 'codeman';
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable signature for change-detection — the statusline fires on every
|
||||
* assistant message, so the route only rebroadcasts when this value changes.
|
||||
*
|
||||
* Keys on EXACTLY the values the header chip displays: the two windows' ROUNDED
|
||||
* percentages (the chip renders `Math.round`) + their reset times. Deliberately
|
||||
* excludes contextUsedPercentage / costUsd / modelDisplayName — none are shown
|
||||
* in the chip, and contextUsedPercentage in particular drifts on every assistant
|
||||
* message, which would defeat the dedup and fan out a redundant SSE broadcast +
|
||||
* localStorage write + identical chip re-render each time.
|
||||
*/
|
||||
export function telemetrySignature(t: StatusTelemetry): string {
|
||||
return JSON.stringify([
|
||||
t.fiveHour ? Math.round(t.fiveHour.usedPercentage) : null,
|
||||
t.fiveHour?.resetAt ?? null,
|
||||
t.sevenDay ? Math.round(t.sevenDay.usedPercentage) : null,
|
||||
t.sevenDay?.resetAt ?? null,
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* @fileoverview Probe engine for `codeman doctor`. Resolves each registry tool
|
||||
* against an injectable ProbeHost (real impl uses child_process/fs; tests inject
|
||||
* fakes) and returns structured results. Pure given the host — no global I/O.
|
||||
*
|
||||
* @module utils/dependency-checker
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import type { ProbeEnvironment, ToolCategory, ToolDependency } from '../config/dependency-registry.js';
|
||||
|
||||
export interface EnvDetectionInputs {
|
||||
platform: NodeJS.Platform;
|
||||
procVersion: string;
|
||||
hasWindowsInterop: boolean;
|
||||
}
|
||||
|
||||
export function detectEnvironment(inputs: EnvDetectionInputs): ProbeEnvironment {
|
||||
if (inputs.platform === 'win32') return 'win32';
|
||||
if (inputs.platform === 'darwin') return 'darwin';
|
||||
const isWsl = /microsoft|wsl/i.test(inputs.procVersion) && inputs.hasWindowsInterop;
|
||||
return isWsl ? 'wsl' : 'linux';
|
||||
}
|
||||
|
||||
const DEFAULT_VERSION_RE = /(\d+\.\d+(?:\.\d+)?)/;
|
||||
|
||||
export function extractVersion(text: string, re?: RegExp): string | undefined {
|
||||
const m = (re ?? DEFAULT_VERSION_RE).exec(text);
|
||||
return m ? m[1] : undefined;
|
||||
}
|
||||
|
||||
/** Returns -1 if a < b, 0 if equal, 1 if a > b (numeric, component-wise). */
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const pa = a.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
const pb = b.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
const len = Math.max(pa.length, pb.length);
|
||||
for (let i = 0; i < len; i++) {
|
||||
const d = (pa[i] || 0) - (pb[i] || 0);
|
||||
if (d !== 0) return d < 0 ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export type ToolStatus = 'ok' | 'missing' | 'outdated' | 'skipped' | 'error';
|
||||
|
||||
export interface ToolResult {
|
||||
id: string;
|
||||
label: string;
|
||||
category: ToolCategory;
|
||||
required: boolean;
|
||||
usedBy: string[];
|
||||
status: ToolStatus;
|
||||
version?: string;
|
||||
path?: string;
|
||||
installHint?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface ProbeHost {
|
||||
environment: ProbeEnvironment;
|
||||
which(bin: string): string | null;
|
||||
fileExists(path: string): boolean;
|
||||
runVersion(bin: string, args: string[]): string | null;
|
||||
windowsProgramRoots(): string[];
|
||||
windowsFileVersion(winPath: string): string | null;
|
||||
}
|
||||
|
||||
function finalize(
|
||||
base: Pick<ToolResult, 'id' | 'label' | 'category' | 'required' | 'usedBy'>,
|
||||
tool: ToolDependency,
|
||||
path: string,
|
||||
version: string | undefined
|
||||
): ToolResult {
|
||||
if (tool.minVersion) {
|
||||
if (!version) return { ...base, status: 'error', path, reason: 'version required but could not be parsed' };
|
||||
if (compareVersions(version, tool.minVersion) < 0) return { ...base, status: 'outdated', path, version };
|
||||
}
|
||||
return { ...base, status: 'ok', path, version };
|
||||
}
|
||||
|
||||
export function checkTool(tool: ToolDependency, host: ProbeHost): ToolResult {
|
||||
const base = {
|
||||
id: tool.id,
|
||||
label: tool.label,
|
||||
category: tool.category,
|
||||
required: tool.required,
|
||||
usedBy: tool.usedBy ?? [],
|
||||
};
|
||||
const installHint = tool.installHint?.[host.environment];
|
||||
|
||||
const spec = tool.resolvers.find((r) => r.match.includes(host.environment));
|
||||
if (!spec) return { ...base, status: 'skipped', reason: `not applicable on ${host.environment}` };
|
||||
|
||||
if (spec.resolver.kind === 'path') {
|
||||
const { bins, versionArg, versionRegex } = spec.resolver;
|
||||
for (const bin of bins) {
|
||||
const resolved = host.which(bin);
|
||||
if (resolved) {
|
||||
const out = host.runVersion(bin, [versionArg ?? '--version']);
|
||||
const version = out ? extractVersion(out, versionRegex) : undefined;
|
||||
return finalize(base, tool, resolved, version);
|
||||
}
|
||||
}
|
||||
return { ...base, status: 'missing', installHint };
|
||||
}
|
||||
|
||||
// windows-side
|
||||
const { appDirs, exes } = spec.resolver;
|
||||
for (const root of host.windowsProgramRoots()) {
|
||||
for (const dir of appDirs) {
|
||||
for (const exe of exes) {
|
||||
const winPath = `${root}/${dir}/${exe}`;
|
||||
if (host.fileExists(winPath)) {
|
||||
const raw = host.windowsFileVersion(winPath);
|
||||
const version = raw ? extractVersion(raw) : undefined;
|
||||
return finalize(base, tool, winPath, version);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, status: 'missing', installHint };
|
||||
}
|
||||
|
||||
export function checkAll(registry: ToolDependency[], host: ProbeHost): ToolResult[] {
|
||||
return registry.map((tool) => checkTool(tool, host));
|
||||
}
|
||||
|
||||
function safeWhich(bin: string): string | null {
|
||||
try {
|
||||
const out = execFileSync(process.platform === 'win32' ? 'where' : 'which', [bin], {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
}).trim();
|
||||
const first = out.split(/\r?\n/)[0]?.trim();
|
||||
return first && existsSync(first) ? first : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeRunVersion(bin: string, args: string[]): string | null {
|
||||
try {
|
||||
return execFileSync(bin, args, {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
// Some tools (e.g. ffmpeg) exit non-zero on -version but still print to stdout
|
||||
const stdout = (err as { stdout?: Buffer | string })?.stdout;
|
||||
return stdout ? stdout.toString() : null;
|
||||
}
|
||||
}
|
||||
|
||||
function readProcVersion(): string {
|
||||
try {
|
||||
return readFileSync('/proc/version', 'utf-8');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function listWindowsProgramRoots(): string[] {
|
||||
const roots: string[] = [];
|
||||
try {
|
||||
for (const entry of readdirSync('/mnt')) {
|
||||
for (const pf of ['Program Files', 'Program Files (x86)']) {
|
||||
const root = `/mnt/${entry}/${pf}`;
|
||||
if (existsSync(root)) roots.push(root);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// /mnt absent (not WSL) -> no roots
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
function readWindowsFileVersion(winPath: string): string | null {
|
||||
try {
|
||||
const windowsPath = execFileSync('wslpath', ['-w', winPath], {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
}).trim();
|
||||
const out = execFileSync(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-Command', `(Get-Item '${windowsPath.replace(/'/g, "''")}').VersionInfo.ProductVersion`],
|
||||
{ encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }
|
||||
).trim();
|
||||
return out || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function createRealHost(): ProbeHost {
|
||||
const environment = detectEnvironment({
|
||||
platform: process.platform,
|
||||
procVersion: readProcVersion(),
|
||||
hasWindowsInterop: safeWhich('cmd.exe') !== null || safeWhich('powershell.exe') !== null,
|
||||
});
|
||||
return {
|
||||
environment,
|
||||
which: safeWhich,
|
||||
fileExists: existsSync,
|
||||
runVersion: safeRunVersion,
|
||||
windowsProgramRoots: listWindowsProgramRoots,
|
||||
windowsFileVersion: readWindowsFileVersion,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @fileoverview Renders ToolResult[] from the dependency checker into a
|
||||
* human-readable grouped table or JSON, and computes the process exit code.
|
||||
* Plain text only (no color) so output is stable and snapshot-friendly; the
|
||||
* CLI layer may colorize.
|
||||
*
|
||||
* @module utils/dependency-report
|
||||
*/
|
||||
|
||||
import type { ProbeEnvironment, ToolCategory } from '../config/dependency-registry.js';
|
||||
import type { ToolResult, ToolStatus } from './dependency-checker.js';
|
||||
|
||||
const CATEGORY_ORDER: ToolCategory[] = ['core', 'office', 'other'];
|
||||
|
||||
function glyph(r: ToolResult): string {
|
||||
if (r.status === 'ok') return '✓';
|
||||
if (r.status === 'skipped') return '○';
|
||||
return r.required ? '✗' : '○';
|
||||
}
|
||||
|
||||
function statusText(r: ToolResult): string {
|
||||
if (r.status === 'ok') return r.version ?? 'installed';
|
||||
if (r.status === 'outdated') return `${r.version ?? '?'} (below minimum)`;
|
||||
if (r.status === 'skipped') return 'n/a';
|
||||
if (r.status === 'error') return 'version error';
|
||||
return 'not found';
|
||||
}
|
||||
|
||||
export function computeExitCode(results: ToolResult[]): number {
|
||||
const failed = results.some(
|
||||
(r) => r.required && (r.status === 'missing' || r.status === 'outdated' || r.status === 'error')
|
||||
);
|
||||
return failed ? 1 : 0;
|
||||
}
|
||||
|
||||
export function renderTable(results: ToolResult[], environment: ProbeEnvironment): string {
|
||||
const lines: string[] = [`Codeman dependency check — ${environment}`, ''];
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = results.filter((r) => r.category === category);
|
||||
if (rows.length === 0) continue;
|
||||
lines.push(category.toUpperCase());
|
||||
for (const r of rows) {
|
||||
const detail = r.path ? ` ${r.path}` : '';
|
||||
lines.push(` ${glyph(r)} ${r.label.padEnd(14)} ${statusText(r).padEnd(22)}${detail}`);
|
||||
if (r.usedBy.length) lines.push(` used by: ${r.usedBy.join(', ')}`);
|
||||
if (r.installHint) lines.push(` install: ${r.installHint}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
const ok = results.filter((r) => r.status === 'ok').length;
|
||||
const requiredMissing = results.filter((r) => r.required && r.status !== 'ok' && r.status !== 'skipped').length;
|
||||
const optionalMissing = results.filter((r) => !r.required && r.status === 'missing').length;
|
||||
lines.push(`Summary: ${ok} ok · ${requiredMissing} required missing · ${optionalMissing} optional missing`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export interface DependencyReportJson {
|
||||
platform: { environment: ProbeEnvironment };
|
||||
summary: { ok: number; requiredMissing: number; optionalMissing: number; exitCode: number };
|
||||
tools: ToolResult[];
|
||||
}
|
||||
|
||||
export function renderJson(results: ToolResult[], environment: ProbeEnvironment): DependencyReportJson {
|
||||
const byStatus = (s: ToolStatus) => results.filter((r) => r.status === s).length;
|
||||
return {
|
||||
platform: { environment },
|
||||
summary: {
|
||||
ok: byStatus('ok'),
|
||||
requiredMissing: results.filter((r) => r.required && r.status !== 'ok' && r.status !== 'skipped').length,
|
||||
optionalMissing: results.filter((r) => !r.required && r.status === 'missing').length,
|
||||
exitCode: computeExitCode(results),
|
||||
},
|
||||
tools: results,
|
||||
};
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
AUTH_FAILURE_MAX,
|
||||
AUTH_FAILURE_WINDOW_MS,
|
||||
} from '../../config/auth-config.js';
|
||||
import { getHookSecret, HOOK_SECRET_HEADER } from '../../config/hook-secret.js';
|
||||
|
||||
// Auth session cookie name
|
||||
export const AUTH_COOKIE_NAME = 'codeman_session';
|
||||
@@ -28,12 +29,16 @@ interface AuthState {
|
||||
authSessions: StaleExpirationMap<string, AuthSessionRecord> | null;
|
||||
authFailures: StaleExpirationMap<string, number> | null;
|
||||
qrAuthFailures: StaleExpirationMap<string, number> | null;
|
||||
hookSecretFailures: StaleExpirationMap<string, number> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register HTTP Basic Auth middleware with session cookies and rate limiting.
|
||||
* Only active when CODEMAN_PASSWORD is set.
|
||||
*
|
||||
* The `/api/hook-event` + `/api/status-telemetry` localhost bypass requires the
|
||||
* shared hook secret unconditionally (COD-91) — see the onRequest hook below.
|
||||
*
|
||||
* @returns AuthState for lifecycle management (dispose on server stop)
|
||||
*/
|
||||
export function registerAuthMiddleware(app: FastifyInstance, https: boolean): AuthState {
|
||||
@@ -41,6 +46,7 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean): Au
|
||||
authSessions: null,
|
||||
authFailures: null,
|
||||
qrAuthFailures: null,
|
||||
hookSecretFailures: null,
|
||||
};
|
||||
|
||||
const authPassword = process.env.CODEMAN_PASSWORD;
|
||||
@@ -67,24 +73,67 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean): Au
|
||||
refreshOnGet: false,
|
||||
});
|
||||
|
||||
// Separate hook-secret failure counter (COD-54). MUST NOT share authFailures:
|
||||
// legacy (pre-secret) hook configs fire constantly from 127.0.0.1, and counting
|
||||
// their 401s against the shared bucket would 429 every cookie-less request from
|
||||
// loopback — locking out the Basic-Auth login path (and, through a tunnel, every
|
||||
// client, since tunneled traffic also arrives as 127.0.0.1).
|
||||
state.hookSecretFailures = new StaleExpirationMap<string, number>({
|
||||
ttlMs: AUTH_FAILURE_WINDOW_MS,
|
||||
refreshOnGet: false,
|
||||
});
|
||||
|
||||
const authSessions = state.authSessions;
|
||||
const authFailures = state.authFailures;
|
||||
const hookSecretFailures = state.hookSecretFailures;
|
||||
|
||||
function sendAuthRateLimit(reply: FastifyReply, clientIp: string): void {
|
||||
const remainingMs = authFailures.getRemainingTtl(clientIp) ?? AUTH_FAILURE_WINDOW_MS;
|
||||
function sendAuthRateLimit(
|
||||
reply: FastifyReply,
|
||||
clientIp: string,
|
||||
failures: StaleExpirationMap<string, number> = authFailures
|
||||
): void {
|
||||
const remainingMs = failures.getRemainingTtl(clientIp) ?? AUTH_FAILURE_WINDOW_MS;
|
||||
const retryAfterSeconds = Math.max(1, Math.ceil(remainingMs / 1000));
|
||||
reply.header('Retry-After', String(retryAfterSeconds));
|
||||
reply.code(429).send('Too Many Requests — try again later');
|
||||
}
|
||||
|
||||
app.addHook('onRequest', (req, reply, done) => {
|
||||
// Hook events come from local Claude Code hooks (curl from localhost) — no auth headers available.
|
||||
// Safe: validated by HookEventSchema, only triggers broadcasts.
|
||||
// Security: restrict bypass to localhost only — prevents forged hook events via tunnel/LAN.
|
||||
if (req.url === '/api/hook-event' && req.method === 'POST') {
|
||||
// Hook events + statusline telemetry come from local Claude Code (curl from
|
||||
// localhost) — no Basic-Auth credentials available. Validated downstream by
|
||||
// HookEventSchema / StatusTelemetrySchema. Same loopback+hook-secret gate.
|
||||
//
|
||||
// COD-54: the bare localhost bypass is unsafe while a tunnel is running, because
|
||||
// `cloudflared --url http://127.0.0.1:port` proxies internet traffic INTO the
|
||||
// loopback origin, so a tunneled request arrives with req.ip === 127.0.0.1 and
|
||||
// would pass. COD-91: require the shared hook secret on the loopback bypass
|
||||
// UNCONDITIONALLY (not just while the managed tunnel is up). Codeman can't detect
|
||||
// a user's own loopback reverse proxy (their own `cloudflared --url`, `tailscale
|
||||
// serve`, nginx → 127.0.0.1), so tunnel-gating left that path with the unsafe plain
|
||||
// bypass. Managed-session hooks always present the secret (X-Codeman-Hook-Secret,
|
||||
// from $CODEMAN_HOOK_SECRET_FILE — generated for every instance), so requiring it
|
||||
// always closes the gap without breaking the legitimate hook channel.
|
||||
if ((req.url === '/api/hook-event' || req.url === '/api/status-telemetry') && req.method === 'POST') {
|
||||
const ip = req.ip;
|
||||
if (ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1') {
|
||||
done();
|
||||
const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
||||
if (isLoopback) {
|
||||
// Always require the shared secret (constant-time compare).
|
||||
const presented = Buffer.from(req.headers[HOOK_SECRET_HEADER.toLowerCase()]?.toString() ?? '');
|
||||
const expected = Buffer.from(getHookSecret());
|
||||
if (presented.length === expected.length && timingSafeEqual(presented, expected)) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
// Wrong/absent secret — rate-limit per IP in the DEDICATED hook bucket
|
||||
// (never authFailures, which would lock out the login path).
|
||||
const hookIp = req.ip;
|
||||
const hookFailures = hookSecretFailures.get(hookIp) ?? 0;
|
||||
if (hookFailures >= AUTH_FAILURE_MAX) {
|
||||
sendAuthRateLimit(reply, hookIp, hookSecretFailures);
|
||||
return;
|
||||
}
|
||||
hookSecretFailures.set(hookIp, hookFailures + 1);
|
||||
reply.code(401).send('Unauthorized: hook secret required');
|
||||
return;
|
||||
}
|
||||
// Non-localhost hook requests fall through to normal auth
|
||||
@@ -205,7 +254,12 @@ export function registerSecurityHeaders(app: FastifyInstance, https: boolean): v
|
||||
const scriptSrc =
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net" + (gesture ? " 'wasm-unsafe-eval'" : '');
|
||||
const connectSrc = "connect-src 'self' wss://api.deepgram.com";
|
||||
const workerSrc = gesture ? "; worker-src 'self' blob:" : '';
|
||||
// blob: workers are needed unconditionally: terminal-ui's _safeYield tick
|
||||
// worker (throttling escape) is created from a Blob URL. Without this, every
|
||||
// page load logs a CSP violation and the worker leg of _safeYield is dead.
|
||||
// Risk is minimal — only same-origin scripts (already governed by script-src)
|
||||
// can construct blob workers.
|
||||
const workerSrc = "; worker-src 'self' blob:";
|
||||
const csp =
|
||||
`default-src 'self'; ${scriptSrc}; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; ` +
|
||||
`img-src 'self' data: blob:; ${connectSrc}; font-src 'self' https://cdn.jsdelivr.net; frame-ancestors 'self'${workerSrc}`;
|
||||
|
||||
@@ -6,6 +6,16 @@ export function isExplicitlyEnabled(value: string | undefined): boolean {
|
||||
return value !== undefined && EXPLICIT_TRUE_VALUES.has(value.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* True when unauthenticated network exposure is acceptable: either a password is
|
||||
* set (auth active) or the operator explicitly acknowledged it. Used by the
|
||||
* tunnel-enable guard (COD-55) to refuse publishing an unauthenticated public URL.
|
||||
*/
|
||||
export function isUnauthenticatedNetworkAcknowledged(allowFlag = false): boolean {
|
||||
if (process.env.CODEMAN_PASSWORD) return true;
|
||||
return allowFlag || isExplicitlyEnabled(process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK);
|
||||
}
|
||||
|
||||
export function isLoopbackBindHost(host: string): boolean {
|
||||
const normalized = host
|
||||
.trim()
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @fileoverview Process-wide last-known plan-usage telemetry (account-global).
|
||||
*
|
||||
* The status-telemetry route writes the latest broadcast value here; the SSE
|
||||
* init snapshot (`getLightState`) replays it so the header "Plan Usage Limits"
|
||||
* chip shows immediately on a fresh page load / SSE reconnect — before any new
|
||||
* statusline render arrives, and without relying on per-browser localStorage.
|
||||
*
|
||||
* Null until the first telemetry of the process; cleared naturally on restart.
|
||||
*
|
||||
* @module plan-usage-latest
|
||||
*/
|
||||
|
||||
let latest: Record<string, unknown> | null = null;
|
||||
|
||||
export function setLatestPlanUsage(value: Record<string, unknown>): void {
|
||||
latest = value;
|
||||
}
|
||||
|
||||
export function getLatestPlanUsage(): Record<string, unknown> | null {
|
||||
return latest;
|
||||
}
|
||||
+732
-115
File diff suppressed because it is too large
Load Diff
@@ -51,6 +51,7 @@ const GROUPING_TIMEOUT_MS = 5000; // 5 seconds - notification grouping
|
||||
const NOTIFICATION_LIST_CAP = 100; // Max notifications in list
|
||||
const TITLE_FLASH_INTERVAL_MS = 1500; // Title flash rate
|
||||
const BROWSER_NOTIF_RATE_LIMIT_MS = 3000; // Rate limit for browser notifications
|
||||
const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send while a desktop sizing claim is hot
|
||||
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
|
||||
const THROTTLE_DELAY_MS = 100; // General UI throttle delay
|
||||
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
|
||||
@@ -113,9 +114,24 @@ function evaluateWebGLLongTaskTrip(recent, entries, now, config = WEBGL_FALLBACK
|
||||
// Expose for tests. `const` declarations at the top of a non-module script
|
||||
// are global lexical bindings but not `window` properties, so explicit
|
||||
// assignment is the test-visible API surface.
|
||||
// Desktop tab-overflow policy: auto-wrap the session tabs to a second row when
|
||||
// they overflow one row (and the user hasn't pinned the manual two-row layout).
|
||||
function shouldAutoWrapTabs(input) {
|
||||
if (!input || input.deviceType !== 'desktop') return false;
|
||||
if (input.manualTwoRows) return false;
|
||||
if ((input.tabCount || 0) < 2) return false;
|
||||
|
||||
const scrollWidth = Number(input.scrollWidth) || 0;
|
||||
const clientWidth = Number(input.clientWidth) || 0;
|
||||
return scrollWidth > clientWidth + 1;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
|
||||
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
|
||||
window.CodemanTabOverflow = {
|
||||
shouldAutoWrapTabs,
|
||||
};
|
||||
}
|
||||
|
||||
// Scheduler API — prioritize terminal writes over background UI updates.
|
||||
@@ -243,10 +259,14 @@ const SSE_EVENTS = {
|
||||
SESSION_WORKING: 'session:working',
|
||||
SESSION_AUTO_CLEAR: 'session:autoClear',
|
||||
SESSION_AUTO_COMPACT: 'session:autoCompact',
|
||||
SESSION_LIMIT_PAUSE_SCHEDULED: 'session:limitPauseScheduled',
|
||||
SESSION_LIMIT_RESUME: 'session:limitResume',
|
||||
SESSION_LIMIT_RESUME_CANCELLED: 'session:limitResumeCancelled',
|
||||
SESSION_CLI_INFO: 'session:cliInfo',
|
||||
SESSION_MESSAGE: 'session:message',
|
||||
SESSION_INTERACTIVE: 'session:interactive',
|
||||
SESSION_RUNNING: 'session:running',
|
||||
SESSION_STATUS_TELEMETRY: 'session:statusTelemetry',
|
||||
|
||||
// Scheduled runs
|
||||
SCHEDULED_CREATED: 'scheduled:created',
|
||||
@@ -330,8 +350,14 @@ const SSE_EVENTS = {
|
||||
SUBAGENT_TOOL_RESULT: 'subagent:tool_result',
|
||||
SUBAGENT_COMPLETED: 'subagent:completed',
|
||||
|
||||
// Workflow runs (ultracode / Workflow tool)
|
||||
WORKFLOW_RUN_DISCOVERED: 'workflow:run_discovered',
|
||||
WORKFLOW_RUN_UPDATED: 'workflow:run_updated',
|
||||
WORKFLOW_RUN_REMOVED: 'workflow:run_removed',
|
||||
|
||||
// Images
|
||||
IMAGE_DETECTED: 'image:detected',
|
||||
ATTACHMENT_DETECTED: 'attachment:detected',
|
||||
|
||||
// Tunnel
|
||||
TUNNEL_STARTED: 'tunnel:started',
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -4449,6 +4449,7 @@ var GestureController = class {
|
||||
// packages/gesture-control/src/codeman/entry.ts
|
||||
var TAB_SELECTOR = ".session-tab";
|
||||
var PANEL_SELECTOR = ".cg-float";
|
||||
var WINDOW_SELECTOR = ".subagent-window, .ultracode-window";
|
||||
var DOCK_SELECTOR = ".session-tabs";
|
||||
var CLICK_SELECTOR = "#runBtn, .btn-shell";
|
||||
var Z2 = 2147483e3;
|
||||
@@ -4476,6 +4477,8 @@ var GestureBridge = class {
|
||||
__publicField(this, "taps", /* @__PURE__ */ new Map());
|
||||
/** Live floating panels, keyed by session id (idempotent per id). */
|
||||
__publicField(this, "floats", /* @__PURE__ */ new Map());
|
||||
/** rAF coalescing for connector-line redraws while dragging an agent window. */
|
||||
__publicField(this, "connectorRedrawScheduled", false);
|
||||
injectStyles();
|
||||
this.surface = el("div", "cg-surface");
|
||||
this.canvas = el("canvas", "cg-canvas");
|
||||
@@ -4530,7 +4533,7 @@ var GestureBridge = class {
|
||||
await this.gc.start();
|
||||
this.running = true;
|
||||
this.button.classList.add("on");
|
||||
this.status.textContent = "on \u2014 pinch a tab or button";
|
||||
this.status.textContent = "on \u2014 pinch a tab, window, or button";
|
||||
} catch (err) {
|
||||
const msg = describeError(err);
|
||||
this.status.textContent = `failed: ${msg}`;
|
||||
@@ -4575,6 +4578,16 @@ var GestureBridge = class {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const win = this.hitClosest(x2, y2, WINDOW_SELECTOR);
|
||||
if (win) {
|
||||
const rect = win.getBoundingClientRect();
|
||||
win.style.bottom = "auto";
|
||||
win.classList.add("cg-win-grabbed");
|
||||
this.bringWindowToFront(win);
|
||||
this.grabs.set(hand, { kind: "window", el: win, dx: x2 - rect.left, dy: y2 - rect.top });
|
||||
this.status.textContent = "moving window";
|
||||
return;
|
||||
}
|
||||
const tab = this.hitClosest(x2, y2, TAB_SELECTOR);
|
||||
const id = tab?.dataset.id;
|
||||
if (tab && id) {
|
||||
@@ -4620,11 +4633,15 @@ var GestureBridge = class {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (grab?.kind === "window") {
|
||||
this.moveWindow(grab.el, x2 - grab.dx, y2 - grab.dy);
|
||||
return;
|
||||
}
|
||||
const tap = this.taps.get(hand);
|
||||
if (tap && Math.hypot(x2 - tap.ox, y2 - tap.oy) > TAP_CANCEL_PX) {
|
||||
tap.el.classList.remove("cg-tap-armed");
|
||||
this.taps.delete(hand);
|
||||
this.status.textContent = "on \u2014 pinch a tab or button";
|
||||
this.status.textContent = "on \u2014 pinch a tab, window, or button";
|
||||
}
|
||||
}
|
||||
onDrop(hand, x2, y2) {
|
||||
@@ -4645,6 +4662,18 @@ var GestureBridge = class {
|
||||
else this.flash("placed");
|
||||
return;
|
||||
}
|
||||
if (grab?.kind === "window") {
|
||||
this.grabs.delete(hand);
|
||||
grab.el.classList.remove("cg-win-grabbed");
|
||||
this.connectorRedrawScheduled = false;
|
||||
this.redrawWindowConnectors();
|
||||
try {
|
||||
window.app?.saveSubagentWindowStates?.();
|
||||
} catch {
|
||||
}
|
||||
this.flash("placed window");
|
||||
return;
|
||||
}
|
||||
const tap = this.taps.get(hand);
|
||||
if (tap) {
|
||||
this.taps.delete(hand);
|
||||
@@ -4694,6 +4723,54 @@ var GestureBridge = class {
|
||||
float.el.style.left = `${l}px`;
|
||||
float.el.style.top = `${t2}px`;
|
||||
}
|
||||
/** Move a dashboard-owned agent window by its top-left, clamped on-screen, then
|
||||
* redraw its connector line. The window self-positions via `style.left/top` and
|
||||
* app.js's connector redraw reads live rects, so this tracks without touching
|
||||
* app.js internals. Guards on `isConnected`: ultracode windows can be torn down
|
||||
* (SSE reconnect / auto-close) while still held. Clamps to `innerWidth/Height`,
|
||||
* which equals the *spanned* viewport in a multi-monitor window — so the window
|
||||
* can still travel across the physical monitor seam, just not off-screen. */
|
||||
moveWindow(el2, left, top) {
|
||||
if (!el2.isConnected) return;
|
||||
const w2 = el2.offsetWidth || 380;
|
||||
const h2 = el2.offsetHeight || 320;
|
||||
const l = Math.min(Math.max(4, left), Math.max(4, window.innerWidth - w2 - 4));
|
||||
const t2 = Math.min(Math.max(4, top), Math.max(4, window.innerHeight - h2 - 4));
|
||||
el2.style.left = `${l}px`;
|
||||
el2.style.top = `${t2}px`;
|
||||
this.redrawWindowConnectors();
|
||||
}
|
||||
/** Ask app.js to redraw all connector lines (subagent + ultracode), coalesced to
|
||||
* one per frame so per-frame drags don't thrash. `updateConnectionLines()` is
|
||||
* itself debounced in app.js, but we rAF-gate too in case an older dashboard
|
||||
* build isn't, and to no-op cleanly when app.js isn't present (standalone). */
|
||||
redrawWindowConnectors() {
|
||||
if (this.connectorRedrawScheduled) return;
|
||||
this.connectorRedrawScheduled = true;
|
||||
requestAnimationFrame(() => {
|
||||
this.connectorRedrawScheduled = false;
|
||||
try {
|
||||
window.app?.updateConnectionLines?.();
|
||||
} catch {
|
||||
}
|
||||
});
|
||||
}
|
||||
/** Pop a grabbed window above its siblings using app.js's own z-counter, so a
|
||||
* picked-up window comes to the front like a real focus. Cosmetic + best-effort. */
|
||||
bringWindowToFront(el2) {
|
||||
const app = window.app;
|
||||
if (!app) return;
|
||||
try {
|
||||
if (el2.classList.contains("ultracode-window")) {
|
||||
app.ultracodeWindowZIndex = (app.ultracodeWindowZIndex ?? 1e3) + 1;
|
||||
el2.style.zIndex = String(app.ultracodeWindowZIndex);
|
||||
} else {
|
||||
app.subagentWindowZIndex = (app.subagentWindowZIndex ?? 1e3) + 1;
|
||||
el2.style.zIndex = String(app.subagentWindowZIndex);
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
positionGhost(ghost, x2, y2) {
|
||||
ghost.style.left = `${x2}px`;
|
||||
ghost.style.top = `${y2}px`;
|
||||
@@ -4703,15 +4780,17 @@ var GestureBridge = class {
|
||||
if (grab.kind === "tab") {
|
||||
grab.ghost.remove();
|
||||
grab.tab.classList.remove("cg-grabbed");
|
||||
} else {
|
||||
} else if (grab.kind === "panel") {
|
||||
grab.panel.el.style.pointerEvents = "";
|
||||
grab.panel.el.classList.remove("cg-float-grabbed", "cg-redock");
|
||||
} else {
|
||||
grab.el.classList.remove("cg-win-grabbed");
|
||||
}
|
||||
}
|
||||
this.grabs.clear();
|
||||
for (const tap of this.taps.values()) tap.el.classList.remove("cg-tap-armed");
|
||||
this.taps.clear();
|
||||
document.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed`).forEach((t2) => t2.classList.remove("cg-grabbed", "cg-tap-armed"));
|
||||
document.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed, .cg-win-grabbed`).forEach((t2) => t2.classList.remove("cg-grabbed", "cg-tap-armed", "cg-win-grabbed"));
|
||||
}
|
||||
onStatus(fps, hands) {
|
||||
const { width, height } = this.canvas;
|
||||
@@ -4797,6 +4876,10 @@ function injectStyles() {
|
||||
.cg-status { color: #9aa0a6; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.session-tab.cg-grabbed { opacity: .35; outline: 2px dashed #4ade80; outline-offset: -2px; }
|
||||
.cg-tap-armed { outline: 2px solid #4ade80 !important; outline-offset: 2px; box-shadow: 0 0 0 4px rgba(74,222,128,.25) !important; }
|
||||
.subagent-window.cg-win-grabbed, .ultracode-window.cg-win-grabbed {
|
||||
outline: 2px solid #4ade80 !important; outline-offset: -2px;
|
||||
box-shadow: 0 12px 48px rgba(74,222,128,.5) !important;
|
||||
}
|
||||
.cg-float {
|
||||
position: fixed; left: 0; top: 0; width: ${FLOAT_W}px; height: ${FLOAT_H}px;
|
||||
z-index: ${Z2}; display: flex; flex-direction: column; overflow: hidden;
|
||||
|
||||
@@ -104,34 +104,78 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.execCommand('paste');
|
||||
},
|
||||
|
||||
async _uploadAndInsertImages(files) {
|
||||
// Max images accepted in one batch (paste / drop / mobile picker). Each is
|
||||
// uploaded as its own request, so 20 stays under the server's 30 uploads/min
|
||||
// rate limit while covering "select a bunch of photos at once".
|
||||
_maxBatchImages: 20,
|
||||
// How many uploads to run concurrently. Small enough that decoding several
|
||||
// large images through <canvas> at once won't OOM a phone, large enough that
|
||||
// 20 photos don't crawl through serially.
|
||||
_uploadConcurrency: 3,
|
||||
|
||||
async _uploadAndInsertImages(fileList) {
|
||||
const sessionId = this.activeSessionId;
|
||||
if (!sessionId) return;
|
||||
|
||||
this.showToast('Uploading ' + files.length + ' image' + (files.length > 1 ? 's' : '') + '...', 'info');
|
||||
let files = Array.from(fileList || []);
|
||||
if (files.length === 0) return;
|
||||
|
||||
const paths = [];
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Re-encode to a standard JPEG/PNG before upload. Galleries on some
|
||||
// phones (notably Android/MIUI) hand back a WebP/HEIF whose filename and
|
||||
// MIME claim "image/jpeg", which passes the server's extension allowlist
|
||||
// but fails its magic-byte check ("bytes do not match declared type").
|
||||
// Decoding through the browser and re-encoding guarantees the bytes
|
||||
// match the extension we send.
|
||||
const normalized = await this._normalizeImageForUpload(file);
|
||||
const path = await this._uploadPasteImage(sessionId, normalized);
|
||||
paths.push(path);
|
||||
} catch (err) {
|
||||
this.showToast('Upload failed: ' + (err.message || 'unknown error'), 'error');
|
||||
// Cap the batch and tell the user what got dropped (no silent truncation).
|
||||
let capped = false;
|
||||
if (files.length > this._maxBatchImages) {
|
||||
files = files.slice(0, this._maxBatchImages);
|
||||
capped = true;
|
||||
}
|
||||
|
||||
const total = files.length;
|
||||
let done = 0;
|
||||
let failed = 0;
|
||||
const results = new Array(total); // preserve selection order for insertion
|
||||
const progress = () =>
|
||||
this.showToast(`Uploading ${Math.min(done + 1, total)}/${total} image${total > 1 ? 's' : ''}…`, 'info');
|
||||
progress();
|
||||
|
||||
// Bounded-concurrency worker pool over the file list.
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
for (;;) {
|
||||
const i = next++;
|
||||
if (i >= total) return;
|
||||
try {
|
||||
// Re-encode to a standard JPEG/PNG (and downscale very large images)
|
||||
// before upload. Galleries on some phones (notably Android/MIUI) hand
|
||||
// back a WebP/HEIF whose filename and MIME claim "image/jpeg", which
|
||||
// passes the server's extension allowlist but fails its magic-byte
|
||||
// check. Decoding through the browser and re-encoding guarantees the
|
||||
// bytes match the extension we send — and shrinks huge photos so they
|
||||
// fit the upload limit and iOS's <canvas> area cap.
|
||||
const normalized = await this._normalizeImageForUpload(files[i]);
|
||||
results[i] = await this._uploadPasteImage(sessionId, normalized);
|
||||
} catch (err) {
|
||||
failed++;
|
||||
console.warn('Image upload failed:', err);
|
||||
results[i] = null;
|
||||
} finally {
|
||||
done++;
|
||||
if (done < total) progress();
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(this._uploadConcurrency, total) }, () => worker()));
|
||||
|
||||
const paths = results.filter(Boolean);
|
||||
if (paths.length > 0) {
|
||||
// Insert all paths in one shot, space-separated, in selection order.
|
||||
await this.sendInput(paths.join(' '));
|
||||
}
|
||||
|
||||
if (paths.length > 0) {
|
||||
const pathStr = paths.join(' ');
|
||||
await this.sendInput(pathStr);
|
||||
this.showToast(paths.length + ' image' + (paths.length > 1 ? 's' : '') + ' ready', 'success');
|
||||
}
|
||||
// Final status: successes, plus any failures / cap so nothing is silent.
|
||||
const parts = [];
|
||||
if (paths.length > 0) parts.push(`${paths.length} image${paths.length > 1 ? 's' : ''} ready`);
|
||||
if (failed > 0) parts.push(`${failed} failed`);
|
||||
if (capped) parts.push(`max ${this._maxBatchImages} per batch`);
|
||||
const tone = paths.length > 0 ? (failed > 0 || capped ? 'info' : 'success') : 'error';
|
||||
this.showToast(parts.join(' · ') || 'No images uploaded', tone);
|
||||
},
|
||||
|
||||
async _uploadPasteImage(sessionId, file) {
|
||||
@@ -176,12 +220,24 @@ Object.assign(CodemanApp.prototype, {
|
||||
const height = img.naturalHeight;
|
||||
if (!width || !height) return file;
|
||||
|
||||
// Downscale very large images. Two reasons: (1) iOS Safari refuses to
|
||||
// render a <canvas> larger than ~16.7M px (it returns a blank/null
|
||||
// blob), so a 48MP photo would otherwise fail to re-encode and fall back
|
||||
// to the original — which then trips the server's magic-byte check for
|
||||
// HEIF mislabeled as JPEG. (2) It keeps multi-photo uploads fast and well
|
||||
// under the size limit. Cap the longest edge so area stays safely below
|
||||
// the canvas limit while still uploading a large, high-quality image.
|
||||
const MAX_EDGE = 4096;
|
||||
const scale = Math.min(1, MAX_EDGE / Math.max(width, height));
|
||||
const w = Math.max(1, Math.round(width * scale));
|
||||
const h = Math.max(1, Math.round(height * scale));
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return file;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
|
||||
const mime = toPng ? 'image/png' : 'image/jpeg';
|
||||
const blob = await new Promise((resolve) => canvas.toBlob(resolve, mime, 0.92));
|
||||
|
||||
+136
-53
@@ -8,7 +8,7 @@
|
||||
<base href="/">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
|
||||
<meta name="description" content="Claude Code session manager with web interface">
|
||||
<meta name="theme-color" content="#0a0a0a">
|
||||
<meta name="theme-color" content="#11151c">
|
||||
<meta name="google" content="notranslate">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
@@ -30,21 +30,31 @@
|
||||
'defer' preserves execution order (xterm loads before fit addon). -->
|
||||
<script defer src="vendor/xterm.min.js"></script>
|
||||
<script defer src="vendor/xterm-addon-fit.min.js"></script>
|
||||
<!-- SerializeAddon: snapshots xterm state (viewport + scrollback + attrs) for
|
||||
per-session restore on tab switches. Lets codex tabs survive switch-away
|
||||
without codeman having to replay codex's byte stream (which loses earlier
|
||||
conversation because codex's TUI redraws drop it from the viewport). -->
|
||||
<script defer src="vendor/xterm-addon-serialize.min.js"></script>
|
||||
<!-- WebGL addon lazy-loaded by app.js on desktop only (skipped on mobile, saving 244KB) -->
|
||||
<script defer src="vendor/xterm-addon-unicode11.min.js"></script>
|
||||
<script defer src="vendor/xterm-zerolag-input.js"></script>
|
||||
<script defer src="vendor/marked.min.js"></script>
|
||||
<!-- DOMPurify (allowlist HTML sanitizer for rendered markdown).
|
||||
Must load before sanitize-html.js (which wires it) and app.js (which calls it). -->
|
||||
<script defer src="vendor/dompurify.min.js"></script>
|
||||
<!-- Synchronous mobile detection — runs before first paint to prevent panel flash -->
|
||||
<script>if(window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024))document.documentElement.classList.add('mobile-init');</script>
|
||||
<!-- Synchronous skin selection — runs before first paint to prevent theme flash -->
|
||||
<script>try{var s=localStorage.getItem('codeman:skin');if(s!=='og'&&s!=='daylight-green'&&s!=='daylight-blue')s='daylight-blue';document.documentElement.dataset.skin=s;window.__codemanSkin=s;}catch(e){document.documentElement.dataset.skin='daylight-blue';window.__codemanSkin='daylight-blue';}</script>
|
||||
<!-- Inline critical CSS for instant skeleton paint (before styles.css loads) -->
|
||||
<style>
|
||||
.loading-skeleton{display:flex;flex-direction:column;height:100vh;height:100dvh;background:#09090b}
|
||||
.skeleton-header{height:40px;background:rgba(19,19,22,0.85);border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;padding:0 12px}
|
||||
.skeleton-brand{color:#60a5fa;font-size:14px;font-weight:700;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;opacity:.7}
|
||||
.loading-skeleton{display:flex;flex-direction:column;height:100vh;height:100dvh;background:#11151c}
|
||||
.skeleton-header{height:40px;background:rgba(31,38,48,0.85);border-bottom:1px solid rgba(255,255,255,0.08);display:flex;align-items:center;padding:0 12px}
|
||||
.skeleton-brand{color:#38b6f0;font-size:14px;font-weight:700;font-family:'Manrope',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;opacity:.85}
|
||||
.skeleton-tabs{display:flex;gap:4px;margin-left:16px}
|
||||
.skeleton-tab{width:80px;height:24px;background:rgba(255,255,255,0.04);border-radius:6px}
|
||||
.skeleton-terminal{flex:1;background:#0d0d0d}
|
||||
.skeleton-toolbar{height:42px;background:rgba(19,19,22,0.85);border-top:1px solid rgba(255,255,255,0.06)}
|
||||
.skeleton-terminal{flex:1;background:#161b23}
|
||||
.skeleton-toolbar{height:42px;background:rgba(31,38,48,0.85);border-top:1px solid rgba(255,255,255,0.08)}
|
||||
.app-loaded .loading-skeleton{display:none}
|
||||
</style>
|
||||
</head>
|
||||
@@ -69,10 +79,6 @@
|
||||
<span class="logo" onclick="app.goHome()" title="Go to main page">Codeman</span>
|
||||
</div>
|
||||
|
||||
<button class="mobile-header-utility-toggle" id="mobileHeaderUtilityToggle" type="button" aria-label="Toggle header utilities" aria-controls="headerRight" aria-expanded="false" title="Header utilities">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>
|
||||
</button>
|
||||
|
||||
<!-- Session Tabs -->
|
||||
<div class="session-tabs" id="sessionTabs" role="tablist" aria-label="Session tabs">
|
||||
</div>
|
||||
@@ -80,7 +86,7 @@
|
||||
<!-- Detached single-session window title (shown only in solo mode) -->
|
||||
<div class="solo-session-title" id="soloSessionTitle" style="display: none;" aria-live="polite"></div>
|
||||
|
||||
<div class="header-right mobile-collapsed" id="headerRight">
|
||||
<div class="header-right" id="headerRight">
|
||||
<button class="btn-icon-header btn-solo-redock" id="soloRedockBtn" style="display: none;" onclick="window.close()" title="Re-dock to dashboard (close window)" aria-label="Re-dock session to dashboard">⊞</button>
|
||||
<button class="tunnel-indicator" id="tunnelIndicator" style="display: none;" onclick="app.toggleTunnelPanel()" title="Cloudflare Tunnel" aria-label="Tunnel status">
|
||||
<span class="tunnel-dot"></span>
|
||||
@@ -110,8 +116,15 @@
|
||||
<span class="stat-value" id="statMem">--</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-icon-header btn-redraw-terminal btn-redraw-terminal--hidden" onclick="app.restoreTerminalSize()" title="Redraw terminal to fit current screen (Ctrl+Shift+R)" aria-label="Redraw terminal"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg></button>
|
||||
<button class="btn-icon-header btn-response-viewer-header btn-response-viewer-header--hidden" onclick="app.toggleResponseViewer()" title="View last response" aria-label="View last response"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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="btn-icon-header btn-attachments-history btn-attachments-history--hidden" id="attachmentsHistoryBtn" onclick="app.toggleAttachmentHistory()" title="Attachments" aria-label="Open attachment history" aria-expanded="false">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
|
||||
<span class="attachment-history-badge" id="attachmentHistoryBadge" style="display:none;">0</span>
|
||||
</button>
|
||||
<button class="btn-icon-header btn-multimonitor btn-multimonitor--hidden" onclick="app.launchMultiMonitor()" title="Open Codeman across all displays" aria-label="Open Codeman across all displays"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="4" width="13" height="9" rx="1.5"/><rect x="11" y="9" width="11" height="8" rx="1.5"/></svg></button>
|
||||
<button class="btn-icon-header btn-ultracode-agents btn-ultracode-agents--hidden" onclick="app.toggleUltracodeAgentsPanel()" title="Ultracode / Workflow agents" aria-label="Open ultracode workflow agents"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="12" r="2.5"/><path d="M8.2 7.2 15.6 11M8.2 16.8 15.6 13"/></svg></button>
|
||||
<div class="header-plan-usage header-plan-usage--hidden" id="planUsageChip" title="Claude plan usage limits">—</div>
|
||||
<button class="btn-icon-header btn-notifications" onclick="app.toggleNotifications()" title="Notifications" aria-label="Toggle notifications" style="display:none;">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
<span class="notification-badge" id="notifBadge" style="display:none;">0</span>
|
||||
@@ -177,8 +190,8 @@
|
||||
<svg viewBox="0 0 36 36" class="ralph-ring-svg">
|
||||
<defs>
|
||||
<linearGradient id="ralphGradientMini" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#3b82f6" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
<stop offset="0%" stop-color="#3ec8ee" />
|
||||
<stop offset="100%" stop-color="#2b8fd9" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<circle class="ralph-ring-bg" cx="18" cy="18" r="15.9" />
|
||||
@@ -223,8 +236,8 @@
|
||||
<svg viewBox="0 0 100 100" class="ralph-ring-svg-large">
|
||||
<defs>
|
||||
<linearGradient id="ralphGradient" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#3b82f6" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
<stop offset="0%" stop-color="#3ec8ee" />
|
||||
<stop offset="100%" stop-color="#2b8fd9" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<circle class="ralph-ring-track" cx="50" cy="50" r="42" />
|
||||
@@ -497,7 +510,8 @@
|
||||
<div class="shortcuts-grid">
|
||||
<div><kbd>Ctrl</kbd>+<kbd>W</kbd></div><div>Close Session</div>
|
||||
<div><kbd>Ctrl</kbd>+<kbd>Tab</kbd></div><div>Next Session</div>
|
||||
<div><kbd>Alt</kbd>+<kbd>1-9</kbd></div><div>Switch to Tab N</div>
|
||||
<div><kbd>Alt/Option</kbd>+<kbd>[</kbd> / <kbd>Alt/Option</kbd>+<kbd>]</kbd></div><div>Previous / Next Session</div>
|
||||
<div><kbd>Alt/Option</kbd>+<kbd>1-9</kbd></div><div>Switch to Tab N</div>
|
||||
<div><kbd>Ctrl</kbd>+<kbd>L</kbd></div><div>Clear Terminal</div>
|
||||
<div><kbd>Ctrl</kbd>+<kbd>+</kbd></div><div>Increase Font</div>
|
||||
<div><kbd>Ctrl</kbd>+<kbd>-</kbd></div><div>Decrease Font</div>
|
||||
@@ -588,6 +602,29 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ultracode / Workflow agents master-detail panel (opt-in via showUltracodeAgents) -->
|
||||
<div class="subagents-panel ultracode-agents-panel hidden" id="ultracodeAgentsPanel">
|
||||
<div class="subagents-panel-header">
|
||||
<div class="subagents-panel-title">
|
||||
Ultracode Agents <span id="ultracodeCountBadge" class="subagent-badge"></span>
|
||||
</div>
|
||||
<div class="subagents-panel-actions">
|
||||
<button class="btn-icon-sm" onclick="app.toggleUltracodeAgentsPanel()" title="Toggle panel">▲</button>
|
||||
<button class="btn-icon-sm" onclick="app.closeUltracodeAgentsPanel()" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="subagents-panel-body">
|
||||
<div class="subagent-container">
|
||||
<div class="subagent-list ultracode-run-list" id="ultracodeRunList">
|
||||
<div class="subagent-empty">No ultracode runs detected</div>
|
||||
</div>
|
||||
<div class="subagent-detail ultracode-agent-grid" id="ultracodeAgentGrid">
|
||||
<div class="subagent-empty">Select a run to view its agents</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Session Options Modal (includes Respawn Settings) -->
|
||||
<div class="modal" id="sessionOptionsModal">
|
||||
<div class="modal-backdrop" onclick="app.closeSessionOptions()"></div>
|
||||
@@ -608,17 +645,19 @@
|
||||
<div class="modal-tab-content" id="respawn-tab">
|
||||
<!-- Respawn Settings Section -->
|
||||
<div class="session-respawn-section" id="sessionRespawnSection">
|
||||
<div class="respawn-header">
|
||||
<div class="session-respawn-status" id="sessionRespawnStatus">
|
||||
<span class="respawn-status-indicator"></span>
|
||||
<span class="respawn-status-text">Not active</span>
|
||||
</div>
|
||||
<div class="respawn-actions">
|
||||
<button class="btn-toolbar btn-success btn-sm" onclick="app.enableRespawnFromModal()" id="modalEnableRespawnBtn">Enable</button>
|
||||
<button class="btn-toolbar btn-danger btn-sm" onclick="app.stopRespawnFromModal()" id="modalStopRespawnBtn" style="display: none;">Stop</button>
|
||||
</div>
|
||||
<div class="auto-resume-box">
|
||||
<label class="checkbox-inline">
|
||||
<input type="checkbox" id="modalAutoResumeEnabled" onchange="app.autoSaveAutoResume()">
|
||||
<span>Auto-resume when usage limit resets</span>
|
||||
</label>
|
||||
<span class="auto-resume-status" id="autoResumeStatus"></span>
|
||||
<span class="form-hint">If Claude pauses on a usage limit ("limit reached · resets 3pm"), Codeman waits for the reset time and automatically continues the work. Independent of the respawn loop below.</span>
|
||||
</div>
|
||||
|
||||
<div class="respawn-loop-box">
|
||||
<div class="respawn-loop-title">Respawn loop</div>
|
||||
<span class="form-hint respawn-loop-hint">One autonomous work cycle: whenever Claude goes idle, Codeman sends the update prompt, optionally runs /clear + /init, and kickstarts the next round — repeating for the chosen duration. All settings below belong to this loop; configure them, then press Enable.</span>
|
||||
|
||||
<div class="form-row">
|
||||
<label>Duration</label>
|
||||
<div class="duration-presets">
|
||||
@@ -655,10 +694,10 @@
|
||||
<p class="form-hint" id="presetDescriptionHint"></p>
|
||||
</div>
|
||||
|
||||
<div class="form-section-header">Respawn Cycle</div>
|
||||
<div class="form-section-header">Cycle Steps</div>
|
||||
<div class="form-row">
|
||||
<label>1. Update Prompt</label>
|
||||
<textarea id="modalRespawnPrompt" rows="3" placeholder="Prompt to send when idle" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 60px;">update all the docs and CLAUDE.md</textarea>
|
||||
<textarea id="modalRespawnPrompt" rows="1" placeholder="Prompt to send when idle" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 30px;">update all the docs and CLAUDE.md</textarea>
|
||||
</div>
|
||||
|
||||
<div class="respawn-options-row" style="margin: 8px 0;">
|
||||
@@ -670,22 +709,29 @@
|
||||
<input type="checkbox" id="modalRespawnSendInit" checked onchange="app.autoSaveRespawnConfig()">
|
||||
<span>3. Send /init</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>4. Kickstart Prompt</label>
|
||||
<textarea id="modalRespawnKickstart" rows="2" placeholder="Optional: prompt if /init doesn't trigger work" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 40px;"></textarea>
|
||||
<span class="form-hint">Sent only when /init completes but Claude stays idle</span>
|
||||
</div>
|
||||
|
||||
<div class="form-section-header">Behavior</div>
|
||||
<div class="respawn-options-row">
|
||||
<label class="checkbox-inline">
|
||||
<label class="checkbox-inline" title="Presses Enter for plan approvals and default question options">
|
||||
<input type="checkbox" id="modalRespawnAutoAccept" checked onchange="app.autoSaveRespawnConfig()">
|
||||
<span>Auto-accept prompts</span>
|
||||
</label>
|
||||
</div>
|
||||
<span class="form-hint">Auto-accept presses Enter for plan approvals and default question options</span>
|
||||
|
||||
<div class="form-row">
|
||||
<label>4. Kickstart Prompt</label>
|
||||
<textarea id="modalRespawnKickstart" rows="1" placeholder="Optional: prompt if /init doesn't trigger work" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 30px;"></textarea>
|
||||
<span class="form-hint">Sent only when /init completes but Claude stays idle · Auto-accept presses Enter for plan approvals and default options</span>
|
||||
</div>
|
||||
|
||||
<div class="respawn-header">
|
||||
<div class="session-respawn-status" id="sessionRespawnStatus">
|
||||
<span class="respawn-status-indicator"></span>
|
||||
<span class="respawn-status-text">Not active</span>
|
||||
</div>
|
||||
<div class="respawn-actions">
|
||||
<button class="btn-toolbar btn-success btn-sm" onclick="app.enableRespawnFromModal()" id="modalEnableRespawnBtn">Enable</button>
|
||||
<button class="btn-toolbar btn-danger btn-sm" onclick="app.stopRespawnFromModal()" id="modalStopRespawnBtn" style="display: none;">Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- End respawn-loop-box -->
|
||||
</div>
|
||||
</div><!-- End respawn-tab -->
|
||||
|
||||
@@ -908,6 +954,16 @@
|
||||
<!-- Display Tab -->
|
||||
<div class="modal-tab-content" id="settings-display">
|
||||
<div class="settings-grid">
|
||||
<!-- Appearance Section -->
|
||||
<div class="settings-section-header">Appearance</div>
|
||||
<div class="settings-item settings-item-skin" title="Visual theme for this device (not synced)">
|
||||
<span class="settings-item-label">Skin</span>
|
||||
<select id="appSettingsSkin" class="form-select">
|
||||
<option value="daylight-blue">Daylight Blue</option>
|
||||
<option value="daylight-green">Daylight Green</option>
|
||||
<option value="og">OG Codeman</option>
|
||||
</select>
|
||||
</div>
|
||||
<!-- Input Section -->
|
||||
<div class="settings-section-header">Input</div>
|
||||
<div class="settings-item settings-item-multiline" title="Shows typed characters instantly via overlay while forwarding keystrokes to the server in the background. Enables Tab completion, preserves input across tab switches, and protects against session crashes. Recommended for mobile and high-latency connections.">
|
||||
@@ -954,6 +1010,13 @@
|
||||
|
||||
<!-- Header Displays Section -->
|
||||
<div class="settings-section-header">Header Displays</div>
|
||||
<div class="settings-item" title="Show Claude plan usage limits (5-hour & weekly) in the header. Applies to newly created sessions.">
|
||||
<span class="settings-item-label">Plan Usage Limits</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowPlanUsageLimits">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show A-/A+ font size buttons in header">
|
||||
<span class="settings-item-label">Font Controls</span>
|
||||
<label class="switch switch-sm">
|
||||
@@ -968,20 +1031,6 @@
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show total token count in header">
|
||||
<span class="settings-item-label">Token Count</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowTokenCount" checked>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show estimated cost next to token count">
|
||||
<span class="settings-item-label">Show Cost ($)</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowCost">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show session lifecycle log button in header">
|
||||
<span class="settings-item-label">Lifecycle Log</span>
|
||||
<label class="switch switch-sm">
|
||||
@@ -996,6 +1045,13 @@
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show the attachments button in header (opens the attachment history drawer)">
|
||||
<span class="settings-item-label">Attachments Button</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowAttachmentsButton">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show the multi-monitor button in the header (opens Codeman spanned across all displays)">
|
||||
<span class="settings-item-label">Multi-monitor Button</span>
|
||||
<label class="switch switch-sm">
|
||||
@@ -1003,6 +1059,13 @@
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show a terminal redraw button in the header — refit the terminal to the current screen size (useful when switching between devices)">
|
||||
<span class="settings-item-label">Redraw Terminal Button</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowRedrawButton">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Tab Bar Section -->
|
||||
<div class="settings-section-header">Tab Bar</div>
|
||||
@@ -1044,6 +1107,20 @@
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show ultracode / Workflow runs as a master-detail tab (tasks on the left, agents with tokens + tool calls on the right)">
|
||||
<span class="settings-item-label">Ultracode Agents</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowUltracodeAgents">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Pop a floating window for each active ultracode / Workflow run, connected by a line to its session tab (additional to the Ultracode Agents panel)">
|
||||
<span class="settings-item-label">Ultracode Floating Windows</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsUltracodeFloatingWindows">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Subagent Options Section -->
|
||||
<div class="settings-section-header">Subagent Options</div>
|
||||
@@ -1156,6 +1233,8 @@
|
||||
<option value="claude-fable-5">Fable 5</option>
|
||||
<option value="opus[1m]">Opus (1M context)</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="claude-opus-4-6[1m]">Opus 4.6 (1M context)</option>
|
||||
<option value="claude-opus-4-6">Opus 4.6</option>
|
||||
<option value="sonnet">Sonnet</option>
|
||||
<option value="haiku">Haiku</option>
|
||||
</select>
|
||||
@@ -1885,6 +1964,8 @@
|
||||
<script defer src="notification-manager.js"></script>
|
||||
<script defer src="keyboard-accessory.js"></script>
|
||||
<script defer src="input-cjk.js"></script>
|
||||
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
|
||||
<script defer src="sanitize-html.js"></script>
|
||||
<script defer src="app.js"></script>
|
||||
<script defer src="terminal-ui.js"></script>
|
||||
<script defer src="respawn-ui.js"></script>
|
||||
@@ -1892,10 +1973,12 @@
|
||||
<script defer src="orchestrator-panel.js"></script>
|
||||
<script defer src="settings-ui.js"></script>
|
||||
<script defer src="panels-ui.js"></script>
|
||||
<script defer src="ultracode-panel.js"></script>
|
||||
<script defer src="session-ui.js"></script>
|
||||
<script defer src="ralph-wizard.js"></script>
|
||||
<script defer src="api-client.js"></script>
|
||||
<script defer src="subagent-windows.js"></script>
|
||||
<script defer src="ultracode-windows.js"></script>
|
||||
<script defer src="image-input.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+123
-123
@@ -14,13 +14,21 @@
|
||||
* This means compositionstart fires even for English text, and compositionend
|
||||
* may not fire until the user explicitly confirms (space, candidate tap).
|
||||
*
|
||||
* We use InputEvent.inputType to distinguish:
|
||||
* - `insertCompositionText`: tentative text, may change (CJK candidates, pinyin)
|
||||
* - `insertText`: final committed text (confirmed word, punctuation, space)
|
||||
* During composition, all input events are ignored — only compositionend
|
||||
* triggers a flush (CJK candidate selection).
|
||||
*
|
||||
* During composition, `insertText` events are flushed immediately (punctuation,
|
||||
* English words confirmed by IME). `insertCompositionText` waits for
|
||||
* compositionend (CJK candidate selection).
|
||||
* ## iOS dictation challenge (WebKit Bug 261764)
|
||||
*
|
||||
* iOS/iPadOS voice dictation does NOT fire composition events. Text arrives
|
||||
* as bare input events with isComposing === false. Dictation refinement is
|
||||
* a delete→reinsert cycle (deleteContentBackward + insertReplacementText),
|
||||
* all within a few ms. Flushing on every input event would send irrevocable
|
||||
* provisional text to the PTY, causing duplication when the IME replaces it.
|
||||
*
|
||||
* Solution: outside composition, flush is DEBOUNCED (200ms). The entire
|
||||
* delete→reinsert cycle collapses into one flush of the final textarea value.
|
||||
* Keyboard typing of single printable characters still goes through the
|
||||
* keydown handler (immediate, no debounce).
|
||||
*
|
||||
* ## Phantom character for Android backspace
|
||||
*
|
||||
@@ -41,16 +49,30 @@
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const CjkInput = (() => {
|
||||
let _textarea = null;
|
||||
let _terminalContainer = null;
|
||||
let _xtermTextarea = null;
|
||||
let _send = null;
|
||||
let _initialized = false;
|
||||
let _composing = false;
|
||||
let _flushTimer = null;
|
||||
let _dictationActive = false;
|
||||
let _dictationDecayTimer = null;
|
||||
let _keydownSentAt = 0;
|
||||
const _listeners = {};
|
||||
|
||||
// Zero-width space: always present in textarea so Android backspace has
|
||||
// something to delete, triggering the `input` event we need to detect it.
|
||||
const PHANTOM = '\u200B';
|
||||
const PHANTOM = '';
|
||||
|
||||
// Two-tier debounce for non-composition input:
|
||||
// - KEYBOARD: short debounce (third-party IMEs like Doubao may not fire
|
||||
// composition events even for keyboard CJK typing)
|
||||
// - DICTATION: long debounce (iOS voice dictation sends delete→reinsert
|
||||
// refinement cycles without composition events — WebKit Bug 261764)
|
||||
//
|
||||
// Dictation is detected by deleteContentBackward on non-empty text or
|
||||
// insertReplacementText — signals that the IME is rewriting provisional
|
||||
// text. Once detected, dictation mode persists for 3s (covers multi-word
|
||||
// dictation with natural pauses between words).
|
||||
const DEBOUNCE_KEYBOARD_MS = 150;
|
||||
const DEBOUNCE_DICTATION_MS = 1500;
|
||||
const DICTATION_DECAY_MS = 3000;
|
||||
|
||||
const PASSTHROUGH_KEYS = {
|
||||
ArrowUp: '\x1b[A',
|
||||
@@ -66,35 +88,15 @@ const CjkInput = (() => {
|
||||
c: '\x03', d: '\x04', l: '\x0c', z: '\x1a', a: '\x01', e: '\x05',
|
||||
};
|
||||
|
||||
/** Strip phantom characters from a string */
|
||||
function _strip(str) {
|
||||
return str.replace(/\u200B/g, '');
|
||||
return str.replace(//g, '');
|
||||
}
|
||||
|
||||
/** Reset textarea to phantom-only state with cursor at end */
|
||||
function _resetToPhantom() {
|
||||
_textarea.value = PHANTOM;
|
||||
_textarea.setSelectionRange(1, 1);
|
||||
}
|
||||
|
||||
function _isMobileComposer() {
|
||||
return !!(
|
||||
_textarea &&
|
||||
typeof MobileDetection !== 'undefined' &&
|
||||
MobileDetection.isTouchDevice() &&
|
||||
_textarea.classList.contains('cjk-input-visible')
|
||||
);
|
||||
}
|
||||
|
||||
function _resetInput() {
|
||||
if (_isMobileComposer()) {
|
||||
_textarea.value = '';
|
||||
} else {
|
||||
_resetToPhantom();
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if textarea contains only phantom(s) or is empty — no real user text */
|
||||
function _isEffectivelyEmpty() {
|
||||
return !_strip(_textarea.value);
|
||||
}
|
||||
@@ -108,61 +110,77 @@ const CjkInput = (() => {
|
||||
_resetToPhantom();
|
||||
}
|
||||
|
||||
/** Cancel any pending debounced flush */
|
||||
function _cancelDebouncedFlush() {
|
||||
if (_flushTimer) {
|
||||
clearTimeout(_flushTimer);
|
||||
_flushTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Mark that dictation rewriting is in progress */
|
||||
function _enterDictationMode() {
|
||||
_dictationActive = true;
|
||||
clearTimeout(_dictationDecayTimer);
|
||||
_dictationDecayTimer = setTimeout(() => {
|
||||
_dictationActive = false;
|
||||
_dictationDecayTimer = null;
|
||||
}, DICTATION_DECAY_MS);
|
||||
}
|
||||
|
||||
/** Schedule a flush after input settles */
|
||||
function _debouncedFlush() {
|
||||
_cancelDebouncedFlush();
|
||||
const delay = _dictationActive ? DEBOUNCE_DICTATION_MS : DEBOUNCE_KEYBOARD_MS;
|
||||
_flushTimer = setTimeout(() => {
|
||||
_flushTimer = null;
|
||||
_flush();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
return {
|
||||
init({ send }) {
|
||||
if (_initialized) this.destroy();
|
||||
|
||||
_send = send;
|
||||
_composing = false;
|
||||
_flushTimer = null;
|
||||
_textarea = document.getElementById('cjkInput');
|
||||
if (!_textarea) return this;
|
||||
_terminalContainer = document.getElementById('terminalContainer');
|
||||
|
||||
// Seed the phantom character for the hidden/immediate CJK path.
|
||||
_resetInput();
|
||||
_resetToPhantom();
|
||||
|
||||
_listeners.mousedown = (e) => { e.stopPropagation(); };
|
||||
_listeners.focus = () => {
|
||||
window.cjkActive = true;
|
||||
if (_isMobileComposer() && _textarea.value === PHANTOM) {
|
||||
_textarea.value = '';
|
||||
return;
|
||||
if (!_textarea.value) _resetToPhantom();
|
||||
};
|
||||
_listeners.blur = () => {
|
||||
// Keep cjkActive while CJK input is visible — iOS dictation and system
|
||||
// UI may steal focus temporarily, and clearing the flag during that
|
||||
// window lets xterm's onData process duplicated input.
|
||||
if (!_textarea.classList.contains('cjk-input-visible')) {
|
||||
window.cjkActive = false;
|
||||
}
|
||||
// Restore phantom if textarea was emptied while blurred
|
||||
if (!_textarea.value && !_isMobileComposer()) _resetToPhantom();
|
||||
// Reset composing state — some IMEs fire compositionstart without a
|
||||
// matching compositionend, leaving _composing stuck true and blocking
|
||||
// all subsequent input events.
|
||||
_composing = false;
|
||||
};
|
||||
_listeners.blur = () => { window.cjkActive = false; };
|
||||
_textarea.addEventListener('mousedown', _listeners.mousedown);
|
||||
_textarea.addEventListener('focus', _listeners.focus);
|
||||
_textarea.addEventListener('blur', _listeners.blur);
|
||||
|
||||
_listeners.xtermFocusRedirect = () => {
|
||||
if (!_isMobileComposer()) return;
|
||||
_textarea.focus();
|
||||
};
|
||||
if (_terminalContainer) {
|
||||
_xtermTextarea = _terminalContainer.querySelector('.xterm-helper-textarea');
|
||||
if (_xtermTextarea) {
|
||||
_xtermTextarea.addEventListener('focus', _listeners.xtermFocusRedirect, { capture: true });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Composition tracking ──
|
||||
// ── Composition tracking (keyboard IME — works for CJK typing) ──
|
||||
_listeners.compositionstart = () => {
|
||||
_composing = true;
|
||||
if (_isMobileComposer()) {
|
||||
if (_textarea.value === PHANTOM) _textarea.value = '';
|
||||
return;
|
||||
}
|
||||
// Clear phantom so IME sees a clean textarea — some IMEs include
|
||||
// existing text in the composition region which would corrupt input.
|
||||
if (_textarea.value === PHANTOM) {
|
||||
_textarea.value = '';
|
||||
}
|
||||
_cancelDebouncedFlush();
|
||||
// Leave textarea.value untouched — programmatic changes during
|
||||
// compositionstart cancel the IME composition on iOS Safari.
|
||||
};
|
||||
_listeners.compositionend = () => {
|
||||
_composing = false;
|
||||
if (_isMobileComposer()) return;
|
||||
_cancelDebouncedFlush();
|
||||
// Defer flush: some Android IMEs haven't committed text to textarea
|
||||
// when compositionend fires. setTimeout(0) ensures we read the final value.
|
||||
setTimeout(_flush, 0);
|
||||
@@ -172,56 +190,40 @@ const CjkInput = (() => {
|
||||
|
||||
// ── Keydown: special keys work REGARDLESS of composition state ──
|
||||
_listeners.keydown = (e) => {
|
||||
// Enter: flush accumulated text (or bare Enter if empty).
|
||||
// No isComposing guard — Android IMEs set isComposing=true for English
|
||||
// prediction, but Enter should ALWAYS send. We preventDefault to stop
|
||||
// the IME from also handling Enter (which could double-send or do nothing).
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
_composing = false;
|
||||
_cancelDebouncedFlush();
|
||||
const val = _strip(_textarea.value);
|
||||
if (val) {
|
||||
_send(val + '\r');
|
||||
} else {
|
||||
_send('\r');
|
||||
}
|
||||
_resetInput();
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
|
||||
// Escape: clear textarea (always works)
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
_composing = false;
|
||||
_resetInput();
|
||||
_cancelDebouncedFlush();
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl combos: forward to PTY (always works)
|
||||
if (e.ctrlKey && CTRL_KEYS[e.key]) {
|
||||
e.preventDefault();
|
||||
_send(CTRL_KEYS[e.key]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Below: only when NOT composing (composing keystrokes belong to IME)
|
||||
if (_composing) return;
|
||||
|
||||
if (_isMobileComposer()) {
|
||||
if (e.key === 'Backspace' && _isEffectivelyEmpty()) {
|
||||
e.preventDefault();
|
||||
_send('\x7f');
|
||||
return;
|
||||
}
|
||||
if (PASSTHROUGH_KEYS[e.key] && _isEffectivelyEmpty()) {
|
||||
e.preventDefault();
|
||||
_send(PASSTHROUGH_KEYS[e.key]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Below: only when NOT composing (composing keystrokes belong to IME).
|
||||
// Also check isComposing/keyCode 229 — the first keydown of a CJK
|
||||
// sequence arrives BEFORE compositionstart, so _composing is still false.
|
||||
if (_composing || e.isComposing || e.keyCode === 229) return;
|
||||
|
||||
// Backspace: forward to PTY when no real text in textarea
|
||||
// (Desktop path — Android uses the input event + phantom approach)
|
||||
if (e.key === 'Backspace' && _isEffectivelyEmpty()) {
|
||||
e.preventDefault();
|
||||
_send('\x7f');
|
||||
@@ -236,62 +238,62 @@ const CjkInput = (() => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Single printable character: send immediately to PTY
|
||||
// (Desktop keyboards with physical keys — Android sends 'Unidentified')
|
||||
// Single printable character: send immediately to PTY.
|
||||
// Third-party IMEs on iOS may ignore preventDefault, so the char
|
||||
// still enters the textarea and fires an input event — _keydownSentAt
|
||||
// tells the input handler to skip that echo.
|
||||
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey && _isEffectivelyEmpty()) {
|
||||
e.preventDefault();
|
||||
_send(e.key);
|
||||
_keydownSentAt = performance.now();
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
};
|
||||
_textarea.addEventListener('keydown', _listeners.keydown);
|
||||
|
||||
// ── Input event: the primary path for Android virtual keyboards ──
|
||||
// Android sends keyCode 229 + key "Unidentified" for virtual key presses,
|
||||
// making keydown unreliable. input fires AFTER character insertion and
|
||||
// carries inputType which tells us whether the text is final or tentative.
|
||||
// ── Input event: primary path for virtual keyboards + dictation ──
|
||||
_listeners.input = (e) => {
|
||||
if (_isMobileComposer()) {
|
||||
if (_textarea.value.includes(PHANTOM)) {
|
||||
_textarea.value = _strip(_textarea.value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Backspace / delete detection ──
|
||||
// Android long-press backspace generates rapid deleteContentBackward events.
|
||||
// The phantom character ensures the textarea is never truly empty, so each
|
||||
// press/repeat fires an input event that we can catch here.
|
||||
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
||||
if (_composing) return;
|
||||
if (_isEffectivelyEmpty()) {
|
||||
// No real text left — forward backspace to PTY
|
||||
_cancelDebouncedFlush();
|
||||
_send('\x7f');
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
// User is editing their own text in the textarea — let it be.
|
||||
// Ensure phantom is still present for the NEXT backspace.
|
||||
// Delete on non-empty text outside composition = dictation rewrite.
|
||||
// The IME is revising provisional text — switch to long debounce.
|
||||
_enterDictationMode();
|
||||
if (!_textarea.value.startsWith(PHANTOM)) {
|
||||
_textarea.value = PHANTOM + _textarea.value;
|
||||
_textarea.setSelectionRange(1, 1);
|
||||
}
|
||||
_debouncedFlush();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_composing) {
|
||||
// insertText during composition = IME committed final text
|
||||
// (e.g., punctuation key inserts 。directly, or IME confirms a word).
|
||||
// Flush immediately — this text won't change.
|
||||
if (e.inputType === 'insertText') {
|
||||
_flush();
|
||||
return;
|
||||
}
|
||||
// insertCompositionText = IME is still working (pinyin, candidates,
|
||||
// English prediction). Wait for compositionend to flush.
|
||||
// insertReplacementText = dictation/autocorrect refinement
|
||||
if (e.inputType === 'insertReplacementText') {
|
||||
_enterDictationMode();
|
||||
_debouncedFlush();
|
||||
return;
|
||||
}
|
||||
// Outside composition: send immediately
|
||||
_flush();
|
||||
|
||||
if (_composing) return;
|
||||
|
||||
// Keydown handler already sent this character — just clear the
|
||||
// textarea echo that the IME inserted despite preventDefault.
|
||||
if (performance.now() - _keydownSentAt < 100) {
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
|
||||
// Outside composition: keyboard typing or voice dictation.
|
||||
// If dictation mode was detected (delete/replacement events seen
|
||||
// recently), use long debounce. Otherwise short debounce for keyboard.
|
||||
_debouncedFlush();
|
||||
};
|
||||
_textarea.addEventListener('input', _listeners.input);
|
||||
|
||||
@@ -300,18 +302,16 @@ const CjkInput = (() => {
|
||||
},
|
||||
|
||||
destroy() {
|
||||
_cancelDebouncedFlush();
|
||||
clearTimeout(_dictationDecayTimer);
|
||||
_dictationActive = false;
|
||||
if (_textarea) {
|
||||
for (const [event, handler] of Object.entries(_listeners)) {
|
||||
if (handler) _textarea.removeEventListener(event, handler);
|
||||
}
|
||||
}
|
||||
if (_xtermTextarea && _listeners.xtermFocusRedirect) {
|
||||
_xtermTextarea.removeEventListener('focus', _listeners.xtermFocusRedirect, { capture: true });
|
||||
}
|
||||
window.cjkActive = false;
|
||||
_composing = false;
|
||||
_terminalContainer = null;
|
||||
_xtermTextarea = null;
|
||||
for (const key of Object.keys(_listeners)) delete _listeners[key];
|
||||
_initialized = false;
|
||||
},
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
* Defines two exports:
|
||||
*
|
||||
* - KeyboardAccessoryBar (singleton object) — Quick action buttons shown above the virtual
|
||||
* keyboard on mobile: arrow up/down, /init, /clear, paste, Esc, and dismiss.
|
||||
* keyboard on mobile: arrow up/down, /init, /clear, /compact, paste, Esc, and dismiss.
|
||||
* The paste button opens a dialog that handles both text paste and image attach
|
||||
* (native picker + best-effort image paste, routed through app._uploadAndInsertImages).
|
||||
* Destructive actions (/clear) require double-tap confirmation (2s amber state).
|
||||
* Destructive actions (/clear, /compact) require double-tap confirmation (2s amber state).
|
||||
* Commands are sent as text + Enter separately for Ink compatibility.
|
||||
* Only initializes on touch devices (MobileDetection.isTouchDevice guard).
|
||||
*
|
||||
@@ -100,6 +100,7 @@ const KeyboardAccessoryBar = {
|
||||
<button class="accessory-btn" data-action="esc" title="Escape">Esc</button>
|
||||
<button class="accessory-btn" data-action="init" title="/init">/init</button>
|
||||
<button class="accessory-btn" data-action="clear" title="/clear">/clear</button>
|
||||
<button class="accessory-btn" data-action="compact" title="/compact">/compact</button>
|
||||
<button class="accessory-btn accessory-btn-dismiss" data-action="dismiss" title="Dismiss keyboard">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
|
||||
<path d="M19 9l-7 7-7-7"/>
|
||||
@@ -129,7 +130,7 @@ const KeyboardAccessoryBar = {
|
||||
// Refocus terminal so keyboard stays open (tap blurs terminal → keyboard dismisses → toolbar shifts)
|
||||
const refocusActions = new Set(['scroll-up', 'scroll-down', 'arrow-left', 'arrow-right', 'tab', 'shift-tab', 'ctrl-o', 'opt-enter', 'esc', 'effort-max']);
|
||||
if (refocusActions.has(action) ||
|
||||
(action === 'clear' && this._confirmAction)) {
|
||||
((action === 'clear' || action === 'compact') && this._confirmAction)) {
|
||||
if (typeof app !== 'undefined' && app.terminal) {
|
||||
app.terminal.focus();
|
||||
}
|
||||
@@ -192,11 +193,12 @@ const KeyboardAccessoryBar = {
|
||||
case 'init':
|
||||
this.sendCommand('/init');
|
||||
break;
|
||||
case 'clear': {
|
||||
// Require double-tap: first tap turns amber, second tap within 2s sends
|
||||
case 'clear':
|
||||
case 'compact': {
|
||||
const cmd = action === 'clear' ? '/clear' : '/compact';
|
||||
if (this._confirmAction === action && this._confirmTimer) {
|
||||
this.clearConfirm();
|
||||
this.sendCommand('/clear');
|
||||
this.sendCommand(cmd);
|
||||
} else {
|
||||
this.setConfirm(action, btn);
|
||||
}
|
||||
@@ -300,7 +302,10 @@ const KeyboardAccessoryBar = {
|
||||
const sendText = () => {
|
||||
const text = textarea.value;
|
||||
close();
|
||||
if (text) app.sendInput(text);
|
||||
if (text) {
|
||||
app.sendInput(text);
|
||||
setTimeout(() => app.sendInput('\r'), 80);
|
||||
}
|
||||
};
|
||||
|
||||
// Filter to images, close the dialog, and hand off to the shared
|
||||
|
||||
@@ -139,6 +139,9 @@ const MobileDetection = {
|
||||
resizeTimeout = setTimeout(() => {
|
||||
this.updateBodyClass();
|
||||
this.updateAppHeight();
|
||||
// Tab auto-wrap is width-driven, so it must re-evaluate on resize — the only
|
||||
// other trigger is a tab content render. No-op on mobile/tablet (method bails).
|
||||
if (typeof app !== 'undefined') app.updateTabOverflowMode?.();
|
||||
}, 100);
|
||||
};
|
||||
window.addEventListener('resize', this._resizeHandler);
|
||||
@@ -288,49 +291,60 @@ const KeyboardHandler = {
|
||||
updateLayoutForKeyboard() {
|
||||
if (!window.visualViewport) return;
|
||||
|
||||
// Only adjust on mobile
|
||||
if (!MobileDetection.isSmallScreen() && !MobileDetection.isMediumScreen()) {
|
||||
if (!MobileDetection.isTouchDevice()) {
|
||||
this.resetLayout();
|
||||
return;
|
||||
}
|
||||
|
||||
const toolbar = document.querySelector('.toolbar');
|
||||
const accessoryBar = document.querySelector('.keyboard-accessory-bar');
|
||||
const cjkInput = document.getElementById('cjkInput');
|
||||
const main = document.querySelector('.main');
|
||||
const isSmallMedium = MobileDetection.isSmallScreen() || MobileDetection.isMediumScreen();
|
||||
|
||||
if (this.keyboardVisible) {
|
||||
// Calculate how far the toolbar (position:fixed, bottom:0) needs to
|
||||
// translate up so it sits at the bottom of the visual viewport.
|
||||
// This formula accounts for iOS scrolling the visual viewport (offsetTop)
|
||||
// when the user types in xterm's hidden textarea.
|
||||
const appEl = document.querySelector('.app');
|
||||
const layoutHeight = appEl?.getBoundingClientRect().bottom || window.innerHeight;
|
||||
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
|
||||
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
|
||||
|
||||
// Move toolbar and accessory bar above keyboard.
|
||||
// When keyboardOffset is 0 (viewport scrolled to layout bottom),
|
||||
// the bars are naturally positioned via their CSS bottom values —
|
||||
// just clear the transforms. Never dismiss keyboard state here;
|
||||
// that's handleViewportResize's job.
|
||||
if (toolbar) {
|
||||
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
||||
}
|
||||
if (accessoryBar) {
|
||||
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
||||
}
|
||||
if (cjkInput?.classList.contains('cjk-input-visible')) {
|
||||
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
||||
}
|
||||
|
||||
// Reserve only Codeman's visible controls. The OS keyboard is outside
|
||||
// the visual viewport; adding its height here creates a large blank area
|
||||
// above the mobile toolbar on iPhone.
|
||||
const keyboardHeight = this.initialViewportHeight - (window.visualViewport.height || window.innerHeight);
|
||||
if (main && keyboardHeight > 0) {
|
||||
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0;
|
||||
main.style.paddingBottom = `${84 + cjkInputHeight}px`;
|
||||
const accessoryBar = document.querySelector('.keyboard-accessory-bar');
|
||||
|
||||
if (isSmallMedium) {
|
||||
// Phones/small tablets: toolbar and accessory bar are position:fixed
|
||||
// via CSS. Use translateY to lift them above the keyboard.
|
||||
const toolbar = document.querySelector('.toolbar');
|
||||
const main = document.querySelector('.main');
|
||||
|
||||
const layoutHeight = window.innerHeight;
|
||||
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
|
||||
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
|
||||
|
||||
if (toolbar) {
|
||||
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
||||
}
|
||||
if (accessoryBar) {
|
||||
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
||||
}
|
||||
if (main && keyboardHeight > 0) {
|
||||
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0;
|
||||
main.style.paddingBottom = `${84 + cjkInputHeight}px`;
|
||||
}
|
||||
} else if (keyboardHeight > 0) {
|
||||
// iPad: use direct bottom positioning (translateY unreliable —
|
||||
// iOS auto-scrolls the visual viewport, making keyboardOffset ≈ 0).
|
||||
if (accessoryBar) {
|
||||
accessoryBar.style.bottom = `${keyboardHeight}px`;
|
||||
}
|
||||
}
|
||||
|
||||
// CJK textarea positioning (always position:fixed on touch devices).
|
||||
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
|
||||
if (isSmallMedium) {
|
||||
// Phones: use translateY like toolbar/accessory bar.
|
||||
const layoutHeight = window.innerHeight;
|
||||
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
|
||||
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
|
||||
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
||||
cjkInput.style.bottom = '';
|
||||
} else {
|
||||
// iPad: direct bottom = keyboard + accessory bar height.
|
||||
cjkInput.style.bottom = `${keyboardHeight + 44}px`;
|
||||
cjkInput.style.transform = '';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.resetLayout();
|
||||
@@ -349,9 +363,11 @@ const KeyboardHandler = {
|
||||
}
|
||||
if (accessoryBar) {
|
||||
accessoryBar.style.transform = '';
|
||||
accessoryBar.style.bottom = '';
|
||||
}
|
||||
if (cjkInput) {
|
||||
cjkInput.style.transform = '';
|
||||
cjkInput.style.bottom = '';
|
||||
}
|
||||
if (main) {
|
||||
main.style.paddingBottom = '';
|
||||
|
||||
+97
-275
@@ -36,6 +36,13 @@ html.mobile-init .file-browser-panel {
|
||||
html {
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
/* No "open in new window" (detach) on phones/tablets — popped-out browser
|
||||
windows aren't usable there. !important beats the hover/detached reveal
|
||||
rules in styles.css */
|
||||
.session-tab .tab-detach {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
@@ -94,55 +101,12 @@ html.mobile-init .file-browser-panel {
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.mobile-header-utility-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
margin: -4px 0.2rem -4px 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
color: var(--text-muted);
|
||||
order: -1;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mobile-header-utility-toggle.active,
|
||||
.mobile-header-utility-toggle:active {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* Inline, always-visible header utilities (eye / multimonitor). The
|
||||
position:fixed collapsible tray (02fa3f3) had its expand toggle reverted on
|
||||
master but left this container permanently `mobile-collapsed` → the response
|
||||
viewer eye became unreachable on phones. Restored to the simple inline flow. */
|
||||
.header-right {
|
||||
position: fixed;
|
||||
top: calc(52px + var(--safe-area-top));
|
||||
left: calc(0.5rem + var(--safe-area-left));
|
||||
right: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
max-width: calc(100vw - 1rem - var(--safe-area-left) - var(--safe-area-right));
|
||||
padding: 0.35rem;
|
||||
background: rgba(10, 10, 10, 0.96);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
z-index: 2000;
|
||||
}
|
||||
|
||||
.header-right::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.header-right.mobile-collapsed {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.btn-icon-header:not(.btn-sm) {
|
||||
@@ -224,6 +188,12 @@ html.mobile-init .file-browser-panel {
|
||||
|
||||
/* ---- Settings Modal: Tablet Optimizations ---- */
|
||||
|
||||
/* Modals must stack above the fixed tablet header (z-index 1200) so the
|
||||
modal header with the close button stays visible */
|
||||
.modal {
|
||||
z-index: 1300;
|
||||
}
|
||||
|
||||
.modal-tabs {
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
@@ -446,49 +416,8 @@ html.mobile-init .file-browser-panel {
|
||||
}
|
||||
|
||||
.header-right {
|
||||
position: fixed;
|
||||
top: calc(40px + var(--safe-area-top));
|
||||
left: calc(0.3rem + var(--safe-area-left));
|
||||
right: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 0.2rem;
|
||||
gap: 0.1rem;
|
||||
max-width: calc(100vw - 0.6rem - var(--safe-area-left) - var(--safe-area-right));
|
||||
padding: 0.25rem;
|
||||
background: rgba(10, 10, 10, 0.96);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
border-left: none;
|
||||
z-index: 2000;
|
||||
}
|
||||
|
||||
.header-right::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.header-right.mobile-collapsed {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.mobile-header-utility-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
margin: -6px 0.15rem -6px 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
color: var(--text-muted);
|
||||
order: -1;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
flex-shrink: 0;
|
||||
border-left: none;
|
||||
}
|
||||
@@ -505,7 +434,9 @@ html.mobile-init .file-browser-panel {
|
||||
height: 12px;
|
||||
}
|
||||
|
||||
/* Hide header settings gear and lifecycle log on mobile - settings moved to toolbar */
|
||||
/* Hide header settings gear and lifecycle log on mobile - settings moved to toolbar.
|
||||
(The attachments button is opt-in / default-hidden everywhere via its own
|
||||
--hidden marker, so it needs no mobile-specific rule here.) */
|
||||
.btn-icon-header.btn-settings,
|
||||
.btn-icon-header.btn-lifecycle-log {
|
||||
display: none !important;
|
||||
@@ -1134,85 +1065,7 @@ html.mobile-init .file-browser-panel {
|
||||
}
|
||||
|
||||
/* Paste overlay for iOS clipboard access */
|
||||
.paste-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 15vh;
|
||||
}
|
||||
|
||||
.paste-dialog {
|
||||
background: var(--bg-secondary, #1e1e2e);
|
||||
border: 1px solid var(--border-color, #444);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
width: calc(100% - 24px);
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.paste-textarea {
|
||||
width: 100%;
|
||||
min-height: 80px;
|
||||
max-height: 200px;
|
||||
background: var(--bg-primary, #0d0d14);
|
||||
color: var(--text-primary, #e0e0e0);
|
||||
border: 1px solid var(--border-color, #444);
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
font-family: inherit;
|
||||
font-size: 16px;
|
||||
resize: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.paste-textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-color, #7aa2f7);
|
||||
}
|
||||
|
||||
.paste-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.paste-cancel, .paste-new, .paste-send, .paste-image {
|
||||
padding: 8px 18px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Image attach button — left-aligned, accent outline */
|
||||
.paste-image {
|
||||
margin-right: auto;
|
||||
background: var(--bg-tertiary, #333);
|
||||
color: var(--accent-color, #7aa2f7);
|
||||
border: 1px solid var(--accent-color, #7aa2f7);
|
||||
}
|
||||
|
||||
.paste-cancel {
|
||||
background: var(--bg-tertiary, #333);
|
||||
color: var(--text-secondary, #aaa);
|
||||
}
|
||||
|
||||
.paste-new {
|
||||
background: var(--bg-tertiary, #333);
|
||||
color: var(--accent-color, #7aa2f7);
|
||||
border: 1px solid var(--accent-color, #7aa2f7);
|
||||
}
|
||||
|
||||
.paste-send {
|
||||
background: var(--accent-color, #7aa2f7);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
}
|
||||
/* Paste overlay styles extracted to universal section below (line ~2293+) */
|
||||
|
||||
/* LEGACY: Hide old toolbar select (no longer used on mobile) */
|
||||
.toolbar-select {
|
||||
@@ -1258,6 +1111,13 @@ html.mobile-init .file-browser-panel {
|
||||
max-height: 35vh;
|
||||
}
|
||||
|
||||
/* Modals must stack above the fixed mobile header (z-index 1200), or the
|
||||
modal header with the close button is buried underneath it and the
|
||||
full-screen modal cannot be dismissed */
|
||||
.modal {
|
||||
z-index: 1300;
|
||||
}
|
||||
|
||||
/* Full-screen modals on phones */
|
||||
.modal-content {
|
||||
width: 100%;
|
||||
@@ -1571,42 +1431,36 @@ html.mobile-init .file-browser-panel {
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* Duration preset buttons — grid layout, 4 columns for even spacing */
|
||||
/* Duration preset buttons — one compact row */
|
||||
.duration-presets {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.duration-preset-btn {
|
||||
min-height: 32px;
|
||||
padding: 0.2rem 0.25rem;
|
||||
font-size: 0.65rem;
|
||||
border-radius: 5px;
|
||||
min-height: 24px;
|
||||
padding: 0.1rem 0.4rem;
|
||||
font-size: 0.6rem;
|
||||
border-radius: 4px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Custom duration — spans full row below */
|
||||
.duration-custom {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
gap: 0.2rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.duration-custom .duration-preset-btn {
|
||||
flex: 0 0 auto;
|
||||
min-width: 50px;
|
||||
}
|
||||
|
||||
.duration-custom-input.visible {
|
||||
flex: 1;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.duration-custom-input input {
|
||||
width: 100%;
|
||||
min-height: 28px;
|
||||
width: 64px;
|
||||
min-height: 24px;
|
||||
font-size: 16px; /* Prevents iOS zoom */
|
||||
padding: 0.1rem 0.3rem;
|
||||
}
|
||||
|
||||
/* Preset selector row — full-width dropdown, buttons below */
|
||||
@@ -1665,6 +1519,16 @@ html.mobile-init .file-browser-panel {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
/* Respawn-loop box title matches the auto-resume title; its cycle-step
|
||||
checkboxes match the step labels */
|
||||
#sessionOptionsModal .respawn-loop-title {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
#sessionOptionsModal .respawn-loop-box .checkbox-inline {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
|
||||
/* Respawn options row — stack if needed */
|
||||
#sessionOptionsModal .respawn-options-row {
|
||||
gap: 0.5rem;
|
||||
@@ -2235,95 +2099,9 @@ html.mobile-init .file-browser-panel {
|
||||
}
|
||||
|
||||
|
||||
/* ============================================================================
|
||||
Keyboard Accessory Bar — all mobile/tablet sizes
|
||||
Visual styles extracted from phone breakpoint so they apply on iPad too.
|
||||
Phone-specific positioning (position: fixed) remains in @media (max-width: 430px).
|
||||
============================================================================ */
|
||||
.keyboard-accessory-bar {
|
||||
display: none;
|
||||
height: 44px;
|
||||
background: #1a1a1a;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
padding: 6px 8px;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
z-index: 51;
|
||||
}
|
||||
|
||||
.keyboard-accessory-bar.visible {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.keyboard-accessory-bar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.accessory-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
gap: 4px;
|
||||
padding: 6px 12px;
|
||||
background: #2a2a2a;
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
color: #e5e5e5;
|
||||
font-size: 0.65rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, border-color 0.15s;
|
||||
}
|
||||
|
||||
.accessory-btn.confirming {
|
||||
background: #6b4f00;
|
||||
border-color: #b8860b;
|
||||
color: #ffd54f;
|
||||
}
|
||||
|
||||
.accessory-btn:active {
|
||||
background: #3a3a3a;
|
||||
}
|
||||
|
||||
.accessory-btn svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.accessory-btn-arrow {
|
||||
padding: 6px 10px;
|
||||
background: #2563eb;
|
||||
border-color: rgba(59, 130, 246, 0.5);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.accessory-btn-arrow:active {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
|
||||
.accessory-btn-dismiss {
|
||||
margin-left: auto;
|
||||
flex: 1 1 0;
|
||||
max-width: 80px;
|
||||
padding: 10px 8px;
|
||||
background: #334d6e;
|
||||
border-color: rgba(100, 150, 200, 0.4);
|
||||
color: #c0d4e8;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.accessory-btn-dismiss svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.accessory-btn-dismiss:active {
|
||||
background: #3d5f85;
|
||||
}
|
||||
/* Keyboard accessory bar + paste overlay base styles moved to styles.css
|
||||
(always loaded — covers iPad landscape where mobile.css doesn't load).
|
||||
Phone-specific overrides remain in @media (max-width: 430px) above. */
|
||||
|
||||
/* ============================================================================
|
||||
iOS Safari Specific Fixes
|
||||
@@ -2365,3 +2143,47 @@ html.mobile-init .file-browser-panel {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 430px) {
|
||||
/* Attachment history (COD-18): full-screen sheet on phones */
|
||||
.attachment-history-drawer {
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
border-left: none;
|
||||
border-radius: 0;
|
||||
padding-top: var(--safe-area-top);
|
||||
padding-left: var(--safe-area-left);
|
||||
padding-right: var(--safe-area-right);
|
||||
padding-bottom: var(--safe-area-bottom);
|
||||
}
|
||||
|
||||
.attachment-history-header {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.attachment-history-list {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.attachment-history-item {
|
||||
grid-template-columns: 104px minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
padding: 8px 6px;
|
||||
}
|
||||
|
||||
.attachment-history-thumb {
|
||||
width: 104px;
|
||||
}
|
||||
|
||||
.attachment-history-actions {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.attachment-history-actions button {
|
||||
padding: 4px 7px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ class NotificationManager {
|
||||
const readClass = n.read ? '' : ' unread';
|
||||
const countLabel = n.count > 1 ? `<span class="notif-item-count">×${n.count}</span>` : '';
|
||||
const sessionChip = n.sessionName ? `<span class="notif-item-session">${escapeHtml(n.sessionName)}</span>` : '';
|
||||
return `<div class="notif-item ${urgencyClass}${readClass}" data-notif-id="${n.id}" data-session-id="${n.sessionId || ''}" onclick="app.notificationManager.clickNotification('${escapeHtml(n.id)}')">
|
||||
return `<div class="notif-item ${urgencyClass}${readClass}" data-notif-id="${n.id}" data-session-id="${n.sessionId || ''}" onclick="app.notificationManager.clickNotification(${escapeHtml(JSON.stringify(n.id))})">
|
||||
<div class="notif-item-header">
|
||||
<span class="notif-item-title">${escapeHtml(n.title)}${countLabel}</span>
|
||||
<span class="notif-item-time">${this.relativeTime(n.timestamp)}</span>
|
||||
|
||||
@@ -392,10 +392,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
let actions = '';
|
||||
if (orchState === 'executing' || orchState === 'failed') {
|
||||
if (phase.status === 'pending') {
|
||||
actions += `<button class="orch-phase-btn" onclick="app.orchestratorSkipPhase('${phase.id}')" title="Skip">skip</button>`;
|
||||
actions += `<button class="orch-phase-btn" onclick="app.orchestratorSkipPhase(${escapeHtml(JSON.stringify(phase.id))})" title="Skip">skip</button>`;
|
||||
}
|
||||
if (phase.status === 'failed') {
|
||||
actions += `<button class="orch-phase-btn" onclick="app.orchestratorRetryPhase('${phase.id}')" title="Retry">retry</button>`;
|
||||
actions += `<button class="orch-phase-btn" onclick="app.orchestratorRetryPhase(${escapeHtml(JSON.stringify(phase.id))})" title="Retry">retry</button>`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+525
-44
@@ -753,8 +753,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
const agentIcon = teammateInfo ? `<span class="subagent-icon teammate-dot teammate-color-${teammateInfo.color}">●</span>` : '<span class="subagent-icon">🤖</span>';
|
||||
html.push(`
|
||||
<div class="subagent-item ${statusClass} ${isActive ? 'selected' : ''}${teammateInfo ? ' is-teammate' : ''}"
|
||||
onclick="app.selectSubagent('${escapeHtml(agent.agentId)}')"
|
||||
ondblclick="app.openSubagentWindow('${escapeHtml(agent.agentId)}')"
|
||||
onclick="app.selectSubagent(${escapeHtml(JSON.stringify(agent.agentId))})"
|
||||
ondblclick="app.openSubagentWindow(${escapeHtml(JSON.stringify(agent.agentId))})"
|
||||
title="Double-click to open tracking window">
|
||||
<div class="subagent-header">
|
||||
${agentIcon}
|
||||
@@ -762,8 +762,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
${teammateBadge}
|
||||
${modelBadge}
|
||||
<span class="subagent-status ${statusClass}">${agent.status}</span>
|
||||
${canKill ? `<button class="subagent-kill-btn" onclick="event.stopPropagation(); app.killSubagent('${escapeHtml(agent.agentId)}')" title="Kill agent">✕</button>` : ''}
|
||||
<button class="subagent-window-btn" onclick="event.stopPropagation(); app.${hasWindow ? 'closeSubagentWindow' : 'openSubagentWindow'}('${escapeHtml(agent.agentId)}')" title="${hasWindow ? 'Close window' : 'Open in window'}">
|
||||
${canKill ? `<button class="subagent-kill-btn" onclick="event.stopPropagation(); app.killSubagent(${escapeHtml(JSON.stringify(agent.agentId))})" title="Kill agent">✕</button>` : ''}
|
||||
<button class="subagent-window-btn" onclick="event.stopPropagation(); app.${hasWindow ? 'closeSubagentWindow' : 'openSubagentWindow'}(${escapeHtml(JSON.stringify(agent.agentId))})" title="${hasWindow ? 'Close window' : 'Open in window'}">
|
||||
${hasWindow ? '✕' : '⧉'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -810,7 +810,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="icon">${this.getToolIcon(a.tool)}</span>
|
||||
<span class="name">${escapeHtml(a.tool)}</span>
|
||||
<span class="detail">${escapeHtml(toolDetail.primary)}</span>
|
||||
${toolDetail.hasMore ? `<button class="tool-expand-btn" onclick="app.toggleToolParams('${escapeHtml(a.toolUseId)}')">▶</button>` : ''}
|
||||
${toolDetail.hasMore ? `<button class="tool-expand-btn" onclick="app.toggleToolParams(${escapeHtml(JSON.stringify(a.toolUseId))})">▶</button>` : ''}
|
||||
${toolDetail.hasMore ? `<div class="tool-params-expanded" id="tool-params-${escapeHtml(a.toolUseId)}" style="display:none;"><pre>${escapeHtml(JSON.stringify(a.fullInput || a.input, null, 2))}</pre></div>` : ''}
|
||||
</div>`;
|
||||
} else if (a.type === 'tool_result') {
|
||||
@@ -859,7 +859,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="subagent-id" title="${escapeHtml(agent.description || agent.agentId)}">${escapeHtml(detailTitle.length > 60 ? detailTitle.substring(0, 60) + '...' : detailTitle)}</span>
|
||||
${modelBadge}
|
||||
<span class="subagent-status ${agent.status}">${agent.status}</span>
|
||||
<button class="subagent-transcript-btn" onclick="app.viewSubagentTranscript('${escapeHtml(agent.agentId)}')">
|
||||
<button class="subagent-transcript-btn" onclick="app.viewSubagentTranscript(${escapeHtml(JSON.stringify(agent.agentId))})">
|
||||
View Full Transcript
|
||||
</button>
|
||||
</div>
|
||||
@@ -1195,7 +1195,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
parentDiv.dataset.parentSession = parentSessionId;
|
||||
parentDiv.innerHTML = `
|
||||
<span class="parent-label">from</span>
|
||||
<span class="parent-name" onclick="app.selectSession('${escapeHtml(parentSessionId)}')">${escapeHtml(parentName)}</span>
|
||||
<span class="parent-name" onclick="app.selectSession(${escapeHtml(JSON.stringify(parentSessionId))})">${escapeHtml(parentName)}</span>
|
||||
`;
|
||||
header.insertAdjacentElement('afterend', parentDiv);
|
||||
}
|
||||
@@ -1550,29 +1550,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
|
||||
const terminal = new Terminal({
|
||||
theme: {
|
||||
background: '#0d0d0d',
|
||||
foreground: '#e0e0e0',
|
||||
cursor: '#e0e0e0',
|
||||
cursorAccent: '#0d0d0d',
|
||||
selection: 'rgba(255, 255, 255, 0.3)',
|
||||
black: '#0d0d0d',
|
||||
red: '#ff6b6b',
|
||||
green: '#51cf66',
|
||||
yellow: '#ffd43b',
|
||||
blue: '#339af0',
|
||||
magenta: '#cc5de8',
|
||||
cyan: '#22b8cf',
|
||||
white: '#e0e0e0',
|
||||
brightBlack: '#495057',
|
||||
brightRed: '#ff8787',
|
||||
brightGreen: '#69db7c',
|
||||
brightYellow: '#ffe066',
|
||||
brightBlue: '#5c7cfa',
|
||||
brightMagenta: '#da77f2',
|
||||
brightCyan: '#66d9e8',
|
||||
brightWhite: '#ffffff',
|
||||
},
|
||||
theme: { ...window.codemanCurrentXtermTheme() },
|
||||
fontFamily: '"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',
|
||||
fontSize: 12,
|
||||
lineHeight: 1.2,
|
||||
@@ -1709,7 +1687,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="status running">terminal</span>
|
||||
</div>
|
||||
<div class="subagent-window-actions">
|
||||
<button onclick="app.closeSubagentWindow('${escapeHtml(windowId)}')" title="Minimize to tab">─</button>
|
||||
<button onclick="app.closeSubagentWindow(${escapeHtml(JSON.stringify(windowId))})" title="Minimize to tab">─</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="subagent-window-body teammate-terminal-body" id="subagent-window-body-${windowId}">
|
||||
@@ -2222,7 +2200,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const fileName = path.split('/').pop();
|
||||
html.push(`
|
||||
<span class="project-insight-filepath"
|
||||
onclick="app.openLogViewerWindow('${escapeHtml(path)}', '${escapeHtml(tool.sessionId)}')"
|
||||
onclick="app.openLogViewerWindow(${escapeHtml(JSON.stringify(path))}, ${escapeHtml(JSON.stringify(tool.sessionId))})"
|
||||
title="${escapeHtml(path)}">${escapeHtml(fileName)}</span>
|
||||
`);
|
||||
}
|
||||
@@ -2465,8 +2443,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.saveAppSettingsToStorage(settings);
|
||||
},
|
||||
|
||||
async openFilePreview(filePath) {
|
||||
if (!this.activeSessionId || !filePath) return;
|
||||
async openFilePreview(filePath, sessionId = this.activeSessionId, attachmentId = null) {
|
||||
if (!sessionId || !filePath) return;
|
||||
|
||||
const overlay = this.$('filePreviewOverlay');
|
||||
const titleEl = this.$('filePreviewTitle');
|
||||
@@ -2481,8 +2459,72 @@ Object.assign(CodemanApp.prototype, {
|
||||
bodyEl.innerHTML = '<div class="binary-message">Loading...</div>';
|
||||
footerEl.textContent = '';
|
||||
|
||||
const ext = (filePath.split('.').pop() || '').toLowerCase();
|
||||
|
||||
// Registered attachment: render straight from its by-id routes — images and
|
||||
// PDFs inline, Office docs via the server-converted PDF preview, text fetched
|
||||
// raw. (Workspace-path previews fall through to the file-content endpoint.)
|
||||
if (attachmentId) {
|
||||
const base = `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}`;
|
||||
const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']);
|
||||
footerEl.textContent = ext.toUpperCase();
|
||||
if (IMAGE_EXTS.has(ext)) {
|
||||
bodyEl.innerHTML = `<img src="${escapeHtml(`${base}/raw`)}" alt="${escapeHtml(filePath)}">`;
|
||||
} else if (ext === 'pdf') {
|
||||
bodyEl.innerHTML = `<iframe src="${escapeHtml(`${base}/raw`)}" title="${escapeHtml(filePath)}"></iframe>`;
|
||||
} else if (ext === 'docx' || ext === 'pptx') {
|
||||
bodyEl.innerHTML = `<iframe src="${escapeHtml(`${base}/preview`)}" title="${escapeHtml(filePath)}"></iframe>`;
|
||||
} else {
|
||||
try {
|
||||
const res = await fetch(`${base}/raw`);
|
||||
if (!res.ok) throw new Error('Failed to load attachment');
|
||||
const text = await res.text();
|
||||
bodyEl.innerHTML = `<pre><code>${escapeHtml(text)}</code></pre>`;
|
||||
} catch (err) {
|
||||
bodyEl.innerHTML = `<div class="binary-message">Error: ${escapeHtml(err.message)}</div>`;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Workspace-path (auto-detected, unregistered) attachments: Office docs are
|
||||
// converted to PDF server-side via the file-preview route; PDFs stream raw.
|
||||
// Both render inline in an iframe. Without this, docx/pptx/pdf fall through
|
||||
// to file-content below, which would dump the binary bytes as mojibake.
|
||||
if (ext === 'docx' || ext === 'pptx') {
|
||||
footerEl.textContent = ext.toUpperCase();
|
||||
const previewSrc = `/api/sessions/${sessionId}/file-preview?path=${encodeURIComponent(filePath)}`;
|
||||
bodyEl.innerHTML = `<iframe src="${escapeHtml(previewSrc)}" title="${escapeHtml(filePath)}"></iframe>`;
|
||||
return;
|
||||
}
|
||||
if (ext === 'pdf') {
|
||||
footerEl.textContent = 'PDF';
|
||||
const rawSrc = `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`;
|
||||
bodyEl.innerHTML = `<iframe src="${escapeHtml(rawSrc)}" title="${escapeHtml(filePath)}"></iframe>`;
|
||||
return;
|
||||
}
|
||||
// SVG renders as an image, but file-raw deliberately serves SVG as an
|
||||
// untrusted octet-stream attachment (XSS hardening), so a direct
|
||||
// <img src=file-raw> would break. Fetch the bytes and render via a
|
||||
// same-origin blob typed image/svg+xml — <img> never executes scripts in
|
||||
// the referenced SVG, so this is safe while still rendering the graphic.
|
||||
if (ext === 'svg') {
|
||||
footerEl.textContent = 'SVG';
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`);
|
||||
if (!res.ok) throw new Error('Failed to load image');
|
||||
const blobUrl = URL.createObjectURL(new Blob([await res.text()], { type: 'image/svg+xml' }));
|
||||
bodyEl.innerHTML = `<img src="${blobUrl}" alt="${escapeHtml(filePath)}">`;
|
||||
const img = bodyEl.querySelector('img');
|
||||
if (img) img.onload = () => URL.revokeObjectURL(blobUrl);
|
||||
} catch (err) {
|
||||
bodyEl.innerHTML = `<div class="binary-message">Error: ${escapeHtml(err.message)}</div>`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${this.activeSessionId}/file-content?path=${encodeURIComponent(filePath)}&lines=500`);
|
||||
const res = await fetch(`/api/sessions/${sessionId}/file-content?path=${encodeURIComponent(filePath)}&lines=500`);
|
||||
if (!res.ok) throw new Error('Failed to load file');
|
||||
|
||||
const result = await res.json();
|
||||
@@ -2496,8 +2538,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
} else if (data.type === 'video') {
|
||||
bodyEl.innerHTML = `<video src="${data.url}" controls autoplay></video>`;
|
||||
footerEl.textContent = `${this.formatFileSize(data.size)} \u2022 ${data.extension}`;
|
||||
} else if (data.type === 'audio') {
|
||||
bodyEl.innerHTML = `<audio src="${data.url}" controls autoplay></audio>`;
|
||||
footerEl.textContent = `${this.formatFileSize(data.size)} \u2022 ${data.extension}`;
|
||||
} else if (data.type === 'binary') {
|
||||
bodyEl.innerHTML = `<div class="binary-message">Binary file (${this.formatFileSize(data.size)})<br>Cannot preview</div>`;
|
||||
const downloadHref = `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}&download=true`;
|
||||
bodyEl.innerHTML = `<div class="binary-message">Binary file (${this.formatFileSize(data.size)})<br>Cannot preview<br><a href="${escapeHtml(downloadHref)}" download>Download</a></div>`;
|
||||
footerEl.textContent = data.extension || 'binary';
|
||||
} else {
|
||||
// Text content
|
||||
@@ -2520,6 +2566,441 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.filePreviewContent = '';
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Attachment Cards (detected documents/images)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
// SSE `attachment:detected` consumer: surface a dismissible card for the file
|
||||
// and bump the per-session history unread count (refreshing the open drawer).
|
||||
_onAttachmentDetected(data) {
|
||||
console.log('[Attachment Detected]', data);
|
||||
this.addAttachmentCard(data);
|
||||
if (data.sessionId) {
|
||||
const current =
|
||||
this.attachmentHistoryCounts.get(data.sessionId) ??
|
||||
this.sessions.get(data.sessionId)?.attachmentHistory?.length ??
|
||||
0;
|
||||
this.attachmentHistoryCounts.set(data.sessionId, Math.min(current + 1, 100));
|
||||
if (data.sessionId === this.activeSessionId) {
|
||||
this.updateAttachmentHistoryBadge();
|
||||
if (this.attachmentHistoryDrawerOpen) {
|
||||
this._debouncedCall(
|
||||
'attachmentHistoryRefresh',
|
||||
() => {
|
||||
// The drawer may have closed or the active session changed during
|
||||
// the debounce window — don't refresh for a stale session.
|
||||
if (this.attachmentHistoryDrawerOpen && this.activeSessionId === data.sessionId) {
|
||||
this.loadAttachmentHistory(data.sessionId);
|
||||
}
|
||||
},
|
||||
250
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Lazily create the floating stack the cards live in (appended to <body>).
|
||||
ensureAttachmentCardStack() {
|
||||
let stack = this.attachmentCardStack || document.getElementById('attachmentCardStack');
|
||||
if (!stack) {
|
||||
stack = document.createElement('div');
|
||||
stack.id = 'attachmentCardStack';
|
||||
stack.className = 'attachment-card-stack';
|
||||
document.body.appendChild(stack);
|
||||
}
|
||||
this.attachmentCardStack = stack;
|
||||
return stack;
|
||||
},
|
||||
|
||||
openAttachmentInNewTab(sessionId, filePath, attachmentId = null) {
|
||||
const url = attachmentId
|
||||
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/raw`
|
||||
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`;
|
||||
window.open(url, '_blank');
|
||||
},
|
||||
|
||||
addAttachmentCard(attachmentEvent) {
|
||||
const {
|
||||
sessionId,
|
||||
relativePath,
|
||||
fileName,
|
||||
timestamp,
|
||||
size,
|
||||
attachmentType,
|
||||
extension,
|
||||
attachmentId,
|
||||
rawUrl,
|
||||
previewUrl,
|
||||
thumbnailUrl,
|
||||
} = attachmentEvent;
|
||||
const filePath = relativePath || fileName;
|
||||
const cardId = attachmentId || `${sessionId}-${timestamp}-${fileName}`;
|
||||
|
||||
if (this.attachmentCards.has(cardId)) {
|
||||
const existing = this.attachmentCards.get(cardId);
|
||||
existing.element.focus?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const MAX_ATTACHMENT_CARDS = 10;
|
||||
if (this.attachmentCards.size >= MAX_ATTACHMENT_CARDS) {
|
||||
const oldestId = this.attachmentCards.keys().next().value;
|
||||
if (oldestId) this.closeAttachmentCard(oldestId);
|
||||
}
|
||||
|
||||
const stack = this.ensureAttachmentCardStack();
|
||||
const session = this.sessions.get(sessionId);
|
||||
const sessionName = session?.name || sessionId.substring(0, 8);
|
||||
const attachmentRawUrl =
|
||||
rawUrl ||
|
||||
(attachmentId
|
||||
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/raw`
|
||||
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`);
|
||||
const attachmentPreviewUrl =
|
||||
previewUrl ||
|
||||
(attachmentId ? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/preview` : null);
|
||||
const attachmentThumbnailUrl =
|
||||
thumbnailUrl ||
|
||||
(attachmentId
|
||||
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/thumbnail`
|
||||
: `/api/sessions/${sessionId}/file-thumbnail?path=${encodeURIComponent(filePath)}`);
|
||||
const downloadUrl = attachmentId ? `${attachmentRawUrl}?download=true` : `${attachmentRawUrl}&download=true`;
|
||||
const typeLabel = (extension || attachmentType || 'file').toUpperCase();
|
||||
|
||||
const card = document.createElement('article');
|
||||
card.className = `attachment-card attachment-${escapeHtml(attachmentType || 'file')}`;
|
||||
card.tabIndex = 0;
|
||||
card.dataset.attachmentId = cardId;
|
||||
card.dataset.previewUrl = attachmentPreviewUrl || '';
|
||||
card.innerHTML = `
|
||||
<div class="attachment-thumbnail">
|
||||
${attachmentThumbnailUrl ? `<img class="attachment-thumbnail-img" src="${escapeHtml(attachmentThumbnailUrl)}" alt="">` : ''}
|
||||
<div class="attachment-thumbnail-fallback ${attachmentThumbnailUrl ? '' : 'visible'}">${escapeHtml(typeLabel)}</div>
|
||||
</div>
|
||||
<div class="attachment-card-main">
|
||||
<div class="attachment-file-name" title="${escapeHtml(filePath)}">${escapeHtml(fileName)}</div>
|
||||
<div class="attachment-file-meta">
|
||||
<span>${escapeHtml(sessionName)}</span>
|
||||
<span>${this.formatFileSize(size || 0)}</span>
|
||||
</div>
|
||||
<div class="attachment-actions">
|
||||
<button type="button" class="attachment-preview-btn">Preview</button>
|
||||
<a href="${escapeHtml(downloadUrl)}">Download</a>
|
||||
<button type="button" class="attachment-open-btn">Open</button>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="attachment-close-btn" title="Dismiss">×</button>
|
||||
`;
|
||||
|
||||
const attachmentThumbnailImg = card.querySelector('.attachment-thumbnail-img');
|
||||
if (attachmentThumbnailImg) {
|
||||
attachmentThumbnailImg.onerror = () => {
|
||||
attachmentThumbnailImg.remove();
|
||||
card.querySelector('.attachment-thumbnail-fallback')?.classList.add('visible');
|
||||
};
|
||||
}
|
||||
|
||||
card.querySelector('.attachment-preview-btn')?.addEventListener('click', () => {
|
||||
this.openFilePreview(filePath, sessionId, attachmentId || null);
|
||||
});
|
||||
card.querySelector('.attachment-open-btn')?.addEventListener('click', () => {
|
||||
this.openAttachmentInNewTab(sessionId, filePath, attachmentId || null);
|
||||
});
|
||||
card.querySelector('.attachment-close-btn')?.addEventListener('click', () => {
|
||||
this.closeAttachmentCard(cardId);
|
||||
});
|
||||
|
||||
stack.prepend(card);
|
||||
this.attachmentCards.set(cardId, { element: card, sessionId, filePath });
|
||||
this._refreshAttachmentClearAll();
|
||||
},
|
||||
|
||||
// Centralized show/hide for the stack's "Clear all" control. Both addAttachmentCard and
|
||||
// closeAttachmentCard call this so the control appears on the 2nd card and hides at <=1.
|
||||
_refreshAttachmentClearAll() {
|
||||
const stack = this.attachmentCardStack;
|
||||
if (!stack) return;
|
||||
let control = stack.querySelector('.attachment-clear-all');
|
||||
if (this.attachmentCards.size < 2) {
|
||||
if (control) control.hidden = true;
|
||||
return;
|
||||
}
|
||||
if (!control) {
|
||||
control = document.createElement('button');
|
||||
control.type = 'button';
|
||||
control.className = 'attachment-clear-all';
|
||||
control.textContent = 'Clear all';
|
||||
control.title = 'Dismiss all attachment cards';
|
||||
control.addEventListener('click', () => this.closeAllAttachmentCards());
|
||||
stack.prepend(control);
|
||||
}
|
||||
control.hidden = false;
|
||||
},
|
||||
|
||||
closeAttachmentCard(attachmentId) {
|
||||
const cardData = this.attachmentCards.get(attachmentId);
|
||||
if (!cardData) return;
|
||||
cardData.element.remove();
|
||||
this.attachmentCards.delete(attachmentId);
|
||||
if (this.attachmentCardStack && this.attachmentCards.size === 0) {
|
||||
this.attachmentCardStack.remove();
|
||||
this.attachmentCardStack = null;
|
||||
} else {
|
||||
this._refreshAttachmentClearAll();
|
||||
}
|
||||
},
|
||||
|
||||
closeAllAttachmentCards() {
|
||||
for (const attachmentId of [...this.attachmentCards.keys()]) {
|
||||
this.closeAttachmentCard(attachmentId);
|
||||
}
|
||||
},
|
||||
|
||||
closeSessionAttachmentCards(sessionId) {
|
||||
const toClose = [];
|
||||
for (const [attachmentId, data] of this.attachmentCards) {
|
||||
if (data.sessionId === sessionId) toClose.push(attachmentId);
|
||||
}
|
||||
for (const attachmentId of toClose) {
|
||||
this.closeAttachmentCard(attachmentId);
|
||||
}
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Attachment History Drawer
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
updateAttachmentHistoryBadge(count = null) {
|
||||
const badge = document.getElementById('attachmentHistoryBadge');
|
||||
const button = document.getElementById('attachmentsHistoryBtn');
|
||||
const sessionId = this.activeSessionId;
|
||||
const nextCount = count ?? (sessionId ? this.attachmentHistoryCounts.get(sessionId) || 0 : 0);
|
||||
if (badge) {
|
||||
badge.textContent = nextCount > 99 ? '99+' : String(nextCount);
|
||||
badge.style.display = nextCount > 0 ? '' : 'none';
|
||||
}
|
||||
if (button) {
|
||||
button.classList.toggle('active', this.attachmentHistoryDrawerOpen);
|
||||
button.setAttribute('aria-expanded', this.attachmentHistoryDrawerOpen ? 'true' : 'false');
|
||||
}
|
||||
},
|
||||
|
||||
ensureAttachmentHistoryDrawer() {
|
||||
let drawer = document.getElementById('attachmentHistoryDrawer');
|
||||
if (drawer) return drawer;
|
||||
|
||||
drawer = document.createElement('aside');
|
||||
drawer.id = 'attachmentHistoryDrawer';
|
||||
drawer.className = 'attachment-history-drawer';
|
||||
drawer.setAttribute('aria-label', 'Attachment history');
|
||||
drawer.innerHTML = `
|
||||
<div class="attachment-history-header">
|
||||
<div>
|
||||
<div class="attachment-history-title">Attachments</div>
|
||||
<div class="attachment-history-subtitle" id="attachmentHistorySubtitle">0 files</div>
|
||||
</div>
|
||||
<div class="attachment-history-header-actions">
|
||||
<button type="button" class="btn-icon-sm" id="attachmentHistoryRefreshBtn" title="Refresh" aria-label="Refresh attachments">↻</button>
|
||||
<button type="button" class="btn-icon-sm" id="attachmentHistoryCloseBtn" title="Close" aria-label="Close attachments">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="attachment-history-list" id="attachmentHistoryList"></div>
|
||||
`;
|
||||
document.body.appendChild(drawer);
|
||||
drawer.querySelector('#attachmentHistoryRefreshBtn')?.addEventListener('click', () => {
|
||||
this.loadAttachmentHistory(this.activeSessionId);
|
||||
});
|
||||
drawer.querySelector('#attachmentHistoryCloseBtn')?.addEventListener('click', () => {
|
||||
this.closeAttachmentHistory();
|
||||
});
|
||||
return drawer;
|
||||
},
|
||||
|
||||
async toggleAttachmentHistory() {
|
||||
if (this.attachmentHistoryDrawerOpen) {
|
||||
this.closeAttachmentHistory();
|
||||
return;
|
||||
}
|
||||
await this.openAttachmentHistory();
|
||||
},
|
||||
|
||||
async openAttachmentHistory() {
|
||||
const drawer = this.ensureAttachmentHistoryDrawer();
|
||||
this.attachmentHistoryDrawerOpen = true;
|
||||
drawer.classList.add('open');
|
||||
this.updateAttachmentHistoryBadge();
|
||||
await this.loadAttachmentHistory(this.activeSessionId);
|
||||
},
|
||||
|
||||
closeAttachmentHistory() {
|
||||
const drawer = document.getElementById('attachmentHistoryDrawer');
|
||||
this.attachmentHistoryDrawerOpen = false;
|
||||
drawer?.classList.remove('open');
|
||||
// Cancel any pending debounced refresh so it can't fire against a closed drawer.
|
||||
if (this._debounceTimers?.attachmentHistoryRefresh) {
|
||||
clearTimeout(this._debounceTimers.attachmentHistoryRefresh);
|
||||
this._debounceTimers.attachmentHistoryRefresh = null;
|
||||
}
|
||||
this.updateAttachmentHistoryBadge();
|
||||
},
|
||||
|
||||
async loadAttachmentHistory(sessionId = this.activeSessionId) {
|
||||
const drawer = this.ensureAttachmentHistoryDrawer();
|
||||
const list = drawer.querySelector('#attachmentHistoryList');
|
||||
const subtitle = drawer.querySelector('#attachmentHistorySubtitle');
|
||||
if (!list || !subtitle) return;
|
||||
|
||||
if (!sessionId) {
|
||||
this.attachmentHistoryItems = [];
|
||||
subtitle.textContent = 'No session';
|
||||
list.innerHTML = '<div class="attachment-history-empty">No active session</div>';
|
||||
this.updateAttachmentHistoryBadge(0);
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = '<div class="attachment-history-empty">Loading...</div>';
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${sessionId}/attachments`);
|
||||
if (!res.ok) throw new Error('Failed to load attachments');
|
||||
const result = await res.json();
|
||||
if (!result.success) throw new Error(result.error || 'Failed to load attachments');
|
||||
const items = result.data?.items || [];
|
||||
this.attachmentHistoryItems = items;
|
||||
this.attachmentHistoryCounts.set(sessionId, items.length);
|
||||
this.updateAttachmentHistoryBadge(items.length);
|
||||
this.renderAttachmentHistory(items);
|
||||
} catch (err) {
|
||||
console.error('Failed to load attachment history:', err);
|
||||
subtitle.textContent = 'Unavailable';
|
||||
list.innerHTML = `<div class="attachment-history-empty">Error: ${escapeHtml(err.message)}</div>`;
|
||||
}
|
||||
},
|
||||
|
||||
renderAttachmentHistory(items = this.attachmentHistoryItems || []) {
|
||||
const drawer = this.ensureAttachmentHistoryDrawer();
|
||||
const list = drawer.querySelector('#attachmentHistoryList');
|
||||
const subtitle = drawer.querySelector('#attachmentHistorySubtitle');
|
||||
if (!list || !subtitle) return;
|
||||
|
||||
subtitle.textContent = `${items.length} ${items.length === 1 ? 'file' : 'files'}`;
|
||||
if (items.length === 0) {
|
||||
list.innerHTML = `
|
||||
<div class="attachment-history-empty">
|
||||
<div class="attachment-history-empty-title">No attachments yet</div>
|
||||
<div>Show a file here by running:</div>
|
||||
<code>codeman attach /absolute/path/to/file.pptx</code>
|
||||
<div>Supports .pptx, .docx, .pdf, .png, .md, and .txt.</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = items.map((item) => this.renderAttachmentHistoryItem(item)).join('');
|
||||
list.querySelectorAll('.attachment-history-thumb-img').forEach((img) => {
|
||||
img.onerror = () => {
|
||||
img.remove();
|
||||
const fallback = img.closest('.attachment-history-thumb')?.querySelector('.attachment-history-thumb-fallback');
|
||||
fallback?.classList.add('visible');
|
||||
};
|
||||
});
|
||||
list.querySelectorAll('[data-attachment-action]').forEach((button) => {
|
||||
button.addEventListener('click', () => {
|
||||
const id = button.getAttribute('data-history-id');
|
||||
const action = button.getAttribute('data-attachment-action');
|
||||
if (!id || !action) return;
|
||||
if (action === 'preview') this.previewAttachmentHistoryItem(id);
|
||||
if (action === 'download') this.downloadAttachmentHistoryItem(id);
|
||||
if (action === 'open') this.openAttachmentHistoryItem(id);
|
||||
if (action === 'reshow') this.reshowAttachmentCard(id);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
renderAttachmentHistoryItem(item) {
|
||||
const typeLabel = (item.extension || item.attachmentType || 'file').toUpperCase();
|
||||
const meta = [
|
||||
item.source === 'external' ? 'published' : 'workspace',
|
||||
this.formatFileSize(item.size || 0),
|
||||
item.missing ? 'missing' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' • ');
|
||||
const thumb =
|
||||
item.thumbnailUrl && !item.missing
|
||||
? `<img class="attachment-history-thumb-img" src="${escapeHtml(item.thumbnailUrl)}" alt="">`
|
||||
: '';
|
||||
const disabled = item.missing ? 'disabled aria-disabled="true"' : '';
|
||||
return `
|
||||
<div class="attachment-history-item ${item.missing ? 'missing' : ''}" data-history-item="${escapeHtml(item.id)}">
|
||||
<div class="attachment-history-thumb">
|
||||
${thumb}
|
||||
<div class="attachment-history-thumb-fallback ${thumb ? '' : 'visible'}">${escapeHtml(typeLabel)}</div>
|
||||
</div>
|
||||
<div class="attachment-history-item-main">
|
||||
<div class="attachment-history-file-name" title="${escapeHtml(item.fileName)}">${escapeHtml(item.fileName)}</div>
|
||||
<div class="attachment-history-meta">${escapeHtml(meta)}</div>
|
||||
<div class="attachment-history-actions">
|
||||
<button type="button" data-attachment-action="preview" data-history-id="${escapeHtml(item.id)}" ${disabled}>Preview</button>
|
||||
<button type="button" data-attachment-action="download" data-history-id="${escapeHtml(item.id)}" ${disabled}>Download</button>
|
||||
<button type="button" data-attachment-action="open" data-history-id="${escapeHtml(item.id)}" ${disabled}>Open</button>
|
||||
<button type="button" data-attachment-action="reshow" data-history-id="${escapeHtml(item.id)}" ${disabled}>Card</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
getAttachmentHistoryItem(itemId) {
|
||||
return (this.attachmentHistoryItems || []).find((item) => item.id === itemId) || null;
|
||||
},
|
||||
|
||||
previewAttachmentHistoryItem(itemId) {
|
||||
const item = this.getAttachmentHistoryItem(itemId);
|
||||
if (!item || item.missing) return;
|
||||
const path = item.relativePath || item.fileName;
|
||||
this.openFilePreview(path, item.sessionId, item.attachmentId || null);
|
||||
// Close the drawer so the preview window is unobstructed.
|
||||
this.closeAttachmentHistory();
|
||||
},
|
||||
|
||||
openAttachmentHistoryItem(itemId) {
|
||||
const item = this.getAttachmentHistoryItem(itemId);
|
||||
if (!item || item.missing) return;
|
||||
if (item.rawUrl || item.url) {
|
||||
window.open(item.rawUrl || item.url, '_blank');
|
||||
return;
|
||||
}
|
||||
this.openAttachmentInNewTab(item.sessionId, item.relativePath || item.fileName, item.attachmentId || null);
|
||||
},
|
||||
|
||||
downloadAttachmentHistoryItem(itemId) {
|
||||
const item = this.getAttachmentHistoryItem(itemId);
|
||||
if (!item || item.missing || !item.downloadUrl) return;
|
||||
window.open(item.downloadUrl, '_blank');
|
||||
},
|
||||
|
||||
reshowAttachmentCard(itemId) {
|
||||
const item = this.getAttachmentHistoryItem(itemId);
|
||||
if (!item || item.missing) return;
|
||||
this.addAttachmentCard({
|
||||
sessionId: item.sessionId,
|
||||
relativePath: item.relativePath,
|
||||
fileName: item.fileName,
|
||||
// Use the item's own timestamp (not Date.now()) so the derived cardId is
|
||||
// stable across clicks — re-showing focuses the existing card instead of
|
||||
// stacking a duplicate.
|
||||
timestamp: item.timestamp ?? Date.now(),
|
||||
size: item.size,
|
||||
attachmentType: item.attachmentType,
|
||||
extension: item.extension,
|
||||
attachmentId: item.attachmentId,
|
||||
rawUrl: item.rawUrl,
|
||||
previewUrl: item.previewUrl,
|
||||
thumbnailUrl: item.thumbnailUrl,
|
||||
});
|
||||
},
|
||||
|
||||
copyFilePreviewContent() {
|
||||
if (this.filePreviewContent) {
|
||||
navigator.clipboard.writeText(this.filePreviewContent).then(() => {
|
||||
@@ -2618,7 +3099,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="status streaming">streaming</span>
|
||||
</div>
|
||||
<div class="log-viewer-window-actions">
|
||||
<button onclick="app.closeLogViewerWindow('${escapeHtml(windowId)}')" title="Close">×</button>
|
||||
<button onclick="app.closeLogViewerWindow(${escapeHtml(JSON.stringify(windowId))})" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="log-viewer-window-body" id="log-viewer-body-${windowId}">
|
||||
@@ -2794,14 +3275,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="size-badge">${sizeKB} KB</span>
|
||||
</div>
|
||||
<div class="image-popup-actions">
|
||||
<button onclick="app.openImageInNewTab('${escapeHtml(imageUrl)}')" title="Open in new tab">↗</button>
|
||||
<button onclick="app.closeImagePopup('${escapeHtml(imageId)}')" title="Close">×</button>
|
||||
<button onclick="app.openImageInNewTab(${escapeHtml(JSON.stringify(imageUrl))})" title="Open in new tab">↗</button>
|
||||
<button onclick="app.closeImagePopup(${escapeHtml(JSON.stringify(imageId))})" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="image-popup-body">
|
||||
<img src="${imageUrl}" alt="${escapeHtml(fileName)}"
|
||||
onerror="this.parentElement.innerHTML='<div class=\\'image-error\\'>Failed to load image</div>'"
|
||||
onclick="app.openImageInNewTab('${escapeHtml(imageUrl)}')" />
|
||||
onclick="app.openImageInNewTab(${escapeHtml(JSON.stringify(imageUrl))})" />
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -3024,9 +3505,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
modelHtml = `<span class="monitor-model-badge ${modelShort}">${modelShort}</span>`;
|
||||
}
|
||||
|
||||
const sid = escapeHtml(muxSession.sessionId);
|
||||
const sid = escapeHtml(JSON.stringify(muxSession.sessionId));
|
||||
html += `
|
||||
<div class="process-item process-item-clickable" onclick="app.selectSession('${sid}')" title="Switch to session">
|
||||
<div class="process-item process-item-clickable" onclick="app.selectSession(${sid})" title="Switch to session">
|
||||
<span class="monitor-status-badge ${statusClass}">${statusLabel}</span>
|
||||
<div class="process-info">
|
||||
<div class="process-name">${modelHtml} ${escapeHtml(muxSession.name || muxSession.muxName)}</div>
|
||||
@@ -3039,7 +3520,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
</div>
|
||||
</div>
|
||||
<div class="process-actions">
|
||||
<button class="btn-toolbar btn-sm btn-danger" onclick="event.stopPropagation(); app.killMuxSession('${sid}')" title="Kill session">Kill</button>
|
||||
<button class="btn-toolbar btn-sm btn-danger" onclick="event.stopPropagation(); app.killMuxSession(${sid})" title="Kill session">Kill</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -3082,7 +3563,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
</div>
|
||||
</div>
|
||||
<div class="process-actions">
|
||||
${agent.status !== 'completed' ? `<button class="btn-toolbar btn-sm btn-danger" onclick="app.killSubagent('${escapeHtml(agent.agentId)}')" title="Kill agent">Kill</button>` : ''}
|
||||
${agent.status !== 'completed' ? `<button class="btn-toolbar btn-sm btn-danger" onclick="app.killSubagent(${escapeHtml(JSON.stringify(agent.agentId))})" title="Kill agent">Kill</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -378,7 +378,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
prompt += `Output \`<promise>${config.completionPhrase}</promise>\` when done\n\n`;
|
||||
|
||||
prompt += '## If Stuck\n';
|
||||
prompt += 'Output `<promise>BLOCKED</promise>` with explanation';
|
||||
prompt += 'Output `<promise>BLOCKED</promise>` with explanation\n\n';
|
||||
|
||||
prompt += '## Status Reporting\n';
|
||||
prompt += '• End every response with a `RALPH_STATUS` block (parsed by Codeman)';
|
||||
|
||||
// Show preview with highlighting (escape first, then apply formatting)
|
||||
const escapedPrompt = escapeHtml(prompt);
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* @fileoverview Allowlist-based HTML sanitizer for markdown-rendered, agent/transcript-derived
|
||||
* content that is subsequently assigned via innerHTML (response viewer, attachment markdown
|
||||
* preview, message bodies).
|
||||
*
|
||||
* Security (COD-56): the previous sanitizer was a hand-rolled DENYLIST — it removed a fixed
|
||||
* set of tags (script/iframe/object/embed/form/base/meta/link/style), stripped on* attrs and a
|
||||
* few dangerous URL schemes, then re-serialized. Denylists are mXSS-prone: they did not strip
|
||||
* `svg`/`math` (which carry their own foreign-namespace parsing rules and can smuggle script via
|
||||
* namespace confusion), did not strip `style` attributes (CSS `expression()`/`url(javascript:)`
|
||||
* on legacy engines), and had no positive allowlist, so any tag/attribute not explicitly named
|
||||
* survived. `marked` runs with raw-HTML passthrough, so crafted HTML echoed by an agent flows
|
||||
* straight into this function.
|
||||
*
|
||||
* This module replaces that with DOMPurify (Cure53), an allowlist sanitizer that is the
|
||||
* industry standard for mXSS defense. It is configured to allow exactly the tag/attribute set
|
||||
* that markdown rendering legitimately produces (headings, lists, code, blockquotes, links,
|
||||
* tables, images with safe src) and to FORBID `style`/`svg`/`math` plus all event handlers and
|
||||
* dangerous URL schemes.
|
||||
*
|
||||
* Cross-environment: in the browser this file runs as a classic <script> after
|
||||
* vendor/dompurify.min.js and wires `window.sanitizeMarkdownHtml`. The factory is also exported
|
||||
* (window/globalThis + CommonJS) so a jsdom unit test can build a sanitizer bound to a
|
||||
* jsdom-window DOMPurify instance and exercise the exact same config.
|
||||
*
|
||||
* @globals {function} sanitizeMarkdownHtml - (html:string) => string, sanitized HTML
|
||||
* @globals {function} createMarkdownSanitizer - (DOMPurify) => sanitizeMarkdownHtml (for tests)
|
||||
* @dependency vendor/dompurify.min.js (provides the global DOMPurify)
|
||||
* @loadorder 5.6 of 15 — after input-cjk.js(5.5), before app.js(6) (app.js calls it)
|
||||
*/
|
||||
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Tags markdown rendering (marked, gfm) legitimately emits. Anything outside this set is
|
||||
* dropped by DOMPurify. Deliberately excludes svg/math (mXSS foreign-namespace vectors) and
|
||||
* form/embed/object/iframe/script/style (no place in rendered markdown).
|
||||
*/
|
||||
var ALLOWED_TAGS = [
|
||||
'a',
|
||||
'b',
|
||||
'blockquote',
|
||||
'br',
|
||||
'caption',
|
||||
'code',
|
||||
'del',
|
||||
'div',
|
||||
'em',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'hr',
|
||||
'i',
|
||||
'img',
|
||||
'ins',
|
||||
'kbd',
|
||||
'li',
|
||||
'mark',
|
||||
'ol',
|
||||
'p',
|
||||
'pre',
|
||||
'q',
|
||||
's',
|
||||
'samp',
|
||||
'span',
|
||||
'strong',
|
||||
'sub',
|
||||
'sup',
|
||||
'table',
|
||||
'tbody',
|
||||
'td',
|
||||
'tfoot',
|
||||
'th',
|
||||
'thead',
|
||||
'tr',
|
||||
'ul',
|
||||
'var',
|
||||
];
|
||||
|
||||
/**
|
||||
* Attributes allowed on the tags above. `style` is intentionally absent (CSS-based vectors).
|
||||
* `class`/`id` survive because the response viewer adds wrapper classes downstream and code
|
||||
* blocks may carry `language-*` classes from marked.
|
||||
*/
|
||||
var ALLOWED_ATTR = [
|
||||
'href',
|
||||
'src',
|
||||
'alt',
|
||||
'title',
|
||||
'class',
|
||||
'id',
|
||||
'name',
|
||||
'colspan',
|
||||
'rowspan',
|
||||
'align',
|
||||
'width',
|
||||
'height',
|
||||
'lang',
|
||||
'dir',
|
||||
'start',
|
||||
'reversed',
|
||||
'type',
|
||||
];
|
||||
|
||||
/**
|
||||
* Build a sanitizer bound to a specific DOMPurify instance. The browser passes the global
|
||||
* DOMPurify; tests pass a jsdom-window-bound instance so the same config is exercised under
|
||||
* vitest without a real browser.
|
||||
*/
|
||||
function createMarkdownSanitizer(DOMPurify) {
|
||||
if (!DOMPurify || typeof DOMPurify.sanitize !== 'function') {
|
||||
throw new Error('createMarkdownSanitizer: a DOMPurify instance is required');
|
||||
}
|
||||
|
||||
var CONFIG = {
|
||||
ALLOWED_TAGS: ALLOWED_TAGS,
|
||||
ALLOWED_ATTR: ALLOWED_ATTR,
|
||||
// Defense in depth even though style/svg/math are not in ALLOWED_TAGS: also forbid the
|
||||
// foreign-namespace roots and style so config drift can't silently re-admit them.
|
||||
FORBID_TAGS: ['style', 'svg', 'math', 'script', 'iframe', 'object', 'embed', 'form'],
|
||||
FORBID_ATTR: ['style'],
|
||||
// NOTE: do NOT set USE_PROFILES here. DOMPurify treats USE_PROFILES and
|
||||
// ALLOWED_TAGS/ALLOWED_ATTR as mutually exclusive — when a profile is set it
|
||||
// RESETS the allow-lists to the full profile and silently ignores the curated
|
||||
// lists above, widening the tag set far beyond what markdown emits. Relying on
|
||||
// the explicit ALLOWED_TAGS/ALLOWED_ATTR keeps the tight allowlist in force;
|
||||
// FORBID_TAGS/FORBID_ATTR remain as defense-in-depth. DOMPurify still applies
|
||||
// its default safe-URI handling (blocks javascript:/vbscript:, allows
|
||||
// http/https/mailto/tel + data: only on image tags).
|
||||
ALLOW_DATA_ATTR: false,
|
||||
ADD_ATTR: [],
|
||||
RETURN_DOM: false,
|
||||
RETURN_DOM_FRAGMENT: false,
|
||||
// Keep text content of any removed element (so stripping a stray tag doesn't eat prose),
|
||||
// matching the previous serializer's behavior of dropping the element but not its text.
|
||||
KEEP_CONTENT: true,
|
||||
};
|
||||
|
||||
return function sanitizeMarkdownHtml(html) {
|
||||
return DOMPurify.sanitize(html == null ? '' : String(html), CONFIG);
|
||||
};
|
||||
}
|
||||
|
||||
// Expose the factory for tests (and any non-browser consumer).
|
||||
if (root) {
|
||||
root.createMarkdownSanitizer = createMarkdownSanitizer;
|
||||
// In the browser, vendor/dompurify.min.js has already defined the global DOMPurify.
|
||||
if (root.DOMPurify && typeof root.DOMPurify.sanitize === 'function') {
|
||||
root.sanitizeMarkdownHtml = createMarkdownSanitizer(root.DOMPurify);
|
||||
}
|
||||
}
|
||||
|
||||
// CommonJS export for the vitest/jsdom unit test.
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = {
|
||||
createMarkdownSanitizer: createMarkdownSanitizer,
|
||||
ALLOWED_TAGS: ALLOWED_TAGS,
|
||||
ALLOWED_ATTR: ALLOWED_ATTR,
|
||||
};
|
||||
}
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : this);
|
||||
@@ -370,6 +370,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
...(hasEnvOverrides ? { envOverrides } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(modelOverride !== undefined ? { modelOverride } : {}),
|
||||
// Plan-usage statusLine exporter (App Settings → Display). The server
|
||||
// ADDS our exporter on create when true; when false it intentionally
|
||||
// leaves any existing exporter in place (a per-repo settings.local.json
|
||||
// is shared by sibling sessions, so create-with-false must not yank it
|
||||
// — see the comment in session-routes create). Disabling the setting
|
||||
// removes it via the App Settings toggle path (system-routes), not here.
|
||||
statusLineTelemetry: globalSettings.showPlanUsageLimits === true,
|
||||
})
|
||||
}).then(r => r.json())
|
||||
);
|
||||
@@ -690,6 +697,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('modalAutoCompactPrompt').value = session.autoCompactPrompt ?? '';
|
||||
document.getElementById('modalAutoClearEnabled').checked = session.autoClearEnabled ?? false;
|
||||
document.getElementById('modalAutoClearThreshold').value = session.autoClearThreshold ?? 140000;
|
||||
|
||||
// Populate auto-resume on usage limit (token pause control)
|
||||
document.getElementById('modalAutoResumeEnabled').checked = session.autoResumeEnabled ?? false;
|
||||
this.updateAutoResumeStatus(sessionId);
|
||||
document.getElementById('modalImageWatcherEnabled').checked = session.imageWatcherEnabled ?? true;
|
||||
document.getElementById('modalFlickerFilterEnabled').checked = session.flickerFilterEnabled ?? false;
|
||||
|
||||
@@ -790,6 +801,39 @@ Object.assign(CodemanApp.prototype, {
|
||||
} catch { /* silent */ }
|
||||
},
|
||||
|
||||
async autoSaveAutoResume() {
|
||||
if (!this.editingSessionId) return;
|
||||
const enabled = document.getElementById('modalAutoResumeEnabled').checked;
|
||||
try {
|
||||
await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`, { enabled });
|
||||
const session = this.sessions.get(this.editingSessionId);
|
||||
if (session) {
|
||||
session.autoResumeEnabled = enabled;
|
||||
if (!enabled) session.autoResumeAt = undefined;
|
||||
}
|
||||
this.updateAutoResumeStatus(this.editingSessionId);
|
||||
this.showToast(`Auto-resume on usage limit ${enabled ? 'enabled' : 'disabled'}`, 'success');
|
||||
} catch (err) {
|
||||
this.showToast('Failed to toggle auto-resume: ' + err.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// Show "resumes at HH:MM" in the session options modal while a usage-limit
|
||||
// pause is armed for the session being edited
|
||||
updateAutoResumeStatus(sessionId) {
|
||||
const el = document.getElementById('autoResumeStatus');
|
||||
if (!el || this.editingSessionId !== sessionId) return;
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (session?.autoResumeAt && session.autoResumeAt > Date.now()) {
|
||||
const at = new Date(session.autoResumeAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
el.textContent = `Usage limit pause active — resumes at ${at}`;
|
||||
el.classList.add('active');
|
||||
} else {
|
||||
el.textContent = '';
|
||||
el.classList.remove('active');
|
||||
}
|
||||
},
|
||||
|
||||
async toggleSessionImageWatcher() {
|
||||
if (!this.editingSessionId) return;
|
||||
const enabled = document.getElementById('modalImageWatcherEnabled').checked;
|
||||
@@ -1341,11 +1385,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="case-manage-path">${escapeHtml(pathDisplay)}</span>
|
||||
</div>
|
||||
<div class="case-manage-actions">
|
||||
<button class="case-manage-btn" onclick="app.moveCaseUp('${escapeHtml(c.name)}')"
|
||||
<button class="case-manage-btn" onclick="app.moveCaseUp(${escapeHtml(JSON.stringify(c.name))})"
|
||||
title="Move up" ${isFirst ? 'disabled' : ''}>▲</button>
|
||||
<button class="case-manage-btn" onclick="app.moveCaseDown('${escapeHtml(c.name)}')"
|
||||
<button class="case-manage-btn" onclick="app.moveCaseDown(${escapeHtml(JSON.stringify(c.name))})"
|
||||
title="Move down" ${isLast ? 'disabled' : ''}>▼</button>
|
||||
<button class="case-manage-btn case-manage-btn-delete" onclick="app.deleteCase('${escapeHtml(c.name)}')"
|
||||
<button class="case-manage-btn case-manage-btn-delete" onclick="app.deleteCase(${escapeHtml(JSON.stringify(c.name))})"
|
||||
title="Delete case">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1440,14 +1484,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
const isSelected = c.name === currentCase;
|
||||
html += `
|
||||
<button class="mobile-case-item ${isSelected ? 'selected' : ''}"
|
||||
onclick="app.selectMobileCase('${escapeHtml(c.name)}')">
|
||||
onclick="app.selectMobileCase(${escapeHtml(JSON.stringify(c.name))})">
|
||||
<span class="mobile-case-item-icon">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="mobile-case-item-name">${escapeHtml(c.name)}</span>
|
||||
<span class="mobile-case-item-delete" onclick="event.stopPropagation(); app.deleteCaseMobile('${escapeHtml(c.name)}')" title="Delete">
|
||||
<span class="mobile-case-item-delete" onclick="event.stopPropagation(); app.deleteCaseMobile(${escapeHtml(JSON.stringify(c.name))})" title="Delete">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</svg>
|
||||
|
||||
+244
-76
@@ -305,15 +305,20 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Header visibility settings
|
||||
document.getElementById('appSettingsShowFontControls').checked = settings.showFontControls ?? defaults.showFontControls ?? false;
|
||||
document.getElementById('appSettingsShowSystemStats').checked = settings.showSystemStats ?? defaults.showSystemStats ?? true;
|
||||
document.getElementById('appSettingsShowTokenCount').checked = settings.showTokenCount ?? defaults.showTokenCount ?? true;
|
||||
document.getElementById('appSettingsShowCost').checked = settings.showCost ?? defaults.showCost ?? false;
|
||||
document.getElementById('appSettingsShowLifecycleLog').checked = settings.showLifecycleLog ?? defaults.showLifecycleLog ?? true;
|
||||
document.getElementById('appSettingsShowResponseViewer').checked = settings.showResponseViewer ?? defaults.showResponseViewer ?? false;
|
||||
document.getElementById('appSettingsShowAttachmentsButton').checked = settings.showAttachmentsButton ?? defaults.showAttachmentsButton ?? false;
|
||||
document.getElementById('appSettingsSkin').value = settings.skin ?? defaults.skin ?? 'daylight-blue';
|
||||
document.getElementById('appSettingsShowMonitor').checked = settings.showMonitor ?? defaults.showMonitor ?? false;
|
||||
document.getElementById('appSettingsShowProjectInsights').checked = settings.showProjectInsights ?? defaults.showProjectInsights ?? false;
|
||||
document.getElementById('appSettingsShowFileBrowser').checked = settings.showFileBrowser ?? defaults.showFileBrowser ?? false;
|
||||
document.getElementById('appSettingsShowSubagents').checked = settings.showSubagents ?? defaults.showSubagents ?? false;
|
||||
document.getElementById('appSettingsShowUltracodeAgents').checked = settings.showUltracodeAgents ?? defaults.showUltracodeAgents ?? false;
|
||||
document.getElementById('appSettingsUltracodeFloatingWindows').checked =
|
||||
settings.ultracodeFloatingWindows ?? defaults.ultracodeFloatingWindows ?? false;
|
||||
document.getElementById('appSettingsShowMultiMonitorButton').checked = settings.showMultiMonitorButton ?? defaults.showMultiMonitorButton ?? false;
|
||||
document.getElementById('appSettingsShowPlanUsageLimits').checked = settings.showPlanUsageLimits ?? defaults.showPlanUsageLimits ?? false;
|
||||
document.getElementById('appSettingsShowRedrawButton').checked = settings.showRedrawButton ?? defaults.showRedrawButton ?? false;
|
||||
// Gesture control lives in the Input section (alongside Local Echo / CJK Input)
|
||||
// but is only available when the instance runs with CODEMAN_GESTURE=1 (server sets
|
||||
// window.__codemanGestureAvailable). Hide just this item otherwise so the toggle
|
||||
@@ -844,11 +849,18 @@ Object.assign(CodemanApp.prototype, {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const newEnabled = !isActive;
|
||||
await fetch('/api/settings', {
|
||||
const res = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tunnelEnabled: newEnabled }),
|
||||
});
|
||||
// COD-55: server refuses an unauthenticated public tunnel (403). Surface it.
|
||||
if (newEnabled && (await this._handleTunnelEnableRefusal(res))) {
|
||||
this._dismissTunnelConnecting();
|
||||
this._updateWelcomeTunnelBtn(false);
|
||||
btn.disabled = false;
|
||||
return;
|
||||
}
|
||||
if (newEnabled) {
|
||||
this._showTunnelConnecting();
|
||||
// Poll tunnel status as fallback in case SSE event is missed
|
||||
@@ -1148,13 +1160,82 @@ Object.assign(CodemanApp.prototype, {
|
||||
return `${Math.floor(hrs / 24)}d ago`;
|
||||
},
|
||||
|
||||
/**
|
||||
* COD-55: detect the server's refusal to start an unauthenticated public tunnel.
|
||||
* The PUT /api/settings route returns a 4xx with { success:false, error } when no
|
||||
* CODEMAN_PASSWORD is set and the unauthenticated-network opt-in is not acknowledged.
|
||||
* Shows the server's (actionable) message as an error toast.
|
||||
* @param {Response|null} res - the fetch Response from the settings PUT
|
||||
* @returns {Promise<boolean>} true if the tunnel-enable was refused (caller should abort)
|
||||
*/
|
||||
async _handleTunnelEnableRefusal(res) {
|
||||
if (!res || res.ok) return false;
|
||||
let message = 'Tunnel refused: set CODEMAN_PASSWORD before exposing Codeman publicly.';
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body && body.error) message = body.error;
|
||||
} catch {
|
||||
/* non-JSON body — use the default message */
|
||||
}
|
||||
// 403 = the no-password safety refusal (COD-55). Warn loudly and let the
|
||||
// operator acknowledge the risk; on confirm, retry with explicit acknowledgment.
|
||||
if (res.status === 403) {
|
||||
const confirmed = confirm(
|
||||
'⚠️ SECURITY WARNING — no password set\n\n' +
|
||||
'Enabling the Cloudflare tunnel will publish THIS machine to a public URL with ' +
|
||||
'NO login. Anyone who gets the URL has full terminal control — effectively remote ' +
|
||||
'code execution on your computer.\n\n' +
|
||||
'Strongly recommended: set CODEMAN_PASSWORD instead.\n\n' +
|
||||
'Enable the unauthenticated public tunnel anyway?'
|
||||
);
|
||||
if (!confirmed) {
|
||||
this._dismissTunnelConnecting?.();
|
||||
this.showToast('Tunnel not enabled', 'info');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const retry = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tunnelEnabled: true, acknowledgeUnauthTunnel: true }),
|
||||
});
|
||||
if (retry.ok) {
|
||||
this.showToast('Public tunnel enabling — no password set ⚠️', 'warning');
|
||||
return false; // proceed with the caller's success/connecting path
|
||||
}
|
||||
let m = 'Failed to enable tunnel.';
|
||||
try {
|
||||
const b = await retry.json();
|
||||
if (b && b.error) m = b.error;
|
||||
} catch {
|
||||
/* non-JSON */
|
||||
}
|
||||
this._dismissTunnelConnecting?.();
|
||||
this.showToast(m, 'error');
|
||||
return true;
|
||||
} catch {
|
||||
this._dismissTunnelConnecting?.();
|
||||
this.showToast('Failed to enable tunnel', 'error');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
this._dismissTunnelConnecting?.();
|
||||
this.showToast(message, 'error');
|
||||
return true;
|
||||
},
|
||||
|
||||
async _tunnelPanelToggle(enable) {
|
||||
try {
|
||||
await fetch('/api/settings', {
|
||||
const res = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tunnelEnabled: enable }),
|
||||
});
|
||||
// COD-55: server refuses an unauthenticated public tunnel (403). Surface it.
|
||||
if (enable && (await this._handleTunnelEnableRefusal(res))) {
|
||||
this.closeTunnelPanel();
|
||||
return;
|
||||
}
|
||||
if (enable) {
|
||||
this._updateTunnelIndicator(false);
|
||||
const indicator = document.getElementById('tunnelIndicator');
|
||||
@@ -1317,7 +1398,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
async saveAppSettings() {
|
||||
// Gesture overlay is injected at page render (server-side), so a change to it
|
||||
// only takes effect on reload — remember the prior value to decide below.
|
||||
const _prevGestureEnabled = (this.loadAppSettingsFromStorage().gestureControlEnabled ?? false) === true;
|
||||
const _prev = this.loadAppSettingsFromStorage();
|
||||
const _prevGestureEnabled = (_prev.gestureControlEnabled ?? false) === true;
|
||||
const settings = {
|
||||
defaultClaudeMdPath: document.getElementById('appSettingsClaudeMdPath').value.trim(),
|
||||
defaultWorkingDir: document.getElementById('appSettingsDefaultDir').value.trim(),
|
||||
@@ -1325,15 +1407,18 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Header visibility settings
|
||||
showFontControls: document.getElementById('appSettingsShowFontControls').checked,
|
||||
showSystemStats: document.getElementById('appSettingsShowSystemStats').checked,
|
||||
showTokenCount: document.getElementById('appSettingsShowTokenCount').checked,
|
||||
showCost: document.getElementById('appSettingsShowCost').checked,
|
||||
showLifecycleLog: document.getElementById('appSettingsShowLifecycleLog').checked,
|
||||
showResponseViewer: document.getElementById('appSettingsShowResponseViewer').checked,
|
||||
showAttachmentsButton: document.getElementById('appSettingsShowAttachmentsButton').checked,
|
||||
showMonitor: document.getElementById('appSettingsShowMonitor').checked,
|
||||
showProjectInsights: document.getElementById('appSettingsShowProjectInsights').checked,
|
||||
showFileBrowser: document.getElementById('appSettingsShowFileBrowser').checked,
|
||||
showSubagents: document.getElementById('appSettingsShowSubagents').checked,
|
||||
showUltracodeAgents: document.getElementById('appSettingsShowUltracodeAgents').checked,
|
||||
ultracodeFloatingWindows: document.getElementById('appSettingsUltracodeFloatingWindows').checked,
|
||||
showMultiMonitorButton: document.getElementById('appSettingsShowMultiMonitorButton').checked,
|
||||
showPlanUsageLimits: document.getElementById('appSettingsShowPlanUsageLimits').checked,
|
||||
showRedrawButton: document.getElementById('appSettingsShowRedrawButton').checked,
|
||||
gestureControlEnabled: document.getElementById('appSettingsGestureControl').checked,
|
||||
subagentTrackingEnabled: document.getElementById('appSettingsSubagentTracking').checked,
|
||||
subagentActiveTabOnly: document.getElementById('appSettingsSubagentActiveTabOnly').checked,
|
||||
@@ -1343,6 +1428,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
|
||||
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
|
||||
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
|
||||
skin: document.getElementById('appSettingsSkin').value,
|
||||
// Claude CLI settings
|
||||
claudeMode: document.getElementById('appSettingsClaudeMode').value,
|
||||
allowedTools: document.getElementById('appSettingsAllowedTools').value.trim(),
|
||||
@@ -1360,6 +1446,16 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
};
|
||||
|
||||
// The "Token Count" / "Show Cost ($)" header toggles were removed from the
|
||||
// UI, but their features still read settings.showTokenCount / settings.showCost
|
||||
// (applyHeaderVisibilitySettings, the header cost render). saveAppSettings
|
||||
// rebuilds `settings` fresh from the DOM (a full replacement, not a merge), so
|
||||
// without this these keys would be DROPPED on every save and fall back to their
|
||||
// defaults — silently re-enabling the token chip for anyone who'd turned it off,
|
||||
// with no UI left to turn it back off. Preserve the prior stored preference.
|
||||
if (_prev.showTokenCount !== undefined) settings.showTokenCount = _prev.showTokenCount;
|
||||
if (_prev.showCost !== undefined) settings.showCost = _prev.showCost;
|
||||
|
||||
// Save to localStorage
|
||||
this.saveAppSettingsToStorage(settings);
|
||||
this._updateLocalEchoState();
|
||||
@@ -1457,6 +1553,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Apply header visibility immediately
|
||||
this.applyHeaderVisibilitySettings();
|
||||
this.applySkin();
|
||||
this.applyTabWrapSettings();
|
||||
this._updateTokensImmediate(); // Re-render token display (picks up showCost change)
|
||||
this.applyMonitorVisibility();
|
||||
@@ -1469,11 +1566,42 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Apply keyboard bar mode
|
||||
KeyboardAccessoryBar.setMode(settings.extendedKeyboardBar ? 'extended' : 'simple');
|
||||
|
||||
// Save to server (includes notification prefs for cross-browser persistence)
|
||||
// Strip device-specific keys — localEchoEnabled/cjkInputEnabled are per-platform
|
||||
const { localEchoEnabled: _leo, cjkInputEnabled: _cjk, extendedKeyboardBar: _ekb, ...serverSettings } = settings;
|
||||
// Save to server (includes notification prefs for cross-browser persistence).
|
||||
// Strip device-specific DISPLAY keys so they never sync across devices —
|
||||
// localEcho/cjk/extendedKeyboard/skin are per-platform, and showPlanUsageLimits
|
||||
// is per-device too (desktop can show the usage chip while mobile stays hidden).
|
||||
// Telemetry COLLECTION is requested out-of-band via statusLineTelemetry (sent on
|
||||
// ENABLE only, so a device with the chip OFF never strips the exporter that
|
||||
// another device's chip depends on — see system-routes settings handler).
|
||||
const {
|
||||
localEchoEnabled: _leo,
|
||||
cjkInputEnabled: _cjk,
|
||||
extendedKeyboardBar: _ekb,
|
||||
skin: _skin,
|
||||
showPlanUsageLimits: _pul,
|
||||
showAttachmentsButton: _ahb,
|
||||
...serverSettings
|
||||
} = settings;
|
||||
try {
|
||||
await this._apiPut('/api/settings', { ...serverSettings, notificationPreferences: notifPrefsToSave, voiceSettings });
|
||||
const res = await this._apiPut('/api/settings', {
|
||||
...serverSettings,
|
||||
...(settings.showPlanUsageLimits ? { statusLineTelemetry: true } : {}),
|
||||
notificationPreferences: notifPrefsToSave,
|
||||
voiceSettings,
|
||||
});
|
||||
|
||||
// COD-55: the server refuses an unauthenticated public tunnel with a 403 — which
|
||||
// rejects the WHOLE settings PUT. Surface the message and revert the tunnel toggle
|
||||
// (in the UI + localStorage) so it doesn't look enabled. Other settings persisted
|
||||
// to localStorage above still apply locally.
|
||||
if (settings.tunnelEnabled && (await this._handleTunnelEnableRefusal(res))) {
|
||||
settings.tunnelEnabled = false;
|
||||
this.saveAppSettingsToStorage(settings);
|
||||
const cb = document.getElementById('appSettingsTunnelEnabled');
|
||||
if (cb) cb.checked = false;
|
||||
this.closeAppSettings();
|
||||
return;
|
||||
}
|
||||
|
||||
// Save model configuration separately
|
||||
await this.saveModelConfigFromSettings();
|
||||
@@ -1603,7 +1731,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
showProjectInsights: false,
|
||||
showFileBrowser: false,
|
||||
showSubagents: false,
|
||||
showUltracodeAgents: false,
|
||||
ultracodeFloatingWindows: false,
|
||||
showMultiMonitorButton: false,
|
||||
showPlanUsageLimits: false,
|
||||
showAttachmentsButton: false,
|
||||
showRedrawButton: false,
|
||||
// Input
|
||||
gestureControlEnabled: false,
|
||||
// Feature toggles - keep tracking on even on mobile
|
||||
@@ -1613,6 +1746,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
ralphTrackerEnabled: false,
|
||||
tabTwoRows: false,
|
||||
cjkInputEnabled: false,
|
||||
skin: 'daylight-blue',
|
||||
};
|
||||
}
|
||||
// Desktop defaults - rely on ?? operators in apply functions
|
||||
@@ -1650,6 +1784,24 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
// Apply the chosen skin live: sets the html[data-skin] attribute, syncs BOTH
|
||||
// localStorage locations (the standalone 'codeman:skin' key the pre-paint head
|
||||
// script reads + the app-settings blob field written by saveAppSettingsToStorage),
|
||||
// updates window.__codemanSkin, and re-themes any live terminals.
|
||||
applySkin() {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
const skin = settings.skin ?? defaults.skin ?? 'daylight-blue';
|
||||
document.documentElement.setAttribute('data-skin', skin);
|
||||
window.__codemanSkin = skin;
|
||||
try {
|
||||
localStorage.setItem('codeman:skin', skin);
|
||||
} catch (_e) {
|
||||
/* private mode */
|
||||
}
|
||||
if (typeof this.applyTerminalSkin === 'function') this.applyTerminalSkin(skin);
|
||||
},
|
||||
|
||||
applyHeaderVisibilitySettings() {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
@@ -1687,6 +1839,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
responseViewerBtn.classList.toggle('btn-response-viewer-header--hidden', !showResponseViewer);
|
||||
}
|
||||
|
||||
// Hide the attachments (history) button when disabled. Opt-in, default OFF —
|
||||
// marker class, base is display:inline-flex !important.
|
||||
const showAttachmentsButton = settings.showAttachmentsButton ?? defaults.showAttachmentsButton ?? false;
|
||||
const attachmentsBtn = document.getElementById('attachmentsHistoryBtn');
|
||||
if (attachmentsBtn) {
|
||||
attachmentsBtn.classList.toggle('btn-attachments-history--hidden', !showAttachmentsButton);
|
||||
}
|
||||
|
||||
// Multi-monitor button — hidden by default (App Settings → Display → "Header
|
||||
// Displays"). The server renders the correct initial state on every reload;
|
||||
// this handles a live toggle from a settings save (no reload). Toggle the
|
||||
@@ -1697,6 +1857,31 @@ Object.assign(CodemanApp.prototype, {
|
||||
multiMonitorBtn.classList.toggle('btn-multimonitor--hidden', !showMultiMonitorButton);
|
||||
}
|
||||
|
||||
// Ultracode/Workflow agents launcher — hidden by default; reveal when enabled.
|
||||
// Marker class only (base is display:inline-flex !important) so it's auto-excluded
|
||||
// from the mobile-header-buttons-policy guard.
|
||||
const showUltracodeAgents = settings.showUltracodeAgents ?? defaults.showUltracodeAgents ?? false;
|
||||
const ultracodeBtn = document.querySelector('.btn-ultracode-agents');
|
||||
if (ultracodeBtn) {
|
||||
ultracodeBtn.classList.toggle('btn-ultracode-agents--hidden', !showUltracodeAgents);
|
||||
}
|
||||
|
||||
// Plan-usage chip — hidden by default (App Settings → Display → "Plan Usage
|
||||
// Limits"). Server renders the initial state on reload; this handles a live
|
||||
// toggle from a settings save. Marker class (base is display:inline-flex
|
||||
// !important), matching the response-viewer/multimonitor pattern.
|
||||
const showPlanUsageLimits = settings.showPlanUsageLimits ?? defaults.showPlanUsageLimits ?? false;
|
||||
const planUsageChip = document.getElementById('planUsageChip');
|
||||
if (planUsageChip) {
|
||||
planUsageChip.classList.toggle('header-plan-usage--hidden', !showPlanUsageLimits);
|
||||
}
|
||||
|
||||
const showRedrawButton = settings.showRedrawButton ?? defaults.showRedrawButton ?? false;
|
||||
const redrawBtn = document.querySelector('.btn-redraw-terminal');
|
||||
if (redrawBtn) {
|
||||
redrawBtn.classList.toggle('btn-redraw-terminal--hidden', !showRedrawButton);
|
||||
}
|
||||
|
||||
// Notification bell is retired (notifications live in Settings → Notifications
|
||||
// + the drawer); keep it hidden regardless of the notification-enabled state.
|
||||
const notifBtn = document.querySelector('.btn-notifications');
|
||||
@@ -1711,70 +1896,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
toggleMobileHeaderUtilities() {
|
||||
const tray = document.getElementById('headerRight');
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
if (!tray) return;
|
||||
|
||||
const expanded = tray.classList.toggle('mobile-collapsed') === false;
|
||||
if (toggle) {
|
||||
toggle.classList.toggle('active', expanded);
|
||||
toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
|
||||
}
|
||||
},
|
||||
|
||||
handleMobileHeaderUtilityToggle(event) {
|
||||
if (event) {
|
||||
event.preventDefault?.();
|
||||
event.stopPropagation?.();
|
||||
|
||||
const now = Date.now();
|
||||
if ((event.type === 'click' || event.type === 'touchend') && this._lastMobileHeaderUtilityPointerAt) {
|
||||
if (now - this._lastMobileHeaderUtilityPointerAt < 500) return;
|
||||
}
|
||||
if (event.type === 'click' && this._lastMobileHeaderUtilityTouchAt) {
|
||||
if (now - this._lastMobileHeaderUtilityTouchAt < 500) return;
|
||||
}
|
||||
if (event.type === 'touchend') {
|
||||
this._lastMobileHeaderUtilityTouchAt = now;
|
||||
}
|
||||
if (event.type === 'pointerup') {
|
||||
this._lastMobileHeaderUtilityPointerAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
this.toggleMobileHeaderUtilities();
|
||||
},
|
||||
|
||||
bindMobileHeaderUtilityToggle() {
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
if (!toggle || this._mobileHeaderUtilityToggleEl === toggle) return;
|
||||
|
||||
if (this._mobileHeaderUtilityToggleEl && this._mobileHeaderUtilityToggleHandler) {
|
||||
this._mobileHeaderUtilityToggleEl.removeEventListener('click', this._mobileHeaderUtilityToggleHandler);
|
||||
this._mobileHeaderUtilityToggleEl.removeEventListener('touchend', this._mobileHeaderUtilityToggleHandler);
|
||||
this._mobileHeaderUtilityToggleEl.removeEventListener('pointerup', this._mobileHeaderUtilityToggleHandler);
|
||||
}
|
||||
|
||||
this._mobileHeaderUtilityToggleEl = toggle;
|
||||
this._mobileHeaderUtilityToggleHandler = (event) => this.handleMobileHeaderUtilityToggle(event);
|
||||
toggle.addEventListener('click', this._mobileHeaderUtilityToggleHandler);
|
||||
toggle.addEventListener('touchend', this._mobileHeaderUtilityToggleHandler, { passive: false });
|
||||
toggle.addEventListener('pointerup', this._mobileHeaderUtilityToggleHandler);
|
||||
},
|
||||
|
||||
closeMobileHeaderUtilities() {
|
||||
const tray = document.getElementById('headerRight');
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
if (!tray || tray.classList.contains('mobile-collapsed')) return;
|
||||
|
||||
tray.classList.add('mobile-collapsed');
|
||||
if (toggle) {
|
||||
toggle.classList.remove('active');
|
||||
toggle.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
},
|
||||
|
||||
applyTabWrapSettings() {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
@@ -1822,6 +1943,27 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
}
|
||||
|
||||
// Ultracode agents panel visibility (SYNCED setting — not in displayKeys)
|
||||
const showUltracodeAgents = settings.showUltracodeAgents ?? defaults.showUltracodeAgents ?? false;
|
||||
const ultracodePanel = document.getElementById('ultracodeAgentsPanel');
|
||||
if (ultracodePanel) {
|
||||
if (showUltracodeAgents) {
|
||||
ultracodePanel.classList.remove('hidden');
|
||||
} else {
|
||||
ultracodePanel.classList.remove('open');
|
||||
ultracodePanel.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
// Floating ultracode run windows have their OWN opt-in (default OFF), independent of the
|
||||
// docked panel above: pop active runs when enabled, tear them all down when disabled
|
||||
// (additional layer — ultracode-windows.js).
|
||||
const ultracodeFloatingWindows = settings.ultracodeFloatingWindows ?? defaults.ultracodeFloatingWindows ?? false;
|
||||
if (ultracodeFloatingWindows) {
|
||||
if (typeof this.syncAllUltracodeFloatingWindows === 'function') this.syncAllUltracodeFloatingWindows();
|
||||
} else if (typeof this.removeAllUltracodeWindows === 'function') {
|
||||
this.removeAllUltracodeWindows();
|
||||
}
|
||||
|
||||
// File browser panel visibility
|
||||
const fileBrowserPanel = document.getElementById('fileBrowserPanel');
|
||||
if (fileBrowserPanel) {
|
||||
@@ -1943,6 +2085,25 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
async loadAppSettingsFromServer(settingsPromise = null) {
|
||||
// One-time migration: showPlanUsageLimits became a per-device display setting.
|
||||
// Before this, it synced from the server, so the (separate) mobile settings blob
|
||||
// may carry a stale `true` the user never enabled on this device. Clear it once
|
||||
// so mobile defaults to OFF; the desktop blob is untouched and keeps its value.
|
||||
try {
|
||||
if (
|
||||
MobileDetection.getDeviceType() === 'mobile' &&
|
||||
!localStorage.getItem('codeman:planUsagePerDeviceMigrated')
|
||||
) {
|
||||
const s = this.loadAppSettingsFromStorage();
|
||||
if (s && s.showPlanUsageLimits) {
|
||||
s.showPlanUsageLimits = false;
|
||||
this.saveAppSettingsToStorage(s);
|
||||
}
|
||||
localStorage.setItem('codeman:planUsagePerDeviceMigrated', '1');
|
||||
}
|
||||
} catch {
|
||||
/* best-effort migration */
|
||||
}
|
||||
try {
|
||||
const settings = settingsPromise ? await settingsPromise : await fetch('/api/settings').then(r => r.ok ? r.json() : null).then(env => env?.success === true ? env.data : env);
|
||||
if (settings) {
|
||||
@@ -1954,10 +2115,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
// are NOT display keys — they control server-side behavior and must sync from server.
|
||||
const displayKeys = new Set([
|
||||
'showFontControls', 'showSystemStats', 'showTokenCount', 'showCost',
|
||||
'showLifecycleLog', 'showResponseViewer',
|
||||
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
|
||||
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'skin', 'showPlanUsageLimits', 'showAttachmentsButton',
|
||||
]);
|
||||
// The plan-usage chip is a PER-DEVICE display setting (default OFF): desktop
|
||||
// can show it while mobile stays hidden. It used to sync, so an older
|
||||
// server.json may still carry `true` — drop it so the server value is NEVER
|
||||
// seeded into a device that didn't explicitly enable it (collection is handled
|
||||
// separately via the statusLineTelemetry action, not this display flag).
|
||||
delete appSettings.showPlanUsageLimits;
|
||||
// Merge settings: non-display keys always sync from server,
|
||||
// display keys only seed from server when localStorage has no value
|
||||
// (prevents cross-device overwrite while fixing settings re-enabling on fresh loads)
|
||||
|
||||
+1586
-38
File diff suppressed because it is too large
Load Diff
@@ -33,10 +33,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
const truncatedName = displayName.length > 25 ? displayName.substring(0, 25) + '…' : displayName;
|
||||
const statusClass = agent?.status || 'idle';
|
||||
agentItems.push(`
|
||||
<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreMinimizedSubagent('${escapeHtml(agentId)}', '${escapeHtml(sessionId)}')" title="Click to restore">
|
||||
<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreMinimizedSubagent(${escapeHtml(JSON.stringify(agentId))}, ${escapeHtml(JSON.stringify(sessionId))})" title="Click to restore">
|
||||
<span class="subagent-dropdown-status ${statusClass}"></span>
|
||||
<span class="subagent-dropdown-name">${escapeHtml(truncatedName)}</span>
|
||||
<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.permanentlyCloseMinimizedSubagent('${escapeHtml(agentId)}', '${escapeHtml(sessionId)}')" title="Dismiss">×</span>
|
||||
<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.permanentlyCloseMinimizedSubagent(${escapeHtml(JSON.stringify(agentId))}, ${escapeHtml(JSON.stringify(sessionId))})" title="Dismiss">×</span>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
@@ -455,6 +455,16 @@ Object.assign(CodemanApp.prototype, {
|
||||
svg.appendChild(line);
|
||||
}
|
||||
}
|
||||
|
||||
// Ultracode floating run windows → parent tab (additional layer, ultracode-windows.js).
|
||||
// Drawn into the same SVG and same batched read/write pass; the tab-rect cache is shared.
|
||||
if (typeof this._appendUltracodeConnectionLines === 'function') {
|
||||
this._appendUltracodeConnectionLines(svg, rects);
|
||||
}
|
||||
// Agent-transcript windows → their run window / tab (ultracode-windows.js).
|
||||
if (typeof this._appendUltracodeAgentConnectionLines === 'function') {
|
||||
this._appendUltracodeAgentConnectionLines(svg, rects);
|
||||
}
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -689,7 +699,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
parentSessionId && parentSessionName
|
||||
? `<div class="subagent-window-parent" data-parent-session="${parentSessionId}">
|
||||
<span class="parent-label">from</span>
|
||||
<span class="parent-name" onclick="app.selectSession('${escapeHtml(parentSessionId)}')">${escapeHtml(parentSessionName)}</span>
|
||||
<span class="parent-name" onclick="app.selectSession(${escapeHtml(JSON.stringify(parentSessionId))})">${escapeHtml(parentSessionName)}</span>
|
||||
</div>`
|
||||
: '';
|
||||
|
||||
@@ -710,7 +720,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="status ${agent.status}">${agent.status}</span>
|
||||
</div>
|
||||
<div class="subagent-window-actions">
|
||||
<button onclick="app.closeSubagentWindow('${escapeHtml(agentId)}')" title="Minimize to tab">─</button>
|
||||
<button onclick="app.closeSubagentWindow(${escapeHtml(JSON.stringify(agentId))})" title="Minimize to tab">─</button>
|
||||
</div>
|
||||
</div>
|
||||
${parentHeader}
|
||||
@@ -975,6 +985,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
this.imagePopups.clear();
|
||||
|
||||
// Clean up ultracode floating run windows (re-seeded from data.workflowRuns on reconnect)
|
||||
if (typeof this.removeAllUltracodeWindows === 'function') this.removeAllUltracodeWindows();
|
||||
|
||||
// Clear orphaned plan generation state
|
||||
this.activePlanOrchestratorId = null;
|
||||
this._planProgressHandler = null;
|
||||
|
||||
+247
-114
@@ -15,6 +15,14 @@
|
||||
(function (global) {
|
||||
const TERMINAL_QUERY_RESPONSE_PATTERN = /^\x1b\[[\?>=]?[\d;]*[cnR]$/;
|
||||
const TERMINAL_OSC_RESPONSE_PATTERN = /^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/;
|
||||
// Grace window after a manual scroll-up gesture during which sticky-scroll is
|
||||
// suppressed, so high-frequency Codex status redraws don't snap the viewport
|
||||
// back to the bottom while the user is inspecting earlier output.
|
||||
const USER_SCROLL_STICKY_SUPPRESS_MS = 1500;
|
||||
// Mobile browsers synthesize trusted mouse events after touchend. During this
|
||||
// short window, only the app's synthetic tap-to-position mouse event should
|
||||
// reach xterm.
|
||||
const TOUCH_COMPAT_MOUSE_SUPPRESS_MS = 450;
|
||||
|
||||
function isTerminalQueryResponse(data) {
|
||||
return TERMINAL_QUERY_RESPONSE_PATTERN.test(data) || TERMINAL_OSC_RESPONSE_PATTERN.test(data);
|
||||
@@ -24,10 +32,28 @@
|
||||
return isTerminalQueryResponse(data);
|
||||
}
|
||||
|
||||
// Per-skin xterm.js palettes. The 'daylight-blue' object equals the legacy hardcoded
|
||||
// theme, so default behavior is unchanged. Shared at module scope and exported on the
|
||||
// global so both terminal-ui.js (main terminal) and panels-ui.js (teammate terminals,
|
||||
// a separate IIFE) can read the current skin's palette.
|
||||
const CODEMAN_XTERM_THEMES = {
|
||||
og: { background: '#0d0d0d', foreground: '#e0e0e0', cursor: '#e0e0e0', cursorAccent: '#0d0d0d', selection: 'rgba(255,255,255,0.3)', black: '#0d0d0d', red: '#ff6b6b', green: '#51cf66', yellow: '#ffd43b', blue: '#339af0', magenta: '#cc5de8', cyan: '#22b8cf', white: '#e0e0e0', brightBlack: '#495057', brightRed: '#ff8787', brightGreen: '#69db7c', brightYellow: '#ffe066', brightBlue: '#5c7cfa', brightMagenta: '#da77f2', brightCyan: '#66d9e8', brightWhite: '#ffffff' },
|
||||
'daylight-green': { background: '#161b23', foreground: '#dfe6ef', cursor: '#2fd3aa', cursorAccent: '#161b23', selection: 'rgba(47,211,170,0.22)', black: '#161b23', red: '#ff8585', green: '#34d8a0', yellow: '#f0c25a', blue: '#5cc6e8', magenta: '#c79af2', cyan: '#2bcbbb', white: '#dfe6ef', brightBlack: '#5b6675', brightRed: '#ffa0a0', brightGreen: '#5fe6b8', brightYellow: '#ffd884', brightBlue: '#82d4ee', brightMagenta: '#d6b3f7', brightCyan: '#5ee0d4', brightWhite: '#f3f6fa' },
|
||||
'daylight-blue': { background: '#161b23', foreground: '#dfe6ef', cursor: '#38b6f0', cursorAccent: '#161b23', selection: 'rgba(56,182,240,0.22)', black: '#161b23', red: '#ff8585', green: '#34d8a0', yellow: '#f0c25a', blue: '#5cc6e8', magenta: '#c79af2', cyan: '#2bcbbb', white: '#dfe6ef', brightBlack: '#5b6675', brightRed: '#ffa0a0', brightGreen: '#5fe6b8', brightYellow: '#ffd884', brightBlue: '#82d4ee', brightMagenta: '#d6b3f7', brightCyan: '#5ee0d4', brightWhite: '#f3f6fa' },
|
||||
};
|
||||
function currentXtermTheme() {
|
||||
const skin = (typeof document !== 'undefined' && document.documentElement.dataset.skin) || 'daylight-blue';
|
||||
return CODEMAN_XTERM_THEMES[skin] || CODEMAN_XTERM_THEMES['daylight-blue'];
|
||||
}
|
||||
|
||||
global.CodemanTerminalInput = {
|
||||
isTerminalQueryResponse,
|
||||
shouldSuppressTerminalQueryResponse,
|
||||
USER_SCROLL_STICKY_SUPPRESS_MS,
|
||||
TOUCH_COMPAT_MOUSE_SUPPRESS_MS,
|
||||
};
|
||||
global.CODEMAN_XTERM_THEMES = CODEMAN_XTERM_THEMES;
|
||||
global.codemanCurrentXtermTheme = currentXtermTheme;
|
||||
})(window);
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
@@ -42,29 +68,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const scrollback = Number.isFinite(stored) && stored > 0 ? Math.max(stored, DEFAULT_SCROLLBACK) : DEFAULT_SCROLLBACK;
|
||||
|
||||
this.terminal = new Terminal({
|
||||
theme: {
|
||||
background: '#0d0d0d',
|
||||
foreground: '#e0e0e0',
|
||||
cursor: '#e0e0e0',
|
||||
cursorAccent: '#0d0d0d',
|
||||
selection: 'rgba(255, 255, 255, 0.3)',
|
||||
black: '#0d0d0d',
|
||||
red: '#ff6b6b',
|
||||
green: '#51cf66',
|
||||
yellow: '#ffd43b',
|
||||
blue: '#339af0',
|
||||
magenta: '#cc5de8',
|
||||
cyan: '#22b8cf',
|
||||
white: '#e0e0e0',
|
||||
brightBlack: '#495057',
|
||||
brightRed: '#ff8787',
|
||||
brightGreen: '#69db7c',
|
||||
brightYellow: '#ffe066',
|
||||
brightBlue: '#5c7cfa',
|
||||
brightMagenta: '#da77f2',
|
||||
brightCyan: '#66d9e8',
|
||||
brightWhite: '#ffffff',
|
||||
},
|
||||
theme: { ...window.codemanCurrentXtermTheme() },
|
||||
fontFamily: '"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',
|
||||
// Use smaller font on mobile to fit more columns (prevents wrapping of Claude's status line)
|
||||
fontSize: MobileDetection.getDeviceType() === 'mobile' ? 10 : 14,
|
||||
@@ -79,6 +83,23 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.fitAddon = new FitAddon.FitAddon();
|
||||
this.terminal.loadAddon(this.fitAddon);
|
||||
|
||||
// SerializeAddon: lets us snapshot the xterm rendered state (viewport +
|
||||
// scrollback + colors/attrs) when switching away from a tab and restore
|
||||
// it on switch-back. Needed primarily for codex tabs — codex's TUI drops
|
||||
// earlier conversation from its current frame, so replaying the server
|
||||
// byte buffer on tab-switch shows only the latest (idle) frame. The
|
||||
// snapshot captures what the user was actually looking at.
|
||||
this._xtermSnapshots = new Map(); // Map<sessionId, serialized-string>
|
||||
if (typeof SerializeAddon !== 'undefined') {
|
||||
try {
|
||||
this._serializeAddon = new SerializeAddon.SerializeAddon();
|
||||
this.terminal.loadAddon(this._serializeAddon);
|
||||
} catch (_e) {
|
||||
/* SerializeAddon failed — snapshot/restore disabled, fallback to buffer-fetch */
|
||||
this._serializeAddon = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof Unicode11Addon !== 'undefined') {
|
||||
try {
|
||||
const unicode11Addon = new Unicode11Addon.Unicode11Addon();
|
||||
@@ -91,6 +112,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
const container = document.getElementById('terminalContainer');
|
||||
this.terminal.open(container);
|
||||
this._installMobileTapMouseGuard();
|
||||
|
||||
// Suppress xterm key handling during CJK IME composition.
|
||||
// Without this, xterm processes raw keyDown events (e.g., "Process" key)
|
||||
@@ -98,8 +120,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.terminal.attachCustomKeyEventHandler((ev) => {
|
||||
if (ev.isComposing || ev.keyCode === 229) return false;
|
||||
|
||||
// Let Alt+digit pass through to browser (tab switching)
|
||||
if (ev.altKey && ev.key >= '0' && ev.key <= '9') return false;
|
||||
// Let the app's Alt/Option session-nav shortcuts reach the document keydown handler
|
||||
// (app.js switches tabs by PHYSICAL e.code) instead of xterm injecting ESC<char> into
|
||||
// the PTY. Mirror app.js's gate exactly — same physical codes + modifier guard — so
|
||||
// macOS Option layouts (Option+1 -> "¡", Option+[ -> "“") are suppressed here too and
|
||||
// don't leak an escape sequence into the focused terminal on every tab switch.
|
||||
if (ev.altKey && !ev.ctrlKey && !ev.shiftKey && /^(Digit[1-9]|BracketLeft|BracketRight)$/.test(ev.code || '')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ctrl+V / Cmd+V: intercept before xterm sends ^V to PTY.
|
||||
// Route through our paste trap which handles both images and text.
|
||||
@@ -302,6 +330,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
(ev) => {
|
||||
ev.preventDefault();
|
||||
const lines = Math.round(ev.deltaY / 25) || (ev.deltaY > 0 ? 1 : -1);
|
||||
this._noteTerminalUserScroll(lines);
|
||||
this.terminal.scrollLines(lines);
|
||||
},
|
||||
{ passive: false }
|
||||
@@ -342,11 +371,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
let pixelAccum = 0;
|
||||
|
||||
let didScroll = false; // track whether touchmove fired (tap vs scroll)
|
||||
let touchStartY = 0;
|
||||
const TAP_THRESHOLD = 8; // px — ignore micro-drift to distinguish tap from scroll
|
||||
container.addEventListener(
|
||||
'touchstart',
|
||||
(ev) => {
|
||||
if (ev.touches.length === 1) {
|
||||
touchLastY = ev.touches[0].clientY;
|
||||
touchStartY = touchLastY;
|
||||
velocity = 0;
|
||||
pixelAccum = 0;
|
||||
isTouching = true;
|
||||
@@ -365,9 +397,18 @@ Object.assign(CodemanApp.prototype, {
|
||||
'touchmove',
|
||||
(ev) => {
|
||||
if (ev.touches.length === 1 && isTouching) {
|
||||
ev.preventDefault();
|
||||
didScroll = true;
|
||||
const touchY = ev.touches[0].clientY;
|
||||
if (!didScroll && Math.abs(touchY - touchStartY) >= TAP_THRESHOLD) {
|
||||
didScroll = true;
|
||||
}
|
||||
// Below the tap threshold, treat the gesture as a potential tap:
|
||||
// don't preventDefault (iOS needs click synthesis to show the
|
||||
// keyboard) and don't accumulate scroll distance or velocity. Without
|
||||
// this guard, sub-threshold micro-drift still scrolls a line and
|
||||
// leaves a non-zero velocity that touchend turns into a momentum
|
||||
// fling, so a jittery tap would both position the cursor AND scroll.
|
||||
if (!didScroll) return;
|
||||
ev.preventDefault();
|
||||
const delta = touchLastY - touchY; // positive = scroll down
|
||||
pixelAccum += delta;
|
||||
velocity = delta * 1.2;
|
||||
@@ -376,6 +417,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const ch = cellHeight();
|
||||
const lines = Math.trunc(pixelAccum / ch);
|
||||
if (lines !== 0) {
|
||||
this._noteTerminalUserScroll(lines);
|
||||
this.terminal.scrollLines(lines);
|
||||
pixelAccum -= lines * ch;
|
||||
}
|
||||
@@ -386,20 +428,38 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
container.addEventListener(
|
||||
'touchend',
|
||||
() => {
|
||||
(ev) => {
|
||||
isTouching = false;
|
||||
if (!scrollFrame && Math.abs(velocity) > 0.3) {
|
||||
scrollFrame = requestAnimationFrame(scrollLoop);
|
||||
}
|
||||
// Tap (no scroll): refocus xterm's hidden textarea so keyboard input
|
||||
// routes back to the terminal. Without this, a tap on the terminal area
|
||||
// consumes the touch event but xterm's textarea never regains focus.
|
||||
if (!didScroll && this.terminal) {
|
||||
// ── Tap-to-position cursor ──────────────────────────────────
|
||||
// Synthesize a click from the real touch point so the foreground app
|
||||
// moves its cursor to the tapped cell (iOS doesn't reliably do this
|
||||
// itself under touch-action:none). CRITICAL: only when mouse tracking
|
||||
// is ON. xterm disables its local SelectionService while mouse events
|
||||
// are active, so the synthetic click is forwarded to the PTY as an SGR
|
||||
// report (cursor moves). But when tracking is OFF, that same click
|
||||
// drives xterm's LOCAL selection (detail 1/2/3 → char/word/line) — a
|
||||
// tap on CJK text would select & copy it instead of positioning. So
|
||||
// gate strictly on the live mouse-tracking mode.
|
||||
const touch = ev.changedTouches && ev.changedTouches[0];
|
||||
const mouseMode = this.terminal.modes?.mouseTrackingMode;
|
||||
const mouseTrackingOn = !!mouseMode && mouseMode !== 'none';
|
||||
if (touch) {
|
||||
this._suppressTrustedTapMouseEvents();
|
||||
}
|
||||
if (touch && mouseTrackingOn) {
|
||||
this._dispatchSyntheticTerminalClick(touch.clientX, touch.clientY);
|
||||
}
|
||||
this._syncMobileHelperTextareaToCursor();
|
||||
// Route subsequent typing to the right place: keep the CJK input
|
||||
// field focused when Chinese input is on, otherwise the terminal.
|
||||
const cjkInput = document.getElementById('cjkInput');
|
||||
if (cjkInput?.classList.contains('cjk-input-visible')) {
|
||||
cjkInput.focus();
|
||||
} else {
|
||||
this._syncMobileHelperTextareaToCursor();
|
||||
this.terminal.focus();
|
||||
}
|
||||
}
|
||||
@@ -428,6 +488,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._chunkedWriteGen = 0;
|
||||
this._bufferLoadSeq = 0;
|
||||
this._bufferLoadOwner = null;
|
||||
this._lastUserScrollUpAt = null;
|
||||
|
||||
// Handle resize with throttling for performance
|
||||
this._resizeTimeout = null;
|
||||
@@ -560,8 +621,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
// survives tab switches and reconnects.
|
||||
|
||||
this.terminal.onData((data) => {
|
||||
// CJK input has focus — block xterm from sending to PTY
|
||||
if (window.cjkActive || document.activeElement?.id === 'cjkInput') return;
|
||||
// Mouse SGR reports (tap-to-position) are NOT IME input — they must reach
|
||||
// the PTY even while the CJK input field owns focus. Without this exception
|
||||
// tapping to move the cursor silently does nothing whenever Chinese input
|
||||
// is on, because cjkActive stays true the whole time the field is visible.
|
||||
const isMouseReport = /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data);
|
||||
// CJK input has focus — block xterm from sending keystrokes to PTY
|
||||
if (!isMouseReport && (window.cjkActive || document.activeElement?.id === 'cjkInput')) return;
|
||||
if (this.activeSessionId) {
|
||||
// Filter terminal query replies generated by xterm.js itself.
|
||||
// Forwarding them through the WebSocket injects DA/DSR/CPR replies
|
||||
@@ -839,7 +905,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Pattern 1: Commands with file paths (tail -f, cat, head, grep pattern, etc.)
|
||||
// Handles: tail -f /path, grep pattern /path, cat -n /path
|
||||
const cmdPattern = /(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g;
|
||||
// ⚠ The arg group must stay linear-time: `(?:[^\s\/]*\s+)*` (empty-matchable
|
||||
// token, unbounded) backtracks exponentially on lines with a trigger word
|
||||
// followed by multi-space runs (e.g. wrapped heredoc/table output) — froze
|
||||
// the whole tab on hover. Non-empty token + bounded reps is O(n).
|
||||
const cmdPattern = /\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g;
|
||||
|
||||
// Pattern 2: Paths with common extensions
|
||||
const extPattern =
|
||||
@@ -914,6 +984,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.loadTunnelStatus();
|
||||
this.loadHistorySessions();
|
||||
}
|
||||
// Home screen has no input target — hide the CJK textarea (activeSessionId
|
||||
// is null by the time we get here). Guarded: defined on the app object.
|
||||
this._updateCjkInputState?.();
|
||||
},
|
||||
|
||||
hideWelcome() {
|
||||
@@ -927,6 +1000,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
clearTimeout(this._welcomeQrShrinkTimer);
|
||||
qrWrap.classList.remove('expanded');
|
||||
}
|
||||
// Entering a session — restore CJK textarea if the user has it enabled
|
||||
// (activeSessionId is already set by selectSession before this call).
|
||||
this._updateCjkInputState?.();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1360,6 +1436,22 @@ Object.assign(CodemanApp.prototype, {
|
||||
return buffer.viewportY >= buffer.baseY - 2;
|
||||
},
|
||||
|
||||
// Record manual scroll gestures so sticky-scroll can give an upward scroll a
|
||||
// short grace window (see _hasRecentUserScrollUp). A downward scroll that
|
||||
// lands back at the bottom clears the suppression immediately.
|
||||
_noteTerminalUserScroll(lines) {
|
||||
if (lines < 0) {
|
||||
this._lastUserScrollUpAt = performance.now();
|
||||
} else if (this.isTerminalAtBottom()) {
|
||||
this._lastUserScrollUpAt = null;
|
||||
}
|
||||
},
|
||||
|
||||
_hasRecentUserScrollUp() {
|
||||
if (typeof this._lastUserScrollUpAt !== 'number') return false;
|
||||
return performance.now() - this._lastUserScrollUpAt < window.CodemanTerminalInput.USER_SCROLL_STICKY_SUPPRESS_MS;
|
||||
},
|
||||
|
||||
batchTerminalWrite(data) {
|
||||
// If a buffer load (chunkedTerminalWrite) is in progress, queue live events
|
||||
// to prevent interleaving historical buffer data with live SSE data.
|
||||
@@ -1526,71 +1618,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
// CJK textarea already provides visual feedback — bypass local echo
|
||||
// buffering so each composed word reaches the PTY immediately.
|
||||
_handleCjkInput(text) {
|
||||
if (!this.activeSessionId) return;
|
||||
const sessionId = this.activeSessionId;
|
||||
const session = this.sessions.get(sessionId);
|
||||
const useLocalEcho = !!(this._localEchoEnabled && this._localEchoOverlay && session?.mode !== 'shell');
|
||||
if (!useLocalEcho) {
|
||||
this._sendInputAsync(sessionId, text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (text === '\x7f') {
|
||||
const source = this._localEchoOverlay.removeChar();
|
||||
if (source === 'flushed') {
|
||||
// Sync app-level flushed Maps (per-session state for tab switching),
|
||||
// mirroring the onData backspace path — otherwise switching tabs away
|
||||
// and back restores a stale, too-long flushed overlay.
|
||||
const { count, text: flushedText } = this._localEchoOverlay.getFlushed();
|
||||
if (this._flushedOffsets?.has(sessionId)) {
|
||||
if (count === 0) {
|
||||
this._flushedOffsets.delete(sessionId);
|
||||
this._flushedTexts?.delete(sessionId);
|
||||
} else {
|
||||
this._flushedOffsets.set(sessionId, count);
|
||||
this._flushedTexts?.set(sessionId, flushedText);
|
||||
}
|
||||
}
|
||||
this._sendInputAsync(sessionId, text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (/[\r\n]+$/.test(text)) {
|
||||
const committed = text.replace(/[\r\n]+$/g, '');
|
||||
if (committed) this._localEchoOverlay.appendText(committed);
|
||||
const pending = this._localEchoOverlay.pendingText || '';
|
||||
this._localEchoOverlay.clear();
|
||||
this._localEchoOverlay.suppressBufferDetection();
|
||||
this._flushedOffsets?.delete(sessionId);
|
||||
this._flushedTexts?.delete(sessionId);
|
||||
if (pending) this._sendInputAsync(sessionId, pending);
|
||||
setTimeout(() => this._sendInputAsync(sessionId, '\r'), pending ? 80 : 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// Multi-byte escape sequence (arrow/Home/End from a hardware keyboard on
|
||||
// the composer) — forward to the PTY without touching overlay state,
|
||||
// mirroring the onData path. Appending it to pending text would type raw
|
||||
// ESC bytes into the prompt on the next Enter.
|
||||
if (text.length > 1 && text.charCodeAt(0) === 27) {
|
||||
this._sendInputAsync(sessionId, text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (text.length === 1 && text.charCodeAt(0) < 32) {
|
||||
const pending = this._localEchoOverlay.pendingText || '';
|
||||
this._localEchoOverlay.clear();
|
||||
this._localEchoOverlay.suppressBufferDetection();
|
||||
this._flushedOffsets?.delete(sessionId);
|
||||
this._flushedTexts?.delete(sessionId);
|
||||
if (pending) this._sendInputAsync(sessionId, pending);
|
||||
this._sendInputAsync(sessionId, text);
|
||||
return;
|
||||
}
|
||||
|
||||
this._localEchoOverlay.appendText(text);
|
||||
this._sendInputAsync(this.activeSessionId, text);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1611,8 +1643,16 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Per-frame byte budget to prevent main thread blocking.
|
||||
// Large writes (141KB+) can freeze Chrome for 2+ minutes.
|
||||
const MAX_FRAME_BYTES = 65536; // 64KB budget per frame
|
||||
// Codex's TUI emits dense synchronized redraws during thinking/high-effort
|
||||
// phases, so it gets a smaller first frame to keep per-frame xterm/WebGL
|
||||
// stalls short; other modes keep the larger 64KB budget.
|
||||
const activeSession = this.activeSessionId && this.sessions ? this.sessions.get(this.activeSessionId) : null;
|
||||
const MAX_FRAME_BYTES = activeSession?.mode === 'codex' ? 32768 : 65536;
|
||||
let deferred = false;
|
||||
// If the user recently scrolled up, remember the viewport so we can restore
|
||||
// it after the write — Codex status redraws would otherwise jump it.
|
||||
const preserveViewportY =
|
||||
this._hasRecentUserScrollUp() && this.terminal.buffer?.active ? this.terminal.buffer.active.viewportY : null;
|
||||
|
||||
if (_joinedLen <= MAX_FRAME_BYTES) {
|
||||
this.terminal.write(joined);
|
||||
@@ -1629,6 +1669,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
preserveViewportY !== null &&
|
||||
this.terminal.buffer?.active?.viewportY !== preserveViewportY &&
|
||||
typeof this.terminal.scrollToLine === 'function'
|
||||
) {
|
||||
this.terminal.scrollToLine(preserveViewportY);
|
||||
}
|
||||
const bytesThisFrame = deferred ? MAX_FRAME_BYTES : _joinedLen;
|
||||
const _dt = performance.now() - _t0;
|
||||
if (_dt > 100 || deferred)
|
||||
@@ -1636,8 +1683,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
`[CRASH-DIAG] flushPendingWrites: ${_dt.toFixed(0)}ms, ${(bytesThisFrame / 1024).toFixed(0)}KB written${deferred ? ', rest deferred' : ''} (total ${(_joinedLen / 1024).toFixed(0)}KB)`
|
||||
);
|
||||
|
||||
// Sticky scroll: if user was at bottom, keep them there after new output
|
||||
if (this._wasAtBottomBeforeWrite) {
|
||||
// Sticky scroll: if user was at bottom, keep them there after new output.
|
||||
// Give manual scroll-up gestures a short grace window so high-frequency
|
||||
// Codex status ticks do not snap the viewport back while the user is
|
||||
// trying to inspect earlier output.
|
||||
if (this._wasAtBottomBeforeWrite && !this._hasRecentUserScrollUp()) {
|
||||
this.terminal.scrollToBottom();
|
||||
}
|
||||
|
||||
@@ -1926,9 +1976,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
|
||||
try {
|
||||
// Send resize to restore proper dimensions (with minimum enforcement).
|
||||
// The PTY's SIGWINCH on real dim change is enough for Ink to redraw.
|
||||
await this.sendResize(this.activeSessionId);
|
||||
// Force resize even when dimensions match the server's last known state —
|
||||
// another device may have changed the PTY size since this client last sent,
|
||||
// and force guarantees a SIGWINCH → Ink redraw at the current device's size.
|
||||
await this.sendResize(this.activeSessionId, { force: true });
|
||||
|
||||
this.showToast(`Terminal restored to ${dims.cols}x${dims.rows}`, 'success');
|
||||
} catch (err) {
|
||||
@@ -1985,6 +2036,62 @@ Object.assign(CodemanApp.prototype, {
|
||||
} catch {}
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Synthetic tap → mouse report
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Dispatch a mousedown+mouseup pair at viewport coords (clientX/clientY) to
|
||||
// xterm's root element. xterm's mouse-reporting handler reads the event's
|
||||
// client coords, maps them to a terminal cell relative to .xterm-screen, and
|
||||
// — when the foreground app has mouse tracking active (DECSET 1000/1002/1006,
|
||||
// which Claude's input enables) — encodes an SGR mouse report to the PTY.
|
||||
// That is the same path a real desktop click takes; on touch devices the
|
||||
// browser's own compatibility-event synthesis is unreliable (and suppressed
|
||||
// by touch-action:none), so we drive it explicitly. With mouse tracking off
|
||||
// it degrades to a harmless zero-length click (no drag → no text selection).
|
||||
_dispatchSyntheticTerminalClick(clientX, clientY) {
|
||||
const el = this.terminal?.element;
|
||||
if (!el || !Number.isFinite(clientX) || !Number.isFinite(clientY)) return;
|
||||
// xterm registers its mouseup listener on document during mousedown, so a
|
||||
// bubbling mouseup reaches it; dispatch both to the root element in order.
|
||||
const base = {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
view: window,
|
||||
clientX,
|
||||
clientY,
|
||||
screenX: clientX,
|
||||
screenY: clientY,
|
||||
button: 0,
|
||||
detail: 1,
|
||||
};
|
||||
try {
|
||||
el.dispatchEvent(new MouseEvent('mousedown', { ...base, buttons: 1 }));
|
||||
el.dispatchEvent(new MouseEvent('mouseup', { ...base, buttons: 0 }));
|
||||
} catch {
|
||||
/* MouseEvent constructor unavailable — tap-to-position simply no-ops */
|
||||
}
|
||||
},
|
||||
|
||||
_installMobileTapMouseGuard() {
|
||||
const el = this.terminal?.element;
|
||||
if (!el || el._codemanTapMouseGuardInstalled) return;
|
||||
if (typeof MobileDetection !== 'undefined' && MobileDetection.isTouchDevice && !MobileDetection.isTouchDevice()) return;
|
||||
el._codemanTapMouseGuardInstalled = true;
|
||||
const suppressTrustedCompatMouse = (ev) => {
|
||||
const suppressUntil = this._trustedTapMouseSuppressUntil || 0;
|
||||
if (!ev.isTrusted || performance.now() > suppressUntil) return;
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
};
|
||||
el.addEventListener('mousedown', suppressTrustedCompatMouse, true);
|
||||
el.addEventListener('mouseup', suppressTrustedCompatMouse, true);
|
||||
},
|
||||
|
||||
_suppressTrustedTapMouseEvents() {
|
||||
const ms = window.CodemanTerminalInput?.TOUCH_COMPAT_MOUSE_SUPPRESS_MS || 450;
|
||||
this._trustedTapMouseSuppressUntil = performance.now() + ms;
|
||||
},
|
||||
|
||||
increaseFontSize() {
|
||||
const current = this.terminal.options.fontSize || 14;
|
||||
this.setFontSize(Math.min(current + 2, 24));
|
||||
@@ -2034,8 +2141,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
/**
|
||||
* Send resize to a session with minimum dimension enforcement.
|
||||
* @param {string} sessionId
|
||||
* @param {{ forceHttp?: boolean }} [options]
|
||||
* @returns {Promise<void>}
|
||||
* @param {{ forceHttp?: boolean, force?: boolean }} [options]
|
||||
* @returns {Promise<boolean>} Whether dimensions changed from the last send
|
||||
*/
|
||||
async sendResize(sessionId, options = {}) {
|
||||
// Fit terminal to container before reading dimensions — ensures local
|
||||
@@ -2064,16 +2171,20 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Fast path: WebSocket resize
|
||||
if (!options.forceHttp && this._wsReady && this._wsSessionId === sessionId) {
|
||||
try {
|
||||
this._ws.send(JSON.stringify({ t: 'z', c: dims.cols, r: dims.rows, v: viewportType }));
|
||||
const msg = { t: 'z', c: dims.cols, r: dims.rows, v: viewportType };
|
||||
if (options.force) msg.f = true;
|
||||
this._ws.send(JSON.stringify(msg));
|
||||
return changed;
|
||||
} catch {
|
||||
// Fall through to HTTP POST
|
||||
}
|
||||
}
|
||||
const body = { ...dims, viewportType };
|
||||
if (options.force) body.force = true;
|
||||
await fetch(`/api/sessions/${sessionId}/resize`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...dims, viewportType }),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return changed;
|
||||
},
|
||||
@@ -2084,12 +2195,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async sendInput(input) {
|
||||
if (!this.activeSessionId) return;
|
||||
await fetch(`/api/sessions/${this.activeSessionId}/input`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ input, useMux: true }),
|
||||
});
|
||||
if (!this.activeSessionId || !input) return;
|
||||
// Route through the durable, exactly-once delivery layer (useMux for the
|
||||
// POST fallback) so voice / keyboard-accessory / paste input also survives a
|
||||
// dropped link instead of being lost in a single best-effort fetch.
|
||||
this._sendInputAsync(this.activeSessionId, input, { useMux: true });
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -2119,4 +2229,27 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('dirDisplay').textContent = value || 'No directory';
|
||||
}, 100);
|
||||
},
|
||||
|
||||
// Re-theme all live xterm terminals (main + teammate) to the given skin's palette.
|
||||
// Uses the xterm v5+ live setter (full object assignment triggers a repaint for both
|
||||
// DOM and WebGL renderers) plus a belt-and-suspenders refresh().
|
||||
applyTerminalSkin(skin) {
|
||||
const theme = { ...(window.CODEMAN_XTERM_THEMES[skin] || window.CODEMAN_XTERM_THEMES['daylight-blue']) };
|
||||
if (this.terminal) {
|
||||
this.terminal.options.theme = theme;
|
||||
try {
|
||||
this.terminal.refresh(0, this.terminal.rows - 1);
|
||||
} catch {}
|
||||
}
|
||||
if (this.teammateTerminals) {
|
||||
for (const [, entry] of this.teammateTerminals) {
|
||||
if (entry && entry.terminal) {
|
||||
entry.terminal.options.theme = { ...theme };
|
||||
try {
|
||||
entry.terminal.refresh(0, entry.terminal.rows - 1);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* @fileoverview Ultracode / Workflow run visualization — master-detail dock panel.
|
||||
*
|
||||
* Mirrors Claude Code's "working agents" TUI: LEFT pane = runs and their phases
|
||||
* (selectable "tasks"), RIGHT pane = the selected run's agents with model, live
|
||||
* state, TOKENS burned, and TOOL CALLS. Opt-in via the `showUltracodeAgents`
|
||||
* setting; the launcher button + panel are hidden until enabled.
|
||||
*
|
||||
* Data: run SUMMARIES arrive via getLightState (`data.workflowRuns`) and the
|
||||
* `workflow:run_*` SSE events (LEFT list). The full run (with agents[]) is fetched
|
||||
* per-run from GET /api/workflows/:runId when a run is selected (RIGHT pane).
|
||||
*
|
||||
* Standalone: reads only the workflow-run endpoints; never touches subagent state.
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @loadorder 11.5 (after panels-ui.js, before session-ui.js)
|
||||
*/
|
||||
/* global CodemanApp, SSE_EVENTS, escapeHtml */
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
/** Ensure workflow state maps exist (lazy — constructor also seeds them). */
|
||||
_ensureWorkflowState() {
|
||||
if (!this.workflowRuns) this.workflowRuns = new Map(); // runId -> summary
|
||||
if (!this.workflowRunDetails) this.workflowRunDetails = new Map(); // runId -> full run (with agents)
|
||||
if (this.activeWorkflowRunId === undefined) this.activeWorkflowRunId = null;
|
||||
if (this.activeWorkflowPhaseIndex === undefined) this.activeWorkflowPhaseIndex = null;
|
||||
},
|
||||
|
||||
/** Seed the LEFT list from a getLightState snapshot (array of run summaries). */
|
||||
seedWorkflowRuns(summaries) {
|
||||
this._ensureWorkflowState();
|
||||
this.workflowRuns.clear();
|
||||
(summaries || []).forEach((s) => this.workflowRuns.set(s.runId, s));
|
||||
// Restore floating windows for runs that are still active & recent (additional layer).
|
||||
if (typeof this._syncUltracodeFloatingWindow === 'function') {
|
||||
(summaries || []).forEach((s) => this._syncUltracodeFloatingWindow(s, { fromSeed: true }));
|
||||
}
|
||||
this.renderUltracodeAgentsPanel();
|
||||
},
|
||||
|
||||
// ----- SSE handlers (wired in app.js _SSE_HANDLER_MAP) -----
|
||||
_onWorkflowRunDiscovered(data) {
|
||||
this._upsertWorkflowRun(data);
|
||||
},
|
||||
_onWorkflowRunUpdated(data) {
|
||||
this._upsertWorkflowRun(data);
|
||||
},
|
||||
_onWorkflowRunRemoved(data) {
|
||||
this._ensureWorkflowState();
|
||||
if (!data || !data.runId) return;
|
||||
this.workflowRuns.delete(data.runId);
|
||||
this.workflowRunDetails.delete(data.runId);
|
||||
if (this.activeWorkflowRunId === data.runId) this.activeWorkflowRunId = null;
|
||||
// Retire the floating run window too (additional layer — ultracode-windows.js).
|
||||
if (typeof this.closeUltracodeWindow === 'function') this.closeUltracodeWindow(data.runId, false);
|
||||
this.renderUltracodeAgentsPanel();
|
||||
},
|
||||
|
||||
_upsertWorkflowRun(summary) {
|
||||
this._ensureWorkflowState();
|
||||
if (!summary || !summary.runId) return;
|
||||
this.workflowRuns.set(summary.runId, summary);
|
||||
// If the live-updating run is the one open in the detail pane, refresh its agents.
|
||||
if (this.activeWorkflowRunId === summary.runId) {
|
||||
this._fetchWorkflowRunDetail(summary.runId);
|
||||
}
|
||||
// Auto-pop / refresh the floating run window for active runs (additional layer).
|
||||
if (typeof this._syncUltracodeFloatingWindow === 'function') this._syncUltracodeFloatingWindow(summary);
|
||||
this.renderUltracodeAgentsPanel();
|
||||
},
|
||||
|
||||
// ----- Panel open/close -----
|
||||
toggleUltracodeAgentsPanel() {
|
||||
const panel = document.getElementById('ultracodeAgentsPanel');
|
||||
if (!panel) return;
|
||||
panel.classList.remove('hidden');
|
||||
panel.classList.toggle('open');
|
||||
if (panel.classList.contains('open')) this.renderUltracodeAgentsPanel();
|
||||
},
|
||||
closeUltracodeAgentsPanel() {
|
||||
// The X must FULLY hide the panel. Removing only `open` drops it to the
|
||||
// collapsed peek state (header strip still visible), so add `hidden`
|
||||
// (display:none) too — mirrors closeSubagentsPanel. Not the showUltracodeAgents
|
||||
// setting: that also gates the watcher + floating windows; the launcher reopens.
|
||||
const panel = document.getElementById('ultracodeAgentsPanel');
|
||||
if (panel) {
|
||||
panel.classList.remove('open');
|
||||
panel.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
|
||||
// ----- Selection -----
|
||||
selectWorkflowRun(runId) {
|
||||
this._ensureWorkflowState();
|
||||
this.activeWorkflowRunId = runId;
|
||||
this.activeWorkflowPhaseIndex = null; // reset phase filter on run change
|
||||
this._fetchWorkflowRunDetail(runId);
|
||||
this.renderUltracodeAgentsPanel();
|
||||
// Clicking a run also pops its floating window (with connector line to the
|
||||
// session tab), like the auto-popped one — an explicit open, so it ignores the
|
||||
// floating-windows auto-pop toggle (ultracode-windows.js).
|
||||
if (typeof this.openUltracodeWindowForRun === 'function') this.openUltracodeWindowForRun(runId);
|
||||
},
|
||||
selectWorkflowPhase(phaseIndex) {
|
||||
this._ensureWorkflowState();
|
||||
// phaseIndex null => show all phases
|
||||
this.activeWorkflowPhaseIndex = phaseIndex === null || phaseIndex === undefined ? null : Number(phaseIndex);
|
||||
this._renderUltracodeDetail();
|
||||
},
|
||||
|
||||
async _fetchWorkflowRunDetail(runId) {
|
||||
// De-dupe concurrent fetches for the same run — selecting a run can trigger both
|
||||
// a panel refresh and a floating-window open, which would otherwise double-fetch.
|
||||
if (!this._wfDetailInFlight) this._wfDetailInFlight = new Set();
|
||||
if (this._wfDetailInFlight.has(runId)) return;
|
||||
this._wfDetailInFlight.add(runId);
|
||||
try {
|
||||
const res = await fetch(`/api/workflows/${encodeURIComponent(runId)}`);
|
||||
const env = await res.json();
|
||||
const run = env && env.success ? env.data : null;
|
||||
if (run) {
|
||||
this.workflowRunDetails.set(runId, run);
|
||||
if (this.activeWorkflowRunId === runId) this._renderUltracodeDetail();
|
||||
// Refresh the floating window (if one is open for this run) with the fetched agents[].
|
||||
if (this.ultracodeWindows && this.ultracodeWindows.has(runId)) this.renderUltracodeWindowContent(runId);
|
||||
}
|
||||
} catch {
|
||||
/* transient — next update retries */
|
||||
} finally {
|
||||
this._wfDetailInFlight.delete(runId);
|
||||
}
|
||||
},
|
||||
|
||||
// Phase 4: fetch an agent's live transcript by agentId. The workflow agent's
|
||||
// agentId is byte-identical to the agent-<id>.jsonl stem already tracked by
|
||||
// subagent-watcher, so we reuse the existing transcript route — no watcher edits.
|
||||
// Returns { formatted: string[], entryCount } or null when nothing is available
|
||||
// (queued / aged out of tracking / tracking disabled). Rendering into a connected
|
||||
// in-page floating window lives in ultracode-windows.js (openUltracodeAgentWindow) —
|
||||
// we no longer spawn a detached browser popup.
|
||||
async _fetchWorkflowAgentTranscript(agentId) {
|
||||
if (!agentId) return null;
|
||||
let data = null;
|
||||
try {
|
||||
const res = await fetch(`/api/subagents/${encodeURIComponent(agentId)}/transcript?format=formatted`);
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
const ok = data && data.success && data.data;
|
||||
const formatted = ok ? data.data.formatted : null;
|
||||
const entryCount = ok ? data.data.entryCount || 0 : 0;
|
||||
if (!formatted || !entryCount) return null;
|
||||
return { formatted, entryCount };
|
||||
},
|
||||
|
||||
// ----- Render (debounced) -----
|
||||
renderUltracodeAgentsPanel() {
|
||||
clearTimeout(this._ultracodeRenderTimer);
|
||||
this._ultracodeRenderTimer = setTimeout(() => this._renderUltracodeAgentsPanelImmediate(), 150);
|
||||
},
|
||||
|
||||
_renderUltracodeAgentsPanelImmediate() {
|
||||
this._ensureWorkflowState();
|
||||
const panel = document.getElementById('ultracodeAgentsPanel');
|
||||
if (!panel) return;
|
||||
const badge = document.getElementById('ultracodeCountBadge');
|
||||
if (badge) badge.textContent = this.workflowRuns.size ? String(this.workflowRuns.size) : '';
|
||||
this._renderUltracodeRunList();
|
||||
this._renderUltracodeDetail();
|
||||
},
|
||||
|
||||
_renderUltracodeRunList() {
|
||||
const list = document.getElementById('ultracodeRunList');
|
||||
if (!list) return;
|
||||
const runs = Array.from(this.workflowRuns.values()).sort(
|
||||
(a, b) => (b.lastActivityAt || 0) - (a.lastActivityAt || 0)
|
||||
);
|
||||
if (!runs.length) {
|
||||
list.innerHTML = '<div class="subagent-empty">No ultracode runs detected</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = runs.map((r) => this._workflowRunRowHtml(r)).join('');
|
||||
},
|
||||
|
||||
_workflowRunRowHtml(r) {
|
||||
const active = r.runId === this.activeWorkflowRunId;
|
||||
const name = escapeHtml(r.workflowName || r.summary || r.runId);
|
||||
const status = String(r.status || '');
|
||||
const statusCls = this._workflowStatusClass(status);
|
||||
const stats = `${r.agentCount ?? 0} agents · ${this._fmtNum(r.totalTokens)} tok · ${r.totalToolCalls ?? 0} tools`;
|
||||
let phasesHtml = '';
|
||||
if (active && Array.isArray(r.phases) && r.phases.length) {
|
||||
const allActive = this.activeWorkflowPhaseIndex === null ? ' selected' : '';
|
||||
const chips = [
|
||||
`<div class="ultracode-phase-chip${allActive}" onclick="event.stopPropagation();app.selectWorkflowPhase(null)">All</div>`,
|
||||
];
|
||||
r.phases.forEach((p, i) => {
|
||||
const sel = this.activeWorkflowPhaseIndex === i + 1 ? ' selected' : '';
|
||||
chips.push(
|
||||
`<div class="ultracode-phase-chip${sel}" title="${escapeHtml(p.detail || '')}" onclick="event.stopPropagation();app.selectWorkflowPhase(${i + 1})">${escapeHtml(p.title || 'Phase ' + (i + 1))}</div>`
|
||||
);
|
||||
});
|
||||
phasesHtml = `<div class="ultracode-phase-list">${chips.join('')}</div>`;
|
||||
}
|
||||
return (
|
||||
`<div class="ultracode-run-item${active ? ' selected' : ''}" onclick="app.selectWorkflowRun(${escapeHtml(JSON.stringify(r.runId))})">` +
|
||||
`<div class="ultracode-run-head"><span class="ultracode-run-name">${name}</span>` +
|
||||
`<span class="ultracode-status ${statusCls}">${escapeHtml(status || '—')}</span></div>` +
|
||||
`<div class="ultracode-run-stats">${escapeHtml(stats)}</div>` +
|
||||
phasesHtml +
|
||||
`</div>`
|
||||
);
|
||||
},
|
||||
|
||||
_renderUltracodeDetail() {
|
||||
const detail = document.getElementById('ultracodeAgentGrid');
|
||||
if (!detail) return;
|
||||
const runId = this.activeWorkflowRunId;
|
||||
if (!runId) {
|
||||
detail.innerHTML = '<div class="subagent-empty">Select a run to view its agents</div>';
|
||||
return;
|
||||
}
|
||||
const run = this.workflowRunDetails.get(runId);
|
||||
if (!run) {
|
||||
detail.innerHTML = '<div class="subagent-empty">Loading agents…</div>';
|
||||
return;
|
||||
}
|
||||
const phases = Array.isArray(run.phases) ? run.phases : [];
|
||||
let agents = Array.isArray(run.agents) ? run.agents : [];
|
||||
if (this.activeWorkflowPhaseIndex !== null) {
|
||||
agents = agents.filter((a) => a.phaseIndex === this.activeWorkflowPhaseIndex);
|
||||
}
|
||||
if (!agents.length) {
|
||||
detail.innerHTML = '<div class="subagent-empty">No agents in this view</div>';
|
||||
return;
|
||||
}
|
||||
// Group agents by phaseIndex, in phase order.
|
||||
const groups = new Map();
|
||||
agents.forEach((a) => {
|
||||
const key = a.phaseIndex || 0;
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key).push(a);
|
||||
});
|
||||
const orderedKeys = Array.from(groups.keys()).sort((a, b) => a - b);
|
||||
const html = orderedKeys
|
||||
.map((key) => {
|
||||
const group = groups.get(key);
|
||||
const title = (phases[key - 1] && phases[key - 1].title) || `Phase ${key}`;
|
||||
const tok = group.reduce((s, a) => s + (a.tokens || 0), 0);
|
||||
const tools = group.reduce((s, a) => s + (a.toolCalls || 0), 0);
|
||||
const header =
|
||||
`<div class="ultracode-phase-header"><span>${escapeHtml(title)}</span>` +
|
||||
`<span class="ultracode-phase-sub">${this._fmtNum(tok)} tok · ${tools} tools</span></div>`;
|
||||
return header + group.map((a) => this._workflowAgentCardHtml(a, runId)).join('');
|
||||
})
|
||||
.join('');
|
||||
detail.innerHTML = html;
|
||||
},
|
||||
|
||||
_workflowAgentCardHtml(a, runId) {
|
||||
const state = String(a.state || 'start');
|
||||
const stateCls = this._workflowAgentStateClass(state);
|
||||
const stateLabel = state === 'start' ? 'queued' : state === 'progress' ? 'running' : state;
|
||||
const model = this._modelShort(a.model);
|
||||
const tokens = a.tokens === undefined ? '—' : this._fmtNum(a.tokens);
|
||||
const tools = a.toolCalls === undefined ? '—' : String(a.toolCalls);
|
||||
let secondary = '';
|
||||
if (state === 'done' && a.resultPreview) {
|
||||
secondary = escapeHtml(a.resultPreview);
|
||||
} else if (a.lastToolName) {
|
||||
secondary = escapeHtml(a.lastToolName + (a.lastToolSummary ? ' · ' + a.lastToolSummary : ''));
|
||||
}
|
||||
// Phase 4: cards with an agentId open the live transcript (the agentId is byte-identical
|
||||
// to the agent-<id>.jsonl stem already tracked by subagent-watcher). 'start' agents have
|
||||
// no agentId yet, so they stay non-clickable.
|
||||
const clickable = !!a.agentId;
|
||||
// At-a-glance state tint on the whole card: green when done, yellow while working.
|
||||
const cardStateCls = state === 'done' ? ' uw-state-done' : state === 'progress' ? ' uw-state-working' : '';
|
||||
const cardAttrs = clickable
|
||||
? ` class="ultracode-agent-card ultracode-agent-card--clickable${cardStateCls}" role="button" tabindex="0"` +
|
||||
` title="View transcript" onclick="app.openUltracodeAgentWindow(${escapeHtml(JSON.stringify(a.agentId))},${escapeHtml(JSON.stringify(runId || ''))})"`
|
||||
: ` class="ultracode-agent-card${cardStateCls}"`;
|
||||
return (
|
||||
`<div${cardAttrs}>` +
|
||||
`<div class="ultracode-agent-top">` +
|
||||
`<span class="ultracode-agent-label">${escapeHtml(a.label || 'agent')}</span>` +
|
||||
`<span class="ultracode-agent-state ${stateCls}">${escapeHtml(stateLabel)}</span>` +
|
||||
`</div>` +
|
||||
`<div class="ultracode-agent-meta">` +
|
||||
`<span class="ultracode-chip" title="model">${escapeHtml(model)}</span>` +
|
||||
`<span class="ultracode-chip ultracode-chip-tok" title="tokens burned">${tokens} tok</span>` +
|
||||
`<span class="ultracode-chip ultracode-chip-tool" title="tool calls">${tools} tools</span>` +
|
||||
`</div>` +
|
||||
(secondary ? `<div class="ultracode-agent-sub">${secondary}</div>` : '') +
|
||||
`</div>`
|
||||
);
|
||||
},
|
||||
|
||||
// ----- helpers -----
|
||||
_workflowStatusClass(status) {
|
||||
if (status === 'completed') return 'completed';
|
||||
if (status === 'running') return 'active';
|
||||
if (status === 'killed' || status === 'failed') return 'failed';
|
||||
return '';
|
||||
},
|
||||
_workflowAgentStateClass(state) {
|
||||
if (state === 'done') return 'completed';
|
||||
if (state === 'progress') return 'active';
|
||||
return 'idle'; // start / queued
|
||||
},
|
||||
_modelShort(model) {
|
||||
if (!model) return '';
|
||||
return String(model)
|
||||
.replace(/^claude-/, '')
|
||||
.replace(/-\d{8}$/, '');
|
||||
},
|
||||
_fmtNum(n) {
|
||||
if (n === undefined || n === null) return '0';
|
||||
if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';
|
||||
if (n >= 1000) return (n / 1000).toFixed(1) + 'k';
|
||||
return String(n);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,848 @@
|
||||
/**
|
||||
* @fileoverview Ultracode floating run windows — auto-popping draggable windows
|
||||
* with a connector line to the originating session tab.
|
||||
*
|
||||
* This is the "floating thing" companion to the docked master-detail panel in
|
||||
* `ultracode-panel.js` (the dock panel stays — these windows are ADDITIONAL).
|
||||
* When the `ultracodeFloatingWindows` setting is on (a DEDICATED toggle, separate
|
||||
* from the dock panel's `showUltracodeAgents` — see `_ultracodeFloatingEnabled`),
|
||||
* a small floating window pops up
|
||||
* for each ACTIVE ultracode/Workflow run (status not completed/killed/failed),
|
||||
* mirroring the live agent grid, and is connected by a glowing line to the
|
||||
* Codeman tab whose `claudeSessionId` matches the run's `sessionUuid` — the same
|
||||
* line idiom subagent windows use. The window auto-closes a few seconds after
|
||||
* its run finishes; an explicitly-closed run is remembered and never re-pops.
|
||||
*
|
||||
* Reuses, rather than duplicates:
|
||||
* - `makeWindowDraggable` + the shared `#connectionLines` SVG (subagent-windows.js)
|
||||
* - `_workflowAgentCardHtml`, `_fmtNum`, `_workflowStatusClass`, `_fetchWorkflowRunDetail`,
|
||||
* and the `workflowRuns` / `workflowRunDetails` maps (ultracode-panel.js)
|
||||
*
|
||||
* The connector-line draw is appended to the shared SVG from inside
|
||||
* `_updateConnectionLinesImmediate` (subagent-windows.js calls
|
||||
* `_appendUltracodeConnectionLines` at the end of its render pass), so both the
|
||||
* subagent and ultracode lines live in one batched read→write reflow pass.
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency subagent-windows.js (makeWindowDraggable, updateConnectionLines, #connectionLines)
|
||||
* @dependency ultracode-panel.js (workflowRuns/workflowRunDetails, _workflowAgentCardHtml, _fmtNum)
|
||||
* @loadorder 15.5 (after subagent-windows.js — needs makeWindowDraggable at runtime)
|
||||
*/
|
||||
/* global CodemanApp, escapeHtml */
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
/** Lazily seed the floating-window state maps (constructor also seeds them). */
|
||||
_ensureUltracodeWindowState() {
|
||||
if (!this.ultracodeWindows) this.ultracodeWindows = new Map(); // runId -> { element, parentSessionId, dragListeners }
|
||||
if (!this.ultracodeWindowsClosed) this.ultracodeWindowsClosed = new Set(); // runIds the user dismissed
|
||||
if (!this.ultracodeWindowCloseTimers) this.ultracodeWindowCloseTimers = new Map(); // runId -> setTimeout id
|
||||
if (!this.ultracodeAgentWindows) this.ultracodeAgentWindows = new Map(); // agentId -> { element, runId, dragListeners }
|
||||
if (!this.minimizedUltracodeRuns) this.minimizedUltracodeRuns = new Map(); // sessionId -> Set<runId> minimized to a tab
|
||||
if (!this.minimizedUltracodeAgents) this.minimizedUltracodeAgents = new Map(); // sessionId -> Map<agentId,{runId,label}>
|
||||
if (this.ultracodeWindowZIndex === undefined) this.ultracodeWindowZIndex = 1000;
|
||||
},
|
||||
|
||||
/** Floating windows have their own opt-in (default OFF), independent of the dock panel. */
|
||||
_ultracodeFloatingEnabled() {
|
||||
const settings = this.loadAppSettingsFromStorage ? this.loadAppSettingsFromStorage() : {};
|
||||
return !!(settings && settings.ultracodeFloatingWindows);
|
||||
},
|
||||
|
||||
/** A run is "working" until it reaches a terminal status. Mid-run status is absent. */
|
||||
_isWorkflowRunActive(run) {
|
||||
const s = String((run && run.status) || '');
|
||||
return !(s === 'completed' || s === 'killed' || s === 'failed');
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolve which Codeman tab a run belongs to: the session whose
|
||||
* `claudeSessionId` equals the run's `sessionUuid` (the path segment the watcher
|
||||
* captured). Falls back to the active session so the line still lands somewhere.
|
||||
*/
|
||||
_resolveUltracodeParentSession(run) {
|
||||
const uuid = run && run.sessionUuid;
|
||||
if (uuid && this.sessions) {
|
||||
for (const [sessionId, session] of this.sessions) {
|
||||
if (session && session.claudeSessionId === uuid) return sessionId;
|
||||
}
|
||||
}
|
||||
if (this.activeSessionId && this.sessions && this.sessions.has(this.activeSessionId)) {
|
||||
return this.activeSessionId;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Auto-pop driver — called for every run discovered/updated and on reconnect seed.
|
||||
* Creates a floating window for active runs, refreshes existing ones, and schedules
|
||||
* an auto-close once a run finishes.
|
||||
*/
|
||||
_syncUltracodeFloatingWindow(run, opts) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!run || !run.runId) return;
|
||||
const runId = run.runId;
|
||||
const existing = this.ultracodeWindows.get(runId);
|
||||
// Auto-pop is gated on the floating-windows toggle, but an ALREADY-open window
|
||||
// (e.g. one opened by clicking the run in the dock) keeps refreshing regardless.
|
||||
if (!existing && !this._ultracodeFloatingEnabled()) return;
|
||||
if (this.ultracodeWindowsClosed.has(runId)) return; // respect explicit dismissal
|
||||
|
||||
const active = this._isWorkflowRunActive(run);
|
||||
|
||||
// Minimized to a tab — keep it there (don't re-pop a window). Clear the tab badge a
|
||||
// short while after the run finishes, mirroring the floating window's finish grace.
|
||||
if (this._isUltracodeRunMinimized(runId)) {
|
||||
if (!active && !this.ultracodeWindowCloseTimers.has(runId)) {
|
||||
const timer = setTimeout(() => {
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
this._removeMinimizedUltracodeRun(runId);
|
||||
this.renderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
}, 8000);
|
||||
this.ultracodeWindowCloseTimers.set(runId, timer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (active) {
|
||||
// Run is alive — cancel any pending auto-close.
|
||||
const pending = this.ultracodeWindowCloseTimers.get(runId);
|
||||
if (pending) {
|
||||
clearTimeout(pending);
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
}
|
||||
if (existing) {
|
||||
this.renderUltracodeWindowContent(runId);
|
||||
this._fetchWorkflowRunDetail(runId); // refresh agents[]; re-renders window on land
|
||||
} else {
|
||||
// On a reconnect snapshot, only restore windows for genuinely recent runs so
|
||||
// a backlog of stale undefined-status runs doesn't carpet the screen.
|
||||
if (opts && opts.fromSeed) {
|
||||
const FLOAT_SEED_MAX_AGE_MS = 5 * 60 * 1000;
|
||||
const age = Date.now() - (run.lastActivityAt || 0);
|
||||
if (!(run.lastActivityAt && age < FLOAT_SEED_MAX_AGE_MS)) return;
|
||||
}
|
||||
this.createUltracodeWindow(run);
|
||||
}
|
||||
} else if (existing) {
|
||||
// Finished — refresh to the final state (status + final agent states), show it
|
||||
// briefly, then retire the floating window.
|
||||
this._fetchWorkflowRunDetail(runId);
|
||||
this.renderUltracodeWindowContent(runId);
|
||||
if (!this.ultracodeWindowCloseTimers.has(runId)) {
|
||||
const FLOAT_FINISH_GRACE_MS = 8000;
|
||||
const timer = setTimeout(() => {
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
this.closeUltracodeWindow(runId, false);
|
||||
}, FLOAT_FINISH_GRACE_MS);
|
||||
this.ultracodeWindowCloseTimers.set(runId, timer);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Explicitly open (or focus) the floating window for a run — the click-through
|
||||
* from the dock panel's run list. Unlike auto-pop this ignores the floating-windows
|
||||
* toggle and clears any prior dismissal (it's a direct user action), then draws the
|
||||
* connector line from the run's session tab.
|
||||
*/
|
||||
openUltracodeWindowForRun(runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!runId) return;
|
||||
const run = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
if (!run) return;
|
||||
this.ultracodeWindowsClosed.delete(runId); // an explicit open overrides a past dismissal
|
||||
this._removeMinimizedUltracodeRun(runId); // …and a past minimize-to-tab
|
||||
const existing = this.ultracodeWindows.get(runId);
|
||||
if (existing) {
|
||||
// Already open — bring to front and refresh.
|
||||
existing.element.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
this.renderUltracodeWindowContent(runId);
|
||||
this._fetchWorkflowRunDetail(runId);
|
||||
this.updateConnectionLines();
|
||||
} else {
|
||||
this.createUltracodeWindow(run);
|
||||
}
|
||||
},
|
||||
|
||||
/** Build and mount a floating window for a run, positioned near its parent tab. */
|
||||
createUltracodeWindow(run) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const runId = run.runId;
|
||||
if (this.ultracodeWindows.has(runId)) return;
|
||||
const parentSessionId = this._resolveUltracodeParentSession(run);
|
||||
const titleText = run.workflowName || run.summary || runId;
|
||||
|
||||
const win = document.createElement('div');
|
||||
win.className = 'ultracode-window spawning';
|
||||
win.id = `ultracode-window-${runId}`;
|
||||
win.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
win.innerHTML = `
|
||||
<div class="ultracode-window-header">
|
||||
<div class="ultracode-window-title" title="${escapeHtml(titleText)}">
|
||||
<span class="icon">🧬</span>
|
||||
<span class="uw-name">${escapeHtml(titleText)}</span>
|
||||
<span class="uw-status"></span>
|
||||
</div>
|
||||
<div class="ultracode-window-actions">
|
||||
<button class="uw-min" type="button" title="Minimize to tab">─</button>
|
||||
<button class="uw-close" type="button" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ultracode-window-body" id="ultracode-window-body-${runId}">
|
||||
<div class="subagent-empty">Loading agents…</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Position: spawn from the parent tab if we can find it, else cascade.
|
||||
const parentTab = parentSessionId ? document.querySelector(`.session-tab[data-id="${parentSessionId}"]`) : null;
|
||||
if (parentTab) {
|
||||
const r = parentTab.getBoundingClientRect();
|
||||
const left = Math.max(8, Math.min(r.left, window.innerWidth - 392));
|
||||
win.style.left = `${left}px`;
|
||||
win.style.top = `${r.bottom + 14}px`;
|
||||
} else {
|
||||
const n = this.ultracodeWindows.size;
|
||||
win.style.left = `${24 + n * 26}px`;
|
||||
win.style.top = `${96 + n * 26}px`;
|
||||
}
|
||||
|
||||
document.body.appendChild(win);
|
||||
// Drop the spawn class on the next frame so the transition runs.
|
||||
requestAnimationFrame(() => win.classList.remove('spawning'));
|
||||
|
||||
const header = win.querySelector('.ultracode-window-header');
|
||||
const dragListeners = this.makeWindowDraggable(win, header);
|
||||
|
||||
win.querySelector('.uw-min').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.minimizeUltracodeWindowToTab(runId);
|
||||
});
|
||||
win.querySelector('.uw-close').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.closeUltracodeWindow(runId, true);
|
||||
});
|
||||
const nameEl = win.querySelector('.uw-name');
|
||||
if (parentSessionId) {
|
||||
nameEl.style.cursor = 'pointer';
|
||||
nameEl.title = 'Go to session';
|
||||
nameEl.addEventListener('click', () => this.selectSession(parentSessionId));
|
||||
}
|
||||
|
||||
this.ultracodeWindows.set(runId, { element: win, parentSessionId, dragListeners });
|
||||
|
||||
this.renderUltracodeWindowContent(runId);
|
||||
this._fetchWorkflowRunDetail(runId); // pull agents[] for the body
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
// ── Minimize a run window into its originating tab (same idiom as subagent windows) ──
|
||||
|
||||
/** Is this run currently minimized to a tab (so auto-pop should leave it alone)? */
|
||||
_isUltracodeRunMinimized(runId) {
|
||||
if (!this.minimizedUltracodeRuns) return false;
|
||||
for (const set of this.minimizedUltracodeRuns.values()) {
|
||||
if (set.has(runId)) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/** Drop a run from the minimized-to-tab tracking (all sessions, or a specific one). */
|
||||
_removeMinimizedUltracodeRun(runId, sessionId) {
|
||||
if (!this.minimizedUltracodeRuns) return;
|
||||
if (sessionId) {
|
||||
const set = this.minimizedUltracodeRuns.get(sessionId);
|
||||
if (set) {
|
||||
set.delete(runId);
|
||||
if (!set.size) this.minimizedUltracodeRuns.delete(sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const [sid, set] of this.minimizedUltracodeRuns) {
|
||||
if (set.delete(runId) && !set.size) this.minimizedUltracodeRuns.delete(sid);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Minimize the floating run window into its originating session tab: record it as
|
||||
* minimized (so a badge renders on the tab), genie-animate the window toward that
|
||||
* tab, then remove the floating element. Restorable from the tab badge dropdown.
|
||||
*/
|
||||
minimizeUltracodeWindowToTab(runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const data = this.ultracodeWindows.get(runId);
|
||||
if (!data) return;
|
||||
|
||||
let parentSessionId = data.parentSessionId;
|
||||
if (!parentSessionId) {
|
||||
const summary = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
parentSessionId = summary ? this._resolveUltracodeParentSession(summary) : null;
|
||||
}
|
||||
// No tab to fly into → fall back to a plain close so the window isn't orphaned.
|
||||
if (!parentSessionId) {
|
||||
this.closeUltracodeWindow(runId, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel any pending finish auto-close — the badge owns the run's lifecycle now.
|
||||
const pending = this.ultracodeWindowCloseTimers.get(runId);
|
||||
if (pending) {
|
||||
clearTimeout(pending);
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
}
|
||||
|
||||
if (!this.minimizedUltracodeRuns.has(parentSessionId)) this.minimizedUltracodeRuns.set(parentSessionId, new Set());
|
||||
this.minimizedUltracodeRuns.get(parentSessionId).add(runId);
|
||||
|
||||
const element = data.element;
|
||||
const dragListeners = data.dragListeners;
|
||||
this._animateUltracodeWindowToTab(element, parentSessionId, () => {
|
||||
this._teardownUltracodeDrag(dragListeners);
|
||||
if (element) element.remove();
|
||||
this.ultracodeWindows.delete(runId);
|
||||
// Full rebuild so the tab badge renders (the incremental path only knows subagent badges).
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
});
|
||||
},
|
||||
|
||||
/** Genie the window toward the center of its tab, then invoke `done` to tear it down. */
|
||||
_animateUltracodeWindowToTab(element, sessionId, done) {
|
||||
const tab = sessionId ? document.querySelector(`.session-tab[data-id="${sessionId}"]`) : null;
|
||||
if (!tab || !element) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
const w = element.getBoundingClientRect();
|
||||
const t = tab.getBoundingClientRect();
|
||||
const dx = t.left + t.width / 2 - (w.left + w.width / 2);
|
||||
const dy = t.top + t.height / 2 - (w.top + w.height / 2);
|
||||
element.style.transformOrigin = 'center center';
|
||||
element.style.transition = 'transform 0.26s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.26s ease';
|
||||
element.style.pointerEvents = 'none';
|
||||
requestAnimationFrame(() => {
|
||||
element.style.transform = `translate(${dx}px, ${dy}px) scale(0.06)`;
|
||||
element.style.opacity = '0';
|
||||
});
|
||||
let finished = false;
|
||||
const finish = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
done();
|
||||
};
|
||||
element.addEventListener('transitionend', finish, { once: true });
|
||||
setTimeout(finish, 320); // fallback in case transitionend doesn't fire
|
||||
},
|
||||
|
||||
/** Tab badge (with restore/dismiss dropdown) for runs minimized to this session's tab. */
|
||||
renderUltracodeTabBadge(sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const runSet = this.minimizedUltracodeRuns.get(sessionId);
|
||||
const agentMap = this.minimizedUltracodeAgents.get(sessionId);
|
||||
const total = (runSet ? runSet.size : 0) + (agentMap ? agentMap.size : 0);
|
||||
if (total === 0) return '';
|
||||
|
||||
const trunc = (s) => (s.length > 25 ? s.slice(0, 25) + '…' : s);
|
||||
const items = [];
|
||||
// Minimized run windows (🧬) first…
|
||||
if (runSet) {
|
||||
for (const runId of runSet) {
|
||||
const run = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
const name = run ? run.workflowName || run.summary || runId : runId;
|
||||
const statusCls = this._workflowStatusClass(run ? String(run.status || '') : '');
|
||||
items.push(
|
||||
`<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreUltracodeRunFromTab(${escapeHtml(JSON.stringify(runId))},${escapeHtml(JSON.stringify(sessionId))})" title="Click to restore run">` +
|
||||
`<span class="subagent-dropdown-status ${statusCls}"></span>` +
|
||||
`<span class="ultracode-dd-icon">🧬</span>` +
|
||||
`<span class="subagent-dropdown-name">${escapeHtml(trunc(name))}</span>` +
|
||||
`<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.dismissMinimizedUltracodeRun(${escapeHtml(JSON.stringify(runId))},${escapeHtml(JSON.stringify(sessionId))})" title="Dismiss">×</span>` +
|
||||
`</div>`
|
||||
);
|
||||
}
|
||||
}
|
||||
// …then minimized agent transcripts (📄).
|
||||
if (agentMap) {
|
||||
for (const [agentId, entry] of agentMap) {
|
||||
const name = (entry && entry.label) || agentId;
|
||||
items.push(
|
||||
`<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreUltracodeAgentFromTab(${escapeHtml(JSON.stringify(agentId))},${escapeHtml(JSON.stringify(sessionId))})" title="Click to restore transcript">` +
|
||||
`<span class="subagent-dropdown-status"></span>` +
|
||||
`<span class="ultracode-dd-icon">📄</span>` +
|
||||
`<span class="subagent-dropdown-name">${escapeHtml(trunc(name))}</span>` +
|
||||
`<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.dismissMinimizedUltracodeAgent(${escapeHtml(JSON.stringify(agentId))},${escapeHtml(JSON.stringify(sessionId))})" title="Dismiss">×</span>` +
|
||||
`</div>`
|
||||
);
|
||||
}
|
||||
}
|
||||
const label = total === 1 ? 'ULTRA' : `ULTRA (${total})`;
|
||||
return (
|
||||
`<span class="tab-ultracode-badge" onmouseenter="app.showSubagentDropdown(this)" onmouseleave="app.scheduleHideSubagentDropdown(this)" onclick="event.stopPropagation(); app.pinSubagentDropdown(this);">` +
|
||||
`<span class="subagent-label">${label}</span>` +
|
||||
`<div class="subagent-dropdown" onmouseenter="app.cancelHideSubagentDropdown()" onmouseleave="app.scheduleHideSubagentDropdown(this.parentElement)">${items.join('')}</div>` +
|
||||
`</span>`
|
||||
);
|
||||
},
|
||||
|
||||
/** Restore a minimized run from its tab badge: re-open the floating window. */
|
||||
restoreUltracodeRunFromTab(runId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
this._removeMinimizedUltracodeRun(runId, sessionId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.openUltracodeWindowForRun(runId);
|
||||
},
|
||||
|
||||
/** Dismiss a minimized run from its tab badge (don't re-pop it). */
|
||||
dismissMinimizedUltracodeRun(runId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
this._removeMinimizedUltracodeRun(runId, sessionId);
|
||||
this.ultracodeWindowsClosed.add(runId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
// ── Minimize an agent transcript window into its tab (same idiom as run windows) ──
|
||||
|
||||
/** Is this agent transcript currently minimized to a tab? */
|
||||
_isUltracodeAgentMinimized(agentId) {
|
||||
if (!this.minimizedUltracodeAgents) return false;
|
||||
for (const map of this.minimizedUltracodeAgents.values()) {
|
||||
if (map.has(agentId)) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/** Look up a minimized agent's {runId,label} entry (across sessions). */
|
||||
_getMinimizedUltracodeAgent(agentId) {
|
||||
if (!this.minimizedUltracodeAgents) return null;
|
||||
for (const map of this.minimizedUltracodeAgents.values()) {
|
||||
if (map.has(agentId)) return map.get(agentId);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/** Drop an agent from minimized tracking (all sessions, or a specific one). */
|
||||
_removeMinimizedUltracodeAgent(agentId, sessionId) {
|
||||
if (!this.minimizedUltracodeAgents) return;
|
||||
if (sessionId) {
|
||||
const map = this.minimizedUltracodeAgents.get(sessionId);
|
||||
if (map) {
|
||||
map.delete(agentId);
|
||||
if (!map.size) this.minimizedUltracodeAgents.delete(sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const [sid, map] of this.minimizedUltracodeAgents) {
|
||||
if (map.delete(agentId) && !map.size) this.minimizedUltracodeAgents.delete(sid);
|
||||
}
|
||||
},
|
||||
|
||||
/** Minimize an agent transcript window into the run's originating session tab. */
|
||||
minimizeUltracodeAgentWindowToTab(agentId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const info = this.ultracodeAgentWindows.get(agentId);
|
||||
if (!info) return;
|
||||
const runId = info.runId;
|
||||
const summary = runId && this.workflowRuns ? this.workflowRuns.get(runId) : null;
|
||||
let parentSessionId = summary ? this._resolveUltracodeParentSession(summary) : null;
|
||||
if (!parentSessionId && this.activeSessionId && this.sessions && this.sessions.has(this.activeSessionId)) {
|
||||
parentSessionId = this.activeSessionId;
|
||||
}
|
||||
// No tab to fly into → plain close rather than orphan it.
|
||||
if (!parentSessionId) {
|
||||
this.closeUltracodeAgentWindow(agentId);
|
||||
return;
|
||||
}
|
||||
const labelEl = info.element.querySelector('.uw-name');
|
||||
const label = labelEl ? labelEl.textContent : agentId;
|
||||
if (!this.minimizedUltracodeAgents.has(parentSessionId))
|
||||
this.minimizedUltracodeAgents.set(parentSessionId, new Map());
|
||||
this.minimizedUltracodeAgents.get(parentSessionId).set(agentId, { runId, label });
|
||||
|
||||
const element = info.element;
|
||||
const dragListeners = info.dragListeners;
|
||||
this._animateUltracodeWindowToTab(element, parentSessionId, () => {
|
||||
this._teardownUltracodeDrag(dragListeners);
|
||||
if (element) element.remove();
|
||||
this.ultracodeAgentWindows.delete(agentId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
});
|
||||
},
|
||||
|
||||
/** Restore a minimized agent transcript from its tab badge: re-open its window. */
|
||||
restoreUltracodeAgentFromTab(agentId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const entry = this._getMinimizedUltracodeAgent(agentId);
|
||||
const runId = entry ? entry.runId : null;
|
||||
this._removeMinimizedUltracodeAgent(agentId, sessionId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.openUltracodeAgentWindow(agentId, runId);
|
||||
},
|
||||
|
||||
/** Dismiss a minimized agent transcript from its tab badge. */
|
||||
dismissMinimizedUltracodeAgent(agentId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
this._removeMinimizedUltracodeAgent(agentId, sessionId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
/** Remove a floating window. `userInitiated` records a dismissal so it won't re-pop. */
|
||||
closeUltracodeWindow(runId, userInitiated) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const pending = this.ultracodeWindowCloseTimers.get(runId);
|
||||
if (pending) {
|
||||
clearTimeout(pending);
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
}
|
||||
const data = this.ultracodeWindows.get(runId);
|
||||
if (userInitiated) this.ultracodeWindowsClosed.add(runId);
|
||||
if (!data) return;
|
||||
this._teardownUltracodeDrag(data.dragListeners);
|
||||
data.element.remove();
|
||||
this.ultracodeWindows.delete(runId);
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
/** Detach the document-level drag listeners returned by makeWindowDraggable. */
|
||||
_teardownUltracodeDrag(dl) {
|
||||
if (!dl) return;
|
||||
document.removeEventListener('mousemove', dl.move);
|
||||
document.removeEventListener('mouseup', dl.up);
|
||||
if (dl.touchMove) {
|
||||
document.removeEventListener('touchmove', dl.touchMove);
|
||||
document.removeEventListener('touchend', dl.up);
|
||||
document.removeEventListener('touchcancel', dl.up);
|
||||
}
|
||||
if (dl.handle) {
|
||||
dl.handle.removeEventListener('mousedown', dl.handleMouseDown);
|
||||
dl.handle.removeEventListener('touchstart', dl.handleTouchStart);
|
||||
}
|
||||
},
|
||||
|
||||
// ── Agent-transcript windows ────────────────────────────────────────────────
|
||||
// Clicking an agent card (in a run window OR the dock panel) opens the agent's
|
||||
// live transcript as its OWN in-page floating window, line-tied to its parent run
|
||||
// window (or the run's session tab when that window is closed). Replaces the old
|
||||
// detached `window.open` browser popup so the transcript stays inside the same
|
||||
// draggable, connector-line floating-window system as the run windows.
|
||||
|
||||
/** Open (or focus) the floating transcript window for a workflow agent. */
|
||||
async openUltracodeAgentWindow(agentId, runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!agentId) return;
|
||||
this._removeMinimizedUltracodeAgent(agentId); // an explicit open overrides a past minimize
|
||||
const existing = this.ultracodeAgentWindows.get(agentId);
|
||||
if (existing && existing.element) {
|
||||
// Already open — bring to front and refresh transcript.
|
||||
existing.element.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
this.updateConnectionLines();
|
||||
} else if (!this.createUltracodeAgentWindow(agentId, runId)) {
|
||||
return;
|
||||
}
|
||||
// Body shows a loading state until the fetch lands (re-fetch on focus too, so a
|
||||
// still-running agent's transcript grows as you re-click).
|
||||
const data = this._fetchWorkflowAgentTranscript ? await this._fetchWorkflowAgentTranscript(agentId) : null;
|
||||
this.renderUltracodeAgentWindowContent(agentId, data);
|
||||
},
|
||||
|
||||
/** Build and mount the floating agent-transcript window shell near its parent. */
|
||||
createUltracodeAgentWindow(agentId, runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (this.ultracodeAgentWindows.has(agentId)) return this.ultracodeAgentWindows.get(agentId).element;
|
||||
|
||||
const label = this._ultracodeAgentLabel(agentId, runId) || agentId;
|
||||
const win = document.createElement('div');
|
||||
win.className = 'ultracode-window ultracode-agent-window spawning';
|
||||
win.id = `ultracode-agent-window-${agentId}`;
|
||||
win.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
win.innerHTML = `
|
||||
<div class="ultracode-window-header">
|
||||
<div class="ultracode-window-title" title="${escapeHtml(label)} — transcript">
|
||||
<span class="icon">📄</span>
|
||||
<span class="uw-name">${escapeHtml(label)}</span>
|
||||
</div>
|
||||
<div class="ultracode-window-actions">
|
||||
<button class="uw-min" type="button" title="Minimize to tab">─</button>
|
||||
<button class="uw-close" type="button" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ultracode-window-body">
|
||||
<div class="subagent-empty">Loading transcript…</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Position: offset from the parent run window if it's open, else cascade.
|
||||
const parentWin = runId ? this.ultracodeWindows.get(runId) : null;
|
||||
if (parentWin && parentWin.element) {
|
||||
const r = parentWin.element.getBoundingClientRect();
|
||||
win.style.left = `${Math.max(8, Math.min(r.left + 40, window.innerWidth - 472))}px`;
|
||||
win.style.top = `${Math.max(8, Math.min(r.top + 40, window.innerHeight - 160))}px`;
|
||||
} else {
|
||||
const n = this.ultracodeAgentWindows.size;
|
||||
win.style.left = `${Math.min(140 + n * 28, Math.max(8, window.innerWidth - 472))}px`;
|
||||
win.style.top = `${110 + n * 28}px`;
|
||||
}
|
||||
|
||||
document.body.appendChild(win);
|
||||
requestAnimationFrame(() => win.classList.remove('spawning'));
|
||||
|
||||
const header = win.querySelector('.ultracode-window-header');
|
||||
const dragListeners = this.makeWindowDraggable(win, header);
|
||||
win.querySelector('.uw-min').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.minimizeUltracodeAgentWindowToTab(agentId);
|
||||
});
|
||||
win.querySelector('.uw-close').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.closeUltracodeAgentWindow(agentId);
|
||||
});
|
||||
|
||||
this.ultracodeAgentWindows.set(agentId, { element: win, runId, dragListeners });
|
||||
this.updateConnectionLines();
|
||||
return win;
|
||||
},
|
||||
|
||||
/** Resolve a human label for an agent from the run's fetched detail.agents[]. */
|
||||
_ultracodeAgentLabel(agentId, runId) {
|
||||
const detail = this.workflowRunDetails && runId ? this.workflowRunDetails.get(runId) : null;
|
||||
const agents = detail && Array.isArray(detail.agents) ? detail.agents : null;
|
||||
if (agents) {
|
||||
const found = agents.find((a) => a.agentId === agentId);
|
||||
if (found && found.label) return found.label;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/** Fill an agent window's body with the fetched transcript (or a friendly empty state). */
|
||||
renderUltracodeAgentWindowContent(agentId, data) {
|
||||
const info = this.ultracodeAgentWindows.get(agentId);
|
||||
if (!info || !info.element) return;
|
||||
const body = info.element.querySelector('.ultracode-window-body');
|
||||
if (!body) return;
|
||||
if (!data || !data.formatted || !data.entryCount) {
|
||||
body.innerHTML =
|
||||
'<div class="subagent-empty">No transcript available yet — the agent may be queued, aged out of tracking, or subagent tracking is disabled.</div>';
|
||||
return;
|
||||
}
|
||||
const text = escapeHtml(data.formatted.join('\n'));
|
||||
body.innerHTML = `<div class="uw-summary">${data.entryCount} entries</div><pre class="uw-transcript">${text}</pre>`;
|
||||
},
|
||||
|
||||
/** Close one floating agent-transcript window. */
|
||||
closeUltracodeAgentWindow(agentId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const info = this.ultracodeAgentWindows.get(agentId);
|
||||
if (!info) return;
|
||||
this._teardownUltracodeDrag(info.dragListeners);
|
||||
if (info.element) info.element.remove();
|
||||
this.ultracodeAgentWindows.delete(agentId);
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
/** Tear down every floating window (called on SSE reconnect; keeps user dismissals). */
|
||||
removeAllUltracodeWindows() {
|
||||
this._ensureUltracodeWindowState();
|
||||
const hadMinimized = this.minimizedUltracodeRuns.size > 0 || this.minimizedUltracodeAgents.size > 0;
|
||||
const had = this.ultracodeWindows.size > 0 || this.ultracodeAgentWindows.size > 0;
|
||||
for (const [, data] of this.ultracodeWindows) {
|
||||
this._teardownUltracodeDrag(data.dragListeners);
|
||||
if (data.element) data.element.remove();
|
||||
}
|
||||
this.ultracodeWindows.clear();
|
||||
for (const [, info] of this.ultracodeAgentWindows) {
|
||||
this._teardownUltracodeDrag(info.dragListeners);
|
||||
if (info.element) info.element.remove();
|
||||
}
|
||||
this.ultracodeAgentWindows.clear();
|
||||
for (const t of this.ultracodeWindowCloseTimers.values()) clearTimeout(t);
|
||||
this.ultracodeWindowCloseTimers.clear();
|
||||
this.minimizedUltracodeRuns.clear();
|
||||
this.minimizedUltracodeAgents.clear();
|
||||
// Redraw so the now-orphaned connector lines are cleared from the shared SVG.
|
||||
if (had) this.updateConnectionLines();
|
||||
// Drop any now-stale tab badges.
|
||||
if (hadMinimized) this.renderSessionTabs();
|
||||
},
|
||||
|
||||
/** When the feature is toggled on, pop windows for any currently-active runs. */
|
||||
syncAllUltracodeFloatingWindows() {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!this._ultracodeFloatingEnabled()) {
|
||||
this.removeAllUltracodeWindows();
|
||||
return;
|
||||
}
|
||||
if (!this.workflowRuns) return;
|
||||
for (const run of this.workflowRuns.values()) {
|
||||
this._syncUltracodeFloatingWindow(run, { fromSeed: true });
|
||||
}
|
||||
},
|
||||
|
||||
/** Refresh a floating window's header + body from the latest summary/detail. */
|
||||
renderUltracodeWindowContent(runId) {
|
||||
const data = this.ultracodeWindows.get(runId);
|
||||
if (!data) return;
|
||||
const summary = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
const detail = this.workflowRunDetails && this.workflowRunDetails.get(runId);
|
||||
// Summary is the freshest run-level info (every SSE tick); detail supplies agents[]
|
||||
// but is fetched less often. Merge so a completed summary isn't masked by stale detail.
|
||||
const run = summary && detail ? { ...detail, ...summary, agents: detail.agents } : detail || summary;
|
||||
if (!run) return;
|
||||
|
||||
const nameEl = data.element.querySelector('.uw-name');
|
||||
if (nameEl) nameEl.textContent = run.workflowName || run.summary || runId;
|
||||
|
||||
const statusEl = data.element.querySelector('.uw-status');
|
||||
if (statusEl) {
|
||||
const finished = !this._isWorkflowRunActive(run);
|
||||
const label = run.status ? String(run.status) : finished ? '—' : 'running';
|
||||
const clsKey = run.status ? run.status : finished ? '' : 'running';
|
||||
statusEl.textContent = label;
|
||||
statusEl.className = 'uw-status ultracode-status ' + this._workflowStatusClass(clsKey);
|
||||
}
|
||||
|
||||
const body = data.element.querySelector('.ultracode-window-body');
|
||||
if (body) body.innerHTML = this._ultracodeWindowBodyHtml(run);
|
||||
},
|
||||
|
||||
/** Compact body: a stats line + agent cards grouped by phase (reuses panel helpers). */
|
||||
_ultracodeWindowBodyHtml(run) {
|
||||
const phases = Array.isArray(run.phases) ? run.phases : [];
|
||||
const agents = Array.isArray(run.agents) ? run.agents : null;
|
||||
const agentCount = run.agentCount ?? (agents ? agents.length : 0);
|
||||
const head = `<div class="uw-summary">${this._fmtNum(run.totalTokens)} tok · ${run.totalToolCalls ?? 0} tools · ${agentCount} agents</div>`;
|
||||
|
||||
if (!agents) {
|
||||
// Summary-only (detail not fetched yet): show phase chips as a teaser.
|
||||
if (phases.length) {
|
||||
const chips = phases
|
||||
.map(
|
||||
(p) =>
|
||||
`<span class="ultracode-phase-chip" title="${escapeHtml(p.detail || '')}">${escapeHtml(p.title || '')}</span>`
|
||||
)
|
||||
.join('');
|
||||
return (
|
||||
head + `<div class="ultracode-phase-list">${chips}</div><div class="subagent-empty">Loading agents…</div>`
|
||||
);
|
||||
}
|
||||
return head + '<div class="subagent-empty">Loading agents…</div>';
|
||||
}
|
||||
if (!agents.length) return head + '<div class="subagent-empty">No agents yet</div>';
|
||||
|
||||
const groups = new Map();
|
||||
agents.forEach((a) => {
|
||||
const key = a.phaseIndex || 0;
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key).push(a);
|
||||
});
|
||||
const orderedKeys = Array.from(groups.keys()).sort((a, b) => a - b);
|
||||
const grid = orderedKeys
|
||||
.map((key) => {
|
||||
const group = groups.get(key);
|
||||
const title = (phases[key - 1] && phases[key - 1].title) || `Phase ${key}`;
|
||||
const tok = group.reduce((s, a) => s + (a.tokens || 0), 0);
|
||||
const tools = group.reduce((s, a) => s + (a.toolCalls || 0), 0);
|
||||
const header =
|
||||
`<div class="ultracode-phase-header"><span>${escapeHtml(title)}</span>` +
|
||||
`<span class="ultracode-phase-sub">${this._fmtNum(tok)} tok · ${tools} tools</span></div>`;
|
||||
return header + group.map((a) => this._workflowAgentCardHtml(a, run.runId)).join('');
|
||||
})
|
||||
.join('');
|
||||
return head + grid;
|
||||
},
|
||||
|
||||
/**
|
||||
* Append ultracode-window → parent-tab connector lines into the shared SVG.
|
||||
* Invoked at the tail of `_updateConnectionLinesImmediate` (subagent-windows.js),
|
||||
* so it shares that pass's batched read/write discipline. `rects` is the tab-rect
|
||||
* cache already populated for subagent lines — reuse it, fill any gaps.
|
||||
*/
|
||||
_appendUltracodeConnectionLines(svg, rects) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!svg || !this.ultracodeWindows.size) return;
|
||||
if (!rects) rects = new Map();
|
||||
|
||||
// PHASE 1: layout reads (resolve parents, batch getBoundingClientRect).
|
||||
const winList = [];
|
||||
for (const [runId, data] of this.ultracodeWindows) {
|
||||
if (!data.element) continue;
|
||||
if (!data.parentSessionId) {
|
||||
const summary = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
if (summary) data.parentSessionId = this._resolveUltracodeParentSession(summary);
|
||||
}
|
||||
const parentSessionId = data.parentSessionId;
|
||||
if (!parentSessionId) continue;
|
||||
const tabKey = 'tab:' + parentSessionId;
|
||||
if (!rects.has(tabKey)) {
|
||||
const tab = document.querySelector(`.session-tab[data-id="${parentSessionId}"]`);
|
||||
if (tab) rects.set(tabKey, tab.getBoundingClientRect());
|
||||
}
|
||||
winList.push({ runId, parentSessionId, winRect: data.element.getBoundingClientRect() });
|
||||
}
|
||||
|
||||
// PHASE 2: writes (curve from tab bottom-center to window top-center).
|
||||
for (const { runId, parentSessionId, winRect } of winList) {
|
||||
const tabRect = rects.get('tab:' + parentSessionId);
|
||||
if (!tabRect) continue;
|
||||
const x1 = tabRect.left + tabRect.width / 2;
|
||||
const y1 = tabRect.bottom;
|
||||
const x2 = winRect.left + winRect.width / 2;
|
||||
const y2 = winRect.top;
|
||||
const midY = (y1 + y2) / 2;
|
||||
const path = `M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}`;
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line ultracode-connection');
|
||||
line.setAttribute('data-run-id', runId);
|
||||
line.setAttribute('data-parent-tab', parentSessionId);
|
||||
svg.appendChild(line);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Append agent-window → parent connector lines into the shared SVG. Parent is the
|
||||
* agent's run floating window when open, else the run's session tab. Called right
|
||||
* after `_appendUltracodeConnectionLines` so it shares the same batched pass + the
|
||||
* tab-rect cache.
|
||||
*/
|
||||
_appendUltracodeAgentConnectionLines(svg, rects) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!svg || !this.ultracodeAgentWindows.size) return;
|
||||
if (!rects) rects = new Map();
|
||||
|
||||
for (const [agentId, info] of this.ultracodeAgentWindows) {
|
||||
if (!info.element) continue;
|
||||
const winRect = info.element.getBoundingClientRect();
|
||||
// Anchor: parent run window bottom-center if open, else the run's tab.
|
||||
let px, py;
|
||||
const runWin = info.runId ? this.ultracodeWindows.get(info.runId) : null;
|
||||
if (runWin && runWin.element) {
|
||||
const pr = runWin.element.getBoundingClientRect();
|
||||
px = pr.left + pr.width / 2;
|
||||
py = pr.bottom;
|
||||
} else {
|
||||
const summary = info.runId && this.workflowRuns ? this.workflowRuns.get(info.runId) : null;
|
||||
const parentSessionId = summary ? this._resolveUltracodeParentSession(summary) : null;
|
||||
if (!parentSessionId) continue;
|
||||
const tabKey = 'tab:' + parentSessionId;
|
||||
if (!rects.has(tabKey)) {
|
||||
const tab = document.querySelector(`.session-tab[data-id="${parentSessionId}"]`);
|
||||
if (tab) rects.set(tabKey, tab.getBoundingClientRect());
|
||||
}
|
||||
const tabRect = rects.get(tabKey);
|
||||
if (!tabRect) continue;
|
||||
px = tabRect.left + tabRect.width / 2;
|
||||
py = tabRect.bottom;
|
||||
}
|
||||
const x2 = winRect.left + winRect.width / 2;
|
||||
const y2 = winRect.top;
|
||||
const midY = (py + y2) / 2;
|
||||
const path = `M ${px} ${py} C ${px} ${midY}, ${x2} ${midY}, ${x2} ${y2}`;
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line ultracode-connection ultracode-agent-connection');
|
||||
line.setAttribute('data-agent-id', agentId);
|
||||
svg.appendChild(line);
|
||||
}
|
||||
},
|
||||
});
|
||||
+3
File diff suppressed because one or more lines are too long
+652
-46
@@ -3,16 +3,370 @@
|
||||
* Provides directory listing, file content preview, raw file serving, and tail streaming.
|
||||
*/
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { FastifyInstance, type FastifyReply } from 'fastify';
|
||||
import { basename as pathBasename, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { createReadStream, realpathSync, type ReadStream } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { ApiErrorCode, createErrorResponse, getErrorMessage } from '../../types.js';
|
||||
import { fileStreamManager } from '../../file-stream-manager.js';
|
||||
import {
|
||||
AttachmentRegistrationError,
|
||||
attachmentRecordToEvent,
|
||||
attachmentRegistry,
|
||||
buildFileThumbnailRoute,
|
||||
isSupportedAttachmentExtension,
|
||||
registerExternalAttachment,
|
||||
type AttachmentRecord,
|
||||
} from '../../attachment-registry.js';
|
||||
import { generateFirstPageThumbnail } from '../../document-thumbnailer.js';
|
||||
import { getOfficePreviewPdfPath, getPreviewPdfDownloadName } from '../../document-preview-cache.js';
|
||||
import { sanitizeAttachmentHistoryItem } from '../../session-attachment-history.js';
|
||||
import { isBlockedAttachmentPath, loadAttachmentGuardConfig } from '../../config/attachment-guard.js';
|
||||
import { findSessionOrFail, validateSessionFilePath } from '../route-helpers.js';
|
||||
import type { SessionPort } from '../ports/index.js';
|
||||
import type { SessionAttachmentHistoryItem, SessionState } from '../../types/session.js';
|
||||
import { isSensitivePath } from '../sensitive-path.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import type { ConfigPort, EventPort, SessionPort } from '../ports/index.js';
|
||||
|
||||
export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort): void {
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
webp: 'image/webp',
|
||||
ico: 'image/x-icon',
|
||||
bmp: 'image/bmp',
|
||||
pdf: 'application/pdf',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
json: 'application/json',
|
||||
md: 'text/markdown',
|
||||
txt: 'text/plain',
|
||||
};
|
||||
|
||||
function sanitizeDownloadName(fileName: string): string {
|
||||
return fileName.replace(/["\\\r\n]/g, '_');
|
||||
}
|
||||
|
||||
function sendRawStream(reply: FastifyReply, content: ReadStream): void {
|
||||
const headers = reply.getHeaders();
|
||||
reply.hijack();
|
||||
|
||||
for (const [name, value] of Object.entries(headers)) {
|
||||
if (value !== undefined) {
|
||||
reply.raw.setHeader(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
content.on('error', (err) => {
|
||||
if (reply.raw.headersSent) {
|
||||
reply.raw.destroy(err);
|
||||
return;
|
||||
}
|
||||
|
||||
reply.raw.statusCode = 500;
|
||||
reply.raw.end('Failed to read file');
|
||||
});
|
||||
content.pipe(reply.raw);
|
||||
}
|
||||
|
||||
async function serveRawFile(
|
||||
reply: FastifyReply,
|
||||
resolvedPath: string,
|
||||
fileName: string,
|
||||
extension: string,
|
||||
download?: boolean
|
||||
): Promise<void> {
|
||||
const stat = await fs.stat(resolvedPath);
|
||||
const MAX_RAW_ATTACHMENT_SIZE = 50 * 1024 * 1024; // 50MB, matching file-raw / download
|
||||
if (stat.size > MAX_RAW_ATTACHMENT_SIZE) {
|
||||
reply
|
||||
.code(413)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
`File too large (${Math.round(stat.size / 1024 / 1024)}MB > ${MAX_RAW_ATTACHMENT_SIZE / 1024 / 1024}MB limit)`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
const content = createReadStream(resolvedPath);
|
||||
const safeName = sanitizeDownloadName(fileName);
|
||||
if (download || extension === 'svg') {
|
||||
reply.header(
|
||||
'Content-Type',
|
||||
extension === 'svg' ? 'application/octet-stream' : MIME_TYPES[extension] || 'application/octet-stream'
|
||||
);
|
||||
reply.header('Content-Disposition', `attachment; filename="${safeName}"`);
|
||||
reply.header('Content-Length', stat.size);
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
sendRawStream(reply, content);
|
||||
return;
|
||||
}
|
||||
|
||||
reply.header('Content-Type', MIME_TYPES[extension] || 'application/octet-stream');
|
||||
reply.header('Content-Disposition', `inline; filename="${safeName}"`);
|
||||
reply.header('Content-Length', stat.size);
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
sendRawStream(reply, content);
|
||||
}
|
||||
|
||||
function getAttachmentOr404(
|
||||
reply: FastifyReply,
|
||||
sessionId: string,
|
||||
attachmentId: string
|
||||
): AttachmentRecord | undefined {
|
||||
const record = attachmentRegistry.get(sessionId, attachmentId);
|
||||
if (!record) {
|
||||
reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, 'Attachment not found'));
|
||||
return undefined;
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* COD-53 defense-in-depth: refuse to stream a record whose underlying path is
|
||||
* blocked by the active attachment-guard policy, even though registration
|
||||
* already blocks them. Guards against records that predate the guard or were
|
||||
* crafted to point at a sensitive file. Resolves symlinks before the check so a
|
||||
* record pointing at a symlink that now resolves to a sensitive target is also
|
||||
* caught; if the path can't be resolved (deleted/unreadable) the check still
|
||||
* runs on the stored path. When workspace confinement is enabled it additionally
|
||||
* rejects any record outside the session workspace. Returns true (and sends a
|
||||
* 403) when blocked.
|
||||
*/
|
||||
async function resolveServableAttachmentPath(
|
||||
reply: FastifyReply,
|
||||
record: AttachmentRecord,
|
||||
sessionWorkingDir?: string
|
||||
): Promise<string | null> {
|
||||
let pathToCheck = record.filePath;
|
||||
let resolved = false;
|
||||
try {
|
||||
pathToCheck = realpathSync(record.filePath);
|
||||
resolved = true;
|
||||
} catch {
|
||||
// Fall back to the stored (already realpath-resolved at registration) path.
|
||||
}
|
||||
|
||||
const guard = await loadAttachmentGuardConfig();
|
||||
|
||||
const blocked =
|
||||
isBlockedAttachmentPath(pathToCheck, guard.blockedTrees) ||
|
||||
isBlockedAttachmentPath(record.filePath, guard.blockedTrees) ||
|
||||
(guard.confineToWorkspace && (!sessionWorkingDir || !validateSessionFilePath(sessionWorkingDir, pathToCheck)));
|
||||
|
||||
if (blocked) {
|
||||
reply.code(403).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Access to this file is blocked'));
|
||||
return null;
|
||||
}
|
||||
// Serve the freshly-resolved path, not the stored one: if a path component
|
||||
// became a symlink after registration, the guard checked the resolved target
|
||||
// but streaming record.filePath would follow the symlink to a swapped file.
|
||||
return resolved ? pathToCheck : record.filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a DOCX/PPTX to a single-PDF preview (LibreOffice when available) and
|
||||
* stream it inline. PDF/PNG and text formats don't need conversion — callers
|
||||
* redirect those to the raw route instead.
|
||||
*/
|
||||
async function serveConvertedPreview(
|
||||
reply: FastifyReply,
|
||||
resolvedPath: string,
|
||||
fileName: string,
|
||||
extension: string
|
||||
): Promise<void> {
|
||||
if (extension !== 'docx' && extension !== 'pptx') {
|
||||
reply
|
||||
.code(400)
|
||||
.send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Preview is not supported for this file type'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const previewPath = await getOfficePreviewPdfPath(resolvedPath, extension);
|
||||
if (!previewPath) {
|
||||
reply.code(500).send(createErrorResponse(ApiErrorCode.OPERATION_FAILED, 'Document preview conversion failed'));
|
||||
return;
|
||||
}
|
||||
|
||||
const content = await fs.readFile(previewPath);
|
||||
reply.header('Content-Type', 'application/pdf');
|
||||
reply.header('Content-Disposition', `inline; filename="${getPreviewPdfDownloadName(fileName, extension)}"`);
|
||||
reply.header('Cache-Control', 'no-cache');
|
||||
reply.header('Content-Length', content.length);
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
reply.send(content);
|
||||
} catch (err) {
|
||||
reply
|
||||
.code(500)
|
||||
.send(createErrorResponse(ApiErrorCode.OPERATION_FAILED, `Failed to generate preview: ${getErrorMessage(err)}`));
|
||||
}
|
||||
}
|
||||
|
||||
/** Generate and stream a first-page thumbnail (PNG) for a supported attachment. */
|
||||
async function serveThumbnail(reply: FastifyReply, resolvedPath: string, extension: string): Promise<void> {
|
||||
const thumbnail = await generateFirstPageThumbnail(resolvedPath, extension);
|
||||
if (!thumbnail) {
|
||||
reply.code(204).send();
|
||||
return;
|
||||
}
|
||||
|
||||
reply.header('Content-Type', thumbnail.contentType);
|
||||
reply.header('Cache-Control', 'no-cache');
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
reply.send(thumbnail.content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a session's working dir from the live session, falling back to the
|
||||
* persisted record so preview/thumbnail requests keep working for a session
|
||||
* that has since detached. Sends a 404 and returns undefined when unknown.
|
||||
*/
|
||||
function getKnownSessionWorkingDir(
|
||||
ctx: SessionPort & ConfigPort,
|
||||
sessionId: string,
|
||||
reply: FastifyReply
|
||||
): string | undefined {
|
||||
const liveSession = ctx.sessions.get(sessionId);
|
||||
if (liveSession) return liveSession.workingDir;
|
||||
|
||||
const stored = ctx.store.getSession(sessionId);
|
||||
if (stored) return stored.workingDir;
|
||||
|
||||
reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, `Session ${sessionId} not found`));
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Persisted sessions carry the private (externalPath-bearing) history under a
|
||||
// `__attachmentHistory` key so the list route can re-register external files.
|
||||
type StoredSessionWithPrivateAttachmentHistory = SessionState & {
|
||||
__attachmentHistory?: SessionAttachmentHistoryItem[];
|
||||
};
|
||||
|
||||
type AttachmentHistoryRouteItem = Omit<SessionAttachmentHistoryItem, 'externalPath'> & {
|
||||
missing: boolean;
|
||||
rawUrl?: string;
|
||||
url?: string;
|
||||
previewUrl?: string;
|
||||
thumbnailUrl?: string;
|
||||
downloadUrl?: string;
|
||||
attachmentId?: string;
|
||||
};
|
||||
|
||||
function appendDownloadFlag(url: string): string {
|
||||
return `${url}${url.includes('?') ? '&' : '?'}download=true`;
|
||||
}
|
||||
|
||||
function getSessionAttachmentHistory(
|
||||
ctx: SessionPort & ConfigPort,
|
||||
sessionId: string
|
||||
): { workingDir: string; history: SessionAttachmentHistoryItem[] } | undefined {
|
||||
const liveSession = ctx.sessions.get(sessionId);
|
||||
if (liveSession) {
|
||||
return {
|
||||
workingDir: liveSession.workingDir,
|
||||
history: liveSession.getAttachmentHistoryForPersist() ?? liveSession.attachmentHistory ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
const stored = ctx.store.getSession(sessionId) as StoredSessionWithPrivateAttachmentHistory | undefined;
|
||||
if (!stored) return undefined;
|
||||
|
||||
return {
|
||||
workingDir: stored.workingDir,
|
||||
history: stored.__attachmentHistory ?? stored.attachmentHistory ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
// History item for a file detected inside the workspace: re-stat for live
|
||||
// size/mtime and resolve preview/thumbnail/raw routes off the relative path.
|
||||
async function buildDetectedAttachmentRouteItem(
|
||||
sessionId: string,
|
||||
workingDir: string,
|
||||
item: SessionAttachmentHistoryItem
|
||||
): Promise<AttachmentHistoryRouteItem> {
|
||||
const safe = sanitizeAttachmentHistoryItem(item);
|
||||
if (!item.relativePath) {
|
||||
return { ...safe, missing: true };
|
||||
}
|
||||
|
||||
const validated = validateSessionFilePath(workingDir, item.relativePath);
|
||||
if (!validated) {
|
||||
return { ...safe, missing: true };
|
||||
}
|
||||
|
||||
let size = item.size;
|
||||
let mtimeMs = item.mtimeMs;
|
||||
try {
|
||||
const stat = await fs.stat(validated.resolvedPath);
|
||||
size = stat.size;
|
||||
mtimeMs = stat.mtimeMs ?? mtimeMs;
|
||||
} catch {
|
||||
return { ...safe, missing: true };
|
||||
}
|
||||
|
||||
const encodedPath = encodeURIComponent(item.relativePath);
|
||||
const rawUrl = `/api/sessions/${sessionId}/file-raw?path=${encodedPath}`;
|
||||
const previewUrl =
|
||||
item.extension === 'docx' || item.extension === 'pptx'
|
||||
? `/api/sessions/${sessionId}/file-preview?path=${encodedPath}`
|
||||
: rawUrl;
|
||||
const thumbnailUrl = isSupportedAttachmentExtension(item.extension)
|
||||
? buildFileThumbnailRoute(sessionId, item.relativePath)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
...safe,
|
||||
size,
|
||||
mtimeMs,
|
||||
missing: false,
|
||||
rawUrl,
|
||||
url: rawUrl,
|
||||
previewUrl,
|
||||
thumbnailUrl,
|
||||
downloadUrl: appendDownloadFlag(rawUrl),
|
||||
};
|
||||
}
|
||||
|
||||
// History item for an explicitly published external file: re-register it to mint
|
||||
// a fresh id + by-id routes (the guard runs again), or mark it missing.
|
||||
async function buildExternalAttachmentRouteItem(
|
||||
sessionId: string,
|
||||
item: SessionAttachmentHistoryItem,
|
||||
sessionWorkingDir?: string
|
||||
): Promise<AttachmentHistoryRouteItem> {
|
||||
const safe = sanitizeAttachmentHistoryItem(item);
|
||||
if (!item.externalPath) {
|
||||
return { ...safe, missing: true };
|
||||
}
|
||||
|
||||
try {
|
||||
const event = await registerExternalAttachment(sessionId, item.externalPath, { sessionWorkingDir });
|
||||
return {
|
||||
...safe,
|
||||
fileName: event.fileName,
|
||||
extension: event.extension,
|
||||
attachmentType: event.attachmentType,
|
||||
size: event.size,
|
||||
missing: false,
|
||||
attachmentId: event.attachmentId,
|
||||
rawUrl: event.rawUrl,
|
||||
url: event.rawUrl,
|
||||
previewUrl: event.previewUrl,
|
||||
thumbnailUrl: event.thumbnailUrl,
|
||||
downloadUrl: appendDownloadFlag(event.rawUrl),
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof AttachmentRegistrationError) {
|
||||
return { ...safe, missing: true };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & EventPort & ConfigPort): void {
|
||||
// File tree listing
|
||||
app.get('/api/sessions/:id/files', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
@@ -157,49 +511,73 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort): void
|
||||
try {
|
||||
const stat = await fs.stat(resolvedPath);
|
||||
|
||||
// Check if it's a binary/media file
|
||||
// Classify by extension. Known media types render with a dedicated player;
|
||||
// other known-binary types are flagged so the client offers a download
|
||||
// affordance instead of trying to decode the bytes as text. Matches the
|
||||
// breadth of formats the attachments viewer renders (image/audio/video/pdf)
|
||||
// so the file viewer can open the same files.
|
||||
const ext = filePath.split('.').pop()?.toLowerCase() || '';
|
||||
const binaryExts = new Set([
|
||||
'png',
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'gif',
|
||||
'webp',
|
||||
'ico',
|
||||
'svg',
|
||||
'bmp',
|
||||
'mp4',
|
||||
'webm',
|
||||
'mov',
|
||||
'avi',
|
||||
'mp3',
|
||||
'wav',
|
||||
'ogg',
|
||||
const imageExts = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico']);
|
||||
const videoExts = new Set(['mp4', 'webm', 'mov', 'm4v', 'ogv']);
|
||||
const audioExts = new Set(['mp3', 'wav', 'ogg', 'oga', 'm4a', 'aac', 'flac', 'opus']);
|
||||
const otherBinaryExts = new Set([
|
||||
'pdf',
|
||||
'zip',
|
||||
'tar',
|
||||
'gz',
|
||||
'bz2',
|
||||
'xz',
|
||||
'7z',
|
||||
'rar',
|
||||
'exe',
|
||||
'dll',
|
||||
'so',
|
||||
'dylib',
|
||||
'bin',
|
||||
'wasm',
|
||||
'class',
|
||||
'o',
|
||||
'a',
|
||||
'woff',
|
||||
'woff2',
|
||||
'ttf',
|
||||
'eot',
|
||||
'otf',
|
||||
'xlsx',
|
||||
'xls',
|
||||
'doc',
|
||||
'docx',
|
||||
'ppt',
|
||||
'pptx',
|
||||
'odt',
|
||||
'ods',
|
||||
'odp',
|
||||
'avi',
|
||||
'mkv',
|
||||
'wmv',
|
||||
'flv',
|
||||
]);
|
||||
const imageExts = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico']);
|
||||
const videoExts = new Set(['mp4', 'webm', 'mov', 'avi']);
|
||||
|
||||
if (raw === 'true' || binaryExts.has(ext)) {
|
||||
// Return metadata for binary files
|
||||
const mediaType = imageExts.has(ext)
|
||||
? 'image'
|
||||
: videoExts.has(ext)
|
||||
? 'video'
|
||||
: audioExts.has(ext)
|
||||
? 'audio'
|
||||
: null;
|
||||
|
||||
const fileRawUrl = `/api/sessions/${id}/file-raw?path=${encodeURIComponent(filePath)}`;
|
||||
|
||||
if (raw === 'true' || mediaType || otherBinaryExts.has(ext)) {
|
||||
// Return metadata for media/binary files (no text body)
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
path: filePath,
|
||||
size: stat.size,
|
||||
type: imageExts.has(ext) ? 'image' : videoExts.has(ext) ? 'video' : 'binary',
|
||||
type: mediaType ?? 'binary',
|
||||
extension: ext,
|
||||
url: `/api/sessions/${id}/file-raw?path=${encodeURIComponent(filePath)}`,
|
||||
url: fileRawUrl,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -213,10 +591,39 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort): void
|
||||
);
|
||||
}
|
||||
|
||||
// Read as raw bytes so we can sniff for binary content before decoding. An
|
||||
// unrecognized extension (none at all, or a format not listed above) that
|
||||
// is actually binary would otherwise be dumped to the viewer as UTF-8
|
||||
// mojibake; a NUL byte in the first 8KB is a reliable binary signal that
|
||||
// (unlike a static extension list) catches arbitrary binary formats.
|
||||
const fileBuffer = await fs.readFile(resolvedPath);
|
||||
const buf = Buffer.isBuffer(fileBuffer) ? fileBuffer : Buffer.from(String(fileBuffer));
|
||||
const sniffLength = Math.min(buf.length, 8192);
|
||||
let looksBinary = false;
|
||||
for (let i = 0; i < sniffLength; i++) {
|
||||
if (buf[i] === 0) {
|
||||
looksBinary = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (looksBinary) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
path: filePath,
|
||||
size: stat.size,
|
||||
type: 'binary',
|
||||
extension: ext,
|
||||
url: fileRawUrl,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Read text file with line limit (bounded to prevent DoS)
|
||||
const MAX_LINES_LIMIT = 10000;
|
||||
const maxLines = Math.min(parseInt(lines || '500', 10) || 500, MAX_LINES_LIMIT);
|
||||
const content = await fs.readFile(resolvedPath, 'utf-8');
|
||||
const content = buf.toString('utf-8');
|
||||
const allLines = content.split('\n');
|
||||
const truncatedContent = allLines.length > maxLines;
|
||||
const displayContent = truncatedContent ? allLines.slice(0, maxLines).join('\n') : content;
|
||||
@@ -284,9 +691,16 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort): void
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
mov: 'video/quicktime',
|
||||
m4v: 'video/mp4',
|
||||
ogv: 'video/ogg',
|
||||
mp3: 'audio/mpeg',
|
||||
wav: 'audio/wav',
|
||||
ogg: 'audio/ogg',
|
||||
oga: 'audio/ogg',
|
||||
opus: 'audio/ogg',
|
||||
m4a: 'audio/mp4',
|
||||
aac: 'audio/aac',
|
||||
flac: 'audio/flac',
|
||||
pdf: 'application/pdf',
|
||||
json: 'application/json',
|
||||
};
|
||||
@@ -315,6 +729,214 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort): void
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Live external attachments =====
|
||||
// Register an explicit, live external file (absolute host path) as an
|
||||
// attachment with a stable id so browser requests never carry arbitrary
|
||||
// paths. Registration enforces the COD-53 attachment-guard policy. Serving is
|
||||
// by id via the /raw route below; document previews/thumbnails and the
|
||||
// attachment-history list are layered on separately.
|
||||
app.post('/api/sessions/:id/attachments', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
const body = (req.body || {}) as { path?: string };
|
||||
|
||||
if (!body.path || typeof body.path !== 'string') {
|
||||
reply.code(400).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Missing attachment path'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const event = await registerExternalAttachment(id, body.path, { sessionWorkingDir: session.workingDir });
|
||||
ctx.broadcast(SseEvent.AttachmentDetected, event);
|
||||
return { success: true, data: event };
|
||||
} catch (err) {
|
||||
if (err instanceof AttachmentRegistrationError) {
|
||||
reply.code(err.statusCode).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, err.message));
|
||||
return;
|
||||
}
|
||||
return reply
|
||||
.code(500)
|
||||
.send(
|
||||
createErrorResponse(ApiErrorCode.OPERATION_FAILED, `Failed to register attachment: ${getErrorMessage(err)}`)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// List a session's attachment history (live session or persisted), resolving
|
||||
// each entry to current metadata + routes. External entries are re-registered.
|
||||
app.get('/api/sessions/:id/attachments', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const sessionHistory = getSessionAttachmentHistory(ctx, id);
|
||||
if (!sessionHistory) {
|
||||
reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, `Session ${id} not found`));
|
||||
return;
|
||||
}
|
||||
|
||||
const items = await Promise.all(
|
||||
sessionHistory.history.map((item) =>
|
||||
(item.source === 'external'
|
||||
? buildExternalAttachmentRouteItem(id, item, sessionHistory.workingDir)
|
||||
: buildDetectedAttachmentRouteItem(id, sessionHistory.workingDir, item)
|
||||
).catch(() => ({ ...sanitizeAttachmentHistoryItem(item), missing: true }))
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
items,
|
||||
count: items.length,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Metadata poll for a single registered attachment (re-stats for live
|
||||
// size/mtime as the underlying file is rewritten).
|
||||
app.get('/api/sessions/:id/attachments/:attachmentId', async (req, reply) => {
|
||||
const { id, attachmentId } = req.params as { id: string; attachmentId: string };
|
||||
const workingDir = getKnownSessionWorkingDir(ctx, id, reply);
|
||||
if (!workingDir) return;
|
||||
const record = getAttachmentOr404(reply, id, attachmentId);
|
||||
if (!record) return;
|
||||
if (!(await resolveServableAttachmentPath(reply, record, workingDir))) return;
|
||||
const event = attachmentRecordToEvent(record);
|
||||
let size = record.size;
|
||||
let mtimeMs = record.mtimeMs;
|
||||
try {
|
||||
const stat = await fs.stat(record.filePath);
|
||||
size = stat.size;
|
||||
mtimeMs = stat.mtimeMs ?? mtimeMs;
|
||||
} catch {
|
||||
// File temporarily unavailable mid-write — keep cached values.
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
path: record.fileName,
|
||||
size,
|
||||
mtimeMs,
|
||||
type: record.attachmentType,
|
||||
extension: record.extension,
|
||||
url: event.rawUrl,
|
||||
previewUrl: event.previewUrl,
|
||||
thumbnailUrl: event.thumbnailUrl,
|
||||
attachmentId: record.attachmentId,
|
||||
fileName: record.fileName,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Serve the raw bytes of a registered attachment by id. Re-checks the
|
||||
// attachment-guard policy on every request (defense-in-depth) before streaming.
|
||||
app.get('/api/sessions/:id/attachments/:attachmentId/raw', async (req, reply) => {
|
||||
const { id, attachmentId } = req.params as { id: string; attachmentId: string };
|
||||
const { download } = req.query as { download?: string };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
const record = getAttachmentOr404(reply, id, attachmentId);
|
||||
if (!record) return;
|
||||
const servePath = await resolveServableAttachmentPath(reply, record, session.workingDir);
|
||||
if (!servePath) return;
|
||||
|
||||
try {
|
||||
await serveRawFile(reply, servePath, record.fileName, record.extension, download === 'true');
|
||||
} catch (err) {
|
||||
reply
|
||||
.code(500)
|
||||
.send(createErrorResponse(ApiErrorCode.OPERATION_FAILED, `Failed to read file: ${getErrorMessage(err)}`));
|
||||
}
|
||||
});
|
||||
|
||||
// Serve a converted PDF preview of a registered attachment by id. Office docs
|
||||
// convert server-side; PDF/PNG/text redirect to the raw route.
|
||||
app.get('/api/sessions/:id/attachments/:attachmentId/preview', async (req, reply) => {
|
||||
const { id, attachmentId } = req.params as { id: string; attachmentId: string };
|
||||
const workingDir = getKnownSessionWorkingDir(ctx, id, reply);
|
||||
if (!workingDir) return;
|
||||
const record = getAttachmentOr404(reply, id, attachmentId);
|
||||
if (!record) return;
|
||||
const servePath = await resolveServableAttachmentPath(reply, record, workingDir);
|
||||
if (!servePath) return;
|
||||
|
||||
// Only Office formats need server-side conversion; PDF/PNG and text formats
|
||||
// (md/txt) preview directly from their raw bytes.
|
||||
if (record.extension !== 'docx' && record.extension !== 'pptx') {
|
||||
reply.redirect(`/api/sessions/${id}/attachments/${encodeURIComponent(attachmentId)}/raw`);
|
||||
return;
|
||||
}
|
||||
|
||||
await serveConvertedPreview(reply, servePath, record.fileName, record.extension);
|
||||
});
|
||||
|
||||
// Serve a first-page thumbnail of a registered attachment by id.
|
||||
app.get('/api/sessions/:id/attachments/:attachmentId/thumbnail', async (req, reply) => {
|
||||
const { id, attachmentId } = req.params as { id: string; attachmentId: string };
|
||||
const workingDir = getKnownSessionWorkingDir(ctx, id, reply);
|
||||
if (!workingDir) return;
|
||||
const record = getAttachmentOr404(reply, id, attachmentId);
|
||||
if (!record) return;
|
||||
const servePath = await resolveServableAttachmentPath(reply, record, workingDir);
|
||||
if (!servePath) return;
|
||||
await serveThumbnail(reply, servePath, record.extension);
|
||||
});
|
||||
|
||||
// Serve converted document previews for a workspace-relative path. DOCX/PPTX
|
||||
// are converted to PDF via LibreOffice; PDF/PNG/text preview through file-raw.
|
||||
app.get('/api/sessions/:id/file-preview', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { path: filePath } = req.query as { path?: string };
|
||||
const workingDir = getKnownSessionWorkingDir(ctx, id, reply);
|
||||
if (!workingDir) return;
|
||||
|
||||
if (!filePath) {
|
||||
reply.code(400).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Missing path parameter'));
|
||||
return;
|
||||
}
|
||||
|
||||
const validated = validateSessionFilePath(workingDir, filePath);
|
||||
if (!validated) {
|
||||
reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, 'File not found'));
|
||||
return;
|
||||
}
|
||||
const { resolvedPath } = validated;
|
||||
const ext = filePath.split('.').pop()?.toLowerCase() || '';
|
||||
|
||||
if (ext !== 'docx' && ext !== 'pptx') {
|
||||
reply.redirect(`/api/sessions/${id}/file-raw?path=${encodeURIComponent(filePath)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
await serveConvertedPreview(reply, resolvedPath, filePath, ext);
|
||||
});
|
||||
|
||||
// Serve a first-page thumbnail for a workspace-relative path.
|
||||
app.get('/api/sessions/:id/file-thumbnail', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { path: filePath } = req.query as { path?: string };
|
||||
const workingDir = getKnownSessionWorkingDir(ctx, id, reply);
|
||||
if (!workingDir) return;
|
||||
|
||||
if (!filePath) {
|
||||
reply.code(400).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Missing path parameter'));
|
||||
return;
|
||||
}
|
||||
|
||||
const validated = validateSessionFilePath(workingDir, filePath);
|
||||
if (!validated) {
|
||||
reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, 'File not found'));
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = filePath.split('.').pop()?.toLowerCase() || '';
|
||||
if (!isSupportedAttachmentExtension(ext)) {
|
||||
reply
|
||||
.code(400)
|
||||
.send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Thumbnail is not supported for this file type'));
|
||||
return;
|
||||
}
|
||||
|
||||
await serveThumbnail(reply, validated.resolvedPath, ext);
|
||||
});
|
||||
|
||||
// Stream file content via tail -f (SSE endpoint)
|
||||
app.get('/api/sessions/:id/tail-file', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
@@ -387,24 +1009,8 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort): void
|
||||
});
|
||||
// Session-scoped file download.
|
||||
// Uses the same realpath-based workspace boundary as file preview/raw routes;
|
||||
// the sensitive-path blocklist remains defense-in-depth, not the primary boundary.
|
||||
const SENSITIVE_PATTERNS: RegExp[] = [
|
||||
/^\/etc\/shadow$/,
|
||||
/^\/etc\/gshadow$/,
|
||||
/^\/etc\/master\.passwd$/,
|
||||
new RegExp(`^${homedir().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\/\\.ssh\\/`),
|
||||
/\/\.env$/,
|
||||
/\/\.env\./,
|
||||
/\/credentials(\.json|\.yml|\.yaml|\.xml)?$/i,
|
||||
/\/\.aws\/credentials$/,
|
||||
/\/\.gcloud\/credentials\.db$/,
|
||||
/\/\.docker\/config\.json$/,
|
||||
];
|
||||
|
||||
function isSensitivePath(absPath: string): boolean {
|
||||
return SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath));
|
||||
}
|
||||
|
||||
// the shared sensitive-path blocklist (../sensitive-path.js, also used by the
|
||||
// attachment guard) remains defense-in-depth, not the primary boundary.
|
||||
app.get('/api/download', async (req, reply) => {
|
||||
const { path: filePath, sessionId } = req.query as { path?: string; sessionId?: string };
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ export { registerFileRoutes } from './file-routes.js';
|
||||
export { registerScheduledRoutes } from './scheduled-routes.js';
|
||||
export { registerSystemRoutes } from './system-routes.js';
|
||||
export { registerHookEventRoutes } from './hook-event-routes.js';
|
||||
export { registerStatusTelemetryRoutes } from './status-telemetry-routes.js';
|
||||
export { registerCaseRoutes } from './case-routes.js';
|
||||
export { registerSessionRoutes } from './session-routes.js';
|
||||
export { registerRespawnRoutes } from './respawn-routes.js';
|
||||
|
||||
@@ -16,6 +16,7 @@ import { SseEvent } from '../sse-events.js';
|
||||
import { autoConfigureRalph, CASES_DIR, SETTINGS_PATH, findSessionOrFail, parseBody } from '../route-helpers.js';
|
||||
import { writeHooksConfig, stripCaseEnvKeys } from '../../hooks-config.js';
|
||||
import { generateClaudeMd } from '../../templates/claude-md.js';
|
||||
import { buildRalphLoopPrompt } from '../../prompts/index.js';
|
||||
import { getLifecycleLog } from '../../session-lifecycle-log.js';
|
||||
import type { SessionPort, EventPort, RespawnPort, ConfigPort, InfraPort } from '../ports/index.js';
|
||||
import { MAX_CONCURRENT_SESSIONS } from '../../config/map-limits.js';
|
||||
@@ -382,37 +383,12 @@ export function registerRalphRoutes(
|
||||
writeFileSync(fixPlanPath, planContent, 'utf-8');
|
||||
}
|
||||
|
||||
// Build full prompt
|
||||
const hasPlan = enabledItems.length > 0;
|
||||
let fullPrompt = taskDescription + '\n\n---\n\n';
|
||||
if (hasPlan) {
|
||||
fullPrompt += '## Task Plan\n\n';
|
||||
fullPrompt += 'A task plan has been written to `@fix_plan.md`. Use this to track progress:\n';
|
||||
fullPrompt += '- Reference the plan at the start of each iteration\n';
|
||||
fullPrompt += '- Update task checkboxes as you complete items\n';
|
||||
fullPrompt += '- Work through items in priority order (P0 > P1 > P2)\n\n';
|
||||
}
|
||||
fullPrompt += '## Iteration Protocol\n\n';
|
||||
fullPrompt += 'This is an autonomous loop. Files from previous iterations persist. On each iteration:\n';
|
||||
fullPrompt += '1. Check what work has already been done\n';
|
||||
fullPrompt += '2. Make incremental progress toward completion\n';
|
||||
fullPrompt += '3. Commit meaningful changes with descriptive messages\n\n';
|
||||
fullPrompt += '## Verification\n\n';
|
||||
fullPrompt += 'After each significant change:\n';
|
||||
fullPrompt += '- Run tests to verify (npm test, pytest, etc.)\n';
|
||||
fullPrompt += '- Check for type/lint errors if applicable\n';
|
||||
fullPrompt += '- If tests fail, read the error, fix it, and retry\n\n';
|
||||
fullPrompt += '## Completion Criteria\n\n';
|
||||
fullPrompt += `Output \`<promise>${completionPhrase}</promise>\` when ALL of the following are true:\n`;
|
||||
fullPrompt += '- All requirements from the task description are implemented\n';
|
||||
fullPrompt += '- All tests pass\n';
|
||||
fullPrompt += '- Changes are committed\n\n';
|
||||
fullPrompt += '## If Stuck\n\n';
|
||||
fullPrompt += 'If you encounter the same error for 3+ iterations:\n';
|
||||
fullPrompt += "1. Document what you've tried\n";
|
||||
fullPrompt += '2. Identify the specific blocker\n';
|
||||
fullPrompt += '3. Try an alternative approach\n';
|
||||
fullPrompt += '4. If truly blocked, output `<promise>BLOCKED</promise>` with an explanation\n';
|
||||
// Build full prompt (includes the RALPH_STATUS contract)
|
||||
const fullPrompt = buildRalphLoopPrompt({
|
||||
taskDescription,
|
||||
completionPhrase,
|
||||
hasPlan: enabledItems.length > 0,
|
||||
});
|
||||
|
||||
// Write prompt to file
|
||||
const promptPath = join(casePath, '@ralph_prompt.md');
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
type ApiResponse,
|
||||
type SessionColor,
|
||||
} from '../../types.js';
|
||||
import { Session } from '../../session.js';
|
||||
import { Session, isAltScreenStripMode } from '../../session.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import {
|
||||
CreateSessionSchema,
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
ResizeSchema,
|
||||
AutoClearSchema,
|
||||
AutoCompactSchema,
|
||||
AutoResumeSchema,
|
||||
ImageWatcherSchema,
|
||||
FlickerFilterSchema,
|
||||
QuickRunSchema,
|
||||
@@ -44,7 +45,13 @@ import {
|
||||
validatePathWithinBase,
|
||||
} from '../route-helpers.js';
|
||||
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
|
||||
import { writeHooksConfig, updateCaseModel, stripCaseEnvKeys } from '../../hooks-config.js';
|
||||
import {
|
||||
writeHooksConfig,
|
||||
updateCaseModel,
|
||||
stripCaseEnvKeys,
|
||||
applyStatusLineConfig,
|
||||
refreshStaleHookSecret,
|
||||
} from '../../hooks-config.js';
|
||||
import { generateClaudeMd } from '../../templates/claude-md.js';
|
||||
import { imageWatcher } from '../../image-watcher.js';
|
||||
import { getLifecycleLog } from '../../session-lifecycle-log.js';
|
||||
@@ -53,6 +60,7 @@ import { MAX_CONCURRENT_SESSIONS } from '../../config/map-limits.js';
|
||||
import { RunSummaryTracker } from '../../run-summary.js';
|
||||
|
||||
import { MAX_INPUT_LENGTH, MAX_SESSION_NAME_LENGTH } from '../../config/terminal-limits.js';
|
||||
import { MAX_PASTE_IMAGE_BYTES } from '../../config/buffer-limits.js';
|
||||
import { dataPath } from '../../config/instance.js';
|
||||
|
||||
// Path to linked-cases registry (same file used by case-routes resolveCasePath)
|
||||
@@ -65,6 +73,32 @@ const CLAUDE_BANNER_PATTERN = /\x1b\[1mClaud/;
|
||||
const CTRL_L_PATTERN = /\x0c/g;
|
||||
const LEADING_WHITESPACE_PATTERN = /^[\s\r\n]+/;
|
||||
|
||||
/**
|
||||
* Match xterm alternate-screen mode toggles + the standalone scrollback-erase.
|
||||
*
|
||||
* - DECSET/DECRST 47, 1047, 1049 = enter/exit alternate screen buffer
|
||||
* (1049 also saves cursor and clears the alt buffer).
|
||||
* - CSI 3 J = erase saved lines (scrollback).
|
||||
*
|
||||
* Codex AND Claude Code emit `\x1b[?1049h` and clear-scrollback sequences (the
|
||||
* latter intermittently, e.g. full-screen pickers/dialogs). xterm.js obeys them
|
||||
* by switching to the alt buffer (no native scrollback) and wiping saved lines,
|
||||
* so the user's conversation history disappears on every tab switch / pane
|
||||
* refresh (and scroll-up breaks live). Stripping these from the replayed byte
|
||||
* stream keeps everything in the main buffer with scrollback intact. Mirrors the
|
||||
* live-stream strip in Session._handleTerminalOutput (isAltScreenStripMode).
|
||||
*/
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ALT_SCREEN_TOGGLE_PATTERN = /\x1b\[\?(?:47|1047|1049)[hl]/g;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ERASE_SCROLLBACK_PATTERN = /\x1b\[3J/g;
|
||||
// Mouse-tracking enables (X10/button/any-event/UTF-8/SGR/alt-scroll) — once on,
|
||||
// xterm.js forwards wheel events to the app instead of scrolling the viewport.
|
||||
// Live streams are stripped at the source, but buffers persisted BEFORE that
|
||||
// strip existed can still carry them; strip on replay for parity.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const MOUSE_TRACKING_PATTERN = /\x1b\[\?(?:1000|1001|1002|1003|1005|1006|1007)[hl]/g;
|
||||
|
||||
/**
|
||||
* Strip redundant Ink spinner/status-bar redraw frames from the terminal buffer.
|
||||
* Ink (Claude Code's TUI) uses absolute cursor positioning (CSI n d = VPA) to animate
|
||||
@@ -271,6 +305,28 @@ export function registerSessionRoutes(
|
||||
await updateCaseModel(workingDir, body.modelOverride || null);
|
||||
}
|
||||
|
||||
// Plan-usage statusLine exporter (App Settings → Display → "Plan Usage
|
||||
// Limits"). Claude-only; runs for ANY working dir (linked cases / real repos,
|
||||
// where most sessions live), mirroring updateCaseModel above.
|
||||
//
|
||||
// ADD-ONLY: we never remove on create. Sessions in a repo share one
|
||||
// settings.local.json, so a single create-with-false (e.g. a client whose
|
||||
// synced setting hadn't loaded yet) must NOT yank the statusLine out from
|
||||
// under other live sessions in that repo — that breaks their footer + the
|
||||
// chip's data feed for everyone. The exporter is benign when the chip is off
|
||||
// (the footer just shows session status). isOurs-guarded so a user's own
|
||||
// statusLine is never touched.
|
||||
if ((body.mode ?? 'claude') === 'claude' && body.statusLineTelemetry === true) {
|
||||
await applyStatusLineConfig(workingDir, true);
|
||||
}
|
||||
|
||||
// COD-91 self-heal: refresh a pre-secret hooks block in an existing case so the now
|
||||
// unconditional hook-secret gate keeps accepting its hook events. No-op for fresh
|
||||
// cases (writeHooksConfig already wrote the secret) and for non-Codeman/absent hooks.
|
||||
if ((body.mode ?? 'claude') === 'claude') {
|
||||
await refreshStaleHookSecret(workingDir).catch(() => {});
|
||||
}
|
||||
|
||||
// Check OpenCode availability if requested
|
||||
if (body.mode === 'opencode') {
|
||||
const { isOpenCodeAvailable } = await import('../../utils/opencode-cli-resolver.js');
|
||||
@@ -607,7 +663,7 @@ export function registerSessionRoutes(
|
||||
|
||||
app.post('/api/sessions/:id/input', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { input, useMux } = parseBody(SessionInputWithLimitSchema, req.body);
|
||||
const { input, useMux, seq, clientId } = parseBody(SessionInputWithLimitSchema, req.body);
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
const inputStr = String(input);
|
||||
@@ -618,6 +674,13 @@ export function registerSessionRoutes(
|
||||
);
|
||||
}
|
||||
|
||||
// Reliable delivery (POST fallback when the WebSocket is down): a 2xx IS the
|
||||
// client's ACK, so a tagged duplicate redelivery must still return 200 but
|
||||
// skip the write. Untagged requests (curl/legacy) always apply.
|
||||
if (typeof clientId === 'string' && typeof seq === 'number' && !session.shouldApplyInput(clientId, seq)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Write input to PTY. Direct write is synchronous; writeViaMux
|
||||
// (tmux send-keys) is fire-and-forget to avoid blocking the HTTP response.
|
||||
if (useMux) {
|
||||
@@ -691,14 +754,10 @@ export function registerSessionRoutes(
|
||||
|
||||
app.post('/api/sessions/:id/resize', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { cols, rows, viewportType } = parseBody(ResizeSchema, req.body);
|
||||
const { cols, rows, viewportType, force } = parseBody(ResizeSchema, req.body);
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
if (viewportType) {
|
||||
session.resize(cols, rows, { viewportType });
|
||||
} else {
|
||||
session.resize(cols, rows);
|
||||
}
|
||||
session.resize(cols, rows, { viewportType, force });
|
||||
return {};
|
||||
});
|
||||
|
||||
@@ -906,7 +965,24 @@ export function registerSessionRoutes(
|
||||
const query = req.query as { tail?: string };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
const rawBuffer = session.terminalBuffer;
|
||||
// Prepend the live tmux pane buffer so tab-switch replay shows the current
|
||||
// on-screen frame, not just the accumulated byte history. This matters for
|
||||
// TUI modes (codex/opencode) that repaint only their latest frame: the
|
||||
// accumulated buffer alone replays as the idle banner. We clear the viewport
|
||||
// (`\x1b[H\x1b[2J`) between the history and the live pane so they don't
|
||||
// overlap. `captureActivePaneBuffer` is a no-op ('') under test mode and
|
||||
// returns null when unavailable, in which case we fall back to history.
|
||||
const muxName = session.muxName;
|
||||
const liveMuxBuffer =
|
||||
muxName && typeof ctx.mux.captureActivePaneBuffer === 'function'
|
||||
? ctx.mux.captureActivePaneBuffer(muxName)
|
||||
: null;
|
||||
const rawBuffer =
|
||||
liveMuxBuffer !== null && liveMuxBuffer.length > 0
|
||||
? session.terminalBufferLength > 0
|
||||
? `${session.terminalBuffer}\x1b[H\x1b[2J${liveMuxBuffer}`
|
||||
: liveMuxBuffer
|
||||
: session.terminalBuffer;
|
||||
const tailBytes = query.tail ? parseInt(query.tail, 10) : 0;
|
||||
const fullSize = rawBuffer.length;
|
||||
let truncated = false;
|
||||
@@ -916,7 +992,18 @@ export function registerSessionRoutes(
|
||||
// During long thinking phases, Ink rewrites the same rows thousands of times
|
||||
// (500KB+). Without stripping, tail mode returns only spinner frames and
|
||||
// the terminal appears empty when switching tabs.
|
||||
const strippedBuffer = stripInkRedrawBloat(rawBuffer);
|
||||
let strippedBuffer = stripInkRedrawBloat(rawBuffer);
|
||||
|
||||
// Strip alt-screen toggles and scrollback-erase from Codex/Claude byte
|
||||
// streams. xterm.js obeys them by switching to its scrollback-less alt
|
||||
// buffer and wiping saved lines, so conversation history disappears on tab
|
||||
// switch. Same gate as the live-stream strip in session.ts.
|
||||
if (isAltScreenStripMode(session.mode)) {
|
||||
strippedBuffer = strippedBuffer
|
||||
.replace(ALT_SCREEN_TOGGLE_PATTERN, '')
|
||||
.replace(ERASE_SCROLLBACK_PATTERN, '')
|
||||
.replace(MOUSE_TRACKING_PATTERN, '');
|
||||
}
|
||||
|
||||
if (tailBytes > 0 && strippedBuffer.length > tailBytes) {
|
||||
// Fast path: tail from the end, skip expensive banner search on full 2MB buffer.
|
||||
@@ -1003,6 +1090,27 @@ export function registerSessionRoutes(
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Auto-Resume (usage-limit pause) ==========
|
||||
|
||||
app.post('/api/sessions/:id/auto-resume', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const body = parseBody(AutoResumeSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
session.setAutoResume(body.enabled);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
autoResume: {
|
||||
enabled: session.autoResumeEnabled,
|
||||
resumeAt: session.autoResumeAt ?? undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Image Watcher ==========
|
||||
|
||||
app.post('/api/sessions/:id/image-watcher', async (req) => {
|
||||
@@ -1190,6 +1298,11 @@ export function registerSessionRoutes(
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `Failed to create case: ${getErrorMessage(err)}`);
|
||||
}
|
||||
} else if (mode !== 'opencode') {
|
||||
// COD-91 self-heal for an EXISTING case: refresh a pre-secret hooks block so the
|
||||
// now-unconditional hook-secret gate keeps accepting its hook events. No-op when
|
||||
// the hooks aren't ours or already carry the secret.
|
||||
await refreshStaleHookSecret(casePath).catch(() => {});
|
||||
}
|
||||
|
||||
// Strip stale disk entries for keys this request is actively setting (Claude only —
|
||||
@@ -1598,7 +1711,7 @@ export function registerSessionRoutes(
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
const ALLOWED_IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp']);
|
||||
// The 10MB size cap is enforced by @fastify/multipart (registered in server.ts).
|
||||
// The per-file size cap (MAX_PASTE_IMAGE_BYTES) is enforced by @fastify/multipart (registered in server.ts).
|
||||
|
||||
app.post('/api/sessions/:id/paste-image', async (req, reply) => {
|
||||
// CSRF defense: state-changing routes must come from same origin.
|
||||
@@ -1635,7 +1748,7 @@ export function registerSessionRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
|
||||
// Rate limit per (IP, sessionId): 30/min. Defends against disk-fill DoS
|
||||
// — even an authenticated attacker can otherwise loop 10MB POSTs.
|
||||
// — even an authenticated attacker can otherwise loop large image POSTs.
|
||||
if (!consumePasteToken(`${req.ip}:${id}`)) {
|
||||
reply.code(429);
|
||||
reply.header('Retry-After', '60');
|
||||
@@ -1649,8 +1762,9 @@ export function registerSessionRoutes(
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Expected multipart/form-data');
|
||||
}
|
||||
|
||||
// Read the single file part. @fastify/multipart enforces the 10MB size cap
|
||||
// and the 1-file/4-field count limits (server.ts), replacing a hand-rolled
|
||||
// Read the single file part. @fastify/multipart enforces the per-file size
|
||||
// cap (MAX_PASTE_IMAGE_BYTES) and the 1-file/4-field count limits (server.ts),
|
||||
// replacing a hand-rolled
|
||||
// boundary scanner with several bugs: literal boundary matches anywhere in
|
||||
// body, LF-only clients silently corrupted the last byte (hard-coded \r\n
|
||||
// offsets), no part-count cap.
|
||||
@@ -1674,7 +1788,8 @@ export function registerSessionRoutes(
|
||||
imageBytes = await part.toBuffer();
|
||||
} catch (err: unknown) {
|
||||
reply.code(413);
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, getErrorMessage(err) || 'File too large (max 10MB)');
|
||||
const maxMb = Math.round(MAX_PASTE_IMAGE_BYTES / (1024 * 1024));
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, getErrorMessage(err) || `File too large (max ${maxMb}MB)`);
|
||||
}
|
||||
if (imageBytes.length === 0) {
|
||||
reply.code(400);
|
||||
@@ -1738,9 +1853,22 @@ export function registerSessionRoutes(
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
|
||||
// Non-recursive mkdir: errors on EEXIST and does not follow symlinks for
|
||||
// the leaf. session.workingDir is guaranteed to exist (live session).
|
||||
await fs.mkdir(imageDir);
|
||||
// Non-recursive mkdir: does not follow symlinks for the leaf.
|
||||
// session.workingDir is guaranteed to exist (live session).
|
||||
try {
|
||||
await fs.mkdir(imageDir);
|
||||
} catch (mkErr: unknown) {
|
||||
// Concurrent uploads (a batch of photos) race to create .claude-images —
|
||||
// the losers get EEXIST. Treat an already-present REAL directory as
|
||||
// success, but re-verify it isn't a symlink a racing actor planted
|
||||
// (preserve the symlink-safety guarantee above).
|
||||
if ((mkErr as NodeJS.ErrnoException).code !== 'EEXIST') throw mkErr;
|
||||
const raceStat = await fs.lstat(imageDir);
|
||||
if (raceStat.isSymbolicLink() || !raceStat.isDirectory()) {
|
||||
reply.code(403);
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, '.claude-images is not a regular directory');
|
||||
}
|
||||
}
|
||||
}
|
||||
// Date.now() collides on same-ms uploads from two tabs (last-write wins
|
||||
// silently). Append 8 hex chars so concurrent pastes get distinct names.
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* @fileoverview Status-telemetry route.
|
||||
*
|
||||
* Receives Claude Code statusline payloads POSTed by the Codeman-managed
|
||||
* statusLine exporter (see `hooks-config.generateStatusLineCommand`) and
|
||||
* broadcasts the parsed plan-usage limits (5-hour + weekly) to SSE clients for
|
||||
* the header "Plan Usage Limits" chip. Auth-exempt like `/api/hook-event`
|
||||
* (localhost-only; hook-secret-gated while a tunnel runs — see middleware/auth).
|
||||
*
|
||||
* Returns a compact plain-text status string for the exporter to print as the
|
||||
* in-terminal footer (print-through), so injecting our statusLine doesn't leave
|
||||
* the terminal footer blank.
|
||||
*/
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { StatusTelemetrySchema } from '../schemas.js';
|
||||
import { parseBody } from '../route-helpers.js';
|
||||
import {
|
||||
parseStatusTelemetry,
|
||||
parseSessionStatus,
|
||||
formatSessionStatusText,
|
||||
telemetrySignature,
|
||||
type RawStatuslinePayload,
|
||||
} from '../../usage-telemetry.js';
|
||||
import { SessionStatusTelemetry } from '../sse-events.js';
|
||||
import { setLatestPlanUsage } from '../plan-usage-latest.js';
|
||||
import type { SessionPort, EventPort } from '../ports/index.js';
|
||||
|
||||
export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: SessionPort & EventPort): void {
|
||||
// Last broadcast telemetry signature per session — the statusline fires on
|
||||
// every assistant message, so we only rebroadcast when the value changes.
|
||||
const lastSig = new Map<string, string>();
|
||||
|
||||
app.post('/api/status-telemetry', async (req, reply) => {
|
||||
const { sessionId, data } = parseBody(StatusTelemetrySchema, req.body);
|
||||
|
||||
reply.type('text/plain; charset=utf-8');
|
||||
|
||||
// Unknown session — minimal footer, no broadcast.
|
||||
if (!ctx.sessions.has(sessionId)) {
|
||||
lastSig.delete(sessionId);
|
||||
return 'codeman';
|
||||
}
|
||||
|
||||
const payload = data as RawStatuslinePayload | undefined;
|
||||
|
||||
// Plan-usage limits (account-wide) → broadcast to the header chip, when
|
||||
// present and changed (the statusline fires on every assistant message).
|
||||
const telemetry = parseStatusTelemetry(payload);
|
||||
if (telemetry) {
|
||||
const sig = telemetrySignature(telemetry);
|
||||
if (lastSig.get(sessionId) !== sig) {
|
||||
lastSig.set(sessionId, sig);
|
||||
// Bound the map across long multi-session runs: prune dead sessions.
|
||||
if (lastSig.size > 256) {
|
||||
for (const id of [...lastSig.keys()]) {
|
||||
if (!ctx.sessions.has(id)) lastSig.delete(id);
|
||||
}
|
||||
}
|
||||
const payload = { sessionId, ...telemetry };
|
||||
setLatestPlanUsage(payload); // replayed in the SSE init snapshot for fresh loads
|
||||
ctx.broadcast(SessionStatusTelemetry, payload);
|
||||
}
|
||||
}
|
||||
|
||||
// In-terminal statusline footer → CURRENT SESSION status (model / tokens /
|
||||
// context %), NOT the plan limits. Available from the first render, even
|
||||
// before rate_limits appears.
|
||||
return formatSessionStatusText(parseSessionStatus(payload));
|
||||
});
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { execSync, spawn } from 'node:child_process';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { dataPath } from '../../config/instance.js';
|
||||
import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } from '../../types.js';
|
||||
import { isUnauthenticatedNetworkAcknowledged } from '../network-auth-policy.js';
|
||||
import {
|
||||
ConfigUpdateSchema,
|
||||
SettingsUpdateSchema,
|
||||
@@ -25,6 +26,8 @@ import {
|
||||
} from '../schemas.js';
|
||||
import { subagentWatcher } from '../../subagent-watcher.js';
|
||||
import { imageWatcher } from '../../image-watcher.js';
|
||||
import { workflowRunWatcher } from '../../workflow-run-watcher.js';
|
||||
import { applyStatusLineConfig } from '../../hooks-config.js';
|
||||
import { getLifecycleLog } from '../../session-lifecycle-log.js';
|
||||
import {
|
||||
findSessionOrFail,
|
||||
@@ -498,6 +501,40 @@ export function registerSystemRoutes(
|
||||
app.put('/api/settings', async (req) => {
|
||||
const settings = parseBody(SettingsUpdateSchema, req.body, 'Invalid settings') as Record<string, unknown>;
|
||||
|
||||
// COD-55: enabling the Cloudflare tunnel publishes the whole app (full terminal
|
||||
// control = effectively RCE) to a public *.trycloudflare.com URL. Because the
|
||||
// tunnel binds to loopback, server.ts's non-loopback bind guard never trips, and
|
||||
// with no CODEMAN_PASSWORD the auth middleware is inactive — so the tunnel URL is
|
||||
// unauthenticated. Refuse to start a tunnel unless auth is configured OR exposure
|
||||
// is acknowledged: either the CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK env var, or an
|
||||
// explicit per-request `acknowledgeUnauthTunnel:true` (the UI sends this after a
|
||||
// confirm dialog). This keeps curl/API/CLI callers protected by default while
|
||||
// letting an operator opt in from the browser without setting the env var.
|
||||
// Guard runs BEFORE persisting so a refused tunnelEnabled:true is not saved.
|
||||
if (settings.tunnelEnabled === true && !ctx.tunnelManager.isRunning()) {
|
||||
const acknowledged = isUnauthenticatedNetworkAcknowledged() || settings.acknowledgeUnauthTunnel === true;
|
||||
if (!acknowledged) {
|
||||
const msg =
|
||||
'Refusing to start the Cloudflare tunnel without authentication: it would publish ' +
|
||||
'full terminal control to a public URL with no password. Set CODEMAN_PASSWORD to ' +
|
||||
'require login, set CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1, or resend with ' +
|
||||
'acknowledgeUnauthTunnel:true to acknowledge an unauthenticated public tunnel.';
|
||||
throw Object.assign(new Error(msg), {
|
||||
statusCode: 403,
|
||||
body: createErrorResponse(ApiErrorCode.OPERATION_FAILED, msg),
|
||||
});
|
||||
}
|
||||
// Loud warning whenever a public tunnel is started with no password — whether
|
||||
// acknowledged via env var or the per-request UI confirmation.
|
||||
if (!process.env.CODEMAN_PASSWORD) {
|
||||
console.warn(
|
||||
'⚠️ [tunnel] Starting an UNAUTHENTICATED public Cloudflare tunnel — no CODEMAN_PASSWORD set. ' +
|
||||
'Anyone with the tunnel URL gets full terminal control (effectively RCE). ' +
|
||||
'Set CODEMAN_PASSWORD to require login.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const dir = dirname(SETTINGS_PATH);
|
||||
if (!existsSync(dir)) {
|
||||
@@ -509,12 +546,24 @@ export function registerSystemRoutes(
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const merged = { ...existing, ...settings };
|
||||
// statusLineTelemetry and acknowledgeUnauthTunnel are ACTION fields (not stored
|
||||
// settings) — strip them before persisting so settings.json stays clean.
|
||||
const { statusLineTelemetry, acknowledgeUnauthTunnel, ...settingsToStore } = settings;
|
||||
const merged = { ...existing, ...settingsToStore };
|
||||
await fs.writeFile(SETTINGS_PATH, JSON.stringify(merged, null, 2));
|
||||
|
||||
// Handle subagent tracking toggle dynamically
|
||||
toggleService((settings.subagentTrackingEnabled as boolean) ?? true, subagentWatcher, 'Subagent watcher');
|
||||
|
||||
// Handle ultracode/workflow run watcher toggle dynamically (default OFF).
|
||||
// Either the docked panel OR the floating windows keep the watcher running.
|
||||
toggleService(
|
||||
((settings.showUltracodeAgents as boolean) ?? false) ||
|
||||
((settings.ultracodeFloatingWindows as boolean) ?? false),
|
||||
workflowRunWatcher,
|
||||
'Workflow run watcher'
|
||||
);
|
||||
|
||||
// Handle image watcher toggle dynamically
|
||||
toggleService((settings.imageWatcherEnabled as boolean) ?? false, imageWatcher, 'Image watcher', () => {
|
||||
// Re-watch all active sessions that have image watcher enabled
|
||||
@@ -525,6 +574,22 @@ export function registerSystemRoutes(
|
||||
}
|
||||
});
|
||||
|
||||
// Plan-usage chip: its DISPLAY is per-device (client-side, see settings-ui.js).
|
||||
// Telemetry COLLECTION is server-side and enable-sticky — when a client turns
|
||||
// the chip ON it sends statusLineTelemetry:true and we (re)inject our exporter
|
||||
// into every ACTIVE Claude session's working dir so the live % starts flowing
|
||||
// immediately (no new session needed). We deliberately never auto-REMOVE here:
|
||||
// the exporter is benign/print-through and a per-repo settings.local.json is
|
||||
// shared by sibling sessions, so one device's "off" must not yank the exporter
|
||||
// another device's chip depends on. Each dir handled once.
|
||||
if (statusLineTelemetry === true) {
|
||||
const dirs = new Set<string>();
|
||||
for (const session of ctx.sessions.values()) {
|
||||
if (session.mode === 'claude' && session.workingDir) dirs.add(session.workingDir);
|
||||
}
|
||||
await Promise.all([...dirs].map((dir) => applyStatusLineConfig(dir, true).catch(() => {})));
|
||||
}
|
||||
|
||||
// Handle tunnel toggle dynamically
|
||||
if ('tunnelEnabled' in settings) {
|
||||
const tunnelEnabled = settings.tunnelEnabled as boolean;
|
||||
@@ -650,6 +715,27 @@ export function registerSystemRoutes(
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Workflow Run Monitoring (ultracode) ==========
|
||||
|
||||
// LEFT-pane list: lightweight run summaries (no agents[]).
|
||||
app.get('/api/workflows', async (req) => {
|
||||
const { minutes } = req.query as { minutes?: string };
|
||||
const runs = minutes
|
||||
? workflowRunWatcher.getRecentRunSummaries(parseInt(minutes, 10))
|
||||
: workflowRunWatcher.getAllRunSummaries();
|
||||
return { success: true, data: runs };
|
||||
});
|
||||
|
||||
// RIGHT-pane detail: full run incl. agents[] (tokens/toolCalls/state per agent).
|
||||
app.get('/api/workflows/:runId', async (req) => {
|
||||
const { runId } = req.params as { runId: string };
|
||||
const run = workflowRunWatcher.getRun(runId);
|
||||
if (!run) {
|
||||
return createErrorResponse(ApiErrorCode.NOT_FOUND, `Workflow run ${runId} not found`);
|
||||
}
|
||||
return { success: true, data: run };
|
||||
});
|
||||
|
||||
// ========== Subagent Monitoring ==========
|
||||
|
||||
app.get('/api/subagents', async (req) => {
|
||||
|
||||
@@ -21,9 +21,12 @@
|
||||
* {"t":"o","d":"..."} — terminal output
|
||||
* {"t":"c"} — clear terminal
|
||||
* {"t":"r"} — needs refresh (reload buffer)
|
||||
* {"t":"ia","seq":N} — input ACK (echoes the seq of an applied/deduped input frame)
|
||||
* Client -> Server:
|
||||
* {"t":"i","d":"..."} — input (keystroke or paste)
|
||||
* {"t":"z","c":N,"r":N} — resize terminal
|
||||
* {"t":"i","d":"...","seq":N,"cid":"..."} — input (keystroke or paste). seq+cid are
|
||||
* optional reliable-delivery tags: the server applies each
|
||||
* (cid,seq) at-most-once and ACKs with {"t":"ia","seq":N}.
|
||||
* {"t":"z","c":N,"r":N,"f":bool} — resize terminal (f=true forces SIGWINCH even if dims unchanged)
|
||||
*/
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
@@ -114,6 +117,7 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
// can ignore small-viewport resizes only while a desktop is actually
|
||||
// connected (see Session._desktopSizeClaims).
|
||||
const sizingToken = Symbol('ws-desktop-sizing');
|
||||
let holdsDesktopClaim = false;
|
||||
|
||||
// Attach message handler synchronously BEFORE any async work
|
||||
// (@fastify/websocket requirement to avoid dropped messages).
|
||||
@@ -122,7 +126,22 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
const msg = JSON.parse(String(raw));
|
||||
if (msg.t === 'i' && typeof msg.d === 'string') {
|
||||
if (msg.d.length > MAX_INPUT_LENGTH) return;
|
||||
session.write(msg.d);
|
||||
// Reliable delivery: when the frame carries a clientId + seq, apply it
|
||||
// exactly once (skip a duplicate redelivery) but ACK it regardless so
|
||||
// the client can drop it from its durable queue. Frames without seq
|
||||
// (legacy/other tools) are applied as-is — no behavior change.
|
||||
const cid = typeof msg.cid === 'string' ? msg.cid : null;
|
||||
const seq = Number.isInteger(msg.seq) ? (msg.seq as number) : null;
|
||||
const apply = cid && seq !== null ? session.shouldApplyInput(cid, seq) : true;
|
||||
if (apply) {
|
||||
// Typed input from a claim-holding desktop keeps the claim "hot"
|
||||
// and re-asserts the desktop layout after a mobile override.
|
||||
if (holdsDesktopClaim) session.noteDesktopActivity();
|
||||
session.write(msg.d);
|
||||
}
|
||||
if (seq !== null && socket.readyState === 1) {
|
||||
socket.send(`{"t":"ia","seq":${seq}}`);
|
||||
}
|
||||
} else if (
|
||||
msg.t === 'z' &&
|
||||
Number.isInteger(msg.c) &&
|
||||
@@ -135,16 +154,15 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
const viewportType = msg.v === 'mobile' || msg.v === 'tablet' || msg.v === 'desktop' ? msg.v : undefined;
|
||||
if (viewportType === 'desktop') {
|
||||
session.claimDesktopSizing(sizingToken);
|
||||
holdsDesktopClaim = true;
|
||||
} else if (viewportType) {
|
||||
// The connection's viewport can change (e.g. browser window
|
||||
// narrowed past the tablet breakpoint) — drop a stale claim.
|
||||
session.releaseDesktopSizing(sizingToken);
|
||||
holdsDesktopClaim = false;
|
||||
}
|
||||
if (viewportType) {
|
||||
session.resize(msg.c, msg.r, { viewportType });
|
||||
} else {
|
||||
session.resize(msg.c, msg.r);
|
||||
}
|
||||
const force = msg.f === true;
|
||||
session.resize(msg.c, msg.r, { viewportType, force });
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed messages
|
||||
|
||||
@@ -158,6 +158,8 @@ export const CreateSessionSchema = z.object({
|
||||
effort: effortLevelSchema,
|
||||
/** Model override to write to .claude/settings.local.json (e.g., "opus[1m]"). Empty string clears. */
|
||||
modelOverride: z.string().max(50).optional(),
|
||||
/** Inject the plan-usage statusLine exporter into the case (App Settings → Display → "Plan Usage Limits"). Claude-only. */
|
||||
statusLineTelemetry: z.boolean().optional(),
|
||||
openCodeConfig: OpenCodeConfigSchema,
|
||||
codexConfig: CodexConfigSchema,
|
||||
/** Resume a previous Claude conversation by its session ID (used for reboot recovery) */
|
||||
@@ -184,6 +186,52 @@ export const ResizeSchema = z.object({
|
||||
cols: z.number().int().min(1).max(500),
|
||||
rows: z.number().int().min(1).max(200),
|
||||
viewportType: z.enum(['mobile', 'tablet', 'desktop']).optional(),
|
||||
force: z.boolean().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for POST /api/status-telemetry
|
||||
* Claude Code statusline payload forwarded by the Codeman-managed statusLine
|
||||
* exporter (see hooks-config.generateStatusLineCommand). Validates only the
|
||||
* subset Codeman displays; unknown keys (session_id, transcript_path, cwd, …)
|
||||
* are stripped by z.object. Auth-exempt like /api/hook-event.
|
||||
*/
|
||||
// NOTE: every modeled field is `.nullish()` (not `.optional()`) on purpose.
|
||||
// Claude's statusline blob is officially shipped but undocumented in exact
|
||||
// shape, and `z.optional()` REJECTS an explicit `null` (accepts only
|
||||
// `undefined`) — a single stray `null` (e.g. `cost:{total_cost_usd:null}`)
|
||||
// would 400 the ENTIRE POST before the deliberately-tolerant parser
|
||||
// (usage-telemetry.ts, which only acts on `typeof === 'number'/'string'`) ever
|
||||
// runs, silently killing the chip's data feed. `.nullish()` keeps the schema
|
||||
// gate as forgiving as the parser it guards.
|
||||
const RateLimitWindowSchema = z
|
||||
.object({
|
||||
used_percentage: z.number().nullish(),
|
||||
resets_at: z.number().nullish(),
|
||||
})
|
||||
.nullish();
|
||||
|
||||
export const StatusTelemetrySchema = z.object({
|
||||
sessionId: z.string().min(1).max(100),
|
||||
data: z
|
||||
.object({
|
||||
rate_limits: z
|
||||
.object({
|
||||
five_hour: RateLimitWindowSchema,
|
||||
seven_day: RateLimitWindowSchema,
|
||||
})
|
||||
.nullish(),
|
||||
context_window: z
|
||||
.object({
|
||||
used_percentage: z.number().nullish(),
|
||||
total_input_tokens: z.number().nullish(),
|
||||
total_output_tokens: z.number().nullish(),
|
||||
})
|
||||
.nullish(),
|
||||
cost: z.object({ total_cost_usd: z.number().nullish() }).nullish(),
|
||||
model: z.object({ display_name: z.string().max(100).nullish() }).nullish(),
|
||||
})
|
||||
.nullish(),
|
||||
});
|
||||
|
||||
// ========== Case Routes ==========
|
||||
@@ -301,8 +349,17 @@ export const SettingsUpdateSchema = z
|
||||
ralphTrackerEnabled: z.boolean().optional(),
|
||||
subagentTrackingEnabled: z.boolean().optional(),
|
||||
subagentActiveTabOnly: z.boolean().optional(),
|
||||
/** Ultracode/Workflow run visualization (default OFF). Gates workflowRunWatcher + the master-detail tab. SYNCED. */
|
||||
showUltracodeAgents: z.boolean().optional(),
|
||||
/** Floating ultracode run windows w/ tab connector lines (default OFF). Also starts workflowRunWatcher. SYNCED. */
|
||||
ultracodeFloatingWindows: z.boolean().optional(),
|
||||
imageWatcherEnabled: z.boolean().optional(),
|
||||
tunnelEnabled: z.boolean().optional(),
|
||||
// Action field (NOT persisted): explicit per-request acknowledgment that the
|
||||
// operator accepts exposing an UNAUTHENTICATED public tunnel (no CODEMAN_PASSWORD).
|
||||
// Lets the UI enable a tunnel after a confirm dialog without the
|
||||
// CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK env var. Stripped before persisting.
|
||||
acknowledgeUnauthTunnel: z.boolean().optional(),
|
||||
tabTwoRows: z.boolean().optional(),
|
||||
agentTeamsEnabled: z.boolean().optional(),
|
||||
/** Model for new Claude sessions (e.g. "claude-fable-5[1m]", "opus[1m]"); takes precedence over opusContext1mEnabled */
|
||||
@@ -321,6 +378,14 @@ export const SettingsUpdateSchema = z
|
||||
showFileBrowser: z.boolean().optional(),
|
||||
showSubagents: z.boolean().optional(),
|
||||
showMultiMonitorButton: z.boolean().optional(),
|
||||
showPlanUsageLimits: z.boolean().optional(),
|
||||
// Action field (NOT persisted as a setting): when true, (re)injects the
|
||||
// plan-usage statusLine exporter into active Claude sessions so live usage %
|
||||
// starts flowing. Sent on ENABLE only — the chip's DISPLAY is per-device
|
||||
// (client-side), but telemetry COLLECTION is server-side, so the per-device
|
||||
// toggle signals it out-of-band here rather than via showPlanUsageLimits.
|
||||
statusLineTelemetry: z.boolean().optional(),
|
||||
showRedrawButton: z.boolean().optional(),
|
||||
// Input
|
||||
gestureControlEnabled: z.boolean().optional(),
|
||||
// Claude CLI settings
|
||||
@@ -404,6 +469,15 @@ export const SettingsUpdateSchema = z
|
||||
export const SessionInputWithLimitSchema = z.object({
|
||||
input: z.string().max(100000), // 100KB max input
|
||||
useMux: z.boolean().optional(),
|
||||
// Reliable-delivery dedup (optional; absent for curl/legacy clients). The web
|
||||
// client tags each input with a stable clientId + a monotonic per-session seq
|
||||
// and redelivers anything it hasn't seen ACKed (e.g. a frame silently dropped
|
||||
// by a half-open WebSocket on a flaky link). The server applies each (clientId,
|
||||
// seq) at-most-once via Session.shouldApplyInput so a redelivery can't type the
|
||||
// prompt twice. `.optional()` (not `.nullish()`) — the client omits them when
|
||||
// unset rather than sending null. See docs/reliable-input-delivery.md.
|
||||
seq: z.number().int().nonnegative().optional(),
|
||||
clientId: z.string().max(128).optional(),
|
||||
});
|
||||
|
||||
// ========== Session Mutation Routes ==========
|
||||
@@ -450,6 +524,11 @@ export const AutoCompactSchema = z.object({
|
||||
prompt: z.string().max(10000).optional(),
|
||||
});
|
||||
|
||||
/** POST /api/sessions/:id/auto-resume */
|
||||
export const AutoResumeSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
/** POST /api/sessions/:id/image-watcher */
|
||||
export const ImageWatcherSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
|
||||
+28
-1
@@ -161,7 +161,9 @@ export function parseGitHubRepo(remoteUrl: string): { owner: string; repo: strin
|
||||
* persist — or null to leave it untouched.
|
||||
*
|
||||
* Rules (see plan "Hardening"):
|
||||
* - Terminal phases → untouched.
|
||||
* - Terminal phases → untouched, EXCEPT `completed-needs-manual-restart`: once we
|
||||
* boot into the staged target version the manual restart evidently happened, so
|
||||
* it flips to `completed` (otherwise the stale instruction lingers in the UI).
|
||||
* - Only the `restarting` marker (written right before the updater triggers our
|
||||
* restart) flips to completed/failed by comparing running version vs. target.
|
||||
* - Other in-flight phases are owned by the still-running updater scope — leave
|
||||
@@ -174,6 +176,17 @@ export function reconcileStatusDecision(
|
||||
now: number
|
||||
): UpdateStatus | null {
|
||||
if (!status) return null;
|
||||
|
||||
// A staged update that asked for a manual restart: if we're now running the
|
||||
// target version, the user (or supervisor) did restart — mark it completed so
|
||||
// the UI stops showing the stale "restart Codeman to apply" instruction.
|
||||
if (status.phase === 'completed-needs-manual-restart') {
|
||||
if (status.toVersion && runningVersion === status.toVersion) {
|
||||
return { ...status, phase: 'completed', message: `Updated to v${runningVersion}`, updatedAt: now };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!IN_FLIGHT_PHASES.has(status.phase)) return null;
|
||||
|
||||
if (status.phase === 'restarting') {
|
||||
@@ -275,6 +288,16 @@ function detectInstallKind(dir: string): InstallKind {
|
||||
export function detectSupervisor(): SupervisorKind {
|
||||
if (process.platform === 'darwin') {
|
||||
if (existsSync(join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`))) return 'launchd';
|
||||
// Headless Macs (no GUI login → no gui domain) run Codeman as a system-level
|
||||
// LaunchDaemon instead. Restarting one needs no root IF it has KeepAlive: the
|
||||
// updater just kills the server and launchd respawns it on the new build. Only
|
||||
// claim this supervisor when the daemon is actually bootstrapped and KeepAlive.
|
||||
const daemonPlist = join('/Library/LaunchDaemons', `${LAUNCHD_LABEL}.plist`);
|
||||
if (existsSync(daemonPlist)) {
|
||||
const loaded = tryExec('launchctl', ['print', `system/${LAUNCHD_LABEL}`]) !== null;
|
||||
const keepAlive = tryExec('plutil', ['-extract', 'KeepAlive', 'raw', '-o', '-', daemonPlist]);
|
||||
if (loaded && keepAlive === 'true') return 'launchd-daemon';
|
||||
}
|
||||
return 'none';
|
||||
}
|
||||
if (process.platform === 'linux') {
|
||||
@@ -535,6 +558,10 @@ export async function startUpdate(): Promise<StartUpdateResult> {
|
||||
process.execPath,
|
||||
'--log',
|
||||
logFile,
|
||||
// For the launchd-daemon restart path: the updater kills this PID and the
|
||||
// KeepAlive daemon respawns the server on the freshly built dist/.
|
||||
'--server-pid',
|
||||
String(process.pid),
|
||||
];
|
||||
if (prevSha) args.push('--prev-sha', prevSha);
|
||||
if (info.dirty) args.push('--stash');
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* @fileoverview Shared sensitive-path blocklist.
|
||||
*
|
||||
* A small defense-in-depth blocklist of absolute paths that must never be
|
||||
* served to the browser regardless of how the path was obtained (workspace
|
||||
* download, cross-workspace attachment registration, raw/preview serving).
|
||||
*
|
||||
* This is intentionally a BLOCKLIST, not a workspace-confinement check:
|
||||
* cross-workspace attachment is a supported feature (codeman-publish skill +
|
||||
* the automated review-card loop attaching files under ~/.codeman/), so a
|
||||
* strict session-workspace boundary would break legitimate use. The blocklist
|
||||
* rejects well-known secret locations (system password files, SSH keys, cloud
|
||||
* credentials, dotenv files) while leaving ordinary cross-workspace files
|
||||
* attachable.
|
||||
*
|
||||
* Callers MUST resolve symlinks (realpath) BEFORE calling isSensitivePath so a
|
||||
* symlink pointing at a sensitive target is also caught.
|
||||
*/
|
||||
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const SENSITIVE_PATTERNS: RegExp[] = [
|
||||
/^\/etc\/shadow$/,
|
||||
/^\/etc\/gshadow$/,
|
||||
/^\/etc\/master\.passwd$/,
|
||||
new RegExp(`^${homedir().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\/\\.ssh\\/`),
|
||||
/\/\.env$/,
|
||||
/\/\.env\./,
|
||||
/\/credentials(\.json|\.yml|\.yaml|\.xml)?$/i,
|
||||
/\/\.aws\/credentials$/,
|
||||
/\/\.gcloud\/credentials\.db$/,
|
||||
/\/\.docker\/config\.json$/,
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns true if the given ABSOLUTE, symlink-resolved path matches the
|
||||
* sensitive-file blocklist and must not be served to the browser.
|
||||
*/
|
||||
export function isSensitivePath(absPath: string): boolean {
|
||||
return SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath));
|
||||
}
|
||||
+171
-4
@@ -41,9 +41,10 @@ import fs from 'node:fs/promises';
|
||||
import { execSync } from 'node:child_process';
|
||||
import { hostname as getHostname } from 'node:os';
|
||||
import { dataPath } from '../config/instance.js';
|
||||
import { getHookSecret } from '../config/hook-secret.js';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { Session, isExternalCliMode, type BackgroundTask } from '../session.js';
|
||||
import type { ClaudeMode, SessionState } from '../types.js';
|
||||
import type { ClaudeMode, SessionAttachmentHistoryItem, SessionState, WorkflowRunInfo } from '../types.js';
|
||||
import { RespawnController, RespawnConfig } from '../respawn-controller.js';
|
||||
import type { TerminalMultiplexer } from '../mux-interface.js';
|
||||
import { createMultiplexer } from '../mux-factory.js';
|
||||
@@ -59,6 +60,12 @@ import {
|
||||
type SubagentToolResult,
|
||||
} from '../subagent-watcher.js';
|
||||
import { imageWatcher } from '../image-watcher.js';
|
||||
import { workflowRunWatcher, summarizeRun } from '../workflow-run-watcher.js';
|
||||
import { attachmentRegistry, buildFileThumbnailRoute, registerExternalAttachment } from '../attachment-registry.js';
|
||||
import {
|
||||
buildDetectedAttachmentHistoryItem,
|
||||
buildExternalAttachmentHistoryItem,
|
||||
} from '../session-attachment-history.js';
|
||||
import { TranscriptWatcher } from '../transcript-watcher.js';
|
||||
import { TeamWatcher } from '../team-watcher.js';
|
||||
import { TunnelManager } from '../tunnel-manager.js';
|
||||
@@ -109,6 +116,7 @@ import {
|
||||
type PersistedRespawnConfig,
|
||||
type NiceConfig,
|
||||
type ImageDetectedEvent,
|
||||
type AttachmentDetectedEvent,
|
||||
DEFAULT_NICE_CONFIG,
|
||||
} from '../types.js';
|
||||
import {
|
||||
@@ -120,7 +128,9 @@ import {
|
||||
} from '../utils/index.js';
|
||||
import type { EventLoopMonitorHandle } from '../utils/index.js';
|
||||
import { MAX_CONCURRENT_SESSIONS, MAX_SSE_CLIENTS } from '../config/map-limits.js';
|
||||
import { MAX_PASTE_IMAGE_BYTES } from '../config/buffer-limits.js';
|
||||
import { SseEvent } from './sse-events.js';
|
||||
import { getLatestPlanUsage } from './plan-usage-latest.js';
|
||||
import type { ScheduledRun } from './ports/index.js';
|
||||
import { registerAuthMiddleware, registerSecurityHeaders, registerHostGuard } from './middleware/auth.js';
|
||||
import { installRouteErrorHandler } from './route-error-handler.js';
|
||||
@@ -132,6 +142,7 @@ import {
|
||||
registerFileRoutes,
|
||||
registerScheduledRoutes,
|
||||
registerHookEventRoutes,
|
||||
registerStatusTelemetryRoutes,
|
||||
registerSystemRoutes,
|
||||
registerCaseRoutes,
|
||||
registerSessionRoutes,
|
||||
@@ -247,12 +258,19 @@ export class WebServer extends EventEmitter {
|
||||
} | null = null;
|
||||
private imageWatcherHandlers: {
|
||||
detected: (event: ImageDetectedEvent) => void;
|
||||
attachmentDetected: (event: AttachmentDetectedEvent) => void;
|
||||
error: (error: Error, sessionId?: string) => void;
|
||||
} | null = null;
|
||||
private workflowRunWatcherHandlers: {
|
||||
discovered: (info: WorkflowRunInfo) => void;
|
||||
updated: (info: WorkflowRunInfo) => void;
|
||||
removed: (data: { runId: string }) => void;
|
||||
} | null = null;
|
||||
private tunnelManager: TunnelManager = new TunnelManager();
|
||||
private authSessions: StaleExpirationMap<string, import('./ports/auth-port.js').AuthSessionRecord> | null = null;
|
||||
private authFailures: StaleExpirationMap<string, number> | null = null;
|
||||
private qrAuthFailures: StaleExpirationMap<string, number> | null = null;
|
||||
private hookSecretFailures: StaleExpirationMap<string, number> | null = null;
|
||||
private pushStore: PushSubscriptionStore = new PushSubscriptionStore();
|
||||
private teamWatcher: TeamWatcher = new TeamWatcher();
|
||||
private _orchestratorLoop: import('../orchestrator-loop.js').OrchestratorLoop | null = null;
|
||||
@@ -327,6 +345,7 @@ export class WebServer extends EventEmitter {
|
||||
|
||||
// Set up subagent watcher listeners
|
||||
this.setupSubagentWatcherListeners();
|
||||
this.setupWorkflowRunWatcherListeners();
|
||||
|
||||
// Set up image watcher listeners
|
||||
this.setupImageWatcherListeners();
|
||||
@@ -426,6 +445,31 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bridge WorkflowRunWatcher events → SSE. Broadcasts run SUMMARIES (no agents[])
|
||||
* to keep payloads small; the full agents[] is fetched per-run via
|
||||
* GET /api/workflows/:runId when the user selects a run.
|
||||
*/
|
||||
private setupWorkflowRunWatcherListeners(): void {
|
||||
this.workflowRunWatcherHandlers = {
|
||||
discovered: (info: WorkflowRunInfo) => this.broadcast(SseEvent.WorkflowRunDiscovered, summarizeRun(info)),
|
||||
updated: (info: WorkflowRunInfo) => this.broadcast(SseEvent.WorkflowRunUpdated, summarizeRun(info)),
|
||||
removed: (data: { runId: string }) => this.broadcast(SseEvent.WorkflowRunRemoved, data),
|
||||
};
|
||||
workflowRunWatcher.on('run_discovered', this.workflowRunWatcherHandlers.discovered);
|
||||
workflowRunWatcher.on('run_updated', this.workflowRunWatcherHandlers.updated);
|
||||
workflowRunWatcher.on('run_removed', this.workflowRunWatcherHandlers.removed);
|
||||
}
|
||||
|
||||
private cleanupWorkflowRunWatcherListeners(): void {
|
||||
if (this.workflowRunWatcherHandlers) {
|
||||
workflowRunWatcher.off('run_discovered', this.workflowRunWatcherHandlers.discovered);
|
||||
workflowRunWatcher.off('run_updated', this.workflowRunWatcherHandlers.updated);
|
||||
workflowRunWatcher.off('run_removed', this.workflowRunWatcherHandlers.removed);
|
||||
this.workflowRunWatcherHandlers = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up event listeners for image watcher.
|
||||
* Broadcasts image detection events to SSE clients for auto-popup.
|
||||
@@ -434,12 +478,27 @@ export class WebServer extends EventEmitter {
|
||||
// Store handlers for cleanup on shutdown
|
||||
this.imageWatcherHandlers = {
|
||||
detected: (event: ImageDetectedEvent) => this.broadcast(SseEvent.ImageDetected, event),
|
||||
attachmentDetected: (event: AttachmentDetectedEvent) => {
|
||||
const attachmentEvent = {
|
||||
...event,
|
||||
source: event.source || 'detected',
|
||||
thumbnailUrl:
|
||||
event.thumbnailUrl || buildFileThumbnailRoute(event.sessionId, event.relativePath || event.fileName),
|
||||
};
|
||||
const session = this.sessions.get(event.sessionId);
|
||||
if (session) {
|
||||
session.upsertAttachmentHistory(buildDetectedAttachmentHistoryItem(attachmentEvent));
|
||||
this.persistSessionState(session);
|
||||
}
|
||||
this.broadcast(SseEvent.AttachmentDetected, attachmentEvent);
|
||||
},
|
||||
error: (error: Error, sessionId?: string) => {
|
||||
console.error(`[ImageWatcher] Error${sessionId ? ` for ${sessionId}` : ''}:`, error.message);
|
||||
},
|
||||
};
|
||||
|
||||
imageWatcher.on('image:detected', this.imageWatcherHandlers.detected);
|
||||
imageWatcher.on('attachment:detected', this.imageWatcherHandlers.attachmentDetected);
|
||||
imageWatcher.on('image:error', this.imageWatcherHandlers.error);
|
||||
}
|
||||
|
||||
@@ -449,6 +508,7 @@ export class WebServer extends EventEmitter {
|
||||
private cleanupImageWatcherListeners(): void {
|
||||
if (this.imageWatcherHandlers) {
|
||||
imageWatcher.off('image:detected', this.imageWatcherHandlers.detected);
|
||||
imageWatcher.off('attachment:detected', this.imageWatcherHandlers.attachmentDetected);
|
||||
imageWatcher.off('image:error', this.imageWatcherHandlers.error);
|
||||
this.imageWatcherHandlers = null;
|
||||
}
|
||||
@@ -608,6 +668,7 @@ export class WebServer extends EventEmitter {
|
||||
this.authSessions = authState.authSessions;
|
||||
this.authFailures = authState.authFailures;
|
||||
this.qrAuthFailures = authState.qrAuthFailures;
|
||||
this.hookSecretFailures = authState.hookSecretFailures;
|
||||
}
|
||||
|
||||
// WebSocket support (terminal I/O — low-latency bidirectional channel)
|
||||
@@ -619,8 +680,8 @@ export class WebServer extends EventEmitter {
|
||||
// last byte (hard-coded \r\n offsets), and there was no part-count cap.
|
||||
await this.app.register(fastifyMultipart, {
|
||||
limits: {
|
||||
fileSize: 10 * 1024 * 1024, // 10MB per file
|
||||
files: 1, // paste-image only ever sends one file
|
||||
fileSize: MAX_PASTE_IMAGE_BYTES, // per file (default 50MB) — large phone photos / screenshots
|
||||
files: 1, // paste-image sends one file per request (clients batch up to 20 requests)
|
||||
fields: 4, // small headroom for accompanying form fields
|
||||
},
|
||||
});
|
||||
@@ -801,6 +862,7 @@ export class WebServer extends EventEmitter {
|
||||
registerFileRoutes(this.app, ctx);
|
||||
registerScheduledRoutes(this.app, ctx);
|
||||
registerHookEventRoutes(this.app, ctx);
|
||||
registerStatusTelemetryRoutes(this.app, ctx);
|
||||
registerSystemRoutes(this.app, ctx);
|
||||
registerCaseRoutes(this.app, ctx);
|
||||
registerSessionRoutes(this.app, ctx);
|
||||
@@ -891,7 +953,14 @@ export class WebServer extends EventEmitter {
|
||||
// field kept off SessionState to avoid leaking via API broadcasts.
|
||||
const base = session.toState();
|
||||
const envOverrides = session.getEnvOverridesForPersist();
|
||||
const state = (envOverrides ? { ...base, __envOverrides: envOverrides } : base) as SessionState;
|
||||
// __attachmentHistory keeps the private (externalPath-bearing) history on disk,
|
||||
// separate from the sanitized public attachmentHistory in toState().
|
||||
const attachmentHistory = session.getAttachmentHistoryForPersist();
|
||||
const state = {
|
||||
...base,
|
||||
...(envOverrides ? { __envOverrides: envOverrides } : {}),
|
||||
...(attachmentHistory ? { __attachmentHistory: attachmentHistory } : {}),
|
||||
} as SessionState;
|
||||
const controller = this.respawnControllers.get(session.id);
|
||||
if (controller) {
|
||||
const config = controller.getConfig();
|
||||
@@ -1064,6 +1133,8 @@ export class WebServer extends EventEmitter {
|
||||
session.removeAllListeners();
|
||||
// Close any active file streams for this session
|
||||
fileStreamManager.closeSessionStreams(sessionId);
|
||||
// Drop live external attachment registrations for this session
|
||||
attachmentRegistry.clearSession(sessionId);
|
||||
// Stop watching for images in this session's directory
|
||||
imageWatcher.unwatchSession(sessionId);
|
||||
// Clean up pasted images directory for this session
|
||||
@@ -1109,6 +1180,11 @@ export class WebServer extends EventEmitter {
|
||||
if (settings.showMultiMonitorButton === true) {
|
||||
html = html.replace(' btn-multimonitor--hidden', '');
|
||||
}
|
||||
// Plan-usage chip: ships hidden (`header-plan-usage--hidden`) and is revealed
|
||||
// PER-DEVICE by the client (settings-ui.js applyHeaderVisibilitySettings). It
|
||||
// used to be server-revealed from a synced setting, but that leaked the desktop
|
||||
// choice onto mobile — display is now per-device only (like the response viewer).
|
||||
// Telemetry collection stays server-side via the statusLineTelemetry action.
|
||||
// Detached single-session ("solo") window: inject the target session id so
|
||||
// the client can enter solo mode even if a (network-first) service worker
|
||||
// later serves a cached shell. The client primarily detects solo mode from
|
||||
@@ -1249,9 +1325,47 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
},
|
||||
getStore: () => this.store,
|
||||
registerAttachment: (id: string, filePath: string) => this.registerAttachment(id, filePath),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a terminal-requested external file as a live attachment and
|
||||
* broadcast it. Triggered by the session's `attachmentRequested` event
|
||||
* (codeman://attach magic links). Because terminal output is
|
||||
* attacker-influenceable (a prompt-injected session can print an arbitrary
|
||||
* `codeman://attach?path=` link), the scanned path is FORCE-confined to the
|
||||
* session workspace — passive magic links can't expose arbitrary host files.
|
||||
* Deliberate cross-workspace attachment goes through the explicit,
|
||||
* Origin-guarded `POST /attachments` route (and `codeman attach`, which POSTs
|
||||
* directly inside a managed session). Registration also enforces the COD-53
|
||||
* blocklist as defense-in-depth.
|
||||
*/
|
||||
private async registerAttachment(sessionId: string, filePath: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
const event = await registerExternalAttachment(sessionId, filePath, {
|
||||
sessionWorkingDir: session.workingDir,
|
||||
forceWorkspaceConfinement: true,
|
||||
});
|
||||
const record = attachmentRegistry.get(sessionId, event.attachmentId);
|
||||
if (record) {
|
||||
session.upsertAttachmentHistory(
|
||||
buildExternalAttachmentHistoryItem({
|
||||
sessionId,
|
||||
externalPath: record.filePath,
|
||||
fileName: record.fileName,
|
||||
extension: record.extension,
|
||||
size: record.size,
|
||||
mtimeMs: record.mtimeMs,
|
||||
timestamp: event.timestamp,
|
||||
})
|
||||
);
|
||||
this.persistSessionState(session);
|
||||
}
|
||||
this.broadcast(SseEvent.AttachmentDetected, event);
|
||||
}
|
||||
|
||||
private setupRespawnListeners(sessionId: string, controller: RespawnController): void {
|
||||
wireRespawnListeners(sessionId, controller, this.buildRespawnWiringDeps());
|
||||
}
|
||||
@@ -1588,8 +1702,10 @@ export class WebServer extends EventEmitter {
|
||||
respawnStatus,
|
||||
globalStats: this.store.getAggregateStats(activeSessionTokens),
|
||||
subagents: subagentWatcher.getRecentSubagents(15), // 15 min to avoid stale agents
|
||||
workflowRuns: workflowRunWatcher.getAllRunSummaries(), // ultracode run summaries (no agents[]) for the LEFT list
|
||||
timestamp: now,
|
||||
inputCjkForm: process.env.INPUT_CJK_FORM?.toUpperCase() === 'ON',
|
||||
planUsage: getLatestPlanUsage(), // last-known plan-usage telemetry, for the header chip on fresh load
|
||||
};
|
||||
|
||||
this.cachedLightState = { data: result, timestamp: now };
|
||||
@@ -1816,6 +1932,10 @@ export class WebServer extends EventEmitter {
|
||||
this.host === '0.0.0.0' || this.host === 'localhost' || this.host === '::1' ? '127.0.0.1' : this.host;
|
||||
process.env.CODEMAN_API_URL = `${protocol}://${apiHost}:${this.port}`;
|
||||
|
||||
// Ensure the COD-54 hook secret exists on disk before any session exports
|
||||
// $CODEMAN_HOOK_SECRET_FILE — hook curls cat that path at execution time.
|
||||
getHookSecret();
|
||||
|
||||
// Start scheduled runs cleanup timer
|
||||
this.cleanup.setInterval(
|
||||
() => {
|
||||
@@ -1851,6 +1971,14 @@ export class WebServer extends EventEmitter {
|
||||
console.log('Subagent watcher disabled by user settings');
|
||||
}
|
||||
|
||||
// Start workflow run watcher for ultracode / Workflow run visualization (if enabled)
|
||||
if (await this.isWorkflowAgentTrackingEnabled()) {
|
||||
workflowRunWatcher.start();
|
||||
console.log('Workflow run watcher started - monitoring ~/.claude/projects for ultracode run activity');
|
||||
} else {
|
||||
console.log('Workflow run watcher disabled by user settings (showUltracodeAgents off)');
|
||||
}
|
||||
|
||||
// Start image watcher for auto-popup of screenshots (if enabled)
|
||||
if (await this.isImageWatcherEnabled()) {
|
||||
imageWatcher.start();
|
||||
@@ -1897,6 +2025,25 @@ export class WebServer extends EventEmitter {
|
||||
return true; // Default enabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if ultracode/workflow run tracking is enabled in settings (default: FALSE — opt-in).
|
||||
* The watcher feeds BOTH the docked Ultracode Agents panel (`showUltracodeAgents`) and the
|
||||
* floating run windows (`ultracodeFloatingWindows`), so either toggle starts it.
|
||||
*/
|
||||
private async isWorkflowAgentTrackingEnabled(): Promise<boolean> {
|
||||
const settingsPath = dataPath('settings.json');
|
||||
try {
|
||||
const content = await fs.readFile(settingsPath, 'utf-8');
|
||||
const settings = JSON.parse(content);
|
||||
return (settings.showUltracodeAgents ?? false) || (settings.ultracodeFloatingWindows ?? false);
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
console.error('Failed to read showUltracodeAgents setting:', err);
|
||||
}
|
||||
}
|
||||
return false; // Default disabled (opt-in)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if image watcher is enabled in settings (default: false)
|
||||
*/
|
||||
@@ -1962,6 +2109,11 @@ export class WebServer extends EventEmitter {
|
||||
// Note: a legacy CLAUDE_CODE_EFFORT_LEVEL entry is auto-migrated to `effort`
|
||||
// by the Session constructor (env var would hard-lock /effort switching).
|
||||
const savedEnvOverrides = (savedState as { __envOverrides?: Record<string, string> })?.__envOverrides;
|
||||
// Prefer the private (externalPath-bearing) history; fall back to the
|
||||
// sanitized public copy for sessions persisted before that split.
|
||||
const savedAttachmentHistory =
|
||||
(savedState as { __attachmentHistory?: SessionAttachmentHistoryItem[] })?.__attachmentHistory ??
|
||||
savedState?.attachmentHistory;
|
||||
const session = new Session({
|
||||
id: muxSession.sessionId, // Preserve the original session ID
|
||||
workingDir: muxSession.workingDir,
|
||||
@@ -1974,6 +2126,7 @@ export class WebServer extends EventEmitter {
|
||||
allowedTools: recoveryClaudeMode.allowedTools,
|
||||
envOverrides: savedEnvOverrides,
|
||||
effort: savedState?.effort,
|
||||
attachmentHistory: savedAttachmentHistory,
|
||||
});
|
||||
|
||||
// Update session name if it was a "Restored:" placeholder or doesn't match saved name
|
||||
@@ -1993,6 +2146,12 @@ export class WebServer extends EventEmitter {
|
||||
if (savedState.autoClearEnabled !== undefined || savedState.autoClearThreshold !== undefined) {
|
||||
session.setAutoClear(savedState.autoClearEnabled ?? false, savedState.autoClearThreshold);
|
||||
}
|
||||
// Auto-resume on usage limit (re-arms a pending schedule; an
|
||||
// overdue one fires shortly after boot — the limit footer won't
|
||||
// reprint on its own, so the pause would otherwise stall)
|
||||
if (savedState.autoResumeEnabled) {
|
||||
session.restoreAutoResume(true, savedState.autoResumeAt);
|
||||
}
|
||||
// Token tracking
|
||||
if (
|
||||
savedState.inputTokens !== undefined ||
|
||||
@@ -2239,12 +2398,16 @@ export class WebServer extends EventEmitter {
|
||||
|
||||
// Clean up watcher listeners to prevent memory leaks
|
||||
this.cleanupSubagentWatcherListeners();
|
||||
this.cleanupWorkflowRunWatcherListeners();
|
||||
this.cleanupImageWatcherListeners();
|
||||
this.cleanupTeamWatcherListeners();
|
||||
|
||||
// Stop subagent watcher
|
||||
subagentWatcher.stop();
|
||||
|
||||
// Stop workflow run watcher
|
||||
workflowRunWatcher.stop();
|
||||
|
||||
// Stop image watcher
|
||||
imageWatcher.stop();
|
||||
|
||||
@@ -2292,6 +2455,10 @@ export class WebServer extends EventEmitter {
|
||||
this.qrAuthFailures.dispose();
|
||||
this.qrAuthFailures = null;
|
||||
}
|
||||
if (this.hookSecretFailures) {
|
||||
this.hookSecretFailures.dispose();
|
||||
this.hookSecretFailures = null;
|
||||
}
|
||||
this.activePlanOrchestrators.clear();
|
||||
this.cleaningUp.clear();
|
||||
|
||||
|
||||
@@ -45,6 +45,9 @@ export interface SessionListenerRefs {
|
||||
taskFailed: (task: BackgroundTask, error: string) => void;
|
||||
autoClear: (data: { tokens: number; threshold: number }) => void;
|
||||
autoCompact: (data: { tokens: number; threshold: number; prompt?: string }) => void;
|
||||
limitPauseScheduled: (data: { resetAt: number; resumeAt: number; matched: string }) => void;
|
||||
limitResume: (data: { attempt: number }) => void;
|
||||
limitResumeCancelled: (data: { reason: string }) => void;
|
||||
cliInfoUpdated: (data: { version?: string; model?: string; accountType?: string; latestVersion?: string }) => void;
|
||||
ralphLoopUpdate: (state: RalphTrackerState) => void;
|
||||
ralphTodoUpdate: (todos: RalphTodoItem[]) => void;
|
||||
@@ -55,6 +58,7 @@ export interface SessionListenerRefs {
|
||||
bashToolStart: (tool: ActiveBashTool) => void;
|
||||
bashToolEnd: (tool: ActiveBashTool) => void;
|
||||
bashToolsUpdate: (tools: ActiveBashTool[]) => void;
|
||||
attachmentRequested: (event: { path: string }) => void;
|
||||
}
|
||||
|
||||
/** Dependencies injected by WebServer — keeps listener creation decoupled from server internals. */
|
||||
@@ -74,10 +78,11 @@ interface SessionListenerDeps {
|
||||
removeSessionListenerRefs(sessionId: string): void;
|
||||
cleanupRespawnOnExit(sessionId: string): void;
|
||||
getStore(): import('../state-store.js').StateStore;
|
||||
registerAttachment(sessionId: string, filePath: string): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates all 25 session listener handlers, capturing dependencies via closure.
|
||||
* Creates all 26 session listener handlers, capturing dependencies via closure.
|
||||
* Call `attachSessionListeners()` after to wire them to the session.
|
||||
*/
|
||||
export function createSessionListeners(session: Session, deps: SessionListenerDeps): SessionListenerRefs {
|
||||
@@ -243,6 +248,28 @@ export function createSessionListeners(session: Session, deps: SessionListenerDe
|
||||
if (tracker) tracker.recordAutoCompact(data.tokens, data.threshold);
|
||||
},
|
||||
|
||||
/** Broadcasts `session:limitPauseScheduled` — usage-limit pause detected, auto-resume armed.
|
||||
* Persisted so a pending schedule survives a Codeman restart. */
|
||||
limitPauseScheduled: (data: { resetAt: number; resumeAt: number; matched: string }) => {
|
||||
deps.broadcast(SseEvent.SessionLimitPauseScheduled, { sessionId: session.id, ...data });
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
deps.persistSessionState(session);
|
||||
},
|
||||
|
||||
/** Broadcasts `session:limitResume` — auto-resume prompt sent after limit reset */
|
||||
limitResume: (data: { attempt: number }) => {
|
||||
deps.broadcast(SseEvent.SessionLimitResume, { sessionId: session.id, ...data });
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
deps.persistSessionState(session);
|
||||
},
|
||||
|
||||
/** Broadcasts `session:limitResumeCancelled` — pending auto-resume no longer needed */
|
||||
limitResumeCancelled: (data: { reason: string }) => {
|
||||
deps.broadcast(SseEvent.SessionLimitResumeCancelled, { sessionId: session.id, ...data });
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
deps.persistSessionState(session);
|
||||
},
|
||||
|
||||
// ─── CLI Info ────────────────────────────────────────────
|
||||
|
||||
/** Broadcasts `session:cliInfo` — Claude Code version, model, account type parsed from terminal */
|
||||
@@ -330,6 +357,13 @@ export function createSessionListeners(session: Session, deps: SessionListenerDe
|
||||
bashToolsUpdate: (tools: ActiveBashTool[]) => {
|
||||
deps.broadcast(SseEvent.SessionBashToolsUpdate, { sessionId: session.id, tools });
|
||||
},
|
||||
|
||||
/** Registers an explicit attachment card requested by terminal magic text. */
|
||||
attachmentRequested: (event: { path: string }) => {
|
||||
deps.registerAttachment(session.id, event.path).catch((err) => {
|
||||
console.error(`[Attachment] Failed to register ${event.path} for ${session.id}:`, err);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -350,6 +384,9 @@ export function attachSessionListeners(session: Session, refs: SessionListenerRe
|
||||
session.on('taskFailed', refs.taskFailed);
|
||||
session.on('autoClear', refs.autoClear);
|
||||
session.on('autoCompact', refs.autoCompact);
|
||||
session.on('limitPauseScheduled', refs.limitPauseScheduled);
|
||||
session.on('limitResume', refs.limitResume);
|
||||
session.on('limitResumeCancelled', refs.limitResumeCancelled);
|
||||
session.on('cliInfoUpdated', refs.cliInfoUpdated);
|
||||
session.on('ralphLoopUpdate', refs.ralphLoopUpdate);
|
||||
session.on('ralphTodoUpdate', refs.ralphTodoUpdate);
|
||||
@@ -360,6 +397,7 @@ export function attachSessionListeners(session: Session, refs: SessionListenerRe
|
||||
session.on('bashToolStart', refs.bashToolStart);
|
||||
session.on('bashToolEnd', refs.bashToolEnd);
|
||||
session.on('bashToolsUpdate', refs.bashToolsUpdate);
|
||||
session.on('attachmentRequested', refs.attachmentRequested);
|
||||
}
|
||||
|
||||
/** Detach all listeners from a session (prevents memory leaks from closure references). */
|
||||
@@ -379,6 +417,9 @@ export function detachSessionListeners(session: Session, refs: SessionListenerRe
|
||||
session.off('taskFailed', refs.taskFailed);
|
||||
session.off('autoClear', refs.autoClear);
|
||||
session.off('autoCompact', refs.autoCompact);
|
||||
session.off('limitPauseScheduled', refs.limitPauseScheduled);
|
||||
session.off('limitResume', refs.limitResume);
|
||||
session.off('limitResumeCancelled', refs.limitResumeCancelled);
|
||||
session.off('cliInfoUpdated', refs.cliInfoUpdated);
|
||||
session.off('ralphLoopUpdate', refs.ralphLoopUpdate);
|
||||
session.off('ralphTodoUpdate', refs.ralphTodoUpdate);
|
||||
@@ -389,4 +430,5 @@ export function detachSessionListeners(session: Session, refs: SessionListenerRe
|
||||
session.off('bashToolStart', refs.bashToolStart);
|
||||
session.off('bashToolEnd', refs.bashToolEnd);
|
||||
session.off('bashToolsUpdate', refs.bashToolsUpdate);
|
||||
session.off('attachmentRequested', refs.attachmentRequested);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
* - **Mux** (4): created, killed, died, statsUpdated
|
||||
* - **Respawn** (24): stateChanged, cycleStarted/Completed, step*, aiCheck*, planCheck*, timer*, log, ...
|
||||
* - **Subagents** (7): discovered, updated, tool_call, tool_result, progress, message, completed
|
||||
* - **Workflow runs** (3): run_discovered, run_updated, run_removed (ultracode / Workflow tool)
|
||||
* - **Scheduled** (6): created, updated, completed, stopped, log, deleted
|
||||
* - **Teams** (4): created, updated, removed, taskUpdated
|
||||
* - **Transcript** (4): complete, plan_mode, tool_start, tool_end
|
||||
@@ -73,6 +74,12 @@ export const SessionWorking = 'session:working' as const;
|
||||
export const SessionAutoClear = 'session:autoClear' as const;
|
||||
/** Auto-compact triggered for the session. */
|
||||
export const SessionAutoCompact = 'session:autoCompact' as const;
|
||||
/** Usage-limit pause detected; auto-resume scheduled. */
|
||||
export const SessionLimitPauseScheduled = 'session:limitPauseScheduled' as const;
|
||||
/** Auto-resume prompt sent after a usage-limit reset. */
|
||||
export const SessionLimitResume = 'session:limitResume' as const;
|
||||
/** Pending usage-limit auto-resume cancelled (session resumed or feature disabled). */
|
||||
export const SessionLimitResumeCancelled = 'session:limitResumeCancelled' as const;
|
||||
/** CLI version/model info detected from session output. */
|
||||
export const SessionCliInfo = 'session:cliInfo' as const;
|
||||
/** General session message (e.g. status text). */
|
||||
@@ -81,6 +88,8 @@ export const SessionMessage = 'session:message' as const;
|
||||
export const SessionInteractive = 'session:interactive' as const;
|
||||
/** Prompt sent to session for execution. */
|
||||
export const SessionRunning = 'session:running' as const;
|
||||
/** Claude plan-usage telemetry (5-hour + weekly limits) parsed from the statusline. */
|
||||
export const SessionStatusTelemetry = 'session:statusTelemetry' as const;
|
||||
|
||||
// ─── Session: Ralph ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -207,6 +216,15 @@ export const SubagentMessage = 'subagent:message' as const;
|
||||
/** Subagent finished. */
|
||||
export const SubagentCompleted = 'subagent:completed' as const;
|
||||
|
||||
// ─── Workflow Runs (ultracode / Workflow tool) ───────────────────────────────
|
||||
|
||||
/** A workflow run was discovered (first time seen). Payload: WorkflowRunInfo. */
|
||||
export const WorkflowRunDiscovered = 'workflow:run_discovered' as const;
|
||||
/** A workflow run changed (agent state/token tick). Payload: WorkflowRunInfo. */
|
||||
export const WorkflowRunUpdated = 'workflow:run_updated' as const;
|
||||
/** A workflow run's file disappeared. Payload: { runId: string }. */
|
||||
export const WorkflowRunRemoved = 'workflow:run_removed' as const;
|
||||
|
||||
// ─── Scheduled Runs ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Scheduled run created. */
|
||||
@@ -278,6 +296,8 @@ export const TunnelQrAuthUsed = 'tunnel:qrAuthUsed' as const;
|
||||
|
||||
/** New image file detected (e.g. screenshot upload). */
|
||||
export const ImageDetected = 'image:detected' as const;
|
||||
/** New document/image attachment detected in a session working directory. */
|
||||
export const AttachmentDetected = 'attachment:detected' as const;
|
||||
|
||||
// ─── Hooks ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -361,10 +381,14 @@ export const SseEvent = {
|
||||
SessionWorking,
|
||||
SessionAutoClear,
|
||||
SessionAutoCompact,
|
||||
SessionLimitPauseScheduled,
|
||||
SessionLimitResume,
|
||||
SessionLimitResumeCancelled,
|
||||
SessionCliInfo,
|
||||
SessionMessage,
|
||||
SessionInteractive,
|
||||
SessionRunning,
|
||||
SessionStatusTelemetry,
|
||||
|
||||
// Session: Ralph
|
||||
SessionRalphLoopUpdate,
|
||||
@@ -432,6 +456,11 @@ export const SseEvent = {
|
||||
SubagentMessage,
|
||||
SubagentCompleted,
|
||||
|
||||
// Workflow runs (ultracode)
|
||||
WorkflowRunDiscovered,
|
||||
WorkflowRunUpdated,
|
||||
WorkflowRunRemoved,
|
||||
|
||||
// Scheduled runs
|
||||
ScheduledCreated,
|
||||
ScheduledUpdated,
|
||||
@@ -470,6 +499,7 @@ export const SseEvent = {
|
||||
|
||||
// Image
|
||||
ImageDetected,
|
||||
AttachmentDetected,
|
||||
|
||||
// Hooks
|
||||
HookIdlePrompt,
|
||||
|
||||
@@ -0,0 +1,888 @@
|
||||
/**
|
||||
* @fileoverview Workflow (ultracode) Run Watcher
|
||||
*
|
||||
* Emits events powering the master-detail "working agents" view (tasks/phases on
|
||||
* the LEFT, per-agent tokens/tool-calls on the RIGHT) AND the floating run
|
||||
* windows, from TWO disk sources per run:
|
||||
*
|
||||
* 1. COMPLETION artifact — `…/workflows/wf_<id>.json`. The Workflow runtime
|
||||
* writes this with the FULL run state (phases, per-agent tokens/tool-calls,
|
||||
* result), but — as of the mid-2026 runtime — only when the run FINISHES
|
||||
* (always a terminal status). It is the authoritative, detailed record.
|
||||
* 2. LIVE transcript dir — `…/subagents/workflows/wf_<id>/` (agent-*.jsonl +
|
||||
* journal.jsonl). This appears WHILE a run is in flight, before any
|
||||
* `wf_<id>.json` exists. From it we synthesize a minimal ACTIVE run
|
||||
* (status 'running', agent slots keyed by agentId, lastActivityAt from file
|
||||
* mtimes) so the floating window pops DURING the run instead of only after.
|
||||
*
|
||||
* Precedence: when a completion `wf_<id>.json` exists it ALWAYS supersedes the
|
||||
* synthesized live record (same runId), so a finished run shows full detail and
|
||||
* the normal finish→auto-close flow runs. Without source 2 the floating-window
|
||||
* feature is dead for live runs (the completion file only lands at the end, so
|
||||
* the watcher would never see a run while it is active).
|
||||
*
|
||||
* Still STANDALONE: it never imports from or touches subagent-watcher.ts. It
|
||||
* independently reads the same `subagents/workflows/` tree subagent-watcher uses,
|
||||
* but as a separate singleton with no shared mutable state.
|
||||
*
|
||||
* Discovery is dual: a periodic poll (catches new run dirs + removals) plus a
|
||||
* per-dir chokidar watcher (live updates). A per-source mtime skip keeps the hot
|
||||
* path cheap — the completion JSON / live dir is re-read only when its mtime moves.
|
||||
*
|
||||
* @module workflow-run-watcher
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { readdir, readFile, stat } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
|
||||
|
||||
import type { WorkflowRunInfo, WorkflowRunSummary, WorkflowAgentInfo, WorkflowRunPhase } from './types/workflow-run.js';
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
import {
|
||||
WORKFLOW_RUN_POLL_INTERVAL_MS,
|
||||
MAX_CACHED_WORKFLOW_RUNS,
|
||||
WORKFLOW_RUN_RECENT_WINDOW_MIN,
|
||||
} from './config/workflow-config.js';
|
||||
|
||||
const WORKFLOWS_SUBDIR = 'workflows';
|
||||
const SUBAGENTS_SUBDIR = 'subagents';
|
||||
const RUN_FILE_PREFIX = 'wf_';
|
||||
const RUN_FILE_SUFFIX = '.json';
|
||||
const LIVE_JOURNAL_FILE = 'journal.jsonl';
|
||||
const LIVE_AGENT_PREFIX = 'agent-';
|
||||
const LIVE_TRANSCRIPT_SUFFIX = '.jsonl';
|
||||
const SCRIPTS_SUBDIR = 'scripts';
|
||||
|
||||
/** Hard caps on the largest per-agent strings so a 28-agent run stays compact. */
|
||||
const PROMPT_PREVIEW_MAX = 200;
|
||||
const RESULT_PREVIEW_MAX = 240;
|
||||
/** Cap a live script read so a runaway/huge embedded script can't blow memory. */
|
||||
const SCRIPT_READ_MAX_BYTES = 512 * 1024;
|
||||
/** LRU cap on cached per-agent transcript stats across all live runs. */
|
||||
const MAX_CACHED_AGENT_STATS = 2000;
|
||||
|
||||
function truncate(value: string | undefined, max: number): string | undefined {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
return value.length > max ? `${value.slice(0, max)}…` : value;
|
||||
}
|
||||
|
||||
/** First text from a transcript message's `content` (string or content-block array). */
|
||||
function extractMessageText(content: unknown): string | undefined {
|
||||
if (typeof content === 'string') return content.trim() || undefined;
|
||||
if (Array.isArray(content)) {
|
||||
for (const block of content) {
|
||||
if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {
|
||||
const t = (block as { text?: string }).text;
|
||||
if (typeof t === 'string' && t.trim()) return t.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Isolate the `meta = { … }` object literal from a workflow script so that later
|
||||
* declarations (e.g. JSON-Schema objects with their own `description:`/`title:`
|
||||
* fields, or prose containing `phases: [`) can't be mistaken for meta. Brace-matches
|
||||
* naively — a `{`/`}` inside a string value can still confuse it, in which case we
|
||||
* return undefined and the caller falls back to scanning the whole body. Best-effort.
|
||||
*/
|
||||
function extractMetaBlock(body: string): string | undefined {
|
||||
const m = /(?:^|[^A-Za-z0-9_])(?:export\s+const|const|let|var)\s+meta\s*=\s*\{/.exec(body);
|
||||
if (!m) return undefined;
|
||||
const open = body.indexOf('{', m.index);
|
||||
if (open < 0) return undefined;
|
||||
let depth = 0;
|
||||
for (let i = open; i < body.length; i++) {
|
||||
if (body[i] === '{') depth++;
|
||||
else if (body[i] === '}' && --depth === 0) return body.slice(open, i + 1);
|
||||
}
|
||||
return undefined; // unterminated (truncated script) — caller falls back to whole body
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort extraction of a single/double-quoted `key: '...'` value from a workflow
|
||||
* `meta` literal (the script is JS we must not eval). The key is anchored to a key
|
||||
* position (`{`/`,`/whitespace before it) so e.g. `description` can't match the tail
|
||||
* of `..._description`; pass the scoped meta block so later same-named schema fields
|
||||
* can't win. Returns undefined on no match.
|
||||
*/
|
||||
function extractMetaString(body: string, key: string): string | undefined {
|
||||
const re = new RegExp(`(?:^|[{,\\s])${key}\\s*:\\s*(['"])((?:\\\\.|(?!\\1).)*)\\1`);
|
||||
const m = re.exec(body);
|
||||
return m ? m[2].replace(/\\(['"\\`])/g, '$1') : undefined;
|
||||
}
|
||||
|
||||
/** Best-effort `meta.phases: [{title, detail}, …]` extraction (pass the scoped meta block). */
|
||||
function extractMetaPhases(body: string): WorkflowRunPhase[] {
|
||||
const keyMatch = /(?:^|[^A-Za-z0-9_])phases\s*:\s*\[/.exec(body);
|
||||
if (!keyMatch) return [];
|
||||
const open = body.indexOf('[', keyMatch.index);
|
||||
if (open < 0) return [];
|
||||
// Brace-match to the array's closing ] so nested arrays don't end it early.
|
||||
let depth = 0;
|
||||
let end = -1;
|
||||
for (let i = open; i < body.length; i++) {
|
||||
if (body[i] === '[') depth++;
|
||||
else if (body[i] === ']' && --depth === 0) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (end < 0) return [];
|
||||
const block = body.slice(open, end + 1);
|
||||
const phases: WorkflowRunPhase[] = [];
|
||||
const re = /title\s*:\s*(['"])((?:\\.|(?!\1).)*)\1(?:\s*,\s*detail\s*:\s*(['"])((?:\\.|(?!\3).)*)\3)?/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(block)) !== null && phases.length < 20) {
|
||||
phases.push({
|
||||
title: m[2].replace(/\\(['"\\`])/g, '$1'),
|
||||
detail: (m[4] || '').replace(/\\(['"\\`])/g, '$1'),
|
||||
});
|
||||
}
|
||||
return phases;
|
||||
}
|
||||
|
||||
/** Drop the heavy `agents[]` for list/snapshot use. */
|
||||
export function summarizeRun(info: WorkflowRunInfo): WorkflowRunSummary {
|
||||
const { agents: _agents, ...summary } = info;
|
||||
void _agents;
|
||||
return summary;
|
||||
}
|
||||
|
||||
interface DiscoveredRun {
|
||||
filePath: string;
|
||||
projectHash: string;
|
||||
sessionUuid: string;
|
||||
runId: string;
|
||||
}
|
||||
|
||||
/** An in-flight run discovered from its `subagents/workflows/wf_<id>/` transcript dir. */
|
||||
interface DiscoveredLiveRun {
|
||||
dirPath: string;
|
||||
projectHash: string;
|
||||
sessionUuid: string;
|
||||
runId: string;
|
||||
}
|
||||
|
||||
/** Per-agent stats parsed from one `agent-<id>.jsonl` transcript (mtime-cached). */
|
||||
interface AgentTranscriptStats {
|
||||
/** Tokens for the agent's LAST usage-bearing message (in+out+cache) ≈ the completion-JSON `tokens`. */
|
||||
tokens: number;
|
||||
/** Count of `tool_use` blocks across the transcript (matches the completion-JSON `toolCalls`). */
|
||||
toolCalls: number;
|
||||
/** Most-recent model id seen. */
|
||||
model: string;
|
||||
/** Name of the most-recent `tool_use` block. */
|
||||
lastToolName?: string;
|
||||
/** First user-message text, truncated — a hint of what the agent was asked. */
|
||||
promptPreview?: string;
|
||||
}
|
||||
|
||||
/** Workflow meta derived live from `workflows/scripts/<name>-<runId>.js`. */
|
||||
interface LiveWorkflowMeta {
|
||||
workflowName?: string;
|
||||
summary?: string;
|
||||
phases: WorkflowRunPhase[];
|
||||
}
|
||||
|
||||
/** A live agent file on disk (transcript and/or meta), keyed by its `<id>` stem. */
|
||||
interface LiveAgentFile {
|
||||
agentId: string;
|
||||
transcriptPath?: string;
|
||||
transcriptMtime?: number;
|
||||
}
|
||||
|
||||
/** A `workflowProgress[]` entry as it appears on disk (loosely typed for defensive parsing). */
|
||||
interface RawProgressEntry {
|
||||
type?: string;
|
||||
index?: number;
|
||||
label?: string;
|
||||
phaseIndex?: number;
|
||||
phaseTitle?: string;
|
||||
model?: string;
|
||||
state?: string;
|
||||
queuedAt?: number;
|
||||
lastProgressAt?: number;
|
||||
promptPreview?: string;
|
||||
agentId?: string;
|
||||
startedAt?: number;
|
||||
attempt?: number;
|
||||
tokens?: number;
|
||||
toolCalls?: number;
|
||||
lastToolName?: string;
|
||||
lastToolSummary?: string;
|
||||
durationMs?: number;
|
||||
resultPreview?: string;
|
||||
}
|
||||
|
||||
export class WorkflowRunWatcher extends EventEmitter {
|
||||
private projectsDir: string;
|
||||
private pollTimer: NodeJS.Timeout | null = null;
|
||||
private _isRunning = false;
|
||||
|
||||
/** runId -> latest parsed run info (LRU-bounded). */
|
||||
private runs = new LRUMap<string, WorkflowRunInfo>({ maxSize: MAX_CACHED_WORKFLOW_RUNS });
|
||||
/** absolute run-file path -> last seen mtimeMs (skip unchanged files). */
|
||||
private fileMtimes = new Map<string, number>();
|
||||
/** runId -> absolute run-file path (for mtime cleanup on removal). */
|
||||
private runIdToPath = new Map<string, string>();
|
||||
/** absolute live transcript-dir path -> newest member mtimeMs (skip unchanged live runs). */
|
||||
private liveDirMtimes = new Map<string, number>();
|
||||
/** runId -> absolute live transcript-dir path (for mtime cleanup on removal). */
|
||||
private runIdToLiveDir = new Map<string, string>();
|
||||
/** transcript abs path -> { mtimeMs, stats }; re-parse a transcript only when its mtime moves. */
|
||||
private agentStatCache = new LRUMap<string, { mtimeMs: number; stats: AgentTranscriptStats }>({
|
||||
maxSize: MAX_CACHED_AGENT_STATS,
|
||||
});
|
||||
/** runId -> derived script meta (immutable per run; re-derived only until a name is found). */
|
||||
private liveMetaCache = new Map<string, LiveWorkflowMeta>();
|
||||
/** journal abs path -> { mtimeMs, parsed }; re-parse the journal only when it grows. */
|
||||
private journalCache = new Map<
|
||||
string,
|
||||
{ mtimeMs: number; parsed: { startedOrder: string[]; doneIds: Set<string> } }
|
||||
>();
|
||||
/** watched-dir absolute path -> chokidar watcher (workflows/ + subagents/workflows/). */
|
||||
private dirWatchers = new Map<string, ChokidarWatcher>();
|
||||
|
||||
constructor(projectsDir?: string) {
|
||||
super();
|
||||
this.projectsDir = projectsDir || join(homedir(), '.claude', 'projects');
|
||||
this.setMaxListeners(50);
|
||||
}
|
||||
|
||||
// ========== Public API ==========
|
||||
|
||||
isRunning(): boolean {
|
||||
return this._isRunning;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this._isRunning) return;
|
||||
this._isRunning = true;
|
||||
this.poll();
|
||||
this.pollTimer = setInterval(() => this.poll(), WORKFLOW_RUN_POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this._isRunning = false;
|
||||
if (this.pollTimer) {
|
||||
clearInterval(this.pollTimer);
|
||||
this.pollTimer = null;
|
||||
}
|
||||
for (const watcher of this.dirWatchers.values()) {
|
||||
watcher.close().catch(() => {}); // best-effort teardown
|
||||
}
|
||||
this.dirWatchers.clear();
|
||||
this.runs.clear();
|
||||
this.fileMtimes.clear();
|
||||
this.runIdToPath.clear();
|
||||
this.liveDirMtimes.clear();
|
||||
this.runIdToLiveDir.clear();
|
||||
this.agentStatCache.clear();
|
||||
this.liveMetaCache.clear();
|
||||
this.journalCache.clear();
|
||||
}
|
||||
|
||||
/** All cached runs (no recency filter), most-recently-active first. */
|
||||
getAllRuns(): WorkflowRunInfo[] {
|
||||
return Array.from(this.runs.values()).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
||||
}
|
||||
|
||||
/** Runs active within the last `minutes`, most-recently-active first. */
|
||||
getRecentRuns(minutes: number = WORKFLOW_RUN_RECENT_WINDOW_MIN): WorkflowRunInfo[] {
|
||||
const cutoff = Date.now() - minutes * 60_000;
|
||||
return this.getAllRuns().filter((r) => r.lastActivityAt >= cutoff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight summaries (no agents[]) of ALL cached runs, most-recently-active
|
||||
* first. This is the LEFT-pane list + getLightState snapshot source: the cache
|
||||
* is LRU-bounded (MAX_CACHED_WORKFLOW_RUNS), so it's already size-capped, and a
|
||||
* run-browser should show past runs — NOT hide everything older than a window.
|
||||
*/
|
||||
getAllRunSummaries(): WorkflowRunSummary[] {
|
||||
return this.getAllRuns().map(summarizeRun);
|
||||
}
|
||||
|
||||
/** Summaries filtered to the last `minutes` of activity (opt-in via ?minutes). */
|
||||
getRecentRunSummaries(minutes: number = WORKFLOW_RUN_RECENT_WINDOW_MIN): WorkflowRunSummary[] {
|
||||
return this.getRecentRuns(minutes).map(summarizeRun);
|
||||
}
|
||||
|
||||
getRun(runId: string): WorkflowRunInfo | undefined {
|
||||
return this.runs.get(runId);
|
||||
}
|
||||
|
||||
getStats(): { runCount: number; running: number; agentCount: number } {
|
||||
let running = 0;
|
||||
let agentCount = 0;
|
||||
for (const run of this.runs.values()) {
|
||||
if (run.status === 'running') running++;
|
||||
agentCount += run.agents.length;
|
||||
}
|
||||
return { runCount: this.runs.size, running, agentCount };
|
||||
}
|
||||
|
||||
// ========== Private ==========
|
||||
|
||||
private poll(): void {
|
||||
this.pollAsync().catch(() => {
|
||||
// Filesystem may be transiently unavailable; the next poll retries.
|
||||
});
|
||||
}
|
||||
|
||||
private async pollAsync(): Promise<void> {
|
||||
const { files, liveDirs, watchDirs } = await this.discover();
|
||||
|
||||
// Install a live watcher for each watched dir; tear down watchers for dirs that vanished.
|
||||
for (const dir of watchDirs) this.ensureDirWatcher(dir);
|
||||
for (const dir of Array.from(this.dirWatchers.keys())) {
|
||||
if (!watchDirs.has(dir)) this.removeDirWatcher(dir);
|
||||
}
|
||||
|
||||
const seenRunIds = new Set<string>();
|
||||
const realRunIds = new Set<string>();
|
||||
for (const file of files) {
|
||||
seenRunIds.add(file.runId);
|
||||
realRunIds.add(file.runId);
|
||||
await this.maybeParse(file);
|
||||
}
|
||||
|
||||
// In-flight runs: synthesize from the transcript tree ONLY while no completion
|
||||
// wf_*.json exists yet — the real file (full detail + terminal status) supersedes.
|
||||
for (const live of liveDirs) {
|
||||
if (realRunIds.has(live.runId)) continue;
|
||||
seenRunIds.add(live.runId);
|
||||
await this.maybeParseLive(live);
|
||||
}
|
||||
|
||||
// Removal by set-diff: a cached run discoverable from neither source.
|
||||
for (const runId of Array.from(this.runs.keys())) {
|
||||
if (!seenRunIds.has(runId)) {
|
||||
this.runs.delete(runId);
|
||||
const path = this.runIdToPath.get(runId);
|
||||
if (path) this.fileMtimes.delete(path);
|
||||
this.runIdToPath.delete(runId);
|
||||
const liveDir = this.runIdToLiveDir.get(runId);
|
||||
if (liveDir) {
|
||||
this.liveDirMtimes.delete(liveDir);
|
||||
// Drop cached transcript stats + journal parse under this run's live dir.
|
||||
const prefix = liveDir.endsWith('/') ? liveDir : liveDir + '/';
|
||||
for (const key of Array.from(this.agentStatCache.keys())) {
|
||||
if (key.startsWith(prefix)) this.agentStatCache.delete(key);
|
||||
}
|
||||
for (const key of Array.from(this.journalCache.keys())) {
|
||||
if (key.startsWith(prefix)) this.journalCache.delete(key);
|
||||
}
|
||||
}
|
||||
this.liveMetaCache.delete(runId);
|
||||
this.runIdToLiveDir.delete(runId);
|
||||
this.emit('run_removed', { runId });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk projects/<projHash>/<sessionUuid>/ for both run sources:
|
||||
* - completion files: `workflows/wf_*.json`
|
||||
* - in-flight runs: `subagents/workflows/wf_<id>/` (transcript dirs)
|
||||
* Returns the dirs to chokidar-watch (so a new run/file is caught sub-poll).
|
||||
*/
|
||||
private async discover(): Promise<{
|
||||
files: DiscoveredRun[];
|
||||
liveDirs: DiscoveredLiveRun[];
|
||||
watchDirs: Set<string>;
|
||||
}> {
|
||||
const files: DiscoveredRun[] = [];
|
||||
const liveDirs: DiscoveredLiveRun[] = [];
|
||||
const watchDirs = new Set<string>();
|
||||
|
||||
let projectHashes: string[];
|
||||
try {
|
||||
projectHashes = await readdir(this.projectsDir);
|
||||
} catch {
|
||||
return { files, liveDirs, watchDirs };
|
||||
}
|
||||
|
||||
for (const projectHash of projectHashes) {
|
||||
let sessions: string[];
|
||||
try {
|
||||
sessions = await readdir(join(this.projectsDir, projectHash));
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const sessionUuid of sessions) {
|
||||
const sessionDir = join(this.projectsDir, projectHash, sessionUuid);
|
||||
|
||||
// (1) Completion artifacts: workflows/wf_*.json
|
||||
const workflowsDir = join(sessionDir, WORKFLOWS_SUBDIR);
|
||||
try {
|
||||
const names = await readdir(workflowsDir);
|
||||
let hasRun = false;
|
||||
for (const name of names) {
|
||||
if (!name.startsWith(RUN_FILE_PREFIX) || !name.endsWith(RUN_FILE_SUFFIX)) continue;
|
||||
hasRun = true;
|
||||
files.push({
|
||||
filePath: join(workflowsDir, name),
|
||||
projectHash,
|
||||
sessionUuid,
|
||||
runId: name.slice(0, -RUN_FILE_SUFFIX.length),
|
||||
});
|
||||
}
|
||||
if (hasRun) watchDirs.add(workflowsDir);
|
||||
} catch {
|
||||
// no workflows dir for this session — normal
|
||||
}
|
||||
|
||||
// (2) In-flight runs: subagents/workflows/wf_*/
|
||||
const liveParent = join(sessionDir, SUBAGENTS_SUBDIR, WORKFLOWS_SUBDIR);
|
||||
try {
|
||||
const names = await readdir(liveParent);
|
||||
let hasLive = false;
|
||||
for (const name of names) {
|
||||
if (!name.startsWith(RUN_FILE_PREFIX) || name.endsWith(RUN_FILE_SUFFIX)) continue; // wf_<id> dir, not a file
|
||||
hasLive = true;
|
||||
liveDirs.push({
|
||||
dirPath: join(liveParent, name),
|
||||
projectHash,
|
||||
sessionUuid,
|
||||
runId: name,
|
||||
});
|
||||
}
|
||||
if (hasLive) watchDirs.add(liveParent);
|
||||
} catch {
|
||||
// no subagents/workflows dir for this session — normal
|
||||
}
|
||||
}
|
||||
}
|
||||
return { files, liveDirs, watchDirs };
|
||||
}
|
||||
|
||||
private async maybeParse(file: DiscoveredRun): Promise<void> {
|
||||
let mtime: number;
|
||||
try {
|
||||
mtime = (await stat(file.filePath)).mtimeMs;
|
||||
} catch {
|
||||
return; // vanished between discover and stat
|
||||
}
|
||||
if (this.fileMtimes.get(file.filePath) === mtime) return;
|
||||
this.fileMtimes.set(file.filePath, mtime);
|
||||
|
||||
const info = await this.parseFile(file);
|
||||
if (!info) return;
|
||||
|
||||
const existed = this.runs.has(info.runId);
|
||||
this.runs.set(info.runId, info);
|
||||
this.runIdToPath.set(info.runId, file.filePath);
|
||||
this.emit(existed ? 'run_updated' : 'run_discovered', info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-synthesize an in-flight run from its transcript dir. Cheap pass first: stat
|
||||
* the dir members and skip entirely when the newest mtime is unchanged, so an idle
|
||||
* poll never reads a single (large) transcript. Only on a real change do we parse —
|
||||
* and even then per-transcript stats come from an mtime-keyed cache, so only the
|
||||
* transcripts that actually grew are re-read.
|
||||
*/
|
||||
private async maybeParseLive(live: DiscoveredLiveRun): Promise<void> {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(live.dirPath);
|
||||
} catch {
|
||||
return; // vanished between discover and read
|
||||
}
|
||||
|
||||
// Cheap pass: newest member mtime + the agent-file set (no transcript reads yet).
|
||||
let newestMtime = 0;
|
||||
let journalPath: string | null = null;
|
||||
let journalMtime = 0;
|
||||
const agentFiles = new Map<string, LiveAgentFile>();
|
||||
for (const name of entries) {
|
||||
if (name !== LIVE_JOURNAL_FILE && !name.startsWith(LIVE_AGENT_PREFIX)) continue;
|
||||
const full = join(live.dirPath, name);
|
||||
let m = 0;
|
||||
try {
|
||||
m = (await stat(full)).mtimeMs;
|
||||
} catch {
|
||||
continue; // entry vanished — ignore
|
||||
}
|
||||
if (m > newestMtime) newestMtime = m;
|
||||
if (name === LIVE_JOURNAL_FILE) {
|
||||
journalPath = full;
|
||||
journalMtime = m;
|
||||
continue;
|
||||
}
|
||||
// agent-<stem>.jsonl (transcript) or agent-<stem>.meta.json (queued-slot marker)
|
||||
const stem = name.slice(LIVE_AGENT_PREFIX.length).replace(/\.(meta\.json|jsonl)$/, '');
|
||||
if (!stem) continue;
|
||||
const slot = agentFiles.get(stem) || { agentId: stem };
|
||||
if (name.endsWith(LIVE_TRANSCRIPT_SUFFIX)) {
|
||||
slot.transcriptPath = full;
|
||||
slot.transcriptMtime = m;
|
||||
}
|
||||
agentFiles.set(stem, slot);
|
||||
}
|
||||
if (agentFiles.size === 0) return; // nothing to show yet
|
||||
|
||||
// Skip the expensive parse when nothing changed since the last synthesis.
|
||||
if (this.liveDirMtimes.get(live.dirPath) === newestMtime) return;
|
||||
this.liveDirMtimes.set(live.dirPath, newestMtime);
|
||||
|
||||
const info = await this.parseLiveDir(live, agentFiles, journalPath, journalMtime, newestMtime);
|
||||
if (!info) return;
|
||||
|
||||
const existed = this.runs.has(info.runId);
|
||||
this.runs.set(info.runId, info);
|
||||
this.runIdToLiveDir.set(info.runId, live.dirPath);
|
||||
this.emit(existed ? 'run_updated' : 'run_discovered', info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an ACTIVE WorkflowRunInfo from a live transcript dir, ENRICHED so the
|
||||
* floating window / panel show real data mid-run rather than empty slots:
|
||||
* - per-agent tokens + tool-calls + model + last tool, parsed from each
|
||||
* `agent-<id>.jsonl` (mtime-cached — only changed transcripts are re-read);
|
||||
* - per-agent state: 'done' once the journal logs a `result` (→ green badge),
|
||||
* 'progress' once it logs `started` or a transcript exists (→ yellow), else 'start';
|
||||
* - run name/summary/phases from the live `workflows/scripts/<name>-<runId>.js`
|
||||
* (the completion wf_<id>.json, which carries these, only lands at the end);
|
||||
* - run totals = sums of the per-agent stats.
|
||||
*/
|
||||
private async parseLiveDir(
|
||||
live: DiscoveredLiveRun,
|
||||
agentFiles: Map<string, LiveAgentFile>,
|
||||
journalPath: string | null,
|
||||
journalMtime: number,
|
||||
newestMtime: number
|
||||
): Promise<WorkflowRunInfo | null> {
|
||||
const { startedOrder, doneIds } = journalPath
|
||||
? await this.readJournal(journalPath, journalMtime)
|
||||
: { startedOrder: [] as string[], doneIds: new Set<string>() };
|
||||
const startIndex = new Map<string, number>();
|
||||
startedOrder.forEach((id, i) => startIndex.set(id, i));
|
||||
|
||||
// Order agents by journal launch order; not-yet-started ones trail (sorted by id).
|
||||
const ids = Array.from(agentFiles.keys()).sort((a, b) => {
|
||||
const ia = startIndex.has(a) ? (startIndex.get(a) as number) : Number.MAX_SAFE_INTEGER;
|
||||
const ib = startIndex.has(b) ? (startIndex.get(b) as number) : Number.MAX_SAFE_INTEGER;
|
||||
if (ia !== ib) return ia - ib;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
});
|
||||
|
||||
let totalTokens = 0;
|
||||
let totalToolCalls = 0;
|
||||
let defaultModel = '';
|
||||
const agents: WorkflowAgentInfo[] = [];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const id = ids[i];
|
||||
const file = agentFiles.get(id) as LiveAgentFile;
|
||||
const stats = file.transcriptPath
|
||||
? await this.agentTranscriptStats(file.transcriptPath, file.transcriptMtime || 0)
|
||||
: null;
|
||||
const state = doneIds.has(id) ? 'done' : startIndex.has(id) || file.transcriptPath ? 'progress' : 'start';
|
||||
if (stats) {
|
||||
totalTokens += stats.tokens;
|
||||
totalToolCalls += stats.toolCalls;
|
||||
if (stats.model && !defaultModel) defaultModel = stats.model;
|
||||
}
|
||||
agents.push({
|
||||
index: i + 1,
|
||||
label: `agent ${i + 1}`,
|
||||
phaseIndex: 1,
|
||||
phaseTitle: '',
|
||||
model: stats?.model || '',
|
||||
state,
|
||||
agentId: id,
|
||||
tokens: stats ? stats.tokens : undefined,
|
||||
toolCalls: stats ? stats.toolCalls : undefined,
|
||||
lastToolName: stats?.lastToolName,
|
||||
promptPreview: stats?.promptPreview,
|
||||
});
|
||||
}
|
||||
|
||||
// Script meta is immutable for the life of a run, so derive it at most once.
|
||||
// Re-derive only while we still lack a name (the script can land a poll or two
|
||||
// after the first transcripts, which seed the run before the script exists).
|
||||
let meta = this.liveMetaCache.get(live.runId);
|
||||
if (!meta || !meta.workflowName) {
|
||||
meta = await this.deriveLiveWorkflowMeta(live);
|
||||
this.liveMetaCache.set(live.runId, meta);
|
||||
}
|
||||
|
||||
return {
|
||||
runId: live.runId,
|
||||
workflowName: meta.workflowName,
|
||||
summary: meta.summary,
|
||||
status: 'running',
|
||||
agentCount: agents.length,
|
||||
totalTokens,
|
||||
totalToolCalls,
|
||||
defaultModel: defaultModel || undefined,
|
||||
phases: meta.phases,
|
||||
agents,
|
||||
sessionUuid: live.sessionUuid,
|
||||
projectHash: live.projectHash,
|
||||
lastActivityAt: newestMtime || 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse one agent transcript for token/tool stats; cached on the file's mtime. */
|
||||
private async agentTranscriptStats(path: string, mtimeMs: number): Promise<AgentTranscriptStats | null> {
|
||||
// peek (not get) on the hit-check so a cache HIT doesn't churn the LRU — every
|
||||
// active agent is looked up each poll, and get() would delete+reinsert each time.
|
||||
const cached = this.agentStatCache.peek(path);
|
||||
if (cached && cached.mtimeMs === mtimeMs) return cached.stats;
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(path, 'utf-8');
|
||||
} catch {
|
||||
return null; // vanished mid-poll
|
||||
}
|
||||
let tokens = 0;
|
||||
let toolCalls = 0;
|
||||
let model = '';
|
||||
let lastToolName: string | undefined;
|
||||
let promptPreview: string | undefined;
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
let entry: { type?: string; message?: unknown };
|
||||
try {
|
||||
entry = JSON.parse(line) as { type?: string; message?: unknown };
|
||||
} catch {
|
||||
continue; // tolerate a partially-written trailing line
|
||||
}
|
||||
const msg = entry.message as
|
||||
| {
|
||||
model?: string;
|
||||
usage?: {
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
cache_read_input_tokens?: number;
|
||||
cache_creation_input_tokens?: number;
|
||||
};
|
||||
content?: Array<{ type?: string; name?: string; text?: string }> | string;
|
||||
}
|
||||
| undefined;
|
||||
if (!promptPreview && entry.type === 'user' && msg) {
|
||||
promptPreview = truncate(extractMessageText(msg.content), PROMPT_PREVIEW_MAX);
|
||||
}
|
||||
if (!msg || typeof msg !== 'object') continue;
|
||||
if (typeof msg.model === 'string' && msg.model) model = msg.model;
|
||||
const u = msg.usage;
|
||||
if (u) {
|
||||
const total =
|
||||
(u.input_tokens || 0) +
|
||||
(u.output_tokens || 0) +
|
||||
(u.cache_read_input_tokens || 0) +
|
||||
(u.cache_creation_input_tokens || 0);
|
||||
// Anthropic usage already reflects cumulative context, so the agent's running
|
||||
// token total ≈ its LATEST usage-bearing message — last non-zero wins.
|
||||
if (total > 0) tokens = total;
|
||||
}
|
||||
if (Array.isArray(msg.content)) {
|
||||
for (const block of msg.content) {
|
||||
if (block && block.type === 'tool_use' && typeof block.name === 'string') {
|
||||
toolCalls++;
|
||||
lastToolName = block.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const stats: AgentTranscriptStats = { tokens, toolCalls, model, lastToolName, promptPreview };
|
||||
this.agentStatCache.set(path, { mtimeMs, stats });
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the run journal: agent ids in `started` order plus the set that already
|
||||
* logged a terminal `result`. (`started` lines appear in launch order.)
|
||||
*/
|
||||
private async readJournal(
|
||||
journalPath: string,
|
||||
mtimeMs: number
|
||||
): Promise<{ startedOrder: string[]; doneIds: Set<string> }> {
|
||||
const cached = this.journalCache.get(journalPath);
|
||||
if (cached && cached.mtimeMs === mtimeMs) return cached.parsed;
|
||||
const startedOrder: string[] = [];
|
||||
const seenStarted = new Set<string>();
|
||||
const doneIds = new Set<string>();
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(journalPath, 'utf-8');
|
||||
} catch {
|
||||
return { startedOrder, doneIds }; // journal not written yet
|
||||
}
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
try {
|
||||
const ev = JSON.parse(line) as { type?: string; agentId?: string };
|
||||
if (!ev || typeof ev.agentId !== 'string') continue;
|
||||
if (ev.type === 'started' && !seenStarted.has(ev.agentId)) {
|
||||
seenStarted.add(ev.agentId);
|
||||
startedOrder.push(ev.agentId);
|
||||
} else if (ev.type === 'result') {
|
||||
doneIds.add(ev.agentId);
|
||||
}
|
||||
} catch {
|
||||
// tolerate a partially-written trailing line
|
||||
}
|
||||
}
|
||||
const parsed = { startedOrder, doneIds };
|
||||
this.journalCache.set(journalPath, { mtimeMs, parsed });
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive name/summary/phases for a live run from its persisted script file
|
||||
* `…/workflows/scripts/<name>-<runId>.js`. The filename yields a reliable name;
|
||||
* `meta.description`/`meta.phases` are best-effort regex extractions (the script is
|
||||
* JS we must not eval), so any parse miss simply leaves those optional fields absent.
|
||||
*/
|
||||
private async deriveLiveWorkflowMeta(live: DiscoveredLiveRun): Promise<LiveWorkflowMeta> {
|
||||
const empty: LiveWorkflowMeta = { phases: [] };
|
||||
const scriptsDir = join(this.projectsDir, live.projectHash, live.sessionUuid, WORKFLOWS_SUBDIR, SCRIPTS_SUBDIR);
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(scriptsDir);
|
||||
} catch {
|
||||
return empty;
|
||||
}
|
||||
const suffix = `-${live.runId}.js`;
|
||||
const fileName = names.find((n) => n.endsWith(suffix)) || names.find((n) => n.includes(live.runId));
|
||||
if (!fileName) return empty;
|
||||
const nameFromFile = fileName.endsWith(suffix) ? fileName.slice(0, -suffix.length) : fileName.replace(/\.js$/, '');
|
||||
let body = '';
|
||||
try {
|
||||
body = (await readFile(join(scriptsDir, fileName), 'utf-8')).slice(0, SCRIPT_READ_MAX_BYTES);
|
||||
} catch {
|
||||
return { workflowName: nameFromFile || undefined, phases: [] };
|
||||
}
|
||||
// Scope name/summary/phases parsing to the `meta` literal so later script
|
||||
// declarations (schemas, prose) can't be mistaken for it.
|
||||
const metaBlock = extractMetaBlock(body) || body;
|
||||
return {
|
||||
workflowName: nameFromFile || extractMetaString(metaBlock, 'name') || undefined,
|
||||
summary: extractMetaString(metaBlock, 'description') || undefined,
|
||||
phases: extractMetaPhases(metaBlock),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a wf_<runId>.json into WorkflowRunInfo, STRIPPING the heavyweight
|
||||
* `script`/`scriptPath`/`result`/`logs` fields (the embedded script alone is
|
||||
* 15–660KB) so they never reach the cache, SSE, or routes.
|
||||
*/
|
||||
private async parseFile(file: DiscoveredRun): Promise<WorkflowRunInfo | null> {
|
||||
let raw: Record<string, unknown>;
|
||||
try {
|
||||
raw = JSON.parse(await readFile(file.filePath, 'utf-8')) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null; // mid-write or malformed — next mtime change re-parses
|
||||
}
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
|
||||
const progress = Array.isArray(raw.workflowProgress) ? (raw.workflowProgress as RawProgressEntry[]) : [];
|
||||
const agents: WorkflowAgentInfo[] = progress
|
||||
.filter((e) => e && e.type === 'workflow_agent')
|
||||
.map((e) => this.toAgent(e));
|
||||
|
||||
const phases: WorkflowRunPhase[] = Array.isArray(raw.phases)
|
||||
? (raw.phases as Array<Record<string, unknown>>).map((p) => ({
|
||||
title: typeof p.title === 'string' ? p.title : '',
|
||||
detail: typeof p.detail === 'string' ? p.detail : '',
|
||||
}))
|
||||
: [];
|
||||
|
||||
let lastProgress = 0;
|
||||
for (const a of agents) {
|
||||
if (typeof a.lastProgressAt === 'number' && a.lastProgressAt > lastProgress) lastProgress = a.lastProgressAt;
|
||||
}
|
||||
const startTime = typeof raw.startTime === 'number' ? raw.startTime : undefined;
|
||||
const lastActivityAt = lastProgress || startTime || 0;
|
||||
|
||||
return {
|
||||
runId: typeof raw.runId === 'string' ? raw.runId : file.runId,
|
||||
workflowName: typeof raw.workflowName === 'string' ? raw.workflowName : undefined,
|
||||
status: typeof raw.status === 'string' ? raw.status : undefined,
|
||||
summary: typeof raw.summary === 'string' ? raw.summary : undefined,
|
||||
agentCount: typeof raw.agentCount === 'number' ? raw.agentCount : undefined,
|
||||
totalTokens: typeof raw.totalTokens === 'number' ? raw.totalTokens : undefined,
|
||||
totalToolCalls: typeof raw.totalToolCalls === 'number' ? raw.totalToolCalls : undefined,
|
||||
durationMs: typeof raw.durationMs === 'number' ? raw.durationMs : undefined,
|
||||
startTime,
|
||||
timestamp: typeof raw.timestamp === 'string' ? raw.timestamp : undefined,
|
||||
defaultModel: typeof raw.defaultModel === 'string' ? raw.defaultModel : undefined,
|
||||
taskId: typeof raw.taskId === 'string' ? raw.taskId : undefined,
|
||||
error: typeof raw.error === 'string' ? raw.error : undefined,
|
||||
phases,
|
||||
agents,
|
||||
sessionUuid: file.sessionUuid,
|
||||
projectHash: file.projectHash,
|
||||
lastActivityAt,
|
||||
};
|
||||
}
|
||||
|
||||
private toAgent(e: RawProgressEntry): WorkflowAgentInfo {
|
||||
return {
|
||||
index: typeof e.index === 'number' ? e.index : 0,
|
||||
label: typeof e.label === 'string' ? e.label : '',
|
||||
phaseIndex: typeof e.phaseIndex === 'number' ? e.phaseIndex : 0,
|
||||
phaseTitle: typeof e.phaseTitle === 'string' ? e.phaseTitle : '',
|
||||
model: typeof e.model === 'string' ? e.model : '',
|
||||
state: typeof e.state === 'string' ? e.state : 'start',
|
||||
queuedAt: e.queuedAt,
|
||||
lastProgressAt: e.lastProgressAt,
|
||||
promptPreview: truncate(e.promptPreview, PROMPT_PREVIEW_MAX),
|
||||
agentId: e.agentId,
|
||||
startedAt: e.startedAt,
|
||||
attempt: e.attempt,
|
||||
tokens: e.tokens,
|
||||
toolCalls: e.toolCalls,
|
||||
lastToolName: e.lastToolName,
|
||||
lastToolSummary: truncate(e.lastToolSummary, RESULT_PREVIEW_MAX),
|
||||
durationMs: e.durationMs,
|
||||
resultPreview: truncate(e.resultPreview, RESULT_PREVIEW_MAX),
|
||||
};
|
||||
}
|
||||
|
||||
private ensureDirWatcher(workflowsDir: string): void {
|
||||
if (this.dirWatchers.has(workflowsDir)) return;
|
||||
try {
|
||||
const watcher = chokidarWatch(workflowsDir, {
|
||||
depth: 0,
|
||||
awaitWriteFinish: { stabilityThreshold: 200 },
|
||||
ignoreInitial: true,
|
||||
persistent: false,
|
||||
});
|
||||
const handler = () => this.poll();
|
||||
watcher.on('add', handler);
|
||||
watcher.on('change', handler);
|
||||
watcher.on('unlink', handler);
|
||||
// subagents/workflows/ children are wf_<id>/ DIRS — catch their add/remove too.
|
||||
watcher.on('addDir', handler);
|
||||
watcher.on('unlinkDir', handler);
|
||||
watcher.on('error', () => {
|
||||
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
|
||||
this.removeDirWatcher(workflowsDir);
|
||||
});
|
||||
this.dirWatchers.set(workflowsDir, watcher);
|
||||
} catch {
|
||||
// Watch setup failed — periodic poll still discovers changes.
|
||||
}
|
||||
}
|
||||
|
||||
private removeDirWatcher(workflowsDir: string): void {
|
||||
const watcher = this.dirWatchers.get(workflowsDir);
|
||||
if (watcher) {
|
||||
watcher.close().catch(() => {});
|
||||
this.dirWatchers.delete(workflowsDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Process-wide singleton (mirrors subagentWatcher / imageWatcher). */
|
||||
export const workflowRunWatcher = new WorkflowRunWatcher();
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Session } from '../src/session.js';
|
||||
import { parseAttachmentMagicLinks } from '../src/attachment-magic.js';
|
||||
|
||||
describe('attachment magic links', () => {
|
||||
it('extracts absolute paths from codeman attach magic URLs', () => {
|
||||
const links = parseAttachmentMagicLinks(
|
||||
'Preview this: codeman://attach?path=%2Fmnt%2Fc%2FDecks%2FBoard%20Update.pptx'
|
||||
);
|
||||
|
||||
expect(links).toEqual(['/mnt/c/Decks/Board Update.pptx']);
|
||||
});
|
||||
|
||||
it('ignores duplicate links in one terminal chunk', () => {
|
||||
const links = parseAttachmentMagicLinks(
|
||||
[
|
||||
'codeman://attach?path=/tmp/report.pdf',
|
||||
'codeman://attach?path=/tmp/report.pdf',
|
||||
'codeman://attach?path=/tmp/brief.docx',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
expect(links).toEqual(['/tmp/report.pdf', '/tmp/brief.docx']);
|
||||
});
|
||||
|
||||
it('accepts markdown and plain-text magic paths', () => {
|
||||
const links = parseAttachmentMagicLinks(
|
||||
['codeman://attach?path=/tmp/notes.md', 'codeman://attach?path=/tmp/run.txt'].join('\n')
|
||||
);
|
||||
|
||||
expect(links).toEqual(['/tmp/notes.md', '/tmp/run.txt']);
|
||||
});
|
||||
|
||||
it('rejects relative or unsupported magic paths', () => {
|
||||
const links = parseAttachmentMagicLinks(
|
||||
[
|
||||
'codeman://attach?path=relative.pdf',
|
||||
'codeman://attach?path=/tmp/archive.zip',
|
||||
'codeman://attach?path=/tmp/deck.pptx',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
expect(links).toEqual(['/tmp/deck.pptx']);
|
||||
});
|
||||
|
||||
it('emits attachmentRequested from raw terminal output', () => {
|
||||
const session = new Session({ id: 'session-attach-test', workingDir: '/tmp', mode: 'codex' });
|
||||
const requested: string[] = [];
|
||||
session.on('attachmentRequested', (event: { path: string }) => requested.push(event.path));
|
||||
|
||||
(session as unknown as { _handleTerminalOutput(data: string): void })._handleTerminalOutput(
|
||||
'codeman://attach?path=%2Ftmp%2Fdeck.pptx'
|
||||
);
|
||||
|
||||
expect(requested).toEqual(['/tmp/deck.pptx']);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi }
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
import { TmuxManager } from '../src/tmux-manager.js';
|
||||
import { SettingsUpdateSchema } from '../src/web/schemas.js';
|
||||
import { getHookSecret, HOOK_SECRET_HEADER } from '../src/config/hook-secret.js';
|
||||
|
||||
const AUTH_PORT = 3160;
|
||||
const NOAUTH_PORT = 3161;
|
||||
@@ -250,28 +251,28 @@ describe('Auth Security', () => {
|
||||
});
|
||||
|
||||
describe('Hook Event Endpoint', () => {
|
||||
it('should allow hook events from localhost without auth', async () => {
|
||||
it('should allow hook events from localhost with the hook secret (no Basic auth)', async () => {
|
||||
const res = await fetch(`${baseUrl}/api/hook-event`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', [HOOK_SECRET_HEADER]: getHookSecret() },
|
||||
body: JSON.stringify({
|
||||
event: 'stop',
|
||||
sessionId: 'nonexistent-session',
|
||||
data: {},
|
||||
}),
|
||||
});
|
||||
// Should pass auth (localhost bypass) but may 404 on session — that's fine
|
||||
// The key assertion is it does NOT return 401
|
||||
// Should pass auth (localhost bypass + hook secret) but may 404 on session — that's fine.
|
||||
// The key assertion is it does NOT return 401 (COD-91: secret required even with no tunnel).
|
||||
expect(res.status).not.toBe(401);
|
||||
});
|
||||
|
||||
it('should reject hook events with invalid schema', async () => {
|
||||
const res = await fetch(`${baseUrl}/api/hook-event`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', [HOOK_SECRET_HEADER]: getHookSecret() },
|
||||
body: JSON.stringify({ invalid: 'data' }),
|
||||
});
|
||||
// Schema validation should catch this
|
||||
// Past the auth gate (valid secret) → schema validation should catch this (not a 401).
|
||||
expect(res.status).not.toBe(401); // Not an auth error
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Session, isAltScreenStripMode } from '../src/session.js';
|
||||
|
||||
type SessionInternals = {
|
||||
_handleTerminalOutput(data: string): void;
|
||||
};
|
||||
|
||||
function handleOutput(session: Session, data: string): void {
|
||||
(session as unknown as SessionInternals)._handleTerminalOutput(data);
|
||||
}
|
||||
|
||||
describe('isAltScreenStripMode', () => {
|
||||
it('strips for the controlled TUIs (codex + claude), not shell/opencode', () => {
|
||||
expect(isAltScreenStripMode('codex')).toBe(true);
|
||||
expect(isAltScreenStripMode('claude')).toBe(true);
|
||||
expect(isAltScreenStripMode('shell')).toBe(false);
|
||||
expect(isAltScreenStripMode('opencode')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Claude terminal scrollback strip', () => {
|
||||
it('strips alt-screen toggles, scrollback-erase, and mouse-tracking', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
handleOutput(session, '\x1b[?1049h\x1b[55;1Hdialog\x1b[3J\x1b[?1006h\x1b[?1049l');
|
||||
|
||||
expect(emitted[0]).toBe('\x1b[55;1Hdialog');
|
||||
expect(session.terminalBuffer).toBe('\x1b[55;1Hdialog');
|
||||
});
|
||||
|
||||
it('keeps the visible-screen erase (2J / [J) — only scrollback-erase (3J) is dropped', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
|
||||
handleOutput(session, '\x1b[?1049h\x1b[2Jvisible\x1b[3Jscrollback\x1b[?1049l');
|
||||
|
||||
expect(session.terminalBuffer).toBe('\x1b[2Jvisiblescrollback');
|
||||
});
|
||||
|
||||
it('preserves an ordinary erase-display redraw (no scrollback sequences)', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
|
||||
handleOutput(session, '\x1b[H\x1b[Jclaude redraw');
|
||||
|
||||
expect(session.terminalBuffer).toBe('\x1b[H\x1b[Jclaude redraw');
|
||||
});
|
||||
|
||||
it('strips sequences split across PTY chunk boundaries (carry reassembly)', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
handleOutput(session, 'before\x1b[?104');
|
||||
handleOutput(session, '9h\x1b[2Jafter\x1b[3');
|
||||
handleOutput(session, 'Jtail');
|
||||
|
||||
expect(session.terminalBuffer).toBe('before\x1b[2Jaftertail');
|
||||
expect(emitted).toEqual(['before', '\x1b[2Jafter', 'tail']);
|
||||
});
|
||||
|
||||
it('emits nothing for a chunk that is only a partial CSI, then completes it', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
handleOutput(session, '\x1b[?100'); // pure partial — held, nothing emitted
|
||||
handleOutput(session, '6h done'); // completes ?1006h (stripped); rest passes
|
||||
|
||||
expect(emitted).toEqual([' done']);
|
||||
expect(session.terminalBuffer).toBe(' done');
|
||||
});
|
||||
|
||||
it('does not touch ordinary Claude conversation output', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
|
||||
const text = 'Here is line one\r\nHere is line two\r\n\x1b[2mdim status\x1b[0m';
|
||||
handleOutput(session, text);
|
||||
|
||||
expect(session.terminalBuffer).toBe(text);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Shell terminal output is NOT stripped (vim/less/htop need the alt screen)', () => {
|
||||
it('leaves alt-screen toggles, scrollback-erase, and mouse-tracking intact for shell', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'shell' });
|
||||
|
||||
const vimLike = '\x1b[?1049h\x1b[?1002h\x1b[2J~ editing\x1b[3J\x1b[?1002l\x1b[?1049l';
|
||||
handleOutput(session, vimLike);
|
||||
|
||||
expect(session.terminalBuffer).toBe(vimLike);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* @fileoverview COD-54 — hook-event auth bypass hardening.
|
||||
*
|
||||
* The `/api/hook-event` localhost bypass let tunnel traffic (cloudflared
|
||||
* --url http://127.0.0.1:port) reach the loopback origin with req.ip ===
|
||||
* 127.0.0.1 and drive respawn/Ralph signals unauthenticated. The fix gates
|
||||
* the bypass behind a shared hook secret. COD-91 makes that requirement
|
||||
* UNCONDITIONAL — the loopback bypass requires the secret whether or not a
|
||||
* managed tunnel is running, because Codeman can't detect a user's own loopback
|
||||
* reverse proxy (own cloudflared / `tailscale serve` / nginx → 127.0.0.1).
|
||||
* Managed-session hooks always present the secret, so the legitimate channel
|
||||
* keeps working.
|
||||
*
|
||||
* Tests:
|
||||
* - tunnel running + no secret → 401 (closes the hole)
|
||||
* - tunnel running + bad secret → 401
|
||||
* - tunnel running + good secret → not 401 (allowed)
|
||||
* - tunnel NOT running + no secret → 401 (COD-91: secret required unconditionally)
|
||||
* - tunnel NOT running + good secret → not 401 (allowed)
|
||||
* - rate limiting: rapid unauthorized hook POSTs eventually 429
|
||||
*
|
||||
* Port: 3230 (tunnel-running), 3231 (tunnel-down), 3232 (rate-limit)
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
import { TmuxManager } from '../src/tmux-manager.js';
|
||||
import { TunnelManager } from '../src/tunnel-manager.js';
|
||||
import { getHookSecret, HOOK_SECRET_HEADER } from '../src/config/hook-secret.js';
|
||||
import { AUTH_FAILURE_MAX } from '../src/config/auth-config.js';
|
||||
|
||||
const TUNNEL_UP_PORT = 3230;
|
||||
const TUNNEL_DOWN_PORT = 3231;
|
||||
const RATE_LIMIT_PORT = 3232;
|
||||
const TEST_USER = 'admin';
|
||||
const TEST_PASS = 'cod54-test-password';
|
||||
|
||||
vi.spyOn(TmuxManager, 'isTmuxAvailable').mockReturnValue(true);
|
||||
|
||||
function hookBody(): string {
|
||||
return JSON.stringify({ event: 'stop', sessionId: 'nonexistent-session', data: {} });
|
||||
}
|
||||
|
||||
async function postHook(baseUrl: string, headers: Record<string, string> = {}): Promise<Response> {
|
||||
return fetch(`${baseUrl}/api/hook-event`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body: hookBody(),
|
||||
});
|
||||
}
|
||||
|
||||
describe('COD-54 hook-event auth — tunnel running requires secret', () => {
|
||||
let server: WebServer;
|
||||
let baseUrl: string;
|
||||
let isRunningSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.CODEMAN_PASSWORD = TEST_PASS;
|
||||
process.env.CODEMAN_USERNAME = TEST_USER;
|
||||
// Force the middleware's tunnel check to report "running".
|
||||
isRunningSpy = vi.spyOn(TunnelManager.prototype, 'isRunning').mockReturnValue(true);
|
||||
server = new WebServer(TUNNEL_UP_PORT, false, true);
|
||||
await server.start();
|
||||
baseUrl = `http://localhost:${TUNNEL_UP_PORT}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.stop();
|
||||
isRunningSpy.mockRestore();
|
||||
delete process.env.CODEMAN_PASSWORD;
|
||||
delete process.env.CODEMAN_USERNAME;
|
||||
});
|
||||
|
||||
it('rejects a localhost hook POST WITHOUT the secret header (closes the tunnel hole)', async () => {
|
||||
const res = await postHook(baseUrl);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('rejects a localhost hook POST with a WRONG secret', async () => {
|
||||
const res = await postHook(baseUrl, { [HOOK_SECRET_HEADER]: 'wrong-secret-value' });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('allows a localhost hook POST WITH the correct secret', async () => {
|
||||
const res = await postHook(baseUrl, { [HOOK_SECRET_HEADER]: getHookSecret() });
|
||||
// Passes auth (may 200 with success:false for unknown session) — key is NOT 401.
|
||||
expect(res.status).not.toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('COD-91 hook-event auth — tunnel down ALSO requires the secret', () => {
|
||||
let server: WebServer;
|
||||
let baseUrl: string;
|
||||
let isRunningSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.CODEMAN_PASSWORD = TEST_PASS;
|
||||
process.env.CODEMAN_USERNAME = TEST_USER;
|
||||
// Tunnel NOT running — loopback-only normal prod case.
|
||||
isRunningSpy = vi.spyOn(TunnelManager.prototype, 'isRunning').mockReturnValue(false);
|
||||
server = new WebServer(TUNNEL_DOWN_PORT, false, true);
|
||||
await server.start();
|
||||
baseUrl = `http://localhost:${TUNNEL_DOWN_PORT}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.stop();
|
||||
isRunningSpy.mockRestore();
|
||||
delete process.env.CODEMAN_PASSWORD;
|
||||
delete process.env.CODEMAN_USERNAME;
|
||||
});
|
||||
|
||||
it('rejects a localhost hook POST WITHOUT a secret even with no tunnel (COD-91)', async () => {
|
||||
const res = await postHook(baseUrl);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('allows a localhost hook POST WITH the correct secret when no tunnel is running', async () => {
|
||||
const res = await postHook(baseUrl, { [HOOK_SECRET_HEADER]: getHookSecret() });
|
||||
expect(res.status).not.toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('COD-54 hook-event auth — rate limiting', () => {
|
||||
let server: WebServer;
|
||||
let baseUrl: string;
|
||||
let isRunningSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.CODEMAN_PASSWORD = TEST_PASS;
|
||||
process.env.CODEMAN_USERNAME = TEST_USER;
|
||||
// Tunnel running so unauthorized (no-secret) hook POSTs are rejected and counted.
|
||||
isRunningSpy = vi.spyOn(TunnelManager.prototype, 'isRunning').mockReturnValue(true);
|
||||
server = new WebServer(RATE_LIMIT_PORT, false, true);
|
||||
await server.start();
|
||||
baseUrl = `http://localhost:${RATE_LIMIT_PORT}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.stop();
|
||||
isRunningSpy.mockRestore();
|
||||
delete process.env.CODEMAN_PASSWORD;
|
||||
delete process.env.CODEMAN_USERNAME;
|
||||
});
|
||||
|
||||
it('eventually returns 429 for rapid unauthorized hook POSTs', async () => {
|
||||
let saw429 = false;
|
||||
// A few more than the failure max to cross the threshold.
|
||||
for (let i = 0; i < AUTH_FAILURE_MAX + 3; i++) {
|
||||
const res = await postHook(baseUrl);
|
||||
if (res.status === 429) {
|
||||
saw429 = true;
|
||||
expect(res.headers.get('retry-after')).toMatch(/^\d+$/);
|
||||
break;
|
||||
}
|
||||
expect(res.status).toBe(401);
|
||||
}
|
||||
expect(saw429).toBe(true);
|
||||
});
|
||||
|
||||
it('hook-secret failures do NOT lock out the Basic-Auth login path (separate bucket)', async () => {
|
||||
// The previous test exhausted the hook bucket for 127.0.0.1. Legacy (pre-secret)
|
||||
// hooks fire constantly, so if they shared authFailures, every cookie-less
|
||||
// request from loopback would now 429 — locking out login (and, via a tunnel,
|
||||
// every client). Assert the login path is unaffected:
|
||||
// 1. A credential-less request still gets a 401 challenge, NOT 429.
|
||||
const unauthed = await fetch(`${baseUrl}/api/status`);
|
||||
expect(unauthed.status).toBe(401);
|
||||
// 2. Correct Basic credentials still authenticate.
|
||||
const authed = await fetch(`${baseUrl}/api/status`, {
|
||||
headers: { Authorization: 'Basic ' + Buffer.from(`${TEST_USER}:${TEST_PASS}`).toString('base64') },
|
||||
});
|
||||
expect(authed.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('COD-54 secret delivery — generated hooks + session env present the secret', () => {
|
||||
it('generated hook curl commands send the secret header, read from the file at exec time', async () => {
|
||||
const { generateHooksConfig } = await import('../src/hooks-config.js');
|
||||
const config = generateHooksConfig();
|
||||
const commands = JSON.stringify(config);
|
||||
// Header present, value sourced from $CODEMAN_HOOK_SECRET_FILE (not embedded).
|
||||
expect(commands).toContain(HOOK_SECRET_HEADER);
|
||||
expect(commands).toContain('$CODEMAN_HOOK_SECRET_FILE');
|
||||
expect(commands).not.toContain(getHookSecret());
|
||||
});
|
||||
|
||||
it('session env builders export CODEMAN_HOOK_SECRET_FILE (path only, never the value)', async () => {
|
||||
const { buildClaudeEnv, buildShellEnv } = await import('../src/session-cli-builder.js');
|
||||
const claudeEnv = buildClaudeEnv('test-session');
|
||||
const shellEnv = buildShellEnv('test-session');
|
||||
expect(claudeEnv.CODEMAN_HOOK_SECRET_FILE).toMatch(/hook-secret$/);
|
||||
expect(shellEnv.CODEMAN_HOOK_SECRET_FILE).toMatch(/hook-secret$/);
|
||||
expect(JSON.stringify(claudeEnv)).not.toContain(getHookSecret());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// Structural tests for the xterm snapshot/replay slice (COD-81). app.js has no
|
||||
// bundler and is hard to drive through a real DOM, so — following the repo's
|
||||
// existing pattern for app.js — these assert the source structure that makes
|
||||
// the snapshot first-paint correct rather than executing it.
|
||||
describe('xterm snapshot/replay (codex tab-switch)', () => {
|
||||
const appSource = () => readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
|
||||
|
||||
it('rejects blank xterm snapshots before saving or restoring them', () => {
|
||||
const source = appSource();
|
||||
const helper = source.indexOf('_isUsableXtermSnapshot(snapshot)');
|
||||
const save = source.indexOf('this._xtermSnapshots.set(this.activeSessionId, snapshot)');
|
||||
const restore = source.indexOf('SNAPSHOT_RESTORE:', save);
|
||||
const restoreBlock = source.slice(save, restore);
|
||||
|
||||
expect(helper).toBeGreaterThan(-1);
|
||||
// The save is gated on a usability check immediately above it.
|
||||
const usabilityGate = source.lastIndexOf('if (this._isUsableXtermSnapshot(snapshot))', save);
|
||||
expect(usabilityGate).toBeGreaterThan(-1);
|
||||
expect(usabilityGate).toBeLessThan(save);
|
||||
// …and so is each restore path (in-memory + persisted).
|
||||
expect(restoreBlock).toContain('if (snapshot && !this._isUsableXtermSnapshot(snapshot))');
|
||||
expect(restoreBlock).toContain('persisted && this._isUsableXtermSnapshot(persisted)');
|
||||
});
|
||||
|
||||
it('declares the snapshot-restore flag before selectSession uses it', () => {
|
||||
const source = appSource();
|
||||
const selectStart = source.indexOf('async selectSession(sessionId, options = {})');
|
||||
const declaration = source.indexOf('let restoredSnapshot = false;', selectStart);
|
||||
const snapshotBranch = source.indexOf("if (snapshot && !sessionIsBusy && session?.mode !== 'shell')", selectStart);
|
||||
const rewriteDecision = source.indexOf(
|
||||
'restoredSnapshot || clearedForBusy || data.terminalBuffer !== cachedBuffer',
|
||||
selectStart
|
||||
);
|
||||
|
||||
expect(selectStart).toBeGreaterThan(-1);
|
||||
expect(declaration).toBeGreaterThan(selectStart);
|
||||
expect(declaration).toBeLessThan(snapshotBranch);
|
||||
expect(declaration).toBeLessThan(rewriteDecision);
|
||||
});
|
||||
|
||||
it('uses xterm snapshots as first paint but still fetches the canonical terminal frame', () => {
|
||||
const source = appSource();
|
||||
const snapshotRestore = source.indexOf('SNAPSHOT_RESTORE:');
|
||||
const cacheRestore = source.indexOf('Instant cache restore', snapshotRestore);
|
||||
const fetchStart = source.indexOf("FETCH_START'", snapshotRestore);
|
||||
const needsRewrite = source.indexOf('const needsRewrite', fetchStart);
|
||||
const snapshotBlock = source.slice(snapshotRestore, cacheRestore);
|
||||
const postSnapshotRestore = source.slice(snapshotRestore, needsRewrite + 160);
|
||||
|
||||
expect(snapshotRestore).toBeGreaterThan(-1);
|
||||
expect(cacheRestore).toBeGreaterThan(snapshotRestore);
|
||||
expect(fetchStart).toBeGreaterThan(cacheRestore);
|
||||
expect(needsRewrite).toBeGreaterThan(fetchStart);
|
||||
// Snapshot restore must NOT short-circuit the canonical fetch.
|
||||
expect(snapshotBlock).not.toContain('this._finishBufferLoad();');
|
||||
expect(postSnapshotRestore).toContain('restoredSnapshot');
|
||||
expect(postSnapshotRestore).toContain('restoredSnapshot || clearedForBusy || data.terminalBuffer !== cachedBuffer');
|
||||
});
|
||||
|
||||
it('forces replay after clearing a busy tab even when the fetched frame matches cache', () => {
|
||||
const source = appSource();
|
||||
const cacheRestore = source.indexOf('Instant cache restore');
|
||||
const busyClear = source.indexOf('CACHE_SKIP_BUSY', cacheRestore);
|
||||
const needsRewrite = source.indexOf('const needsRewrite', busyClear);
|
||||
const replayBlock = source.slice(cacheRestore, needsRewrite + 160);
|
||||
|
||||
expect(cacheRestore).toBeGreaterThan(-1);
|
||||
expect(busyClear).toBeGreaterThan(cacheRestore);
|
||||
expect(needsRewrite).toBeGreaterThan(busyClear);
|
||||
expect(replayBlock).toContain('clearedForBusy');
|
||||
expect(replayBlock).toContain('restoredSnapshot || clearedForBusy || data.terminalBuffer !== cachedBuffer');
|
||||
});
|
||||
|
||||
it('loads the SerializeAddon and keeps a per-session snapshot map', () => {
|
||||
const terminalSource = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
|
||||
expect(terminalSource).toContain('this._xtermSnapshots = new Map()');
|
||||
expect(terminalSource).toContain('new SerializeAddon.SerializeAddon()');
|
||||
expect(terminalSource).toContain('this.terminal.loadAddon(this._serializeAddon)');
|
||||
});
|
||||
|
||||
it('evicts the in-memory snapshot cache and persists with a bounded localStorage budget', () => {
|
||||
const source = appSource();
|
||||
// In-memory cache is LRU-bounded…
|
||||
expect(source).toContain('if (this._xtermSnapshots.size > 20)');
|
||||
// …per-snapshot localStorage writes are size-capped…
|
||||
expect(source).toContain('snapshot.length < 256 * 1024');
|
||||
// …and the persisted key set is pruned of dead sessions.
|
||||
expect(source).toContain("k.startsWith('codeman-xs-')");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Session } from '../src/session.js';
|
||||
|
||||
type SessionInternals = {
|
||||
_handleTerminalOutput(data: string): void;
|
||||
_ptyRows: number;
|
||||
};
|
||||
|
||||
function handleOutput(session: Session, data: string): void {
|
||||
(session as unknown as SessionInternals)._handleTerminalOutput(data);
|
||||
}
|
||||
|
||||
describe('Codex terminal output filtering', () => {
|
||||
it('keeps browser scrollback guards but skips Codeman row repair in hybrid render mode', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex', codexConfig: { renderMode: 'hybrid' } });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
const hybridRedraw = '\x1b[?1049h\x1b[55;1H\x1b[2m• Working (21s)\x1b[3J\x1b[?1006h\x1b[?1049l';
|
||||
|
||||
handleOutput(session, hybridRedraw);
|
||||
|
||||
expect(emitted[0]).toBe('\x1b[55;1H\x1b[2m• Working (21s)');
|
||||
expect(emitted[0]).not.toContain('\x1b[55;1H\x1b[2K');
|
||||
expect(session.terminalBuffer).toBe(emitted[0]);
|
||||
});
|
||||
|
||||
it('preserves Codex erase-display redraws used by the TUI layout engine', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
|
||||
handleOutput(session, '\x1b[H\x1b[Jidle redraw');
|
||||
|
||||
expect(session.terminalBuffer).toBe('\x1b[H\x1b[Jidle redraw');
|
||||
});
|
||||
|
||||
it('strips Codex scrollback erase without stripping visible-screen erase', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
|
||||
handleOutput(session, '\x1b[?1049h\x1b[2Jvisible\x1b[3Jscrollback\x1b[?1049l');
|
||||
|
||||
expect(session.terminalBuffer).toBe('\x1b[2Jvisiblescrollback');
|
||||
});
|
||||
|
||||
it('strips sequences split across PTY chunk boundaries (carry reassembly)', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
// '\x1b[?1049h' split mid-sequence, then '\x1b[3J' split before its final byte.
|
||||
handleOutput(session, 'before\x1b[?104');
|
||||
handleOutput(session, '9h\x1b[2Jafter\x1b[3');
|
||||
handleOutput(session, 'Jtail');
|
||||
|
||||
expect(session.terminalBuffer).toBe('before\x1b[2Jaftertail');
|
||||
expect(emitted).toEqual(['before', '\x1b[2Jafter', 'tail']);
|
||||
});
|
||||
|
||||
it('emits nothing for a chunk that is only a partial CSI, and completes it next chunk', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
handleOutput(session, '\x1b[?100'); // pure partial — held, nothing emitted
|
||||
handleOutput(session, '6h\x1b[55;1H• Working'); // completes ?1006h (stripped); rest passes
|
||||
|
||||
expect(emitted).toEqual(['\x1b[55;1H• Working']);
|
||||
expect(session.terminalBuffer).toBe('\x1b[55;1H• Working');
|
||||
});
|
||||
|
||||
it('preserves Codex erase-display redraw when the user pressed Ctrl+L', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
|
||||
session.write('\x0c');
|
||||
handleOutput(session, '\x1b[H\x1b[Jredraw after clear');
|
||||
|
||||
expect(session.terminalBuffer).toBe('\x1b[H\x1b[Jredraw after clear');
|
||||
});
|
||||
|
||||
it('passes native Codex TUI prompt/status redraws through without row repair', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const bottomBandRedraw =
|
||||
'\x1b[48;2;42;42;42m' +
|
||||
'\x1b[60;2H\x1b[K' +
|
||||
'\x1b[61;39H\x1b[K' +
|
||||
'\x1b[62;2H\x1b[K' +
|
||||
'\x1b[52;1H\x1b[49m\x1b[2m• \x1b[1mRunning node -e ...' +
|
||||
'\x1b[60;1H\x1b[48;2;42;42;42m \r\n' +
|
||||
'\x1b[1m›\x1b[0m\x1b[48;2;42;42;42m \x1b[2mUse /skills to list available skills\r\n' +
|
||||
'\x1b[63;3H\x1b[49m\x1b[38;2;246;226;183mgpt-5.5 xhigh\x1b[39m' +
|
||||
'\x1b[2m · \x1b[38;2;242;181;144mContext 42% left\x1b[39m' +
|
||||
'\x1b[61;3H';
|
||||
|
||||
handleOutput(session, bottomBandRedraw);
|
||||
|
||||
expect(emitted[0]).not.toContain('\x1b[52;1H\x1b[2K');
|
||||
expect(emitted[0]).not.toContain('\x1b[60;1H\x1b[2K');
|
||||
expect(emitted[0]).not.toContain('\x1b[63;1H\x1b[2K');
|
||||
expect(emitted[0]).toContain(bottomBandRedraw);
|
||||
});
|
||||
|
||||
it('passes Codex advisory rows through without row repair', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const advisoryRedraw =
|
||||
'\x1b[55;1H\x1b[2mMessages\x1b[Cto\x1b[Cbe submitted\x1b[Cafter\x1b[Cnext toolcall ' +
|
||||
'(press esc to interrupt and send immediately)\x1b[56;1H';
|
||||
|
||||
handleOutput(session, advisoryRedraw);
|
||||
|
||||
expect(emitted[0]).not.toContain('\x1b[55;1H\x1b[2K');
|
||||
expect(emitted[0]).toContain(advisoryRedraw);
|
||||
});
|
||||
|
||||
it('does not clear Codex resume-picker rows just because an option is selected', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const resumePickerRedraw =
|
||||
'\x1b[1;2H\x1b[36m\x1b[1mResume a previous session' +
|
||||
'\x1b[3;2H\x1b[2mType to search Filter: \x1b[35m[Cwd]\x1b[39m\x1b[2m All' +
|
||||
'\x1b[5;3H\x1b[33m\x1b[48;2;42;42;42m\x1b[1m❯ \x1b[2m22h ago ll' +
|
||||
'\x1b[6;3H\x1b[2m 1d ago $kb-health' +
|
||||
'\x1b[60;1H\x1b[2m──── 2 / 2 · 100% ─' +
|
||||
'\x1b[61;1H enter resume esc exit ↑/↓ browse';
|
||||
|
||||
handleOutput(session, resumePickerRedraw);
|
||||
|
||||
expect(emitted[0]).not.toContain('\x1b[4;1H\x1b[2K');
|
||||
expect(emitted[0]).not.toContain('\x1b[5;1H\x1b[2K');
|
||||
expect(emitted[0]).toContain(resumePickerRedraw);
|
||||
});
|
||||
|
||||
it('does not full-clear sparse Codex resume-picker navigation redraws', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
let sparseResumePickerRedraw = '';
|
||||
for (let row = 1; row <= 51; row++) {
|
||||
const col = row % 2 === 0 ? 239 : 27;
|
||||
sparseResumePickerRedraw += `\x1b[${row};${col}H\x1b[K`;
|
||||
}
|
||||
sparseResumePickerRedraw +=
|
||||
'\x1b[21;3H \x1b[2m9d ago \x1b[mreview this webex room webexteams://im?space=672465b0-4fcb-11f1-9d54-51475df86e3a\x1b[K' +
|
||||
'\x1b[22;3H\x1b[33m\x1b[1m❯ \x1b[m\x1b[33m\x1b[2m9d ago \x1b[m\x1b[33mcisco hybrid mesh firewall includes support for smart switch enforcement...\x1b[K' +
|
||||
'\x1b[52;229H\x1b[39m\x1b[2m8\x1b[m';
|
||||
|
||||
handleOutput(session, sparseResumePickerRedraw);
|
||||
|
||||
expect(emitted[0]).not.toContain('\x1b[H\x1b[2J');
|
||||
expect(emitted[0]).toContain(sparseResumePickerRedraw);
|
||||
});
|
||||
|
||||
it('passes Codex UI rows through when the status band moves downward', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
handleOutput(
|
||||
session,
|
||||
'\x1b[55;1H\x1b[2m• Working (1s)\x1b[56;1H\x1b[1m›\x1b[0m ask\x1b[57;3Hgpt-5.5 · Context 80% left'
|
||||
);
|
||||
handleOutput(
|
||||
session,
|
||||
'\x1b[58;1H\x1b[2m• Working (2s)\x1b[59;1H\x1b[1m›\x1b[0m ask\x1b[60;3Hgpt-5.5 · Context 79% left'
|
||||
);
|
||||
|
||||
expect(emitted[1]).not.toContain('\x1b[55;1H\x1b[2K');
|
||||
expect(emitted[1]).not.toContain('\x1b[56;1H\x1b[2K');
|
||||
expect(emitted[1]).not.toContain('\x1b[57;1H\x1b[2K');
|
||||
expect(emitted[1]).toContain('\x1b[58;1H');
|
||||
expect(emitted[1]).not.toContain('\x1b[54;1H\x1b[2K');
|
||||
});
|
||||
|
||||
it('does not full-clear the viewport for stable Codex UI rows at the same position', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const stableRedraw =
|
||||
'\x1b[58;1H\x1b[2m• Working (2s)\x1b[59;1H\x1b[1m›\x1b[0m ask\x1b[60;3Hgpt-5.5 · Context 79% left';
|
||||
|
||||
handleOutput(session, stableRedraw);
|
||||
handleOutput(session, stableRedraw.replace('2s', '3s'));
|
||||
|
||||
expect(emitted[1]).not.toContain('\x1b[H\x1b[2J');
|
||||
});
|
||||
|
||||
it('passes status-only Codex Working redraw rows through', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const workingRedraw = '\x1b[55;1H\x1b[2m• Working (21s)';
|
||||
|
||||
handleOutput(session, workingRedraw);
|
||||
|
||||
expect(emitted[0]).not.toContain('\x1b[55;1H\x1b[2K');
|
||||
expect(emitted[0]).toContain(workingRedraw);
|
||||
expect(emitted[0]).not.toContain('\x1b[H\x1b[2J');
|
||||
});
|
||||
|
||||
it('passes Codex spinner Working rows that omit elapsed time parentheses through', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 29;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const spinnerRedraw = '\x1b[24;1H\x1b[38;5;254m\x1b[1m•\x1b[CWorking\x1b[27;3H';
|
||||
|
||||
handleOutput(session, spinnerRedraw);
|
||||
|
||||
expect(emitted[0]).not.toContain('\x1b[24;1H\x1b[2K');
|
||||
expect(emitted[0]).toContain(spinnerRedraw);
|
||||
expect(emitted[0]).not.toContain('\x1b[H\x1b[2J');
|
||||
});
|
||||
|
||||
it('does not treat ordinary gpt model mentions as Codex status rows', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
const outputRow = '\x1b[20;1Hnormal output comparing gpt-5 and another model';
|
||||
|
||||
handleOutput(session, outputRow);
|
||||
|
||||
expect(emitted[0]).toContain(outputRow);
|
||||
expect(emitted[0]).not.toContain('\x1b[19;1H\x1b[2K');
|
||||
expect(emitted[0]).not.toContain('\x1b[20;1H\x1b[2K');
|
||||
});
|
||||
|
||||
it('does not inject row erases during partial Working spinner ticks', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
(session as unknown as SessionInternals)._ptyRows = 63;
|
||||
|
||||
const emitted: string[] = [];
|
||||
session.on('terminal', (data) => emitted.push(data));
|
||||
|
||||
handleOutput(
|
||||
session,
|
||||
'\x1b[55;1H\x1b[2m• Working (1s)' +
|
||||
'\x1b[56;1H\x1b[1m›\x1b[0m ask' +
|
||||
'\x1b[57;3Hgpt-5.5 xhigh fast · codeman · Working · Context 79% left'
|
||||
);
|
||||
handleOutput(session, '\x1b[55;1H\x1b[2m• Working (2s)');
|
||||
|
||||
expect(emitted[1]).not.toContain('\x1b[55;1H\x1b[2K');
|
||||
expect(emitted[1]).not.toContain('\x1b[56;1H\x1b[2K');
|
||||
expect(emitted[1]).not.toContain('\x1b[57;1H\x1b[2K');
|
||||
expect(emitted[1]).toContain('\x1b[55;1H\x1b[2m• Working (2s)');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { DEPENDENCY_REGISTRY } from '../src/config/dependency-registry.js';
|
||||
import {
|
||||
detectEnvironment,
|
||||
extractVersion,
|
||||
compareVersions,
|
||||
checkTool,
|
||||
checkAll,
|
||||
createRealHost,
|
||||
} from '../src/utils/dependency-checker.js';
|
||||
import type { ProbeHost } from '../src/utils/dependency-checker.js';
|
||||
import type { ProbeEnvironment, ToolDependency } from '../src/config/dependency-registry.js';
|
||||
|
||||
describe('DEPENDENCY_REGISTRY', () => {
|
||||
it('has unique ids', () => {
|
||||
const ids = DEPENDENCY_REGISTRY.map((t) => t.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
|
||||
it('hard-requires only node and tmux; agent CLIs and office are optional', () => {
|
||||
const required = DEPENDENCY_REGISTRY.filter((t) => t.required)
|
||||
.map((t) => t.id)
|
||||
.sort();
|
||||
expect(required).toEqual(['node', 'tmux']);
|
||||
// all agent CLIs are optional (Codeman runs any of them)
|
||||
const agentClis = ['claude', 'opencode', 'codex'];
|
||||
expect(DEPENDENCY_REGISTRY.filter((t) => agentClis.includes(t.id)).every((t) => t.required === false)).toBe(true);
|
||||
const office = DEPENDENCY_REGISTRY.filter((t) => t.category === 'office');
|
||||
expect(office.every((t) => t.required === false)).toBe(true);
|
||||
});
|
||||
|
||||
it('gives msoffice a windows-side resolver scoped to wsl + win32 only', () => {
|
||||
const ms = DEPENDENCY_REGISTRY.find((t) => t.id === 'msoffice');
|
||||
expect(ms).toBeDefined();
|
||||
const spec = ms!.resolvers.find((r) => r.resolver.kind === 'windows-side');
|
||||
expect(spec).toBeDefined();
|
||||
expect([...spec!.match].sort()).toEqual(['win32', 'wsl']);
|
||||
expect(ms!.resolvers.some((r) => r.match.includes('linux'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('detectEnvironment', () => {
|
||||
it('returns win32/darwin straight from platform', () => {
|
||||
expect(detectEnvironment({ platform: 'win32', procVersion: '', hasWindowsInterop: false })).toBe('win32');
|
||||
expect(detectEnvironment({ platform: 'darwin', procVersion: '', hasWindowsInterop: false })).toBe('darwin');
|
||||
});
|
||||
|
||||
it('detects wsl from /proc/version + interop, else linux', () => {
|
||||
const wsl = detectEnvironment({
|
||||
platform: 'linux',
|
||||
procVersion: 'Linux version 6.6 (Microsoft@WSL2)',
|
||||
hasWindowsInterop: true,
|
||||
});
|
||||
expect(wsl).toBe('wsl');
|
||||
expect(detectEnvironment({ platform: 'linux', procVersion: 'Microsoft', hasWindowsInterop: false })).toBe('linux');
|
||||
expect(detectEnvironment({ platform: 'linux', procVersion: 'generic', hasWindowsInterop: true })).toBe('linux');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractVersion', () => {
|
||||
it('pulls a dotted version from typical --version output', () => {
|
||||
expect(extractVersion('v22.22.1')).toBe('22.22.1');
|
||||
expect(extractVersion('tmux 3.4')).toBe('3.4');
|
||||
expect(extractVersion('no digits here')).toBeUndefined();
|
||||
});
|
||||
it('honors a custom regex', () => {
|
||||
expect(extractVersion('ProductVersion 16.0.19929.20172', /(\d+\.\d+\.\d+)/)).toBe('16.0.19929');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compareVersions', () => {
|
||||
it('orders by numeric components', () => {
|
||||
expect(compareVersions('18.0.0', '18.0.0')).toBe(0);
|
||||
expect(compareVersions('16.5.0', '18.0.0')).toBe(-1);
|
||||
expect(compareVersions('22.22.1', '18.0.0')).toBe(1);
|
||||
expect(compareVersions('3.4', '3.4.0')).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
function fakeHost(env: ProbeEnvironment, over: Partial<ProbeHost> = {}): ProbeHost {
|
||||
return {
|
||||
environment: env,
|
||||
which: () => null,
|
||||
fileExists: () => false,
|
||||
runVersion: () => null,
|
||||
windowsProgramRoots: () => [],
|
||||
windowsFileVersion: () => null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
const tmuxTool: ToolDependency = {
|
||||
id: 'tmux',
|
||||
label: 'tmux',
|
||||
category: 'core',
|
||||
required: true,
|
||||
resolvers: [{ match: ['linux', 'wsl'], resolver: { kind: 'path', bins: ['tmux'], versionArg: '-V' } }],
|
||||
};
|
||||
const nodeTool: ToolDependency = {
|
||||
id: 'node',
|
||||
label: 'Node.js',
|
||||
category: 'core',
|
||||
required: true,
|
||||
minVersion: '18.0.0',
|
||||
resolvers: [{ match: ['linux'], resolver: { kind: 'path', bins: ['node'] } }],
|
||||
};
|
||||
const msTool: ToolDependency = {
|
||||
id: 'msoffice',
|
||||
label: 'MS Office',
|
||||
category: 'office',
|
||||
required: false,
|
||||
resolvers: [
|
||||
{
|
||||
match: ['wsl', 'win32'],
|
||||
resolver: { kind: 'windows-side', appDirs: ['Microsoft Office/root/Office16'], exes: ['WINWORD.EXE'] },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe('checkTool', () => {
|
||||
it('reports ok with path + version when found on PATH', () => {
|
||||
const host = fakeHost('linux', {
|
||||
which: (b) => (b === 'tmux' ? '/usr/bin/tmux' : null),
|
||||
runVersion: () => 'tmux 3.4',
|
||||
});
|
||||
expect(checkTool(tmuxTool, host)).toMatchObject({
|
||||
id: 'tmux',
|
||||
status: 'ok',
|
||||
version: '3.4',
|
||||
path: '/usr/bin/tmux',
|
||||
});
|
||||
});
|
||||
|
||||
it('reports missing when no bin resolves', () => {
|
||||
expect(checkTool(tmuxTool, fakeHost('linux'))).toMatchObject({ id: 'tmux', status: 'missing' });
|
||||
});
|
||||
|
||||
it('reports outdated when below minVersion', () => {
|
||||
const host = fakeHost('linux', { which: () => '/n', runVersion: () => 'v16.5.0' });
|
||||
expect(checkTool(nodeTool, host)).toMatchObject({ id: 'node', status: 'outdated', version: '16.5.0' });
|
||||
});
|
||||
|
||||
it('reports error when minVersion set but version unparseable', () => {
|
||||
const host = fakeHost('linux', { which: () => '/n', runVersion: () => 'unknown' });
|
||||
expect(checkTool(nodeTool, host)).toMatchObject({ id: 'node', status: 'error' });
|
||||
});
|
||||
|
||||
it('reports skipped when no resolver matches the environment', () => {
|
||||
expect(checkTool(msTool, fakeHost('linux'))).toMatchObject({ id: 'msoffice', status: 'skipped' });
|
||||
});
|
||||
|
||||
it('finds windows-side apps under WSL', () => {
|
||||
const host = fakeHost('wsl', {
|
||||
windowsProgramRoots: () => ['/mnt/c/Program Files'],
|
||||
fileExists: (p) => p === '/mnt/c/Program Files/Microsoft Office/root/Office16/WINWORD.EXE',
|
||||
windowsFileVersion: () => '16.0.19929.20172',
|
||||
});
|
||||
expect(checkTool(msTool, host)).toMatchObject({
|
||||
id: 'msoffice',
|
||||
status: 'ok',
|
||||
version: '16.0.19929',
|
||||
path: '/mnt/c/Program Files/Microsoft Office/root/Office16/WINWORD.EXE',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkAll', () => {
|
||||
it('maps every tool to a result', () => {
|
||||
const results = checkAll([tmuxTool, msTool], fakeHost('linux'));
|
||||
expect(results.map((r) => r.id)).toEqual(['tmux', 'msoffice']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createRealHost', () => {
|
||||
it('returns a host with a valid detected environment and callable methods', () => {
|
||||
const host = createRealHost();
|
||||
expect(['linux', 'darwin', 'win32', 'wsl']).toContain(host.environment);
|
||||
expect(typeof host.which).toBe('function');
|
||||
expect(Array.isArray(host.windowsProgramRoots())).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderTable, renderJson, computeExitCode } from '../src/utils/dependency-report.js';
|
||||
import type { ToolResult } from '../src/utils/dependency-checker.js';
|
||||
|
||||
const results: ToolResult[] = [
|
||||
{
|
||||
id: 'node',
|
||||
label: 'Node.js',
|
||||
category: 'core',
|
||||
required: true,
|
||||
usedBy: [],
|
||||
status: 'ok',
|
||||
version: '22.22.1',
|
||||
path: '/n',
|
||||
},
|
||||
{
|
||||
id: 'tmux',
|
||||
label: 'tmux',
|
||||
category: 'core',
|
||||
required: true,
|
||||
usedBy: [],
|
||||
status: 'missing',
|
||||
installHint: 'sudo apt install tmux',
|
||||
},
|
||||
{
|
||||
id: 'libreoffice',
|
||||
label: 'LibreOffice',
|
||||
category: 'office',
|
||||
required: false,
|
||||
usedBy: ['document preview', 'thumbnails'],
|
||||
status: 'missing',
|
||||
},
|
||||
{
|
||||
id: 'msoffice',
|
||||
label: 'MS Office',
|
||||
category: 'office',
|
||||
required: false,
|
||||
usedBy: ['document preview', 'thumbnails'],
|
||||
status: 'skipped',
|
||||
reason: 'not applicable on linux',
|
||||
},
|
||||
];
|
||||
|
||||
describe('computeExitCode', () => {
|
||||
it('non-zero when a required tool is missing/outdated/error', () => {
|
||||
expect(computeExitCode(results)).toBe(1);
|
||||
});
|
||||
it('zero when only optional tools are missing', () => {
|
||||
const ok = results.filter((r) => r.id !== 'tmux');
|
||||
expect(computeExitCode(ok)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderTable', () => {
|
||||
it('groups by category and shows status, version, and install hints', () => {
|
||||
const out = renderTable(results, 'linux');
|
||||
expect(out).toContain('CORE');
|
||||
expect(out).toContain('Node.js');
|
||||
expect(out).toContain('22.22.1');
|
||||
expect(out).toContain('OFFICE');
|
||||
expect(out).toContain('document preview');
|
||||
expect(out).toContain('sudo apt install tmux');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderJson', () => {
|
||||
it('includes environment, summary, and per-tool data', () => {
|
||||
const json = renderJson(results, 'linux');
|
||||
expect(json.platform.environment).toBe('linux');
|
||||
expect(json.summary.exitCode).toBe(1);
|
||||
expect(json.summary.ok).toBe(1);
|
||||
expect(json.tools).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { runWithConversionLimit, getActiveConversionCount } from '../src/document-conversion-limiter.js';
|
||||
|
||||
describe('document-conversion-limiter', () => {
|
||||
it('never runs more converters than the cap (default 3) concurrently', async () => {
|
||||
let running = 0;
|
||||
let maxObserved = 0;
|
||||
|
||||
const task = () => async () => {
|
||||
running++;
|
||||
maxObserved = Math.max(maxObserved, running);
|
||||
// The module's own accounting must also stay within the cap.
|
||||
expect(getActiveConversionCount()).toBeLessThanOrEqual(3);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
running--;
|
||||
};
|
||||
|
||||
await Promise.all(Array.from({ length: 12 }, () => runWithConversionLimit(task())));
|
||||
|
||||
expect(maxObserved).toBeLessThanOrEqual(3);
|
||||
expect(maxObserved).toBeGreaterThan(1); // proves it genuinely parallelizes, not serializes
|
||||
expect(getActiveConversionCount()).toBe(0); // every slot released
|
||||
});
|
||||
|
||||
it('processes every queued task even when far more are submitted than the cap', async () => {
|
||||
let completed = 0;
|
||||
await Promise.all(
|
||||
Array.from({ length: 25 }, () =>
|
||||
runWithConversionLimit(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
completed++;
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(completed).toBe(25);
|
||||
expect(getActiveConversionCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('releases the slot when a task throws', async () => {
|
||||
await expect(
|
||||
runWithConversionLimit(async () => {
|
||||
throw new Error('boom');
|
||||
})
|
||||
).rejects.toThrow('boom');
|
||||
expect(getActiveConversionCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user