Compare commits

...

37 commits
v0.4.9 ... main

Author SHA1 Message Date
Ramnique Singh
e2178c1488
Merge pull request #610 from rowboatlabs/dev
Dev
2026-06-08 19:47:49 +05:30
Ramnique Singh
f6f6c715a0 fix spacing 2026-06-08 19:37:12 +05:30
Ramnique Singh
8fb0833b19 upgrade gh actions pnpm 2026-06-08 19:37:05 +05:30
gagan
46042f9465
fix: keep chat input toolbar usable when the panel is narrow (#606)
* fix: prevent chat bar model selector from overflowing in narrow panel

* fix: contain chat bar left items so code pill clips instead of overflowing

* fix: compact icon-only mode for chat bar when panel is narrow

* fix: dynamic compact threshold based on visible toolbar items

* fix: use actual DOM overflow detection to eliminate toolbar overlap

* fix: progressive right-to-left icon collapse for chat toolbar

* fix: instant icon switch, remove search label transition

* fix: correct right-to-left collapse order (code→perm→search→workDir)

* fix: measure actual DOM overflow instead of estimating — eliminates half-text and disappearing icons

* refactor: replace JS overflow logic with CSS container queries

Drop the ResizeObserver/useLayoutEffect collapse machinery and the
estimated pixel thresholds in favor of declarative @container variants.
Each toolbar item swaps to icon-only at a fixed container-width
breakpoint (code 560, perm 460, search 410, workDir 370px), collapsing
right-to-left. Atomic swaps mean no half-clipped text and no
disappearing buttons.

* fix: move @container to card root so breakpoints track panel width

Putting container-type on the toolbar's own flex row made it stop
stretching to fill the card and hug its collapsed content instead, so
the query read a permanently-narrow width that never grew on widen.
The card root reliably spans the full panel width.

* fix: collapse toolbar by measuring real overflow, not fixed breakpoints

Fixed container-query breakpoints can't know the workdir name length or
model name width, so labels stayed full and overflowed into the model
selector. Replace with overflow measurement: a ResizeObserver resets to
full on any width/content change, then a pre-paint layout effect collapses
items right-to-left (code -> perm -> search -> workdir) until the row fits.
overflow-hidden on the group is a hard guarantee against any overlap.

* feat: overflow menu for toolbar items that don't fit even as icons

When the bar is too narrow to show every control as an icon, the
right-most items move into a '...' overflow dropdown (code -> perm ->
search -> workdir) instead of being clipped, so no icon is ever hidden.
Toggle items keep the menu open on click via onSelect preventDefault.

* fix: keep overflow menu open when toggling items inside it

Toggling an in-menu item (code mode, agent, search, perm) updated state
that was in the collapse-reset deps, resetting collapseLevel to 0 and
unmounting the '...' trigger mid-interaction. Drop the in-place toggles
from the reset deps so the menu stays open on click.

* fix: drop 'Options' label from toolbar overflow menu

---------

Co-authored-by: arkml <6592213+arkml@users.noreply.github.com>
2026-06-08 02:10:23 +05:30
arkml
13b5bab18f
Merge pull request #600 from rowboatlabs/dev
Dev
2026-06-06 11:00:27 +05:30
gagan
372309eb18
feat: run code mode on an in-app ACP client with live approvals (#593)
* feat(code-mode): add ACP client engine (Layer 2 core)

Own the Agent Client Protocol client instead of shelling out to `acpx`, so code
mode can stream structured events (tool calls, diffs, plan) and surface live
permission requests. Headless acpx can't do live approvals (it only supports
--approve-all), which is why we drive the agent adapters ourselves.

- code-mode/acp/{agents,client,permission-broker,session-store,manager,types}.ts:
  headless engine driving the Claude/Codex ACP adapters; one warm session per chat
  with create-or-resume via session/load; approval policy (ask | auto-approve-reads
  | yolo) in the broker.
- claude-exec.ts: cross-platform claude resolver (Windows .cmd EINVAL fix + macOS/Linux
  GUI-PATH safety net) shared with the legacy acpx path in builtin-tools.ts.
- add @agentclientprotocol/sdk + claude/codex adapters to core.

* feat(code-mode): route code mode through code_agent_run tool + live approvals

Replace the acpx shell-out with a structured code_agent_run tool that drives the
ACP engine directly, streaming the agent's tool calls / diffs / plan into the chat
and surfacing permission requests inline.

- shared: code-mode.ts zod schemas; add code-run-event + code-run-permission-request
  RunEvent variants (stream to the renderer over the existing runs:events channel);
  codeRun:resolvePermission IPC channel.
- core: CodePermissionRegistry (promise-based mid-run approvals — the LLM tool-loop's
  pre-call gate can't model a mid-execution wait); register codeModeManager +
  codePermissionRegistry in awilix.
- core: code_agent_run builtin tool (streams via ctx.publish, asks via the registry,
  cancels on ctx.signal, returns the agent summary). CodeModeConfig.approvalPolicy
  (ask | auto-approve-reads | yolo; default ask). Exclude the tool from the headless
  background-task / live-note / inline-task agents so they can't block on an approval.
- main: codeRun:resolvePermission handler -> registry.resolve.
- rewrite the code-with-agents skill and the runtime "Code Mode (Active)" block to call
  code_agent_run instead of emitting npx acpx commands.

* feat(code-mode): render coding runs inline (live timeline + permission card)

Render a code_agent_run tool call as a live CodingRun block instead of generic
tool output: the agent's text, tool-call rows (kind icon + status + changed-file
names from diffs), a plan checklist, and resolved-permission lines — plus an
inline Allow / Always-allow / Deny card wired to codeRun:resolvePermission.

- chat-conversation.ts: ToolCall carries codeRunEvents + pendingCodePermission;
  code_agent_run is excluded from tool-grouping so it renders standalone.
- App.tsx: handle code-run-event / code-run-permission-request, clear the pending
  card on tool-result, handleCodePermissionResponse, render via CodingRunBlock.

* fix(code-mode): run the ACP adapter as Node under Electron + resolve it from main

Two runtime failures that only surfaced inside the packaged/bundled Electron app
(the headless harness used real node, so neither showed there):

- "ACP connection closed": the main process spawns the adapter via
  process.execPath, which inside Electron is the Electron binary, not node — so
  the child never ran as Node and its ACP stdio stream closed immediately. Set
  ELECTRON_RUN_AS_NODE=1 on the adapter env (a no-op under real node).
- "Cannot find module '@agentclientprotocol/claude-agent-acp'": the adapters were
  transitive (core) deps, unreachable from the esbuild-bundled main.cjs. Add them
  as direct deps of the main app so require.resolve finds them at runtime (and so
  they ship when packaged).

Also capture the adapter's stderr + exit code and enrich connection errors, so a
future failure reports the real cause instead of the opaque "ACP connection closed".

* chore(code-mode): remove dead acpx code paths and stale copy

Code mode now runs through the code_agent_run tool (owning the ACP client), so the
legacy acpx shell-out paths are dead. Remove them:

- core: envForCommand (acpx-only CLAUDE_CODE_EXECUTABLE injection) from
  executeCommand; getCodeModeCommandLabel (acpx run-status label).
- renderer: the acpx-detection "switch agent / auto-flip the code-mode chip" flow —
  App.tsx executeCommand detection, the permission-request onSwitchAgent button +
  badge, and the composer's code-mode-detected listener.
- copy: Settings -> Code Mode and the code-with-agents skill summary no longer
  mention acpx; tidy stale comments (claude-exec, command-executor).

No behavior change for code mode; the general executeCommand tool is unaffected.

* feat(code-mode): approval-policy selector in Settings

Surface the approval policy (Ask every time / Auto-approve reads / YOLO) in
Settings -> Code Mode, instead of being config-file only. The broker already
reads CodeModeConfig.approvalPolicy; this plumbs it through the
codeMode:getConfig / setConfig IPC + main handlers and adds the picker UI
(with a one-line explanation of each level). Defaults to "ask".

* fix(code-mode): harden ACP engine — turn-scoped connections, chip-authoritative agent, reliable stop

Three robustness fixes that co-modify manager.runPrompt and the code_agent_run
tool, so they land together:

- Lifecycle: scope each ACP adapter connection to the agent turn. Dispose it a
  short grace (60s) after the turn ends instead of holding it for the app's life;
  the next turn resumes via session/load (both agents support it). Wire
  disposeAll() on app quit (was dead code). Fixes the unbounded per-chat leak of
  booted agent processes.

- Agent selection: make the composer chip the source of truth. Thread codeMode
  into ToolContext; code_agent_run uses it instead of the model's guessed `agent`
  arg, which anchored on the thread's earlier agent and ignored a chip change.
  Prompts updated to match; the run is labelled by the agent that actually ran.

- Stop/abort: guarantee a stopped turn unwinds. On abort the manager sends ACP
  session/cancel, then force-kills the adapter after a 2s grace and resolves the
  turn as cancelled — a wedged adapter can no longer hang the run and lock the
  chat. code_agent_run returns a clean cancelled result.

* fix(code-mode): hide Codex's native console window on Windows

Codex's engine ships as a native console-subsystem binary (codex.exe). Launched
from our console-less Electron process tree, Windows allocated a fresh *visible*
console window for it; closing that window wedged the run in a pending state.
(Claude Code is a Node CLI, so it never triggers this.)

The window is created by @openai/codex's launcher (bin/codex.js), which spawns
codex.exe with no windowsHide. Patch it via pnpm to pass windowsHide: true
(CREATE_NO_WINDOW) so the console stays hidden — no window, nothing to close.

* refactor(code-mode): move ACP session files out of WorkDir/config

Per-run ACP session state is runtime state that accumulates one file per
chat run, not user/app config. Relocate it from WorkDir/config to a
dedicated WorkDir/code-mode/sessions/ so it can be listed, cleaned up, and
managed on its own without crowding config. Drop the now-redundant
codesession- filename prefix (the directory conveys it).
2026-06-05 14:45:08 +05:30
arkml
7f3c16cc33
Pane placement (#598)
* allow user to change pane placement

* allow user to change starting pane size
2026-06-05 00:49:49 +05:30
Arjun
97c8f9d787 hide background task details if there is output already 2026-06-05 00:43:43 +05:30
Arjun
05a93c98ae show last working directories 2026-06-05 00:19:09 +05:30
gagan
81cc4e10b7
fix: set rowboat icon for windows taskbar and installer (#595)
Co-authored-by: arkml <6592213+arkml@users.noreply.github.com>
2026-06-04 14:01:10 +05:30
Ramnique Singh
08a727c5ec
Merge pull request #594 from hrsvrn/linux-icon-and-url-scheme
added icon and rowboat url scheme handler to linux packages
2026-06-03 12:01:15 +05:30
hrsvrn
547a22ae1a added icon and rowboat url scheme handler to linux packages 2026-06-03 11:54:06 +05:30
Ramnique Singh
d47cab6a0f Add run-level auto permission mode
- add LLM-based auto permission classifier for permission-gated tool calls
- store run-level permission mode and auto permission decision events
- auto-approve low-risk calls, and bubble auto-denied calls to manual approval
- show auto-denied reasons in chat and auto-approved labels below tool cards
- add BYOK setting for the auto-permission decision model
2026-06-03 07:58:04 +05:30
Arjun
8a8b78071d more recents in side bar 2026-06-02 22:25:05 +05:30
arkml
30356e36b1
Merge pull request #591 from rowboatlabs/dev
Dev
2026-05-29 22:41:55 +05:30
arkml
caea83aecf
clamp sync to 7 days even after long hiatus (#590) 2026-05-29 22:23:21 +05:30
gagan
5368751f61
feat: render and edit docx files in-app (#589)
Add a DocxFileViewer (via @eigenpal/docx-editor-react) wired into the file-type viewer switch, reading/saving bytes through the existing base64 workspace IPC with debounced autosave.
2026-05-29 18:04:04 +05:30
Ramnique Singh
732401f72e Add app version to analytics events 2026-05-29 17:02:01 +05:30
arkml
5ae853e15c
fix thread boundary in email reply drafts (#588) 2026-05-29 10:58:57 +05:30
arkml
78d51ccbf6
fix navigation and other minor issue in workspace view (#587) 2026-05-28 23:57:43 +05:30
Ramnique Singh
5677916790
Merge pull request #586 from rowboatlabs/dev
fix(ci): make electron release artifacts deterministic
2026-05-28 23:45:55 +05:30
Ramnique Singh
cc034c7688 fix(ci): make electron release artifacts deterministic
Pin Electron release builds to Node 24.15.0, the last known-good runner version for Windows/Linux packaging, and fail artifact upload when out/make is empty so successful jobs cannot hide missing release assets.
2026-05-28 23:40:46 +05:30
Ramnique Singh
56246b84e6
Merge pull request #585 from rowboatlabs/dev
Dev changes
2026-05-28 23:01:55 +05:30
Ramnique Singh
129d91dc8d Persist per-message context for prompt caching
Move volatile current time and middle-pane data out of the system prompt and into a hidden userMessageContext stored on each user message. Reconstruct the LLM-facing message from this persisted context so older conversation turns remain stable across later requests while UI-facing content stays unchanged.

Keep finite branch instructions such as voice, search, code mode, agent notes, and workdir behavior in the system prompt so each conversation can still benefit from reusable prompt-cache prefixes.
2026-05-28 23:00:44 +05:30
Arjun
c213274723 enable coding agents if they are available by default 2026-05-28 22:33:32 +05:30
Arjun
e7c7d0e90f remove chat options from middle pane 2026-05-28 21:20:57 +05:30
arkml
f378c7c604
Oauth migration (#584)
* oauth migration for new scopes

* trigger google reconnect popover
2026-05-28 19:07:02 +05:30
gagan
537b6f66bb
Code Mode: in-chat toggle, settings tab, and permission/command UX (#572)
* feat: add in-chat code mode toggle with claude/codex swap

* feat: show agent and add swap-and-retry on acpx permission card

* style: reorder permission card buttons (approve, deny, swap)

* feat: add tooltips to composer plus and web search buttons

* feat: add code mode settings tab with agent install/auth checks

* feat: show sign-in command when agent installed but signed out

* style: refine code-mode permission and command block UX

- Render permission block before the command block
- Collapse permission details after a response; click header to expand
- Drop status icons/badge; use minimal green / bold red blocks
- Auto-collapse the running command block once it completes

* feat: rotating progress labels for code-mode commands; darker tool borders

- Code-mode (acpx) command block shows status-aware labels: rotating
  'Working on the task…' phrases (5s each, holding on the last) while
  running, then 'Completed the task' / "Couldn't complete the task"
- Darken outer border on all tool blocks in light and dark modes

* fix: detect Claude Code sign-in via macOS Keychain

On macOS, Claude Code stores OAuth credentials in the login Keychain
(service 'Claude Code-credentials'), not in ~/.claude/.credentials.json.
Read the Keychain as a fallback so signed-in Mac users are detected.

* feat: persistent per-chat sessions for code-mode coding agents

- Use a named acpx session (rowboat-<runId>) per chat so follow-up
  coding requests resume the same agent and keep context
- Create the session once at chat start (sessions new --name), then
  prompt with -s <name>; reuse on follow-ups (no re-create)
- Drop the redundant in-chat 'reply yes' confirmation (the executeCommand
  permission card is the confirmation)
- Code-mode output uses plain-text paths (overrides global filepath rule)
- On not-installed/auth errors, point user to Settings -> Code Mode

* fix: code-mode session creation uses idempotent ensure, run sequentially

- Use 'sessions ensure --name' instead of 'sessions new' so reopening a
  chat resumes the existing session instead of erroring on a name clash
- Create the session and run the prompt as separate sequential calls so
  the permission/command blocks render one at a time (not all at once)

* fix: reliable Claude Code session resume on Windows (avoid claude.cmd EINVAL)

Resuming a code-mode chat after restarting the app spawns a fresh ACP
agent. On Windows + Node >=20.12 the bridge spawning claude.cmd throws
EINVAL, so the session queue owner fails to start. Rowboat injects
CLAUDE_CODE_EXECUTABLE=claude.exe to dodge this, but the override didn't
reliably reach the spawn. Windows-only; no-op on macOS/Linux.

- executeCommand now accepts an env override and the non-abortable
  fallback path passes it through (was silently dropped)
- resolveClaudeExeOnWindows also scans known npm/pnpm/volta global bin
  dirs, not just PATH (Electron's runtime PATH can omit them)
- add --timeout 600 to acpx prompt commands so a genuine stall fails
  cleanly instead of hanging on 'Running' forever
2026-05-28 14:52:09 +05:30
gagan
b89b91258e
feat: redesign web search & tool-call cards (rolling reveal, shared surface, action summaries) (#579)
* feat: roll web search sources in one-by-one with settle animation

* fix: keep web search toggle on for the rest of the chat session

* feat: redesign collapsed web search card with favicon stack and source summary

* style: tune web search card surface tints for light and dark mode

* feat: rounder web search card with subtle expand/collapse animation

* feat: apply web search card design to tool-call box with action summary

Shared --card-surface token, rounded card, hover, collapse animation, and a state-driven lead icon (spinner/check/cross). Single tools and the group now match. Completed group shows 'Ran N tools · <up to 2 actions>, more...' with the action summary in lighter gray.

* style: drop lead icon from tool group child rows and round them more
2026-05-28 01:57:46 +05:30
Arjun
daff21481a show recording status in sidebar 2026-05-28 01:07:12 +05:30
Arjun
78c5ad2e6f elevate folder navigation to app view state 2026-05-28 00:46:25 +05:30
Arjun
373d1ee92b search defaults to knowledge 2026-05-28 00:46:25 +05:30
Arjun
0af48ecd4a new knowledge view 2026-05-28 00:46:25 +05:30
Ramnique Singh
2e930612f8 Merge branch 'main' into dev 2026-05-27 23:49:30 +05:30
Ramnique Singh
6288f99a85
Merge pull request #581 from rowboatlabs/chat-log
Add chat log download menu
2026-05-27 23:18:46 +05:30
Ramnique Singh
2f9ce051c0 Add chat log download menu 2026-05-27 23:17:47 +05:30
Arjun
f78f1380eb added expand buttons for middle and side pane and fixed issue with moving new chat to side pane 2026-05-27 23:17:25 +05:30
75 changed files with 6041 additions and 868 deletions

View file

@ -16,14 +16,14 @@ jobs:
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 9
version: 10
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 24
node-version: 24.15.0
cache: 'pnpm'
cache-dependency-path: 'apps/x/pnpm-lock.yaml'
@ -39,17 +39,17 @@ jobs:
node -e "
const fs = require('fs');
const version = '${{ steps.version.outputs.version }}';
// Update apps/x/package.json
const rootPackage = JSON.parse(fs.readFileSync('apps/x/package.json', 'utf8'));
rootPackage.version = version;
fs.writeFileSync('apps/x/package.json', JSON.stringify(rootPackage, null, 2) + '\n');
// Update apps/x/apps/main/package.json
const mainPackage = JSON.parse(fs.readFileSync('apps/x/apps/main/package.json', 'utf8'));
mainPackage.version = version;
fs.writeFileSync('apps/x/apps/main/package.json', JSON.stringify(mainPackage, null, 2) + '\n');
console.log('Updated version to:', version);
"
@ -61,25 +61,25 @@ jobs:
# Create a temporary keychain
KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
KEYCHAIN_PASSWORD=$(openssl rand -base64 32)
# Create keychain
security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
# Decode and import certificate
echo "$APPLE_CERTIFICATE" | base64 --decode > $RUNNER_TEMP/certificate.p12
security import $RUNNER_TEMP/certificate.p12 -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
# Allow codesign to access the keychain
security set-key-partition-list -S apple-tool:,apple: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
# Add keychain to search list
security list-keychains -d user -s "$KEYCHAIN_PATH" login.keychain
# Verify certificate was imported
security find-identity -v "$KEYCHAIN_PATH"
# Clean up certificate file
rm -f $RUNNER_TEMP/certificate.p12
@ -111,6 +111,7 @@ jobs:
with:
name: distributables
path: apps/x/apps/main/out/make/*
if-no-files-found: error
retention-days: 30
build-linux:
@ -121,14 +122,14 @@ jobs:
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 9
version: 10
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 24
node-version: 24.15.0
cache: 'pnpm'
cache-dependency-path: 'apps/x/pnpm-lock.yaml'
@ -144,17 +145,17 @@ jobs:
node -e "
const fs = require('fs');
const version = '${{ steps.version.outputs.version }}';
// Update apps/x/package.json
const rootPackage = JSON.parse(fs.readFileSync('apps/x/package.json', 'utf8'));
rootPackage.version = version;
fs.writeFileSync('apps/x/package.json', JSON.stringify(rootPackage, null, 2) + '\n');
// Update apps/x/apps/main/package.json
const mainPackage = JSON.parse(fs.readFileSync('apps/x/apps/main/package.json', 'utf8'));
mainPackage.version = version;
fs.writeFileSync('apps/x/apps/main/package.json', JSON.stringify(mainPackage, null, 2) + '\n');
console.log('Updated version to:', version);
"
@ -175,6 +176,7 @@ jobs:
with:
name: distributables-linux
path: apps/x/apps/main/out/make/*
if-no-files-found: error
retention-days: 30
build-windows:
@ -185,14 +187,14 @@ jobs:
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 9
version: 10
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 24
node-version: 24.15.0
cache: 'pnpm'
cache-dependency-path: 'apps/x/pnpm-lock.yaml'
@ -210,17 +212,17 @@ jobs:
node -e "
const fs = require('fs');
const version = '${{ steps.version.outputs.version }}';
// Update apps/x/package.json
const rootPackage = JSON.parse(fs.readFileSync('apps/x/package.json', 'utf8'));
rootPackage.version = version;
fs.writeFileSync('apps/x/package.json', JSON.stringify(rootPackage, null, 2) + '\n');
// Update apps/x/apps/main/package.json
const mainPackage = JSON.parse(fs.readFileSync('apps/x/apps/main/package.json', 'utf8'));
mainPackage.version = version;
fs.writeFileSync('apps/x/apps/main/package.json', JSON.stringify(mainPackage, null, 2) + '\n');
console.log('Updated version to:', version);
"
@ -241,4 +243,5 @@ jobs:
with:
name: distributables-windows
path: apps/x/apps/main/out/make/*
if-no-files-found: error
retention-days: 30

View file

@ -16,6 +16,8 @@
## Event catalog
All PostHog events include `app_version` automatically. Main-process events add it in `packages/core/src/analytics/posthog.ts`; renderer events get it from the `analytics:bootstrap` IPC payload and an initialization-time `before_send` hook.
### `llm_usage`
Emitted whenever ai-sdk returns token usage (one event per LLM call, not per run).
@ -101,6 +103,7 @@ Persistent across sessions for the same user. Set via `posthog.people.set` or as
| `email` | main on identify | From `/v1/me`; powers PostHog cohort match + integrations |
| `plan`, `status` | main on identify | Subscription state |
| `api_url` | both processes (init + identify) | Distinguishes prod / staging / custom — assign meaning in PostHog dashboard. `https://api.x.rowboatlabs.com` = production |
| `app_version` | both processes (init + identify) | Electron app version; also included automatically on every event |
| `signed_in` | renderer | `true` while rowboat OAuth is connected |
| `{provider}_connected` | renderer | One of `gmail`, `calendar`, `slack`, `rowboat` |
| `total_notes` | renderer (init) | Workspace size signal |

View file

@ -10,11 +10,13 @@
*/
import * as esbuild from 'esbuild';
import { readFile } from 'node:fs/promises';
// In CommonJS, import.meta.url doesn't exist. We need to polyfill it.
// The banner defines __import_meta_url at the top of the bundle,
// and we use define to replace all import.meta.url references with it.
const cjsBanner = `var __import_meta_url = require('url').pathToFileURL(__filename).href;`;
const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'));
await esbuild.build({
entryPoints: ['./dist/main.js'],
@ -36,6 +38,7 @@ await esbuild.build({
// Empty strings disable analytics gracefully.
'process.env.POSTHOG_KEY': JSON.stringify(process.env.VITE_PUBLIC_POSTHOG_KEY ?? ''),
'process.env.POSTHOG_HOST': JSON.stringify(process.env.VITE_PUBLIC_POSTHOG_HOST ?? 'https://us.i.posthog.com'),
'process.env.ROWBOAT_APP_VERSION': JSON.stringify(pkg.version ?? ''),
},
});

View file

@ -56,6 +56,7 @@ module.exports = {
description: 'AI coworker with memory',
name: `Rowboat-win32-${arch}`,
setupExe: `Rowboat-win32-${arch}-${pkg.version}-setup.exe`,
setupIcon: path.join(__dirname, 'icons/icon.ico'),
})
},
{
@ -66,7 +67,9 @@ module.exports = {
bin: "rowboat",
description: 'AI coworker with memory',
maintainer: 'rowboatlabs',
homepage: 'https://rowboatlabs.com'
homepage: 'https://rowboatlabs.com',
icon: path.join(__dirname, 'icons/icon.png'),
mimeType: ['x-scheme-handler/rowboat'],
}
})
},
@ -77,7 +80,9 @@ module.exports = {
name: `Rowboat-linux`,
bin: "rowboat",
description: 'AI coworker with memory',
homepage: 'https://rowboatlabs.com'
homepage: 'https://rowboatlabs.com',
icon: path.join(__dirname, 'icons/icon.png'),
mimeType: ['x-scheme-handler/rowboat'],
}
}
},

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View file

@ -13,6 +13,8 @@
"make": "electron-forge make"
},
"dependencies": {
"@agentclientprotocol/claude-agent-acp": "^0.39.0",
"@agentclientprotocol/codex-acp": "^0.0.44",
"@x/core": "workspace:*",
"@x/shared": "workspace:*",
"chokidar": "^4.0.3",

View file

@ -1,4 +1,4 @@
import { ipcMain, BrowserWindow, shell, dialog, systemPreferences, desktopCapturer } from 'electron';
import { ipcMain, BrowserWindow, shell, dialog, systemPreferences, desktopCapturer, app } from 'electron';
import { ipc } from '@x/shared';
import path from 'node:path';
import os from 'node:os';
@ -8,6 +8,7 @@ import {
listProviders,
} from './oauth-handler.js';
import { watcher as watcherCore, workspace } from '@x/core';
import { WorkDir } from '@x/core/dist/config/config.js';
import { workspace as workspaceShared } from '@x/shared';
import * as mcpCore from '@x/core/dist/mcp/mcp.js';
import * as runsCore from '@x/core/dist/runs/runs.js';
@ -30,6 +31,10 @@ import { listGatewayModels } from '@x/core/dist/models/gateway.js';
import type { IModelConfigRepo } from '@x/core/dist/models/repo.js';
import type { IOAuthRepo } from '@x/core/dist/auth/repo.js';
import { IGranolaConfigRepo } from '@x/core/dist/knowledge/granola/repo.js';
import { ICodeModeConfigRepo } from '@x/core/dist/code-mode/repo.js';
import { CodePermissionRegistry } from '@x/core/dist/code-mode/acp/permission-registry.js';
import { checkCodeModeAgentStatus } from '@x/core/dist/code-mode/status.js';
import { invalidateCopilotInstructionsCache } from '@x/core/dist/application/assistant/instructions.js';
import { triggerSync as triggerGranolaSync } from '@x/core/dist/knowledge/granola/sync.js';
import { ISlackConfigRepo } from '@x/core/dist/slack/repo.js';
import { isOnboardingComplete, markOnboardingComplete } from '@x/core/dist/config/note_creation_config.js';
@ -451,6 +456,7 @@ export function setupIpcHandlers() {
return {
installationId: getInstallationId(),
apiUrl: API_URL,
appVersion: app.getVersion(),
};
},
'workspace:getRoot': async () => {
@ -525,12 +531,17 @@ export function setupIpcHandlers() {
return runsCore.createRun(args);
},
'runs:createMessage': async (_event, args) => {
return { messageId: await runsCore.createMessage(args.runId, args.message, args.voiceInput, args.voiceOutput, args.searchEnabled, args.middlePaneContext) };
return { messageId: await runsCore.createMessage(args.runId, args.message, args.voiceInput, args.voiceOutput, args.searchEnabled, args.middlePaneContext, args.codeMode) };
},
'runs:authorizePermission': async (_event, args) => {
await runsCore.authorizePermission(args.runId, args.authorization);
return { success: true };
},
'codeRun:resolvePermission': async (_event, args) => {
const registry = container.resolve<CodePermissionRegistry>('codePermissionRegistry');
registry.resolve(args.requestId, args.decision);
return { success: true };
},
'runs:provideHumanInput': async (_event, args) => {
await runsCore.replyToHumanInputRequest(args.runId, args.reply);
return { success: true };
@ -549,6 +560,35 @@ export function setupIpcHandlers() {
await runsCore.deleteRun(args.runId);
return { success: true };
},
'runs:downloadLog': async (event, args) => {
const runFileName = `${args.runId}.jsonl`;
if (path.basename(runFileName) !== runFileName) {
return { success: false, error: 'Invalid run id' };
}
const sourcePath = path.join(WorkDir, 'runs', runFileName);
const win = BrowserWindow.fromWebContents(event.sender);
const result = await dialog.showSaveDialog(win!, {
defaultPath: `${runFileName}.log`,
filters: [
{ name: 'Chat Log', extensions: ['log'] },
{ name: 'JSONL', extensions: ['jsonl'] },
{ name: 'All Files', extensions: ['*'] },
],
});
if (result.canceled || !result.filePath) {
return { success: false };
}
try {
await fs.copyFile(sourcePath, result.filePath);
return { success: true };
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to download chat log';
return { success: false, error: message };
}
},
'models:list': async () => {
if (await isSignedIn()) {
return await listGatewayModels();
@ -600,6 +640,20 @@ export function setupIpcHandlers() {
const config = await repo.getConfig();
return { enabled: config.enabled };
},
'codeMode:getConfig': async () => {
const repo = container.resolve<ICodeModeConfigRepo>('codeModeConfigRepo');
const config = await repo.getConfig();
return { enabled: config.enabled, approvalPolicy: config.approvalPolicy };
},
'codeMode:setConfig': async (_event, args) => {
const repo = container.resolve<ICodeModeConfigRepo>('codeModeConfigRepo');
await repo.setConfig({ enabled: args.enabled, approvalPolicy: args.approvalPolicy });
invalidateCopilotInstructionsCache();
return { success: true };
},
'codeMode:checkAgentStatus': async () => {
return await checkCodeModeAgentStatus();
},
'granola:setConfig': async (_event, args) => {
const repo = container.resolve<IGranolaConfigRepo>('granolaConfigRepo');
await repo.setConfig({ enabled: args.enabled });

View file

@ -40,7 +40,8 @@ import started from "electron-squirrel-startup";
import { execSync, exec, execFileSync } from "node:child_process";
import { promisify } from "node:util";
import { init as initChromeSync } from "@x/core/dist/knowledge/chrome-extension/server/server.js";
import { registerBrowserControlService, registerNotificationService } from "@x/core/dist/di/container.js";
import container, { registerBrowserControlService, registerNotificationService } from "@x/core/dist/di/container.js";
import type { CodeModeManager } from "@x/core/dist/code-mode/acp/manager.js";
import { browserViewManager, BROWSER_PARTITION } from "./browser/view.js";
import { setupBrowserEventForwarding } from "./browser/ipc.js";
import { ElectronBrowserControlService } from "./browser/control-service.js";
@ -51,6 +52,7 @@ import {
extractDeepLinkFromArgv,
setMainWindowForDeepLinks,
} from "./deeplink.js";
import { disconnectGoogleIfScopesStale } from "./oauth-handler.js";
const execAsync = promisify(exec);
@ -219,6 +221,7 @@ function createWindow() {
backgroundColor: "#252525", // Prevent white flash (matches dark mode)
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 12, y: 12 },
icon: process.platform !== "darwin" ? path.join(__dirname, "../../icons/icon.png") : undefined,
webPreferences: {
// IMPORTANT: keep Node out of renderer
nodeIntegration: false,
@ -351,6 +354,11 @@ app.whenReady().then(async () => {
registerConsumer(backgroundTaskEventConsumer);
initEventProcessor();
// If the stored Google grant predates a scope change (only old scopes),
// disconnect it now so the user re-connects with the current scopes before
// any Google sync runs against the stale grant.
await disconnectGoogleIfScopesStale();
// start gmail sync
initGmailSync();
@ -410,6 +418,12 @@ app.on("before-quit", () => {
stopWorkspaceWatcher();
stopRunsWatcher();
stopServicesWatcher();
// Tear down any live ACP coding-agent adapter processes so they don't outlive the app.
try {
container.resolve<CodeModeManager>('codeModeManager').disposeAll();
} catch {
// nothing live to dispose
}
shutdownLocalSites().catch((error) => {
console.error('[LocalSites] Failed to shut down cleanly:', error);
});

View file

@ -508,7 +508,7 @@ export async function disconnectProvider(provider: string): Promise<{ success: b
if (connection.mode === 'rowboat' && connection.tokens?.access_token) {
try {
const revokeUrl = `https://oauth2.googleapis.com/revoke?token=${encodeURIComponent(connection.tokens.access_token)}`;
const res = await fetch(revokeUrl, { method: 'POST' });
const res = await fetch(revokeUrl, { method: 'POST', signal: AbortSignal.timeout(5000) });
if (!res.ok) {
console.warn(`[OAuth] Google revoke returned ${res.status}; continuing with local disconnect`);
}
@ -532,6 +532,81 @@ export async function disconnectProvider(provider: string): Promise<{ success: b
}
}
/**
* Startup migration for Google scope changes. When a connected Google grant was
* issued before a scope was added (e.g. old installs on gmail.readonly that
* never received gmail.modify), invalidate it so the user is prompted to
* reconnect and re-grant with the current scopes. The currently-requested
* scopes in the provider config are the source of truth: a grant missing any
* of them is treated as stale.
*
* We revoke + clear the stale token but DELIBERATELY keep the provider entry
* with an `error` set rather than calling disconnectProvider (which deletes the
* whole entry). The renderer's reconnect prompts the sidebar "Reconnect your
* accounts" alert and the connectors "Reconnect" row key off this `error`
* field, not off the connected flag. A fully deleted entry has no error and is
* indistinguishable from "never connected", so no prompt would ever appear.
*
* Tokens with no recorded scopes (very old installs that never persisted them)
* are also treated as stale. Safe to call on every startup it's a no-op once
* the grant covers all current scopes, and once invalidated the early return on
* the missing token keeps it from re-running until the user reconnects.
*/
export async function disconnectGoogleIfScopesStale(): Promise<void> {
try {
const oauthRepo = getOAuthRepo();
const connection = await oauthRepo.read('google');
// Not connected (or already invalidated) — nothing to migrate.
if (!connection.tokens) {
return;
}
const providerConfig = await getProviderConfig('google');
const requiredScopes = providerConfig.scopes ?? [];
if (requiredScopes.length === 0) {
return;
}
const granted = new Set(connection.tokens.scopes ?? []);
const missingScopes = requiredScopes.filter((scope) => !granted.has(scope));
if (missingScopes.length === 0) {
return;
}
console.log(
`[OAuth] Google grant is missing current scopes [${missingScopes.join(', ')}]; ` +
'invalidating it so the user is prompted to reconnect with the new scopes.'
);
// Best-effort revoke at Google for rowboat-mode grants (mirrors disconnectProvider).
if (connection.mode === 'rowboat' && connection.tokens.access_token) {
try {
const revokeUrl = `https://oauth2.googleapis.com/revoke?token=${encodeURIComponent(connection.tokens.access_token)}`;
const res = await fetch(revokeUrl, { method: 'POST', signal: AbortSignal.timeout(5000) });
if (!res.ok) {
console.warn(`[OAuth] Google revoke returned ${res.status}; continuing with local invalidation`);
}
} catch (error) {
console.warn('[OAuth] Google revoke failed; continuing with local invalidation:', error);
}
}
// Drop the stale token but keep the entry with an error so the reconnect
// prompt fires (see the note above).
await oauthRepo.upsert('google', {
tokens: null,
error: 'Google permissions changed. Please reconnect to continue.',
});
// Nudge any already-open window to re-read state. The renderer's initial
// mount also re-reads, so the prompt shows even if no window is up yet.
emitOAuthEvent({ provider: 'google', success: false });
} catch (error) {
console.error('[OAuth] Google scope migration check failed:', error);
}
}
/**
* Get access token for a provider (internal use only)
* Refreshes token if expired

View file

@ -9,6 +9,7 @@
"preview": "vite preview"
},
"dependencies": {
"@eigenpal/docx-editor-react": "^1.0.3",
"@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-context-menu": "^2.2.16",
@ -46,6 +47,15 @@
"motion": "^12.23.26",
"nanoid": "^5.1.6",
"posthog-js": "^1.332.0",
"prosemirror-commands": "^1.7.1",
"prosemirror-dropcursor": "^1.8.2",
"prosemirror-history": "^1.5.0",
"prosemirror-keymap": "^1.2.3",
"prosemirror-model": "^1.25.7",
"prosemirror-state": "^1.4.4",
"prosemirror-tables": "^1.8.5",
"prosemirror-transform": "^1.12.0",
"prosemirror-view": "^1.41.8",
"radix-ui": "^1.4.3",
"react": "^19.2.0",
"react-dom": "^19.2.0",

View file

@ -35,6 +35,30 @@
}
}
/* Radix Collapsible expand/collapse animate height (via the radix CSS var)
plus a subtle fade. Used by the web search card. */
@keyframes collapsible-down {
from {
height: 0;
opacity: 0;
}
to {
height: var(--radix-collapsible-content-height);
opacity: 1;
}
}
@keyframes collapsible-up {
from {
height: var(--radix-collapsible-content-height);
opacity: 1;
}
to {
height: 0;
opacity: 0;
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
@ -1176,6 +1200,10 @@
--scrollbar-track: oklch(0.95 0 0);
--scrollbar-thumb: oklch(0.75 0 0);
--scrollbar-thumb-hover: oklch(0.65 0 0);
/* Subtle raised-card surface: tints toward foreground, so it reads a hair
darker than the background in light mode and a hair lighter in dark mode.
Shared by the web search card and tool-call group. */
--card-surface: color-mix(in oklab, var(--background) 98.5%, var(--foreground));
--rowboat-panel: oklch(0.97 0 0);
--rowboat-raised: oklch(1 0 0);
--rowboat-wash: color-mix(in oklab, var(--background) 88%, var(--primary) 12%);

View file

@ -5,19 +5,20 @@ import { RunEvent, ListRunsResponse } from '@x/shared/src/runs.js';
import type { LanguageModelUsage, ToolUIPart } from 'ai';
import './App.css'
import z from 'zod';
import { CheckIcon, LoaderIcon, PanelLeftIcon, ArrowRight, MessageSquare, ChevronLeftIcon, ChevronRightIcon, Plus, HistoryIcon, X } from 'lucide-react';
import { CheckIcon, LoaderIcon, PanelLeftIcon, ArrowLeft, ArrowRight, MessageSquare, ChevronLeftIcon, ChevronRightIcon, Plus, HistoryIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { MarkdownEditor, type MarkdownEditorHandle } from './components/markdown-editor';
import { ChatSidebar } from './components/chat-sidebar';
import { ChatHeader } from './components/chat-header';
import { ChatEmptyState } from './components/chat-empty-state';
import { ChatInputWithMentions, type StagedAttachment } from './components/chat-input-with-mentions';
import { ChatInputWithMentions, type PermissionMode, type StagedAttachment } from './components/chat-input-with-mentions';
import { ChatMessageAttachments } from '@/components/chat-message-attachments'
import { GraphView, type GraphEdge, type GraphNode } from '@/components/graph-view';
import { BasesView, type BaseConfig, DEFAULT_BASE_CONFIG } from '@/components/bases-view';
import { ImageFileViewer } from '@/components/image-file-viewer';
import { VideoFileViewer } from '@/components/video-file-viewer';
import { AudioFileViewer } from '@/components/audio-file-viewer';
import { DocxFileViewer } from '@/components/docx-file-viewer';
import { PersistentViewerCache } from '@/components/persistent-viewer-cache';
import { UnsupportedFileViewer } from '@/components/unsupported-file-viewer';
import { getViewerType, isCacheableViewerPath } from '@/lib/file-types';
@ -28,6 +29,7 @@ import { LiveNotesView } from '@/components/live-notes-view';
import { BgTasksView } from '@/components/bg-tasks-view';
import { EmailView } from '@/components/email-view';
import { WorkspaceView } from '@/components/workspace-view';
import { CodingRunBlock } from '@/components/coding-run';
import { KnowledgeView } from '@/components/knowledge-view';
import { ChatHistoryView } from '@/components/chat-history-view';
import { HomeView } from '@/components/home-view';
@ -55,9 +57,10 @@ import { WebSearchResult } from '@/components/ai-elements/web-search-result';
import { AppActionCard } from '@/components/ai-elements/app-action-card';
import { ComposioConnectCard } from '@/components/ai-elements/composio-connect-card';
import { PermissionRequest } from '@/components/ai-elements/permission-request';
import { AutoPermissionDecision } from '@/components/ai-elements/auto-permission-decision';
import { TerminalOutput } from '@/components/terminal-output';
import { AskHumanRequest } from '@/components/ai-elements/ask-human-request';
import { ToolPermissionRequestEvent, AskHumanRequestEvent } from '@x/shared/src/runs.js';
import { ToolPermissionAutoDecisionEvent, ToolPermissionRequestEvent, AskHumanRequestEvent } from '@x/shared/src/runs.js';
import {
SidebarInset,
SidebarProvider,
@ -74,7 +77,7 @@ import { splitFrontmatter, joinFrontmatter } from '@/lib/frontmatter'
import { extractConferenceLink } from '@/lib/calendar-event'
import { OnboardingModal } from '@/components/onboarding'
import { ComposioGoogleMigrationModal } from '@/components/composio-google-migration-modal'
import { CommandPalette, type CommandPaletteMention } from '@/components/search-dialog'
import { CommandPalette, type CommandPaletteMention, type SearchType } from '@/components/search-dialog'
import { LiveNoteSidebar } from '@/components/live-note-sidebar'
import { BackgroundTaskDetail } from '@/components/background-task-detail'
import { BrowserPane } from '@/components/browser-pane/BrowserPane'
@ -115,6 +118,7 @@ import { useVoiceTTS } from '@/hooks/useVoiceTTS'
import { useMeetingTranscription, type CalendarEventMeta } from '@/hooks/useMeetingTranscription'
import { useAnalyticsIdentity } from '@/hooks/useAnalyticsIdentity'
import * as analytics from '@/lib/analytics'
import { useTheme } from '@/contexts/theme-context'
type DirEntry = z.infer<typeof workspace.DirEntry>
type RunEventType = z.infer<typeof RunEvent>
@ -163,6 +167,7 @@ function AutoScrollPre({ className, children }: { className?: string; children:
}
const DEFAULT_SIDEBAR_WIDTH = 256
const DEFAULT_CHAT_PANE_WIDTH = 460
const wikiLinkRegex = /\[\[([^[\]]+)\]\]/g
const graphPalette = [
{ hue: 210, sat: 72, light: 52 },
@ -581,7 +586,7 @@ type ViewState =
| { type: 'live-notes' }
| { type: 'email' }
| { type: 'workspace'; path?: string }
| { type: 'knowledge-view' }
| { type: 'knowledge-view'; folderPath?: string }
| { type: 'chat-history' }
| { type: 'home' }
@ -591,6 +596,7 @@ function viewStatesEqual(a: ViewState, b: ViewState): boolean {
if (a.type === 'file' && b.type === 'file') return a.path === b.path
if (a.type === 'task' && b.type === 'task') return a.name === b.name
if (a.type === 'workspace' && b.type === 'workspace') return (a.path ?? '') === (b.path ?? '')
if (a.type === 'knowledge-view' && b.type === 'knowledge-view') return (a.folderPath ?? '') === (b.folderPath ?? '')
return true // both graph
}
@ -638,8 +644,10 @@ function parseDeepLink(input: string): ViewState | null {
const path = params.get('path')
return { type: 'workspace', path: path ?? undefined }
}
case 'knowledge-view':
return { type: 'knowledge-view' }
case 'knowledge-view': {
const folderPath = params.get('folderPath')
return { type: 'knowledge-view', folderPath: folderPath ?? undefined }
}
case 'chat-history':
return { type: 'chat-history' }
case 'home':
@ -731,6 +739,9 @@ function ContentHeader({
}
function App() {
const { chatPanePlacement, chatPaneSize } = useTheme()
const isChatPaneInMiddle = chatPanePlacement === 'middle'
type ShortcutPane = 'left' | 'right'
type MarkdownHistoryHandlers = { undo: () => boolean; redo: () => boolean }
@ -756,8 +767,11 @@ function App() {
const [isWorkspaceOpen, setIsWorkspaceOpen] = useState(false)
const [workspaceInitialPath, setWorkspaceInitialPath] = useState<string | null>(null)
const [isKnowledgeViewOpen, setIsKnowledgeViewOpen] = useState(false)
// Folder being browsed inside the knowledge view (null = root overview).
// Lives in ViewState so folder drill-down participates in back/forward history.
const [knowledgeViewFolderPath, setKnowledgeViewFolderPath] = useState<string | null>(null)
const [isChatHistoryOpen, setIsChatHistoryOpen] = useState(false)
// Default landing view: Home in the middle with the chat docked on the right.
// Default landing view: Home with the chat docked according to appearance settings.
const [isHomeOpen, setIsHomeOpen] = useState(true)
const [emailInitialThreadId, setEmailInitialThreadId] = useState<string | null>(null)
const [emailThreadIdVersion, setEmailThreadIdVersion] = useState(0)
@ -954,7 +968,7 @@ function App() {
voice.start()
}, [voice])
const handlePromptSubmitRef = useRef<((message: PromptInputMessage, mentions?: FileMention[], stagedAttachments?: StagedAttachment[], searchEnabled?: boolean) => Promise<void>) | null>(null)
const handlePromptSubmitRef = useRef<((message: PromptInputMessage, mentions?: FileMention[], stagedAttachments?: StagedAttachment[], searchEnabled?: boolean, codeMode?: 'claude' | 'codex', permissionMode?: PermissionMode) => Promise<void>) | null>(null)
const pendingVoiceInputRef = useRef(false)
// Palette: per-tab editor handles for capturing cursor context on Cmd+K, and pending payload
@ -1173,6 +1187,7 @@ function App() {
const [allPermissionRequests, setAllPermissionRequests] = useState<Map<string, z.infer<typeof ToolPermissionRequestEvent>>>(new Map())
// Track permission responses (toolCallId -> response)
const [permissionResponses, setPermissionResponses] = useState<Map<string, 'approve' | 'deny'>>(new Map())
const [autoPermissionDecisions, setAutoPermissionDecisions] = useState<Map<string, z.infer<typeof ToolPermissionAutoDecisionEvent>>>(new Map())
useEffect(() => {
chatViewStateByTabRef.current = chatViewStateByTab
@ -1186,6 +1201,7 @@ function App() {
pendingAskHumanRequests: new Map(pendingAskHumanRequests),
allPermissionRequests: new Map(allPermissionRequests),
permissionResponses: new Map(permissionResponses),
autoPermissionDecisions: new Map(autoPermissionDecisions),
}
setChatViewStateByTab((prev) => ({ ...prev, [activeChatTabId]: snapshot }))
}, [
@ -1196,6 +1212,7 @@ function App() {
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
autoPermissionDecisions,
])
useEffect(() => {
@ -1247,6 +1264,8 @@ function App() {
// Search state
const [isSearchOpen, setIsSearchOpen] = useState(false)
// Optional scope override for the next time search opens (cleared on close).
const [searchDefaultScope, setSearchDefaultScope] = useState<SearchType | undefined>(undefined)
// Background tasks state
type BackgroundTaskItem = {
@ -2017,6 +2036,7 @@ function App() {
// Track permission requests and responses from history
const allPermissionRequests = new Map<string, z.infer<typeof ToolPermissionRequestEvent>>()
const permResponseMap = new Map<string, 'approve' | 'deny'>()
const autoPermissionDecisions = new Map<string, z.infer<typeof ToolPermissionAutoDecisionEvent>>()
const askHumanRequests = new Map<string, z.infer<typeof AskHumanRequestEvent>>()
const respondedAskHumanIds = new Set<string>()
@ -2025,6 +2045,8 @@ function App() {
allPermissionRequests.set(event.toolCall.toolCallId, event)
} else if (event.type === 'tool-permission-response') {
permResponseMap.set(event.toolCallId, event.response)
} else if (event.type === 'tool-permission-auto-decision') {
autoPermissionDecisions.set(event.toolCallId, event)
} else if (event.type === 'ask-human-request') {
askHumanRequests.set(event.toolCallId, event)
} else if (event.type === 'ask-human-response') {
@ -2057,6 +2079,7 @@ function App() {
setPendingAskHumanRequests(pendingAsks)
setAllPermissionRequests(allPermissionRequests)
setPermissionResponses(permResponseMap)
setAutoPermissionDecisions(autoPermissionDecisions)
// Restore the run's per-chat work directory into the tab it was loaded into.
const tabId = activeChatTabIdRef.current
@ -2273,6 +2296,8 @@ function App() {
...item,
result: event.result as ToolUIPart['output'],
status: 'completed' as const,
// a code_agent_run finished — drop any lingering permission card
pendingCodePermission: null,
}
}
return item
@ -2290,7 +2315,7 @@ function App() {
return next
})
if (event.toolCallId && event.toolName !== 'executeCommand') {
if (event.toolCallId) {
setToolOpenForTab(activeChatTabIdRef.current, event.toolCallId, false)
}
@ -2353,6 +2378,43 @@ function App() {
break
}
case 'code-run-event': {
if (!isActiveRun) return
setConversation(prev => prev.map(item => {
if (isToolCall(item) && item.id === event.toolCallId) {
const existing = item.codeRunEvents ?? []
if (existing.length === 0) {
setToolOpenForTab(activeChatTabIdRef.current, item.id, true)
}
return { ...item, codeRunEvents: [...existing, event.event] }
}
return item
}))
break
}
case 'code-run-permission-request': {
if (!isActiveRun) return
setConversation(prev => prev.map(item => {
if (isToolCall(item) && item.id === event.toolCallId) {
setToolOpenForTab(activeChatTabIdRef.current, item.id, true)
return { ...item, pendingCodePermission: { requestId: event.requestId, ask: event.ask } }
}
return item
}))
break
}
case 'tool-permission-auto-decision': {
if (!isActiveRun) return
setAutoPermissionDecisions(prev => {
const next = new Map(prev)
next.set(event.toolCallId, event)
return next
})
break
}
case 'ask-human-request': {
if (!isActiveRun) return
const key = event.toolCallId
@ -2468,6 +2530,8 @@ function App() {
mentions?: FileMention[],
stagedAttachments: StagedAttachment[] = [],
searchEnabled?: boolean,
codeMode?: 'claude' | 'codex',
permissionMode?: PermissionMode,
) => {
if (isProcessing) return
@ -2507,6 +2571,7 @@ function App() {
const run = await window.ipc.invoke('runs:create', {
agentId,
...(selected ? { model: selected.model, provider: selected.provider } : {}),
permissionMode: permissionMode ?? 'manual',
})
currentRunId = run.id
newRunCreatedAt = run.createdAt
@ -2579,6 +2644,7 @@ function App() {
voiceInput: pendingVoiceInputRef.current || undefined,
voiceOutput: ttsEnabledRef.current ? ttsModeRef.current : undefined,
searchEnabled: searchEnabled || undefined,
codeMode: codeMode || undefined,
middlePaneContext,
})
analytics.chatMessageSent({
@ -2594,6 +2660,7 @@ function App() {
voiceInput: pendingVoiceInputRef.current || undefined,
voiceOutput: ttsEnabledRef.current ? ttsModeRef.current : undefined,
searchEnabled: searchEnabled || undefined,
codeMode: codeMode || undefined,
middlePaneContext,
})
analytics.chatMessageSent({
@ -2680,6 +2747,26 @@ function App() {
}
}, [runId])
// Answer a mid-run permission request from a code_agent_run coding turn. The
// pending ask lives on the tool call itself, so we optimistically clear it and
// tell main which decision the user picked (keyed by the request id).
const handleCodePermissionResponse = useCallback(async (
toolCallId: string,
requestId: string,
decision: 'allow_once' | 'allow_always' | 'reject',
) => {
setConversation(prev => prev.map(item =>
isToolCall(item) && item.id === toolCallId
? { ...item, pendingCodePermission: null }
: item
))
try {
await window.ipc.invoke('codeRun:resolvePermission', { requestId, decision })
} catch (error) {
console.error('Failed to resolve code permission:', error)
}
}, [])
const handleAskHumanResponse = useCallback(async (toolCallId: string, subflow: string[], response: string) => {
if (!runId) return
try {
@ -2709,6 +2796,7 @@ function App() {
setPendingAskHumanRequests(new Map())
setAllPermissionRequests(new Map())
setPermissionResponses(new Map())
setAutoPermissionDecisions(new Map())
setSelectedBackgroundTask(null)
setChatViewportAnchor(activeChatTabIdRef.current, null)
setChatViewStateByTab(prev => ({
@ -2735,6 +2823,7 @@ function App() {
setPendingAskHumanRequests(new Map())
setAllPermissionRequests(new Map())
setPermissionResponses(new Map())
setAutoPermissionDecisions(new Map())
setChatViewportAnchor(tab.id, null)
}
}, [loadRun, setChatViewportAnchor])
@ -2760,6 +2849,7 @@ function App() {
setPendingAskHumanRequests(new Map(cached.pendingAskHumanRequests))
setAllPermissionRequests(new Map(cached.allPermissionRequests))
setPermissionResponses(new Map(cached.permissionResponses))
setAutoPermissionDecisions(new Map(cached.autoPermissionDecisions))
setIsProcessing(Boolean(resolvedRunId && processingRunIdsRef.current.has(resolvedRunId)))
return true
}, [])
@ -3391,8 +3481,10 @@ function App() {
setIsMeetingsOpen(false); setIsLiveNotesOpen(false); setIsBgTasksOpen(false); setIsEmailOpen(false); setIsWorkspaceOpen(false); setIsKnowledgeViewOpen(false); setIsChatHistoryOpen(false); setIsHomeOpen(false)
}, [selectedPath, isGraphOpen, isSuggestedTopicsOpen, isMeetingsOpen, isLiveNotesOpen, isBgTasksOpen, isEmailOpen, isWorkspaceOpen, isKnowledgeViewOpen, isChatHistoryOpen, dismissBrowserOverlay])
const handleCloseFullScreenChat = useCallback(() => {
const handleCloseFullScreenChat = useCallback((): boolean => {
let restored = false
if (expandedFrom) {
restored = true
if (expandedFrom.graph) {
setIsGraphOpen(true)
setIsSuggestedTopicsOpen(false)
@ -3434,10 +3526,16 @@ function App() {
setIsSuggestedTopicsOpen(false)
setIsMeetingsOpen(false); setIsLiveNotesOpen(false); setIsBgTasksOpen(false); setIsEmailOpen(false); setIsWorkspaceOpen(false); setIsKnowledgeViewOpen(false); setIsChatHistoryOpen(false); setIsHomeOpen(false)
setSelectedPath(expandedFrom.path)
} else {
// expandedFrom was captured from a view this restorer doesn't track
// (e.g. Home): there's nothing to re-open, so report it and let the
// caller fall back instead of leaving a blank full-screen chat.
restored = false
}
setExpandedFrom(null)
setIsRightPaneMaximized(false)
}
return restored
}, [expandedFrom])
const currentViewState = React.useMemo<ViewState>(() => {
@ -3447,13 +3545,13 @@ function App() {
if (isLiveNotesOpen) return { type: 'live-notes' }
if (isSuggestedTopicsOpen) return { type: 'suggested-topics' }
if (isWorkspaceOpen) return { type: 'workspace', path: workspaceInitialPath ?? undefined }
if (isKnowledgeViewOpen) return { type: 'knowledge-view' }
if (isKnowledgeViewOpen) return { type: 'knowledge-view', folderPath: knowledgeViewFolderPath ?? undefined }
if (isChatHistoryOpen) return { type: 'chat-history' }
if (isHomeOpen) return { type: 'home' }
if (selectedPath) return { type: 'file', path: selectedPath }
if (isGraphOpen) return { type: 'graph' }
return { type: 'chat', runId }
}, [selectedBackgroundTask, isEmailOpen, isMeetingsOpen, isLiveNotesOpen, isBgTasksOpen, isSuggestedTopicsOpen, selectedPath, isGraphOpen, isWorkspaceOpen, isKnowledgeViewOpen, isChatHistoryOpen, isHomeOpen, workspaceInitialPath, runId])
}, [selectedBackgroundTask, isEmailOpen, isMeetingsOpen, isLiveNotesOpen, isBgTasksOpen, isSuggestedTopicsOpen, selectedPath, isGraphOpen, isWorkspaceOpen, isKnowledgeViewOpen, knowledgeViewFolderPath, isChatHistoryOpen, isHomeOpen, workspaceInitialPath, runId])
const appendUnique = useCallback((stack: ViewState[], entry: ViewState) => {
const last = stack[stack.length - 1]
@ -3793,6 +3891,7 @@ function App() {
setIsEmailOpen(false)
setIsWorkspaceOpen(false)
setIsKnowledgeViewOpen(true)
setKnowledgeViewFolderPath(view.folderPath ?? null)
setIsChatHistoryOpen(false)
setIsHomeOpen(false)
ensureKnowledgeViewFileTab()
@ -3885,12 +3984,13 @@ function App() {
const pushChatToSidePane = useCallback(() => {
setIsRightPaneMaximized(false)
setIsChatSidebarOpen(true)
if (expandedFrom) {
handleCloseFullScreenChat()
} else {
// Restore the view we expanded from; if there was nothing to restore
// (e.g. the chat was started fresh from Home), fall back to Home so a
// single click always docks the chat instead of needing two.
if (!handleCloseFullScreenChat()) {
void navigateToView({ type: 'home' })
}
}, [expandedFrom, handleCloseFullScreenChat, navigateToView])
}, [handleCloseFullScreenChat, navigateToView])
const navigateBack = useCallback(async () => {
const { back, forward } = historyRef.current
@ -4539,10 +4639,8 @@ function App() {
void navigateToView({ type: 'workspace', path })
},
openKnowledgeView: () => {
if (!selectedPath && !isGraphOpen && !isSuggestedTopicsOpen && !isMeetingsOpen && !isLiveNotesOpen && !isBgTasksOpen && !isEmailOpen && !isWorkspaceOpen && !isKnowledgeViewOpen && !isChatHistoryOpen && !selectedBackgroundTask) {
setIsChatSidebarOpen(false)
setIsRightPaneMaximized(false)
}
// Open in the middle pane without touching the chat sidebar — leave it
// open or closed exactly as the user had it (matches Email/Meetings).
void navigateToView({ type: 'knowledge-view' })
},
createWorkspace: async (name: string): Promise<string> => {
@ -5024,7 +5122,11 @@ function App() {
}
}, [isGraphOpen, knowledgeFilePaths])
const renderConversationItem = (item: ConversationItem, tabId: string) => {
const renderConversationItem = (
item: ConversationItem,
tabId: string,
options?: { autoPermissionDetail?: { decision: 'allow'; reason: string } },
) => {
if (isChatMessage(item)) {
if (item.role === 'user') {
if (item.attachments && item.attachments.length > 0) {
@ -5082,6 +5184,21 @@ function App() {
}
if (isToolCall(item)) {
if (item.name === 'code_agent_run') {
return (
<CodingRunBlock
key={item.id}
item={item}
open={isToolOpenForTab(tabId, item.id)}
onOpenChange={(open) => setToolOpenForTab(tabId, item.id, open)}
onPermissionDecision={(decision) => {
if (item.pendingCodePermission) {
handleCodePermissionResponse(item.id, item.pendingCodePermission.requestId, decision)
}
}}
/>
)
}
const appActionData = getAppActionCardData(item)
if (appActionData) {
return <AppActionCard key={item.id} data={appActionData} status={item.status} />
@ -5122,6 +5239,7 @@ function App() {
key={item.id}
open={isToolOpenForTab(tabId, item.id)}
onOpenChange={(open) => setToolOpenForTab(tabId, item.id, open)}
autoPermissionDetail={options?.autoPermissionDetail}
>
<ToolHeader
title={toolTitle}
@ -5164,6 +5282,7 @@ function App() {
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
autoPermissionDecisions,
}), [
runId,
conversation,
@ -5171,6 +5290,7 @@ function App() {
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
autoPermissionDecisions,
])
const emptyChatTabState = React.useMemo<ChatTabViewState>(() => createEmptyChatTabViewState(), [])
const getChatTabStateForRender = useCallback((tabId: string): ChatTabViewState => {
@ -5183,6 +5303,17 @@ function App() {
const isRightPaneContext = Boolean(selectedPath || isGraphOpen || isSuggestedTopicsOpen || isMeetingsOpen || isLiveNotesOpen || isBgTasksOpen || isEmailOpen || isWorkspaceOpen || isKnowledgeViewOpen || isChatHistoryOpen || isHomeOpen || isBrowserOpen)
const isRightPaneOnlyMode = isRightPaneContext && isChatSidebarOpen && isRightPaneMaximized
const shouldCollapseLeftPane = isRightPaneOnlyMode
const nonChatPaneStyle = React.useMemo<React.CSSProperties>(() => {
const style: React.CSSProperties = { maxWidth: insetMaxWidth }
if (!isRightPaneContext || !isChatSidebarOpen || isRightPaneMaximized) return style
if (chatPaneSize === 'chat-equal') {
return { ...style, width: 0, flex: '1 1 0' }
}
if (chatPaneSize === 'chat-bigger') {
return { ...style, width: DEFAULT_CHAT_PANE_WIDTH, flex: '0 0 auto' }
}
return style
}, [chatPaneSize, insetMaxWidth, isChatSidebarOpen, isRightPaneContext, isRightPaneMaximized])
// Collapsing: pin max-width to the snapshot px (no transition) for one frame so it's
// binding immediately (no flex jump), then animate to 0. Expanding goes back to 100%
// — its non-binding range lands at the end of the range, where it isn't visible.
@ -5260,10 +5391,11 @@ function App() {
<SidebarInset
className={cn(
"overflow-hidden! min-h-0 min-w-0",
isRightPaneContext && isChatPaneInMiddle && "order-3",
insetAnimateMaxWidth && "transition-[max-width] duration-200 ease-linear",
shouldCollapseLeftPane && "pointer-events-none select-none"
)}
style={{ maxWidth: insetMaxWidth }}
style={nonChatPaneStyle}
aria-hidden={shouldCollapseLeftPane}
onMouseDownCapture={() => setActiveShortcutPane('left')}
onFocusCapture={() => setActiveShortcutPane('left')}
@ -5375,7 +5507,11 @@ function App() {
: (viewOpen && !isChatSidebarOpen)
? { onClick: openChatSidePane, icon: <MessageSquare className="size-5" />, label: 'Open chat' }
: (viewOpen && isChatSidebarOpen && !isRightPaneMaximized)
? { onClick: toggleRightPaneMaximize, icon: <X className="size-5" />, label: 'Expand chat' }
? {
onClick: () => setIsChatSidebarOpen(false),
icon: isChatPaneInMiddle ? <ArrowLeft className="size-5" /> : <ArrowRight className="size-5" />,
label: 'Expand pane'
}
: null
return (
<Tooltip>
@ -5474,7 +5610,11 @@ function App() {
remove: knowledgeActions.remove,
copyPath: knowledgeActions.copyPath,
revealInFileManager: knowledgeActions.revealInFileManager,
createNote: knowledgeActions.createNote,
createFolder: knowledgeActions.createFolder,
onOpenInNewTab: knowledgeActions.onOpenInNewTab,
}}
onNavigate={(path) => { void navigateToView({ type: 'workspace', path: path === WORKSPACE_ROOT ? undefined : path }) }}
onOpenNote={(path) => navigateToFile(path)}
onCreateWorkspace={async (name) => { await knowledgeActions.createWorkspace(name) }}
/>
@ -5492,9 +5632,11 @@ function App() {
revealInFileManager: knowledgeActions.revealInFileManager,
onOpenInNewTab: knowledgeActions.onOpenInNewTab,
}}
folderPath={knowledgeViewFolderPath}
onNavigateFolder={(path) => { void navigateToView({ type: 'knowledge-view', folderPath: path ?? undefined }) }}
onOpenNote={(path) => navigateToFile(path)}
onOpenGraph={() => knowledgeActions.openGraph()}
onOpenSearch={() => setIsSearchOpen(true)}
onOpenSearch={() => { setSearchDefaultScope('knowledge'); setIsSearchOpen(true) }}
onOpenBases={() => knowledgeActions.openBases()}
onVoiceNoteCreated={handleVoiceNoteCreated}
/>
@ -5684,6 +5826,10 @@ function App() {
<div className="flex-1 min-h-0 overflow-hidden">
<AudioFileViewer path={selectedPath} />
</div>
) : selectedPath && getViewerType(selectedPath) === 'docx' ? (
<div className="flex-1 min-h-0 overflow-hidden">
<DocxFileViewer path={selectedPath} />
</div>
) : (
<div className="flex-1 min-h-0 overflow-hidden">
<UnsupportedFileViewer path={selectedPath} />
@ -5747,7 +5893,7 @@ function App() {
<>
{groupConversationItems(
tabState.conversation,
(id) => !!tabState.allPermissionRequests.get(id)
(id) => !!tabState.allPermissionRequests.get(id) || !!tabState.autoPermissionDecisions.get(id)
).map(item => {
if (isToolGroup(item)) {
return (
@ -5759,24 +5905,44 @@ function App() {
/>
)
}
const rendered = renderConversationItem(item, tab.id)
const autoDecision = isToolCall(item)
? tabState.autoPermissionDecisions.get(item.id)
: undefined
const rendered = renderConversationItem(
item,
tab.id,
autoDecision?.decision === 'allow'
? { autoPermissionDetail: { decision: 'allow', reason: autoDecision.reason } }
: undefined,
)
if (isToolCall(item)) {
const deniedAutoDecision = autoDecision?.decision === 'deny' ? autoDecision : null
const permRequest = tabState.allPermissionRequests.get(item.id)
if (permRequest) {
if (deniedAutoDecision || permRequest) {
const response = tabState.permissionResponses.get(item.id) || null
return (
<React.Fragment key={item.id}>
{deniedAutoDecision && (
<AutoPermissionDecision
toolCall={deniedAutoDecision.toolCall}
permission={deniedAutoDecision.permission}
decision={deniedAutoDecision.decision}
reason={deniedAutoDecision.reason}
/>
)}
{permRequest && (
<PermissionRequest
toolCall={permRequest.toolCall}
permission={permRequest.permission}
onApprove={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve')}
onApproveSession={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'session')}
onApproveAlways={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'always')}
onDeny={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')}
isProcessing={isActive && isProcessing}
response={response}
/>
)}
{rendered}
<PermissionRequest
toolCall={permRequest.toolCall}
permission={permRequest.permission}
onApprove={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve')}
onApproveSession={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'session')}
onApproveAlways={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'always')}
onDeny={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')}
isProcessing={isActive && isProcessing}
response={response}
/>
</React.Fragment>
)
}
@ -5788,6 +5954,7 @@ function App() {
<AskHumanRequest
key={request.toolCallId}
query={request.query}
options={request.options}
onResponse={(response) => handleAskHumanResponse(request.toolCallId, request.subflow, response)}
isProcessing={isActive && isProcessing}
/>
@ -5877,10 +6044,13 @@ function App() {
)}
</SidebarInset>
{/* Chat sidebar - shown when viewing files/graph */}
{/* Chat pane - shown when viewing files/graph */}
{isRightPaneContext && (
<ChatSidebar
defaultWidth={460}
placement={chatPanePlacement}
paneSize={chatPaneSize}
className={isChatPaneInMiddle ? "order-2" : undefined}
defaultWidth={DEFAULT_CHAT_PANE_WIDTH}
isOpen={isChatSidebarOpen}
isMaximized={isRightPaneMaximized}
chatTabs={chatTabs}
@ -5899,7 +6069,6 @@ function App() {
}}
onOpenChatHistory={() => void navigateToView({ type: 'chat-history' })}
onOpenFullScreen={toggleRightPaneMaximize}
onCloseChat={() => { setIsRightPaneMaximized(false); setIsChatSidebarOpen(false) }}
conversation={conversation}
currentAssistantMessage={currentAssistantMessage}
chatTabStates={chatViewStateByTab}
@ -5928,6 +6097,7 @@ function App() {
pendingAskHumanRequests={pendingAskHumanRequests}
allPermissionRequests={allPermissionRequests}
permissionResponses={permissionResponses}
autoPermissionDecisions={autoPermissionDecisions}
onPermissionResponse={handlePermissionResponse}
onAskHumanResponse={handleAskHumanResponse}
isToolOpenForTab={isToolOpenForTab}
@ -5958,7 +6128,8 @@ function App() {
</div>
<CommandPalette
open={isSearchOpen}
onOpenChange={setIsSearchOpen}
onOpenChange={(o) => { setIsSearchOpen(o); if (!o) setSearchDefaultScope(undefined) }}
defaultScope={searchDefaultScope}
onSelectFile={navigateToFile}
onSelectRun={(id) => { void navigateToView({ type: 'chat', runId: id }) }}
/>

View file

@ -9,6 +9,7 @@ import { useState, useRef, useEffect } from "react";
export type AskHumanRequestProps = ComponentProps<"div"> & {
query: string;
options?: string[];
onResponse: (response: string) => void;
isProcessing?: boolean;
};
@ -16,17 +17,21 @@ export type AskHumanRequestProps = ComponentProps<"div"> & {
export const AskHumanRequest = ({
className,
query,
options,
onResponse,
isProcessing = false,
...props
}: AskHumanRequestProps) => {
const [response, setResponse] = useState("");
const textareaRef = useRef<HTMLTextAreaElement>(null);
const hasOptions = Array.isArray(options) && options.length > 0;
useEffect(() => {
// Auto-focus the textarea when component mounts
textareaRef.current?.focus();
}, []);
// Auto-focus the textarea when in free-text mode; nothing to focus for buttons.
if (!hasOptions) {
textareaRef.current?.focus();
}
}, [hasOptions]);
const handleSubmit = () => {
const trimmed = response.trim();
@ -36,6 +41,11 @@ export const AskHumanRequest = ({
}
};
const handleOptionClick = (option: string) => {
if (isProcessing) return;
onResponse(option);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
@ -65,30 +75,47 @@ export const AskHumanRequest = ({
{query}
</p>
</div>
<div className="space-y-2">
<Textarea
ref={textareaRef}
value={response}
onChange={(e) => setResponse(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type your response..."
disabled={isProcessing}
rows={3}
className="resize-none"
/>
<div className="flex justify-end">
<Button
variant="default"
size="sm"
onClick={handleSubmit}
disabled={!canSubmit}
className="gap-2"
>
<ArrowUpIcon className="size-4" />
Send Response
</Button>
{hasOptions ? (
<div className="flex flex-wrap gap-2">
{options!.map((option) => (
<Button
key={option}
variant="outline"
size="sm"
onClick={() => handleOptionClick(option)}
disabled={isProcessing}
className="bg-background"
>
{option}
</Button>
))}
</div>
</div>
) : (
<div className="space-y-2">
<Textarea
ref={textareaRef}
value={response}
onChange={(e) => setResponse(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type your response..."
disabled={isProcessing}
rows={3}
className="resize-none"
/>
<div className="flex justify-end">
<Button
variant="default"
size="sm"
onClick={handleSubmit}
disabled={!canSubmit}
className="gap-2"
>
<ArrowUpIcon className="size-4" />
Send Response
</Button>
</div>
</div>
)}
</div>
</div>
</div>

View file

@ -0,0 +1,100 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { CheckCircle2Icon, ShieldAlertIcon, Terminal } from "lucide-react";
import type { ComponentProps } from "react";
import { ToolCallPart } from "@x/shared/dist/message.js";
import { ToolPermissionMetadata } from "@x/shared/dist/runs.js";
import z from "zod";
export type AutoPermissionDecisionProps = ComponentProps<"div"> & {
toolCall: z.infer<typeof ToolCallPart>;
decision: "allow" | "deny";
reason: string;
permission?: z.infer<typeof ToolPermissionMetadata>;
};
const fileActionLabels: Record<string, string> = {
read: "Read file",
list: "List folder",
search: "Search files",
write: "Write files",
delete: "Delete path",
};
export function AutoPermissionDecision({
className,
toolCall,
decision,
reason,
permission,
...props
}: AutoPermissionDecisionProps) {
const command = permission?.kind === "command" || toolCall.toolName === "executeCommand"
? (typeof toolCall.arguments === "object" && toolCall.arguments !== null && "command" in toolCall.arguments
? String(toolCall.arguments.command)
: JSON.stringify(toolCall.arguments))
: null;
const filePermission = permission?.kind === "file" ? permission : null;
const allowed = decision === "allow";
return (
<div
className={cn(
"not-prose mb-4 w-full rounded-md border",
allowed
? "border-green-500/50 bg-green-50/80 dark:border-green-500/35 dark:bg-green-950/30"
: "border-[#fa2525]/60 bg-[#fa2525]/15 dark:border-[#fa2525]/50 dark:bg-[#fa2525]/20",
className,
)}
{...props}
>
<div className="space-y-3 p-4">
<div className="flex items-start gap-3">
{allowed ? (
<CheckCircle2Icon className="mt-0.5 size-5 shrink-0 text-green-600 dark:text-green-400" />
) : (
<ShieldAlertIcon className="mt-0.5 size-5 shrink-0 text-destructive" />
)}
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-sm font-semibold text-foreground">
{allowed ? "Auto Allowed" : "Auto Denied"}
</h3>
<Badge variant="secondary" className="bg-secondary text-foreground">
<Terminal className="mr-1 size-3" />
{toolCall.toolName}
</Badge>
</div>
<p className="mt-1 text-sm text-muted-foreground">{reason}</p>
</div>
</div>
{command && (
<div className="rounded-md border bg-background/50 p-3">
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">Command</p>
<pre className="whitespace-pre-wrap break-all font-mono text-xs text-foreground">{command}</pre>
</div>
)}
{filePermission && (
<div className="space-y-3 rounded-md border bg-background/50 p-3">
<div>
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">Action</p>
<p className="text-xs font-medium text-foreground">
{fileActionLabels[filePermission.operation] ?? filePermission.operation}
</p>
</div>
<div>
<p className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">
Path{filePermission.paths.length === 1 ? "" : "s"}
</p>
<pre className="whitespace-pre-wrap break-all font-mono text-xs text-foreground">
{filePermission.paths.join("\n")}
</pre>
</div>
</div>
)}
</div>
</div>
);
}

View file

@ -1,6 +1,5 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@ -9,8 +8,8 @@ import {
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { AlertTriangleIcon, CheckCircleIcon, CheckIcon, ChevronDownIcon, XCircleIcon, XIcon } from "lucide-react";
import type { ComponentProps } from "react";
import { AlertTriangleIcon, CheckIcon, ChevronDownIcon, XIcon } from "lucide-react";
import { useState, type ComponentProps } from "react";
import { ToolCallPart } from "@x/shared/dist/message.js";
import { ToolPermissionMetadata } from "@x/shared/dist/runs.js";
import z from "zod";
@ -57,14 +56,19 @@ export const PermissionRequest = ({
const isResponded = response !== null;
const isApproved = response === 'approve';
// Once a response is chosen, collapse the details to just the header.
// Users can click the header to expand them again.
const [expanded, setExpanded] = useState(false);
const showDetails = !isResponded || expanded;
return (
<div
className={cn(
"not-prose mb-4 w-full rounded-md border",
isResponded
? isApproved
? "border-green-500/50 bg-green-50/50 dark:bg-green-950/20"
: "border-red-500/50 bg-red-50/50 dark:bg-red-950/20"
? "border-green-500/60 bg-green-200/80 dark:border-green-500/40 dark:bg-green-900/40"
: "border-[#fa2525]/70 bg-[#fa2525]/30 dark:border-[#fa2525]/60 dark:bg-[#fa2525]/30"
: "border-amber-500/50 bg-amber-50/50 dark:bg-amber-950/20",
className
)}
@ -72,17 +76,14 @@ export const PermissionRequest = ({
>
<div className="p-4 space-y-4">
<div className="flex items-start gap-3">
{isResponded ? (
isApproved ? (
<CheckCircleIcon className="size-5 text-green-600 dark:text-green-500 shrink-0 mt-0.5" />
) : (
<XCircleIcon className="size-5 text-red-600 dark:text-red-500 shrink-0 mt-0.5" />
)
) : (
{!isResponded && (
<AlertTriangleIcon className="size-5 text-amber-600 dark:text-amber-500 shrink-0 mt-0.5" />
)}
<div className="flex-1 space-y-2">
<div className="flex items-center gap-2">
<div
className={cn("flex items-center gap-2", isResponded && "cursor-pointer select-none")}
onClick={isResponded ? () => setExpanded((v) => !v) : undefined}
>
<div className="flex-1">
<h3 className="font-semibold text-sm text-foreground">
{isResponded ? (isApproved ? "Permission Granted" : "Permission Denied") : "Permission Required"}
@ -92,30 +93,15 @@ export const PermissionRequest = ({
</p>
</div>
{isResponded && (
<Badge
variant="secondary"
<ChevronDownIcon
className={cn(
"shrink-0",
isApproved
? "bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-400"
: "bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-400"
"size-4 shrink-0 text-muted-foreground transition-transform",
expanded ? "rotate-180" : "rotate-0"
)}
>
{isApproved ? (
<>
<CheckIcon className="size-3 mr-1" />
Approved
</>
) : (
<>
<XIcon className="size-3 mr-1" />
Denied
</>
)}
</Badge>
/>
)}
</div>
{command && (
{showDetails && command && (
<div className="rounded-md border bg-background/50 p-3 mt-3">
<p className="text-xs font-medium text-muted-foreground mb-1.5 uppercase tracking-wide">
Command
@ -125,7 +111,7 @@ export const PermissionRequest = ({
</pre>
</div>
)}
{filePermission && (
{showDetails && filePermission && (
<div className="rounded-md border bg-background/50 p-3 mt-3 space-y-3">
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 uppercase tracking-wide">
@ -153,7 +139,7 @@ export const PermissionRequest = ({
</div>
</div>
)}
{!command && !filePermission && toolCall.arguments && (
{showDetails && !command && !filePermission && toolCall.arguments && (
<div className="rounded-md border bg-background/50 p-3 mt-3">
<p className="text-xs font-medium text-muted-foreground mb-1.5 uppercase tracking-wide">
Arguments

View file

@ -1,25 +1,28 @@
"use client";
import { Badge } from "@/components/ui/badge";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import type { ToolUIPart } from "ai";
import {
CheckCircleIcon,
ChevronDownIcon,
CircleIcon,
ClockIcon,
WrenchIcon,
CircleCheck,
LoaderIcon,
ShieldCheckIcon,
XCircleIcon,
} from "lucide-react";
import { type ComponentProps, type ReactNode, isValidElement, useState } from "react";
import { AnimatePresence, motion } from "motion/react";
import type { ToolCall, ToolGroup as ToolGroupType } from "@/lib/chat-conversation";
import { getToolDisplayName, getToolGroupSummary, toToolState } from "@/lib/chat-conversation";
import { getToolActionsSummary, getToolDisplayName, getToolGroupSummary, toToolState } from "@/lib/chat-conversation";
const formatToolValue = (value: unknown) => {
if (typeof value === "string") return value;
@ -48,51 +51,68 @@ const ToolCode = ({
</pre>
);
export type ToolProps = ComponentProps<typeof Collapsible>;
export type ToolAutoPermissionDetail = {
decision: "allow";
reason: string;
};
export const Tool = ({ className, ...props }: ToolProps) => (
<Collapsible
className={cn("not-prose mb-4 w-full rounded-md border", className)}
{...props}
/>
);
export type ToolProps = ComponentProps<typeof Collapsible> & {
autoPermissionDetail?: ToolAutoPermissionDetail;
};
export const Tool = ({ className, children, autoPermissionDetail, ...props }: ToolProps) => {
const toolCard = (
<Collapsible
className={cn(
autoPermissionDetail
? "w-full rounded-[28px] border bg-[var(--card-surface)] transition-colors duration-150 ease-out hover:border-foreground/30"
: "not-prose mb-4 w-full rounded-[28px] border bg-[var(--card-surface)] transition-colors duration-150 ease-out hover:border-foreground/30",
className
)}
{...props}
>
{children}
</Collapsible>
);
if (!autoPermissionDetail) return toolCard;
return (
<div className="not-prose mb-4 w-full">
{toolCard}
<div className="mt-1 flex justify-end px-3">
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help items-center gap-1 text-[11px] text-muted-foreground/70">
<ShieldCheckIcon className="size-3 text-muted-foreground/70" />
Auto-approved
</span>
</TooltipTrigger>
<TooltipContent side="bottom" align="end" className="max-w-sm">
{autoPermissionDetail.reason}
</TooltipContent>
</Tooltip>
</div>
</div>
);
};
export type ToolHeaderProps = {
title?: string;
type: ToolUIPart["type"];
state: ToolUIPart["state"];
className?: string;
/** Hide the leading status icon (used for child rows inside a tool group). */
hideLeadIcon?: boolean;
};
const getStatusBadge = (status: ToolUIPart["state"]) => {
const labels: Record<ToolUIPart["state"], string> = {
"input-streaming": "Pending",
"input-available": "Running",
// @ts-expect-error state only available in AI SDK v6
"approval-requested": "Awaiting Approval",
"approval-responded": "Responded",
"output-available": "Completed",
"output-error": "Error",
"output-denied": "Denied",
};
const icons: Record<ToolUIPart["state"], ReactNode> = {
"input-streaming": <CircleIcon className="size-4" />,
"input-available": <ClockIcon className="size-4 animate-pulse" />,
// @ts-expect-error state only available in AI SDK v6
"approval-requested": <ClockIcon className="size-4 text-yellow-600" />,
"approval-responded": <CheckCircleIcon className="size-4 text-blue-600" />,
"output-available": <CheckCircleIcon className="size-4 text-green-600" />,
"output-error": <XCircleIcon className="size-4 text-red-600" />,
"output-denied": <XCircleIcon className="size-4 text-orange-600" />,
};
return (
<Badge className="gap-1.5 rounded-full text-xs" variant="secondary">
{icons[status]}
{labels[status]}
</Badge>
);
// Lead icon shown to the left of the tool label: spinner while running, a
// green check when done, a red cross on error. Shared by ToolHeader (single
// tools) and the tool-call group.
const getLeadIcon = (state: ToolUIPart["state"]): ReactNode => {
if (state === "output-available") return <CircleCheck className="size-4 shrink-0 text-green-600" />;
if (state === "output-error") return <XCircleIcon className="size-4 shrink-0 text-red-600" />;
return <LoaderIcon className="size-4 shrink-0 animate-spin text-muted-foreground" />;
};
export const ToolHeader = ({
@ -100,6 +120,7 @@ export const ToolHeader = ({
title,
type,
state,
hideLeadIcon,
...props
}: ToolHeaderProps) => {
const displayTitle = title ?? type.split("-").slice(1).join("-")
@ -107,13 +128,13 @@ export const ToolHeader = ({
return (
<CollapsibleTrigger
className={cn(
"flex w-full items-center justify-between gap-4 p-3",
"group flex w-full cursor-pointer items-center justify-between gap-3 px-4 py-2.5",
className
)}
{...props}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
<WrenchIcon className="size-4 shrink-0 text-muted-foreground" />
{!hideLeadIcon && getLeadIcon(state)}
<span
className="min-w-0 flex-1 truncate text-left font-medium text-sm"
title={displayTitle}
@ -121,10 +142,7 @@ export const ToolHeader = ({
{displayTitle}
</span>
</div>
<div className="flex shrink-0 items-center gap-3">
{getStatusBadge(state)}
<ChevronDownIcon className="size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
</div>
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
</CollapsibleTrigger>
)
};
@ -134,7 +152,7 @@ export type ToolContentProps = ComponentProps<typeof CollapsibleContent>;
export const ToolContent = ({ className, ...props }: ToolContentProps) => (
<CollapsibleContent
className={cn(
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
"overflow-hidden text-popover-foreground outline-none data-[state=open]:animate-[collapsible-down_0.09s_ease-out] data-[state=closed]:animate-[collapsible-up_0.08s_ease-in]",
className
)}
{...props}
@ -247,41 +265,48 @@ export const ToolGroupComponent = ({ group, isToolOpen, onToolOpenChange }: Tool
const isCompleted = state === 'output-available' || state === 'output-error'
const runningTool = group.items.find(t => t.status === 'running' || t.status === 'pending')
const currentTool = runningTool ?? group.items[group.items.length - 1]
const summary = isCompleted
? `Ran ${group.items.length} tool${group.items.length !== 1 ? 's' : ''}`
const toolCount = group.items.length
const ranLabel = `Ran ${toolCount} tool${toolCount !== 1 ? 's' : ''}`
const actions = isCompleted ? getToolActionsSummary(group.items) : ''
// Plain string used as the AnimatePresence key + tooltip; the rendered node
// shows the action summary in a lighter gray than the "Ran N tools" prefix.
const summaryText = isCompleted
? `${ranLabel} · ${actions}`
: currentTool ? getToolDisplayName(currentTool) : getToolGroupSummary(group.items)
const summaryNode: ReactNode = isCompleted
? <>{ranLabel} <span className="font-normal text-muted-foreground">{`· ${actions}`}</span></>
: summaryText
const leadIcon = getLeadIcon(state)
return (
<Collapsible
open={open}
onOpenChange={setOpen}
className="not-prose mb-4 w-full rounded-md border"
className="not-prose mb-4 w-full rounded-[28px] border bg-[var(--card-surface)] transition-colors duration-150 ease-out hover:border-foreground/30"
>
<CollapsibleTrigger className="flex w-full items-center justify-between gap-4 p-3">
<CollapsibleTrigger className="flex w-full cursor-pointer items-center justify-between gap-3 px-4 py-2.5">
<div className="flex min-w-0 flex-1 items-center gap-2">
<WrenchIcon className="size-4 shrink-0 text-muted-foreground" />
{leadIcon}
<div className="relative min-w-0 flex-1 overflow-hidden" style={{ height: '1.25rem' }}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={summary}
key={summaryText}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="absolute inset-0 truncate text-left font-medium text-sm leading-5"
title={summary}
title={summaryText}
>
{summary}
{summaryNode}
</motion.span>
</AnimatePresence>
</div>
</div>
<div className="flex shrink-0 items-center gap-3">
{getStatusBadge(state)}
<ChevronDownIcon className={cn("size-4 text-muted-foreground transition-transform", open && "rotate-180")} />
</div>
<ChevronDownIcon className={cn("size-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-180")} />
</CollapsibleTrigger>
<CollapsibleContent className="border-t">
<CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_0.09s_ease-out] data-[state=closed]:animate-[collapsible-up_0.08s_ease-in]">
<div className="flex flex-col gap-2 p-2">
{group.items.map((tool) => {
const toolState = toToolState(tool.status)
@ -291,12 +316,14 @@ export const ToolGroupComponent = ({ group, isToolOpen, onToolOpenChange }: Tool
key={tool.id}
open={isOpen}
onOpenChange={(o) => onToolOpenChange(tool.id, o)}
className="mb-0 border-border/60"
className="mb-0 rounded-[20px] border-border/60 bg-transparent hover:border-border/60"
>
<ToolHeader
title={getToolDisplayName(tool)}
type={`tool-${tool.name}`}
state={toolState}
className="text-muted-foreground"
hideLeadIcon
/>
<ToolContent>
<ToolTabbedContent

View file

@ -5,12 +5,14 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";
import {
CheckCircleIcon,
ChevronDownIcon,
GlobeIcon,
LoaderIcon,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { AnimatePresence, motion } from "motion/react";
interface WebSearchResultProps {
query: string;
@ -19,39 +21,219 @@ interface WebSearchResultProps {
title?: string;
}
// How long each fetched website stays on the rolling header before the
// next one slides in. Kept slow enough to read the domain + title.
const ROLL_INTERVAL_MS = 700;
// How many favicons to show in the settled stack before the rest collapse
// into a "+N" chip. The text names this many domains too, so the chip count
// (total - MAX_STACK) lines up with the "and N others" in the summary.
const MAX_STACK = 3;
function getDomain(url: string): string {
try {
return new URL(url).hostname;
return new URL(url).hostname.replace(/^www\./, "");
} catch {
return url;
}
}
function faviconUrl(domain: string, size = 32): string {
return `https://www.google.com/s2/favicons?domain=${domain}&sz=${size}`;
}
// Collapse the result list into unique domains, preserving order.
function uniqueDomains(results: WebSearchResultProps["results"]): string[] {
const seen = new Set<string>();
const out: string[] = [];
for (const result of results) {
const domain = getDomain(result.url);
if (seen.has(domain)) continue;
seen.add(domain);
out.push(domain);
}
return out;
}
// Summary with text hierarchy: "Searched" + "and N others" are secondary
// weight/color, the domain names are primary text at medium weight.
function buildSearchedSummary(domains: string[]): React.ReactNode {
const muted = "font-normal text-muted-foreground";
const name = (d: string) => <span className="font-medium text-foreground">{d}</span>;
if (domains.length === 1) {
return (
<>
<span className={muted}>Searched </span>
{name(domains[0])}
</>
);
}
if (domains.length === 2) {
return (
<>
<span className={muted}>Searched </span>
{name(domains[0])}
<span className={muted}> and </span>
{name(domains[1])}
</>
);
}
const others = domains.length - 2;
return (
<>
<span className={muted}>Searched </span>
{name(domains[0])}
<span className={muted}>, </span>
{name(domains[1])}
<span className={muted}>{` and ${others} other${others !== 1 ? "s" : ""}`}</span>
</>
);
}
type RollPhase = "searching" | "rolling" | "settled";
export function WebSearchResult({ query, results, status, title = "Searched the web" }: WebSearchResultProps) {
const isRunning = status === "pending" || status === "running";
const [open, setOpen] = useState(false);
return (
<Collapsible defaultOpen className="not-prose mb-4 w-full rounded-md border">
<CollapsibleTrigger className="flex w-full items-center justify-between gap-4 p-3">
<div className="flex items-center gap-2">
<GlobeIcon className="size-4 text-muted-foreground" />
<span className="font-medium text-sm">{title}</span>
</div>
<ChevronDownIcon className="size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
</CollapsibleTrigger>
<CollapsibleContent>
<div className="px-3 pb-3 space-y-3">
{/* Query + result count */}
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 text-sm text-muted-foreground min-w-0">
<GlobeIcon className="size-3.5 shrink-0" />
<span className="truncate">{query}</span>
</div>
{results.length > 0 && (
<span className="text-xs text-muted-foreground whitespace-nowrap">
{results.length} result{results.length !== 1 ? "s" : ""}
const domains = useMemo(() => uniqueDomains(results), [results]);
// Drive the one-shot rolling reveal. Results arrive all at once, so we
// simulate "fetching one site at a time" by stepping through them with the
// same slide animation the tool group uses, then settle on a summary.
// `settled` is seeded from the initial status so a card loaded already-
// complete from history skips straight to the summary (no roll).
const [settled, setSettled] = useState(() => !isRunning);
const [rollIndex, setRollIndex] = useState(0);
// Phase is fully derived: searching while the tool runs, rolling once
// results land, then settled. No setState-in-effect needed for transitions.
const phase: RollPhase = isRunning
? "searching"
: !settled && results.length > 0
? "rolling"
: "settled";
// Warm the browser cache for every favicon the moment results arrive, so
// each icon is already loaded by the time its row rolls in (~700ms each).
// Without this the network fetch lags the text and rows flash icon-less.
useEffect(() => {
for (const result of results) {
const img = new Image();
img.src = faviconUrl(getDomain(result.url));
}
}, [results]);
// Advance the roll, then settle after the last site has had its moment.
// setState only fires inside the timeout callback, never synchronously.
useEffect(() => {
if (phase !== "rolling") return;
const isLast = rollIndex >= results.length - 1;
const timer = setTimeout(
() => (isLast ? setSettled(true) : setRollIndex((i) => i + 1)),
ROLL_INTERVAL_MS,
);
return () => clearTimeout(timer);
}, [phase, rollIndex, results.length]);
// Build the content for the compact (collapsed) header line. Each distinct
// value gets a unique key so AnimatePresence runs the slide transition.
let headerKey: string;
let headerContent: React.ReactNode;
if (phase === "searching") {
headerKey = "searching";
headerContent = (
<span className="flex min-w-0 flex-1 items-center gap-2 text-muted-foreground">
<LoaderIcon className="size-4 shrink-0 animate-spin" />
<span className="truncate">Searching the web&hellip;</span>
</span>
);
} else if (phase === "rolling") {
const result = results[rollIndex];
const domain = getDomain(result.url);
headerKey = `roll-${rollIndex}`;
headerContent = (
<span className="flex min-w-0 flex-1 items-center gap-2">
<img src={faviconUrl(domain)} alt="" className="size-4 shrink-0 rounded-sm bg-muted/60" />
<span className="truncate">
<span className="text-muted-foreground">{domain}</span>
<span className="text-muted-foreground/50"> &middot; </span>
<span>{result.title}</span>
</span>
</span>
);
} else {
headerKey = "settled";
const stack = domains.slice(0, MAX_STACK);
// Chip count matches the "and N others" in the text (total minus the 2
// named domains), shown only when there are sites beyond the stack.
const overflow = domains.length > MAX_STACK ? domains.length - 2 : 0;
headerContent = (
<span className="flex min-w-0 flex-1 items-center gap-2.5">
{domains.length > 0 ? (
<span className="flex shrink-0 items-center">
{stack.map((domain, i) => (
<img
key={domain}
src={faviconUrl(domain)}
alt=""
className="size-5 rounded-full bg-muted object-cover -ml-[5px] first:ml-0"
style={{ zIndex: stack.length - i }}
/>
))}
{overflow > 0 && (
<span className="ml-0.5 flex size-5 shrink-0 items-center justify-center rounded-full bg-foreground/10 dark:bg-muted text-[10px] font-medium text-muted-foreground">
+{overflow}
</span>
)}
</span>
) : (
<GlobeIcon className="size-4 shrink-0 text-muted-foreground" />
)}
<span className="truncate text-sm">
{domains.length > 0 ? buildSearchedSummary(domains) : title}
</span>
</span>
);
}
return (
<Collapsible
open={open}
onOpenChange={setOpen}
className="not-prose mb-4 w-full rounded-[28px] border bg-[var(--card-surface)] transition-colors duration-150 ease-out hover:border-foreground/30"
>
<CollapsibleTrigger className="flex w-full cursor-pointer items-center justify-between gap-3 px-4 py-2.5">
{/* Rolling header: clipped, fixed height so sliding lines stay contained */}
<div className="relative min-w-0 flex-1 overflow-hidden" style={{ height: "1.5rem" }}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={headerKey}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.18, ease: "easeOut" }}
className="absolute inset-0 flex items-center text-left font-medium text-sm"
>
{headerContent}
</motion.span>
</AnimatePresence>
</div>
<div className="flex shrink-0 items-center gap-2">
{phase === "settled" && domains.length > 0 && (
<span className="whitespace-nowrap text-xs text-muted-foreground">
{domains.length} source{domains.length !== 1 ? "s" : ""}
</span>
)}
<ChevronDownIcon className={cn("size-4 text-muted-foreground transition-transform", open && "rotate-180")} />
</div>
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_0.09s_ease-out] data-[state=closed]:animate-[collapsible-up_0.08s_ease-in]">
<div className="px-4 pb-3 space-y-3">
{/* Query */}
<div className="flex items-center gap-2 text-sm text-muted-foreground min-w-0">
<GlobeIcon className="size-3.5 shrink-0" />
<span className="truncate">{query}</span>
</div>
{/* Results list */}
@ -73,7 +255,7 @@ export function WebSearchResult({ query, results, status, title = "Searched the
>
<div className="flex items-center gap-2 min-w-0">
<img
src={`https://www.google.com/s2/favicons?domain=${domain}&sz=16`}
src={faviconUrl(domain)}
alt=""
className="size-4 shrink-0"
/>
@ -88,20 +270,13 @@ export function WebSearchResult({ query, results, status, title = "Searched the
</div>
)}
{/* Status */}
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
{isRunning ? (
<>
<LoaderIcon className="size-3.5 animate-spin" />
<span>Searching...</span>
</>
) : (
<>
<CheckCircleIcon className="size-3.5 text-green-600" />
<span>Done</span>
</>
)}
</div>
{/* Status — only while the search is still running. */}
{isRunning && (
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<LoaderIcon className="size-3.5 animate-spin" />
<span>Searching...</span>
</div>
)}
</div>
</CollapsibleContent>
</Collapsible>

View file

@ -1237,6 +1237,8 @@ function TaskDetail({
const [confirmingDelete, setConfirmingDelete] = useState(false)
const [sidebarOpen, setSidebarOpen] = useState(true)
const [outputRefreshKey, setOutputRefreshKey] = useState(0)
// Whether we've already chosen the initial sidebar state for this task.
const sidebarInitialized = useRef(false)
const agentStatus = useBackgroundTaskAgentStatus()
const liveStatus = agentStatus.get(slug)
@ -1252,6 +1254,23 @@ function TaskDetail({
if (result.success && result.task) {
setTask(result.task)
setDraft(result.task)
// On first open, collapse the details sidebar when the agent
// already has output — let the user read it without chrome.
// Resolved before `loading` clears so the sidebar never flashes.
if (!sidebarInitialized.current) {
sidebarInitialized.current = true
try {
const out = await window.ipc.invoke('workspace:readFile', {
path: `bg-tasks/${slug}/index.md`,
})
const body = (out.data ?? '').trim()
if (body && body !== `# ${result.task.name}`) {
setSidebarOpen(false)
}
} catch {
// No output file yet — keep the sidebar open.
}
}
}
} finally {
setLoading(false)

View file

@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import {
ArrowUp,
@ -10,24 +10,34 @@ import {
FileSpreadsheet,
FileText,
FileVideo,
FolderCheck,
FolderClock,
FolderCog,
FolderOpen,
Globe,
Headphones,
ImagePlus,
LoaderIcon,
Mic,
MoreHorizontal,
Plus,
ShieldCheck,
Square,
Terminal,
X,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
@ -59,6 +69,12 @@ export type StagedAttachment = {
}
const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 // 10MB
const MAX_VISIBLE_RECENT_WORK_DIRS = 3
const MAX_STORED_RECENT_WORK_DIRS = 8
// Stored in the workspace (~/.rowboat/config) so it travels with the workspace and
// stays consistent with the other config/*.json files (e.g. coding-agents.json).
const RECENT_WORK_DIRS_CONFIG_PATH = 'config/recent-work-dirs.json'
const RECENT_WORK_DIRS_CHANGED_EVENT = 'rowboat-chat-recent-work-dirs-changed'
const providerDisplayNames: Record<string, string> = {
@ -79,11 +95,18 @@ interface ConfiguredModel {
model: string
}
type RecentWorkDir = {
path: string
lastUsedAt: number
}
export interface SelectedModel {
provider: string
model: string
}
export type PermissionMode = 'manual' | 'auto'
function getSelectedModelDisplayName(model: string) {
return model.split('/').pop() || model
}
@ -107,8 +130,86 @@ function getAttachmentIcon(kind: AttachmentIconKind) {
}
}
function normalizeRecentWorkDir(value: unknown): RecentWorkDir | null {
if (typeof value === 'string') {
const path = value.trim()
return path ? { path, lastUsedAt: 0 } : null
}
if (!value || typeof value !== 'object') return null
const entry = value as Record<string, unknown>
const path = typeof entry.path === 'string' ? entry.path.trim() : ''
const lastUsedAt = typeof entry.lastUsedAt === 'number' && Number.isFinite(entry.lastUsedAt)
? entry.lastUsedAt
: 0
return path ? { path, lastUsedAt } : null
}
async function readRecentWorkDirs(): Promise<RecentWorkDir[]> {
try {
const result = await window.ipc.invoke('workspace:readFile', { path: RECENT_WORK_DIRS_CONFIG_PATH })
const parsed = JSON.parse(result.data)
if (!Array.isArray(parsed)) return []
const seen = new Set<string>()
const dirs: RecentWorkDir[] = []
for (const value of parsed) {
const entry = normalizeRecentWorkDir(value)
if (!entry || seen.has(entry.path)) continue
seen.add(entry.path)
dirs.push(entry)
if (dirs.length >= MAX_STORED_RECENT_WORK_DIRS) break
}
return dirs
} catch {
// File missing or invalid — no recents yet.
return []
}
}
async function writeRecentWorkDirs(dirs: RecentWorkDir[]) {
try {
await window.ipc.invoke('workspace:writeFile', {
path: RECENT_WORK_DIRS_CONFIG_PATH,
data: JSON.stringify(dirs.slice(0, MAX_STORED_RECENT_WORK_DIRS), null, 2),
})
} catch (err) {
console.error('Failed to persist recent work directories', err)
}
// Notify other mounted chat inputs in this window to re-read.
window.dispatchEvent(new CustomEvent(RECENT_WORK_DIRS_CHANGED_EVENT))
}
function formatRecentWorkDirTime(lastUsedAt: number) {
if (!lastUsedAt) return ''
const now = Date.now()
const diffMs = Math.max(0, now - lastUsedAt)
const minute = 60 * 1000
const hour = 60 * minute
const day = 24 * hour
if (diffMs < minute) return 'now'
if (diffMs < hour) return `${Math.max(1, Math.floor(diffMs / minute))}m ago`
if (diffMs < day) return `${Math.floor(diffMs / hour)}h ago`
const used = new Date(lastUsedAt)
const yesterday = new Date(now - day)
if (
used.getFullYear() === yesterday.getFullYear() &&
used.getMonth() === yesterday.getMonth() &&
used.getDate() === yesterday.getDate()
) {
return 'Yesterday'
}
if (diffMs < 7 * day) {
return used.toLocaleDateString(undefined, { weekday: 'short' })
}
return used.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
}
function compactWorkDirPath(path: string) {
return path.replace(/^\/Users\/[^/]+/, '~')
}
interface ChatInputInnerProps {
onSubmit: (message: PromptInputMessage, mentions?: FileMention[], attachments?: StagedAttachment[], searchEnabled?: boolean) => void
onSubmit: (message: PromptInputMessage, mentions?: FileMention[], attachments?: StagedAttachment[], searchEnabled?: boolean, codeMode?: 'claude' | 'codex', permissionMode?: PermissionMode) => void
onStop?: () => void
isProcessing: boolean
isStopping?: boolean
@ -178,11 +279,62 @@ function ChatInputInner({
const [searchEnabled, setSearchEnabled] = useState(false)
const [searchAvailable, setSearchAvailable] = useState(false)
const [isRowboatConnected, setIsRowboatConnected] = useState(false)
const [codingAgent, setCodingAgent] = useState<'claude' | 'codex'>('claude')
const [codeModeEnabled, setCodeModeEnabled] = useState(false)
const [codeModeFeatureEnabled, setCodeModeFeatureEnabled] = useState(false)
const [permissionMode, setPermissionMode] = useState<PermissionMode>('auto')
const [recentWorkDirs, setRecentWorkDirs] = useState<RecentWorkDir[]>([])
// Responsive toolbar: measure real overflow and progressively collapse items
// right→left until everything fits. Stages:
// 1 code→icon · 2 perm→icon · 3 search label hidden · 4 workDir→icon
// 5 code→menu · 6 perm→menu · 7 search→menu · 8 workDir→menu
// Once items move into the "⋯" overflow menu (≥5) no icon is ever hidden.
// overflow-hidden on the left group is the hard guarantee against any overlap.
const toolbarRef = useRef<HTMLDivElement>(null)
const leftGroupRef = useRef<HTMLDivElement>(null)
const lastWidthRef = useRef(0)
const [collapseLevel, setCollapseLevel] = useState(0)
// Re-evaluate from scratch (level 0) whenever the available width changes…
useEffect(() => {
const outer = toolbarRef.current
if (!outer) return
const ro = new ResizeObserver(() => {
const w = outer.clientWidth
if (w !== lastWidthRef.current) {
lastWidthRef.current = w
setCollapseLevel(0)
}
})
ro.observe(outer)
return () => ro.disconnect()
}, [])
// …or when the *set* of items changes (an item appears/disappears, or the model
// name width changes). Deliberately excludes the in-place toggles (searchEnabled,
// permissionMode, codeModeEnabled, codingAgent): those fire from the overflow menu
// for items already inside it, so resetting here would unmount the open menu. The
// no-dep effect below still re-collapses if any toggle happens to widen the row.
useLayoutEffect(() => {
setCollapseLevel(0)
}, [workDir, searchAvailable, codeModeFeatureEnabled, lockedModel, activeModelKey])
// After each render, if the left group still overflows, collapse one more step.
// Runs before paint, so the intermediate (overflowing) state is never visible.
useLayoutEffect(() => {
const el = leftGroupRef.current
if (!el) return
if (el.scrollWidth > el.clientWidth + 1 && collapseLevel < 8) {
setCollapseLevel((l) => Math.min(8, l + 1))
}
})
// When a run exists, freeze the dropdown to the run's resolved model+provider.
useEffect(() => {
if (!runId) {
setLockedModel(null)
setPermissionMode('auto')
return
}
let cancelled = false
@ -191,10 +343,20 @@ function ChatInputInner({
if (run.provider && run.model) {
setLockedModel({ provider: run.provider, model: run.model })
}
setPermissionMode(run.permissionMode ?? 'manual')
}).catch(() => { /* legacy run or fetch failure — leave unlocked */ })
return () => { cancelled = true }
}, [runId])
useEffect(() => {
const syncRecentWorkDirs = () => { void readRecentWorkDirs().then(setRecentWorkDirs) }
syncRecentWorkDirs()
window.addEventListener(RECENT_WORK_DIRS_CHANGED_EVENT, syncRecentWorkDirs)
return () => {
window.removeEventListener(RECENT_WORK_DIRS_CHANGED_EVENT, syncRecentWorkDirs)
}
}, [])
// Check Rowboat sign-in state
useEffect(() => {
window.ipc.invoke('oauth:getState', null).then((result) => {
@ -260,8 +422,90 @@ function ChatInputInner({
return () => window.removeEventListener('models-config-changed', handler)
}, [loadModelConfig])
// Load the global code-mode feature flag (from settings) and stay in sync.
useEffect(() => {
const load = () => {
window.ipc.invoke('codeMode:getConfig', null)
.then((r) => setCodeModeFeatureEnabled(r.enabled))
.catch(() => setCodeModeFeatureEnabled(false))
}
load()
window.addEventListener('code-mode-config-changed', load)
return () => window.removeEventListener('code-mode-config-changed', load)
}, [])
// If the feature is turned off in settings, also turn off any per-conversation chip.
useEffect(() => {
if (!codeModeFeatureEnabled && codeModeEnabled) {
setCodeModeEnabled(false)
}
}, [codeModeFeatureEnabled, codeModeEnabled])
// Cross-platform basename — handles both / and \ separators.
const basename = useCallback((p: string): string => {
const trimmed = p.replace(/[\\/]+$/, '')
const idx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
return idx >= 0 ? trimmed.slice(idx + 1) : trimmed
}, [])
const rememberWorkDir = useCallback(async (dir: string) => {
const trimmed = dir.trim()
if (!trimmed) return
const next = [
{ path: trimmed, lastUsedAt: Date.now() },
...(await readRecentWorkDirs()).filter((item) => item.path !== trimmed),
].slice(0, MAX_STORED_RECENT_WORK_DIRS)
setRecentWorkDirs(next)
await writeRecentWorkDirs(next)
}, [])
// Load coding-agent preference for a given workdir.
// Storage: config/coding-agents.json — { [workDirPath]: 'claude' | 'codex' }
const loadCodingAgentFor = useCallback(async (dir: string | null): Promise<'claude' | 'codex'> => {
if (!dir) return 'claude'
try {
const result = await window.ipc.invoke('workspace:readFile', { path: 'config/coding-agents.json' })
const parsed = JSON.parse(result.data) as Record<string, unknown>
const value = parsed?.[dir]
if (value === 'codex' || value === 'claude') return value
} catch {
/* file missing or invalid — fall through to default */
}
return 'claude'
}, [])
const persistCodingAgent = useCallback(async (dir: string, agent: 'claude' | 'codex') => {
const existing: Record<string, 'claude' | 'codex'> = {}
try {
const result = await window.ipc.invoke('workspace:readFile', { path: 'config/coding-agents.json' })
const parsed = JSON.parse(result.data) as Record<string, unknown>
for (const [k, v] of Object.entries(parsed ?? {})) {
if (v === 'claude' || v === 'codex') existing[k] = v
}
} catch { /* start fresh */ }
existing[dir] = agent
await window.ipc.invoke('workspace:writeFile', {
path: 'config/coding-agents.json',
data: JSON.stringify(existing, null, 2),
})
}, [])
// Work directory is owned per-chat by the parent (App). This component only
// drives the picker dialog and reports changes up via onWorkDirChange.
// drives the picker dialog and reports changes up via onWorkDirChange. Whenever
// the work directory changes, load its persisted coding-agent preference.
useEffect(() => {
let cancelled = false
loadCodingAgentFor(workDir).then((agent) => {
if (!cancelled) setCodingAgent(agent)
})
return () => { cancelled = true }
}, [workDir, loadCodingAgentFor])
useEffect(() => {
if (isActive && workDir) void rememberWorkDir(workDir)
}, [isActive, workDir, rememberWorkDir])
const handleSetWorkDir = useCallback(async () => {
try {
let defaultPath: string | undefined = workDir ?? undefined
@ -282,18 +526,43 @@ function ChatInputInner({
})
if (!chosen) return
onWorkDirChange?.(chosen)
await rememberWorkDir(chosen)
setCodingAgent(await loadCodingAgentFor(chosen))
toast.success(`Work directory set: ${chosen}`)
} catch (err) {
console.error('Failed to set work directory', err)
toast.error('Failed to set work directory')
}
}, [workDir, onWorkDirChange])
}, [workDir, onWorkDirChange, rememberWorkDir, loadCodingAgentFor])
const handleSelectRecentWorkDir = useCallback(async (dir: string) => {
onWorkDirChange?.(dir)
await rememberWorkDir(dir)
setCodingAgent(await loadCodingAgentFor(dir))
toast.success(`Work directory set: ${dir}`)
}, [onWorkDirChange, rememberWorkDir, loadCodingAgentFor])
const handleClearWorkDir = useCallback(() => {
onWorkDirChange?.(null)
setCodingAgent('claude')
toast.success('Work directory cleared')
}, [onWorkDirChange])
const handleToggleCodingAgent = useCallback(async () => {
const next: 'claude' | 'codex' = codingAgent === 'claude' ? 'codex' : 'claude'
setCodingAgent(next)
// Persist only when scoped to a workdir; without one there's nothing to key on.
if (!workDir) return
try {
await persistCodingAgent(workDir, next)
} catch (err) {
console.error('Failed to save coding agent', err)
toast.error('Failed to save coding agent')
// revert on failure
setCodingAgent(codingAgent)
}
}, [workDir, codingAgent, persistCodingAgent])
// Check search tool availability (exa or signed-in via gateway)
useEffect(() => {
const checkSearch = async () => {
@ -378,12 +647,15 @@ function ChatInputInner({
const handleSubmit = useCallback(() => {
if (!canSubmit) return
onSubmit({ text: message.trim(), files: [] }, controller.mentions.mentions, attachments, searchEnabled || undefined)
// codeMode is sticky per conversation — don't reset after send.
const effectiveCodeMode = codeModeEnabled ? codingAgent : undefined
onSubmit({ text: message.trim(), files: [] }, controller.mentions.mentions, attachments, searchEnabled || undefined, effectiveCodeMode, permissionMode)
controller.textInput.clear()
controller.mentions.clearMentions()
setAttachments([])
setSearchEnabled(false)
}, [attachments, canSubmit, controller, message, onSubmit, searchEnabled])
// Web search toggle stays on for the rest of the chat session; the user
// turns it off explicitly. (Not persisted across app restarts.)
}, [attachments, canSubmit, controller, message, onSubmit, searchEnabled, codeModeEnabled, codingAgent, permissionMode, workDir])
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
@ -422,6 +694,12 @@ function ChatInputInner({
}
}, [addFiles, isActive])
const visibleRecentWorkDirs = recentWorkDirs
.filter((entry) => entry.path !== workDir)
.slice(0, MAX_VISIBLE_RECENT_WORK_DIRS)
const currentWorkDirLabel = workDir ? basename(workDir) || workDir : 'Not set'
const currentWorkDirPath = workDir ? compactWorkDirPath(workDir) : ''
return (
<div className="rowboat-chat-input rounded-lg border border-border bg-background shadow-none">
{attachments.length > 0 && (
@ -526,48 +804,138 @@ function ChatInputInner({
className="min-h-6 rounded-none border-0 py-0 shadow-none focus-visible:ring-0"
/>
</div>
<div className="flex items-center gap-2 px-4 pb-3">
<div ref={toolbarRef} className="flex items-center gap-2 px-4 pb-3">
<div ref={leftGroupRef} className="flex min-w-0 items-center gap-2 overflow-hidden">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
aria-label="Add"
>
<Plus className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-56">
<DropdownMenuItem onSelect={() => fileInputRef.current?.click()}>
<ImagePlus className="size-4" />
<span>Add files or photos</span>
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => { void handleSetWorkDir() }}>
<FolderCog className="size-4" />
<span>{workDir ? 'Change work directory' : 'Set work directory'}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{workDir && (
<Tooltip>
<TooltipTrigger asChild>
<div className="group flex h-7 max-w-[180px] shrink-0 items-center rounded-full border border-border bg-muted/40 pl-2.5 pr-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
aria-label="Add"
>
<Plus className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="top">
{workDir ? 'Add files or change work directory' : 'Add files or set work directory'}
</TooltipContent>
</Tooltip>
<DropdownMenuContent align="start" className="w-72 max-w-[calc(100vw-2rem)] p-2">
<div className="rounded-[14px] border border-border/80 bg-background p-1">
<DropdownMenuItem onSelect={() => fileInputRef.current?.click()} className="h-9 rounded-[9px] px-2.5">
<ImagePlus className="size-4" />
<span>Add files or photos</span>
</DropdownMenuItem>
{/* Working directory lives behind a submenu so the main menu stays to two
items. One hover/click away for power users; out of the way otherwise. */}
<DropdownMenuSub>
<DropdownMenuSubTrigger className="h-9 rounded-[9px] px-2.5">
<FolderCog className="size-4" />
<span className="flex min-w-0 flex-1 items-center justify-between gap-3">
<span>Set working directory</span>
<span className="min-w-0 max-w-[110px] truncate text-xs text-muted-foreground">
{currentWorkDirLabel}
</span>
</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-72 max-w-[calc(100vw-2rem)] p-1">
{/* Current selection — shown for context only when one is set. */}
{workDir && (
<div
title={workDir}
className="mb-1 flex items-center gap-2 rounded-[9px] bg-blue-50/80 px-2.5 py-2 text-blue-700 dark:bg-blue-950/30 dark:text-blue-300"
>
<FolderCheck className="size-4 shrink-0 text-blue-600 dark:text-blue-300" />
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate text-sm font-medium">{currentWorkDirLabel}</span>
<span className="truncate text-xs text-blue-700/70 dark:text-blue-300/70">
{currentWorkDirPath}
</span>
</span>
</div>
)}
{/* Primary action: choose when unset, change when set. Always on top. */}
<DropdownMenuItem
onSelect={() => { void handleSetWorkDir() }}
className="h-9 rounded-[9px] px-2.5"
>
<FolderOpen className="size-4" />
<span>{workDir ? 'Change folder…' : 'Choose a folder…'}</span>
</DropdownMenuItem>
{visibleRecentWorkDirs.length > 0 && (
<>
<div className="px-2.5 pb-1 pt-2 text-[10.5px] font-semibold uppercase tracking-wider text-muted-foreground">
Recent
</div>
{visibleRecentWorkDirs.map((entry) => {
const name = basename(entry.path) || entry.path
const when = formatRecentWorkDirTime(entry.lastUsedAt)
return (
<DropdownMenuItem
key={entry.path}
title={entry.path}
onSelect={() => { void handleSelectRecentWorkDir(entry.path) }}
className="h-8 rounded-[9px] px-2.5"
>
<FolderClock className="size-4" />
<span className="min-w-0 flex-1 truncate">{name}</span>
{when && <span className="shrink-0 text-xs text-muted-foreground">{when}</span>}
</DropdownMenuItem>
)
})}
</>
)}
{/* Clear — only meaningful once a directory is set. Kept at the bottom. */}
{workDir && (
<>
<div className="my-1 h-px bg-border/60" />
<DropdownMenuItem
onSelect={handleClearWorkDir}
className="h-8 rounded-[9px] px-2.5 text-red-600 focus:bg-red-50 focus:text-red-600 dark:text-red-400 dark:focus:bg-red-950/30"
>
<X className="size-4" />
<span>Clear folder</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuSubContent>
</DropdownMenuSub>
</div>
</DropdownMenuContent>
</DropdownMenu>
{workDir && collapseLevel < 8 && (
<Tooltip>
<TooltipTrigger asChild>
{/* Level 4: collapse to a square icon */}
<div className={cn(
"group flex h-7 shrink-0 items-center rounded-full border border-border bg-muted/40 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
collapseLevel >= 4 ? "w-7 justify-center" : "max-w-[180px] pl-2.5 pr-2"
)}>
<button
type="button"
onClick={handleSetWorkDir}
className="flex min-w-0 items-center gap-1.5"
>
<FolderCog className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">{workDir.split('/').pop() || workDir}</span>
</button>
<button
type="button"
onClick={handleClearWorkDir}
aria-label="Remove work directory"
className="flex h-3.5 w-0 shrink-0 items-center justify-center overflow-hidden opacity-0 transition-all duration-150 ease-out hover:text-red-500 group-hover:ml-1 group-hover:w-3.5 group-hover:opacity-100"
>
<X className="h-3.5 w-3.5 shrink-0" />
{collapseLevel < 4 && <span className="truncate">{basename(workDir) || workDir}</span>}
</button>
{collapseLevel < 4 && (
<button
type="button"
onClick={handleClearWorkDir}
aria-label="Remove work directory"
className="flex h-3.5 w-0 shrink-0 items-center justify-center overflow-hidden opacity-0 transition-all duration-150 ease-out hover:text-red-500 group-hover:ml-1 group-hover:w-3.5 group-hover:opacity-100"
>
<X className="h-3.5 w-3.5 shrink-0" />
</button>
)}
</div>
</TooltipTrigger>
<TooltipContent side="top">
@ -575,7 +943,7 @@ function ChatInputInner({
</TooltipContent>
</Tooltip>
)}
{searchAvailable && (
{searchAvailable && collapseLevel < 7 && (
<button
type="button"
onClick={() => setSearchEnabled((v) => !v)}
@ -589,35 +957,191 @@ function ChatInputInner({
)}
>
<Globe className="h-4 w-4 shrink-0" />
<span
className={cn(
'overflow-hidden whitespace-nowrap text-xs font-medium transition-all duration-150 ease-out',
searchEnabled ? 'ml-1.5 max-w-[60px] opacity-100' : 'max-w-0 opacity-0'
)}
>
Search
</span>
{searchEnabled && collapseLevel < 3 && (
<span className="ml-1.5 whitespace-nowrap text-xs font-medium">
Search
</span>
)}
</button>
)}
{collapseLevel < 6 && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => {
if (runId) return
setPermissionMode((mode) => mode === 'auto' ? 'manual' : 'auto')
}}
disabled={Boolean(runId)}
className={cn(
"flex h-7 shrink-0 items-center gap-1.5 rounded-full text-xs font-medium transition-colors",
collapseLevel >= 2 ? "w-7 justify-center" : "px-2.5",
permissionMode === 'auto'
? "bg-secondary text-foreground hover:bg-secondary/70"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
runId && "cursor-not-allowed opacity-70 hover:bg-secondary"
)}
aria-label="Permission mode"
>
<ShieldCheck className="h-3.5 w-3.5 shrink-0" />
{collapseLevel < 2 && <span>{permissionMode === 'auto' ? 'Auto' : 'Manual'}</span>}
</button>
</TooltipTrigger>
<TooltipContent side="top">
{runId
? `Permission mode is fixed for this run: ${permissionMode === 'auto' ? 'Auto' : 'Manual'}`
: permissionMode === 'auto'
? 'Auto-permission on — click for manual approval prompts'
: 'Manual approval prompts — click for auto-permission'}
</TooltipContent>
</Tooltip>
)}
{codeModeFeatureEnabled && collapseLevel < 5 && (codeModeEnabled ? (
collapseLevel >= 1 ? (
/* Level 1: collapse the pill to a single icon */
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setCodeModeEnabled(false)}
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-secondary text-foreground transition-colors hover:bg-secondary/70"
>
<Terminal className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top">Code mode on ({codingAgent === 'claude' ? 'Claude Code' : 'Codex'}) click to disable</TooltipContent>
</Tooltip>
) : (
<div className="flex h-7 shrink-0 items-center rounded-full bg-secondary text-xs font-medium text-foreground">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setCodeModeEnabled(false)}
className="flex h-full items-center gap-1.5 rounded-l-full pl-2.5 pr-2 transition-colors hover:bg-secondary/70"
>
<Terminal className="h-3.5 w-3.5" />
<span>Code</span>
</button>
</TooltipTrigger>
<TooltipContent side="top">Code mode on click to disable</TooltipContent>
</Tooltip>
<span className="text-foreground/30">·</span>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={handleToggleCodingAgent}
className="flex h-full items-center rounded-r-full pl-2 pr-2.5 transition-colors hover:bg-secondary/70"
>
<span>{codingAgent === 'claude' ? 'Claude' : 'Codex'}</span>
</button>
</TooltipTrigger>
<TooltipContent side="top">
Coding agent: {codingAgent === 'claude' ? 'Claude Code' : 'Codex'} click to swap
</TooltipContent>
</Tooltip>
</div>
)
) : (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setCodeModeEnabled(true)}
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
aria-label="Code mode"
>
<Terminal className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent side="top">Use a coding agent (Claude Code or Codex)</TooltipContent>
</Tooltip>
))}
</div>
{collapseLevel >= 5 && (
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label="More options"
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<MoreHorizontal className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="top">More options</TooltipContent>
</Tooltip>
<DropdownMenuContent align="start" side="top" className="min-w-52">
{workDir && collapseLevel >= 8 && (
<DropdownMenuItem onSelect={() => { void handleSetWorkDir() }}>
<FolderCog className="size-4" />
<span className="min-w-0 flex-1 truncate">{basename(workDir) || workDir}</span>
</DropdownMenuItem>
)}
{searchAvailable && collapseLevel >= 7 && (
<DropdownMenuCheckboxItem
checked={searchEnabled}
onSelect={(e) => e.preventDefault()}
onCheckedChange={(c) => setSearchEnabled(Boolean(c))}
>
Web search
</DropdownMenuCheckboxItem>
)}
{collapseLevel >= 6 && (
<DropdownMenuCheckboxItem
checked={permissionMode === 'auto'}
disabled={Boolean(runId)}
onSelect={(e) => e.preventDefault()}
onCheckedChange={(c) => setPermissionMode(c ? 'auto' : 'manual')}
>
Auto-approve actions
</DropdownMenuCheckboxItem>
)}
{codeModeFeatureEnabled && collapseLevel >= 5 && (
<>
<DropdownMenuCheckboxItem
checked={codeModeEnabled}
onSelect={(e) => e.preventDefault()}
onCheckedChange={(c) => setCodeModeEnabled(Boolean(c))}
>
Code mode
</DropdownMenuCheckboxItem>
{codeModeEnabled && (
<DropdownMenuItem onSelect={(e) => { e.preventDefault(); handleToggleCodingAgent() }}>
<Terminal className="size-4" />
<span className="min-w-0 flex-1">Coding agent</span>
<span className="text-xs text-muted-foreground">{codingAgent === 'claude' ? 'Claude' : 'Codex'}</span>
</DropdownMenuItem>
)}
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
<div className="flex-1" />
{lockedModel ? (
<span
className="flex h-7 shrink-0 items-center gap-1 rounded-full px-2 text-xs text-muted-foreground"
className="flex h-7 min-w-0 items-center gap-1 rounded-full px-2 text-xs text-muted-foreground"
title={`${providerDisplayNames[lockedModel.provider] || lockedModel.provider} — fixed for this chat`}
>
<span className="max-w-[150px] truncate">{getSelectedModelDisplayName(lockedModel.model)}</span>
<span className="min-w-0 truncate">{getSelectedModelDisplayName(lockedModel.model)}</span>
</span>
) : configuredModels.length > 0 ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-7 shrink-0 items-center gap-1 rounded-full px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
className="flex h-7 min-w-0 items-center gap-1 rounded-full px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<span className="max-w-[150px] truncate">
<span className="min-w-0 truncate">
{getSelectedModelDisplayName(configuredModels.find((m) => `${m.provider}/${m.model}` === activeModelKey)?.model || configuredModels[0]?.model || 'Model')}
</span>
<ChevronDown className="h-3 w-3" />
<ChevronDown className="h-3 w-3 shrink-0" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
@ -759,7 +1283,7 @@ export interface ChatInputWithMentionsProps {
knowledgeFiles: string[]
recentFiles: string[]
visibleFiles: string[]
onSubmit: (message: PromptInputMessage, mentions?: FileMention[], attachments?: StagedAttachment[]) => void
onSubmit: (message: PromptInputMessage, mentions?: FileMention[], attachments?: StagedAttachment[], searchEnabled?: boolean, codeMode?: 'claude' | 'codex', permissionMode?: PermissionMode) => void
onStop?: () => void
isProcessing: boolean
isStopping?: boolean

View file

@ -1,11 +1,18 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ArrowRight, X } from 'lucide-react'
import { ArrowLeft, ArrowRight, Bug, MoreHorizontal } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { ChatHeader } from '@/components/chat-header'
import { ChatEmptyState } from '@/components/chat-empty-state'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
Conversation,
ConversationContent,
@ -21,6 +28,7 @@ import { Tool, ToolContent, ToolGroupComponent, ToolHeader, ToolTabbedContent }
import { WebSearchResult } from '@/components/ai-elements/web-search-result'
import { ComposioConnectCard } from '@/components/ai-elements/composio-connect-card'
import { PermissionRequest } from '@/components/ai-elements/permission-request'
import { AutoPermissionDecision } from '@/components/ai-elements/auto-permission-decision'
import { TerminalOutput } from '@/components/terminal-output'
import { AskHumanRequest } from '@/components/ai-elements/ask-human-request'
import { type PromptInputMessage, type FileMention } from '@/components/ai-elements/prompt-input'
@ -29,10 +37,11 @@ import { MarkdownPreOverride } from '@/components/ai-elements/markdown-code-over
import { defaultRemarkPlugins } from 'streamdown'
import remarkBreaks from 'remark-breaks'
import { type ChatTab } from '@/components/tab-bar'
import { ChatInputWithMentions, type StagedAttachment, type SelectedModel } from '@/components/chat-input-with-mentions'
import { ChatInputWithMentions, type PermissionMode, type StagedAttachment, type SelectedModel } from '@/components/chat-input-with-mentions'
import { ChatMessageAttachments } from '@/components/chat-message-attachments'
import { useSidebar } from '@/components/ui/sidebar'
import { wikiLabel } from '@/lib/wiki-links'
import type { ChatPaneSize } from '@/contexts/theme-context'
import {
type ChatViewportAnchorState,
type ChatTabViewState,
@ -117,6 +126,9 @@ interface ChatSidebarProps {
defaultWidth?: number
isOpen?: boolean
isMaximized?: boolean
placement?: 'middle' | 'right'
paneSize?: ChatPaneSize
className?: string
chatTabs: ChatTab[]
activeChatTabId: string
getChatTabTitle: (tab: ChatTab) => string
@ -125,7 +137,6 @@ interface ChatSidebarProps {
onSelectRun?: (runId: string) => void
onOpenChatHistory?: () => void
onOpenFullScreen?: () => void
onCloseChat?: () => void
conversation: ConversationItem[]
currentAssistantMessage: string
chatTabStates?: Record<string, ChatTabViewState>
@ -133,7 +144,7 @@ interface ChatSidebarProps {
isProcessing: boolean
isStopping?: boolean
onStop?: () => void
onSubmit: (message: PromptInputMessage, mentions?: FileMention[], attachments?: StagedAttachment[]) => void
onSubmit: (message: PromptInputMessage, mentions?: FileMention[], attachments?: StagedAttachment[], searchEnabled?: boolean, codeMode?: 'claude' | 'codex', permissionMode?: PermissionMode) => void
knowledgeFiles?: string[]
recentFiles?: string[]
visibleFiles?: string[]
@ -148,6 +159,7 @@ interface ChatSidebarProps {
pendingAskHumanRequests?: ChatTabViewState['pendingAskHumanRequests']
allPermissionRequests?: ChatTabViewState['allPermissionRequests']
permissionResponses?: ChatTabViewState['permissionResponses']
autoPermissionDecisions?: ChatTabViewState['autoPermissionDecisions']
onPermissionResponse?: (toolCallId: string, subflow: string[], response: PermissionResponse, scope?: 'once' | 'session' | 'always') => void
onAskHumanResponse?: (toolCallId: string, subflow: string[], response: string) => void
isToolOpenForTab?: (tabId: string, toolId: string) => boolean
@ -175,6 +187,9 @@ export function ChatSidebar({
defaultWidth = DEFAULT_WIDTH,
isOpen = true,
isMaximized = false,
placement = 'right',
paneSize = 'chat-smaller',
className,
chatTabs,
activeChatTabId,
getChatTabTitle,
@ -183,7 +198,6 @@ export function ChatSidebar({
onSelectRun,
onOpenChatHistory,
onOpenFullScreen,
onCloseChat,
conversation,
currentAssistantMessage,
chatTabStates = {},
@ -206,6 +220,7 @@ export function ChatSidebar({
pendingAskHumanRequests = new Map(),
allPermissionRequests = new Map(),
permissionResponses = new Map(),
autoPermissionDecisions = new Map(),
onPermissionResponse,
onAskHumanResponse,
isToolOpenForTab,
@ -238,6 +253,8 @@ export function ChatSidebar({
const startWidthRef = useRef(0)
const prevIsMaximizedRef = useRef(isMaximized)
const justToggledMaximize = prevIsMaximizedRef.current !== isMaximized
const isMiddlePlacement = placement === 'middle'
const isResizable = paneSize === 'chat-smaller'
const getMaxAllowedWidth = useCallback(() => {
if (typeof window === 'undefined') return MAX_WIDTH
@ -298,7 +315,9 @@ export function ChatSidebar({
setIsResizing(true)
const handleMouseMove = (event: MouseEvent) => {
const delta = startXRef.current - event.clientX
const delta = isMiddlePlacement
? event.clientX - startXRef.current
: startXRef.current - event.clientX
const maxAllowedWidth = getMaxAllowedWidth()
setWidth(clampPaneWidth(startWidthRef.current + delta, maxAllowedWidth))
}
@ -311,7 +330,7 @@ export function ChatSidebar({
document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp)
}, [width, getMaxAllowedWidth])
}, [width, getMaxAllowedWidth, isMiddlePlacement])
const activeTabState = useMemo<ChatTabViewState>(() => ({
runId: runId ?? null,
@ -320,6 +339,7 @@ export function ChatSidebar({
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
autoPermissionDecisions,
}), [
runId,
conversation,
@ -327,14 +347,38 @@ export function ChatSidebar({
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
autoPermissionDecisions,
])
const emptyTabState = useMemo<ChatTabViewState>(() => createEmptyChatTabViewState(), [])
const getTabState = useCallback((tabId: string): ChatTabViewState => {
if (tabId === activeChatTabId) return activeTabState
return chatTabStates[tabId] ?? emptyTabState
}, [activeChatTabId, activeTabState, chatTabStates, emptyTabState])
const activeRunId = activeTabState.runId
const handleDownloadChatLog = useCallback(async () => {
if (!activeRunId) {
toast.error('No chat log available yet')
return
}
const renderConversationItem = (item: ConversationItem, tabId: string) => {
try {
const result = await window.ipc.invoke('runs:downloadLog', { runId: activeRunId })
if (result.success) {
toast.success('Chat log saved')
} else if (result.error) {
toast.error(result.error)
}
} catch (err) {
console.error('Download chat log failed:', err)
toast.error('Failed to download chat log')
}
}, [activeRunId])
const renderConversationItem = (
item: ConversationItem,
tabId: string,
options?: { autoPermissionDetail?: { decision: 'allow'; reason: string } },
) => {
if (isChatMessage(item)) {
if (item.role === 'user') {
if (item.attachments && item.attachments.length > 0) {
@ -427,6 +471,7 @@ export function ChatSidebar({
key={item.id}
open={isToolOpenForTab?.(tabId, item.id) ?? false}
onOpenChange={(open) => onToolOpenChangeForTab?.(tabId, item.id, open)}
autoPermissionDetail={options?.autoPermissionDetail}
>
<ToolHeader title={toolTitle} type={`tool-${item.name}`} state={toToolState(item.status)} />
<ToolContent>
@ -467,8 +512,11 @@ export function ChatSidebar({
// not add extra width to the right and overflow the app viewport.
return { width: 0, flex: '1 1 auto' }
}
if (paneSize === 'chat-equal' || paneSize === 'chat-bigger') {
return { width: 0, flex: '1 1 0' }
}
return { width, flex: '0 0 auto' }
}, [isOpen, isMaximized, width])
}, [isOpen, isMaximized, paneSize, width])
return (
<div
@ -477,16 +525,19 @@ export function ChatSidebar({
onMouseDownCapture={onActivate}
onFocusCapture={onActivate}
className={cn(
'relative flex min-w-0 flex-col overflow-hidden border-l border-border bg-background',
!isResizing && !justToggledMaximize && 'transition-[width] duration-200 ease-linear'
'relative flex min-w-0 flex-col overflow-hidden bg-background',
isMiddlePlacement ? 'border-r border-border' : 'border-l border-border',
!isResizing && !justToggledMaximize && 'transition-[width] duration-200 ease-linear',
className
)}
style={paneStyle}
>
{!isMaximized && (
{!isMaximized && isResizable && (
<div
onMouseDown={handleMouseDown}
className={cn(
'absolute inset-y-0 left-0 z-20 w-4 -translate-x-1/2 cursor-col-resize',
'absolute inset-y-0 z-20 w-4 cursor-col-resize',
isMiddlePlacement ? 'right-0 translate-x-1/2' : 'left-0 -translate-x-1/2',
'after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] after:transition-colors',
'hover:after:bg-sidebar-border',
isResizing && 'after:bg-primary'
@ -515,40 +566,51 @@ export function ChatSidebar({
onSelectRun={onSelectRun}
onOpenChatHistory={onOpenChatHistory}
/>
{isMaximized ? (
onOpenFullScreen && (
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={onOpenFullScreen}
className="titlebar-no-drag my-1 mr-2 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
aria-label="Dock chat to side pane"
className="titlebar-no-drag my-1 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
aria-label="Chat options"
>
<ArrowRight className="size-5" />
<MoreHorizontal className="size-5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Dock to side pane</TooltipContent>
</Tooltip>
)
) : (
onCloseChat && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={onCloseChat}
className="titlebar-no-drag my-1 mr-2 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
aria-label="Close chat"
>
<X className="size-5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Close chat</TooltipContent>
</Tooltip>
)
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom">Chat options</TooltipContent>
</Tooltip>
<DropdownMenuContent align="end" className="min-w-48">
<DropdownMenuItem
disabled={!activeRunId}
onSelect={() => {
void handleDownloadChatLog()
}}
>
<Bug className="size-4" />
Download chat log
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{onOpenFullScreen && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={onOpenFullScreen}
className="titlebar-no-drag my-1 mr-2 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
aria-label={isMaximized ? 'Dock chat to side pane' : 'Expand chat'}
>
{isMaximized
? (isMiddlePlacement ? <ArrowLeft className="size-5" /> : <ArrowRight className="size-5" />)
: (isMiddlePlacement ? <ArrowRight className="size-5" /> : <ArrowLeft className="size-5" />)}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">{isMaximized ? 'Dock to side pane' : 'Expand chat'}</TooltipContent>
</Tooltip>
)}
</header>
@ -593,7 +655,7 @@ export function ChatSidebar({
<>
{groupConversationItems(
tabState.conversation,
(id) => !!tabState.allPermissionRequests.get(id)
(id) => !!tabState.allPermissionRequests.get(id) || !!tabState.autoPermissionDecisions.get(id)
).map((item) => {
if (isToolGroup(item)) {
return (
@ -605,23 +667,44 @@ export function ChatSidebar({
/>
)
}
const rendered = renderConversationItem(item, tab.id)
if (isToolCall(item) && onPermissionResponse) {
const autoDecision = isToolCall(item)
? tabState.autoPermissionDecisions.get(item.id)
: undefined
const rendered = renderConversationItem(
item,
tab.id,
autoDecision?.decision === 'allow'
? { autoPermissionDetail: { decision: 'allow', reason: autoDecision.reason } }
: undefined,
)
if (isToolCall(item)) {
const deniedAutoDecision = autoDecision?.decision === 'deny' ? autoDecision : null
const permRequest = tabState.allPermissionRequests.get(item.id)
if (permRequest) {
if (deniedAutoDecision || (permRequest && onPermissionResponse)) {
const response = tabState.permissionResponses.get(item.id) || null
return (
<React.Fragment key={item.id}>
{deniedAutoDecision && (
<AutoPermissionDecision
toolCall={deniedAutoDecision.toolCall}
permission={deniedAutoDecision.permission}
decision={deniedAutoDecision.decision}
reason={deniedAutoDecision.reason}
/>
)}
{permRequest && onPermissionResponse && (
<PermissionRequest
toolCall={permRequest.toolCall}
permission={permRequest.permission}
onApprove={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve')}
onApproveSession={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'session')}
onApproveAlways={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'always')}
onDeny={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')}
isProcessing={isActive && isProcessing}
response={response}
/>
)}
{rendered}
<PermissionRequest
toolCall={permRequest.toolCall}
onApprove={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve')}
onApproveSession={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'session')}
onApproveAlways={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'always')}
onDeny={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')}
isProcessing={isActive && isProcessing}
response={response}
/>
</React.Fragment>
)
}

View file

@ -0,0 +1,253 @@
import { useMemo, useState } from 'react'
import {
CheckCircle2,
Circle,
CircleDot,
Eye,
FileText,
Loader,
Pencil,
Search,
ShieldQuestion,
Terminal,
Trash2,
Wrench,
} from 'lucide-react'
import type { CodeRunEvent, PermissionAsk, PermissionDecision } from '@x/shared/src/code-mode.js'
import { cn } from '@/lib/utils'
import { Tool, ToolContent, ToolHeader } from '@/components/ai-elements/tool'
import { toToolState, type ToolCall } from '@/lib/chat-conversation'
// ── Timeline reduction ──────────────────────────────────────────────
// The raw ACP stream is a flat list of events; collapse it into ordered rows,
// folding tool_call + tool_call_update (by id) and the latest plan in place.
type TextRow = { kind: 'text'; id: string; text: string }
type ToolRow = { kind: 'tool'; id: string; title?: string; toolKind?: string; status?: string; diffs: string[] }
type PlanRow = { kind: 'plan'; id: string; entries: { content: string; status?: string }[] }
type PermRow = { kind: 'perm'; id: string; title: string; decision: string }
type Row = TextRow | ToolRow | PlanRow | PermRow
function reduceEvents(events: CodeRunEvent[]): Row[] {
const rows: Row[] = []
const toolIdx = new Map<string, number>()
let planIdx = -1
events.forEach((e, i) => {
switch (e.type) {
case 'message': {
if (e.role !== 'agent' || !e.text) return
const last = rows[rows.length - 1]
if (last && last.kind === 'text') last.text += e.text
else rows.push({ kind: 'text', id: `t${i}`, text: e.text })
break
}
case 'tool_call': {
const id = e.id ?? `tc${i}`
const at = toolIdx.get(id)
if (at != null) {
const r = rows[at] as ToolRow
r.title = e.title ?? r.title
r.toolKind = e.kind ?? r.toolKind
r.status = e.status ?? r.status
} else {
toolIdx.set(id, rows.length)
rows.push({ kind: 'tool', id, title: e.title, toolKind: e.kind, status: e.status, diffs: [] })
}
break
}
case 'tool_call_update': {
const id = e.id ?? `tu${i}`
let at = toolIdx.get(id)
if (at == null) {
at = rows.length
toolIdx.set(id, at)
rows.push({ kind: 'tool', id, diffs: [] })
}
const r = rows[at] as ToolRow
if (e.status) r.status = e.status
for (const d of e.diffs) if (!r.diffs.includes(d)) r.diffs.push(d)
break
}
case 'plan': {
if (planIdx >= 0) (rows[planIdx] as PlanRow).entries = e.entries
else {
planIdx = rows.length
rows.push({ kind: 'plan', id: 'plan', entries: e.entries })
}
break
}
case 'permission':
rows.push({ kind: 'perm', id: `p${i}`, title: e.ask.title, decision: e.decision })
break
default:
break
}
})
return rows
}
function toolKindIcon(kind?: string) {
switch (kind) {
case 'read': return <Eye className="size-3.5 shrink-0 text-muted-foreground" />
case 'edit': return <Pencil className="size-3.5 shrink-0 text-muted-foreground" />
case 'delete': return <Trash2 className="size-3.5 shrink-0 text-muted-foreground" />
case 'search': return <Search className="size-3.5 shrink-0 text-muted-foreground" />
case 'execute': return <Terminal className="size-3.5 shrink-0 text-muted-foreground" />
case 'fetch': return <FileText className="size-3.5 shrink-0 text-muted-foreground" />
default: return <Wrench className="size-3.5 shrink-0 text-muted-foreground" />
}
}
function planMarker(status?: string) {
if (status === 'completed') return <CheckCircle2 className="size-3.5 shrink-0 text-green-600" />
if (status === 'in_progress') return <CircleDot className="size-3.5 shrink-0 text-blue-500" />
return <Circle className="size-3.5 shrink-0 text-muted-foreground" />
}
const basename = (p: string) => p.split(/[\\/]/).pop() || p
function CodingRunTimeline({ events }: { events: CodeRunEvent[] }) {
const rows = useMemo(() => reduceEvents(events), [events])
if (rows.length === 0) {
return <div className="px-4 py-3 text-xs text-muted-foreground">Starting the agent</div>
}
return (
<div className="flex flex-col gap-2 px-4 py-3">
{rows.map((row) => {
if (row.kind === 'text') {
return (
<p key={row.id} className="whitespace-pre-wrap text-sm leading-relaxed text-foreground/90">
{row.text}
</p>
)
}
if (row.kind === 'tool') {
const running = row.status !== 'completed' && row.status !== 'failed'
return (
<div key={row.id} className="flex flex-col gap-1">
<div className="flex items-center gap-2 text-sm">
{running
? <Loader className="size-3.5 shrink-0 animate-spin text-muted-foreground" />
: <CheckCircle2 className="size-3.5 shrink-0 text-green-600" />}
{toolKindIcon(row.toolKind)}
<span className="truncate text-foreground/90">{row.title ?? row.toolKind ?? 'Tool call'}</span>
</div>
{row.diffs.length > 0 && (
<div className="ml-7 flex flex-col gap-0.5">
{row.diffs.map((d) => (
<span key={d} className="truncate font-mono text-xs text-muted-foreground" title={d}>
{basename(d)}
</span>
))}
</div>
)}
</div>
)
}
if (row.kind === 'plan') {
return (
<div key={row.id} className="flex flex-col gap-1 rounded-lg border bg-muted/30 p-2">
{row.entries.map((entry, idx) => (
<div key={idx} className="flex items-center gap-2 text-sm text-foreground/90">
{planMarker(entry.status)}
<span className={cn('truncate', entry.status === 'completed' && 'text-muted-foreground line-through')}>
{entry.content}
</span>
</div>
))}
</div>
)
}
// resolved permission
const denied = row.decision === 'reject' || row.decision === 'cancelled'
return (
<div key={row.id} className={cn('flex items-center gap-2 text-xs', denied ? 'text-red-600' : 'text-green-600')}>
{denied ? '✕' : '✓'}
<span className="truncate">{denied ? 'Denied' : 'Allowed'}: {row.title}</span>
</div>
)
})}
</div>
)
}
// ── In-run permission card ──────────────────────────────────────────
export function CodeRunPermissionRequest({
ask,
onDecide,
}: {
ask: PermissionAsk
onDecide: (decision: PermissionDecision) => void
}) {
const [busy, setBusy] = useState(false)
const decide = (d: PermissionDecision) => {
if (busy) return
setBusy(true)
onDecide(d)
}
const btn = 'rounded-full px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50'
return (
<div className="mb-4 rounded-[20px] border border-amber-500/40 bg-amber-500/5 p-4">
<div className="flex items-center gap-2 text-sm font-medium text-foreground">
<ShieldQuestion className="size-4 shrink-0 text-amber-600" />
Permission needed
</div>
<p className="mt-1 text-sm text-muted-foreground">
The agent wants to: <span className="font-medium text-foreground">{ask.title}</span>
</p>
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" disabled={busy} onClick={() => decide('allow_once')}
className={cn(btn, 'bg-foreground text-background hover:bg-foreground/90')}>
Allow
</button>
<button type="button" disabled={busy} onClick={() => decide('allow_always')}
className={cn(btn, 'border hover:bg-muted')}>
Always allow{ask.kind ? ` (${ask.kind})` : ''}
</button>
<button type="button" disabled={busy} onClick={() => decide('reject')}
className={cn(btn, 'border border-red-500/40 text-red-600 hover:bg-red-500/10')}>
Deny
</button>
</div>
</div>
)
}
// ── Block wrapper (rendered in the chat for a code_agent_run tool call) ──
const AGENT_LABEL: Record<string, string> = { claude: 'Claude Code', codex: 'Codex' }
export function CodingRunBlock({
item,
open,
onOpenChange,
onPermissionDecision,
}: {
item: ToolCall
open: boolean
onOpenChange: (open: boolean) => void
onPermissionDecision: (decision: PermissionDecision) => void
}) {
// Prefer the agent the backend actually ran (the chip) once the run returns; fall
// back to the requested input agent while it's still in flight. Never trust only the
// model's input — it can pass a stale agent the backend overrode with the chip.
const agent =
(item.result as { agent?: string } | undefined)?.agent ??
(item.input as { agent?: string } | undefined)?.agent
const title = AGENT_LABEL[agent ?? ''] ?? 'Coding agent'
return (
<>
<Tool open={open} onOpenChange={onOpenChange}>
<ToolHeader title={title} type="tool-code_agent_run" state={toToolState(item.status)} />
<ToolContent>
<CodingRunTimeline events={item.codeRunEvents ?? []} />
</ToolContent>
</Tool>
{item.pendingCodePermission && (
<CodeRunPermissionRequest ask={item.pendingCodePermission.ask} onDecide={onPermissionDecision} />
)}
</>
)
}

View file

@ -0,0 +1,196 @@
import { Suspense, lazy, useEffect, useRef, useState } from 'react'
import { ExternalLinkIcon, FileTextIcon, Loader2Icon } from 'lucide-react'
import type { DocxEditorRef } from '@eigenpal/docx-editor-react'
// The editor (and its CSS) is heavy and only needed when a .docx is open, so it
// loads in its own chunk the first time a Word document is viewed.
const LazyDocxEditor = lazy(async () => {
const [mod] = await Promise.all([
import('@eigenpal/docx-editor-react'),
import('@eigenpal/docx-editor-react/styles.css'),
])
return { default: mod.DocxEditor }
})
interface DocxFileViewerProps {
path: string
}
type LoadState = 'loading' | 'ready' | 'error'
type SaveState = 'idle' | 'saving' | 'saved' | 'error'
const SAVE_DEBOUNCE_MS = 800
// onChange fires for the editor's own load-time normalization. Ignore changes
// until shortly after the document settles so opening a file never rewrites it.
const ARM_DELAY_MS = 500
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64)
const len = binary.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i)
return bytes.buffer
}
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer)
let binary = ''
const chunk = 0x8000
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunk))
}
return btoa(binary)
}
function baseName(path: string): string {
const segs = path.split('/')
return segs[segs.length - 1] || path
}
export function DocxFileViewer({ path }: DocxFileViewerProps) {
const [loadState, setLoadState] = useState<LoadState>('loading')
const [buffer, setBuffer] = useState<ArrayBuffer | null>(null)
const [saveState, setSaveState] = useState<SaveState>('idle')
const editorRef = useRef<DocxEditorRef>(null)
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const armTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const armedRef = useRef(false)
const dirtyRef = useRef(false)
const savingRef = useRef(false)
// Load the .docx bytes whenever the path changes.
useEffect(() => {
let cancelled = false
setLoadState('loading')
setBuffer(null)
setSaveState('idle')
armedRef.current = false
dirtyRef.current = false
savingRef.current = false
;(async () => {
try {
const result = await window.ipc.invoke('workspace:readFile', { path, encoding: 'base64' })
if (cancelled) return
setBuffer(base64ToArrayBuffer(result.data))
setLoadState('ready')
if (armTimerRef.current) clearTimeout(armTimerRef.current)
armTimerRef.current = setTimeout(() => { armedRef.current = true }, ARM_DELAY_MS)
} catch (err) {
console.error('Failed to load docx:', err)
if (!cancelled) setLoadState('error')
}
})()
return () => {
cancelled = true
if (armTimerRef.current) clearTimeout(armTimerRef.current)
}
}, [path])
// Serialize the current document and write it back to disk.
const persist = async () => {
const editor = editorRef.current
if (!editor || savingRef.current) return
savingRef.current = true
dirtyRef.current = false
setSaveState('saving')
try {
const out = await editor.save()
if (out) {
await window.ipc.invoke('workspace:writeFile', {
path,
data: arrayBufferToBase64(out),
opts: { encoding: 'base64' },
})
}
setSaveState('saved')
} catch (err) {
console.error('Failed to save docx:', err)
dirtyRef.current = true
setSaveState('error')
} finally {
savingRef.current = false
// A change landed while we were saving — flush it.
if (dirtyRef.current) scheduleSave()
}
}
const scheduleSave = () => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
saveTimerRef.current = setTimeout(() => { void persist() }, SAVE_DEBOUNCE_MS)
}
const handleChange = () => {
if (!armedRef.current) return
dirtyRef.current = true
scheduleSave()
}
// Flush a pending save when navigating away or unmounting.
useEffect(() => {
return () => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
if (dirtyRef.current) void persist()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [path])
if (loadState === 'error') {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-3 px-6 text-center text-muted-foreground">
<FileTextIcon className="size-6" />
<p className="text-sm font-medium text-foreground">Cannot open this document</p>
<p className="max-w-md text-xs">The file may be corrupted or not a valid Word document.</p>
<button
type="button"
onClick={() => { void window.ipc.invoke('shell:openPath', { path }) }}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-accent"
>
<ExternalLinkIcon className="size-3.5" />
Open in system
</button>
</div>
)
}
if (loadState === 'loading' || !buffer) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-3 text-muted-foreground">
<Loader2Icon className="size-6 animate-spin" />
<p className="text-sm">Loading document</p>
</div>
)
}
return (
<div className="relative flex h-full w-full flex-col overflow-hidden">
<Suspense
fallback={
<div className="flex h-full w-full flex-col items-center justify-center gap-3 text-muted-foreground">
<Loader2Icon className="size-6 animate-spin" />
<p className="text-sm">Loading editor</p>
</div>
}
>
<LazyDocxEditor
key={path}
ref={editorRef}
documentBuffer={buffer}
mode="editing"
documentName={baseName(path)}
documentNameEditable={false}
onChange={handleChange}
onError={(err) => { console.error('docx editor error:', err) }}
className="flex-1 min-h-0"
/>
</Suspense>
{saveState !== 'idle' && (
<div className="pointer-events-none absolute bottom-3 right-4 z-10 rounded-md bg-background/80 px-2 py-1 text-xs text-muted-foreground shadow-sm backdrop-blur">
{saveState === 'saving' ? 'Saving…' : saveState === 'saved' ? 'Saved' : 'Save failed'}
</div>
)}
</div>
)
}

View file

@ -69,6 +69,31 @@ function snippet(text?: string): string {
return (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
}
function isReplyQuoteBoundary(lines: string[], index: number): boolean {
const line = lines[index]?.trim() || ''
if (/^On\b.+\bwrote:\s*$/i.test(line)) return true
if (/^-{2,}\s*(Original Message|Forwarded message)\s*-{2,}$/i.test(line)) return true
if (/^From:\s+\S/i.test(line)) {
const next = lines.slice(index + 1, index + 6).map((value) => value.trim())
return next.some((value) => /^(Sent|Date):\s+\S/i.test(value))
&& next.some((value) => /^To:\s+\S/i.test(value))
&& next.some((value) => /^Subject:\s+\S/i.test(value))
}
return false
}
function stripQuotedReplyText(text: string): string {
const lines = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n')
const boundary = lines.findIndex((line, index) => {
if (isReplyQuoteBoundary(lines, index)) return true
return index > 0
&& line.trim().startsWith('>')
&& (lines[index - 1]?.trim() === '' || lines[index - 1]?.trim().startsWith('>'))
})
const visible = boundary >= 0 ? lines.slice(0, boundary) : lines
return visible.join('\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim()
}
function getInitial(from?: string): string {
return (extractName(from)[0] || '?').toUpperCase()
}
@ -692,7 +717,7 @@ function ComposeBox({
const initialContent = useMemo(() => {
if (mode === 'forward') return buildForwardedContent(thread)
// Gmail-side draft (user's own work) wins over the AI-generated draft.
const source = thread.gmail_draft || thread.draft_response
const source = stripQuotedReplyText(thread.gmail_draft || thread.draft_response || '')
if (!source) return ''
return source
.split(/\n{2,}/)
@ -1048,8 +1073,7 @@ function ThreadDetail({
const MAX_KEPT_OPEN = 5
const PAGE_SIZE = 25
const SECTIONS = ['important', 'other'] as const
type InboxSection = (typeof SECTIONS)[number]
type InboxSection = 'important' | 'other'
interface SectionState {
threads: GmailThread[]

View file

@ -1,11 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
ArrowLeft,
ChevronRight,
Copy,
ExternalLink,
File as FileIcon,
FilePlus,
Folder as FolderIcon,
FileText,
FolderOpen,
FolderPlus,
Network,
@ -49,6 +49,10 @@ export type KnowledgeViewActions = {
type KnowledgeViewProps = {
tree: TreeNode[]
actions: KnowledgeViewActions
// Folder currently being browsed (null = root overview). Controlled by the
// app so drill-down participates in the global back/forward history.
folderPath: string | null
onNavigateFolder: (path: string | null) => void
onOpenNote: (path: string) => void
onOpenGraph: () => void
onOpenSearch: () => void
@ -56,9 +60,48 @@ type KnowledgeViewProps = {
onVoiceNoteCreated?: (path: string) => void
}
type FlatRow = {
node: TreeNode
depth: number
// Folders that have their own dedicated destinations elsewhere in the app.
const HIDDEN_PATHS = new Set(['knowledge/Meetings', 'knowledge/Workspace'])
// Theme-aware accent palette for folder avatars — colored letter on a faint
// tint of the same hue. Mirrors the design's six-colour rotation.
const AVATAR_PALETTE = [
'bg-indigo-500/10 text-indigo-600 dark:text-indigo-400',
'bg-violet-500/10 text-violet-600 dark:text-violet-400',
'bg-amber-500/10 text-amber-600 dark:text-amber-400',
'bg-rose-500/10 text-rose-600 dark:text-rose-400',
'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
'bg-sky-500/10 text-sky-600 dark:text-sky-400',
] as const
function avatarClass(name: string): string {
let hash = 0
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) >>> 0
return AVATAR_PALETTE[hash % AVATAR_PALETTE.length]
}
function isMarkdown(node: TreeNode): boolean {
return node.kind === 'file' && node.name.toLowerCase().endsWith('.md')
}
// All markdown notes within a node (recurses into subfolders).
function collectNotes(node: TreeNode): TreeNode[] {
if (node.kind === 'file') return isMarkdown(node) ? [node] : []
const out: TreeNode[] = []
for (const child of node.children ?? []) out.push(...collectNotes(child))
return out
}
function recentNotes(node: TreeNode, limit: number): TreeNode[] {
return collectNotes(node)
.sort((a, b) => (b.stat?.mtimeMs ?? 0) - (a.stat?.mtimeMs ?? 0))
.slice(0, limit)
}
function latestMtime(node: TreeNode): number {
let max = node.stat?.mtimeMs ?? 0
for (const child of node.children ?? []) max = Math.max(max, latestMtime(child))
return max
}
function sortNodes(nodes: TreeNode[]): TreeNode[] {
@ -68,23 +111,22 @@ function sortNodes(nodes: TreeNode[]): TreeNode[] {
})
}
function flatten(
nodes: TreeNode[],
expanded: Set<string>,
depth: number,
out: FlatRow[],
): void {
for (const node of sortNodes(nodes)) {
out.push({ node, depth })
if (node.kind === 'dir' && expanded.has(node.path) && node.children?.length) {
flatten(node.children, expanded, depth + 1, out)
function findNode(nodes: TreeNode[], path: string): TreeNode | null {
for (const node of nodes) {
if (node.path === path) return node
if (node.children) {
const found = findNode(node.children, path)
if (found) return found
}
}
return null
}
function formatModified(mtimeMs?: number): string {
if (!mtimeMs) return ''
return formatRelativeTime(new Date(mtimeMs).toISOString())
const rel = formatRelativeTime(new Date(mtimeMs).toISOString())
if (!rel || rel === 'just now') return rel
return `${rel} ago`
}
function getFileManagerName(): string {
@ -96,209 +138,607 @@ function getFileManagerName(): string {
}
function displayName(node: TreeNode): string {
if (node.kind === 'file' && node.name.toLowerCase().endsWith('.md')) {
return node.name.slice(0, -3)
}
if (isMarkdown(node)) return node.name.slice(0, -3)
return node.name
}
const INDENT_PX = 16
const ROW_PADDING_PX = 12
export function KnowledgeView({
tree,
actions,
folderPath,
onNavigateFolder,
onOpenNote,
onOpenGraph,
onOpenSearch,
onOpenBases,
onVoiceNoteCreated,
}: KnowledgeViewProps) {
const [expanded, setExpanded] = useState<Set<string>>(new Set())
const [renameTarget, setRenameTarget] = useState<string | null>(null)
const rows = useMemo<FlatRow[]>(() => {
const out: FlatRow[] = []
// Meetings and Workspace have dedicated destinations, so hide them here.
const visible = tree.filter((n) => n.path !== 'knowledge/Meetings' && n.path !== 'knowledge/Workspace')
flatten(visible, expanded, 0, out)
return out
}, [tree, expanded])
const handleRowClick = useCallback(
(node: TreeNode) => {
if (node.kind === 'dir') {
setExpanded((prev) => {
const next = new Set(prev)
if (next.has(node.path)) next.delete(node.path)
else next.add(node.path)
return next
})
} else {
onOpenNote(node.path)
}
},
[onOpenNote],
const topLevel = useMemo(
() => tree.filter((n) => !HIDDEN_PATHS.has(n.path)),
[tree],
)
const folders = useMemo(
() => sortNodes(topLevel.filter((n) => n.kind === 'dir')),
[topLevel],
)
const looseNotes = useMemo(
() => sortNodes(topLevel.filter((n) => isMarkdown(n))),
[topLevel],
)
const totalNotes = useMemo(
() => topLevel.reduce((sum, n) => sum + collectNotes(n).length, 0),
[topLevel],
)
const openFolder = useCallback((path: string) => onNavigateFolder(path), [onNavigateFolder])
// When the open folder no longer exists (deleted/renamed externally), fall
// back to the root overview rather than holding a dangling drill-down.
const currentFolder = folderPath ? findNode(tree, folderPath) : null
return (
<div className="flex h-full flex-col overflow-hidden">
<div className="shrink-0 flex items-center justify-between gap-3 border-b border-border px-8 py-6">
<h1 className="text-2xl font-bold tracking-tight">Notes</h1>
<div className="flex items-center gap-2">
<div className="shrink-0 flex items-start justify-between gap-4 border-b border-border px-8 py-6">
<div className="min-w-0">
<h1 className="text-2xl font-bold tracking-tight">Notes</h1>
<p className="mt-1 text-sm text-muted-foreground">
{totalNotes} {totalNotes === 1 ? 'note' : 'notes'} across {folders.length}{' '}
{folders.length === 1 ? 'folder' : 'folders'}
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<VoiceNoteButton onNoteCreated={onVoiceNoteCreated} />
<SecondaryButton icon={SearchIcon} label="Search" onClick={onOpenSearch} />
<SecondaryButton icon={Network} label="Graph" onClick={onOpenGraph} />
<button
type="button"
onClick={() => actions.createNote()}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
onClick={() => actions.createNote(currentFolder?.path)}
className="inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
>
<FilePlus className="size-4" />
<span>New note</span>
</button>
<button
type="button"
onClick={async () => {
try {
const path = await actions.createFolder()
setRenameTarget(path)
} catch { /* ignore */ }
}}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
>
<FolderPlus className="size-4" />
<span>New folder</span>
</button>
<VoiceNoteButton onNoteCreated={onVoiceNoteCreated} />
<button
type="button"
onClick={onOpenSearch}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
>
<SearchIcon className="size-4" />
<span>Search</span>
</button>
<button
type="button"
onClick={onOpenBases}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
>
<Table2 className="size-4" />
<span>Bases</span>
</button>
<button
type="button"
onClick={onOpenGraph}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
>
<Network className="size-4" />
<span>Graph view</span>
</button>
<button
type="button"
onClick={() => actions.revealInFileManager('knowledge', true)}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
>
<FolderOpen className="size-4" />
<span>Open in {getFileManagerName()}</span>
</button>
</div>
</div>
<div className="flex-1 overflow-y-auto">
<div className="min-w-[480px]">
<div className="sticky top-0 z-10 flex items-center border-b border-border bg-background px-6 py-2 text-xs font-medium text-muted-foreground">
<div className="flex-1">Page name</div>
<div className="w-32 shrink-0">Modified</div>
</div>
{rows.length === 0 ? (
<div className="px-6 py-8 text-sm text-muted-foreground">No pages yet.</div>
<div className="mx-auto w-full max-w-3xl px-8 py-6">
{currentFolder ? (
<FolderDetail
folder={currentFolder}
actions={actions}
renameTarget={renameTarget}
onRequestRename={setRenameTarget}
onClearRename={() => setRenameTarget(null)}
onNavigate={onNavigateFolder}
onOpenFolder={openFolder}
onOpenNote={onOpenNote}
/>
) : (
rows.map(({ node, depth }) => (
<KnowledgeRow
key={node.path}
node={node}
depth={depth}
isExpanded={expanded.has(node.path)}
actions={actions}
renameActive={renameTarget === node.path}
onRequestRename={(p) => setRenameTarget(p)}
onClearRename={() => setRenameTarget(null)}
onClick={handleRowClick}
/>
))
<>
<SectionHeader label={`Folders · ${folders.length}`} aside="Sorted by name" />
{folders.length === 0 ? (
<EmptyState text="No folders yet." />
) : (
<div className="overflow-hidden rounded-xl border border-border">
{folders.map((node, i) => (
<div key={node.path} className={cn(i > 0 && 'border-t border-border/60')}>
<FolderCard
node={node}
actions={actions}
renameTarget={renameTarget}
onRequestRename={setRenameTarget}
onClearRename={() => setRenameTarget(null)}
onOpenFolder={openFolder}
onOpenNote={onOpenNote}
/>
</div>
))}
</div>
)}
{looseNotes.length > 0 && (
<div className="mt-8">
<SectionHeader label={`Loose notes · ${looseNotes.length}`} />
<div className="overflow-hidden rounded-xl border border-border">
{looseNotes.map((node, i) => (
<div key={node.path} className={cn(i > 0 && 'border-t border-border/60')}>
<ItemRow
node={node}
actions={actions}
renameTarget={renameTarget}
onRequestRename={setRenameTarget}
onClearRename={() => setRenameTarget(null)}
onOpenFolder={openFolder}
onOpenNote={onOpenNote}
/>
</div>
))}
</div>
</div>
)}
</>
)}
<QuickActions
actions={actions}
currentFolder={currentFolder}
onOpenBases={onOpenBases}
onFolderCreated={setRenameTarget}
/>
</div>
</div>
</div>
)
}
function KnowledgeRow({
node,
depth,
isExpanded,
function QuickActions({
actions,
renameActive,
onRequestRename,
onClearRename,
currentFolder,
onOpenBases,
onFolderCreated,
}: {
actions: KnowledgeViewActions
currentFolder: TreeNode | null
onOpenBases: () => void
onFolderCreated: (path: string) => void
}) {
// Inside a folder these target that folder; at the root they target knowledge/.
const parent = currentFolder?.path
return (
<div className="mt-8">
<SectionHeader label="Quick actions" />
<div className="flex flex-wrap gap-2">
<QuickAction icon={FilePlus} label="New note" onClick={() => actions.createNote(parent)} />
<QuickAction
icon={FolderPlus}
label="New folder"
onClick={async () => {
try {
const path = await actions.createFolder(parent)
onFolderCreated(path)
} catch { /* ignore */ }
}}
/>
<QuickAction icon={Table2} label="Open as base" onClick={onOpenBases} />
<QuickAction
icon={FolderOpen}
label={`Reveal in ${getFileManagerName()}`}
onClick={() => actions.revealInFileManager(parent ?? 'knowledge', true)}
/>
</div>
</div>
)
}
function SecondaryButton({
icon: Icon,
label,
onClick,
}: {
icon: typeof SearchIcon
label: string
onClick: () => void
}) {
return (
<button
type="button"
onClick={onClick}
className="inline-flex items-center gap-1.5 rounded-lg border border-border bg-background px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
>
<Icon className="size-4" />
<span>{label}</span>
</button>
)
}
function QuickAction({
icon: Icon,
label,
onClick,
}: {
icon: typeof FilePlus
label: string
onClick: () => void
}) {
return (
<button
type="button"
onClick={onClick}
className="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground transition-colors hover:bg-accent"
>
<Icon className="size-4 text-muted-foreground" />
<span>{label}</span>
</button>
)
}
function SectionHeader({ label, aside }: { label: string; aside?: string }) {
return (
<div className="mb-2.5 flex items-center justify-between">
<span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
{label}
</span>
{aside && <span className="text-xs text-muted-foreground">{aside}</span>}
</div>
)
}
function EmptyState({ text }: { text: string }) {
return (
<div className="rounded-xl border border-dashed border-border px-6 py-10 text-center text-sm text-muted-foreground">
{text}
</div>
)
}
function FolderAvatar({ name, className }: { name: string; className?: string }) {
return (
<div
className={cn(
'flex size-8 shrink-0 items-center justify-center rounded-md text-[13px] font-bold',
avatarClass(name),
className,
)}
>
{name.charAt(0).toUpperCase() || '?'}
</div>
)
}
function FolderCard({
node,
actions,
renameTarget,
onRequestRename,
onClearRename,
onOpenFolder,
onOpenNote,
}: {
node: TreeNode
depth: number
isExpanded: boolean
actions: KnowledgeViewActions
renameActive: boolean
renameTarget: string | null
onRequestRename: (path: string) => void
onClearRename: () => void
onClick: (node: TreeNode) => void
onOpenFolder: (path: string) => void
onOpenNote: (path: string) => void
}) {
const count = useMemo(() => collectNotes(node).length, [node])
const peek = useMemo(() => recentNotes(node, 3), [node])
const modified = formatModified(latestMtime(node))
const renameActive = renameTarget === node.path
const card = (
<div
role="button"
tabIndex={0}
onClick={() => onOpenFolder(node.path)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onOpenFolder(node.path)
}
}}
className="group flex w-full cursor-pointer items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-accent/50"
>
<FolderAvatar name={node.name} className="mt-0.5" />
<div className="min-w-0 flex-1">
{renameActive ? (
<RenameField
initial={node.name}
isDir
path={node.path}
actions={actions}
onDone={onClearRename}
/>
) : (
<span className="block truncate text-sm font-semibold text-foreground">
{node.name}
</span>
)}
<div className="mt-0.5 text-xs text-muted-foreground">
{count} {count === 1 ? 'note' : 'notes'}
</div>
{peek.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{peek.map((n) => (
<button
key={n.path}
type="button"
onClick={(e) => {
e.stopPropagation()
onOpenNote(n.path)
}}
className="max-w-[200px] truncate rounded-full border border-border/60 bg-muted px-2.5 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
{displayName(n)}
</button>
))}
</div>
)}
</div>
<div className="flex shrink-0 items-center gap-2 pt-1">
<span className="text-xs text-muted-foreground tabular-nums whitespace-nowrap">
{modified}
</span>
<ChevronRight className="size-4 text-muted-foreground/40 opacity-0 transition-opacity group-hover:opacity-100" />
</div>
</div>
)
return (
<RowContextMenu node={node} actions={actions} onRequestRename={onRequestRename}>
{card}
</RowContextMenu>
)
}
function FolderDetail({
folder,
actions,
renameTarget,
onRequestRename,
onClearRename,
onNavigate,
onOpenFolder,
onOpenNote,
}: {
folder: TreeNode
actions: KnowledgeViewActions
renameTarget: string | null
onRequestRename: (path: string) => void
onClearRename: () => void
onNavigate: (path: string | null) => void
onOpenFolder: (path: string) => void
onOpenNote: (path: string) => void
}) {
const items = useMemo(() => sortNodes(folder.children ?? []), [folder])
// Breadcrumb segments from "knowledge/A/B" → [{ name: 'A', path }, ...].
const crumbs = useMemo(() => {
const rel = folder.path.startsWith('knowledge/')
? folder.path.slice('knowledge/'.length)
: folder.path
const parts = rel.split('/').filter(Boolean)
const out: { name: string; path: string }[] = []
let acc = 'knowledge'
for (const part of parts) {
acc = `${acc}/${part}`
out.push({ name: part, path: acc })
}
return out
}, [folder.path])
return (
<>
<div className="mb-4 flex min-w-0 items-center gap-1.5 text-sm">
<button
type="button"
onClick={() => {
const parent = crumbs.length >= 2 ? crumbs[crumbs.length - 2].path : null
onNavigate(parent)
}}
className="inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
aria-label="Back"
>
<ArrowLeft className="size-4" />
</button>
<button
type="button"
onClick={() => onNavigate(null)}
className="rounded-md px-1.5 py-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
Notes
</button>
{crumbs.map((c, i) => (
<span key={c.path} className="flex min-w-0 items-center gap-1.5">
<ChevronRight className="size-3.5 shrink-0 text-muted-foreground/50" />
{i === crumbs.length - 1 ? (
<span className="truncate font-medium text-foreground">{c.name}</span>
) : (
<button
type="button"
onClick={() => onNavigate(c.path)}
className="truncate rounded-md px-1.5 py-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
{c.name}
</button>
)}
</span>
))}
</div>
<SectionHeader label={`${items.length} ${items.length === 1 ? 'item' : 'items'}`} />
{items.length === 0 ? (
<EmptyState text="This folder is empty." />
) : (
<div className="overflow-hidden rounded-xl border border-border">
{items.map((node, i) => (
<div key={node.path} className={cn(i > 0 && 'border-t border-border/60')}>
<ItemRow
node={node}
actions={actions}
renameTarget={renameTarget}
onRequestRename={onRequestRename}
onClearRename={onClearRename}
onOpenFolder={onOpenFolder}
onOpenNote={onOpenNote}
/>
</div>
))}
</div>
)}
</>
)
}
function ItemRow({
node,
actions,
renameTarget,
onRequestRename,
onClearRename,
onOpenFolder,
onOpenNote,
}: {
node: TreeNode
actions: KnowledgeViewActions
renameTarget: string | null
onRequestRename: (path: string) => void
onClearRename: () => void
onOpenFolder: (path: string) => void
onOpenNote: (path: string) => void
}) {
const isDir = node.kind === 'dir'
const Icon = isDir ? FolderIcon : FileIcon
const paddingLeft = ROW_PADDING_PX + depth * INDENT_PX
const baseName = displayName(node)
const renameActive = renameTarget === node.path
const modified = formatModified(isDir ? latestMtime(node) : node.stat?.mtimeMs)
const count = useMemo(() => (isDir ? collectNotes(node).length : 0), [isDir, node])
const [newName, setNewName] = useState(baseName)
const handleOpen = useCallback(() => {
if (isDir) onOpenFolder(node.path)
else onOpenNote(node.path)
}, [isDir, node.path, onOpenFolder, onOpenNote])
const row = (
<div
role="button"
tabIndex={0}
onClick={handleOpen}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
handleOpen()
}
}}
className="group flex w-full cursor-pointer items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-accent/50"
>
{isDir ? (
<FolderAvatar name={node.name} />
) : (
<div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
<FileText className="size-4" />
</div>
)}
<div className="min-w-0 flex-1">
{renameActive ? (
<RenameField
initial={displayName(node)}
isDir={isDir}
path={node.path}
actions={actions}
onDone={onClearRename}
/>
) : (
<span className="block truncate text-sm text-foreground">{displayName(node)}</span>
)}
{isDir && (
<div className="mt-0.5 text-xs text-muted-foreground">
{count} {count === 1 ? 'note' : 'notes'}
</div>
)}
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="text-xs text-muted-foreground tabular-nums whitespace-nowrap">
{modified}
</span>
{isDir && (
<ChevronRight className="size-4 text-muted-foreground/40 opacity-0 transition-opacity group-hover:opacity-100" />
)}
</div>
</div>
)
return (
<RowContextMenu node={node} actions={actions} onRequestRename={onRequestRename}>
{row}
</RowContextMenu>
)
}
function RenameField({
initial,
isDir,
path,
actions,
onDone,
}: {
initial: string
isDir: boolean
path: string
actions: KnowledgeViewActions
onDone: () => void
}) {
const [value, setValue] = useState(initial)
const inputRef = useRef<HTMLInputElement | null>(null)
const isSubmittingRef = useRef(false)
useEffect(() => {
if (renameActive) {
setNewName(baseName)
isSubmittingRef.current = false
// focus on next tick after mount
requestAnimationFrame(() => {
inputRef.current?.focus()
inputRef.current?.select()
})
}
}, [renameActive, baseName])
requestAnimationFrame(() => {
inputRef.current?.focus()
inputRef.current?.select()
})
}, [])
const handleRenameSubmit = useCallback(async () => {
const submit = useCallback(async () => {
if (isSubmittingRef.current) return
isSubmittingRef.current = true
const trimmed = newName.trim()
if (trimmed && trimmed !== baseName) {
const trimmed = value.trim()
if (trimmed && trimmed !== initial) {
try {
await actions.rename(node.path, trimmed, isDir)
await actions.rename(path, trimmed, isDir)
toast('Renamed successfully', 'success')
} catch {
toast('Failed to rename', 'error')
}
}
onClearRename()
setTimeout(() => {
isSubmittingRef.current = false
}, 100)
}, [actions, baseName, isDir, newName, node.path, onClearRename])
onDone()
}, [actions, initial, isDir, onDone, path, value])
const cancelRename = useCallback(() => {
const cancel = useCallback(() => {
isSubmittingRef.current = true
setNewName(baseName)
onClearRename()
setTimeout(() => {
isSubmittingRef.current = false
}, 100)
}, [baseName, onClearRename])
onDone()
}, [onDone])
return (
<Input
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation()
if (e.key === 'Enter') {
e.preventDefault()
void submit()
} else if (e.key === 'Escape') {
e.preventDefault()
cancel()
}
}}
onBlur={() => {
if (!isSubmittingRef.current) void submit()
}}
className="h-7 text-sm"
/>
)
}
function RowContextMenu({
node,
actions,
onRequestRename,
children,
}: {
node: TreeNode
actions: KnowledgeViewActions
onRequestRename: (path: string) => void
children: React.ReactNode
}) {
const isDir = node.kind === 'dir'
const handleDelete = useCallback(async () => {
try {
@ -314,58 +754,9 @@ function KnowledgeRow({
toast('Path copied', 'success')
}, [actions, node.path])
const row = (
<button
type="button"
onClick={() => onClick(node)}
className="group flex w-full items-center border-b border-border/60 px-6 py-1.5 text-left text-sm transition-colors hover:bg-accent"
>
<div className="flex flex-1 items-center gap-1.5 min-w-0" style={{ paddingLeft }}>
<span className="inline-flex w-4 shrink-0 items-center justify-center text-muted-foreground">
{isDir ? (
<ChevronRight
className={cn(
'size-3.5 transition-transform',
isExpanded && 'rotate-90',
)}
/>
) : null}
</span>
<Icon className="size-4 shrink-0 text-muted-foreground" />
{renameActive ? (
<Input
ref={inputRef}
value={newName}
onChange={(e) => setNewName(e.target.value)}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation()
if (e.key === 'Enter') {
e.preventDefault()
void handleRenameSubmit()
} else if (e.key === 'Escape') {
e.preventDefault()
cancelRename()
}
}}
onBlur={() => {
if (!isSubmittingRef.current) void handleRenameSubmit()
}}
className="h-6 text-sm flex-1"
/>
) : (
<span className="min-w-0 truncate">{baseName}</span>
)}
</div>
<div className="w-32 shrink-0 text-xs text-muted-foreground tabular-nums">
{formatModified(node.stat?.mtimeMs)}
</div>
</button>
)
return (
<ContextMenu>
<ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
<ContextMenuContent className="w-48" onCloseAutoFocus={(e) => e.preventDefault()}>
{isDir && (
<>

View file

@ -21,7 +21,7 @@ interface SearchResult {
path: string
}
type SearchType = 'knowledge' | 'chat'
export type SearchType = 'knowledge' | 'chat'
function activeTabToTypes(section: ActiveSection): SearchType[] {
if (section === 'knowledge') return ['knowledge']
@ -46,6 +46,9 @@ interface CommandPaletteProps {
onOpenChange: (open: boolean) => void
onSelectFile: (path: string) => void
onSelectRun: (runId: string) => void
// Overrides the sidebar-section default for the initial scope (e.g. the
// knowledge view opens search scoped to knowledge).
defaultScope?: SearchType
}
export function CommandPalette({
@ -53,6 +56,7 @@ export function CommandPalette({
onOpenChange,
onSelectFile,
onSelectRun,
defaultScope,
}: CommandPaletteProps) {
const { activeSection } = useSidebarSection()
const searchInputRef = useRef<HTMLInputElement>(null)
@ -61,7 +65,7 @@ export function CommandPalette({
const [results, setResults] = useState<SearchResult[]>([])
const [isSearching, setIsSearching] = useState(false)
const [activeTypes, setActiveTypes] = useState<Set<SearchType>>(
() => new Set(activeTabToTypes(activeSection))
() => new Set(defaultScope ? [defaultScope] : activeTabToTypes(activeSection))
)
const debouncedQuery = useDebounce(query, 250)
@ -69,9 +73,9 @@ export function CommandPalette({
useEffect(() => {
if (open) {
setQuery('')
setActiveTypes(new Set(activeTabToTypes(activeSection)))
setActiveTypes(new Set(defaultScope ? [defaultScope] : activeTabToTypes(activeSection)))
}
}, [open, activeSection])
}, [open, activeSection, defaultScope])
useEffect(() => {
if (!open) return

View file

@ -2,7 +2,7 @@
import * as React from "react"
import { useState, useEffect, useCallback, useMemo } from "react"
import { Server, Key, Shield, Palette, Monitor, Sun, Moon, Loader2, CheckCircle2, Plus, X, Wrench, Search, ChevronRight, Link2, Tags, Mail, BookOpen, User, Plug, HelpCircle, MessageCircle, Bug } from "lucide-react"
import { Server, Key, Shield, Palette, Monitor, Sun, Moon, Loader2, CheckCircle2, Plus, X, Wrench, Search, ChevronRight, Link2, Tags, Mail, BookOpen, User, Plug, HelpCircle, MessageCircle, Bug, Terminal, AlertTriangle, RefreshCw, PanelRight } from "lucide-react"
import {
Dialog,
@ -25,8 +25,9 @@ import { useTheme } from "@/contexts/theme-context"
import { toast } from "sonner"
import { AccountSettings } from "@/components/settings/account-settings"
import { ConnectedAccountsSettings } from "@/components/settings/connected-accounts-settings"
import type { ApprovalPolicy } from "@x/shared/src/code-mode.js"
type ConfigTab = "account" | "connections" | "models" | "mcp" | "security" | "appearance" | "note-tagging" | "help"
type ConfigTab = "account" | "connections" | "models" | "mcp" | "security" | "code-mode" | "appearance" | "note-tagging" | "help"
interface TabConfig {
id: ConfigTab
@ -70,6 +71,12 @@ const tabs: TabConfig[] = [
path: "config/security.json",
description: "Configure allowed shell commands",
},
{
id: "code-mode",
label: "Code Mode",
icon: Terminal,
description: "Delegate coding tasks to Claude Code or Codex",
},
{
id: "appearance",
label: "Appearance",
@ -204,7 +211,7 @@ function ThemeOption({
}
function AppearanceSettings() {
const { theme, setTheme } = useTheme()
const { theme, setTheme, chatPanePlacement, setChatPanePlacement, chatPaneSize, setChatPaneSize } = useTheme()
return (
<div className="space-y-6">
@ -234,6 +241,50 @@ function AppearanceSettings() {
/>
</div>
</div>
<div>
<h4 className="text-sm font-medium mb-3">Chat</h4>
<p className="text-xs text-muted-foreground mb-4">
Choose where chat sits when another pane is open
</p>
<div className="grid grid-cols-2 gap-3">
<ThemeOption
label="Chat right"
icon={PanelRight}
isSelected={chatPanePlacement === "right"}
onClick={() => setChatPanePlacement("right")}
/>
<ThemeOption
label="Chat middle"
icon={MessageCircle}
isSelected={chatPanePlacement === "middle"}
onClick={() => setChatPanePlacement("middle")}
/>
</div>
<h4 className="mt-6 text-sm font-medium mb-3">Chat size</h4>
<p className="text-xs text-muted-foreground mb-4">
Choose how much width chat gets when another pane is open
</p>
<div className="grid grid-cols-3 gap-3">
<ThemeOption
label="Chat smaller"
icon={MessageCircle}
isSelected={chatPaneSize === "chat-smaller"}
onClick={() => setChatPaneSize("chat-smaller")}
/>
<ThemeOption
label="Chat equal"
icon={Monitor}
isSelected={chatPaneSize === "chat-equal"}
onClick={() => setChatPaneSize("chat-equal")}
/>
<ThemeOption
label="Chat bigger"
icon={PanelRight}
isSelected={chatPaneSize === "chat-bigger"}
onClick={() => setChatPaneSize("chat-bigger")}
/>
</div>
</div>
</div>
)
}
@ -271,17 +322,27 @@ const defaultBaseURLs: Partial<Record<LlmProviderFlavor, string>> = {
"openai-compatible": "http://localhost:1234/v1",
}
type ProviderModelConfig = {
apiKey: string
baseURL: string
models: string[]
knowledgeGraphModel: string
meetingNotesModel: string
liveNoteAgentModel: string
autoPermissionDecisionModel: string
}
function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
const [provider, setProvider] = useState<LlmProviderFlavor>("openai")
const [defaultProvider, setDefaultProvider] = useState<LlmProviderFlavor | null>(null)
const [providerConfigs, setProviderConfigs] = useState<Record<LlmProviderFlavor, { apiKey: string; baseURL: string; models: string[]; knowledgeGraphModel: string; meetingNotesModel: string; liveNoteAgentModel: string }>>({
openai: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
anthropic: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
google: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
openrouter: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
aigateway: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
ollama: { apiKey: "", baseURL: "http://localhost:11434", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
"openai-compatible": { apiKey: "", baseURL: "http://localhost:1234/v1", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
const [providerConfigs, setProviderConfigs] = useState<Record<LlmProviderFlavor, ProviderModelConfig>>({
openai: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
anthropic: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
google: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
openrouter: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
aigateway: { apiKey: "", baseURL: "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
ollama: { apiKey: "", baseURL: "http://localhost:11434", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
"openai-compatible": { apiKey: "", baseURL: "http://localhost:1234/v1", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
})
const [modelsCatalog, setModelsCatalog] = useState<Record<string, LlmModelOption[]>>({})
const [modelsLoading, setModelsLoading] = useState(false)
@ -307,7 +368,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
(!requiresBaseURL || activeConfig.baseURL.trim().length > 0)
const updateConfig = useCallback(
(prov: LlmProviderFlavor, updates: Partial<{ apiKey: string; baseURL: string; models: string[]; knowledgeGraphModel: string; meetingNotesModel: string; liveNoteAgentModel: string }>) => {
(prov: LlmProviderFlavor, updates: Partial<ProviderModelConfig>) => {
setProviderConfigs(prev => ({
...prev,
[prov]: { ...prev[prov], ...updates },
@ -382,6 +443,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
knowledgeGraphModel: e.knowledgeGraphModel || "",
meetingNotesModel: e.meetingNotesModel || "",
liveNoteAgentModel: e.liveNoteAgentModel || "",
autoPermissionDecisionModel: e.autoPermissionDecisionModel || "",
};
}
}
@ -400,6 +462,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
knowledgeGraphModel: parsed.knowledgeGraphModel || "",
meetingNotesModel: parsed.meetingNotesModel || "",
liveNoteAgentModel: parsed.liveNoteAgentModel || "",
autoPermissionDecisionModel: parsed.autoPermissionDecisionModel || "",
};
}
return next;
@ -475,6 +538,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
knowledgeGraphModel: activeConfig.knowledgeGraphModel.trim() || undefined,
meetingNotesModel: activeConfig.meetingNotesModel.trim() || undefined,
liveNoteAgentModel: activeConfig.liveNoteAgentModel.trim() || undefined,
autoPermissionDecisionModel: activeConfig.autoPermissionDecisionModel.trim() || undefined,
}
const result = await window.ipc.invoke("models:test", providerConfig)
if (result.success) {
@ -509,6 +573,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
knowledgeGraphModel: config.knowledgeGraphModel.trim() || undefined,
meetingNotesModel: config.meetingNotesModel.trim() || undefined,
liveNoteAgentModel: config.liveNoteAgentModel.trim() || undefined,
autoPermissionDecisionModel: config.autoPermissionDecisionModel.trim() || undefined,
})
setDefaultProvider(prov)
window.dispatchEvent(new Event('models-config-changed'))
@ -540,6 +605,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
parsed.knowledgeGraphModel = defConfig.knowledgeGraphModel.trim() || undefined
parsed.meetingNotesModel = defConfig.meetingNotesModel.trim() || undefined
parsed.liveNoteAgentModel = defConfig.liveNoteAgentModel.trim() || undefined
parsed.autoPermissionDecisionModel = defConfig.autoPermissionDecisionModel.trim() || undefined
}
await window.ipc.invoke("workspace:writeFile", {
path: "config/models.json",
@ -547,7 +613,7 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
})
setProviderConfigs(prev => ({
...prev,
[prov]: { apiKey: "", baseURL: defaultBaseURLs[prov] || "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "" },
[prov]: { apiKey: "", baseURL: defaultBaseURLs[prov] || "", models: [""], knowledgeGraphModel: "", meetingNotesModel: "", liveNoteAgentModel: "", autoPermissionDecisionModel: "" },
}))
setTestState({ status: "idle" })
window.dispatchEvent(new Event('models-config-changed'))
@ -805,6 +871,40 @@ function ModelSettings({ dialogOpen }: { dialogOpen: boolean }) {
</Select>
)}
</div>
{/* Auto-permission model */}
<div className="space-y-2">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Auto-permission model</span>
{modelsLoading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
Loading...
</div>
) : showModelInput ? (
<Input
value={activeConfig.autoPermissionDecisionModel}
onChange={(e) => updateConfig(provider, { autoPermissionDecisionModel: e.target.value })}
placeholder={primaryModel || "Enter model"}
/>
) : (
<Select
value={activeConfig.autoPermissionDecisionModel || "__same__"}
onValueChange={(value) => updateConfig(provider, { autoPermissionDecisionModel: value === "__same__" ? "" : value })}
>
<SelectTrigger>
<SelectValue placeholder="Select a model" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__same__">Same as assistant</SelectItem>
{modelsForProvider.map((m) => (
<SelectItem key={m.id} value={m.id}>
{m.name || m.id}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
{/* API Key */}
@ -1648,6 +1748,245 @@ function NoteTaggingSettings({ dialogOpen }: { dialogOpen: boolean }) {
)
}
// --- Code Mode Settings ---
type AgentStatus = { installed: boolean; signedIn: boolean }
type CodeModeAgentStatus = { claude: AgentStatus; codex: AgentStatus }
function AgentStatusRow({
name,
installLink,
signInCommand,
status,
}: {
name: string
installLink: string
signInCommand: string
status: AgentStatus | null
}) {
const ready = status?.installed && status?.signedIn
const needsSignInOnly = status?.installed && !status?.signedIn
return (
<div className="rounded-md border px-3 py-2.5 flex items-center gap-3">
<Terminal className="size-4 text-muted-foreground shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium">{name}</div>
<div className="text-xs text-muted-foreground mt-0.5 flex items-center gap-3">
<span className={cn("inline-flex items-center gap-1", status?.installed ? "text-green-600" : "text-muted-foreground")}>
{status?.installed ? <CheckCircle2 className="size-3" /> : <X className="size-3" />}
Installed
</span>
<span className={cn("inline-flex items-center gap-1", status?.signedIn ? "text-green-600" : "text-muted-foreground")}>
{status?.signedIn ? <CheckCircle2 className="size-3" /> : <X className="size-3" />}
Signed in
</span>
</div>
</div>
{ready ? (
<span className="rounded-full bg-green-500/10 px-2 py-0.5 text-[10px] font-medium leading-none text-green-600">
Ready
</span>
) : needsSignInOnly ? (
<span className="text-xs text-muted-foreground shrink-0">
Run <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px] text-foreground">{signInCommand}</code>
</span>
) : (
<a
href={installLink}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-primary hover:underline shrink-0"
>
Install &amp; sign in
</a>
)}
</div>
)
}
function CodeModeSettings({ dialogOpen }: { dialogOpen: boolean }) {
const [enabled, setEnabled] = useState(false)
const [approvalPolicy, setApprovalPolicy] = useState<ApprovalPolicy>('ask')
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [status, setStatus] = useState<CodeModeAgentStatus | null>(null)
const [statusLoading, setStatusLoading] = useState(false)
const loadStatus = useCallback(async () => {
setStatusLoading(true)
try {
const result = await window.ipc.invoke("codeMode:checkAgentStatus", null)
setStatus(result)
} catch {
setStatus(null)
} finally {
setStatusLoading(false)
}
}, [])
useEffect(() => {
if (!dialogOpen) return
let cancelled = false
async function load() {
setLoading(true)
try {
const result = await window.ipc.invoke("codeMode:getConfig", null)
if (!cancelled) {
setEnabled(result.enabled)
setApprovalPolicy(result.approvalPolicy ?? 'ask')
}
} catch {
if (!cancelled) setEnabled(false)
} finally {
if (!cancelled) setLoading(false)
}
}
load()
loadStatus()
return () => { cancelled = true }
}, [dialogOpen, loadStatus])
const handleToggle = useCallback(async (next: boolean) => {
setSaving(true)
setEnabled(next)
try {
await window.ipc.invoke("codeMode:setConfig", { enabled: next, approvalPolicy })
window.dispatchEvent(new Event("code-mode-config-changed"))
toast.success(next ? "Code mode enabled" : "Code mode disabled")
} catch {
setEnabled(!next)
toast.error("Failed to update code mode")
} finally {
setSaving(false)
}
}, [approvalPolicy])
const handlePolicyChange = useCallback(async (next: ApprovalPolicy) => {
const prev = approvalPolicy
setSaving(true)
setApprovalPolicy(next)
try {
await window.ipc.invoke("codeMode:setConfig", { enabled, approvalPolicy: next })
window.dispatchEvent(new Event("code-mode-config-changed"))
} catch {
setApprovalPolicy(prev)
toast.error("Failed to update approval policy")
} finally {
setSaving(false)
}
}, [enabled, approvalPolicy])
const anyReady = status?.claude.installed && status?.claude.signedIn
|| status?.codex.installed && status?.codex.signedIn
if (loading) {
return (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">
<Loader2 className="size-4 animate-spin mr-2" />
Loading...
</div>
)
}
return (
<div className="space-y-5">
<div className="space-y-2 text-sm text-muted-foreground leading-relaxed">
<p>
<strong className="text-foreground">Code mode</strong> lets the assistant delegate coding tasks
to <strong className="text-foreground">Claude Code</strong> or <strong className="text-foreground">Codex</strong> running
on your machine. Pick the agent inline from the composer; the assistant runs it on-device
and streams its work tool calls, file diffs, and approvals back into chat.
</p>
<p>
Requires an active <strong className="text-foreground">Claude Code</strong> subscription or
a <strong className="text-foreground">ChatGPT/Codex</strong> subscription. You can have one or both.
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Agent status</span>
<button
onClick={() => { void loadStatus() }}
disabled={statusLoading}
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{statusLoading ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
Re-check
</button>
</div>
<div className="space-y-2">
<AgentStatusRow
name="Claude Code"
installLink="https://claude.ai/code"
signInCommand="claude login"
status={status?.claude ?? null}
/>
<AgentStatusRow
name="Codex"
installLink="https://developers.openai.com/codex/cli"
signInCommand="codex login"
status={status?.codex ?? null}
/>
</div>
</div>
<div className="rounded-md border px-3 py-3 flex items-start gap-3">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium">Enable code mode</div>
<div className="text-xs text-muted-foreground mt-0.5">
Shows the code mode chip in the composer and lets the assistant delegate to your installed agents.
</div>
</div>
<Switch
checked={enabled}
onCheckedChange={handleToggle}
disabled={saving}
/>
</div>
{enabled && (
<div className="rounded-md border px-3 py-3 space-y-2">
<div className="text-sm font-medium">Approvals</div>
<div className="text-xs text-muted-foreground">
How the coding agent checks in before changing files or running commands. You always see
everything it does in the timeline this only controls the prompts.
</div>
<Select
value={approvalPolicy}
onValueChange={(v) => handlePolicyChange(v as ApprovalPolicy)}
disabled={saving}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask every time</SelectItem>
<SelectItem value="auto-approve-reads">Auto-approve reads</SelectItem>
<SelectItem value="yolo">Auto-approve everything (YOLO)</SelectItem>
</SelectContent>
</Select>
<div className="text-xs text-muted-foreground">
{approvalPolicy === 'ask' && 'You approve every file change and command the agent wants to run.'}
{approvalPolicy === 'auto-approve-reads' && 'Reading and searching run automatically; you still approve writes, edits, and commands.'}
{approvalPolicy === 'yolo' && 'The agent runs everything — writes, edits, and commands — without asking. Use only in folders you trust.'}
</div>
</div>
)}
{enabled && status && !anyReady && (
<div className="rounded-md border border-amber-500/40 bg-amber-50/60 dark:bg-amber-950/20 px-3 py-2.5 flex items-start gap-2 text-xs">
<AlertTriangle className="size-4 text-amber-600 dark:text-amber-500 shrink-0 mt-0.5" />
<div className="text-amber-900 dark:text-amber-200">
Neither Claude Code nor Codex is ready. Install at least one and sign in with a subscription
account, then click Re-check.
</div>
</div>
)}
</div>
)
}
// --- Main Settings Dialog ---
export function SettingsDialog({ children, defaultTab = "account", open: controlledOpen, onOpenChange }: SettingsDialogProps) {
@ -1695,7 +2034,7 @@ export function SettingsDialog({ children, defaultTab = "account", open: control
}
const loadConfig = useCallback(async (tab: ConfigTab) => {
if (tab === "appearance" || tab === "models" || tab === "note-tagging" || tab === "account" || tab === "connections" || tab === "help") return
if (tab === "appearance" || tab === "models" || tab === "note-tagging" || tab === "account" || tab === "connections" || tab === "help" || tab === "code-mode") return
const tabConfig = tabs.find((t) => t.id === tab)!
if (!tabConfig.path) return
setLoading(true)
@ -1803,7 +2142,7 @@ export function SettingsDialog({ children, defaultTab = "account", open: control
</div>
{/* Content */}
<div className={cn("flex-1 p-4 min-h-0", (activeTab === "models" || activeTab === "connections" || activeTab === "account") ? "overflow-y-auto" : activeTab === "note-tagging" ? "overflow-hidden flex flex-col" : "overflow-hidden")}>
<div className={cn("flex-1 p-4 min-h-0", (activeTab === "models" || activeTab === "connections" || activeTab === "account" || activeTab === "code-mode") ? "overflow-y-auto" : activeTab === "note-tagging" ? "overflow-hidden flex flex-col" : "overflow-hidden")}>
{activeTab === "account" ? (
<AccountSettings dialogOpen={open} />
) : activeTab === "connections" ? (
@ -1828,6 +2167,8 @@ export function SettingsDialog({ children, defaultTab = "account", open: control
<AppearanceSettings />
) : activeTab === "help" ? (
<HelpSettings />
) : activeTab === "code-mode" ? (
<CodeModeSettings dialogOpen={open} />
) : loading ? (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">
Loading...

View file

@ -512,7 +512,7 @@ export function SidebarContentPanel({
const out: TreeNode[] = []
const walk = (nodes: TreeNode[]) => {
for (const n of nodes) {
if (n.path === 'knowledge/Meetings' || n.path === 'knowledge/Workspace') continue
if (n.path === 'knowledge/Meetings' || n.path === 'knowledge/Workspace' || n.path === 'knowledge/Agent Notes') continue
if (n.kind === 'file') out.push(n)
else if (n.children?.length) walk(n.children)
}
@ -521,11 +521,11 @@ export function SidebarContentPanel({
return out
.filter((n) => n.stat?.mtimeMs)
.sort((a, b) => (b.stat?.mtimeMs ?? 0) - (a.stat?.mtimeMs ?? 0))
.slice(0, 5)
.slice(0, 10)
}, [tree])
// Recents: most recently touched notes / agents / chats, interleaved by
// recency. Capped per type (3 notes, 2 agents, 1 chat) and 5 overall.
// recency. Capped per type (4 notes, 4 agents, 4 chats) and 12 overall.
type QuickAccessItem = {
key: string
label: string
@ -536,7 +536,7 @@ export function SidebarContentPanel({
const quickAccessItems = React.useMemo<QuickAccessItem[]>(() => {
const items: QuickAccessItem[] = []
for (const note of recentNotes.slice(0, 3)) {
for (const note of recentNotes.slice(0, 4)) {
items.push({
key: `note:${note.path}`,
label: displayNoteName(note),
@ -551,7 +551,7 @@ export function SidebarContentPanel({
const ms = ts ? new Date(ts).getTime() : 0
return Number.isFinite(ms) ? ms : 0
}
for (const t of [...bgTaskSummaries].sort((a, b) => agentRecency(b) - agentRecency(a)).slice(0, 2)) {
for (const t of [...bgTaskSummaries].sort((a, b) => agentRecency(b) - agentRecency(a)).slice(0, 4)) {
items.push({
key: `agent:${t.slug}`,
label: t.name,
@ -565,7 +565,7 @@ export function SidebarContentPanel({
const ms = new Date(r.createdAt).getTime()
return Number.isFinite(ms) ? ms : 0
}
for (const r of [...recentRuns].sort((a, b) => chatRecency(b) - chatRecency(a)).slice(0, 1)) {
for (const r of [...recentRuns].sort((a, b) => chatRecency(b) - chatRecency(a)).slice(0, 4)) {
items.push({
key: `chat:${r.id}`,
label: r.title || '(Untitled chat)',
@ -575,7 +575,7 @@ export function SidebarContentPanel({
})
}
return items.sort((a, b) => b.recency - a.recency).slice(0, 5)
return items.sort((a, b) => b.recency - a.recency).slice(0, 12)
}, [recentNotes, bgTaskSummaries, recentRuns, onSelectFile, onOpenAgent, onOpenRun])
// Workspace count for the Workspaces sublabel — top-level dir children of
@ -691,10 +691,20 @@ export function SidebarContentPanel({
// Single preview shown as a sublabel on the Email / Meetings nav buttons.
const previewEmail = emailThreads[0]
const previewMeeting = meetings[0]
const meetingIsRecording = previewMeeting != null
&& recordingMeetingSource === previewMeeting.source
&& (meetingRecordingState === 'recording' || meetingRecordingState === 'connecting' || meetingRecordingState === 'stopping')
const meetingIsBusy = meetingIsRecording && (meetingRecordingState === 'connecting' || meetingRecordingState === 'stopping')
// Drive the recording indicator off the global recording state — there is only
// one active recording, so it must show even for ad-hoc recordings or meetings
// that aren't the upcoming one previewed here.
const meetingIsRecording = meetingRecordingState === 'recording'
|| meetingRecordingState === 'connecting'
|| meetingRecordingState === 'stopping'
const meetingIsBusy = meetingRecordingState === 'connecting' || meetingRecordingState === 'stopping'
// Title of the meeting being recorded, when it's the upcoming one we preview.
const recordingMeeting = previewMeeting != null && recordingMeetingSource === previewMeeting.source
? previewMeeting
: null
const meetingSublabel = meetingIsRecording
? (recordingMeeting?.summary ?? 'Recording…')
: (previewMeeting ? `${previewMeeting.summary} · ${formatMeetingTime(previewMeeting)}` : null)
return (
<Sidebar className="rowboat-sidebar border-r-0" {...props}>
@ -750,19 +760,22 @@ export function SidebarContentPanel({
<SidebarMenuButton
isActive={activeNav === 'meetings'}
onClick={onOpenMeetings}
className={previewMeeting ? 'h-auto py-1.5' : undefined}
className={meetingSublabel ? 'h-auto py-1.5' : undefined}
>
<Mic className="size-4 shrink-0" />
<Mic className={cn('size-4 shrink-0', meetingIsRecording && 'text-red-500')} />
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate">Meetings</span>
{previewMeeting && (
<span className="truncate text-[11px] text-muted-foreground">
{meetingIsRecording ? previewMeeting.summary : `${previewMeeting.summary} · ${formatMeetingTime(previewMeeting)}`}
{meetingSublabel && (
<span className={cn(
'truncate text-[11px]',
meetingIsRecording ? 'text-red-500' : 'text-muted-foreground',
)}>
{meetingSublabel}
</span>
)}
</div>
</SidebarMenuButton>
{previewMeeting && (meetingIsRecording ? (
{meetingIsRecording ? (
<div className="absolute inset-y-0 right-1 flex items-center gap-1.5">
<span className="relative flex size-2">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-500 opacity-75" />
@ -786,7 +799,7 @@ export function SidebarContentPanel({
</TooltipContent>
</Tooltip>
</div>
) : (
) : previewMeeting ? (
<div className="absolute inset-y-0 right-1 flex items-center gap-0.5 opacity-0 transition-opacity group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100">
<Tooltip>
<TooltipTrigger asChild>
@ -819,7 +832,7 @@ export function SidebarContentPanel({
</Tooltip>
)}
</div>
))}
) : null}
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton

View file

@ -1,7 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useCallback, useMemo, useRef, useState } from 'react'
import {
ChevronRight,
Copy,
ExternalLink,
File as FileIcon,
FilePlus,
Folder as FolderIcon,
@ -53,12 +54,18 @@ type WorkspaceActions = {
remove: (path: string) => Promise<void>
copyPath: (path: string) => void
revealInFileManager: (path: string, isDir: boolean) => void
createNote: (parentPath?: string) => void
createFolder: (parentPath?: string) => Promise<string>
onOpenInNewTab?: (path: string) => void
}
type WorkspaceViewProps = {
tree: TreeNode[]
initialPath?: string | null
actions: WorkspaceActions
// Folder currently being browsed. Controlled by the app so drill-down
// participates in the global back/forward history.
onNavigate: (path: string) => void
onOpenNote: (path: string) => void
onCreateWorkspace: (name: string) => Promise<void>
}
@ -71,6 +78,12 @@ function getFileManagerName(): string {
return 'File Manager'
}
function fileExtensionLabel(name: string): string {
const dot = name.lastIndexOf('.')
if (dot <= 0 || dot === name.length - 1) return 'File'
return `${name.slice(dot + 1).toUpperCase()} file`
}
function findNode(nodes: TreeNode[] | undefined, path: string): TreeNode | null {
if (!nodes) return null
for (const node of nodes) {
@ -113,8 +126,8 @@ function readFileAsBase64(file: File): Promise<string> {
})
}
export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreateWorkspace }: WorkspaceViewProps) {
const [currentPath, setCurrentPath] = useState<string>(initialPath || WORKSPACE_ROOT)
export function WorkspaceView({ tree, initialPath, actions, onNavigate, onOpenNote, onCreateWorkspace }: WorkspaceViewProps) {
const currentPath = initialPath || WORKSPACE_ROOT
const [addOpen, setAddOpen] = useState(false)
const [newName, setNewName] = useState('')
const [creating, setCreating] = useState(false)
@ -127,10 +140,6 @@ export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreate
const filesInputRef = useRef<HTMLInputElement | null>(null)
const folderInputRef = useRef<HTMLInputElement | null>(null)
useEffect(() => {
if (initialPath) setCurrentPath(initialPath)
}, [initialPath])
const isRoot = currentPath === WORKSPACE_ROOT
const fileManagerName = getFileManagerName()
@ -160,12 +169,12 @@ export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreate
(item: TreeNode) => {
if (renameTarget) return
if (item.kind === 'dir') {
setCurrentPath(item.path)
onNavigate(item.path)
} else {
onOpenNote(item.path)
}
},
[onOpenNote, renameTarget],
[onNavigate, onOpenNote, renameTarget],
)
const beginRename = useCallback((item: TreeNode) => {
@ -295,7 +304,7 @@ export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreate
<div className="flex min-w-0 items-center gap-1 text-sm">
<button
type="button"
onClick={() => setCurrentPath(WORKSPACE_ROOT)}
onClick={() => onNavigate(WORKSPACE_ROOT)}
className={cn(
'inline-flex items-center gap-1.5 rounded-md px-2 py-1 transition-colors',
isRoot ? 'text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-accent',
@ -316,7 +325,7 @@ export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreate
) : (
<button
type="button"
onClick={() => setCurrentPath(crumb.path)}
onClick={() => onNavigate(crumb.path)}
className="rounded-md px-2 py-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground truncate"
>
{crumb.name}
@ -326,31 +335,42 @@ export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreate
)
})}
</div>
{isRoot ? (
<Button size="sm" onClick={() => setAddOpen(true)}>
<Plus className="size-4" />
Add workspace
<div className="grid shrink-0 grid-cols-2 items-center gap-2">
<Button
size="sm"
variant="outline"
className="w-full"
onClick={() => actions.revealInFileManager(currentPath, true)}
>
<FolderOpen className="size-4" />
Open in {fileManagerName}
</Button>
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm">
<Plus className="size-4" />
Add
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => filesInputRef.current?.click()}>
<FilePlus className="mr-2 size-4" />
Add files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => folderInputRef.current?.click()}>
<FolderPlus className="mr-2 size-4" />
Add folder
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
{isRoot ? (
<Button size="sm" className="w-full" onClick={() => setAddOpen(true)}>
<Plus className="size-4" />
Add workspace
</Button>
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm" className="w-full">
<Plus className="size-4" />
Add
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => filesInputRef.current?.click()}>
<FilePlus className="mr-2 size-4" />
Add files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => folderInputRef.current?.click()}>
<FolderPlus className="mr-2 size-4" />
Add folder
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
<input
ref={filesInputRef}
@ -429,31 +449,56 @@ export function WorkspaceView({ tree, initialPath, actions, onOpenNote, onCreate
) : (
<div className="truncate text-sm font-medium">{item.name}</div>
)}
{item.kind === 'dir' && !isRenaming && (
<div className="text-xs text-muted-foreground">
{childCount} {childCount === 1 ? 'item' : 'items'}
{!isRenaming && (
<div className="truncate text-xs text-muted-foreground">
{item.kind === 'dir'
? `${childCount} ${childCount === 1 ? 'item' : 'items'}`
: fileExtensionLabel(item.name)}
</div>
)}
</div>
</button>
)
const isDir = item.kind === 'dir'
return (
<ContextMenu key={item.path}>
<ContextMenuTrigger asChild>{card}</ContextMenuTrigger>
<ContextMenuContent className="w-48">
<ContextMenuItem onClick={() => beginRename(item)}>
<Pencil className="mr-2 size-4" />
Rename
</ContextMenuItem>
<ContextMenuContent className="w-48" onCloseAutoFocus={(e) => e.preventDefault()}>
{isDir && (
<>
<ContextMenuItem onClick={() => actions.createNote(item.path)}>
<FilePlus className="mr-2 size-4" />
New Note
</ContextMenuItem>
<ContextMenuItem onClick={() => void actions.createFolder(item.path)}>
<FolderPlus className="mr-2 size-4" />
New Folder
</ContextMenuItem>
<ContextMenuSeparator />
</>
)}
{!isDir && actions.onOpenInNewTab && (
<>
<ContextMenuItem onClick={() => actions.onOpenInNewTab!(item.path)}>
<ExternalLink className="mr-2 size-4" />
Open in new tab
</ContextMenuItem>
<ContextMenuSeparator />
</>
)}
<ContextMenuItem onClick={() => { actions.copyPath(item.path); toast('Path copied', 'success') }}>
<Copy className="mr-2 size-4" />
Copy Path
</ContextMenuItem>
<ContextMenuItem onClick={() => actions.revealInFileManager(item.path, item.kind === 'dir')}>
<ContextMenuItem onClick={() => actions.revealInFileManager(item.path, isDir)}>
<FolderOpen className="mr-2 size-4" />
Show in {fileManagerName}
Open in {fileManagerName}
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onClick={() => beginRename(item)}>
<Pencil className="mr-2 size-4" />
Rename
</ContextMenuItem>
<ContextMenuItem variant="destructive" onClick={() => void handleDelete(item)}>
<Trash2 className="mr-2 size-4" />
Delete

View file

@ -3,16 +3,32 @@
import * as React from "react"
export type Theme = "light" | "dark" | "system"
export type ChatPanePlacement = "right" | "middle"
export type ChatPaneSize = "chat-smaller" | "chat-equal" | "chat-bigger"
type ThemeContextProps = {
theme: Theme
resolvedTheme: "light" | "dark"
setTheme: (theme: Theme) => void
chatPanePlacement: ChatPanePlacement
setChatPanePlacement: (placement: ChatPanePlacement) => void
chatPaneSize: ChatPaneSize
setChatPaneSize: (size: ChatPaneSize) => void
}
const ThemeContext = React.createContext<ThemeContextProps | null>(null)
const STORAGE_KEY = "rowboat-theme"
const CHAT_PANE_PLACEMENT_STORAGE_KEY = "rowboat-chat-pane-placement"
const CHAT_PANE_SIZE_STORAGE_KEY = "rowboat-chat-pane-size"
function isChatPanePlacement(value: string | null): value is ChatPanePlacement {
return value === "right" || value === "middle"
}
function isChatPaneSize(value: string | null): value is ChatPaneSize {
return value === "chat-smaller" || value === "chat-equal" || value === "chat-bigger"
}
function getSystemTheme(): "light" | "dark" {
if (typeof window === "undefined") return "light"
@ -39,6 +55,16 @@ export function ThemeProvider({
const stored = localStorage.getItem(STORAGE_KEY) as Theme | null
return stored || defaultTheme
})
const [chatPanePlacement, setChatPanePlacementState] = React.useState<ChatPanePlacement>(() => {
if (typeof window === "undefined") return "right"
const stored = localStorage.getItem(CHAT_PANE_PLACEMENT_STORAGE_KEY)
return isChatPanePlacement(stored) ? stored : "right"
})
const [chatPaneSize, setChatPaneSizeState] = React.useState<ChatPaneSize>(() => {
if (typeof window === "undefined") return "chat-smaller"
const stored = localStorage.getItem(CHAT_PANE_SIZE_STORAGE_KEY)
return isChatPaneSize(stored) ? stored : "chat-smaller"
})
const [resolvedTheme, setResolvedTheme] = React.useState<"light" | "dark">(() => {
if (theme === "system") return getSystemTheme()
@ -76,13 +102,27 @@ export function ThemeProvider({
setThemeState(newTheme)
}, [])
const setChatPanePlacement = React.useCallback((placement: ChatPanePlacement) => {
localStorage.setItem(CHAT_PANE_PLACEMENT_STORAGE_KEY, placement)
setChatPanePlacementState(placement)
}, [])
const setChatPaneSize = React.useCallback((size: ChatPaneSize) => {
localStorage.setItem(CHAT_PANE_SIZE_STORAGE_KEY, size)
setChatPaneSizeState(size)
}, [])
const contextValue = React.useMemo<ThemeContextProps>(
() => ({
theme,
resolvedTheme,
setTheme,
chatPanePlacement,
setChatPanePlacement,
chatPaneSize,
setChatPaneSize,
}),
[theme, resolvedTheme, setTheme]
[theme, resolvedTheme, setTheme, chatPanePlacement, setChatPanePlacement, chatPaneSize, setChatPaneSize]
)
return (

View file

@ -1,5 +1,6 @@
import { useEffect } from 'react'
import posthog from 'posthog-js'
import { identifyUser, resetAnalyticsIdentity } from '@/lib/analytics'
/**
* Identifies the user in PostHog when signed into Rowboat,
@ -17,7 +18,7 @@ export function useAnalyticsIdentity() {
// Identify if Rowboat account is connected
const rowboat = config.rowboat
if (rowboat?.connected && rowboat?.userId) {
posthog.identify(rowboat.userId)
identifyUser(rowboat.userId)
}
// Set provider connection flags
@ -69,7 +70,7 @@ export function useAnalyticsIdentity() {
// Rowboat sign-in
if (event.success) {
if (event.userId) {
posthog.identify(event.userId)
identifyUser(event.userId)
}
posthog.people.set({ signed_in: true, rowboat_connected: true })
posthog.capture('user_signed_in')
@ -80,7 +81,7 @@ export function useAnalyticsIdentity() {
// future events on this device don't get attributed to the prior user.
posthog.people.set({ signed_in: false, rowboat_connected: false })
posthog.capture('user_signed_out')
posthog.reset()
resetAnalyticsIdentity()
})
return cleanup

View file

@ -1,5 +1,42 @@
import posthog from 'posthog-js'
let appVersion: string | undefined
let apiUrl: string | undefined
function appVersionProperties(): Record<string, string> {
return appVersion ? { app_version: appVersion } : {}
}
export function configureAnalyticsContext(props: { appVersion?: string; apiUrl?: string }) {
appVersion = props.appVersion?.trim() || undefined
apiUrl = props.apiUrl?.trim() || undefined
const eventProperties = appVersionProperties()
if (Object.keys(eventProperties).length > 0) {
posthog.register(eventProperties)
}
const personProperties = {
...(apiUrl ? { api_url: apiUrl } : {}),
...eventProperties,
}
if (Object.keys(personProperties).length > 0) {
posthog.people.set(personProperties)
}
}
export function identifyUser(userId: string, properties?: Record<string, unknown>) {
posthog.identify(userId, {
...properties,
...appVersionProperties(),
})
}
export function resetAnalyticsIdentity() {
posthog.reset()
configureAnalyticsContext({ appVersion, apiUrl })
}
export function chatSessionCreated(runId: string) {
posthog.capture('chat_session_created', { run_id: runId })
}

View file

@ -1,7 +1,8 @@
import type { ToolUIPart } from 'ai'
import z from 'zod'
import { AskHumanRequestEvent, ToolPermissionRequestEvent } from '@x/shared/src/runs.js'
import { AskHumanRequestEvent, ToolPermissionAutoDecisionEvent, ToolPermissionRequestEvent } from '@x/shared/src/runs.js'
import { COMPOSIO_DISPLAY_NAMES } from '@x/shared/src/composio.js'
import type { CodeRunEvent, PermissionAsk } from '@x/shared/src/code-mode.js'
export interface MessageAttachment {
path: string
@ -27,6 +28,9 @@ export interface ToolCall {
streamingOutput?: string
status: 'pending' | 'running' | 'completed' | 'error'
timestamp: number
// code_agent_run only: structured ACP stream items + the in-flight permission ask.
codeRunEvents?: CodeRunEvent[]
pendingCodePermission?: { requestId: string; ask: PermissionAsk } | null
}
export interface ErrorMessage {
@ -46,6 +50,7 @@ export type ChatTabViewState = {
pendingAskHumanRequests: Map<string, z.infer<typeof AskHumanRequestEvent>>
allPermissionRequests: Map<string, z.infer<typeof ToolPermissionRequestEvent>>
permissionResponses: Map<string, PermissionResponse>
autoPermissionDecisions: Map<string, z.infer<typeof ToolPermissionAutoDecisionEvent>>
}
export type ChatViewportAnchorState = {
@ -60,6 +65,7 @@ export const createEmptyChatTabViewState = (): ChatTabViewState => ({
pendingAskHumanRequests: new Map(),
allPermissionRequests: new Map(),
permissionResponses: new Map(),
autoPermissionDecisions: new Map(),
})
export type ToolState = 'input-streaming' | 'input-available' | 'output-available' | 'output-error'
@ -600,6 +606,7 @@ export const isToolGroup = (item: GroupedConversationItem): item is ToolGroup =>
const isPlainToolCall = (item: ConversationItem): item is ToolCall => {
if (!isToolCall(item)) return false
if (item.name === 'code_agent_run') return false // rich standalone block, never grouped
if (getWebSearchCardData(item)) return false
if (getComposioConnectCardData(item)) return false
if (getAppActionCardData(item)) return false
@ -653,6 +660,63 @@ export const getToolGroupSummary = (tools: ToolCall[]): string => {
return names.join(' · ')
}
// Past-tense action phrases for summarizing a finished tool group, e.g.
// "read 3 files, listed directory". Keyed by builtin tool name.
const TOOL_ACTION_VERBS: Record<string, { verb: string; one: string; many: string }> = {
'file-readText': { verb: 'read', one: 'file', many: 'files' },
'file-writeText': { verb: 'wrote', one: 'file', many: 'files' },
'file-editText': { verb: 'edited', one: 'file', many: 'files' },
'file-list': { verb: 'listed', one: 'directory', many: 'directories' },
'file-exists': { verb: 'checked', one: 'path', many: 'paths' },
'file-stat': { verb: 'inspected', one: 'file', many: 'files' },
'file-glob': { verb: 'searched for', one: 'file', many: 'files' },
'file-grep': { verb: 'searched', one: 'file', many: 'files' },
'file-mkdir': { verb: 'created', one: 'directory', many: 'directories' },
'file-rename': { verb: 'renamed', one: 'file', many: 'files' },
'file-copy': { verb: 'copied', one: 'file', many: 'files' },
'file-remove': { verb: 'removed', one: 'file', many: 'files' },
'file-getRoot': { verb: 'resolved', one: 'file root', many: 'file roots' },
'executeCommand': { verb: 'ran', one: 'command', many: 'commands' },
'executeMcpTool': { verb: 'ran', one: 'MCP tool', many: 'MCP tools' },
'listMcpServers': { verb: 'listed', one: 'MCP server', many: 'MCP servers' },
'listMcpTools': { verb: 'listed', one: 'MCP tool', many: 'MCP tools' },
'save-to-memory': { verb: 'saved', one: 'memory', many: 'memories' },
'loadSkill': { verb: 'loaded', one: 'skill', many: 'skills' },
'parseFile': { verb: 'parsed', one: 'file', many: 'files' },
}
// Summarize what a group of tools actually did, grouping identical actions
// and counting them: "read 3 files, listed directory". Unmapped tools fall
// back to their lowercased display name.
export const getToolActionsSummary = (tools: ToolCall[]): string => {
const order: string[] = []
const grouped = new Map<string, { phrase: typeof TOOL_ACTION_VERBS[string] | null; count: number; fallback: string }>()
for (const tool of tools) {
const phrase = TOOL_ACTION_VERBS[tool.name] ?? null
const key = phrase ? `${phrase.verb}|${phrase.one}` : tool.name
const existing = grouped.get(key)
if (existing) {
existing.count++
} else {
grouped.set(key, { phrase, count: 1, fallback: getToolDisplayName(tool) })
order.push(key)
}
}
const phrases = order.map((key) => {
const { phrase, count, fallback } = grouped.get(key)!
if (!phrase) return fallback.toLowerCase()
if (count > 1) return `${phrase.verb} ${count} ${phrase.many}`
const article = /^[aeiou]/i.test(phrase.one) ? 'an' : 'a'
return `${phrase.verb} ${article} ${phrase.one}`
})
// Show at most two operations; collapse the rest into "more...".
const MAX_ACTIONS = 2
if (phrases.length > MAX_ACTIONS) {
return `${phrases.slice(0, MAX_ACTIONS).join(', ')}, more...`
}
return phrases.join(', ')
}
export const inferRunTitleFromMessage = (content: string): string | undefined => {
const { message } = parseAttachedFiles(content)
const normalized = message.replace(/\s+/g, ' ').trim()

View file

@ -6,7 +6,7 @@
* also uses it to decide what to keep mounted.
*/
export type ViewerType = 'html' | 'image' | 'video' | 'audio' | 'pdf'
export type ViewerType = 'html' | 'image' | 'video' | 'audio' | 'pdf' | 'docx'
const VIEWER_BY_EXT: Record<string, ViewerType> = {
html: 'html',
@ -31,6 +31,7 @@ const VIEWER_BY_EXT: Record<string, ViewerType> = {
flac: 'audio',
aac: 'audio',
pdf: 'pdf',
docx: 'docx',
}
function extensionOf(path: string): string {

View file

@ -2,9 +2,10 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'
import type { CaptureResult } from 'posthog-js'
import { ThemeProvider } from '@/contexts/theme-context'
import { configureAnalyticsContext } from './lib/analytics'
// Fetch the stable installation ID from main so renderer + main share one
// PostHog distinct_id. Falls back to PostHog's auto-generated anonymous ID
@ -12,19 +13,36 @@ import { ThemeProvider } from '@/contexts/theme-context'
async function bootstrap() {
let installationId: string | undefined
let apiUrl: string | undefined
let appVersion: string | undefined
try {
const result = await window.ipc.invoke('analytics:bootstrap', null)
installationId = result.installationId
apiUrl = result.apiUrl
appVersion = result.appVersion
} catch (err) {
console.error('[Analytics] Failed to bootstrap from main:', err)
}
configureAnalyticsContext({ apiUrl, appVersion })
const options = {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
defaults: '2025-11-30',
defaults: '2025-11-30' as const,
...(installationId ? { bootstrap: { distinctID: installationId } } : {}),
} as const
before_send: (event: CaptureResult | null) => {
if (!event) return event
if (appVersion) {
event.properties = {
...event.properties,
app_version: appVersion,
}
}
return event
},
loaded: () => {
configureAnalyticsContext({ apiUrl, appVersion })
},
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
@ -36,11 +54,7 @@ async function bootstrap() {
</StrictMode>,
)
// Tag the active person record with api_url so anonymous users are also
// segmentable by environment.
if (apiUrl) {
posthog.people.set({ api_url: apiUrl })
}
// The loaded callback applies api_url/app_version once PostHog has initialized.
}
bootstrap()

View file

@ -11,6 +11,9 @@
"test:watch": "vitest"
},
"dependencies": {
"@agentclientprotocol/claude-agent-acp": "^0.39.0",
"@agentclientprotocol/codex-acp": "^0.0.44",
"@agentclientprotocol/sdk": "^0.22.1",
"@ai-sdk/anthropic": "^2.0.63",
"@ai-sdk/google": "^2.0.53",
"@ai-sdk/openai": "^2.0.91",

View file

@ -3,7 +3,7 @@ import fs from "fs";
import path from "path";
import { WorkDir } from "../config/config.js";
import { Agent, ToolAttachment } from "@x/shared/dist/agent.js";
import { AssistantContentPart, AssistantMessage, Message, MessageList, ProviderOptions, ToolCallPart, ToolMessage } from "@x/shared/dist/message.js";
import { AssistantContentPart, AssistantMessage, Message, MessageList, ProviderOptions, ToolCallPart, ToolMessage, UserMessageContext } from "@x/shared/dist/message.js";
import { LanguageModel, stepCountIs, streamText, tool, Tool, ToolSet } from "ai";
import { z } from "zod";
import { LlmStepStreamEvent } from "@x/shared/dist/llm-step-events.js";
@ -23,7 +23,7 @@ import { resolveProviderConfig } from "../models/defaults.js";
import { IAgentsRepo } from "./repo.js";
import { IMonotonicallyIncreasingIdGenerator } from "../application/lib/id-gen.js";
import { IBus } from "../application/lib/bus.js";
import { IMessageQueue } from "../application/lib/message-queue.js";
import { IMessageQueue, type MiddlePaneContext } from "../application/lib/message-queue.js";
import { IRunsRepo } from "../runs/repo.js";
import { IRunsLock } from "../runs/lock.js";
import { IAbortRegistry } from "../runs/abort-registry.js";
@ -36,6 +36,7 @@ import { getRaw as getLabelingAgentRaw } from "../knowledge/labeling_agent.js";
import { getRaw as getNoteTaggingAgentRaw } from "../knowledge/note_tagging_agent.js";
import { getRaw as getInlineTaskAgentRaw } from "../knowledge/inline_task_agent.js";
import { getRaw as getAgentNotesAgentRaw } from "../knowledge/agent_notes_agent.js";
import { classifyToolPermissions, type AutoPermissionCandidate } from "../security/auto-permission-classifier.js";
const AGENT_NOTES_DIR = path.join(WorkDir, 'knowledge', 'Agent Notes');
@ -235,6 +236,96 @@ function loadAgentNotesContext(): string | null {
return `# Agent Memory\n\n${sections.join('\n\n')}`;
}
function isCopilotLikeAgent(agentName: string | null | undefined): boolean {
return agentName === 'copilot' || agentName === 'rowboatx';
}
function formatCurrentDateTime(now: Date): string {
return now.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short',
});
}
function toUserMessageContextMiddlePane(middlePaneContext: MiddlePaneContext | null): z.infer<typeof UserMessageContext>['middlePane'] {
if (!middlePaneContext) {
return { kind: 'empty' };
}
if (middlePaneContext.kind === 'note') {
return {
kind: 'note',
path: middlePaneContext.path,
content: middlePaneContext.content,
};
}
return {
kind: 'browser',
url: middlePaneContext.url,
title: middlePaneContext.title,
};
}
function buildUserMessageContext({
agentName,
middlePaneContext,
}: {
agentName: string | null | undefined;
middlePaneContext: MiddlePaneContext | null;
}): z.infer<typeof UserMessageContext> {
return {
currentDateTime: formatCurrentDateTime(new Date()),
...(isCopilotLikeAgent(agentName)
? { middlePane: toUserMessageContextMiddlePane(middlePaneContext) }
: {}),
};
}
function formatUserMessageContextForLlm(userMessageContext: z.infer<typeof UserMessageContext>): string {
const sections: string[] = [];
if (userMessageContext.currentDateTime) {
sections.push(`Current date and time: ${userMessageContext.currentDateTime}`);
}
if (userMessageContext.middlePane) {
if (userMessageContext.middlePane.kind === 'empty') {
sections.push(`Middle pane:\nState: empty`);
} else if (userMessageContext.middlePane.kind === 'note') {
sections.push(`Middle pane:\nState: note\nPath: ${userMessageContext.middlePane.path}\n\nContent:\n\`\`\`\n${userMessageContext.middlePane.content}\n\`\`\``);
} else {
sections.push(`Middle pane:\nState: browser\nURL: ${userMessageContext.middlePane.url}\nTitle: ${userMessageContext.middlePane.title}`);
}
}
if (sections.length === 0) {
return '';
}
return `# User Context
${sections.join('\n\n')}
# User Message
`;
}
const USER_CONTEXT_SYSTEM_INSTRUCTIONS = `# Hidden User Context
User messages may include a hidden "# User Context" section before "# User Message". Treat it as runtime metadata captured when that specific user message was sent. The actual user-authored text starts under "# User Message".
Use "Current date and time" for temporal reasoning.
If Middle pane context is present, it reflects what the user had open at the time of that specific message and overrides earlier middle-pane references. If the conversation history references a different note or browser page, the user had since closed or navigated away from it. Do not treat earlier context as current.
If Middle pane state is empty, the user was not looking at any relevant note or web page at that point. Answer the user's message on its own merits.
If Middle pane state is note, the supplied path and content are available so you can reference the note when relevant. The user may or may not be talking about this note. Do NOT assume every message is about it. Only reference or act on this note when the user's message clearly relates to it, such as "this note", "what I'm looking at", "here", "above", "below", or questions whose subject is plainly the note's content. For unrelated questions, ignore this note entirely and answer normally. Do not mention that you can see this note unless it is relevant to the answer.
If Middle pane state is browser, only the URL and page title are supplied; the page content itself is NOT included. If you need the page content to answer, use the browser tools available to you to read the page. The user may or may not be talking about this page. Only reference or act on this page when the user's message clearly relates to it, such as "this page", "this article", "what I'm looking at", "this site", or "summarize this". For unrelated questions, ignore this page entirely and answer normally. Do not mention that you can see the browser unless it is relevant to the answer.`;
export interface IAgentRuntime {
trigger(runId: string): Promise<void>;
}
@ -392,9 +483,10 @@ export async function mapAgentTool(t: z.infer<typeof ToolAttachment>): Promise<T
case "builtin": {
if (t.name === "ask-human") {
return tool({
description: "Ask a human before proceeding",
description: "Ask a human before proceeding. Optionally pass `options` (an array of short button labels) to render the question as a one-click choice; the user's response will be the chosen label verbatim.",
inputSchema: z.object({
question: z.string().describe("The question to ask the human"),
options: z.array(z.string()).optional().describe("Optional short button labels (2-4 recommended). If provided, the user picks one with a single click instead of typing. The response you receive will be the chosen label."),
}),
});
}
@ -721,17 +813,18 @@ export function convertFromMessages(messages: z.infer<typeof Message>[]): ModelM
providerOptions,
});
break;
case "user":
case "user": {
const userMessageContextPrefix = msg.userMessageContext ? formatUserMessageContextForLlm(msg.userMessageContext) : '';
if (typeof msg.content === 'string') {
// Legacy string — pass through unchanged
result.push({
role: "user",
content: msg.content,
content: `${userMessageContextPrefix}${msg.content}`,
providerOptions,
});
} else {
// New content parts array — collapse to text for LLM
const textSegments: string[] = [];
const textSegments: string[] = userMessageContextPrefix ? [userMessageContextPrefix] : [];
const attachmentLines: string[] = [];
for (const part of msg.content) {
@ -745,7 +838,11 @@ export function convertFromMessages(messages: z.infer<typeof Message>[]): ModelM
}
if (attachmentLines.length > 0) {
textSegments.unshift("User has attached the following files:", ...attachmentLines, "");
if (userMessageContextPrefix) {
textSegments.push("User has attached the following files:", ...attachmentLines, "");
} else {
textSegments.unshift("User has attached the following files:", ...attachmentLines, "");
}
}
result.push({
@ -755,6 +852,7 @@ export function convertFromMessages(messages: z.infer<typeof Message>[]): ModelM
});
}
break;
}
case "tool":
result.push({
role: "tool",
@ -804,6 +902,7 @@ export class AgentState {
agentName: string | null = null;
runModel: string | null = null;
runProvider: string | null = null;
permissionMode: "manual" | "auto" = "manual";
runUseCase: UseCase | null = null;
runSubUseCase: string | null = null;
messages: z.infer<typeof MessageList> = [];
@ -815,6 +914,8 @@ export class AgentState {
pendingAskHumanRequests: Record<string, z.infer<typeof AskHumanRequestEvent>> = {};
allowedToolCallIds: Record<string, true> = {};
deniedToolCallIds: Record<string, true> = {};
autoAllowedToolCalls: Record<string, { reason: string }> = {};
autoDeniedToolCalls: Record<string, { reason: string }> = {};
sessionAllowedCommands: Set<string> = new Set();
sessionAllowedFileAccess: FileAccessGrant[] = [];
@ -922,6 +1023,7 @@ export class AgentState {
this.agentName = event.agentName;
this.runModel = event.model;
this.runProvider = event.provider;
this.permissionMode = event.permissionMode ?? "manual";
this.runUseCase = event.useCase ?? null;
this.runSubUseCase = event.subUseCase ?? null;
break;
@ -934,6 +1036,7 @@ export class AgentState {
this.subflowStates[event.toolCallId].agentName = event.agentName;
this.subflowStates[event.toolCallId].runModel = this.runModel;
this.subflowStates[event.toolCallId].runProvider = this.runProvider;
this.subflowStates[event.toolCallId].permissionMode = this.permissionMode;
this.subflowStates[event.toolCallId].runUseCase = this.runUseCase;
this.subflowStates[event.toolCallId].runSubUseCase = this.runSubUseCase;
break;
@ -984,10 +1087,22 @@ export class AgentState {
break;
case "deny":
this.deniedToolCallIds[event.toolCallId] = true;
delete this.autoDeniedToolCalls[event.toolCallId];
break;
}
delete this.pendingToolPermissionRequests[event.toolCallId];
break;
case "tool-permission-auto-decision":
switch (event.decision) {
case "allow":
this.allowedToolCallIds[event.toolCallId] = true;
this.autoAllowedToolCalls[event.toolCallId] = { reason: event.reason };
break;
case "deny":
this.autoDeniedToolCalls[event.toolCallId] = { reason: event.reason };
break;
}
break;
case "ask-human-request":
this.pendingAskHumanRequests[event.toolCallId] = event;
break;
@ -1065,6 +1180,7 @@ export async function* streamAgent({
let voiceInput = false;
let voiceOutput: 'summary' | 'full' | null = null;
let searchEnabled = false;
let codeMode: 'claude' | 'codex' | null = null;
let middlePaneContext:
| { kind: 'note'; path: string; content: string }
| { kind: 'browser'; url: string; title: string }
@ -1092,13 +1208,19 @@ export async function* streamAgent({
// if tool has been denied, deny
if (state.deniedToolCallIds[toolCallId]) {
_logger.log('returning denied tool message, reason: tool has been denied');
const autoDenied = state.autoDeniedToolCalls[toolCallId];
yield* processEvent({
runId,
messageId: await idGenerator.next(),
type: "message",
message: {
role: "tool",
content: "Unable to execute this tool: Permission was denied.",
content: autoDenied
? JSON.stringify({
success: false,
error: `Auto-permission denied: ${autoDenied.reason}`,
})
: "Unable to execute this tool: Permission was denied.",
toolCallId: toolCallId,
toolName: toolCall.toolName,
},
@ -1157,6 +1279,7 @@ export async function* streamAgent({
signal,
abortRegistry,
publish: (event) => bus.publish(event),
codeMode,
});
}
} catch (error) {
@ -1213,6 +1336,9 @@ export async function* streamAgent({
if (msg.searchEnabled) {
searchEnabled = true;
}
// Code mode is per-message: latest message decides whether the assistant
// should route coding work through the code-with-agents skill / chosen agent.
codeMode = msg.codeMode ?? null;
if (msg.voiceOutput) {
voiceOutput = msg.voiceOutput;
}
@ -1220,6 +1346,10 @@ export async function* streamAgent({
// latest user message. If the user closed the pane between messages, clear it.
middlePaneContext = msg.middlePaneContext ?? null;
loopLogger.log('dequeued user message', msg.messageId);
const userMessageContext = buildUserMessageContext({
agentName: state.agentName,
middlePaneContext,
});
yield* processEvent({
runId,
type: "message",
@ -1227,6 +1357,7 @@ export async function* streamAgent({
message: {
role: "user",
content: msg.message,
userMessageContext,
},
subflow: [],
});
@ -1248,17 +1379,7 @@ export async function* streamAgent({
loopLogger.log('running llm turn');
// stream agent response and build message
const messageBuilder = new StreamStepMessageBuilder();
const now = new Date();
const currentDateTime = now.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short'
});
let instructionsWithDateTime = `Current date and time: ${currentDateTime}\n\n${agent.instructions}`;
let instructionsWithDateTime = `${agent.instructions}\n\n${USER_CONTEXT_SYSTEM_INSTRUCTIONS}`;
// Inject Agent Notes context for copilot
if (state.agentName === 'copilot' || state.agentName === 'rowboatx') {
const agentNotesContext = loadAgentNotesContext();
@ -1287,19 +1408,6 @@ Use absolute paths rooted at this directory with the \`file-*\` tools. For examp
Do not announce the work directory unless it's relevant. Just use it.`;
}
// Always inject a Middle Pane section so the LLM has a clear, up-to-date signal
// that supersedes any earlier middle-pane mention in the conversation history.
const middlePaneHeader = `\n\n# Middle Pane (Current State)\nThis section reflects what the user has open in the middle pane RIGHT NOW, at the time of their latest message. **This is authoritative and overrides any earlier mention of a note or web page in this conversation** — if the conversation history references a different note or browser page, the user has since closed or navigated away from it. Do not treat earlier context as current.\n\n`;
if (!middlePaneContext) {
loopLogger.log('injecting middle pane context (empty)');
instructionsWithDateTime += `${middlePaneHeader}**Nothing relevant is open in the middle pane right now.** The user is not looking at any note or web page. If earlier in this conversation you referenced a note or browser page as "what the user is viewing", that is no longer accurate — do not refer to it as currently open. Answer the user's latest message on its own merits.`;
} else if (middlePaneContext.kind === 'note') {
loopLogger.log('injecting middle pane context (note)', middlePaneContext.path);
instructionsWithDateTime += `${middlePaneHeader}The user has a note open. Its path and full content are provided below so you can reference it when relevant.\n\n**How to use this context:**\n- The user may or may not be talking about this note. Do NOT assume every message is about it.\n- Only reference or act on this note when the user's message clearly relates to it (e.g. "this note", "what I'm looking at", "here", "above", "below", or questions whose subject is plainly this note's content).\n- For unrelated questions (general chat, questions about other notes, tasks, emails, calendar, etc.), ignore this context entirely and answer normally.\n- Do not mention that you can see this note unless it is relevant to the answer.\n\n## Open note path\n${middlePaneContext.path}\n\n## Open note content\n\`\`\`\n${middlePaneContext.content}\n\`\`\``;
} else if (middlePaneContext.kind === 'browser') {
loopLogger.log('injecting middle pane context (browser)', middlePaneContext.url);
instructionsWithDateTime += `${middlePaneHeader}The user has the embedded browser open and is viewing a web page. Only the URL and page title are shown below — the page content itself is NOT included here. If you need the page content to answer, use the browser tools available to you to read the page.\n\n**How to use this context:**\n- The user may or may not be talking about this page. Do NOT assume every message is about it.\n- Only reference or act on this page when the user's message clearly relates to it (e.g. "this page", "this article", "what I'm looking at", "this site", "summarize this").\n- For unrelated questions (general chat, questions about other notes, tasks, emails, calendar, etc.), ignore this context entirely and answer normally.\n- Do not mention that you can see the browser unless it is relevant to the answer.\n\n## Current page\nURL: ${middlePaneContext.url}\nTitle: ${middlePaneContext.title}`;
}
}
if (voiceInput) {
loopLogger.log('voice input enabled, injecting voice input prompt');
@ -1316,6 +1424,25 @@ Do not announce the work directory unless it's relevant. Just use it.`;
loopLogger.log('search enabled, injecting search prompt');
instructionsWithDateTime += `\n\n# Search\nThe user has requested a search. Use the web-search tool to answer their query.`;
}
if (codeMode) {
loopLogger.log('code mode enabled, injecting coding-agent context', codeMode);
const agentDisplay = codeMode === 'claude' ? 'Claude Code' : 'Codex';
instructionsWithDateTime += `\n\n# Code Mode (Active) — Agent: ${agentDisplay}
The user has turned on **code mode** and the composer chip is set to **${agentDisplay}** (\`${codeMode}\`). For EVERY coding task this turn, use **${agentDisplay}**, and narrate that agent ("Using ${agentDisplay} to …").
The chip is the single source of truth for which agent runs:
- Do NOT carry over a different agent from earlier in this thread even if a previous run used the other agent, use **${agentDisplay}** now.
- Do NOT switch agents based on an in-chat text request ("use codex", "switch to claude"). The agent only changes when the user toggles the chip; if they ask in chat, tell them to toggle the chip.
**How to run coding work call the \`code_agent_run\` tool** with:
- \`agent\`: \`${codeMode}\` (always — match the chip).
- \`cwd\`: the absolute project/working directory (resolve it per the code-with-agents skill — a path the user named, the "# User Work Directory" block, or ask once).
- \`prompt\`: a clear, self-contained coding instruction.
The tool runs the agent on-device and streams its tool calls, file diffs, and plan into the chat; any action needing approval surfaces as an inline permission card, so you do NOT pre-confirm with an in-chat "reply yes". This chat keeps ONE persistent agent session, so follow-up coding requests automatically resume with full context just call \`code_agent_run\` again. Do NOT shell out to \`acpx\` or \`executeCommand\` for coding, and do NOT fall back to your own file tools.
If the user's message is clearly NOT a coding request (small talk, an unrelated question), answer directly without invoking the coding agent. Code mode signals readiness, not that every message must route through the agent.`;
}
let streamError: string | null = null;
for await (const event of streamLlm(
model,
@ -1366,16 +1493,22 @@ Do not announce the work directory unless it's relevant. Just use it.`;
// if there were any ask-human calls, emit those events
if (message.content instanceof Array) {
const permissionCandidates: AutoPermissionCandidate[] = [];
for (const part of message.content) {
if (part.type === "tool-call") {
const underlyingTool = agent.tools![part.toolName];
if (underlyingTool.type === "builtin" && underlyingTool.name === "ask-human") {
loopLogger.log('emitting ask-human-request, toolCallId:', part.toolCallId);
const rawOptions = (part.arguments as { options?: unknown }).options;
const options = Array.isArray(rawOptions)
? rawOptions.filter((o): o is string => typeof o === 'string' && o.trim().length > 0)
: undefined;
yield* processEvent({
runId,
type: "ask-human-request",
toolCallId: part.toolCallId,
query: part.arguments.question,
...(options && options.length > 0 ? { options } : {}),
subflow: [],
});
}
@ -1386,14 +1519,7 @@ Do not announce the work directory unless it's relevant. Just use it.`;
state.sessionAllowedFileAccess,
);
if (permission) {
loopLogger.log('emitting tool-permission-request, toolCallId:', part.toolCallId);
yield* processEvent({
runId,
type: "tool-permission-request",
toolCall: part,
permission,
subflow: [],
});
permissionCandidates.push({ toolCall: part, permission });
}
if (underlyingTool.type === "agent" && underlyingTool.name) {
loopLogger.log('emitting spawn-subflow, toolCallId:', part.toolCallId);
@ -1417,6 +1543,87 @@ Do not announce the work directory unless it's relevant. Just use it.`;
}
}
}
if (permissionCandidates.length > 0) {
if (state.permissionMode === "auto") {
let decisionsByToolCallId = new Map<string, { decision: "allow" | "deny"; reason: string }>();
try {
const decisions = await classifyToolPermissions({
runId,
agentName: state.agentName,
messages: convertFromMessages(state.messages),
candidates: permissionCandidates,
useCase: state.runUseCase ?? "copilot_chat",
subUseCase: state.runSubUseCase,
});
decisionsByToolCallId = new Map(decisions.map((decision) => [
decision.toolCallId,
{ decision: decision.decision, reason: decision.reason },
]));
} catch (error) {
loopLogger.log(
'auto-permission classifier failed:',
error instanceof Error ? error.message : String(error),
);
}
for (const candidate of permissionCandidates) {
const decision = decisionsByToolCallId.get(candidate.toolCall.toolCallId);
if (!decision) {
loopLogger.log('auto-permission missing decision, falling back to prompt:', candidate.toolCall.toolCallId);
yield* processEvent({
runId,
type: "tool-permission-request",
toolCall: candidate.toolCall,
permission: candidate.permission,
subflow: [],
});
continue;
}
loopLogger.log(
'emitting tool-permission-auto-decision, toolCallId:',
candidate.toolCall.toolCallId,
'decision:',
decision.decision,
);
yield* processEvent({
runId,
type: "tool-permission-auto-decision",
toolCallId: candidate.toolCall.toolCallId,
toolCall: candidate.toolCall,
permission: candidate.permission,
decision: decision.decision,
reason: decision.reason,
subflow: [],
});
if (decision.decision === "deny") {
loopLogger.log(
'auto-permission denied, falling back to prompt:',
candidate.toolCall.toolCallId,
);
yield* processEvent({
runId,
type: "tool-permission-request",
toolCall: candidate.toolCall,
permission: candidate.permission,
subflow: [],
});
}
}
} else {
for (const candidate of permissionCandidates) {
loopLogger.log('emitting tool-permission-request, toolCallId:', candidate.toolCall.toolCallId);
yield* processEvent({
runId,
type: "tool-permission-request",
toolCall: candidate.toolCall,
permission: candidate.permission,
subflow: [],
});
}
}
}
}
}
}

View file

@ -6,6 +6,7 @@ import { API_URL } from '../config/env.js';
// In dev/tsc, fall back to process.env so local runs work too.
const POSTHOG_KEY = process.env.POSTHOG_KEY ?? process.env.VITE_PUBLIC_POSTHOG_KEY ?? '';
const POSTHOG_HOST = process.env.POSTHOG_HOST ?? process.env.VITE_PUBLIC_POSTHOG_HOST ?? 'https://us.i.posthog.com';
const APP_VERSION = (process.env.ROWBOAT_APP_VERSION ?? process.env.npm_package_version ?? '').trim();
let client: PostHog | null = null;
let initAttempted = false;
@ -29,7 +30,7 @@ function getClient(): PostHog | null {
// distinguishes prod / staging / custom — meaning is assigned in PostHog).
client.identify({
distinctId: getInstallationId(),
properties: { api_url: API_URL },
properties: { api_url: API_URL, ...appVersionProperties() },
});
} catch (err) {
console.error('[Analytics] Failed to init PostHog:', err);
@ -42,6 +43,10 @@ function activeDistinctId(): string {
return identifiedUserId ?? getInstallationId();
}
function appVersionProperties(): Record<string, string> {
return APP_VERSION ? { app_version: APP_VERSION } : {};
}
export function capture(event: string, properties?: Record<string, unknown>): void {
const ph = getClient();
if (!ph) return;
@ -49,7 +54,10 @@ export function capture(event: string, properties?: Record<string, unknown>): vo
ph.capture({
distinctId: activeDistinctId(),
event,
properties,
properties: {
...properties,
...appVersionProperties(),
},
});
} catch (err) {
console.error('[Analytics] capture failed:', err);
@ -68,6 +76,7 @@ export function identify(userId: string, properties?: Record<string, unknown>):
properties: {
...properties,
api_url: API_URL,
...appVersionProperties(),
},
});
identifiedUserId = userId;

View file

@ -3,6 +3,8 @@ import { getRuntimeContext, getRuntimeContextPrompt } from "./runtime-context.js
import { composioAccountsRepo } from "../../composio/repo.js";
import { isConfigured as isComposioConfigured } from "../../composio/client.js";
import { CURATED_TOOLKITS } from "@x/shared/dist/composio.js";
import container from "../../di/container.js";
import type { ICodeModeConfigRepo } from "../../code-mode/repo.js";
const runtimeContextPrompt = getRuntimeContextPrompt(getRuntimeContext());
@ -29,7 +31,7 @@ Load the \`composio-integration\` skill when the user asks to interact with any
`;
}
function buildStaticInstructions(composioEnabled: boolean, catalog: string): string {
function buildStaticInstructions(composioEnabled: boolean, catalog: string, codeModeEnabled: boolean = true): string {
// Conditionally include Composio-related instruction sections
const emailDraftSuffix = composioEnabled
? ` Do NOT load this skill for reading, fetching, or checking emails — use the \`composio-integration\` skill for that instead.`
@ -80,7 +82,9 @@ ${thirdPartyBlock}**Meeting Prep:** When users ask you to prepare for a meeting,
**Document Collaboration:** When users ask you to work on a document, collaborate on writing, create a new document, edit/refine existing notes, or say things like "let's work on [X]", "help me write [X]", "create a doc for [X]", or "let's draft [X]", you MUST load the \`doc-collab\` skill first. **This applies even for small one-off edits** — the skill carries the canonical *terse-and-scannable* writing style for the knowledge base, and that style applies whether you're authoring a fresh note or fixing a single section. Load it before writing anything into a note.
**Code with Agents:** When users ask you to write code, build a project, create a script, fix a bug, or do any software development task, load the \`code-with-agents\` skill first. It provides guidance for delegating coding work to Claude Code or Codex via acpx.
${codeModeEnabled
? `**Code with Agents:** When users ask you to write code, build a project, create a script, fix a bug, or do any software development task — **including simple things like "create a .c file" or "write a hello-world in Python"** — your FIRST action MUST be \`loadSkill('code-with-agents')\`. Do NOT reach for \`executeCommand\` (PowerShell / bash / shell) or any workspace file tool to do code work yourself before loading this skill. The skill decides whether to delegate to Claude Code / Codex (via acpx) or hand control back to you, and it presents the user a one-click choice when needed. Paths outside the Rowboat workspace root (e.g. \`G:/...\`, \`~/projects/...\`) are NORMAL for coding tasks — do NOT raise "outside workspace" concerns or fall back to your own tools.`
: `**Code with Agents (disabled):** Code mode is currently OFF in the user's settings. Do NOT load \`code-with-agents\` and do NOT call acpx. Handle coding requests yourself with your normal tools if you can. After answering, add a final line letting the user know they can delegate coding to Claude Code or Codex by enabling Code Mode in Settings → Code Mode.`}
**App Control:** When users ask you to open notes, show the bases or graph view, filter or search notes, or manage saved views, load the \`app-navigation\` skill first. It provides structured guidance for navigating the app UI and controlling the knowledge base view.
@ -312,30 +316,29 @@ Never output raw file paths in plain text when they could be wrapped in a filepa
/** Keep backward-compatible export for any external consumers */
export const CopilotInstructions = buildStaticInstructions(true, skillCatalog);
/**
* Cached Composio instructions. Invalidated by calling invalidateCopilotInstructionsCache().
*/
let cachedInstructions: string | null = null;
/**
* Invalidate the cached instructions so the next buildCopilotInstructions() call
* regenerates the Composio section. Call this after connecting/disconnecting a toolkit.
*/
export function invalidateCopilotInstructionsCache(): void {
cachedInstructions = null;
}
/**
* Build full copilot instructions with dynamic Composio tools section.
* Results are cached and reused until invalidated via invalidateCopilotInstructionsCache().
*/
export async function buildCopilotInstructions(): Promise<string> {
if (cachedInstructions !== null) return cachedInstructions;
const composioEnabled = await isComposioConfigured();
const catalog = composioEnabled
? skillCatalog
: buildSkillCatalog({ excludeIds: ['composio-integration'] });
const baseInstructions = buildStaticInstructions(composioEnabled, catalog);
let codeModeEnabled = false;
try {
const repo = container.resolve<ICodeModeConfigRepo>('codeModeConfigRepo');
codeModeEnabled = (await repo.getConfig()).enabled;
} catch {
// repo unavailable — default to disabled
}
const excludeIds: string[] = [];
if (!composioEnabled) excludeIds.push('composio-integration');
if (!codeModeEnabled) excludeIds.push('code-with-agents');
const catalog = excludeIds.length > 0
? buildSkillCatalog({ excludeIds })
: skillCatalog;
const baseInstructions = buildStaticInstructions(composioEnabled, catalog, codeModeEnabled);
const composioPrompt = await getComposioToolsPrompt();
cachedInstructions = composioPrompt
? baseInstructions + '\n' + composioPrompt

View file

@ -1,90 +1,98 @@
export const skill = String.raw`
# Code with Agents Skill
Use this skill when the user asks you to write code, build a project, create scripts, fix bugs, or do any software development task that should be delegated to a coding agent (Claude Code or Codex).
Use this skill whenever the user asks you to write code, build a project, create scripts, fix bugs, read/explain code, or do any software development task even simple file creations like "make a .c file".
## Important: delegate ALL coding work
Coding agents operate on **arbitrary file paths** (including paths outside the Rowboat workspace root, like \`G:/4th sem/CN\` or \`~/projects/foo\`). Do NOT raise "outside workspace" concerns, and do NOT fall back to your own \`executeCommand\` (PowerShell / bash) or workspace file tools to do code work yourself.
Once the user has chosen to use Claude Code or Codex, you MUST delegate ALL code-related tasks to the coding agent. This includes:
- Writing, editing, or refactoring code
- Reading, summarizing, or explaining code
- Debugging and fixing bugs
- Running tests or build commands
- Exploring project structure
- Any other task that involves interacting with a codebase
All coding work runs through the **\`code_agent_run\`** tool. It launches the selected on-device coding agent (Claude Code / Codex), streams its tool calls, file diffs, and plan into the chat, and surfaces any action needing approval as an inline permission card. One persistent session is kept per chat, so follow-up requests resume with full context automatically.
Do NOT attempt to do any of these yourself no reading files, no running commands, no writing code. You are the coordinator; the coding agent does the work. Your job is to translate the user's request into a clear prompt and pass it to the agent.
---
## Prerequisites
## STEP 1 MANDATORY FIRST ACTION
The user must have one of the following installed on their machine:
- **Claude Code** https://claude.ai/code
- **Codex** https://codex.openai.com
Look in your **system context** for a section titled **"# Code Mode (Active)"**.
These are external tools that you cannot install for the user.
### Case A "# Code Mode (Active)" IS present
## Workflow
Code mode is on and the user has selected an agent. Skip directly to Step 2. Do NOT call ask-human.
### Step 1: Gather requirements
### Case B "# Code Mode (Active)" is NOT present
Before running anything, confirm the following with the user:
Your **very next tool call MUST be \`ask-human\`** with options. Do not write any explanation text first. Do not describe a plan. Do not check the workspace boundary. Just call:
1. **Working directory** Ask which folder the code should be written in, unless the user has already specified it. Example: "Which folder should I work in?"
2. **Agent choice** Ask whether to use **Claude Code** or **Codex**. Mention that the chosen agent must already be installed on their machine.
\`\`\`
ask-human({
question: "How should I handle this coding request?",
options: [
"Use code mode (Claude Code)",
"Use code mode (Codex)",
"Continue with default Rowboat"
]
})
\`\`\`
### Step 2: Confirm execution plan
This is non-negotiable. The user gets clickable buttons. Free-text "which agent?" questions are forbidden here.
Once you know the folder and agent, tell the user:
**Branch on the response:**
- "Use code mode (Claude Code)" proceed to Step 2 with agent = \`claude\`.
- "Use code mode (Codex)" proceed to Step 2 with agent = \`codex\`.
- "Continue with default Rowboat" ABANDON this skill. Handle the request yourself using your own tools (workspace file tools, \`executeCommand\` shell, etc.). The rest of this skill does not apply for this turn.
> I'll use [Claude Code / Codex] to [description of the task] in \`[folder]\`. Permission requests from the coding agent itself (file writes, command execution, etc.) will be automatically approved once it starts. Wait for the user's confirmation before you execute anything.
---
### Step 3: Execute with acpx
## STEP 2 Resolve workdir, then run
Use the \`executeCommand\` tool to run the coding agent via acpx. The command format is:
**Resolve the workdir** (in this priority order):
1. A path the user named in their original message (e.g. \`G:/4th sem/CN\`).
2. The path from a "# User Work Directory" block in your context.
3. Ask once in plain text: "Which folder should I work in?"
**For Claude Code:**
` + "`" + `
npx acpx@latest --approve-all --cwd <folder> claude exec "<prompt>"
` + "`" + `
**Pick the agent** (\`claude\` or \`codex\`): use the agent from the "# Code Mode (Active)" block (the composer chip) / the Step 1 choice. The chip is authoritative — do NOT carry over a different agent from earlier in this thread, and do NOT switch on an in-chat text request ("use codex"); tell the user to toggle the chip instead.
**For Codex:**
` + "`" + `
npx acpx@latest --approve-all --cwd <folder> codex exec "<prompt>"
` + "`" + `
**State your intent in one line, then call the tool immediately do NOT wait for a "yes".** The tool's own permission cards are the user's confirmation, so an extra in-chat "reply yes to proceed" is redundant friction. Say something like:
### Critical: flag order
> Using [Claude Code / Codex] to [task description] in \`[folder]\`.
The \`--approve-all\` and \`--cwd\` flags are global flags and MUST come before the agent name (\`claude\` or \`codex\`). This is the correct order:
and then immediately call:
` + "`" + `
npx acpx@latest [global flags] <agent> exec "<prompt>"
` + "`" + `
\`\`\`
code_agent_run({
agent: "<claude|codex>",
cwd: "<resolved absolute folder>",
prompt: "<clear, self-contained coding instruction>"
})
\`\`\`
**Correct:**
` + "`" + `
npx acpx@latest --approve-all --cwd ~/projects/myapp claude exec "fix the bug"
` + "`" + `
**Writing good prompts for the agent:**
- Be specific: file names, function signatures, expected behavior.
- Mention constraints (language, framework, style).
- Expand short user requests into clear, actionable instructions.
**Wrong (will fail):**
` + "`" + `
npx acpx@latest claude --approve-all exec "fix the bug"
` + "`" + `
**Follow-ups:** for every later coding request in this chat, just call \`code_agent_run\` again with the same \`cwd\` and the chip's current agent. The session resumes automatically — do NOT start over or re-explain prior context.
### Writing good prompts
---
When constructing the prompt for the coding agent:
- Be specific and detailed about what to build or fix
- Include file names, function signatures, and expected behavior
- Mention any constraints (language, framework, style)
- If the user gave you a short request, expand it into a clear, actionable prompt for the agent
## STEP 3 Report results
### Step 4: Report results
After \`code_agent_run\` returns:
- Pass through the agent's \`summary\` as-is. Do not rewrite it.
- Refer to file paths as plain text. Do NOT use \`\`\`file:path\`\`\` reference blocks. (This overrides the global "always wrap paths in filepath blocks" rule — for code-mode output, plain text.)
- Only add your own explanation if it failed:
- \`success: false\` with a message — surface the message. If it mentions the agent isn't installed or signed in, tell the user to install or sign in via **Settings → Code Mode**.
- \`stopReason: "cancelled"\` — the run was stopped; acknowledge briefly and ask if they want to continue.
After the command finishes, look for the summary that the coding agent produced at the end of its output and pass that along to the user as-is. Do not rewrite or add to it. Only add your own explanation if the command failed or the exit code is non-zero.
---
Do NOT use file reference blocks (e.g. \`\`\`file:path/to/file\`\`\`) when mentioning code files — they may not open correctly. Just refer to file paths as plain text.
## Once delegating: delegate fully
- If the exit code is 5, it means permissions were denied this should not happen with \`--approve-all\`, but if it does, let the user know
After Step 2 fires, delegate ALL related coding tasks for this turn to \`code_agent_run\` — writing, editing, reading, debugging, exploring structure, running tests. You are the coordinator; the agent does the work.
## Prerequisites (informational)
The user must have one of these installed locally these are external tools you cannot install:
- Claude Code https://claude.ai/code
- Codex https://codex.openai.com
`;
export default skill;

View file

@ -99,7 +99,7 @@ const definitions: SkillDefinition[] = [
{
id: "code-with-agents",
title: "Code with Agents",
summary: "Write code, build projects, create scripts, or fix bugs by delegating to Claude Code or Codex via acpx.",
summary: "Write code, build projects, create scripts, or fix bugs by delegating to Claude Code or Codex.",
content: codeWithAgentsSkill,
},
{

View file

@ -1,7 +1,6 @@
import { z, ZodType } from "zod";
import * as path from "path";
import * as fs from "fs/promises";
import { existsSync, readFileSync } from "fs";
import { executeCommand, executeCommandAbortable } from "./command-executor.js";
import { resolveSkill, availableSkills } from "../assistant/skills/index.js";
import { executeTool, listServers, listTools } from "../../mcp/mcp.js";
@ -16,6 +15,10 @@ import { executeAction as executeComposioAction, isConfigured as isComposioConfi
import { CURATED_TOOLKITS, CURATED_TOOLKIT_SLUGS } from "@x/shared/dist/composio.js";
import { BrowserControlInputSchema, type BrowserControlInput } from "@x/shared/dist/browser-control.js";
import { BackgroundTaskSchema, TriggersSchema } from "@x/shared/dist/background-task.js";
import type { CodeModeManager } from "../../code-mode/acp/manager.js";
import type { CodePermissionRegistry } from "../../code-mode/acp/permission-registry.js";
import { ICodeModeConfigRepo } from "../../code-mode/repo.js";
import type { ApprovalPolicy } from "@x/shared/dist/code-mode.js";
// Inputs for the bg-task builtin tools. Reuse the canonical schema field
// descriptions; only `triggers` gets a tighter contextual override (the
@ -90,43 +93,6 @@ const LLMPARSE_MIME_TYPES: Record<string, string> = {
'.tiff': 'image/tiff',
};
// Windows-only workaround: the Claude ACP bridge spawns CLAUDE_CODE_EXECUTABLE
// without `shell: true`, and Node refuses to spawn .cmd files that way (EINVAL).
// When the LLM invokes acpx via executeCommand, pre-resolve claude's real .exe
// from the npm-shim layout and inject it via env so the bridge can spawn it.
function resolveClaudeExeOnWindows(): string | undefined {
const pathDirs = (process.env.PATH ?? '').split(';');
for (const dir of pathDirs) {
const trimmed = dir.trim();
if (!trimmed) continue;
const cmdPath = path.join(trimmed, 'claude.cmd');
if (!existsSync(cmdPath)) continue;
const exeFromLayout = path.join(trimmed, 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe');
if (existsSync(exeFromLayout)) return exeFromLayout;
try {
const content = readFileSync(cmdPath, 'utf-8');
const absMatch = content.match(/[A-Z]:[\\/][^\s"]*claude\.exe/i);
if (absMatch && existsSync(absMatch[0])) return absMatch[0];
const relMatch = content.match(/%~dp0[\\/]?([^\s"%]+claude\.exe)/i);
if (relMatch) {
const resolved = path.join(trimmed, relMatch[1]);
if (existsSync(resolved)) return resolved;
}
} catch {
// ignore shim parse failures
}
}
return undefined;
}
function envForCommand(command: string): NodeJS.ProcessEnv | undefined {
if (process.platform !== 'win32') return undefined;
if (!/\bacpx\b/.test(command)) return undefined;
if (process.env.CLAUDE_CODE_EXECUTABLE) return undefined;
const exe = resolveClaudeExeOnWindows();
if (!exe) return undefined;
return { ...process.env, CLAUDE_CODE_EXECUTABLE: exe };
}
export const BuiltinTools: z.infer<typeof BuiltinToolsSchema> = {
loadSkill: {
@ -788,14 +754,11 @@ export const BuiltinTools: z.infer<typeof BuiltinToolsSchema> = {
// };
// }
const envOverride = envForCommand(command);
// Use abortable version when we have a signal
if (ctx?.signal) {
const { promise, process: proc } = executeCommandAbortable(command, {
cwd: workingDir,
signal: ctx.signal,
env: envOverride,
onData: (chunk: string) => {
ctx.publish({
runId: ctx.runId,
@ -845,6 +808,104 @@ export const BuiltinTools: z.infer<typeof BuiltinToolsSchema> = {
},
},
code_agent_run: {
description: 'Run a coding/software task with the selected on-device coding agent (Claude Code or Codex) inside a project folder. Streams the agent\'s tool calls, file diffs, and plan into the chat and surfaces permission requests inline. Use this for ALL code-mode work (writing/editing/reading code, running tests, debugging, exploring a repo). Reuses one persistent session per chat, so follow-up requests keep context.',
inputSchema: z.object({
agent: z.enum(['claude', 'codex']).describe('Which coding agent to use: "claude" (Claude Code) or "codex". Set this to the active code-mode chip agent. Note: when the chip is set, the backend uses the chip agent regardless of this value — this only takes effect in the ask-human flow where no chip is set.'),
cwd: z.string().describe('Absolute path to the working directory / project folder the agent should operate in.'),
prompt: z.string().describe('The full, self-contained coding instruction for the agent (file names, expected behavior, constraints).'),
}),
execute: async ({ agent, cwd, prompt }: { agent: 'claude' | 'codex', cwd: string, prompt: string }, ctx?: ToolContext) => {
if (!ctx) {
return { success: false, message: 'code_agent_run requires run context (runId / streaming).' };
}
// The composer chip is the source of truth for the agent. The model's `agent`
// argument is only a fallback for the ask-human flow (code mode not active, no
// chip set) — otherwise it can anchor on the thread's earlier agent and ignore a
// chip change. Honor the chip so switching it deterministically switches agents.
const effectiveAgent = ctx.codeMode ?? agent;
const manager = container.resolve<CodeModeManager>('codeModeManager');
const registry = container.resolve<CodePermissionRegistry>('codePermissionRegistry');
// Approval policy from settings; default to asking the user.
let policy: ApprovalPolicy = 'ask';
try {
const cfg = await container.resolve<ICodeModeConfigRepo>('codeModeConfigRepo').getConfig();
if (cfg.approvalPolicy) policy = cfg.approvalPolicy;
} catch {
// fall back to 'ask'
}
// On stop, unblock any pending approval card so the broker stops waiting for
// an answer that will never come. The ACP cancel + force-kill backstop that
// actually ends the turn is handled inside manager.runPrompt via the signal
// we pass below.
const onAbort = () => registry.cancelRun(ctx.runId);
if (ctx.signal.aborted) onAbort();
else ctx.signal.addEventListener('abort', onAbort, { once: true });
let finalText = '';
const changedFiles = new Set<string>();
try {
const result = await manager.runPrompt({
runId: ctx.runId,
agent: effectiveAgent,
cwd,
prompt,
policy,
signal: ctx.signal,
onEvent: (event) => {
if (event.type === 'message' && event.role === 'agent') finalText += event.text;
if (event.type === 'tool_call_update') for (const f of event.diffs) changedFiles.add(f);
void ctx.publish({
runId: ctx.runId,
type: 'code-run-event',
toolCallId: ctx.toolCallId,
event,
subflow: [],
});
},
ask: (permAsk) => registry.request(ctx.runId, (requestId) => {
void ctx.publish({
runId: ctx.runId,
type: 'code-run-permission-request',
toolCallId: ctx.toolCallId,
requestId,
ask: permAsk,
subflow: [],
});
}),
});
return {
success: result.stopReason === 'end_turn',
stopReason: result.stopReason,
// The agent that actually ran (the chip), so the UI can label the run
// authoritatively rather than trusting the model's `agent` argument.
agent: effectiveAgent,
summary: finalText.trim(),
changedFiles: [...changedFiles],
};
} catch (error) {
// A stop mid-run isn't a failure — report it as a clean cancellation.
if (ctx.signal.aborted) {
return {
success: false,
stopReason: 'cancelled',
agent: effectiveAgent,
summary: finalText.trim(),
changedFiles: [...changedFiles],
};
}
return {
success: false,
message: `Coding agent failed: ${error instanceof Error ? error.message : String(error)}`,
};
} finally {
ctx.signal.removeEventListener('abort', onAbort);
}
},
},
// ============================================================================
// Browser Skills (browser-use/browser-harness domain-skills cache)
// ============================================================================

View file

@ -80,6 +80,7 @@ export async function executeCommand(
cwd?: string;
timeout?: number; // timeout in milliseconds
maxBuffer?: number; // max buffer size in bytes
env?: NodeJS.ProcessEnv; // override environment
}
): Promise<CommandResult> {
try {
@ -89,6 +90,7 @@ export async function executeCommand(
timeout: options?.timeout,
maxBuffer: options?.maxBuffer || 1024 * 1024, // default 1MB
shell,
env: options?.env,
});
return {

View file

@ -14,6 +14,10 @@ export interface ToolContext {
signal: AbortSignal;
abortRegistry: IAbortRegistry;
publish: (event: z.infer<typeof RunEvent>) => Promise<void>;
// The composer code-mode chip for the message that triggered this turn. When set,
// it is the authoritative coding agent — code_agent_run uses it rather than the
// agent the model guessed, so switching the chip deterministically switches agents.
codeMode?: 'claude' | 'codex' | null;
}
async function execMcpTool(agentTool: z.infer<typeof ToolAttachment> & { type: "mcp" }, input: Record<string, unknown>): Promise<unknown> {

View file

@ -8,17 +8,20 @@ export type MiddlePaneContext =
| { kind: 'note'; path: string; content: string }
| { kind: 'browser'; url: string; title: string };
export type CodeMode = 'claude' | 'codex';
type EnqueuedMessage = {
messageId: string;
message: UserMessageContentType;
voiceInput?: boolean;
voiceOutput?: VoiceOutputMode;
searchEnabled?: boolean;
codeMode?: CodeMode;
middlePaneContext?: MiddlePaneContext;
};
export interface IMessageQueue {
enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext): Promise<string>;
enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext, codeMode?: CodeMode): Promise<string>;
dequeue(runId: string): Promise<EnqueuedMessage | null>;
}
@ -34,7 +37,7 @@ export class InMemoryMessageQueue implements IMessageQueue {
this.idGenerator = idGenerator;
}
async enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext): Promise<string> {
async enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext, codeMode?: CodeMode): Promise<string> {
if (!this.store[runId]) {
this.store[runId] = [];
}
@ -45,6 +48,7 @@ export class InMemoryMessageQueue implements IMessageQueue {
voiceInput,
voiceOutput,
searchEnabled,
codeMode,
middlePaneContext,
});
return id;

View file

@ -71,7 +71,9 @@ The workspace lives at \`${WorkDir}\`.
export function buildBackgroundTaskAgent(): z.infer<typeof Agent> {
const tools: Record<string, z.infer<typeof ToolAttachment>> = {};
for (const name of Object.keys(BuiltinTools)) {
if (name === 'executeCommand') continue;
// code_agent_run requires an interactive UI for permission approvals — skip it
// here (headless) so it can't hang on an approval no one can answer.
if (name === 'executeCommand' || name === 'code_agent_run') continue;
tools[name] = { type: 'builtin', name };
}

View file

@ -0,0 +1,60 @@
import { createRequire } from 'module';
import * as path from 'path';
import type { CodingAgent } from './types.js';
import { resolveClaudeExecutable } from './claude-exec.js';
const require = createRequire(import.meta.url);
// The ACP adapter npm package that exposes each coding agent as an ACP server.
const ADAPTER_PACKAGE: Record<CodingAgent, string> = {
claude: '@agentclientprotocol/claude-agent-acp',
codex: '@agentclientprotocol/codex-acp',
};
export interface AgentLaunchSpec {
/** Executable to spawn — always `node` so we never hit the Windows .cmd EINVAL. */
command: string;
/** Args = [adapter entry script]. */
args: string[];
/** Extra env merged over process.env (e.g. CLAUDE_CODE_EXECUTABLE on Windows). */
env: NodeJS.ProcessEnv;
}
// Resolve the adapter's executable ENTRY (its `bin`, not its library `main`) to an
// absolute path so we can spawn it directly with `node <entry>`. createRequire lets
// us resolve workspace/pnpm-installed packages from this module's location.
function resolveAdapterEntry(pkg: string): string {
const pkgJsonPath = require.resolve(`${pkg}/package.json`);
const pkgDir = path.dirname(pkgJsonPath);
const pkgJson = require(`${pkg}/package.json`) as { bin?: string | Record<string, string> };
const bin = pkgJson.bin;
const rel = typeof bin === 'string' ? bin : bin ? Object.values(bin)[0] : undefined;
if (!rel) {
throw new Error(`ACP adapter ${pkg} has no bin entry to spawn`);
}
return path.join(pkgDir, rel);
}
export function getAgentLaunchSpec(agent: CodingAgent): AgentLaunchSpec {
const entry = resolveAdapterEntry(ADAPTER_PACKAGE[agent]);
const env: NodeJS.ProcessEnv = { ...process.env };
// Point the Claude adapter at the real claude executable. On Windows this is
// mandatory (Node can't spawn the .cmd shim — EINVAL); on macOS/Linux it's a
// PATH safety net for GUI launches. Resolver is a no-op when claude isn't found,
// leaving the adapter to do its own lookup. (Codex relies on PATH for now — wire
// an equivalent when we add Codex support.)
if (agent === 'claude' && !env.CLAUDE_CODE_EXECUTABLE) {
const exe = resolveClaudeExecutable();
if (exe) env.CLAUDE_CODE_EXECUTABLE = exe;
}
// We spawn the adapter with process.execPath. Inside Electron's main process
// that is the Electron binary, NOT node — so set ELECTRON_RUN_AS_NODE=1 to make
// it behave as a plain Node runtime. (Harmless under a real node process, which
// ignores the var.) Without this the child never runs as node and the ACP stdio
// stream closes immediately ("ACP connection closed").
env.ELECTRON_RUN_AS_NODE = '1';
return { command: process.execPath, args: [entry], env };
}

View file

@ -0,0 +1,91 @@
import { execSync } from 'child_process';
import * as path from 'path';
import { existsSync, readFileSync } from 'fs';
import { commonInstallPaths } from '../status.js';
// Windows-only: Node refuses to spawn `.cmd` files without `shell: true` (EINVAL),
// and the Claude ACP adapter spawns its executable directly. So we pre-resolve
// claude's real `.exe` from the npm-shim layout. Used by resolveClaudeExecutable below.
export function resolveClaudeExeOnWindows(): string | undefined {
// Candidate dirs = everything on PATH, plus well-known npm/pnpm/volta global
// bin dirs. Electron's runtime PATH can omit these even when the user's shell
// includes them, which would otherwise leave us unable to find claude.exe and
// force a fallback to claude.cmd (which Node refuses to spawn — EINVAL).
const home = process.env.USERPROFILE ?? '';
const appData = process.env.APPDATA || (home && path.join(home, 'AppData', 'Roaming'));
const localAppData = process.env.LOCALAPPDATA || (home && path.join(home, 'AppData', 'Local'));
const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
const knownDirs = [
appData && path.join(appData, 'npm'),
localAppData && path.join(localAppData, 'npm'),
appData && path.join(appData, 'pnpm'),
localAppData && path.join(localAppData, 'pnpm'),
home && path.join(home, '.volta', 'bin'),
path.join(programFiles, 'nodejs'),
].filter(Boolean) as string[];
const pathDirs = (process.env.PATH ?? '').split(';').map((d) => d.trim()).filter(Boolean);
const seen = new Set<string>();
const candidates = [...pathDirs, ...knownDirs].filter((d) => {
const key = d.toLowerCase();
if (seen.has(key)) return false;
seen.add(key);
return true;
});
for (const dir of candidates) {
// Direct npm-shim layout: <dir>\node_modules\@anthropic-ai\claude-code\bin\claude.exe
const exeFromLayout = path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe');
if (existsSync(exeFromLayout)) return exeFromLayout;
// Otherwise parse the claude.cmd shim for the real exe path.
const cmdPath = path.join(dir, 'claude.cmd');
if (!existsSync(cmdPath)) continue;
try {
const content = readFileSync(cmdPath, 'utf-8');
const absMatch = content.match(/[A-Z]:[\\/][^\s"]*claude\.exe/i);
if (absMatch && existsSync(absMatch[0])) return absMatch[0];
const relMatch = content.match(/%~dp0[\\/]?([^\s"%]+claude\.exe)/i);
if (relMatch) {
const resolved = path.join(dir, relMatch[1]);
if (existsSync(resolved)) return resolved;
}
} catch {
// ignore shim parse failures
}
}
return undefined;
}
// macOS/Linux: find the real `claude` binary. Unlike Windows this isn't a spawn
// requirement (no .cmd problem) — it's a PATH safety net. Electron apps launched
// from the GUI (Dock/Finder) often don't inherit the login shell's PATH, so the
// spawned adapter may fail to find `claude`. We resolve the path here so the adapter
// can be pointed straight at it.
function resolveClaudeBinaryUnix(): string | undefined {
// Primary: a login shell sees the user's full PATH (~/.zprofile, nvm, homebrew, …).
try {
const out = execSync("/bin/sh -lc 'command -v claude'", { timeout: 5000, encoding: 'utf-8' }).trim();
if (out && existsSync(out)) return out;
} catch {
// not found on the login-shell PATH
}
// Fallback: scan well-known install locations directly.
for (const candidate of commonInstallPaths('claude')) {
if (existsSync(candidate)) return candidate;
}
return undefined;
}
let cached: string | undefined;
// Cross-platform: the real `claude` executable to hand the ACP adapter via
// CLAUDE_CODE_EXECUTABLE (the adapter prefers this env var on every OS). Returns
// undefined if it can't be found — callers then fall back to the adapter's own lookup.
// Cached on first success so we don't re-probe the shell on every cold start.
export function resolveClaudeExecutable(): string | undefined {
if (cached) return cached;
const resolved = process.platform === 'win32' ? resolveClaudeExeOnWindows() : resolveClaudeBinaryUnix();
if (resolved) cached = resolved;
return resolved;
}

View file

@ -0,0 +1,219 @@
import { spawn, type ChildProcess } from 'child_process';
import { Writable, Readable } from 'node:stream';
import fs from 'fs/promises';
import {
ClientSideConnection,
ndJsonStream,
PROTOCOL_VERSION,
type Client,
type RequestPermissionRequest,
type RequestPermissionResponse,
type SessionNotification,
type SessionUpdate,
type PromptResponse,
type ReadTextFileRequest,
type ReadTextFileResponse,
type WriteTextFileRequest,
type WriteTextFileResponse,
} from '@agentclientprotocol/sdk';
import type { CodingAgent, CodeRunEvent } from './types.js';
import type { PermissionBroker } from './permission-broker.js';
import { getAgentLaunchSpec } from './agents.js';
export interface AcpClientOptions {
agent: CodingAgent;
cwd: string;
broker: PermissionBroker;
onEvent: (event: CodeRunEvent) => void;
}
// Map a raw ACP session/update notification onto our small CodeRunEvent union.
function toEvent(update: SessionUpdate): CodeRunEvent {
switch (update.sessionUpdate) {
case 'agent_message_chunk':
case 'user_message_chunk': {
const c = update.content;
const role = update.sessionUpdate === 'user_message_chunk' ? 'user' : 'agent';
return { type: 'message', role, text: c.type === 'text' ? c.text : `[${c.type}]` };
}
case 'agent_thought_chunk':
return { type: 'thought' };
case 'tool_call':
return {
type: 'tool_call',
id: update.toolCallId,
title: update.title,
kind: update.kind ?? undefined,
status: update.status ?? undefined,
};
case 'tool_call_update': {
const diffs = (update.content ?? [])
.filter((c): c is Extract<typeof c, { type: 'diff' }> => c.type === 'diff')
.map((c) => c.path);
return { type: 'tool_call_update', id: update.toolCallId, status: update.status ?? undefined, diffs };
}
case 'plan':
return {
type: 'plan',
entries: (update.entries ?? []).map((e) => ({
content: e.content,
status: e.status ?? undefined,
priority: e.priority ?? undefined,
})),
};
default:
return { type: 'other', sessionUpdate: update.sessionUpdate };
}
}
// Owns one spawned adapter process + ACP connection. Stateless about sessions —
// the manager decides whether to newSession or loadSession.
//
// The connection is long-lived and reused across follow-up prompts, but each prompt
// may stream to a different message's UI, so broker + onEvent are swappable via
// setHandlers() rather than fixed at construction.
export class AcpClient {
readonly agent: CodingAgent;
readonly cwd: string;
private broker: PermissionBroker;
private onEvent: (event: CodeRunEvent) => void;
private child?: ChildProcess;
private connection?: ClientSideConnection;
private loadSession_ = false;
// Diagnostics: the adapter's stderr/exit are captured so a dropped connection
// reports WHY (e.g. a crash) instead of the SDK's bare "ACP connection closed".
private stderrTail = '';
private exitInfo: string | null = null;
constructor(opts: AcpClientOptions) {
this.agent = opts.agent;
this.cwd = opts.cwd;
this.broker = opts.broker;
this.onEvent = opts.onEvent;
}
get loadSupported(): boolean {
return this.loadSession_;
}
// Re-point the live connection at a new prompt's broker / event sink.
setHandlers(broker: PermissionBroker, onEvent: (event: CodeRunEvent) => void): void {
this.broker = broker;
this.onEvent = onEvent;
}
// Spawn the adapter and negotiate the protocol. Returns once initialized.
async start(): Promise<void> {
const spec = getAgentLaunchSpec(this.agent);
const child = spawn(spec.command, spec.args, {
cwd: this.cwd,
env: spec.env,
// Capture stderr (not inherit) so we can attribute a dropped connection.
stdio: ['pipe', 'pipe', 'pipe'],
});
this.child = child;
child.stderr?.on('data', (d: Buffer) => {
this.stderrTail = (this.stderrTail + d.toString()).slice(-4000);
});
child.on('exit', (code, signal) => {
this.exitInfo = `adapter exited (code ${code}${signal ? `, signal ${signal}` : ''})`;
});
child.on('error', (err) => {
this.stderrTail = (this.stderrTail + `\nspawn error: ${err.message}`).slice(-4000);
});
const stream = ndJsonStream(
Writable.toWeb(child.stdin!) as WritableStream<Uint8Array>,
Readable.toWeb(child.stdout!) as ReadableStream<Uint8Array>,
);
const client = this.buildClient();
this.connection = new ClientSideConnection(() => client, stream);
try {
const init = await this.connection.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: { fs: { readTextFile: true, writeTextFile: true } },
});
this.loadSession_ = init.agentCapabilities?.loadSession === true;
} catch (e) {
throw this.enrich(e, 'initialize');
}
}
async newSession(): Promise<string> {
try {
const res = await this.conn().newSession({ cwd: this.cwd, mcpServers: [] });
return res.sessionId;
} catch (e) {
throw this.enrich(e, 'newSession');
}
}
async loadSession(sessionId: string): Promise<void> {
try {
await this.conn().loadSession({ sessionId, cwd: this.cwd, mcpServers: [] });
} catch (e) {
throw this.enrich(e, 'loadSession');
}
}
async prompt(sessionId: string, text: string): Promise<PromptResponse> {
try {
return await this.conn().prompt({ sessionId, prompt: [{ type: 'text', text }] });
} catch (e) {
throw this.enrich(e, 'prompt');
}
}
// Wrap a connection error with the adapter's exit/stderr so failures are
// self-explanatory rather than the SDK's opaque "ACP connection closed".
private enrich(err: unknown, phase: string): Error {
const base = err instanceof Error ? err.message : String(err);
const parts = [
this.exitInfo,
this.stderrTail.trim() ? `adapter output: ${this.stderrTail.trim().slice(-1200)}` : '',
].filter(Boolean);
return new Error(parts.length ? `${base}${parts.join(' | ')} [during ${phase}]` : `${base} [during ${phase}]`);
}
async cancel(sessionId: string): Promise<void> {
await this.conn().cancel({ sessionId });
}
dispose(): void {
try {
this.child?.kill();
} catch {
// already gone
}
this.child = undefined;
this.connection = undefined;
}
private conn(): ClientSideConnection {
if (!this.connection) throw new Error('AcpClient not started');
return this.connection;
}
// The client side of ACP: the agent calls these on us. These read the CURRENT
// handlers off `self` so follow-up prompts can swap them via setHandlers().
private buildClient(): Client {
const self = this;
return {
async requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
return self.broker.resolve(params);
},
async sessionUpdate(params: SessionNotification): Promise<void> {
self.onEvent(toEvent(params.update));
},
async readTextFile(params: ReadTextFileRequest): Promise<ReadTextFileResponse> {
const content = await fs.readFile(params.path, 'utf8');
return { content };
},
async writeTextFile(params: WriteTextFileRequest): Promise<WriteTextFileResponse> {
await fs.writeFile(params.path, params.content);
return {};
},
};
}
}

View file

@ -0,0 +1,186 @@
import type { ApprovalPolicy, CodeRunEvent, CodingAgent, PermissionAsk, PermissionDecision, RunPromptResult } from './types.js';
import { AcpClient } from './client.js';
import { PermissionBroker } from './permission-broker.js';
import { readStoredSession, writeStoredSession, clearStoredSession } from './session-store.js';
export interface RunPromptArgs {
runId: string;
agent: CodingAgent;
cwd: string;
prompt: string;
policy: ApprovalPolicy;
/** Called when the policy needs the user to decide (the "ask" path). */
ask: (ask: PermissionAsk) => Promise<PermissionDecision>;
/** Stream sink for this prompt's run. */
onEvent: (event: CodeRunEvent) => void;
/** Aborts the turn on stop; the manager cancels then force-kills the adapter. */
signal?: AbortSignal;
}
interface ActiveRun {
client: AcpClient;
sessionId: string;
agent: CodingAgent;
cwd: string;
// Prompts currently streaming on this connection. Disposal is deferred while
// this is > 0 so we never tear down a connection mid-turn.
inflight: number;
// Pending grace-window teardown, cleared if the run is reused before it fires.
disposeTimer?: ReturnType<typeof setTimeout>;
}
// How long a connection stays warm after its last turn ends before we tear it down.
// A coding "turn" is one code_agent_run tool call; we keep the adapter briefly so
// back-to-back calls within one copilot turn (edit -> test -> fix) and quick user
// follow-ups reuse the warm connection instead of cold-starting. Set to 0 for strict
// per-turn teardown. Context is never lost either way: the next turn resumes the
// persisted session via session/load.
const DISPOSE_GRACE_MS = 60_000;
// On stop, how long to let the adapter cancel gracefully (ACP session/cancel) before
// we force-kill it. The kill guarantees the turn unwinds even if the adapter ignores
// cancel or is blocked — otherwise a hung prompt would lock the chat indefinitely.
const CANCEL_GRACE_MS = 2_000;
// Drives ACP coding sessions. A connection's lifetime is scoped to the agent turn
// (one code_agent_run): it is torn down a short grace window after the turn ends, so
// idle chats hold no adapter processes. Turns that land within the grace window reuse
// the warm connection; anything colder (grace elapsed, or after an app restart)
// resumes the persisted session via session/load.
export class CodeModeManager {
private readonly runs = new Map<string, ActiveRun>();
async runPrompt(args: RunPromptArgs): Promise<RunPromptResult> {
const { runId, agent, cwd, prompt, policy, ask, onEvent, signal } = args;
const broker = new PermissionBroker({
policy,
ask,
onResolved: (a, decision, auto) => onEvent({ type: 'permission', ask: a, decision, auto }),
});
const run = await this.ensureRun(runId, agent, cwd, broker, onEvent);
run.inflight++;
let graceTimer: ReturnType<typeof setTimeout> | undefined;
let onAbort: (() => void) | undefined;
try {
const promptP = run.client.prompt(run.sessionId, prompt);
// We may stop awaiting this prompt below (force-kill on stop rejects it);
// attach a no-op catch so the orphaned rejection isn't flagged.
promptP.catch(() => {});
// Stop handling: on abort, ask the adapter to cancel; if it hasn't unwound
// within the grace, force-kill it and resolve as cancelled. This guarantees
// the turn ends even if the adapter ignores cancel or is wedged — a hung
// prompt would otherwise lock the chat (no run-stopped, composer disabled).
const cancelledP = new Promise<{ stopReason: string }>((resolve) => {
if (!signal) return;
onAbort = () => {
run.client.cancel(run.sessionId).catch(() => {});
graceTimer = setTimeout(() => {
this.dispose(runId);
resolve({ stopReason: 'cancelled' });
}, CANCEL_GRACE_MS);
graceTimer.unref?.();
};
if (signal.aborted) onAbort();
else signal.addEventListener('abort', onAbort, { once: true });
});
const res = await Promise.race([promptP, cancelledP]);
return { stopReason: res.stopReason, sessionId: run.sessionId };
} catch (e) {
// A kill-induced "connection closed" during a stop is an expected cancel.
if (signal?.aborted) return { stopReason: 'cancelled', sessionId: run.sessionId };
throw e;
} finally {
if (signal && onAbort) signal.removeEventListener('abort', onAbort);
if (graceTimer) clearTimeout(graceTimer);
run.inflight--;
this.scheduleDispose(runId);
}
}
dispose(runId: string): void {
const run = this.runs.get(runId);
if (!run) return;
this.cancelDispose(run);
run.client.dispose();
this.runs.delete(runId);
}
// Tear down the connection a grace window after its last turn ends. Skipped while a
// prompt is still streaming, and re-armed when each turn ends so the window measures
// idle-since-last-activity. With grace 0 we dispose immediately (strict per-turn).
private scheduleDispose(runId: string): void {
const run = this.runs.get(runId);
if (!run || run.inflight > 0) return;
this.cancelDispose(run);
if (DISPOSE_GRACE_MS <= 0) {
this.dispose(runId);
return;
}
run.disposeTimer = setTimeout(() => {
const r = this.runs.get(runId);
if (r && r.inflight === 0) this.dispose(runId);
}, DISPOSE_GRACE_MS);
// A pending teardown timer must not keep the process alive at quit.
run.disposeTimer.unref?.();
}
private cancelDispose(run: ActiveRun): void {
if (run.disposeTimer) {
clearTimeout(run.disposeTimer);
run.disposeTimer = undefined;
}
}
disposeAll(): void {
for (const runId of [...this.runs.keys()]) this.dispose(runId);
}
// Reuse the warm connection if it matches; otherwise (cold start, or the user
// switched agent/cwd for this chat) build a fresh one and create-or-resume its session.
private async ensureRun(
runId: string,
agent: CodingAgent,
cwd: string,
broker: PermissionBroker,
onEvent: (event: CodeRunEvent) => void,
): Promise<ActiveRun> {
const existing = this.runs.get(runId);
if (existing && existing.agent === agent && existing.cwd === cwd) {
this.cancelDispose(existing); // reused before its grace window elapsed
existing.client.setHandlers(broker, onEvent);
return existing;
}
if (existing) this.dispose(runId); // agent/cwd changed — start over
const client = new AcpClient({ agent, cwd, broker, onEvent });
await client.start();
const sessionId = await this.openSession(runId, agent, cwd, client);
const run: ActiveRun = { client, sessionId, agent, cwd, inflight: 0 };
this.runs.set(runId, run);
return run;
}
// Resume the persisted session for this chat when possible; else start a new one
// and persist its id so a later restart can resume it.
private async openSession(runId: string, agent: CodingAgent, cwd: string, client: AcpClient): Promise<string> {
const stored = await readStoredSession(runId);
if (stored && stored.agent === agent && stored.cwd === cwd && client.loadSupported) {
try {
await client.loadSession(stored.sessionId);
return stored.sessionId;
} catch {
// Stored session is stale/unloadable — fall through to a fresh one.
await clearStoredSession(runId);
}
}
const sessionId = await client.newSession();
await writeStoredSession({ runId, agent, cwd, sessionId });
return sessionId;
}
}

View file

@ -0,0 +1,91 @@
import type {
RequestPermissionRequest,
RequestPermissionResponse,
PermissionOption,
PermissionOptionKind,
} from '@agentclientprotocol/sdk';
import type { ApprovalPolicy, PermissionDecision, PermissionAsk } from './types.js';
// Tool kinds that don't mutate anything — eligible for `auto-approve-reads`.
const READ_KINDS = new Set(['read', 'search', 'fetch', 'think']);
function toAsk(request: RequestPermissionRequest): PermissionAsk {
const tc = request.toolCall;
const kind = tc.kind ?? undefined;
const title = tc.title ?? kind ?? 'Tool call';
return {
toolCallId: tc.toolCallId ?? undefined,
title,
kind,
isRead: kind ? READ_KINDS.has(kind) : false,
};
}
// Map a desired decision to one of the options the agent actually offered.
// Agents may offer only a subset (e.g. allow_once + reject_once, no allow_always),
// so we fall back within the same allow/reject family before giving up.
function pickOption(options: PermissionOption[], decision: PermissionDecision): PermissionOption | undefined {
const order: Record<PermissionDecision, PermissionOptionKind[]> = {
allow_always: ['allow_always', 'allow_once'],
allow_once: ['allow_once', 'allow_always'],
reject: ['reject_once', 'reject_always'],
};
for (const kind of order[decision]) {
const found = options.find((o) => o.kind === kind);
if (found) return found;
}
return undefined;
}
function selected(optionId: string): RequestPermissionResponse {
return { outcome: { outcome: 'selected', optionId } };
}
// A request's identity for "always allow" memory: prefer tool kind, else title.
function memoryKey(ask: PermissionAsk): string {
return ask.kind ? `kind:${ask.kind}` : `title:${ask.title}`;
}
export interface PermissionBrokerOptions {
policy: ApprovalPolicy;
// Called only when the policy can't decide on its own (the "ask" path).
ask: (ask: PermissionAsk) => Promise<PermissionDecision>;
// Notified of every resolved request so the engine can emit a stream event.
onResolved?: (ask: PermissionAsk, decision: PermissionDecision, auto: boolean) => void;
}
// Decides how to answer the agent's requestPermission calls. Holds per-session
// "always allow" memory so a one-time approval sticks for the rest of the run.
export class PermissionBroker {
private readonly opts: PermissionBrokerOptions;
private readonly alwaysAllow = new Set<string>();
constructor(opts: PermissionBrokerOptions) {
this.opts = opts;
}
async resolve(request: RequestPermissionRequest): Promise<RequestPermissionResponse> {
const ask = toAsk(request);
const key = memoryKey(ask);
const finish = (decision: PermissionDecision, auto: boolean): RequestPermissionResponse => {
if (decision === 'allow_always') this.alwaysAllow.add(key);
this.opts.onResolved?.(ask, decision, auto);
const opt = pickOption(request.options, decision);
// If the agent offered no matching option we fall back to its first one
// (don't deadlock the turn); decision precedence above keeps this rare.
return selected(opt?.optionId ?? request.options[0]?.optionId ?? '');
};
// 1. Sticky "always allow" from earlier this session.
if (this.alwaysAllow.has(key)) return finish('allow_always', true);
// 2. Policy-level auto decisions.
if (this.opts.policy === 'yolo') return finish('allow_always', true);
if (this.opts.policy === 'auto-approve-reads' && ask.isRead) return finish('allow_once', true);
// 3. Ask the user.
const decision = await this.opts.ask(ask);
return finish(decision, false);
}
}

View file

@ -0,0 +1,43 @@
import type { PermissionDecision } from './types.js';
interface Pending {
runId: string;
resolve: (decision: PermissionDecision) => void;
}
// Holds in-flight mid-run permission asks. The agent (via the broker) calls
// request() which BLOCKS the coding turn until the user answers; the renderer's
// answer arrives over IPC and calls resolve(). This is separate from the LLM
// tool-loop's pre-call permission gate, which can't model a mid-execution wait.
export class CodePermissionRegistry {
private readonly pending = new Map<string, Pending>();
private counter = 0;
// Register a pending ask, hand the generated requestId to `emit` (so the caller
// can publish the UI event), and resolve once the user answers.
request(runId: string, emit: (requestId: string) => void): Promise<PermissionDecision> {
const requestId = `cpr-${runId}-${++this.counter}`;
return new Promise<PermissionDecision>((resolve) => {
this.pending.set(requestId, { runId, resolve });
emit(requestId);
});
}
// Called from the IPC handler when the user answers a card.
resolve(requestId: string, decision: PermissionDecision): void {
const entry = this.pending.get(requestId);
if (!entry) return;
this.pending.delete(requestId);
entry.resolve(decision);
}
// On run stop/cancel: reject anything still waiting so the turn can unwind.
cancelRun(runId: string): void {
for (const [id, entry] of [...this.pending]) {
if (entry.runId === runId) {
this.pending.delete(id);
entry.resolve('reject');
}
}
}
}

View file

@ -0,0 +1,48 @@
import fs from 'fs/promises';
import path from 'path';
import { WorkDir } from '../../config/config.js';
import type { CodingAgent } from './types.js';
// One ACP session is pinned per chat run. We persist its sessionId (plus the agent
// and cwd it belongs to) so reopening the chat after an app restart can resume the
// same agent context via session/load instead of starting over.
export interface StoredSession {
runId: string;
agent: CodingAgent;
cwd: string;
sessionId: string;
}
// Per-run ACP session state lives in its own directory (not WorkDir/config): it's
// runtime state that accumulates one file per chat run, so it's kept separate from
// user/app config to be listed and cleaned up on its own.
const SESSIONS_DIR = path.join(WorkDir, 'code-mode', 'sessions');
function sessionFile(runId: string): string {
return path.join(SESSIONS_DIR, `${runId}.json`);
}
export async function readStoredSession(runId: string): Promise<StoredSession | null> {
try {
const raw = await fs.readFile(sessionFile(runId), 'utf8');
const parsed = JSON.parse(raw) as StoredSession;
if (parsed && parsed.sessionId && parsed.agent && parsed.cwd) return parsed;
return null;
} catch {
return null;
}
}
export async function writeStoredSession(session: StoredSession): Promise<void> {
const file = sessionFile(session.runId);
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, JSON.stringify(session, null, 2));
}
export async function clearStoredSession(runId: string): Promise<void> {
try {
await fs.rm(sessionFile(runId), { force: true });
} catch {
// best effort
}
}

View file

@ -0,0 +1,11 @@
// Rowboat-facing types for the ACP code-mode engine. The schemas live in
// @x/shared (so the IPC/renderer layers share them); we re-export the inferred
// types here so the engine modules import from one local barrel.
export type {
CodingAgent,
ApprovalPolicy,
PermissionDecision,
PermissionAsk,
CodeRunEvent,
RunPromptResult,
} from '@x/shared/dist/code-mode.js';

View file

@ -0,0 +1,3 @@
export { CodeModeConfig, CodeModeAgentStatus, AgentStatus } from './types.js';
export { FSCodeModeConfigRepo, type ICodeModeConfigRepo } from './repo.js';
export { checkCodeModeAgentStatus } from './status.js';

View file

@ -0,0 +1,47 @@
import fs from 'fs/promises';
import path from 'path';
import { WorkDir } from '../config/config.js';
import { CodeModeConfig } from './types.js';
import { checkCodeModeAgentStatus } from './status.js';
export interface ICodeModeConfigRepo {
getConfig(): Promise<CodeModeConfig>;
setConfig(config: CodeModeConfig): Promise<void>;
}
export class FSCodeModeConfigRepo implements ICodeModeConfigRepo {
private readonly configPath = path.join(WorkDir, 'config', 'code-mode.json');
private agentReadyPromise: Promise<boolean> | null = null;
// Reuse the existing agent check (Claude Code / Codex installed + signed in),
// cached for the process lifetime so we probe (shell + keychain) at most once
// per session rather than on every getConfig call.
private agentReady(): Promise<boolean> {
if (!this.agentReadyPromise) {
this.agentReadyPromise = checkCodeModeAgentStatus()
.then((s) =>
(s.claude.installed && s.claude.signedIn)
|| (s.codex.installed && s.codex.signedIn))
.catch(() => false);
}
return this.agentReadyPromise;
}
async getConfig(): Promise<CodeModeConfig> {
try {
// The file only exists once the user has explicitly toggled code mode
// in settings — always honor that choice.
const content = await fs.readFile(this.configPath, 'utf8');
return CodeModeConfig.parse(JSON.parse(content));
} catch {
// No explicit choice yet: enable automatically when a coding agent is ready.
return { enabled: await this.agentReady() };
}
}
async setConfig(config: CodeModeConfig): Promise<void> {
const validated = CodeModeConfig.parse(config);
await fs.mkdir(path.dirname(this.configPath), { recursive: true });
await fs.writeFile(this.configPath, JSON.stringify(validated, null, 2));
}
}

View file

@ -0,0 +1,199 @@
import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import path from 'path';
import fs from 'fs/promises';
import { existsSync } from 'fs';
import { CodeModeAgentStatus } from './types.js';
const execAsync = promisify(exec);
// Where claude.cmd / codex.cmd typically live when installed via npm/pnpm/yarn.
// We scan these directly because Electron's spawned shell sometimes doesn't
// inherit the user's full PATH (especially on macOS GUI launches, and even on
// Windows when global npm prefix isn't propagated to system PATH).
export function commonInstallPaths(binary: string): string[] {
const home = os.homedir();
if (process.platform === 'win32') {
const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
return [
path.join(appData, 'npm', `${binary}.cmd`),
path.join(appData, 'npm', `${binary}.exe`),
path.join(localAppData, 'npm', `${binary}.cmd`),
path.join(localAppData, 'pnpm', `${binary}.cmd`),
path.join(home, 'AppData', 'Roaming', 'pnpm', `${binary}.cmd`),
path.join(programFiles, 'nodejs', `${binary}.cmd`),
path.join(home, '.volta', 'bin', `${binary}.cmd`),
];
}
return [
'/usr/local/bin',
'/opt/homebrew/bin', // Apple Silicon Homebrew
'/usr/bin',
path.join(home, '.npm-global', 'bin'),
path.join(home, '.local', 'bin'),
path.join(home, '.volta', 'bin'),
path.join(home, '.nvm', 'versions', 'node'), // partial; nvm has versioned subdirs
path.join(home, 'bin'),
].map(dir => path.join(dir, binary));
}
async function probeShell(binary: string): Promise<boolean> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(`where ${binary}`, { timeout: 5000 });
return stdout.trim().length > 0;
}
// Login shell so ~/.zprofile / ~/.bashrc PATH additions are visible —
// essential for Homebrew, nvm, asdf, volta installs on macOS GUI launches.
const { stdout } = await execAsync(`/bin/sh -lc 'command -v ${binary}'`, { timeout: 5000 });
return stdout.trim().length > 0;
} catch {
return false;
}
}
async function isInstalled(binary: string): Promise<boolean> {
if (await probeShell(binary)) return true;
// Fallback: scan well-known install locations directly.
for (const candidate of commonInstallPaths(binary)) {
if (existsSync(candidate)) return true;
}
return false;
}
function decodeJwtPayload(token: string): Record<string, unknown> | null {
try {
const parts = token.split('.');
if (parts.length < 2) return null;
const padded = parts[1].replace(/-/g, '+').replace(/_/g, '/');
const pad = padded.length % 4 === 0 ? '' : '='.repeat(4 - (padded.length % 4));
const json = Buffer.from(padded + pad, 'base64').toString('utf-8');
const parsed = JSON.parse(json);
return typeof parsed === 'object' && parsed !== null ? parsed as Record<string, unknown> : null;
} catch {
return null;
}
}
// Given the raw credentials JSON (from a file or the macOS Keychain), decide
// whether it represents a usable signed-in state: a valid API key, an unexpired
// access token, or a refresh token (which can mint a new access token).
function isClaudeCredentialSignedIn(raw: string): boolean {
try {
const parsed = JSON.parse(raw) as Record<string, unknown>;
const oauth = parsed.claudeAiOauth as Record<string, unknown> | undefined;
if (oauth) {
const access = typeof oauth.accessToken === 'string' ? oauth.accessToken : '';
const refresh = typeof oauth.refreshToken === 'string' ? oauth.refreshToken : '';
if (refresh.length > 0) return true;
if (access.length > 0) {
if (typeof oauth.expiresAt === 'number' && oauth.expiresAt > 0 && oauth.expiresAt < Date.now()) {
return false;
}
return true;
}
}
if (typeof parsed.apiKey === 'string' && parsed.apiKey.length > 10) return true;
if (typeof parsed.accessToken === 'string' && parsed.accessToken.length > 10) return true;
} catch {
// malformed JSON
}
return false;
}
// Reads Claude Code's credentials from the macOS login Keychain, where the
// CLI stores them on macOS (service "Claude Code-credentials"). On Linux/Windows
// it uses the ~/.claude/.credentials.json file instead, so this is a no-op there.
//
// Caveats:
// - The first read by this app (a different binary than the `claude` CLI that
// created the item) triggers a one-time macOS authorization dialog; the user
// must "Always Allow". Headless/SSH sessions can't show it and will fail.
// - If CLAUDE_CONFIG_DIR is set, Claude appends a SHA-256 suffix to the service
// name, which this lookup won't match — such setups usually keep the file too.
async function readClaudeKeychainCredential(): Promise<string | null> {
if (process.platform !== 'darwin') return null;
try {
const { stdout } = await execAsync(
`security find-generic-password -s "Claude Code-credentials" -w`,
{ timeout: 5000 },
);
const out = stdout.trim();
return out.length > 0 ? out : null;
} catch {
// not present in keychain
return null;
}
}
// Validates Claude Code auth. On macOS the credentials live in the login
// Keychain; on Linux/Windows in ~/.claude/.credentials.json (or ~/.config
// fallback). We check both so detection works across platforms.
async function checkClaudeSignedIn(): Promise<boolean> {
const home = os.homedir();
const candidates = [
path.join(home, '.claude', '.credentials.json'),
path.join(home, '.config', 'claude', '.credentials.json'),
];
for (const full of candidates) {
try {
const raw = await fs.readFile(full, 'utf-8');
if (isClaudeCredentialSignedIn(raw)) return true;
} catch {
// try next candidate
}
}
// macOS: credentials are stored in the Keychain rather than on disk.
const keychainRaw = await readClaudeKeychainCredential();
if (keychainRaw && isClaudeCredentialSignedIn(keychainRaw)) return true;
return false;
}
// Validates Codex auth at ~/.codex/auth.json on all platforms.
// Considered signed in if API key set, or a refresh_token / access_token
// exists. id_token expiry is intentionally NOT used as a rejection signal —
// id_tokens are short-lived (~1h) but refresh_tokens persist for weeks.
async function checkCodexSignedIn(): Promise<boolean> {
const home = os.homedir();
const full = path.join(home, '.codex', 'auth.json');
try {
const raw = await fs.readFile(full, 'utf-8');
const parsed = JSON.parse(raw) as Record<string, unknown>;
if (typeof parsed.OPENAI_API_KEY === 'string' && parsed.OPENAI_API_KEY.length > 10) return true;
const tokens = parsed.tokens as Record<string, unknown> | undefined;
if (tokens) {
const refresh = typeof tokens.refresh_token === 'string' ? tokens.refresh_token : '';
const access = typeof tokens.access_token === 'string' ? tokens.access_token : '';
const id = typeof tokens.id_token === 'string' ? tokens.id_token : '';
if (refresh.length > 0 || access.length > 0 || id.length > 0) return true;
}
} catch {
// file missing or unreadable
}
return false;
}
// Exported for diagnostics — silenced unused-var warning by re-export only.
export { decodeJwtPayload };
export async function checkCodeModeAgentStatus(): Promise<CodeModeAgentStatus> {
const [claudeInstalled, codexInstalled, claudeSignedIn, codexSignedIn] = await Promise.all([
isInstalled('claude'),
isInstalled('codex'),
checkClaudeSignedIn(),
checkCodexSignedIn(),
]);
return {
claude: { installed: claudeInstalled, signedIn: claudeSignedIn },
codex: { installed: codexInstalled, signedIn: codexSignedIn },
};
}

View file

@ -0,0 +1,22 @@
import z from "zod";
import { ApprovalPolicy } from "@x/shared/dist/code-mode.js";
export const CodeModeConfig = z.object({
enabled: z.boolean(),
// How the ACP engine answers the coding agent's permission requests.
// Optional for back-compat; the tool defaults to "ask" when unset.
approvalPolicy: ApprovalPolicy.optional(),
});
export type CodeModeConfig = z.infer<typeof CodeModeConfig>;
export const AgentStatus = z.object({
installed: z.boolean(),
signedIn: z.boolean(),
});
export type AgentStatus = z.infer<typeof AgentStatus>;
export const CodeModeAgentStatus = z.object({
claude: AgentStatus,
codex: AgentStatus,
});
export type CodeModeAgentStatus = z.infer<typeof CodeModeAgentStatus>;

View file

@ -11,10 +11,13 @@ import { IAgentRuntime, AgentRuntime } from "../agents/runtime.js";
import { FSOAuthRepo, IOAuthRepo } from "../auth/repo.js";
import { FSClientRegistrationRepo, IClientRegistrationRepo } from "../auth/client-repo.js";
import { FSGranolaConfigRepo, IGranolaConfigRepo } from "../knowledge/granola/repo.js";
import { FSCodeModeConfigRepo, ICodeModeConfigRepo } from "../code-mode/repo.js";
import { IAbortRegistry, InMemoryAbortRegistry } from "../runs/abort-registry.js";
import { FSAgentScheduleRepo, IAgentScheduleRepo } from "../agent-schedule/repo.js";
import { FSAgentScheduleStateRepo, IAgentScheduleStateRepo } from "../agent-schedule/state-repo.js";
import { FSSlackConfigRepo, ISlackConfigRepo } from "../slack/repo.js";
import { CodeModeManager } from "../code-mode/acp/manager.js";
import { CodePermissionRegistry } from "../code-mode/acp/permission-registry.js";
import type { IBrowserControlService } from "../application/browser-control/service.js";
import type { INotificationService } from "../application/notification/service.js";
@ -38,9 +41,16 @@ container.register({
oauthRepo: asClass<IOAuthRepo>(FSOAuthRepo).singleton(),
clientRegistrationRepo: asClass<IClientRegistrationRepo>(FSClientRegistrationRepo).singleton(),
granolaConfigRepo: asClass<IGranolaConfigRepo>(FSGranolaConfigRepo).singleton(),
codeModeConfigRepo: asClass<ICodeModeConfigRepo>(FSCodeModeConfigRepo).singleton(),
agentScheduleRepo: asClass<IAgentScheduleRepo>(FSAgentScheduleRepo).singleton(),
agentScheduleStateRepo: asClass<IAgentScheduleStateRepo>(FSAgentScheduleStateRepo).singleton(),
slackConfigRepo: asClass<ISlackConfigRepo>(FSSlackConfigRepo).singleton(),
// ACP code-mode engine: the manager holds a live agent connection per chat only
// around an active turn (torn down after a short idle grace; resumed via
// session/load); the registry brokers mid-run approvals.
codeModeManager: asClass(CodeModeManager).singleton(),
codePermissionRegistry: asClass(CodePermissionRegistry).singleton(),
});
export default container;

View file

@ -1,7 +1,10 @@
import { BuiltinTools } from '../application/lib/builtin-tools.js';
export function getRaw(): string {
// code_agent_run needs an interactive UI to answer its permission asks; exclude it
// from this headless agent so it can't hang waiting on an approval no one can give.
const toolEntries = Object.keys(BuiltinTools)
.filter(name => name !== 'code_agent_run')
.map(name => ` ${name}:\n type: builtin\n name: ${name}`)
.join('\n');

View file

@ -152,7 +152,9 @@ Avoid: "I updated the note.", "Done!", "Here is the update:". The summary is a d
export function buildLiveNoteAgent(): z.infer<typeof Agent> {
const tools: Record<string, z.infer<typeof ToolAttachment>> = {};
for (const name of Object.keys(BuiltinTools)) {
if (name === 'executeCommand') continue;
// code_agent_run requires an interactive UI for permission approvals — skip it
// here (headless) so it can't hang on an approval no one can answer.
if (name === 'executeCommand' || name === 'code_agent_run') continue;
tools[name] = { type: 'builtin', name };
}

View file

@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import {
sanitizeReplyBodyForGmailReply,
stripGmailQuotedReplyHtml,
stripGmailQuotedReplyText,
} from './sync_gmail.js';
describe('Gmail reply body sanitization', () => {
it('strips Gmail quote attribution and older quoted text from plain text replies', () => {
const body = [
'Sounds good, thanks. I will send it over today.',
'',
'On Thu, 28 May 2026 at 23:45, PRAKHAR <prakhar9999pandey@gmail.com> wrote:',
'> Can you share the final file?',
'> Thanks',
].join('\n');
expect(stripGmailQuotedReplyText(body)).toBe('Sounds good, thanks. I will send it over today.');
});
it('strips Gmail quote blocks from html replies', () => {
const html = [
'<p>Sounds good, thanks.</p>',
'<div class="gmail_quote">',
'<div dir="ltr" class="gmail_attr">On Thu, 28 May 2026 at 23:45, PRAKHAR wrote:<br></div>',
'<blockquote>Older thread text</blockquote>',
'</div>',
].join('');
expect(stripGmailQuotedReplyHtml(html)).toBe('<p>Sounds good, thanks.</p>');
});
it('regenerates html from clean text if only the text boundary is detected', () => {
const result = sanitizeReplyBodyForGmailReply(
'<p>Sounds good, thanks.</p><p>Older thread text</p>',
'Sounds good, thanks.\n\nOn Thu, 28 May 2026 at 23:45, PRAKHAR <prakhar9999pandey@gmail.com> wrote:\nOlder thread text',
);
expect(result.bodyText).toBe('Sounds good, thanks.');
expect(result.bodyHtml).toBe('<p>Sounds good, thanks.</p>');
});
});

View file

@ -35,7 +35,7 @@ const nhm = new NodeHtmlMarkdown();
// previously cached snapshots (e.g. attachment / recipient parsing fixes). The
// short-circuit in buildAndCacheSnapshot only reuses a cache whose version matches,
// so stale entries are transparently rebuilt on the next sync.
const SNAPSHOT_PARSER_VERSION = 2;
const SNAPSHOT_PARSER_VERSION = 3;
interface SnapshotCacheEntry {
historyId: string;
@ -405,6 +405,112 @@ function normalizeBody(body: string): string {
return body.replace(/\r\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
}
function isGmailQuoteAttribution(line: string): boolean {
const trimmed = line.trim();
return /^On\b.+\bwrote:\s*$/i.test(trimmed);
}
function isOriginalMessageBoundary(line: string): boolean {
return /^-{2,}\s*Original Message\s*-{2,}$/i.test(line.trim());
}
function isForwardedMessageBoundary(line: string): boolean {
return /^-{2,}\s*Forwarded message\s*-{2,}$/i.test(line.trim());
}
function isOutlookHeaderBoundary(lines: string[], index: number): boolean {
if (!/^From:\s+\S/i.test(lines[index]?.trim() || '')) return false;
const next = lines.slice(index + 1, index + 6).map((line) => line.trim());
return next.some((line) => /^(Sent|Date):\s+\S/i.test(line))
&& next.some((line) => /^To:\s+\S/i.test(line))
&& next.some((line) => /^Subject:\s+\S/i.test(line));
}
function findQuotedReplyBoundary(lines: string[]): number {
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i] || '';
if (
isGmailQuoteAttribution(line)
|| isOriginalMessageBoundary(line)
|| isForwardedMessageBoundary(line)
|| isOutlookHeaderBoundary(lines, i)
) {
return i;
}
// Gmail plain text drafts often carry older messages as a quoted block.
// Treat a trailing blockquote as history, but avoid stripping an inline
// quote the user is actively writing at the top of the reply.
if (i > 0 && line.trim().startsWith('>') && (lines[i - 1]?.trim() === '' || lines[i - 1]?.trim().startsWith('>'))) {
return i;
}
}
return -1;
}
export function stripGmailQuotedReplyText(text: string): string {
const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const lines = normalized.split('\n');
const boundary = findQuotedReplyBoundary(lines);
const visible = boundary >= 0 ? lines.slice(0, boundary) : lines;
return visible
.join('\n')
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function htmlQuoteBoundaryIndex(html: string): number {
const candidates: number[] = [];
const patterns = [
/<[^>]+\bclass\s*=\s*["'][^"']*\bgmail_(?:quote|attr)\b[^"']*["'][^>]*>/i,
/<blockquote\b[^>]*(?:type\s*=\s*["']cite["']|class\s*=\s*["'][^"']*\bgmail_quote\b[^"']*["'])[^>]*>/i,
/<(p|div|li)\b[^>]*>\s*(?:<(?:span|b|strong|i|em)\b[^>]*>\s*)*On\b[\s\S]{0,800}?\bwrote:\s*(?:<br\s*\/?>\s*)?(?:<\/(?:span|b|strong|i|em)>\s*)*<\/\1>/i,
/<(p|div|li)\b[^>]*>\s*-{2,}\s*(?:Original Message|Forwarded message)\s*-{2,}\s*<\/\1>/i,
];
for (const pattern of patterns) {
const match = pattern.exec(html);
if (match?.index !== undefined) candidates.push(match.index);
}
return candidates.length > 0 ? Math.min(...candidates) : -1;
}
export function stripGmailQuotedReplyHtml(html: string): string {
const boundary = htmlQuoteBoundaryIndex(html);
const visible = boundary >= 0 ? html.slice(0, boundary) : html;
return visible.trim();
}
function textToHtml(text: string): string {
return text
.split(/\n{2,}/)
.map((para) => `<p>${escapeHtml(para).replace(/\n/g, '<br />')}</p>`)
.join('');
}
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
export function sanitizeReplyBodyForGmailReply(bodyHtml: string, bodyText: string): { bodyHtml: string; bodyText: string } {
const cleanText = stripGmailQuotedReplyText(bodyText);
const cleanHtml = stripGmailQuotedReplyHtml(bodyHtml);
const textWasStripped = cleanText !== bodyText.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
const htmlWasStripped = cleanHtml !== bodyHtml.trim();
return {
bodyText: cleanText,
bodyHtml: textWasStripped && !htmlWasStripped ? textToHtml(cleanText) : cleanHtml,
};
}
function headerValue(headers: gmail.Schema$MessagePartHeader[] | undefined, name: string): string | undefined {
return headers?.find(h => h.name?.toLowerCase() === name.toLowerCase())?.value || undefined;
}
@ -636,9 +742,13 @@ async function buildAndCacheSnapshot(
const sentMessages = parsed.filter((m) => !m.isDraft);
const draftMessages = parsed.filter((m) => m.isDraft);
const visibleMessages = sentMessages.map(({ isDraft: _isDraft, ...rest }) => rest);
const visibleMessages = sentMessages.map((msg) => {
const rest: Partial<typeof msg> = { ...msg };
delete rest.isDraft;
return rest as Omit<typeof msg, 'isDraft'>;
});
const latestDraftBody = draftMessages.length > 0
? draftMessages[draftMessages.length - 1]!.body.trim()
? stripGmailQuotedReplyText(draftMessages[draftMessages.length - 1]!.body)
: '';
if (visibleMessages.length === 0) return null;
@ -674,7 +784,10 @@ async function buildAndCacheSnapshot(
const classification = await classifyThread(snapshot, userEmail, { skipDraft });
snapshot.importance = classification.importance;
if (classification.summary) snapshot.summary = classification.summary;
if (classification.draftResponse) snapshot.draft_response = classification.draftResponse;
if (classification.draftResponse) {
const draftResponse = stripGmailQuotedReplyText(classification.draftResponse);
if (draftResponse) snapshot.draft_response = draftResponse;
}
} catch (err) {
console.warn(`[Gmail] classify failed for ${threadId}:`, err);
}
@ -947,16 +1060,20 @@ async function fullSync(auth: OAuth2Client, syncDir: string, attachmentsDir: str
// If the state file holds a last_sync timestamp (e.g. left over from a
// prior Composio sync, or from a previous successful native sync that
// we're falling back to after a history.list 404), use that as the
// floor instead of the default lookback. Carries forward Composio's
// last_sync on first migration so we don't refetch the last 7 days.
// floor — but never reach back further than lookbackDays. This caps the
// window at "1 week at most": if last_sync is within the lookback window
// we resume from it (a smaller window), otherwise we clamp to lookbackDays
// ago. Mail older than the cap that arrived during a long offline gap is
// intentionally skipped rather than backfilled.
const state = loadState(stateFile);
const lookbackFloor = new Date();
lookbackFloor.setDate(lookbackFloor.getDate() - lookbackDays);
let pastDate: Date;
if (state.last_sync) {
if (state.last_sync && new Date(state.last_sync) > lookbackFloor) {
pastDate = new Date(state.last_sync);
console.log(`Performing full sync from last_sync=${state.last_sync}...`);
} else {
pastDate = new Date();
pastDate.setDate(pastDate.getDate() - lookbackDays);
pastDate = lookbackFloor;
console.log(`Performing full sync of last ${lookbackDays} days...`);
}
@ -1222,12 +1339,22 @@ async function performSync() {
// this runs once, the cache directory is populated and we fall back to
// partial-sync on subsequent calls.
const cacheMissing = !fs.existsSync(CACHE_DIR) || fs.readdirSync(CACHE_DIR).length === 0;
// partialSync replays *every* messageAdded since the stored historyId,
// regardless of date — so after a long offline gap a still-valid
// historyId would pull the entire gap (e.g. 3 weeks). To honor the
// "1 week at most" cap, bypass it when last_sync is older than the
// lookback window and run a (date-clamped) fullSync instead.
const gapMs = state.last_sync ? Date.now() - new Date(state.last_sync).getTime() : 0;
const gapTooLarge = gapMs > LOOKBACK_DAYS * 24 * 60 * 60 * 1000;
if (!state.historyId) {
console.log("No history ID found, starting full sync...");
await fullSync(auth, SYNC_DIR, ATTACHMENTS_DIR, STATE_FILE, LOOKBACK_DAYS);
} else if (cacheMissing) {
console.log("History ID present but inbox cache empty — running full sync to backfill snapshots...");
await fullSync(auth, SYNC_DIR, ATTACHMENTS_DIR, STATE_FILE, LOOKBACK_DAYS);
} else if (gapTooLarge) {
console.log(`Last sync older than ${LOOKBACK_DAYS} days — running full sync clamped to the lookback window instead of partial sync...`);
await fullSync(auth, SYNC_DIR, ATTACHMENTS_DIR, STATE_FILE, LOOKBACK_DAYS);
} else {
console.log("History ID found, starting partial sync...");
await partialSync(auth, state.historyId, SYNC_DIR, ATTACHMENTS_DIR, STATE_FILE, LOOKBACK_DAYS);
@ -1330,6 +1457,10 @@ export async function sendThreadReply(opts: SendReplyOptions): Promise<SendReply
const safeBcc = opts.bcc?.trim() ? requireSafeHeaderValue('Bcc', opts.bcc) : undefined;
const safeInReplyTo = opts.inReplyTo ? requireSafeHeaderValue('In-Reply-To', opts.inReplyTo) : undefined;
const safeReferences = opts.references ? requireSafeHeaderValue('References', opts.references) : undefined;
const replyBody = opts.threadId
? sanitizeReplyBodyForGmailReply(opts.bodyHtml, opts.bodyText)
: { bodyHtml: opts.bodyHtml.trim(), bodyText: opts.bodyText.trim() };
if (!replyBody.bodyText.trim()) return { error: 'Draft is empty.' };
const boundary = `b_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
const headers: string[] = [];
@ -1348,13 +1479,13 @@ export async function sendThreadReply(opts: SendReplyOptions): Promise<SendReply
parts.push('Content-Type: text/plain; charset="UTF-8"');
parts.push('Content-Transfer-Encoding: base64');
parts.push('');
parts.push(encodeMimeBase64(opts.bodyText));
parts.push(encodeMimeBase64(replyBody.bodyText));
parts.push('');
parts.push(`--${boundary}`);
parts.push('Content-Type: text/html; charset="UTF-8"');
parts.push('Content-Transfer-Encoding: base64');
parts.push('');
parts.push(encodeMimeBase64(opts.bodyHtml));
parts.push(encodeMimeBase64(replyBody.bodyHtml));
parts.push('');
parts.push(`--${boundary}--`);

View file

@ -8,6 +8,7 @@ const SIGNED_IN_DEFAULT_MODEL = "gpt-5.4";
const SIGNED_IN_DEFAULT_PROVIDER = "rowboat";
const SIGNED_IN_KG_MODEL = "google/gemini-3.1-flash-lite";
const SIGNED_IN_LIVE_NOTE_AGENT_MODEL = "google/gemini-3.1-flash-lite";
const SIGNED_IN_AUTO_PERMISSION_DECISION_MODEL = "google/gemini-3.1-flash-lite";
/**
* The single source of truth for "what model+provider should we use when
@ -76,6 +77,17 @@ export async function getLiveNoteAgentModel(): Promise<string> {
return cfg.liveNoteAgentModel ?? cfg.model;
}
/**
* Model used by the auto-permission classifier.
* Signed-in: curated default. BYOK: user override
* (`autoPermissionDecisionModel`) or assistant model.
*/
export async function getAutoPermissionDecisionModel(): Promise<string> {
if (await isSignedIn()) return SIGNED_IN_AUTO_PERMISSION_DECISION_MODEL;
const cfg = await container.resolve<IModelConfigRepo>("modelConfigRepo").getConfig();
return cfg.autoPermissionDecisionModel ?? cfg.model;
}
/**
* Model used by the meeting-notes summarizer. No special signed-in default
* historically meetings used the assistant model. BYOK: user override

View file

@ -53,6 +53,7 @@ export class FSModelConfigRepo implements IModelConfigRepo {
knowledgeGraphModel: config.knowledgeGraphModel,
meetingNotesModel: config.meetingNotesModel,
liveNoteAgentModel: config.liveNoteAgentModel,
autoPermissionDecisionModel: config.autoPermissionDecisionModel,
};
const toWrite = { ...config, providers: existingProviders };

View file

@ -35,6 +35,7 @@ export type CreateRunRepoOptions = {
agentId: string;
model: string;
provider: string;
permissionMode: "manual" | "auto";
useCase: z.infer<typeof UseCase>;
subUseCase?: string;
};
@ -204,6 +205,7 @@ export class FSRunsRepo implements IRunsRepo {
agentName: options.agentId,
model: options.model,
provider: options.provider,
permissionMode: options.permissionMode,
useCase: options.useCase,
...(options.subUseCase ? { subUseCase: options.subUseCase } : {}),
subflow: [],
@ -216,6 +218,7 @@ export class FSRunsRepo implements IRunsRepo {
agentId: options.agentId,
model: options.model,
provider: options.provider,
permissionMode: options.permissionMode,
useCase: options.useCase,
...(options.subUseCase ? { subUseCase: options.subUseCase } : {}),
log: [start],
@ -251,6 +254,7 @@ export class FSRunsRepo implements IRunsRepo {
agentId: start.agentName,
model: start.model,
provider: start.provider,
permissionMode: start.permissionMode ?? "manual",
...(start.useCase ? { useCase: start.useCase } : {}),
...(start.subUseCase ? { subUseCase: start.subUseCase } : {}),
log: events,
@ -320,4 +324,4 @@ export class FSRunsRepo implements IRunsRepo {
async delete(id: string): Promise<void> {
await fsp.unlink(runLogPath(id));
}
}
}

View file

@ -32,6 +32,7 @@ export async function createRun(opts: z.infer<typeof CreateRunOptions>): Promise
agentId: opts.agentId,
model,
provider,
permissionMode: opts.permissionMode ?? "manual",
useCase,
...(opts.subUseCase ? { subUseCase: opts.subUseCase } : {}),
});
@ -39,9 +40,9 @@ export async function createRun(opts: z.infer<typeof CreateRunOptions>): Promise
return run;
}
export async function createMessage(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext): Promise<string> {
export async function createMessage(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext, codeMode?: 'claude' | 'codex'): Promise<string> {
const queue = container.resolve<IMessageQueue>('messageQueue');
const id = await queue.enqueue(runId, message, voiceInput, voiceOutput, searchEnabled, middlePaneContext);
const id = await queue.enqueue(runId, message, voiceInput, voiceOutput, searchEnabled, middlePaneContext, codeMode);
const runtime = container.resolve<IAgentRuntime>('agentRuntime');
runtime.trigger(runId);
return id;

View file

@ -0,0 +1,112 @@
import { generateObject, type ModelMessage } from "ai";
import z from "zod";
import { ToolPermissionMetadata } from "@x/shared/dist/runs.js";
import { ToolCallPart } from "@x/shared/dist/message.js";
import { captureLlmUsage } from "../analytics/usage.js";
import { withUseCase, type UseCase } from "../analytics/use_case.js";
import { getAutoPermissionDecisionModel, getDefaultModelAndProvider, resolveProviderConfig } from "../models/defaults.js";
import { createProvider } from "../models/models.js";
const DecisionSchema = z.object({
decisions: z.array(z.object({
toolCallId: z.string(),
decision: z.enum(["allow", "deny"]),
reason: z.string().min(1),
})),
});
export type AutoPermissionCandidate = {
toolCall: z.infer<typeof ToolCallPart>;
permission: z.infer<typeof ToolPermissionMetadata>;
};
export type AutoPermissionDecision = {
toolCallId: string;
decision: "allow" | "deny";
reason: string;
};
const SYSTEM_PROMPT = `You decide whether a personal productivity app may run tool calls without interrupting the user.
You only receive tool calls that already require permission under deterministic rules.
Allow a tool call only when it is clearly consistent with the user's request and low risk.
Deny tool calls that are destructive, credential-sensitive, privacy-sensitive, broad in scope, likely irreversible, or not clearly requested.
Command examples to deny unless explicitly requested: deleting data, force pushing, deploying, running migrations, changing permissions, reading secrets, exfiltrating tokens, or modifying files outside the user's workspace.
File examples to deny unless explicitly requested: deleting paths, writing outside the workspace, reading secrets or credentials, or broad access to private directories.
Return one decision for every toolCallId. Use the exact toolCallId values provided.`;
function compact(value: unknown, max = 8_000): string {
const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
if (text.length <= max) return text;
return `${text.slice(0, max)}\n...<truncated>`;
}
function recentContext(messages: ModelMessage[]): unknown[] {
return messages.slice(-8).map((message) => {
if (typeof message.content === "string") {
return { role: message.role, content: compact(message.content, 2_000) };
}
return { role: message.role, content: compact(message.content, 3_000) };
});
}
function buildPrompt(input: {
agentName: string | null;
messages: ModelMessage[];
candidates: AutoPermissionCandidate[];
}) {
return compact({
agentName: input.agentName,
recentConversation: recentContext(input.messages),
toolCalls: input.candidates.map(({ toolCall, permission }) => ({
toolCallId: toolCall.toolCallId,
toolName: toolCall.toolName,
arguments: toolCall.arguments,
permission,
})),
}, 24_000);
}
export async function classifyToolPermissions(input: {
runId: string;
agentName: string | null;
messages: ModelMessage[];
candidates: AutoPermissionCandidate[];
useCase: UseCase;
subUseCase?: string | null;
}): Promise<AutoPermissionDecision[]> {
if (input.candidates.length === 0) return [];
const modelId = await getAutoPermissionDecisionModel();
const { provider: providerName } = await getDefaultModelAndProvider();
const providerConfig = await resolveProviderConfig(providerName);
const model = createProvider(providerConfig).languageModel(modelId);
const result = await withUseCase(
{
useCase: input.useCase,
subUseCase: "auto_permission_classifier",
...(input.agentName ? { agentName: input.agentName } : {}),
},
() => generateObject({
model,
system: SYSTEM_PROMPT,
prompt: buildPrompt(input),
schema: DecisionSchema,
}),
);
captureLlmUsage({
useCase: input.useCase,
subUseCase: "auto_permission_classifier",
model: modelId,
provider: providerName,
usage: result.usage,
});
const allowedIds = new Set(input.candidates.map((candidate) => candidate.toolCall.toolCallId));
return result.object.decisions.filter((decision) => allowedIds.has(decision.toolCallId));
}

View file

@ -0,0 +1,70 @@
import z from "zod";
// Shared zod schemas for the ACP code-mode engine. Single source of truth: the
// core engine re-exports the inferred TS types, and runs.ts builds the RunEvent
// variants that carry these to the renderer.
export const CodingAgent = z.enum(["claude", "codex"]);
export type CodingAgent = z.infer<typeof CodingAgent>;
// How the permission broker answers the agent's requests before any per-tool
// "always allow" memory is applied. `yolo` is the safe, scoped equivalent of
// `claude --dangerously-skip-permissions` (our toggle, not a CLI flag).
export const ApprovalPolicy = z.enum(["ask", "auto-approve-reads", "yolo"]);
export type ApprovalPolicy = z.infer<typeof ApprovalPolicy>;
export const PermissionDecision = z.enum(["allow_once", "allow_always", "reject"]);
export type PermissionDecision = z.infer<typeof PermissionDecision>;
// What the UI needs to render a permission card.
export const PermissionAsk = z.object({
toolCallId: z.string().optional(),
title: z.string(),
kind: z.string().optional(), // tool kind, e.g. "edit" | "execute" | "read"
isRead: z.boolean(),
});
export type PermissionAsk = z.infer<typeof PermissionAsk>;
// Normalized per-run stream items. The engine maps raw ACP session/update
// notifications onto this union; the renderer renders them.
export const CodeRunEvent = z.discriminatedUnion("type", [
// role distinguishes the agent's own output from replayed user turns
// (loadSession streams the whole prior conversation back on resume).
z.object({ type: z.literal("message"), role: z.enum(["agent", "user"]), text: z.string() }),
z.object({ type: z.literal("thought") }),
z.object({
type: z.literal("tool_call"),
id: z.string().optional(),
title: z.string().optional(),
kind: z.string().optional(),
status: z.string().optional(),
}),
z.object({
type: z.literal("tool_call_update"),
id: z.string().optional(),
status: z.string().optional(),
diffs: z.array(z.string()),
}),
z.object({
type: z.literal("plan"),
entries: z.array(z.object({
content: z.string(),
status: z.string().optional(),
priority: z.string().optional(),
})),
}),
z.object({
type: z.literal("permission"),
ask: PermissionAsk,
decision: z.union([PermissionDecision, z.literal("cancelled")]),
auto: z.boolean(),
}),
z.object({ type: z.literal("other"), sessionUpdate: z.string() }),
]);
export type CodeRunEvent = z.infer<typeof CodeRunEvent>;
export const RunPromptResult = z.object({
stopReason: z.string(),
sessionId: z.string(),
});
export type RunPromptResult = z.infer<typeof RunPromptResult>;

View file

@ -19,6 +19,7 @@ import { ZListToolkitsResponse } from './composio.js';
import { BrowserStateSchema } from './browser-control.js';
import { BillingInfoSchema } from './billing.js';
import { EmailBlockSchema, GmailThreadSchema } from './blocks.js';
import { PermissionDecision, ApprovalPolicy } from './code-mode.js';
// ============================================================================
// Runtime Validation Schemas (Single Source of Truth)
@ -38,6 +39,7 @@ const ipcSchemas = {
res: z.object({
installationId: z.string(),
apiUrl: z.string(),
appVersion: z.string(),
}),
},
'workspace:getRoot': {
@ -228,6 +230,7 @@ const ipcSchemas = {
voiceInput: z.boolean().optional(),
voiceOutput: z.enum(['summary', 'full']).optional(),
searchEnabled: z.boolean().optional(),
codeMode: z.enum(['claude', 'codex']).optional(),
middlePaneContext: z.discriminatedUnion('kind', [
z.object({
kind: z.literal('note'),
@ -290,6 +293,15 @@ const ipcSchemas = {
}),
res: z.object({ success: z.boolean() }),
},
'runs:downloadLog': {
req: z.object({
runId: z.string().min(1),
}),
res: z.object({
success: z.boolean(),
error: z.string().optional(),
}),
},
'runs:events': {
req: z.null(),
res: z.null(),
@ -415,6 +427,39 @@ const ipcSchemas = {
enabled: z.boolean(),
}),
},
'codeMode:getConfig': {
req: z.null(),
res: z.object({
enabled: z.boolean(),
approvalPolicy: ApprovalPolicy.optional(),
}),
},
'codeMode:setConfig': {
req: z.object({
enabled: z.boolean(),
approvalPolicy: ApprovalPolicy.optional(),
}),
res: z.object({
success: z.literal(true),
}),
},
// Answer a mid-run permission request from a code_agent_run coding turn.
'codeRun:resolvePermission': {
req: z.object({
requestId: z.string(),
decision: PermissionDecision,
}),
res: z.object({
success: z.literal(true),
}),
},
'codeMode:checkAgentStatus': {
req: z.null(),
res: z.object({
claude: z.object({ installed: z.boolean(), signedIn: z.boolean() }),
codex: z.object({ installed: z.boolean(), signedIn: z.boolean() }),
}),
},
'granola:setConfig': {
req: z.object({
enabled: z.boolean(),

View file

@ -50,9 +50,29 @@ export const UserContentPart = z.union([UserTextPart, UserAttachmentPart]);
// Named type for user message content — used everywhere instead of repeating the union
export const UserMessageContent = z.union([z.string(), z.array(UserContentPart)]);
export const UserMessageContext = z.object({
currentDateTime: z.string().optional(),
middlePane: z.discriminatedUnion("kind", [
z.object({
kind: z.literal("empty"),
}),
z.object({
kind: z.literal("note"),
path: z.string(),
content: z.string(),
}),
z.object({
kind: z.literal("browser"),
url: z.string(),
title: z.string(),
}),
]).optional(),
});
export const UserMessage = z.object({
role: z.literal("user"),
content: UserMessageContent,
userMessageContext: UserMessageContext.optional(),
providerOptions: ProviderOptions.optional(),
});
@ -86,4 +106,4 @@ export const Message = z.discriminatedUnion("role", [
UserMessage,
]);
export const MessageList = z.array(Message);
export const MessageList = z.array(Message);

View file

@ -17,10 +17,15 @@ export const LlmModelConfig = z.object({
headers: z.record(z.string(), z.string()).optional(),
model: z.string().optional(),
models: z.array(z.string()).optional(),
knowledgeGraphModel: z.string().optional(),
meetingNotesModel: z.string().optional(),
liveNoteAgentModel: z.string().optional(),
autoPermissionDecisionModel: z.string().optional(),
})).optional(),
// Per-category model overrides (BYOK only — signed-in users always get
// the curated gateway defaults). Read by helpers in core/models/defaults.ts.
knowledgeGraphModel: z.string().optional(),
meetingNotesModel: z.string().optional(),
liveNoteAgentModel: z.string().optional(),
autoPermissionDecisionModel: z.string().optional(),
});

View file

@ -1,5 +1,6 @@
import { LlmStepStreamEvent } from "./llm-step-events.js";
import { Message, ToolCallPart } from "./message.js";
import { CodeRunEvent as CodeRunEventSchema, PermissionAsk } from "./code-mode.js";
import z from "zod";
const BaseRunEvent = z.object({
@ -21,6 +22,7 @@ export const StartEvent = BaseRunEvent.extend({
agentName: z.string(),
model: z.string(),
provider: z.string(),
permissionMode: z.enum(["manual", "auto"]).optional(),
// useCase/subUseCase tag the run for analytics. Optional on read so legacy
// run files written before these fields existed still parse cleanly.
useCase: z.enum([
@ -75,6 +77,7 @@ export const AskHumanRequestEvent = BaseRunEvent.extend({
type: z.literal("ask-human-request"),
toolCallId: z.string(),
query: z.string(),
options: z.array(z.string()).optional(),
});
export const AskHumanResponseEvent = BaseRunEvent.extend({
@ -109,6 +112,32 @@ export const ToolPermissionResponseEvent = BaseRunEvent.extend({
scope: z.enum(["once", "session", "always"]).optional(),
});
// A structured item from a code_agent_run coding turn (tool call, diff, plan,
// message chunk, resolved permission). Fire-and-forget — rendered live.
export const CodeRunStreamEvent = BaseRunEvent.extend({
type: z.literal("code-run-event"),
toolCallId: z.string(),
event: CodeRunEventSchema,
});
// The coding agent is asking for permission mid-turn and the run is BLOCKED until
// the user answers via `codeRun:resolvePermission` (keyed by requestId).
export const CodeRunPermissionRequestEvent = BaseRunEvent.extend({
type: z.literal("code-run-permission-request"),
toolCallId: z.string(),
requestId: z.string(),
ask: PermissionAsk,
});
export const ToolPermissionAutoDecisionEvent = BaseRunEvent.extend({
type: z.literal("tool-permission-auto-decision"),
toolCallId: z.string(),
toolCall: ToolCallPart,
permission: ToolPermissionMetadata.optional(),
decision: z.enum(["allow", "deny"]),
reason: z.string(),
});
export const RunErrorEvent = BaseRunEvent.extend({
type: z.literal("error"),
error: z.string(),
@ -133,6 +162,9 @@ export const RunEvent = z.union([
AskHumanResponseEvent,
ToolPermissionRequestEvent,
ToolPermissionResponseEvent,
CodeRunStreamEvent,
CodeRunPermissionRequestEvent,
ToolPermissionAutoDecisionEvent,
RunErrorEvent,
RunStoppedEvent,
]);
@ -165,6 +197,7 @@ export const Run = z.object({
agentId: z.string(),
model: z.string(),
provider: z.string(),
permissionMode: z.enum(["manual", "auto"]).optional(),
useCase: UseCase.optional(),
subUseCase: z.string().optional(),
log: z.array(RunEvent),
@ -184,6 +217,7 @@ export const CreateRunOptions = z.object({
agentId: z.string(),
model: z.string().optional(),
provider: z.string().optional(),
permissionMode: z.enum(["manual", "auto"]).optional(),
useCase: UseCase.optional(),
subUseCase: z.string().optional(),
});

View file

@ -0,0 +1,15 @@
diff --git a/bin/codex.js b/bin/codex.js
index 67ab3e2d95dfac1c91882578b5403916c3121484..f8030b6e1459e05161af99e152b2e7f65ea6c41d 100644
--- a/bin/codex.js
+++ b/bin/codex.js
@@ -175,6 +175,10 @@ env[packageManagerEnvVar] = "1";
const child = spawn(binaryPath, process.argv.slice(2), {
stdio: "inherit",
env,
+ // Native console-subsystem binary: without this Windows pops a visible console
+ // window when launched from a console-less (Electron GUI) parent. Closing that
+ // window wedges the agent. CREATE_NO_WINDOW keeps the console hidden.
+ windowsHide: true,
});
child.on("error", (err) => {

692
apps/x/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -13,3 +13,5 @@ onlyBuiltDependencies:
- fs-xattr
- macos-alias
- protobufjs
patchedDependencies:
'@openai/codex@0.128.0': patches/@openai__codex@0.128.0.patch