Skip to content

refactor(agent-session): keep which conversation each chat tab shows in one host table - #22709

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/chat-tab-identity-p2-published-id
Sep 26, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/chat-tab-identity-p2-published-id

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​692 $\color{#cf222e}{\Huge{\mathbf{−}}}$​187 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​505
Prod 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​364 $\color{#cf222e}{\Huge{\mathbf{−}}}$​163 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​201

ELI5

A chat tab and the conversation it shows are two different things. After /clear, the same tab shows a new conversation. Until now the host kept this link in two places: a list of which conversations have a tab, and a tab id written onto each conversation's record. This PR replaces both with one table owned by the host: "tab X currently shows conversation Y". /clear just moves tab X to point at the new conversation.

What Changed

Users should see no change. Tabs, their order, their read/unread state and their status dots behave as they do on main. This change lays the ground for the later step, in which every client starts using the host's tab id.

How it works:

  • One table. The agent-session store on the host now persists sessionTabs, a list of { tabId, sessionId }. In memory it keeps a reverse index, so a lookup from a conversation to its tab takes constant time and returns at most one id. A conversation with an entry has a visible tab, so this table replaces the old visible-conversation list.
  • /clear moves the entry. The transaction that commits the clear moves the tab's entry from the old conversation to the new one. The tab keeps its id and its position. No record carries a copied id, so one tab id can only ever name one conversation.
  • A create that reserved a tab id (from agent.launch or agentSession.create) takes it when its tab is published, the same moment every other chat gets its entry. The reservation only checks that no other chat's tab holds the id, and refuses it if one does; the old scan over every record is gone. A create that stops before its tab is published, whether it fails or the app quits, leaves nothing in the table, so there is nothing to release and nothing for the next launch to restore. Closing a chat frees its id. If two creates race for one id, both pass the check and the second fails to publish its tab, answering that the outcome is unknown. Its provider keeps running without a tab until the app quits; nothing is persisted for it, so the next launch does not restore it. No shipped client sends a reserved chat tab id yet, and client-minted ids make a collision a client bug, not a user path.
  • Showing a chat that has no entry, such as a new chat or a conversation reopened from history, gives it the id clients use today, structured-agent-session-<sessionId>. There is one exception. When a cleared conversation is reopened, its tab id is already held by the tab now showing its replacement, so the reopened one gets structured-agent-session-<sessionId>-reopened (with a number added if that is taken too). Seeding from an older store file uses the same rule, so the id survives an older build dropping the table. Ids never contain :.
  • Closing or retiring a conversation removes only that conversation's own entry, so closing a cleared conversation never touches the tab now showing its replacement. If a close does not go through, the tab is put back under the id it had.

Deliberately not in this PR:

  • The host tab snapshot still names chat tabs agent-session:<sessionId>.
  • There is no new capability and no id translation for clients.
  • The status-row key and the orchestration worker pane-key prefix are byte-for-byte what main produces.
  • replaceConversationInSnapshot is unchanged.

Publishing the host id, one inbound conversion point, and the move of the status and worker keys all ship with the desktop change that uses them.

The surfaceTabId record field (added in #22616) is no longer part of the record type and is never written on new records. It is read in one place only: when the host loads a store file that has no sessionTabs, it seeds the table from the visible list, using each visible chat's surfaceTabId if it has one and today's derived id otherwise. A chat cleared on an older build is the exception: its tab was opened for the first conversation of its /clear chain, and clients still hold that tab under the first conversation's id, so it seeds under that id, found by following the committed clears on the source records. Those chats seed first, so a cleared conversation reopened from history gets the same -reopened id when its own is held, as it does on this build. Once the table is on disk, the field is never read again. Records that already carry it keep it unchanged through rewrites; nothing drops it and nothing reads it. A malformed value no longer marks the record unreadable. #22616 is in no release: v1.4.210 and the newest tag, v1.4.211, both lack it.

Why

The first version of this PR copied the tab id from the cleared conversation's record onto its replacement's record. Records are never deleted, so after a /clear two records claimed one tab, and every lookup had to guess which one was current. That caused three bugs:

  • A second /clear was refused as a conflict, because the exemption covered only one hop, and the chat then refused every send.
  • Reopening the cleared conversation from history activated the current chat's tab.
  • Retiring the old conversation matched the current chat's tab.

That version also published the new id before any client could read it. It then had to convert ids back to the old spelling at each call site, which broke two things: tab reorder from a paired client, where the tab order list was never converted, and the old-mobile close check, which ran before the conversion.

A table keyed by tab id rules out the first set of bugs by construction: each id has one owner, and /clear changes which conversation that owner points to rather than creating a second holder. Waiting to publish removes the second set. Nothing outside the host reads the new id until the client that uses it ships with the one conversion point.

The table also absorbs the visible-conversation list rather than sitting next to it. Two lists that both mean "this chat has a tab" can disagree.

Linked Issue

No issue. This is the second step of the chat tab identity series, after #22616.

Visual Proof

N/A. Nothing users see changes. The table is host bookkeeping, and the snapshot, status keys and read-state keys are unchanged.

Testing

  • I manually tested these changes locally (not run in the Electron app; see below)
  • Automated tests added/updated

New tests use a real store on disk, the real structured host, the real runtime and the real RPC handlers. Only the provider process is faked. They are in rpc/methods/structured-chat-tab-table.test.ts and agent-session-record-store-tab-table.test.ts. They cover:

  • /clear three times in a row, then a send: every clear succeeds, the tab follows each replacement, and the send is accepted.
  • Reopening a cleared conversation from history: it opens in its own tab under a new id, the new tab is the active one, and the current chat's tab is untouched.
  • Closing the reopened old conversation: the current chat keeps its tab and still sends.
  • A close that does not go through: the tab comes back under the same id.
  • Restart: after two clears, a reopened store keeps the tab id and its pointer.
  • An older build dropping the table: after a clear, a reopen from history and a second clear, the file loses sessionTabs and is loaded again; the current chat and the reopened conversation seed under the ids they had.
  • Seeding from an older store file: a visible chat keeps its recorded id or today's derived id, opening writes nothing, and the first write persists the table and the list older builds read.
  • Seeding a chat cleared twice on an older build, with its first conversation reopened from history: the current chat gets the first conversation's id, the reopened one gets a different id without :, the visible order is kept, and a second read gives the same ids.
  • Once the table is on disk, a stale surfaceTabId on a record is ignored.
  • A reserved create answers with its id, and a second chat asking for the same id is refused.
  • A create that reserved nothing answers with the id its tab was given.
  • A reserved create that stopped after the provider started but before its tab was published: after a restart nothing is restored for it, and a later create can take the id.
  • A failed reserved create leaves no tab entry, so a later create can use the id.
  • Tab reorder from a paired client, in a group holding chats, succeeds.
  • An old mobile client closing a chat it may only view is refused, as on main.

The last two exercise code this PR does not change. They pin that the table does not disturb those paths and have no ablation.

Ablation. For each mechanism, the code was deleted on a committed tree and the targeted files were run, then the code was restored. Also, with the production code of the first version of this change put back and the new tests kept, 4 of 42 tests fail: the id is taken at reservation, an unreserved create's reply lacks its id, and a create that stopped before publishing is restored as a visible chat.

Mechanism deleted Red Why it went red
/clear moves the table entry 7 / 30 The replacement has no tab entry, and the restart and history tests lose the pointer
Fresh id when a reopened chat's derived id is taken 2 / 17 Reopening history is refused as a conflict; the table will not let it take the current chat's id
The published tab takes the reserved id 3 / 11 The chat is shown under the derived id, so the reply and the later create see the wrong id
Seeding from a record's surfaceTabId 1 / 8 A visible chat seeds under the derived id instead of the one it recorded
Chats showing a /clear chain seed under the chain's first id 1 / 9 The current chat seeds under its own derived id, not the one clients hold
A reopened conversation gets the same id at runtime as at seeding (random id put back) 1 / 12 After the table is dropped and seeded again, the reopened conversation comes back under a different id
A failed close restores the same id 3 / 19 The chat comes back under a different id
/clear drops the old conversation's reverse entry 3 / 17 The old conversation still maps to the tab, so closing it would take the current chat's tab
The table is read before the legacy fields 10 / 17 The targeted test sees the stale record field. The other failures are broader: every transaction then sees the file as changed on disk

Also run:

  • pnpm tc.
  • 208 affected test files (agent-session store, structured host, create, close, teardown, orchestration workers, session tabs, agent launch): all pass except agent-session-pty-write-enforcement.test.ts > "withholds orchestration Enter after the pointer lease fence moves", which fails the same way on main.
  • tests/e2e/cross-version-wire/cross-version-agent-session-wire.unit.test.ts and cross-version-session-tabs-retirement-proof.unit.test.ts, each run alone: passed.
  • oxlint on the changed files, and check:code-quality:changed: 0 findings.

AI Disclosure

Written with Claude.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Wire compatibility. No RPC parameter, frame or published snapshot content changes. The only reply field involved is agentSession.create / attach tabId (and the agent.launch outcome's tabId), which is already optional. It now comes from the table and is present when the chat has a tab. A create reads it after its tab is published, so a create that reserved nothing answers with the derived id, as on main, and a retry of the same create answers the same. No released client reads it.
  • Store file compatibility. The store stays on schema version 2. Older builds ignore sessionTabs and keep reading visibleSessionIds, which is still written, derived from the table. If an older build rewrites the file it drops the table. The next load of this build seeds it again, with the same ids for every chat except three kinds: a chat created with a reserved id, which gets the derived id; a cleared conversation reopened from history whose replacement's tab has since closed, which gets its own derived id back; and, in that same case, a replacement later reopened from history, which reseeds under the first conversation's id instead of its own. Nothing reads the host's id yet, so none of these is visible to a user; the step that publishes the host's id has to settle them.
  • SSH/remote. Structured chat runs only on the local execution host: both provider adapters require the local host and no WSL distro. A paired client reaches the table only through the host it is paired to, and the table lives in that host's store.
  • Folder workspaces. Entries are keyed by tab and conversation, not by workspace, so folder workspaces and git worktrees behave the same.
  • Performance. A lookup from a conversation to its tab is a map read. Status ingest does not touch the table. Each store transaction copies the table for rollback; its size is the number of open chat tabs.
  • Small behavior difference. Before, a cleared chat moved to the end of the restore order. Now it keeps its place, because /clear moves the entry in place.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

Two functional regressions to fix before merge: session.tabs.move mistranslates chat tab ids for every paired client that does not advertise session.tabs.chat-tab-id.v1 (all of them today), and a second /clear on a replacement is refused agent_session_conflict.

Reviewed changes

  • Publish the record id: new structuredAgentSessionSurfaceTabId reads record.surfaceTabId and falls back to the derived structured-agent-session-<sessionId>; publishStructuredAgentSessionTab, the restore-once publisher, the hook status address, worker pane keys, findStructuredAgentSessionTab and the CLI handle all move onto it.
  • Compatibility projection: new host capability session.tabs.chat-tab-id.v1; projectSessionTabChatIds rewrites every id-bearing snapshot field to agent-session:<sessionId> for a paired client that does not advertise it, and resolveClientSessionTabId maps that spelling back on activate/close/refuse and in resolveMobileSessionHostTabId.
  • /clear keeps its tab: the replacement inherits the source's surfaceTabId, admission exempts the declared replacement, and replaceConversationInSnapshot stops renaming.
  • Derivation ratchet: pins the remaining structuredAgentSessionTabId callers to the four that translate older state.

Two notes that are minor enough to leave inline rather than block: the fold in replaceConversationInSnapshot does not clean group references, and the helper's early fallback can key a status row by the derived string during teardown.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-tab-identity-p2-published-id branch from b4a3297 to 38f8746 Compare September 25, 2026 01:52
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/chat-tab-identity-p1-host-owned-id to main September 25, 2026 01:52
@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0b513e4c-0a30-4930-904c-0da317c2f340

📥 Commits

Reviewing files that changed from the base of the PR and between 33815fa and 8badedd.

📒 Files selected for processing (10)
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/runtime/agent-session-record-store-file.ts
  • src/main/runtime/agent-session-record-store-surface-tab-id.test.ts
  • src/main/runtime/agent-session-record-store-tab-table.test.ts
  • src/main/runtime/agent-session-record-store.ts
  • src/main/runtime/agent-session-reservation-admission.test.ts
  • src/main/runtime/agent-session-reservation-admission.ts
  • src/shared/agent-session-record.ts
  • src/shared/agent-session-wire.ts
💤 Files with no reviewable changes (2)
  • src/main/runtime/agent-session-record-store-surface-tab-id.test.ts
  • src/shared/agent-session-record.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/shared/agent-session-wire.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The runtime replaces the visible-session index and record-level tab IDs with a persisted tab table. Create reservations check that requested IDs are unheld; publication assigns the tab ID, which create and attach responses can return. Clear commands move tab mappings to replacement sessions, and close rollback can restore a captured tab ID. The changes also add table persistence and lifecycle tests, remove legacy backfilling, and update record validation.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 8bade

Concurrent chat operations can leave a created chat without a visible tab or restore a stale tab after a failed close. Resolve the create race before merging and assess the close/clear interleaving.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 8bade

The new ownership model reduces the chance that an old conversation and its replacement claim the same tab. The main access checks remain in place, but this is a persistent lifecycle change, and recovery and compatibility paths are not fully established by the available evidence.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A mistaken persisted mapping could affect which conversation the host republishes as a chat tab after restart. The inspected design places that authority in the local host store; the available evidence does not establish a new cross-service or tenant boundary.

Trust Boundaries and Controls

  • observed — Caller-supplied session and tab identifiers do not by themselves grant attachment: existing-session ownership checks and transactional checks against an already-held tab remain in the inspected path.

Resilience and Maintainability Implications

  • observed — Close rollback captures the prior tab ID before hiding it and attempts restoration only for an unproven close with a worker that has not exited. Restoration failure is logged rather than treated as a successful recovery.

Hardening Proposals

  • proposed — Make a repeated source-to-replacement move preserve an already-published destination tab even if a future caller bypasses public operation replay; this would put the identity guarantee at the state-transition boundary.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 48 functions across 26 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the required change, rationale, testing, visual proof, compatibility, and checklist areas. However, the required linked issue is missing; it states "No issue" in… Add the issue reference that this PR addresses using the required Fixes #<issue-number> format. Keep the existing explanation if this is an intentional follow-up to #22616.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: consolidating chat-tab conversation ownership in one host table.
Full details: Description check

Explanation

The description is detailed and covers the required change, rationale, testing, visual proof, compatibility, and checklist areas. However, the required linked issue is missing; it states "No issue" instead of providing a Fixes #... reference.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…in one host table

The host now persists one table in the agent-session store, from chat tab id to
the conversation that tab currently shows. It replaces both the visible-session
list and the per-record surfaceTabId, so there is one answer to "which chats have
a tab, and under what id".

- /clear moves the tab's entry from the old conversation to its replacement in
  the same transaction that commits the clear. No record carries a copied tab
  id, so a tab id names one conversation by construction, and the lookup from a
  conversation to its tab returns at most one id.
- A create that reserved a tab id claims it in its reservation transaction;
  uniqueness is a key check on the table. A create that fails releases its
  claim, and hiding a chat frees its id.
- Showing a chat with no entry gives it today's id, structured-agent-session-<sid>,
  unless a cleared chat's tab kept that id; then it gets a fresh one.
- A close that does not land puts the tab back under the id it had.
- Stores written by older builds are seeded on read from the visible list and,
  for chats that have one, the record's surfaceTabId. That field is no longer
  part of the record type, is never written, and is read only by this seed when
  the file has no table. The visible list is still written, derived from the
  table, for older builds.

Tab snapshots, status keys and worker pane keys are unchanged.

Co-Authored-By: Claude <[email protected]>
@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-tab-identity-p2-published-id branch from 38f8746 to c48ed35 Compare September 25, 2026 07:28
@brennanb2025 brennanb2025 changed the title feat(session-tabs): publish a chat tab under the id its session record holds refactor(agent-session): keep which conversation each chat tab shows in one host table Sep 25, 2026
brennanb2025 and others added 2 commits September 25, 2026 00:46
…shed

A create that reserved a tab id put it in the tab table at reservation, and table membership is
visibility. A create that stopped before its tab was published (a crash, or a failure after the
provider started) left an entry that the next launch either restored as a tab nobody asked to see
again or kept forever with no way to close it. Reservation now only refuses an id another chat's
tab holds; the id is taken when the tab is published, so there is nothing to release on failure.

The create reply now reads the tab id after publishing, so an unreserved create answers with the
id its tab was given, as it did before the table, and agrees with a replay of the same create.

Co-Authored-By: Claude <[email protected]>
…first tab id

A chat cleared on an older build shows a later conversation of its /clear chain in the tab that was
opened for the first one, and clients key that tab, its read state and its status by the first
conversation's id. Seeding gave it the latest conversation's derived id instead, so the stored id
disagreed with the one clients hold and with what a /clear on this build leaves behind.

Seeding now follows the source records' committed clears back to the chain's first conversation
and gives the chat showing the chain that conversation's id. Those chats seed first, so a cleared
conversation reopened from history takes a fresh id when its own is held. A seeded chat is no
longer dropped when every candidate id is taken, and the table keeps the visible list's order.

Co-Authored-By: Claude <[email protected]>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

This rewrite replaces the record-pinned id with a single host sessionTabs table and resolves both prior threads cleanly. One logic gap remains before merge: on a failed create, the tab release is keyed to the request rather than to whether the reservation actually claimed an entry, so a failed re-create can delete a tab the create never owned.

Reviewed changes

This run re-reviewed c48ed35 against the prior pullfrog review at b4a3297; the delta is a full reimplementation, not a rebase.

  • Introduced one host-owned table. AgentSessionTabTable (tabId → sessionId plus a reverse index) now owns chat-tab membership and id; it replaces the record's surfaceTabId and the visible-conversation set, and agent-session-visible-tab-index.ts is deleted.
  • /clear moves the entry. commitConversationCommandRecord calls move(sessionId, replacementSessionId) so the tab keeps its id and place, and a chain of clears is admitted by construction instead of by a one-hop exemption.
  • Removed the client-side new id entirely. structuredAgentSessionSurfaceTabId, the session.tabs.chat-tab-id.v1 capability and its projection are gone; the snapshot still names chat tabs agent-session:<sessionId>, so session.tabs.move sees matching ids again.
  • Reserved creates claim and release in the reservation transaction. claimReservedTab shows the reserved id; failure settlement hides it; a failed close restores the exact prior id.
  • Reworked persistence and tests. The store persists sessionTabs while still writing visibleSessionIds for older builds, and seeds from a legacy file using each visible record's surfaceTabId; new end-to-end tests cover repeated clears, reveal, close, restart, and seeding.

ℹ️ Nitpicks

  • getSessionTabId (agent-session-record-store.ts:137) reads the table unfiltered while listVisibleSessionIds filters by records.has, so seeding an entry for a session with no readable record makes the two accessors disagree about whether a chat has a tab. Harmless today (the close restore throws agent_session_identity_required and is warned), but filtering both the same way would keep the contract single-valued.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f7ef3560-aba7-4827-97ef-a69a214cac7c

📥 Commits

Reviewing files that changed from the base of the PR and between c48ed35 and 2718782.

📒 Files selected for processing (12)
  • src/main/native-chat/agent-session-wire/structured-agent-session-acquisition-options.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/runtime/agent-session-record-store-tab-table.test.ts
  • src/main/runtime/agent-session-reservation-admission.ts
  • src/main/runtime/agent-session-tab-table.ts
  • src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts
  • src/main/runtime/rpc/methods/structured-agent-session-create.ts
  • src/main/runtime/rpc/methods/structured-chat-tab-table.test.ts
  • src/shared/agent-launch-intent.ts
  • src/shared/agent-session-wire.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/agent-session-wire.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +263 to 266
const holder = state.sessionTabs?.sessionIdFor(request.surfaceTabId)
if (holder !== undefined && holder !== request.sessionId) {
throw new Error('agent_session_conflict')
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '150,215p' src/main/runtime/agent-session-reservation-admission.ts
sed -n '240,275p' src/main/runtime/agent-session-reservation-admission.ts
sed -n '110,175p' src/main/runtime/rpc/methods/structured-agent-session-create.ts
sed -n '1,118p' src/main/runtime/agent-session-tab-table.ts
rg -n 'settleFailedAcquisition|agent_session_operation_unknown|commitStructuredAgentSessionCreate|reserveOwner' src/main/native-chat/agent-session-wire src/main/runtime/rpc/methods src/main/runtime/agent-session-record-store.ts

Repository: stablyai/orca

Length of output: 18441


🏁 Script executed:

rg -n -C 8 "class AgentSessionRecordStore|reserveOwner|settleFailedAcquisition|withTransaction|transaction|publishStructuredAgentSessionTab|setAgentSessionTabVisibility|attach\(" src/main/runtime src/main/native-chat/agent-session-wire -g '*.ts'
printf '\n--- record store ---\n'
sed -n '1,290p' src/main/runtime/agent-session-record-store.ts
printf '\n--- attach flow ---\n'
sed -n '1,330p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
printf '\n--- runtime publish binding ---\n'
rg -n -C 12 "publishStructuredAgentSessionTab|setAgentSessionTabVisibility" src/main/runtime src/main/native-chat -g '*.ts'

Repository: stablyai/orca

Length of output: 45666


🏁 Script executed:

printf '%s\n' '--- store symbols ---'
rg -n "export class AgentSessionRecordStore|reserveOwner|settleFailedAcquisition|transactionQueue|run|enqueue|withTransaction" src/main/runtime/agent-session-record-store.ts src/main/runtime/agent-session-store-transaction-queue.ts
printf '%s\n' '--- store reserve/settlement ---'
sed -n '150,275p' src/main/runtime/agent-session-record-store.ts
printf '%s\n' '--- transaction queue ---'
cat -n src/main/runtime/agent-session-store-transaction-queue.ts
printf '%s\n' '--- attach flow symbols ---'
rg -n "performAttach|settleFailedAcquisition|releaseAcquisition|onAttached|catch|attach" src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
printf '%s\n' '--- attach flow relevant sections ---'
sed -n '70,205p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
sed -n '235,290p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
printf '%s\n' '--- publication implementation ---'
rg -n -C 15 "publishStructuredAgentSessionTab" src/main/runtime -g '*.ts' -g '!*.test.ts'

Repository: stablyai/orca

Length of output: 45074


🏁 Script executed:

printf '%s\n' '--- attach flow post-acquisition ---'
cat -n src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts | sed -n '190,300p'
printf '%s\n' '--- host attach implementation ---'
rg -n -C 12 "async attach|attach\\(" src/main/native-chat/agent-session-wire/structured-agent-session-host.ts src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts src/main/native-chat/agent-session-wire -g '*.ts' -g '!*.test.ts' | head -n 260
printf '%s\n' '--- provider acquisition and release bindings ---'
rg -n -C 10 "acquireOwner|releaseAcquisition|settlePostAcquisitionAttachFailure|providerChildPhase" src/main/native-chat/agent-session-wire -g '*.ts' -g '!*.test.ts'

Repository: stablyai/orca

Length of output: 42649


Claim surfaceTabId before spawning, and settle a loser after publication conflict.

reserveOwner serializes transactions, but assertReservedTabUnheld only reads state.sessionTabs; it does not claim the ID. Two creates with different session IDs can therefore reserve the same surfaceTabId.

Each host.attach can acquire the provider and record a successful operation before tab publication. The first publication claims the tab. The second can receive agent_session_conflict. commitStructuredAgentSessionCreate converts that error to agent_session_operation_unknown, but no post-acquisition settlement or provider release runs after host.attach returns.

The failure is not that nothing is persisted. The losing record and successful operation remain persisted, but the provider and record can remain without a visible tab.

Keep a transient pending claim from reserveOwner through publication. If publication fails after attach, use the post-acquisition failure path to release the provider, settle the record, and clear the pending claim. Do not silently allocate a fresh ID, because that changes the caller's requested surfaceTabId and removes the before-spawn refusal contract.

…untime and at seeding

A cleared conversation reopened from history got a random tab id at runtime but a
deterministic `-reopened` id when the table is seeded from an older store. One rule now
serves both, so a table dropped by an older build and seeded again gives that chat the
id it already had.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

This run re-reviewed the two commits pushed since the prior pullfrog review at c48ed35; both prior findings are resolved and the delta introduces no new issues.

  • A reserved chat tab id is now taken when the tab is published, not at reservation. assertReservedTabUnheld only checks the table, createAgentSessionRecord no longer writes surfaceTabId, and the failed-create release path (releaseTab / releaseFailedCreateTab) is gone, so a failed create can no longer hide a tab it never claimed.
  • The create commit half publishes the reserved id and reads it back. publishStructuredAgentSessionTab threads the reserved tabId into setSessionTabVisibility, and commitStructuredAgentSessionCreate answers with host.getSessionTabId(...) after publication.
  • Seeding follows a /clear chain to its first conversation. seedFromVisibleSessions seeds a chain's tab under the chain root's id, with a deterministic <derived>-reopened fallback so a colliding visible session is never dropped, matching what move + show would have produced.
  • Close rollback restores the exact prior id. readPersistedTabId reads store.getSessionTabId before hiding and passes it back on a failed close.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

A commit landed while the prior review was posting; this run covers only that new commit (33815fa).

  • The reopened cleared-chat id is now deterministic and shared. AgentSessionTabTable.show and the seed's assign both call a new reopenedTabId helper, so a table dropped by an older build reseeds a reopened cleared conversation under the same id the runtime had assigned; randomUUID() is gone from show.
  • New coverage pins the invariant. The added test drives create → clear → reveal → clear, drops sessionTabs, reloads the store, and asserts the current chat and the reopened conversation keep the same ids.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…-identity-p2-published-id

# Conflicts:
#	src/main/runtime/agent-session-record-store-file.ts
#	src/main/runtime/agent-session-record-store-surface-tab-id.test.ts
#	src/main/runtime/agent-session-record-store.ts

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

This run re-reviewed the only commit pushed since the prior pullfrog review at 33815fa; it is a merge of main (8009939) with conflict resolution in three files the PR also touches. The PR's own logic is byte-for-byte unchanged, and the resolution is clean.

  • Merged main's persisted-lease refactor into the store file. agent-session-record-store-file.ts now decodes records through isPersistedAgentSessionRecord + normalizeLegacyHandoffRecord and threads legacyHandoffLeasesNormalized into needsRewrite. It composes correctly with the PR's table: parseAgentSessionTabTable still runs, state.sessionTabs is still set, and getVisibleSessionTabIndex().present still means sessionTabs !== null.
  • Narrowed an attach param to 'native'. AgentSessionAttachParams.runtimeKind no longer references the removed runtime-kind union; the PR's surfaceTabId param is intact.

Verified against the merged tree: structured-chat-tab-table, agent-session-record-store-tab-table, structured-agent-session-acquisition-options, structured-agent-session-close, structured-session-worktree-teardown and the store/reservation/legacy-handoff suites all pass (151 tests), and pnpm run typecheck:node ends EXIT 0. No new inline comments.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready for review (head 8badedd861)

What changed from the first version of this PR. The first version copied the chat tab id onto the /clear replacement's record. Records are never deleted, so after a /clear two records claimed one tab. That caused three reproduced bugs: a second /clear was refused and the chat then refused every send, reopening the cleared conversation from history jumped to the current chat, and retiring the old conversation closed the current chat's tab. It also published the new id before any client read it, which broke tab reorder from a paired client and the older-mobile close check. This PR was rebuilt as the host table only: one entry per tab, /clear moves the entry, and nothing is published yet.

Review loops.

  • Loop 1 fixed three issues. A reserved tab id is now taken when the tab is published rather than at reservation, so a crash mid-create cannot restore a phantom tab or leave an entry behind. Seeding from an older store follows the /clear chain to its first conversation, so a chat cleared before the upgrade keeps the id the desktop holds. The create reply carries the tab id again, as on main.
  • Loop 2 made a reopened cleared conversation get the same id at runtime and when the table is seeded.
  • Loop 3 found no code defects. origin/main was then merged in, keeping main's legacy lease normalization and dropping only the old id backfill that the table replaces.

Readiness checklist. Run at the start and at the end: nothing blocking either time (SSH/remote, mixed-version wire, store migration and downgrade, performance, cross-platform, folder workspaces).

Validation at this head.

  • CI: 21 pass, 0 fail, 0 pending, 11 path-filtered skips.
  • Locally: pnpm tc, 334 tests across 23 affected files, both cross-version wire tests run alone, oxlint, and check:code-quality:changed with 0 findings.
  • Each behavior fix fails its test when the code is deleted (table in the PR body).

Live Electron QA (Claude chat, isolated profile, head 27187829ba; later commits change only the id seeding rule and the merge).

  • Three /clears in a row, each followed by a send: every send works in the same tab, and the stored tab id stays the same while its pointer moves.
  • Reopening the pre-clear conversation from Agent Session History opens it in its own tab.
  • After a restart the tabs come back in the same order, and each chat still sends.
  • The unread dot behaves as on main, before and after /clear.
  • Codex: two /clears with sends, with the same tab id kept.
  • No difference from origin/main was found in these flows.

Three sends in a row after /clear:
pr-11-send4-reply-after-clear3.png

The pre-clear conversation reopened from history in its own tab:
pr-14-reopen-preclear-alpha.png

After a restart, all chat tabs are back in order:
pr-21-after-restart.png

A cleared chat still sends after the restart:
pr-24-after-restart-chatB-send-kappa.png

Found during QA, not caused by this PR. On origin/main, closing a conversation reopened from history also closes the current chat's tab. The host tells the window to close a tab id built from the closed conversation's id, and after a /clear that id belongs to the current chat's tab. This PR does not touch that path. A separate fix PR is in progress.

Known and documented.

  • Two creates racing for the same reserved tab id: the second's provider runs with no tab until quit. No shipped client sends a reserved id, so this cannot happen today.
  • A downgrade followed by an upgrade can change three kinds of host tab ids. Nothing reads the host id yet.
  • A cleared chat now keeps its place in the restore order instead of moving to the end.

The status keys, worker keys and the published snapshot are unchanged. Publishing the host id, with one inbound conversion point, ships in the later step together with the desktop change that uses it.

@brennanb2025
brennanb2025 merged commit 6627c65 into main Sep 26, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant