${values
.map(
([value, title]) =>
@@ -86,25 +92,54 @@
if (actionId.endsWith(".agent-status")) {
html =
number("slot", "Agent slot", 1, 1, 8) +
- `Slots follow Codex chat recency; the bundled pages place slots 1 to 6. Press a key to open and acknowledge that chat.
`;
+ `Slots follow the selected app’s chat recency; the bundled pages place slots 1 to 6. Press a key to open and acknowledge that chat.
`;
} else if (actionId.endsWith(".command")) {
html =
controller === "Encoder"
- ? `Rotate between FAST, Plan, Compact, Review, Browser, Files, and Side chat. The dial list is fixed so every position remains predictable.
`
- : select("commandId", "Command", commandOptions, "new-chat") +
+ ? `Rotate between FAST, Plan, Compact, Review, Browser, Files, and Side chat. Claude skips commands not available in its current Code view.
`
+ : select(
+ "commandId",
+ "Command",
+ settings.provider === "claude" || settings.provider === "auto"
+ ? commandOptions.filter(([id]) => !codexOnlyCommands.has(id))
+ : commandOptions,
+ "new-chat",
+ ) +
`Commands apply only to the visible active task and fail closed if focus changes.
`;
} else if (actionId.endsWith(".workflow")) {
html =
select("workflowId", "Workflow", workflowOptions, "pr-review") +
- text("path", "Workspace path", "Latest Codex workspace when empty");
+ (settings.provider === "claude"
+ ? `Starts an unsent draft in the current folder or Cloud repository. Existing draft text is preserved.
`
+ : text(
+ "path",
+ "Workspace path (Codex only)",
+ "Focused workspace when empty",
+ ));
} else if (actionId.endsWith(".reasoning")) {
- html = `The dial reads the model's supported levels from Codex and applies changes to the active chat.
`;
+ html = `The dial reads the model's supported levels from the selected app and applies changes to the active chat. Current Claude menus offer Low through Max; the separate Ultracode toggle is preserved.
`;
+ } else if (actionId.endsWith(".usage")) {
+ html = `Codex shows weekly capacity. Claude shows the quota period and bucket exposed by its Code view. A missing quota is not treated as zero or unlimited.
`;
+ } else if (actionId.endsWith(".context")) {
+ html = `Claude reads the Context card in Session Details (or the older Usage control). Keep Session Details visible to refresh its reading.
`;
} else if (actionId.endsWith(".agent-navigator")) {
html = `Rotate to browse recent chats and press to open the selected one. With no recent chats, press starts a new chat. Touch-strip taps and holds are intentionally inert.
`;
} else {
html = `No settings are required for this action.
`;
}
- app.innerHTML = html;
+ app.innerHTML =
+ select(
+ "provider",
+ "Application",
+ [
+ ["codex", "Codex"],
+ ["claude", "Claude Code"],
+ ["auto", "Follow active app"],
+ ],
+ "codex",
+ ) +
+ `Existing keys stay on Codex. Claude supports the Code tab only; unavailable controls show their status. Shared profiles follow the foreground app.
` +
+ html;
app.querySelectorAll("[data-setting]").forEach((element) => {
element.addEventListener("change", save);
if (element.tagName === "TEXTAREA" || element.type === "text") {
@@ -122,5 +157,6 @@
socket.send(
JSON.stringify({ event: "setSettings", context, payload: settings }),
);
+ if (element.dataset.setting === "provider") render();
}
})();
diff --git a/docs/claude-integration-research.md b/docs/claude-integration-research.md
new file mode 100644
index 0000000..438ed7c
--- /dev/null
+++ b/docs/claude-integration-research.md
@@ -0,0 +1,322 @@
+# Claude Code Desktop integration research
+
+Reviewed 2026-09-05. Baseline: plugin v0.2.4; installed Claude Desktop
+1.46388.4 on macOS. This document distinguishes source inspection, synthetic
+tests, and live acceptance. A passing fixture is not evidence of hardware acceptance.
+
+**Update reviewed 2026-11-15:** the current combined picker, independent Ultracode
+toggle, Fast labels, Context card and quota semantics supersede the September
+observations below. See the [current compatibility and QA record](desktop-compatibility-2026-11.md)
+for Claude 5.11492.5, Codex/ChatGPT 26.1111.21308 and SDK 3.0.4. Historical observations
+remain here to explain the retained legacy selectors.
+
+## Decision and reuse audit
+
+One plugin with application adapters shares SDK actions, images, profile generation,
+packaging, and the existing bounded native process transport. The Codex adapter
+retains its existing store, controls, targeting, and PTT guard. Claude has an
+independent native target contract. No external project code or runtime is bundled.
+
+| Project / reviewed revision | Source and license evidence | Decision |
+| ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [agentsd](https://github.com/paultyng/agentsd/tree/1621f2448662b9c2330df351b2f67a7d1375ef09) | MIT; `src/state-machine.ts`, `src/util/applescript.ts`, hook server/session manager. macOS; HTTP hooks drive state. Desktop focus is application activation; stop targets frontmost Ghostty. | Useful event-state reference for optional hooks. Its focus/stop implementation cannot prove the current Desktop session. No code copied. |
+| [AgentDeck](https://github.com/puritysb/AgentDeck/tree/1d75b78b44d093fc13ec17b9363ab88fcf66b8c6) | MIT; architecture, bridge state machine/hook server, shared model-provider types reviewed. A daemon coordinates clients; Claude adapter uses hooks and terminal UI observation. | Reuse the architectural principle of isolated app adapters and explicit unknown states. Existing local helpers already cover transport/rendering. A required daemon or terminal observer conflicts with this release's scope. |
+| [streamdeck-claude-answer](https://github.com/hardkoded/streamdeck-claude-answer/tree/39ccfe2972ae7112b5827b284711e8d7e9960d61) | MIT; plugin, CLI and bundled-profile workflow. Explicit question files and answer files implement requested Q&A. | Different workflow and profile assumptions; does not provide arbitrary Desktop approval or session control. No runtime dependency. |
+| [alejandrosnz/claude-deck](https://github.com/alejandrosnz/claude-deck/tree/0b50c6b6d20ae6e66af835d4bd5c3b29dae60457) | Usage client and tests reviewed. Client reads CLI credentials and calls an OAuth usage endpoint. No root license file found in the reviewed checkout. | No code adoption. Credential extraction and private account API calls are outside this design. |
+| [Alish3r/claude-deck](https://github.com/Alish3r/claude-deck/tree/9d6b7f46f7367d27265650d1aa5f9f148d1891a6) | Companion installer/extension reviewed. Root license includes Commons Clause conditions. VS Code companion reapplies a patch to the Claude extension. | Wrong target surface, app patching, and incompatible reuse assumptions. No code copied. |
+
+The search also covered [Agent Vitals](https://github.com/tapparello/agent-vitals),
+[deck-threads](https://github.com/rschwabco/deck-threads),
+[StreamDeck-Claude](https://github.com/Corrugator/StreamDeck-Claude), and
+[yolodeck](https://github.com/cruftbox/yolodeck). Their published designs focus on
+CLI hooks, account-token usage reads, Windows terminal control, or a companion
+application. README review does not establish exact Claude Desktop Code control.
+
+Maintenance dates and source revisions are recorded for reproducibility, not as
+endorsements. License review must be repeated before adopting any code. AgentDeck's
+initial full clone timed out; the relevant files were subsequently read at the
+pinned revision through GitHub's contents API.
+
+## Anthropic and platform guidance
+
+- [Desktop reference](https://code.claude.com/docs/en/desktop#keyboard-shortcuts):
+ Code has its own keyboard shortcuts and a shortcut panel (`Cmd+/`). Model,
+ effort and permissions menus have dedicated entry points. CLI shortcuts such as
+ `Shift+Tab` do not apply to Desktop. Installed menu semantics take priority over
+ a copied list of positional shortcuts.
+- [Keybinding customization](https://code.claude.com/docs/en/keybindings) and
+ [interactive mode](https://code.claude.com/docs/en/interactive-mode): terminal
+ configuration must not be mistaken for Desktop automation settings.
+- [Hooks guide](https://code.claude.com/docs/en/hooks-guide) and
+ [reference](https://code.claude.com/docs/en/hooks): hooks provide lifecycle
+ events with session IDs and bounded responses. An optional future integration
+ must correlate request/session identity, preserve unrelated hook configuration,
+ handle cancellation and timeouts, and distinguish local from remote hook hosts.
+ This release does not install hooks or expose a listener.
+- [Agent SDK sessions](https://code.claude.com/docs/en/agent-sdk/sessions) concern
+ running/resuming an agent. They do not by themselves prove control of the current
+ visible Desktop composer.
+- [Computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool)
+ uses an agent/tool execution loop. Button operations should not require a model
+ call, additional API credentials, or screenshot-driven inference.
+- [Elgato profiles](https://docs.elgato.com/stream-deck/profiles/getting-started/)
+ are device-specific. Shared profiles remain separate opt-in archives; existing
+ and hand-built profiles retain their application binding.
+
+Our implementation policy, rather than an Anthropic guarantee: prefer semantic
+Accessibility actions, use documented shortcuts only with foreground/target proof,
+inspect offered options, and verify the observed result. Never infer success from
+successful input delivery. Do not click absolute screen coordinates in production.
+
+## Feature evidence and acceptance matrix
+
+Every Claude operation requires foreground Code, one focused window, one composer,
+a content-root Code session URL, and unique matching Desktop metadata. Titles and
+focus timestamps do not establish identity. Session IDs are namespaced by app,
+window/process and environment. An unrecognized route or environment fails closed.
+
+| Feature | Verified mechanism and postcondition | Accepted environment / limitation |
+| ------------------------------------ | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| Provider routing | Foreground bundle ID; per-action provider; namespaced window/session/environment identity | Native wrong-provider, window, session, environment and background rejections; automated mixed-profile tests |
+| Model | Unique Model picker and offered menu rows; unchanged draft and verified selection | Local + SSH; primary menu choices |
+| Effort | Combined picker via documented Cmd-Shift-E; named menu rows; verified result. Legacy slider retained | Local + SSH; current Low–Max preserves independent Ultracode toggle |
+| Permission cycle / Plan | Exact offered mode rows; verify selection; restore prior non-Plan mode | Local + SSH; full offered cycle including Bypass; first-use workspace confirmation handled |
+| Context / quota usage | Unique Usage picker and scoped Session Details Context card in exact Code session | Local + SSH; period/bucket labeled; missing data never becomes zero; cached readings identified |
+| Fast | Offered model-menu checkbox; verify combined label's Fast state and unchanged model | Local + SSH; current Opus/Fable controls supported when offered; no substitute model |
+| Sidebar / Changes | Unique named button or numeric toggle; verify changed state and unchanged draft | Local + SSH |
+| Browser pane | Unique Browser toggle; verify changed state and unchanged draft | Local + SSH verified on 2026-11-14 |
+| Send / stop | Guarded implementation exists but is not in the release capability allowlist | Unsupported until separately accepted |
+| Session discovery / navigation | Bounded metadata plus exact visible session correlation | Metadata supports identity; navigation unsupported |
+| Approvals | Requires unique approval request/card identity and verified dismissal | Unsupported |
+| New session / workflows | Requires verified destination identity/project/environment and draft preservation | Unsupported |
+| Compact / Files / side chat / skills | Requires feature-specific surface and result proof | Unsupported |
+| PTT | Visible recording control; hold/release equivalent not yet validated | Unsupported; no global dictation fallback |
+
+Ordinary Cloud sessions remain unsupported. The November Project exception below
+qualifies only its model picker and displayed telemetry. Local and SSH native transactions passed separately;
+physical hardware acceptance is pending for this prerelease.
+
+### Live observations after the approved reload
+
+On 2026-09-05, the installed Claude 1.46388.4 exposed its Code accessibility tree
+and a Local session. These observations supersede the initial blank-window blocker:
+
+- The focused window is identified by the application's `AXFocusedWindow` reference.
+ Its own `AXFocused` flag was false. The helper now uses the reference and verifies
+ it belongs to the current window list.
+- `AXEnhancedUserInterface=true` did not mean Electron manual accessibility had
+ been requested. Claude now requests `AXManualAccessibility` explicitly once per
+ native transaction. The setting's readback remained false after successful
+ activation, so repeated verification does not repeat the activation delay.
+- A Code content-root URL used `/epitaxy/local_`, matching the `sessionId`
+ in Desktop metadata. `cliSessionId` was a different UUID. The parser preserves
+ the prefix; it does not collapse these two namespaces.
+- The installed shortcut panel confirmed Cmd-Shift-I for model, Cmd-Shift-E for
+ effort, Cmd-Shift-M for permissions, and Cmd-Option-F for Fast mode.
+- Model controls expose descriptions such as `Model: Fable 5.1`. Their menus use
+ `AXMenuItem` rows. A UI test selected Opus 5 and restored Fable 5.1.
+- Effort is an `AXSlider`, with observed minimum 0, maximum 5, value 2 and value
+ description High. Increment produced Extra (3); decrement restored High (2).
+ The helper derives offered numeric positions from the accessible range, uses
+ Increment/Decrement, and verifies both position and selected description.
+ Beta 1 used ordinal previews. Beta 2 verifies and displays the six named levels.
+- Permission menu rows contain a primary mode label and descriptive text. The
+ helper reads exact mode labels from each row's child text. Visible Local choices
+ were Auto, Manual, Accept edits, Plan and Bypass permissions. Native cycling
+ verified Auto → Manual → Accept edits → Plan → Auto. Bypass opened an additional
+ confirmation, which was cancelled during beta 1. Beta 2 handles that exact dialog
+ after an explicit Bypass selection, with target and draft checks.
+- Opus 5 exposed an Enable fast mode checkbox in its model menu. A UI test turned
+ it on and off and verified both the checkbox and Fast mode status. Fable 5.1 did
+ not expose it. Native toggling and restoration subsequently passed separately
+ on Local and SSH with Opus 5.
+- A Usage picker exposed a model-family weekly percentage and active-session
+ context usage. Parsing and rendering now use these fields, with the bucket
+ explicitly labeled. The PTT control is visible but hold/release is unvalidated.
+
+The shell sandbox can hide running applications. Preflight reports an unobserved
+foreground without calling it locked; live probes require normal desktop process
+access. Native tests brought Claude forward explicitly and verified Local and SSH
+model/effort selection and restoration, Plan restoration, full non-Bypass permission
+cycling, Fast restoration, pane toggles and visible telemetry. Local additionally
+passed an actual unsent-draft test with focus on the Code mode selector rather than
+the composer; the exact test draft survived and was removed afterward without sending.
+
+Negative native tests rejected changed window, session, provider and environment
+identities; a Claude operation while Codex was foreground; ordinary Claude Chat;
+and an actual split with two Prompt composers. The empty split was closed afterward.
+The compiled per-environment capability allowlists contain only these accepted
+operations; send/stop remain disabled despite guarded source implementations.
+
+## Privacy and release gates
+
+Only known local session metadata is read; no credential files, Keychain access,
+private API calls, application patches, transcript writes, or hooks are installed.
+Diagnostics must exclude prompts, account IDs, and local paths from public artifacts.
+
+Before stable release: qualify physical Mini and Plus controls and all generated
+layouts, including legacy and mixed hand-built profiles. Native Local/SSH acceptance
+is recorded above; Cloud and other unproven combinations stay disabled. Wrong-target
+mutations and Codex regressions block publishing. The stable installed plugin remains
+unchanged while this prerelease is offered for hardware acceptance.
+
+### Repeatable native acceptance
+
+Run `node scripts/qa-claude-controls.mjs --environment=local --activate` with an
+existing Local Code session selected (use `ssh` for SSH). This reads options and
+checks invalid-target rejection without selecting new settings. Add `--exercise`
+to change and restore model, effort, Plan, permissions, available Fast and panes.
+Use an idle test session. Logs omit identifiers, drafts and private paths. If the
+target changes, restoration fails closed rather than editing the new session.
+
+`STREAMDECK_CLAUDE_ACCEPTANCE_ENVIRONMENT` is a developer-process override used by
+the acceptance runner to exercise guarded, not-yet-qualified native transactions.
+It is not a user setup requirement, persisted preference, or packaged default.
+Normal operation uses `verifiedClaudeCapabilities`, separately for Local and SSH.
+
+### Final qualification replay
+
+On 2026-09-06, the unlocked Local replay exposed an independent metadata bug:
+Desktop's valid session JSON had grown to 321,001 bytes because it also contains
+prompt snapshots. The old 256 KiB limit silently excluded it. The metadata reader
+now accepts up to 4 MiB and bounds the read itself, including concurrent file growth.
+Regression tests cover the observed size, the limit, and an oversized file.
+Optional diagnostics expose only counts for Code roots, matching metadata and
+matching windows; they do not print session identities or content.
+
+After this fix, the complete Local replay passed model/effort discovery and
+selection, Fast, Plan, a full permission cycle, sidebar, Changes, Browser and
+wrong-target rejection. Original settings were restored and both telemetry fields
+were observed. The complete SSH replay subsequently passed the same supported
+operations independently, including restoration and both telemetry fields. The earlier unavailable/inconsistent menu state did not recur in
+this complete replay; locking has not been established as its cause.
+
+The console-session guard rejects locked, off-console and unavailable desktop
+states before provider targeting or input. It was verified against a locked desktop,
+which returned `LOCKED` without a target. Automatic unlock is not part of the plugin.
+
+### Beta 2 effort and permission follow-up
+
+Reviewed 2026-09-06 against the same installed Desktop version. The numeric menu
+shortcuts in the [Desktop reference](https://code.claude.com/docs/en/desktop#keyboard-shortcuts)
+were verified live: 4 selected Plan and 5 selected Bypass in the offered five-mode
+menu. Production presses the exact semantic row rather than relying on its position.
+
+All six effort descriptions were observed: Low, Medium, High, Extra, Max and
+Ultracode. Fable and Opus exposed the same six names; Sonnet exposed the same slider
+range. Haiku did not offer an enabled effort control. Named choices are validated
+against the actual range and current description; changed semantics are rejected.
+The missing Ultracode picker label was also corrected and selection/restoration tested.
+
+Permission cycling now includes every offered mode. Plan restores a remembered
+non-Plan mode, including Bypass. With no history it selects the unique Default marked
+in Claude's menu, or Manual if none is marked; it never remains stuck in Plan for
+lack of plugin history. Local's full five-mode cycle and history-free return to its
+marked Bypass default passed native testing.
+
+SSH displayed “Bypass all permissions?” on its first Bypass selection. The user
+authorized that workspace confirmation, and the native helper selected Bypass.
+The initial postcheck rejected the result despite the visible Bypass selection;
+it required the original composer Accessibility object to survive the modal. The
+postcheck now allows a composer remount only after this operation confirmed the exact
+dialog, and only with the captured Code session, window, unique composer and draft
+unchanged. Tests reject changed session URLs, ambiguous dialogs, outside buttons,
+and changed drafts. The repeated full SSH cycle and Plan restoration passed;
+SSH Auto mode was restored after acceptance testing.
+
+Fast remains unchanged following the user's clarification. Anthropic's
+[Fast documentation](https://code.claude.com/docs/en/fast-mode) distinguishes supported
+Opus models from other models; this preview retains its verified Opus 5 control.
+
+## Reset-count discovery follow-up — 2026-11-14
+
+Reviewed Claude Desktop 5.11492.5. The visible Usage inventory reports separate
+weekly and Fable balances. The native helper independently read 2 and 1; the SDK
+button harness verified both values and cached display after switching apps.
+
+| Candidate | Evidence | Decision |
+| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Desktop Usage accessibility | Exact Settings → Your usage → Limit resets hierarchy; row totals reconcile | Verified baseline; requires the page to be exposed once per plugin run |
+| Desktop Code usage ring | Official [Desktop reference](https://code.claude.com/docs/en/desktop#check-usage); observed percentages and scheduled reset time | No observed banked-credit counts |
+| CLI status line / hooks | [Status-line schema](https://code.claude.com/docs/en/statusline) documents quota percentages and reset timestamps | No documented banked weekly/Fable credit inventory; timestamps must not be converted into counts |
+| CLI local reset cache | `unusedLimitResetStatusCache` contains an account identifier, boolean, checked time and expiry | Only answers whether an unused reset exists; sampled entry was expired; cannot supply separate counts |
+| Desktop local usage history | `plan-usage-history.json` v2 stores timestamped quota percentages | No reset inventory in inspected file |
+| Desktop web caches | Bounded field-name inspection of Local Storage, Session Storage and HTTP cache | Matches were compressed analytics or JavaScript definitions, not a verified current inventory. Do not parse analytics into balances |
+| Background OAuth usage polling | [Comradex maintenance source](https://github.com/nicosuave/comradex/blob/ec295c6ae4b29dd48cd991617b3e44d78a078507/src/proxy/claude/maintenance.rs) requests `/api/oauth/usage?cedar_ember=1&skip_spend=1`; [tests](https://github.com/nicosuave/comradex/blob/ec295c6ae4b29dd48cd991617b3e44d78a078507/src/proxy/management_reset_credit_tests.rs) cover account-scoped cached grant metadata | Technically promising; uses a bearer credential and an undocumented endpoint, outside the approved integration constraints. No endpoint request made, no credentials extracted, no source adopted. Its fixture does not prove correct weekly/Fable classification |
+
+Comradex reviewed revision: `ec295c6ae4b29dd48cd991617b3e44d78a078507`. No license
+file was found in that checkout; no code was copied or dependency introduced.
+
+[Anthropic's reset documentation](https://support.claude.com/en/articles/17007452-what-is-a-limit-reset)
+points to Settings > Usage and limit-reached messages. No documented direct
+reset-count API or Desktop reset-inventory shortcut was found in the reviewed
+sources. This is a research finding, not proof that no other interface exists.
+
+Recommended next UX improvement within the existing constraints: persist a
+verified, account-scoped inventory with its observation time, explicitly label
+cached data, and offer an intentional refresh that opens Usage and restores the
+prior session/draft. Both account correlation and restoration need verification
+before implementation. Do not silently navigate Settings on every poll. The
+current build still uses its in-memory cache; this recommendation is not shipped.
+
+### Boolean fallback
+
+Implemented the requested fallback: when no exact inventory has been observed, a
+positive unexpired `unusedLimitResetStatusCache` displays **Claude / Resets
+available / Cached status**. It does not label a type or invent a count. Desktop's
+`lastKnownAccountUuid`, CLI's `oauthAccount.accountUuid`, and the cache's account
+identifier must agree. False, malformed, future-dated, expired or account-mismatched
+entries remain unknown. Reads are bounded and do not use credential fields. Exact
+UI counts take priority and are cleared when Desktop account identity changes.
+
+The inspected test machine's account identities matched, but its boolean cache
+was expired. It is correctly rejected; no cache was edited or artificially
+refreshed for acceptance. This fallback's useful availability depends on Claude
+refreshing its own cache. Synthetic positive-path checks are separate from this
+observed expired-cache behavior.
+
+## Claude Code Projects — 2026-11-14 follow-up
+
+User hardware acceptance exposed a surface omitted from the earlier QA matrix:
+Desktop 5.11492.5's Code Project coordinator at the exact first-party
+`/epitaxy/project/chan_…` content URL. This is distinct from UUID-addressed
+Local/SSH sessions. The old adapter returned UNSUPPORTED before reading controls.
+
+Observed Project model menu: Opus 5.5, Fable 5.2, Sonnet 5.5 and Haiku 5.5. The
+menu explicitly states that the coordinator runs at fixed effort. Its Usage
+control reports plan percentages and “Compacts automatically”; it does not expose
+a context percentage. The Project adapter therefore provides model selection,
+Fixed effort, AUTO / COMPACTION context and visible quota only. No percentage or
+adjustable effort is fabricated. Other operations fail closed.
+
+Target proof requires one visible Project content root, one descendant composer
+and Usage control, one matching on-screen window, foreground continuity and a
+re-read of the unchanged content URL. Model selection checks the exact offered
+label and unchanged draft, project and window before and after. It does not use
+sidebar titles or metadata recency. No private API, credentials or app patches.
+
+The complete SDK event path initially failed despite successful native selection:
+unused model/effort dial-down events were doing an extra Accessibility read and
+could cause the following dial-up commit to expire in the queue. Those no-op
+dial-down events are now ignored; Project reads reuse the captured tree instead
+of scanning twice. Fixed-effort inputs do not invoke a change or flash an alert.
+
+`scripts/qa-claude-project.mjs` passed all four model preview/press/release commits
+through the packaged plugin process, verified actual app selection, restored the
+original model, rejected a wrong project, checked the model scale, automatic
+context and fixed-effort display, and rejected any warning alert. This is software
+event acceptance; physical hardware acceptance is a separate check.
+
+## November 15 expanded Desktop controls
+
+The [Sagan live audit](sagan-control-audit-2026-11-14.md) supersedes the September unsupported-command matrix above. Dedicated Local, genuine SSH, and classic Cloud QA sessions were inspected and exercised separately.
+
+- New Local/SSH drafts: installed Cmd-Shift-N shortcut (new session with current settings), exact visible environment preset plus account/folder/SSH identity, then verify the new draft and preserve existing text. Workflows use the same verified destination and never send automatically.
+- Send: current composer-owned Send control, verify emptied composer and sent text in the same session. Compact: exact empty composer, `/compact`, then explicit compaction result.
+- Files and panes: observed toggles and selected-state changes. Side chat: installed shortcut and distinct second composer, preserving the main draft.
+- Skills: observed Add → Slash commands → skills, followed by Local's project view or Cloud's Skills tab. Settings uses the actual Code settings control.
+- PTT: actual recording checkbox; verify start and stop. Reuse the existing plugin child lease for parent-loss/max-hold cleanup, with the captured provider/window/session on release. No hooks, model calls, or companion service.
+- Classic Cloud: case-sensitive `session_` Code content route, one session header and main composer. Independently correlated with its visible cloud-environment card during qualification. No local session JSON exists; no remote private API is used. New-session/workflow creation matches the visible Cloud Environment card’s environment and single repository to the new draft; its selected branch is part of draft identity. Unexposed or ambiguous destination evidence is rejected.
+- Reset inventory: persist only observed, account-scoped weekly/Fable counts in the plugin's own cache. Never modify Claude storage or extract credentials. Saved values are explicitly CACHED.
+
+Reference reviewed November 15: [Desktop reference and keyboard shortcuts](https://code.claude.com/docs/en/desktop). Actual installed controls determine available actions; terminal bindings are not substituted.
diff --git a/docs/desktop-compatibility-2026-11.md b/docs/desktop-compatibility-2026-11.md
new file mode 100644
index 0000000..6ebec58
--- /dev/null
+++ b/docs/desktop-compatibility-2026-11.md
@@ -0,0 +1,227 @@
+# Desktop compatibility refresh — 2026-11-14
+
+Local beta: v0.3.0-beta.3, continuing the existing Claude integration worktree.
+No repository rename, profile replacement, credential access, hooks, or model API
+calls are part of this update.
+
+## Versions and sources
+
+Installed applications inspected: Claude 5.11492.5, Codex/ChatGPT 26.1111.21308,
+Stream Deck 7.5.1 (22901) on sagan; 7.6.1 was offered but not installed during QA. Dependency versions checked against the npm registry on
+2026-11-14: Stream Deck SDK 3.0.4, Elgato CLI 1.10.4, Vitest 5.1.0, TypeScript
+7.0.2, esbuild 0.28.2, Prettier 3.10.1, lucide-static 1.73.0, opentype.js 2.0.0,
+ws 8.23.0, and @types/node 26.6.6. Runtime remains Node 24 and minimum Stream
+Deck remains 7.1. Both production and full dependency audits report zero findings.
+
+Reviewed sources, all on 2026-11-14:
+
+- [Elgato SDK 3 migration](https://docs.elgato.com/streamdeck/sdk/upgrading/v3/):
+ action settings types move to the action instance; the action union includes
+ Neo; explicit settings reads no longer emit settings-change events. The plugin
+ reads returned settings directly and guards key/dial-only operations.
+- [Elgato getting started](https://docs.elgato.com/streamdeck/sdk/introduction/getting-started/)
+ and [WebSocket changelog](https://docs.elgato.com/streamdeck/sdk/references/websocket/changelog/):
+ runtime/minimum-version requirements and the newer Neo surface. No Infobar
+ action is added; existing Neo key profiles remain supported.
+- [Claude Desktop reference](https://code.claude.com/docs/en/desktop): dedicated
+ menu shortcuts and Session Details Context card. Documented Cmd-Shift-E opens
+ the nested effort menu; available options and results are then read from AX.
+- [Ultra plan](https://support.claude.com/en/articles/17728952-what-is-the-ultra-plan)
+ and [usage versus length limits](https://support.claude.com/en/articles/11647753-how-do-usage-and-length-limits-work):
+ verified Ultra accounts have no five-hour limit; weekly and Fable allowances
+ remain. A missing UI reading is not proof of unlimited usage.
+- [Codex app commands](https://developers.openai.com/codex/app/commands), now
+ redirected to [Commands](https://learn.chatgpt.com/docs/reference/commands):
+ current app reference, checked alongside installed controls and model metadata.
+
+## Observed changes and implementation
+
+| Surface | Observed mechanism | Verification and behavior |
+| ------------------ | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Claude model | Combined `Model: Fable 5.2 High` popup; Opus 5.5, Fable 5.2, Sonnet 5.5, Haiku 5.5 menu rows | Parse anchored control labels, including Fast and numeric usage-multiplier suffixes. Verify the same target, draft and resulting model. |
+| Claude effort | Nested Low, Medium, High, Extra, Max radio rows; separate Ultracode checkbox | Use the Desktop shortcut, sort offered rows in displayed order, select the named effort and verify it. Preserve independent Ultracode. Legacy six-position sliders still work. |
+| Claude Fast | `Enable fast mode` menu toggle; `Model: Fable 5.2 Fast High` label | Require the offered control, then verify Fast changed and the model/draft did not. Never substitute a different model. |
+| Claude permissions | Auto, Manual, Accept edits, Plan, Bypass; workspace confirmation on first use | Exact target check before menu selection and confirmation; Plan restores its recorded non-Plan mode. Nested menu/dialog traversal uses the current depth. |
+| Claude quota | Accessible Usage label still exposes Weekly/Fable on the tested account | Preserve period and bucket. Support bounded percentages for exposed Weekly, Session, Daily or Monthly labels. Clear removed quota after a valid active observation; background last readings explicitly say CACHED. |
+| Claude context | Unique Context card, Reorder Context control, total such as `18% used` or collapsed `Context 18%` | Read only the card total. Ignore category percentages, loading text and transcript text. Empty sessions remain NO DATA. Same-session cached readings are marked; session changes invalidate them. |
+| Dial bars | Remember offered option order after selection | Keep the applied position bar; invalidate previews and scales when app/session changes, or when the model changes under an effort preview. |
+
+Newer effort menus do not expose the independent Ultracode toggle as a dial
+level. Change it in Claude; effort selection preserves its state. Current context
+refresh requires the Session Details card to be exposed. The expanded Local, SSH, and Cloud results are recorded in the live audit below; capabilities are gated separately by environment.
+
+## Current Codex/ChatGPT targeting and controls
+
+The running app is ChatGPT 26.1111.21308 (bundle `com.openai.codex`). An older
+Codex.app is also installed but was not used for live acceptance. The app exposes
+multiple versions of each model family; selections now bind the exact version to
+its catalog slug. Chat-title menus containing “Astra” are excluded from picker
+candidates. Duplicate title/description attributes are collapsed within each
+control, so Plan and Dictate remain exact-label matches without merging controls.
+
+Current host activity logs retain multiple streams and do not establish which chat
+is visible. Current builds use renderer-owned route synchronization, correlated
+with the running process and one supported foreground window. A composer or the
+exact current approval footer is required. Complete startup and continuation
+fragments establish provenance; route/activity cursors reject A → B → A changes.
+Daily UTC rollover is supported. The older single-retained-view and renderer-specific
+paths remain available for earlier desktop versions.
+
+Multiple content windows and split composers remain unavailable. Missing, truncated,
+oversized or otherwise incomplete process history fails closed. No clipboard or
+private remote API is used. The full sagan audit cycled permissions and tested
+actual Allow once and Deny cards, all eight session keys, and the navigator dial.
+See the [complete control audit](sagan-control-audit-2026-11-14.md) for current
+results and distinctions between supported, unsupported and unqualified surfaces.
+
+## Earlier validation record (superseded by full live audit)
+
+Automated checks cover both legacy and current selectors, quota removal, period
+labels, cache isolation, changed targets, setting compatibility and stale effort
+previews. The five legacy Codex layouts retain their action positions and IDs. Five opt-in Master layouts have new, distinct identities and device-specific page navigation.
+The fixed-provider action IDs retain `weekly` internally for compatibility; the
+visible name remains Claude Left and its display follows the exposed quota.
+
+- Full `npm run check`: 697 tests across 52 files, type checking, formatting,
+ generated assets/contracts, 100 key rasters, profile design evaluation and
+ Elgato validation passed. Design evaluation reports zero failures or warnings.
+- Full and production dependency audits: zero vulnerabilities; dependency update
+ check reports no outdated packages.
+- Live Claude Local and SSH: model/effort round trips, Fast twice, Plan restoration,
+ all five permission modes including Bypass, sidebar, Changes and Browser passed.
+ Wrong provider/window/session/environment requests were rejected. Model, effort,
+ permission, Fast and independent Ultracode states were restored.
+- Local Claude context: exposed Context card read 18% used. The tested empty SSH
+ session correctly had no context reading. Weekly/Fable quota remained exposed.
+ A temporary draft survived an unfocused effort change and was then removed.
+- Codex dial event harness: exact model and effort application, preview-before-press,
+ applied position bars, Plan activation/restoration, PTT start/release and return
+ to an empty composer passed. An earlier PTT run transcribed ambient speech;
+ the harness now reports draft state instead of assuming a silent microphone.
+- Codex Plan/Fast event harness: both modes toggled on and off through four
+ exact-chat native dispatches, with both original off states restored.
+- Duplicate-window live QA: two content windows were observed; composer targeting
+ refused with NO_FOCUS. Only the QA-created window was closed, and the original
+ window returned to a verified empty composer.
+- Native regression fixtures reject ambiguous/hidden/off-owner recording controls;
+ current PTT recognizes the recording strip even while the editor is absent.
+ Composer observations measured roughly 1.5 seconds; their bounded timeout is
+ now three seconds instead of 1.2 seconds.
+- Packaged plugin version 0.3.0.3: archive integrity, 15 action registrations and
+ all ten embedded profile archives validated. All ten archives are byte-for-byte
+ identical to beta 2. No installed profile was imported, replaced or switched.
+
+Physical Mini/Plus button acceptance remains pending. The all-key connected
+release gate also remains incomplete: send/compact/workflow/new-chat actions need
+isolated fixtures and proven cleanup before claiming a full hardware release.
+Cloud and unsupported Claude commands remain outside this beta's verified matrix.
+Software event-harness results are not physical button testing.
+
+## Local installation
+
+Loaded through the existing Stream Deck development link on 2026-11-14. The
+running plugin reports manifest version 0.3.0.3 on Stream Deck 7.5.1 (22901) on sagan; 7.6.1 was offered but not installed during QA.23033 using
+its bundled Node 24.22.1. Focus, permissions, context, model, effort, usage and
+input all reached ready after startup. Switching to Claude selected its SSH Code
+session and exposed Fable 5.2 / High / Weekly Fable usage; empty context stayed
+empty. The prior beta 2 installer was retained locally for rollback. No public
+release or commit was made during this refresh.
+
+Post-reload observation exceeded two minutes with the same plugin process and no
+runtime errors. The one warning was the expected background-target rejection
+while Claude was foreground; Codex focus and permissions returned to ready when
+Codex was restored. No repeated timeout, crash or unexpected restart was observed.
+
+## Follow-up: existing provider-key press behavior
+
+The initial acceptance missed presses on the four fixed-provider keys. Claude
+Left/Context fell through to the unsupported-command branch; Codex Left/Context
+had rendering but no press handlers. Those were implementation defects, not a
+profile migration requirement.
+
+Codex Left now toggles weekly remaining/reset credits; Codex Context toggles
+percentage/token counts. Claude Left/Context refresh read-only observations,
+including cached/background and changed-session states, without attempting a
+chat command or raising an unsupported warning. Missing data remains missing.
+
+Follow-up validation: 704 tests in 53 files passed. The SDK event harness exercised
+all four key-down/key-up handlers twice with Claude foreground and twice with
+Codex foreground (16 presses), verified labels/toggle restoration and rejected any
+alert. It also repeated that run using settings read from the eight existing
+fixed-provider keys in saved profiles. These settings were empty and all action
+UUIDs matched the current plugin. Profile content was read only; no profiles were
+imported or replaced. Hardware button presses are still user acceptance, distinct
+from these event tests.
+
+Follow-up reload: 148 seconds of observation with no warnings or errors.
+All 18 saved profile JSON files containing plugin actions remained byte-for-byte
+unchanged across the reload.
+
+## Separate Claude reset credits
+
+Verified on 2026-11-14: Settings > Usage exposes a scoped Limit resets section
+with 3 available, a Fable reset (1) and Weekly reset · 2. Code's usage popup shows
+percentage and scheduled reset time, but not these balances. The helper reads
+only the visible Settings/Your usage/Limit resets hierarchy, requires matching
+redemption controls as structural evidence, and reconciles row counts against
+the section total. It never presses a redemption control. Hidden, duplicate,
+unscoped or inconsistent inventories remain unknown. Explicit empty inventory
+can report zero. This account telemetry does not authorize Code-session commands.
+
+Claude Left cycles allowance → weekly reset credits → Fable reset credits.
+Counts refresh only while Usage settings is exposed and are marked CACHED after
+it closes. OPEN USAGE means a reset inventory has not been observed in this plugin
+run. The existing action UUID and installed profiles are unchanged.
+
+Source reviewed 2026-11-14: [Anthropic limit resets](https://support.claude.com/en/articles/17007452-what-is-a-limit-reset).
+The two credit types are kept distinct; scheduled reset times are not credit counts.
+
+## Remote QA continuation — 2026-11-14
+
+QA moved to the dedicated test Mac with both Mini and Plus attached. The copied
+working tree passed 713 tests, design/visual checks, manifest validation and
+packaging. Beta 3 is loaded there; the prior plugin installation is preserved.
+Post-reload logs remained free of warnings/errors for more than two minutes.
+
+After unlock, the native helper read 2 weekly resets and 1 Fable reset from the
+visible Usage page. The real SDK event harness passed 24 key-down/key-up cycles
+across four provider keys, using settings from eight existing saved keys: three
+presses with Claude foreground and three with ChatGPT foreground. It verified
+weekly/Fable counts, cached counts after app switching, Codex view toggles and no
+warning alerts. This is event-path QA, not proof of physical button presses.
+
+The boolean fallback follow-up passed 727 tests in 54 files, type checking, build,
+manifest validation and packaging. The 24-event live count/caching run passed
+again with the fallback build. The rendered fallback was inspected at 144×144.
+After installation, more than 191 seconds of logs contained no warnings/errors;
+172 original saved-profile files were unchanged. Separately named copies of the
+existing Plus and Mini layouts were added and activated for hardware acceptance.
+The Plus preview shows the original fixed-provider keys and dial arrangement;
+physical input acceptance remains pending. No public release was made.
+
+## Project surface gap discovered in hardware acceptance
+
+The user's active Code Project was not a qualified Local/SSH session. Generic
+UNSUPPORTED and NO DATA masked that distinction. Project model selection is now
+separately targeted and verified; fixed coordinator effort shows Fixed, automatic
+context shows AUTO / COMPACTION, and its visible plan quota is read. No other
+Project command is enabled by this change.
+
+The live SDK run caught an additional dial-down queue-delay bug that native helper
+tests could not reveal. After correction, preview/press/release selection passed
+for all four offered models and restored the original model. Wrong-project
+rejection, scale rendering, fixed effort, automatic context and no-alert checks
+passed in the same run.
+
+Final Project build: 737 tests in 54 files passed, with type checking, manifest
+validation and package creation. Installed on the dedicated test Mac. Actual
+Stream Deck Plus preview showed Opus 5.5, Fixed effort, AUTO / COMPACTION context
+and 46% weekly remaining; Mini preview independently showed AUTO / COMPACTION
+and 46%. Reset inventory was refreshed and still reported 2 weekly / 1 Fable.
+The user’s Project was restored with its original Opus selection. Post-reload
+logs were observed for 156 seconds with no warnings/errors. Physical press
+acceptance after this fix remains distinct from the successful SDK event replay.
+
+## Final expanded audit
+
+See the [November 14–15 control audit](sagan-control-audit-2026-11-14.md) for expanded Local/SSH/Cloud coverage, persistent reset inventory, stale context display, guarded Claude PTT, removed shared controls, and the five new Master profile archives. Historical counts above describe earlier intermediate builds.
diff --git a/docs/sagan-control-audit-2026-11-14.md b/docs/sagan-control-audit-2026-11-14.md
new file mode 100644
index 0000000..c4911e6
--- /dev/null
+++ b/docs/sagan-control-audit-2026-11-14.md
@@ -0,0 +1,98 @@
+# Sagan connected control audit — November 14–15, 2026
+
+Status: software and installed-profile qualification completed. Expanded Local, genuine SSH, and classic Cloud coverage supersedes the earlier limited adapter audit. The updated beta and separate Plus/Mini Masters are installed on sagan; no public release has been made.
+
+Environment: sagan, ChatGPT 26.1111.21308, Claude 5.11492.5, Stream Deck 7.5.1 (22901), Plus and Mini. Source baseline d3960ec plus preserved beta.3 development changes. GUI tests and installation occur only on sagan. Existing profiles are preserved; separate QA copies of the hand-built layouts are used.
+
+## Evidence standard
+
+A passing operation requires the bundled SDK handler, an independently observed app result, and cleanup or restoration. Successful dispatch, native-only results, simulated selectors, and idle refusals do not establish a positive end-to-end pass. Stream Deck's device preview establishes rendering, not a physical button press. GUI mutations run serially. The SDK harness executes the current bundled code. A final process check showed that the Elgato plugin-only stop/restart command did not reliably terminate the installed process; it must not be used as evidence of process isolation. Final installation therefore used a complete host exit/relaunch and verified the new plugin process, startup log, and updated artwork.
+
+Private evidence under `.cache/control-audit` can contain UI text and must not be committed. Local/SSH submitted requests use an isolated QA workspace with no remotes. Cloud requests use this project’s public repository and explicitly prohibit tools, edits, commits, and pushes. Workflow previews are never submitted. Approval tests request only a no-op command.
+
+The old all-key connected-release harness deliberately stops before dispatch. It did not establish comprehensive control coverage. The first Codex dial test in this audit overlapped another GUI test and was discarded; its isolated repeat passed.
+
+## Repairs discovered in the full audit
+
+- **Codex Sidebar:** repeated accessibility labels rejected the real toggle. Match its own visible label and verify the transition.
+- **Codex workspace panes:** current Review, Browser and Side chat use selected radio tabs. Recognize their actual names and numeric state. The tab group reports a two-pixel anchor, so accept a tab only inside its visible framed header; hidden and off-window controls remain rejected.
+- **Files:** the old shortcut opened file search. Use the installed app's dedicated file-tree shortcut and verify the actual toggle.
+- **Skills:** numeric heading state was mistaken for text. Read numeric state only for toggle roles.
+- **New chat/workflows:** current new chats are unsaved drafts. Verify the exact draft, account-selected project and canonical project path without borrowing a retained chat identity. Decode the current plain-text document format conservatively; unknown content never means an empty draft.
+- **New Project:** the current folder chooser is a focused native sheet. Verify its exact owner without recursively inspecting the directory listing.
+- **Send:** press the composer-owned Send button. Verify an empty current composer and the newly observed sent message, including composer replacement and repeated messages in a virtualized transcript.
+- **Compact:** focus the verified empty composer before entering the command.
+- **Picker cleanup:** model, effort and Fast verify that the picker has actually closed; fixed Escape timing could leave the menu open and report a failed selection after the app had applied it.
+- **Action dial:** retain both command ID and index across page changes; honor legacy Claude command indexes.
+- **Claude model confirmation:** handle the current cache-cost dialog only when the captured session and exact old/new models match. Preserve the draft and the user's confirmation preference.
+- **Claude Bypass confirmation:** an accessibility press can succeed during the opening animation without dismissing the dialog. Require actual dismissal, retrying only the same verified dialog.
+- **Claude context:** a collapsed card reports `Context 24%`, while its expanded body reports `24% used`. Recognize both with the same card ownership checks; reject contradictory or out-of-range values. The key correctly reports 76% remaining.
+- **Codex session navigation:** retained stream activity is not foreground identity. Use the renderer-owned route synchronization event, with one supported window, one composer, complete process provenance and continuity. Cached-chat returns change the route cursor; unknown routes and ambiguous windows invalidate the target.
+- **UTC midnight:** current desktop logs split into daily fragments. Reduce complete process history across those fragments rather than retaining yesterday's route or rejecting the new file. Keep startup fragments even when newer empty worker logs exceed the ordinary discovery limit.
+- **Pending approvals:** the current app replaces the composer with an approval footer. Recognize unique visible Allow once, Deny and Approval options siblings; target the verified footer and require the composer to return after resolution. Hidden, duplicate, split-owner and composer-present fixtures are rejected.
+- **Plus effort text:** reduce the value font so the full Extra High label fits beside its icon; verify actual installed device preview rendering for both providers.
+- **Native latency:** remove redundant full-log parsing and compile the helper with production optimization. Live acceptance requires both the app outcome and an SDK response without a timeout warning.
+
+## Expanded control matrix
+
+A genuine SSH session was created using the test Mac's SSH connection and an isolated QA folder. Transport was independently confirmed in its `sshConfig`, rather than inferred from a title. A classic Cloud session used this project's public GitHub repository and a no-tools QA request. The Cloud environment card and exact Code content route established its environment. No private source, credentials, or database writes were used.
+
+| Control | Codex | Claude Local / SSH | Claude classic Cloud | Claude Project |
+| ---------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------- | ----------------------------- |
+| Model / effort | SDK preview, commit, restore | Named options, preview, selection and restoration | Offered options and restoration | Model selector; effort Fixed |
+| Permissions / Plan | Ask, Approve, YOLO; restoration | All five offered modes, Bypass dialog, Plan restoration | Actual three offered modes; Plan restoration | Unavailable |
+| Fast | On/off restored | Actual offered toggle, restored | Actual offered toggle, restored | Unavailable |
+| PTT | Start/stop; release after switching app | Actual recording checkbox; background release | Actual recording checkbox; background release | Unavailable |
+| Send / Compact | Actual harmless send and compaction | Actual harmless send and compaction | Actual harmless send and compaction | Unavailable |
+| Settings / Skills | Opened and verified | Opened and verified | Cloud Skills tab selected and verified separately | Unavailable |
+| Sidebar / Review / Browser / Files | Actual pane changes | Actual pane changes | Actual pane changes | Unavailable |
+| Side chat | Second composer observed | Separate Side chat composer observed | Separate Side chat composer observed | Unavailable |
+| New chat / workflow draft | 35 bindings: exact destination and unsent text | 35 bindings: current folder/environment and exact unsent text preserved | Repository/environment preserved; all three control types | Unavailable |
+| Accept / Reject | Genuine Allow once / Deny verified | Removed from shared masters and Claude command choices | Removed | Removed |
+| New Project | Native chooser opened and canceled | Removed from shared masters | Removed | Removed |
+| Agent Status / Navigator | All eight keys, three dial selections; duplicate titles | Removed from shared masters | Removed | Removed |
+| Quota / resets | All press display cycles | Visible quota; separate weekly/Fable credit counts | Same account quota and reset inventory | Visible quota |
+| Context | Exact-chat reading; old values marked CACHED | Current Context card; missing readings never zero | Current Context card | Explicit automatic compaction |
+| Health | All eight views | Capability status | Capability status | Limited-capability status |
+
+There is no separate Stop action in the published catalog. Send is not relabeled as Stop. Cloud new-session/workflow creation verifies the visible Environment card, one repository, and the new draft’s repository/environment. Draft identity also includes the branch selected by the new-session composer. Multi-repository or hidden/unexposed destination evidence remains unavailable. Local/SSH workflows preserve the current folder. All workflows leave the prompt unsent. Existing Codex-only action IDs remain available for saved user profiles.
+
+## Additional fixes after the first audit
+
+- Persist observed weekly/Fable reset balances in the plugin's own account-scoped cache. Saved values remain visibly CACHED after restart; account switches, invalid values and future timestamps are rejected. Usage observation refreshes the inventory without consuming a reset.
+- Retain the last valid Codex token event for its exact chat instead of expiring the display to NO DATA after an idle period. Old readings say CACHED; Health still distinguishes fresh and stale data.
+- Implement Local/SSH Files, Send, Compact, Settings, Skills, Side chat, new-session, workflow drafting and PTT from actual observed controls.
+- Match saved Local/SSH environment presets for new drafts by account, exact visible name, environment kind, folder and SSH connection identity. Never choose a preset by recency.
+- Guard Claude PTT with the existing child-process lease mechanism: key release, page disappearance, maximum hold and parent exit stop the captured recording. App changes do not redirect release to another provider.
+- Recognize case-sensitive classic Cloud IDs only on exact Code routes, together with one session header and main Code composer. Cloud has no Local session JSON. Pane changes can hide Session Details without invalidating the route; duplicate or missing ownership still fails closed.
+- Freeze new-draft identity before Send changes its live accessibility URL. Verify the resulting session and message rather than rereading the former draft URL after navigation. A successful Cloud send must not generate a false warning.
+- Use Cloud's actual Skills tab and Active heading instead of Local's In this project heading.
+- Cancel obsolete page appearances, share a fresh observation across queued controls, and invalidate render caches when pages reappear. The actual nine-page Plus archive can be traversed and returned home with model/effort labels restored in 1,026 ms in the embedded SDK harness. Button and dial input still revalidates its target independently.
+- Skip unavailable Claude commands on the Actions dial. Omit stale approval/session controls from new shared profiles without deleting their working Codex implementations.
+
+## New master profiles
+
+Five distinct opt-in **Codex + Claude Master** archives cover Plus, Mini, Neo, Standard, and XL. Every page reserves the last two keys for native Previous/Next Page actions. The Mini therefore needs no swipe or editor to reach subsequent pages. Plus keeps Workflows, Actions, Model, and Effort on all pages. Live controls contain fixed Codex/Claude quota/context keys; remaining actions follow the supported foreground app.
+
+The original five Codex archives and original installed profiles are preserved. Masters have separate profile/page/action identities, so importing them does not overwrite hand-built layouts.
+
+## Qualification record
+
+The expanded workflow sweep passed 27 keycaps, four Workflow keys and four Workflow encoder bindings in a genuine SSH session. Every draft matched exactly and was cleared before returning to the original session; nothing was submitted. Two QA harness defects (unbounded AX cleanup traversal and waiting for a key image from an encoder) were corrected and their affected cases rerun. They were not counted as product passes until successful reruns. Model and Effort SDK preview/apply/restore also passed in SSH.
+
+Automated: 814 tests across 56 files pass, including parent-loss/max-hold recording cleanup, reset persistence/account isolation, stale context and exact Cloud route rejection. Type checking, generated asset/profile checks, formatting, documentation and public-tree checks, and Elgato validation pass. All ten profile archives and the packaged plugin pass archive integrity checks. All 36 installed plugin files match the final build.
+
+New-draft Send passes independently in Local, SSH, and Cloud, with the sent message and resulting session verified, no SDK warning, and navigation restored to the original QA chat. The first SSH attempt refused before dispatch; its isolated repeat passed. Cloud workflow coverage includes a keycap, Workflow key, and all four encoder prompts. The reset-cache restart test retains two weekly and one Fable reset as CACHED without reopening Usage; the exact Codex chat context also remains available as CACHED. PTT parent-exit and maximum-hold tests stop the actual recording.
+
+The SDK harness exercises actual bundled handlers in Stream Deck's embedded Node runtime against the real applications. Device previews establish rendering and profile loading. Physical switch actuation requires a person; neither software events nor previews are reported as physical button presses. Actual permission revocation and unavailable-app scenarios are not simulated by disabling the user's permissions or uninstalling applications. Ambiguous targets remain guarded by regression tests and live changed-target refusals.
+
+The Plus Master has nine pages; Mini has twelve. Every installed page was selected through the real UI and checked against the saved current-page identity, then both devices were restored to their first pages. Mini’s live control page shows PTT, Send, Fast, and Permissions; Plus retains all four dials. The original 172 saved-profile files are byte-for-byte unchanged. Neo, Standard, and XL archives are structurally validated; those physical layouts were not tested on attached hardware.
+
+After the verified host relaunch, the plugin remained running through more than two minutes of observation and provider switching. Logs contained the expected background-target refusals during app changes, with no timeout or crash. Installed previews showed Astra/Extra High in Codex and Opus 5.5/High in Claude, current Claude context, retained Codex context, separate provider quota keys, and the corrected Permissions shield.
+
+The final package SHA-256 is `97c6d5ee883000138f3f6d12d3f426a5b123d93120b110d5bff400654b82f2c6`. Private detailed traces and screenshots remain outside tracked source.
+
+## References
+
+- [ChatGPT/Codex commands](https://learn.chatgpt.com/docs/reference/commands), reviewed November 14, 2026 and compared with sagan's actual controls.
+- [Claude Desktop reference](https://code.claude.com/docs/en/desktop), reviewed November 14, 2026 and compared with Local and Project surfaces.
diff --git a/marketplace/LISTING.md b/marketplace/LISTING.md
index f937a26..014de9c 100644
--- a/marketplace/LISTING.md
+++ b/marketplace/LISTING.md
@@ -80,3 +80,9 @@ or endorsed by OpenAI, Elgato, or Corsair.
## Upload package
`dist/com.todd.streamdeckcodex.streamDeckPlugin`
+
+## Current prerelease: Claude Code and Master profiles
+
+The 0.3.0 prerelease adds Claude Desktop Code Local, SSH, and classic Cloud controls to the same plugin. Supported controls vary by surface; see the [live acceptance matrix](../docs/sagan-control-audit-2026-11-14.md). Ordinary Claude Chat and Cowork are outside scope. No API key, hooks, or companion service is required.
+
+Five opt-in Codex + Claude Master profiles provide fixed provider quota/context keys, foreground-app controls, and Previous/Next keys on every page. Plus adds Workflows, Actions, Model, and Effort dials. Original Codex archives and user profiles remain intact. Workflow buttons prepare an unsent draft; they do not automatically execute publication, Git, or shell operations.
diff --git a/marketplace/media/app-icon.png b/marketplace/media/app-icon.png
index a40ce2e..5e3faf0 100644
Binary files a/marketplace/media/app-icon.png and b/marketplace/media/app-icon.png differ
diff --git a/marketplace/media/gallery-01-live-status.png b/marketplace/media/gallery-01-live-status.png
index 803898f..a04f597 100644
Binary files a/marketplace/media/gallery-01-live-status.png and b/marketplace/media/gallery-01-live-status.png differ
diff --git a/marketplace/media/gallery-02-controls.png b/marketplace/media/gallery-02-controls.png
index c777489..f1a8e45 100644
Binary files a/marketplace/media/gallery-02-controls.png and b/marketplace/media/gallery-02-controls.png differ
diff --git a/marketplace/media/gallery-03-workflows.png b/marketplace/media/gallery-03-workflows.png
index 60739e7..14c3308 100644
Binary files a/marketplace/media/gallery-03-workflows.png and b/marketplace/media/gallery-03-workflows.png differ
diff --git a/marketplace/media/gallery-04-key-actions.png b/marketplace/media/gallery-04-key-actions.png
index a5d6796..d8d337b 100644
Binary files a/marketplace/media/gallery-04-key-actions.png and b/marketplace/media/gallery-04-key-actions.png differ
diff --git a/marketplace/media/thumbnail.png b/marketplace/media/thumbnail.png
index dfc6278..60709f4 100644
Binary files a/marketplace/media/thumbnail.png and b/marketplace/media/thumbnail.png differ
diff --git a/native/Accessibility.swift b/native/Accessibility.swift
index ca52b04..52ee4c7 100644
--- a/native/Accessibility.swift
+++ b/native/Accessibility.swift
@@ -7,13 +7,14 @@ import Foundation
// AXManualAccessibility switch. Both debounce activation for two seconds.
// https://github.com/chromium/chromium/blob/main/chrome/browser/chrome_browser_application_mac.mm
func initializePickerAccessibility(
+ requireManual: Bool = false,
read: (String) -> Bool,
enable: (String) -> AXError,
settle: () -> Void
) -> String {
let manual = "AXManualAccessibility"
let enhanced = "AXEnhancedUserInterface"
- if read(manual) || read(enhanced) { return "already enabled" }
+ if read(manual) || (!requireManual && read(enhanced)) { return "already enabled" }
let manualResult = enable(manual)
if manualResult == .success {
settle()
@@ -77,7 +78,8 @@ func capturedFrame(
func captureAXSnapshot(
_ root: AXUIElement,
- maximumDepth: Int = 40
+ maximumDepth: Int = 40,
+ skippingChildrenOfRoles: Set = []
) -> AXSnapshot {
var result: [ElementInfo] = []
var queue: [(AXUIElement, Int, Int?)] = [(root, 0, nil)]
@@ -99,7 +101,8 @@ func captureAXSnapshot(
element,
kAXDescriptionAttribute as CFString
)
- let value = stringAttribute(element, kAXValueAttribute as CFString)
+ let rawValue = attribute(element, kAXValueAttribute as CFString)
+ let value = (rawValue as? String) ?? (["AXRadioButton", "AXCheckBox"].contains(role) ? (rawValue as? NSNumber)?.stringValue : nil) ?? ""
let help = stringAttribute(element, kAXHelpAttribute as CFString)
let elementFrame = capturedFrame(
positionValue: attribute(
@@ -133,7 +136,7 @@ func captureAXSnapshot(
depth: depth
)
)
- if shouldTraverseAXChildren(atDepth: depth, maximumDepth: maximumDepth) {
+ if !skippingChildrenOfRoles.contains(role), shouldTraverseAXChildren(atDepth: depth, maximumDepth: maximumDepth) {
let currentIndex = result.count - 1
queue.append(contentsOf: childElements(element).map { ($0, depth + 1, currentIndex) })
}
@@ -314,15 +317,16 @@ func normalized(_ value: String) -> String {
.replacingOccurrences(of: " ", with: "")
}
+// Chromium can expose the same accessible name in both title and description.
+// Deduplicate attributes of one element, never separate controls or descendants.
+func uniqueAXAttributeText(_ values: [String]) -> String {
+ var seen = Set()
+ return values.filter { !$0.isEmpty && seen.insert($0).inserted }
+ .joined(separator: " ")
+}
+
func elementText(_ info: ElementInfo) -> String {
- [
- info.title,
- info.description,
- info.value,
- info.help,
- ]
- .filter { !$0.isEmpty }
- .joined(separator: " ")
+ uniqueAXAttributeText([info.title, info.description, info.value, info.help])
}
func neutralNodes(from elements: [ElementInfo]) -> [NeutralAXNode] {
@@ -345,9 +349,7 @@ func neutralNodes(from elements: [ElementInfo]) -> [NeutralAXNode] {
}
func neutralNodeText(_ node: NeutralAXNode) -> String {
- [node.title, node.description, node.value, node.help]
- .filter { !$0.isEmpty }
- .joined(separator: " ")
+ uniqueAXAttributeText([node.title, node.description, node.value, node.help])
}
// One immutable parent-aware query context per AX capture. It normalizes
@@ -714,7 +716,8 @@ func addProjectOwnerIndices(in query: NeutralAXQuery) -> [Int] {
|| ownText.contains("openfolder")
else { return nil }
}
- guard isAddProjectPickerPresentation(
+ let rootPicker = node.role == "AXSheet" && [node.title, node.description].contains { normalized($0) == "selectprojectroot" }
+ guard rootPicker || isAddProjectPickerPresentation(
node.role,
query.visibleDescendantText[index],
hasOpenPanel: hasOpenPanel
@@ -753,6 +756,7 @@ func pickerSelectionConfirmed(
effort: String?
) -> Bool {
if categoryPrefix == "Model " {
+ if let requested = codexModelIdentity(targetLabel) { return codexModelIdentity(model ?? "") == requested }
return normalized(model ?? "").contains(normalized(targetLabel))
}
if categoryPrefix == "Effort " {
@@ -820,8 +824,8 @@ func workspaceShortcut(_ payload: String) -> WorkspaceShortcutSpec? {
case "files":
return WorkspaceShortcutSpec(
label: "Files",
- key: 35,
- flags: .maskCommand
+ key: 14,
+ flags: [.maskCommand, .maskShift]
)
case "side-chat":
return WorkspaceShortcutSpec(
diff --git a/native/Claude.swift b/native/Claude.swift
new file mode 100644
index 0000000..37c85c9
--- /dev/null
+++ b/native/Claude.swift
@@ -0,0 +1,1263 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+// Claude uses its own surface/identity contract. Never reuse Codex selectors.
+struct ProviderTarget: Codable, Equatable {
+ let provider: String
+ let windowId: String
+ let sessionId: String
+ let environment: String
+}
+struct ProviderChoice: Codable { let value: String; let label: String }
+struct ProviderSessionInfo: Codable {
+ let id: String
+ let title: String
+ let environment: String
+}
+struct ProviderState: Codable {
+ var foreground: String? = nil
+ var target: ProviderTarget? = nil
+ var reason: String? = nil
+ var model: String? = nil
+ var effort: String? = nil
+ var permission: String? = nil
+ var draftEmpty: Bool? = nil
+ var recording: Bool? = nil
+ var fast: Bool? = nil
+ var ultracode: Bool? = nil
+ var weeklyUsedPercent: Double? = nil
+ var weeklyBucket: String? = nil
+ var usageUsedPercent: Double? = nil
+ var usagePeriod: String? = nil
+ var usageBucket: String? = nil
+ var usageAvailability: String? = nil
+ var weeklyResetsAvailable: Int? = nil
+ var fableResetsAvailable: Int? = nil
+ var contextUsedPercent: Double? = nil
+ var contextAvailability: String? = nil
+ var readOnlyScope: String? = nil
+ var sessions: [ProviderSessionInfo]? = nil
+ var capabilities: [String] = []
+ var options: [ProviderChoice]? = nil
+ var observedAt: Double = Date().timeIntervalSince1970 * 1000
+}
+struct ClaudeRequest: Codable {
+ let operation: String
+ let target: ProviderTarget
+ let value: String?
+}
+
+// Native transactions are qualified separately by environment; see the dated
+// compatibility record for tested Desktop versions and hardware acceptance.
+let commonClaudeCapabilities: Set = [
+ "model", "model-options", "reasoning", "reasoning-options", "permission-cycle",
+ "plan", "fast", "sidebar", "review-panel", "usage", "context", "files", "send", "stop", "new-chat", "workflow", "compact", "settings", "skills", "side-chat", "dictate", "dictation-stop"
+]
+let verifiedClaudeCapabilities: [String: Set] = [
+ "local": commonClaudeCapabilities.union(["browser"]),
+ "ssh": commonClaudeCapabilities.union(["browser"]),
+ "cloud": commonClaudeCapabilities.union(["browser"])
+]
+func claudeDevelopmentProbe(_ environment: String) -> Bool {
+ ProcessInfo.processInfo.environment["STREAMDECK_CLAUDE_ACCEPTANCE_ENVIRONMENT"] == environment
+}
+func claudeEnvironmentAccepted(_ environment: String) -> Bool {
+ verifiedClaudeCapabilities[environment] != nil || claudeDevelopmentProbe(environment)
+}
+
+let claudeBundleId = "com.anthropic.claudefordesktop"
+let claudeAccessibilityDefaultsSuite = "com.todd.streamdeckcodex.native"
+let claudeAccessibilityGenerationKey = "claude-accessibility-generation"
+func claudeAccessibilityGeneration(pid: pid_t, launchDate: Date?) -> String {
+ let launchMilliseconds = Int64((launchDate ?? .distantPast).timeIntervalSince1970 * 1_000)
+ return "\(pid):\(launchMilliseconds)"
+}
+func claudeAccessibilityNeedsInitialization(cachedGeneration: String?, currentGeneration: String) -> Bool {
+ cachedGeneration != currentGeneration
+}
+func claudeDiagnostic(_ text: String) {
+ guard ProcessInfo.processInfo.environment["STREAMDECK_CLAUDE_DIAGNOSTICS"] == "1" else { return }
+ FileHandle.standardError.write(Data((text + "\n").utf8))
+}
+func providerDesktopUnavailableReason(_ session: [String: Any]?) -> String? {
+ guard let session, (session[kCGSessionOnConsoleKey as String] as? NSNumber)?.boolValue == true else { return "NO DESKTOP" }
+ return (session["CGSSessionScreenIsLocked"] as? NSNumber)?.boolValue == true ? "LOCKED" : nil
+}
+func providerDesktopState() -> String? {
+ providerDesktopUnavailableReason(CGSessionCopyCurrentDictionary() as? [String: Any])
+}
+func providerForeground() -> String? {
+ guard providerDesktopState() == nil else { return nil }
+ switch NSWorkspace.shared.frontmostApplication?.bundleIdentifier {
+ case "com.openai.codex": return "codex"
+ case claudeBundleId: return "claude"
+ default: return nil
+ }
+}
+
+func claudeSessionIdentifier(_ value: String) -> String? {
+ if value.range(of: "^session_[A-Za-z0-9]{24}$", options: .regularExpression) != nil { return value }
+ let raw = value.hasPrefix("local_") ? String(value.dropFirst(6)) : value
+ guard UUID(uuidString: raw) != nil else { return nil }
+ return value.lowercased()
+}
+
+// A URL is identity evidence only for the Code route and a complete session ID.
+// No title matching, sidebar recency, or Chat/Cowork fallback.
+func claudeCodeSessionId(_ url: String) -> String? {
+ guard let parsed = URLComponents(string: url),
+ ["https", "http", "claude"].contains(parsed.scheme ?? ""),
+ parsed.scheme == "claude" || ["claude.ai", "localhost"].contains(parsed.host ?? "")
+ else { return nil }
+ let parts = parsed.path.split(separator: "/").map(String.init)
+ guard parts.count == 2,
+ ["code", "epitaxy", "claude-code-desktop"].contains(parts[0]),
+ claudeSessionIdentifier(parts[1]) != nil
+ else { return nil }
+ return claudeSessionIdentifier(parts[1])
+}
+
+struct ClaudeMetadata {
+ let id: String
+ let aliases: Set
+ let title: String
+ let environment: String
+ var cwd: String? = nil
+ var cloudWorkspace: String? = nil
+}
+// Desktop metadata includes prompt snapshots and can exceed 256 KiB. Bound
+// the read itself, including files that grow between stat and read.
+let claudeMetadataByteLimit = 4 * 1024 * 1024
+func claudeMetadataData(_ file: URL) -> Data? {
+ guard let handle = try? FileHandle(forReadingFrom: file) else { return nil }
+ defer { try? handle.close() }
+ guard let data = try? handle.read(upToCount: claudeMetadataByteLimit + 1),
+ data.count <= claudeMetadataByteLimit else { return nil }
+ return data
+}
+func claudeMetadata() -> [ClaudeMetadata] {
+ let root = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/Claude/claude-code-sessions")
+ let fm = FileManager.default
+ var rows: [ClaudeMetadata] = []
+ // Bounded known directory depth; never traverse transcripts or credentials.
+ let accounts = (try? fm.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []
+ for account in accounts.prefix(100) {
+ let projects = (try? fm.contentsOfDirectory(at: account, includingPropertiesForKeys: nil)) ?? []
+ for project in projects.prefix(100) {
+ let files = (try? fm.contentsOfDirectory(at: project, includingPropertiesForKeys: [.fileSizeKey])) ?? []
+ for file in files.filter({ $0.pathExtension == "json" }).prefix(1000) {
+ guard let size = try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize,
+ size <= claudeMetadataByteLimit,
+ let data = claudeMetadataData(file),
+ let record = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let id = record["sessionId"] as? String,
+ claudeSessionIdentifier(id) != nil,
+ record["isArchived"] as? Bool != true
+ else { continue }
+ let aliases = Set([id, record["cliSessionId"] as? String].compactMap { $0?.lowercased() })
+ let environment: String
+ if record["sshConfig"] is [String: Any] { environment = "ssh" }
+ else if record["isRemote"] as? Bool == true || record["cloudSessionId"] is String { environment = "cloud" }
+ else if let cwd = record["cwd"] as? String, cwd.hasPrefix("/"), record["cliSessionId"] is String { environment = "local" }
+ else { continue }
+ rows.append(ClaudeMetadata(id: id.lowercased(), aliases: aliases, title: String((record["title"] as? String ?? "Claude session").prefix(100)), environment: environment, cwd: record["cwd"] as? String))
+ }
+ }
+ }
+ return rows
+}
+
+func claudeCloudWorkspaceKey(environment: String, repository: String) -> String? {
+ guard !environment.isEmpty, environment.count <= 100, !environment.contains("\n"),
+ repository.range(of: "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", options: .regularExpression) != nil,
+ repository.count <= 200 else { return nil }
+ return Data((environment + "\n" + repository).utf8).base64EncodedString()
+}
+func claudeCloudWorkspace(_ snapshot: AXSnapshot) -> String? {
+ let cards = snapshot.elements.indices.filter { !snapshot.elements[$0].hidden && snapshot.elements[$0].role == "AXGroup" && snapshot.elements[$0].title == "Environment" }
+ guard cards.count == 1, let card = cards.first else { return nil }
+ let nodes = snapshot.elements.indices.filter { !snapshot.elements[$0].hidden && snapshot.query.isDescendant($0, of: card) }.map { snapshot.elements[$0] }
+ guard nodes.contains(where: { $0.role == "AXButton" && $0.description == "Edit cloud environment" }) else { return nil }
+ let names = nodes.filter { $0.role == "AXStaticText" && !$0.value.isEmpty }
+ let add = nodes.filter { $0.role == "AXButton" && $0.description == "Add repository…" }
+ guard names.count == 1, add.count == 1, let parent = add[0].parentIndex else { return nil }
+ let repositories = nodes.filter { $0.role == "AXPopUpButton" && $0.parentIndex == parent }
+ guard repositories.count == 1 else { return nil }
+ return claudeCloudWorkspaceKey(environment: names[0].value, repository: repositories[0].title)
+}
+
+func claudeCloudMetadata(_ snapshot: AXSnapshot, sessionId: String) -> ClaudeMetadata? {
+ guard sessionId.hasPrefix("session_"), claudeSessionIdentifier(sessionId) != nil else { return nil }
+ let headings = snapshot.elements.filter { !$0.hidden && $0.role == "AXButton" && $0.description.hasSuffix(", rename session") }
+ guard headings.count == 1 else { return nil }
+ let title = String(headings[0].description.dropLast(", rename session".count))
+ return ClaudeMetadata(id: sessionId, aliases: [sessionId], title: title, environment: "cloud", cloudWorkspace: claudeCloudWorkspace(snapshot))
+}
+
+func claudeUsageLabel(_ text: String) -> (weekly: Double?, bucket: String?, context: Double?, used: Double?, period: String?) {
+ func groups(_ pattern: String) -> [String]? {
+ guard let regex = try? NSRegularExpression(pattern: pattern),
+ let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return nil }
+ return (1.. String {
+ value.lowercased().split(whereSeparator: { $0.isWhitespace }).joined(separator: " ")
+}
+
+func claudeContextCard(_ snapshot: AXSnapshot) -> (used: Double?, empty: Bool) {
+ let cards = snapshot.elements.indices.filter {
+ let e = snapshot.elements[$0]
+ return !e.hidden && e.role == "AXGroup" && [e.title, e.description].contains {
+ $0 == "Context" || $0.range(of: "^Context [0-9]+(?:\\.[0-9]+)?%$", options: .regularExpression) != nil
+ }
+ }
+ guard cards.count == 1, let card = cards.first else { return (nil, false) }
+ let children = snapshot.elements.indices.filter { snapshot.query.isDescendant($0, of: card) && !snapshot.elements[$0].hidden }.map { snapshot.elements[$0] }
+ // Require the actual card controls as well as its name. Never parse a
+ // percentage from the transcript or add its per-category percentages.
+ guard children.contains(where: { $0.role == "AXButton" && [$0.title, $0.description].contains("Reorder Context") }) else { return (nil, false) }
+ let texts = children.filter { $0.role == "AXStaticText" }.map { $0.value.isEmpty ? $0.title : $0.value }
+ let values = texts.compactMap { text -> Double? in
+ guard text.range(of: "^[0-9]+(?:\\.[0-9]+)?% used$", options: .regularExpression) != nil,
+ let value = Double(text.dropLast("% used".count)), (0...100).contains(value) else { return nil }
+ return value
+ }
+ let cardNames = Set([snapshot.elements[card].title, snapshot.elements[card].description])
+ let headerValues = cardNames.compactMap { name -> Double? in
+ guard name.hasPrefix("Context "), name.hasSuffix("%"),
+ let value = Double(name.dropFirst("Context ".count).dropLast()), (0...100).contains(value) else { return nil }
+ return value
+ }
+ guard values.count <= 1, Set(headerValues).count <= 1,
+ values.first == nil || headerValues.first == nil || values.first == headerValues.first else { return (nil, false) }
+ let used = values.first ?? headerValues.first
+ return (used, used == nil && texts.contains("Send a message to see context usage."))
+}
+
+func claudeText(_ e: ElementInfo) -> String {
+ [e.title, e.description, e.value, e.help].filter { !$0.isEmpty }.joined(separator: " ")
+}
+func claudeButton(_ snapshot: AXSnapshot, labels: Set) -> ElementInfo? {
+ let matches = snapshot.elements.filter {
+ !$0.hidden && $0.enabled && ["AXButton", "AXPopUpButton", "AXMenuButton"].contains($0.role)
+ && labels.contains(claudeNormalized($0.title.isEmpty ? $0.description : $0.title))
+ }
+ return matches.count == 1 ? matches[0] : nil
+}
+func claudeModelControlLabel(_ text: String) -> String {
+ var value = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ if value.hasPrefix("Model: "), let suffix = value.range(of: " [0-9]+(?:\\.[0-9]+)?×(?: or more)? usage$", options: .regularExpression) {
+ value.removeSubrange(suffix)
+ }
+ if value.hasPrefix("Model: ") && value.hasSuffix(" · Ultracode") {
+ value = String(value.dropLast(" · Ultracode".count))
+ }
+ return value
+}
+func claudePickLabel(_ text: String, kind: String) -> String? {
+ var value = claudeModelControlLabel(text)
+ // Current Desktop combines model and effort in one named pop-up button.
+ // Parse only the anchored control label; ordinary transcript text cannot match.
+ if value.hasPrefix("Model: ") {
+ var combined = String(value.dropFirst(7))
+ if combined.hasSuffix(" Fast") { combined = String(combined.dropLast(5)) }
+ for effort in ["Ultracode", "Extra high", "Medium", "High", "Extra", "Low", "Max", "Ultra"] {
+ guard combined.hasSuffix(" " + effort) else { continue }
+ let model = String(combined.dropLast(effort.count + 1))
+ if let valid = claudePickLabel(model, kind: "model") {
+ if kind == "model" { return valid }
+ if kind == "reasoning" { return effort }
+ }
+ }
+ }
+ let prefix = kind == "model" ? "Model: " : kind == "reasoning" ? "Effort: " : "Permissions: "
+ if !prefix.isEmpty && value.hasPrefix(prefix) { value = String(value.dropFirst(prefix.count)) }
+ if kind == "model" && value.hasSuffix(" Fast") { value = String(value.dropLast(5)) }
+ guard value.count <= 100 else { return nil }
+ if kind == "model", value.range(of: "^(?:Claude )?(?:Opus|Sonnet|Haiku|Fable) [0-9]+(?:\\.[0-9]+)*(?: \\([^)]*\\))?$", options: .regularExpression) != nil { return value }
+ if kind == "reasoning", ["Low", "Medium", "High", "Extra", "Max", "Extra high", "Ultra", "Ultracode"].contains(value) { return value }
+ if kind == "permission", ["Manual", "Accept edits", "Plan", "Auto", "Bypass permissions", "Ask permissions", "Auto accept edits", "Plan mode"].contains(value) { return value }
+ return nil
+}
+func claudeFastLabel(_ text: String) -> Bool {
+ var value = claudeModelControlLabel(text)
+ if let effort = claudePickLabel(value, kind: "reasoning"), value.hasSuffix(" " + effort) {
+ value = String(value.dropLast(effort.count + 1))
+ }
+ return value.hasSuffix(" Fast")
+}
+func captureClaudeSnapshot(_ root: AXUIElement) -> AXSnapshot {
+ captureAXSnapshot(root, maximumDepth: 72)
+}
+func claudeMenuOpen(_ snapshot: AXSnapshot) -> Bool {
+ snapshot.elements.contains { !$0.hidden && ["AXMenu", "AXMenuItem"].contains($0.role) }
+}
+func claudeKey(_ key: CGKeyCode, app: NSRunningApplication, flags: CGEventFlags = []) {
+ let source = CGEventSource(stateID: .hidSystemState)
+ for down in [true, false] {
+ let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: down)
+ event?.flags = flags
+ event?.postToPid(app.processIdentifier)
+ }
+}
+func claudePicker(_ snapshot: AXSnapshot, kind: String) -> (ElementInfo, String)? {
+ let matches = snapshot.elements.compactMap { e -> (ElementInfo, String)? in
+ guard !e.hidden, e.enabled, ["AXButton", "AXPopUpButton"].contains(e.role) else { return nil }
+ for text in [e.title, e.description] {
+ if let label = claudePickLabel(text, kind: kind) { return (e, label) }
+ }
+ return nil
+ }
+ return matches.count == 1 ? matches[0] : nil
+}
+func claudeContentSessionIds(_ snapshot: AXSnapshot) -> Set {
+ Set(snapshot.elements.filter { ["AXWebArea", "AXWindow"].contains($0.role) }.compactMap { e -> String? in
+ let value = attribute(e.element, kAXURLAttribute as CFString)
+ return claudeCodeSessionId((value as? URL)?.absoluteString ?? (value as? String) ?? "")
+ })
+}
+
+// Unsaved Code drafts have no session UUID. Correlate the exact Code start
+// route, unique heading/composer, and selected local folder. Mutations also
+// compare the draft itself; this identity never authorizes an existing chat.
+func claudeCanonicalFolder(_ path: String, environment: String) -> String {
+ let url = URL(fileURLWithPath: path).standardizedFileURL
+ return environment == "local" ? url.resolvingSymlinksInPath().path : url.path
+}
+func claudeDraftMetadata(_ snapshot: AXSnapshot) -> ClaudeMetadata? {
+ let routes = snapshot.elements.filter { $0.role == "AXWebArea" }.compactMap { e -> String? in
+ let raw = attribute(e.element, kAXURLAttribute as CFString)
+ return (raw as? URL)?.absoluteString ?? (raw as? String)
+ }
+ guard routes.contains("https://claude.ai/epitaxy"),
+ snapshot.elements.filter({ !$0.hidden && $0.role == "AXHeading" && $0.title == "New session" }).count == 1 else { return nil }
+ let root = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/Claude")
+ func json(_ name: String) -> [String: Any]? {
+ guard let data = claudeMetadataData(root.appendingPathComponent(name)) else { return nil }
+ return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
+ }
+ guard let account = json("config.json")?["lastKnownAccountUuid"] as? String, UUID(uuidString: account) != nil else { return nil }
+ let environments = snapshot.elements.filter { !$0.hidden && $0.enabled && $0.role == "AXPopUpButton" && $0.description.hasPrefix("Environment: ") }
+ guard environments.count == 1 else { return nil }
+ let environmentLabel = String(environments[0].description.dropFirst(13))
+ let repositories = snapshot.elements.filter { !$0.hidden && $0.enabled && $0.role == "AXComboBox" && [$0.title, $0.description].contains("Add repository") }
+ if repositories.count == 1, let workspace = claudeCloudWorkspaceKey(environment: environmentLabel, repository: repositories[0].value) {
+ let branches = snapshot.elements.filter { !$0.hidden && $0.enabled && $0.role == "AXPopUpButton" && $0.description.hasPrefix("Branch: ") }
+ guard branches.count == 1, branches[0].description.count > 8 else { return nil }
+ let id = "draft:" + account + ":cloud:" + workspace + ":" + Data(branches[0].description.utf8).base64EncodedString()
+ return ClaudeMetadata(id: id, aliases: [id], title: "New session", environment: "cloud", cloudWorkspace: workspace)
+ }
+ if environmentLabel == "This computer" {
+ let folders = snapshot.elements.filter { !$0.hidden && $0.enabled && $0.role == "AXPopUpButton" && ($0.description.hasPrefix("Folder: /") || $0.title.hasPrefix("Folder: /")) }
+ guard folders.count == 1 else { return nil }
+ let label = folders[0].description.hasPrefix("Folder: /") ? folders[0].description : folders[0].title
+ let path = String(label.dropFirst(8))
+ guard path.hasPrefix("/"), !path.contains("\n") else { return nil }
+ let cwd = claudeCanonicalFolder(path, environment: "local")
+ let id = "draft:" + account + ":" + Data(cwd.utf8).base64EncodedString()
+ return ClaudeMetadata(id: id, aliases: [id], title: "New session", environment: "local", cwd: cwd)
+ }
+ // Saved environments own their folder; the composer intentionally omits a
+ // Folder control. Correlate the visible unique name with this account's
+ // exact preset ID, target kind and path, never with session recency.
+ guard let byAccount = json("ccd-session-presets.json")?["byAccount"] as? [String: Any],
+ let owned = byAccount[account] as? [String: Any], let presets = owned["presets"] as? [[String: Any]] else { return nil }
+ let matches = presets.filter { $0["name"] as? String == environmentLabel }
+ guard matches.count == 1, let preset = matches.first, let presetId = preset["id"] as? String, UUID(uuidString: presetId) != nil,
+ let target = preset["target"] as? [String: Any], let kind = target["kind"] as? String, ["local", "ssh"].contains(kind),
+ let path = target["cwd"] as? String, path.hasPrefix("/"), !path.contains("\n"),
+ kind != "ssh" || target["sshConfigId"] is String,
+ json("config.json")?["lastKnownAccountUuid"] as? String == account else { return nil }
+ let cwd = claudeCanonicalFolder(path, environment: kind)
+ let id = "draft:" + account + ":" + presetId + ":" + Data(cwd.utf8).base64EncodedString()
+ return ClaudeMetadata(id: id, aliases: [id], title: "New session", environment: kind, cwd: cwd)
+}
+
+// A first-use Bypass modal hides the composer but keeps the Code session URL.
+// Recognize only its exact container and its two buttons, never transcript text.
+func claudeBypassConfirmation(_ snapshot: AXSnapshot) -> ElementInfo? {
+ let dialogs = snapshot.elements.enumerated().filter { _, e in
+ !e.hidden && ["AXGroup", "AXDialog", "AXSheet"].contains(e.role)
+ && [e.title, e.description].contains("Bypass all permissions?")
+ }
+ guard dialogs.count == 1, let dialog = dialogs.first else { return nil }
+ func inside(_ index: Int) -> Bool {
+ var parent = snapshot.elements[index].parentIndex
+ while let current = parent {
+ if current == dialog.offset { return true }
+ parent = snapshot.elements[current].parentIndex
+ }
+ return false
+ }
+ let buttons = snapshot.elements.enumerated().filter { index, e in
+ inside(index) && !e.hidden && e.enabled && e.role == "AXButton"
+ }.map { $0.element }
+ let confirm = buttons.filter { [ $0.title, $0.description ].contains("Bypass permissions") }
+ let cancel = buttons.filter { [ $0.title, $0.description ].contains("Cancel") }
+ return confirm.count == 1 && cancel.count == 1 ? confirm[0] : nil
+}
+func claudeModelSwitchConfirmation(_ snapshot: AXSnapshot, from: String, to: String) -> ElementInfo? {
+ let dialogs = snapshot.elements.indices.filter {
+ let e = snapshot.elements[$0]
+ return !e.hidden && ["AXGroup", "AXDialog", "AXSheet"].contains(e.role)
+ && [e.title, e.description].contains("Switch model?")
+ }
+ guard dialogs.count == 1, let dialog = dialogs.first else { return nil }
+ let children = snapshot.elements.indices.filter { snapshot.query.isDescendant($0, of: dialog) && !snapshot.elements[$0].hidden }
+ guard children.contains(where: {
+ let e = snapshot.elements[$0]
+ return e.role == "AXStaticText" && [e.title, e.description, e.value].contains { $0.hasPrefix("This session is cached for \(from). Switching to \(to) means ") }
+ }) else { return nil }
+ let buttons = children.map { snapshot.elements[$0] }.filter { $0.role == "AXButton" && $0.enabled }
+ let confirm = buttons.filter { [$0.title, $0.description].contains("Switch model") }
+ let cancel = buttons.filter { [$0.title, $0.description].contains("Cancel") }
+ return confirm.count == 1 && cancel.count == 1 ? confirm[0] : nil
+}
+func confirmClaudeModelSwitchIfPresent(_ captured: ClaudeCapture, target: ProviderTarget, desired: String) throws -> Bool {
+ guard captured.state.target == target, providerForeground() == "claude", let original = captured.state.model,
+ let focused = attribute(captured.appElement, kAXFocusedWindowAttribute as CFString),
+ CFGetTypeID(focused) == AXUIElementGetTypeID(), sameElement(captured.window, focused as! AXUIElement)
+ else { throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH") }
+ let snapshot = captureClaudeSnapshot(captured.window)
+ guard claudeConfirmationSessionMatches(expected: captured.contentSessionId, current: claudeContentSessionIds(snapshot))
+ else { throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH") }
+ guard let button = claudeModelSwitchConfirmation(snapshot, from: original, to: desired) else { return false }
+ try pressAccessibilityControl(button.element)
+ return true
+}
+
+func claudeConfirmationSessionMatches(expected: String, current: Set) -> Bool {
+ current == Set([expected])
+}
+struct ClaudeCapture {
+ let contentSessionId: String
+ let app: NSRunningApplication
+ let appElement: AXUIElement
+ let window: AXUIElement
+ let snapshot: AXSnapshot
+ let composer: ElementInfo
+ let state: ProviderState
+}
+func captureClaude(requireForeground: Bool = true) throws -> ClaudeCapture {
+ if let reason = providerDesktopState() { throw ControlError.failed(reason, "NO_FOCUS") }
+ guard (!requireForeground || providerForeground() == "claude"),
+ let app = NSRunningApplication.runningApplications(withBundleIdentifier: claudeBundleId).first
+ else { throw ControlError.failed("BACKGROUND", "NO_FOCUS") }
+ guard AXIsProcessTrusted() else { throw ControlError.failed("ACCESS", "UNAVAILABLE") }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ AXUIElementSetMessagingTimeout(root, 0.5)
+ let accessibilityDefaults = UserDefaults(suiteName: claudeAccessibilityDefaultsSuite)
+ let accessibilityGeneration = claudeAccessibilityGeneration(pid: app.processIdentifier, launchDate: app.launchDate)
+ if claudeAccessibilityNeedsInitialization(
+ cachedGeneration: accessibilityDefaults?.string(forKey: claudeAccessibilityGenerationKey),
+ currentGeneration: accessibilityGeneration
+ ) {
+ let initialization = initializePickerAccessibility(
+ requireManual: true,
+ read: { boolAttribute(root, $0 as CFString) },
+ enable: { AXUIElementSetAttributeValue(root, $0 as CFString, kCFBooleanTrue) },
+ settle: { usleep(2_200_000) }
+ )
+ // The helper is launched once per transaction, while Claude continues to
+ // report ManualAccessibility=false after accepting the request. Persist the
+ // accepted process generation so background reads cannot starve dial events.
+ if initialization == "manual enabled" || initialization == "already enabled" {
+ accessibilityDefaults?.set(accessibilityGeneration, forKey: claudeAccessibilityGenerationKey)
+ }
+ }
+ let windows = attribute(root, kAXWindowsAttribute as CFString) as? [AXUIElement] ?? []
+ // AXFocused is an element keyboard-focus flag, not window identity. Claude's
+ // active window reports false there; the application exposes AXFocusedWindow.
+ guard let focusedValue = attribute(root, kAXFocusedWindowAttribute as CFString),
+ CFGetTypeID(focusedValue) == AXUIElementGetTypeID()
+ else { throw ControlError.failed("NO CHAT", "NO_FOCUS") }
+ let window = focusedValue as! AXUIElement
+ guard windows.filter({ sameElement($0, window) }).count == 1
+ else { throw ControlError.failed("NO CHAT", "NO_FOCUS") }
+ let snapshot = captureClaudeSnapshot(window)
+ // Only a content-root URL counts. Sidebar link URLs must not identify the target.
+ let ids = claudeContentSessionIds(snapshot)
+ claudeDiagnostic("Code roots: \(ids.count), AX nodes: \(snapshot.elements.count)")
+ if ids.isEmpty, let project = captureClaudeProject(snapshot) { return project }
+ let draft = ids.isEmpty ? claudeDraftMetadata(snapshot) : nil
+ guard ids.count == 1 || draft != nil, let sessionId = ids.first ?? draft?.id else {
+ throw ControlError.failed(ids.count > 1 ? "WRONG CHAT" : "UNSUPPORTED", "TARGET_MISMATCH")
+ }
+ let composers = snapshot.elements.indices.filter { claudeMainComposer(snapshot, index: $0) }.map { snapshot.elements[$0] }
+ guard composers.count == 1 else { throw ControlError.failed(composers.isEmpty ? "NO DATA" : "WRONG CHAT", "TARGET_MISMATCH") }
+ // Cloud sessions have no local session JSON. Correlate the exact Code
+ // content route with the session heading and main Code composer. The
+ // Cloud environment card independently establishes this route family during
+ // qualification, but is hidden when Files/Changes panes are open.
+ let cloud = claudeCloudMetadata(snapshot, sessionId: sessionId)
+ let metadata = draft.map { [$0] } ?? cloud.map { [$0] } ?? claudeMetadata().filter { $0.aliases.contains(sessionId) }
+ claudeDiagnostic("Matching metadata: \(metadata.count)")
+ guard metadata.count == 1 else { throw ControlError.failed("UNSUPPORTED", "TARGET_MISMATCH") }
+ let row = metadata[0]
+ let frame = snapshot.elements.first?.elementFrame
+ let matches = (CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] ?? []).filter { info in
+ guard (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == app.processIdentifier,
+ let bounds = info[kCGWindowBounds as String] as? [String: Any],
+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary), let frame else { return false }
+ return abs(rect.minX - frame.minX) < 2 && abs(rect.minY - frame.minY) < 2
+ && abs(rect.width - frame.width) < 2 && abs(rect.height - frame.height) < 2
+ }
+ let windowNumber = matches.count == 1 ? (matches[0][kCGWindowNumber as String] as? NSNumber)?.stringValue : nil
+ claudeDiagnostic("Matching windows: \(matches.count)")
+ guard let windowNumber else { throw ControlError.failed("UNSUPPORTED", "TARGET_MISMATCH") }
+ var state = ProviderState(foreground: "claude")
+ state.target = ProviderTarget(provider: "claude", windowId: "\(app.processIdentifier):\(windowNumber)", sessionId: row.id, environment: row.environment)
+ let modelPicker = claudePicker(snapshot, kind: "model")
+ state.model = modelPicker?.1
+ if let picker = modelPicker {
+ state.fast = claudeFastLabel(picker.0.description) || claudeFastLabel(picker.0.title)
+ state.ultracode = [picker.0.title, picker.0.description].contains { $0.contains(" · Ultracode") }
+ }
+ state.effort = claudePicker(snapshot, kind: "reasoning")?.1
+ state.permission = claudePicker(snapshot, kind: "permission")?.1
+ state.draftEmpty = composers[0].value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ state.sessions = [ProviderSessionInfo(id: row.id, title: row.title, environment: row.environment)]
+ let usageControls = snapshot.elements.filter {
+ !$0.hidden && $0.role == "AXPopUpButton" && $0.description.hasPrefix("Usage:")
+ }
+ if usageControls.count == 1 {
+ let usage = claudeUsageLabel(usageControls[0].description)
+ state.weeklyUsedPercent = usage.weekly
+ state.weeklyBucket = usage.bucket
+ state.contextUsedPercent = usage.context
+ state.usageUsedPercent = usage.used
+ state.usagePeriod = usage.period
+ state.usageBucket = usage.bucket
+ }
+ state.usageAvailability = state.usageUsedPercent == nil ? "unavailable" : "ready"
+ let contextCard = claudeContextCard(snapshot)
+ if let used = contextCard.used { state.contextUsedPercent = used }
+ state.contextAvailability = state.contextUsedPercent != nil ? "ready" : contextCard.empty ? "empty" : "unavailable"
+ // Environment acceptance is explicit: unverified combinations remain unsupported.
+ // The source includes guarded picker operations for the hardware acceptance build.
+ // Legacy Fast was Opus-only. The combined picker exposes it on newer
+ // models too; execution still requires the offered toggle and verifies it.
+ if state.model == "Opus 5" || modelPicker.map({ picker in
+ [picker.0.title, picker.0.description].contains { $0.hasPrefix("Model: ") && claudePickLabel($0, kind: "reasoning") != nil }
+ }) == true {
+ state.capabilities.append("fast")
+ }
+ for operation in ["review-panel", "browser", "files"] where claudePaneControl(snapshot, operation: operation) != nil {
+ state.capabilities.append(operation)
+ }
+ if claudeButton(snapshot, labels: ["hide sidebar", "show sidebar"]) != nil { state.capabilities.append("sidebar") }
+ if state.usageUsedPercent != nil { state.capabilities.append("usage") }
+ if state.contextUsedPercent != nil { state.capabilities.append("context") }
+ if row.cwd != nil || row.cloudWorkspace != nil { state.capabilities += ["new-chat", "workflow"] }
+ if !row.id.hasPrefix("draft:") { state.capabilities += ["compact", "side-chat"] }
+ if claudeButton(snapshot, labels: ["code settings"]) != nil { state.capabilities.append("settings") }
+ if claudeButton(snapshot, labels: ["add"]) != nil { state.capabilities.append("skills") }
+ if let recording = claudeRecordingControl(snapshot) {
+ state.recording = claudeToggleValue(recording.element)
+ state.capabilities += ["dictate", "dictation-stop"]
+ }
+ if state.model != nil { state.capabilities += ["model", "model-options"] }
+ if state.effort != nil { state.capabilities += ["reasoning", "reasoning-options"] }
+ if state.permission != nil { state.capabilities += ["permission-cycle", "plan"] }
+ if claudeButton(snapshot, labels: ["send", "send message"]) != nil { state.capabilities.append("send") }
+ if claudeButton(snapshot, labels: ["stop", "stop response"]) != nil { state.capabilities.append("stop") }
+ if !claudeDevelopmentProbe(row.environment) {
+ state.capabilities = state.capabilities.filter {
+ verifiedClaudeCapabilities[row.environment]?.contains($0) == true
+ }
+ }
+ if !claudeEnvironmentAccepted(row.environment) { state.reason = "UNVERIFIED" }
+ guard (!requireForeground || providerForeground() == "claude"),
+ let finalWindow = attribute(root, kAXFocusedWindowAttribute as CFString),
+ CFGetTypeID(finalWindow) == AXUIElementGetTypeID(),
+ sameElement(window, finalWindow as! AXUIElement)
+ else { throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH") }
+ return ClaudeCapture(contentSessionId: sessionId, app: app, appElement: root, window: window, snapshot: snapshot, composer: composers[0], state: state)
+}
+
+// Account-level readings only, scoped to the visible Settings > Usage surface.
+// This parser never invokes the adjacent redemption buttons.
+func claudeResetBalances(_ query: NeutralAXQuery) -> (weekly: Int, fable: Int)? {
+ let headings = query.nodes.indices.filter { query.ownerIsVisible($0) && query.nodes[$0].role == "AXHeading" && neutralNodeText(query.nodes[$0]) == "Limit resets" }
+ guard headings.count == 1, let heading = headings.first else { return nil }
+ var owner = query.parents[heading]
+ while let index = owner {
+ defer { owner = query.parents[index] }
+ guard query.nodes[index].role == "AXGroup", neutralNodeText(query.nodes[index]) == "Settings" else { continue }
+ let children = query.nodes.indices.filter { query.ownerIsVisible($0) && query.isDescendant($0, of: index) }
+ guard children.contains(where: { query.nodes[$0].role == "AXHeading" && neutralNodeText(query.nodes[$0]) == "Your usage" }) else { continue }
+ let totals = children.compactMap { i -> Int? in
+ let text = neutralNodeText(query.nodes[i])
+ guard query.nodes[i].role == "AXStaticText", text.range(of: "^[0-9]+ available$", options: .regularExpression) != nil else { return nil }
+ return Int(text.components(separatedBy: " ")[0])
+ }
+ guard totals.count == 1, let total = totals.first, total <= 999 else { return nil }
+ var counts: [String: Int] = [:]
+ for i in children where query.nodes[i].role == "AXGroup" {
+ let text = neutralNodeText(query.nodes[i])
+ guard text.range(of: "^(Weekly|Fable) reset(?: · [0-9]+)?$", options: .regularExpression) != nil else { continue }
+ let type = text.hasPrefix("Weekly") ? "weekly" : "fable"
+ guard counts[type] == nil,
+ children.contains(where: { query.isDescendant($0, of: i) && ["AXButton", "AXPopUpButton"].contains(query.nodes[$0].role) && neutralNodeText(query.nodes[$0]) == "Reset for free " + text }) else { return nil }
+ let parts = text.components(separatedBy: " · ")
+ guard let count = parts.count == 1 ? 1 : Int(parts[1]), count <= 999 else { return nil }
+ counts[type] = count
+ }
+ let weekly = counts["weekly"] ?? 0, fable = counts["fable"] ?? 0
+ guard weekly + fable == total else { return nil }
+ return (weekly, fable)
+ }
+ return nil
+}
+
+func observeClaudeResetBalances() -> (weekly: Int, fable: Int)? {
+ guard providerForeground() == "claude", let app = NSRunningApplication.runningApplications(withBundleIdentifier: claudeBundleId).first else { return nil }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ guard let value = attribute(root, kAXFocusedWindowAttribute as CFString), CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
+ let window = value as! AXUIElement
+ let result = claudeResetBalances(captureClaudeSnapshot(window).query)
+ guard providerForeground() == "claude", let final = attribute(root, kAXFocusedWindowAttribute as CFString), CFGetTypeID(final) == AXUIElementGetTypeID(), sameElement(window, final as! AXUIElement) else { return nil }
+ return result
+}
+
+// Projects have a separate identity contract and independently verified controls.
+func claudeProjectId(_ value: String) -> String? {
+ guard let url = URLComponents(string: value), url.scheme == "https", url.host == "claude.ai", url.user == nil, url.password == nil, url.port == nil else { return nil }
+ let parts = url.path.split(separator: "/").map(String.init)
+ guard parts.count == 3, parts[0] == "epitaxy", parts[1] == "project",
+ parts[2].range(of: "^chan_[A-Za-z0-9]{16,40}$", options: .regularExpression) != nil else { return nil }
+ return parts[2]
+}
+func claudeProjectUsage(_ text: String, scope: String) -> ProviderState? {
+ let usage = claudeUsageLabel(text)
+ guard usage.used != nil else { return nil }
+ var state = ProviderState(foreground: "claude", reason: "PROJECT VIEW")
+ state.readOnlyScope = scope
+ state.usageUsedPercent = usage.used; state.usagePeriod = usage.period; state.usageBucket = usage.bucket
+ state.usageAvailability = "ready"
+ state.contextAvailability = text.hasSuffix(", Compacts automatically") ? "automatic" : "unavailable"
+ return state
+}
+func captureClaudeProject(_ existingSnapshot: AXSnapshot? = nil) -> ClaudeCapture? {
+ guard providerForeground() == "claude", let app = NSRunningApplication.runningApplications(withBundleIdentifier: claudeBundleId).first else { return nil }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ guard let value = attribute(root, kAXFocusedWindowAttribute as CFString), CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
+ let window = value as! AXUIElement
+ let snapshot = existingSnapshot ?? captureClaudeSnapshot(window)
+ let roots = snapshot.elements.indices.compactMap { i -> (Int, String)? in
+ let element = snapshot.elements[i]
+ guard snapshot.query.ownerIsVisible(i), element.role == "AXWebArea" else { return nil }
+ let raw = attribute(element.element, kAXURLAttribute as CFString)
+ guard let id = claudeProjectId((raw as? URL)?.absoluteString ?? (raw as? String) ?? "") else { return nil }
+ return (i, id)
+ }
+ guard roots.count == 1, let project = roots.first, claudeContentSessionIds(snapshot).isEmpty else { return nil }
+ let children = snapshot.elements.indices.filter { snapshot.query.ownerIsVisible($0) && snapshot.query.isDescendant($0, of: project.0) }
+ let composers = children.filter { snapshot.elements[$0].role == "AXTextArea" && snapshot.elements[$0].enabled && [snapshot.elements[$0].title, snapshot.elements[$0].description].contains("Write your prompt to Claude") }
+ let controls = children.filter { snapshot.elements[$0].role == "AXPopUpButton" && snapshot.elements[$0].description.hasPrefix("Usage:") }
+ guard composers.count == 1, controls.count == 1,
+ var state = claudeProjectUsage(snapshot.elements[controls[0]].description, scope: project.1),
+ providerForeground() == "claude", let final = attribute(root, kAXFocusedWindowAttribute as CFString), CFGetTypeID(final) == AXUIElementGetTypeID(), sameElement(window, final as! AXUIElement) else { return nil }
+ // Re-read the content URL to reject navigation during the snapshot.
+ let finalURL = attribute(snapshot.elements[project.0].element, kAXURLAttribute as CFString)
+ guard claudeProjectId((finalURL as? URL)?.absoluteString ?? (finalURL as? String) ?? "") == project.1 else { return nil }
+ let frame = snapshot.elements.first?.elementFrame
+ let matches = (CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] ?? []).filter { info in
+ guard (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == app.processIdentifier,
+ let bounds = info[kCGWindowBounds as String] as? [String: Any], let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary), let frame else { return false }
+ return abs(rect.minX-frame.minX)<2 && abs(rect.minY-frame.minY)<2 && abs(rect.width-frame.width)<2 && abs(rect.height-frame.height)<2
+ }
+ guard matches.count == 1, let number = (matches[0][kCGWindowNumber as String] as? NSNumber)?.stringValue,
+ let picker = claudePicker(snapshot, kind: "model") else { return nil }
+ state.target = ProviderTarget(provider: "claude", windowId: "\(app.processIdentifier):\(number)", sessionId: project.1, environment: "cloud")
+ state.model = picker.1
+ state.effort = "Fixed"
+ state.reason = nil
+ state.draftEmpty = snapshot.elements[composers[0]].value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ state.capabilities = ["model", "model-options", "usage"]
+ return ClaudeCapture(contentSessionId: project.1, app: app, appElement: root, window: window, snapshot: snapshot, composer: snapshot.elements[composers[0]], state: state)
+}
+
+func observeProviderState() -> ProviderState {
+ if let reason = providerDesktopState() { return ProviderState(reason: reason) }
+ guard providerForeground() == "claude" else { return ProviderState(foreground: providerForeground()) }
+ var state: ProviderState
+ do { state = try captureClaude().state }
+ catch { state = ProviderState(foreground: "claude", reason: error.localizedDescription) }
+ if state.readOnlyScope == nil, let resets = observeClaudeResetBalances() {
+ state.weeklyResetsAvailable = resets.weekly
+ state.fableResetsAvailable = resets.fable
+ }
+ return state
+}
+func claudeComposerContinuity(sameComposer: Bool, confirmedDialog: Bool, sameSession: Bool, sameDraft: Bool) -> Bool {
+ sameComposer || (confirmedDialog && sameSession && sameDraft)
+}
+func verifyClaude(_ captured: ClaudeCapture, target: ProviderTarget, afterConfirmation: Bool = false) throws -> ClaudeCapture {
+ let current = try captureClaude()
+ guard current.state.target == target,
+ sameElement(captured.window, current.window),
+ claudeComposerContinuity(sameComposer: sameElement(captured.composer.element, current.composer.element), confirmedDialog: afterConfirmation, sameSession: captured.contentSessionId == current.contentSessionId, sameDraft: captured.composer.value == current.composer.value)
+ else { throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH") }
+ return current
+}
+
+func confirmClaudeBypassIfPresent(_ captured: ClaudeCapture, target: ProviderTarget) throws -> Bool {
+ guard captured.state.target == target, providerForeground() == "claude",
+ let currentWindow = attribute(captured.appElement, kAXFocusedWindowAttribute as CFString),
+ CFGetTypeID(currentWindow) == AXUIElementGetTypeID(),
+ sameElement(captured.window, currentWindow as! AXUIElement)
+ else { throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH") }
+ let snapshot = captureClaudeSnapshot(captured.window)
+ let ids = claudeContentSessionIds(snapshot)
+ claudeDiagnostic("Bypass confirmation: roots=\(ids.count), sameSession=\(claudeConfirmationSessionMatches(expected: captured.contentSessionId, current: ids)), button=\(claudeBypassConfirmation(snapshot) != nil)")
+ guard claudeConfirmationSessionMatches(expected: captured.contentSessionId, current: ids)
+ else { throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH") }
+ guard let button = claudeBypassConfirmation(snapshot) else { return false }
+ try pressAccessibilityControl(button.element)
+ // During the opening animation Chromium can acknowledge AXPress without
+ // dispatching the click. Only record confirmation after the modal closes;
+ // the caller may retry the same verified dialog while it is still present.
+ usleep(150_000)
+ return claudeBypassConfirmation(captureClaudeSnapshot(captured.window)) == nil
+}
+
+func claudeNextPermission(current: String, offered: [String]) -> String? {
+ guard offered.count > 1, let index = offered.firstIndex(of: current) else { return nil }
+ return offered[(index + 1) % offered.count]
+}
+
+func claudePlanExitMode(previous: String?, offered: [String], defaultMode: String?) -> String? {
+ let modes = offered.filter { !["Plan", "Plan mode"].contains($0) }
+ if let previous, modes.contains(previous) { return previous }
+ if let defaultMode, modes.contains(defaultMode) { return defaultMode }
+ // First use without history or an app default still has a deterministic exit.
+ return modes.first { ["Manual", "Ask permissions"].contains($0) }
+}
+
+func claudeDefaultPermission(_ choices: [(ElementInfo, String)]) -> String? {
+ let marked = choices.filter { item, _ in
+ if [item.title, item.description].contains(where: { $0.hasSuffix(" Default") }) { return true }
+ return captureAXSnapshot(item.element, maximumDepth: 4).elements.contains {
+ $0.role == "AXStaticText" && ($0.value == "Default" || $0.title == "Default")
+ }
+ }.map { $0.1 }
+ return marked.count == 1 ? marked[0] : nil
+}
+
+let claudeEffortLevelNames = ["Low", "Medium", "High", "Extra", "Max", "Ultracode"]
+func claudeEffortOptions(range: ClosedRange, selected: Int?, currentLabel: String) -> [ProviderChoice]? {
+ guard range.lowerBound == 0, range.upperBound < claudeEffortLevelNames.count,
+ let selected, range.contains(selected), claudeEffortLevelNames[selected] == currentLabel
+ else { return nil }
+ return range.map { ProviderChoice(value: "slider:\($0)", label: claudeEffortLevelNames[$0]) }
+}
+
+func claudePermissionMenuLabel(_ text: String) -> String? {
+ if let exact = claudePickLabel(text, kind: "permission") { return exact }
+ let rows = [
+ ("Auto", "Auto , teach auto mode"),
+ ("Auto", "Auto Claude handles permission decisions"),
+ ("Manual", "Manual Always ask before making changes"),
+ ("Accept edits", "Accept edits Automatically accept all file edits"),
+ ("Plan", "Plan Create a plan before making changes"),
+ ("Bypass permissions", "Bypass permissions Accepts all permissions")
+ ]
+ return rows.first { text.hasPrefix($0.1) }?.0
+}
+
+func claudeMenuOptions(_ snapshot: AXSnapshot, kind: String) -> [(ElementInfo, String)] {
+ let choices: [(ElementInfo, String)] = snapshot.elements.compactMap { e in
+ guard !e.hidden, e.enabled, ["AXMenuItem", "AXRadioButton"].contains(e.role) else { return nil }
+ for value in [e.title, e.description] {
+ let menuValue = kind == "reasoning" && value.hasSuffix(" Recommended") ? String(value.dropLast(12)) : value
+ if let label = kind == "permission" ? claudePermissionMenuLabel(menuValue) : claudePickLabel(menuValue, kind: kind) { return (e, label) }
+ }
+ // Permission rows combine the mode label with explanatory copy. Read
+ // exact text labels inside this menu item, never arbitrary transcript text.
+ if kind == "permission" {
+ let labels = Set(captureAXSnapshot(e.element, maximumDepth: 4).elements.compactMap { child -> String? in
+ guard child.role == "AXStaticText" else { return nil }
+ return claudePickLabel(child.value.isEmpty ? child.title : child.value, kind: kind)
+ })
+ if labels.count == 1, let label = labels.first { return (e, label) }
+ }
+ return nil
+ }
+ // AX traversal is breadth-first; nested radio rows can follow independent
+ // toggles in traversal order. Preserve the actual displayed menu order.
+ return choices.sorted { a, b in
+ guard let left = a.0.elementFrame, let right = b.0.elementFrame else { return false }
+ return left.minY == right.minY ? left.minX < right.minX : left.minY < right.minY
+ }
+}
+
+func claudeEffortSlider(_ snapshot: AXSnapshot) -> ElementInfo? {
+ let sliders = snapshot.elements.filter {
+ !$0.hidden && $0.enabled && $0.role == "AXSlider"
+ && claudeNormalized($0.description) == "effort"
+ }
+ return sliders.count == 1 ? sliders[0] : nil
+}
+func claudeSliderRange(_ element: AXUIElement) -> ClosedRange? {
+ guard let low = attribute(element, kAXMinValueAttribute as CFString) as? NSNumber,
+ let high = attribute(element, kAXMaxValueAttribute as CFString) as? NSNumber,
+ low.doubleValue == Double(low.intValue), high.doubleValue == Double(high.intValue),
+ low.intValue >= 0, high.intValue > low.intValue, high.intValue - low.intValue <= 10
+ else { return nil }
+ return low.intValue...high.intValue
+}
+
+func claudeToggleValue(_ element: AXUIElement) -> Bool? {
+ guard let value = attribute(element, kAXValueAttribute as CFString) as? NSNumber,
+ [0, 1].contains(value.intValue) else { return nil }
+ return value.boolValue
+}
+
+func claudePaneControl(_ snapshot: AXSnapshot, operation: String) -> ElementInfo? {
+ let label = operation == "review-panel" ? "changes" : operation == "files" ? "files" : "browser"
+ let controls = snapshot.elements.filter {
+ !$0.hidden && $0.enabled && ["AXCheckBox", "AXButton"].contains($0.role)
+ && claudeNormalized($0.description.isEmpty ? $0.title : $0.description) == label
+ && claudeToggleValue($0.element) != nil
+ }
+ return controls.count == 1 ? controls[0] : nil
+}
+
+func executeClaudeProject(_ request: ClaudeRequest) throws -> ProviderState {
+ guard ["model", "model-options"].contains(request.operation),
+ let captured = captureClaudeProject(), captured.state.target == request.target,
+ let picker = claudePicker(captured.snapshot, kind: "model"), !claudeMenuOpen(captured.snapshot)
+ else { throw ControlError.failed("Project control unavailable", "UNAVAILABLE") }
+ func verify() throws -> ClaudeCapture {
+ guard let current = captureClaudeProject(), current.state.target == captured.state.target,
+ current.composer.value == captured.composer.value else { throw ControlError.failed("Target or draft changed", "TARGET_MISMATCH") }
+ return current
+ }
+ func dismiss() {
+ guard let current = try? verify(), claudeMenuOpen(current.snapshot) else { return }
+ claudeKey(53, app: captured.app)
+ }
+ _ = try verify()
+ try pressAccessibilityControl(picker.0.element)
+ defer { dismiss() }
+ guard let choices = waitUntil(timeout: 2, operation: { () -> [(ElementInfo, String)]? in
+ guard let current = try? verify() else { return nil }
+ let rows = claudeMenuOptions(current.snapshot, kind: "model")
+ return rows.isEmpty ? nil : rows
+ }), Set(choices.map { $0.1 }).count == choices.count else { throw ControlError.failed("Model menu unavailable", "UNAVAILABLE") }
+ if request.operation == "model-options" {
+ dismiss()
+ guard let after = waitUntil(timeout: 2, operation: { () -> ClaudeCapture? in
+ guard let current = try? verify(), !claudeMenuOpen(current.snapshot) else { return nil }; return current
+ }) else { throw ControlError.failed("Menu did not close", "UNCHANGED") }
+ var state = after.state; state.options = choices.map { ProviderChoice(value: $0.1, label: $0.1) }; return state
+ }
+ guard let desired = request.value, let choice = choices.first(where: { $0.1 == desired }) else { throw ControlError.failed("Model unavailable", "UNAVAILABLE") }
+ _ = try verify()
+ try pressAccessibilityControl(choice.0.element)
+ guard let state = waitUntil(timeout: 3, operation: { () -> ProviderState? in
+ guard let current = try? verify(), current.state.model == desired, !claudeMenuOpen(current.snapshot) else { return nil }; return current.state
+ }) else { throw ControlError.failed("Model selection unverified", "UNCHANGED") }
+ return state
+}
+
+func executeClaude(_ request: ClaudeRequest) throws -> ProviderState {
+ if request.target.sessionId.hasPrefix("chan_") { return try executeClaudeProject(request) }
+ let captured = try captureClaude(requireForeground: request.operation != "dictation-stop")
+ guard request.target.provider == "claude", captured.state.target == request.target else {
+ throw ControlError.failed("Target changed; select again", "TARGET_MISMATCH")
+ }
+ // No undocumented equivalent is substituted for unavailable PTT, Fast,
+ // workflow launch, approval requests, or remote controls.
+ guard captured.state.capabilities.contains(request.operation) else {
+ throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE")
+ }
+ if let extra = try executeClaudeExtra(request, captured: captured) { return extra }
+ if ["new-chat", "workflow"].contains(request.operation) {
+ guard !claudeMenuOpen(captured.snapshot), captured.state.draftEmpty == true,
+ let source = claudeDraftMetadata(captured.snapshot) ?? claudeCloudMetadata(captured.snapshot, sessionId: request.target.sessionId) ?? claudeMetadata().first(where: { $0.id == request.target.sessionId }),
+ source.cwd != nil || source.cloudWorkspace != nil else { throw ControlError.failed("Preserve current draft", "DRAFT_PRESENT") }
+ let canonical = source.cwd.map { claudeCanonicalFolder($0, environment: source.environment) }
+ _ = try verifyClaude(captured, target: request.target)
+ claudeKey(45, app: captured.app, flags: [.maskCommand, .maskShift])
+ guard let draft = waitUntil(timeout: 3, operation: { () -> ClaudeCapture? in
+ guard let current = try? captureClaude(), sameElement(current.window, captured.window),
+ current.state.draftEmpty == true, let destination = claudeDraftMetadata(current.snapshot), destination.environment == source.environment,
+ source.environment == "cloud" ? (destination.cloudWorkspace != nil && destination.cloudWorkspace == source.cloudWorkspace) : destination.cwd == canonical else { return nil }
+ return current
+ }) else { throw ControlError.failed("New session unverified", "UNCHANGED") }
+ if request.operation == "new-chat" { return draft.state }
+ guard let prompt = request.value, !prompt.isEmpty, prompt.utf8.count <= 32768 else { throw ControlError.failed("Invalid workflow", "UNAVAILABLE") }
+ _ = try verifyClaude(draft, target: draft.state.target!)
+ guard AXUIElementSetAttributeValue(draft.composer.element, kAXValueAttribute as CFString, prompt as CFString) == .success else { throw ControlError.failed("Draft insertion failed", "UNAVAILABLE") }
+ guard let after = waitUntil(timeout: 2, operation: { () -> ClaudeCapture? in
+ guard let current = try? verifyClaude(draft, target: draft.state.target!), current.composer.value.trimmingCharacters(in: .whitespacesAndNewlines) == prompt.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil }; return current
+ }) else { throw ControlError.failed("Workflow draft unverified", "UNCHANGED") }
+ return after.state
+ }
+ if ["review-panel", "browser", "files", "sidebar"].contains(request.operation) {
+ let control = request.operation == "sidebar"
+ ? claudeButton(captured.snapshot, labels: ["hide sidebar", "show sidebar"])
+ : claudePaneControl(captured.snapshot, operation: request.operation)
+ guard let control else { throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE") }
+ let originalValue = claudeToggleValue(control.element)
+ _ = try verifyClaude(captured, target: request.target)
+ try pressAccessibilityControl(control.element)
+ guard let result = waitUntil(timeout: 2, operation: { () -> ProviderState? in
+ guard let after = try? verifyClaude(captured, target: request.target),
+ after.composer.value == captured.composer.value else { return nil }
+ if request.operation == "sidebar" {
+ let label = claudeNormalized(control.title.isEmpty ? control.description : control.title)
+ let expected = label == "hide sidebar" ? "show sidebar" : "hide sidebar"
+ return claudeButton(after.snapshot, labels: [expected]) == nil ? nil : after.state
+ }
+ guard let current = claudePaneControl(after.snapshot, operation: request.operation), claudeToggleValue(current.element) != originalValue else { return nil }
+ return after.state
+ }) else { throw ControlError.failed("Pane change unverified", "UNCHANGED") }
+ return result
+ }
+ if ["model", "model-options", "reasoning", "reasoning-options", "permission-cycle", "plan", "fast"].contains(request.operation) {
+ let kind = (request.operation.hasPrefix("model") || request.operation == "fast") ? "model" : request.operation.hasPrefix("reasoning") ? "reasoning" : "permission"
+ guard let picker = claudePicker(captured.snapshot, kind: kind) else { throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE") }
+ _ = try verifyClaude(captured, target: request.target)
+ guard !claudeMenuOpen(captured.snapshot) else {
+ throw ControlError.failed("BUSY", "UNAVAILABLE")
+ }
+ func dismiss() {
+ for _ in 0..<3 {
+ guard providerForeground() == "claude",
+ let current = try? verifyClaude(captured, target: request.target),
+ claudeMenuOpen(current.snapshot) || claudeEffortSlider(current.snapshot) != nil else { return }
+ claudeKey(53, app: captured.app)
+ usleep(80_000)
+ }
+ }
+ defer { dismiss() }
+ let combinedEffort = kind == "reasoning" && [picker.0.title, picker.0.description].contains(where: { $0.hasPrefix("Model: ") })
+ if combinedEffort {
+ // Desktop's documented shortcut opens the nested effort menu directly.
+ claudeKey(14, app: captured.app, flags: [.maskCommand, .maskShift])
+ } else { try pressAccessibilityControl(picker.0.element) }
+ if request.operation == "fast" {
+ guard let toggle = waitUntil(timeout: 1.8, operation: { () -> ElementInfo? in
+ let rows = captureClaudeSnapshot(captured.window).elements.filter {
+ !$0.hidden && $0.enabled && ["AXMenuItem", "AXCheckBox"].contains($0.role)
+ && claudeNormalized($0.title.isEmpty ? $0.description : $0.title) == "enable fast mode"
+ }
+ return rows.count == 1 ? rows[0] : nil
+ }), let original = captured.state.fast else { throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE") }
+ _ = try verifyClaude(captured, target: request.target)
+ try pressAccessibilityControl(toggle.element)
+ guard let result = waitUntil(timeout: 2, operation: { () -> ProviderState? in
+ guard let current = try? verifyClaude(captured, target: request.target),
+ current.composer.value == captured.composer.value,
+ current.state.model == captured.state.model,
+ current.state.fast == !original else { return nil }
+ return current.state
+ }) else { throw ControlError.failed("Fast change unverified", "UNCHANGED") }
+ dismiss()
+ return result
+ }
+ if kind == "reasoning" && !combinedEffort, let slider = waitUntil(timeout: 1.8, operation: {
+ claudeEffortSlider(captureClaudeSnapshot(captured.window))
+ }) {
+ guard let range = claudeSliderRange(slider.element) else { throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE") }
+ if request.operation == "reasoning-options" {
+ let selected = (attribute(slider.element, kAXValueAttribute as CFString) as? NSNumber)?.intValue
+ guard let options = claudeEffortOptions(range: range, selected: selected, currentLabel: picker.1)
+ else { throw ControlError.failed("Effort choices changed", "UNAVAILABLE") }
+ dismiss()
+ let after = try verifyClaude(captured, target: request.target)
+ guard after.composer.value == captured.composer.value else { throw ControlError.failed("Draft changed", "DRAFT_PRESENT") }
+ var state = after.state
+ state.options = options
+ return state
+ }
+ guard let value = request.value, value.hasPrefix("slider:"),
+ let desired = Int(value.dropFirst(7)), range.contains(desired)
+ else { throw ControlError.failed("Option unavailable", "UNAVAILABLE") }
+ for _ in 0...range.count {
+ let current = try verifyClaude(captured, target: request.target)
+ guard current.composer.value == captured.composer.value,
+ let currentSlider = claudeEffortSlider(current.snapshot),
+ claudeSliderRange(currentSlider.element) == range,
+ let number = attribute(currentSlider.element, kAXValueAttribute as CFString) as? NSNumber
+ else { throw ControlError.failed("Effort control changed", "TARGET_MISMATCH") }
+ if number.intValue == desired {
+ let label = stringAttribute(currentSlider.element, "AXValueDescription" as CFString)
+ guard !label.isEmpty, current.state.effort == label else { throw ControlError.failed("Selection unverified", "UNCHANGED") }
+ dismiss()
+ return try verifyClaude(captured, target: request.target).state
+ }
+ let action = number.intValue < desired ? kAXIncrementAction : kAXDecrementAction
+ guard AXUIElementPerformAction(currentSlider.element, action as CFString) == .success else {
+ throw ControlError.failed("Effort action unavailable", "UNAVAILABLE")
+ }
+ let expected = number.intValue + (number.intValue < desired ? 1 : -1)
+ guard waitUntil(timeout: 1, operation: { () -> Bool? in
+ guard let fresh = claudeEffortSlider(captureClaudeSnapshot(captured.window)),
+ (attribute(fresh.element, kAXValueAttribute as CFString) as? NSNumber)?.intValue == expected
+ else { return nil }
+ return true
+ }) != nil else { throw ControlError.failed("Effort unchanged", "UNCHANGED") }
+ }
+ throw ControlError.failed("Selection unverified", "UNCHANGED")
+ }
+ guard let choices = waitUntil(timeout: 1.8, operation: {
+ let choices = claudeMenuOptions(captureClaudeSnapshot(captured.window), kind: kind).filter {
+ // In the combined picker Ultracode is an independent checkbox,
+ // not a sixth effort level. Preserve it when selecting a level.
+ !(combinedEffort && $0.1 == "Ultracode")
+ }
+ return choices.isEmpty ? nil : choices
+ }) else { throw ControlError.failed("Menu unavailable", "UNAVAILABLE") }
+ let labels = choices.map { $0.1 }
+ guard Set(labels).count == labels.count else { throw ControlError.failed("Ambiguous menu", "TARGET_MISMATCH") }
+ // Dismiss only a menu opened by this operation, in the captured process.
+ if request.operation.hasSuffix("-options") {
+ dismiss()
+ usleep(100_000)
+ let after = try verifyClaude(captured, target: request.target)
+ guard after.composer.value == captured.composer.value else { throw ControlError.failed("Draft changed", "DRAFT_PRESENT") }
+ var state = after.state
+ state.options = labels.map { ProviderChoice(value: $0, label: $0) }
+ return state
+ }
+ let value: String
+ if request.operation == "permission-cycle" {
+ guard let next = claudeNextPermission(current: picker.1, offered: labels) else { throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE") }
+ value = next
+ } else if request.operation == "plan" {
+ if ["Plan", "Plan mode"].contains(picker.1) {
+ guard let restored = claudePlanExitMode(previous: request.value, offered: labels, defaultMode: claudeDefaultPermission(choices))
+ else { throw ControlError.failed("No non-Plan mode available", "UNAVAILABLE") }
+ value = restored
+ } else {
+ guard let plan = labels.first(where: { ["Plan", "Plan mode"].contains($0) }) else { dismiss(); throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE") }
+ value = plan
+ }
+ } else {
+ guard let requested = request.value, labels.contains(requested) else { dismiss(); throw ControlError.failed("Option unavailable", "UNAVAILABLE") }
+ value = requested
+ }
+ do {
+ _ = try verifyClaude(captured, target: request.target)
+ guard let item = choices.first(where: { $0.1 == value }) else { throw ControlError.failed("Option unavailable", "UNAVAILABLE") }
+ try pressAccessibilityControl(item.0.element)
+ var confirmedBypass = false
+ var confirmedModelSwitch = false
+ guard let result = waitUntil(timeout: value == "Bypass permissions" || kind == "model" ? 4 : 2, operation: { () -> ProviderState? in
+ if value == "Bypass permissions", !confirmedBypass {
+ confirmedBypass = (try? confirmClaudeBypassIfPresent(captured, target: request.target)) == true
+ }
+ if kind == "model", !confirmedModelSwitch {
+ confirmedModelSwitch = (try? confirmClaudeModelSwitchIfPresent(captured, target: request.target, desired: value)) == true
+ }
+ guard let current = try? verifyClaude(captured, target: request.target, afterConfirmation: confirmedBypass || confirmedModelSwitch),
+ current.composer.value == captured.composer.value,
+ (kind != "reasoning" || current.state.ultracode == captured.state.ultracode),
+ claudePicker(current.snapshot, kind: kind)?.1 == value else { return nil }
+ return current.state
+ }) else { throw ControlError.failed("Selection unverified", "UNCHANGED") }
+ return result
+ } catch { dismiss(); throw error }
+ }
+ if request.operation == "send" || request.operation == "stop" {
+ let current = try verifyClaude(captured, target: request.target)
+ let labels: Set = request.operation == "send" ? ["send", "send message"] : ["stop", "stop response"]
+ guard let button = claudeButton(current.snapshot, labels: labels) else { throw ControlError.failed("UNAVAILABLE", "UNAVAILABLE") }
+ if request.operation == "send" && current.state.draftEmpty != false { throw ControlError.failed("Empty composer", "DRAFT_PRESENT") }
+ // Freeze draft identity before Send changes the AXWebArea URL. Re-reading
+ // that live AX attribute from a captured snapshot would lose its source.
+ let sourceDraft = claudeDraftMetadata(current.snapshot)
+ try pressAccessibilityControl(button.element)
+ guard let result = waitUntil(timeout: request.operation == "send" && request.target.environment == "cloud" && request.target.sessionId.hasPrefix("draft:") ? 25 : request.operation == "send" ? 6 : 2, operation: { () -> ProviderState? in
+ guard let after = try? captureClaude(), sameElement(after.window, captured.window) else { return nil }
+ let sameSession = after.state.target == request.target
+ let startedDraft = request.target.sessionId.hasPrefix("draft:") && after.state.target?.sessionId.hasPrefix("local_") == true && claudeMetadata().first(where: { $0.id == after.state.target?.sessionId && $0.environment == request.target.environment })?.cwd.map { claudeCanonicalFolder($0, environment: request.target.environment) } == sourceDraft?.cwd
+ let sourceCloud = sourceDraft?.cloudWorkspace
+ let startedCloud = request.target.sessionId.hasPrefix("draft:") && request.target.environment == "cloud" && after.state.target?.sessionId.hasPrefix("session_") == true && sourceCloud != nil && claudeCloudWorkspace(after.snapshot) == sourceCloud
+ guard sameSession || startedDraft || startedCloud else { return nil }
+ if request.operation == "send" {
+ let text = captured.composer.value.trimmingCharacters(in: .whitespacesAndNewlines)
+ let sent = after.snapshot.elements.contains { !$0.hidden && $0.role == "AXStaticText" && ($0.value == text || $0.title == text) }
+ return after.state.draftEmpty == true && sent ? after.state : nil
+ }
+ return claudeButton(after.snapshot, labels: labels) == nil ? after.state : nil
+ }) else { throw ControlError.failed("Action unverified", "UNCHANGED") }
+ return result
+ }
+ throw ControlError.failed("UNSUPPORTED", "UNAVAILABLE")
+}
+
+func runProviderAction(_ action: String, requested: String?) {
+ if action == "fixture-claude-policy", let requested,
+ let data = Data(base64Encoded: requested),
+ let fixture = (try? JSONSerialization.jsonObject(with: data)) as? [String: String] {
+ if fixture["kind"] == "context-card" {
+ func node(_ role: String, _ title: String, _ parent: Int?, hidden: Bool = false) -> ElementInfo {
+ ElementInfo(element: AXUIElementCreateSystemWide(), role: role, title: title, description: "", value: "", help: "", elementFrame: nil, enabled: true, hidden: hidden, selected: false, parentIndex: parent, depth: parent == nil ? 0 : 1)
+ }
+ var elements = [node("AXWindow", "", nil), node("AXGroup", fixture["title"] ?? "Context", 0), node("AXButton", fixture["control"] ?? "Reorder Context", 1), node("AXStaticText", fixture["text"] ?? "18% used", fixture["outside"] == "true" ? 0 : 1, hidden: fixture["hidden"] == "true"), node("AXStaticText", "78.5%", 1)]
+ if fixture["duplicate"] == "true" { elements.append(node("AXStaticText", "20% used", 1)) }
+ let snapshot = AXSnapshot(elements: elements, query: NeutralAXQuery(nodes: neutralNodes(from: elements)))
+ let context = claudeContextCard(snapshot)
+ var result = ControlResult(ok: true, action: action, requested: nil, model: nil, effort: nil, message: "Context card fixture")
+ var state = ProviderState()
+ state.contextUsedPercent = context.used
+ state.contextAvailability = context.used != nil ? "ready" : context.empty ? "empty" : "unavailable"
+ result.providerState = state
+ emit(result, exitCode: 0)
+ }
+ if fixture["kind"] == "fast-label" {
+ emit(ControlResult(ok: true, action: action, requested: nil, model: claudeFastLabel(fixture["text"] ?? "") ? "ON" : "OFF", effort: nil, message: "Fast label fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "composer-continuity" {
+ let matched = claudeComposerContinuity(sameComposer: fixture["sameComposer"] == "true", confirmedDialog: fixture["confirmed"] == "true", sameSession: fixture["sameSession"] == "true", sameDraft: fixture["sameDraft"] == "true")
+ emit(ControlResult(ok: true, action: action, requested: nil, model: matched ? "MATCHED" : "REJECTED", effort: nil, message: "Composer remount fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "confirmation-session" {
+ let matched = claudeConfirmationSessionMatches(expected: fixture["expected"] ?? "", current: Set((fixture["current"] ?? "").components(separatedBy: "|")))
+ emit(ControlResult(ok: true, action: action, requested: nil, model: matched ? "MATCHED" : "REJECTED", effort: nil, message: "Captured confirmation session fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "model-dialog" {
+ func node(_ role: String, _ title: String, _ parent: Int?, hidden: Bool = false) -> ElementInfo {
+ ElementInfo(element: AXUIElementCreateSystemWide(), role: role, title: title, description: "", value: "", help: "", elementFrame: nil, enabled: true, hidden: hidden, selected: false, parentIndex: parent, depth: parent == nil ? 0 : 1)
+ }
+ var elements = [node("AXWindow", "", nil), node("AXGroup", fixture["title"] ?? "Switch model?", 0, hidden: fixture["hidden"] == "true"), node("AXButton", "Switch model", fixture["outside"] == "true" ? 0 : 1), node("AXButton", fixture["cancel"] ?? "Cancel", 1), node("AXStaticText", "This session is cached for Opus 5.5. Switching to Fable 5.2 means Claude re-reads the session.", 1)]
+ if fixture["duplicate"] == "true" { elements.append(node("AXButton", "Switch model", 1)) }
+ let snapshot = AXSnapshot(elements: elements, query: NeutralAXQuery(nodes: neutralNodes(from: elements)))
+ let matched = claudeModelSwitchConfirmation(snapshot, from: fixture["from"] ?? "Opus 5.5", to: fixture["to"] ?? "Fable 5.2") != nil
+ emit(ControlResult(ok: true, action: action, requested: nil, model: matched ? "MATCHED" : "REJECTED", effort: nil, message: "Model confirmation fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "bypass-dialog" {
+ func node(_ role: String, _ title: String, _ parent: Int?, hidden: Bool = false) -> ElementInfo {
+ ElementInfo(element: AXUIElementCreateSystemWide(), role: role, title: title, description: "", value: "", help: "", elementFrame: nil, enabled: true, hidden: hidden, selected: false, parentIndex: parent, depth: parent == nil ? 0 : 1)
+ }
+ var elements = [node("AXWindow", "", nil), node("AXGroup", fixture["title"] ?? "Bypass all permissions?", 0, hidden: fixture["hidden"] == "true"), node("AXButton", fixture["button"] ?? "Bypass permissions", fixture["outside"] == "true" ? 0 : 1), node("AXButton", "Cancel", 1)]
+ if fixture["duplicate"] == "true" { elements.append(node("AXButton", "Bypass permissions", 1)) }
+ let snapshot = AXSnapshot(elements: elements, query: NeutralAXQuery(nodes: neutralNodes(from: elements)))
+ let matched = claudeBypassConfirmation(snapshot) != nil
+ emit(ControlResult(ok: true, action: action, requested: nil, model: matched ? "MATCHED" : "REJECTED", effort: nil, message: "Bypass modal selector fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "effort-options" {
+ let low = Int(fixture["low"] ?? "0") ?? -1
+ let high = Int(fixture["high"] ?? "5") ?? -1
+ let selected = Int(fixture["selected"] ?? "")
+ var state = ProviderState()
+ if low <= high { state.options = claudeEffortOptions(range: low...high, selected: selected, currentLabel: fixture["text"] ?? "") }
+ var result = ControlResult(ok: true, action: action, requested: nil, model: nil, effort: nil, message: "Effort names fixture")
+ result.providerState = state
+ emit(result, exitCode: 0)
+ }
+ if fixture["kind"] == "plan-exit" {
+ let mode = claudePlanExitMode(previous: fixture["previous"], offered: (fixture["choices"] ?? "").components(separatedBy: "|"), defaultMode: fixture["default"])
+ emit(ControlResult(ok: true, action: action, requested: nil, model: mode, effort: nil, message: "Plan restoration fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "metadata-size", let requestedSize = Int(fixture["text"] ?? ""), requestedSize >= 0, requestedSize <= claudeMetadataByteLimit + 1 {
+ let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ do {
+ try Data(repeating: 32, count: requestedSize).write(to: file)
+ let accepted = claudeMetadataData(file) != nil
+ try? FileManager.default.removeItem(at: file)
+ emit(ControlResult(ok: true, action: action, requested: nil, model: accepted ? "ACCEPTED" : "REJECTED", effort: nil, message: "Bounded metadata read fixture"), exitCode: 0)
+ } catch {
+ emit(ControlResult(ok: false, action: action, requested: nil, model: nil, effort: nil, message: "Metadata fixture failed"), exitCode: 1)
+ }
+ }
+ if fixture["kind"] == "desktop" {
+ let session: [String: Any]? = fixture["missing"] == "true" ? nil : [
+ kCGSessionOnConsoleKey as String: fixture["console"] == "true",
+ "CGSSessionScreenIsLocked": fixture["locked"] == "true"
+ ]
+ emit(ControlResult(ok: true, action: action, requested: nil, model: providerDesktopUnavailableReason(session) ?? "READY", effort: nil, message: "Desktop availability fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "accessibility-generation" {
+ let pid = pid_t(Int32(fixture["pid"] ?? "") ?? 0)
+ let launchMilliseconds = Double(fixture["launchMilliseconds"] ?? "") ?? 0
+ let current = claudeAccessibilityGeneration(pid: pid, launchDate: Date(timeIntervalSince1970: launchMilliseconds / 1_000))
+ let status = claudeAccessibilityNeedsInitialization(cachedGeneration: fixture["cached"], currentGeneration: current) ? "INITIALIZE" : "CACHED"
+ emit(ControlResult(ok: true, action: action, requested: nil, model: "\(current)|\(status)", effort: nil, message: "Claude accessibility generation fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "resets" {
+ let frame = CGRect(x: 0, y: 0, width: 800, height: 600)
+ func node(_ id: String, _ parent: String?, _ role: String, _ text: String, _ depth: Int) -> NeutralAXNode {
+ selectorFixtureNode(id, parentId: parent, role: role, text: text, frame: frame, hidden: id == "settings" && fixture["hidden"] == "true", depth: depth)
+ }
+ var nodes = [node("root", nil, "AXWindow", "", 0), node("settings", "root", "AXGroup", fixture["owner"] ?? "Settings", 1), node("usage", "settings", "AXHeading", "Your usage", 2), node("limit", "settings", "AXHeading", "Limit resets", 2), node("total", "settings", "AXStaticText", (fixture["total"] ?? "3") + " available", 2)]
+ for type in ["Weekly", "Fable"] {
+ let label = fixture[type] ?? (type == "Weekly" ? "Weekly reset · 2" : "Fable reset")
+ if label.isEmpty { continue }
+ nodes.append(node(type, "settings", "AXGroup", label, 2))
+ if fixture["button"] != "missing" { nodes.append(node(type + "button", type, "AXButton", "Reset for free " + label, 3)) }
+ }
+ if fixture["duplicate"] == "true" { nodes.append(node("duplicate", "settings", "AXStaticText", "3 available", 2)) }
+ let balances = claudeResetBalances(NeutralAXQuery(nodes: nodes))
+ var state = ProviderState()
+ state.weeklyResetsAvailable = balances?.weekly; state.fableResetsAvailable = balances?.fable
+ emit(ControlResult(providerState: state, ok: true, action: action, requested: nil, model: nil, effort: nil, message: "Scoped reset balances fixture"), exitCode: 0)
+ }
+ if fixture["kind"] == "project-usage" {
+ let id = claudeProjectId(fixture["url"] ?? "")
+ var result = ControlResult(ok: true, action: action, requested: nil, model: nil, effort: nil, message: "Read-only project telemetry fixture")
+ if let id { result.providerState = claudeProjectUsage(fixture["text"] ?? "", scope: id) }
+ emit(result, exitCode: 0)
+ }
+ if fixture["kind"] == "usage" {
+ let usage = claudeUsageLabel(fixture["text"] ?? "")
+ var result = ControlResult(ok: true, action: action, requested: nil, model: nil, effort: nil, message: "Claude usage label fixture")
+ var state = ProviderState()
+ state.weeklyUsedPercent = usage.weekly; state.weeklyBucket = usage.bucket; state.contextUsedPercent = usage.context
+ state.usageUsedPercent = usage.used; state.usagePeriod = usage.period; state.usageBucket = usage.bucket
+ state.usageAvailability = usage.used == nil ? "unavailable" : "ready"
+ result.providerState = state
+ emit(result, exitCode: 0)
+ }
+ if fixture["kind"] == "cloud-workspace" {
+ emit(ControlResult(ok: true, action: action, requested: nil, model: claudeCloudWorkspaceKey(environment: fixture["environment"] ?? "", repository: fixture["repository"] ?? ""), effort: nil, message: "Cloud workspace key"), exitCode: 0)
+ }
+ let session = claudeCodeSessionId(fixture["url"] ?? "")
+ let label = fixture["kind"] == "permission-next"
+ ? claudeNextPermission(current: fixture["text"] ?? "", offered: (fixture["choices"] ?? "").components(separatedBy: "|"))
+ : fixture["kind"] == "control-label" ? claudeNormalized(fixture["text"] ?? "") : fixture["kind"] == "permission-row"
+ ? claudePermissionMenuLabel(fixture["text"] ?? "")
+ : claudePickLabel(fixture["text"] ?? "", kind: fixture["kind"] ?? "")
+ emit(ControlResult(ok: true, action: action, requested: nil, model: label, effort: nil, conversationId: session, message: "Claude selector policy fixture"), exitCode: 0)
+ }
+ guard ["provider-read", "claude"].contains(action) else { return }
+ do {
+ let state: ProviderState
+ if action == "provider-read" { state = observeProviderState() }
+ else {
+ guard let requested, let request = decodeNativePayload(requested, as: ClaudeRequest.self) else {
+ throw ControlError.failed("Malformed Claude request", "UNAVAILABLE")
+ }
+ state = try executeClaude(request)
+ }
+ var result = ControlResult(ok: true, action: action, requested: nil, model: state.model, effort: state.effort, message: "Observed desktop provider")
+ result.providerState = state
+ emit(result, exitCode: 0)
+ } catch {
+ emit(ControlResult(ok: false, action: action, requested: nil, model: nil, effort: nil, reasonCode: (error as? ControlError)?.reasonCode ?? "UNKNOWN", message: error.localizedDescription), exitCode: 1)
+ }
+}
diff --git a/native/ClaudeCommands.swift b/native/ClaudeCommands.swift
new file mode 100644
index 0000000..6169b0e
--- /dev/null
+++ b/native/ClaudeCommands.swift
@@ -0,0 +1,115 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+func claudeMainComposer(_ snapshot: AXSnapshot, index: Int) -> Bool {
+ let node = snapshot.elements[index]
+ guard !node.hidden, node.enabled, node.role == "AXTextArea", claudeNormalized(node.description) == "prompt" else { return false }
+ var parent = node.parentIndex
+ while let i = parent {
+ let owner = snapshot.elements[i]
+ if owner.role == "AXGroup", [owner.title, owner.description].contains("Side chat") { return false }
+ parent = owner.parentIndex
+ }
+ return true
+}
+func claudeRecordingControl(_ snapshot: AXSnapshot) -> ElementInfo? {
+ let matches = snapshot.elements.filter { !$0.hidden && $0.enabled && $0.role == "AXCheckBox" && ["Press and hold to record", "Stop dictation"].contains($0.description) }
+ return matches.count == 1 ? matches[0] : nil
+}
+func claudeSettingsVisible(_ snapshot: AXSnapshot) -> Bool {
+ snapshot.elements.contains { !$0.hidden && $0.role == "AXGroup" && $0.title == "Settings" }
+ && claudeButton(snapshot, labels: ["close"]) != nil
+}
+func executeClaudeExtra(_ request: ClaudeRequest, captured: ClaudeCapture) throws -> ProviderState? {
+ if ["dictate", "dictation-stop"].contains(request.operation) {
+ let stopping = request.operation == "dictation-stop"
+ if stopping, let control = claudeRecordingControl(captured.snapshot), claudeToggleValue(control.element) == false { return captured.state }
+ guard let control = claudeRecordingControl(captured.snapshot),
+ claudeToggleValue(control.element) == stopping else {
+ throw ControlError.failed(stopping ? "Not recording" : "Already recording", "UNAVAILABLE")
+ }
+ try pressAccessibilityControl(control.element)
+ guard let after = waitUntil(timeout: 3, operation: { () -> ClaudeCapture? in
+ guard let current = try? captureClaude(requireForeground: !stopping),
+ current.state.target == request.target, sameElement(current.window, captured.window),
+ let next = claudeRecordingControl(current.snapshot), claudeToggleValue(next.element) == !stopping else { return nil }
+ return current
+ }) else { throw ControlError.failed("Recording unverified", "UNCHANGED") }
+ return after.state
+ }
+ if request.operation == "side-chat" {
+ let hasSide = { (snapshot: AXSnapshot) in snapshot.elements.contains { !$0.hidden && $0.role == "AXGroup" && [$0.title, $0.description].contains("Side chat") } }
+ if hasSide(captured.snapshot) { return captured.state }
+ _ = try verifyClaude(captured, target: request.target)
+ claudeKey(41, app: captured.app, flags: .maskCommand)
+ guard let after = waitUntil(timeout: 3, operation: { () -> ClaudeCapture? in
+ guard let current = try? verifyClaude(captured, target: request.target), current.composer.value == captured.composer.value,
+ hasSide(current.snapshot), current.snapshot.elements.filter({ !$0.hidden && $0.role == "AXTextArea" }).count == 2 else { return nil }; return current
+ }) else { throw ControlError.failed("Side chat unverified", "UNCHANGED") }
+ return after.state
+ }
+ if request.operation == "settings" {
+ guard let button = claudeButton(captured.snapshot, labels: ["code settings"]), !claudeMenuOpen(captured.snapshot) else { throw ControlError.failed("Settings unavailable", "UNAVAILABLE") }
+ _ = try verifyClaude(captured, target: request.target)
+ try pressAccessibilityControl(button.element)
+ guard waitUntil(timeout: 3, operation: { claudeSettingsVisible(captureClaudeSnapshot(captured.window)) ? true : nil }) == true else { throw ControlError.failed("Settings unverified", "UNCHANGED") }
+ return observeProviderState()
+ }
+ if request.operation == "compact" {
+ guard captured.state.draftEmpty == true, !claudeMenuOpen(captured.snapshot) else { throw ControlError.failed("Preserve current draft", "DRAFT_PRESENT") }
+ let before = Set(captured.snapshot.elements.filter { $0.role == "AXStaticText" }.map { $0.value })
+ _ = try verifyClaude(captured, target: request.target)
+ guard AXUIElementSetAttributeValue(captured.composer.element, kAXValueAttribute as CFString, "/compact" as CFString) == .success,
+ AXUIElementSetAttributeValue(captured.composer.element, kAXFocusedAttribute as CFString, kCFBooleanTrue) == .success,
+ boolAttribute(captured.composer.element, kAXFocusedAttribute as CFString) else { throw ControlError.failed("Composer unavailable", "UNAVAILABLE") }
+ let staged = try verifyClaude(captured, target: request.target)
+ guard staged.composer.value == "/compact" else { throw ControlError.failed("Draft changed", "DRAFT_PRESENT") }
+ claudeKey(36, app: captured.app)
+ guard let after = waitUntil(timeout: 4, operation: { () -> ClaudeCapture? in
+ guard let current = try? captureClaude(), current.state.target == request.target, current.state.draftEmpty == true,
+ current.snapshot.elements.contains(where: { !$0.hidden && $0.role == "AXStaticText" && ($0.value == "Compacting session" || ($0.value.hasPrefix("Compacted session") && !before.contains($0.value))) }) else { return nil }; return current
+ }) else { throw ControlError.failed("Compaction unverified", "UNCHANGED") }
+ return after.state
+ }
+ if request.operation == "skills" {
+ guard captured.state.draftEmpty == true, !claudeMenuOpen(captured.snapshot),
+ let add = claudeButton(captured.snapshot, labels: ["add"]) else { throw ControlError.failed("Preserve current draft", "DRAFT_PRESENT") }
+ func menuItem(_ label: String) -> ElementInfo? {
+ let items = captureClaudeSnapshot(captured.window).elements.filter { !$0.hidden && $0.enabled && $0.role == "AXMenuItem" && [$0.title, $0.description].contains(label) }
+ return items.count == 1 ? items[0] : nil
+ }
+ _ = try verifyClaude(captured, target: request.target)
+ try pressAccessibilityControl(add.element)
+ guard let slash = waitUntil(timeout: 2, operation: { menuItem("Slash commands") }) else { throw ControlError.failed("Commands unavailable", "UNAVAILABLE") }
+ _ = try verifyClaude(captured, target: request.target)
+ try pressAccessibilityControl(slash.element)
+ guard let skills = waitUntil(timeout: 2, operation: { menuItem("skills") }) else { throw ControlError.failed("Skills unavailable", "UNAVAILABLE") }
+ _ = try verifyClaude(captured, target: request.target)
+ try pressAccessibilityControl(skills.element)
+ guard let staged = waitUntil(timeout: 2, operation: { () -> ClaudeCapture? in
+ guard let current = try? verifyClaude(captured, target: request.target), current.composer.value.trimmingCharacters(in: .whitespacesAndNewlines) == "skills" else { return nil }; return current
+ }) else { throw ControlError.failed("Skills command unverified", "UNCHANGED") }
+ guard AXUIElementSetAttributeValue(staged.composer.element, kAXFocusedAttribute as CFString, kCFBooleanTrue) == .success else { throw ControlError.failed("Composer unavailable", "UNAVAILABLE") }
+ claudeKey(36, app: captured.app)
+ if captured.state.target?.environment == "cloud" {
+ guard let skillsTab = waitUntil(timeout: 3, operation: { () -> ElementInfo? in
+ guard providerForeground() == "claude" else { return nil }
+ let snapshot = captureClaudeSnapshot(captured.window)
+ guard claudeSettingsVisible(snapshot) else { return nil }
+ let tabs = snapshot.elements.filter { !$0.hidden && $0.enabled && $0.role == "AXRadioButton" && [$0.title, $0.description].contains("Skills") }
+ return tabs.count == 1 ? tabs[0] : nil
+ }) else { throw ControlError.failed("Skills unavailable", "UNCHANGED") }
+ if claudeToggleValue(skillsTab.element) != true { try pressAccessibilityControl(skillsTab.element) }
+ }
+ guard waitUntil(timeout: 3, operation: { () -> Bool? in
+ let snapshot = captureClaudeSnapshot(captured.window)
+ let localSkills = snapshot.elements.contains { !$0.hidden && $0.role == "AXHeading" && $0.title == "In this project" }
+ let cloudSkills = captured.state.target?.environment == "cloud" && snapshot.elements.contains { !$0.hidden && $0.role == "AXRadioButton" && [$0.title, $0.description].contains("Skills") && claudeToggleValue($0.element) == true }
+ && snapshot.elements.contains { !$0.hidden && $0.role == "AXHeading" && $0.title == "Active" }
+ return claudeSettingsVisible(snapshot) && (localSkills || cloudSkills) ? true : nil
+ }) == true else { throw ControlError.failed("Skills view unverified", "UNCHANGED") }
+ return observeProviderState()
+ }
+ return nil
+}
diff --git a/native/CodexDraft.swift b/native/CodexDraft.swift
new file mode 100644
index 0000000..743671b
--- /dev/null
+++ b/native/CodexDraft.swift
@@ -0,0 +1,100 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+// Current desktop creates a persisted chat only after Send. The new-conversation
+// composer is therefore not evidence for any retained host-view session.
+func codexNewDraftComposer(in snapshot: AXSnapshot) -> ElementInfo? {
+ guard let composer = composerCandidates(in: snapshot).first,
+ [composer.title, composer.description].contains("Do anything") else { return nil }
+ return composer
+}
+
+struct CodexDraftMetadata {
+ let prompt: String
+ let projectName: String?
+ let projectRoots: [String]
+}
+// Desktop now persists a ProseMirror document. Decode only plain paragraphs
+// and text; unknown nodes (attachments, mentions, etc.) must never mean empty.
+func codexStoredDraftText(_ value: Any?) -> String? {
+ if let text = value as? String { return text }
+ guard let prompt = value as? [String: Any],
+ let document = prompt["document"] as? [String: Any],
+ document["type"] as? String == "doc",
+ let paragraphs = document["content"] as? [[String: Any]] else { return nil }
+ var result: [String] = []
+ for paragraph in paragraphs {
+ guard paragraph["type"] as? String == "paragraph" else { return nil }
+ guard paragraph["content"] == nil || paragraph["content"] is [[String: Any]] else { return nil }
+ var text = ""
+ for node in (paragraph["content"] as? [[String: Any]] ?? []) {
+ if node["type"] as? String == "text", let value = node["text"] as? String { text += value }
+ else if node["type"] as? String == "hardBreak" { text += "\n" }
+ else { return nil }
+ }
+ result.append(text)
+ }
+ return result.joined(separator: "\n")
+}
+func codexDraftMetadata(_ data: Data) -> CodexDraftMetadata? {
+ guard data.count <= 16 * 1024 * 1024,
+ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let atoms = object["electron-persisted-atom-state"] as? [String: Any] else { return nil }
+ let drafts = atoms["composer-prompt-drafts-v2"] as? [String: Any]
+ let draft = drafts?["new-conversation"] as? [String: Any]
+ let prompt: String
+ if let draft {
+ guard let text = codexStoredDraftText(draft["prompt"]) else { return nil }
+ prompt = text
+ } else { prompt = "" }
+ var name: String?; var roots: [String] = []
+ if let owner = object["electron-renderer-content-owner"] as? String,
+ owner.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil,
+ let selected = object["electron-owner-value:selected-project:\(owner)"] as? [String: Any],
+ selected["type"] as? String == "local",
+ let id = selected["projectId"] as? String,
+ let projects = object["local-projects"] as? [String: [String: Any]],
+ let project = projects[id], project["id"] as? String == id,
+ let projectName = project["name"] as? String,
+ let projectRoots = project["rootPaths"] as? [String] {
+ name = projectName; roots = projectRoots
+ }
+ return CodexDraftMetadata(prompt: prompt, projectName: name, projectRoots: roots)
+}
+func readCodexDraftMetadata() -> CodexDraftMetadata? {
+ let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".codex/.codex-global-state.json")
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }
+ defer { try? handle.close() }
+ guard let data = try? handle.read(upToCount: 16 * 1024 * 1024 + 1) else { return nil }
+ let result = codexDraftMetadata(data)
+ if result == nil && ProcessInfo.processInfo.environment["STREAMDECK_DRAFT_DIAGNOSTICS"] == "1" {
+ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
+ let atoms = object?["electron-persisted-atom-state"] as? [String: Any]
+ let drafts = atoms?["composer-prompt-drafts-v2"] as? [String: Any]
+ let draft = drafts?["new-conversation"] as? [String: Any]
+ FileHandle.standardError.write(Data("metadata: bytes=\(data.count) object=\(object != nil) atoms=\(atoms != nil) keys=\(draft?.keys.sorted() ?? []) promptType=\(draft?["prompt"].map { String(describing: type(of: $0)) } ?? "absent")\n".utf8))
+ }
+ return result
+}
+func verifyCodexNewDraft(_ app: NSRunningApplication, root: AXUIElement, prompt: String, cwd: String?) -> Bool {
+ func fail(_ reason: String) -> Bool {
+ if ProcessInfo.processInfo.environment["STREAMDECK_DRAFT_DIAGNOSTICS"] == "1" { FileHandle.standardError.write(Data(("draft: " + reason + "\n").utf8)) }; return false
+ }
+ guard isCodexFrontmost(app), let window = try? uniqueFocusedCodexWindow(root) else { return fail("window") }
+ let snapshot = captureAXSnapshot(window, maximumDepth: maximumCodexWindowTraversalDepth)
+ guard let composer = codexNewDraftComposer(in: snapshot) else { return fail("composer") }
+ guard composerDraft(composer) == prompt else { return fail("prompt mismatch lengths \(composerDraft(composer).count)/\(prompt.count)") }
+ guard let metadata = readCodexDraftMetadata() else { return fail("metadata") }
+ guard metadata.prompt.isEmpty || metadata.prompt == prompt else { return fail("stored prompt") }
+ if let cwd {
+ guard metadata.projectRoots.count == 1, canonicalPath(metadata.projectRoots[0]) == canonicalPath(cwd),
+ let name = metadata.projectName else { return fail("project path") }
+ let controls = snapshot.elements.filter { info in
+ ["AXButton", "AXPopUpButton"].contains(info.role) && !info.hidden && info.enabled
+ && [info.title, info.description].contains("Change project: \(name)")
+ }
+ guard controls.count == 1 else { return fail("project control") }
+ }
+ return isCodexFrontmost(app) && (try? uniqueFocusedCodexWindow(root)).map { sameElement($0, window) } == true
+}
diff --git a/native/ComposerControls.swift b/native/ComposerControls.swift
index 9d07615..7a825ce 100644
--- a/native/ComposerControls.swift
+++ b/native/ComposerControls.swift
@@ -6,8 +6,14 @@ import Foundation
func pickerCandidate(in elements: [ElementInfo]) -> ElementInfo? {
let matches = elements.filter { info in
guard info.role == (kAXPopUpButtonRole as String) else { return false }
- let text = normalized("\(info.title) \(info.description)")
- return !info.hidden && (text.contains("luna") || text.contains("terra") || text.contains("sol") || text.contains("astra"))
+ guard !info.hidden else { return false }
+ // Chat-title menus can contain model names (for example "Add Astra
+ // model selectors"). Only an actual versioned model + effort control
+ // qualifies; substring matching made those chats appear ambiguous.
+ return [info.title, info.description].contains { title in
+ guard let parsed = parsePickerTitle(title) else { return false }
+ return parsed.model.range(of: "^(?:GPT[- ]?)?[0-9]+(?:\\.[0-9]+)* (?:Luna|Terra|Sol|Astra)$", options: [.regularExpression, .caseInsensitive]) != nil
+ }
}
return matches.count == 1 ? matches[0] : nil
}
@@ -27,6 +33,9 @@ func requirePicker(in elements: [ElementInfo]) throws -> ElementInfo {
}
func pickerMenuTextMatches(_ rawText: String, label: String) -> Bool {
+ if let requested = codexModelIdentity(label) {
+ return codexModelIdentity(rawText) == requested
+ }
let text = normalized(rawText)
let target = normalized(label)
return !target.isEmpty
@@ -37,6 +46,13 @@ func pickerMenuTextMatches(_ rawText: String, label: String) -> Bool {
|| text.contains("effort\(target)"))
}
+func codexModelIdentity(_ label: String) -> String? {
+ let value = label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ guard let regex = try? NSRegularExpression(pattern: "^(?:gpt[- ]?)?([0-9]+(?:\\.[0-9]+)*) (luna|terra|sol|astra)$"),
+ let match = regex.firstMatch(in: value, range: NSRange(value.startIndex..., in: value)) else { return nil }
+ return (value as NSString).substring(with: match.range(at: 1)) + "-" + (value as NSString).substring(with: match.range(at: 2))
+}
+
func effortMenuTextMatches(_ rawText: String, label: String) -> Bool {
let text = normalized(rawText)
let target = normalized(label)
@@ -237,20 +253,43 @@ func dictationTextMatches(
}
}
+func dictationControlIndex(in query: NeutralAXQuery, phase: ComposerDictationPhase) -> Int? {
+ if let composerIndex = uniqueComposerIndex(in: query) {
+ return controlIndex(inComposerRegion: composerIndex, query: query,
+ roles: Set([kAXButtonRole as String])) {
+ dictationTextMatches($0, phase: phase)
+ }
+ }
+ // Current desktops replace the editor with a recording strip. Require both
+ // unique recording controls in the same small visible owner, not transcript
+ // text or a system menu. Never broaden the idle/start selector.
+ guard phase == .recording else { return nil }
+ let buttons = query.nodes.indices.filter {
+ query.nodes[$0].role == (kAXButtonRole as String)
+ && query.nodes[$0].enabled && query.ownerIsVisible($0)
+ }
+ let stops = buttons.filter { dictationTextMatches(neutralNodeText(query.nodes[$0]), phase: .recording) }
+ let cancels = buttons.filter { normalized(neutralNodeText(query.nodes[$0])) == "canceldictation" }
+ guard stops.count == 1, cancels.count == 1,
+ let stop = stops.first, let cancel = cancels.first,
+ let stopFrame = query.nodes[stop].elementFrame,
+ let cancelFrame = query.nodes[cancel].elementFrame,
+ abs(stopFrame.midY - cancelFrame.midY) <= 20 else { return nil }
+ let owners = query.nodes.indices.filter {
+ guard query.nodes[$0].role == "AXGroup", query.ownerIsVisible($0),
+ let frame = query.nodes[$0].elementFrame,
+ frame.width >= 240, frame.height <= 200,
+ frame.intersects(stopFrame), frame.intersects(cancelFrame) else { return false }
+ return query.isDescendant(stop, of: $0) && query.isDescendant(cancel, of: $0)
+ }
+ return owners.isEmpty ? nil : stop
+}
+
func dictationControl(
in snapshot: AXSnapshot,
phase: ComposerDictationPhase
) -> ElementInfo? {
- guard
- let composerIndex = uniqueComposerIndex(in: snapshot.query),
- let control = controlIndex(
- inComposerRegion: composerIndex,
- query: snapshot.query,
- roles: Set([kAXButtonRole as String]),
- predicate: { dictationTextMatches($0, phase: phase) }
- )
- else { return nil }
- return snapshot.elements[control]
+ dictationControlIndex(in: snapshot.query, phase: phase).map { snapshot.elements[$0] }
}
func composerModeControl(
@@ -388,13 +427,14 @@ func exposeFastControl(in appElement: AXUIElement) throws {
func readFastMode(_ appElement: AXUIElement) throws -> Bool {
dismissOpenMenus()
try exposeFastControl(in: appElement)
- defer { pressEscape() }
+ defer { try? closePickerMenu(appElement) }
let snapshot = captureAXSnapshot(appElement)
guard let active = pickerFastState(in: snapshot.elements) else {
throw ControlError.failed(
"Codex opened no verifiable Fast mode state."
)
}
+ try closePickerMenu(appElement)
return active
}
@@ -418,7 +458,7 @@ func fastControlIndex(in query: NeutralAXQuery, speedMenu: Bool = false, option:
}
func toggleFastMode(appElement: AXUIElement, initial: AXSnapshot) throws -> Bool {
- defer { dismissOpenMenus() }
+ defer { try? closePickerMenu(appElement) }
guard let composer = composerCandidates(in: initial).first else {
throw ControlError.failed("The live Codex composer is unavailable.", "UNAVAILABLE")
}
@@ -450,7 +490,7 @@ func toggleFastMode(appElement: AXUIElement, initial: AXSnapshot) throws -> Bool
}) else {
throw ControlError.failed("The visible Fast control did not confirm a change.", "UNCHANGED")
}
- dismissOpenMenus()
+ try closePickerMenu(appElement)
guard let finalComposer = composerCandidates(in: captureAXSnapshot(appElement)).first,
composerDraft(finalComposer) == originalDraft else {
throw ControlError.failed("The composer changed during the Fast toggle.", "TARGET_MISMATCH")
@@ -518,6 +558,23 @@ func approvalModeControl(
return (elements[controlIndex], mode)
}
+// Current desktop temporarily replaces the composer with an approval footer.
+// All three controls must be unique, visible siblings of the same framed group.
+func codexApprovalCard(in query: NeutralAXQuery) -> (allow: Int, deny: Int)? {
+ func matches(_ role: String, _ label: String) -> [Int] {
+ query.nodes.indices.filter { query.nodes[$0].role == role &&
+ query.nodes[$0].title == label && query.nodes[$0].enabled && query.ownerIsVisible($0) }
+ }
+ let allow = matches("AXButton", "Allow once"), deny = matches("AXButton", "Deny")
+ let options = matches("AXPopUpButton", "Approval options")
+ guard allow.count == 1, deny.count == 1, options.count == 1,
+ let owner = query.parents[allow[0]], query.parents[deny[0]] == owner,
+ query.parents[options[0]] == owner, query.nodes[owner].role == "AXGroup",
+ query.ownerIsVisible(owner),
+ !query.nodes.indices.contains(where: { query.nodes[$0].role == "AXTextArea" && query.ownerIsVisible($0) }) else { return nil }
+ return (allow[0], deny[0])
+}
+
struct ComposerObservation {
let pending: Bool
let pendingTitle: String?
@@ -533,6 +590,9 @@ struct NeutralComposerSnapshot {
// native fixtures. Mutation selectors query the same neutral node snapshot.
func evaluateComposerSnapshot(_ snapshot: NeutralComposerSnapshot) -> ComposerObservation? {
let query = NeutralAXQuery(nodes: snapshot.nodes)
+ if codexApprovalCard(in: query) != nil {
+ return ComposerObservation(pending: true, pendingTitle: "Approval required", approvalMode: nil)
+ }
let composers = query.nodes.filter {
$0.role == (kAXTextAreaRole as String)
&& $0.enabled
@@ -988,19 +1048,46 @@ func toggleMode(
throw ControlError.failed("Unsupported Codex mode.", "UNAVAILABLE")
}
+func dismissPickerUntilClosed(
+ isOpen: () -> Bool,
+ dismiss: () -> Void,
+ settle: () -> Void,
+ attempts: Int = 4
+) -> Bool {
+ for _ in 0.. Bool? {
- let states = elements.compactMap { info -> Bool? in
- guard info.role == (kAXButtonRole as String) else { return nil }
- let text = normalized("\(info.title) \(info.description)")
- if text == "hidesidebar" { return true }
- if text == "showsidebar" { return false }
- return nil
+func sidebarControlIndex(in query: NeutralAXQuery) -> Int? {
+ let matches = query.nodes.indices.filter { index in
+ let node = query.nodes[index]
+ return node.role == "AXButton" && node.enabled && query.ownerIsVisible(index)
+ && [node.title, node.description].contains { ["hidesidebar", "showsidebar"].contains(normalized($0)) }
}
- return states.count == 1 ? states[0] : nil
+ return matches.count == 1 ? matches[0] : nil
+}
+
+func sidebarVisibleState(_ elements: [ElementInfo]) -> Bool? {
+ let query = NeutralAXQuery(nodes: neutralNodes(from: elements))
+ guard let index = sidebarControlIndex(in: query) else { return nil }
+ return [query.nodes[index].title, query.nodes[index].description].contains { normalized($0) == "hidesidebar" }
}
func compactingMarkerCount(_ elements: [ElementInfo]) -> Int {
@@ -1191,21 +1282,20 @@ func observedNewMarker(before: Int, after: Int) -> Bool {
after > before
}
-func visibleDraftMessageCount(_ elements: [ElementInfo], draft: String) -> Int {
+func visibleDraftMessages(_ elements: [ElementInfo], draft: String) -> [ElementInfo] {
let expected = normalized(draft)
return elements.filter { info in
guard info.role == (kAXStaticTextRole as String) else { return false }
return normalized(elementText(info)) == expected
- }.count
+ }
}
func submittedComposerProof(
- sameComposer: Bool,
+ uniqueComposerInCapturedWindow: Bool,
draftIsEmpty: Bool,
- beforeMessages: Int,
- afterMessages: Int
+ newMessageObserved: Bool
) -> Bool {
- sameComposer && draftIsEmpty && afterMessages > beforeMessages
+ uniqueComposerInCapturedWindow && draftIsEmpty && newMessageObserved
}
func approvalResolutionObserved(pendingRemains: Bool) -> Bool {
@@ -1233,13 +1323,40 @@ func workspaceSurfaceVisible(
label: String
) -> Bool {
let expected = normalized(label)
- return query.nodes.contains { node in
- guard normalized(neutralNodeText(node)) == expected else { return false }
- if node.role == (kAXWindowRole as String) || node.role == "AXHeading" {
- return true
+ func named(_ index: Int, _ labels: Set) -> Bool {
+ let node = query.nodes[index]
+ var visible = query.ownerIsVisible(index)
+ // Chromium's tab list can report a 2px layout anchor rather than its
+ // children's bounds. Keep this exception scoped to radio tabs inside
+ // a visible tab list and its actual, framed header.
+ if !visible, node.role == "AXRadioButton", !node.hidden,
+ let parent = query.parents[index], query.nodes[parent].role == "AXTabGroup",
+ query.ownerIsVisible(parent), let header = query.parents[parent],
+ query.ownerIsVisible(header), let headerFrame = query.nodes[header].elementFrame,
+ let frame = node.elementFrame, !frame.isEmpty, headerFrame.intersects(frame) {
+ visible = true
}
- return (node.role == "AXTab" || node.role == (kAXButtonRole as String))
- && node.selected
+ return visible && [node.title, node.description].contains { labels.contains(normalized($0)) }
+ }
+ // Current desktop tabs are radio buttons. Their numeric value is state,
+ // not part of their name; transcript text and unselected launch tiles do
+ // not establish an open workspace surface.
+ if expected == "files", query.nodes.indices.contains(where: {
+ named($0, ["hidefiles"]) && query.nodes[$0].role == "AXCheckBox"
+ && (query.nodes[$0].selected || query.nodes[$0].value == "1")
+ }) { return true }
+ var names: Set = [expected]
+ if expected == "review" { names.insert("changes") }
+ if expected == "browser" { names.insert("newtab") }
+ return query.nodes.indices.contains { index in
+ let node = query.nodes[index]
+ guard named(index, names) else { return false }
+ if node.role == "AXWindow" || node.role == "AXHeading" { return true }
+ guard ["AXTab", "AXButton", "AXRadioButton"].contains(node.role), node.selected || (node.role == "AXRadioButton" && node.value == "1") else { return false }
+ if expected == "browser", named(index, ["newtab"]) {
+ return query.nodes.indices.contains { query.nodes[$0].role == "AXComboBox" && named($0, ["searchfilesorenteraurl"]) }
+ }
+ return true
}
}
@@ -1280,6 +1397,10 @@ func dispatchControl(
throw ControlError.failed("Compact requires an empty visible composer.", "DRAFT_PRESENT")
}
let beforeMarkers = compactingMarkerCount(initial.elements)
+ guard AXUIElementSetAttributeValue(composer.element, kAXFocusedAttribute as CFString, kCFBooleanTrue) == .success,
+ boolAttribute(composer.element, kAXFocusedAttribute as CFString) else {
+ throw ControlError.failed("Codex could not focus the verified empty composer.", "UNAVAILABLE")
+ }
try typeCommandAndReturn(payload)
guard waitUntil(timeout: 2.4, operation: {
let snapshot = captureAXSnapshot(appElement)
@@ -1303,12 +1424,15 @@ func dispatchControl(
)?.pending == true else {
throw ControlError.failed("No visible eligible approval is pending.")
}
- try pressKey(36)
- guard waitUntil(timeout: 1.8, operation: { () -> Bool? in
+ if let card = codexApprovalCard(in: initial.query) {
+ try pressAccessibilityControl(initial.elements[card.allow].element)
+ } else { try pressKey(36) }
+ guard waitUntil(timeout: 2.5, operation: { () -> Bool? in
let snapshot = captureAXSnapshot(
appElement,
maximumDepth: maximumCodexWindowTraversalDepth
)
+ guard composerCandidates(in: snapshot).count == 1 else { return nil }
return approvalResolutionObserved(
pendingRemains: observeComposer(
in: snapshot.elements,
@@ -1325,12 +1449,15 @@ func dispatchControl(
)?.pending == true else {
throw ControlError.failed("No visible eligible approval is pending.")
}
- try pressKey(53)
- guard waitUntil(timeout: 1.8, operation: { () -> Bool? in
+ if let card = codexApprovalCard(in: initial.query) {
+ try pressAccessibilityControl(initial.elements[card.deny].element)
+ } else { try pressKey(53) }
+ guard waitUntil(timeout: 2.5, operation: { () -> Bool? in
let snapshot = captureAXSnapshot(
appElement,
maximumDepth: maximumCodexWindowTraversalDepth
)
+ guard composerCandidates(in: snapshot).count == 1 else { return nil }
return approvalResolutionObserved(
pendingRemains: observeComposer(
in: snapshot.elements,
@@ -1348,24 +1475,29 @@ func dispatchControl(
throw ControlError.failed("Send requires a nonempty visible composer draft.", "DRAFT_PRESENT")
}
let draft = composerDraft(composer)
- let beforeMessages = visibleDraftMessageCount(
+ let beforeMessages = visibleDraftMessages(
initial.elements,
draft: draft
)
- try pressKey(36)
+ guard let composerIndex = uniqueComposerIndex(in: initial.query),
+ let send = controlIndex(inComposerRegion: composerIndex, query: initial.query, roles: ["AXButton"], predicate: { normalized($0) == "send" }) else {
+ throw ControlError.failed("The verified composer has no unique Send button.", "UNAVAILABLE")
+ }
+ try pressAccessibilityControl(initial.elements[send].element)
guard waitUntil(timeout: 1.8, operation: { () -> Bool? in
let snapshot = captureAXSnapshot(appElement)
guard
let after = composerCandidates(in: snapshot.elements).first
else { return nil }
return submittedComposerProof(
- sameComposer: sameElement(composer.element, after.element),
+ uniqueComposerInCapturedWindow: composerCandidates(in: snapshot).count == 1,
draftIsEmpty: composerDraft(after).isEmpty,
- beforeMessages: beforeMessages,
- afterMessages: visibleDraftMessageCount(
- snapshot.elements,
- draft: draft
- )
+ // Virtualized transcripts can retain the same message count
+ // when a repeated prompt is sent. Prove a newly exposed message
+ // element instead of requiring the count to grow.
+ newMessageObserved: visibleDraftMessages(snapshot.elements, draft: draft).contains { message in
+ !beforeMessages.contains { sameElement($0.element, message.element) }
+ }
) ? true : nil
}) != nil else {
throw ControlError.failed("The visible composer did not submit its draft.", "TIMEOUT")
@@ -1374,7 +1506,10 @@ func dispatchControl(
guard let before = sidebarVisibleState(initial.elements) else {
throw ControlError.failed("Codex exposes no unambiguous sidebar control.")
}
- try pressKey(11, flags: .maskCommand)
+ guard let control = sidebarControlIndex(in: initial.query) else {
+ throw ControlError.failed("Codex exposes no unambiguous sidebar control.")
+ }
+ try pressAccessibilityControl(initial.elements[control].element)
guard waitUntil(timeout: 1.8, operation: { () -> Bool? in
let snapshot = captureAXSnapshot(appElement)
guard
@@ -1397,7 +1532,7 @@ func dispatchControl(
)
}
case "review-panel", "browser", "files", "side-chat":
- let root = applicationElement ?? appElement
+ let root = appElement
guard let shortcut = workspaceShortcut(payload) else {
throw ControlError.failed(
"Unsupported Codex workspace shortcut."
@@ -1414,11 +1549,12 @@ func dispatchControl(
snapshot.elements,
label: shortcut.label
)
- return workspaceSurfaceTransitionObserved(before: before, after: after)
- ? true : nil
+ // Files is a toggle. Review, Browser and Side chat open a tab;
+ // opening an already selected tab is a successful idempotent action.
+ return (payload == "files" ? before != after : after) ? true : nil
}) != nil else {
throw ControlError.failed(
- "Codex did not visibly toggle the \(shortcut.label) surface.",
+ "Codex did not visibly open the \(shortcut.label) surface.",
"UNCHANGED"
)
}
@@ -1537,7 +1673,10 @@ func launchVerifiedRoute(
guard let url = components.url, NSWorkspace.shared.open(url), app.activate() else {
throw ControlError.failed("Codex could not open a new chat.")
}
- guard let witness = waitUntil(timeout: 3.5, operation: {
+ if waitUntil(timeout: 2.0, operation: {
+ verifyCodexNewDraft(app, root: appElement, prompt: "", cwd: request.path) ? true : nil
+ }) == true { return }
+ guard let witness = waitUntil(timeout: 1.5, operation: {
freshNewWitness(after: cursor, excluding: existingIds)
}) else {
throw ControlError.failed("Codex emitted no unique fresh new-chat witness.")
@@ -1579,7 +1718,7 @@ func launchVerifiedWorkflow(
_ request: WorkflowRequest,
app: NSRunningApplication,
appElement: AXUIElement
-) throws -> DesktopWitness {
+) throws -> DesktopWitness? {
let expectedCwd = canonicalPath(request.cwd)
guard isRegularCanonicalSQLiteDatabase(request.databasePath),
let databaseIdentity = databaseProvenance(request.databasePath),
@@ -1602,6 +1741,9 @@ func launchVerifiedWorkflow(
appElement: appElement,
witness: sourceWitness
)
+ if let draft = readCodexDraftMetadata(), !draft.prompt.isEmpty {
+ throw ControlError.failed("Clear or send the existing new-chat draft before starting a workflow.", "DRAFT_PRESENT")
+ }
let cursor = desktopLogCursor()
var components = URLComponents()
components.scheme = "codex"
@@ -1614,7 +1756,10 @@ func launchVerifiedWorkflow(
guard let url = components.url, NSWorkspace.shared.open(url), app.activate() else {
throw ControlError.failed("Codex could not open the requested workflow task.")
}
- guard let witness = waitUntil(timeout: 3.5, operation: {
+ if waitUntil(timeout: 2.5, operation: {
+ verifyCodexNewDraft(app, root: appElement, prompt: request.prompt, cwd: request.cwd) ? true : nil
+ }) == true { return nil }
+ guard let witness = waitUntil(timeout: 1.0, operation: {
freshNewWitness(after: cursor, excluding: existingIds)
}) else {
throw ControlError.failed("Codex emitted no unique fresh workflow task witness.")
diff --git a/native/DesktopActivity.swift b/native/DesktopActivity.swift
new file mode 100644
index 0000000..7be897e
--- /dev/null
+++ b/native/DesktopActivity.swift
@@ -0,0 +1,170 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+// Newer desktops retain multiple active streams. Prefer renderer-owned route
+// synchronization with complete process history and one supported foreground
+// window. The older host-activity fallback requires exactly one retained view.
+// Never take the last active=true line as a focused-chat witness.
+struct DesktopViewEvent {
+ let threadId: String
+ let active: Bool
+ let cursor: UInt64
+}
+func desktopActivityDiagnostic(_ message: String) {
+ guard ProcessInfo.processInfo.environment["STREAMDECK_ACTIVITY_DIAGNOSTICS"] == "1" else { return }
+ FileHandle.standardError.write(Data((message + "\n").utf8))
+}
+
+func desktopViewEvents(_ text: String) -> [DesktopViewEvent]? {
+ var events: [DesktopViewEvent] = []
+ var cursor: UInt64 = 0
+ for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
+ cursor += UInt64(line.utf8.count + 1)
+ guard line.contains("[host-app-server-manager] thread_stream_view_activity_changed ") else { continue }
+ // Do not reinterpret the older renderer-specific format.
+ if line.contains("rendererWindow") { continue }
+ var fields: [String: String] = [:]
+ for field in line.split(separator: " ") {
+ let pair = field.split(separator: "=", maxSplits: 1).map(String.init)
+ guard pair.count == 2 else { continue }
+ guard fields[pair[0]] == nil else { return nil }
+ fields[pair[0]] = pair[1]
+ }
+ guard let id = fields["conversationId"], UUID(uuidString: id) != nil,
+ let active = fields["active"], ["true", "false"].contains(active) else { return nil }
+ events.append(DesktopViewEvent(threadId: id.lowercased(), active: active == "true", cursor: cursor))
+ }
+ return events
+}
+
+func uniqueDesktopView(_ events: [DesktopViewEvent]) -> DesktopViewEvent? {
+ var views: [String: DesktopViewEvent] = [:]
+ for event in events {
+ if event.active { views[event.threadId] = event }
+ else { views.removeValue(forKey: event.threadId) }
+ }
+ return views.count == 1 ? views.values.first : nil
+}
+
+// Sidebar owner synchronization describes the renderer route, unlike retained
+// stream activity. Require one renderer/window pair over the complete process
+// history. Unknown routes invalidate the selection, including new-chat drafts.
+struct DesktopRouteState {
+ let observed: Bool
+ let threadId: String?
+ let cursor: UInt64
+}
+func desktopRouteState(_ text: String) -> DesktopRouteState {
+ var owners = Set(); var selected: String?; var cursor: UInt64 = 0
+ var latest: UInt64 = 0; var observed = false; var malformed = false
+ for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
+ cursor += UInt64(line.utf8.count + 1)
+ guard line.contains("[electron-message-handler] IAB_LIFECYCLE received browser sidebar owner sync ") else { continue }
+ observed = true; latest = cursor; selected = nil
+ var fields: [String: String] = [:]
+ for field in line.split(separator: " ") {
+ let pair = field.split(separator: "=", maxSplits: 1).map(String.init)
+ guard pair.count == 2 else { continue }
+ if fields[pair[0]] != nil { malformed = true }
+ fields[pair[0]] = pair[1]
+ }
+ guard let window = fields["windowId"], Int(window).map({ $0 > 0 }) == true,
+ let renderer = fields["originWebContentsId"], Int(renderer).map({ $0 > 0 }) == true else { malformed = true; continue }
+ owners.insert(window + ":" + renderer)
+ guard let route = fields["ownerRoutePath"], route.hasPrefix("/local/"),
+ let conversation = fields["conversationId"] else { continue }
+ let id = String(route.dropFirst(7)).lowercased()
+ guard UUID(uuidString: id) != nil else { continue }
+ let alias = conversation.hasPrefix("client-new-thread:") && UUID(uuidString: String(conversation.dropFirst(18))) != nil
+ guard conversation.lowercased() == id || alias else { continue }
+ selected = id
+ }
+ return DesktopRouteState(observed: observed, threadId: !malformed && owners.count == 1 ? selected : nil, cursor: latest)
+}
+
+func singleComposerWindowIdentity(_ app: NSRunningApplication) -> String? {
+ guard isCodexFrontmost(app) else { return nil }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ guard let focused = try? uniqueFocusedCodexWindow(root) else { return nil }
+ let windows = attribute(root, kAXWindowsAttribute as CFString) as? [AXUIElement] ?? []
+ let contentWindows = windows.filter {
+ guard let frame = captureAXSnapshot($0, maximumDepth: 0).elements.first?.elementFrame else { return false }
+ return frame.width >= 320 && frame.height >= 200
+ }
+ desktopActivityDiagnostic("content windows=\(contentWindows.count)")
+ guard contentWindows.count == 1, sameElement(contentWindows[0], focused) else { return nil }
+ let composerWindows = windows.filter {
+ let snapshot = captureAXSnapshot($0, maximumDepth: maximumCodexWindowTraversalDepth)
+ return (composerCandidates(in: snapshot).count == 1 || codexApprovalCard(in: snapshot.query) != nil) && codexNewDraftComposer(in: snapshot) == nil
+ }
+ desktopActivityDiagnostic("composer windows=\(composerWindows.count)")
+ guard composerWindows.count == 1, sameElement(composerWindows[0], focused),
+ let frame = captureAXSnapshot(focused, maximumDepth: 0).elements.first?.elementFrame else { return nil }
+ let matches = (CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] ?? []).filter {
+ guard ($0[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == app.processIdentifier,
+ let bounds = $0[kCGWindowBounds as String] as? [String: Any],
+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { return false }
+ return abs(rect.minX - frame.minX) < 2 && abs(rect.minY - frame.minY) < 2 && abs(rect.width - frame.width) < 2 && abs(rect.height - frame.height) < 2
+ }
+ guard matches.count == 1, let number = matches[0][kCGWindowNumber as String] as? NSNumber else { return nil }
+ return "activity:\(app.processIdentifier):\(number.stringValue)"
+}
+
+func currentSingleViewWitness() -> DesktopWitness? {
+ guard let app = try? runningCodex(), let launchDate = app.launchDate,
+ let windowIdentity = singleComposerWindowIdentity(app) else { return nil }
+ // Read complete daily fragments for this process in chronological order.
+ // Missing startup, oversized history, truncation, or replacement fail closed.
+ let paths = desktopLogFiles().filter {
+ URL(fileURLWithPath: $0).lastPathComponent.contains("-\(app.processIdentifier)-t0-i1-")
+ }.sorted()
+ guard let path = paths.first, paths.allSatisfy({ $0.hasSuffix("-0.log") }) else { return nil }
+ var baselines: [String: DesktopLogSnapshot] = [:]; var text = ""
+ for fragment in paths {
+ guard let snapshot = logSnapshot(fragment), snapshot.size <= maximumWitnessReadBytes,
+ let handle = FileHandle(forReadingAtPath: fragment) else { return nil }
+ let data = try? handle.read(upToCount: Int(snapshot.size)); try? handle.close()
+ guard let data, data.count == Int(snapshot.size),
+ let chunk = String(data: data, encoding: .utf8), chunk.hasSuffix("\n"),
+ text.utf8.count + data.count <= maximumWitnessReadBytes else { return nil }
+ text += chunk; baselines[fragment] = snapshot
+ }
+ guard let snapshot = baselines[path] else { return nil }
+ guard
+ let startup = text.split(separator: "\n").prefix(40).first(where: { $0.contains(" info Launching app ") }),
+ abs(witnessTimestamp(String(startup), fallback: 0) - launchDate.timeIntervalSince1970) < 10,
+ let events = desktopViewEvents(text),
+ baselines.allSatisfy({ path, before in
+ guard let after = logSnapshot(path) else { return false }; return after.identity == before.identity && after.size >= before.size
+ }),
+ singleComposerWindowIdentity(app) == windowIdentity else { return nil }
+ let route = desktopRouteState(text)
+ guard let selected = route.observed ? route.threadId : uniqueDesktopView(events)?.threadId else { return nil }
+ return DesktopWitness(conversationId: selected, rendererWindowId: windowIdentity, path: path,
+ cursor: max(route.cursor, events.last?.cursor ?? 0), fileIdentity: snapshot.identity,
+ observedAt: snapshot.modifiedAt, fileModifiedAt: snapshot.modifiedAt,
+ baselines: baselines)
+}
+
+func singleViewWitnessStillCurrent(_ expected: DesktopWitness) -> Bool {
+ guard let current = currentSingleViewWitness(), current.conversationId == expected.conversationId,
+ current.rendererWindowId == expected.rendererWindowId,
+ current.path == expected.path, current.fileIdentity == expected.fileIdentity,
+ current.cursor == expected.cursor,
+ expected.baselines.allSatisfy({ path, before in
+ guard let now = current.baselines[path] else { return false }; return now.identity == before.identity && now.size >= before.size
+ }) else { return false }
+ // The combined route/activity cursor rules out A → B → A, including cached tokens.
+ return true
+}
+
+func freshSingleViewWitness(after cursor: DesktopLogCursor) -> DesktopWitness? {
+ guard let current = currentSingleViewWitness(),
+ cursor.snapshots[current.path]?.identity == current.fileIdentity,
+ current.baselines.allSatisfy({ path, now in
+ guard let before = cursor.snapshots[path] else { return true }; return now.identity == before.identity && now.size >= before.size
+ }),
+ current.cursor > current.baselines.keys.reduce(UInt64(0), { $0 + (cursor.snapshots[$1]?.size ?? 0) }) else { return nil }
+ return current
+}
diff --git a/native/Fixtures.swift b/native/Fixtures.swift
index 67e1b9d..b69986b 100644
--- a/native/Fixtures.swift
+++ b/native/Fixtures.swift
@@ -32,6 +32,7 @@ func selectorFixtureNode(
parentId: String?,
role: String,
text: String,
+ description: String = "",
frame: CGRect? = nil,
enabled: Bool = true,
hidden: Bool = false,
@@ -43,7 +44,7 @@ func selectorFixtureNode(
parentId: parentId,
role: role,
title: text,
- description: "",
+ description: description,
value: "",
help: "",
elementFrame: frame,
@@ -213,6 +214,30 @@ func selectorFixtureNodes(_ scenario: String) -> [NeutralAXNode] {
depth: 1
),
]
+ case "recording-no-editor", "recording-no-cancel", "recording-duplicate", "recording-hidden", "recording-off-owner", "recording-unrelated-owner":
+ var nodes = [root,
+ selectorFixtureNode("strip", parentId: "root", role: "AXGroup", text: "", frame: CGRect(x: 260, y: 500, width: 480, height: 80), hidden: scenario == "recording-hidden", depth: 1),
+ selectorFixtureNode("stop", parentId: "strip", role: kAXButtonRole as String, text: "Stop dictation", description: "Stop dictation", frame: CGRect(x: 690, y: 540, width: 28, height: 28), depth: 2)]
+ if scenario != "recording-no-cancel" {
+ nodes.append(selectorFixtureNode("cancel", parentId: scenario == "recording-unrelated-owner" ? "root" : "strip", role: kAXButtonRole as String, text: "Cancel dictation", frame: CGRect(x: scenario == "recording-off-owner" ? 20 : 270, y: 540, width: 28, height: 28), depth: 2))
+ }
+ if scenario == "recording-duplicate" {
+ nodes.append(selectorFixtureNode("other-stop", parentId: "strip", role: kAXButtonRole as String, text: "Stop dictation", frame: CGRect(x: 650, y: 540, width: 28, height: 28), depth: 2))
+ }
+ return nodes
+ case "mode-repeated-attributes", "dictation-repeated-attributes", "dictation-duplicate-controls":
+ let label = scenario.hasPrefix("mode") ? "Plan" : "Dictate"
+ var nodes = [root, composer, selectorFixtureNode(
+ "control", parentId: "root", role: kAXButtonRole as String,
+ text: label, description: label,
+ frame: CGRect(x: 480, y: 560, width: 120, height: 28), depth: 1)]
+ if scenario == "dictation-duplicate-controls" {
+ nodes.append(selectorFixtureNode(
+ "other-control", parentId: "root", role: kAXButtonRole as String,
+ text: label, description: label,
+ frame: CGRect(x: 620, y: 560, width: 80, height: 28), depth: 1))
+ }
+ return nodes
case "mode-inside":
return [
root,
@@ -441,14 +466,14 @@ func selectorFixtureNodes(_ scenario: String) -> [NeutralAXNode] {
offConfirmButton: scenario == "confirmation-descendant-off-owner-button",
duplicateConfirm: scenario == "confirmation-descendant-duplicate-confirm"
)
- case "add-project":
+ case "add-project", "add-project-current":
return [
root,
selectorFixtureNode(
"sheet",
parentId: "root",
role: kAXSheetRole as String,
- text: "Add New Project",
+ text: scenario == "add-project-current" ? "select project root" : "Add New Project",
frame: CGRect(x: 220, y: 200, width: 360, height: 180),
depth: 1
),
@@ -456,7 +481,7 @@ func selectorFixtureNodes(_ scenario: String) -> [NeutralAXNode] {
"picker",
parentId: "sheet",
role: "AXOpenPanel",
- text: "Open Folder",
+ text: scenario == "add-project-current" ? "" : "Open Folder",
frame: CGRect(x: 260, y: 240, width: 280, height: 120),
depth: 2
),
@@ -866,7 +891,17 @@ func runFixtureAction(_ action: String, arguments: [String]) {
valid = composerIndex.flatMap {
permissionControlIndex(composerIndex: $0, query: query)
} == nil
- case "mode-inside", "mode-outside", "mode-hidden-ancestor", "mode-offwindow":
+ case "recording-no-editor", "recording-no-cancel", "recording-duplicate", "recording-hidden", "recording-off-owner", "recording-unrelated-owner":
+ valid = (dictationControlIndex(in: query, phase: .recording) != nil) == (scenario == "recording-no-editor")
+ && dictationControlIndex(in: query, phase: .idle) == nil
+ case "dictation-repeated-attributes", "dictation-duplicate-controls":
+ let control = composerIndex.flatMap {
+ controlIndex(inComposerRegion: $0, query: query, roles: Set([kAXButtonRole as String])) {
+ dictationTextMatches($0, phase: .idle)
+ }
+ }
+ valid = (control != nil) == (scenario == "dictation-repeated-attributes")
+ case "mode-inside", "mode-repeated-attributes", "mode-outside", "mode-hidden-ancestor", "mode-offwindow":
guard let composerIndex = uniqueComposerIndex(in: query) else {
emit(
ControlResult(
@@ -891,12 +926,12 @@ func runFixtureAction(_ action: String, arguments: [String]) {
let text = normalized($0)
return text == "plan" || text == "planmode"
}
- valid = (mode != nil) == (scenario == "mode-inside")
+ valid = (mode != nil) == (["mode-inside", "mode-repeated-attributes"].contains(scenario))
case "confirmation-valid", "confirmation-nested", "confirmation-descendant-labels":
valid = fullAccessConfirmationButtonIndex(in: query) != nil
case "confirmation-ambiguous", "confirmation-sibling-unequal", "confirmation-missing-cancel", "confirmation-hidden", "confirmation-offwindow", "confirmation-off-owner-button", "confirmation-descendant-hidden-label", "confirmation-descendant-off-owner-child", "confirmation-descendant-off-owner-button", "confirmation-descendant-duplicate-confirm":
valid = fullAccessConfirmationButtonIndex(in: query) == nil
- case "add-project":
+ case "add-project", "add-project-current":
valid = addProjectOwnerIndices(in: query).count == 1
case "add-project-owned":
guard let owner = addProjectOwnerIndices(in: query).first,
@@ -1092,6 +1127,9 @@ func runFixtureAction(_ action: String, arguments: [String]) {
switch scenario {
case "versioned-model":
valid = pickerMenuTextMatches("5.6 Terra", label: "Terra")
+ && pickerMenuTextMatches("GPT-6.1 Sol", label: "6.1 Sol")
+ && !pickerMenuTextMatches("GPT-6 Sol", label: "6.1 Sol")
+ && !pickerMenuTextMatches("GPT-16.1 Sol", label: "6.1 Sol")
case "annotated-ultra":
valid = pickerMenuTextMatches(
"Ultra Consumes usage limits faster",
@@ -1306,6 +1344,39 @@ func runFixtureAction(_ action: String, arguments: [String]) {
)
}
+ if action == "--codex-draft-metadata-fixture" {
+ let payload = arguments.dropFirst().first ?? ""
+ guard let data = Data(base64Encoded: payload), let state = codexDraftMetadata(data) else {
+ emit(ControlResult(ok: false, action: action, requested: nil, model: nil, effort: nil, message: "Draft metadata rejected"), exitCode: 1)
+ }
+ emit(ControlResult(ok: true, action: action, requested: nil, model: state.projectName, effort: String(state.projectRoots.count), draftEmpty: state.prompt.isEmpty, message: "Draft metadata parsed"), exitCode: 0)
+ }
+
+ if action == "--workspace-observation-fixture" {
+ let scenario = arguments.dropFirst().first ?? ""
+ let label = scenario.hasPrefix("review") ? "Review" : scenario.hasPrefix("browser") ? "Browser" : "Side chat"
+ let title = label == "Review" ? "Changes" : label == "Browser" ? "New tab" : "Side chat"
+ let window = selectorFixtureNode("window", parentId: nil, role: "AXWindow", text: "QA", frame: CGRect(x: 0, y: 0, width: 800, height: 600))
+ var nodes = [window, selectorFixtureNode("tab", parentId: "window", role: scenario.hasSuffix("transcript") ? "AXStaticText" : "AXRadioButton", text: title, description: title, frame: CGRect(x: 20, y: 20, width: 200, height: 30), hidden: scenario.hasSuffix("hidden"), selected: !scenario.hasSuffix("unselected"))]
+ if scenario.contains("tiny-tab-list") {
+ nodes = [window,
+ selectorFixtureNode("header", parentId: "window", role: "AXGroup", text: "", frame: CGRect(x: 10, y: 10, width: 750, height: 50)),
+ selectorFixtureNode("list", parentId: "header", role: "AXTabGroup", text: "", frame: CGRect(x: 10, y: 30, width: 2, height: 2), hidden: scenario.hasSuffix("hidden")),
+ selectorFixtureNode("tab", parentId: "list", role: "AXRadioButton", text: title, frame: CGRect(x: scenario.hasSuffix("offwindow") ? 900 : 50, y: 20, width: 200, height: 30), selected: true)]
+ }
+ if scenario.hasPrefix("browser") && !scenario.hasSuffix("no-address") {
+ nodes.append(selectorFixtureNode("address", parentId: "window", role: "AXComboBox", text: "Search files or enter a URL", frame: CGRect(x: 20, y: 60, width: 200, height: 30)))
+ }
+ let expected = !["hidden", "transcript", "unselected", "no-address", "offwindow"].contains { scenario.hasSuffix($0) }
+ let valid: Bool
+ if scenario.hasPrefix("sidebar") {
+ nodes = [window, selectorFixtureNode("sidebar", parentId: "window", role: "AXButton", text: "Hide sidebar", description: "Hide sidebar", frame: CGRect(x: 20, y: 20, width: 30, height: 30))]
+ if scenario.hasSuffix("duplicate") { nodes.append(selectorFixtureNode("other", parentId: "window", role: "AXButton", text: "Hide sidebar", frame: CGRect(x: 60, y: 20, width: 30, height: 30))) }
+ valid = (sidebarControlIndex(in: NeutralAXQuery(nodes: nodes)) != nil) == !scenario.hasSuffix("duplicate")
+ } else { valid = workspaceSurfaceVisible(in: NeutralAXQuery(nodes: nodes), label: label) == expected }
+ emit(ControlResult(ok: valid, action: action, requested: scenario, model: nil, effort: nil, message: "Live workspace observation fixture"), exitCode: valid ? 0 : 1)
+ }
+
if action == "--workspace-shortcut-fixture" {
let scenario = arguments.dropFirst().first ?? ""
let expected: (String, CGKeyCode, CGEventFlags)?
@@ -1315,7 +1386,7 @@ func runFixtureAction(_ action: String, arguments: [String]) {
case "browser":
expected = ("Browser", 17, .maskCommand)
case "files":
- expected = ("Files", 35, .maskCommand)
+ expected = ("Files", 14, [.maskCommand, .maskShift])
case "side-chat":
expected = ("Side chat", 1, [.maskCommand, .maskAlternate])
default:
@@ -1323,20 +1394,24 @@ func runFixtureAction(_ action: String, arguments: [String]) {
}
let observed = workspaceShortcut(scenario)
let before = NeutralAXQuery(nodes: [
+ selectorFixtureNode("window", parentId: nil, role: "AXWindow", text: "QA", frame: CGRect(x: 0, y: 0, width: 800, height: 600)),
selectorFixtureNode(
"surface",
- parentId: nil,
+ parentId: "window",
role: "AXTab",
text: expected?.0 ?? "",
+ frame: CGRect(x: 20, y: 20, width: 200, height: 30),
selected: false
),
])
let after = NeutralAXQuery(nodes: [
+ selectorFixtureNode("window", parentId: nil, role: "AXWindow", text: "QA", frame: CGRect(x: 0, y: 0, width: 800, height: 600)),
selectorFixtureNode(
"surface",
- parentId: nil,
+ parentId: "window",
role: "AXTab",
text: expected?.0 ?? "",
+ frame: CGRect(x: 20, y: 20, width: 200, height: 30),
selected: true
),
])
@@ -1449,10 +1524,55 @@ func runFixtureAction(_ action: String, arguments: [String]) {
)
}
+ if action == "--approval-card-fixture" {
+ let scenario = arguments.dropFirst().first ?? ""
+ let frame = CGRect(x: 0, y: 0, width: 900, height: 700)
+ var nodes = [selectorFixtureNode("root", parentId: nil, role: "AXWindow", text: "", frame: frame),
+ selectorFixtureNode("footer", parentId: "root", role: "AXGroup", text: "", frame: frame, hidden: scenario == "hidden"),
+ selectorFixtureNode("allow", parentId: "footer", role: "AXButton", text: "Allow once", frame: CGRect(x: 500, y: scenario == "offwindow" ? 900 : 600, width: 130, height: 34), enabled: scenario != "disabled"),
+ selectorFixtureNode("deny", parentId: scenario == "split-owner" ? "root" : "footer", role: "AXButton", text: "Deny", frame: CGRect(x: 380, y: 600, width: 100, height: 34))]
+ if scenario != "missing-options" { nodes.append(selectorFixtureNode("options", parentId: "footer", role: "AXPopUpButton", text: "Approval options", frame: CGRect(x: 650, y: 600, width: 30, height: 34))) }
+ if scenario == "duplicate" { nodes.append(selectorFixtureNode("duplicate", parentId: "footer", role: "AXButton", text: "Allow once", frame: CGRect(x: 500, y: 500, width: 130, height: 34))) }
+ if scenario == "composer-present" { nodes.append(selectorFixtureNode("composer", parentId: "root", role: "AXTextArea", text: "", frame: CGRect(x: 200, y: 400, width: 500, height: 40))) }
+ let accepted = codexApprovalCard(in: NeutralAXQuery(nodes: nodes)) != nil
+ let valid = accepted == (scenario == "current-card")
+ emit(ControlResult(ok: valid, action: action, requested: nil, model: nil, effort: nil, message: "Approval footer ownership fixture"), exitCode: valid ? 0 : 1)
+ }
+ if action == "--log-selection-fixture" {
+ let workers = (1...12).map { "/logs/codex-desktop-session-42-t\($0)-i1-000001-0.log" }
+ let startup = "/logs/codex-desktop-session-42-t0-i1-170000-0.log"
+ let current = "/logs/codex-desktop-session-42-t0-i1-000001-0.log"
+ let selected = desktopLogCandidates(workers + [current, startup], processId: 42)
+ let valid = selected.count == 10 && selected.contains(startup) && selected.contains(current) && !selected.contains(workers.last!)
+ emit(ControlResult(ok: valid, action: action, requested: nil, model: nil, effort: nil, message: "Main-process fragments retained beyond worker limit"), exitCode: valid ? 0 : 1)
+ }
+ if action == "--picker-dismissal-fixture" {
+ let scenario = arguments.dropFirst().first ?? ""
+ var presses = 0
+ let closed = dismissPickerUntilClosed(isOpen: {
+ scenario == "stuck" || (scenario == "delayed" && presses < 2)
+ }, dismiss: { presses += 1 }, settle: {})
+ let valid = scenario == "stuck" ? !closed && presses == 4 : closed && presses == (scenario == "delayed" ? 2 : 0)
+ emit(ControlResult(ok: valid, action: action, requested: nil, model: nil, effort: nil, message: "Picker dismissal observation fixture"), exitCode: valid ? 0 : 1)
+ }
+ if action == "--activity-fixture", let payload = arguments.dropFirst().first,
+ let data = Data(base64Encoded: payload), let text = String(data: data, encoding: .utf8) {
+ let events = desktopViewEvents(text)
+ let route = desktopRouteState(text)
+ let selected = route.observed ? route.threadId : events.flatMap { uniqueDesktopView($0) }?.threadId
+ emit(ControlResult(ok: events != nil, action: action, requested: nil, model: selected, effort: String(max(route.cursor, events?.last?.cursor ?? 0)), message: "Host view reduction fixture"), exitCode: events == nil ? 1 : 0)
+ }
if action == "--power-fixture" {
let scenario = arguments.dropFirst().first ?? ""
let valid: Bool
switch scenario {
+ case "picker-chat-title", "picker-duplicate", "picker-hidden":
+ func popup(_ title: String, hidden: Bool = false) -> ElementInfo {
+ ElementInfo(element: AXUIElementCreateSystemWide(), role: kAXPopUpButtonRole as String, title: title, description: "", value: "", help: "", elementFrame: nil, enabled: true, hidden: hidden, selected: false, parentIndex: nil, depth: 0)
+ }
+ var elements = [popup("Add Astra model selectors"), popup("GPT-6 Astra Extra High", hidden: scenario == "picker-hidden")]
+ if scenario == "picker-duplicate" { elements.append(popup("GPT-6.1 Sol Medium")) }
+ valid = scenario == "picker-chat-title" ? pickerCandidate(in: elements)?.title == "GPT-6 Astra Extra High" : pickerCandidate(in: elements) == nil
case "fast-control", "fast-control-hidden", "fast-control-disabled", "fast-control-ambiguous", "fast-speed-menu", "fast-speed-option":
let root = selectorFixtureNode("root", parentId: nil, role: kAXWindowRole as String, text: "", frame: CGRect(x: 0, y: 0, width: 900, height: 700))
let label = scenario == "fast-speed-menu" ? "Speed Standard" : scenario == "fast-speed-option" ? "Fast" : "Enable Fast mode"
@@ -1466,11 +1586,12 @@ func runFixtureAction(_ action: String, arguments: [String]) {
}
let index = fastControlIndex(in: NeutralAXQuery(nodes: nodes), speedMenu: scenario == "fast-speed-menu", option: scenario == "fast-speed-option" ? "fast" : nil)
valid = ["fast-control", "fast-speed-menu", "fast-speed-option"].contains(scenario) ? index == 1 : index == nil
- case "accessibility-chromium", "accessibility-chromium-appkit", "accessibility-electron", "accessibility-enabled", "accessibility-denied":
+ case "accessibility-chromium", "accessibility-chromium-appkit", "accessibility-electron", "accessibility-enabled", "accessibility-denied", "accessibility-claude-enhanced-only":
var enabled: [String] = []
var settled = 0
_ = initializePickerAccessibility(
- read: { scenario == "accessibility-enabled" && $0 == "AXEnhancedUserInterface" },
+ requireManual: scenario == "accessibility-claude-enhanced-only",
+ read: { ["accessibility-enabled", "accessibility-claude-enhanced-only"].contains(scenario) && $0 == "AXEnhancedUserInterface" },
enable: { name in
enabled.append(name)
if scenario == "accessibility-denied" { return .apiDisabled }
@@ -2096,11 +2217,11 @@ func runFixtureAction(_ action: String, arguments: [String]) {
if let before = state.markerBefore, let after = state.markerAfter {
return observedNewMarker(before: before, after: after)
}
- if let sameComposer = state.sameComposer,
+ if let uniqueComposerInCapturedWindow = state.uniqueComposerInCapturedWindow,
let draftIsEmpty = state.draftIsEmpty,
let before = state.messagesBefore,
let after = state.messagesAfter {
- return submittedComposerProof(sameComposer: sameComposer, draftIsEmpty: draftIsEmpty, beforeMessages: before, afterMessages: after)
+ return submittedComposerProof(uniqueComposerInCapturedWindow: uniqueComposerInCapturedWindow, draftIsEmpty: draftIsEmpty, newMessageObserved: state.newMessageObserved ?? (after > before))
}
if let pendingRemains = state.pendingRemains {
return approvalResolutionObserved(pendingRemains: pendingRemains)
diff --git a/native/Models.swift b/native/Models.swift
index 948c100..ea51057 100644
--- a/native/Models.swift
+++ b/native/Models.swift
@@ -4,6 +4,7 @@ import Darwin
import Foundation
struct ControlResult: Codable {
+ var providerState: ProviderState? = nil
let ok: Bool
let action: String
let requested: String?
@@ -43,10 +44,10 @@ struct AXSnapshot {
let query: NeutralAXQuery
}
-// Current Codex builds place the visible composer at AX depth 27. Keep one
+// Current OpenAI desktop builds wrap picker/permission labels beyond depth 32. Keep one
// bounded window traversal policy so preflight, postflight, approval reads,
// and diagnostics cannot silently diverge as the Electron tree gains wrappers.
-let maximumCodexWindowTraversalDepth = 32
+let maximumCodexWindowTraversalDepth = 40
func shouldInitializeCodexAccessibility(action: String) -> Bool {
Set([
@@ -199,7 +200,8 @@ struct WorkflowProofState: Codable {
struct DispatchFixtureState: Codable {
let markerBefore: Int?
let markerAfter: Int?
- let sameComposer: Bool?
+ let uniqueComposerInCapturedWindow: Bool?
+ let newMessageObserved: Bool?
let draftIsEmpty: Bool?
let messagesBefore: Int?
let messagesAfter: Int?
@@ -244,6 +246,7 @@ struct NeutralTargetState {
let focusedWindowIds: [String]
let capturedWindowId: String
let composerCount: Int
+ var pendingApprovalCard: Bool = false
}
enum ControlError: LocalizedError {
@@ -282,7 +285,7 @@ func validatedModelSelection(_ payload: String) -> PickerSelectionRequest? {
guard
let request = decodeNativePayload(payload, as: PickerSelectionRequest.self),
request.value.count <= 64,
- request.label.count <= 16,
+ request.label.count <= 64,
request.value.lowercased().hasPrefix("gpt-"),
request.value.unicodeScalars.allSatisfy({ scalar in
CharacterSet.alphanumerics.contains(scalar)
@@ -293,10 +296,14 @@ func validatedModelSelection(_ payload: String) -> PickerSelectionRequest? {
let family = ["luna", "terra", "sol", "astra"].first(where: {
lower.hasSuffix("-\($0)")
})
- guard let family, normalized(request.label) == normalized(family) else {
- return nil
- }
- return request
+ guard let family else { return nil }
+ let exactLabel = String(lower.dropFirst(4).dropLast(family.count + 1)) + " " + family.capitalized
+ guard normalized(request.label) == normalized(family)
+ || codexModelIdentity(request.label) == codexModelIdentity(exactLabel),
+ codexModelIdentity(exactLabel) != nil else { return nil }
+ // Old action settings may still send a family label. The value already
+ // names an exact catalog model, so use its version for menu selection.
+ return PickerSelectionRequest(value: request.value, label: exactLabel)
}
func validatedEffortSelection(_ payload: String) -> PickerSelectionRequest? {
diff --git a/native/Targeting.swift b/native/Targeting.swift
index 38fabcd..652cb05 100644
--- a/native/Targeting.swift
+++ b/native/Targeting.swift
@@ -17,6 +17,7 @@ func runningCodex() throws -> NSRunningApplication {
}
func desktopLogFiles() -> [String] {
+ guard let app = try? runningCodex() else { return [] }
let root = URL(fileURLWithPath: NSHomeDirectory())
.appendingPathComponent("Library/Logs/com.openai.codex")
let formatter = DateFormatter()
@@ -24,22 +25,32 @@ func desktopLogFiles() -> [String] {
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy/MM/dd"
let manager = FileManager.default
- return [Date(), Date(timeIntervalSinceNow: -86_400)].flatMap { date in
+ let candidates = [Date(), Date(timeIntervalSinceNow: -86_400)].flatMap { date in
let directory = root.appendingPathComponent(formatter.string(from: date))
return (try? manager.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey]
)) ?? []
}
- .filter { $0.pathExtension == "log" }
+ .filter {
+ guard $0.pathExtension == "log", $0.lastPathComponent.contains("-\(app.processIdentifier)-t") else { return false }
+ let modified = try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ return (modified ?? Date.distantPast) >= (app.launchDate ?? Date.distantPast)
+ }
.sorted {
let left = try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
let right = try? $1.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
return (left ?? .distantPast) > (right ?? .distantPast)
}
- .prefix(8).map {
- $0.standardized.resolvingSymlinksInPath().path
- }
+ .map { $0.standardized.resolvingSymlinksInPath().path }
+ return desktopLogCandidates(candidates, processId: app.processIdentifier)
+}
+
+func desktopLogCandidates(_ paths: [String], processId: Int32) -> [String] {
+ // New empty worker logs must not evict yesterday's main-process startup.
+ paths.enumerated().filter { index, path in
+ index < 8 || URL(fileURLWithPath: path).lastPathComponent.contains("-\(processId)-t0-i1-")
+ }.map { $0.element }
}
func desktopLogCursor() -> DesktopLogCursor {
@@ -260,6 +271,9 @@ func freshWitnessEvents(paths: [String], after cursor: DesktopLogCursor, scoped:
}
func freshWitness(threadId: String, after cursor: DesktopLogCursor) -> DesktopWitness? {
+ if let witness = freshSingleViewWitness(after: cursor) {
+ return witness.conversationId == threadId ? witness : nil
+ }
let paths = desktopLogFiles()
guard let collected = freshWitnessEvents(paths: paths, after: cursor, scoped: true),
let witness = globalNewestWitness(collected.events),
@@ -278,13 +292,19 @@ func freshWitness(threadId: String, after cursor: DesktopLogCursor) -> DesktopWi
}
func currentWitness(threadId: String) -> DesktopWitness? {
- currentWitness(in: desktopLogFiles(), threadId: threadId, scoped: true)
+ if let witness = currentSingleViewWitness() {
+ return witness.conversationId == threadId ? witness : nil
+ }
+ return currentWitness(in: desktopLogFiles(), threadId: threadId, scoped: true)
}
func freshNewWitness(
after cursor: DesktopLogCursor,
excluding existingThreadIds: Set
) -> DesktopWitness? {
+ if let witness = freshSingleViewWitness(after: cursor) {
+ return existingThreadIds.contains(witness.conversationId) ? nil : witness
+ }
let paths = desktopLogFiles()
guard let collected = freshWitnessEvents(paths: paths, after: cursor, scoped: true),
collected.events.count == 1,
@@ -472,6 +492,7 @@ func canonicalPath(_ path: String) -> String {
}
func hasCurrentWitness(_ expected: DesktopWitness) -> Bool {
+ if expected.rendererWindowId.hasPrefix("activity:") { return singleViewWitnessStillCurrent(expected) }
let paths = desktopLogFiles()
guard paths.contains(expected.path),
!expected.baselines.isEmpty,
@@ -618,7 +639,7 @@ func validatedTargetWindow(
state.historyContinuous,
state.tokenRoundTrips,
state.frontmost,
- state.composerCount == 1,
+ (state.composerCount == 1 || (state.composerCount == 0 && state.pendingApprovalCard)),
let fresh = state.freshWitness,
fresh.conversationId == requestedThreadId,
fresh.rendererWindowId == requestedRendererWindowId,
@@ -653,6 +674,7 @@ func verifyTarget(
throw ControlError.failed("The focused Codex accessibility window changed before mutation.", "TARGET_MISMATCH")
}
let windowId = sameFocusedWindow ? "captured" : "changed"
+ let elementsForProof = composerElements ?? captureAXSnapshot(window, maximumDepth: maximumCodexWindowTraversalDepth).elements
let neutral = NeutralTargetState(
freshWitness: expected,
currentWitness: witnessMatches ? expected : nil,
@@ -664,8 +686,8 @@ func verifyTarget(
allWindowIds: ["captured"],
focusedWindowIds: [windowId],
capturedWindowId: "captured",
- composerCount: composerElements.map { composerCandidates(in: $0).count }
- ?? composerCandidates(in: window).count
+ composerCount: composerCandidates(in: elementsForProof).count,
+ pendingApprovalCard: codexApprovalCard(in: NeutralAXQuery(nodes: neutralNodes(from: elementsForProof))) != nil
)
guard validatedTargetWindow(
neutral,
@@ -717,6 +739,9 @@ func focusCodex(_ app: NSRunningApplication, appElement: AXUIElement, threadId:
guard let threadId else {
throw ControlError.failed("A focused Codex task ID is required for mutation.")
}
+ if let current = currentSingleViewWitness(), current.conversationId == threadId {
+ return TargetContext(window: try verifyTarget(app, appElement: appElement, witness: current), witness: current)
+ }
let cursor = desktopLogCursor()
guard let url = URL(string: "codex://threads/\(threadId)"), NSWorkspace.shared.open(url) else {
throw ControlError.failed("Could not open the target Codex task.")
diff --git a/native/main.swift b/native/main.swift
index 6c64939..8987cca 100644
--- a/native/main.swift
+++ b/native/main.swift
@@ -18,6 +18,7 @@ let requested = arguments.count > 1 ? arguments[1] : nil
let threadId = arguments.count > 2 ? arguments[2] : nil
runFixtureAction(action, arguments: arguments)
+runProviderAction(action, requested: requested)
var accessibilityInitialization = "not attempted"
do {
@@ -359,23 +360,23 @@ do {
)
case "new-project":
var transaction = try preflight()
- let beforeSnapshot = captureAXSnapshot(appElement)
+ let beforeSnapshot = transaction.snapshot
let originalWindow = transaction.window
try pressKey(31, flags: .maskCommand)
- guard waitUntil(timeout: 2.4, operation: {
+ guard let openedPicker = waitUntil(timeout: 2.4, operation: {
singlePassQuery(
poll: SinglePassCapture(),
- capture: { captureAXSnapshot(appElement) },
+ capture: { captureAXSnapshot(originalWindow, skippingChildrenOfRoles: ["AXOutline", "AXTable", "AXBrowser", "AXList"]) },
query: { snapshot in
newOwnedAddProjectPicker(
before: beforeSnapshot,
after: snapshot,
retainedWindow: originalWindow
- )
+ ).map { snapshot.elements[$0].element }
}
)
?? nil
- }) != nil else {
+ }) else {
throw ControlError.failed(
"Codex did not show a verified Add Project picker."
)
@@ -388,11 +389,14 @@ do {
)
}
try recordTransactionOperation(&transaction)
- try postflightTargetTransaction(
- &transaction,
- app: app,
- appElement: appElement
- )
+ // The newly opened sheet is already proven to belong to this exact
+ // window. Do not walk its potentially enormous directory listing.
+ guard let focused = attribute(appElement, kAXFocusedWindowAttribute as CFString),
+ CFGetTypeID(focused) == AXUIElementGetTypeID(),
+ (sameElement(originalWindow, focused as! AXUIElement) || sameElement(openedPicker, focused as! AXUIElement)),
+ transaction.state.record(.postflight), transaction.state.complete else {
+ throw ControlError.failed("Project picker window changed.", "TARGET_MISMATCH")
+ }
emit(
ControlResult(
ok: true,
@@ -419,9 +423,9 @@ do {
requested: nil,
model: nil,
effort: nil,
- rendererWindowId: witness.rendererWindowId,
- witnessToken: try encodeWitnessToken(witness),
- message: "The new Codex workflow task has the verified project and draft."
+ rendererWindowId: witness?.rendererWindowId,
+ witnessToken: try witness.map { try encodeWitnessToken($0) },
+ message: "The new Codex workflow draft has the verified project and prompt."
),
exitCode: 0
)
diff --git a/package-lock.json b/package-lock.json
index cbf08fb..c7a85ff 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,39 +1,39 @@
{
"name": "streamdeck-codex-companion",
- "version": "0.2.5",
+ "version": "0.3.0-beta.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "streamdeck-codex-companion",
- "version": "0.2.5",
+ "version": "0.3.0-beta.3",
"license": "MIT",
"dependencies": {
- "@elgato/streamdeck": "3.0.1"
+ "@elgato/streamdeck": "3.0.4"
},
"devDependencies": {
- "@elgato/cli": "1.10.1",
- "@types/node": "26.6.4",
+ "@elgato/cli": "1.10.4",
+ "@types/node": "26.6.6",
"esbuild": "0.28.2",
- "lucide-static": "^1.52.0",
- "opentype.js": "1.3.4",
- "prettier": "3.9.9",
+ "lucide-static": "1.73.0",
+ "opentype.js": "2.0.0",
+ "prettier": "3.10.1",
"typescript": "7.0.2",
- "vitest": "5.0.3",
- "ws": "8.22.0"
+ "vitest": "5.1.0",
+ "ws": "8.23.0"
},
"engines": {
"node": ">=24"
}
},
"node_modules/@elgato/cli": {
- "version": "1.10.1",
- "resolved": "https://registry.npmjs.org/@elgato/cli/-/cli-1.10.1.tgz",
- "integrity": "sha512-9qizVxHvLjVu6kK8kilpdXdvGrJF/232Bpt1+qtJ5vgONO8vuaYCp2TZe3BMOwOPrL/YDtoohgf+1gj5nEw8aQ==",
+ "version": "1.10.4",
+ "resolved": "https://registry.npmjs.org/@elgato/cli/-/cli-1.10.4.tgz",
+ "integrity": "sha512-v4u+TNyGxmOPsQgL04iHJ2LHViO0UE2BLngVCKfsM39V/dHbXrzp71VsAv5Y3GspFlP8f0YW+ONMPvJyx/ySpA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@elgato/schemas": "0.5.1",
+ "@elgato/schemas": "0.6.0",
"@humanwhocodes/momoa": "^3.0.0",
"@zip.js/zip.js": "^2.7.54",
"ajv": "^8.17.1",
@@ -58,19 +58,19 @@
}
},
"node_modules/@elgato/schemas": {
- "version": "0.5.1",
- "resolved": "https://registry.npmjs.org/@elgato/schemas/-/schemas-0.5.1.tgz",
- "integrity": "sha512-w/YjOlBI+hbCqXF6FXrYvNu6wRvsmfu+Pf123xh3hC5Fcv3R2wLrQvgD8lKR87+zyj7/4Xh3/oXosHL6a/8LMQ==",
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/@elgato/schemas/-/schemas-0.6.0.tgz",
+ "integrity": "sha512-fK3y35ZDwow3HV7/wuQyN/cy/Ir2rlYHiGAV9cUrNETz1T1bjtMl5tSaIooC3CBVLtMjsM4JuHwxejJouTkR1Q==",
"license": "MIT"
},
"node_modules/@elgato/streamdeck": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/@elgato/streamdeck/-/streamdeck-3.0.1.tgz",
- "integrity": "sha512-p9rfc9SaPfvsCX6PyzQDN0zo2QetwpPK3eR9jq6nWWmhhoLrBA0ndm/mTK+7WisDUIY7Mo41lgwNObaYvKagkw==",
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@elgato/streamdeck/-/streamdeck-3.0.4.tgz",
+ "integrity": "sha512-AAaRxzR1bWwR6v2OVaqiAe3pjsbm3llddPSiioYgYQsHDorV+Cq/ZxQv5gIvjbnuh06CmItPpN7JuEEdrnQ1PQ==",
"license": "MIT",
"dependencies": {
- "@elgato/schemas": "0.5.1",
- "@elgato/utils": "0.6.0",
+ "@elgato/schemas": "0.6.0",
+ "@elgato/utils": "0.6.2",
"ws": "^8.19.0"
},
"engines": {
@@ -78,14 +78,51 @@
}
},
"node_modules/@elgato/utils": {
- "version": "0.6.0",
- "resolved": "https://registry.npmjs.org/@elgato/utils/-/utils-0.6.0.tgz",
- "integrity": "sha512-DkBf07zo0qzHkoMO2L8HSDlfEwI56rI0fWedJjXcafPpoePoZ/nzqi+xL60Ad2KpQzCxstyN65oqVZ/Ar6woNg==",
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/@elgato/utils/-/utils-0.6.2.tgz",
+ "integrity": "sha512-YxBKhF52a+rJdPwyDIBOXgyNCe9+lU+q8wMocZ7Zn50D6nRmOiCQksbNvw0UzYtC4uIIn8+f3CGMn/QnX+/3uQ==",
"license": "MIT",
"dependencies": {
"zod": "^3.25.24"
}
},
+ "node_modules/@emnapi/core": {
+ "version": "2.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
+ "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "2.2.0",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "2.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
+ "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
+ "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
@@ -889,9 +926,9 @@
}
},
"node_modules/@jridgewell/resolve-uri": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
- "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
"dev": true,
"license": "MIT",
"engines": {
@@ -916,10 +953,33 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.2.6",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
+ "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.3"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
+ "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
+ }
+ },
"node_modules/@oxc-project/types": {
- "version": "0.152.0",
- "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",
- "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==",
+ "version": "0.156.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz",
+ "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==",
"dev": true,
"license": "MIT",
"peer": true,
@@ -928,9 +988,9 @@
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz",
- "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
+ "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==",
"cpu": [
"arm"
],
@@ -946,9 +1006,9 @@
}
},
"node_modules/@rolldown/binding-android-arm64": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz",
- "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz",
+ "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==",
"cpu": [
"arm64"
],
@@ -964,9 +1024,9 @@
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz",
- "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz",
+ "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==",
"cpu": [
"arm64"
],
@@ -982,9 +1042,9 @@
}
},
"node_modules/@rolldown/binding-darwin-x64": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz",
- "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz",
+ "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==",
"cpu": [
"x64"
],
@@ -1000,9 +1060,9 @@
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz",
- "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz",
+ "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==",
"cpu": [
"x64"
],
@@ -1018,9 +1078,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz",
- "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz",
+ "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==",
"cpu": [
"arm"
],
@@ -1036,16 +1096,13 @@
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz",
- "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz",
+ "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==",
"cpu": [
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1057,16 +1114,13 @@
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz",
- "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz",
+ "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==",
"cpu": [
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1078,16 +1132,13 @@
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz",
- "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz",
+ "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==",
"cpu": [
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1099,16 +1150,13 @@
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz",
- "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz",
+ "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==",
"cpu": [
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1120,16 +1168,13 @@
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz",
- "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz",
+ "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==",
"cpu": [
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1141,16 +1186,13 @@
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz",
- "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz",
+ "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==",
"cpu": [
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1162,9 +1204,9 @@
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz",
- "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz",
+ "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==",
"cpu": [
"arm64"
],
@@ -1179,10 +1221,30 @@
"node": "^20.19.0 || >=22.12.0"
}
},
+ "node_modules/@rolldown/binding-wasm32-wasi": {
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz",
+ "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@emnapi/core": "2.0.0-beta.2",
+ "@emnapi/runtime": "2.0.0-beta.2",
+ "@napi-rs/wasm-runtime": "1.2.6"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
+ }
+ },
"node_modules/@rolldown/binding-win32-arm64-msvc": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz",
- "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz",
+ "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==",
"cpu": [
"arm64"
],
@@ -1198,9 +1260,9 @@
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz",
- "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz",
+ "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==",
"cpu": [
"x64"
],
@@ -1216,13 +1278,25 @@
}
},
"node_modules/@rolldown/pluginutils": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
- "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
+ "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
"dev": true,
"license": "MIT",
"peer": true
},
+ "node_modules/@tybys/wasm-util": {
+ "version": "0.10.4",
+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",
+ "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -1242,16 +1316,16 @@
"license": "MIT"
},
"node_modules/@types/estree": {
- "version": "1.0.9",
- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
- "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
+ "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "26.6.4",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz",
- "integrity": "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==",
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1599,22 +1673,22 @@
}
},
"node_modules/@vitest/mocker": {
- "version": "5.0.3",
- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz",
- "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==",
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz",
+ "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.31",
- "@vitest/spy": "5.0.3",
+ "@vitest/spy": "5.1.0",
"estree-walker": "^3.0.3",
- "magic-string": "^1.2.3"
+ "magic-string": "^1.4.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
- "msw": "^2.4.9",
+ "msw": "^2.4.9 || ^3.0.0",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
@@ -1627,9 +1701,9 @@
}
},
"node_modules/@vitest/spy": {
- "version": "5.0.3",
- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz",
- "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==",
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz",
+ "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==",
"dev": true,
"license": "MIT",
"funding": {
@@ -1732,9 +1806,9 @@
}
},
"node_modules/chai": {
- "version": "6.2.2",
- "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
- "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
+ "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -2288,9 +2362,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -2313,9 +2384,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -2338,9 +2406,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -2363,9 +2428,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -2463,16 +2525,16 @@
}
},
"node_modules/lucide-static": {
- "version": "1.52.0",
- "resolved": "https://registry.npmjs.org/lucide-static/-/lucide-static-1.52.0.tgz",
- "integrity": "sha512-0zZYihAze4ZmUCcyNa9OkWYqn/Y5f9AdTh02AZIxMtP5ravcTTfoSIAnUPBH6ZvKxt+ZW28JB0ldzLRyD82fcw==",
+ "version": "1.73.0",
+ "resolved": "https://registry.npmjs.org/lucide-static/-/lucide-static-1.73.0.tgz",
+ "integrity": "sha512-/FfzdRThAPnDVMk643pzENqYUnxudEON/fyOdh31ZiPiw/seE9VoYeIJPRDTCLDNtnF+5pK6CNwf6IkQMfrJ5w==",
"dev": true,
"license": "ISC"
},
"node_modules/magic-string": {
- "version": "1.4.2",
- "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.2.tgz",
- "integrity": "sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g==",
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
+ "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2523,9 +2585,9 @@
}
},
"node_modules/obug": {
- "version": "2.1.4",
- "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
- "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==",
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz",
+ "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==",
"dev": true,
"funding": [
"https://github.com/sponsors/sxzz",
@@ -2537,20 +2599,13 @@
}
},
"node_modules/opentype.js": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-1.3.4.tgz",
- "integrity": "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-2.0.0.tgz",
+ "integrity": "sha512-kCyjv6xdDY1W/jLWZ/L3QhhTlKUqDZMQ5+Jdlw12b3dXkKNpYBqqlMMj0YDQPShWFTMwgZI1hG14kN3XUDSg/A==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "string.prototype.codepointat": "^0.2.1",
- "tiny-inflate": "^1.0.3"
- },
"bin": {
"ot": "bin/ot"
- },
- "engines": {
- "node": ">= 8.0.0"
}
},
"node_modules/picocolors": {
@@ -2574,9 +2629,9 @@
}
},
"node_modules/postcss": {
- "version": "8.5.28",
- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
- "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "version": "8.5.33",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
+ "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
"dev": true,
"funding": [
{
@@ -2595,18 +2650,18 @@
"license": "MIT",
"peer": true,
"dependencies": {
- "nanoid": "^3.3.18",
+ "nanoid": "^3.3.20",
"picocolors": "^1.1.1",
- "source-map-js": "^1.2.1"
+ "source-map-js": "^1.2.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/prettier": {
- "version": "3.9.9",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.9.tgz",
- "integrity": "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==",
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.10.1.tgz",
+ "integrity": "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==",
"dev": true,
"license": "MIT",
"bin": {
@@ -2637,14 +2692,14 @@
}
},
"node_modules/rolldown": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz",
- "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==",
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz",
+ "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "@oxc-project/types": "=0.152.0",
+ "@oxc-project/types": "=0.156.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
@@ -2654,21 +2709,22 @@
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
- "@rolldown/binding-android-arm-eabi": "1.2.12",
- "@rolldown/binding-android-arm64": "1.2.12",
- "@rolldown/binding-darwin-arm64": "1.2.12",
- "@rolldown/binding-darwin-x64": "1.2.12",
- "@rolldown/binding-freebsd-x64": "1.2.12",
- "@rolldown/binding-linux-arm-gnueabihf": "1.2.12",
- "@rolldown/binding-linux-arm64-gnu": "1.2.12",
- "@rolldown/binding-linux-arm64-musl": "1.2.12",
- "@rolldown/binding-linux-ppc64-gnu": "1.2.12",
- "@rolldown/binding-linux-s390x-gnu": "1.2.12",
- "@rolldown/binding-linux-x64-gnu": "1.2.12",
- "@rolldown/binding-linux-x64-musl": "1.2.12",
- "@rolldown/binding-openharmony-arm64": "1.2.12",
- "@rolldown/binding-win32-arm64-msvc": "1.2.12",
- "@rolldown/binding-win32-x64-msvc": "1.2.12"
+ "@rolldown/binding-android-arm-eabi": "1.2.19",
+ "@rolldown/binding-android-arm64": "1.2.19",
+ "@rolldown/binding-darwin-arm64": "1.2.19",
+ "@rolldown/binding-darwin-x64": "1.2.19",
+ "@rolldown/binding-freebsd-x64": "1.2.19",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.19",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.19",
+ "@rolldown/binding-linux-arm64-musl": "1.2.19",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.19",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.19",
+ "@rolldown/binding-linux-x64-gnu": "1.2.19",
+ "@rolldown/binding-linux-x64-musl": "1.2.19",
+ "@rolldown/binding-openharmony-arm64": "1.2.19",
+ "@rolldown/binding-wasm32-wasi": "1.2.19",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.19",
+ "@rolldown/binding-win32-x64-msvc": "1.2.19"
}
},
"node_modules/run-async": {
@@ -2736,9 +2792,9 @@
}
},
"node_modules/std-env": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
- "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
+ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
"dev": true,
"license": "MIT"
},
@@ -2757,13 +2813,6 @@
"node": ">=8"
}
},
- "node_modules/string.prototype.codepointat": {
- "version": "0.2.1",
- "resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz",
- "integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -2790,17 +2839,10 @@
"node": ">=8"
}
},
- "node_modules/tiny-inflate": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
- "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/tinybench": {
- "version": "6.1.4",
- "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.1.4.tgz",
- "integrity": "sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==",
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz",
+ "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -2808,9 +2850,9 @@
}
},
"node_modules/tinyexec": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",
- "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -2884,17 +2926,17 @@
"license": "MIT"
},
"node_modules/vite": {
- "version": "8.3.1",
- "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",
- "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",
+ "version": "8.3.8",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
+ "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.7",
- "postcss": "^8.5.28",
- "rolldown": "~1.2.9",
+ "postcss": "^8.5.32",
+ "rolldown": "~1.2.18",
"tinyglobby": "^0.2.17"
},
"bin": {
@@ -2911,7 +2953,7 @@
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
- "@vitejs/devtools": "^0.7.1",
+ "@vitejs/devtools": "^0.7.1 || ^0.8.0",
"esbuild": "^0.27.0 || ^0.28.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
@@ -2963,23 +3005,23 @@
}
},
"node_modules/vitest": {
- "version": "5.0.3",
- "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz",
- "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==",
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz",
+ "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
- "@vitest/mocker": "5.0.3",
- "chai": "^6.2.2",
+ "@vitest/mocker": "5.1.0",
+ "chai": "^6.3.0",
"es-module-lexer": "^2.3.2",
"expect-type": "^1.4.0",
- "magic-string": "^1.2.3",
- "obug": "^2.1.4",
+ "magic-string": "^1.4.3",
+ "obug": "^3.0.0",
"picomatch": "^4.0.7",
- "std-env": "^4.2.0",
- "tinybench": "^6.1.4",
- "tinyexec": "^1.3.0",
+ "std-env": "^4.3.0",
+ "tinybench": "^6.2.2",
+ "tinyexec": "^1.3.1",
"tinyglobby": "^0.2.17",
"why-is-node-running": "3.2.1"
},
@@ -2996,12 +3038,12 @@
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^22.0.0 || >=24.0.0",
- "@vitest/browser-playwright": "5.0.3",
- "@vitest/browser-preview": "5.0.3",
+ "@vitest/browser-playwright": "5.1.0",
+ "@vitest/browser-preview": "5.1.0",
"@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
- "@vitest/coverage-istanbul": "5.0.3",
- "@vitest/coverage-v8": "5.0.3",
- "@vitest/ui": "5.0.3",
+ "@vitest/coverage-istanbul": "5.1.0",
+ "@vitest/coverage-v8": "5.1.0",
+ "@vitest/ui": "5.1.0",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
@@ -3074,9 +3116,9 @@
}
},
"node_modules/ws": {
- "version": "8.22.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
- "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
+ "version": "8.23.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
+ "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@@ -3121,9 +3163,9 @@
}
},
"node_modules/zod": {
- "version": "3.25.76",
- "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "version": "4.6.6",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.6.tgz",
+ "integrity": "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
diff --git a/package.json b/package.json
index e16291a..24341b2 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,9 @@
{
"name": "streamdeck-codex-companion",
- "version": "0.2.5",
+ "version": "0.3.0-beta.3",
"private": true,
"type": "module",
- "description": "Independent Stream Deck companion for the Codex desktop app.",
+ "description": "Independent Stream Deck companion for Codex and Claude Code Desktop.",
"author": "Todd",
"license": "MIT",
"repository": {
@@ -19,12 +19,15 @@
"stream-deck",
"stream-deck-plus",
"macos",
- "openai"
+ "openai",
+ "claude",
+ "anthropic"
],
"overrides": {
- "brace-expansion": ">=5.0.12",
+ "brace-expansion": "5.0.12",
"fast-uri": "3.1.8",
- "nanoid": "3.3.18"
+ "nanoid": "3.3.18",
+ "zod": "4.6.6"
},
"engines": {
"node": ">=24"
@@ -76,17 +79,17 @@
"test:fast": "vitest run --project unit"
},
"dependencies": {
- "@elgato/streamdeck": "3.0.1"
+ "@elgato/streamdeck": "3.0.4"
},
"devDependencies": {
- "@elgato/cli": "1.10.1",
- "@types/node": "26.6.4",
+ "@elgato/cli": "1.10.4",
+ "@types/node": "26.6.6",
"esbuild": "0.28.2",
- "lucide-static": "^1.52.0",
- "opentype.js": "1.3.4",
- "prettier": "3.9.9",
+ "lucide-static": "1.73.0",
+ "opentype.js": "2.0.0",
+ "prettier": "3.10.1",
"typescript": "7.0.2",
- "vitest": "5.0.3",
- "ws": "8.22.0"
+ "vitest": "5.1.0",
+ "ws": "8.23.0"
}
}
diff --git a/scripts/build-native.mjs b/scripts/build-native.mjs
index 5f890fb..68a4c78 100644
--- a/scripts/build-native.mjs
+++ b/scripts/build-native.mjs
@@ -28,6 +28,7 @@ const result = spawnSync(
"/usr/bin/xcrun",
[
"swiftc",
+ "-O",
...nativeSources,
"-framework",
"AppKit",
diff --git a/scripts/build-profile.mjs b/scripts/build-profile.mjs
index b02b21d..67196ac 100644
--- a/scripts/build-profile.mjs
+++ b/scripts/build-profile.mjs
@@ -1,3 +1,5 @@
+import { writeMasterProfile } from "./lib/master-profile.mjs";
+import { sharedId, sharedProfileName } from "./lib/shared-profile.mjs";
import {
cp,
mkdir,
@@ -7,6 +9,7 @@ import {
rename,
rm,
utimes,
+ writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
@@ -41,12 +44,28 @@ const profiles = [
{
archiveName: "streamdeckcodex-plus",
profileDirectory: "2533E930-E936-4286-84E4-70B4A8D75417.sdProfile",
+ slug: "plus",
+ columns: 4,
+ rows: 2,
+ model: "20GBD9901",
+ name: "Stream Deck +",
},
...keypadProfiles.map((profile) => ({
+ ...profile,
archiveName: profile.archiveName,
profileDirectory: `${profile.archiveName}.sdProfile`,
})),
];
+const allProfiles = [
+ ...profiles,
+ ...profiles.map((profile) => ({
+ ...profile,
+ sourceArchiveName: profile.archiveName,
+ archiveName: sharedProfileName(profile.archiveName),
+ profileDirectory: `${sharedId("master-v2:" + profile.profileDirectory)}.sdProfile`,
+ shared: true,
+ })),
+];
const temporary = await mkdtemp(join(tmpdir(), "streamdeckcodex-profile-"));
const archiveTimestamp = new Date("2000-01-01T00:00:00.000Z");
@@ -77,12 +96,28 @@ async function normalizeArchiveTimes(directory, entries) {
try {
await mkdir(outputRoot, { recursive: true });
- for (const profile of profiles) {
- const source = join(root, "profile-src", profile.archiveName);
+ for (const profile of allProfiles) {
+ const source = join(
+ root,
+ "profile-src",
+ profile.sourceArchiveName ?? profile.archiveName,
+ );
const profileRoot = join(temporary, profile.profileDirectory);
const archive = join(temporary, `${profile.archiveName}.streamDeckProfile`);
const output = join(outputRoot, `${profile.archiveName}.streamDeckProfile`);
- await cp(source, profileRoot, { recursive: true });
+ if (profile.shared) {
+ await writeMasterProfile(
+ profileRoot,
+ profile,
+ JSON.parse(
+ await readFile(
+ join(root, "profile-src/profile-contract.json"),
+ "utf8",
+ ),
+ ),
+ join(root, "assets/profile-navigation"),
+ );
+ } else await cp(source, profileRoot, { recursive: true });
const entries = [
`${profile.profileDirectory}/`,
...(await archiveEntries(profileRoot)).map(
diff --git a/scripts/generate-lucide-paths.mjs b/scripts/generate-lucide-paths.mjs
index ab46380..b8be7fd 100644
--- a/scripts/generate-lucide-paths.mjs
+++ b/scripts/generate-lucide-paths.mjs
@@ -61,6 +61,7 @@ const icons = {
bolt: "zap",
enter: "corner-down-left",
"cloud-upload": "cloud-upload",
+ shield: "shield",
yolo: "shield-alert",
yeet: "rocket",
voice: "mic",
diff --git a/scripts/generate-marketplace-media.mjs b/scripts/generate-marketplace-media.mjs
index 1ed217b..22303d9 100644
--- a/scripts/generate-marketplace-media.mjs
+++ b/scripts/generate-marketplace-media.mjs
@@ -19,6 +19,7 @@ const sources = {
allPages: resolve(visualQaRoot, "all-pages.png"),
};
await ensureVisualQa();
+run(process.execPath, ["scripts/render-master-profiles.mjs"]);
await mkdir(outputRoot, { recursive: true });
await Promise.all([
@@ -57,10 +58,10 @@ async function makeThumbnail() {
await canvas(
destination,
[
- text("CODEX COMPANION", 108, 86, 42, "#9CD5FE"),
+ text("CODEX + CLAUDE", 108, 86, 42, "#9CD5FE"),
text("FOR STREAM DECK", 108, 136, 84, "#F7F9FC"),
text(
- "Live chat status · focused controls · local by design",
+ "Codex + Claude Code controls · one plugin",
112,
238,
30,
@@ -98,7 +99,7 @@ async function makeLiveStatusGallery() {
await canvas(
resolve(outputRoot, "gallery-01-live-status.png"),
[
- eyebrow("LIVE CHAT STATUS"),
+ eyebrow("CODEX LIVE CHAT STATUS"),
...heading("SEE RECENT CHATS", "AT A GLANCE"),
body("Status, focus, unread work,", 126, 328),
body("and input needs stay visible", 126, 366),
@@ -115,7 +116,7 @@ async function makeControlsGallery() {
await canvas(
resolve(outputRoot, "gallery-02-controls.png"),
[
- eyebrow("FOCUSED CONTROLS"),
+ eyebrow("CODEX CONTROLS · CLAUDE PREVIEW"),
...heading("KEEP WORK", "MOVING"),
body("Plan, permissions, push-to-talk,", 126, 328),
body("usage, and context are available", 126, 366),
@@ -132,13 +133,13 @@ async function makeWorkflowGallery() {
await canvas(
resolve(outputRoot, "gallery-03-workflows.png"),
[
- eyebrow("BUILT-IN WORKFLOWS"),
+ eyebrow("CODEX WORKFLOWS"),
...heading("YOUR ROUTINE,", "ON KEYS"),
body("Git and delivery, code quality,", 126, 328),
body("decisions, workspace work, and", 126, 366),
body("Codex panels have ready-made pages.", 126, 404),
rule(126, 492, 390, "#FFD166"),
- caption("MODEL-SPECIFIC PROFILES", 126, 542, "#FFD166"),
+ caption("DEVICE-SPECIFIC PROFILES", 126, 542, "#FFD166"),
body("Each key uses the project's original generated artwork.", 126, 582),
],
[
@@ -153,20 +154,36 @@ async function makeCompatibilityGallery() {
await canvas(
resolve(outputRoot, "gallery-04-key-actions.png"),
[
- eyebrow("KEYPAD ACTIONS"),
+ eyebrow("CODEX + CLAUDE MASTER PROFILES"),
...heading("BUILT FOR", "BUTTONS"),
body("Included layouts fit Stream Deck,", 126, 328),
- body("Mini, Neo, and XL without dropping", 126, 366),
- body("actions or adding fake dial controls.", 126, 404),
+ body("Mini, Neo, and XL with on-key", 126, 366),
+ body("page navigation and clear app colors.", 126, 404),
rule(126, 492, 390, "#7EE787"),
caption("STREAM DECK + ADDS DIALS", 126, 542, "#7EE787"),
- body("Agent, Action, Model, and Reasoning are optional dials.", 126, 582),
+ body("Workflows, Actions, Model, and Effort on Plus.", 126, 582),
+ ],
+ [
+ layer(
+ resolve(".cache/master-profile-visuals/plus-overview.png"),
+ 900,
+ 148,
+ 780,
+ ),
],
- [layer(sources.allPages, 1040, 148, 540)],
);
}
async function canvas(destination, labels, layers) {
+ labels.push(
+ text(
+ "LOCAL · SSH · CLOUD — CAPABILITIES VARY BY SURFACE",
+ 126,
+ 918,
+ 20,
+ "#E7A589",
+ ),
+ );
const labelArguments = labels.flatMap((item) => [
"-font",
font,
diff --git a/scripts/lib/master-profile.mjs b/scripts/lib/master-profile.mjs
new file mode 100644
index 0000000..25bca2e
--- /dev/null
+++ b/scripts/lib/master-profile.mjs
@@ -0,0 +1,171 @@
+import { mkdir, writeFile, readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { sharedId } from "./shared-profile.mjs";
+
+const prefix = "com.todd.streamdeckcodex.";
+const id = (value) => sharedId(`master-v2:${value}`);
+const command = (commandId, name) => ({
+ name,
+ uuid: prefix + "command",
+ settings: { commandId },
+});
+export function masterGroups(contract) {
+ const controls = [
+ ...["Codex Left", "Claude Left", "Codex Context", "Claude Context"].map(
+ (name) => ({
+ name,
+ uuid:
+ prefix +
+ name.toLowerCase().replaceAll(" ", "-").replace("-left", "-weekly"),
+ settings: {},
+ }),
+ ),
+ command("dictate", "PTT"),
+ command("send", "Send"),
+ command("fast", "Fast"),
+ { name: "Permissions", uuid: prefix + "approval-mode", settings: {} },
+ ];
+ // The dedicated quota action is named Left, but its stable ID predates that label.
+ controls[0].uuid = prefix + "codex-weekly";
+ controls[1].uuid = prefix + "claude-weekly";
+ const workspace = [
+ command("new-chat", "New chat"),
+ command("plan", "Plan"),
+ command("compact", "Compact"),
+ command("skills", "Skills"),
+ command("settings", "Settings"),
+ command("review-panel", "Review"),
+ command("browser", "Browser"),
+ command("files", "Files"),
+ command("side-chat", "Side chat"),
+ command("sidebar", "Sidebar"),
+ ];
+ const workflows = contract.pages.flatMap((page) =>
+ page.keys.filter((key) =>
+ String(key.settings.action ?? "").startsWith("workflow:"),
+ ),
+ );
+ return [
+ { name: "Live controls", keys: controls },
+ { name: "Workspace", keys: workspace },
+ { name: "Workflows", keys: workflows },
+ ];
+}
+export async function writeMasterProfile(root, device, contract, assetsRoot) {
+ const capacity = device.columns * device.rows;
+ // Every device can navigate from its own keys, including Mini (no swipe surface).
+ const contentCapacity = capacity - 2;
+ const groups = masterGroups(contract);
+ const pages = groups.flatMap((group) =>
+ Array.from(
+ { length: Math.ceil(group.keys.length / contentCapacity) },
+ (_, i) => ({
+ id: id(`${device.slug}:${group.name}:${i}`),
+ name: `${group.name}${group.keys.length > contentCapacity ? ` ${i + 1}` : ""}`,
+ keys: group.keys.slice(i * contentCapacity, (i + 1) * contentCapacity),
+ }),
+ ),
+ );
+ const defaultId = id(`${device.slug}:default`);
+ const name = `Codex + Claude Master — ${device.name}`;
+ const json = async (path, value) => {
+ await mkdir(join(path, ".."), { recursive: true });
+ await writeFile(path, JSON.stringify(value, null, 2) + "\n");
+ };
+ await json(join(root, "manifest.json"), {
+ Device: { Model: device.model, UUID: "" },
+ InstalledByPluginUUID: "com.todd.streamdeckcodex",
+ Name: name,
+ PreconfiguredName: name,
+ Version: "3.0",
+ Pages: {
+ Current: pages[0].id,
+ Default: defaultId,
+ Pages: pages.map((p) => p.id),
+ },
+ });
+ await json(join(root, "Profiles", defaultId, "manifest.json"), {
+ Controllers: [{ Type: "Keypad", Actions: null }],
+ Name: "",
+ Icon: "",
+ });
+ function action(key, identity) {
+ return {
+ ActionID: id(identity),
+ LinkedTitle: false,
+ Name: key.name,
+ Resources: null,
+ Settings: { ...key.settings, provider: "auto" },
+ State: 0,
+ States: [{ Image: "", TitleAlignment: "bottom" }],
+ UUID: key.uuid,
+ };
+ }
+ for (const page of pages) {
+ const actions = Object.fromEntries(
+ page.keys.map((key, index) => [
+ `${index % device.columns},${Math.floor(index / device.columns)}`,
+ action(key, `${device.slug}:${page.id}:${index}`),
+ ]),
+ );
+ const pageRoot = join(root, "Profiles", page.id);
+ await mkdir(join(pageRoot, "Images"), { recursive: true });
+ for (const [offset, direction] of [
+ [2, "previous"],
+ [1, "next"],
+ ]) {
+ const index = capacity - offset;
+ const image = `${direction}.png`;
+ await writeFile(
+ join(pageRoot, "Images", image),
+ await readFile(join(assetsRoot, image)),
+ );
+ actions[
+ `${index % device.columns},${Math.floor(index / device.columns)}`
+ ] = {
+ ActionID: id(`${device.slug}:${page.id}:${direction}`),
+ LinkedTitle: false,
+ Name: direction === "next" ? "Next Page" : "Previous Page",
+ Plugin: {
+ Name: "Pages",
+ UUID: "com.elgato.streamdeck.page",
+ Version: "1.0",
+ },
+ Resources: null,
+ Settings: {},
+ State: 0,
+ States: [{ Image: `Images/${image}` }],
+ UUID: `com.elgato.streamdeck.page.${direction}`,
+ };
+ }
+ const controllers = [{ Type: "Keypad", Actions: actions }];
+ if (device.slug === "plus")
+ controllers.push({
+ Type: "Encoder",
+ Actions: Object.fromEntries(
+ [
+ {
+ name: "Workflows",
+ uuid: prefix + "workflow",
+ settings: { workflowId: "pr-review" },
+ },
+ {
+ name: "Actions",
+ uuid: prefix + "command",
+ settings: { commandId: "fast" },
+ },
+ { name: "Model", uuid: prefix + "model", settings: {} },
+ { name: "Effort", uuid: prefix + "reasoning", settings: {} },
+ ].map((key, index) => [
+ `${index},0`,
+ action(key, `${device.slug}:${page.id}:encoder:${index}`),
+ ]),
+ ),
+ });
+ await json(join(pageRoot, "manifest.json"), {
+ Controllers: controllers,
+ Name: page.name,
+ Icon: "",
+ });
+ }
+}
diff --git a/scripts/lib/shared-profile.mjs b/scripts/lib/shared-profile.mjs
new file mode 100644
index 0000000..81d7218
--- /dev/null
+++ b/scripts/lib/shared-profile.mjs
@@ -0,0 +1,47 @@
+import { createHash } from "node:crypto";
+
+/** Stable distinct IDs let shared and legacy profiles coexist on the same deck. */
+export function sharedId(value) {
+ const hex = createHash("sha256")
+ .update(`streamdeck-shared-v1:${value}`)
+ .digest("hex")
+ .slice(0, 32);
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20)}`.toUpperCase();
+}
+export function sharedProfileName(name) {
+ return name.replace(/^streamdeckcodex-/, "streamdeckai-");
+}
+export function sharedProfileDocument(value) {
+ if (Array.isArray(value)) return value.map(sharedProfileDocument);
+ if (value && typeof value === "object") {
+ const result = Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ sharedProfileDocument(item),
+ ]),
+ );
+ if (
+ typeof result.UUID === "string" &&
+ result.UUID.startsWith("com.todd.streamdeckcodex.")
+ ) {
+ result.Settings = { ...(result.Settings ?? {}), provider: "auto" };
+ }
+ if (
+ typeof result.Name === "string" &&
+ result.Name.includes("Codex Companion")
+ )
+ result.Name = result.Name.replace("Codex Companion", "Codex + Claude");
+ if (typeof result.PreconfiguredName === "string")
+ result.PreconfiguredName = result.PreconfiguredName.replace(
+ "Codex Companion",
+ "Codex + Claude",
+ );
+ return result;
+ }
+ if (
+ typeof value === "string" &&
+ /^[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}$/i.test(value)
+ )
+ return sharedId(value);
+ return value;
+}
diff --git a/scripts/lib/streamdeck-action-harness.mjs b/scripts/lib/streamdeck-action-harness.mjs
index 1072312..cbc6884 100644
--- a/scripts/lib/streamdeck-action-harness.mjs
+++ b/scripts/lib/streamdeck-action-harness.mjs
@@ -128,15 +128,35 @@ export async function createStreamDeckActionHarness({
let socket;
const outbound = [];
+ const actionState = new Map();
server.on("connection", (connected) => {
socket = connected;
connected.on("message", (data) => {
const message = JSON.parse(data.toString());
outbound.push(message);
+ if (message.event === "setSettings") {
+ const state = actionState.get(message.context);
+ if (state) state.payload.settings = message.payload;
+ }
+ if (message.event === "getSettings") {
+ const state = actionState.get(message.context);
+ if (state)
+ connected.send(
+ JSON.stringify({
+ action: state.action,
+ context: message.context,
+ device: state.device,
+ event: "didReceiveSettings",
+ id: message.id,
+ payload: { ...state.payload },
+ }),
+ );
+ }
if (message.event === "getGlobalSettings") {
connected.send(
JSON.stringify({
event: "didReceiveGlobalSettings",
+ id: message.id,
payload: {
settings: { profileActivationVersion: "profile-v1" },
},
@@ -238,6 +258,17 @@ export async function createStreamDeckActionHarness({
outbound,
output: () => output,
send(message) {
+ if (["willAppear", "didReceiveSettings"].includes(message.event)) {
+ actionState.set(message.context, structuredClone(message));
+ } else if (message.payload && actionState.has(message.context)) {
+ message = {
+ ...message,
+ payload: {
+ ...message.payload,
+ settings: actionState.get(message.context).payload.settings,
+ },
+ };
+ }
socket.send(JSON.stringify(message));
},
waitFor,
diff --git a/scripts/qa-claude-commands.mjs b/scripts/qa-claude-commands.mjs
new file mode 100644
index 0000000..a31375b
--- /dev/null
+++ b/scripts/qa-claude-commands.mjs
@@ -0,0 +1,281 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import {
+ createStreamDeckActionHarness,
+ delay,
+ waitFor,
+} from "./lib/streamdeck-action-harness.mjs";
+const helper = resolve(
+ "com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control",
+);
+const directory = resolve(".cache/control-audit");
+mkdirSync(directory, { recursive: true });
+const trace = resolve(directory, "claude-command-completion.jsonl");
+writeFileSync(trace, "");
+function native(op, request) {
+ const r = spawnSync(
+ helper,
+ [
+ op,
+ ...(request
+ ? [Buffer.from(JSON.stringify(request)).toString("base64")]
+ : []),
+ ],
+ { encoding: "utf8", timeout: 20000 },
+ );
+ const result = JSON.parse(r.stdout || "{}");
+ assert(result.ok, result.message);
+ return result.providerState;
+}
+function ui(op, argument) {
+ const r = spawnSync(
+ "node",
+ [
+ "/private/tmp/audit-ui.cjs",
+ "claude",
+ op,
+ ...(argument ? [argument] : []),
+ ],
+ { encoding: "utf8", timeout: 20000 },
+ );
+ assert.equal(r.status, 0, r.stderr);
+ return JSON.parse(readFileSync("/private/tmp/audit-claude-ui.json", "utf8"))
+ .data.ui_elements;
+}
+function setDraft(value) {
+ const r = spawnSync(
+ "/private/tmp/audit-set-composer",
+ ["com.anthropic.claudefordesktop", value],
+ { encoding: "utf8" },
+ );
+ assert.equal(r.status, 0);
+ assert.equal(r.stdout.trim(), "0");
+}
+ui("activate");
+const initial = native("provider-read");
+assert(
+ initial.sessions?.[0]?.title.toLowerCase().includes("audit"),
+ "Open an isolated audit session first",
+);
+assert(
+ initial.draftEmpty && !initial.recording,
+ "QA needs an empty, idle composer",
+);
+const h = await createStreamDeckActionHarness({
+ plugin: resolve("com.todd.streamdeckcodex.sdPlugin/bin/plugin.js"),
+ pluginContext: "qa-claude-commands",
+ env: {
+ CODEX_UI_CONTROL: resolve("scripts/qa-native-completion.mjs"),
+ QA_NATIVE_REAL: helper,
+ QA_NATIVE_LOG: trace,
+ },
+});
+let sequence = 0;
+function completions() {
+ return readFileSync(trace, "utf8")
+ .trim()
+ .split("\n")
+ .filter(Boolean)
+ .map((s) => JSON.parse(s));
+}
+async function key(
+ command,
+ kind = "command",
+ settings = {},
+ controller = "Keypad",
+) {
+ const context = `claude-command-${sequence++}`;
+ const payload = {
+ controller,
+ coordinates: { column: 0, row: 0 },
+ isInMultiAction: false,
+ settings: { provider: "claude", commandId: command, ...settings },
+ };
+ const send = (event) =>
+ h.send({
+ event,
+ action: `com.todd.streamdeckcodex.${kind}`,
+ context,
+ device: "qa-stream-deck-plus",
+ payload,
+ });
+ send("willAppear");
+ await waitFor(
+ () =>
+ h.outbound.some(
+ (m) =>
+ m.context === context &&
+ m.event === (controller === "Encoder" ? "setFeedback" : "setImage"),
+ ),
+ 20000,
+ );
+ const before = completions().length;
+ const events = h.outbound.length;
+ send(controller === "Encoder" ? "dialUp" : "keyDown");
+ if (command !== "dictate" && controller === "Keypad") send("keyUp");
+ const result = await waitFor(
+ () =>
+ completions()
+ .slice(before)
+ .find(
+ (x) =>
+ x.operation ===
+ (["workflow", "keycap"].includes(kind) ? "workflow" : command),
+ ),
+ command === "send" ? 35000 : 20000,
+ command,
+ );
+ assert(result.result.ok, JSON.stringify(result.result));
+ await delay(200);
+ assert(
+ !h.outbound
+ .slice(events)
+ .some((m) => m.context === context && m.event === "showAlert"),
+ `${command} showed a warning`,
+ );
+ return { result: result.result.providerState, send, context };
+}
+try {
+ const fixtureFlag = process.argv.indexOf("--workflows-file");
+ if (fixtureFlag >= 0) {
+ const cases = JSON.parse(
+ readFileSync(process.argv[fixtureFlag + 1], "utf8"),
+ );
+ for (const test of cases) {
+ const before = native("provider-read");
+ assert(before.draftEmpty);
+ const row = await key(
+ "workflow",
+ test.kind,
+ test.settings,
+ test.controller,
+ );
+ const elements = ui("read");
+ const composer = elements.filter((e) => e.ax_role === "AXTextArea");
+ assert.equal(composer.length, 1);
+ assert.equal(composer[0].value.trim(), test.prompt.trim());
+ assert.equal(row.result.target.environment, before.target.environment);
+ assert(row.result.target.sessionId.startsWith("draft:"));
+ assert(!h.outbound.some((m) => m.event === "showAlert"));
+ setDraft("");
+ ui("click", "Back");
+ row.send("willDisappear");
+ assert.deepEqual(native("provider-read").target, before.target);
+ console.log(
+ JSON.stringify({
+ workflow: test.id,
+ kind: test.kind,
+ controller: test.controller,
+ passed: true,
+ exactDraft: true,
+ submitted: false,
+ }),
+ );
+ }
+ }
+ for (const spec of fixtureFlag >= 0 ? [] : process.argv.slice(2)) {
+ const [requested, workflowId = "tests"] = spec.split(":");
+ const command = requested.startsWith("ptt-")
+ ? "dictate"
+ : requested === "new-send"
+ ? "new-chat"
+ : requested;
+ const before = native("provider-read");
+ if (command === "send")
+ setDraft("Reply only QA READY. Do not use tools or modify files.");
+ const row = await key(
+ command,
+ command === "workflow" ? "workflow" : "command",
+ command === "workflow" ? { workflowId } : {},
+ );
+ let elements = ui("read");
+ if (command === "files") {
+ assert(elements.some((e) => /Files|file tree/i.test(e.label)));
+ await key("files");
+ }
+ if (command === "settings" || command === "skills") {
+ assert(elements.some((e) => e.label === "Close"));
+ ui("click", "Close");
+ }
+ if (command === "side-chat") {
+ assert.equal(
+ elements.filter((e) => e.ax_role === "AXTextArea").length,
+ 2,
+ );
+ ui("press", "cmd+backslash");
+ }
+ if (command === "workflow") {
+ assert.equal(row.result.draftEmpty, false);
+ assert(row.result.target.sessionId.startsWith("draft:"));
+ setDraft("");
+ ui("click", "Back");
+ }
+ if (command === "new-chat") {
+ assert(row.result.target.sessionId.startsWith("draft:"));
+ assert(row.result.draftEmpty);
+ if (requested === "new-send") {
+ const prompt =
+ "Stream Deck draft audit. Reply only QA READY. Do not use tools, edit files, commit, or push.";
+ setDraft(prompt);
+ const sent = await key("send");
+ assert(sent.result.draftEmpty);
+ assert.equal(sent.result.target.environment, before.target.environment);
+ assert(!sent.result.target.sessionId.startsWith("draft:"));
+ assert(ui("read").some((e) => e.label === prompt));
+ sent.send("willDisappear");
+ }
+ ui("click", "Back");
+ }
+ if (command === "send") {
+ assert(row.result.draftEmpty);
+ assert(
+ elements.some(
+ (e) =>
+ e.label ===
+ "Reply only QA READY. Do not use tools or modify files.",
+ ),
+ );
+ }
+ if (command === "dictate") {
+ assert.equal(row.result.recording, true);
+ spawnSync("osascript", [
+ "-e",
+ 'tell application id "com.openai.codex" to activate',
+ ]);
+ const start = completions().length;
+ if (requested === "ptt-interrupt") await h.close();
+ else if (requested === "ptt-timeout") await delay(2500);
+ else row.send("keyUp");
+ const stopped = await waitFor(
+ () =>
+ completions()
+ .slice(requested === "ptt-timeout" ? 0 : start)
+ .find((x) => x.operation === "dictation-stop"),
+ 20000,
+ );
+ assert(stopped.result.ok, JSON.stringify(stopped));
+ assert.equal(stopped.result.providerState.recording, false);
+ ui("activate");
+ }
+ row.send("willDisappear");
+ console.log(
+ JSON.stringify({ command: requested, passed: true, independentUI: true }),
+ );
+ if (!["compact", "send"].includes(command))
+ assert.deepEqual(native("provider-read").target, before.target);
+ }
+} catch (error) {
+ writeFileSync(
+ trace + ".sdk.json",
+ JSON.stringify({ outbound: h.outbound, output: h.output() }, null, 2),
+ );
+ throw error;
+} finally {
+ await h.close();
+ ui("activate");
+ const current = native("provider-read");
+ if (current.recording)
+ native("claude", { operation: "dictation-stop", target: current.target });
+}
diff --git a/scripts/qa-claude-controls.mjs b/scripts/qa-claude-controls.mjs
new file mode 100644
index 0000000..e327eb9
--- /dev/null
+++ b/scripts/qa-claude-controls.mjs
@@ -0,0 +1,175 @@
+import { spawnSync } from "node:child_process";
+import assert from "node:assert/strict";
+import { resolve } from "node:path";
+import { nativeHelperPath } from "./lib/native-helper-path.mjs";
+
+// Development acceptance only. No session identifiers, drafts, or paths are printed.
+const args = process.argv.slice(2);
+const environment = args
+ .find((a) => a.startsWith("--environment="))
+ ?.split("=")[1];
+if (!["local", "ssh", "cloud"].includes(environment)) {
+ throw new Error(
+ "Specify --environment=local, --environment=ssh, or --environment=cloud.",
+ );
+}
+const exercise = args.includes("--exercise");
+const helper = nativeHelperPath(resolve("."));
+const env = {
+ ...process.env,
+ STREAMDECK_CLAUDE_ACCEPTANCE_ENVIRONMENT: environment,
+};
+function activate() {
+ if (!args.includes("--activate")) return;
+ const activation = spawnSync(
+ "osascript",
+ ["-e", 'tell application "Claude" to activate'],
+ { encoding: "utf8", timeout: 5000 },
+ );
+ assert.equal(activation.status, 0, "Claude activation failed");
+}
+function invoke(action, payload) {
+ // Explicit live QA may bring Claude forward; production adapters never do.
+ // Reassert before each transaction, since inspecting test output can focus Codex.
+ activate();
+ const callArgs = [action];
+ if (payload)
+ callArgs.push(Buffer.from(JSON.stringify(payload)).toString("base64"));
+ const result = spawnSync(helper, callArgs, {
+ env,
+ encoding: "utf8",
+ timeout: 15000,
+ maxBuffer: 256 * 1024,
+ });
+ assert.equal(result.error, undefined, "Native helper did not finish");
+ const reply = JSON.parse(result.stdout || "{}");
+ if (!reply.ok) throw new Error(reply.message || "Native request failed");
+ return reply.providerState;
+}
+let initial;
+const deadline = Date.now() + 8000;
+do {
+ initial = invoke("provider-read");
+ if (initial.target?.environment === environment) break;
+ if (Date.now() < deadline)
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
+} while (Date.now() < deadline);
+assert.equal(
+ initial.target?.environment,
+ environment,
+ `Select the expected Code environment first (${initial.reason ?? initial.foreground ?? "unobserved"})`,
+);
+const target = initial.target;
+function read() {
+ const result = invoke("provider-read");
+ assert.deepEqual(
+ result.target,
+ target,
+ "Target changed; refusing restoration in another session",
+ );
+ return result;
+}
+function perform(operation, value) {
+ const result = invoke("claude", {
+ operation,
+ target,
+ ...(value === undefined ? {} : { value }),
+ });
+ assert.deepEqual(result.target, target);
+ console.log(JSON.stringify({ environment, operation, passed: true }));
+ return result;
+}
+const models = perform("model-options").options;
+const efforts = perform("reasoning-options").options;
+assert.ok(models?.length && efforts?.length, "Pickers exposed no choices");
+for (const [field, replacement] of Object.entries({
+ windowId: "different-window",
+ sessionId: "local_11111111-2222-4333-a444-555555555555",
+ environment: environment === "local" ? "ssh" : "local",
+ provider: "codex",
+})) {
+ assert.throws(
+ () =>
+ invoke("claude", {
+ operation: "model",
+ target: { ...target, [field]: replacement },
+ value: initial.model,
+ }),
+ /Target changed/,
+ );
+ assert.equal(read().model, initial.model);
+ console.log(
+ JSON.stringify({ environment, rejectsChanged: field, passed: true }),
+ );
+}
+if (exercise) {
+ const alternate = models.find((o) => o.value !== initial.model);
+ if (alternate) {
+ try {
+ assert.equal(perform("model", alternate.value).model, alternate.value);
+ const beforeFast = read();
+ if (beforeFast.capabilities?.includes("fast")) {
+ try {
+ assert.equal(perform("fast").fast, !beforeFast.fast);
+ } finally {
+ if (read().fast !== beforeFast.fast) perform("fast");
+ }
+ }
+ } finally {
+ if (read().model !== initial.model) perform("model", initial.model);
+ }
+ }
+ const originalEffort = efforts.find(
+ (o) => o.value === initial.effort || o.label === initial.effort,
+ );
+ assert.ok(originalEffort, "Current effort is not in the offered options");
+ const alternativeEffort = efforts.find(
+ (o) => o.value !== originalEffort.value,
+ );
+ if (alternativeEffort) {
+ try {
+ perform("reasoning", alternativeEffort.value);
+ } finally {
+ perform("reasoning", originalEffort.value);
+ }
+ assert.equal(read().effort, initial.effort);
+ }
+ if (!["Plan", "Plan mode"].includes(initial.permission)) {
+ try {
+ assert.ok(["Plan", "Plan mode"].includes(perform("plan").permission));
+ } finally {
+ if (["Plan", "Plan mode"].includes(read().permission))
+ perform("plan", initial.permission);
+ }
+ assert.equal(read().permission, initial.permission);
+ let returned = false;
+ for (let i = 0; i < 8; i++) {
+ if (perform("permission-cycle").permission === initial.permission) {
+ returned = true;
+ break;
+ }
+ }
+ assert.ok(returned, "Permission cycle did not return to its initial mode");
+ }
+ for (const operation of ["sidebar", "review-panel", "browser"]) {
+ if (!read().capabilities?.includes(operation)) continue;
+ perform(operation);
+ perform(operation);
+ }
+}
+const final = read();
+assert.equal(final.model, initial.model);
+assert.equal(final.effort, initial.effort);
+assert.equal(final.permission, initial.permission);
+assert.equal(final.fast, initial.fast);
+assert.equal(final.ultracode, initial.ultracode);
+console.log(
+ JSON.stringify({
+ environment,
+ passed: true,
+ exercised: exercise,
+ weeklyObserved: final.weeklyUsedPercent !== undefined,
+ usagePeriod: final.usagePeriod ?? "unavailable",
+ contextObserved: final.contextUsedPercent !== undefined,
+ }),
+);
diff --git a/scripts/qa-claude-dials.mjs b/scripts/qa-claude-dials.mjs
new file mode 100644
index 0000000..5fb0746
--- /dev/null
+++ b/scripts/qa-claude-dials.mjs
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
+import { resolve } from "node:path";
+import {
+ createStreamDeckActionHarness,
+ waitFor,
+ delay,
+} from "./lib/streamdeck-action-harness.mjs";
+const helper = resolve(
+ "com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control",
+);
+const trace = resolve(".cache/control-audit/claude-dial-completion.jsonl");
+mkdirSync(resolve(".cache/control-audit"), { recursive: true });
+writeFileSync(trace, "");
+const read = () =>
+ JSON.parse(spawnSync(helper, ["provider-read"], { encoding: "utf8" }).stdout)
+ .providerState;
+spawnSync("osascript", [
+ "-e",
+ 'tell application id "com.anthropic.claudefordesktop" to activate',
+]);
+const initial = read();
+assert(initial.sessions?.[0]?.title.toLowerCase().includes("audit"));
+assert(initial.draftEmpty);
+const h = await createStreamDeckActionHarness({
+ plugin: resolve("com.todd.streamdeckcodex.sdPlugin/bin/plugin.js"),
+ pluginContext: "qa-claude-dials",
+ env: {
+ CODEX_UI_CONTROL: resolve("scripts/qa-native-completion.mjs"),
+ QA_NATIVE_REAL: helper,
+ QA_NATIVE_LOG: trace,
+ },
+});
+const completions = () =>
+ readFileSync(trace, "utf8")
+ .trim()
+ .split("\n")
+ .filter(Boolean)
+ .map((s) => JSON.parse(s));
+try {
+ for (const kind of ["model", "reasoning"]) {
+ const context = "qa-claude-" + kind;
+ const send = (event, extra = {}) =>
+ h.send({
+ event,
+ context,
+ action: "com.todd.streamdeckcodex." + kind,
+ device: "qa-stream-deck-plus",
+ payload: {
+ controller: "Encoder",
+ coordinates: { column: kind === "model" ? 2 : 3, row: 0 },
+ settings: { provider: "auto" },
+ ...extra,
+ },
+ });
+ send("willAppear");
+ await waitFor(
+ () =>
+ h.outbound.some(
+ (m) => m.context === context && m.event === "setFeedback",
+ ),
+ 15000,
+ );
+ for (const ticks of [1, -1]) {
+ const marker = h.outbound.length;
+ send("dialRotate", { ticks, pressed: false });
+ await waitFor(
+ () =>
+ h.outbound
+ .slice(marker)
+ .some(
+ (m) =>
+ m.context === context &&
+ m.event === "setFeedback" &&
+ m.payload?.indicator?.bar_fill_c === "#F4B740",
+ ),
+ 15000,
+ "dial preview",
+ );
+ const count = completions().length;
+ send("dialDown");
+ send("dialUp");
+ const applied = await waitFor(
+ () =>
+ completions()
+ .slice(count)
+ .find((r) => r.operation === kind),
+ 20000,
+ "dial apply",
+ );
+ assert(applied.result.ok, JSON.stringify(applied));
+ await delay(250);
+ const actual = read();
+ assert.deepEqual(actual.target, initial.target);
+ assert.equal(
+ actual[kind === "model" ? "model" : "effort"],
+ applied.result.providerState[kind === "model" ? "model" : "effort"],
+ );
+ assert(!h.outbound.some((m) => m.event === "showAlert"));
+ }
+ assert.equal(
+ read()[kind === "model" ? "model" : "effort"],
+ initial[kind === "model" ? "model" : "effort"],
+ );
+ send("willDisappear");
+ console.log(
+ JSON.stringify({
+ environment: initial.target.environment,
+ kind,
+ previewCommitRestore: true,
+ passed: true,
+ }),
+ );
+ }
+} finally {
+ await h.close();
+}
diff --git a/scripts/qa-claude-preflight.mjs b/scripts/qa-claude-preflight.mjs
new file mode 100644
index 0000000..3708faf
--- /dev/null
+++ b/scripts/qa-claude-preflight.mjs
@@ -0,0 +1,36 @@
+import { spawnSync } from "node:child_process";
+import { nativeHelperPath } from "./lib/native-helper-path.mjs";
+import { resolve } from "node:path";
+
+// Requires desktop process access; a sandbox can hide the foreground app.
+// Read-only, bounded and public-safe: do not print session IDs, titles or paths.
+const result = spawnSync(nativeHelperPath(resolve(".")), ["provider-read"], {
+ encoding: "utf8",
+ timeout: 10000,
+ maxBuffer: 256 * 1024,
+});
+let state;
+try {
+ state = JSON.parse(result.stdout || "{}").providerState;
+} catch {
+ /* reported below */
+}
+const ready =
+ result.status === 0 && state?.foreground === "claude" && !!state.target;
+console.log(
+ JSON.stringify(
+ {
+ foreground: state?.foreground ?? "unobserved",
+ exactCodeTarget: !!state?.target,
+ environment: state?.target?.environment ?? "unavailable",
+ modelExposed: !!state?.model,
+ effortExposed: !!state?.effort,
+ permissionsExposed: !!state?.permission,
+ capabilities: state?.capabilities ?? [],
+ reason: state?.reason ?? (ready ? "observed" : "unavailable"),
+ },
+ null,
+ 2,
+ ),
+);
+process.exitCode = ready ? 0 : 1;
diff --git a/scripts/qa-claude-project.mjs b/scripts/qa-claude-project.mjs
new file mode 100644
index 0000000..c45193f
--- /dev/null
+++ b/scripts/qa-claude-project.mjs
@@ -0,0 +1,166 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { resolve } from "node:path";
+import {
+ createStreamDeckActionHarness,
+ delay,
+ waitFor,
+} from "./lib/streamdeck-action-harness.mjs";
+const helper = resolve(
+ "com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control",
+);
+function native(action, request) {
+ const result = spawnSync(
+ helper,
+ [
+ action,
+ ...(request
+ ? [Buffer.from(JSON.stringify(request)).toString("base64")]
+ : []),
+ ],
+ { encoding: "utf8", timeout: 20000 },
+ );
+ const reply = JSON.parse(result.stdout);
+ if (!reply.ok) throw Error(reply.message);
+ return reply.providerState;
+}
+const original = native("provider-read");
+assert(
+ original.readOnlyScope && original.target && original.model,
+ "Select the observed Claude Code Project first",
+);
+const options = native("claude", {
+ operation: "model-options",
+ target: original.target,
+}).options;
+assert(options.length >= 2);
+const wrong = spawnSync(
+ helper,
+ [
+ "claude",
+ Buffer.from(
+ JSON.stringify({
+ operation: "model",
+ target: {
+ ...original.target,
+ sessionId: "chan_000000000000000000000000",
+ },
+ value: options[1].value,
+ }),
+ ).toString("base64"),
+ ],
+ { encoding: "utf8", timeout: 20000 },
+);
+assert.equal(
+ JSON.parse(wrong.stdout).ok,
+ false,
+ "Wrong project must be rejected",
+);
+const harness = await createStreamDeckActionHarness({
+ plugin: resolve("com.todd.streamdeckcodex.sdPlugin/bin/plugin.js"),
+ pluginContext: "qa-claude-project",
+});
+function event(kind, name, ticks = 0) {
+ return {
+ event: name,
+ action: `com.todd.streamdeckcodex.${kind}`,
+ context: `project-${kind}`,
+ device: "qa-stream-deck-plus",
+ payload: {
+ controller: kind === "claude-context" ? "Keypad" : "Encoder",
+ coordinates: { column: kind === "model" ? 2 : 3, row: 0 },
+ settings: { provider: "claude" },
+ isInMultiAction: false,
+ ticks,
+ },
+ };
+}
+const feedback = (kind) =>
+ harness.outbound.findLast(
+ (m) => m.context === `project-${kind}` && m.event === "setFeedback",
+ )?.payload;
+try {
+ for (const kind of ["model", "reasoning", "claude-context"])
+ harness.send(event(kind, "willAppear"));
+ await waitFor(
+ () => feedback("reasoning")?.value === "Fixed",
+ 15000,
+ "Fixed effort display",
+ );
+ await waitFor(
+ () =>
+ harness.outbound.some(
+ (m) =>
+ m.context === "project-claude-context" &&
+ m.event === "setImage" &&
+ Buffer.from(m.payload.image.split(",")[1], "base64")
+ .toString()
+ .includes(">AUTO"),
+ ),
+ 15000,
+ "automatic compaction display",
+ );
+ harness.send(event("reasoning", "dialRotate", 1));
+ harness.send(event("reasoning", "dialDown"));
+ harness.send(event("reasoning", "dialUp"));
+ await delay(2500);
+ assert.equal(feedback("reasoning")?.value, "Fixed");
+ const start = options.findIndex((o) => o.value === original.model);
+ for (let i = 1; i <= options.length; i++) {
+ const desired = options[(start + i) % options.length].value;
+ harness.send(event("model", "dialRotate", 1));
+ await waitFor(
+ () => feedback("model")?.value === desired,
+ 20000,
+ "model preview",
+ );
+ assert(feedback("model").indicator, "Missing model scale");
+ harness.send(event("model", "dialDown"));
+ harness.send(event("model", "dialUp"));
+ await waitFor(
+ () => native("provider-read").model === desired,
+ 20000,
+ "model applied",
+ );
+ await delay(500);
+ console.log(JSON.stringify({ model: desired, previewAndCommit: true }));
+ }
+ assert(
+ !harness.outbound.some((m) => m.event === "showAlert"),
+ "A dial flashed an alert",
+ );
+ assert.equal(native("provider-read").model, original.model);
+ console.log(
+ JSON.stringify({
+ context: "AUTO",
+ effort: "Fixed",
+ wrongTargetRejected: true,
+ noAlerts: true,
+ restored: true,
+ }),
+ );
+} catch (error) {
+ console.error(
+ JSON.stringify({
+ feedback: harness.outbound
+ .filter((m) => ["setFeedback", "showAlert"].includes(m.event))
+ .slice(-15),
+ output: harness.output(),
+ }),
+ );
+ throw error;
+} finally {
+ await harness.close();
+ const after = native("provider-read");
+ assert.deepEqual(
+ after.target,
+ original.target,
+ "Project changed; restoration refused",
+ );
+ if (after.model !== original.model)
+ native("claude", {
+ operation: "model",
+ target: original.target,
+ value: original.model,
+ });
+}
diff --git a/scripts/qa-dial-events.mjs b/scripts/qa-dial-events.mjs
index 1e12c05..3a91d94 100644
--- a/scripts/qa-dial-events.mjs
+++ b/scripts/qa-dial-events.mjs
@@ -299,6 +299,55 @@ try {
throw new Error("The dials did not emit verified steady-state feedback");
}
+ const commandAction = "com.todd.streamdeckcodex.command";
+ const planContext = "qa-plan-command";
+ const planSettings = { commandIndex: 1 };
+ harness.send(
+ event(commandAction, planContext, "willAppear", {
+ settings: planSettings,
+ }),
+ );
+ await waitFor(() =>
+ outbound.some(
+ (message) =>
+ message.event === "setFeedback" &&
+ message.context === planContext &&
+ message.payload?.value === "Plan",
+ ),
+ );
+ harness.send(
+ event(commandAction, planContext, "dialUp", {
+ settings: planSettings,
+ }),
+ );
+ const planFeedback = await waitFor(
+ () =>
+ outbound.findLast(
+ (message) =>
+ message.event === "setFeedback" &&
+ message.context === planContext &&
+ message.payload?.title !== "ACTION" &&
+ message.payload?.value === "Plan",
+ ),
+ 15_000,
+ "verified Action-dial Plan feedback",
+ );
+ if (planFeedback.payload?.title !== "ACTIVE") {
+ throw new Error(
+ `Action-dial Plan failed: ${JSON.stringify(planFeedback.payload)}`,
+ );
+ }
+ if (!native("mode-read", "plan", activeThreadId).active) {
+ throw new Error("Plan control did not visibly activate Plan mode");
+ }
+
+ // Restore Plan before microphone QA: ambient speech may legitimately produce
+ // a draft. Never treat a successful transcription as a broken release or
+ // silently erase it. Report whether manual QA cleanup is needed.
+ if (native("mode-read", "plan", activeThreadId).active !== initialPlan) {
+ native("mode-toggle", "plan", activeThreadId);
+ }
+
const pttContext = "qa-ptt-key";
const pttSettings = { commandId: "dictate" };
const pttEvent = (name) =>
@@ -333,61 +382,18 @@ try {
),
);
await waitFor(() => !pttGuardRunning());
- await waitFor(
+ const pttComposer = await waitFor(
() => {
try {
- return (
- native("composer-read", undefined, activeThreadId).draftEmpty === true
- );
+ const observed = native("composer-read", undefined, activeThreadId);
+ return typeof observed.draftEmpty === "boolean" ? observed : undefined;
} catch {
return undefined;
}
},
- 5_000,
- "a clean composer after PTT release",
- );
-
- const commandAction = "com.todd.streamdeckcodex.command";
- const planContext = "qa-plan-command";
- const planSettings = { commandIndex: 1 };
- harness.send(
- event(commandAction, planContext, "willAppear", {
- settings: planSettings,
- }),
- );
- await waitFor(() =>
- outbound.some(
- (message) =>
- message.event === "setFeedback" &&
- message.context === planContext &&
- message.payload?.value === "Plan",
- ),
- );
- harness.send(
- event(commandAction, planContext, "dialUp", {
- settings: planSettings,
- }),
- );
- const planFeedback = await waitFor(
- () =>
- outbound.findLast(
- (message) =>
- message.event === "setFeedback" &&
- message.context === planContext &&
- message.payload?.title !== "ACTION" &&
- message.payload?.value === "Plan",
- ),
15_000,
- "verified Action-dial Plan feedback",
+ "the composer returning after PTT release",
);
- if (planFeedback.payload?.title !== "ACTIVE") {
- throw new Error(
- `Action-dial Plan failed: ${JSON.stringify(planFeedback.payload)}`,
- );
- }
- if (!native("mode-read", "plan", activeThreadId).active) {
- throw new Error("Plan control did not visibly activate Plan mode");
- }
const finalPicker = await readPicker(activeThreadId);
process.stdout.write(
@@ -399,22 +405,29 @@ try {
modelFeedback: modelActive.payload,
reasoningFeedback: reasoningActive.payload,
pttFeedback: pttReleased.event,
+ pttDraftEmpty: pttComposer.draftEmpty,
planFeedback: planFeedback.payload,
})}\n`,
);
} catch (error) {
process.stderr.write(
`${harness.output()}\n${JSON.stringify(
- outbound.filter(
- (message) =>
- message.event === "showAlert" ||
- [
- "qa-model-dial",
- "qa-reasoning-dial",
- "qa-ptt-key",
- "qa-plan-command",
- ].includes(message.context),
- ),
+ outbound
+ .filter(
+ (message) =>
+ message.event === "showAlert" ||
+ [
+ "qa-model-dial",
+ "qa-reasoning-dial",
+ "qa-ptt-key",
+ "qa-plan-command",
+ ].includes(message.context),
+ )
+ .map((message) =>
+ message.event === "setImage"
+ ? { ...message, payload: { image: "" } }
+ : message,
+ ),
)}\n`,
);
throw error;
diff --git a/scripts/qa-mode-events.mjs b/scripts/qa-mode-events.mjs
index 1089022..94dd03c 100644
--- a/scripts/qa-mode-events.mjs
+++ b/scripts/qa-mode-events.mjs
@@ -120,16 +120,19 @@ async function pressMode(mode, commandIndex, expectedTitle) {
event: "dialUp",
payload,
});
- const feedback = await waitFor(() =>
- outbound
- .slice(before)
- .find(
- (message) =>
- message.context === context &&
- message.event === "setFeedback" &&
- message.payload?.title === expectedTitle &&
- message.payload?.value?.toLowerCase() === mode,
- ),
+ const feedback = await waitFor(
+ () =>
+ outbound
+ .slice(before)
+ .find(
+ (message) =>
+ message.context === context &&
+ message.event === "setFeedback" &&
+ message.payload?.title === expectedTitle &&
+ message.payload?.value?.toLowerCase() === mode,
+ ),
+ 20_000,
+ `verified ${mode} ${expectedTitle} feedback`,
);
return feedback.payload;
}
diff --git a/scripts/qa-native-completion.mjs b/scripts/qa-native-completion.mjs
new file mode 100755
index 0000000..78d5098
--- /dev/null
+++ b/scripts/qa-native-completion.mjs
@@ -0,0 +1,21 @@
+#!/usr/bin/env node
+import { appendFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+const args = process.argv.slice(2);
+const call = spawnSync(process.env.QA_NATIVE_REAL, args, { encoding: "utf8" });
+let operation = args[0];
+if (operation === "claude")
+ operation = JSON.parse(Buffer.from(args[1], "base64").toString()).operation;
+let result;
+try {
+ result = JSON.parse(call.stdout);
+} catch {
+ result = { ok: false, message: call.stderr };
+}
+appendFileSync(
+ process.env.QA_NATIVE_LOG,
+ JSON.stringify({ operation, result }) + "\n",
+);
+process.stdout.write(call.stdout ?? "");
+process.stderr.write(call.stderr ?? "");
+process.exit(call.status ?? 1);
diff --git a/scripts/qa-page-refresh.mjs b/scripts/qa-page-refresh.mjs
new file mode 100644
index 0000000..6e9af8f
--- /dev/null
+++ b/scripts/qa-page-refresh.mjs
@@ -0,0 +1,105 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import {
+ createStreamDeckActionHarness,
+ waitFor,
+} from "./lib/streamdeck-action-harness.mjs";
+
+const helper = resolve(
+ "com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control",
+);
+const read = () =>
+ JSON.parse(execFileSync(helper, ["provider-read"], { encoding: "utf8" }))
+ .providerState;
+const initial = read();
+assert.equal(initial.foreground, "claude");
+assert(initial.sessions?.[0]?.title.toLowerCase().includes("audit"));
+assert(initial.draftEmpty);
+const archive = resolve(
+ "com.todd.streamdeckcodex.sdPlugin/streamdeckai-plus.streamDeckProfile",
+);
+const entries = execFileSync("unzip", ["-Z1", archive], { encoding: "utf8" })
+ .trim()
+ .split("\n");
+const base = entries.find((e) => e.endsWith(".sdProfile/"));
+assert(base);
+const json = (path) =>
+ JSON.parse(
+ execFileSync("unzip", ["-p", archive, path], { encoding: "utf8" }),
+ );
+const root = json(base + "manifest.json");
+const pages = root.Pages.Pages.map((id, index) => {
+ const page = json(`${base}Profiles/${id}/manifest.json`);
+ return page.Controllers.flatMap((controller) =>
+ Object.entries(controller.Actions ?? {})
+ .filter(([, action]) =>
+ action.UUID.startsWith("com.todd.streamdeckcodex."),
+ )
+ .map(([coordinate, action]) => {
+ const [column, row] = coordinate.split(",").map(Number);
+ return {
+ context: `qa-page-${index}-${controller.Type}-${coordinate}`,
+ action: action.UUID,
+ device: "qa-stream-deck-plus",
+ payload: {
+ controller: controller.Type,
+ coordinates: { column, row },
+ settings: action.Settings,
+ },
+ };
+ }),
+ );
+});
+const h = await createStreamDeckActionHarness({
+ plugin: resolve("com.todd.streamdeckcodex.sdPlugin/bin/plugin.js"),
+ pluginContext: "qa-page-refresh",
+});
+try {
+ let visible = [];
+ const started = performance.now();
+ for (const page of [...pages, pages[0]]) {
+ for (const entry of visible) h.send({ ...entry, event: "willDisappear" });
+ for (const entry of page) h.send({ ...entry, event: "willAppear" });
+ visible = page;
+ }
+ for (const [kind, expected] of [
+ ["model", initial.model],
+ ["reasoning", initial.effort],
+ ]) {
+ const entry = visible.find((e) => e.action.endsWith("." + kind));
+ assert(entry);
+ await waitFor(
+ () =>
+ h.outbound.some(
+ (m) =>
+ m.context === entry.context &&
+ m.event === "setFeedback" &&
+ m.payload?.value === expected &&
+ m.payload?.title?.startsWith("CLAUDE"),
+ ),
+ 8000,
+ kind + " after rapid page navigation",
+ );
+ }
+ const elapsedMs = Math.round(performance.now() - started);
+ assert(!h.outbound.some((m) => m.event === "showAlert"));
+ assert.deepEqual(read().target, initial.target);
+ const result = {
+ pages: pages.length,
+ returnedHome: true,
+ elapsedMs,
+ model: initial.model,
+ effort: initial.effort,
+ passed: true,
+ };
+ mkdirSync(resolve(".cache/control-audit"), { recursive: true });
+ writeFileSync(
+ resolve(".cache/control-audit/page-refresh.json"),
+ JSON.stringify(result, null, 2) + "\n",
+ );
+ console.log(JSON.stringify(result));
+} finally {
+ await h.close();
+}
diff --git a/scripts/qa-provider-keys.mjs b/scripts/qa-provider-keys.mjs
new file mode 100644
index 0000000..f801f78
--- /dev/null
+++ b/scripts/qa-provider-keys.mjs
@@ -0,0 +1,129 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { resolve } from "node:path";
+import {
+ createStreamDeckActionHarness,
+ delay,
+ waitFor,
+} from "./lib/streamdeck-action-harness.mjs";
+const fixturePath =
+ process.argv[process.argv.indexOf("--profile-fixtures") + 1];
+const fixtures = process.argv.includes("--profile-fixtures")
+ ? JSON.parse(readFileSync(fixturePath, "utf8"))
+ : [];
+const keys = [
+ "codex-weekly",
+ "codex-context",
+ "claude-weekly",
+ "claude-context",
+];
+const harness = await createStreamDeckActionHarness({
+ plugin: resolve("com.todd.streamdeckcodex.sdPlugin/bin/plugin.js"),
+ pluginContext: "qa-provider-keys",
+});
+const event = (kind, phase, name) => ({
+ event: name,
+ action: `com.todd.streamdeckcodex.${kind}`,
+ context: `${phase}-${kind}`,
+ device: "qa-stream-deck-plus",
+ payload: {
+ controller: "Keypad",
+ coordinates: { column: keys.indexOf(kind), row: 0 },
+ settings: fixtures.find((row) => row.kind === kind)?.settings ?? {},
+ isInMultiAction: false,
+ },
+});
+const svg = (kind, phase) => {
+ const m = harness.outbound.findLast(
+ (m) => m.context === `${phase}-${kind}` && m.event === "setImage",
+ );
+ return m
+ ? Buffer.from(m.payload.image.split(",")[1], "base64").toString()
+ : "";
+};
+try {
+ if (fixtures.length) {
+ for (const kind of keys)
+ assert(
+ fixtures.some((row) => row.kind === kind),
+ `Missing installed ${kind}`,
+ );
+ console.log(
+ JSON.stringify({
+ savedProfileKeys: fixtures.filter((row) => keys.includes(row.kind))
+ .length,
+ settingsFromInstalledProfiles: true,
+ }),
+ );
+ }
+ for (const phase of ["Claude", "ChatGPT"]) {
+ const activated = spawnSync(
+ "osascript",
+ ["-e", `tell application "${phase}" to activate`],
+ { encoding: "utf8" },
+ );
+ assert.equal(activated.status, 0);
+ await delay(1200);
+ for (const kind of keys) harness.send(event(kind, phase, "willAppear"));
+ await waitFor(
+ () => keys.every((kind) => svg(kind, phase)),
+ 10000,
+ "all four key images",
+ );
+ for (const [pass, weekly, context] of [
+ [1, "CODEX RESETS", "CODEX TOKENS"],
+ [2, "CODEX LEFT", "CODEX CONTEXT"],
+ [3, "CODEX RESETS", "CODEX TOKENS"],
+ ]) {
+ for (const kind of keys) {
+ harness.send(event(kind, phase, "keyDown"));
+ harness.send(event(kind, phase, "keyUp"));
+ }
+ await waitFor(
+ () =>
+ svg("codex-weekly", phase).includes(weekly) &&
+ svg("codex-context", phase).includes(context),
+ 10000,
+ "Codex display toggles",
+ );
+ await delay(3000);
+ assert(
+ svg("claude-weekly", phase).includes(
+ pass === 1
+ ? "WEEKLY RESETS"
+ : pass === 2
+ ? "FABLE RESETS"
+ : "CLAUDE LEFT",
+ ),
+ );
+ if (process.argv.includes("--verify-reset-balances") && pass < 3) {
+ assert(
+ svg("claude-weekly", phase).includes(
+ pass === 1 ? ">2" : ">1",
+ ),
+ "Reset count does not match the inspected Usage inventory",
+ );
+ if (phase === "ChatGPT")
+ assert(svg("claude-weekly", phase).includes("CACHED"));
+ }
+ assert(svg("claude-context", phase).includes("CLAUDE CONTEXT"));
+ assert(
+ !harness.outbound.some((m) => m.event === "showAlert"),
+ "A status key flashed a warning",
+ );
+ console.log(
+ JSON.stringify({
+ foreground: phase,
+ press: pass,
+ keys: 4,
+ passed: true,
+ }),
+ );
+ }
+ for (const kind of keys) harness.send(event(kind, phase, "willDisappear"));
+ }
+} finally {
+ await harness.close();
+ spawnSync("osascript", ["-e", 'tell application "ChatGPT" to activate']);
+}
diff --git a/scripts/qa-telemetry-restart.mjs b/scripts/qa-telemetry-restart.mjs
new file mode 100644
index 0000000..531a9a1
--- /dev/null
+++ b/scripts/qa-telemetry-restart.mjs
@@ -0,0 +1,73 @@
+import assert from "node:assert/strict";
+import { resolve } from "node:path";
+import {
+ createStreamDeckActionHarness,
+ waitFor,
+ delay,
+} from "./lib/streamdeck-action-harness.mjs";
+const seed = process.argv.includes("--seed");
+const h = await createStreamDeckActionHarness({
+ plugin: resolve("com.todd.streamdeckcodex.sdPlugin/bin/plugin.js"),
+ pluginContext: seed ? "qa-reset-seed" : "qa-reset-restart",
+});
+const event = (kind, name) =>
+ h.send({
+ event: name,
+ context: kind,
+ action: "com.todd.streamdeckcodex." + kind,
+ device: "qa-stream-deck-plus",
+ payload: {
+ controller: "Keypad",
+ coordinates: { column: 0, row: 0 },
+ settings: {},
+ },
+ });
+const svg = (kind) => {
+ const m = h.outbound.findLast(
+ (m) => m.context === kind && m.event === "setImage",
+ );
+ return m
+ ? Buffer.from(m.payload.image.split(",")[1], "base64").toString()
+ : "";
+};
+try {
+ for (const kind of ["claude-weekly", "codex-context"])
+ event(kind, "willAppear");
+ await waitFor(() => svg("claude-weekly"), 15000);
+ await delay(1500);
+ for (const [heading, count] of [
+ ["WEEKLY RESETS", 2],
+ ["FABLE RESETS", 1],
+ ]) {
+ event("claude-weekly", "keyDown");
+ event("claude-weekly", "keyUp");
+ await waitFor(
+ () =>
+ svg("claude-weekly").includes(heading) &&
+ svg("claude-weekly").includes(`>${count}`),
+ 15000,
+ heading,
+ );
+ if (!seed) assert(svg("claude-weekly").includes("CACHED"));
+ console.log(
+ JSON.stringify({
+ heading,
+ count,
+ persistedAfterRestart: !seed,
+ passed: true,
+ }),
+ );
+ }
+ if (!seed) {
+ await waitFor(
+ () => svg("codex-context").includes("CACHED"),
+ 15000,
+ "old exact-chat context retained",
+ );
+ assert(!svg("codex-context").includes("NO DATA"));
+ console.log(JSON.stringify({ codexContext: "CACHED", passed: true }));
+ }
+ assert(!h.outbound.some((m) => m.event === "showAlert"));
+} finally {
+ await h.close();
+}
diff --git a/scripts/render-master-profiles.mjs b/scripts/render-master-profiles.mjs
new file mode 100644
index 0000000..eb77994
--- /dev/null
+++ b/scripts/render-master-profiles.mjs
@@ -0,0 +1,130 @@
+import { build } from "esbuild";
+import { mkdirSync, writeFileSync, readFileSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+const root = resolve(".cache/master-profile-visuals");
+mkdirSync(root, { recursive: true });
+const bundle = resolve(root, "visuals.mjs");
+await build({
+ stdin: {
+ contents:
+ 'export * from "./src/lib/visuals.ts"; export {COMMANDS} from "./src/lib/commands.ts";',
+ resolveDir: process.cwd(),
+ },
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ outfile: bundle,
+});
+const v = await import(pathToFileURL(bundle));
+for (const [device, columns, rows] of [
+ ["plus", 4, 2],
+ ["mini", 3, 2],
+]) {
+ const zip = resolve(
+ `com.todd.streamdeckcodex.sdPlugin/streamdeckai-${device}.streamDeckProfile`,
+ );
+ const entries = execFileSync("unzip", ["-Z1", zip], { encoding: "utf8" })
+ .trim()
+ .split("\n");
+ const base = entries.find((e) => e.endsWith(".sdProfile/"));
+ const data = (p) =>
+ JSON.parse(execFileSync("unzip", ["-p", zip, p], { encoding: "utf8" }));
+ const profile = data(base + "manifest.json"),
+ sheets = [];
+ for (const [pageIndex, id] of profile.Pages.Pages.entries()) {
+ const page = data(`${base}Profiles/${id}/manifest.json`);
+ const actions = page.Controllers.find((c) => c.Type === "Keypad").Actions;
+ const keys = [];
+ for (let i = 0; i < columns * rows; i++) {
+ const a = actions[`${i % columns},${Math.floor(i / columns)}`],
+ stem = resolve(root, `${device}-${pageIndex}-${i}`);
+ let svg;
+ if (!a)
+ svg =
+ ' ';
+ else if (a.UUID.startsWith("com.elgato.streamdeck.page."))
+ svg = readFileSync(
+ `assets/profile-navigation/${a.UUID.split(".").at(-1)}.svg`,
+ "utf8",
+ );
+ else if (a.UUID.endsWith("-weekly")) {
+ const claude = a.UUID.includes("claude-");
+ svg = v.usageKeySvg(
+ { usedPercent: claude ? 40 : 25, observedAt: Date.now() },
+ "weekly",
+ Date.now(),
+ {
+ heading: claude ? "CLAUDE LEFT" : "CODEX LEFT",
+ accent: claude ? "#E7A589" : "#9CD5FE",
+ footer: "EXAMPLE",
+ },
+ );
+ } else if (a.UUID.endsWith("-context")) {
+ const claude = a.UUID.includes("claude-");
+ svg = v.contextKeySvg(
+ {
+ remainingPercent: claude ? 76 : 89,
+ observedAt: Date.now(),
+ threadId: "example",
+ },
+ "remaining",
+ {
+ heading: claude ? "CLAUDE CONTEXT" : "CODEX CONTEXT",
+ accent: claude ? "#E7A589" : "#9CD5FE",
+ footer: "EXAMPLE",
+ },
+ );
+ } else if (a.UUID.endsWith(".keycap"))
+ svg = v.keycapSvg(
+ a.Settings.label,
+ a.Settings.description,
+ a.Settings.icon,
+ );
+ else if (a.UUID.endsWith(".approval-mode"))
+ svg = v.commandKeySvg("Auto", "#E7A589", "shield");
+ else {
+ const c = v.COMMANDS.find((c) => c.id === a.Settings.commandId);
+ if (!c) throw Error(a.UUID);
+ svg = v.commandKeySvg(c.label, c.accent, c.icon);
+ }
+ writeFileSync(stem + ".svg", svg);
+ execFileSync("rsvg-convert", [
+ "-w",
+ "144",
+ "-h",
+ "144",
+ "-o",
+ stem + ".png",
+ stem + ".svg",
+ ]);
+ keys.push(stem + ".png");
+ }
+ const sheet = resolve(root, `${device}-${pageIndex}.png`);
+ execFileSync("magick", [
+ "montage",
+ ...keys,
+ "-tile",
+ `${columns}x${rows}`,
+ "-geometry",
+ "144x144+8+8",
+ "-background",
+ "#05070A",
+ sheet,
+ ]);
+ sheets.push(sheet);
+ }
+ execFileSync("magick", [
+ "montage",
+ ...sheets.slice(0, 6),
+ "-tile",
+ "2x3",
+ "-geometry",
+ "+12+12",
+ "-background",
+ "#05070A",
+ resolve(root, device + "-overview.png"),
+ ]);
+ console.log(`${device}: rendered ${sheets.length} actual Master pages`);
+}
diff --git a/scripts/stage-release.mjs b/scripts/stage-release.mjs
index 087f903..551cfe4 100644
--- a/scripts/stage-release.mjs
+++ b/scripts/stage-release.mjs
@@ -9,11 +9,18 @@ const pluginPackage = resolve(
const keypadProfiles = JSON.parse(
await readFile(resolve("profile-src", "keypad-profiles.json"), "utf8"),
);
-const profileNames = [
+const legacyProfileNames = [
...keypadProfiles.devices.map((device) => device.archiveName),
"streamdeckcodex-plus",
];
+const profileNames = [
+ ...legacyProfileNames,
+ ...legacyProfileNames.map((name) =>
+ name.replace("streamdeckcodex-", "streamdeckai-"),
+ ),
+];
+
await mkdir(resolve("dist"), { recursive: true });
await readFile(pluginPackage);
const profileDestinations = [];
diff --git a/src/actions/antigravity.ts b/src/actions/antigravity.ts
new file mode 100644
index 0000000..e6a285d
--- /dev/null
+++ b/src/actions/antigravity.ts
@@ -0,0 +1,116 @@
+import streamDeck, {
+ action,
+ type Action,
+ type KeyDownEvent,
+ SingletonAction,
+ type WillAppearEvent,
+} from "@elgato/streamdeck";
+import {
+ ANTIGRAVITY_PRESET_LABEL,
+ antigravityStore,
+} from "../lib/antigravity.js";
+import { renderKey } from "../lib/render-cache.js";
+import {
+ contextKeySvg,
+ modeKeySvg,
+ svgDataUrl,
+ usageKeySvg,
+} from "../lib/visuals.js";
+
+const ACCENT = "#8AB4F8";
+
+abstract class AntigravityKey extends SingletonAction {
+ async onWillAppear(event: WillAppearEvent): Promise {
+ await this.draw(event.action);
+ void antigravityStore.refresh().then(() => this.draw(event.action));
+ }
+
+ async refreshAll(): Promise {
+ await Promise.all([...this.actions].map((visible) => this.draw(visible)));
+ }
+
+ protected abstract svg(id: string): string;
+
+ protected async draw(actionInstance: Action<{}>): Promise {
+ if (!actionInstance.isKey()) return;
+ await renderKey(actionInstance, svgDataUrl(this.svg(actionInstance.id)));
+ }
+}
+
+/** Press to step through each quota group's weekly and five-hour limits. */
+@action({ UUID: "com.todd.streamdeckcodex.antigravity-usage" })
+export class AntigravityUsageAction extends AntigravityKey {
+ readonly #view = new Map();
+
+ async onKeyDown(event: KeyDownEvent): Promise {
+ this.#view.set(event.action.id, (this.#view.get(event.action.id) ?? 0) + 1);
+ await this.draw(event.action);
+ }
+
+ protected svg(id: string): string {
+ const buckets = antigravityStore.quota;
+ const bucket = buckets[(this.#view.get(id) ?? 0) % (buckets.length || 1)];
+ const now = Date.now();
+ const reset = bucket?.usage.resetsAt
+ ? bucket.usage.resetsAt * 1000 - now
+ : undefined;
+ const due =
+ reset === undefined
+ ? ""
+ : reset >= 86_400_000
+ ? ` · ${Math.ceil(reset / 86_400_000)}D`
+ : ` · ${Math.max(1, Math.ceil(reset / 3_600_000))}H`;
+ return usageKeySvg(bucket?.usage, "weekly", now, {
+ heading: bucket ? `AGY ${bucket.group}` : "ANTIGRAVITY",
+ footer: bucket
+ ? `${bucket.window} LEFT${due}`
+ : (antigravityStore.reason ?? ""),
+ accent: ACCENT,
+ });
+ }
+}
+
+@action({ UUID: "com.todd.streamdeckcodex.antigravity-context" })
+export class AntigravityContextAction extends AntigravityKey {
+ async onKeyDown(event: KeyDownEvent): Promise {
+ await antigravityStore.refresh(true);
+ await this.draw(event.action);
+ }
+
+ protected svg(): string {
+ return contextKeySvg(antigravityStore.context, "remaining", {
+ heading: "AGY CONTEXT",
+ accent: ACCENT,
+ unavailableValue: antigravityStore.reason ?? "NO CHAT",
+ });
+ }
+}
+
+/** Press to cycle the global permission preset: Review, Default, Turbo. */
+@action({ UUID: "com.todd.streamdeckcodex.antigravity-permissions" })
+export class AntigravityPermissionsAction extends AntigravityKey {
+ async onKeyDown(event: KeyDownEvent): Promise {
+ try {
+ await antigravityStore.cyclePreset();
+ await this.draw(event.action);
+ await event.action.showOk();
+ } catch (error) {
+ streamDeck.logger.warn(
+ `Antigravity permissions: ${error instanceof Error ? error.message : "unavailable"}`,
+ );
+ await this.draw(event.action);
+ await event.action.showAlert();
+ }
+ }
+
+ protected svg(): string {
+ const preset = antigravityStore.preset;
+ return modeKeySvg(
+ preset
+ ? ANTIGRAVITY_PRESET_LABEL[preset]
+ : (antigravityStore.reason ?? "UNAVAILABLE"),
+ "Antigravity",
+ "shield",
+ );
+ }
+}
diff --git a/src/actions/command.ts b/src/actions/command.ts
index 9619191..ea26cfa 100644
--- a/src/actions/command.ts
+++ b/src/actions/command.ts
@@ -107,6 +107,7 @@ export class CommandAction extends SingletonAction {
await event.action.setSettings({
...event.payload.settings,
commandIndex: index,
+ commandId: dialCommandAt(index).id,
});
await this.draw(event.action, dialCommandAt(index));
}
diff --git a/src/actions/model.ts b/src/actions/model.ts
index eb739e2..0603e13 100644
--- a/src/actions/model.ts
+++ b/src/actions/model.ts
@@ -139,6 +139,7 @@ export class ModelAction extends SingletonAction {
codexStore.invalidate();
this.#state.set(context, state);
await actionInstance.setSettings({
+ ...(await actionInstance.getSettings()),
selectedModel: state.selected,
appliedModel: state.applied,
});
diff --git a/src/actions/provider-context.ts b/src/actions/provider-context.ts
new file mode 100644
index 0000000..cf20ee0
--- /dev/null
+++ b/src/actions/provider-context.ts
@@ -0,0 +1,49 @@
+import {
+ action,
+ type Action,
+ type KeyDownEvent,
+ SingletonAction,
+ type WillAppearEvent,
+} from "@elgato/streamdeck";
+import { toggleContextView, type ContextView } from "../lib/context.js";
+import { codexStore } from "../lib/codex-store.js";
+import { renderKey } from "../lib/render-cache.js";
+import { contextKeySvg, svgDataUrl } from "../lib/visuals.js";
+
+@action({ UUID: "com.todd.streamdeckcodex.codex-context" })
+export class CodexContextAction extends SingletonAction {
+ readonly #mode = new Map();
+
+ async onKeyDown(event: KeyDownEvent): Promise {
+ const current = this.#mode.get(event.action.id) ?? "remaining";
+ this.#mode.set(event.action.id, toggleContextView(current));
+ await this.draw(event.action);
+ }
+ async onWillAppear(event: WillAppearEvent): Promise {
+ this.#mode.set(event.action.id, "remaining");
+ await this.draw(event.action);
+ }
+
+ async refreshAll(): Promise {
+ await Promise.all([...this.actions].map((visible) => this.draw(visible)));
+ }
+
+ private async draw(actionInstance: Action<{}>): Promise {
+ if (!actionInstance.isKey()) return;
+ const mode = this.#mode.get(actionInstance.id) ?? "remaining";
+ await renderKey(
+ actionInstance,
+ svgDataUrl(
+ contextKeySvg(codexStore.contextSnapshot(), mode, {
+ heading: mode === "exact" ? "CODEX TOKENS" : "CODEX CONTEXT",
+ accent: "#9CD5FE",
+ }),
+ ),
+ );
+ }
+}
+
+// ProviderAction renders Claude context so it can preserve and invalidate the
+// session-bound last observation independently from Codex.
+@action({ UUID: "com.todd.streamdeckcodex.claude-context" })
+export class ClaudeContextAction extends SingletonAction {}
diff --git a/src/actions/provider-weekly.ts b/src/actions/provider-weekly.ts
new file mode 100644
index 0000000..27ef942
--- /dev/null
+++ b/src/actions/provider-weekly.ts
@@ -0,0 +1,49 @@
+import {
+ action,
+ type Action,
+ type KeyDownEvent,
+ SingletonAction,
+ type WillAppearEvent,
+} from "@elgato/streamdeck";
+import { toggleUsageView, type UsageView } from "../lib/usage.js";
+import { codexStore } from "../lib/codex-store.js";
+import { renderKey } from "../lib/render-cache.js";
+import { svgDataUrl, usageKeySvg } from "../lib/visuals.js";
+
+@action({ UUID: "com.todd.streamdeckcodex.codex-weekly" })
+export class CodexWeeklyAction extends SingletonAction {
+ readonly #mode = new Map();
+
+ async onKeyDown(event: KeyDownEvent): Promise {
+ const current = this.#mode.get(event.action.id) ?? "weekly";
+ this.#mode.set(event.action.id, toggleUsageView(current));
+ await this.draw(event.action);
+ }
+ async onWillAppear(event: WillAppearEvent): Promise {
+ this.#mode.set(event.action.id, "weekly");
+ await this.draw(event.action);
+ }
+
+ async refreshAll(): Promise {
+ await Promise.all([...this.actions].map((visible) => this.draw(visible)));
+ }
+
+ private async draw(actionInstance: Action<{}>): Promise {
+ if (!actionInstance.isKey()) return;
+ const mode = this.#mode.get(actionInstance.id) ?? "weekly";
+ await renderKey(
+ actionInstance,
+ svgDataUrl(
+ usageKeySvg(codexStore.usageSnapshotCached(), mode, Date.now(), {
+ heading: mode === "resets" ? "CODEX RESETS" : "CODEX LEFT",
+ accent: "#9CD5FE",
+ }),
+ ),
+ );
+ }
+}
+
+// Claude rendering is handled by ProviderAction so it can consume the last
+// verified UI observation even after Claude moves to the background.
+@action({ UUID: "com.todd.streamdeckcodex.claude-weekly" })
+export class ClaudeWeeklyAction extends SingletonAction {}
diff --git a/src/actions/reasoning.ts b/src/actions/reasoning.ts
index 7c2db20..d29a005 100644
--- a/src/actions/reasoning.ts
+++ b/src/actions/reasoning.ts
@@ -157,6 +157,7 @@ export class ReasoningAction extends SingletonAction {
const state = confirmReasoning({ selected: level, applied: "" }).state;
this.#state.set(context, state);
await actionInstance.setSettings({
+ ...(await actionInstance.getSettings()),
selectedLevel: level,
appliedLevel: level,
});
diff --git a/src/lib/antigravity.ts b/src/lib/antigravity.ts
new file mode 100644
index 0000000..5abb079
--- /dev/null
+++ b/src/lib/antigravity.ts
@@ -0,0 +1,297 @@
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import type { ContextSnapshot, UsageSnapshot } from "../types.js";
+
+/**
+ * Google Antigravity runs a local language server that answers quota,
+ * conversation and permission questions over Connect-RPC JSON on localhost.
+ * It writes its port and a per-launch CSRF token to a daemon descriptor, so
+ * nothing here reads the screen or needs Accessibility.
+ */
+const DAEMON_DIRECTORY = join(homedir(), ".gemini", "antigravity", "daemon");
+const SERVICE = "exa.language_server_pb.LanguageServerService";
+const REQUEST_TIMEOUT_MS = 2_500;
+const QUOTA_CACHE_MS = 30_000;
+const LIVE_CACHE_MS = 3_000;
+const PRESET_PREFIX = "AGENT_PERMISSION_PRESET_";
+
+/** The presets the server keeps distinct; every other value reads back as Default. */
+export const ANTIGRAVITY_PRESETS = [
+ "REQUEST_REVIEW",
+ "DEFAULT",
+ "TURBO",
+] as const;
+export type AntigravityPreset = (typeof ANTIGRAVITY_PRESETS)[number];
+export const ANTIGRAVITY_PRESET_LABEL: Record = {
+ REQUEST_REVIEW: "Review",
+ DEFAULT: "Default",
+ TURBO: "Turbo",
+};
+
+export interface AntigravityQuotaBucket {
+ /** First word of the quota group, e.g. "GEMINI" or "CLAUDE". */
+ group: string;
+ window: string;
+ usage: UsageSnapshot;
+}
+
+export type AntigravityReason = "NOT OPEN" | "UNAVAILABLE";
+
+interface Daemon {
+ httpPort: number;
+ csrfToken: string;
+}
+
+function processAlive(pid: unknown): boolean {
+ if (typeof pid !== "number") return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function findAntigravityDaemon(
+ directory = DAEMON_DIRECTORY,
+): Daemon | undefined {
+ let names: string[];
+ try {
+ names = readdirSync(directory).filter((name) =>
+ /^hub_\d+\.json$/.test(name),
+ );
+ } catch {
+ return undefined;
+ }
+ return names
+ .map((name) => {
+ try {
+ const path = join(directory, name);
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ if (
+ !processAlive(parsed.pid) ||
+ typeof parsed.httpPort !== "number" ||
+ typeof parsed.csrfToken !== "string"
+ )
+ return undefined;
+ return {
+ httpPort: parsed.httpPort,
+ csrfToken: parsed.csrfToken,
+ modifiedAt: statSync(path).mtimeMs,
+ };
+ } catch {
+ return undefined;
+ }
+ })
+ .filter((daemon) => daemon !== undefined)
+ .sort((left, right) => right.modifiedAt - left.modifiedAt)[0];
+}
+
+export function parseAntigravityQuota(
+ response: unknown,
+ observedAt = Date.now(),
+): AntigravityQuotaBucket[] {
+ const groups = (response as any)?.response?.groups;
+ if (!Array.isArray(groups)) return [];
+ return groups.flatMap((group: any) =>
+ (Array.isArray(group?.buckets) ? group.buckets : []).flatMap(
+ (bucket: any): AntigravityQuotaBucket[] => {
+ const remaining = bucket?.remainingFraction;
+ if (typeof remaining !== "number" || remaining < 0 || remaining > 1)
+ return [];
+ const resetsAt = Date.parse(bucket.resetTime ?? "");
+ return [
+ {
+ group: String(group.displayName ?? "")
+ .split(" ")[0]!
+ .toUpperCase(),
+ window:
+ bucket.window === "weekly"
+ ? "WEEK"
+ : String(bucket.window ?? "").toUpperCase(),
+ usage: {
+ usedPercent: (1 - remaining) * 100,
+ observedAt,
+ ...(Number.isFinite(resetsAt)
+ ? { resetsAt: resetsAt / 1000 }
+ : {}),
+ },
+ },
+ ];
+ },
+ ),
+ );
+}
+
+/** The conversation the user looked at most recently. */
+export function latestAntigravityConversation(
+ response: unknown,
+): string | undefined {
+ const summaries = (response as any)?.trajectorySummaries;
+ if (!summaries || typeof summaries !== "object") return undefined;
+ const seen = (summary: any) =>
+ Date.parse(
+ summary?.annotations?.lastUserViewTime ?? summary?.lastModifiedTime ?? "",
+ ) || 0;
+ return Object.entries(summaries).sort(
+ ([, left], [, right]) => seen(right) - seen(left),
+ )[0]?.[0];
+}
+
+export function parseAntigravityContext(
+ response: unknown,
+ conversationId: string,
+ observedAt = Date.now(),
+): ContextSnapshot | undefined {
+ const turns = (response as any)?.generatorMetadata;
+ if (!Array.isArray(turns)) return undefined;
+ for (let index = turns.length - 1; index >= 0; index--) {
+ const window =
+ turns[index]?.chatModel?.chatStartMetadata?.contextWindowMetadata;
+ const used = Number(window?.estimatedTokensUsed);
+ const max = Number(window?.maxContextTokens);
+ if (!Number.isFinite(used) || !Number.isFinite(max) || max <= 0) continue;
+ return {
+ threadId: conversationId,
+ usedTokens: used,
+ maxTokens: max,
+ remainingPercent: Math.max(
+ 0,
+ Math.min(100, Math.round(100 - (used / max) * 100)),
+ ),
+ observedAt,
+ };
+ }
+ return undefined;
+}
+
+export function parseAntigravityPreset(
+ response: unknown,
+): AntigravityPreset | undefined {
+ const value = String((response as any)?.globalPreset ?? "").slice(
+ PRESET_PREFIX.length,
+ );
+ return (ANTIGRAVITY_PRESETS as readonly string[]).includes(value)
+ ? (value as AntigravityPreset)
+ : undefined;
+}
+
+export function nextAntigravityPreset(
+ current: AntigravityPreset,
+): AntigravityPreset {
+ return ANTIGRAVITY_PRESETS[
+ (ANTIGRAVITY_PRESETS.indexOf(current) + 1) % ANTIGRAVITY_PRESETS.length
+ ]!;
+}
+
+export class AntigravityStore {
+ quota: AntigravityQuotaBucket[] = [];
+ context: ContextSnapshot | undefined;
+ preset: AntigravityPreset | undefined;
+ reason: AntigravityReason | undefined = "NOT OPEN";
+ #quotaAt = 0;
+ #liveAt = 0;
+ #refreshing: Promise | undefined;
+ readonly #daemon: () => Daemon | undefined;
+
+ constructor(daemon: () => Daemon | undefined = findAntigravityDaemon) {
+ this.#daemon = daemon;
+ }
+
+ async #call(method: string, body: unknown = {}): Promise {
+ const daemon = this.#daemon();
+ if (!daemon) throw new Error("NOT OPEN");
+ const response = await fetch(
+ `http://127.0.0.1:${daemon.httpPort}/${SERVICE}/${method}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Connect-Protocol-Version": "1",
+ "X-Codeium-Csrf-Token": daemon.csrfToken,
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ },
+ );
+ if (!response.ok) throw new Error(`${method} returned ${response.status}`);
+ return response.json();
+ }
+
+ /** Stale-while-revalidate: callers render the cached fields and never wait. */
+ refresh(force = false, now = Date.now()): Promise {
+ this.#refreshing ??= this.#read(force, now).finally(() => {
+ this.#refreshing = undefined;
+ });
+ return this.#refreshing;
+ }
+
+ async #read(force: boolean, now: number): Promise {
+ if (!this.#daemon()) {
+ this.quota = [];
+ this.context = undefined;
+ this.preset = undefined;
+ this.reason = "NOT OPEN";
+ this.#quotaAt = this.#liveAt = 0;
+ return;
+ }
+ try {
+ if (force || now - this.#liveAt >= LIVE_CACHE_MS) {
+ this.#liveAt = now;
+ this.preset = parseAntigravityPreset(
+ await this.#call("GetPermissionSettings"),
+ );
+ const conversation = latestAntigravityConversation(
+ await this.#call("GetAllCascadeTrajectories"),
+ );
+ this.context = conversation
+ ? parseAntigravityContext(
+ await this.#call("GetCascadeTrajectoryGeneratorMetadata", {
+ cascadeId: conversation,
+ }),
+ conversation,
+ now,
+ )
+ : undefined;
+ }
+ if (force || now - this.#quotaAt >= QUOTA_CACHE_MS) {
+ this.#quotaAt = now;
+ this.quota = parseAntigravityQuota(
+ await this.#call("RetrieveUserQuotaSummary"),
+ now,
+ );
+ }
+ this.reason = undefined;
+ } catch (error) {
+ this.reason =
+ error instanceof Error && error.message === "NOT OPEN"
+ ? "NOT OPEN"
+ : "UNAVAILABLE";
+ }
+ }
+
+ /** Apply the next preset and return what the server then reports. */
+ async cyclePreset(): Promise {
+ const current = parseAntigravityPreset(
+ await this.#call("GetPermissionSettings"),
+ );
+ if (!current) throw new Error("Antigravity reported no known preset.");
+ const wanted = nextAntigravityPreset(current);
+ await this.#call("UpdatePermissionSettings", {
+ preset: PRESET_PREFIX + wanted,
+ });
+ const applied = parseAntigravityPreset(
+ await this.#call("GetPermissionSettings"),
+ );
+ this.preset = applied;
+ if (applied !== wanted)
+ throw new Error(`Antigravity kept ${applied ?? "an unknown preset"}.`);
+ return applied;
+ }
+}
+
+export const antigravityStore = new AntigravityStore();
diff --git a/src/lib/codex-store.ts b/src/lib/codex-store.ts
index 8b1bcad..2d42c24 100644
--- a/src/lib/codex-store.ts
+++ b/src/lib/codex-store.ts
@@ -29,7 +29,10 @@ import {
} from "./rollout-status.js";
import { fetchAccountUsage, parseLatestUsage } from "./usage.js";
import { activeDesktopThreadId } from "./desktop-active.js";
-import { contextAvailabilityFromLines } from "./context.js";
+import {
+ contextAvailabilityFromLines,
+ contextDisplayFromLines,
+} from "./context.js";
import {
availabilityReasonFromError,
ready,
@@ -886,8 +889,13 @@ export class CodexStore {
}
contextSnapshot(): ContextSnapshot | undefined {
- const availability = this.contextAvailability();
- return availability.state === "ready" ? availability.value : undefined;
+ const thread = this.focusedThread();
+ return thread
+ ? contextDisplayFromLines(
+ this.#rolloutTail(thread.rolloutPath),
+ thread.id,
+ )
+ : undefined;
}
reasoningSnapshot(): ReasoningSnapshot {
@@ -998,11 +1006,16 @@ export class CodexStore {
// The fetch reason is the useful one; a fallback failure adds nothing.
}
}
+ const previous = this.#usageCache?.snapshot;
this.#usageCache = {
at: Date.now(),
- ...(snapshot ? { snapshot } : { reason }),
+ ...(snapshot
+ ? { snapshot }
+ : previous
+ ? { snapshot: previous, reason }
+ : { reason }),
};
- return snapshot;
+ return snapshot ?? previous;
})().finally(() => {
this.#usagePromise = undefined;
});
@@ -1011,8 +1024,9 @@ export class CodexStore {
/**
* The last successful fetch within the current window, served synchronously
- * while a refresh is in flight. A failed refresh clears it so stale usage is
- * never shown as current.
+ * while a refresh is in flight. A failed refresh retains the last known
+ * account value for the dedicated capacity key; health still records the
+ * structured failure reason.
*/
usageSnapshotCached(): UsageSnapshot | undefined {
return this.#usageCache?.snapshot;
@@ -1020,7 +1034,7 @@ export class CodexStore {
usageAvailabilityCached(): Availability {
const snapshot = this.#usageCache?.snapshot;
- return snapshot
+ return snapshot && !this.#usageCache?.reason
? ready(snapshot, snapshot.observedAt)
: unavailable(
this.#usageCache?.reason ?? "not-exposed",
diff --git a/src/lib/codex-ui-control.ts b/src/lib/codex-ui-control.ts
index 1fb2ee5..45e1c7a 100644
--- a/src/lib/codex-ui-control.ts
+++ b/src/lib/codex-ui-control.ts
@@ -14,7 +14,8 @@ export interface LivePickerState {
effort?: string;
}
-interface NativeControlResult extends LivePickerState {
+export interface NativeControlResult extends LivePickerState {
+ providerState?: import("./providers/types.js").ProviderObservation;
ok: boolean;
action: string;
requested?: string;
@@ -79,7 +80,7 @@ function ensureNativeHelperExecutable(executablePath: string): void {
}
}
-function invoke(
+export function invoke(
action:
| "model"
| "reasoning"
@@ -91,7 +92,9 @@ function invoke(
| "workflow"
| "route"
| "target-capture"
- | "target-check",
+ | "target-check"
+ | "provider-read"
+ | "claude",
requested?: string,
timeoutMs?: number,
threadId?: string,
@@ -263,6 +266,9 @@ export interface LiveComposerState {
}
const composerWitnesses = new Map();
+// Current desktop target proofs include the process-generation activity history
+// and window correlation; observed reads take about 1.5 s on a populated chat.
+const COMPOSER_READ_TIMEOUT_MS = 3_000;
type NativeInvoker = typeof invoke;
@@ -276,7 +282,7 @@ async function readLiveComposerStateUsing(
parsed = await invokeControl(
"composer-read",
cachedWitness,
- 1_200,
+ COMPOSER_READ_TIMEOUT_MS,
threadId,
);
} catch (error) {
@@ -289,7 +295,12 @@ async function readLiveComposerStateUsing(
throw error;
}
composerWitnesses.delete(threadId);
- parsed = await invokeControl("composer-read", undefined, 1_200, threadId);
+ parsed = await invokeControl(
+ "composer-read",
+ undefined,
+ COMPOSER_READ_TIMEOUT_MS,
+ threadId,
+ );
}
if (
typeof parsed.pendingInput !== "boolean" ||
diff --git a/src/lib/context.ts b/src/lib/context.ts
index 84777af..fb8342c 100644
--- a/src/lib/context.ts
+++ b/src/lib/context.ts
@@ -37,6 +37,22 @@ export function parseLatestContext(
return availability.state === "ready" ? availability.value : undefined;
}
+// A saved token event remains useful while a chat is idle. Keep its exact
+// thread identity and timestamp; freshness controls presentation, not existence.
+export function contextDisplayFromLines(
+ lines: string,
+ threadId: string,
+ now = Date.now(),
+): ContextSnapshot | undefined {
+ const value = parseLatestContext(lines, threadId, now, Infinity);
+ return value
+ ? {
+ ...value,
+ ...(now - value.observedAt > CONTEXT_STALE_MS ? { cached: true } : {}),
+ }
+ : undefined;
+}
+
export function contextAvailabilityFromLines(
lines: string,
threadId: string,
diff --git a/src/lib/desktop-active.ts b/src/lib/desktop-active.ts
index cc3605a..08ef2fe 100644
--- a/src/lib/desktop-active.ts
+++ b/src/lib/desktop-active.ts
@@ -22,6 +22,131 @@ export interface DesktopActivityWitness {
}
const desktopLogCursors = new Map();
+const hostActivityCache = new Map<
+ string,
+ { size: number; modifiedAt: number; state: HostViewActivity | undefined }
+>();
+
+interface HostViewActivity {
+ launchedAt: number;
+ threadId?: string;
+}
+
+export function parseDesktopRoute(text: string): {
+ observed: boolean;
+ threadId?: string;
+} {
+ const owners = new Set();
+ let observed = false,
+ malformed = false;
+ let threadId: string | undefined;
+ for (const line of text.split("\n")) {
+ if (
+ !line.includes(
+ "[electron-message-handler] IAB_LIFECYCLE received browser sidebar owner sync ",
+ )
+ )
+ continue;
+ observed = true;
+ threadId = undefined;
+ const fields = new Map();
+ for (const field of line.split(" ")) {
+ const split = field.indexOf("=");
+ if (split < 0) continue;
+ const key = field.slice(0, split);
+ if (fields.has(key)) malformed = true;
+ fields.set(key, field.slice(split + 1));
+ }
+ const window = fields.get("windowId"),
+ renderer = fields.get("originWebContentsId");
+ if (
+ !window ||
+ !renderer ||
+ !/^[1-9][0-9]*$/.test(window) ||
+ !/^[1-9][0-9]*$/.test(renderer)
+ ) {
+ malformed = true;
+ continue;
+ }
+ owners.add(`${window}:${renderer}`);
+ const id = fields
+ .get("ownerRoutePath")
+ ?.match(new RegExp(`^/local/(${CODEX_THREAD_ID})$`, "i"))?.[1]
+ ?.toLowerCase();
+ const conversation = fields.get("conversationId");
+ if (
+ id &&
+ (conversation?.toLowerCase() === id ||
+ new RegExp(`^client-new-thread:${CODEX_THREAD_ID}$`, "i").test(
+ conversation ?? "",
+ ))
+ )
+ threadId = id;
+ }
+ return {
+ observed,
+ ...(!malformed && owners.size === 1 && threadId ? { threadId } : {}),
+ };
+}
+
+/** Discovery only. Native code separately proves the live process, one content
+ * window, one composer, complete log provenance and unchanged view history. */
+export function parseHostViewActivity(
+ text: string,
+): HostViewActivity | undefined {
+ const lines = text.split("\n");
+ const startup = lines
+ .slice(0, 40)
+ .find((line) => line.includes(" info Launching app "));
+ if (!startup || !text.endsWith("\n")) return undefined;
+ const launchedAt = Date.parse(startup.split(" ")[0]!);
+ if (!Number.isFinite(launchedAt)) return undefined;
+ const active = new Set();
+ let observed = false;
+ for (const line of lines) {
+ if (
+ !line.includes(
+ "[host-app-server-manager] thread_stream_view_activity_changed ",
+ ) ||
+ line.includes("rendererWindow")
+ )
+ continue;
+ observed = true;
+ const id = line
+ .match(
+ new RegExp(`(?:^| )conversationId=(${CODEX_THREAD_ID})(?: |$)`, "i"),
+ )?.[1]
+ ?.toLowerCase();
+ const state = line.match(/(?:^| )active=(true|false)(?: |$)/)?.[1];
+ if (!id || !state) return { launchedAt };
+ if (state === "true") active.add(id);
+ else active.delete(id);
+ }
+ const route = parseDesktopRoute(text);
+ if (route.observed)
+ return {
+ launchedAt,
+ ...(route.threadId ? { threadId: route.threadId } : {}),
+ };
+ if (!observed) return undefined;
+ const threadId = active.size === 1 ? [...active][0] : undefined;
+ return { launchedAt, ...(threadId ? { threadId } : {}) };
+}
+
+function hostActivityInLog(
+ path: string,
+ modifiedAt: number,
+): HostViewActivity | undefined {
+ if (!/-\d+-t0-i1-\d{6}-0\.log$/.test(path)) return undefined;
+ const size = statSync(path).size;
+ if (size > 16 * 1024 * 1024) return undefined;
+ const cached = hostActivityCache.get(path);
+ if (cached?.size === size && cached.modifiedAt === modifiedAt)
+ return cached.state;
+ const state = parseHostViewActivity(readLogRange(path, 0, size));
+ hostActivityCache.set(path, { size, modifiedAt, state });
+ return state;
+}
export function parseActiveDesktopThreadId(
desktopLogTail: string,
@@ -180,6 +305,42 @@ export function activeDesktopThreadId(
}
});
candidates.sort((left, right) => right.modifiedAt - left.modifiedAt);
+ // A daily rollover keeps the process ID but creates a new log fragment.
+ // Reduce the complete startup + continuation history, never the newest file alone.
+ const groups = new Map();
+ for (const candidate of candidates) {
+ const key = candidate.path.match(
+ /(codex-desktop-.+-[0-9]+-t0-i1)-[0-9]{6}-0\.log$/,
+ )?.[1];
+ if (!key) continue;
+ const group = groups.get(key) ?? [];
+ group.push(candidate);
+ groups.set(key, group);
+ }
+ const hostViews = [...groups.values()]
+ .map((group) => {
+ group.sort((a, b) => a.path.localeCompare(b.path));
+ if (group.length === 1)
+ return hostActivityInLog(group[0]!.path, group[0]!.modifiedAt);
+ try {
+ let bytes = 0;
+ let text = "";
+ for (const { path } of group) {
+ const size = statSync(path).size;
+ bytes += size;
+ if (bytes > 16 * 1024 * 1024) return undefined;
+ const chunk = readLogRange(path, 0, size);
+ if (!chunk.endsWith("\n")) return undefined;
+ text += chunk;
+ }
+ return parseHostViewActivity(text);
+ } catch {
+ return undefined;
+ }
+ })
+ .filter((state): state is HostViewActivity => !!state)
+ .sort((a, b) => b.launchedAt - a.launchedAt);
+ if (hostViews.length) return hostViews[0]!.threadId;
const newest = candidates
.slice(0, 8)
.map((candidate) => ({
diff --git a/src/lib/lucide-paths.ts b/src/lib/lucide-paths.ts
index 38b810c..4cbb56f 100644
--- a/src/lib/lucide-paths.ts
+++ b/src/lib/lucide-paths.ts
@@ -8,10 +8,10 @@ export const LUCIDE_PATHS: Record = {
"status-unread":
' ',
"status-thinking":
- ' ',
+ ' ',
"status-running": ' ',
"status-needs-input":
- ' ',
+ ' ',
"status-error":
' ',
"status-off":
@@ -52,7 +52,7 @@ export const LUCIDE_PATHS: Record = {
model:
' ',
reasoning:
- ' ',
+ ' ',
clock: ' ',
settings:
' ',
@@ -97,6 +97,8 @@ export const LUCIDE_PATHS: Record = {
enter: ' ',
"cloud-upload":
' ',
+ shield:
+ ' ',
yolo: ' ',
yeet: ' ',
voice:
@@ -107,7 +109,7 @@ export const LUCIDE_PATHS: Record = {
release:
' ',
explain:
- ' ',
+ ' ',
document:
' ',
optimize: ' ',
diff --git a/src/lib/model.ts b/src/lib/model.ts
index 84c1e59..2088e00 100644
--- a/src/lib/model.ts
+++ b/src/lib/model.ts
@@ -105,7 +105,7 @@ export function supportedModelOptions(parsed: unknown): ModelOption[] {
slug: model.slug,
label: family.toUpperCase(),
displayName,
- pickerLabel: family[0]!.toUpperCase() + family.slice(1),
+ pickerLabel: `${model.slug.slice(4, -(family.length + 1))} ${family[0]!.toUpperCase() + family.slice(1)}`,
defaultReasoning: supportedReasoning.includes(defaultReasoning)
? defaultReasoning
: supportedReasoning[0]!,
diff --git a/src/lib/providers/claude-ptt.ts b/src/lib/providers/claude-ptt.ts
new file mode 100644
index 0000000..a8484be
--- /dev/null
+++ b/src/lib/providers/claude-ptt.ts
@@ -0,0 +1,105 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ sameTarget,
+ type ProviderObservation,
+ type TargetIdentity,
+} from "./types.js";
+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+let lease:
+ | {
+ target: TargetIdentity;
+ child: ChildProcessWithoutNullStreams;
+ stopped: Promise;
+ }
+ | undefined;
+export async function startClaudePtt(
+ target: TargetIdentity,
+): Promise {
+ if (lease) await stopClaudePtt(lease.target);
+ const child = spawn(
+ process.execPath,
+ [resolve(root, "scripts/ptt-guard.mjs")],
+ {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: {
+ ...process.env,
+ STREAMDECK_PTT_TARGET_RUNNER:
+ process.env.CODEX_UI_CONTROL ?? resolve(root, "bin/codex-ui-control"),
+ STREAMDECK_PTT_CLAUDE_TARGET: JSON.stringify(target),
+ },
+ },
+ );
+ let ready!: (value: ProviderObservation) => void,
+ failed!: (error: Error) => void;
+ const started = new Promise((yes, no) => {
+ ready = yes;
+ failed = no;
+ });
+ let result: ProviderObservation | undefined,
+ buffer = "",
+ errorText = "";
+ const timer = setTimeout(() => {
+ child.stdin.end();
+ failed(new Error("Claude recording timed out"));
+ }, 12000);
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (text: string) => {
+ buffer += text;
+ let end;
+ while ((end = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, end);
+ buffer = buffer.slice(end + 1);
+ try {
+ if (line.startsWith("CLAUDE_READY ")) {
+ clearTimeout(timer);
+ ready(JSON.parse(line.slice(13)));
+ }
+ if (line.startsWith("CLAUDE_STOPPED "))
+ result = JSON.parse(line.slice(15));
+ } catch {
+ child.stdin.end();
+ failed(new Error("Invalid recording result"));
+ }
+ }
+ if (buffer.length > 65536) {
+ child.stdin.end();
+ failed(new Error("Invalid recording output"));
+ }
+ });
+ child.stderr.on("data", (text: string) => {
+ errorText = (errorText + text).slice(-2000);
+ });
+ const stopped = new Promise((yes, no) => {
+ child.once("error", (error) => {
+ clearTimeout(timer);
+ failed(error);
+ no(error);
+ });
+ child.once("close", (code) => {
+ clearTimeout(timer);
+ if (code === 0 && result) yes(result);
+ else no(new Error(errorText || "Claude recording stopped unexpectedly"));
+ failed(new Error(errorText || "Claude recording ended before starting"));
+ });
+ });
+ // A max-hold or parent-loss stop can precede the user's key-up.
+ void stopped.catch(() => undefined);
+ lease = { target, child, stopped };
+ return started;
+}
+export async function stopClaudePtt(
+ target: TargetIdentity,
+): Promise {
+ const current = lease;
+ if (!current || !sameTarget(current.target, target))
+ throw new Error("No matching recording");
+ current.child.stdin.end();
+ try {
+ return await current.stopped;
+ } finally {
+ if (lease === current) lease = undefined;
+ }
+}
diff --git a/src/lib/providers/claude-reset-status.ts b/src/lib/providers/claude-reset-status.ts
new file mode 100644
index 0000000..58e0b98
--- /dev/null
+++ b/src/lib/providers/claude-reset-status.ts
@@ -0,0 +1,101 @@
+import { open } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+export interface ClaudeResetHint {
+ accountId: string;
+ checkedAt: number;
+ validUntil: number;
+}
+export interface ClaudeResetMetadata {
+ accountId?: string;
+ hint?: ClaudeResetHint;
+}
+const uuid = (value: unknown): value is string =>
+ typeof value === "string" &&
+ /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value);
+const record = (v: unknown): Record =>
+ v !== null && typeof v === "object" && !Array.isArray(v)
+ ? (v as Record)
+ : {};
+
+// This is only evidence that SOME reset exists. It cannot identify its type,
+// count, or redeemability. Never turn false/missing/expired into zero credits.
+export function parseClaudeResetMetadata(
+ desktop: unknown,
+ cli: unknown,
+ now = Date.now(),
+): ClaudeResetMetadata {
+ const account = record(desktop).lastKnownAccountUuid;
+ if (!uuid(account)) return {};
+ const accountId = account.toLowerCase();
+ const result: ClaudeResetMetadata = { accountId };
+ const config = record(cli);
+ const owner = record(config.oauthAccount).accountUuid;
+ const cache = record(config.unusedLimitResetStatusCache);
+ const checkedAt = cache.checkedAt,
+ validUntil = cache.validUntil;
+ if (
+ !uuid(owner) ||
+ owner.toLowerCase() !== accountId ||
+ !uuid(cache.accountUuid) ||
+ cache.accountUuid.toLowerCase() !== accountId ||
+ cache.holdsUnusedReset !== true ||
+ typeof checkedAt !== "number" ||
+ !Number.isFinite(checkedAt) ||
+ typeof validUntil !== "number" ||
+ !Number.isFinite(validUntil) ||
+ checkedAt <= 0 ||
+ checkedAt > now ||
+ validUntil <= now ||
+ validUntil <= checkedAt ||
+ validUntil - checkedAt > 7 * 86400000
+ )
+ return result;
+ result.hint = { accountId, checkedAt, validUntil };
+ return result;
+}
+
+async function boundedJson(path: string): Promise {
+ const file = await open(path, "r");
+ try {
+ const max = 4 * 1024 * 1024;
+ if ((await file.stat()).size > max) return undefined;
+ const buffer = Buffer.alloc(max + 1);
+ let size = 0;
+ while (size <= max) {
+ const { bytesRead } = await file.read(
+ buffer,
+ size,
+ buffer.length - size,
+ null,
+ );
+ if (!bytesRead) break;
+ size += bytesRead;
+ }
+ return size > max
+ ? undefined
+ : JSON.parse(buffer.subarray(0, size).toString("utf8"));
+ } finally {
+ await file.close();
+ }
+}
+export async function readClaudeResetMetadata(
+ home = homedir(),
+): Promise {
+ const desktopPath = join(
+ home,
+ "Library/Application Support/Claude/config.json",
+ );
+ const [desktop, cli] = await Promise.all([
+ boundedJson(desktopPath).catch(() => undefined),
+ boundedJson(join(home, ".claude.json")).catch(() => undefined),
+ ]);
+ const result = parseClaudeResetMetadata(desktop, cli);
+ // Reject an account switch during the read. No credential fields are used.
+ const after = parseClaudeResetMetadata(
+ await boundedJson(desktopPath).catch(() => undefined),
+ undefined,
+ );
+ return after.accountId === result.accountId ? result : {};
+}
diff --git a/src/lib/providers/claude.ts b/src/lib/providers/claude.ts
new file mode 100644
index 0000000..5cff3e7
--- /dev/null
+++ b/src/lib/providers/claude.ts
@@ -0,0 +1,83 @@
+import { startClaudePtt, stopClaudePtt } from "./claude-ptt.js";
+import { ResetCache, validResetBalance } from "./reset-cache.js";
+import { readClaudeResetMetadata } from "./claude-reset-status.js";
+import { encodeNativePayload, invoke } from "../codex-ui-control.js";
+import {
+ freshObservation,
+ sameTarget,
+ type DesktopProvider,
+ type ProviderObservation,
+ type ProviderReply,
+ type ProviderRequest,
+} from "./types.js";
+
+export class ClaudeProvider implements DesktopProvider {
+ readonly id = "claude" as const;
+ constructor(
+ private readonly call = invoke,
+ private readonly readResetMetadata = readClaudeResetMetadata,
+ private readonly resetCache = new ResetCache(),
+ ) {}
+ async read(): Promise {
+ const reply = await this.call("provider-read", undefined, 8000);
+ if (!reply.providerState)
+ throw new Error("Provider helper returned no observation");
+ const metadata = await this.readResetMetadata();
+ let cachedResets;
+ if (metadata.accountId) {
+ const balance = {
+ accountId: metadata.accountId,
+ weekly: reply.providerState.weeklyResetsAvailable,
+ fable: reply.providerState.fableResetsAvailable,
+ observedAt: reply.providerState.observedAt,
+ };
+ if (
+ reply.providerState.foreground === "claude" &&
+ freshObservation(reply.providerState) &&
+ validResetBalance(balance, metadata.accountId)
+ ) {
+ await this.resetCache.write(balance).catch(() => undefined);
+ }
+ cachedResets = await this.resetCache.read(metadata.accountId);
+ }
+ return {
+ ...reply.providerState,
+ ...(cachedResets ? { cachedResets } : {}),
+ ...(metadata.accountId ? { claudeAccountId: metadata.accountId } : {}),
+ ...(metadata.hint ? { resetAvailabilityHint: metadata.hint } : {}),
+ };
+ }
+ async perform(request: ProviderRequest): Promise {
+ if (request.target.provider !== this.id)
+ throw new Error("Wrong provider target");
+ const before =
+ request.operation === "dictation-stop" ? undefined : await this.read();
+ if (
+ request.operation !== "dictation-stop" &&
+ (!before ||
+ !freshObservation(before) ||
+ before.foreground !== this.id ||
+ !sameTarget(before.target, request.target))
+ ) {
+ throw new Error("Target changed; select again");
+ }
+ if (request.operation === "dictate") return startClaudePtt(request.target);
+ if (request.operation === "dictation-stop")
+ return stopClaudePtt(request.target);
+ const reply = await this.call(
+ "claude",
+ encodeNativePayload(request),
+ request.operation === "send" &&
+ request.target.environment === "cloud" &&
+ request.target.sessionId.startsWith("draft:")
+ ? 30000
+ : ["plan", "permission-cycle", "model"].includes(request.operation)
+ ? 15000
+ : 10000,
+ );
+ if (!reply.providerState)
+ throw new Error("Claude returned no verified result");
+ return reply.providerState as ProviderReply;
+ }
+}
+export const claudeProvider = new ClaudeProvider();
diff --git a/src/lib/providers/codex.ts b/src/lib/providers/codex.ts
new file mode 100644
index 0000000..bae5aa2
--- /dev/null
+++ b/src/lib/providers/codex.ts
@@ -0,0 +1,38 @@
+import { SingletonAction } from "@elgato/streamdeck";
+import { codexStore } from "../codex-store.js";
+
+/** Preserve the mature Codex implementation behind an event adapter. */
+export class CodexProvider {
+ readonly id = "codex" as const;
+ constructor(
+ readonly action: SingletonAction,
+ include: (id: string) => boolean,
+ ) {
+ const getActions = Object.getOwnPropertyDescriptor(
+ SingletonAction.prototype,
+ "actions",
+ )!.get!;
+ Object.defineProperty(action, "actions", {
+ get: () =>
+ getActions
+ .call(action)
+ .filter((visible: { id: string }) => include(visible.id)),
+ });
+ }
+ identity(): string {
+ const thread = codexStore.focusedThread();
+ const composer = codexStore.liveComposerState();
+ return JSON.stringify([
+ "codex",
+ composer?.rendererWindowId ?? "",
+ thread?.id ?? "",
+ ]);
+ }
+ async event(name: string, event: any): Promise {
+ const handler = (this.action as any)[name];
+ if (handler) await handler.call(this.action, event);
+ }
+ async refresh(): Promise {
+ await (this.action as any).refreshAll?.();
+ }
+}
diff --git a/src/lib/providers/presentation.ts b/src/lib/providers/presentation.ts
new file mode 100644
index 0000000..1897782
--- /dev/null
+++ b/src/lib/providers/presentation.ts
@@ -0,0 +1,33 @@
+import type { ProviderId } from "./types.js";
+const badges = new Map();
+export function setProviderBadge(
+ id: string,
+ provider?: ProviderId | "auto",
+): void {
+ if (provider) badges.set(id, provider);
+ else badges.delete(id);
+}
+export function badgeFor(id?: string): string | undefined {
+ const provider = id ? badges.get(id) : undefined;
+ return provider === "claude"
+ ? "CLAUDE"
+ : provider === "codex"
+ ? "CODEX"
+ : provider === "auto"
+ ? "AUTO"
+ : undefined;
+}
+export function badgeImage(image: string, label?: string): string {
+ if (!label || !image.startsWith("data:image/svg+xml;base64,")) return image;
+ const svg = Buffer.from(image.split(",")[1]!, "base64").toString("utf8");
+ const badge = `${label} `;
+ return (
+ "data:image/svg+xml;base64," +
+ Buffer.from(svg.replace("", badge + "")).toString("base64")
+ );
+}
+export function badgeFeedback(feedback: unknown, label?: string): unknown {
+ if (!label || !feedback || typeof feedback !== "object") return feedback;
+ const value = feedback as Record;
+ return { ...value, title: `${label} · ${value.title ?? ""}` };
+}
diff --git a/src/lib/providers/reset-cache.ts b/src/lib/providers/reset-cache.ts
new file mode 100644
index 0000000..f8914dc
--- /dev/null
+++ b/src/lib/providers/reset-cache.ts
@@ -0,0 +1,67 @@
+import { mkdir, open, rename, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+export interface ResetBalance {
+ accountId: string;
+ weekly: number;
+ fable: number;
+ observedAt: number;
+}
+export function validResetBalance(
+ value: unknown,
+ accountId: string,
+ now = Date.now(),
+): value is ResetBalance {
+ const row = value as Partial | null;
+ return (
+ !!row &&
+ typeof row === "object" &&
+ /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(accountId) &&
+ row.accountId === accountId &&
+ [row.weekly, row.fable].every(
+ (n) => Number.isInteger(n) && n! >= 0 && n! <= 999,
+ ) &&
+ typeof row.observedAt === "number" &&
+ Number.isFinite(row.observedAt) &&
+ row.observedAt > 0 &&
+ row.observedAt <= now
+ );
+}
+// Our own cache, never Claude's database. A saved value is always presented as
+// CACHED until the visible Usage surface supplies another account-matched read.
+export class ResetCache {
+ constructor(
+ private readonly path = join(
+ homedir(),
+ "Library/Application Support/com.todd.streamdeckcodex/claude-resets.json",
+ ),
+ ) {}
+ async read(accountId: string): Promise {
+ try {
+ const file = await open(this.path, "r");
+ let value: unknown;
+ try {
+ if ((await file.stat()).size > 4096) return undefined;
+ const buffer = Buffer.alloc(4097);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ if (bytesRead > 4096) return undefined;
+ value = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8"));
+ } finally {
+ await file.close();
+ }
+ return validResetBalance(value, accountId) ? value : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ async write(value: ResetBalance): Promise {
+ if (!validResetBalance(value, value.accountId)) return;
+ const previous = await this.read(value.accountId);
+ if (previous && previous.observedAt > value.observedAt) return;
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
+ const temporary = `${this.path}.${process.pid}.tmp`;
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });
+ await rename(temporary, this.path);
+ }
+}
diff --git a/src/lib/providers/router.ts b/src/lib/providers/router.ts
new file mode 100644
index 0000000..a9f880a
--- /dev/null
+++ b/src/lib/providers/router.ts
@@ -0,0 +1,944 @@
+import streamDeck, { SingletonAction, type Action } from "@elgato/streamdeck";
+import { claudeProvider } from "./claude.js";
+import { CodexProvider } from "./codex.js";
+import {
+ freshObservation,
+ resolveProvider,
+ providerSetting,
+ targetKey,
+ type ProviderObservation,
+ type ProviderOption,
+ type ProviderId,
+ type ProviderSetting,
+ type TargetIdentity,
+} from "./types.js";
+import { setProviderBadge } from "./presentation.js";
+import { renderFeedback, renderKey, resetRender } from "../render-cache.js";
+import {
+ keycapSvg,
+ modeKeySvg,
+ commandKeySvg,
+ contextKeySvg,
+ svgDataUrl,
+ usageKeySvg,
+ resetAvailabilityKeySvg,
+} from "../visuals.js";
+import { COMMANDS, DIAL_COMMANDS, dialCommandAt } from "../commands.js";
+import { WORKFLOWS } from "../workflows.js";
+import { keycapWorkflow } from "../keycap-workflows.js";
+import {
+ claudeUsage,
+ claudeUsageLabel,
+ type ClaudeUsage,
+} from "./telemetry.js";
+
+const priorModes = new Map();
+let observation: ProviderObservation = { observedAt: 0, reason: "NO DATA" };
+let lastClaudeWeekly: ClaudeUsage | undefined;
+let resetAccountId: string | undefined;
+let lastClaudeResets:
+ { weekly: number; fable: number; observedAt: number } | undefined;
+let lastClaudeContext:
+ | {
+ usedPercent: number;
+ observedAt: number;
+ targetKey: string;
+ sessionId: string;
+ }
+ | undefined;
+let observationRevision = 0;
+let tail: Promise = Promise.resolve();
+/** All menu transactions and refreshes share one queue; no overlapping menus. */
+export function serializeProviders(work: () => Promise): Promise {
+ const next = tail.then(work, work);
+ tail = next.catch(() => undefined);
+ return next;
+}
+function rememberNonPlanMode(): void {
+ if (
+ observation.foreground === "claude" &&
+ observation.target &&
+ freshObservation(observation) &&
+ observation.permission &&
+ !["Plan", "Plan mode"].includes(observation.permission)
+ ) {
+ priorModes.set(targetKey(observation.target), observation.permission);
+ }
+}
+export async function observeProviders(): Promise {
+ try {
+ observation = await claudeProvider.read();
+ if (observation.claudeAccountId !== resetAccountId) {
+ lastClaudeResets = undefined;
+ lastClaudeWeekly = undefined;
+ lastClaudeContext = undefined;
+ resetAccountId = observation.claudeAccountId;
+ }
+ if (
+ observation.cachedResets?.accountId === resetAccountId &&
+ observation.cachedResets
+ ) {
+ lastClaudeResets = observation.cachedResets;
+ }
+ if (
+ observation.foreground === "claude" &&
+ freshObservation(observation) &&
+ [
+ observation.weeklyResetsAvailable,
+ observation.fableResetsAvailable,
+ ].every((n) => Number.isInteger(n) && n! >= 0 && n! <= 999)
+ ) {
+ lastClaudeResets = {
+ weekly: observation.weeklyResetsAvailable!,
+ fable: observation.fableResetsAvailable!,
+ observedAt: observation.observedAt,
+ };
+ }
+ if (
+ observation.foreground === "claude" &&
+ (observation.target || observation.readOnlyScope) &&
+ freshObservation(observation)
+ ) {
+ lastClaudeWeekly = claudeUsage(observation);
+ }
+ if (observation.foreground === "claude" && observation.readOnlyScope)
+ lastClaudeContext = undefined;
+ if (observation.foreground === "claude" && observation.target) {
+ const currentTargetKey = targetKey(observation.target);
+ if (
+ lastClaudeContext?.targetKey !== currentTargetKey ||
+ observation.contextAvailability === "empty"
+ ) {
+ lastClaudeContext = undefined;
+ }
+ if (typeof observation.contextUsedPercent === "number") {
+ lastClaudeContext = {
+ usedPercent: observation.contextUsedPercent,
+ observedAt: observation.observedAt,
+ targetKey: currentTargetKey,
+ sessionId: observation.target.sessionId,
+ };
+ }
+ }
+ rememberNonPlanMode();
+ } catch {
+ observation = { observedAt: Date.now(), reason: "NO DATA" };
+ }
+ observationRevision += 1;
+}
+
+type Settings = Record & { provider?: ProviderSetting };
+type Visible = {
+ action: Action;
+ settings: Settings;
+ provider?: string | undefined;
+ identity?: string;
+ model?: string | undefined;
+ preview?: { identity: string; options: ProviderOption[]; index: number };
+ optionScale?: { identity: string; options: ProviderOption[] };
+ commandIndex?: number;
+ usageView?: number;
+ error?: string;
+};
+
+type ProviderActionOptions = {
+ kind?: string;
+ provider?: ProviderId;
+};
+
+export class ProviderAction extends SingletonAction {
+ override readonly manifestId: string;
+ readonly #visible = new Map();
+ readonly #appearances = new Map();
+ readonly #codex: CodexProvider;
+ readonly #kindOverride: string | undefined;
+ readonly #providerOverride: ProviderId | undefined;
+ // Key-up must return to the adapter that received key-down, even after focus changes.
+ readonly #held = new Map();
+ readonly #claudeHeld = new Map();
+ readonly #pressed = new Set();
+ constructor(
+ action: SingletonAction,
+ options: ProviderActionOptions = {},
+ ) {
+ super();
+ this.manifestId = action.manifestId!;
+ this.#kindOverride = options.kind;
+ this.#providerOverride = options.provider;
+ this.#codex = new CodexProvider(
+ action,
+ (id) => this.#visible.get(id)?.provider === "codex",
+ );
+ }
+ onWillAppear = (ev: any) => this.route("onWillAppear", ev);
+ onWillDisappear = (ev: any) => this.route("onWillDisappear", ev);
+ onDidReceiveSettings = (ev: any) => this.route("onDidReceiveSettings", ev);
+ onKeyDown = (ev: any) => this.route("onKeyDown", ev);
+ onKeyUp = (ev: any) => this.route("onKeyUp", ev);
+ onDialDown = (ev: any) => this.route("onDialDown", ev);
+ onDialUp = (ev: any) => this.route("onDialUp", ev);
+ onDialRotate = (ev: any) => this.route("onDialRotate", ev);
+ onTouchTap = (ev: any) => this.route("onTouchTap", ev);
+
+ private update(entry: Visible): boolean {
+ const foreground = freshObservation(observation)
+ ? observation.foreground
+ : undefined;
+ const provider =
+ this.#providerOverride ??
+ resolveProvider(entry.settings.provider, foreground);
+ const identity =
+ provider === "codex"
+ ? this.#codex.identity()
+ : targetKey(observation.target);
+ const changed = entry.provider !== provider || entry.identity !== identity;
+ if (
+ changed ||
+ (provider === "claude" &&
+ this.kind() === "reasoning" &&
+ entry.model !== observation.model)
+ ) {
+ delete entry.preview;
+ delete entry.optionScale;
+ delete entry.error;
+ }
+ entry.provider = provider;
+ entry.identity = identity;
+ entry.model = observation.model;
+ setProviderBadge(
+ entry.action.id,
+ this.#providerOverride
+ ? undefined
+ : entry.settings.provider === undefined
+ ? undefined
+ : (provider ?? "auto"),
+ );
+ return changed;
+ }
+
+ private route(name: string, ev: any): Promise {
+ // Every encoder commits on release. Neither adapter uses press-down;
+ // queueing a read here can expire the real release behind slow Accessibility.
+ if (name === "onDialDown") return Promise.resolve();
+ const receivedAt = Date.now();
+ const receivedRevision = observationRevision;
+ const appearance = name === "onWillAppear" ? {} : undefined;
+ if (appearance) this.#appearances.set(ev.action.id, appearance);
+ if (name === "onWillDisappear") this.#appearances.delete(ev.action.id);
+ const obsolete = () =>
+ appearance !== undefined &&
+ this.#appearances.get(ev.action.id) !== appearance;
+ const readingOnly = [
+ "health",
+ "usage",
+ "context",
+ "claude-weekly",
+ "claude-context",
+ ].includes(this.kind());
+ const receivedIdentity = this.#visible.get(ev.action.id)?.identity;
+ const settingsAtReceipt =
+ ev.payload.settings ?? this.#visible.get(ev.action.id)?.settings ?? {};
+ const pinnedCodex = this.#providerOverride
+ ? this.#providerOverride === "codex"
+ : providerSetting(settingsAtReceipt.provider) === "codex";
+ if (name === "onKeyDown") this.#pressed.add(ev.action.id);
+ if (name === "onKeyUp") {
+ this.#pressed.delete(ev.action.id);
+ const claudeTarget = this.#claudeHeld.get(ev.action.id);
+ if (claudeTarget) {
+ this.#claudeHeld.delete(ev.action.id);
+ return serializeProviders(async () => {
+ try {
+ await claudeProvider.perform({
+ operation: "dictation-stop",
+ target: claudeTarget,
+ });
+ } catch (error) {
+ streamDeck.logger.warn(`Claude PTT release: ${error}`);
+ await ev.action.showAlert();
+ }
+ });
+ }
+ const heldSettings = this.#held.get(ev.action.id);
+ if (heldSettings) {
+ this.#held.delete(ev.action.id);
+ return this.#codex.event(name, {
+ ...ev,
+ payload: { ...ev.payload, settings: heldSettings },
+ });
+ }
+ }
+ const work = async () => {
+ if (obsolete()) return;
+ if (
+ !pinnedCodex &&
+ !readingOnly &&
+ !(
+ this.kind() === "reasoning" &&
+ observation.readOnlyScope &&
+ observation.effort === "Fixed"
+ ) &&
+ ["onKeyDown", "onDialRotate", "onDialUp"].includes(name) &&
+ Date.now() - receivedAt > 2000
+ ) {
+ await ev.action.showAlert();
+ return;
+ }
+ let entry = this.#visible.get(ev.action.id);
+ if (!entry || appearance) {
+ entry = { action: ev.action, settings: ev.payload.settings ?? {} };
+ this.#visible.set(ev.action.id, entry);
+ }
+ if (ev.payload.settings) entry.settings = ev.payload.settings;
+ if (name === "onWillDisappear") {
+ // Remove visibility before yielding so a later appearance cannot be
+ // erased by this page's asynchronous PTT cleanup.
+ this.#visible.delete(ev.action.id);
+ setProviderBadge(ev.action.id);
+ this.#held.delete(ev.action.id);
+ this.#pressed.delete(ev.action.id);
+ const held = this.#claudeHeld.get(ev.action.id);
+ this.#claudeHeld.delete(ev.action.id);
+ await this.#codex.event(name, ev);
+ if (held) {
+ await claudeProvider
+ .perform({ operation: "dictation-stop", target: held })
+ .catch((error) =>
+ streamDeck.logger.warn(`Claude PTT cleanup: ${error}`),
+ );
+ }
+ return;
+ }
+ // Read fresh foreground state at every input boundary. This also prevents a
+ // cached automatic binding from opening Codex after switching to another app.
+ if (
+ !pinnedCodex &&
+ !["onDidReceiveSettings", "onTouchTap"].includes(name) &&
+ // A page's controls share the observation completed while they were
+ // queued. Actual input events always revalidate their target.
+ !(
+ appearance &&
+ observationRevision !== receivedRevision &&
+ freshObservation(observation)
+ )
+ )
+ await observeProviders();
+ if (obsolete()) return;
+ if (appearance) {
+ await resetRender(ev.action);
+ // Keep the full Extra High label readable on Plus.
+ if (this.kind() === "reasoning" && ev.action.isDial())
+ await ev.action.setFeedback({ value: { font: { size: 16 } } });
+ }
+ const changed = this.update(entry);
+ if (name === "onDidReceiveSettings") {
+ delete entry.preview;
+ delete entry.commandIndex;
+ }
+ // Reading a status key never requires a mutation target. Refresh above,
+ // then render the fresh/cached/unavailable reading even after app changes.
+ if (
+ readingOnly &&
+ entry.provider !== "codex" &&
+ ["onKeyDown", "onDialUp", "onDialRotate"].includes(name)
+ ) {
+ delete entry.error;
+ if (this.kind() === "claude-weekly" && name === "onKeyDown")
+ entry.usageView =
+ ((entry.usageView ?? 0) + 1) %
+ (lastClaudeResets || !observation.resetAvailabilityHint ? 3 : 2);
+ await this.draw(entry);
+ return;
+ }
+ if (
+ !pinnedCodex &&
+ receivedIdentity &&
+ entry.identity !== receivedIdentity &&
+ ["onKeyDown", "onDialRotate", "onDialUp"].includes(name)
+ ) {
+ await ev.action.showAlert();
+ if (entry.provider !== "codex") await this.draw(entry);
+ return;
+ }
+ if (entry.provider === "codex") {
+ if (changed && name !== "onWillAppear") {
+ const settings = { ...entry.settings };
+ delete settings.selectedModel;
+ delete settings.selectedLevel;
+ delete settings.appliedModel;
+ delete settings.appliedLevel;
+ await this.#codex.event("onWillAppear", {
+ ...ev,
+ payload: { ...ev.payload, settings },
+ });
+ if (name === "onDialUp") {
+ await ev.action.showAlert();
+ return;
+ }
+ }
+ if (name === "onKeyDown") {
+ if (
+ this.kind() === "command" &&
+ this.command(entry)?.id === "dictate" &&
+ !this.#pressed.has(ev.action.id)
+ )
+ return;
+ this.#held.set(ev.action.id, { ...entry.settings });
+ }
+ await this.#codex.event(name, ev);
+ return;
+ }
+ if (["onKeyUp", "onDialDown", "onTouchTap"].includes(name)) return;
+ try {
+ delete entry.error;
+ if (["onKeyDown", "onDialUp", "onDialRotate"].includes(name)) {
+ if (!entry.provider) throw new Error("NO APP");
+ if (observation.foreground !== "claude")
+ throw new Error("BACKGROUND");
+ if (!observation.target)
+ throw new Error(observation.reason ?? "NO CHAT");
+ await this.claudeEvent(entry, name, ev.payload.ticks ?? 0);
+ }
+ } catch (error) {
+ entry.error =
+ error instanceof Error && error.message.length <= 24
+ ? error.message
+ : "UNAVAILABLE";
+ streamDeck.logger.warn(
+ `Claude ${this.manifestId.split(".").at(-1)}: ${error instanceof Error ? error.message : "unavailable"}`,
+ );
+ await ev.action.showAlert();
+ }
+ await this.draw(entry);
+ };
+ // Existing Codex-only profiles retain their original event latency. In
+ // particular, PTT release must never wait behind a Claude menu observation.
+ return pinnedCodex || name === "onWillDisappear"
+ ? work()
+ : serializeProviders(work);
+ }
+
+ async refreshAll(): Promise {
+ for (const entry of this.#visible.values()) {
+ const changed = this.update(entry);
+ if (entry.provider === "codex") {
+ if (changed) {
+ const settings = { ...entry.settings };
+ delete settings.selectedModel;
+ delete settings.selectedLevel;
+ await this.#codex.event("onWillAppear", {
+ action: entry.action,
+ payload: { settings },
+ });
+ }
+ } else await this.draw(entry);
+ }
+ await this.#codex.refresh();
+ }
+
+ private kind(): string {
+ return this.#kindOverride ?? this.manifestId.split(".").at(-1)!;
+ }
+ private command(entry: Visible) {
+ if (entry.action.isDial()) {
+ const named = DIAL_COMMANDS.findIndex(
+ (c) => c.id === entry.settings.commandId,
+ );
+ return dialCommandAt(
+ entry.commandIndex ??
+ (named >= 0 ? named : Number(entry.settings.commandIndex ?? 0)),
+ );
+ }
+ const id =
+ entry.settings.commandId ??
+ COMMANDS[entry.settings.commandIndex ?? 0]?.id;
+ return COMMANDS.find(
+ (c) =>
+ c.id ===
+ (id === "approve" ? "accept" : id === "decline" ? "reject" : id),
+ );
+ }
+ private async perform(operation: string, value?: string) {
+ if (!observation.target) throw new Error("NO CHAT");
+ const key = targetKey(observation.target);
+ rememberNonPlanMode();
+ if (
+ operation === "plan" &&
+ ["Plan", "Plan mode"].includes(observation.permission ?? "")
+ ) {
+ value = priorModes.get(key);
+ }
+ const reply = await claudeProvider.perform({
+ operation,
+ ...(value === undefined ? {} : { value }),
+ target: observation.target,
+ });
+ observation = reply;
+ return reply;
+ }
+ private async performCommand(
+ entry: Visible,
+ operation: string,
+ ): Promise {
+ if (operation !== "dictate") {
+ await this.perform(operation);
+ return;
+ }
+ if (!this.#pressed.has(entry.action.id)) return;
+ const target = observation.target!;
+ await this.perform("dictate");
+ if (this.#pressed.has(entry.action.id))
+ this.#claudeHeld.set(entry.action.id, target);
+ else await claudeProvider.perform({ operation: "dictation-stop", target });
+ }
+ private async claudeEvent(
+ entry: Visible,
+ name: string,
+ ticks: number,
+ ): Promise {
+ const kind = this.kind();
+ if (
+ kind === "reasoning" &&
+ observation.readOnlyScope &&
+ observation.effort === "Fixed"
+ )
+ return;
+ if (kind === "model" || kind === "reasoning") {
+ if (name === "onDialRotate") {
+ if (!entry.preview) {
+ const reply = await this.perform(`${kind}-options`);
+ if (!reply.options?.length) throw new Error("UNSUPPORTED");
+ const current = kind === "model" ? reply.model : reply.effort;
+ entry.preview = {
+ identity: targetKey(reply.target),
+ options: reply.options,
+ index: Math.max(
+ 0,
+ reply.options.findIndex(
+ (o) => o.value === current || o.label === current,
+ ),
+ ),
+ };
+ entry.optionScale = {
+ identity: entry.preview.identity,
+ options: reply.options,
+ };
+ }
+ const p = entry.preview;
+ p.index =
+ (((p.index + Math.sign(ticks)) % p.options.length) +
+ p.options.length) %
+ p.options.length;
+ } else if (name === "onDialUp") {
+ const p = entry.preview;
+ if (!p || p.identity !== targetKey(observation.target))
+ throw new Error("SELECT AGAIN");
+ await this.perform(kind, p.options[p.index]!.value);
+ delete entry.preview;
+ }
+ return;
+ }
+ if (kind === "workflow" && name === "onDialRotate") {
+ const index = Math.max(
+ 0,
+ WORKFLOWS.findIndex((w) => w.id === entry.settings.workflowId),
+ );
+ const next =
+ (index + Math.sign(ticks) + WORKFLOWS.length) % WORKFLOWS.length;
+ entry.settings = {
+ ...entry.settings,
+ workflowId: WORKFLOWS[next]!.id,
+ workflowIndex: next,
+ };
+ await entry.action.setSettings(entry.settings);
+ return;
+ }
+ if (kind === "command" && name === "onDialRotate") {
+ const available = DIAL_COMMANDS.filter((c) =>
+ observation.capabilities?.includes(c.id),
+ );
+ if (!available.length) throw new Error("NO ACTIONS");
+ const current = available.findIndex(
+ (c) => c.id === this.command(entry)?.id,
+ );
+ const next =
+ (current + Math.sign(ticks) + available.length) % available.length;
+ entry.commandIndex = DIAL_COMMANDS.indexOf(available[next]!);
+ entry.settings = {
+ ...entry.settings,
+ commandIndex: entry.commandIndex,
+ commandId: DIAL_COMMANDS[entry.commandIndex]!.id,
+ };
+ await entry.action.setSettings(entry.settings);
+ return;
+ }
+ if (name !== "onKeyDown" && name !== "onDialUp") return;
+ if (["health", "usage", "context"].includes(kind)) {
+ await observeProviders();
+ return;
+ }
+ if (kind === "approval-mode") {
+ await this.perform("permission-cycle");
+ return;
+ }
+ if (kind === "command") {
+ const command = this.command(entry);
+ if (!command) throw new Error("UNSUPPORTED");
+ await this.performCommand(entry, command.id);
+ return;
+ }
+ if (kind === "workflow") {
+ if (entry.settings.path) throw new Error("USE CURRENT FOLDER");
+ const workflow =
+ WORKFLOWS.find((w) => w.id === entry.settings.workflowId) ??
+ WORKFLOWS[Number(entry.settings.workflowIndex ?? 0)];
+ if (!workflow) throw new Error("UNSUPPORTED");
+ await this.perform("workflow", workflow.prompt);
+ return;
+ }
+ if (kind === "keycap") {
+ const action = entry.settings.action ?? "info";
+ if (action.startsWith("workflow:")) {
+ const workflow = keycapWorkflow(action.slice(9));
+ if (!workflow) throw new Error("UNSUPPORTED");
+ await this.perform("workflow", workflow.prompt);
+ } else await this.performCommand(entry, action.replace(/^command:/, ""));
+ return;
+ }
+ throw new Error("UNSUPPORTED");
+ }
+
+ private async draw(entry: Visible): Promise {
+ const kind = this.kind();
+ const active =
+ entry.provider === "claude" &&
+ observation.foreground === "claude" &&
+ freshObservation(observation);
+ const state = !freshObservation(observation)
+ ? "STALE"
+ : !entry.provider
+ ? "NO APP"
+ : !active
+ ? "BACKGROUND"
+ : observation.reason;
+ let label = kind.replaceAll("-", " ");
+ let detail = entry.error ?? state ?? "UNAVAILABLE";
+ let icon = "command";
+ if (kind === "claude-weekly") {
+ if (entry.usageView) {
+ const fable = entry.usageView === 2;
+ const resets = lastClaudeResets;
+ const hint = observation.resetAvailabilityHint;
+ if (
+ !resets &&
+ hint &&
+ hint.accountId === observation.claudeAccountId &&
+ hint.checkedAt <= Date.now() &&
+ hint.validUntil > Date.now()
+ ) {
+ if (entry.action.isKey())
+ await renderKey(
+ entry.action,
+ svgDataUrl(resetAvailabilityKeySvg()),
+ );
+ return;
+ }
+ const current =
+ observation.foreground === "claude" &&
+ freshObservation(observation) &&
+ observation.weeklyResetsAvailable !== undefined &&
+ observation.fableResetsAvailable !== undefined;
+ if (entry.action.isKey())
+ await renderKey(
+ entry.action,
+ svgDataUrl(
+ usageKeySvg(
+ resets
+ ? {
+ usedPercent: 0,
+ observedAt: resets.observedAt,
+ resetsAvailable: fable ? resets.fable : resets.weekly,
+ }
+ : undefined,
+ "resets",
+ Date.now(),
+ {
+ heading: fable ? "FABLE RESETS" : "WEEKLY RESETS",
+ accent: "#E7A589",
+ footer: resets
+ ? current
+ ? "AVAILABLE"
+ : "CACHED"
+ : "OPEN USAGE",
+ },
+ ),
+ ),
+ );
+ return;
+ }
+ const current = active ? claudeUsage(observation) : undefined;
+ const cached = current ?? lastClaudeWeekly;
+ if (entry.action.isKey()) {
+ await renderKey(
+ entry.action,
+ svgDataUrl(
+ usageKeySvg(
+ cached
+ ? {
+ usedPercent: cached.usedPercent,
+ observedAt: cached.observedAt,
+ }
+ : undefined,
+ "weekly",
+ Date.now(),
+ {
+ heading: "CLAUDE LEFT",
+ footer: current
+ ? claudeUsageLabel(current).toUpperCase()
+ : cached
+ ? "CACHED"
+ : "NOT EXPOSED",
+ accent: "#E7A589",
+ },
+ ),
+ ),
+ );
+ }
+ return;
+ }
+ if (kind === "claude-context") {
+ const activeContext =
+ observation.foreground === "claude" &&
+ observation.target &&
+ typeof observation.contextUsedPercent === "number"
+ ? {
+ usedPercent: observation.contextUsedPercent,
+ observedAt: observation.observedAt,
+ targetKey: targetKey(observation.target),
+ sessionId: observation.target.sessionId,
+ }
+ : undefined;
+ const cached = activeContext ?? lastClaudeContext;
+ if (entry.action.isKey()) {
+ await renderKey(
+ entry.action,
+ svgDataUrl(
+ contextKeySvg(
+ cached
+ ? {
+ threadId: cached.sessionId,
+ usedTokens: cached.usedPercent,
+ maxTokens: 100,
+ remainingPercent: Math.round(100 - cached.usedPercent),
+ observedAt: cached.observedAt,
+ }
+ : undefined,
+ "remaining",
+ {
+ heading: "CLAUDE CONTEXT",
+ accent: "#E7A589",
+ unavailableValue:
+ active && observation.contextAvailability === "automatic"
+ ? "AUTO"
+ : "NO DATA",
+ footer:
+ cached && (!activeContext || !active)
+ ? "CACHED"
+ : active && observation.contextAvailability === "automatic"
+ ? "COMPACTION"
+ : active && observation.contextAvailability === "empty"
+ ? "EMPTY CHAT"
+ : active &&
+ observation.contextAvailability === "unavailable"
+ ? "NOT EXPOSED"
+ : "",
+ },
+ ),
+ ),
+ );
+ }
+ return;
+ }
+ if (kind === "model") {
+ label = "Model";
+ icon = "model";
+ detail =
+ entry.error ??
+ state ??
+ entry.preview?.options[entry.preview.index]?.label ??
+ observation.model ??
+ "NO DATA";
+ }
+ if (kind === "reasoning") {
+ label = "Effort";
+ icon = "brain-medium";
+ detail =
+ entry.error ??
+ state ??
+ entry.preview?.options[entry.preview.index]?.label ??
+ observation.effort ??
+ "NO DATA";
+ }
+ if (kind === "approval-mode") {
+ label = "Permissions";
+ icon = "shield";
+ detail = entry.error ?? state ?? observation.permission ?? "NO DATA";
+ }
+ if (kind === "usage") {
+ const usage = claudeUsage(observation);
+ label = usage ? claudeUsageLabel(usage) : "Usage left";
+ icon = "usage";
+ detail =
+ entry.error ??
+ state ??
+ (usage === undefined
+ ? "NO DATA"
+ : `${Math.round(100 - usage.usedPercent)}% left`);
+ }
+ if (kind === "context") {
+ label = "Context left";
+ icon = "context";
+ detail =
+ entry.error ??
+ state ??
+ (observation.contextUsedPercent === undefined
+ ? "NO DATA"
+ : `${Math.round(100 - observation.contextUsedPercent)}%`);
+ }
+ if (kind === "health") {
+ label = "Health";
+ detail = entry.error ?? state ?? "LIMITED";
+ }
+ if (kind === "workflow") {
+ label =
+ (
+ WORKFLOWS.find((w) => w.id === entry.settings.workflowId) ??
+ WORKFLOWS[Number(entry.settings.workflowIndex ?? 0)]
+ )?.label ?? "Workflow";
+ detail =
+ entry.error ??
+ state ??
+ (observation.capabilities?.includes("workflow")
+ ? "READY"
+ : "UNAVAILABLE");
+ icon = "workflow";
+ }
+ if (kind === "keycap") {
+ label = entry.settings.label ?? "Keycap";
+ icon = entry.settings.icon ?? "command";
+ const operation = String(entry.settings.action ?? "").startsWith(
+ "workflow:",
+ )
+ ? "workflow"
+ : String(entry.settings.action ?? "").replace(/^command:/, "");
+ detail =
+ entry.error ??
+ state ??
+ (observation.capabilities?.includes(operation)
+ ? "READY"
+ : "UNAVAILABLE");
+ }
+ const command =
+ kind === "command"
+ ? this.command(entry)
+ : kind === "keycap" &&
+ typeof entry.settings.action === "string" &&
+ entry.settings.action.startsWith("command:")
+ ? COMMANDS.find((c) => c.id === entry.settings.action.slice(8))
+ : undefined;
+ if (kind === "command") {
+ label = command?.dialLabel ?? command?.label ?? "Command";
+ icon = command?.icon ?? "command";
+ }
+ if (
+ command &&
+ !entry.error &&
+ !state &&
+ observation.capabilities?.includes(command.id)
+ ) {
+ const modeState =
+ command.id === "dictate"
+ ? observation.recording
+ ? "ACTIVE"
+ : "OFF"
+ : command.id === "plan"
+ ? ["Plan", "Plan mode"].includes(observation.permission ?? "")
+ ? "ACTIVE"
+ : "OFF"
+ : command.id === "fast"
+ ? observation.fast
+ ? "ACTIVE"
+ : "OFF"
+ : undefined;
+ detail = modeState ?? "READY";
+ if (entry.action.isKey()) {
+ await renderKey(
+ entry.action,
+ svgDataUrl(
+ commandKeySvg(
+ kind === "command" ? command.label : label,
+ command.accent,
+ icon,
+ modeState,
+ ),
+ ),
+ );
+ return;
+ }
+ }
+ if (
+ command?.id === "send" &&
+ active &&
+ observation.draftEmpty &&
+ !entry.error
+ )
+ detail = "EMPTY";
+ if (entry.action.isDial()) {
+ const current =
+ kind === "model"
+ ? observation.model
+ : kind === "reasoning"
+ ? observation.effort
+ : undefined;
+ const optionScale = entry.optionScale;
+ let scaled = entry.preview;
+ if (
+ !scaled &&
+ optionScale &&
+ optionScale.identity === entry.identity &&
+ current
+ ) {
+ scaled = {
+ identity: optionScale.identity,
+ options: optionScale.options,
+ index: optionScale.options.findIndex(
+ (option) => option.value === current || option.label === current,
+ ),
+ };
+ }
+ const indicator =
+ scaled && scaled.index >= 0
+ ? {
+ value:
+ scaled.options.length <= 1
+ ? 100
+ : (scaled.index / (scaled.options.length - 1)) * 100,
+ bar_fill_c: entry.preview ? "#F4B740" : "#E7A589",
+ }
+ : { value: 0, bar_fill_c: "#8B949E" };
+ await renderFeedback(entry.action, {
+ title: label.toUpperCase(),
+ value: detail,
+ indicator,
+ });
+ } else if (entry.action.isKey())
+ await renderKey(
+ entry.action,
+ svgDataUrl(
+ kind === "approval-mode"
+ ? modeKeySvg(detail, label, icon)
+ : keycapSvg(label, detail, icon),
+ ),
+ );
+ }
+}
diff --git a/src/lib/providers/telemetry.ts b/src/lib/providers/telemetry.ts
new file mode 100644
index 0000000..6d069a6
--- /dev/null
+++ b/src/lib/providers/telemetry.ts
@@ -0,0 +1,52 @@
+import type { ProviderObservation } from "./types.js";
+
+export interface ClaudeUsage {
+ usedPercent: number;
+ period: string;
+ bucket?: string;
+ observedAt: number;
+}
+
+export function claudeUsage(
+ observation: ProviderObservation,
+): ClaudeUsage | undefined {
+ if (
+ observation.foreground !== "claude" ||
+ (observation.target?.provider !== "claude" && !observation.readOnlyScope) ||
+ (observation.reason &&
+ !(observation.readOnlyScope && observation.reason === "PROJECT VIEW"))
+ )
+ return undefined;
+ // Old helpers expose only the weekly fields. A modern unavailable observation
+ // is authoritative: never resurrect the previously exposed weekly bucket.
+ const modern = observation.usageAvailability !== undefined;
+ if (modern && observation.usageAvailability !== "ready") return undefined;
+ const usedPercent = modern
+ ? observation.usageUsedPercent
+ : observation.weeklyUsedPercent;
+ const period = modern ? observation.usagePeriod : "Weekly";
+ const bucket = modern ? observation.usageBucket : observation.weeklyBucket;
+ if (
+ typeof usedPercent !== "number" ||
+ !Number.isFinite(usedPercent) ||
+ usedPercent < 0 ||
+ usedPercent > 100 ||
+ !period
+ )
+ return undefined;
+ return {
+ usedPercent,
+ period,
+ observedAt: observation.observedAt,
+ ...(bucket ? { bucket } : {}),
+ };
+}
+
+export function claudeUsageLabel(reading: ClaudeUsage): string {
+ return [
+ reading.period,
+ reading.bucket === "all models" ? undefined : reading.bucket,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+}
diff --git a/src/lib/providers/types.ts b/src/lib/providers/types.ts
new file mode 100644
index 0000000..a5777fc
--- /dev/null
+++ b/src/lib/providers/types.ts
@@ -0,0 +1,113 @@
+import type { AgentStatus } from "../../types.js";
+
+export type ProviderId = "codex" | "claude";
+export type ProviderSetting = ProviderId | "auto";
+export type Environment = "local" | "ssh" | "cloud";
+export interface ProviderSettings {
+ provider?: ProviderSetting;
+}
+export interface TargetIdentity {
+ provider: ProviderId;
+ windowId: string;
+ sessionId: string;
+ environment: Environment;
+}
+export interface ProviderSession {
+ id: string;
+ title: string;
+ environment: Environment;
+ cwd?: string;
+ status?: AgentStatus;
+}
+export interface ProviderObservation {
+ foreground?: ProviderId;
+ target?: TargetIdentity;
+ reason?: string;
+ model?: string;
+ effort?: string;
+ permission?: string;
+ draftEmpty?: boolean;
+ fast?: boolean;
+ recording?: boolean;
+ ultracode?: boolean;
+ claudeAccountId?: string;
+ cachedResets?: {
+ accountId: string;
+ weekly: number;
+ fable: number;
+ observedAt: number;
+ };
+ resetAvailabilityHint?: {
+ accountId: string;
+ checkedAt: number;
+ validUntil: number;
+ };
+ weeklyResetsAvailable?: number;
+ fableResetsAvailable?: number;
+ weeklyUsedPercent?: number;
+ weeklyBucket?: string;
+ usageUsedPercent?: number;
+ usagePeriod?: string;
+ usageBucket?: string;
+ usageAvailability?: "ready" | "unavailable";
+ contextUsedPercent?: number;
+ contextAvailability?: "ready" | "empty" | "unavailable" | "automatic";
+ readOnlyScope?: string;
+ sessions?: ProviderSession[];
+ capabilities?: string[];
+ observedAt: number;
+}
+export interface ProviderOption {
+ value: string;
+ label: string;
+}
+export interface ProviderReply extends ProviderObservation {
+ options?: ProviderOption[];
+}
+export interface ProviderRequest {
+ operation: string;
+ target: TargetIdentity;
+ value?: string;
+}
+export interface DesktopProvider {
+ readonly id: ProviderId;
+ read(): Promise;
+ perform(request: ProviderRequest): Promise;
+}
+
+export function providerSetting(value: unknown): ProviderSetting | undefined {
+ if (value === undefined) return "codex";
+ return value === "codex" || value === "claude" || value === "auto"
+ ? value
+ : undefined;
+}
+export function resolveProvider(
+ value: unknown,
+ foreground?: ProviderId,
+): ProviderId | undefined {
+ const setting = providerSetting(value);
+ return setting === "auto" ? foreground : setting;
+}
+export function targetKey(target?: TargetIdentity): string {
+ return target
+ ? JSON.stringify([
+ target.provider,
+ target.windowId,
+ target.sessionId,
+ target.environment,
+ ])
+ : "";
+}
+export function sameTarget(a?: TargetIdentity, b?: TargetIdentity): boolean {
+ return !!a && !!b && targetKey(a) === targetKey(b);
+}
+export function freshObservation(
+ observation: ProviderObservation,
+ now = Date.now(),
+): boolean {
+ return (
+ Number.isFinite(observation.observedAt) &&
+ now >= observation.observedAt &&
+ now - observation.observedAt <= 4000
+ );
+}
diff --git a/src/lib/render-cache.ts b/src/lib/render-cache.ts
index d209813..05aec21 100644
--- a/src/lib/render-cache.ts
+++ b/src/lib/render-cache.ts
@@ -1,9 +1,16 @@
+import {
+ badgeFor,
+ badgeImage,
+ badgeFeedback,
+} from "./providers/presentation.js";
type KeyAction = {
+ id?: string;
setImage(value: string): Promise;
setTitle(value: string): Promise;
};
type DialAction = {
+ id?: string;
setFeedback(value: unknown): Promise;
};
@@ -35,11 +42,22 @@ function serialize(
return task;
}
+/** A page reappearance resets the host layout even when the SDK action is reused. */
+export async function resetRender(action: object): Promise {
+ const state = stateFor(action);
+ await serialize(state, async () => {
+ delete state.image;
+ delete state.title;
+ delete state.feedback;
+ });
+}
+
/** Send a key render only when its image or title transport payload changed. */
export async function renderKey(
action: KeyAction,
image: string,
): Promise {
+ image = badgeImage(image, badgeFor(action.id));
const state = stateFor(action);
if (state.keyPending?.payload === image) {
return state.keyPending.promise;
@@ -68,6 +86,7 @@ export async function renderFeedback(
action: DialAction,
feedback: unknown,
): Promise {
+ feedback = badgeFeedback(feedback, badgeFor(action.id));
const serialized = JSON.stringify(feedback);
const state = stateFor(action);
if (state.feedbackPending?.payload === serialized) {
diff --git a/src/lib/visuals.ts b/src/lib/visuals.ts
index eccfc87..c71d028 100644
--- a/src/lib/visuals.ts
+++ b/src/lib/visuals.ts
@@ -278,6 +278,64 @@ export function approvalKeySvg(mode: ApprovalDisplayMode): string {
`;
}
+const MODE_ACCENT: [RegExp, string][] = [
+ [/^bypass/i, "#FFD166"],
+ [/accept/i, "#7EE787"],
+ [/^plan/i, "#C8A4FF"],
+ [/^auto/i, "#E7A589"],
+ [/^(manual|ask|review)/i, "#79C0FF"],
+ [/^turbo/i, "#FFD166"],
+ [/^default/i, "#7EE787"],
+];
+
+/**
+ * A key whose whole job is to show one app-reported mode name ("Accept
+ * edits", "Bypass permissions"). The mode is the headline, sized to fill the
+ * key on one or two lines; the caption names what the key controls.
+ */
+export function modeKeySvg(
+ mode: string,
+ caption: string,
+ icon: string,
+): string {
+ const name = mode.replace(/ (permissions|mode)$/i, "").trim() || mode;
+ const words = name.split(/\s+/);
+ // Two lines when it shortens the longest line; break at the most balanced point.
+ let lines = [name];
+ for (let i = 1; i < words.length; i++) {
+ const split = [words.slice(0, i).join(" "), words.slice(i).join(" ")];
+ const widest = (candidate: string[]) =>
+ Math.max(...candidate.map((line) => line.length));
+ if (widest(split) < widest(lines)) lines = split;
+ }
+ const longest = Math.max(...lines.map((line) => line.length));
+ // Capitals (the reason codes) run wider than mixed-case mode names.
+ const advance = name === name.toUpperCase() ? 0.74 : 0.6;
+ const size = Math.max(
+ 14,
+ Math.min(
+ lines.length === 2 ? 26 : 30,
+ Math.floor(126 / (advance * longest)),
+ ),
+ );
+ const accent =
+ MODE_ACCENT.find(([pattern]) => pattern.test(name))?.[1] ?? "#8D97A5";
+ const first = lines.length === 2 ? 112 - size : 104;
+ const text = lines
+ .map(
+ (line, index) =>
+ `${escapeXml(line)} `,
+ )
+ .join("");
+ return `
+
+
+ ${commandIcon(icon, accent, 22, 1.6)}
+ ${text}
+ ${escapeXml(caption)}
+ `;
+}
+
/**
* Dedicated Codex Micro reference-key renderer. Command buttons can trade
* space between an icon and a label; the keycap pages cannot. This reserves
@@ -318,10 +376,23 @@ export function keycapSvg(
`;
}
+/** Positive account-level hint; never implies a reset type or exact count. */
+export function resetAvailabilityKeySvg(): string {
+ return `
+
+
+ CLAUDE
+ RESETS
+ AVAILABLE
+ CACHED STATUS
+ `;
+}
+
export function usageKeySvg(
snapshot: UsageSnapshot | undefined,
mode: "weekly" | "resets" = "weekly",
now = Date.now(),
+ labels: { heading?: string; footer?: string; accent?: string } = {},
): string {
const used = Math.round(snapshot?.usedPercent ?? 0);
const remaining = Math.max(0, 100 - used);
@@ -350,27 +421,41 @@ export function usageKeySvg(
: snapshot
? `${remaining}%`
: "NO DATA";
- const heading = mode === "resets" ? "RESETS" : "WEEKLY LEFT";
+ const heading =
+ labels.heading ?? (mode === "resets" ? "RESETS" : "WEEKLY LEFT");
const footer =
- mode === "resets" ? "AVAILABLE" : snapshot ? `RESET ${reset}` : "";
+ labels.footer ??
+ (mode === "resets"
+ ? "AVAILABLE"
+ : snapshot && resetMs !== undefined
+ ? `RESET ${reset}`
+ : "");
const valueSize = snapshot ? 40 : 22;
const barWidth =
snapshot && mode === "weekly" ? Math.round(104 * (remaining / 100)) : 0;
return `
- ${heading}
+ ${labels.accent ? ` ` : ""}
+ ${escapeXml(heading)}
${mainValue}
- ${footer}
+ ${escapeXml(footer)}
`;
}
export function contextKeySvg(
snapshot: ContextSnapshot | undefined,
mode: ContextView = "remaining",
+ labels: {
+ heading?: string;
+ accent?: string;
+ footer?: string;
+ unavailableValue?: string;
+ } = {},
): string {
+ const footer = labels.footer ?? (snapshot?.cached ? "CACHED" : undefined);
const known = snapshot !== undefined;
const remaining = snapshot?.remainingPercent ?? 0;
const used = Math.max(0, 100 - remaining);
@@ -386,19 +471,23 @@ export function contextKeySvg(
const maxValue = compact[1] ?? "--";
const barWidth = snapshot ? Math.round(104 * (used / 100)) : 0;
const valueMarkup = !known
- ? 'NO DATA '
+ ? `${escapeXml(labels.unavailableValue ?? "NO DATA")} `
: mode === "exact"
? `${usedValue} USED
${maxValue} MAX `
: `${remaining}% `;
- const heading = mode === "remaining" && known ? "CONTEXT LEFT" : "CONTEXT";
+ const heading =
+ labels.heading ??
+ (mode === "remaining" && known ? "CONTEXT LEFT" : "CONTEXT");
return `
- ${heading}
+ ${labels.accent ? ` ` : ""}
+ ${escapeXml(heading)}
${valueMarkup}
+ ${footer ? `${escapeXml(footer)} ` : ""}
`;
}
diff --git a/src/lib/wordmark-paths.ts b/src/lib/wordmark-paths.ts
index 010fc10..34951f7 100644
--- a/src/lib/wordmark-paths.ts
+++ b/src/lib/wordmark-paths.ts
@@ -2,13 +2,13 @@
// The source font is licensed under the SIL Open Font License 1.1.
export const WORDMARK_PATHS = {
yeet: {
- d: "M9.81 72.80L25.11 72.80C26.01 72.80 26.71 72.20 26.81 71.30L29.61 48.20C29.61 48 29.61 47.90 29.81 47.60L48.81 4.70C49.21 3.70 48.91 3 47.91 3L31.81 3C30.91 3 30.21 3.40 29.91 4.30L23.81 24.40C23.61 24.80 23.31 24.80 23.21 24.40L22.01 4.30C21.91 3.40 21.41 3 20.51 3L4.41 3C3.31 3 2.91 3.70 3.01 4.70L11.31 47.60C11.41 47.90 11.41 48 11.41 48.20L8.51 71.30C8.41 72.20 8.91 72.80 9.81 72.80ZM89.41 17.60L91.01 4.50C91.11 3.60 90.61 3 89.71 3L53.81 3C52.91 3 52.31 3.60 52.21 4.50L44.01 71.50C43.81 72.40 44.41 73 45.21 73L81.11 73C82.01 73 82.61 72.40 82.81 71.50L84.41 58.40C84.51 57.50 84.01 56.90 83.11 56.90L64.51 56.90C64.21 56.90 64.01 56.70 64.01 56.40L65.31 46.50C65.31 46.20 65.51 46 65.81 46L75.51 46C76.41 46 77.01 45.40 77.11 44.50L78.81 31.40C78.91 30.50 78.41 29.90 77.51 29.90L67.81 29.90C67.51 29.90 67.31 29.70 67.41 29.40L68.61 19.60C68.61 19.30 68.81 19.10 69.11 19.10L87.71 19.10C88.61 19.10 89.31 18.50 89.41 17.60ZM132.51 17.60L134.11 4.50C134.21 3.60 133.71 3 132.81 3L96.91 3C96.01 3 95.41 3.60 95.31 4.50L87.11 71.50C86.91 72.40 87.51 73 88.31 73L124.21 73C125.11 73 125.71 72.40 125.91 71.50L127.51 58.40C127.61 57.50 127.11 56.90 126.21 56.90L107.61 56.90C107.31 56.90 107.11 56.70 107.11 56.40L108.41 46.50C108.41 46.20 108.61 46 108.91 46L118.61 46C119.51 46 120.11 45.40 120.21 44.50L121.91 31.40C122.01 30.50 121.51 29.90 120.61 29.90L110.91 29.90C110.61 29.90 110.41 29.70 110.51 29.40L111.71 19.60C111.71 19.30 111.91 19.10 112.21 19.10L130.81 19.10C131.71 19.10 132.41 18.50 132.51 17.60ZM179.91 3L137.91 3C137.01 3 136.41 3.60 136.21 4.50L134.61 17.60C134.51 18.50 135.01 19.10 135.91 19.10L147.21 19.10C147.51 19.10 147.61 19.30 147.61 19.60L141.21 71.50C141.11 72.40 141.61 73 142.51 73L157.81 73C158.71 73 159.31 72.40 159.41 71.50L165.81 19.60C165.91 19.30 166.11 19.10 166.41 19.10L177.91 19.10C178.81 19.10 179.41 18.50 179.51 17.60L181.21 4.50C181.31 3.60 180.81 3 179.91 3Z",
+ d: "M9.81 72.80L25.11 72.80C26.01 72.80 26.71 72.20 26.81 71.30L29.61 48.20C29.61 48 29.61 47.90 29.81 47.60L48.81 4.70C49.21 3.70 48.91 3 47.91 3L31.81 3C30.91 3 30.21 3.40 29.91 4.30L23.81 24.40C23.61 24.80 23.31 24.80 23.21 24.40L22.01 4.30C21.91 3.40 21.41 3 20.51 3L4.41 3C3.31 3 2.91 3.70 3.01 4.70L11.31 47.60C11.41 47.90 11.41 48 11.41 48.20L8.51 71.30C8.41 72.20 8.91 72.80 9.81 72.80M89.41 17.60L91.01 4.50C91.11 3.60 90.61 3 89.71 3L53.81 3C52.91 3 52.31 3.60 52.21 4.50L44.01 71.50C43.81 72.40 44.41 73 45.21 73L81.11 73C82.01 73 82.61 72.40 82.81 71.50L84.41 58.40C84.51 57.50 84.01 56.90 83.11 56.90L64.51 56.90C64.21 56.90 64.01 56.70 64.01 56.40L65.31 46.50C65.31 46.20 65.51 46 65.81 46L75.51 46C76.41 46 77.01 45.40 77.11 44.50L78.81 31.40C78.91 30.50 78.41 29.90 77.51 29.90L67.81 29.90C67.51 29.90 67.31 29.70 67.41 29.40L68.61 19.60C68.61 19.30 68.81 19.10 69.11 19.10L87.71 19.10C88.61 19.10 89.31 18.50 89.41 17.60M132.51 17.60L134.11 4.50C134.21 3.60 133.71 3 132.81 3L96.91 3C96.01 3 95.41 3.60 95.31 4.50L87.11 71.50C86.91 72.40 87.51 73 88.31 73L124.21 73C125.11 73 125.71 72.40 125.91 71.50L127.51 58.40C127.61 57.50 127.11 56.90 126.21 56.90L107.61 56.90C107.31 56.90 107.11 56.70 107.11 56.40L108.41 46.50C108.41 46.20 108.61 46 108.91 46L118.61 46C119.51 46 120.11 45.40 120.21 44.50L121.91 31.40C122.01 30.50 121.51 29.90 120.61 29.90L110.91 29.90C110.61 29.90 110.41 29.70 110.51 29.40L111.71 19.60C111.71 19.30 111.91 19.10 112.21 19.10L130.81 19.10C131.71 19.10 132.41 18.50 132.51 17.60M179.91 3L137.91 3C137.01 3 136.41 3.60 136.21 4.50L134.61 17.60C134.51 18.50 135.01 19.10 135.91 19.10L147.21 19.10C147.51 19.10 147.61 19.30 147.61 19.60L141.21 71.50C141.11 72.40 141.61 73 142.51 73L157.81 73C158.71 73 159.31 72.40 159.41 71.50L165.81 19.60C165.91 19.30 166.11 19.10 166.41 19.10L177.91 19.10C178.81 19.10 179.41 18.50 179.51 17.60L181.21 4.50C181.31 3.60 180.81 3 179.91 3",
width: 184.23,
height: 76,
viewBox: "0 0 184.23 76",
},
yolo: {
- d: "M9.81 73.60L25.11 73.60C26.01 73.60 26.71 73 26.81 72.10L29.61 49C29.61 48.80 29.61 48.70 29.81 48.40L48.81 5.50C49.21 4.50 48.91 3.80 47.91 3.80L31.81 3.80C30.91 3.80 30.21 4.20 29.91 5.10L23.81 25.20C23.61 25.60 23.31 25.60 23.21 25.20L22.01 5.10C21.91 4.20 21.41 3.80 20.51 3.80L4.41 3.80C3.31 3.80 2.91 4.50 3.01 5.50L11.31 48.40C11.41 48.70 11.41 48.80 11.41 49L8.51 72.10C8.41 73 8.91 73.60 9.81 73.60ZM64.21 74.60C77.21 74.60 86.81 66.30 88.41 53.20L91.91 24.40C93.51 11.30 86.01 3 73.01 3C59.91 3 50.51 11.30 48.91 24.40L45.31 53.20C43.71 66.30 51.11 74.60 64.21 74.60ZM66.21 58.50C64.11 58.50 63.11 56.70 63.51 54L67.21 23.60C67.51 20.90 68.91 19.10 71.11 19.10C73.21 19.10 74.11 20.90 73.81 23.60L70.11 54C69.71 56.70 68.31 58.50 66.21 58.50ZM92.11 73.80L128.41 73.80C129.31 73.80 129.91 73.20 130.01 72.30L131.71 59.20C131.81 58.30 131.31 57.70 130.41 57.70L111.41 57.70C111.11 57.70 110.91 57.50 110.91 57.20L117.31 5.30C117.41 4.40 116.91 3.80 116.01 3.80L100.71 3.80C99.81 3.80 99.21 4.40 99.11 5.30L90.91 72.30C90.71 73.20 91.31 73.80 92.11 73.80ZM154.01 74.60C167.01 74.60 176.61 66.30 178.21 53.20L181.71 24.40C183.31 11.30 175.81 3 162.81 3C149.71 3 140.31 11.30 138.71 24.40L135.11 53.20C133.51 66.30 140.91 74.60 154.01 74.60ZM156.01 58.50C153.91 58.50 152.91 56.70 153.31 54L157.01 23.60C157.31 20.90 158.71 19.10 160.91 19.10C163.01 19.10 163.91 20.90 163.61 23.60L159.91 54C159.51 56.70 158.11 58.50 156.01 58.50Z",
+ d: "M9.81 73.60L25.11 73.60C26.01 73.60 26.71 73 26.81 72.10L29.61 49C29.61 48.80 29.61 48.70 29.81 48.40L48.81 5.50C49.21 4.50 48.91 3.80 47.91 3.80L31.81 3.80C30.91 3.80 30.21 4.20 29.91 5.10L23.81 25.20C23.61 25.60 23.31 25.60 23.21 25.20L22.01 5.10C21.91 4.20 21.41 3.80 20.51 3.80L4.41 3.80C3.31 3.80 2.91 4.50 3.01 5.50L11.31 48.40C11.41 48.70 11.41 48.80 11.41 49L8.51 72.10C8.41 73 8.91 73.60 9.81 73.60M64.21 74.60C77.21 74.60 86.81 66.30 88.41 53.20L91.91 24.40C93.51 11.30 86.01 3 73.01 3C59.91 3 50.51 11.30 48.91 24.40L45.31 53.20C43.71 66.30 51.11 74.60 64.21 74.60M66.21 58.50C64.11 58.50 63.11 56.70 63.51 54L67.21 23.60C67.51 20.90 68.91 19.10 71.11 19.10C73.21 19.10 74.11 20.90 73.81 23.60L70.11 54C69.71 56.70 68.31 58.50 66.21 58.50M92.11 73.80L128.41 73.80C129.31 73.80 129.91 73.20 130.01 72.30L131.71 59.20C131.81 58.30 131.31 57.70 130.41 57.70L111.41 57.70C111.11 57.70 110.91 57.50 110.91 57.20L117.31 5.30C117.41 4.40 116.91 3.80 116.01 3.80L100.71 3.80C99.81 3.80 99.21 4.40 99.11 5.30L90.91 72.30C90.71 73.20 91.31 73.80 92.11 73.80M154.01 74.60C167.01 74.60 176.61 66.30 178.21 53.20L181.71 24.40C183.31 11.30 175.81 3 162.81 3C149.71 3 140.31 11.30 138.71 24.40L135.11 53.20C133.51 66.30 140.91 74.60 154.01 74.60M156.01 58.50C153.91 58.50 152.91 56.70 153.31 54L157.01 23.60C157.31 20.90 158.71 19.10 160.91 19.10C163.01 19.10 163.91 20.90 163.61 23.60L159.91 54C159.51 56.70 158.11 58.50 156.01 58.50",
width: 184.93,
height: 77.6,
viewBox: "0 0 184.93 77.6",
diff --git a/src/plugin.ts b/src/plugin.ts
index 440ca2c..90b3c04 100644
--- a/src/plugin.ts
+++ b/src/plugin.ts
@@ -1,3 +1,8 @@
+import {
+ ProviderAction,
+ observeProviders,
+ serializeProviders,
+} from "./lib/providers/router.js";
import streamDeck from "@elgato/streamdeck";
import { AgentNavigatorAction } from "./actions/agent-navigator.js";
import { AgentStatusAction } from "./actions/agent-status.js";
@@ -9,29 +14,57 @@ import { HealthAction } from "./actions/health.js";
import { ModelAction } from "./actions/model.js";
import { ReasoningAction } from "./actions/reasoning.js";
import { UsageAction } from "./actions/usage.js";
+import {
+ ClaudeWeeklyAction,
+ CodexWeeklyAction,
+} from "./actions/provider-weekly.js";
+import {
+ ClaudeContextAction,
+ CodexContextAction,
+} from "./actions/provider-context.js";
+import {
+ AntigravityContextAction,
+ AntigravityPermissionsAction,
+ AntigravityUsageAction,
+} from "./actions/antigravity.js";
+import { antigravityStore } from "./lib/antigravity.js";
import { WorkflowAction } from "./actions/workflow.js";
import { codexStore } from "./lib/codex-store.js";
import { releaseSynthesizedKeysSync } from "./lib/automation.js";
import { createRefreshCoordinator } from "./lib/refresh-coordinator.js";
-import {
- BUNDLED_PROFILE_VERSION,
- bundledProfileTargets,
- bundledProfileTargetsVisible,
-} from "./lib/bundled-profiles.js";
import { BUILD_INFO } from "./lib/build-info.js";
import { collectHealth, HealthTransitionLogger } from "./lib/health.js";
-const agentStatus = new AgentStatusAction();
-const agentNavigator = new AgentNavigatorAction();
-const approvalMode = new ApprovalModeAction();
-const command = new CommandAction();
-const context = new ContextAction();
-const keycap = new KeycapAction();
-const health = new HealthAction();
-const model = new ModelAction();
-const workflow = new WorkflowAction();
-const reasoning = new ReasoningAction();
-const usage = new UsageAction();
+const agentStatus = new ProviderAction(new AgentStatusAction());
+const agentNavigator = new ProviderAction(new AgentNavigatorAction());
+const approvalMode = new ProviderAction(new ApprovalModeAction());
+const command = new ProviderAction(new CommandAction());
+const context = new ProviderAction(new ContextAction());
+const keycap = new ProviderAction(new KeycapAction());
+const health = new ProviderAction(new HealthAction());
+const model = new ProviderAction(new ModelAction());
+const workflow = new ProviderAction(new WorkflowAction());
+const reasoning = new ProviderAction(new ReasoningAction());
+const usage = new ProviderAction(new UsageAction());
+const codexWeekly = new ProviderAction(new CodexWeeklyAction(), {
+ kind: "codex-weekly",
+ provider: "codex",
+});
+const claudeWeekly = new ProviderAction(new ClaudeWeeklyAction(), {
+ kind: "claude-weekly",
+ provider: "claude",
+});
+const codexContext = new ProviderAction(new CodexContextAction(), {
+ kind: "codex-context",
+ provider: "codex",
+});
+const claudeContext = new ProviderAction(new ClaudeContextAction(), {
+ kind: "claude-context",
+ provider: "claude",
+});
+const antigravityUsage = new AntigravityUsageAction();
+const antigravityContext = new AntigravityContextAction();
+const antigravityPermissions = new AntigravityPermissionsAction();
streamDeck.logger.setLevel("info");
streamDeck.logger.info(
@@ -48,84 +81,69 @@ streamDeck.actions.registerAction(model);
streamDeck.actions.registerAction(workflow);
streamDeck.actions.registerAction(reasoning);
streamDeck.actions.registerAction(usage);
+streamDeck.actions.registerAction(codexWeekly);
+streamDeck.actions.registerAction(claudeWeekly);
+streamDeck.actions.registerAction(codexContext);
+streamDeck.actions.registerAction(claudeContext);
+streamDeck.actions.registerAction(antigravityUsage);
+streamDeck.actions.registerAction(antigravityContext);
+streamDeck.actions.registerAction(antigravityPermissions);
-export const refresh = async (): Promise => {
- // The account-usage fetch spawns the app server at most once per window;
- // it runs off the critical path and keys render the last cached value.
- void codexStore.usageSnapshot();
- // One bounded composer observation per tick feeds every key that projects
- // live input; the store limits it to one native spawn per cache window and
- // keeps a structured reason when Codex is unreachable.
- await codexStore.refreshLiveComposer().catch((error) => {
- const signature =
- error instanceof Error
- ? `${error.name}: ${error.message}`
- : String(error);
- if (signature !== lastComposerFailure) {
- lastComposerFailure = signature;
- streamDeck.logger.warn(`Live composer refresh failed: ${signature}`);
+export const refresh = async (): Promise =>
+ serializeProviders(async () => {
+ await observeProviders();
+ // The account-usage fetch spawns the app server at most once per window;
+ // it runs off the critical path and keys render the last cached value.
+ void codexStore.usageSnapshot();
+ // Antigravity answers over localhost; its keys render the last reading.
+ void antigravityStore.refresh();
+ // One bounded composer observation per tick feeds every key that projects
+ // live input; the store limits it to one native spawn per cache window and
+ // keeps a structured reason when Codex is unreachable.
+ await codexStore.refreshLiveComposer().catch((error) => {
+ const signature =
+ error instanceof Error
+ ? `${error.name}: ${error.message}`
+ : String(error);
+ if (signature !== lastComposerFailure) {
+ lastComposerFailure = signature;
+ streamDeck.logger.warn(`Live composer refresh failed: ${signature}`);
+ }
+ });
+ // Health summarizes what was observed and logs only transitions.
+ // Rendering continues so every surface can show the same bounded reason.
+ const healthSnapshot = collectHealth(codexStore);
+ if (healthSnapshot.components.focus.state === "ready") {
+ lastComposerFailure = undefined;
}
+ healthTransitions.observe(healthSnapshot, (message) =>
+ streamDeck.logger.info(message),
+ );
+ await Promise.all([
+ agentStatus.refreshAll(),
+ agentNavigator.refreshAll(),
+ approvalMode.refreshAll(),
+ context.refreshAll(),
+ health.refreshAll(),
+ model.refreshAll(),
+ reasoning.refreshAll(),
+ usage.refreshAll(),
+ codexWeekly.refreshAll(),
+ claudeWeekly.refreshAll(),
+ codexContext.refreshAll(),
+ claudeContext.refreshAll(),
+ antigravityUsage.refreshAll(),
+ antigravityContext.refreshAll(),
+ antigravityPermissions.refreshAll(),
+ command.refreshAll(),
+ keycap.refreshAll(),
+ workflow.refreshAll(),
+ ]);
});
- // Health summarizes what was observed and logs only transitions.
- // Rendering continues so every surface can show the same bounded reason.
- const healthSnapshot = collectHealth(codexStore);
- if (healthSnapshot.components.focus.state === "ready") {
- lastComposerFailure = undefined;
- }
- healthTransitions.observe(healthSnapshot, (message) =>
- streamDeck.logger.info(message),
- );
- await Promise.all([
- agentStatus.refreshAll(),
- agentNavigator.refreshAll(),
- approvalMode.refreshAll(),
- context.refreshAll(),
- health.refreshAll(),
- model.refreshAll(),
- reasoning.refreshAll(),
- usage.refreshAll(),
- ]);
-};
const healthTransitions = new HealthTransitionLogger();
let lastComposerFailure: string | undefined;
-const activateBundledProfileOnce = async (): Promise => {
- const globalSettings = await streamDeck.settings.getGlobalSettings<{
- profileActivated?: boolean;
- profileActivationVersion?: string;
- }>();
- if (globalSettings.profileActivationVersion === BUNDLED_PROFILE_VERSION)
- return;
-
- const profiles = bundledProfileTargets(streamDeck.devices);
- if (profiles.length === 0) return;
-
- // Stream Deck serializes bundled-profile imports. Concurrent requests race
- // and are rejected as "another operation is already in progress".
- for (const { device, profile } of profiles) {
- await streamDeck.profiles.switchToProfile(device.id, profile, 0);
- }
-
- const deadline = Date.now() + 3_000;
- while (!bundledProfileTargetsVisible(profiles) && Date.now() < deadline) {
- await new Promise((resolvePromise) => setTimeout(resolvePromise, 100));
- }
- if (!bundledProfileTargetsVisible(profiles)) {
- throw new Error(
- "Bundled profile activation did not expose actions; it remains pending.",
- );
- }
- await streamDeck.settings.setGlobalSettings({
- ...globalSettings,
- profileActivated: true,
- profileActivationVersion: BUNDLED_PROFILE_VERSION,
- });
- streamDeck.logger.info(
- `Activated ${profiles.length} bundled Codex Companion profile(s)`,
- );
-};
-
const refreshCoordinator = createRefreshCoordinator(refresh, 1250, (error) =>
streamDeck.logger.error("Failed to refresh Codex companion state", error),
);
@@ -144,9 +162,5 @@ await streamDeck.connect();
// macOS may block an untrusted AppleScript on its Accessibility prompt; the
// cleanup is bounded and must never put Stream Deck into a plugin restart loop.
releaseSynthesizedKeysSync();
-try {
- await activateBundledProfileOnce();
-} catch (error) {
- streamDeck.logger.error("Failed to activate bundled profile", error);
-}
+// Bundled profiles are opt-in. Never replace or switch a hand-built profile.
await refreshCoordinator.runNow();
diff --git a/src/types.ts b/src/types.ts
index c83783d..9cdc5d8 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -61,6 +61,7 @@ export interface UsageSnapshot {
}
export interface ContextSnapshot {
+ cached?: boolean;
threadId: string;
usedTokens: number;
maxTokens: number;
diff --git a/test/antigravity.test.ts b/test/antigravity.test.ts
new file mode 100644
index 0000000..a6660a3
--- /dev/null
+++ b/test/antigravity.test.ts
@@ -0,0 +1,123 @@
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ findAntigravityDaemon,
+ latestAntigravityConversation,
+ nextAntigravityPreset,
+ parseAntigravityContext,
+ parseAntigravityPreset,
+ parseAntigravityQuota,
+} from "../src/lib/antigravity.js";
+
+describe("Antigravity local server readings", () => {
+ it("uses only a daemon descriptor whose process is alive", () => {
+ const directory = mkdtempSync(join(tmpdir(), "agy-daemon-"));
+ writeFileSync(
+ join(directory, "hub_1.json"),
+ JSON.stringify({ pid: 2 ** 30, httpPort: 1, csrfToken: "dead" }),
+ );
+ expect(findAntigravityDaemon(directory)).toBeUndefined();
+ writeFileSync(
+ join(directory, "hub_2.json"),
+ JSON.stringify({ pid: process.pid, httpPort: 2, csrfToken: "live" }),
+ );
+ expect(findAntigravityDaemon(directory)).toMatchObject({
+ httpPort: 2,
+ csrfToken: "live",
+ });
+ expect(findAntigravityDaemon(join(directory, "missing"))).toBeUndefined();
+ });
+
+ it("reads each group's weekly and five-hour buckets", () => {
+ const buckets = parseAntigravityQuota(
+ {
+ response: {
+ groups: [
+ {
+ displayName: "Gemini Models",
+ buckets: [
+ {
+ window: "weekly",
+ remainingFraction: 0.75,
+ resetTime: "2026-12-08T06:07:11Z",
+ },
+ { window: "5h", remainingFraction: 1 },
+ { window: "5h", remainingFraction: 7 },
+ ],
+ },
+ {
+ displayName: "Claude and GPT models",
+ buckets: [{ window: "weekly", remainingFraction: 0 }],
+ },
+ ],
+ },
+ },
+ 5,
+ );
+ expect(
+ buckets.map((b) => [b.group, b.window, b.usage.usedPercent]),
+ ).toEqual([
+ ["GEMINI", "WEEK", 25],
+ ["GEMINI", "5H", 0],
+ ["CLAUDE", "WEEK", 100],
+ ]);
+ expect(buckets[0]!.usage.resetsAt).toBe(
+ Date.parse("2026-12-08T06:07:11Z") / 1000,
+ );
+ expect(buckets[1]!.usage.resetsAt).toBeUndefined();
+ expect(parseAntigravityQuota({})).toEqual([]);
+ });
+
+ it("picks the conversation viewed most recently and its latest context", () => {
+ const id = latestAntigravityConversation({
+ trajectorySummaries: {
+ older: { annotations: { lastUserViewTime: "2026-12-01T06:00:00Z" } },
+ newer: { lastModifiedTime: "2026-12-01T07:00:00Z" },
+ },
+ });
+ expect(id).toBe("newer");
+ expect(latestAntigravityConversation({})).toBeUndefined();
+ const window = (used: number) => ({
+ chatModel: {
+ chatStartMetadata: {
+ contextWindowMetadata: {
+ estimatedTokensUsed: used,
+ maxContextTokens: 512000,
+ },
+ },
+ },
+ });
+ expect(
+ parseAntigravityContext(
+ { generatorMetadata: [window(1000), window(128000), {}] },
+ "newer",
+ 9,
+ ),
+ ).toEqual({
+ threadId: "newer",
+ usedTokens: 128000,
+ maxTokens: 512000,
+ remainingPercent: 75,
+ observedAt: 9,
+ });
+ expect(
+ parseAntigravityContext({ generatorMetadata: [] }, "x"),
+ ).toBeUndefined();
+ });
+
+ it("cycles only the presets the server keeps distinct", () => {
+ expect(
+ parseAntigravityPreset({ globalPreset: "AGENT_PERMISSION_PRESET_TURBO" }),
+ ).toBe("TURBO");
+ expect(
+ parseAntigravityPreset({
+ globalPreset: "AGENT_PERMISSION_PRESET_VETTED",
+ }),
+ ).toBeUndefined();
+ expect(nextAntigravityPreset("REQUEST_REVIEW")).toBe("DEFAULT");
+ expect(nextAntigravityPreset("DEFAULT")).toBe("TURBO");
+ expect(nextAntigravityPreset("TURBO")).toBe("REQUEST_REVIEW");
+ });
+});
diff --git a/test/astra-picker.fixture.test.ts b/test/astra-picker.fixture.test.ts
index 2ebf526..6e51443 100644
--- a/test/astra-picker.fixture.test.ts
+++ b/test/astra-picker.fixture.test.ts
@@ -19,6 +19,7 @@ describe("Astra picker", () => {
"accessibility-chromium-appkit",
"accessibility-electron",
"accessibility-enabled",
+ "accessibility-claude-enhanced-only",
"accessibility-denied",
"title-astra",
"readout-astra",
@@ -65,7 +66,7 @@ describe("Astra picker", () => {
]);
expect(options.at(-1)).toMatchObject({
slug: "gpt-6-astra",
- pickerLabel: "Astra",
+ pickerLabel: "6 Astra",
defaultReasoning: "medium",
supportedReasoning: ["low", "medium", "high", "xhigh", "ultra"],
});
diff --git a/test/build-pipeline.test.ts b/test/build-pipeline.test.ts
index 6754f91..a9f7da7 100644
--- a/test/build-pipeline.test.ts
+++ b/test/build-pipeline.test.ts
@@ -45,7 +45,11 @@ function temporaryRoot(prefix: string): string {
describe("non-repeating check pipeline", () => {
it("keeps the package and four-part Stream Deck versions aligned", () => {
- expect(manifest.Version).toBe(`${packageJson.version}.0`);
+ const match = packageJson.version.match(
+ /^(\d+\.\d+\.\d+)(?:-beta\.(\d+))?$/,
+ );
+ expect(match).not.toBeNull();
+ expect(manifest.Version).toBe(`${match![1]}.${match![2] ?? "0"}`);
});
it("builds the native helper exactly once per check", () => {
diff --git a/test/claude-reset-status.test.ts b/test/claude-reset-status.test.ts
new file mode 100644
index 0000000..cb45cc9
--- /dev/null
+++ b/test/claude-reset-status.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { parseClaudeResetMetadata } from "../src/lib/providers/claude-reset-status.js";
+const account = "11111111-1111-4111-8111-111111111111";
+const other = "22222222-2222-4222-8222-222222222222";
+const now = 1000000000;
+const desktop = { lastKnownAccountUuid: account };
+const cli = (patch = {}, owner = account) => ({
+ oauthAccount: { accountUuid: owner },
+ unusedLimitResetStatusCache: {
+ accountUuid: account,
+ holdsUnusedReset: true,
+ checkedAt: now - 1000,
+ validUntil: now + 1000,
+ ...patch,
+ },
+});
+describe("Claude passive reset availability", () => {
+ it("accepts only a positive current account-matched hint without inventing counts", () => {
+ expect(parseClaudeResetMetadata(desktop, cli(), now)).toEqual({
+ accountId: account,
+ hint: {
+ accountId: account,
+ checkedAt: now - 1000,
+ validUntil: now + 1000,
+ },
+ });
+ });
+ it.each([
+ { holdsUnusedReset: false },
+ { holdsUnusedReset: "true" },
+ { accountUuid: other },
+ { checkedAt: now + 1 },
+ { validUntil: now },
+ { validUntil: now - 1 },
+ { checkedAt: NaN },
+ { validUntil: Infinity },
+ { validUntil: now + 8 * 86400000 },
+ { checkedAt: 0 },
+ ])("rejects unavailable or untrusted hint %j", (patch) => {
+ expect(parseClaudeResetMetadata(desktop, cli(patch), now)).toEqual({
+ accountId: account,
+ });
+ });
+ it("rejects another CLI account and absent or malformed Desktop identity", () => {
+ expect(
+ parseClaudeResetMetadata(desktop, cli({}, other), now).hint,
+ ).toBeUndefined();
+ expect(parseClaudeResetMetadata({}, cli(), now)).toEqual({});
+ expect(
+ parseClaudeResetMetadata(
+ { lastKnownAccountUuid: "not-an-account" },
+ cli(),
+ now,
+ ),
+ ).toEqual({});
+ expect(parseClaudeResetMetadata(desktop, null, now)).toEqual({
+ accountId: account,
+ });
+ });
+});
diff --git a/test/claude-selector.fixture.test.ts b/test/claude-selector.fixture.test.ts
new file mode 100644
index 0000000..1697fb3
--- /dev/null
+++ b/test/claude-selector.fixture.test.ts
@@ -0,0 +1,495 @@
+import { execFileSync } from "node:child_process";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+const helper = resolve(
+ "com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control",
+);
+function fixture(input: Record) {
+ return JSON.parse(
+ execFileSync(
+ helper,
+ [
+ "fixture-claude-policy",
+ Buffer.from(JSON.stringify(input)).toString("base64"),
+ ],
+ { encoding: "utf8", timeout: 5000 },
+ ),
+ );
+}
+const id = "11111111-2222-4333-a444-555555555555";
+describe("Claude native selector policy", () => {
+ it("preserves case-sensitive Cloud IDs only in exact Code routes", () => {
+ const session = "session_" + "AbCd".repeat(6);
+ expect(
+ fixture({ url: `https://claude.ai/epitaxy/${session}` }).conversationId,
+ ).toBe(session);
+ for (const url of [
+ `https://claude.ai/chat/${session}`,
+ `https://example.com/epitaxy/${session}`,
+ `https://claude.ai/epitaxy/${session}/extra`,
+ "https://claude.ai/epitaxy/session_short",
+ ]) {
+ expect(fixture({ url }).conversationId).toBeUndefined();
+ }
+ });
+ it.each([
+ ["Default", "example/project", true],
+ ["", "example/project", false],
+ ["A\nB", "example/project", false],
+ ["Default", "https://example.com/project", false],
+ ["Default", "example/project other/repo", false],
+ ])(
+ "bounds Cloud workspace identity %s / %s",
+ (environment, repository, valid) => {
+ expect(
+ !!fixture({
+ kind: "cloud-workspace",
+ environment: String(environment),
+ repository: String(repository),
+ }).model,
+ ).toBe(valid);
+ },
+ );
+ it.each([
+ ["Model: Fable 5.2 High", "Fable 5.2", "High"],
+ ["Model: Opus 5.5 Fast Extra", "Opus 5.5", "Extra"],
+ ["Model: Sonnet 5.5 Medium", "Sonnet 5.5", "Medium"],
+ ["Model: Haiku 5.5 Low", "Haiku 5.5", "Low"],
+ ["Model: Opus 5.5 Max 3.5× or more usage", "Opus 5.5", "Max"],
+ ["Model: Opus 5.5 Fast Extra 2× usage", "Opus 5.5", "Extra"],
+ ["Model: Fable 5.2 Fast High · Ultracode", "Fable 5.2", "High"],
+ ])("reads combined picker %s", (text, model, effort) => {
+ expect(fixture({ kind: "model", text }).model).toBe(model);
+ expect(fixture({ kind: "reasoning", text }).model).toBe(effort);
+ });
+ it.each([
+ [321001, "ACCEPTED"],
+ [4 * 1024 * 1024, "ACCEPTED"],
+ [4 * 1024 * 1024 + 1, "REJECTED"],
+ ])("bounds real metadata reads of %i bytes", (size, expected) => {
+ expect(fixture({ kind: "metadata-size", text: String(size) }).model).toBe(
+ expected,
+ );
+ });
+ it.each([
+ [{ console: "true", locked: "false" }, "READY"],
+ [{ console: "true", locked: "true" }, "LOCKED"],
+ [{ console: "false", locked: "false" }, "NO DESKTOP"],
+ [{ missing: "true" }, "NO DESKTOP"],
+ ])("rejects inactive desktop state %j", (state, expected) => {
+ expect(fixture({ kind: "desktop", ...state }).model).toBe(expected);
+ });
+ it("reuses accessibility activation only for the same Claude process generation", () => {
+ const generation = "123:456000";
+ expect(
+ fixture({
+ kind: "accessibility-generation",
+ pid: "123",
+ launchMilliseconds: "456000",
+ cached: generation,
+ }).model,
+ ).toBe(`${generation}|CACHED`);
+ expect(
+ fixture({
+ kind: "accessibility-generation",
+ pid: "123",
+ launchMilliseconds: "456000",
+ cached: "123:455000",
+ }).model,
+ ).toBe(`${generation}|INITIALIZE`);
+ });
+ it("recognizes observed Desktop local session IDs and prefixed picker labels", () => {
+ expect(
+ fixture({ url: `https://claude.ai/epitaxy/local_${id}` }).conversationId,
+ ).toBe(`local_${id}`);
+ expect(
+ fixture({ url: `https://claude.ai/epitaxy/local_bad-id` }).conversationId,
+ ).toBeUndefined();
+ expect(fixture({ kind: "model", text: "Model: Fable 5.1" }).model).toBe(
+ "Fable 5.1",
+ );
+ expect(fixture({ kind: "reasoning", text: "Effort: Extra" }).model).toBe(
+ "Extra",
+ );
+ });
+ it.each([
+ [
+ "Auto , teach auto mode about your environment Claude handles permission decisions",
+ "Auto",
+ ],
+ ["Manual Always ask before making changes", "Manual"],
+ ["Accept edits Automatically accept all file edits", "Accept edits"],
+ ["Plan Create a plan before making changes", "Plan"],
+ [
+ "Bypass permissions Accepts all permissions Default",
+ "Bypass permissions",
+ ],
+ ])("reads the semantic permission row %s", (text, expected) => {
+ expect(fixture({ kind: "permission-row", text }).model).toBe(expected);
+ });
+ it("rejects unrelated permission-looking row text", () => {
+ expect(
+ fixture({ kind: "permission-row", text: "Plan something else" }).model,
+ ).toBeUndefined();
+ });
+ it("reads context and the selected weekly bucket from the observed Usage control", () => {
+ const state = fixture({
+ kind: "usage",
+ text: "Usage: Weekly · Fable: 31%, Resets Mon 2:00 PM, Context 161.3k / 1M (16%)",
+ }).providerState;
+ expect(state).toMatchObject({
+ weeklyUsedPercent: 31,
+ weeklyBucket: "Fable",
+ contextUsedPercent: 16,
+ });
+ expect(
+ fixture({
+ kind: "usage",
+ text: "Usage: Weekly · all models: 0%, Resets Mon 2:00 PM",
+ }).providerState.weeklyUsedPercent,
+ ).toBe(0);
+ });
+ it.each([
+ "",
+ "31%",
+ "Usage: Weekly · Fable: 120%, Resets Monday",
+ "Not Usage: Weekly · Fable: 31%, Resets Monday",
+ ])("does not invent usage from %s", (text) => {
+ expect(
+ fixture({ kind: "usage", text }).providerState.weeklyUsedPercent,
+ ).toBeUndefined();
+ });
+ it.each(["Session", "Daily", "Monthly", "Weekly"])(
+ "keeps %s usage separate from weekly",
+ (period) => {
+ const state = fixture({
+ kind: "usage",
+ text: `Usage: ${period}: 12%, Resets Monday`,
+ }).providerState;
+ expect(state).toMatchObject({
+ usageUsedPercent: 12,
+ usagePeriod: period,
+ usageAvailability: "ready",
+ });
+ expect(state.weeklyUsedPercent).toBe(
+ period === "Weekly" ? 12 : undefined,
+ );
+ },
+ );
+ it.each([
+ ["Model: Opus 5 Fast", "ON"],
+ ["Model: Fable 5.2 Fast High", "ON"],
+ ["Model: Fable 5.2 Fast High · Ultracode", "ON"],
+ ["Model: Fable 5.2 High · Ultracode", "OFF"],
+ ["Model: Sonnet 5.5 High", "OFF"],
+ ])("reads Fast from %s", (text, expected) => {
+ expect(fixture({ kind: "fast-label", text }).model).toBe(expected);
+ });
+ it("reads only the Context card total, never category percentages", () => {
+ expect(fixture({ kind: "context-card" }).providerState).toMatchObject({
+ contextUsedPercent: 18,
+ contextAvailability: "ready",
+ });
+ expect(
+ fixture({ kind: "context-card", text: "0% used" }).providerState
+ .contextUsedPercent,
+ ).toBe(0);
+ expect(
+ fixture({
+ kind: "context-card",
+ text: "Send a message to see context usage.",
+ }).providerState.contextAvailability,
+ ).toBe("empty");
+ });
+ it.each([
+ { outside: "true" },
+ { hidden: "true" },
+ { duplicate: "true" },
+ { control: "Something else" },
+ { text: "101% used" },
+ { text: "Loading context breakdown…" },
+ { text: "18%" },
+ ])("rejects ambiguous or missing Context card readings %j", (input) => {
+ expect(
+ fixture({ kind: "context-card", ...input }).providerState
+ .contextUsedPercent,
+ ).toBeUndefined();
+ });
+ it("reports removed quota explicitly without fabricating zero", () => {
+ expect(
+ fixture({ kind: "usage", text: "Usage: No usage limits" }).providerState,
+ ).toMatchObject({ usageAvailability: "unavailable" });
+ expect(
+ fixture({ kind: "usage", text: "Usage: No usage limits" }).providerState
+ .usageUsedPercent,
+ ).toBeUndefined();
+ });
+ it("preserves word boundaries in Claude control labels", () => {
+ expect(
+ fixture({ kind: "control-label", text: " Enable fast mode " }).model,
+ ).toBe("enable fast mode");
+ expect(fixture({ kind: "control-label", text: "Hide sidebar" }).model).toBe(
+ "hide sidebar",
+ );
+ });
+ it("cycles all offered permission modes including Bypass", () => {
+ const choices = "Auto|Manual|Accept edits|Plan|Bypass permissions";
+ expect(
+ fixture({ kind: "permission-next", choices, text: "Plan" }).model,
+ ).toBe("Bypass permissions");
+ expect(
+ fixture({ kind: "permission-next", choices, text: "Bypass permissions" })
+ .model,
+ ).toBe("Auto");
+ expect(
+ fixture({ kind: "permission-next", choices, text: "Manual" }).model,
+ ).toBe("Accept edits");
+ expect(
+ fixture({ kind: "permission-next", choices: "Plan", text: "Plan" }).model,
+ ).toBeUndefined();
+ });
+ it("names every offered effort level including Ultracode", () => {
+ const options = fixture({
+ kind: "effort-options",
+ selected: "2",
+ text: "High",
+ }).providerState.options;
+ expect(options.map((o: any) => o.label)).toEqual([
+ "Low",
+ "Medium",
+ "High",
+ "Extra",
+ "Max",
+ "Ultracode",
+ ]);
+ expect(options.at(-1)).toEqual({ value: "slider:5", label: "Ultracode" });
+ expect(
+ fixture({ kind: "reasoning", text: "Effort: Ultracode" }).model,
+ ).toBe("Ultracode");
+ });
+ it.each([
+ { high: "6", selected: "2", text: "High" },
+ { low: "1", selected: "2", text: "High" },
+ { selected: "2", text: "Different" },
+ { selected: "9", text: "High" },
+ ])(
+ "rejects changed effort semantics instead of guessing labels %j",
+ (input) => {
+ expect(
+ fixture({ kind: "effort-options", ...input }).providerState.options,
+ ).toBeUndefined();
+ },
+ );
+ it.each([
+ [{ previous: "Bypass permissions", default: "Auto" }, "Bypass permissions"],
+ [{ default: "Bypass permissions" }, "Bypass permissions"],
+ [{ default: "Auto" }, "Auto"],
+ [{ previous: "Missing", default: "Auto" }, "Auto"],
+ [{ previous: "Plan", default: "Plan" }, "Manual"],
+ [{}, "Manual"],
+ ])(
+ "exits Plan using prior mode, app default, or Manual %j",
+ (input, expected) => {
+ expect(
+ fixture({
+ kind: "plan-exit",
+ choices: "Auto|Manual|Accept edits|Plan|Bypass permissions",
+ ...input,
+ }).model,
+ ).toBe(expected);
+ },
+ );
+ it.each([
+ [{ confirmed: "true", sameSession: "true", sameDraft: "true" }, "MATCHED"],
+ [
+ { confirmed: "false", sameSession: "true", sameDraft: "true" },
+ "REJECTED",
+ ],
+ [
+ { confirmed: "true", sameSession: "false", sameDraft: "true" },
+ "REJECTED",
+ ],
+ [
+ { confirmed: "true", sameSession: "true", sameDraft: "false" },
+ "REJECTED",
+ ],
+ ])(
+ "only accepts a composer remount after the matching Bypass confirmation %j",
+ (input, expected) => {
+ expect(fixture({ kind: "composer-continuity", ...input }).model).toBe(
+ expected,
+ );
+ },
+ );
+ it.each([
+ ["session-before", "MATCHED"],
+ ["session-after", "REJECTED"],
+ ["session-before|session-after", "REJECTED"],
+ ])(
+ "keeps confirmation pinned to the captured URL when the web area changes to %s",
+ (current, expected) => {
+ expect(
+ fixture({
+ kind: "confirmation-session",
+ expected: "session-before",
+ current,
+ }).model,
+ ).toBe(expected);
+ },
+ );
+ it.each([
+ [{}, "MATCHED"],
+ [{ title: "Approve command?" }, "REJECTED"],
+ [{ button: "Run command" }, "REJECTED"],
+ [{ outside: "true" }, "REJECTED"],
+ [{ duplicate: "true" }, "REJECTED"],
+ [{ hidden: "true" }, "REJECTED"],
+ ])("only matches the exact first-use Bypass dialog %j", (input, expected) => {
+ expect(fixture({ kind: "bypass-dialog", ...input }).model).toBe(expected);
+ });
+ it.each(["code", "epitaxy", "claude-code-desktop"])(
+ "recognizes the %s Code root with a full UUID",
+ (path) => {
+ expect(
+ fixture({ url: `https://claude.ai/${path}/${id}` }).conversationId,
+ ).toBe(id);
+ },
+ );
+ it.each([
+ `https://example.com/code/${id}`,
+ `https://claude.ai/chat/${id}`,
+ `https://claude.ai/cowork/${id}`,
+ `https://claude.ai/code/${id}/other`,
+ `https://claude.ai/code/not-a-session`,
+ `file:///code/${id}`,
+ `https://claude.ai.example.com/code/${id}`,
+ ])("rejects unrelated or ambiguous identity %s", (url) => {
+ expect(fixture({ url }).conversationId).toBeUndefined();
+ });
+ it.each(["Fable 5.1", "Opus 4.6", "Sonnet 4.6", "Claude Haiku 4.5"])(
+ "recognizes offered model label %s without a Codex model list",
+ (text) => {
+ expect(fixture({ kind: "model", text }).model).toBe(text);
+ },
+ );
+ it("rejects transcript-like strings and unrecognized permission semantics", () => {
+ expect(
+ fixture({ kind: "model", text: "Please pick Fable 5.1" }).model,
+ ).toBeUndefined();
+ expect(
+ fixture({ kind: "permission", text: "Full access" }).model,
+ ).toBeUndefined();
+ expect(fixture({ kind: "permission", text: "Auto" }).model).toBe("Auto");
+ expect(fixture({ kind: "reasoning", text: "High" }).model).toBe("High");
+ });
+});
+
+describe("Claude reset balances", () => {
+ it("distinguishes weekly and Fable counts", () => {
+ expect(fixture({ kind: "resets" }).providerState).toMatchObject({
+ weeklyResetsAvailable: 2,
+ fableResetsAvailable: 1,
+ });
+ });
+ it("accepts explicit zero only with a complete empty inventory", () => {
+ expect(
+ fixture({ kind: "resets", Weekly: "", Fable: "", total: "0" })
+ .providerState,
+ ).toMatchObject({ weeklyResetsAvailable: 0, fableResetsAvailable: 0 });
+ });
+ it.each([
+ { hidden: "true" },
+ { owner: "Transcript" },
+ { button: "missing" },
+ { duplicate: "true" },
+ { total: "4" },
+ { Weekly: "Weekly reset · 99999999999999999999999", total: "2" },
+ ])("rejects unproved reset readings %j", (input) => {
+ const state = fixture({ kind: "resets", ...input }).providerState;
+ expect(state.weeklyResetsAvailable).toBeUndefined();
+ expect(state.fableResetsAvailable).toBeUndefined();
+ });
+});
+
+describe("read-only Claude Project telemetry", () => {
+ const url = "https://claude.ai/epitaxy/project/chan_0123456789AbCdEfGhIjKlMn";
+ const text =
+ "Usage: Weekly · all models: 53%, Resets Mon 1:00 PM, Compacts automatically";
+ it("reports automatic compaction and quota without authorizing any command", () => {
+ const state = fixture({ kind: "project-usage", url, text }).providerState;
+ expect(state).toMatchObject({
+ reason: "PROJECT VIEW",
+ contextAvailability: "automatic",
+ usageUsedPercent: 53,
+ usagePeriod: "Weekly",
+ capabilities: [],
+ });
+ expect(state.target).toBeUndefined();
+ expect(state.contextUsedPercent).toBeUndefined();
+ });
+ it.each([
+ "http://claude.ai/epitaxy/project/chan_0123456789AbCdEfGhIjKlMn",
+ "https://other.example/epitaxy/project/chan_0123456789AbCdEfGhIjKlMn",
+ "https://claude.ai/chat/chan_0123456789AbCdEfGhIjKlMn",
+ "https://claude.ai/epitaxy/project/chan_short",
+ "https://claude.ai/epitaxy/project/chan_0123456789AbCdEfGhIjKlMn/extra",
+ ])("rejects wrong project identity %s", (bad) => {
+ expect(
+ fixture({ kind: "project-usage", url: bad, text }).providerState,
+ ).toBeUndefined();
+ });
+ it("does not infer automatic compaction or quota from missing evidence", () => {
+ expect(
+ fixture({
+ kind: "project-usage",
+ url,
+ text: "Usage: Weekly · all models: 53%, Resets Mon 1:00 PM",
+ }).providerState.contextAvailability,
+ ).toBe("unavailable");
+ expect(
+ fixture({ kind: "project-usage", url, text: "Compacts automatically" })
+ .providerState,
+ ).toBeUndefined();
+ });
+});
+
+describe("current model-switch confirmation", () => {
+ it("requires exact requested models and a unique confirmation pair", () => {
+ expect(fixture({ kind: "model-dialog" }).model).toBe("MATCHED");
+ for (const changed of [
+ { from: "Other" },
+ { to: "Other" },
+ { title: "Transcript" },
+ { cancel: "Missing" },
+ { hidden: "true" },
+ { outside: "true" },
+ { duplicate: "true" },
+ ])
+ expect(fixture({ kind: "model-dialog", ...changed }).model).toBe(
+ "REJECTED",
+ );
+ });
+});
+
+describe("collapsed current Context card", () => {
+ it("reads the observed used percentage without opening the card", () => {
+ expect(
+ fixture({ kind: "context-card", title: "Context 24%", text: "" })
+ .providerState.contextUsedPercent,
+ ).toBe(24);
+ expect(
+ fixture({ kind: "context-card", title: "Context 0%", text: "" })
+ .providerState.contextUsedPercent,
+ ).toBe(0);
+ for (const input of [
+ { title: "Context 101%", text: "" },
+ { title: "Context 24%", text: "18% used" },
+ { title: "Context 24%", text: "", control: "Other" },
+ { title: "Transcript Context 24%", text: "" },
+ ])
+ expect(
+ fixture({ kind: "context-card", ...input }).providerState
+ .contextUsedPercent,
+ ).toBeUndefined();
+ });
+});
diff --git a/test/codex-draft.fixture.test.ts b/test/codex-draft.fixture.test.ts
new file mode 100644
index 0000000..af5db3b
--- /dev/null
+++ b/test/codex-draft.fixture.test.ts
@@ -0,0 +1,91 @@
+import { spawnSync } from "node:child_process";
+import { describe, expect, it } from "vitest";
+const owner = "a".repeat(64);
+function read(state: unknown) {
+ const result = spawnSync(
+ "com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control",
+ [
+ "--codex-draft-metadata-fixture",
+ Buffer.from(JSON.stringify(state)).toString("base64"),
+ ],
+ { encoding: "utf8" },
+ );
+ return JSON.parse(result.stdout);
+}
+const valid = {
+ "electron-persisted-atom-state": {
+ "composer-prompt-drafts-v2": { "new-conversation": { prompt: "QA draft" } },
+ },
+ "electron-renderer-content-owner": owner,
+ [`electron-owner-value:selected-project:${owner}`]: {
+ type: "local",
+ projectId: "project",
+ },
+ "local-projects": {
+ project: { id: "project", name: "QA", rootPaths: ["/private/tmp/qa"] },
+ },
+};
+describe("current desktop unsubmitted draft metadata", () => {
+ it("correlates the selected owner and exact project roots", () => {
+ expect(read(valid)).toMatchObject({
+ ok: true,
+ model: "QA",
+ effort: "1",
+ draftEmpty: false,
+ });
+ });
+ it("does not take another account's project", () => {
+ expect(
+ read({ ...valid, "electron-renderer-content-owner": "b".repeat(64) }),
+ ).toMatchObject({ ok: true, effort: "0" });
+ });
+ it("does not accept a remote project as a local path", () => {
+ expect(
+ read({
+ ...valid,
+ [`electron-owner-value:selected-project:${owner}`]: {
+ type: "remote",
+ projectId: "project",
+ },
+ }),
+ ).toMatchObject({ ok: true, effort: "0" });
+ });
+ it("rejects malformed draft content instead of assuming empty", () => {
+ expect(
+ read({
+ ...valid,
+ "electron-persisted-atom-state": {
+ "composer-prompt-drafts-v2": { "new-conversation": { prompt: 123 } },
+ },
+ }).ok,
+ ).toBe(false);
+ });
+ it("reads structured text and treats unknown nodes as protected drafts", () => {
+ const state = (content: unknown[]) => ({
+ ...valid,
+ "electron-persisted-atom-state": {
+ "composer-prompt-drafts-v2": {
+ "new-conversation": {
+ prompt: { document: { type: "doc", content } },
+ },
+ },
+ },
+ });
+ expect(
+ read(
+ state([
+ { type: "paragraph", content: [{ type: "text", text: "QA draft" }] },
+ ]),
+ ),
+ ).toMatchObject({ ok: true, draftEmpty: false });
+ expect(read(state([{ type: "paragraph" }]))).toMatchObject({
+ ok: true,
+ draftEmpty: true,
+ });
+ expect(
+ read(state([{ type: "paragraph", content: [{ type: "mention" }] }])).ok,
+ ).toBe(false);
+ });
+ it("requires the app's metadata schema", () =>
+ expect(read({}).ok).toBe(false));
+});
diff --git a/test/context.test.ts b/test/context.test.ts
index 7227486..99e5e2a 100644
--- a/test/context.test.ts
+++ b/test/context.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
compactContext,
+ contextDisplayFromLines,
CONTEXT_STALE_MS,
parseLatestContext,
toggleContextView,
@@ -107,6 +108,21 @@ describe("focused-chat context", () => {
expect(contextKeySvg(snapshot, "remaining")).not.toContain("BAR");
});
+ it("supports concise provider labels on dedicated context keys", () => {
+ const snapshot = parseLatestContext(
+ tokenEvent("2026-07-25T17:59:00Z", 180_000, 1_000_000),
+ threadId,
+ now,
+ );
+ const svg = contextKeySvg(snapshot, "remaining", {
+ heading: "CLAUDE CONTEXT",
+ accent: "#E7A589",
+ });
+ expect(svg).toContain("CLAUDE CONTEXT");
+ expect(svg).toContain(">82%");
+ expect(svg).toContain(' ');
+ });
+
it("renders unknown instead of a sample number", () => {
for (const mode of ["remaining", "exact"] as const) {
const svg = contextKeySvg(undefined, mode);
@@ -119,3 +135,28 @@ describe("focused-chat context", () => {
}
});
});
+
+describe("idle context display", () => {
+ it("retains an old reading for its exact chat, labelled cached in both views", () => {
+ const value = contextDisplayFromLines(
+ tokenEvent("2026-07-24T17:59:00Z", 25, 100),
+ threadId,
+ now,
+ );
+ expect(value).toMatchObject({
+ threadId,
+ remainingPercent: 75,
+ cached: true,
+ });
+ for (const view of ["remaining", "exact"] as const)
+ expect(contextKeySvg(value, view)).toContain(">CACHED");
+ expect(contextDisplayFromLines("", "another-chat", now)).toBeUndefined();
+ expect(
+ contextDisplayFromLines(
+ tokenEvent("2026-07-26T00:00:00Z", 25, 100),
+ threadId,
+ now,
+ ),
+ ).toBeUndefined();
+ });
+});
diff --git a/test/desktop-view-activity.test.ts b/test/desktop-view-activity.test.ts
new file mode 100644
index 0000000..3b3b27a
--- /dev/null
+++ b/test/desktop-view-activity.test.ts
@@ -0,0 +1,136 @@
+import { execFileSync } from "node:child_process";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+import { parseHostViewActivity } from "../src/lib/desktop-active.js";
+
+const a = "11111111-2222-4333-a444-555555555555";
+const b = "21111111-2222-4333-a444-555555555555";
+const startup = "2026-11-14T17:00:00.000Z info Launching app packaged=true\n";
+const event = (id: string, active: boolean) =>
+ `2026-11-14T17:00:01.000Z info [host-app-server-manager] thread_stream_view_activity_changed active=${active} conversationId=${id} resumeState=resumed streamRole=owner\n`;
+const native = (text: string) =>
+ JSON.parse(
+ execFileSync(
+ resolve("com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control"),
+ ["--activity-fixture", Buffer.from(text).toString("base64")],
+ { encoding: "utf8" },
+ ),
+ );
+
+describe("host view discovery is not last-event focus guessing", () => {
+ it.each([
+ [event(a, true), a],
+ [event(a, true) + event(b, true), undefined],
+ [event(a, true) + event(b, true) + event(a, false), b],
+ [event(a, true) + event(a, false), undefined],
+ [event(a, true) + event(b, false), a],
+ ])("reduces all active/inactive events consistently", (events, expected) => {
+ expect(parseHostViewActivity(startup + events)?.threadId).toBe(expected);
+ expect(native(startup + events).model).toBe(expected);
+ });
+ it("requires complete startup and complete lines for discovery", () => {
+ expect(parseHostViewActivity(event(a, true))).toBeUndefined();
+ expect(
+ parseHostViewActivity((startup + event(a, true)).trimEnd()),
+ ).toBeUndefined();
+ expect(
+ parseHostViewActivity(startup + event(a, true) + event("bad", true))
+ ?.threadId,
+ ).toBeUndefined();
+ });
+ it("invalidates history even when a chat is left and returned to", () => {
+ const initial = native(startup + event(a, true));
+ const returned = native(
+ startup +
+ event(a, true) +
+ event(a, false) +
+ event(b, true) +
+ event(b, false) +
+ event(a, true),
+ );
+ expect(returned.model).toBe(a);
+ expect(returned.effort).not.toBe(initial.effort);
+ });
+ it("invalidates temporary extra views even if the original remains active", () => {
+ const initial = native(startup + event(a, true));
+ const returned = native(
+ startup + event(a, true) + event(b, true) + event(b, false),
+ );
+ expect(returned.model).toBe(a);
+ expect(returned.effort).not.toBe(initial.effort);
+ });
+});
+
+const route = (id: string, window = "1", conversation = id) =>
+ `2026-11-14T17:00:02.000Z info [electron-message-handler] IAB_LIFECYCLE received browser sidebar owner sync browserTabId=null conversationId=${conversation} originWebContentsId=${window} ownerRoutePath=/local/${id} windowId=${window}\n`;
+describe("renderer route ownership with retained chats", () => {
+ it.each([
+ [route(a) + event(a, true) + route(b) + event(b, true), b],
+ [route(a) + route(b) + route(a), a],
+ [route(a, "1", `client-new-thread:${b}`), a],
+ [route(a) + route("new"), undefined],
+ [route(a) + route(b, "2"), undefined],
+ [route(a, "1", b), undefined],
+ [route(a, "null"), undefined],
+ [route(a).replace("windowId=1", "windowId=1 windowId=2"), undefined],
+ [route(a) + route(b).replace(`/local/${b}`, `/cloud/${b}`), undefined],
+ [
+ route(a) + route(b).replace(`/local/${b}`, `/local/${b}/extra`),
+ undefined,
+ ],
+ ])(
+ "uses an exact supported route or refuses ambiguity",
+ (events, expected) => {
+ expect(parseHostViewActivity(startup + events)?.threadId).toBe(expected);
+ expect(native(startup + events).model).toBe(expected);
+ },
+ );
+ it("invalidates a return to a cached chat even without new stream activity", () => {
+ expect(native(startup + route(a)).effort).not.toBe(
+ native(startup + route(a) + route(b) + route(a)).effort,
+ );
+ });
+});
+
+describe("daily desktop log rotation", () => {
+ it("continues the same process route across midnight instead of retaining yesterday's chat", async () => {
+ const { mkdtempSync, mkdirSync, writeFileSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { join } = await import("node:path");
+ const { activeDesktopThreadId } =
+ await import("../src/lib/desktop-active.js");
+ const root = mkdtempSync(join(tmpdir(), "streamdeck-route-rollover-"));
+ const old = join(root, "2026/11/14"),
+ current = join(root, "2026/11/15");
+ mkdirSync(old, { recursive: true });
+ mkdirSync(current, { recursive: true });
+ writeFileSync(
+ join(old, "codex-desktop-session-42-t0-i1-170000-0.log"),
+ startup + event(a, true) + route(a),
+ );
+ const continuation = join(
+ current,
+ "codex-desktop-session-42-t0-i1-000001-0.log",
+ );
+ writeFileSync(continuation, route(b));
+ expect(activeDesktopThreadId(root, new Date("2026-11-15T00:01:00Z"))).toBe(
+ b,
+ );
+ writeFileSync(continuation, route(b) + route("new"));
+ expect(
+ activeDesktopThreadId(root, new Date("2026-11-15T00:01:00Z")),
+ ).toBeUndefined();
+ });
+});
+
+it("retains main-process startup and continuation despite newer worker logs", () => {
+ expect(
+ JSON.parse(
+ execFileSync(
+ resolve("com.todd.streamdeckcodex.sdPlugin/bin/codex-ui-control"),
+ ["--log-selection-fixture"],
+ { encoding: "utf8" },
+ ),
+ ).ok,
+ ).toBe(true);
+});
diff --git a/test/manifest.test.ts b/test/manifest.test.ts
index a2fcff5..2ee44be 100644
--- a/test/manifest.test.ts
+++ b/test/manifest.test.ts
@@ -76,7 +76,7 @@ describe("Stream Deck manifest", () => {
manifest.Profiles.map((profile) => profile.DeviceType).sort(
(left, right) => left - right,
),
- ).toEqual([0, 1, 2, 7, 9]);
+ ).toEqual([0, 0, 1, 1, 2, 2, 7, 7, 9, 9]);
});
it("declares the complete companion surface", () => {
@@ -91,7 +91,11 @@ describe("Stream Deck manifest", () => {
"com.todd.streamdeckcodex.reasoning",
"com.todd.streamdeckcodex.agent-navigator",
"com.todd.streamdeckcodex.usage",
+ "com.todd.streamdeckcodex.codex-weekly",
+ "com.todd.streamdeckcodex.claude-weekly",
"com.todd.streamdeckcodex.context",
+ "com.todd.streamdeckcodex.codex-context",
+ "com.todd.streamdeckcodex.claude-context",
"com.todd.streamdeckcodex.health",
]),
);
@@ -105,7 +109,7 @@ describe("Stream Deck manifest", () => {
it("ships Marketplace-compliant metadata and action-list artwork", () => {
expect(manifest.Author).toBe("Todd Dailey");
- expect(manifest.Category).toBe("Codex Companion");
+ expect(manifest.Category).toBe("Codex + Claude Companion");
expect(manifest.SupportURL).toBe(
"https://github.com/twidtwid/streamdeckcodex/issues",
);
diff --git a/test/model-dial.acceptance.test.ts b/test/model-dial.acceptance.test.ts
index 1398d59..ae4653c 100644
--- a/test/model-dial.acceptance.test.ts
+++ b/test/model-dial.acceptance.test.ts
@@ -46,19 +46,19 @@ describe("model dial acceptance", () => {
expect.objectContaining({
slug: "gpt-5.6-luna",
label: "LUNA",
- pickerLabel: "Luna",
+ pickerLabel: "5.6 Luna",
supportedReasoning: ["low", "medium"],
}),
expect.objectContaining({
slug: "gpt-5.6-terra",
label: "TERRA",
- pickerLabel: "Terra",
+ pickerLabel: "5.6 Terra",
supportedReasoning: ["low", "medium"],
}),
expect.objectContaining({
slug: "gpt-5.6-sol",
label: "SOL",
- pickerLabel: "Sol",
+ pickerLabel: "5.6 Sol",
supportedReasoning: ["low", "ultra"],
}),
]);
@@ -160,7 +160,7 @@ describe("model dial acceptance", () => {
).toMatchObject({
slug: "gpt-5.7-terra",
displayName: "GPT-5.7-Terra",
- pickerLabel: "Terra",
+ pickerLabel: "5.7 Terra",
defaultReasoning: "minimal",
supportedReasoning: ["none", "minimal"],
});
diff --git a/test/model-families.test.ts b/test/model-families.test.ts
index e539cad..c510c32 100644
--- a/test/model-families.test.ts
+++ b/test/model-families.test.ts
@@ -75,7 +75,9 @@ describe("model dial families from cache", () => {
expect(options.map((option) => option.label)).toEqual(["LUNA", "HELIX"]);
expect(options[1]).toMatchObject({
slug: "gpt-7-helix",
- pickerLabel: "Helix",
+ // The picker label carries the version so same-named families in
+ // different generations match exactly.
+ pickerLabel: "7 Helix",
displayName: "GPT-7-Helix",
});
});
diff --git a/test/native-selector.fixture.test.ts b/test/native-selector.fixture.test.ts
index b3fc0e7..ae58e64 100644
--- a/test/native-selector.fixture.test.ts
+++ b/test/native-selector.fixture.test.ts
@@ -7,6 +7,8 @@ const native = resolve(
);
type FixtureAction =
+ | "--picker-dismissal-fixture"
+ | "--approval-card-fixture"
| "--composer-draft-fixture"
| "--composer-witness-argument-fixture"
| "--selector-fixture"
@@ -18,7 +20,8 @@ type FixtureAction =
| "--ultra-confirmation-fixture"
| "--power-fixture"
| "--approval-cycle-fixture"
- | "--workspace-shortcut-fixture";
+ | "--workspace-shortcut-fixture"
+ | "--workspace-observation-fixture";
function run(action: FixtureAction, scenario: string) {
const result = spawnSync(native, [action, scenario], { encoding: "utf8" });
@@ -50,6 +53,15 @@ describe("native single-pass AX selectors", () => {
"permission-hidden-ancestor",
"permission-offwindow",
"mode-inside",
+ "mode-repeated-attributes",
+ "dictation-repeated-attributes",
+ "dictation-duplicate-controls",
+ "recording-no-editor",
+ "recording-no-cancel",
+ "recording-duplicate",
+ "recording-hidden",
+ "recording-off-owner",
+ "recording-unrelated-owner",
"mode-outside",
"mode-hidden-ancestor",
"mode-offwindow",
@@ -77,6 +89,7 @@ describe("native single-pass AX selectors", () => {
it.each([
"add-project",
+ "add-project-current",
"add-project-sidebar",
"add-project-unrelated",
"add-project-sibling-unequal",
@@ -200,6 +213,9 @@ describe("native picker ladder and approval cycle", () => {
it("reads the picker title and maps effort to Power segments", () => {
for (const scenario of [
"title-medium",
+ "picker-chat-title",
+ "picker-duplicate",
+ "picker-hidden",
"title-extra-high",
"title-light",
"title-unreadable",
@@ -225,3 +241,47 @@ describe("native picker ladder and approval cycle", () => {
}
});
});
+
+describe("current desktop workspace observations", () => {
+ it.each([
+ "review-selected",
+ "review-tiny-tab-list",
+ "review-tiny-tab-list-hidden",
+ "review-tiny-tab-list-offwindow",
+ "browser-tiny-tab-list",
+ "review-hidden",
+ "review-transcript",
+ "review-unselected",
+ "browser-selected",
+ "browser-no-address",
+ "browser-unselected",
+ "side-selected",
+ "side-transcript",
+ "sidebar-repeated-attributes",
+ "sidebar-duplicate",
+ ])("checks actual controls: %s", (scenario) => {
+ expect(run("--workspace-observation-fixture", scenario).status).toBe(0);
+ });
+});
+
+describe("current composer-replacing approval card", () => {
+ it.each([
+ "current-card",
+ "hidden",
+ "offwindow",
+ "disabled",
+ "split-owner",
+ "missing-options",
+ "duplicate",
+ "composer-present",
+ ])("checks %s", (scenario) => {
+ expect(run("--approval-card-fixture", scenario).status).toBe(0);
+ });
+});
+
+it.each(["delayed", "closed", "stuck"])(
+ "verifies picker dismissal: %s",
+ (scenario) => {
+ expect(run("--picker-dismissal-fixture", scenario).status).toBe(0);
+ },
+);
diff --git a/test/native-workflow.fixture.test.ts b/test/native-workflow.fixture.test.ts
index 1da96b9..58b57f6 100644
--- a/test/native-workflow.fixture.test.ts
+++ b/test/native-workflow.fixture.test.ts
@@ -122,7 +122,7 @@ describe("native workflow postcondition fixture", () => {
expect(run({ markerBefore: 1, markerAfter: 1 })).toBe(1);
expect(
run({
- sameComposer: true,
+ uniqueComposerInCapturedWindow: true,
draftIsEmpty: true,
messagesBefore: 0,
messagesAfter: 1,
@@ -130,7 +130,7 @@ describe("native workflow postcondition fixture", () => {
).toBe(0);
expect(
run({
- sameComposer: false,
+ uniqueComposerInCapturedWindow: false,
draftIsEmpty: true,
messagesBefore: 0,
messagesAfter: 1,
@@ -138,12 +138,30 @@ describe("native workflow postcondition fixture", () => {
).toBe(1);
expect(
run({
- sameComposer: true,
+ uniqueComposerInCapturedWindow: true,
draftIsEmpty: true,
messagesBefore: 0,
messagesAfter: 0,
}),
).toBe(1);
+ expect(
+ run({
+ uniqueComposerInCapturedWindow: true,
+ draftIsEmpty: true,
+ messagesBefore: 2,
+ messagesAfter: 2,
+ newMessageObserved: true,
+ }),
+ ).toBe(0);
+ expect(
+ run({
+ uniqueComposerInCapturedWindow: true,
+ draftIsEmpty: true,
+ messagesBefore: 2,
+ messagesAfter: 2,
+ newMessageObserved: false,
+ }),
+ ).toBe(1);
expect(run({ pendingRemains: false })).toBe(0);
expect(run({ pendingRemains: true })).toBe(1);
expect(run({ sidebarBefore: true, sidebarAfter: false })).toBe(0);
diff --git a/test/profile-keys.behavior.test.ts b/test/profile-keys.behavior.test.ts
index 7a7a451..edbe99b 100644
--- a/test/profile-keys.behavior.test.ts
+++ b/test/profile-keys.behavior.test.ts
@@ -112,6 +112,18 @@ const harness = vi.hoisted(() => {
};
});
+// This suite exercises the unchanged Codex adapter; mixed-provider routing has
+// its own event-level integration suite.
+vi.mock("../src/lib/providers/router.js", () => ({
+ ProviderAction: class {
+ constructor(action: { refreshAll?: () => Promise }) {
+ action.refreshAll ??= async () => undefined;
+ return action;
+ }
+ },
+ observeProviders: async () => undefined,
+ serializeProviders: (work: () => Promise) => work(),
+}));
vi.mock("../src/lib/automation.js", () => ({
cleanupDictation: harness.cleanupDictation,
endDictation: harness.endDictation,
@@ -472,6 +484,29 @@ describe("executable 50-key profile contract", () => {
},
);
+ it("keeps a rotated command dial selection after a page change", async () => {
+ const handler = new CommandAction();
+ const dial = new FakeStreamDeckAction>(
+ { commandId: "fast" },
+ "dial",
+ );
+ await handler.onWillAppear(keyDown(dial) as any);
+ await handler.onDialRotate({
+ ...keyDown(dial),
+ payload: { ...keyDown(dial).payload, ticks: 1 },
+ } as any);
+ expect(dial.currentSettings()).toMatchObject({
+ commandId: "plan",
+ commandIndex: 1,
+ });
+ await handler.onWillDisappear(keyDown(dial) as any);
+ await handler.onWillAppear(keyDown(dial) as any);
+ await handler.onDialUp(keyDown(dial) as any);
+ expect(harness.executeCommand).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id: "plan" }),
+ expect.any(String),
+ );
+ });
it("uses keypad keyDown, not dial events, for Plan Mode and FAST", async () => {
for (const commandId of ["plan", "fast"]) {
const row = PROFILE_KEY_CONTRACT.find(
diff --git a/test/provider-key-press.test.ts b/test/provider-key-press.test.ts
new file mode 100644
index 0000000..2de2aed
--- /dev/null
+++ b/test/provider-key-press.test.ts
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ FakeStreamDeckAction,
+ keyEvent,
+} from "./helpers/fake-streamdeck-action.js";
+const data = vi.hoisted(() => ({
+ usage: { usedPercent: 25, resetsAvailable: 4 },
+ context: {
+ usedTokens: 20000,
+ maxTokens: 100000,
+ remainingPercent: 80,
+ observedAt: Date.now(),
+ threadId: "qa",
+ },
+}));
+vi.mock("../src/lib/codex-store.js", () => ({
+ codexStore: {
+ usageSnapshotCached: () => data.usage,
+ contextSnapshot: () => data.context,
+ },
+}));
+vi.mock("@elgato/streamdeck", () => ({
+ action: () => () => undefined,
+ SingletonAction: class {
+ actions: any[] = [];
+ },
+}));
+vi.mock("../src/lib/render-cache.js", () => ({
+ renderKey: (a: FakeStreamDeckAction, image: string) => a.setImage(image),
+}));
+import { CodexWeeklyAction } from "../src/actions/provider-weekly.js";
+import { CodexContextAction } from "../src/actions/provider-context.js";
+const svg = (key: FakeStreamDeckAction) =>
+ Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!.value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+describe("fixed Codex key press behavior", () => {
+ beforeEach(() => vi.clearAllMocks());
+ it.each([
+ [CodexWeeklyAction, "CODEX LEFT", "CODEX RESETS"],
+ [CodexContextAction, "CODEX CONTEXT", "CODEX TOKENS"],
+ ] as const)(
+ "toggles, retains state during refresh, and returns for %s",
+ async (Type, initial, pressed) => {
+ const action = new Type();
+ const key = new FakeStreamDeckAction({});
+ const event = keyEvent(key) as never;
+ await action.onWillAppear(event);
+ expect(svg(key)).toContain(initial);
+ await action.onKeyDown(event);
+ expect(svg(key)).toContain(pressed);
+ if (pressed === "CODEX RESETS") {
+ expect(svg(key)).toContain(">4");
+ expect(svg(key)).toContain("AVAILABLE");
+ }
+ (action.actions as unknown as any[]).push(key);
+ await action.refreshAll();
+ expect(svg(key)).toContain(pressed);
+ await action.onKeyDown(event);
+ expect(svg(key)).toContain(initial);
+ expect(key.calls.some((c) => c.method === "showAlert")).toBe(false);
+ },
+ );
+});
diff --git a/test/provider-router.test.ts b/test/provider-router.test.ts
new file mode 100644
index 0000000..5001a5b
--- /dev/null
+++ b/test/provider-router.test.ts
@@ -0,0 +1,890 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+const fake = vi.hoisted(() => ({
+ observation: {} as any,
+ read: vi.fn(),
+ perform: vi.fn(),
+ focused: { id: "codex-1" },
+ composer: { rendererWindowId: "window-1" },
+ actions: [] as any[],
+}));
+vi.mock("../src/lib/providers/claude.js", () => ({
+ claudeProvider: {
+ read: () => fake.read(),
+ perform: (...args: any[]) => fake.perform(...args),
+ },
+}));
+vi.mock("../src/lib/codex-store.js", () => ({
+ codexStore: {
+ focusedThread: () => fake.focused,
+ liveComposerState: () => fake.composer,
+ },
+}));
+vi.mock("@elgato/streamdeck", () => ({
+ SingletonAction: class {
+ get actions() {
+ return fake.actions;
+ }
+ },
+ default: { logger: { warn: vi.fn() } },
+}));
+import { SingletonAction } from "@elgato/streamdeck";
+import {
+ ProviderAction,
+ observeProviders,
+ serializeProviders,
+} from "../src/lib/providers/router.js";
+import {
+ FakeStreamDeckAction,
+ keyEvent,
+} from "./helpers/fake-streamdeck-action.js";
+
+const target = {
+ provider: "claude",
+ windowId: "4:8",
+ sessionId: "claude-1",
+ environment: "local",
+};
+function action(
+ kind: string,
+ options: ConstructorParameters[1] = {},
+) {
+ class Legacy extends SingletonAction {
+ override manifestId = `com.todd.streamdeckcodex.${kind}`;
+ onKeyDown = vi.fn();
+ onKeyUp = vi.fn();
+ onDialUp = vi.fn();
+ onDialRotate = vi.fn();
+ onWillAppear = vi.fn();
+ onDidReceiveSettings = vi.fn();
+ onWillDisappear = vi.fn();
+ refreshAll = vi.fn(async () => {
+ for (const a of this.actions)
+ if (a.isKey() || a.isDial()) await a.setTitle("codex");
+ });
+ }
+ const legacy = new Legacy();
+ return { legacy, router: new ProviderAction(legacy, options) };
+}
+beforeEach(() => {
+ vi.clearAllMocks();
+ fake.actions.splice(0);
+ fake.observation = {
+ foreground: "claude",
+ target,
+ model: "Fable 5.1",
+ effort: "High",
+ permission: "Auto",
+ capabilities: ["send"],
+ observedAt: Date.now(),
+ };
+ fake.read.mockImplementation(async () => ({
+ ...fake.observation,
+ observedAt: Date.now(),
+ }));
+ fake.perform.mockImplementation(async () => ({
+ ...fake.observation,
+ observedAt: Date.now(),
+ }));
+});
+describe("shared action adapter", () => {
+ it("shares one observation across a queued page of controls", async () => {
+ const { router } = action("model");
+ const dials = Array.from({ length: 12 }, (_, i) => {
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ Object.defineProperty(dial, "id", { value: `batch-${i}` });
+ return dial;
+ });
+ await Promise.all(dials.map((dial) => router.onWillAppear(keyEvent(dial))));
+ expect(fake.read).toHaveBeenCalledTimes(1);
+ for (const dial of dials)
+ expect(
+ dial.calls.filter((c) => c.method === "setFeedback").at(-1)?.value,
+ ).toMatchObject({ value: "Fable 5.1" });
+ await router.onDialRotate({
+ ...keyEvent(dials[0]!),
+ payload: { ...keyEvent(dials[0]!).payload, ticks: 1 },
+ });
+ expect(fake.read.mock.calls.length).toBeGreaterThan(1);
+ });
+ it("discards an obsolete page before its queued appearance can read or render", async () => {
+ let release!: () => void;
+ const blocked = serializeProviders(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ await Promise.resolve();
+ const { router } = action("model");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ const appeared = router.onWillAppear(keyEvent(dial));
+ await router.onWillDisappear(keyEvent(dial));
+ release();
+ await Promise.all([blocked, appeared]);
+ await router.refreshAll();
+ expect(fake.read).not.toHaveBeenCalled();
+ expect(dial.calls).toEqual([]);
+ });
+ it("does not revive a page that disappeared during its observation", async () => {
+ let release!: (value: any) => void;
+ fake.read.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ const { router } = action("model");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ const appeared = router.onWillAppear(keyEvent(dial));
+ await vi.waitFor(() => expect(fake.read).toHaveBeenCalledOnce());
+ await router.onWillDisappear(keyEvent(dial));
+ release({ ...fake.observation, observedAt: Date.now() });
+ await appeared;
+ await router.refreshAll();
+ expect(dial.calls).toEqual([]);
+ });
+ it("resends unchanged dial feedback when the host restores a page", async () => {
+ const { router } = action("model");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ await router.onWillDisappear(keyEvent(dial));
+ await router.onWillAppear(keyEvent(dial));
+ expect(dial.calls.filter((c) => c.method === "setFeedback")).toHaveLength(
+ 2,
+ );
+ });
+
+ it("preserves legacy Codex events even when Claude is foreground", async () => {
+ const { legacy, router } = action("command");
+ const key = new FakeStreamDeckAction({ commandId: "send" });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ expect(legacy.onKeyDown).toHaveBeenCalledTimes(1);
+ expect(fake.perform).not.toHaveBeenCalled();
+ });
+ it.each([
+ "command",
+ "keycap",
+ "workflow",
+ "approval-mode",
+ "model",
+ "reasoning",
+ "agent-status",
+ "agent-navigator",
+ "usage",
+ "context",
+ "health",
+ ])("never dispatches a Claude %s to Codex", async (kind) => {
+ const { legacy, router } = action(kind);
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ commandId: "send",
+ action: "command:send",
+ workflowId: "debug",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ expect(legacy.onKeyDown).not.toHaveBeenCalled();
+ expect(legacy.onWillAppear).not.toHaveBeenCalled();
+ });
+ it("does not reuse an automatic binding after switching to another app", async () => {
+ const { legacy, router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "auto",
+ commandId: "send",
+ });
+ await router.onWillAppear(keyEvent(key));
+ fake.observation = {};
+ await router.onKeyDown(keyEvent(key));
+ expect(legacy.onKeyDown).not.toHaveBeenCalled();
+ expect(fake.perform).not.toHaveBeenCalled();
+ expect(key.calls.some((c) => c.method === "showAlert")).toBe(true);
+ });
+ it("returns key release to Codex after switching provider", async () => {
+ fake.observation.foreground = "codex";
+ const { legacy, router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "auto",
+ commandId: "dictate",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ fake.observation.foreground = "claude";
+ await router.onKeyUp(keyEvent(key));
+ expect(legacy.onKeyUp).toHaveBeenCalledTimes(1);
+ });
+ it("cancels a model preview when the session changes before press", async () => {
+ fake.perform.mockImplementation(async () => ({
+ ...fake.observation,
+ observedAt: Date.now(),
+ options: [
+ { value: "Fable 5.1", label: "Fable 5.1" },
+ { value: "Sonnet 4.6", label: "Sonnet 4.6" },
+ ],
+ }));
+ const { router } = action("model");
+ const dial = new FakeStreamDeckAction({ provider: "auto" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { settings: { provider: "auto" }, ticks: 1 },
+ });
+ fake.observation.target = { ...target, sessionId: "other" };
+ await router.onDialUp(keyEvent(dial));
+ expect(fake.perform.mock.calls.map((c) => c[0].operation)).toEqual([
+ "model-options",
+ ]);
+ });
+ it("excludes Claude keys from legacy refresh and renders a provider badge", async () => {
+ const { router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ commandId: "send",
+ });
+ fake.actions.push(key);
+ await router.onWillAppear(keyEvent(key));
+ await observeProviders();
+ await router.refreshAll();
+ expect(
+ key.calls.filter((c) => c.method === "setTitle" && c.value === "codex"),
+ ).toHaveLength(0);
+ const image = key.calls.find((c) => c.method === "setImage")!
+ .value as string;
+ expect(Buffer.from(image.split(",")[1]!, "base64").toString()).toContain(
+ ">CLAUDE",
+ );
+ });
+ it.each(["claude-weekly", "claude-context", "usage", "context", "health"])(
+ "pressing %s refreshes without commands or alerts across app/session changes",
+ async (kind) => {
+ const { router } = action(kind, { kind, provider: "claude" });
+ const key = new FakeStreamDeckAction({});
+ await router.onWillAppear(keyEvent(key));
+ for (const state of [
+ fake.observation,
+ { ...fake.observation, target: { ...target, sessionId: "changed" } },
+ { foreground: "codex" },
+ { reason: "NO DATA" },
+ ]) {
+ fake.observation = state;
+ const before = fake.read.mock.calls.length;
+ await router.onKeyDown(keyEvent(key));
+ await router.onKeyUp(keyEvent(key));
+ expect(fake.read.mock.calls.length).toBeGreaterThan(before);
+ }
+ expect(fake.perform).not.toHaveBeenCalled();
+ expect(key.calls.some((c) => c.method === "showAlert")).toBe(false);
+ },
+ );
+ it("cycles Claude allowance, weekly resets and Fable resets with cached counts after focus changes", async () => {
+ Object.assign(fake.observation, {
+ weeklyResetsAvailable: 2,
+ fableResetsAvailable: 1,
+ });
+ const { router } = action("claude-weekly", {
+ kind: "claude-weekly",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ const image = () =>
+ Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!
+ .value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ await router.onKeyUp(keyEvent(key));
+ expect(image()).toContain("WEEKLY RESETS");
+ expect(image()).toContain(">2");
+ fake.observation = { foreground: "codex" };
+ await router.onKeyDown(keyEvent(key));
+ await router.onKeyUp(keyEvent(key));
+ expect(image()).toContain("FABLE RESETS");
+ expect(image()).toContain(">1");
+ expect(image()).toContain("CACHED");
+ await router.onKeyDown(keyEvent(key));
+ expect(image()).toContain("CLAUDE LEFT");
+ expect(fake.perform).not.toHaveBeenCalled();
+ expect(key.calls.some((c) => c.method === "showAlert")).toBe(false);
+ });
+ it("uses a generic reset hint without inventing type or count and drops it on expiry/account switch", async () => {
+ Object.assign(fake.observation, {
+ claudeAccountId: "account-hint",
+ resetAvailabilityHint: {
+ accountId: "account-hint",
+ checkedAt: Date.now() - 1000,
+ validUntil: Date.now() + 60000,
+ },
+ });
+ const { router } = action("claude-weekly", {
+ kind: "claude-weekly",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ const image = () =>
+ Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!
+ .value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ await router.onKeyUp(keyEvent(key));
+ expect(image()).toContain(">AVAILABLE");
+ expect(image()).toContain("CACHED STATUS");
+ expect(image()).not.toContain("FABLE");
+ expect(image()).not.toContain("WEEKLY");
+ await router.onKeyDown(keyEvent(key));
+ await router.onKeyUp(keyEvent(key));
+ expect(image()).toContain("CLAUDE LEFT");
+ fake.observation.resetAvailabilityHint.validUntil = Date.now() - 1;
+ await router.onKeyDown(keyEvent(key));
+ await router.onKeyUp(keyEvent(key));
+ expect(image()).toContain("NO DATA");
+ fake.observation.claudeAccountId = "other-account";
+ fake.observation.resetAvailabilityHint.validUntil = Date.now() + 60000;
+ await observeProviders();
+ await router.refreshAll();
+ expect(image()).not.toContain(">AVAILABLE");
+ expect(fake.perform).not.toHaveBeenCalled();
+ });
+ it("keeps exact reset counts ahead of the generic hint and clears them across accounts", async () => {
+ Object.assign(fake.observation, {
+ claudeAccountId: "exact-account",
+ weeklyResetsAvailable: 2,
+ fableResetsAvailable: 1,
+ resetAvailabilityHint: {
+ accountId: "exact-account",
+ checkedAt: Date.now() - 1000,
+ validUntil: Date.now() + 60000,
+ },
+ });
+ const { router } = action("claude-weekly", {
+ kind: "claude-weekly",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ const image = () =>
+ Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!
+ .value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ expect(image()).toContain(">2");
+ fake.observation = {
+ claudeAccountId: "another-account",
+ foreground: "claude",
+ };
+ await observeProviders();
+ await router.refreshAll();
+ expect(image()).toContain("NO DATA");
+ expect(image()).not.toContain(">2");
+ });
+ it.each(["model", "reasoning", "command", "workflow", "agent-navigator"])(
+ "does not queue an unused %s dial-down before commit",
+ async (kind) => {
+ const { router } = action(kind);
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ const before = fake.read.mock.calls.length;
+ await router.onDialDown(keyEvent(dial));
+ expect(fake.read.mock.calls.length).toBe(before);
+ expect(fake.perform).not.toHaveBeenCalled();
+ },
+ );
+ it("shows automatic Project context and fixed effort without attempting a change", async () => {
+ Object.assign(fake.observation, {
+ readOnlyScope: "chan_project",
+ effort: "Fixed",
+ contextAvailability: "automatic",
+ usageUsedPercent: 53,
+ usagePeriod: "Weekly",
+ usageAvailability: "ready",
+ capabilities: ["model", "model-options", "usage"],
+ });
+ const { router } = action("reasoning");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { settings: { provider: "claude" }, ticks: 1 },
+ });
+ await router.onDialUp(keyEvent(dial));
+ expect(
+ dial.calls.filter((c) => c.method === "setFeedback").at(-1)?.value,
+ ).toMatchObject({ value: "Fixed" });
+ expect(dial.calls.some((c) => c.method === "showAlert")).toBe(false);
+ expect(fake.perform).not.toHaveBeenCalled();
+ const { router: context } = action("claude-context", {
+ kind: "claude-context",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ await context.onWillAppear(keyEvent(key));
+ const image = Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!.value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+ expect(image).toContain(">AUTO");
+ expect(image).toContain("COMPACTION");
+ expect(image).not.toContain("CACHED");
+ });
+ it("keeps the last Claude weekly value visible after Claude moves to the background", async () => {
+ fake.observation.weeklyUsedPercent = 32;
+ fake.observation.weeklyBucket = "Fable";
+ const { router } = action("claude-weekly", {
+ kind: "claude-weekly",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({ provider: "codex" });
+ await router.onWillAppear(keyEvent(key));
+
+ fake.observation = {
+ foreground: "codex",
+ observedAt: Date.now(),
+ };
+ await observeProviders();
+ await router.refreshAll();
+
+ const image = key.calls.filter((call) => call.method === "setImage").at(-1)!
+ .value as string;
+ const svg = Buffer.from(image.split(",")[1]!, "base64").toString();
+ expect(svg).toContain("CLAUDE LEFT");
+ expect(svg).toContain(">68%");
+ expect(svg).toContain(">CACHED");
+ expect(svg).not.toContain("BACKGROUND");
+ expect(svg.match(/CLAUDE/g)).toHaveLength(1);
+ });
+ it("keeps Claude context for one verified session and clears it on a session switch", async () => {
+ fake.observation.contextUsedPercent = 18;
+ const { router } = action("claude-context", {
+ kind: "claude-context",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ await router.onWillAppear(keyEvent(key));
+
+ fake.observation = { foreground: "codex", observedAt: Date.now() };
+ await observeProviders();
+ await router.refreshAll();
+ let image = key.calls.filter((call) => call.method === "setImage").at(-1)!
+ .value as string;
+ let svg = Buffer.from(image.split(",")[1]!, "base64").toString();
+ expect(svg).toContain("CLAUDE CONTEXT");
+ expect(svg).toContain(">82%");
+ expect(svg.match(/CLAUDE/g)).toHaveLength(1);
+
+ fake.observation = {
+ foreground: "claude",
+ target: { ...target, sessionId: "claude-2" },
+ observedAt: Date.now(),
+ };
+ await observeProviders();
+ await router.refreshAll();
+ image = key.calls.filter((call) => call.method === "setImage").at(-1)!
+ .value as string;
+ svg = Buffer.from(image.split(",")[1]!, "base64").toString();
+ expect(svg).toContain("CLAUDE CONTEXT");
+ expect(svg).toContain("NO DATA");
+ expect(svg).not.toContain(">82%");
+ });
+ it("clears a removed Claude quota instead of showing its cached weekly value", async () => {
+ Object.assign(fake.observation, {
+ usageUsedPercent: 32,
+ usagePeriod: "Weekly",
+ usageBucket: "Fable",
+ usageAvailability: "ready",
+ });
+ const { router } = action("claude-weekly", {
+ kind: "claude-weekly",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ await router.onWillAppear(keyEvent(key));
+ delete fake.observation.usageUsedPercent;
+ fake.observation.usageAvailability = "unavailable";
+ await observeProviders();
+ await router.refreshAll();
+ const svg = Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!.value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+ expect(svg).toContain("NO DATA");
+ expect(svg).toContain("NOT EXPOSED");
+ expect(svg).not.toContain(">68%");
+ });
+ it("labels a nonweekly Claude quota with its actual period", async () => {
+ Object.assign(fake.observation, {
+ usageUsedPercent: 12,
+ usagePeriod: "Session",
+ usageAvailability: "ready",
+ });
+ const { router } = action("claude-weekly", {
+ kind: "claude-weekly",
+ provider: "claude",
+ });
+ const key = new FakeStreamDeckAction({});
+ await router.onWillAppear(keyEvent(key));
+ const svg = Buffer.from(
+ (
+ key.calls.filter((c) => c.method === "setImage").at(-1)!.value as string
+ ).split(",")[1]!,
+ "base64",
+ ).toString();
+ expect(svg).toContain(">88%");
+ expect(svg).toContain(">SESSION");
+ expect(svg).not.toContain("WEEKLY");
+ });
+ it.each(["command", "keycap"])(
+ "renders active Fast consistently on %s keys",
+ async (kind) => {
+ fake.observation.fast = true;
+ fake.observation.capabilities = ["fast"];
+ const { router } = action(kind);
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ commandId: "fast",
+ action: "command:fast",
+ label: "FAST",
+ icon: "fast",
+ });
+ await router.onWillAppear(keyEvent(key));
+ const image = key.calls.filter((c) => c.method === "setImage").at(-1)!
+ .value as string;
+ const svg = Buffer.from(image.split(",")[1]!, "base64").toString();
+ expect(svg).toContain(">ACTIVE");
+ expect(svg).toContain('fill="#F4B740" stroke="#F4B740"');
+ expect(svg).not.toContain("UNSUPPORTED");
+ },
+ );
+ it("honors legacy command dial indexes and preserves rotation across reappearance", async () => {
+ fake.observation.capabilities = ["plan", "compact"];
+ const { router } = action("command");
+ const dial = new FakeStreamDeckAction>(
+ { provider: "claude", commandIndex: 1 },
+ "dial",
+ );
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialUp(keyEvent(dial));
+ expect(fake.perform).toHaveBeenLastCalledWith(
+ expect.objectContaining({ operation: "plan" }),
+ );
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { ...keyEvent(dial).payload, ticks: 1 },
+ });
+ expect(dial.currentSettings()).toMatchObject({
+ commandId: "compact",
+ commandIndex: 2,
+ });
+ await router.onWillDisappear(keyEvent(dial));
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialUp(keyEvent(dial));
+ expect(fake.perform).toHaveBeenLastCalledWith(
+ expect.objectContaining({ operation: "compact" }),
+ );
+ });
+ it("shows the actual Fast mode state on a command dial", async () => {
+ fake.observation.fast = true;
+ fake.observation.capabilities = ["fast"];
+ const { router } = action("command");
+ const dial = new FakeStreamDeckAction(
+ { provider: "claude", commandId: "fast" },
+ "dial",
+ );
+ await router.onWillAppear(keyEvent(dial));
+ expect(
+ dial.calls.filter((c) => c.method === "setFeedback").at(-1)?.value,
+ ).toMatchObject({ value: "ACTIVE" });
+ });
+ it("previews and selects Ultracode by name on the effort dial", async () => {
+ fake.observation.effort = "Max";
+ fake.perform.mockImplementation(async () => ({
+ ...fake.observation,
+ observedAt: Date.now(),
+ options: [
+ { value: "slider:4", label: "Max" },
+ { value: "slider:5", label: "Ultracode" },
+ ],
+ }));
+ const { router } = action("reasoning");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { settings: { provider: "claude" }, ticks: 1 },
+ });
+ expect(
+ dial.calls.filter((c) => c.method === "setFeedback").at(-1)?.value,
+ ).toMatchObject({
+ value: "Ultracode",
+ indicator: { value: 100, bar_fill_c: "#F4B740" },
+ });
+ await router.onDialUp(keyEvent(dial));
+ expect(fake.perform.mock.calls.at(-1)![0]).toMatchObject({
+ operation: "reasoning",
+ value: "slider:5",
+ });
+ });
+ it("keeps the Claude model position bar after applying a preview", async () => {
+ fake.perform.mockImplementation(async (request) => ({
+ ...fake.observation,
+ model: request.operation === "model" ? request.value : "Fable 5.1",
+ observedAt: Date.now(),
+ ...(request.operation === "model-options"
+ ? {
+ options: [
+ { value: "Fable 5.1", label: "Fable 5.1" },
+ { value: "Opus 5", label: "Opus 5" },
+ { value: "Sonnet 5", label: "Sonnet 5" },
+ { value: "Haiku 4.5", label: "Haiku 4.5" },
+ ],
+ }
+ : {}),
+ }));
+ const { router } = action("model");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { settings: { provider: "claude" }, ticks: 1 },
+ });
+ const preview = dial.calls.filter((c) => c.method === "setFeedback").at(-1)
+ ?.value as any;
+ expect(preview).toMatchObject({
+ value: "Opus 5",
+ indicator: { bar_fill_c: "#F4B740" },
+ });
+ expect(preview.indicator.value).toBeCloseTo(100 / 3);
+ await router.onDialUp(keyEvent(dial));
+ const applied = dial.calls.filter((c) => c.method === "setFeedback").at(-1)
+ ?.value as any;
+ expect(applied).toMatchObject({
+ value: "Opus 5",
+ indicator: { bar_fill_c: "#E7A589" },
+ });
+ expect(applied.indicator.value).toBeCloseTo(100 / 3);
+ });
+ it("cancels effort previews and their bar when the model changes in the same session", async () => {
+ fake.perform.mockImplementation(async () => ({
+ ...fake.observation,
+ options: [
+ { value: "Low", label: "Low" },
+ { value: "High", label: "High" },
+ ],
+ observedAt: Date.now(),
+ }));
+ const { router } = action("reasoning");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { ...keyEvent(dial).payload, ticks: 1 },
+ });
+ fake.observation.model = "Sonnet 5.5";
+ await observeProviders();
+ await router.refreshAll();
+ expect(
+ dial.calls.filter((c) => c.method === "setFeedback").at(-1)?.value,
+ ).toMatchObject({ value: "High", indicator: { value: 0 } });
+ fake.perform.mockClear();
+ await router.onDialUp(keyEvent(dial));
+ expect(fake.perform).not.toHaveBeenCalled();
+ });
+ it.each(["command", "keycap", "dial"])(
+ "restores Bypass through the %s Plan control",
+ async (surface) => {
+ fake.observation.target = {
+ ...target,
+ sessionId: `bypass-plan-${surface}`,
+ };
+ fake.observation.permission = "Bypass permissions";
+ const { router } = action(surface === "keycap" ? "keycap" : "command");
+ const key = new FakeStreamDeckAction(
+ { provider: "claude", commandId: "plan", action: "command:plan" },
+ surface === "dial" ? "dial" : "key",
+ );
+ await router.onWillAppear(keyEvent(key));
+ fake.observation.permission = "Plan";
+ if (surface === "dial") await router.onDialUp(keyEvent(key));
+ else await router.onKeyDown(keyEvent(key));
+ expect(fake.perform.mock.calls.at(-1)![0]).toMatchObject({
+ operation: "plan",
+ value: "Bypass permissions",
+ });
+ },
+ );
+ it("remembers a prior permission mode per exact session for Plan toggle", async () => {
+ const { router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ commandId: "plan",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ fake.observation.permission = "Plan";
+ await router.onKeyDown(keyEvent(key));
+ expect(fake.perform.mock.calls.at(-1)![0].value).toBe("Auto");
+ fake.observation.target = {
+ ...target,
+ sessionId: "plan-with-no-observed-prior-mode",
+ };
+ await router.onKeyDown(keyEvent(key));
+ expect(fake.perform).toHaveBeenCalledTimes(2);
+ // A second press after the new target is rendered cannot restore the old
+ // session's permission mode.
+ await router.onKeyDown(keyEvent(key));
+ expect(fake.perform.mock.calls.at(-1)![0].value).toBeUndefined();
+ });
+ it("remembers an observed mode when Plan is entered through another control", async () => {
+ fake.observation.target = {
+ ...target,
+ sessionId: "external-plan-transition",
+ };
+ fake.observation.permission = "Manual";
+ const { router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ commandId: "plan",
+ });
+ await router.onWillAppear(keyEvent(key));
+ fake.observation.permission = "Plan";
+ await router.onKeyDown(keyEvent(key));
+ expect(fake.perform.mock.calls.at(-1)![0].value).toBe("Manual");
+ });
+ it("releases Codex PTT with its original settings while a provider read is pending", async () => {
+ const { legacy, router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "codex",
+ commandId: "dictate",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ let release!: () => void;
+ fake.read.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = () =>
+ resolve({ ...fake.observation, observedAt: Date.now() });
+ }),
+ );
+ const other = action("model");
+ const dial = new FakeStreamDeckAction({ provider: "claude" }, "dial");
+ const pending = other.router.onWillAppear(keyEvent(dial));
+ await Promise.resolve();
+ await Promise.resolve();
+ await router.onKeyUp({
+ action: key,
+ payload: { settings: { provider: "claude", commandId: "send" } },
+ });
+ expect(legacy.onKeyUp).toHaveBeenCalledTimes(1);
+ expect(
+ (legacy.onKeyUp.mock.calls[0] as any)[0].payload.settings.commandId,
+ ).toBe("dictate");
+ release();
+ await pending;
+ });
+ it("does not start automatic PTT after its key was released during target observation", async () => {
+ fake.observation.foreground = "codex";
+ const { legacy, router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "auto",
+ commandId: "dictate",
+ });
+ await router.onWillAppear(keyEvent(key));
+ let release!: () => void;
+ fake.read.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = () =>
+ resolve({ ...fake.observation, observedAt: Date.now() });
+ }),
+ );
+ const down = router.onKeyDown(keyEvent(key));
+ await Promise.resolve();
+ await Promise.resolve();
+ const up = router.onKeyUp(keyEvent(key));
+ release();
+ await down;
+ await up;
+ expect(legacy.onKeyDown).not.toHaveBeenCalled();
+ });
+});
+
+describe("Claude controls after the live audit", () => {
+ it("releases recording against its captured Claude target after an app switch", async () => {
+ const { router, legacy } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "auto",
+ commandId: "dictate",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ expect(fake.perform).toHaveBeenLastCalledWith({
+ operation: "dictate",
+ target,
+ });
+ fake.observation = { foreground: "codex", observedAt: Date.now() };
+ await router.onKeyUp(keyEvent(key));
+ expect(fake.perform).toHaveBeenLastCalledWith({
+ operation: "dictation-stop",
+ target,
+ });
+ expect(legacy.onKeyUp).not.toHaveBeenCalled();
+ });
+ it("stops recording when its key disappears", async () => {
+ const { router } = action("command");
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ commandId: "dictate",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ await router.onWillDisappear(keyEvent(key));
+ expect(fake.perform).toHaveBeenLastCalledWith({
+ operation: "dictation-stop",
+ target,
+ });
+ });
+ it("skips unavailable commands instead of offering dead dial positions", async () => {
+ fake.observation.capabilities = ["files", "compact"];
+ const { router } = action("command");
+ const dial = new FakeStreamDeckAction(
+ { provider: "claude", commandId: "fast" },
+ "dial",
+ );
+ await router.onWillAppear(keyEvent(dial));
+ await router.onDialRotate({
+ ...keyEvent(dial),
+ payload: { settings: dial.currentSettings(), ticks: 1 },
+ } as any);
+ expect(
+ dial.calls.filter((c) => c.method === "setSettings").at(-1)?.value,
+ ).toMatchObject({ commandId: "compact" });
+ });
+ it("does not silently ignore a Claude workflow's saved Codex folder override", async () => {
+ const { router } = action("workflow");
+ const key = new FakeStreamDeckAction({
+ provider: "claude",
+ workflowId: "debug",
+ path: "/different-project",
+ });
+ await router.onWillAppear(keyEvent(key));
+ await router.onKeyDown(keyEvent(key));
+ expect(fake.perform).not.toHaveBeenCalled();
+ expect(key.calls.some((c) => c.method === "showAlert")).toBe(true);
+ });
+});
diff --git a/test/providers.test.ts b/test/providers.test.ts
new file mode 100644
index 0000000..92bc14a
--- /dev/null
+++ b/test/providers.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ resolveProvider,
+ targetKey,
+ sameTarget,
+ freshObservation,
+ type TargetIdentity,
+} from "../src/lib/providers/types.js";
+import { ClaudeProvider } from "../src/lib/providers/claude.js";
+import {
+ badgeImage,
+ badgeFeedback,
+} from "../src/lib/providers/presentation.js";
+import { svgDataUrl, keycapSvg } from "../src/lib/visuals.js";
+
+const target: TargetIdentity = {
+ provider: "claude",
+ windowId: "7:1",
+ sessionId: "same-id",
+ environment: "local",
+};
+describe("provider identity and compatibility", () => {
+ it("keeps legacy settings on Codex, and never falls back from auto or invalid settings", () => {
+ expect(resolveProvider(undefined, "claude")).toBe("codex");
+ expect(resolveProvider("codex", "claude")).toBe("codex");
+ expect(resolveProvider("claude", "codex")).toBe("claude");
+ expect(resolveProvider("auto", "claude")).toBe("claude");
+ expect(resolveProvider("auto", "codex")).toBe("codex");
+ expect(resolveProvider("auto")).toBeUndefined();
+ expect(resolveProvider("invalid", "codex")).toBeUndefined();
+ });
+ it("separates equal session IDs across apps, windows and environments", () => {
+ for (const changed of [
+ { provider: "codex" },
+ { windowId: "7:2" },
+ { environment: "ssh" },
+ { sessionId: "other" },
+ ]) {
+ expect(
+ sameTarget(target, { ...target, ...changed } as TargetIdentity),
+ ).toBe(false);
+ expect(targetKey(target)).not.toBe(
+ targetKey({ ...target, ...changed } as TargetIdentity),
+ );
+ }
+ expect(sameTarget(target, { ...target })).toBe(true);
+ expect(sameTarget(undefined, undefined)).toBe(false);
+ });
+ it("rejects stale, future and malformed observations", () => {
+ expect(freshObservation({ observedAt: 1000 }, 5000)).toBe(true);
+ expect(freshObservation({ observedAt: 1000 }, 5001)).toBe(false);
+ expect(freshObservation({ observedAt: 1001 }, 1000)).toBe(false);
+ expect(freshObservation({ observedAt: NaN })).toBe(false);
+ });
+ it("adds an app identity without changing legacy artwork", () => {
+ const image = svgDataUrl(keycapSvg("Send", "READY", "send"));
+ expect(badgeImage(image)).toBe(image);
+ expect(
+ Buffer.from(
+ badgeImage(image, "CLAUDE").split(",")[1]!,
+ "base64",
+ ).toString(),
+ ).toContain(">CLAUDE");
+ expect(badgeFeedback({ title: "MODEL", value: "Fable" }, "CLAUDE")).toEqual(
+ { title: "CLAUDE · MODEL", value: "Fable" },
+ );
+ });
+});
+describe("Claude transaction boundary", () => {
+ it.each(["other-app", "different-session", "stale", "no-target"])(
+ "does not mutate after %s",
+ async (situation) => {
+ const state = {
+ foreground: "claude",
+ target,
+ observedAt: Date.now(),
+ ...(situation === "other-app" ? { foreground: "codex" } : {}),
+ ...(situation === "different-session"
+ ? { target: { ...target, sessionId: "other" } }
+ : {}),
+ ...(situation === "stale" ? { observedAt: 1 } : {}),
+ ...(situation === "no-target" ? { target: undefined } : {}),
+ };
+ const call = vi.fn().mockResolvedValue({ providerState: state });
+ const provider = new ClaudeProvider(call);
+ await expect(
+ provider.perform({ operation: "model", value: "Fable", target }),
+ ).rejects.toThrow("Target changed");
+ expect(call).toHaveBeenCalledTimes(1);
+ expect(call.mock.calls[0]![0]).toBe("provider-read");
+ },
+ );
+ it("rejects a Codex target before calling the helper", async () => {
+ const call = vi.fn();
+ await expect(
+ new ClaudeProvider(call).perform({
+ operation: "model",
+ target: { ...target, provider: "codex" },
+ }),
+ ).rejects.toThrow("Wrong provider");
+ expect(call).not.toHaveBeenCalled();
+ });
+ it("passes exact captured identity to the native transaction", async () => {
+ const state = { foreground: "claude", target, observedAt: Date.now() };
+ const call = vi.fn().mockResolvedValue({ providerState: state });
+ await new ClaudeProvider(call).perform({
+ operation: "model",
+ value: "Fable 5.1",
+ target,
+ });
+ expect(call).toHaveBeenCalledTimes(2);
+ const payload = JSON.parse(
+ Buffer.from(call.mock.calls[1]![1], "base64").toString(),
+ );
+ expect(payload).toEqual({ operation: "model", value: "Fable 5.1", target });
+ });
+});
diff --git a/test/ptt-guard.test.ts b/test/ptt-guard.test.ts
index 401c5a0..ad99605 100644
--- a/test/ptt-guard.test.ts
+++ b/test/ptt-guard.test.ts
@@ -178,3 +178,60 @@ describe("push-to-talk dictation lease", () => {
}
});
});
+
+describe("Claude push-to-talk guard", () => {
+ it.each(["parent-close", "max-hold"])(
+ "stops the captured Claude session after %s",
+ async (reason) => {
+ const { directory, log } = fixture();
+ const runner = join(directory, "claude-runner.mjs");
+ const target = {
+ provider: "claude",
+ windowId: "123:456",
+ sessionId: "local_11111111-2222-4333-a444-555555555555",
+ environment: "ssh",
+ };
+ writeFileSync(
+ runner,
+ `#!${process.execPath}\nimport { appendFileSync } from "node:fs";\nconst request = JSON.parse(Buffer.from(process.argv[3], "base64").toString());\nappendFileSync(process.env.STREAMDECK_PTT_TEST_LOG, JSON.stringify(request) + "\\n");\nconsole.log(JSON.stringify({ok:true,providerState:{target:request.target,recording:request.operation === "dictate"}}));\n`,
+ );
+ chmodSync(runner, 0o700);
+ const child = spawn(process.execPath, [guardScript], {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: {
+ ...process.env,
+ STREAMDECK_PTT_TARGET_RUNNER: runner,
+ STREAMDECK_PTT_CLAUDE_TARGET: JSON.stringify(target),
+ STREAMDECK_PTT_TEST_LOG: log,
+ STREAMDECK_PTT_MAX_HOLD_MS: reason === "max-hold" ? "100" : "2000",
+ },
+ });
+ let output = "",
+ error = "";
+ child.stdout.on("data", (chunk) => {
+ output += chunk;
+ if (reason === "parent-close" && output.includes("CLAUDE_READY"))
+ child.stdin.end();
+ });
+ child.stderr.on("data", (chunk) => {
+ error += chunk;
+ });
+ const code = await new Promise((resolve, reject) => {
+ child.once("exit", resolve);
+ child.once("error", reject);
+ });
+ expect(code, error).toBe(0);
+ expect(output).toContain("CLAUDE_READY");
+ expect(output).toContain('"recording":false');
+ expect(
+ readFileSync(log, "utf8")
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line)),
+ ).toEqual([
+ { target, operation: "dictate" },
+ { target, operation: "dictation-stop" },
+ ]);
+ },
+ );
+});
diff --git a/test/reset-cache.test.ts b/test/reset-cache.test.ts
new file mode 100644
index 0000000..541d45d
--- /dev/null
+++ b/test/reset-cache.test.ts
@@ -0,0 +1,51 @@
+import { mkdtemp, writeFile, stat } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ ResetCache,
+ validResetBalance,
+} from "../src/lib/providers/reset-cache.js";
+const accountId = "11111111-1111-4111-8111-111111111111";
+const balance = () => ({
+ accountId,
+ weekly: 2,
+ fable: 1,
+ observedAt: Date.now() - 1000,
+});
+describe("Claude reset cache", () => {
+ it("survives a new instance, updates on a new observation, and isolates accounts", async () => {
+ const path = join(
+ await mkdtemp(join(tmpdir(), "deck-resets-")),
+ "cache.json",
+ );
+ const saved = balance();
+ await new ResetCache(path).write(saved);
+ const restarted = new ResetCache(path);
+ expect(await restarted.read(accountId)).toEqual(saved);
+ expect(
+ await restarted.read("22222222-2222-4222-8222-222222222222"),
+ ).toBeUndefined();
+ expect((await stat(path)).mode & 0o777).toBe(0o600);
+ const next = { ...saved, weekly: 1, observedAt: Date.now() };
+ await restarted.write(next);
+ await restarted.write(saved);
+ expect(await restarted.read(accountId)).toEqual(next);
+ await writeFile(path, "invalid");
+ expect(await restarted.read(accountId)).toBeUndefined();
+ await writeFile(path, " ".repeat(4097));
+ expect(await restarted.read(accountId)).toBeUndefined();
+ });
+ it.each([
+ { weekly: -1 },
+ { fable: 1.5 },
+ { weekly: 1000 },
+ { observedAt: Infinity },
+ { observedAt: Date.now() + 86400000 },
+ { accountId: "wrong" },
+ ])("rejects invalid saved values %j", (patch) => {
+ expect(validResetBalance({ ...balance(), ...patch }, accountId)).toBe(
+ false,
+ );
+ });
+});
diff --git a/test/shared-profiles.test.ts b/test/shared-profiles.test.ts
new file mode 100644
index 0000000..56b31df
--- /dev/null
+++ b/test/shared-profiles.test.ts
@@ -0,0 +1,114 @@
+import { readFileSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import { describe, expect, it } from "vitest";
+
+const plugin = "com.todd.streamdeckcodex.sdPlugin";
+const manifest = JSON.parse(readFileSync(`${plugin}/manifest.json`, "utf8"));
+describe("opt-in shared profiles", () => {
+ it("retains all legacy profiles and adds one opt-in shared profile per device", () => {
+ const old = manifest.Profiles.filter((p: any) =>
+ p.Name.startsWith("streamdeckcodex-"),
+ );
+ const shared = manifest.Profiles.filter((p: any) =>
+ p.Name.startsWith("streamdeckai-"),
+ );
+ expect(old).toHaveLength(5);
+ expect(shared).toHaveLength(5);
+ expect(shared.map((p: any) => p.DeviceType).sort()).toEqual(
+ old.map((p: any) => p.DeviceType).sort(),
+ );
+ for (const p of shared) {
+ expect(p.AutoInstall).toBe(false);
+ }
+ });
+ for (const device of ["plus", "mini", "neo", "xl", "stream-deck"]) {
+ it(`gives ${device} distinct identities and auto settings on every plugin action`, () => {
+ const archive = `${plugin}/streamdeckai-${device}.streamDeckProfile`;
+ const entries = execFileSync("/usr/bin/unzip", ["-Z1", archive], {
+ encoding: "utf8",
+ })
+ .trim()
+ .split("\n");
+ const rootName = entries.find((e) => e.endsWith(".sdProfile/"))!;
+ const root = JSON.parse(
+ execFileSync(
+ "/usr/bin/unzip",
+ ["-p", archive, `${rootName}manifest.json`],
+ { encoding: "utf8" },
+ ),
+ );
+ expect(root.Name).toContain("Codex + Claude Master");
+ for (const page of [...root.Pages.Pages, root.Pages.Default])
+ expect(entries).toContain(`${rootName}Profiles/${page}/manifest.json`);
+ let count = 0;
+ const ids = new Set();
+ const geometry: Record = {
+ plus: [4, 2],
+ mini: [3, 2],
+ neo: [4, 2],
+ xl: [8, 4],
+ "stream-deck": [5, 3],
+ };
+ const [columns, rows] = geometry[device]!;
+ for (const path of entries.filter(
+ (e) => e.endsWith("/manifest.json") && e.includes("/Profiles/"),
+ )) {
+ const page = JSON.parse(
+ execFileSync("/usr/bin/unzip", ["-p", archive, path], {
+ encoding: "utf8",
+ }),
+ );
+ const keys = page.Controllers?.find(
+ (c: any) => c.Type === "Keypad",
+ )?.Actions;
+ if (keys) {
+ for (const [position, entry] of Object.entries(keys) as [
+ string,
+ any,
+ ][]) {
+ const [column, row] = position.split(",").map(Number);
+ expect(column).toBeGreaterThanOrEqual(0);
+ expect(column).toBeLessThan(columns);
+ expect(row).toBeGreaterThanOrEqual(0);
+ expect(row).toBeLessThan(rows);
+ expect(ids.has(entry.ActionID)).toBe(false);
+ ids.add(entry.ActionID);
+ const image = entry.States?.[0]?.Image;
+ if (image)
+ expect(entries).toContain(path.replace("manifest.json", image));
+ }
+ if (device === "plus")
+ expect(
+ Object.keys(
+ page.Controllers.find((c: any) => c.Type === "Encoder").Actions,
+ ),
+ ).toHaveLength(4);
+ const actions = Object.values(keys) as any[];
+ expect(
+ actions.some((a) => a.UUID === "com.elgato.streamdeck.page.next"),
+ ).toBe(true);
+ expect(
+ actions.some(
+ (a) => a.UUID === "com.elgato.streamdeck.page.previous",
+ ),
+ ).toBe(true);
+ }
+ for (const c of page.Controllers ?? [])
+ for (const a of Object.values(c.Actions ?? {}) as any[]) {
+ if (a.UUID?.startsWith("com.todd.streamdeckcodex.")) {
+ count++;
+ expect(a.UUID).not.toMatch(/\.(agent-status|agent-navigator)$/);
+ expect(a.Settings.commandId ?? "").not.toMatch(
+ /^(accept|reject)$/,
+ );
+ expect(a.Settings.action ?? "").not.toMatch(
+ /^(new-project|command:(accept|reject))$/,
+ );
+ expect(a.Settings.provider).toBe("auto");
+ }
+ }
+ }
+ expect(count).toBeGreaterThanOrEqual(40);
+ });
+ }
+});
diff --git a/test/usage.test.ts b/test/usage.test.ts
index 3119a0d..176ec26 100644
--- a/test/usage.test.ts
+++ b/test/usage.test.ts
@@ -71,6 +71,33 @@ describe("usage refresh off the tick", () => {
store.close();
}
});
+
+ it("retains the last known weekly value when a later refresh fails", async () => {
+ let now = 100_000;
+ const clock = vi.spyOn(Date, "now").mockImplementation(() => now);
+ const fetcher = vi
+ .fn<() => Promise>()
+ .mockResolvedValueOnce({ usedPercent: 20, observedAt: 1 })
+ .mockRejectedValueOnce(new Error("Codex app server timed out"));
+ const store = storeWith(fetcher);
+ try {
+ await expect(store.usageSnapshot()).resolves.toMatchObject({
+ usedPercent: 20,
+ });
+ now += 30_001;
+ await expect(store.usageSnapshot()).resolves.toMatchObject({
+ usedPercent: 20,
+ });
+ expect(store.usageSnapshotCached()).toMatchObject({ usedPercent: 20 });
+ expect(store.usageAvailabilityCached()).toMatchObject({
+ state: "unavailable",
+ reason: "timeout",
+ });
+ } finally {
+ clock.mockRestore();
+ store.close();
+ }
+ });
});
describe("live Codex usage", () => {
@@ -79,6 +106,18 @@ describe("live Codex usage", () => {
expect(toggleUsageView("resets")).toBe("weekly");
});
+ it("supports concise provider labels on dedicated weekly keys", () => {
+ const svg = usageKeySvg({ usedPercent: 32, observedAt: 1 }, "weekly", 1, {
+ heading: "CLAUDE LEFT",
+ footer: "FABLE",
+ accent: "#E7A589",
+ });
+ expect(svg).toContain("CLAUDE LEFT");
+ expect(svg).toContain(">68%");
+ expect(svg).toContain(">FABLE");
+ expect(svg).toContain(' ');
+ });
+
it("selects the longest account window and authoritative reset count", () => {
expect(
usageFromRateLimitsResult(
diff --git a/vitest.config.ts b/vitest.config.ts
index 5b5061a..bda8b26 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -11,6 +11,7 @@ const integrationTests = [
"test/keypad-profiles.test.ts",
"test/model-dial.acceptance.test.ts",
"test/native-*.test.ts",
+ "test/codex-draft.fixture.test.ts",
"test/physical-input.acceptance.test.ts",
"test/plan-mode.acceptance.test.ts",
"test/profile-installer.test.ts",