From c8295f11ba1856ca9b3ab0f5f182260a8f0ad465 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 2 Nov 2026 18:48:52 -0500 Subject: [PATCH 1/2] Keep No workspace copies and first sends in private folders --- .memory/workspace-isolation-backlog.md | 11 ++ PRODUCT.md | 2 +- README.md | 2 +- .../sbtbiswas/AidenOnTheGo/AidenChatTest.kt | 3 +- docs/aiden-remote-api-v1.md | 2 +- docs/no-workspace-chats.md | 4 + .../Features/Remote/AidenChatFeature.swift | 5 +- ios/AidenOnTheGoTests/AidenChatTests.swift | 117 +++++++++--------- ios/PROJECT_SPEC.md | 1 + main/handlers/chats.ts | 10 ++ main/services/aiden-remote-chats.ts | 38 ++++-- main/services/aiden-remote-service-main.ts | 4 +- .../chat-first-message-commit.test.ts | 47 ++++++- main/services/chat-first-message-commit.ts | 48 ++++--- main/services/chat-fork-service-main.ts | 10 ++ main/services/chat-fork-service.test.ts | 97 ++++++++++++++- main/services/chat-fork-service.ts | 34 ++++- .../workspace-application-service.test.ts | 27 +++- .../services/workspace-application-service.ts | 43 +++++-- renderer/main/chat-pane.tsx | 20 +-- 20 files changed, 404 insertions(+), 121 deletions(-) create mode 100644 .memory/workspace-isolation-backlog.md diff --git a/.memory/workspace-isolation-backlog.md b/.memory/workspace-isolation-backlog.md new file mode 100644 index 0000000000..756679fa9e --- /dev/null +++ b/.memory/workspace-isolation-backlog.md @@ -0,0 +1,11 @@ +# Workspace isolation backlog — 2026-11-02 + +Revalidated on main `9b2875d65f316265323d3d06a73904fbe00e2277` after #696. Findings 6.2 (populated No workspace copy/fork sharing a private folder/access) and 6.1 (first-send folder allocation invalidating the selected skill) were confirmed current by behavioral repros. + +A shared main-process reservation now excludes concurrent assignment of an empty hidden home until its owning operation and failure cleanup settle. Desktop first-send, copy/fork and supported Remote creation all use this reservation; unknown commit outcomes keep it until restart/reconciliation. + +The shared fork service now assigns a fresh hidden workspace through the existing workspace application service, admits both source and target, and releases only unowned targets on known failure. Unknown commit outcomes retain the target for reconciliation. Named-workspace forks, Bots, shared No workspace memory, existing shared copies and the legacy shared home remain unchanged; newly copied legacy chats get independent folders. Desktop workspace metadata is refreshed before navigating. iOS validates fork lineage rather than workspace equality; Android accepts the returned workspace already. + +Desktop private first-send allocation now happens inside the main-owned first-message committer after durable-receipt replay checks. Its fingerprint keeps the submitted source identity; skill resolution keeps the original selection authority while the prepared turn and persisted chat own the destination. Both workspace admissions cancel/drain preparation. No Remote wire change or runtime network fetch was added. + +Focused source tests reproduce the original folder sharing and cover file/access isolation, named-workspace sharing, refusal cleanup, skill handoff and replay. Native fork tests exercise returned private workspace IDs. Validation and PR details are recorded in the working chat. diff --git a/PRODUCT.md b/PRODUCT.md index 5629517a16..a4003d5366 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -20,7 +20,7 @@ Aiden combines a native-feeling desktop workspace with Pi-based agent extensibil ## Operating Context -The primary application is an Electron desktop app for macOS and Linux. People work in folder-backed workspaces or in No workspace chats (global settings, with a hidden per-chat folder Aiden manages), use chats and Bots, review files and Git changes, run tools with explicit permissions, and may connect native iOS or Android clients to a paired desktop for remote access. +The primary application is an Electron desktop app for macOS and Linux. People work in folder-backed workspaces or in No workspace chats (global settings, with a hidden per-chat folder Aiden manages), use chats and Bots, review files and Git changes, run tools with explicit permissions, and may connect native iOS or Android clients to a paired desktop for remote access. Copies and forks keep independent private folders and access. ## Capabilities and Constraints diff --git a/README.md b/README.md index c22a769bfa..9438ec3d2f 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ I don't come from a coding background. I'd been bouncing between the coding agen - **Headless server** - `aiden serve` runs Aiden on a macOS or Linux box with no display, such as a server you reach over SSH, for paired phones and Macs: chats, Bots, scheduled tasks and Telegram run there, and it prints a pairing code at startup. `aiden service install` keeps it running across reboots and asks whether phones reach it on the local network, over Tailscale, or both. It is a server with short admin commands, not an interactive terminal app; build it from a clone (see [the server guide](packages/cli/README.md)). It can also enable durable Bot sessions with `aiden bots enable-durable` and a restart; migration preserves legacy conversations and journals in a private recovery backup ([supported capabilities and recovery](docs/cli-durable-bots.md)). - **Workspaces and managed worktrees** - use folders, scratch workspaces, or isolated managed worktrees with three access levels, workspace-scoped tools, Ask-mode approvals, guarded creation/deletion, and crash-aware cleanup. If a workspace's folder is moved, renamed or deleted, Aiden names it above the composer and keeps your message until the folder is back. If a managed worktree's folder is deleted or moved while its branch is still there, the chat offers **Restore worktree** (checks the branch out again in the same place, with its commits; uncommitted changes are gone, so a folder that was only moved or is in the Trash is better put back, then **Check again**) or **New chat in main checkout** (carries your unsent message). - **Inbox sidebar (Beta)** - switch the sidebar from **By workspace** or **Recent only** to **Inbox**, in the sidebar's Organize menu or Settings → Appearance → Sidebar. Chats and Bots that wait on you (an approval, a question, a failed run), on this Mac or a paired one, sit in **Needs you** with how long they've waited; new replies sit in **Updates** with a one-click Mark read; the past week sits in **Earlier**; and running chats collect in a **Working** shelf at the bottom. A row's ••• or right-click menu can **Pin** it to a **Pinned** group, **Mark done** to hide it until something new arrives, or **Snooze** it until later today, tomorrow or next week (an approval, a question, a failed run or your own reply wakes it early); each action shows a short Undo, and a search still finds Done and snoozed chats, with **Mark not done** and **Unsnooze** in their menus. Rows hold still while your pointer or keyboard is in the list, and opening one lands on its pending card. The Dock icon (the launcher icon on Linux) shows how many rows wait in Needs you, counting paired computers only while they're online; turn it off with **Show Needs you count on the Dock icon** (**on the app icon** on Linux) in Settings → Appearance → Sidebar. Also available in Aiden On The Go for iPhone and Android; see the [Inbox sidebar plan](docs/plans/inbox-sidebar-plan.md). -- **Chats without a workspace** - choose **No workspace** to just chat with your global settings. The chat is listed under **Chats** in the sidebar and still runs in its own hidden folder in Aiden's app data, so files, skills and Git work; deleting the chat moves that folder to the Trash. Paired iPhones and Android phones list them the same way and can start one too; see [chats without a workspace](docs/no-workspace-chats.md). +- **Chats without a workspace** - choose **No workspace** to just chat with your global settings. The chat is listed under **Chats** in the sidebar and still runs in its own hidden folder in Aiden's app data, so files, skills and Git work; deleting the chat moves that folder to the Trash. Paired iPhones and Android phones list them the same way and can start one too; see [chats without a workspace](docs/no-workspace-chats.md). Copies and populated forks get a separate empty folder and independent access. - **Models and the Model Pad** - choose from Pi's native hosted-provider catalog, local Ollama or LM Studio models, and declarative compatible endpoints. Arrange a personal capability-and-pace map, optionally enrich hosted models with explicitly fetched Artificial Analysis scores through a benchmark-only OpenRouter key, and keep benchmark evidence visibly separate from runtime limits and availability. Each chat keeps its own model: picking one in a chat that already has messages changes only that chat, while a pick in a new chat sets the model new chats start with. The iOS and Android apps follow the same rule for the Mac they are paired with. - **Usage limits and spending limits** - when a provider's rate limit or plan window turns a reply away before it starts, chats, Bots and routines wait for the reset (up to a longest wait you choose, 6 hours by default), send one test request, then resume one at a time with the same model; a "Waiting for … usage limit · next try at 3:40 PM" row offers **Retry now**. Dollar limits per chat, per Bot per month and per routine run count only pay-as-you-go API keys, and a reached limit offers **Allow $X more**, also from Aiden On The Go. Desktop only; see [usage limits and spending limits](docs/usage-limits-and-spending.md). - **Terminal, Git, and review** - keep a terminal drawer beside the conversation, inspect files and diffs in Environment, edit with dirty-file protection, compare branches, commit or push checked snapshots, and open the workspace in a discovered external editor. diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt index 074ccec70a..fbc11e1f8f 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt @@ -4734,6 +4734,7 @@ class AidenChatTest { model.fork("user-2", AidenChatForkPosition.BEFORE) assertEquals(fork.id, withTimeout(5_000) { model.forkNavigation.first { it != null } }) + assertEquals("private-fork-home", harness.cache.loadChat("instance-fork", fork.id)?.workspaceId) val request = withContext(Dispatchers.IO) { forkRequests.poll(5, TimeUnit.SECONDS) }!! assertEquals("source-r1", request.getHeader("If-Match")) val body = json.parseToJsonElement(request.body.readUtf8()).jsonObject @@ -5152,7 +5153,7 @@ class AidenChatTest { ) private fun forkChat(lineage: AidenChatForkLineage) = AidenChat( - id = "chat-fork", workspaceId = "workspace-fork", title = "Parser review", + id = "chat-fork", workspaceId = "private-fork-home", title = "Parser review", messages = listOf( AidenChatMessage("fork-user-1", AidenChatRole.USER, "Review the parser.", createdAt = Instant.EPOCH), AidenChatMessage("fork-assistant-1", AidenChatRole.ASSISTANT, "Starting.", createdAt = Instant.EPOCH) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 40cfde0690..bfe19073c5 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -470,7 +470,7 @@ Public keys in `info` are their base64url strings. The host uses a fresh ephemer ### Fork (contract revision 21, `chat-fork-v1`, `chat-fork-summary-v1`) -Fork creates a new regular chat in the same workspace from one message of an existing one. The source is never changed. Bot chats are not forked (`404 not_found`). A host that implements forking advertises `chat-fork-v1`; one that can also summarize the rest of the source advertises `chat-fork-summary-v1`. Without a feature its routes answer `404 not_found`. +Fork creates a new regular chat from one message of an existing one. Named workspace chats keep their workspace. A No workspace chat gets a fresh hidden workspace with an empty private folder and independent Ask first access; clients must use the returned chat's workspace ID rather than requiring the source ID. The source is never changed. Bot chats are not forked (`404 not_found`). A host that implements forking advertises `chat-fork-v1`; one that can also summarize the rest of the source advertises `chat-fork-summary-v1`. Without a feature its routes answer `404 not_found`. - `POST /chats/{chatId}/fork` (`chat:write`; requires `If-Match` with the chat revision and an `Idempotency-Key`). The body is `{messageId, position, summary?}`: - `position: "after"` keeps everything through `messageId`, which must be a settled assistant reply. diff --git a/docs/no-workspace-chats.md b/docs/no-workspace-chats.md index a849ef5d61..e90fd78d5b 100644 --- a/docs/no-workspace-chats.md +++ b/docs/no-workspace-chats.md @@ -23,6 +23,10 @@ Each No workspace chat gets its own folder in Aiden's app data, named like a scr The folder is created when the chat is first sent, so a draft you abandon leaves nothing behind. If the folder goes missing (cleared app data, a manual delete), Aiden makes it again, empty, on the next message. The model is told the folder is private to the chat, so it can use it for downloads, clones and scratch files. +Copying a chat or forking from a reply gives the new chat a separate, empty private folder and its own **Ask first** access setting. Conversation history is copied; files and workspace access are not shared. This also applies when copying an older chat from the migrated shared home. Previously created shared copies keep their existing files and access; Aiden does not move or duplicate that existing data automatically. + +A skill selected before the first send is validated in the draft's original workspace, while its one-turn instructions run in the newly assigned private folder. + The chat's header chip reads **No workspace**; its menu can still show the folder in Finder or a file manager. ## Settings, access and memory diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index df97b9a994..0ddee9d34d 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -2336,7 +2336,10 @@ final class AidenChatViewModel { if forkAttempt == attempt { forkAttempt = nil } guard !isRemoved, coordinator.isCurrent(context) else { return nil } let forked = result.chat - guard !forked.isBotChat, forked.workspaceId == source.workspaceId else { + guard !forked.isBotChat, + forked.forkedFrom?.chatId == source.id, + forked.forkedFrom?.messageId == attempt.request.messageId, + forked.forkedFrom?.position == attempt.request.position else { presentedError = String(localized: "Aiden returned a conversation that is unavailable in Workspaces.") coordinator.haptics.play(.error, scope: hapticScope) return nil diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index d4e6f6b9c9..38c88a467b 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -2215,65 +2215,70 @@ final class AidenChatTests: XCTestCase { @MainActor func testEditInForkSeedsTheForkComposerWithThePromptAndItsAttachments() async throws { - let root = FileManager.default.temporaryDirectory.appending(path: "aiden-fork-prefill-\(UUID())") - defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } - let cache = AidenChatCache(root: root) - let draftStore = AidenChatDraftStore(root: root.appending(path: "drafts")) - let attachmentID = "att_\(String(repeating: "F", count: 43))" - let sourceJSON = #"{"id":"chat-progress-lifecycle","workspaceId":"workspace-1","title":"Progress lifecycle","messages":[{"id":"message-u1","role":"user","text":"Review the protocol.","createdAt":"2026-09-14T12:00:00Z"},{"id":"message-a1","role":"assistant","text":"Starting.","createdAt":"2026-09-14T12:00:01Z"},{"id":"message-u2","role":"user","text":"Now check the error codes.","createdAt":"2026-09-14T12:00:02Z"},{"id":"message-a2","role":"assistant","text":"Done.","createdAt":"2026-09-14T12:00:03Z"}],"createdAt":"2026-09-14T12:00:00Z","updatedAt":"2026-09-14T12:00:03Z","revision":"revision-7"}"# - let forkChatJSON = #"{"id":"chat-fork-edit","workspaceId":"workspace-1","title":"Progress lifecycle (fork)","messages":[{"id":"message-f1","role":"user","text":"Review the protocol.","createdAt":"2026-09-14T12:00:00Z"},{"id":"message-f2","role":"assistant","text":"Starting.","createdAt":"2026-09-14T12:00:01Z"}],"createdAt":"2026-09-14T12:05:00Z","updatedAt":"2026-09-14T12:05:00Z","revision":"revision-fork-1","forkedFrom":{"chatId":"chat-progress-lifecycle","messageId":"message-u2","position":"before","at":"2026-09-14T12:05:00Z"}}"# - let forkResultJSON = #"{"chat":\#(forkChatJSON),"prefill":{"text":"Now check the error codes.","attachments":[{"id":"\#(attachmentID)","name":"codes.txt","mimeType":"text/plain","kind":"text","size":42,"expiresAt":"2099-01-01T00:00:00Z"}]}}"# - let serverJSON = #"{"protocolVersion":1,"instanceId":"instance-progress-lifecycle","name":"Progress Lifecycle Mac","appVersion":"1.0","capabilities":["server:read","workspace:read","chat:read","chat:write"],"serverCapabilities":["server:read","workspace:read","chat:read","chat:write"],"features":["chat-fork-v1","chat-fork-summary-v1"],"connectionMode":"lan","serverTime":"2026-09-14T12:00:00Z"}"# - let source = try AidenRemoteJSONDecoder.decode(AidenChat.self, from: Data(sourceJSON.utf8)) - let fixture = AidenStreamRecoveryFixture(chat: source) - var coordinator: AidenRemoteCoordinator! - let model = try await makeProgressLifecycleModel( - mode: .denied, - cache: cache, - draftStore: draftStore, - onCoordinator: { coordinator = $0 }, - initialChat: source, - responseOverride: { request in - switch (request.httpMethod, request.url?.path) { - case (_, "/api/aiden/v1/server"): - return (200, "application/json", Data(serverJSON.utf8)) - case ("POST", "/api/aiden/v1/chats/chat-progress-lifecycle/fork"): - XCTAssertEqual(request.value(forHTTPHeaderField: "If-Match"), "revision-7") - XCTAssertNotNil(request.value(forHTTPHeaderField: "Idempotency-Key")) - return (201, "application/json", Data(forkResultJSON.utf8)) - case ("GET", "/api/aiden/v1/chats/chat-fork-edit"): - return (200, "application/json", Data(forkChatJSON.utf8)) - default: - return fixture.response(request) + for targetWorkspaceID in ["workspace-1", "private-fork-home"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-fork-prefill-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + let cache = AidenChatCache(root: root) + let draftStore = AidenChatDraftStore(root: root.appending(path: "drafts")) + let attachmentID = "att_\(String(repeating: "F", count: 43))" + let sourceJSON = #"{"id":"chat-progress-lifecycle","workspaceId":"workspace-1","title":"Progress lifecycle","messages":[{"id":"message-u1","role":"user","text":"Review the protocol.","createdAt":"2026-09-14T12:00:00Z"},{"id":"message-a1","role":"assistant","text":"Starting.","createdAt":"2026-09-14T12:00:01Z"},{"id":"message-u2","role":"user","text":"Now check the error codes.","createdAt":"2026-09-14T12:00:02Z"},{"id":"message-a2","role":"assistant","text":"Done.","createdAt":"2026-09-14T12:00:03Z"}],"createdAt":"2026-09-14T12:00:00Z","updatedAt":"2026-09-14T12:00:03Z","revision":"revision-7"}"# + let forkChatJSON = #"{"id":"chat-fork-edit","workspaceId":"\#(targetWorkspaceID)","title":"Progress lifecycle (fork)","messages":[{"id":"message-f1","role":"user","text":"Review the protocol.","createdAt":"2026-09-14T12:00:00Z"},{"id":"message-f2","role":"assistant","text":"Starting.","createdAt":"2026-09-14T12:00:01Z"}],"createdAt":"2026-09-14T12:05:00Z","updatedAt":"2026-09-14T12:05:00Z","revision":"revision-fork-1","forkedFrom":{"chatId":"chat-progress-lifecycle","messageId":"message-u2","position":"before","at":"2026-09-14T12:05:00Z"}}"# + let forkResultJSON = #"{"chat":\#(forkChatJSON),"prefill":{"text":"Now check the error codes.","attachments":[{"id":"\#(attachmentID)","name":"codes.txt","mimeType":"text/plain","kind":"text","size":42,"expiresAt":"2099-01-01T00:00:00Z"}]}}"# + let serverJSON = #"{"protocolVersion":1,"instanceId":"instance-progress-lifecycle","name":"Progress Lifecycle Mac","appVersion":"1.0","capabilities":["server:read","workspace:read","chat:read","chat:write"],"serverCapabilities":["server:read","workspace:read","chat:read","chat:write"],"features":["chat-fork-v1","chat-fork-summary-v1"],"connectionMode":"lan","serverTime":"2026-09-14T12:00:00Z"}"# + let source = try AidenRemoteJSONDecoder.decode(AidenChat.self, from: Data(sourceJSON.utf8)) + let fixture = AidenStreamRecoveryFixture(chat: source) + var coordinator: AidenRemoteCoordinator! + let model = try await makeProgressLifecycleModel( + mode: .denied, + cache: cache, + draftStore: draftStore, + onCoordinator: { coordinator = $0 }, + initialChat: source, + responseOverride: { request in + switch (request.httpMethod, request.url?.path) { + case (_, "/api/aiden/v1/server"): + return (200, "application/json", Data(serverJSON.utf8)) + case ("POST", "/api/aiden/v1/chats/chat-progress-lifecycle/fork"): + XCTAssertEqual(request.value(forHTTPHeaderField: "If-Match"), "revision-7") + XCTAssertNotNil(request.value(forHTTPHeaderField: "Idempotency-Key")) + return (201, "application/json", Data(forkResultJSON.utf8)) + case ("GET", "/api/aiden/v1/chats/chat-fork-edit"): + return (200, "application/json", Data(forkChatJSON.utf8)) + default: + return fixture.response(request) + } } - } - ) - - let availability = try XCTUnwrap(model.forkAvailability) - XCTAssertTrue(availability.supportsSummary) - let forked = await model.fork(messageId: "message-u2", action: .editInFork) - XCTAssertNil(model.presentedError) - let fork = try XCTUnwrap(forked) - XCTAssertEqual(fork.id, "chat-fork-edit") - XCTAssertEqual(model.chat.id, "chat-progress-lifecycle", "Forking never rewrites the source chat.") + ) - // Opening the fork restores the edited prompt and its attachments. - let forkModel = AidenChatViewModel( - coordinator: coordinator, - chat: fork, - cache: cache, - draftStore: draftStore, - modelPreferenceStore: testModelPreferences, - onChatUpdated: { _ in } - ) - await forkModel.load(observeProgress: false) - XCTAssertEqual(forkModel.draft, "Now check the error codes.") - XCTAssertEqual(forkModel.pendingAttachments.map(\.id), [attachmentID]) - XCTAssertEqual(forkModel.chat.forkedFrom?.messageId, "message-u2") + let availability = try XCTUnwrap(model.forkAvailability) + XCTAssertTrue(availability.supportsSummary) + let forked = await model.fork(messageId: "message-u2", action: .editInFork) + XCTAssertNil(model.presentedError) + let fork = try XCTUnwrap(forked) + XCTAssertEqual(fork.id, "chat-fork-edit") + XCTAssertEqual(fork.workspaceId, targetWorkspaceID) + let cached = await cache.loadChat(instanceId: "instance-progress-lifecycle", chatId: fork.id) + XCTAssertEqual(cached?.workspaceId, targetWorkspaceID) + XCTAssertEqual(model.chat.id, "chat-progress-lifecycle", "Forking never rewrites the source chat.") + + // Opening the fork restores the edited prompt and its attachments. + let forkModel = AidenChatViewModel( + coordinator: coordinator, + chat: fork, + cache: cache, + draftStore: draftStore, + modelPreferenceStore: testModelPreferences, + onChatUpdated: { _ in } + ) + await forkModel.load(observeProgress: false) + XCTAssertEqual(forkModel.draft, "Now check the error codes.") + XCTAssertEqual(forkModel.pendingAttachments.map(\.id), [attachmentID]) + XCTAssertEqual(forkModel.chat.forkedFrom?.messageId, "message-u2") - // A prompt that is not eligible never reaches the Mac. - let refused = await model.fork(messageId: "message-u1", action: .editInFork) - XCTAssertNil(refused) + // A prompt that is not eligible never reaches the Mac. + let refused = await model.fork(messageId: "message-u1", action: .editInFork) + XCTAssertNil(refused) + } } @MainActor diff --git a/ios/PROJECT_SPEC.md b/ios/PROJECT_SPEC.md index 11b8cbd79a..98f1ad80a3 100644 --- a/ios/PROJECT_SPEC.md +++ b/ios/PROJECT_SPEC.md @@ -21,6 +21,7 @@ Task progress and delegated-agent inspection are separately negotiated, read-onl The complete planned product includes: - Multiple paired Aiden installations with QR or 100-bit setup-code pairing, Keychain credentials, discovery, manual URL entry, switching, and revocation handling. +- No workspace forks follow the returned hidden workspace ID and retain separate private folders and access on the host. - Chat list/open/create/rename/delete, bounded attachments, provider/model/thinking selection, atomic turn start, resumable streaming, cancel, reasoning/tool/timeline status, and allow/deny approvals. - Workspace registry list/create/update/unregister, including folderless, managed scratch, and folders selected through a server-approved desktop directory browser. - Workspace Settings from the conversation toolbar ellipsis. Workspace permission is never a composer control. diff --git a/main/handlers/chats.ts b/main/handlers/chats.ts index a554570188..295632ff39 100644 --- a/main/handlers/chats.ts +++ b/main/handlers/chats.ts @@ -1,3 +1,4 @@ +import { workspaceApplicationService } from "../services/workspace-application-service-main.js"; import { isCompactionEngine } from "../../renderer/shared/compaction.js"; // Chat history CRUD IPC handlers. @@ -127,6 +128,15 @@ export function registerChatHistoryHandlers(): void { }, workspaceExists: async (workspaceId) => Boolean(await configStore.getWorkspace(workspaceId)), resolveSkill: (workspaceId, invocationId) => skillRegistry.resolveFresh(workspaceId, invocationId), + prepareWorkspace: async (workspaceId) => { + const target = await workspaceApplicationService.reserveNoWorkspaceChat(workspaceId); + if (target.workspaceId !== workspaceId) ipcMain.broadcast("workspaces:changed", {}); + return target; + }, + releaseUnusedWorkspace: async (workspaceId) => { + await workspaceApplicationService.releaseNoWorkspaceAfterChat(workspaceId); + ipcMain.broadcast("workspaces:changed", {}); + }, }); const firstMessageWorktrees = createFirstMessageWorktreeCoordinator({ ledger: createFileFirstMessageWorktreeLedger({ diff --git a/main/services/aiden-remote-chats.ts b/main/services/aiden-remote-chats.ts index e85ee74b59..6d3889967e 100644 --- a/main/services/aiden-remote-chats.ts +++ b/main/services/aiden-remote-chats.ts @@ -1,3 +1,4 @@ +import type { WorkspaceChatAssignment } from "./workspace-application-service.js"; import { agentNoticeDisplayText, parseAgentNoticeV1 } from "../../renderer/shared/agent-notices.js"; import { parseAppControlPanels, REMOTE_APP_CONTROL_TOPICS } from "../../renderer/shared/app-controls.js"; import { @@ -1437,7 +1438,7 @@ export class AidenRemoteChatService { * workspaces are used as requested. */ noWorkspace?: { - target(workspaceId: string): Promise; + target(workspaceId: string): Promise; release(workspaceId: string): Promise; }; /** The Mac's Settings → Appearance inline visuals choice for remote turns. */ @@ -2134,18 +2135,29 @@ export class AidenRemoteChatService { const created = await this.assigningNoWorkspace(async () => { // Only a phone that knows the Chats group (revision 51) asks for a folder of its own; // an older phone keeps the workspace it named, as it always has. - const workspaceId = parsed.noWorkspace - ? ((await this.options.noWorkspace?.target(parsed.workspaceId)) ?? parsed.workspaceId) - : parsed.workspaceId; - return this.options.application.create( - { - workspaceId, - ...(selection - ? { providerId: selection.providerId, model: selection.modelId } - : {}), - }, - owner, - ); + const target = parsed.noWorkspace ? await this.options.noWorkspace?.target(parsed.workspaceId) : undefined; + const assignment = typeof target === "object" ? target : undefined; + const workspaceId = assignment?.workspaceId ?? (typeof target === "string" ? target : parsed.workspaceId); + let uncertain = false; + try { + return await this.options.application.create( + { + workspaceId, + ...(selection + ? { providerId: selection.providerId, model: selection.modelId } + : {}), + }, + owner, + ); + } catch (error) { + uncertain = isChatCreateReconciliationRequiredError(error); + if (!uncertain && workspaceId !== parsed.workspaceId) { + await this.options.noWorkspace?.release(workspaceId).catch(() => undefined); + } + throw error; + } finally { + if (!uncertain) assignment?.release(); + } }); if (!created) throw new AidenRemoteServiceError("internal_error", "Aiden could not create the chat.", 500); this.options.notifyChanged?.(created.id); diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index 2ceee93d82..bdffe2c84b 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -645,8 +645,8 @@ async function createRuntime(): Promise { // The desktop's sidebar lists a chat only once it knows the chat's workspace, so a // hidden record made or removed here is announced like any other workspace change. target: async (workspaceId) => { - const target = await workspaceApplicationService.workspaceForNoWorkspaceChat(workspaceId); - if (target !== workspaceId) ipcMain.broadcast("workspaces:changed", {}); + const target = await workspaceApplicationService.reserveNoWorkspaceChat(workspaceId); + if (target.workspaceId !== workspaceId) ipcMain.broadcast("workspaces:changed", {}); return target; }, release: async (workspaceId) => { diff --git a/main/services/chat-first-message-commit.test.ts b/main/services/chat-first-message-commit.test.ts index 0233d8eb96..6930e1e2d2 100644 --- a/main/services/chat-first-message-commit.test.ts +++ b/main/services/chat-first-message-commit.test.ts @@ -11,6 +11,7 @@ import { ChatTurnAdmission, type ChatTurnAdmissionOptions } from "./chat-turn-ad import { WorkspaceOperationRegistry, admitOwnedWorkspaceOperation } from "./workspace-operation-registry.js"; import { isAppendReconciliationRequiredError } from "./chat-append-commit.js"; import { chatForRenderer } from "./visible-chat-projection.js"; +import { SkillRegistry } from "./skill-registry.js"; import type { RegisteredSkill } from "./skill-registry.js"; let nextTurn = 0; @@ -244,7 +245,16 @@ test("payload failure keeps draft retryable; index uncertainty blocks retry and }); const input = parseChatFirstMessage(request()); let failure: unknown; - try { await createFirstMessageCommitter(f.deps)(input, f.owner); } catch (error) { failure = error; } + let assignmentReleased = false; + const removed: string[] = []; + const commit = createFirstMessageCommitter({ + ...f.deps, + prepareWorkspace: async () => ({ workspaceId: "private-target", release: () => { assignmentReleased = true; } }), + releaseUnusedWorkspace: async (id) => { removed.push(id); }, + }); + try { await commit(input, f.owner); } catch (error) { failure = error; } + assert.equal(assignmentReleased, phase === "chat-write", "an uncertain target stays reserved until reconciliation"); + assert.deepEqual(removed, phase === "chat-write" ? ["private-target"] : []); assert.ok(failure); assert.equal(isAppendReconciliationRequiredError(failure), phase === "index-write"); assert.equal(f.turns.requiresAppendReconciliation(f.owner.documentId), phase === "index-write"); @@ -254,3 +264,38 @@ test("payload failure keeps draft retryable; index uncertainty blocks retry and assert.equal((await restart.list()).length, phase === "index-write" ? 1 : 0); } }); + +test("private first send keeps its selected skill authoritative through folder allocation and replay", async (t) => { + const f = await fixture(t); + const registry = new SkillRegistry({ + getWorkspace: async (id) => ({ id, name: id, folderPath: `/private/${id}`, permission: "ask", noWorkspace: true, createdAt: 1, updatedAt: 1 }), + listConfigured: async () => [{ id: "review", name: "Review", description: "Review changes", instructions: "Look for incorrect behavior.", enabled: true }], + discover: async () => [], + }); + const [skill] = (await registry.catalog("workspace")); + let allocated = 0; + const commit = createFirstMessageCommitter({ + ...f.deps, + prepareWorkspace: async () => ({ workspaceId: `private-${++allocated}`, release: () => undefined }), + resolveSkill: (id, invocationId) => registry.resolveFresh(id, invocationId), + }); + const parsed = parseChatFirstMessage(request({ + skillInvocation: { version: 1, invocationId: skill!.invocationId, displayName: "Review", source: "configured" }, + })); + const chat = await commit(parsed, f.owner); + assert.equal(chat.workspaceId, "private-1"); + assert.equal(chat.messages[0]?.skill?.name, "Review"); + let preparedWorkspace: string | undefined; + let preparedPrompt: string | undefined; + assert.equal(f.turns.handoff(chat.id, parsed.turnId, f.owner.documentId, (prepared) => { + preparedWorkspace = prepared?.workspaceId; + preparedPrompt = prepared?.formattedPrompt; + }), true); + assert.equal(preparedWorkspace, chat.workspaceId); + assert.ok(preparedPrompt?.includes("Look for incorrect behavior.")); + f.turns.releaseMatching(chat.id, parsed.turnId, f.owner.documentId); + const replay = await commit(parsed, f.owner); + assert.equal(replay.id, chat.id); + assert.equal(replay.workspaceId, "private-1"); + assert.equal(allocated, 1, "a replay never allocates another folder"); +}); diff --git a/main/services/chat-first-message-commit.ts b/main/services/chat-first-message-commit.ts index 5704df7f0b..269e25c169 100644 --- a/main/services/chat-first-message-commit.ts +++ b/main/services/chat-first-message-commit.ts @@ -1,3 +1,4 @@ +import type { WorkspaceChatAssignment } from "./workspace-application-service.js"; import { createHash, randomUUID } from "node:crypto"; import type { ParsedChatFirstMessage } from "../handlers/chat-first-message-params.js"; import type { Chat } from "./types.js"; @@ -32,6 +33,9 @@ interface Dependencies { clearReconciliation(ownerId: string): void; admitWorkspace(workspaceId: string, owner: Owner): WorkspaceOperationAdmission; workspaceExists(workspaceId: string): Promise; + /** Main-owned assignment of a private No workspace folder before the first commit. */ + prepareWorkspace?(sourceWorkspaceId: string): Promise; + releaseUnusedWorkspace?(workspaceId: string): Promise; resolveSkill(workspaceId: string, invocationId: string): Promise; } @@ -75,12 +79,15 @@ export function createFirstMessageCommitter(deps: Dependencies) { entry.promise = (async () => { let committed = false; let workSettled = false; - let workspace: WorkspaceOperationAdmission | undefined; - try { - workspace = deps.admitWorkspace(input.workspaceId, owner); - const admittedWorkspace = workspace; + const workspaces: WorkspaceOperationAdmission[] = []; + let workspaceId = input.workspaceId; + let preserveWorkspace = false; + let assignment: WorkspaceChatAssignment | undefined; + const admit = (id: string) => { + const admittedWorkspace = deps.admitWorkspace(id, owner); + workspaces.push(admittedWorkspace); const abortTurn = () => turn.release(); - workspace.signal.addEventListener("abort", abortTurn, { once: true }); + admittedWorkspace.signal.addEventListener("abort", abortTurn, { once: true }); turn.onReleased(() => { admittedWorkspace.signal.removeEventListener("abort", abortTurn); // Revocation must drain an in-flight store write before the owning @@ -90,8 +97,11 @@ export function createFirstMessageCommitter(deps: Dependencies) { turn.settleAsyncWork(); } }); - if (workspace.signal.aborted) abortTurn(); - const isCurrent = () => turn.isActive() && !owner.isDestroyed() && !workspace!.signal.aborted; + if (admittedWorkspace.signal.aborted) abortTurn(); + }; + try { + admit(input.workspaceId); + const isCurrent = () => turn.isActive() && !owner.isDestroyed() && workspaces.every((workspace) => !workspace.signal.aborted); const assertCurrent = () => { if (!isCurrent()) throw new Error("The workspace or message turn changed before the chat could be saved."); if (deps.requiresReconciliation(owner.documentId)) { @@ -113,11 +123,15 @@ export function createFirstMessageCommitter(deps: Dependencies) { throw new Error("The selected workspace is no longer available."); } assertCurrent(); + assignment = await deps.prepareWorkspace?.(input.workspaceId); + workspaceId = assignment?.workspaceId ?? input.workspaceId; + if (workspaceId !== input.workspaceId) admit(workspaceId); + assertCurrent(); const userMessageId = randomUUID(); const append = (prepared?: { provenance: SkillProvenanceV1 }) => deps.store.createWithFirstMessage({ id: input.chatId, title: input.title, - workspaceId: input.workspaceId, + workspaceId, providerId: input.providerId, model: input.metaModel, turnId: input.turnId, @@ -137,13 +151,13 @@ export function createFirstMessageCommitter(deps: Dependencies) { role: "user", content: input.content, attachments: input.attachments, - workspaceId: input.workspaceId, + workspaceId, userMessageId, }, { - // A first send in a new worktree carries a skill chosen (and - // bound) in the draft's source workspace; resolve it there. - resolveFresh: (workspaceId, invocationId) => - deps.resolveSkill(input.skillWorkspaceId ?? workspaceId, invocationId), + // Skills remain bound to the workspace where the person selected + // them; the prepared turn belongs to the new private folder/worktree. + resolveFresh: (_workspaceId, invocationId) => + deps.resolveSkill(input.skillWorkspaceId ?? input.workspaceId, invocationId), isCurrent, prepareLease: (prepared) => turn.prepareSkillInvocation(prepared), append, @@ -153,6 +167,7 @@ export function createFirstMessageCommitter(deps: Dependencies) { return chat; } catch (error) { if (isChatCreateReconciliationRequiredError(error)) { + preserveWorkspace = true; deps.markReconciliation(owner.documentId); owner.onInvalidated(() => deps.clearReconciliation(owner.documentId)); throw new AppendReconciliationRequiredError(); @@ -161,7 +176,12 @@ export function createFirstMessageCommitter(deps: Dependencies) { } finally { workSettled = true; if (!committed) turn.release(); - if (!turn.isActive()) workspace?.release(); + if (!turn.isActive()) for (const workspace of workspaces) workspace.release(); + if (!committed && !preserveWorkspace && workspaceId !== input.workspaceId) { + // The release implementation checks for a durable owner before removal. + await deps.releaseUnusedWorkspace?.(workspaceId).catch(() => undefined); + } + if (!preserveWorkspace) assignment?.release(); // A successful receipt remains in pending until handoff/abandon/expiry. // Keep its payload capacity reserved for exactly that same lifetime. turn.settleAsyncWork({ retainAppendPayloadUntilRelease: committed && turn.isActive() }); diff --git a/main/services/chat-fork-service-main.ts b/main/services/chat-fork-service-main.ts index 44423be94e..6f2d8ae726 100644 --- a/main/services/chat-fork-service-main.ts +++ b/main/services/chat-fork-service-main.ts @@ -2,6 +2,7 @@ import { ipcMain } from "../platform.js"; import { persistedChatWorkspaceId } from "../../renderer/shared/chat-workspace.js"; import { createChatForkService } from "./chat-fork-service.js"; import { chatStore } from "./chat-store.js"; +import { workspaceApplicationService } from "./workspace-application-service-main.js"; import { configStore } from "./config-store.js"; import { writeDiagnosticEvent } from "./diagnostic-journal.js"; import { forkSummaryService } from "./fork-summary-service-main.js"; @@ -15,6 +16,15 @@ export const chatForkService = createChatForkService({ chatStore, beginChatCopy: (chatId) => llmClient.beginChatCopy(chatId), workspaceExists: async (workspaceId) => Boolean(await configStore.getWorkspace(workspaceId)), + prepareWorkspace: async (workspaceId) => { + const target = await workspaceApplicationService.reserveNoWorkspaceChat(workspaceId); + if (target.workspaceId !== workspaceId) ipcMain.broadcast("workspaces:changed", {}); + return target; + }, + releaseUnusedWorkspace: async (workspaceId) => { + await workspaceApplicationService.releaseNoWorkspaceAfterChat(workspaceId); + ipcMain.broadcast("workspaces:changed", {}); + }, blockedReason: async (chatId) => { const unresolved = await unresolvedGuiArtifactMessage(chatId); return unresolved diff --git a/main/services/chat-fork-service.test.ts b/main/services/chat-fork-service.test.ts index def2a9ba6a..58626353d4 100644 --- a/main/services/chat-fork-service.test.ts +++ b/main/services/chat-fork-service.test.ts @@ -10,7 +10,9 @@ import { type ChatForkServiceDependencies, } from "./chat-fork-service.js"; import { createChatStore } from "./chat-store-core.js"; -import type { Chat } from "./types.js"; +import type { Chat, Workspace } from "./types.js"; +import { createWorkspaceApplicationService, type WorkspaceApplicationDependencies } from "./workspace-application-service.js"; +import { WorkspaceMutationGate } from "./workspace-mutation-gate.js"; async function fixture(t: TestContext) { const directory = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-fork-service-")); @@ -312,3 +314,96 @@ test("feature-owned chats are ineligible for copy and fork", async (t) => { assert.deepEqual(published, []); assert.equal((await store.list()).length, 1); }); + +async function privateForkWorkspaces(t: TestContext, store: ReturnType, hidden = true) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-private-fork-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const originalFolder = path.join(root, "original"); + await fs.mkdir(originalFolder); + await fs.writeFile(path.join(originalFolder, "private.txt"), "source-only content"); + const records = new Map([["workspace-fork", { + id: "workspace-fork", name: "Source", folderPath: originalFolder, permission: "none", + ...(hidden ? { noWorkspace: true as const } : {}), createdAt: 1, updatedAt: 1, + }]]); + let next = 0; + const application = createWorkspaceApplicationService({ + configStore: { + listWorkspaces: async () => [...records.values()], + getWorkspace: async (id) => records.get(id), + saveWorkspace: async (workspace) => { records.set(workspace.id, workspace); return workspace; }, + removeWorkspace: async (id) => { records.delete(id); }, + }, + llmClient: { cancelWorkspaceAndSettle: async () => undefined }, + scheduleService: { cancelWorkspace: async () => undefined, resumeWorkspace: async () => undefined }, + terminalService: { closeForWorkspace: () => undefined }, + workspaceMutationGate: new WorkspaceMutationGate(), + workspaceOperationRegistry: { cancelAndSettle: async () => undefined }, + noWorkspace: { + createDirectory: async () => { const folderPath = path.join(root, `fresh-${next + 1}`); await fs.mkdir(folderPath); return { folderPath }; }, + chatIdsIn: async (id) => (await store.list(id)).map((chat) => chat.id), + workspaceIdsWithChats: async () => new Set((await store.list()).map((chat) => chat.workspaceId!)), + trash: async (folder) => { await fs.rm(folder, { recursive: true }); }, + }, + createScratchWorkspaceDirectory: async () => { throw new Error("Scratch creation is outside this fixture."); }, + realpath: (folder) => fs.realpath(folder), + stat: (folder) => fs.stat(folder), + removeEmptyDirectory: (folder) => fs.rmdir(folder), + createId: () => `hidden-${++next}`, + now: () => 1, + logError: () => undefined, + } satisfies WorkspaceApplicationDependencies); + return { application, records, originalFolder }; +} + +test("No workspace copy and populated forks isolate files and access, without changing the source", async (t) => { + const { store, source, ids } = await fixture(t); + const { application, records, originalFolder } = await privateForkWorkspaces(t, store); + const forks = service(store, { + prepareWorkspace: (id) => application.reserveNoWorkspaceChat(id), + releaseUnusedWorkspace: (id) => application.releaseNoWorkspaceAfterChat(id), + }); + const copies = [ + await forks.fork({ chatId: source.id }, caller), + await forks.fork({ chatId: source.id, forkAt: { messageId: ids.firstReply, position: "after" } }, caller), + await forks.fork({ chatId: source.id, forkAt: { messageId: ids.secondPrompt, position: "before" } }, caller), + ]; + assert.equal(new Set([source.workspaceId, ...copies.map((chat) => chat.workspaceId)]).size, 4); + for (const copy of copies) { + const target = records.get(copy.workspaceId!)!; + assert.equal(target.noWorkspace, true); + assert.notEqual(target.folderPath, originalFolder); + assert.deepEqual(await fs.readdir(target.folderPath!), []); + await application.update(target.id, { permission: "full" }); + await fs.writeFile(path.join(target.folderPath!, "fork.txt"), "fork only"); + } + assert.equal(records.get(source.workspaceId!)?.permission, "none"); + assert.deepEqual(await fs.readdir(originalFolder), ["private.txt"]); + assert.equal((await store.get(source.id))?.messages.length, 4); +}); + +test("named-workspace forks retain their folder and access", async (t) => { + const { store, source, ids } = await fixture(t); + const { application, records } = await privateForkWorkspaces(t, store, false); + const copied = await service(store, { + prepareWorkspace: (id) => application.reserveNoWorkspaceChat(id), + }).fork({ chatId: source.id, forkAt: { messageId: ids.firstReply, position: "after" } }, caller); + assert.equal(copied.workspaceId, source.workspaceId); + assert.equal(records.size, 1); + assert.equal(records.get(copied.workspaceId!)?.permission, "none"); +}); + +test("a refused private fork releases its unused folder, but a committed one survives cleanup", async (t) => { + const { store, source } = await fixture(t); + const { application, records } = await privateForkWorkspaces(t, store); + const forks = service(store, { + prepareWorkspace: (id) => application.reserveNoWorkspaceChat(id), + releaseUnusedWorkspace: (id) => application.releaseNoWorkspaceAfterChat(id), + }); + await assert.rejects(forks.fork({ chatId: source.id }, { + ...caller, assertInstallable: () => { throw new Error("owner revoked"); }, + }), /owner revoked/u); + assert.equal(records.size, 1); + const copy = await forks.fork({ chatId: source.id }, caller); + await application.releaseNoWorkspaceAfterChat(copy.workspaceId!); + assert.equal(records.has(copy.workspaceId!), true); +}); diff --git a/main/services/chat-fork-service.ts b/main/services/chat-fork-service.ts index f61cd38f9a..26f40e4e6b 100644 --- a/main/services/chat-fork-service.ts +++ b/main/services/chat-fork-service.ts @@ -1,3 +1,4 @@ +import type { WorkspaceChatAssignment } from "./workspace-application-service.js"; import { randomUUID } from "node:crypto"; import { ASSISTANT_WORKSPACE_ID } from "../../renderer/shared/assistant.js"; import type { ChatHtmlArtifactV1 } from "../../renderer/shared/chat-artifacts.js"; @@ -64,6 +65,10 @@ export interface ChatForkServiceDependencies { /** Hold the source still for the copy; null while it is busy. */ beginChatCopy(chatId: string): (() => void) | null; workspaceExists(workspaceId: string): Promise; + /** A fresh hidden home for No workspace copies; named workspaces keep their id. */ + prepareWorkspace?(sourceWorkspaceId: string): Promise; + /** Release only an unowned hidden home; never discard a possibly committed copy. */ + releaseUnusedWorkspace?(workspaceId: string): Promise; /** Why the chat cannot be copied yet, such as an unrecovered visual artifact. */ blockedReason?(chatId: string): Promise; htmlArtifacts?: ChatForkHtmlArtifacts; @@ -145,9 +150,14 @@ export function createChatForkService(deps: ChatForkServiceDependencies) { ); } const admission = caller.admitWorkspace(workspaceId); + let targetWorkspaceId = workspaceId; + let targetAdmission: ChatForkWorkspaceAdmission | undefined; + let preserveTarget = false; + let uncertain = false; + let assignment: WorkspaceChatAssignment | undefined; try { const assertCurrent = () => { - if (admission.isAborted()) { + if (admission.isAborted() || targetAdmission?.isAborted()) { throw new ChatForkError("busy", "The workspace changed before the chat was copied."); } caller.assertCurrent?.(); @@ -155,11 +165,29 @@ export function createChatForkService(deps: ChatForkServiceDependencies) { if (!(await deps.workspaceExists(workspaceId))) { throw new ChatForkError("unavailable", "The chat workspace is no longer available."); } - const copied = await copyRegular(source, workspaceId, request, caller, assertCurrent); + assertCurrent(); + assignment = await deps.prepareWorkspace?.(workspaceId); + targetWorkspaceId = assignment?.workspaceId ?? workspaceId; + if (targetWorkspaceId !== workspaceId) targetAdmission = caller.admitWorkspace(targetWorkspaceId); + assertCurrent(); + const copied = await copyRegular(source, workspaceId, targetWorkspaceId, request, caller, assertCurrent); + preserveTarget = true; deps.published?.(copied); return copied; + } catch (error) { + // The target may be durable even though its index could not be reconciled. + if (isChatCreateReconciliationRequiredError(error)) { + preserveTarget = true; + uncertain = true; + } + throw error; } finally { + targetAdmission?.release(); admission.release(); + if (!preserveTarget && targetWorkspaceId !== workspaceId) { + await deps.releaseUnusedWorkspace?.(targetWorkspaceId).catch((error: unknown) => deps.reportDegraded?.(error)); + } + if (!uncertain) assignment?.release(); } } finally { finishCopy?.(); @@ -171,6 +199,7 @@ export function createChatForkService(deps: ChatForkServiceDependencies) { async function copyRegular( source: Chat, workspaceId: string, + targetWorkspaceId: string, request: ChatForkRequest, caller: ChatForkCaller, assertCurrent: () => void, @@ -184,6 +213,7 @@ export function createChatForkService(deps: ChatForkServiceDependencies) { sourceChatId: request.chatId, targetChatId, expectedWorkspaceId: workspaceId, + targetWorkspaceId, forkAt: request.forkAt, ...(request.summary ? { forkSummary: request.summary } : {}), assertCurrent, diff --git a/main/services/workspace-application-service.test.ts b/main/services/workspace-application-service.test.ts index c7d7ea77a9..d84c5ebe93 100644 --- a/main/services/workspace-application-service.test.ts +++ b/main/services/workspace-application-service.test.ts @@ -464,20 +464,39 @@ test("a paired device's chat in a No workspace folder that holds another chat ge workspace({ id: "default", name: "No workspace", folderPath: "/data/chat-folders/home", noWorkspace: true }), workspace({ id: "project", folderPath: "/code/project" }), ]); - assert.equal(await app.service.workspaceForNoWorkspaceChat("default"), "default", "an unused hidden folder is used"); + const first = await app.service.reserveNoWorkspaceChat("default"); + assert.equal(first.workspaceId, "default", "an unused hidden folder is used"); + first.release(); assert.equal(app.registry.size, 2); app.chatsIn.set("default", ["older"]); - const fresh = await app.service.workspaceForNoWorkspaceChat("default"); + const fresh = (await app.service.reserveNoWorkspaceChat("default")).workspaceId; assert.notEqual(fresh, "default"); assert.equal(app.registry.get(fresh)?.noWorkspace, true); app.chatsIn.set("project", ["a", "b"]); - assert.equal(await app.service.workspaceForNoWorkspaceChat("project"), "project", "a real workspace is shared"); + assert.equal((await app.service.reserveNoWorkspaceChat("project")).workspaceId, "project", "a real workspace is shared"); // A phone still aims at a hidden home that was released with its last chat. - const replacement = await app.service.workspaceForNoWorkspaceChat("released-home"); + const replacement = (await app.service.reserveNoWorkspaceChat("released-home")).workspaceId; assert.notEqual(replacement, "released-home"); assert.equal(app.registry.get(replacement)?.noWorkspace, true, "a gone home gets a fresh hidden folder"); assert.equal(app.registry.has("released-home"), false); }); + +test("private workspace assignment excludes concurrent drafts and forks until commit settles", async (t) => { + const app = await noWorkspaceFixture(t, [workspace({ id: "home", folderPath: "/data/chat-folders/home", noWorkspace: true, permission: "none" })]); + const [first, second] = await Promise.all([ + app.service.reserveNoWorkspaceChat("home"), app.service.reserveNoWorkspaceChat("home"), + ]); + assert.equal(first.workspaceId, "home"); + assert.notEqual(second.workspaceId, first.workspaceId); + assert.equal(app.registry.get(first.workspaceId)?.permission, "none", "chosen draft access stays on its unused home"); + // A newly published private target is not free while its owning copy prepares. + const third = await app.service.reserveNoWorkspaceChat(second.workspaceId); + assert.notEqual(third.workspaceId, second.workspaceId); + first.release(); second.release(); third.release(); + const retried = await app.service.reserveNoWorkspaceChat("home"); + assert.equal(retried.workspaceId, "home", "a failed uncommitted claim becomes reusable"); + retried.release(); +}); diff --git a/main/services/workspace-application-service.ts b/main/services/workspace-application-service.ts index 8a8f411ae0..27c3954ce2 100644 --- a/main/services/workspace-application-service.ts +++ b/main/services/workspace-application-service.ts @@ -73,6 +73,12 @@ export interface WorkspaceApplicationDependencies { logError(area: string, message: string, error: unknown): void; } +/** A private folder cannot be assigned to another chat until this operation settles. */ +export interface WorkspaceChatAssignment { + workspaceId: string; + release(): void; +} + export interface WorkspaceApplicationMutationOptions { assertCurrent?: (workspace: Workspace) => void; beforeSave?: (workspace: Workspace | undefined) => void | Promise; @@ -88,6 +94,8 @@ export interface WorkspaceFolderCreationOptions { export function createWorkspaceApplicationService(deps: WorkspaceApplicationDependencies) { let folderCreationTail: Promise = Promise.resolve(); + let assignmentTail: Promise = Promise.resolve(); + const assignedPrivateWorkspaces = new Set(); const serializeFolderCreation = (operation: () => Promise): Promise => { const result = folderCreationTail.then(operation, operation); @@ -295,15 +303,34 @@ export function createWorkspaceApplicationService(deps: WorkspaceApplicationDepe * A hidden record that is gone (its last chat was deleted, so it was * released) also gets a fresh one: the device asked for No workspace and * still lists the old record as the group's home. Returns the workspace - * to use; any other workspace is unchanged. + * to use; any other workspace is unchanged. Hold the reservation through + * commit and failure cleanup, then release it. Unknown outcomes stay held + * until restart reconciles the chat store. */ - async workspaceForNoWorkspaceChat(workspaceId: string) { - if (!deps.noWorkspace) return workspaceId; - const workspace = await deps.configStore.getWorkspace(workspaceId); - if (!workspace) return (await service.createNoWorkspace()).id; - if (!workspace.noWorkspace) return workspaceId; - if ((await deps.noWorkspace.chatIdsIn(workspaceId)).length === 0) return workspaceId; - return (await service.createNoWorkspace()).id; + reserveNoWorkspaceChat(workspaceId: string): Promise { + const reserve = async (): Promise => { + const workspace = await deps.configStore.getWorkspace(workspaceId); + if (!deps.noWorkspace || (workspace && !workspace.noWorkspace)) { + return { workspaceId, release: () => undefined }; + } + const available = workspace && !assignedPrivateWorkspaces.has(workspaceId) && + (await deps.noWorkspace.chatIdsIn(workspaceId)).length === 0; + const target = available ? workspaceId : (await service.createNoWorkspace()).id; + assignedPrivateWorkspaces.add(target); + let released = false; + return { + workspaceId: target, + release: () => { + if (released) return; + released = true; + assignedPrivateWorkspaces.delete(target); + }, + }; + }; + // Separate from folder creation: reservation may need to create a folder. + const result = assignmentTail.then(reserve, reserve); + assignmentTail = result.catch(() => undefined); + return result; }, /** After a chat is deleted: its hidden No workspace folder goes too once no chat uses it. */ diff --git a/renderer/main/chat-pane.tsx b/renderer/main/chat-pane.tsx index 37fb3e2748..d90003a3d0 100644 --- a/renderer/main/chat-pane.tsx +++ b/renderer/main/chat-pane.tsx @@ -1223,6 +1223,9 @@ export function ChatPane({ chatId }: { chatId: string }) { seedComposerAttachments(copied.id, prefill.attachments); } const copiedWorkspaceId = persistedChatWorkspaceId(copied.workspaceId); + if (copiedWorkspaceId !== effectiveWorkspaceIdRef.current) { + await qc.invalidateQueries({ queryKey: queryKeys.workspaces }); + } qc.setQueryData(queryKeys.chat(copied.id), copied); qc.setQueryData(queryKeys.chatsIn(copiedWorkspaceId), (current) => [ { @@ -2048,24 +2051,12 @@ export function ChatPane({ chatId }: { chatId: string }) { setIsStartingGeneration(true); try { let updated: Chat; - /** Set when this No workspace draft is saved in a fresh hidden folder. */ - let separateNoWorkspaceId: string | undefined; try { - if (firstDraft && !worktreeRequest) { - const draftWorkspace = workspaces.find((entry) => entry.id === firstDraft.chat.workspaceId); - if (isNoWorkspace(draftWorkspace)) { - separateNoWorkspaceId = await noWorkspaceFolderForFirstSend( - { listChats: chatsApi.list, createNoWorkspace: workspacesApi.createNoWorkspace }, - draftWorkspace!.id, - ); - if (separateNoWorkspaceId) await qc.invalidateQueries({ queryKey: queryKeys.workspaces }); - } - } const firstMessageInput = firstDraft ? { draftId: chatId, title: firstDraft.chat.title === "New agent" ? undefined : firstDraft.chat.title, - workspaceId: separateNoWorkspaceId ?? firstDraft.chat.workspaceId!, + workspaceId: firstDraft.chat.workspaceId!, providerId, model, turnId: messageTurnId, @@ -2183,7 +2174,7 @@ export function ChatPane({ chatId }: { chatId: string }) { // A New worktree send saved the chat in the worktree's workspace, // which this render has not seen yet. // A No workspace draft that needed its own folder was saved in a fresh one. - if (worktreeRequest || separateNoWorkspaceId) effectiveWorkspaceIdRef.current = updated.workspaceId; + if (firstDraft) effectiveWorkspaceIdRef.current = updated.workspaceId; void runGeneration(messageTurnId).then((started) => { if (!started.ok && mountedRef.current && chatIdRef.current === chatId) { setError(started.error.message); @@ -2211,7 +2202,6 @@ export function ChatPane({ chatId }: { chatId: string }) { model, qc, runGeneration, - workspaces, ], ); From d84cbc275704164b5d6a1a72c055e587401f677d Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 2 Nov 2026 20:21:05 -0500 Subject: [PATCH 2/2] Avoid workspace singleton startup cycle and verify chat flows in Electron --- .memory/workspace-isolation-backlog.md | 12 +++++ main/handlers/chats.ts | 4 +- main/services/chat-fork-service-main.ts | 4 +- tests/e2e/chat-fork.spec.ts | 64 ++++++++++++++++++++++++- tests/e2e/no-workspace-chat.spec.ts | 57 ++++++++++++++++++++++ 5 files changed, 138 insertions(+), 3 deletions(-) diff --git a/.memory/workspace-isolation-backlog.md b/.memory/workspace-isolation-backlog.md index 756679fa9e..49d11a11e9 100644 --- a/.memory/workspace-isolation-backlog.md +++ b/.memory/workspace-isolation-backlog.md @@ -9,3 +9,15 @@ The shared fork service now assigns a fresh hidden workspace through the existin Desktop private first-send allocation now happens inside the main-owned first-message committer after durable-receipt replay checks. Its fingerprint keeps the submitted source identity; skill resolution keeps the original selection authority while the prepared turn and persisted chat own the destination. Both workspace admissions cancel/drain preparation. No Remote wire change or runtime network fetch was added. Focused source tests reproduce the original folder sharing and cover file/access isolation, named-workspace sharing, refusal cleanup, skill handoff and replay. Native fork tests exercise returned private workspace IDs. Validation and PR details are recorded in the working chat. + +## PR #714 integration follow-up + +The original published head `c8295f11ba1856ca9b3ab0f5f182260a8f0ad465` fails ordinary Electron startup IPC: after real onboarding, `chats:create` throws while reading `requiresAppendReconciliation` from an undefined `llmClient`. This reproduces Linux CI job 125629914575 (run 41548473303), independently of the separate UUID/privacy-filter issue owned by PR #718. A real registered-IPC control was added to the existing No workspace E2E suite; no production correction has yet been made at this checkpoint. + +Current investigation compares that head, main `c975f6e77760d183e4fa548785ffde49423b5cb5`, and #714 merged with that main (`b22394caefda87835558cd52a1fb253ddb8a40f2`). Main was merged normally, retaining Remote revision 53 and the complete package test chain. Keep #714 and #716 open, preserve their branches, and leave hosted CI management to the coordinating chat. Do not implement the #718 privacy correction here; its reviewed branch may be merged as an explicit dependency for validation if needed. + +The real create/read startup control passes on main, and the initialization failure persists on the merged #714 head. Resolving the workspace service lazily inside the new first-send/fork callbacks fixes the failure; those callbacks keep the same reservation/cleanup behavior. Before introducing any privacy dependency, the startup control, ordinary No workspace second send, and Workspace settings follow-up send all passed in Cua Space with zero retries. + +The reviewed #718 head `c5d372c3fbacc1120b9966c88423f22a6d2d309b` was merged normally as an explicit dependency, preserving its owner-bound read implementation; the only textual conflict combined two imports. Integrated validation passes 196 focused tests, root/E2E TypeScript, scoped ESLint and React Doctor, plus two iOS fork tests on iOS 26.5 and two Android fork tests. Rendered coverage verifies new private fork/copy folders, independent access, source-file isolation and follow-up sends. Final rendered-suite evidence and exact published head belong in PR #714; the coordinating chat owns hosted exact-head CI. + +Final local rendered coverage: 48 distinct Electron cases pass with zero retries, including 32 of the 33 cases that failed in the original Linux job. The selected-skill test initially inspected the automatic title request; after correcting its request assertion, its focused run passes. One worktree lifecycle case cannot reach its assertions in the gVisor Cua Space: `statfs` reports about 8 EiB free (`availableBytes=9223372034644681000`, not a safe integer), so the unchanged capacity guard refuses `git:createWorktree`. The exact same case fails with the same capacity error on unchanged main `c975f6e77760d183e4fa548785ffde49423b5cb5`. Preserve that gap for hosted Linux x64/macOS validation; do not bypass the capacity guard or weaken tests. PR #716 remains untouched at `f6710cb9bb93eced7a198b47805a665efb6f8a79`. diff --git a/main/handlers/chats.ts b/main/handlers/chats.ts index eaff5e9292..cd07c602ba 100644 --- a/main/handlers/chats.ts +++ b/main/handlers/chats.ts @@ -1,4 +1,3 @@ -import { workspaceApplicationService } from "../services/workspace-application-service-main.js"; import { isCompactionEngine } from "../../renderer/shared/compaction.js"; // Chat history CRUD IPC handlers. @@ -123,11 +122,14 @@ export function registerChatHistoryHandlers(): void { workspaceExists: async (workspaceId) => Boolean(await configStore.getWorkspace(workspaceId)), resolveSkill: (workspaceId, invocationId) => skillRegistry.resolveFresh(workspaceId, invocationId), prepareWorkspace: async (workspaceId) => { + // Resolve after startup: the workspace service also depends on chat/LLM services. + const { workspaceApplicationService } = await import("../services/workspace-application-service-main.js"); const target = await workspaceApplicationService.reserveNoWorkspaceChat(workspaceId); if (target.workspaceId !== workspaceId) ipcMain.broadcast("workspaces:changed", {}); return target; }, releaseUnusedWorkspace: async (workspaceId) => { + const { workspaceApplicationService } = await import("../services/workspace-application-service-main.js"); await workspaceApplicationService.releaseNoWorkspaceAfterChat(workspaceId); ipcMain.broadcast("workspaces:changed", {}); }, diff --git a/main/services/chat-fork-service-main.ts b/main/services/chat-fork-service-main.ts index 6f2d8ae726..46fa7f68f9 100644 --- a/main/services/chat-fork-service-main.ts +++ b/main/services/chat-fork-service-main.ts @@ -2,7 +2,6 @@ import { ipcMain } from "../platform.js"; import { persistedChatWorkspaceId } from "../../renderer/shared/chat-workspace.js"; import { createChatForkService } from "./chat-fork-service.js"; import { chatStore } from "./chat-store.js"; -import { workspaceApplicationService } from "./workspace-application-service-main.js"; import { configStore } from "./config-store.js"; import { writeDiagnosticEvent } from "./diagnostic-journal.js"; import { forkSummaryService } from "./fork-summary-service-main.js"; @@ -17,11 +16,14 @@ export const chatForkService = createChatForkService({ beginChatCopy: (chatId) => llmClient.beginChatCopy(chatId), workspaceExists: async (workspaceId) => Boolean(await configStore.getWorkspace(workspaceId)), prepareWorkspace: async (workspaceId) => { + // Resolve after startup: the workspace service also depends on chat/LLM services. + const { workspaceApplicationService } = await import("./workspace-application-service-main.js"); const target = await workspaceApplicationService.reserveNoWorkspaceChat(workspaceId); if (target.workspaceId !== workspaceId) ipcMain.broadcast("workspaces:changed", {}); return target; }, releaseUnusedWorkspace: async (workspaceId) => { + const { workspaceApplicationService } = await import("./workspace-application-service-main.js"); await workspaceApplicationService.releaseNoWorkspaceAfterChat(workspaceId); ipcMain.broadcast("workspaces:changed", {}); }, diff --git a/tests/e2e/chat-fork.spec.ts b/tests/e2e/chat-fork.spec.ts index 3172070b2b..a0df32c278 100644 --- a/tests/e2e/chat-fork.spec.ts +++ b/tests/e2e/chat-fork.spec.ts @@ -1,5 +1,6 @@ -import { readFile } from "node:fs/promises"; +import { readFile, writeFile } from "node:fs/promises"; import path from "node:path"; +import type { Page } from "@playwright/test"; import { expect, finishLmStudioOnboarding, test } from "./fixtures"; type StoredMessage = { id: string; role: string; content: string }; @@ -32,6 +33,15 @@ async function regularChats(root: string): Promise { const replies = (chat: StoredChat | undefined) => chat?.messages.filter((message) => message.role === "assistant").length ?? 0; +async function workspaceHome(page: Page, workspaceId: string | undefined) { + return page.evaluate(async (workspaceId) => { + const homes = await (window as unknown as { + aidenAPI: { ipc: { invoke(channel: string): Promise } }; + }).aidenAPI.ipc.invoke>("workspaces:list"); + return homes.find((workspace) => workspace.id === workspaceId)!; + }, workspaceId); +} + test("a chat forks from a reply or edits a prompt in a fork", async ({ aiden }) => { const { page, userDataDir } = aiden; await finishLmStudioOnboarding(page); @@ -47,6 +57,9 @@ test("a chat forks from a reply or edits a prompt in a fork", async ({ aiden }) const [firstPrompt, firstReply, secondPrompt] = source.messages.filter( (message) => message.role === "user" || message.role === "assistant", ); + const sourceHome = await workspaceHome(page, source.workspaceId); + expect(sourceHome.noWorkspace).toBe(true); + await writeFile(path.join(sourceHome.folderPath, "source-only.txt"), "Source private file"); // Fork after the first reply. const forkFromReply = page.getByRole("button", { name: "Fork from here" }).first(); @@ -70,6 +83,20 @@ test("a chat forks from a reply or edits a prompt in a fork", async ({ aiden }) await expect(sourceLink).toBeVisible(); await expect(page.locator('[data-forked="true"]')).toHaveCount(1); + // Opening a populated private fork must refresh its newly assigned workspace + // before the next send, and must not expose the source's files. + expect(afterFork.workspaceId).not.toBe(source.workspaceId); + const forkHome = await workspaceHome(page, afterFork.workspaceId); + expect(forkHome.noWorkspace).toBe(true); + expect(forkHome.folderPath).not.toBe(sourceHome.folderPath); + expect(forkHome.permission).toBe("ask"); + await expect(readFile(path.join(forkHome.folderPath, "source-only.txt"), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + await composer.fill("Continue in the private fork"); + await composer.press("Enter"); + await expect.poll(async () => replies((await regularChats(userDataDir)).find((chat) => chat.id === afterFork.id))).toBe(2); + expect(replies((await regularChats(userDataDir)).find((chat) => chat.id === source.id))).toBe(2); + expect(await readFile(path.join(sourceHome.folderPath, "source-only.txt"), "utf8")).toBe("Source private file"); + // The lineage link returns to the source, where a later prompt can be edited in a fork. await sourceLink.click(); await expect(page.getByRole("button", { name: "Edit in fork" })).toHaveCount(2); @@ -93,3 +120,38 @@ test("a chat forks from a reply or edits a prompt in a fork", async ({ aiden }) await expect(composer).toHaveValue(firstPrompt.content); expect(await regularChats(userDataDir)).toHaveLength(3); }); + +test("duplicating a private chat opens an independent folder with its own access and follow-up turn", async ({ aiden }) => { + const { page, userDataDir } = aiden; + await finishLmStudioOnboarding(page); + const composer = page.locator("textarea"); + await composer.fill("Start a chat to duplicate"); + await composer.press("Enter"); + await expect.poll(async () => replies((await regularChats(userDataDir))[0])).toBe(1); + const [source] = await regularChats(userDataDir); + const sourceHome = await workspaceHome(page, source.workspaceId); + expect(sourceHome.noWorkspace).toBe(true); + await writeFile(path.join(sourceHome.folderPath, "source-only.txt"), "Keep private"); + await page.evaluate((workspaceId) => (window as unknown as { + aidenAPI: { ipc: { invoke(channel: string, ...args: unknown[]): Promise } }; + }).aidenAPI.ipc.invoke("workspaces:update", workspaceId, { permission: "full" }), source.workspaceId); + + await page.locator("[data-chat-title-menu]").click(); + await page.getByRole("menuitem", { name: "Duplicate chat", exact: true }).click(); + await expect.poll(async () => (await regularChats(userDataDir)).length).toBe(2); + const copied = (await regularChats(userDataDir)).find((chat) => chat.id !== source.id)!; + expect(copied.messages.map((message) => message.content)).toEqual(source.messages.map((message) => message.content)); + expect(copied.workspaceId).not.toBe(source.workspaceId); + const copyHome = await workspaceHome(page, copied.workspaceId); + expect(copyHome.noWorkspace).toBe(true); + expect(copyHome.folderPath).not.toBe(sourceHome.folderPath); + expect(copyHome.permission).toBe("ask"); + expect((await workspaceHome(page, source.workspaceId)).permission).toBe("full"); + await expect(readFile(path.join(copyHome.folderPath, "source-only.txt"), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + + await composer.fill("Continue in the duplicate"); + await composer.press("Enter"); + await expect.poll(async () => replies((await regularChats(userDataDir)).find((chat) => chat.id === copied.id))).toBe(2); + expect(replies((await regularChats(userDataDir)).find((chat) => chat.id === source.id))).toBe(1); + expect(await readFile(path.join(sourceHome.folderPath, "source-only.txt"), "utf8")).toBe("Keep private"); +}); diff --git a/tests/e2e/no-workspace-chat.spec.ts b/tests/e2e/no-workspace-chat.spec.ts index 16cd9a2043..62b53c524f 100644 --- a/tests/e2e/no-workspace-chat.spec.ts +++ b/tests/e2e/no-workspace-chat.spec.ts @@ -47,6 +47,29 @@ async function sendAndWaitForReply(page: Page, text: string, userDataDir: string await expect(page.locator("[data-chat-title-menu]")).toBeVisible({ timeout: 20_000 }); } +test("chat history IPC creates and reloads an ordinary chat after startup", async ({ aiden }) => { + const { page, userDataDir } = aiden; + await finishLmStudioOnboarding(page); + const workspaceId = (await workspaces(page))[0].id; + const created = await page.evaluate(async (workspaceId) => { + const ipc = (window as unknown as { + aidenAPI: { ipc: { invoke(channel: string, ...args: unknown[]): Promise } }; + }).aidenAPI.ipc; + return ipc.invoke<{ id: string; title: string; workspaceId: string }>("chats:create", { + workspaceId, + title: "History startup check", + }); + }, workspaceId); + expect(created).toMatchObject({ title: "History startup check", workspaceId }); + expect((await regularChats(userDataDir)).map((chat) => chat.id)).toContain(created.id); + const loaded = await page.evaluate((chatId) => ( + window as unknown as { + aidenAPI: { ipc: { invoke(channel: string, ...args: unknown[]): Promise } }; + } + ).aidenAPI.ipc.invoke<{ chat: { id: string; messages: unknown[] } }>("chats:get", chatId), created.id); + expect(loaded.chat).toMatchObject({ id: created.id, messages: [] }); +}); + test("No workspace chats each run in their own hidden folder and share one Chats group", async ({ aiden }) => { const { page, userDataDir } = aiden; await finishLmStudioOnboarding(page); @@ -121,6 +144,40 @@ test("No workspace chats each run in their own hidden folder and share one Chats expect(await isDirectory(thirdHome!.folderPath!)).toBe(true); }); +test("a selected skill reaches the first turn after allocating a fresh private folder", async ({ aiden }) => { + const { page, userDataDir, lmStudio } = aiden; + await finishLmStudioOnboarding(page); + await page.evaluate(() => (window as unknown as { + aidenAPI: { ipc: { invoke(channel: string, ...args: unknown[]): Promise } }; + }).aidenAPI.ipc.invoke("skills:save", { + id: "private-handoff-fixture", + name: "Private handoff fixture", + description: "A skill selected before its private folder exists.", + instructions: "PRIVATE_HANDOFF_INSTRUCTION: Apply the chosen review checklist.", + enabled: true, + })); + await page.reload(); + await sendAndWaitForReply(page, "Populate the original private home", userDataDir, 1); + const [source] = await regularChats(userDataDir); + await expect.poll(() => savedReplies(userDataDir, source.id)).toBe(1); + await page.getByRole("button", { name: "New Agent", exact: true }).click(); + const composer = page.locator("textarea"); + await composer.fill("$"); + await page.getByRole("listbox", { name: "Skills" }) + .getByRole("option", { name: /Private handoff fixture/u }).click(); + const prompt = "Apply my selected checklist in the new private chat"; + await composer.fill(prompt); + await composer.press("Enter"); + await expect.poll(async () => (await regularChats(userDataDir)).length).toBe(2); + const target = (await regularChats(userDataDir)).find((chat) => chat.id !== source.id)!; + expect(target.workspaceId).not.toBe(source.workspaceId); + await expect.poll(() => savedReplies(userDataDir, target.id)).toBe(1); + expect(lmStudio.requests.some((request) => { + const body = JSON.stringify(request.body); + return body.includes(prompt) && body.includes("PRIVATE_HANDOFF_INSTRUCTION"); + })).toBe(true); +}); + test("an older install's folderless default workspace becomes the home of its chats on the next start", async ({ aiden }) => { await finishLmStudioOnboarding(aiden.page); await sendAndWaitForReply(aiden.page, "Remember this chat", aiden.userDataDir, 1);