diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index cdca70f2..08891c3a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,6 +35,12 @@ jobs: - run: npm install --global npm@^11.5.1 - run: npm ci + # The package's Windows tray, built from this tag's native/tray rather than the committed copy (ompweb-dev/ompweb#530). + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0 + with: + dotnet-version: 8.0.x + - name: Build the Windows tray + run: sh scripts/build-tray.sh # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. - name: Install pi run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 52fc8642..8b9f054b 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -52,6 +52,15 @@ jobs: - name: Install dependencies run: npm ci + # What publish.yml runs before npm publish: the tray must build from these sources and carry this commit. + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0 + if: runner.os == 'Linux' + with: + dotnet-version: 8.0.x + - name: Build the Windows tray (Linux only) + if: runner.os == 'Linux' + run: sh scripts/build-tray.sh + # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. - name: Install pi run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" diff --git a/AGENTS.md b/AGENTS.md index a86a07e0..c4f0f455 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -140,9 +140,9 @@ app/api/ sessions/search/route.ts GET ?q= NDJSON { scores } batches (titles + per-host transcripts) sessions/import/route.ts POST import a session .jsonl sessions/archive/route.ts GET archives of every host | POST restore (see "Session archive and restore") - sessions/[id]/route.ts GET/PATCH/DELETE a session + sessions/[id]/route.ts GET/PATCH/DELETE a session; GET ?meta=1 answers the navigation shape (tree + leaf, no transcript), ?includeState=alive the split liveness shape (`running` = a turn in flight, `alive` = the child exists) sessions/[id]/state/route.ts GET live state; always carries `outbox`, `outboxSettledIds`, `outboxScope` - sessions/[id]/context/route.ts GET ?leafId= context of one leaf (read-only branch view) + sessions/[id]/context/route.ts GET ?leafId= context of one leaf (read-only branch view); strong ETag, 304 on a matching If-None-Match sessions/[id]/entries/[entryId]/thinking/route.ts GET one deferred thinking block sessions/[id]/matches/route.ts GET ?q=&limit= best search hits in the active conversation sessions/[id]/export/route.ts GET exported HTML (`tau-session-.html`; a remote session's always as an attachment) @@ -150,7 +150,7 @@ app/api/ sessions/[id]/auto-name/route.ts POST stored title, else one derived from the first user message (`generated` always false) sessions/[id]/subagents/route.ts, subagents/[subagentId]/route.ts subagent roster history and transcripts agent/new/route.ts POST start a session (host, pool or cluster target) - agent/[id]/route.ts GET state | POST any agent command (`runAgentCommand`) + agent/[id]/route.ts GET state (?systemPrompt=0 drops the system prompt from the poll) | POST any agent command (`runAgentCommand`) agent/[id]/bash-output/route.ts GET streamed `!` command output events/route.ts GET the multiplexed SSE | POST subscribe/unsubscribe channels transport-metrics/route.ts GET { now } (clock probe) | POST { samples } → /tau/transport-metrics.jsonl @@ -177,7 +177,7 @@ app/api/ worktrees/route.ts GET/POST/DELETE git worktrees on the owning daemon files/[...path], file-index, git/status, git/diff, cwd/browse, cwd/validate, default-cwd, home, github-repo workspace reads (daemon-owned) media/[hash]/route.ts GET tool-result image by sha256 (?thumb=1 → 480px WebP) - notifications/devices, presence, history push devices, presence reports, notification history + notifications/devices, presence, history, answer push devices, presence reports, notification history, answering a pending dialog stt/route.ts, stt/[jobId]/route.ts, stt/[jobId]/audio/route.ts transcription jobs uploads/route.ts, uploads/[id]/route.ts composer uploads (start/resume, chunks, abort) usage/route.ts, manifest/route.ts usage report; web app manifest @@ -311,7 +311,7 @@ The table is static imports, not a runtime glob, so `bun build --compile` bundle ### Remote hosts (`lib/hosts/`, `app/api/hosts/`, `bin/tau-host.js`) - **Host seam** (`lib/hosts/host.ts`). Every host, this machine included, is reached over its daemon's link: `getHost(id)` returns a `RemoteHost`. `getHost("local")` is this machine's own `tau host`. `localHost` (`local-host.ts`) is the daemon's side. `RpcProcess`, the wrapper, the event hub, notifications, the queue and `/btw` never see where pi runs. Session and project file reads are `host.sessionOps` (`session-ops.ts`, run in the daemon), addressed by session id, never by path: routes use `resolveSessionHostOr404` (`lib/api-utils.ts`). New route code must not open a session file on main. Workspace operations (files, index, shell output, watch, Git/worktrees, browsing, default cwd `~/tau-cwd-YYYYMMDD`, clone) are `Host.workspaceOps` (`lib/workspace-types.ts`, `workspace-ops.ts`) for every host; they never fall back to main. `SessionInfo.hostId` and `ManagedProject.hostId` carry the host; sidebar/project state keys on `hostProjectKey` (bare path here, `:` elsewhere). -- **Shared hosts** (`docs/specs/2026-11-06-multi-server-host-design.md`): one daemon links every server in `host.json` (the top-level pair is its primary link, `links` the others). `open` joins one session process; events fan out, command replies return only to their sender. The daemon owns lifecycle, streaming snapshots (`stream-snapshot.ts`) and first-answer dialog settlement (`shared-requests.ts`). Web callbacks (host tools) go to the last-active eligible server and are not blindly retried. `channels_changed` announces background runs; `sessions_changed` invalidates lists; one link is the notification publisher (`notifier`). Cross-server fences live in the daemon: a history edit takes the `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo ambiguous (`watchReplacement`). An open's preparation lease passes only to the command that asked for it (`withPendingCommand(run, true)`); a command timeout that recycles the child stops the shared process (`destroyAndWait(reason, true)`). Two daemons must never run competing `pi --resume` children on one agent dir. +- **Shared hosts** (`docs/specs/2026-11-06-multi-server-host-design.md`): one daemon links every server in `host.json` (the top-level pair is its primary link, `links` the others). `open` joins one session process; events fan out, command replies return only to their sender. The daemon owns lifecycle, streaming snapshots (`stream-snapshot.ts`) and first-answer dialog settlement (`shared-requests.ts`). Web callbacks (host tools) go to the last-active eligible server and are not blindly retried. `channels_changed` announces background runs; `sessions_changed` invalidates lists; `pi_version` reports pi found after a hello that said none (the daemon reads it again, 30 s doubling to 5 min); one link is the notification publisher (`notifier`). Cross-server fences live in the daemon: a history edit takes the `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo ambiguous (`watchReplacement`). An open's preparation lease passes only to the command that asked for it (`withPendingCommand(run, true)`); a command timeout that recycles the child stops the shared process (`destroyAndWait(reason, true)`). Two daemons must never run competing `pi --resume` children on one agent dir. - **Application link** (`/api/hosts/link`, `link-protocol.ts`, `hub.ts`, `daemon-link.ts`, `daemon-channels.ts`): one WebSocket per host per web server, dialled by the daemon. Text frames carry messages (hub → daemon one per frame; daemon → hub newline-separated batches flushed every `flushMs` (16 ms) or at one piece); binary frames carry large op results (before the `res` naming them) and upload bytes (hub → daemon, `up:`). Every line except `hello`/`welcome`/`ack`/`ping`/`pong` has a per-direction `seq`; each side keeps unacked lines, resends after a reconnect and drops a `seq` it already applied. The daemon's first line of every frame is an `ack`; the hub answers every uplink frame with exactly one. Lines over `pieceBytes` (256 KiB) go as sequenced `part` messages (`PartJoiner`), results as binary frames of at most a piece; both sides queue per key (channel or request) in `LinkSender` and send round-robin. Each side sends queued units only while less than `unackedBytes` (512 KiB) is unacked (the daemon also waits for `bufferedAmount` under two pieces); control lines skip the window. The hub decodes a whole frame before applying any of it. `hello.ack === 0` means a fresh daemon. Each `hello.channels` entry carries `pending`: the raw stdout lines of that child's still-open `host_tool_call`s and blocking `ui_request`s (`pending-requests.ts`), or null past `pendingBytes`. Close codes (`LINK_CLOSE`): 1001 going away (shutdown), 1007 bad frame, 1008 bad first frame, 1009 too big, 4409 replaced, 4426 version; a revoked or unknown host's hello gets a plain close. - **Protocol versions.** The application link is v1 (`MIN_LINK_PROTOCOL_VERSION` = `LINK_PROTOCOL_VERSION` = 1, literal one-liners that deploy scripts parse with `sed`). A released version changes only compatibly: an added optional field or a message type receivers skip is fine; a changed type or meaning, or a newly required field, needs a new version. Receivers skip unknown message types (acking their `seq`) and answer unknown ops 501 `unknown_op`. A hello outside the range gets 4426 with `{"serverVersion":N}`. Once versions are released, main keeps at least N-1, and the first released version is a floor `MIN_LINK_PROTOCOL_VERSION` never goes above. Upgrade order: web app first, then hosts. - **Maintenance API v1** (`maintenance-protocol.ts`, `maintenance-hub.ts`, `daemon-maintenance.ts`, `/api/hosts/maintenance`): a separate request/reply WebSocket the daemon dials with the same bearer token, versioned apart (`MAINTENANCE_API_VERSION`) and kept stable so a host whose application protocol differs can still be inspected and updated. Ops: `status`, `listSessions`, `checkUpdates`, `updateSoftware`. Frames ≤ 1 MiB, 8 requests in flight, 30 s per request; a hello with another API version gets 4426 `{"apiVersion":N}`. Its hello reports `protocolVersion` (advisory), `tauVersion`, `piVersion`, platform and capabilities. Nothing it meets (no API on the server, another version, a refused token) stops the daemon or its pi children. Host updates use only this API (see "Updates"). @@ -437,6 +437,8 @@ pi's wire `message_update` is delta-only (pi `docs/json.md`): `usage` and `assis - `lib/event-stream-worker.ts` (SharedWorker; dedicated Worker where SharedWorker is missing) holds the browser's one `/api/events` EventSource and multiplexes every tab's subscriptions: frames arrive as `event: `, control frames as `event: mux` (`hello`/`open`/`end`); subscriptions are attached with `POST /api/events`. Tabs POST their agent commands and uploads themselves. `buildEventStreamWorker` bundles it into `dist/event-stream-worker.js`, whose URL carries the content hash. - Tabs use `openEventStream(channel)` (`lib/event-stream.ts`) with EventSource semantics: `onerror` + CONNECTING = reconnecting, CLOSED = fatal (e.g. 409 for a wrapper-less session). Dead tabs are detected with a lifetime Web Lock. - Channels (`event-stream-hub.ts`): `running` (badges + list hints), `notifications` (one tab's, by `clientId`), `hosts` (the `GET /api/hosts` body), `host-tools` (cross-session `open_url`/`notify`/`open_file`), `session` (observer-only, never spawns pi; merges `message_update`s under backpressure), `file` (viewer watch, same allow-list as `/api/files`). A failing frame ends only its own subscription. Split channels by consumer, lifetime, key and access check; `notifications` and `host-tools` are subscribed from `AppShell`. +- **Tool snapshots** (`event-stream-hub.ts`, session channel): pi sends the whole accumulated output on every `tool_execution_update`, so the newest snapshot per `toolCallId` is held outside the ordered message queue and written at most once per `TOOL_UPDATE_FRAME_MIN_INTERVAL_MS` of that tool. Any other session frame is a boundary that releases every held snapshot ahead of itself in emission order, so nothing is dropped or reordered within a domain; across domains an older sequence may arrive later, which the browser's separate floors (`hooks/useAgentSession-sync.ts`) allow. A written snapshot is stamped with its write time. +- **Native-client handshake and keep-alive.** `GET /api/app-info` (behind the `/api` gate, `no-store`) answers `{ name, version, api: 1, capabilities }`: package identity and which server-side features exist, never a credential or setting. A capability is added only with its implementation; today it carries `heartbeatParam`. `GET /api/events?heartbeat=` sets that connection's keep-alive comment frame: an integer in 15..110, anything else the 30 s default (not clamped). A value above the reverse proxy's read timeout (nginx: 60 s) drops an idle stream before its first keep-alive. - **Metrics.** Tabs and the worker record `action`, `event`, `reconnect`, `hang` and `dropped` samples; the worker POSTs them to `/api/transport-metrics` every 30 s or 200 samples. One worker-wide clock (lowest RTT of recent probes) times them. - **Connection tab** (right panel, while "Show connection diagnostics" is on, `tau:connection-diagnostics`): polls the worker (`diag`) once a second; status, last reconnect and per-transport stats (`lib/transport-stats.ts`) over the last 30 min. Command rows include confirmed replies only; app ↔ pi rows skip commands the web app answers itself (`NO_SPAWN_REPLIES` and friends). - **Worker rules.** No `AbortSignal.timeout`/`any` or `Promise.withResolvers` (a test checks the bundle). Every global it uses must be injectable into the `vm` context of `lib/event-stream-worker.test.mjs`. Ids use `Math.random().toString(36).slice(2, 12) + Date.now().toString(36)` (insecure LAN origins lack `crypto.randomUUID`). @@ -561,7 +563,8 @@ The todo plan (`TodoList`) and subagent roster sit pinned above the input, each ### Notifications (`lib/notification-*.ts`, `public/sw.js`, Settings → Notifications) - Detection runs on the server in `AgentSessionWrapper.handleFrame` (and `handleProcessExit`), so unwatched sessions notify. `createNotificationDetector()` inspects top-level frames only (subagent frames never notify). "Completed" fires on `session_settled`; a failed or aborted last prompt suppresses it. A refused message command reaches only the server that sent it (pi answers it only in that command's `response`). Failures arrive as `prompt_error` and `process_exit`; one failure per run. A crash notifies "Run failed" while a run or its background work is unsettled. - **Presence vs streams.** Tabs report `{clientId, deviceId, visible, sessionId, seq}` to `/api/notifications/presence` (on change, input after idling, every 30 s; expires 60 s after receipt; `visible` = visible and input within 3 min; `sessionId` null while Settings hides the chat; an older `seq` is dropped). Streams are the tab's open `notifications` subscriptions. Prefs PUTs run one at a time. -- **Routing** (`routeNotification`): a visible tab on the session drops the event everywhere; else, with a visible connected tab, `whenActive: "toast"` devices get a toast on their active tabs; else push (subscribed devices) or in-page `showNotification`. The server decides before pushing (iOS revokes permission for silent pushes; `sw.js` always shows what it receives). +- **Routing** (`routeNotification`): a visible tab on the session drops the event everywhere; else, with a visible connected tab, `whenActive: "toast"` devices get a toast on their active tabs; else push (subscribed devices) or in-page `showNotification`. The server decides before pushing (iOS revokes permission for silent pushes; `sw.js` always shows what it receives), so a settled dialog is retracted on the tab streams only (`{type: "notification-dismiss", tag, sessionId, requestId}`), never by a push. +- **Answering from a notification.** An `input` notification carries its blocking dialog (`confirm`, `select`, `input`, `editor`, `ask`) as `dialog` when the whole dialog fits the push budget, never clipped. `POST /api/notifications/answer {sessionId, requestId, response}` answers it through the same `ui_response` path the web dialog uses, checked against the pending dialog first (400 leaves it answerable); it never spawns pi (`sessionGone`, `alreadySettled` are 200s). - Prefs and subscriptions are per device (`localStorage`, mirrored to the SQLite store in `/tau/`, 0600, WAL; it holds the VAPID key and the history). Push text is rendered server-side in the device's locale. - `/sw.js` and `/badge-96.png` are ungated. Clicks survive an expired sign-in: `proxy.ts` sends `/?session=…` to `/login?next=…`, and `LoginForm` accepts only `/?…` targets. - The history (`lib/notification-history.ts`, `/api/notifications/history`) keeps the newest 100 of every type some device enabled, already read when a visible tab shows that session; shown by `NotificationBell` (desktop popover) and the right panel's Notifications tab (mobile). Entries become read when the list closes, on Mark all as read or when opened (`OPEN_SESSION_EVENT`, `tau-open-session`); a reused id (`:`) is unread again. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ac8ab75..ce7ebeab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ All notable changes to **tau** (`@ompweb-dev/tau`) are documented in this file. ## [Unreleased] +### Added + +- **Answer a waiting question from the notification itself.** A notification for a blocking dialog (confirm, select, input, editor, or the ask tool's questions) carries the dialog when it fits a push in full, so a phone or a native client can answer without opening the session: `POST /api/notifications/answer` takes the session id, the dialog's request id and one response. The answer goes through the same path as the web dialog and is checked against the pending dialog first; a settled dialog's notification is retracted on every open tab. (ompweb-dev/ompweb#414) +- **Native clients can read a session without its transcript.** `GET /api/sessions/[id]?meta=1` answers only the message tree and current leaf, `?includeState=alive` splits liveness into `running` and `alive`, `GET /api/agent/[id]?systemPrompt=0` drops the system prompt from the state poll, and `GET /api/sessions/[id]/context` answers a strong ETag and 304. (ompweb-dev/ompweb#415) +- **`GET /api/app-info` and a per-connection heartbeat.** Native clients read the package identity and capabilities, and `GET /api/events?heartbeat=<15..110>` chooses that stream's keep-alive interval. (ompweb-dev/ompweb#407) +- **Browse… opens the OS folder dialog** in the directory picker when the page is opened on the server's own desktop. (ompweb-dev/ompweb#544) +- **Fullscreen composer and collapsed long messages.** The composer opens a fullscreen editor for long prompts, and a long sent message collapses to one line. (ompweb-dev/ompweb#556) +- **`svg` code fences render inline**, sanitized and themed. (ompweb-dev/ompweb#455) + ### Changed - **tau runs sessions on pi.** Every session is a `pi --mode rpc` child (`@earendil-works/pi-coding-agent`, found on `PATH` or through `TAU_PI_BIN`) loaded with tau's companion extension (`lib/pi/tau-extension.ts`), which adds host tools, the `ask` dialog, message origins, `/btw`, history Edit and per-host provider logins. The ompweb omp runner, its pinned release and `fetch-omp` are gone. tau keeps pi's state in `~/.pi/agent` (sessions, `settings.json`, `models.json`), lists and installs pi packages and skills instead of omp plugins, and mirrors pi's configuration to cluster members. The host link starts again at protocol v1, and host software updates go through a separately versioned maintenance API. tau shares no state with ompweb: hosts, settings and sessions are set up anew. The routes `/api/omp-settings` and `/api/omp-version` are now `/api/pi-settings` and `/api/pi-version`, a host without pi reports `pi-missing`, and the unused `/api/omp-update` route is removed. @@ -15,6 +24,19 @@ All notable changes to **tau** (`@ompweb-dev/tau`) are documented in this file. ### Fixed +- **In-app updates can replace an npm-global Windows install started by the tray.** The update stops the tray and any process still using that install and runs the install from outside the package, so Windows can rename it. (ompweb-dev/ompweb#519) +- **A host update's failed candidate is stopped on Windows even when it got the old daemon's pid.** (ompweb-dev/ompweb#526) +- **In-app updates work on a Windows install without administrator rights.** Task Scheduler's service host is recognized without reading its executable path. (ompweb-dev/ompweb#539) +- **The Windows tray in the npm package is built from the release's sources.** The committed `bin/tau-tray.exe` was still the ompweb build; releases now build it from `native/tray` (`scripts/build-tray.sh`) and refuse one that does not carry the tagged commit. Host update downloads resume with an HTTP `Range` request after a drop or stall. (ompweb-dev/ompweb#532) +- **A host no longer stays "pi not installed" once pi is there.** The daemon reads the pi version again (30 s, doubling to 5 min) while it found none and tells its servers, so pi installed after the daemon started is picked up without a restart. (ompweb-dev/ompweb#542) +- **The sidebar's green check clears once you open the conversation.** (ompweb-dev/ompweb#336) +- **The subagents header counts only completed subagents.** (ompweb-dev/ompweb#440) +- **Live tool output no longer floods a slow connection.** The newest snapshot of each running tool is sent at most once per second, and the final output at once. (ompweb-dev/ompweb#418) +- **A rename falls back to the session file only when pi refused it or the child is gone**, so a slow or busy session is retried instead of written behind pi's back. (ompweb-dev/ompweb#415) +- **Re-adding a workspace keeps its alias, order and pin**, and new worktrees no longer collide on a sanitized path. (ompweb-dev/ompweb#554) +- **File-panel tabs no longer clip under a horizontal scrollbar.** (ompweb-dev/ompweb#547) +- **Delivered outbox rows are pruned inside the add's write transaction.** (ompweb-dev/ompweb#535) +- **Session responses drop provider-internal assistant fields** (thinking and text signatures, request controls), which the UI never reads. (ompweb-dev/ompweb#454) - **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did. - **GitHub workflow watches no longer regress to stale run states.** Workflow updates retain GitHub's run timestamp and ignore older snapshots for the same or an earlier attempt, so a delayed `queued` response cannot follow a newer `in_progress` delivery. - **Keep sidebar transcript results aligned with expandable hits on every linked host.** Each daemon now searches its own active conversations, ignoring abandoned branches and pre-compaction messages. diff --git a/README.md b/README.md index 0602daa1..b095f287 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,12 @@ VPN, and keep tau itself bound to `127.0.0.1`. The proxy must pass WebSocket upg on the paths that hosts authenticate with their token: `/api/hosts/link`, `/api/hosts/maintenance` and `/api/hosts/cluster-config/…`. +A server-sent-events client keeps its stream alive with a comment frame every 30 s by default; `GET /api/events?heartbeat=` +(15 to 110) chooses another interval for that connection. A value outside that range falls back to the 30 s default. The proxy's +read timeout must stay above the interval the client asks for: nginx's default `proxy_read_timeout` is 60 s, so a client selecting +110 s needs a timeout above 110 s (for example `proxy_read_timeout 120s;`), or the proxy drops the idle stream before its first +keep-alive. `GET /api/app-info` tells a native client whether the server supports the query. + #### Skipping the password behind a trusted proxy tau cannot see client addresses itself, so a reverse proxy can vouch for requests instead. The proxy sends a secret in diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index dde692b5..d30c9d4c 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -33,10 +33,13 @@ export async function POST( // GET /api/agent/[id] - Get current agent state export async function GET( - _req: Request, + req: Request, { params }: { params: Promise<{ id: string }> } ) { const { id } = await params; + // Default stays the full shape; `?systemPrompt=0` drops the ~13 KB prompt + // from the 15 s state poll. Any other value (including "1") keeps it. + const includeSystemPrompt = new URL(req.url).searchParams.get("systemPrompt") !== "0"; try { const session = getRpcSession(id); @@ -44,7 +47,13 @@ export async function GET( return Response.json({ running: false }); } try { - const state = await session.send({ type: "get_state" }); + // Through the wrapper's command path, not a dedicated method: that is + // the contract every wrapper fake implements, and `dispatchCommand` + // already honors `systemPrompt: false`. + const state = await session.send({ + type: "get_state", + ...(includeSystemPrompt ? {} : { systemPrompt: false }), + }); return Response.json({ running: true, state }); } catch (error) { if (error instanceof WebRpcError && error.code === "session_unresponsive") { diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts new file mode 100644 index 00000000..ab06e77a --- /dev/null +++ b/app/api/app-info/route.ts @@ -0,0 +1,22 @@ +import packageJson from "../../../package.json"; + +/** + * Capability handshake for native clients. Rides the normal /api auth gate; it + * carries the package version and which server-side features exist, never any + * credential or configuration value. + * + * Every flag names a route or shape this server actually serves: a client that + * reads one and finds the feature missing would break, so a capability is added + * only together with its implementation. + */ +export function GET(): Response { + return Response.json({ + name: "tau", + version: packageJson.version, + api: 1, + capabilities: { + /** `GET /api/events?heartbeat=<15..110>` chooses this connection's keep-alive. */ + heartbeatParam: true, + }, + }, { headers: { "Cache-Control": "no-store" } }); +} diff --git a/app/api/cwd/pick/route.ts b/app/api/cwd/pick/route.ts new file mode 100644 index 00000000..9a2db36d --- /dev/null +++ b/app/api/cwd/pick/route.ts @@ -0,0 +1,20 @@ +import { apiErrorResponse } from "@/lib/api-utils"; +import { pickDirectory, pickerAvailable } from "@/lib/cwd-picker"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; + +// POST /api/cwd/pick body: { hostId?: string } → { path } | { cancelled: true } +// Opens the OS folder dialog on this machine. A page opened from another machine has no desktop +// here, and another host's paths do not exist here either, so both cases are refused. +export async function POST(req: Request, context: { localPeer: boolean }) { + try { + const body = await req.json().catch(() => ({})) as { hostId?: unknown }; + const hostId = typeof body.hostId === "string" && body.hostId ? body.hostId : LOCAL_HOST_ID; + const picked = hostId === LOCAL_HOST_ID && pickerAvailable(context.localPeer) ? await pickDirectory() : null; + if (!picked) { + return Response.json({ error: "The folder dialog is only available on this machine", code: "picker_unavailable" }, { status: 501 }); + } + return Response.json(picked); + } catch (error) { + return apiErrorResponse(error); + } +} diff --git a/app/api/cwd/picker/route.ts b/app/api/cwd/picker/route.ts new file mode 100644 index 00000000..cec55627 --- /dev/null +++ b/app/api/cwd/picker/route.ts @@ -0,0 +1,9 @@ +import { pickerAvailable } from "@/lib/cwd-picker"; + +// GET /api/cwd/picker → { available } — may this page open the server machine's folder dialog? +// Only a page opened on the machine itself: a remote browser has no desktop here. Locality is the +// connection's peer address from the server (context.localPeer), never request.url's host, which the +// client writes through its Host header. +export function GET(_request: Request, context: { localPeer: boolean }) { + return Response.json({ available: pickerAvailable(context.localPeer) }); +} diff --git a/app/api/events/route.ts b/app/api/events/route.ts index 0c163b7d..38b0c3ba 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -1,5 +1,5 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { EventStreamConnection, getEventStreamConnection } from "@/lib/event-stream-hub"; +import { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } from "@/lib/event-stream-hub"; import { parseEventStreamRequest, UNKNOWN_CONNECTION_CODE } from "@/lib/event-stream-protocol"; const MAX_REQUEST_BYTES = 16 * 1024; @@ -8,7 +8,10 @@ const MAX_REQUEST_BYTES = 16 * 1024; // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). export function GET(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { disableIdleTimeout(); - const connection = new EventStreamConnection(req.signal); + // A native client may ask for a longer keep-alive (`?heartbeat=110`); values + // outside 15..110 fall back to the 30 s default rather than being clamped. + const heartbeat = parseHeartbeatSeconds(new URL(req.url).searchParams.get("heartbeat")); + const connection = new EventStreamConnection(req.signal, { heartbeatMs: heartbeat * 1000 }); return new Response(connection.stream, { headers: { "Content-Type": "text/event-stream", diff --git a/app/api/notifications/answer/route.ts b/app/api/notifications/answer/route.ts new file mode 100644 index 00000000..6763b8e4 --- /dev/null +++ b/app/api/notifications/answer/route.ts @@ -0,0 +1,74 @@ +import { commandErrorResponse } from "@/lib/agent-command"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import type { ExtensionUiResponse, RpcAskDialogAnswer } from "@/lib/pi-types"; +import { getRpcSession, isAskAnswers } from "@/lib/rpc-manager"; +import { isRecord } from "@/lib/type-guards"; + +/** Answers are text; 64 KB leaves room for a long ask customInput without becoming a payload channel. */ +const MAX_BODY_BYTES = 64 * 1024; +const MAX_ID_CHARS = 256; + +const invalid = (error: string) => Response.json({ error, code: "invalid_answer_request" }, { status: 400 }); + +function isId(value: unknown): value is string { + return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_CHARS; +} + +/** + * Exactly one response variant, and nothing else. Shapes come from + * ExtensionDialog; the ask payload reuses the agent route's validation. + */ +function parseResponse(value: unknown): ExtensionUiResponse | null { + if (!isRecord(value)) return null; + const keys = Object.keys(value); + if (keys.length !== 1) return null; + switch (keys[0]) { + case "value": + return typeof value.value === "string" ? { value: value.value } : null; + case "confirmed": + return typeof value.confirmed === "boolean" ? { confirmed: value.confirmed } : null; + case "cancelled": + return value.cancelled === true ? { cancelled: true } : null; + case "answers": + return isAskAnswers(value.answers) ? { answers: value.answers as RpcAskDialogAnswer[] } : null; + default: + return null; + } +} + +/** + * POST /api/notifications/answer — answer a pending blocking extension dialog + * from a notification action. Looks up the live wrapper and never spawns pi. Behind the normal auth gate. + * + * 200 {status:"answered"} routed through the shared extension_ui_response command + * 200 {status:"alreadySettled"} the request id is not pending + * 200 {status:"sessionGone"} no live wrapper for the session + * 400 on an invalid body, an answer the pending dialog does not take, or a + * request that is not a dialog at all (`open_url` takes no answer) + * 400 session_restarting / 503 {hostOffline: true} when it cannot be delivered + */ +export async function POST(req: Request) { + let body: unknown; + try { + body = await parseJsonWithinLimit(req, MAX_BODY_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return Response.json({ error: "Answer is too large", code: "request_too_large" }, { status: 413 }); + } + return invalid("Invalid JSON request body"); + } + if (!isRecord(body) || !isId(body.sessionId) || !isId(body.requestId)) { + return invalid("sessionId, requestId and response are required"); + } + const response = parseResponse(body.response); + if (!response) return invalid("response must be exactly one of value, confirmed, cancelled or answers"); + + const session = getRpcSession(body.sessionId); + if (!session || !session.isAlive()) return Response.json({ status: "sessionGone" }); + + try { + return Response.json({ status: await session.answerExtensionUiRequest(body.requestId, response) }); + } catch (error) { + return commandErrorResponse(error); + } +} diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index d0bc36a6..9431f15f 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -1,8 +1,27 @@ import { buildSessionContext } from "@/lib/session-reader"; -import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; +import { apiErrorResponse, ifNoneMatchSatisfied, opErrorResponse, resolveSessionHostOr404, strongEtag } from "@/lib/api-utils"; import { getRpcSession } from "@/lib/rpc-manager"; import { MAX_SYNC_MESSAGES, parseHistoryCursor, selectSessionHistory, type SessionHistoryCursor, type SessionHistoryPage, type SessionSyncResponse } from "@/lib/session-sync"; +/** + * Serialize once, key the validator on those exact bytes: the ETag cannot + * disagree with the body, and it covers everything that shapes it (branch, + * options, live stream snapshot) without this route needing the file's + * identity — which a remote host would not expose to this process. + */ +function jsonBodyResponse(req: Request, body: unknown, cacheControl: "no-store" | null = null): Response { + const text = JSON.stringify(body); + const etag = strongEtag(text); + const headers: Record = { ETag: etag }; + if (cacheControl) headers["Cache-Control"] = cacheControl; + if (ifNoneMatchSatisfied(req.headers.get("if-none-match"), etag)) { + return new Response(null, { status: 304, headers }); + } + return new Response(text, { + headers: { "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(text)), ...headers }, + }); +} + export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } @@ -63,7 +82,7 @@ export async function GET( const session = notFound && (boundary === "1" || (sync === "1" && !cursor?.lastEntryId && leafId === undefined)) ? getRpcSession(id) : undefined; if (session?.isAlive() && !(await session.host.sessionFileExists(session.sessionFile))) { if (boundary === "1") { - return Response.json({ entryIds: [] }, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, { entryIds: [] }, "no-store"); } const response: SessionSyncResponse = { ...selectSessionHistory(buildSessionContext([]), cursor, limit), @@ -71,12 +90,12 @@ export async function GET( leafId: null, live: session.getStreamSnapshot(), }; - return Response.json(response, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, response, "no-store"); } return "response" in result ? result.response : opErrorResponse(result); } if (boundary === "1") { - return Response.json(result.value, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, result.value, "no-store"); } if (sync === "1") { const page = result.value as { history: SessionHistoryPage; leafId: string | null; tipId: string | null }; @@ -87,9 +106,9 @@ export async function GET( ? session.getStreamSnapshot() : null; const response: SessionSyncResponse = { ...page.history, sessionId: id, leafId: page.leafId, live }; - return Response.json(response, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, response, "no-store"); } - return Response.json(result.value); + return jsonBodyResponse(req, result.value); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index c67b2a77..10f9635a 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -1,11 +1,26 @@ import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { invalidateHostSessionList } from "@/lib/hosts/session-index"; +import type { SessionReadValue } from "@/lib/hosts/session-ops"; import { invalidateSessionCaches } from "@/lib/session-reader"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { clearExitedRpcSession, getLiveRpcSessionIds, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { forgetSessionReplacementMappings } from "@/lib/message-outbox"; import { removeSessionWatches } from "@/lib/github/watch-store"; +import { RpcCommandError, RpcCommandTimeoutError } from "@/lib/pi/rpc-process"; + +/** Session-level failures a client retries instead of treating the request as + * applied: pi is busy, restarting or was reset, and the session keeps going. + * `session_slow` and `session_state_timeout` are the codes the wrapper and the + * `get_state` dispatch use for "the completion is unknown"; this route answers + * its own `RpcCommandTimeoutError` with `session_slow` below, and accepts the + * rest from any wrapper that raises them, so a client sees one stable name. */ +const RETRIABLE_SESSION_CODES: Record = { + session_slow: true, + session_state_timeout: true, + session_restarting: true, + session_unresponsive: true, +}; /** Stable, client-safe error body for catch-all handlers: details go to the * server log only, never to the browser. */ @@ -13,18 +28,51 @@ function sessionsErrorResponse(error: unknown): Response { if (error instanceof WebRpcError && error.code === "session_busy") { return Response.json({ error: error.message, code: error.code }, { status: 409 }); } + // pi is busy, restarting or was reset — not gone: the session keeps running, + // so a client retries instead of treating the rename as applied. + if (error instanceof WebRpcError && RETRIABLE_SESSION_CODES[error.code]) { + return Response.json({ error: error.message, code: error.code }, { status: 503 }); + } + // A command timeout leaves the completion unknown. Nothing was written here + // and the child still owns the file, so the client retries and re-reads the + // title instead of assuming the rename stuck. + if (error instanceof RpcCommandTimeoutError) { + return Response.json( + { error: "The session did not confirm the change in time. It keeps running — retry shortly.", code: "session_slow" }, + { status: 503 }, + ); + } if (error instanceof RequestBodyTooLargeError) { return Response.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); } if (error instanceof SyntaxError) { return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } - // A host link failure keeps its status: 503 offline, 504 timeout. - if (error instanceof HostOpError) return apiErrorResponse(error); + // A host link failure keeps its status: 503 offline, 504 timeout. A live + // wrapper whose link dropped answers 503 `{hostOffline: true}` plus its + // `delivery` ("refused": nothing left this server). + if (error instanceof HostOpError || (error instanceof WebRpcError && error.code === "host_offline")) return apiErrorResponse(error); console.error("[api/sessions]", error); return Response.json({ error: "Session request failed", code: "session_request_failed" }, { status: 500 }); } +/** `?meta=1` against a daemon that predates the option: it ignores `meta` and + * answers the full transcript. Derive the navigation shape from it — the same + * context supplies the branch metadata — so the client never receives the + * second copy. `lastMessageAt` stays absent: that daemon never scanned it. */ +function navigationShape(value: SessionReadValue): SessionReadValue { + if (!value.context) return value; + return { + ...value, + info: { + ...value.info, + model: value.context.model, + thinkingLevel: value.context.thinkingLevel, + }, + context: null, + }; +} + export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } @@ -35,34 +83,62 @@ export async function GET( if ("response" in resolved) return resolved.response; const searchParams = new URL(req.url).searchParams; + const meta = searchParams.get("meta") === "1"; const includeState = searchParams.has("includeState"); + // `?includeState=alive` opts into the split liveness shape; every other + // value (including bare `?includeState`) keeps the historical meaning. + const stateAlive = searchParams.get("includeState") === "alive"; const read = await resolved.host.sessionOps.readSession(id, { deferThinking: searchParams.has("deferThinking"), deferMedia: searchParams.has("deferMedia"), + meta, }); if (!read.ok) return opErrorResponse(read); + // A daemon that predates `meta` ignores the option and answers the full + // transcript; derive the navigation shape here so the client never gets it. + const value = meta ? navigationShape(read.value) : read.value; // ?includeState=1 inlines the wrapper's live agent state (same shape as // GET /api/agent/[id]) so the client's post-turn refresh is one request // instead of two. On a get_state failure the field is omitted entirely — // callers treat a missing `agent` as "fetch it separately". - let agent: { running: boolean; state?: unknown } | undefined; + // + // The historical shape says `running: true` for any live wrapper, idle + // included (that is what /api/agent and /state answer). The idle/running + // split is opt-in (`?includeState=alive`), so an existing caller keeps its + // meaning: `running` there is the child's liveness, not a turn in flight. + let agent: { running: boolean; alive?: boolean; state?: unknown } | undefined; if (includeState) { const rpc = getRpcSession(id); if (rpc?.isAlive()) { try { - agent = { running: true, state: await rpc.send({ type: "get_state" }) }; + const state = await rpc.send({ type: "get_state" }); + // The child can exit between its reply and this line: its state is + // stale then, so answer the not-live shape instead of reporting it. + if (rpc.isAlive()) { + agent = stateAlive + ? { running: rpc.isRunning(), alive: true, state } + : { running: true, state }; + } else { + agent = stateAlive ? { running: false, alive: false } : { running: false }; + } } catch { // Leave agent unset; the session payload is still valid without it. } } else { - agent = { running: false }; + agent = stateAlive ? { running: false, alive: false } : { running: false }; } } + // ?meta=1 is the navigation shape: the tree and leaf the native client + // reads from this route, without a second transcript copy. `context` is + // omitted entirely (not null) so clients keyed on its presence keep their + // historical shape; the transcript comes from /api/sessions/[id]/context. + const { context, ...navigation } = value; return Response.json({ sessionId: id, - ...read.value, + ...navigation, + ...(context ? { context } : {}), ...(agent ? { agent } : {}), }); } catch (error) { @@ -92,8 +168,20 @@ export async function PATCH( await rpc.send({ type: "set_session_name", name: name.trim() }); renamed = true; } catch (error) { - if (error instanceof WebRpcError && error.code === "session_busy") throw error; - // Fall back to a session_info entry in the file below. + // The file fallback is only for "nothing was applied": pi answered + // with a rejection (`RpcCommandError`), or the child died before + // answering, so no live process can flush over our write. Everything + // else keeps its own answer: a timeout leaves the completion unknown + // while the child still owns the file, and a busy/restarting/offline + // session is retried by the client instead of being written behind + // pi's back (its next flush would clobber the slot). + if (error instanceof RpcCommandError) { + // pi rejected the command outright; fall through to the file. + } else if (error instanceof RpcCommandTimeoutError || error instanceof WebRpcError) { + throw error; + } else if (rpc.isAlive?.()) { + throw error; + } } } if (!renamed) { diff --git a/app/globals.css b/app/globals.css index 905a46ae..84e2f73e 100644 --- a/app/globals.css +++ b/app/globals.css @@ -3747,6 +3747,7 @@ html[data-touch-targets="accessible"] .right-panel-toolbar { } .right-panel-toolbar { --right-panel-close-width: 44px; + --tab-height: 44px; } html:root .shell-toolbar-btn.right-panel-close-button { padding-top: env(safe-area-inset-top, 0px) !important; @@ -3758,7 +3759,7 @@ html[data-touch-targets="accessible"] .right-panel-toolbar { .right-panel-toolbar > div:first-child { display: flex; align-items: center; - min-height: 44px; + min-height: var(--tab-height); } .right-panel-toolbar > [role="toolbar"] > button { min-width: 40px; @@ -3767,10 +3768,6 @@ html[data-touch-targets="accessible"] .right-panel-toolbar { .right-panel-toolbar .tabbar-scroll { width: 100%; } - .right-panel-toolbar .tabbar-scroll, - .right-panel-toolbar .tabbar-tab { - height: 44px !important; - } } :root { diff --git a/components/ChatInput.fullscreen.test.mjs b/components/ChatInput.fullscreen.test.mjs new file mode 100644 index 00000000..c21afd57 --- /dev/null +++ b/components/ChatInput.fullscreen.test.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test from "node:test"; +import React from "react"; + +const { act, cleanup, fireEvent, render } = await import("@testing-library/react/pure.js"); +const { ChatInput } = await import("./ChatInput.tsx"); + +// jsdom 29 ships no matchMedia, and the composer reads one at mount for the +// word-completion default (`(pointer: fine)`). Never match: desktop composer. +window.matchMedia = (media) => ({ + media, + matches: false, + onchange: null, + addEventListener() {}, + removeEventListener() {}, + addListener() {}, + removeListener() {}, + dispatchEvent() { return false; }, +}); + +async function renderComposer(t, props = {}) { + const sent = []; + const view = render(React.createElement(ChatInput, { + async onSend(message) { sent.push(message); return { status: "accepted" }; }, + onThinkingLevelChange() {}, + thinkingLevel: "auto", + isStreaming: false, + ...props, + })); + t.after(() => cleanup()); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); + return { view, sent }; +} + +const expandButton = (view) => view.getByRole("button", { name: /Expand editor|chatInput\.expandEditor/ }); + +test("the composer opens a full-screen editor that shares its draft", async (t) => { + const { view } = await renderComposer(t); + assert.equal(view.queryByRole("dialog"), null, "the editor must start closed"); + fireEvent.click(expandButton(view)); + const dialog = view.getByRole("dialog"); + const editor = dialog.querySelector("textarea"); + assert.ok(editor, "the full-screen editor needs a textarea"); + fireEvent.change(editor, { target: { value: "a very long prompt\nwith many lines" } }); + assert.equal(editor.value, "a very long prompt\nwith many lines"); + // Done closes the editor and the compact composer keeps the same text. + // (The header ✕ shares the Done label; the footer button is the text one.) + fireEvent.click(view.getByText("Done")); + assert.equal(view.queryByRole("dialog"), null); + const [compact] = view.container.querySelectorAll("textarea"); + assert.equal(compact.value, "a very long prompt\nwith many lines"); +}); + +test("Ctrl+Enter in the full-screen editor sends the draft", async (t) => { + const { view, sent } = await renderComposer(t); + fireEvent.click(expandButton(view)); + const editor = view.getByRole("dialog").querySelector("textarea"); + fireEvent.change(editor, { target: { value: "send me" } }); + fireEvent.keyDown(editor, { key: "Enter", ctrlKey: true }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); + assert.deepEqual(sent, ["send me"]); + assert.equal(view.queryByRole("dialog"), null, "sending closes the editor"); +}); + +test("Escape closes the full-screen editor without sending", async (t) => { + const { view, sent } = await renderComposer(t); + fireEvent.click(expandButton(view)); + const editor = view.getByRole("dialog").querySelector("textarea"); + fireEvent.change(editor, { target: { value: "keep me" } }); + fireEvent.keyDown(editor, { key: "Escape" }); + assert.equal(view.queryByRole("dialog"), null); + assert.deepEqual(sent, []); +}); + +test("during a run the full-screen editor queues its draft as a follow-up instead of dropping it", async (t) => { + const followUps = []; + const { view, sent } = await renderComposer(t, { + isStreaming: true, + async onFollowUp(message) { followUps.push(message); return { status: "accepted" }; }, + async onSteer() { return { status: "accepted" }; }, + }); + fireEvent.click(expandButton(view)); + const editor = view.getByRole("dialog").querySelector("textarea"); + fireEvent.change(editor, { target: { value: "after this run" } }); + fireEvent.keyDown(editor, { key: "Enter", ctrlKey: true }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); + assert.deepEqual(sent, []); + assert.deepEqual(followUps, ["after this run"]); +}); + +test("Ctrl+Enter that confirms an IME candidate does not send from the full-screen editor", async (t) => { + const { view, sent } = await renderComposer(t); + fireEvent.click(expandButton(view)); + const editor = view.getByRole("dialog").querySelector("textarea"); + fireEvent.change(editor, { target: { value: "にほん" } }); + fireEvent.keyDown(editor, { key: "Enter", ctrlKey: true, keyCode: 229 }); + fireEvent.keyDown(editor, { key: "Escape", keyCode: 229 }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); + assert.deepEqual(sent, []); + assert.ok(view.queryByRole("dialog"), "the editor stays open"); +}); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 1beff50f..6185a93e 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -2,7 +2,7 @@ import React, { useRef, useState, useCallback, useEffect, useLayoutEffect, useImperativeHandle, forwardRef, memo, KeyboardEvent } from "react"; import { createPortal } from "react-dom"; -import { ChevronDown, ClipboardPaste, CornerDownRight, ListChecks, Loader2, Mic, Paperclip, Plus, RotateCw, Shrink, Terminal, Wrench, X } from "lucide-react"; +import { ChevronDown, ClipboardPaste, CornerDownRight, ListChecks, Loader2, Maximize2, Mic, Paperclip, Plus, RotateCw, Shrink, Terminal, Wrench, X } from "lucide-react"; import { getSubmitDuringRunBehavior } from "@/lib/composer-prefs"; import type { BuiltinSlashCommandResult, CompactResultInfo, PromptSendOptions, PromptSubmissionResult, QueuedMessages, SlashCommandInfo } from "@/hooks/useAgentSession"; import type { ActiveGoal, ActivePlan } from "@/lib/web-mode-state"; @@ -356,6 +356,9 @@ export const ChatInput = memo(forwardRef(function ChatIn const contextContainer = isMobile ? sessionInfoContainer : composerContextContainer; const [plusMenuOpen, setPlusMenuOpen] = useState(false); const [plusExpanded, setPlusExpanded] = useState<"tools" | null>(null); + // Full-screen editing surface for long prompts; shares the composer's draft + // value, so closing it (or sending from it) keeps the same text. + const [editorFullscreen, setEditorFullscreen] = useState(false); const [modelSearchQuery, setModelSearchQuery] = useState(""); const [attachedImages, setAttachedImages] = useState(() => ( draftKey ? draftImagesToAttachedImages(getDraft(draftKey)?.images) : [] @@ -1923,6 +1926,17 @@ export const ChatInput = memo(forwardRef(function ChatIn [isMobile, isStreaming, onSteer, onFollowUp, onAbort, onMinimize, slashMenuOpen, slashQuery, filteredSlashCommands, slashActiveIndex, applySlashCommand, sendQueued, handleSend, getNextSlashIndex, atMenuOpen, atQuery, atMatches, atActiveIndex, applyAtCompletion, historyMenuOpen, inputHistory, historyActiveIndex, applyHistoryInput, value, toggleDictation, setValue] ); + // The fullscreen editor submits like Enter in the composer: during a run it queues or steers. + const submitFromEditor = () => { + setEditorFullscreen(false); + if (isStreaming && (onSteer || onFollowUp)) { + if (getSubmitDuringRunBehavior() === "steer" && onSteer) sendQueued("steer"); + else sendQueued("followup"); + } else { + void handleSend(); + } + }; + const handlePaste = useCallback((e: React.ClipboardEvent) => { const items = Array.from(e.clipboardData?.items ?? []); @@ -3569,6 +3583,27 @@ export const ChatInput = memo(forwardRef(function ChatIn