From fee4241d3ca5cbb64661c52c293a8111debcf481 Mon Sep 17 00:00:00 2001 From: LHagfoss Date: Tue, 24 Nov 2026 13:23:53 +0100 Subject: [PATCH] feat(remote): sync the full thread list and projects to devices Saved-thread entries carry the desktop sidebar's status, pin, snooze, harness, model and scheduled job, and their project is the one the sidebar files them under. list_projects lists every project, subscribe_saved_sessions pushes saved_sessions_changed frames, and create_session accepts any listed project's folder. --- docs/remote-protocol/README.md | 112 +++- docs/remote-protocol/v1/frame.schema.json | 176 ++++++ .../v1/golden/frames/response_projects.json | 19 + .../frames/response_saved_sessions.json | 20 +- .../response_saved_sessions_subscribed.json | 8 + .../golden/frames/saved_sessions_changed.json | 37 ++ .../v1/golden/requests/list_projects.json | 7 + .../requests/subscribe_saved_sessions.json | 7 + docs/remote-protocol/v1/request.schema.json | 26 + docs/remote.md | 4 +- rustcode/engine/src/remote/contract.rs | 93 ++- rustcode/engine/src/remote/protocol.rs | 106 +++- .../engine/src/remote_gateway/wire_names.rs | 3 + .../engine/src/remote_gateway/workspace.rs | 114 ++-- .../remote_gateway/workspace/saved_threads.rs | 550 ++++++++++++++++++ .../workspace/saved_threads_tests.rs | 452 ++++++++++++++ scripts/comment-baseline.txt | 2 +- 17 files changed, 1639 insertions(+), 97 deletions(-) create mode 100644 docs/remote-protocol/v1/golden/frames/response_projects.json create mode 100644 docs/remote-protocol/v1/golden/frames/response_saved_sessions_subscribed.json create mode 100644 docs/remote-protocol/v1/golden/frames/saved_sessions_changed.json create mode 100644 docs/remote-protocol/v1/golden/requests/list_projects.json create mode 100644 docs/remote-protocol/v1/golden/requests/subscribe_saved_sessions.json create mode 100644 rustcode/engine/src/remote_gateway/workspace/saved_threads.rs create mode 100644 rustcode/engine/src/remote_gateway/workspace/saved_threads_tests.rs diff --git a/docs/remote-protocol/README.md b/docs/remote-protocol/README.md index 969a8410a..4ed757932 100644 --- a/docs/remote-protocol/README.md +++ b/docs/remote-protocol/README.md @@ -71,9 +71,10 @@ prompts, messages) is never rewritten. | `session_id` | `thread_id` | field | | `session` | `thread` | field | | `sessions` | `threads` | field, and `kind` of the list push frame | -| `subscribe_sessions`, `list_sessions`, `list_saved_sessions` | `subscribe_threads`, `list_threads`, `list_saved_threads` | operation `type` | +| `subscribe_sessions`, `list_sessions`, `list_saved_sessions`, `subscribe_saved_sessions` | `subscribe_threads`, `list_threads`, `list_saved_threads`, `subscribe_saved_threads` | operation `type` | | `create_session`, `attach_session`, `detach_session`, `resume_session`, `set_session_settings` | `create_thread`, `attach_thread`, `detach_thread`, `resume_thread`, `set_thread_settings` | operation `type` | -| `sessions`, `saved_sessions`, `session_created`, `session_resumed`, `session_settings_updated` | `threads`, `saved_threads`, `thread_created`, `thread_resumed`, `thread_settings_updated` | result `type` | +| `sessions`, `saved_sessions`, `saved_sessions_subscribed`, `session_created`, `session_resumed`, `session_settings_updated` | `threads`, `saved_threads`, `saved_threads_subscribed`, `thread_created`, `thread_resumed`, `thread_settings_updated` | result `type` | +| `saved_sessions_changed` | `saved_threads_changed` | `kind` of the saved-thread push frame | | `session_closed` | `thread_closed` | event `type` | | `session_changed` | `thread_changed` | close `reason` | | `stale_session` | `stale_thread` | error `code` | @@ -502,7 +503,8 @@ client holds. the host-wide ones: `list_sessions`, `subscribe_sessions`, `get_request_status`, `list_directories`, `create_session`, `request_share`, `list_saved_sessions`, `resume_session`, `get_usage`, `get_settings`, `set_settings`, `pin_thread`, -`unpin_thread`, `settle_thread` and `unsettle_thread`. Device identity +`unpin_thread`, `settle_thread`, `unsettle_thread`, `list_projects` and +`subscribe_saved_sessions`. Device identity comes from authentication and is never part of a frame. ## Operations @@ -529,6 +531,8 @@ comes from authentication and is never part of a frame. | `set_settings` | gateway (`settings_set`) | `settings` | `invalid_request`, `internal` | | `pin_thread`, `unpin_thread` | gateway (`thread_pin`, `thread_unpin`) | `thread_pinned` | `invalid_request` | | `settle_thread`, `unsettle_thread` | gateway (`thread_settle`, `thread_unsettle`) | `thread_settled` | `invalid_request` | +| `list_projects` | gateway (`projects`) | `projects` | `internal` | +| `subscribe_saved_sessions` | gateway (`saved_session_updates`) | `saved_sessions_subscribed`, then `saved_sessions_changed` frames | | Any request can also be rejected with: @@ -599,7 +603,8 @@ The `sessions` result also carries `capabilities`, the optional host-wide operations the gateway implements. It is absent from gateways that implement none; the flags are `saved_sessions`, `session_changes`, `thread_create_options`, `usage_summary`, `settings_get`, `settings_set`, -`thread_pin`, `thread_unpin`, `thread_settle` and `thread_unsettle`. A client +`thread_pin`, `thread_unpin`, `thread_settle`, `thread_unsettle`, `projects` +and `saved_session_updates`. A client offers a feature only when its flag is listed; an older owner answers `get_changes` with `unsupported_operation`. `thread_create_options` is not a fixed feature of the gateway: it is listed @@ -847,6 +852,10 @@ discover them: - On Unix, a fallback `/tmp/rustcode-` socket directory can remain after gateway shutdown. Socket files are removed; the private directory is retained to avoid racing another process using it. Clients never need that path. +- A saved thread's `status` is `running` or `needs_input` only while it is in + the live list. The desktop app shares at most 32 threads at once, the most + recently used, so a turn running in a thread beyond those shows the status + stored for it (usually `idle`) until it is shared. - `resync_required` with reason `gateway_restarted` is never sent as an event: a restart closes the connection, and the reason reaches the client in `attached.resync`. @@ -963,6 +972,10 @@ Discovery does not pair a device or grant access; a Authenticated clients can use `list_directories { path? }` to browse existing folders (default `~/`) and `create_session { path?, harness?, model? }` to create a session there. The latter returns `session_created { session }`. +`path` must lie inside the home folder or a configured `[remote] roots` +folder, or be exactly the `path` of a project `list_projects` reports, wherever +that lies; a subfolder of such a project outside the roots is refused with +`invalid_request`. A gateway routes that request to the running desktop app when one is sharing a thread: the app's shares advertise `host_threads` in their snapshot's @@ -1037,12 +1050,31 @@ nothing holds. session was started; pass `next_cursor` back as `cursor` for the next page. `limit` is 1 to 100 (30 when absent). `query` keeps sessions whose title, workspace or ID contains it, ignoring case. Each entry has `session_id`, -`title`, `project` (the recorded workspace directory, so a client groups -threads by project; absent when unknown), `parent` (the thread this one was +`title` (the title the desktop app shows, a rename included), `project` (the +project the desktop app's sidebar files the thread under: a worktree's +repository, else the repository recorded for its folder, else the folder; +absent when no folder was recorded or the folder is a drive's root or +RustCode's own data folder), `parent` (the thread this one was started from, the same `{ session_id, relationship }` the live list carries; absent for a top-level thread), `workspace` (absent for sessions that predate workspace recording), `updated_at` (when the transcript was last -written), `message_count` and `state`: +written), `message_count` and `state`. Hosts that list `projects` or +`saved_session_updates` also send what the desktop sidebar shows: + +| Field | Meaning | +| --- | --- | +| `status` | `idle`, `running`, `needs_input` (an approval or question waits), `stalled`, `review` or `done` (settled). A settled thread stays `done` while its last turn winds down; `running` and `needs_input` come from the live list, the rest from the store. A later host may add values: show one you do not know as `idle`. | +| `pinned` | Pinned in the desktop sidebar (`pin_thread`). `false` when absent. | +| `snoozed_until` | RFC 3339 time a snoozed thread wakes; absent when not snoozed. Read-only: a device cannot snooze. | +| `harness` | `rustcode` for the built-in harness, else the harness id (`claude-code`, `codex`, `pi`, …). | +| `model` | The model or model profile recorded for the thread, when known. | +| `scheduled_job` | The scheduled job this thread is a run of. The desktop app shows these under the job, not in the sidebar; a client that mirrors the sidebar hides them. | + +All of them are optional to a client: an older host sends none. Unread marks +and the sidebar's manual order live only in the desktop app's own storage, so +no device sees them. + +`state` says what a client can do with the thread: | `state` | Meaning | What the client does | | --- | --- | --- | @@ -1075,6 +1107,67 @@ session without a recorded workspace, or whose workspace no longer exists, with `invalid_request`, an unknown ID with `not_found`; nothing is started for any of them. +### Projects and keeping the thread list in sync + +`list_projects` (capability `projects`) returns every project the host's saved +threads belong to, the same projects the desktop app's sidebar shows, whether +or not any of their threads is open. It is read-only and host-wide. Projects are +most recently updated first, the desktop's own default order; at most 500, and +`truncated` says when more exist. Each has `path` (the value saved threads +carry in `project`), `name` (the folder's name), `thread_count`, `running` (a +thread's turn runs or waits on the user), `needs_input` (a thread waits on an +approval or question) and `updated_at`. A folder the desktop app knows before +its first thread, and the sidebar's manual project order, live only in the app +and are not listed. + +```json +{"protocol_version": 1, "request_id": "req-projects", "operation": {"type": "list_projects"}} +``` + +```json +{"kind": "response", "protocol_version": 1, "request_id": "req-projects", "result": {"type": "projects", "projects": [{"path": "/Users/example/projects/parser", "name": "parser", "thread_count": 12, "running": true, "needs_input": false, "updated_at": "2026-07-14T09:40:12Z"}], "truncated": false}} +``` + +`subscribe_saved_sessions` (capability `saved_session_updates`) keeps a device's +copy of the saved list and the projects current without paging through it +again. The gateway answers `saved_sessions_subscribed` once it holds the state +later changes are measured against, then pushes a `saved_sessions_changed` +frame whenever a saved thread or project is added, changed or removed, until +the connection ends. A client subscribes first, waits for the answer, then +pages `list_saved_sessions` and calls `list_projects`; a change that races the +listing arrives again in a frame, so applying both in arrival order converges. +After a reconnect it does the same again. + +```json +{"protocol_version": 1, "request_id": "req-saved-sub", "operation": {"type": "subscribe_saved_sessions"}} +``` + +```json +{"kind": "response", "protocol_version": 1, "request_id": "req-saved-sub", "result": {"type": "saved_sessions_subscribed"}} +``` + +Each frame holds whole entries: `sessions` replaces the entry the client holds +under each `session_id` (or adds it), `removed` lists thread IDs that are gone, +`projects` replaces or adds projects by `path`, and `removed_projects` lists +project paths with no thread left. Empty lists are left out. A large change is +split over several frames, each within the frame limit. The gateway looks for +changes about every 5 seconds while a device is subscribed, so a title, status, +pin, snooze, new or deleted thread reaches the device within that time. + +```json +{ + "kind": "saved_sessions_changed", "protocol_version": 1, + "sessions": [{"session_id": "20260714-091502-3fa2c1", "title": "Fix the parser", "project": "/Users/example/projects/parser", "workspace": "/Users/example/worktrees/parser-fix", "updated_at": "2026-07-14T09:40:12Z", "message_count": 42, "state": "saved", "status": "review", "pinned": true, "snoozed_until": "2026-07-15T08:00:00Z", "harness": "codex", "model": "gpt-5.5", "scheduled_job": "nightly-triage"}], + "removed": ["20260713-171233-9b0e44"], + "projects": [{"path": "/Users/example/projects/parser", "name": "parser", "thread_count": 12, "running": true, "needs_input": false, "updated_at": "2026-07-14T09:40:12Z"}], + "removed_projects": ["/Users/example/projects/old"] +} +``` + +A device that asked for thread names receives `saved_threads_subscribed` and +`kind: "saved_threads_changed"` with `threads` and `thread_id` in place of +`sessions` and `session_id`, and subscribes with `subscribe_saved_threads`. + ### Usage, host settings and thread status These five features are host-wide: they name no shared session, so they need @@ -1152,9 +1245,8 @@ Answers are `thread_pinned { session_id, pinned }` and {"kind": "response", "protocol_version": 1, "request_id": "req-settle", "receipt": "applied", "result": {"type": "thread_settled", "session_id": "20260714-091502-3fa2c1", "settled": true}} ``` -Snooze is not in this list: it lives in the desktop app's own local storage, -not in the engine or the host's session store, so a paired device cannot set -it and no capability advertises it. +Snooze is not in this list: a device reads a thread's `snoozed_until` in the +saved list but cannot snooze or wake it, and no capability advertises that. ### Who sent a message diff --git a/docs/remote-protocol/v1/frame.schema.json b/docs/remote-protocol/v1/frame.schema.json index 4f972ae5d..40e81f54a 100644 --- a/docs/remote-protocol/v1/frame.schema.json +++ b/docs/remote-protocol/v1/frame.schema.json @@ -1154,6 +1154,48 @@ ], "type": "string" }, + "RemoteProject": { + "description": "One project as `list_projects` and `saved_sessions_changed` report it.", + "properties": { + "name": { + "description": "The folder's name, as the desktop app's sidebar labels it.", + "type": "string" + }, + "needs_input": { + "description": "A thread of the project waits on an approval or a question.", + "type": "boolean" + }, + "path": { + "description": "The project's folder, the same value saved threads carry in `project`.", + "type": "string" + }, + "running": { + "description": "A thread of the project has a turn running or waits on the user.", + "type": "boolean" + }, + "thread_count": { + "description": "Saved threads in the project, settled ones included.", + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "updated_at": { + "description": "RFC 3339 time the project's most recently written thread was written.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "path", + "name", + "thread_count", + "running", + "needs_input" + ], + "type": "object" + }, "RemoteQuestion": { "properties": { "chain_length": { @@ -1457,6 +1499,44 @@ ], "type": "object" }, + { + "description": "The answer to `list_projects`.", + "properties": { + "projects": { + "items": { + "$ref": "#/$defs/RemoteProject" + }, + "type": "array" + }, + "truncated": { + "description": "More than [`MAX_PROJECTS`] projects, or more than one frame holds,\nexist; the least recently updated were left out.", + "type": "boolean" + }, + "type": { + "const": "projects", + "type": "string" + } + }, + "required": [ + "type", + "projects", + "truncated" + ], + "type": "object" + }, + { + "description": "`subscribe_saved_sessions` took effect: changes after this answer\narrive as `saved_sessions_changed` frames.", + "properties": { + "type": { + "const": "saved_sessions_subscribed", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, { "description": "One page of `list_saved_sessions`.", "properties": { @@ -1855,11 +1935,25 @@ "RemoteSavedSession": { "description": "One saved session as `list_saved_sessions` reports it.", "properties": { + "harness": { + "description": "The harness the thread runs on: `rustcode` for the built-in one, else\nthe harness id (`claude-code`, `codex`, `pi`, …).", + "type": [ + "string", + "null" + ] + }, "message_count": { "format": "uint64", "minimum": 0, "type": "integer" }, + "model": { + "description": "The model or model profile recorded for the thread, when known.", + "type": [ + "string", + "null" + ] + }, "open_in": { "anyOf": [ { @@ -1882,6 +1976,11 @@ ], "description": "The thread this one was started from, so a client folds delegates,\nforks and side chats under their parent here as it does in the live\nlist. Absent for a top-level thread and from a host that predates the\nfield." }, + "pinned": { + "default": false, + "description": "Pinned in the desktop app's sidebar. False from older hosts.", + "type": "boolean" + }, "project": { "description": "The project the thread belongs to: its recorded workspace directory,\nso a device can group threads of one project together. Absent for a\nsession that predates workspace recording; such a session cannot be\nresumed from a device.", "type": [ @@ -1889,12 +1988,33 @@ "null" ] }, + "scheduled_job": { + "description": "The scheduled job whose run this thread is. The desktop app shows such\nthreads under the job, not in the sidebar.", + "type": [ + "string", + "null" + ] + }, "session_id": { "type": "string" }, + "snoozed_until": { + "description": "RFC 3339 time a snoozed thread wakes; absent when it is not snoozed.", + "type": [ + "string", + "null" + ] + }, "state": { "$ref": "#/$defs/SavedSessionState" }, + "status": { + "description": "The thread's status as the desktop app shows it: `idle`, `running`,\n`needs_input` (an approval or question waits), `stalled`, `review` or\n`done` (settled). Absent from older hosts. A later release may add\nvalues; a client shows one it does not know as `idle`.", + "type": [ + "string", + "null" + ] + }, "title": { "type": "string" }, @@ -1921,6 +2041,48 @@ ], "type": "object" }, + "RemoteSavedSessionsChanged": { + "description": "Saved threads and projects that changed since the previous frame (or since\n`saved_sessions_subscribed`). Each entry is whole: replace what the client\nholds under its `session_id` or `path`.", + "properties": { + "projects": { + "description": "Added or changed projects, as `list_projects` reports them.", + "items": { + "$ref": "#/$defs/RemoteProject" + }, + "type": "array" + }, + "protocol_version": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "removed": { + "description": "IDs of threads that are no longer saved on the host.", + "items": { + "type": "string" + }, + "type": "array" + }, + "removed_projects": { + "description": "Paths of projects that no longer have a saved thread.", + "items": { + "type": "string" + }, + "type": "array" + }, + "sessions": { + "description": "Added or changed threads, as `list_saved_sessions` reports them.", + "items": { + "$ref": "#/$defs/RemoteSavedSession" + }, + "type": "array" + } + }, + "required": [ + "protocol_version" + ], + "type": "object" + }, "RemoteSessionInfo": { "properties": { "activity": { @@ -2721,6 +2883,20 @@ "kind" ], "type": "object" + }, + { + "$ref": "#/$defs/RemoteSavedSessionsChanged", + "description": "Pushed after `subscribe_saved_sessions` when saved threads or\nprojects change.", + "properties": { + "kind": { + "const": "saved_sessions_changed", + "type": "string" + } + }, + "required": [ + "kind" + ], + "type": "object" } ], "title": "RemoteFrame" diff --git a/docs/remote-protocol/v1/golden/frames/response_projects.json b/docs/remote-protocol/v1/golden/frames/response_projects.json new file mode 100644 index 000000000..bac94bbb7 --- /dev/null +++ b/docs/remote-protocol/v1/golden/frames/response_projects.json @@ -0,0 +1,19 @@ +{ + "kind": "response", + "protocol_version": 1, + "request_id": "req-projects", + "result": { + "type": "projects", + "projects": [ + { + "path": "/Users/example/projects/parser", + "name": "parser", + "thread_count": 12, + "running": true, + "needs_input": false, + "updated_at": "2026-07-14T09:40:12Z" + } + ], + "truncated": false + } +} diff --git a/docs/remote-protocol/v1/golden/frames/response_saved_sessions.json b/docs/remote-protocol/v1/golden/frames/response_saved_sessions.json index 82e5eddb7..5fd5bd31a 100644 --- a/docs/remote-protocol/v1/golden/frames/response_saved_sessions.json +++ b/docs/remote-protocol/v1/golden/frames/response_saved_sessions.json @@ -9,10 +9,16 @@ "session_id": "20260714-091502-3fa2c1", "title": "Fix the parser", "project": "/Users/example/projects/parser", - "workspace": "/Users/example/projects/parser", + "workspace": "/Users/example/worktrees/parser-fix", "updated_at": "2026-07-14T09:40:12Z", "message_count": 42, - "state": "saved" + "state": "saved", + "status": "review", + "pinned": true, + "snoozed_until": "2026-07-15T08:00:00Z", + "harness": "codex", + "model": "gpt-5.5", + "scheduled_job": "nightly-triage" }, { "session_id": "5f0c2d9e-7a41-4c1b-9d55-0b6c1f2a3e44", @@ -21,14 +27,20 @@ "workspace": "/Users/example/projects/rustcode", "updated_at": "2026-07-14T08:02:55Z", "message_count": 118, - "state": "shared" + "state": "shared", + "status": "running", + "pinned": false, + "harness": "claude-code", + "model": "gpt-5.5" }, { "session_id": "20260713-171233-9b0e44", "title": "Untitled", "message_count": 3, "state": "open", - "open_in": "app" + "open_in": "app", + "status": "idle", + "pinned": false } ], "next_cursor": "20260713-171233-9b0e44" diff --git a/docs/remote-protocol/v1/golden/frames/response_saved_sessions_subscribed.json b/docs/remote-protocol/v1/golden/frames/response_saved_sessions_subscribed.json new file mode 100644 index 000000000..8b71dffe9 --- /dev/null +++ b/docs/remote-protocol/v1/golden/frames/response_saved_sessions_subscribed.json @@ -0,0 +1,8 @@ +{ + "kind": "response", + "protocol_version": 1, + "request_id": "req-saved-sub", + "result": { + "type": "saved_sessions_subscribed" + } +} diff --git a/docs/remote-protocol/v1/golden/frames/saved_sessions_changed.json b/docs/remote-protocol/v1/golden/frames/saved_sessions_changed.json new file mode 100644 index 000000000..ce3d69594 --- /dev/null +++ b/docs/remote-protocol/v1/golden/frames/saved_sessions_changed.json @@ -0,0 +1,37 @@ +{ + "kind": "saved_sessions_changed", + "protocol_version": 1, + "sessions": [ + { + "session_id": "20260714-091502-3fa2c1", + "title": "Fix the parser", + "project": "/Users/example/projects/parser", + "workspace": "/Users/example/worktrees/parser-fix", + "updated_at": "2026-07-14T09:40:12Z", + "message_count": 42, + "state": "saved", + "status": "review", + "pinned": true, + "snoozed_until": "2026-07-15T08:00:00Z", + "harness": "codex", + "model": "gpt-5.5", + "scheduled_job": "nightly-triage" + } + ], + "removed": [ + "20260713-171233-9b0e44" + ], + "projects": [ + { + "path": "/Users/example/projects/parser", + "name": "parser", + "thread_count": 12, + "running": true, + "needs_input": false, + "updated_at": "2026-07-14T09:40:12Z" + } + ], + "removed_projects": [ + "/Users/example/projects/old" + ] +} diff --git a/docs/remote-protocol/v1/golden/requests/list_projects.json b/docs/remote-protocol/v1/golden/requests/list_projects.json new file mode 100644 index 000000000..1082f94c0 --- /dev/null +++ b/docs/remote-protocol/v1/golden/requests/list_projects.json @@ -0,0 +1,7 @@ +{ + "protocol_version": 1, + "request_id": "req-projects", + "operation": { + "type": "list_projects" + } +} diff --git a/docs/remote-protocol/v1/golden/requests/subscribe_saved_sessions.json b/docs/remote-protocol/v1/golden/requests/subscribe_saved_sessions.json new file mode 100644 index 000000000..fe7982c51 --- /dev/null +++ b/docs/remote-protocol/v1/golden/requests/subscribe_saved_sessions.json @@ -0,0 +1,7 @@ +{ + "protocol_version": 1, + "request_id": "req-saved-sub", + "operation": { + "type": "subscribe_saved_sessions" + } +} diff --git a/docs/remote-protocol/v1/request.schema.json b/docs/remote-protocol/v1/request.schema.json index 27b3ad21c..606226c19 100644 --- a/docs/remote-protocol/v1/request.schema.json +++ b/docs/remote-protocol/v1/request.schema.json @@ -621,6 +621,32 @@ "session_id" ], "type": "object" + }, + { + "description": "Every project the host's saved threads belong to, most recently\nupdated first. Read-only. Requires the `projects` host capability.", + "properties": { + "type": { + "const": "list_projects", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + { + "description": "Push a `saved_sessions_changed` frame whenever a saved thread or a\nproject is added, changed or removed, until the connection ends.\nAnswered with `saved_sessions_subscribed` once the host holds the\nstate later frames are measured against: list after that answer.\nRequires the `saved_session_updates` host capability.", + "properties": { + "type": { + "const": "subscribe_saved_sessions", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" } ] }, diff --git a/docs/remote.md b/docs/remote.md index dd69726ff..93ea5307c 100644 --- a/docs/remote.md +++ b/docs/remote.md @@ -184,7 +184,9 @@ already sent to the client. A host streams at most 32 live shares at once, the threads used most recently. That bound limits streaming, not what a device sees: every thread on the machine is in the paged `list_saved_sessions` list, newest first, with its -project, title, last write and state, and a device opens one that is not +project, title, last write, state, status, pin and harness, `list_projects` +lists every project, `subscribe_saved_sessions` pushes their changes, and a +device opens one that is not shared with `resume_session` (see [Saved sessions](#saved-sessions)). Prompts a device queues on a thread are dropped when sharing ends, and a share the gateway turns down is retried no more than once a minute. diff --git a/rustcode/engine/src/remote/contract.rs b/rustcode/engine/src/remote/contract.rs index 44a52a773..96a7ef55a 100644 --- a/rustcode/engine/src/remote/contract.rs +++ b/rustcode/engine/src/remote/contract.rs @@ -722,6 +722,18 @@ pub fn golden_requests() -> Vec<(&'static str, RemoteRequest)> { "get_changes", request("req-changes", session, RemoteOperation::GetChanges), ), + ( + "list_projects", + request("req-projects", None, RemoteOperation::ListProjects), + ), + ( + "subscribe_saved_sessions", + request( + "req-saved-sub", + None, + RemoteOperation::SubscribeSavedSessions, + ), + ), ( "get_usage", request("req-usage", None, RemoteOperation::GetUsage), @@ -1408,43 +1420,50 @@ pub fn golden_frames() -> Vec<(String, RemoteFrame)> { None, RemoteResult::SavedSessions { sessions: vec![ - RemoteSavedSession { - session_id: SAVED_SESSION.to_owned(), - title: "Fix the parser".to_owned(), - project: Some("/Users/example/projects/parser".to_owned()), - parent: None, - workspace: Some("/Users/example/projects/parser".to_owned()), - updated_at: Some("2026-07-14T09:40:12Z".to_owned()), - message_count: 42, - state: SavedSessionState::Saved, - open_in: None, - }, + golden_saved_session(), RemoteSavedSession { session_id: SESSION.0.to_owned(), title: "Refactor the session store".to_owned(), project: Some("/Users/example/projects/rustcode".to_owned()), - parent: None, workspace: Some("/Users/example/projects/rustcode".to_owned()), updated_at: Some("2026-07-14T08:02:55Z".to_owned()), message_count: 118, state: SavedSessionState::Shared, - open_in: None, + status: Some("running".to_owned()), + pinned: false, + snoozed_until: None, + harness: Some("claude-code".to_owned()), + scheduled_job: None, + ..golden_saved_session() }, RemoteSavedSession { session_id: "20260713-171233-9b0e44".to_owned(), title: "Untitled".to_owned(), - project: None, - parent: None, - workspace: None, - updated_at: None, message_count: 3, state: SavedSessionState::Open, open_in: Some(SavedSessionHolder::App), + status: Some("idle".to_owned()), + ..RemoteSavedSession::default() }, ], next_cursor: Some("20260713-171233-9b0e44".to_owned()), }, ), + response( + "projects", + "req-projects", + None, + RemoteResult::Projects { + projects: vec![golden_project()], + truncated: false, + }, + ), + response( + "saved_sessions_subscribed", + "req-saved-sub", + None, + RemoteResult::SavedSessionsSubscribed, + ), response( "share_request_sent", "req-0020", @@ -1852,9 +1871,49 @@ pub fn golden_frames() -> Vec<(String, RemoteFrame)> { ], }), ), + ( + "saved_sessions_changed".to_owned(), + RemoteFrame::SavedSessionsChanged(RemoteSavedSessionsChanged { + protocol_version: REMOTE_PROTOCOL_VERSION, + sessions: vec![golden_saved_session()], + removed: vec!["20260713-171233-9b0e44".to_owned()], + projects: vec![golden_project()], + removed_projects: vec!["/Users/example/projects/old".to_owned()], + }), + ), ] } +/// A saved thread with every optional field the sidebar shows. +fn golden_saved_session() -> RemoteSavedSession { + RemoteSavedSession { + session_id: SAVED_SESSION.to_owned(), + title: "Fix the parser".to_owned(), + project: Some("/Users/example/projects/parser".to_owned()), + workspace: Some("/Users/example/worktrees/parser-fix".to_owned()), + updated_at: Some("2026-07-14T09:40:12Z".to_owned()), + message_count: 42, + status: Some("review".to_owned()), + pinned: true, + snoozed_until: Some("2026-07-15T08:00:00Z".to_owned()), + harness: Some("codex".to_owned()), + model: Some("gpt-5.5".to_owned()), + scheduled_job: Some("nightly-triage".to_owned()), + ..RemoteSavedSession::default() + } +} + +fn golden_project() -> RemoteProject { + RemoteProject { + path: "/Users/example/projects/parser".to_owned(), + name: "parser".to_owned(), + thread_count: 12, + running: true, + needs_input: false, + updated_at: Some("2026-07-14T09:40:12Z".to_owned()), + } +} + /// Every committed file as `(path relative to CONTRACT_DIR, contents)`. pub fn contract_files() -> Vec<(String, String)> { fn pretty(value: &T) -> String { diff --git a/rustcode/engine/src/remote/protocol.rs b/rustcode/engine/src/remote/protocol.rs index 7514fc93c..2628e83db 100644 --- a/rustcode/engine/src/remote/protocol.rs +++ b/rustcode/engine/src/remote/protocol.rs @@ -53,6 +53,11 @@ pub mod host_capability { pub const THREAD_SETTLE: &str = "thread_settle"; /// `unsettle_thread`: return a settled thread to idle. pub const THREAD_UNSETTLE: &str = "thread_unsettle"; + /// `list_projects`: every project the host's saved threads belong to. + pub const PROJECTS: &str = "projects"; + /// `subscribe_saved_sessions`: `saved_sessions_changed` frames whenever a + /// saved thread or project is added, changed or removed. + pub const SAVED_SESSION_UPDATES: &str = "saved_session_updates"; } /// Optional operations one session owner implements, in @@ -64,6 +69,9 @@ pub mod session_capability { pub const HOST_THREADS: &str = "host_threads"; } +/// Most projects one `projects` result lists. +pub const MAX_PROJECTS: usize = 500; + /// Default and largest page of `list_saved_sessions`. pub const SAVED_SESSIONS_DEFAULT_LIMIT: u32 = 30; pub const SAVED_SESSIONS_MAX_LIMIT: u32 = 100; @@ -251,11 +259,20 @@ pub enum RemoteOperation { UnsettleThread { session_id: String, }, + /// Every project the host's saved threads belong to, most recently + /// updated first. Read-only. Requires the `projects` host capability. + ListProjects, + /// Push a `saved_sessions_changed` frame whenever a saved thread or a + /// project is added, changed or removed, until the connection ends. + /// Answered with `saved_sessions_subscribed` once the host holds the + /// state later frames are measured against: list after that answer. + /// Requires the `saved_session_updates` host capability. + SubscribeSavedSessions, } impl RemoteOperation { /// Every `type` tag this version understands. - pub const NAMES: [&'static str; 30] = [ + pub const NAMES: [&'static str; 32] = [ "list_sessions", "list_directories", "create_session", @@ -286,6 +303,8 @@ impl RemoteOperation { "unpin_thread", "settle_thread", "unsettle_thread", + "list_projects", + "subscribe_saved_sessions", ]; pub fn name(&self) -> &'static str { @@ -320,6 +339,8 @@ impl RemoteOperation { Self::UnpinThread { .. } => "unpin_thread", Self::SettleThread { .. } => "settle_thread", Self::UnsettleThread { .. } => "unsettle_thread", + Self::ListProjects => "list_projects", + Self::SubscribeSavedSessions => "subscribe_saved_sessions", } } @@ -343,6 +364,8 @@ impl RemoteOperation { | Self::UnpinThread { .. } | Self::SettleThread { .. } | Self::UnsettleThread { .. } + | Self::ListProjects + | Self::SubscribeSavedSessions ) } @@ -413,6 +436,9 @@ pub enum RemoteFrame { Response(RemoteResponse), Event(RemoteEventFrame), Sessions(RemoteSessionsFrame), + /// Pushed after `subscribe_saved_sessions` when saved threads or + /// projects change. + SavedSessionsChanged(RemoteSavedSessionsChanged), } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] @@ -504,6 +530,16 @@ pub enum RemoteResult { session_id: String, settled: bool, }, + /// The answer to `list_projects`. + Projects { + projects: Vec, + /// More than [`MAX_PROJECTS`] projects, or more than one frame holds, + /// exist; the least recently updated were left out. + truncated: bool, + }, + /// `subscribe_saved_sessions` took effect: changes after this answer + /// arrive as `saved_sessions_changed` frames. + SavedSessionsSubscribed, /// One page of `list_saved_sessions`. SavedSessions { sessions: Vec, @@ -967,7 +1003,7 @@ pub struct RemoteChangedFile { } /// One saved session as `list_saved_sessions` reports it. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub struct RemoteSavedSession { pub session_id: String, pub title: String, @@ -997,12 +1033,74 @@ pub struct RemoteSavedSession { /// place. #[serde(default, skip_serializing_if = "Option::is_none")] pub open_in: Option, + /// The thread's status as the desktop app shows it: `idle`, `running`, + /// `needs_input` (an approval or question waits), `stalled`, `review` or + /// `done` (settled). Absent from older hosts. A later release may add + /// values; a client shows one it does not know as `idle`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Pinned in the desktop app's sidebar. False from older hosts. + #[serde(default)] + pub pinned: bool, + /// RFC 3339 time a snoozed thread wakes; absent when it is not snoozed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snoozed_until: Option, + /// The harness the thread runs on: `rustcode` for the built-in one, else + /// the harness id (`claude-code`, `codex`, `pi`, …). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub harness: Option, + /// The model or model profile recorded for the thread, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + /// The scheduled job whose run this thread is. The desktop app shows such + /// threads under the job, not in the sidebar. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scheduled_job: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +/// One project as `list_projects` and `saved_sessions_changed` report it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct RemoteProject { + /// The project's folder, the same value saved threads carry in `project`. + pub path: String, + /// The folder's name, as the desktop app's sidebar labels it. + pub name: String, + /// Saved threads in the project, settled ones included. + pub thread_count: u64, + /// A thread of the project has a turn running or waits on the user. + pub running: bool, + /// A thread of the project waits on an approval or a question. + pub needs_input: bool, + /// RFC 3339 time the project's most recently written thread was written. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updated_at: Option, +} + +/// Saved threads and projects that changed since the previous frame (or since +/// `saved_sessions_subscribed`). Each entry is whole: replace what the client +/// holds under its `session_id` or `path`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct RemoteSavedSessionsChanged { + pub protocol_version: u32, + /// Added or changed threads, as `list_saved_sessions` reports them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sessions: Vec, + /// IDs of threads that are no longer saved on the host. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub removed: Vec, + /// Added or changed projects, as `list_projects` reports them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub projects: Vec, + /// Paths of projects that no longer have a saved thread. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub removed_projects: Vec, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SavedSessionState { /// No process holds it: `resume_session` opens it. + #[default] Saved, /// Shared and in the live list: attach to it. Shared, @@ -1751,6 +1849,8 @@ mod tests { RemoteOperation::UnsettleThread { session_id: String::new(), }, + RemoteOperation::ListProjects, + RemoteOperation::SubscribeSavedSessions, ]; assert_eq!(operations.len(), RemoteOperation::NAMES.len()); for (operation, name) in operations.iter().zip(RemoteOperation::NAMES) { diff --git a/rustcode/engine/src/remote_gateway/wire_names.rs b/rustcode/engine/src/remote_gateway/wire_names.rs index 5b2c04fc6..3b59e65ff 100644 --- a/rustcode/engine/src/remote_gateway/wire_names.rs +++ b/rustcode/engine/src/remote_gateway/wire_names.rs @@ -34,6 +34,8 @@ const TAGS: &[(&str, &str)] = &[ ("list_sessions", "list_threads"), ("resume_session", "resume_thread"), ("saved_sessions", "saved_threads"), + ("saved_sessions_changed", "saved_threads_changed"), + ("saved_sessions_subscribed", "saved_threads_subscribed"), ("session_changed", "thread_changed"), ("session_closed", "thread_closed"), ("session_created", "thread_created"), @@ -42,6 +44,7 @@ const TAGS: &[(&str, &str)] = &[ ("sessions", "threads"), ("set_session_settings", "set_thread_settings"), ("stale_session", "stale_thread"), + ("subscribe_saved_sessions", "subscribe_saved_threads"), ("subscribe_sessions", "subscribe_threads"), ]; diff --git a/rustcode/engine/src/remote_gateway/workspace.rs b/rustcode/engine/src/remote_gateway/workspace.rs index 9d5528507..1d59f956b 100644 --- a/rustcode/engine/src/remote_gateway/workspace.rs +++ b/rustcode/engine/src/remote_gateway/workspace.rs @@ -24,6 +24,9 @@ const OWNER_START_TIMEOUT: Duration = Duration::from_secs(60); const ANSWER_DEADLINE: Duration = Duration::from_secs(15); const OWNER_LEASE: &str = "remote session"; +mod saved_threads; +use saved_threads::{Live, SavedIndex, SavedWatch, live_state}; + /// The owner of a new session could not be started, and nothing is left of /// the attempt: no process and no receipt. The device may simply ask again. #[derive(Debug)] @@ -474,7 +477,7 @@ fn spawn_host( /// applies. fn list_saved_sessions( config: &Path, - state_of: impl Fn(&str) -> SavedSessionState, + live: impl Fn(&str) -> Live, cursor: Option<&str>, limit: Option, query: Option<&str>, @@ -544,42 +547,8 @@ fn list_saved_sessions( else { continue; }; - let updated_at = std::fs::metadata(&meta.path) - .and_then(|metadata| metadata.modified()) - .ok() - .map(|modified| { - chrono::DateTime::::from(modified) - .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - }); - let state = state_of(&session_id); - let open_in = (state == SavedSessionState::Open) - .then(|| crate::sessions::session_open_by(config, &session_id)) - .flatten() - .flatten() - .map(saved_session_holder); - // A device shows the folder, not a Windows API detail: the verbatim - // prefix a canonical path carries makes one project look like two (#3425). - let workspace = meta.workspace_cwd.as_ref().map(|cwd| { - rustcode_session::strip_verbatim(cwd) - .to_string_lossy() - .into_owned() - }); - let parent = crate::remote::session_parent(&session_id); - let session = RemoteSavedSession { - state, - open_in, - parent, - title: meta - .title - .chars() - .take(MAX_SAVED_SESSION_TITLE_CHARS) - .collect(), - project: workspace.clone(), - workspace, - updated_at, - message_count: meta.message_count as u64, - session_id, - }; + let session = + saved_threads::entry(config, &store, &meta, session_id.clone(), live(&session_id)); bytes += serde_json::to_vec(&session)?.len() + 1; // Long workspace paths must not push the page past one frame: end // the page early and continue after the last session that fits. @@ -671,6 +640,8 @@ pub struct WorkspaceRouter { config: PathBuf, program: PathBuf, creation: Arc>, + saved: Arc>, + watch: Arc, } impl WorkspaceRouter { pub fn new(hub: Arc, config: PathBuf, program: PathBuf) -> Self { @@ -684,14 +655,26 @@ impl WorkspaceRouter { host_capability::THREAD_UNPIN, host_capability::THREAD_SETTLE, host_capability::THREAD_UNSETTLE, + host_capability::PROJECTS, + host_capability::SAVED_SESSION_UPDATES, ]); Self { hub, config, program, creation: Arc::new(tokio::sync::Mutex::new(())), + saved: Arc::default(), + watch: Arc::default(), } } + /// Every saved thread's entry, read through the shared transcript cache. + fn scan(&self) -> Arc Vec + Send + Sync> { + let (hub, config, saved) = (self.hub.clone(), self.config.clone(), self.saved.clone()); + Arc::new(move || { + let mut index = saved.lock().unwrap_or_else(|error| error.into_inner()); + index.scan(&config, &|id| live_state(&hub, &config, id)) + }) + } fn receipt_path(config: &Path, device: &str, request: &str) -> PathBuf { let mut digest = Sha256::new(); digest.update(device); @@ -751,7 +734,7 @@ impl WorkspaceRouter { if let Some(response) = previous.as_ref().and_then(|stored| stored.response.clone()) { return Ok(response); } - let directory = resolve_directory(path, &allowed_roots(config)?)?; + let directory = saved_threads::resolve_creation_directory(config, path)?; // A home directory works but tracks hundreds of thousands of files: // flag it in the session log so the next slow-turn report starts with // the workspace root, not the network (#1954). @@ -1129,6 +1112,7 @@ impl FrameRouter for WorkspaceRouter { self.hub.connected(device, sink); } fn disconnected(&self, device: &DeviceContext) { + self.watch.unsubscribe(device.connection_id); self.hub.disconnected(device); } fn frame(&self, device: &DeviceContext, frame: &str, sink: &FrameSink) { @@ -1172,23 +1156,10 @@ impl FrameRouter for WorkspaceRouter { let config = self.config.clone(); let sink = sink.clone(); tokio::spawn(async move { - let owners = config.join("remote").join("owners"); let result = tokio::task::spawn_blocking(move || { list_saved_sessions( &config, - |session_id| { - if hub.session_info(session_id).is_some() { - SavedSessionState::Shared - } else if hub.is_announced(session_id) - || owner_alive(&owners, session_id) - || crate::sessions::session_open_by(&config, session_id) - .is_some() - { - SavedSessionState::Open - } else { - SavedSessionState::Saved - } - }, + |session_id| live_state(&hub, &config, session_id), cursor.as_deref(), limit, query.as_deref(), @@ -1214,6 +1185,23 @@ impl FrameRouter for WorkspaceRouter { send(&sink, response); }); } + RemoteOperation::ListProjects => { + let scan = self.scan(); + spawn_host( + sink, + request.request_id.clone(), + false, + RemoteErrorCode::Internal, + move || { + saved_threads::list_projects(&scan()).map_err(|error| error.to_string()) + }, + ); + } + RemoteOperation::SubscribeSavedSessions => { + let scan = self.scan(); + self.watch + .subscribe(device.connection_id, sink, request.request_id.clone(), scan); + } RemoteOperation::GetUsage => { let config = self.config.clone(); spawn_host( @@ -1308,8 +1296,8 @@ impl FrameRouter for WorkspaceRouter { } = &request.operation && self.hub.hosts_threads() { - let directory = allowed_roots(&self.config) - .and_then(|roots| resolve_directory(path.as_deref(), &roots)); + let directory = + saved_threads::resolve_creation_directory(&self.config, path.as_deref()); match directory { Ok(directory) => { let mut forwarded = request.clone(); @@ -2403,12 +2391,13 @@ mod tests { ], ); let shared = ids[1].clone(); - let state_of = |id: &str| { - if id == shared { + let state_of = |id: &str| Live { + state: if id == shared { SavedSessionState::Shared } else { SavedSessionState::Saved - } + }, + activity: None, }; let (first, cursor) = saved_page(list_saved_sessions(config.path(), state_of, None, Some(2), None).unwrap()); @@ -2645,12 +2634,13 @@ mod tests { } let saved = list_saved_sessions( config.path(), - |id| { - if crate::sessions::session_open_by(config.path(), id).is_some() { + |id| Live { + state: if crate::sessions::session_open_by(config.path(), id).is_some() { SavedSessionState::Open } else { SavedSessionState::Saved - } + }, + activity: None, }, None, None, @@ -2757,7 +2747,9 @@ mod tests { host_capability::THREAD_PIN, host_capability::THREAD_UNPIN, host_capability::THREAD_SETTLE, - host_capability::THREAD_UNSETTLE + host_capability::THREAD_UNSETTLE, + host_capability::PROJECTS, + host_capability::SAVED_SESSION_UPDATES ] ); }); diff --git a/rustcode/engine/src/remote_gateway/workspace/saved_threads.rs b/rustcode/engine/src/remote_gateway/workspace/saved_threads.rs new file mode 100644 index 000000000..5817de884 --- /dev/null +++ b/rustcode/engine/src/remote_gateway/workspace/saved_threads.rs @@ -0,0 +1,550 @@ +//! What a device's thread list shows: each saved thread as the desktop app's +//! sidebar shows it, the projects those threads belong to, and the watcher +//! that pushes their changes to subscribed devices +//! (`docs/remote-protocol/README.md`, *Saved sessions*). +//! +//! Everything is read from the session store under the gateway's config +//! directory and from the live list the gateway holds. Unread marks, the +//! sidebar's manual order and projects the app knows before their first +//! thread live in the app's own storage, so no device sees them. + +use super::*; +use rustcode_session::{SessionMeta, SessionMetadata, SessionStore}; +use std::collections::{HashMap, HashSet}; +use std::sync::Mutex; +use std::time::SystemTime; + +/// How often the watcher looks for changes while a device is subscribed. +const WATCH_INTERVAL: Duration = Duration::from_secs(5); + +/// The part of a frame a page or a change frame may fill, leaving room for +/// the envelope and the wire-name translation. +const FRAME_BUDGET: usize = MAX_REMOTE_FRAME_BYTES / 2; + +/// What the gateway knows of a thread from processes, not files. +#[derive(Debug, Clone, Copy)] +pub(super) struct Live { + pub state: SavedSessionState, + /// The shared thread's activity, when it is in the live list. + pub activity: Option, +} + +/// Whether `session_id` is shared, held by a process or only saved, and what +/// a shared one is doing. +pub(super) fn live_state(hub: &SessionHub, config: &Path, session_id: &str) -> Live { + if let Some(info) = hub.session_info(session_id) { + return Live { + state: SavedSessionState::Shared, + activity: Some(info.activity), + }; + } + let open = hub.is_announced(session_id) + || owner_alive(&config.join("remote").join("owners"), session_id) + || crate::sessions::session_open_by(config, session_id).is_some(); + Live { + state: if open { + SavedSessionState::Open + } else { + SavedSessionState::Saved + }, + activity: None, + } +} + +fn read_json(path: &Path) -> Option { + serde_json::from_slice(&std::fs::read(path).ok()?).ok() +} + +fn rfc3339(time: chrono::DateTime) -> String { + time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} + +/// The status the desktop app shows: a settled thread stays `done` while its +/// last turn winds down, a live turn comes next, then what the store holds. +fn status_of(directory: &Path, activity: Option) -> &'static str { + let stored = read_json(&directory.join("status.json")) + .and_then(|value| value.get("status")?.as_str().map(str::to_owned)); + if stored.as_deref() == Some("done") { + return "done"; + } + match activity { + Some(SessionActivity::Running) => "running", + Some(SessionActivity::AwaitingApproval | SessionActivity::AwaitingQuestion) => { + "needs_input" + } + Some(SessionActivity::Idle) | None => match stored.as_deref() { + Some("review") => "review", + Some("stalled") => "stalled", + _ => "idle", + }, + } +} + +fn snoozed_until(directory: &Path) -> Option { + let until = read_json(&directory.join("snooze.json"))?.as_u64()?; + let wakes = chrono::DateTime::::from_timestamp_millis(i64::try_from(until).ok()?)?; + (wakes > chrono::Utc::now()).then(|| rfc3339(wakes)) +} + +/// A folder the desktop app never lists as a project: a drive's root, or +/// RustCode's own data folder, where the store and worktrees live. +fn not_a_project(config: &Path, path: &Path) -> bool { + path.parent().is_none() || path.starts_with(config) +} + +/// The project the desktop app files a thread under: a worktree's repository, +/// else the repository recorded for its folder, else the folder itself. None +/// for a thread whose folder was never recorded. +fn thread_project( + config: &Path, + directory: &Path, + workspace: Option<&Path>, + metadata: Option<&SessionMetadata>, +) -> Option { + let workspace = workspace?; + let worktree_repo = read_json(&directory.join("worktree.json")) + .and_then(|value| value.get("repo")?.as_str().map(PathBuf::from)); + let path = worktree_repo + .or_else(|| metadata.and_then(|metadata| metadata.repo.clone())) + .unwrap_or_else(|| workspace.to_path_buf()); + let path = rustcode_session::strip_verbatim(&path); + (!not_a_project(config, &path)).then(|| path.to_string_lossy().into_owned()) +} + +/// One saved thread as `list_saved_sessions` reports it. +pub(super) fn entry( + config: &Path, + store: &SessionStore, + meta: &SessionMeta, + session_id: String, + live: Live, +) -> RemoteSavedSession { + let directory = meta + .path + .parent() + .map_or_else(|| store.session_dir(&session_id), Path::to_path_buf); + let updated_at = std::fs::metadata(&meta.path) + .and_then(|metadata| metadata.modified()) + .ok() + .map(|modified| rfc3339(modified.into())); + let open_in = (live.state == SavedSessionState::Open) + .then(|| crate::sessions::session_open_by(config, &session_id)) + .flatten() + .flatten() + .map(saved_session_holder); + let workspace = meta + .workspace_cwd + .as_ref() + .map(|cwd| rustcode_session::strip_verbatim(cwd)); + let metadata = store.load_session_metadata(&session_id); + let harness = read_json(&directory.join("harness.json")); + let harness_field = |field: &str| { + harness + .as_ref() + .and_then(|record| record.get(field)?.as_str()) + .filter(|value| !value.is_empty()) + .map(str::to_owned) + }; + let parent = metadata + .as_ref() + .and_then(|metadata| metadata.parent.as_ref()) + .and_then(|parent| { + Some(RemoteThreadParent { + session_id: parent.id.clone()?, + relationship: parent.relationship().as_str().to_owned(), + }) + }); + RemoteSavedSession { + state: live.state, + open_in, + parent, + title: meta + .title + .chars() + .take(MAX_SAVED_SESSION_TITLE_CHARS) + .collect(), + project: thread_project(config, &directory, workspace.as_deref(), metadata.as_ref()), + workspace: workspace.map(|cwd| cwd.to_string_lossy().into_owned()), + updated_at, + message_count: meta.message_count as u64, + status: Some(status_of(&directory, live.activity).to_owned()), + pinned: directory.join("pin.json").is_file(), + snoozed_until: snoozed_until(&directory), + harness: Some( + harness_field("harness").unwrap_or_else(|| crate::harness::BUILTIN_ID.to_owned()), + ), + model: harness_field("model").or_else(|| { + metadata + .as_ref() + .and_then(|metadata| metadata.model.as_ref()) + .map(|model| model.profile.clone()) + .filter(|profile| !profile.is_empty()) + }), + scheduled_job: metadata.and_then(|metadata| metadata.scheduled_job), + session_id, + } +} + +/// The projects `entries` belong to, most recently updated first. +pub(super) fn projects(entries: &[RemoteSavedSession]) -> Vec { + let mut by_path: HashMap<&str, RemoteProject> = HashMap::new(); + for entry in entries { + let Some(path) = entry.project.as_deref() else { + continue; + }; + let project = by_path.entry(path).or_insert_with(|| RemoteProject { + path: path.to_owned(), + name: Path::new(path).file_name().map_or_else( + || path.to_owned(), + |name| name.to_string_lossy().into_owned(), + ), + thread_count: 0, + running: false, + needs_input: false, + updated_at: None, + }); + project.thread_count += 1; + let status = entry.status.as_deref(); + project.needs_input |= status == Some("needs_input"); + project.running |= matches!(status, Some("running" | "needs_input")); + if entry.updated_at > project.updated_at { + project.updated_at.clone_from(&entry.updated_at); + } + } + let mut projects: Vec = by_path.into_values().collect(); + projects.sort_by(|left, right| { + right + .updated_at + .cmp(&left.updated_at) + .then_with(|| left.path.cmp(&right.path)) + }); + projects +} + +/// The answer to `list_projects`, bounded to [`MAX_PROJECTS`] and one frame. +pub(super) fn list_projects(entries: &[RemoteSavedSession]) -> Result { + let mut all = projects(entries); + let mut truncated = all.len() > MAX_PROJECTS; + all.truncate(MAX_PROJECTS); + let mut bytes = 0; + let mut kept = 0; + for project in &all { + bytes += serde_json::to_vec(project)?.len() + 1; + if bytes > FRAME_BUDGET { + truncated = true; + break; + } + kept += 1; + } + all.truncate(kept); + Ok(RemoteResult::Projects { + projects: all, + truncated, + }) +} + +type Stamp = [Option<(SystemTime, u64)>; 3]; + +fn stamp_of(path: &Path) -> Option<(SystemTime, u64)> { + let metadata = std::fs::metadata(path).ok()?; + Some((metadata.modified().ok()?, metadata.len())) +} + +/// Every saved thread's entry, with each transcript read again only when it, +/// its title or its workspace record changed since the last scan. +#[derive(Default)] +pub(super) struct SavedIndex { + metas: HashMap)>, +} + +impl SavedIndex { + pub(super) fn scan( + &mut self, + config: &Path, + live: &dyn Fn(&str) -> Live, + ) -> Vec { + let store = SessionStore::new(config); + let mut seen = HashSet::new(); + let mut kept = HashSet::new(); + let mut entries = Vec::new(); + for path in store.session_history_paths() { + let Some(id) = SessionStore::session_id_from_path(&path) else { + continue; + }; + if !rustcode_session::valid_session_id(&id) + || seen.contains(&id) + || !crate::sessions::session_file_in_store(config, &path) + { + continue; + } + let Some(directory) = path.parent() else { + continue; + }; + let stamp = [ + stamp_of(&path), + stamp_of(&directory.join("title.txt")), + stamp_of(&directory.join(rustcode_session::SESSION_WORKSPACE_FILE)), + ]; + let cached = self.metas.get(&path).filter(|(known, _)| *known == stamp); + let meta = match cached { + Some((_, meta)) => meta.clone(), + None => { + let meta = store.load_session_meta(&path); + self.metas.insert(path.clone(), (stamp, meta.clone())); + meta + } + }; + kept.insert(path); + if let Some(meta) = meta { + seen.insert(id.clone()); + let state = live(&id); + entries.push(entry(config, &store, &meta, id, state)); + } + } + self.metas.retain(|path, _| kept.contains(path)); + entries + } +} + +/// The state change frames are measured against. +#[derive(Default)] +struct Baseline { + sessions: HashMap, + projects: HashMap, +} + +impl Baseline { + fn of(entries: Vec) -> Self { + let projects = projects(&entries) + .into_iter() + .map(|project| (project.path.clone(), project)) + .collect(); + let sessions = entries + .into_iter() + .map(|entry| (entry.session_id.clone(), entry)) + .collect(); + Self { sessions, projects } + } +} + +enum Change { + Session(RemoteSavedSession), + Removed(String), + Project(RemoteProject), + RemovedProject(String), +} + +fn empty_change_frame() -> RemoteSavedSessionsChanged { + RemoteSavedSessionsChanged { + protocol_version: REMOTE_PROTOCOL_VERSION, + sessions: Vec::new(), + removed: Vec::new(), + projects: Vec::new(), + removed_projects: Vec::new(), + } +} + +/// The `saved_sessions_changed` frames that take a client from `before` to +/// `after`, each within [`FRAME_BUDGET`]; none when nothing changed. +fn change_frames(before: &Baseline, after: &Baseline) -> Vec { + let mut changes: Vec = Vec::new(); + let mut sessions: Vec<&RemoteSavedSession> = after + .sessions + .values() + .filter(|entry| before.sessions.get(&entry.session_id) != Some(*entry)) + .collect(); + sessions.sort_by(|left, right| right.session_id.cmp(&left.session_id)); + changes.extend(sessions.into_iter().cloned().map(Change::Session)); + let mut removed: Vec<&String> = before + .sessions + .keys() + .filter(|id| !after.sessions.contains_key(*id)) + .collect(); + removed.sort(); + changes.extend(removed.into_iter().cloned().map(Change::Removed)); + let mut projects: Vec<&RemoteProject> = after + .projects + .values() + .filter(|project| before.projects.get(&project.path) != Some(*project)) + .collect(); + projects.sort_by(|left, right| left.path.cmp(&right.path)); + changes.extend(projects.into_iter().cloned().map(Change::Project)); + let mut gone: Vec<&String> = before + .projects + .keys() + .filter(|path| !after.projects.contains_key(*path)) + .collect(); + gone.sort(); + changes.extend(gone.into_iter().cloned().map(Change::RemovedProject)); + + let mut frames = Vec::new(); + let mut frame = empty_change_frame(); + let mut bytes = 0; + for change in changes { + let size = match &change { + Change::Session(entry) => serde_json::to_vec(entry).map_or(0, |bytes| bytes.len()), + Change::Project(project) => serde_json::to_vec(project).map_or(0, |bytes| bytes.len()), + Change::Removed(text) | Change::RemovedProject(text) => text.len() + 3, + } + 1; + if bytes > 0 && bytes + size > FRAME_BUDGET { + frames.push(std::mem::replace(&mut frame, empty_change_frame())); + bytes = 0; + } + bytes += size; + match change { + Change::Session(entry) => frame.sessions.push(entry), + Change::Removed(id) => frame.removed.push(id), + Change::Project(project) => frame.projects.push(project), + Change::RemovedProject(path) => frame.removed_projects.push(path), + } + } + if bytes > 0 { + frames.push(frame); + } + frames +} + +#[derive(Default)] +struct Subscribers { + active: HashMap, + /// Subscribed, waiting for a scan read after they asked. + pending: Vec<(u64, FrameSink, String)>, + running: bool, +} + +/// Pushes `saved_sessions_changed` to every subscribed connection. One task +/// scans while any device is subscribed and stops when the last one leaves. +#[derive(Default)] +pub(super) struct SavedWatch { + subscribers: Mutex, + wake: tokio::sync::Notify, +} + +type Scan = Arc Vec + Send + Sync>; + +impl SavedWatch { + fn subscribers(&self) -> std::sync::MutexGuard<'_, Subscribers> { + self.subscribers + .lock() + .unwrap_or_else(|error| error.into_inner()) + } + + /// Subscribe a connection. It is answered with `saved_sessions_subscribed` + /// after the next scan, which is started now. + pub(super) fn subscribe( + self: &Arc, + connection: u64, + sink: &FrameSink, + request_id: String, + scan: Scan, + ) { + let start = { + let mut subscribers = self.subscribers(); + subscribers.active.remove(&connection); + subscribers.pending.retain(|(id, _, _)| *id != connection); + subscribers + .pending + .push((connection, sink.clone(), request_id)); + !std::mem::replace(&mut subscribers.running, true) + }; + if start { + tokio::spawn(self.clone().run(scan)); + } + self.wake.notify_one(); + } + + pub(super) fn unsubscribe(&self, connection: u64) { + let mut subscribers = self.subscribers(); + subscribers.active.remove(&connection); + subscribers.pending.retain(|(id, _, _)| *id != connection); + } + + async fn run(self: Arc, scan: Scan) { + let mut baseline: Option = None; + loop { + { + let mut subscribers = self.subscribers(); + if subscribers.active.is_empty() && subscribers.pending.is_empty() { + subscribers.running = false; + return; + } + } + let scan = scan.clone(); + if let Ok(entries) = tokio::task::spawn_blocking(move || scan()).await { + let current = Baseline::of(entries); + let frames: Vec = baseline + .as_ref() + .map(|before| change_frames(before, ¤t)) + .unwrap_or_default() + .into_iter() + .filter_map(|frame| { + serde_json::to_string(&RemoteFrame::SavedSessionsChanged(frame)).ok() + }) + .collect(); + let mut subscribers = self.subscribers(); + subscribers + .active + .retain(|_, sink| frames.iter().all(|frame| sink.send(frame.clone()).is_ok())); + for (connection, sink, request_id) in std::mem::take(&mut subscribers.pending) { + let answer = + RemoteResponse::new(request_id, RemoteResult::SavedSessionsSubscribed); + send(&sink, answer); + subscribers.active.insert(connection, sink); + } + baseline = Some(current); + } + tokio::select! { + () = tokio::time::sleep(WATCH_INTERVAL) => {} + () = self.wake.notified() => {} + } + } + } +} + +/// The folder a device asked to start a thread in: one inside the allowed +/// roots, as before, or exactly the folder of a project the store's threads +/// belong to, which `list_projects` reports wherever it lies. +pub(super) fn resolve_creation_directory(config: &Path, path: Option<&str>) -> Result { + let refusal = match resolve_directory(path, &allowed_roots(config)?) { + Ok(directory) => return Ok(directory), + Err(error) => error, + }; + let Some(named) = path + .map(str::trim) + .filter(|path| Path::new(path).is_absolute()) + .and_then(|path| Path::new(path).canonicalize().ok()) + .filter(|path| path.is_dir()) + else { + return Err(refusal); + }; + let store = SessionStore::new(config); + let mut checked = HashSet::new(); + for history in store.session_history_paths() { + let (Some(id), Some(directory)) = ( + SessionStore::session_id_from_path(&history), + history.parent(), + ) else { + continue; + }; + if !crate::sessions::session_file_in_store(config, &history) { + continue; + } + let workspace = store.load_session_workspace(&id).map(|record| record.cwd); + let metadata = store.load_session_metadata(&id); + let Some(project) = + thread_project(config, directory, workspace.as_deref(), metadata.as_ref()) + else { + continue; + }; + if checked.insert(project.clone()) + && Path::new(&project).canonicalize().ok().as_deref() == Some(named.as_path()) + { + return Ok(named); + } + } + Err(refusal) +} + +#[cfg(test)] +#[path = "saved_threads_tests.rs"] +mod tests; diff --git a/rustcode/engine/src/remote_gateway/workspace/saved_threads_tests.rs b/rustcode/engine/src/remote_gateway/workspace/saved_threads_tests.rs new file mode 100644 index 000000000..c64eacc0b --- /dev/null +++ b/rustcode/engine/src/remote_gateway/workspace/saved_threads_tests.rs @@ -0,0 +1,452 @@ +use super::*; + +/// A saved thread in the store under `config`, in `workspace` when given. +fn thread(config: &Path, title: &str, workspace: Option<&Path>) -> String { + let store = SessionStore::new(config); + let id = rustcode_session::next_session_id(); + let history = vec![ + rustcode_core::ChatMessage::new("user", title), + rustcode_core::ChatMessage::new("assistant", "answer"), + ]; + store.save_session_history(&id, &history); + store.save_session_title(&id, title); + if let Some(cwd) = workspace { + store + .save_session_workspace( + &id, + &rustcode_session::SessionWorkspace { + cwd: cwd.to_path_buf(), + additional_directories: Vec::new(), + task_workspace_id: None, + }, + ) + .unwrap(); + } + rustcode_session::flush_history(); + id +} + +fn directory(config: &Path, id: &str) -> PathBuf { + SessionStore::new(config).session_dir(id) +} + +fn write(config: &Path, id: &str, file: &str, value: serde_json::Value) { + std::fs::write(directory(config, id).join(file), value.to_string()).unwrap(); +} + +fn saved(_: &str) -> Live { + Live { + state: SavedSessionState::Saved, + activity: None, + } +} + +fn find<'a>(entries: &'a [RemoteSavedSession], id: &str) -> &'a RemoteSavedSession { + entries + .iter() + .find(|entry| entry.session_id == id) + .unwrap_or_else(|| panic!("{id} is not listed")) +} + +fn plain(path: &Path) -> String { + path.to_string_lossy().into_owned() +} + +/// A listed thread with only what `projects` reads. +fn listed(id: &str, project: Option<&str>, status: &str, updated: &str) -> RemoteSavedSession { + RemoteSavedSession { + session_id: id.to_owned(), + title: id.to_owned(), + project: project.map(str::to_owned), + parent: None, + workspace: project.map(str::to_owned), + updated_at: Some(updated.to_owned()), + message_count: 2, + state: SavedSessionState::Saved, + open_in: None, + status: Some(status.to_owned()), + pinned: false, + snoozed_until: None, + harness: None, + model: None, + scheduled_job: None, + } +} + +#[test] +fn an_entry_carries_what_the_sidebar_shows() { + let config = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let repo = tempfile::tempdir().unwrap(); + let pinned = thread(config.path(), "Pinned and snoozed", Some(project.path())); + let worktree = thread(config.path(), "In a worktree", Some(project.path())); + let loose = thread(config.path(), "No folder", None); + + write( + config.path(), + &pinned, + "pin.json", + serde_json::json!({"pinned": true}), + ); + write( + config.path(), + &pinned, + "status.json", + serde_json::json!({"status": "review"}), + ); + let wakes = chrono::Utc::now().timestamp_millis() + 3_600_000; + write( + config.path(), + &pinned, + "snooze.json", + serde_json::json!(wakes), + ); + write( + config.path(), + &pinned, + "harness.json", + serde_json::json!({"harness": "codex", "model": "gpt-5.5"}), + ); + SessionStore::new(config.path()) + .save_session_scheduled_job(&pinned, "nightly") + .unwrap(); + write( + config.path(), + &worktree, + "worktree.json", + serde_json::json!({"repo": plain(repo.path())}), + ); + write( + config.path(), + &worktree, + "status.json", + serde_json::json!({"status": "done"}), + ); + + let entries = SavedIndex::default().scan(config.path(), &|id| { + if id == worktree { + Live { + state: SavedSessionState::Shared, + activity: Some(SessionActivity::Running), + } + } else { + saved(id) + } + }); + + let first = find(&entries, &pinned); + assert_eq!(first.title, "Pinned and snoozed"); + assert!(first.pinned); + assert_eq!(first.status.as_deref(), Some("review")); + assert!( + first + .snoozed_until + .as_deref() + .is_some_and(|at| at.ends_with('Z')) + ); + assert_eq!(first.harness.as_deref(), Some("codex")); + assert_eq!(first.model.as_deref(), Some("gpt-5.5")); + assert_eq!(first.scheduled_job.as_deref(), Some("nightly")); + assert_eq!(first.project, first.workspace); + + let second = find(&entries, &worktree); + assert_eq!(second.state, SavedSessionState::Shared); + assert_eq!( + second.status.as_deref(), + Some("done"), + "settling outranks the last turn" + ); + assert_eq!(second.project.as_deref(), Some(plain(repo.path()).as_str())); + assert_eq!( + second.workspace.as_deref(), + Some(plain(project.path()).as_str()) + ); + assert!(!second.pinned); + + let third = find(&entries, &loose); + assert_eq!(third.project, None); + assert_eq!(third.status.as_deref(), Some("idle")); + assert_eq!(third.harness.as_deref(), Some(crate::harness::BUILTIN_ID)); + assert_eq!(third.snoozed_until, None); +} + +#[test] +fn a_past_snooze_is_not_reported() { + let config = tempfile::tempdir().unwrap(); + let id = thread(config.path(), "Woke up", None); + write(config.path(), &id, "snooze.json", serde_json::json!(1_000)); + assert_eq!(snoozed_until(&directory(config.path(), &id)), None); +} + +#[test] +fn live_activity_comes_after_settling_and_before_what_is_stored() { + let config = tempfile::tempdir().unwrap(); + let id = thread(config.path(), "Status", None); + let dir = directory(config.path(), &id); + let store = |status: &str| { + write( + config.path(), + &id, + "status.json", + serde_json::json!({"status": status}), + ) + }; + + assert_eq!(status_of(&dir, None), "idle"); + store("review"); + assert_eq!(status_of(&dir, None), "review"); + assert_eq!(status_of(&dir, Some(SessionActivity::Idle)), "review"); + assert_eq!(status_of(&dir, Some(SessionActivity::Running)), "running"); + assert_eq!( + status_of(&dir, Some(SessionActivity::AwaitingQuestion)), + "needs_input" + ); + store("stalled"); + assert_eq!(status_of(&dir, None), "stalled"); + store("done"); + assert_eq!( + status_of(&dir, Some(SessionActivity::AwaitingApproval)), + "done" + ); +} + +#[test] +fn projects_group_threads_newest_first() { + let entries = [ + listed("a", Some("/code/app"), "idle", "2026-11-01T10:00:00Z"), + listed( + "b", + Some("/code/app"), + "needs_input", + "2026-11-03T10:00:00Z", + ), + listed("c", Some("/code/lib"), "done", "2026-11-02T10:00:00Z"), + listed("d", Some("/code/web"), "running", "2026-10-01T10:00:00Z"), + listed("e", None, "running", "2026-11-04T10:00:00Z"), + ]; + let projects = projects(&entries); + assert_eq!( + projects.iter().map(|p| p.path.as_str()).collect::>(), + ["/code/app", "/code/lib", "/code/web"] + ); + let app = &projects[0]; + assert_eq!(app.name, "app"); + assert_eq!(app.thread_count, 2); + assert!(app.running && app.needs_input); + assert_eq!(app.updated_at.as_deref(), Some("2026-11-03T10:00:00Z")); + assert!(!projects[1].running); + assert!(projects[2].running && !projects[2].needs_input); +} + +#[test] +fn a_root_or_the_data_folder_is_no_project() { + let config = tempfile::tempdir().unwrap(); + let dir = config.path().join("threads"); + assert_eq!( + thread_project(config.path(), &dir, Some(Path::new("/")), None), + None + ); + let inside = config.path().join("worktrees").join("x"); + assert_eq!( + thread_project(config.path(), &dir, Some(&inside), None), + None + ); + assert_eq!(thread_project(config.path(), &dir, None, None), None); + assert_eq!( + thread_project(config.path(), &dir, Some(Path::new("/code/app")), None).as_deref(), + Some("/code/app") + ); +} + +#[test] +fn the_project_list_is_bounded() { + let entries: Vec<_> = (0..MAX_PROJECTS + 20) + .map(|n| { + let path = format!("/code/project-{n:04}"); + listed( + &n.to_string(), + Some(&path), + "idle", + &format!("2026-11-01T10:{:02}:00Z", n % 60), + ) + }) + .collect(); + let RemoteResult::Projects { + projects, + truncated, + } = list_projects(&entries).unwrap() + else { + panic!("not a projects result"); + }; + assert_eq!(projects.len(), MAX_PROJECTS); + assert!(truncated); + let RemoteResult::Projects { + projects, + truncated, + } = list_projects(&entries[..3]).unwrap() + else { + panic!("not a projects result"); + }; + assert_eq!(projects.len(), 3); + assert!(!truncated); +} + +#[test] +fn a_rescan_reports_only_what_changed() { + let config = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let other = tempfile::tempdir().unwrap(); + let pin = thread(config.path(), "Pin me", Some(project.path())); + let rename = thread(config.path(), "Rename me", Some(project.path())); + let delete = thread(config.path(), "Delete me", Some(project.path())); + let mut index = SavedIndex::default(); + let before = Baseline::of(index.scan(config.path(), &saved)); + assert!(change_frames(&before, &Baseline::of(index.scan(config.path(), &saved))).is_empty()); + + write( + config.path(), + &pin, + "pin.json", + serde_json::json!({"pinned": true}), + ); + SessionStore::new(config.path()).save_session_title(&rename, "A much longer new title"); + std::fs::remove_dir_all(directory(config.path(), &delete)).unwrap(); + let added = thread(config.path(), "New", Some(other.path())); + let after = Baseline::of(index.scan(config.path(), &saved)); + + let frames = change_frames(&before, &after); + assert_eq!(frames.len(), 1); + let frame = &frames[0]; + let mut changed: Vec<&str> = frame + .sessions + .iter() + .map(|s| s.session_id.as_str()) + .collect(); + changed.sort_unstable(); + let mut expected = vec![pin.as_str(), rename.as_str(), added.as_str()]; + expected.sort_unstable(); + assert_eq!(changed, expected); + assert!(find(&frame.sessions, &pin).pinned); + assert_eq!( + find(&frame.sessions, &rename).title, + "A much longer new title" + ); + assert_eq!(frame.removed, [delete]); + let mut paths: Vec<&str> = frame.projects.iter().map(|p| p.path.as_str()).collect(); + paths.sort_unstable(); + let mut expected = vec![plain(project.path()), plain(other.path())]; + expected.sort_unstable(); + assert_eq!(paths, expected); + assert!(frame.removed_projects.is_empty()); + + std::fs::remove_dir_all(directory(config.path(), &added)).unwrap(); + let last = Baseline::of(index.scan(config.path(), &saved)); + let frames = change_frames(&after, &last); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].removed, [added]); + assert_eq!(frames[0].removed_projects, [plain(other.path())]); + assert!(frames[0].sessions.is_empty()); +} + +#[test] +fn many_changes_are_split_across_frames() { + let long = format!("/code/{}", "x".repeat(2_000)); + let after = Baseline::of( + (0..400) + .map(|n| { + listed( + &format!("{n:04}"), + Some(&long), + "idle", + "2026-11-01T10:00:00Z", + ) + }) + .collect(), + ); + let frames = change_frames(&Baseline::default(), &after); + assert!(frames.len() > 1); + for frame in &frames { + let text = + serde_json::to_string(&RemoteFrame::SavedSessionsChanged(frame.clone())).unwrap(); + assert!(text.len() <= MAX_REMOTE_FRAME_BYTES); + } + assert_eq!(frames.iter().map(|f| f.sessions.len()).sum::(), 400); +} + +async fn next_frame(queue: &mut crate::remote_gateway::router::FrameQueue) -> RemoteFrame { + let text = tokio::time::timeout(Duration::from_secs(10), queue.recv()) + .await + .expect("a frame in time") + .expect("the sink is open"); + serde_json::from_str(&text).unwrap() +} + +#[tokio::test] +async fn a_subscriber_is_answered_then_told_of_each_change() { + let config = tempfile::tempdir().unwrap(); + let id = thread(config.path(), "Watched", None); + let watch = Arc::new(SavedWatch::default()); + let (sink, mut queue) = FrameSink::detached(16); + let root = config.path().to_path_buf(); + let index = Arc::new(Mutex::new(SavedIndex::default())); + let scan: Scan = Arc::new(move || index.lock().unwrap().scan(&root, &saved)); + + watch.subscribe(7, &sink, "req-subscribe".into(), scan); + let RemoteFrame::Response(answer) = next_frame(&mut queue).await else { + panic!("not a response"); + }; + assert_eq!(answer.request_id, "req-subscribe"); + assert_eq!(answer.result, RemoteResult::SavedSessionsSubscribed); + + write( + config.path(), + &id, + "pin.json", + serde_json::json!({"pinned": true}), + ); + watch.wake.notify_one(); + let RemoteFrame::SavedSessionsChanged(changed) = next_frame(&mut queue).await else { + panic!("not a change frame"); + }; + assert_eq!(changed.sessions.len(), 1); + assert_eq!(changed.sessions[0].session_id, id); + assert!(changed.sessions[0].pinned); + + watch.unsubscribe(7); + watch.wake.notify_one(); + tokio::time::timeout(Duration::from_secs(10), async { + while watch.subscribers().running { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the watcher stops with no subscriber"); +} + +#[test] +fn a_project_outside_the_roots_can_be_started_in() { + let config = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + let roots = allowed_roots(config.path()).unwrap(); + if roots + .iter() + .any(|root| elsewhere.path().canonicalize().unwrap().starts_with(root)) + { + return; + } + thread(config.path(), "Outside home", Some(project.path())); + let canonical = project.path().canonicalize().unwrap(); + assert_eq!( + resolve_creation_directory(config.path(), project.path().to_str()).unwrap(), + canonical + ); + let inside = project.path().join("sub"); + std::fs::create_dir(&inside).unwrap(); + for refused_path in [elsewhere.path(), inside.as_path()] { + let error = resolve_creation_directory(config.path(), refused_path.to_str()) + .expect_err("not a project"); + let code = error.downcast_ref::().map(|refused| refused.0); + assert_eq!(code, Some(RemoteErrorCode::InvalidRequest)); + } +} diff --git a/scripts/comment-baseline.txt b/scripts/comment-baseline.txt index 60f17f6f0..998677fe0 100644 --- a/scripts/comment-baseline.txt +++ b/scripts/comment-baseline.txt @@ -964,7 +964,7 @@ 67 rustcode/engine/src/remote_gateway/session_registry/tests.rs 31 rustcode/engine/src/remote_gateway/transport.rs 2 rustcode/engine/src/remote_gateway/wire_names.rs -77 rustcode/engine/src/remote_gateway/workspace.rs +75 rustcode/engine/src/remote_gateway/workspace.rs 8 rustcode/engine/src/serve/server.rs 13 rustcode/engine/src/server/auto_update.rs 3 rustcode/engine/src/server/engine_endpoint.rs