Skip to content

agentHost: make agent-host.db authoritative for session state (Block 3a) - #341626

Merged
Sandeep Somavarapu (sandy081) merged 89 commits into
mainfrom
agents/block3a-session-state-authority
Oct 15, 2026
Merged

Sandeep Somavarapu (sandy081) merged 89 commits into
mainfrom
agents/block3a-session-state-authority

Conversation

@sandy081

Copy link
Copy Markdown
Member

Goal

This is Block 3a of moving chats between sessions, following Block 2b (#341406, opaque chat URIs).

agent-host.db becomes authoritative for session state. Each chat's own database holds only that chat's data. Whatever older builds read is written for them as write-only copies (the "mirror"), so a downgrade keeps working.

Before this change, session-level state (config, flags, workspace, git and GitHub state, titles, read state) lived in each session's session.db, mixed with data that belongs to individual chats. Moving a chat between sessions needs a clean split: state that belongs to the session, and data that belongs to a chat and can travel with it.

Design

Session state store

  • IAgentHostSessionStateStore is the single owner of central session state. It uses new, additive tables in agent-host.db (migration 15): session_state, session_state_values, session_folder_state, session_chat_state and chat_row_mirror. Older builds never read them.
  • Load and import. load imports a session from its session.db once, then reconciles. For each entry, a mirror that differs from the recorded merge base was edited by an older build after a downgrade, and that edit wins. Otherwise central state wins.
  • Nothing imports without an explicit open. Listing, lifecycle sweeps, discovery, catalog synchronization and metadata readers never import a session (readWithoutImport, openMetadataWithoutImport, prefetchWithoutImport, readBaseBranchWithoutImport). Until a session is imported, its session.db stays its authority. A page or pass makes one batched agent-host.db query, and a session written centrally after that query is read afresh.
  • Writes go to central state first, then to the old-format mirror, either immediately or coalesced. Mirror targets are computed from live chats at write time, so nothing is ever mirrored into a deleted chat's database.
  • The store never loads a chat or a detached worktree record as a session (SessionStateNotASessionError).
  • Concurrency. Each session is a per-session sequencer section. Code inside a section uses the exclusive handle and never calls back into the store for the same session. Tests drive every known nesting path end to end, so a re-entrant call would hang and fail.
  • Guard. agentHostSessionStateOwnershipGuard.test.ts fails on any direct session.db access to a store-owned key outside the store, its mirror and the database layer, except an allowlist with a justification for each entry. Keys passed through string constants and statics (such as CopilotAgent._META_*) are resolved like literals. It also fails if the removed central checkpoint or branch-changes state is reintroduced.

Binding decisions

  • Group 1, session flags and config (central, mirrored): configValues, customizationEnablement, isArchived, isRead, defaultChatIsRead, agentHost.autoArchivedAt, agentHost.workspaceless, agentHost.workspaceConversionQuarantined, agentHost.createdBySession.
  • Group 2, workspace (central, mirrored): agentHost.sessionWorkingDirectories, agentHost.additionalWorktrees, copilot.worktree.*, sessionArtifacts.
  • Group 3, git, GitHub and source control (central per folder, mirrored): agentHost.git/gitData, github/githubData, pendingRecordedPullRequests, sourceControl, diffBaseBranch.
  • Group 4, not session state:
    • vscode.scheduleCursors is automation data.
    • The Mission Control cursors are the default chat's own data in its own database.
  • Group 5, chat summaries: titles, title sources, read state and change summaries are central (the normalized catalog, or session_chat_state for legacy-catalog sessions). The session database keeps receiving exactly main's writes. peerChats is written only for legacy-catalog sessions, as on main.
  • Group 6, keys in a peer's own database:
    • Legacy-catalog sessions keep main's keys (chatProviderData, chatOrigin, chatInheritedTurnId, chatWorkingDirectories, isRead).
    • A normalized peer gets only agentHost.chatWorkingDirectories, and only when its folders change. Releases 1.140 and 1.141 overlay that key on every read.
  • Group 7, rows: drafts and local and failed turns are chat data in each chat's own database. A peer's rows are also mirrored into the session database, keyed by chat. New builds read that mirror only to take in an older build's edits after a downgrade, for every peer, including peers this build created (whose central entry records no storage).
  • No changeset blobs. Branch and session-wide changesets are computed live. They are no longer stored, migrated or mirrored. Existing values on disk are left for older builds.
  • Checkpoints are chat data.
    • A chat's turn→ref rows and the repositories it captured in live in its own database.
    • The default chat keeps main's ref names. A peer uses chat-only refs: refs/agents/chats/<chatKey>/checkpoints/turn/<N>, numbered per chat.
    • There is no central checkpoint index or counter.
  • Delete by recorded storage.
    • Session delete captures every chat, private chats included, with its recorded storage before tombstoning.
    • A chat's storage is deleted only if no other live session or chat still records it.
    • Single-peer delete also removes the peer's central rows and its row copies in the session database. It also redirects or drops any base branch mirrored into the peer's database.
  • ehcli markers stay as on main. agentHost.ehcliAdopted and agentHost.ehcliLastMigratedTurn are the adopted chat's own data.
  • No async_hooks. There is no re-entrancy detection at runtime; the structural rule above is enforced by tests instead.
  • Schema v15 is purely additive. The unused central checkpoint and branch-changes tables were removed before shipping.

Downgrade behaviour and accepted trade-offs

  • An older build reads the mirrored keys and sees the same sessions, titles, flags, git state, drafts and turns.
  • Edits that the older build makes to mirrored keys are picked up on the next load: a mirror that differs from the merge base wins.
  • Accepted trade-offs:
    • After a downgrade, older builds can't show Turn Changes for new peer turns (chat-only refs). When they delete a session, they leave those refs behind.
    • Branch and session-wide changesets are computed live, so they show "computing" briefly after a restart.
    • Normalized-catalog peers stay invisible to 1.138, as on main.
    • Legacy rows copied into a peer's own database keep their originals in the session database. Those originals are deleted with the session, as on main.

Performance

Measured with the agent host perf harness: seeded databases with 2,000 and 10,000 sessions, base and branch interleaved, every SQL statement diffed. Base is the merge base 50559e7; branch is 1f88938129b, before the P1, P2 and F3 fixes below.

  • Listing: no regression.
    • agent-host.db statements are identical (7→7 at 2k, 27→27 at 10k).
    • session.db opens are 0→0.
    • Timings at 2k are within ±1.3 ms; the differences at 10k are noise (the sign flips).
  • First listing: +6 statements at 2k (one batched prefetch per listing, not per session), +0.9 ms. At 10k it is −17 to −20 ms.
  • Startup (schema v15): at most +0.9 ms. A first open of a v14 database runs migration 15: +0.2 to +0.65 ms.
  • Lifecycle sweep: session.db opens equal main's. The extra cost is one batched prefetch per sweep.
  • Costlier than main, on paths with no budget:
    • First import of a session: +3 to +6 ms for v2, +8.5 to +10.8 ms for v1.
    • Create: about +5 ms per session (about 9 separate central writes).
    • Legacy restore: about 12 more statements per subagent chat. This is still about 7x cheaper than before Block 2b.
    • An isolated git change flushed immediately: about +1.2 ms. A 50-change burst is cheaper than on main (one coalesced session.db write instead of 50).
  • Fixed after the measurement:
    • P1: a v2 title write opens and writes exactly what main does. The per-key rendering of normalized chats into session.db is gone; a normalized peer's folders are written only when they change.
    • P2: a database without legacy peer rows runs its turn statements without the foreign-row (json_each) filter. The filter cost +25% per checkpoint lookup even with no foreign rows.
    • F3: listing discovered sessions that have no central state and no session folder opens no database for them, as on main.

How to test

Live validation in Code OSS with real Copilot, using Insiders 1.143 as the old build. Rounds 1–3 ran on 1f88938129b, before the live-finding fixes below. Round 4 re-checked the rebased head b823e919c4a, and round 5 the final head 89e2b7bab05.

Scenario Result
S1: fresh v2 session (default and peer turns, renames, archive and unarchive, unread, drafts, restart) Pass
S2: older-build data opened in 3a (legacy-catalog peer, worktree, renames, drafts, cancelled turn) Pass
S3: downgrade round trip 3a → 1.143 → 3a, with edits on both sides Pass, nothing lost
S4 / S4b: delete a peer, then the session; chat-only checkpoint refs Pass
R1–R6, R8–R9: list, config, Changes views, worktree isolation, merge state, fork, workspace-less → folder, cancelled turn Pass
R7, R11, F4, F6, W1 (subagent pill, workbench Chat view, tab title after rename, fork summary after restart, changeset warning) Same as main (pre-existing)
R10: Claude Pass. Codex sessions missing after restart is pre-existing on main (follow-up below)
Round 4 (b823e919c4a): S1 core, S3 round trip, log scan Pass, with one finding (F8, fixed below)
Round 5 (89e2b7bab05): S1 core, R4 worktree isolation (edit, Branch Changes, archive and restore, restart), S3 round trip with F8, log scan Pass. An older build's draft edit in a 3a-created peer is reconciled after re-upgrade. The failed-turn row import could not be exercised live (1.143 kept the failed turn only in the SDK event log, not as a row), so that path is covered by unit tests only. No new error kinds from 3a; one pre-existing customization-publishing dispose race was seen once.

Live findings fixed in this PR:

  • F1: a chat's base-branch read no longer imports the chat as a session.
  • F2: discovery and catalog sync never import.
  • F3: listing opens no database for discovered sessions without a session folder.
  • F5: deleting a legacy-catalog peer now deletes its summary keys instead of leaving empty values. A normalized session keeps them, as on main.
  • The new store guard then caught a second phantom-session path: Copilot peer chat-backing resume. It is fixed too.
  • F8: an older build's edits to the drafts and local or failed turns of a peer this build created are reconciled after re-upgrade. Such a peer records no storage centrally, so its storage now resolves from the catalog.

Validation

All commands ran on head 89e2b7bab05 (rebased onto main 59e0b82), with every COPILOT_*, AGENT_HOST_* and GITHUB_TOKEN variable unset, except where a row names an earlier head:

Command Result
npm run typecheck-client 0 errors
npm run eslint -- <the 99 .ts/.js files changed vs origin/main> (b823e919c4a), then on the 26 files the gap fixes changed and the 4 files F8 changed clean
npm run valid-layers-check pass
hygiene (pre-commit hook on every commit) pass
./scripts/test.sh --reporter dot --grep "AgentHost|Chat" (ab3c1178993) 12,650 passing, 0 failing, 70 pending
./scripts/test.sh --reporter dot --grep "^(?!AgentHostChangesetStrategy ).*(AgentHost|Chat)" (89e2b7bab05, machine load ~20 from other apps) 12,538 passing, 0 failing, 70 pending. Under that load the excluded suite hits the known _doComputeStaticChangeset "after each" leak flake, at ab3c1178993 as well.
./scripts/test.sh --reporter dot --run src/vs/platform/agentHost/test/node/agentHostChangesetStrategy.test.ts, 3 times (89e2b7bab05, load ~11) 115 passing, 0 failing, each time
./scripts/test.sh --reporter dot --run src/vs/platform/agentHost/test/node/agentService.test.ts (89e2b7bab05) 904 passing, 0 failing, 16 pending
./scripts/test.sh --reporter dot --run src/vs/platform/agentHost/test/node/agentHostSessionStateStore.test.ts (89e2b7bab05, incl. the F8 tests) 60 passing, 0 failing
./scripts/test-integration.sh --run src/vs/platform/agentHost/test/node/e2e/providers/copilotAgentHostE2E.integrationTest.ts (89e2b7bab05, strict replay) 268 passing, 24 pending, 0 failing
./scripts/test.sh --reporter dot with --run for agentService, copilotAgent, agentSideEffects, chatContributions, worktreeIsolation, sessionAdditionalWorktrees, agentHostSavedChatService, agentHostCustomizationEnablementService, agentHostSessionStateStore, agentHostSessionStateOwnershipGuard, agentHostGitStateService and the three turn/tool-call telemetry suites (src/vs/platform/agentHost/test/node/) 2,410 passing, 0 failing, 17 pending
npm run test-agent-host-e2e (strict replay, full profile, ab3c1178993) all 6 suites pass: Conformance 368 (15 pending), Claude 124 (38), Codex 153 (34), Copilot 268 (24), Copilot OTel 22, Copilot managed settings 15
npm run test-agent-host-e2e-coverage (on cdd762d9844, before rebase) all suites pass; coverage stats not committed
npm run smoketest-no-compile -- -g "Agents Window" (b823e919c4a) 5 passing, 0 failing, 4 pending (the Dev Container suites over Docker, SSH, Tunnel and WSL, which only run when that environment is available)
npm run smoketest-no-compile -- -g "Electron\) (Chat|Copilot CLI)" (b823e919c4a) 14 passing, 0 failing (Chat Disabled, Chat Sandbox (darwin), Chat Sessions, Chat Model Configuration). The Copilot CLI smoke test is registered only for packaged builds, and its one test is it.skip. No test needed a real sign-in.

After the final rebase onto main b575e28 (head 25818fc; conflicts were import lists and two tests both sides added, all kept), with the same variables unset:

Command Result
npm run typecheck-client 0 errors
npm run eslint -- <the 103 .ts/.js files changed vs origin/main> clean
npm run valid-layers-check pass
./scripts/test.sh --reporter dot --grep "AgentHost|Chat" 12,661 passing, 1 failing, 70 pending. The failure was main's updated base-branch test seeding session.db after the session's state is central; fixed in 25818fc, then --run src/vs/platform/agentHost/test/node/agentHostGitStateService.test.ts: 78 passing, 0 failing
./scripts/test.sh --reporter dot --run copilotAgent, worktreeIsolation, agentHostSessionStateStore, agentHostSessionStateOwnershipGuard, agentSideEffects, agentHostCheckpointService, sessionDatabase (src/vs/platform/agentHost/test/node/) 1,272 passing, 0 failing, 1 pending

Main bumped @github/copilot-sdk to 1.0.22-preview.2 after the last local E2E run; the private npm feed rejected the local install, so that SDK version is validated by CI only.

Every behaviour fix has a mutation-checked test: the reverted change makes the test fail.

Not in this PR (follow-up issues)

  1. Codex peer chat overlays are never deleted.
  2. Sweep storage folders that already leaked from deleted sessions.
  3. Checkpoint refs leak in repositories of folders a session no longer uses.
  4. Copilot fork and side chats copy the source session's keys into the new chat's database.
  5. Per-chat overrides for session config (absorbed into Block 3b, configuration scopes).
  6. Archiving or deleting a session removes a worktree other sessions still use.
  7. Session Changes should show only the chat's changes.
  8. Forked chats share checkpoint refs with their source.
  9. Codex sessions disappear from the list after a restart: they are marked as their own chat backing (pre-existing on main).
  10. MCP state in the session's customization list is last-writer-wins across chats (pre-existing on main).

@sandy081 Sandeep Somavarapu (sandy081) added this to the 1.143.0 milestone Oct 14, 2026
Copilot AI balanced review requested due to automatic review settings October 14, 2026 19:53

Copilot AI 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.

🟡 Changes recommended

One or more issues must be addressed before approval.

3 open findings
What changed in this PR

Separates session-wide state from chat-owned data to support future chat moves while preserving downgrade compatibility.

Changes:

  • Routes session metadata through central state and compatibility mirrors.
  • Passes authoritative settings through chat contexts and redirects chat-row persistence.
  • Updates service wiring, tests, and architecture documentation.
File Description
src/​vs/​platform/​agentHost/​test/​node/​sessionStorageIdentity.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​sessionArtifactRemoval.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​sessionAdditionalWorktrees.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​missionControlSdkEventSource.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​codex/​codexModelRefresh.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​codex/​codexChatDiscovery.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​codex/​codexAgent.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​claudeAgent.integrationTest.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​chatMetadataTestHelpers.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentSessionRegistry.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentServiceTestUtils.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostUtilityModelService.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostTurnTelemetry.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostTurnHangTelemetry.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostToolCallTelemetry.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSessionTitleController.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSeams.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSavedChatService.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostReviewService.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostReviewService.integrationTest.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostPullRequestOperationProvider.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostPullRequestOperationHandler.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostLocalTurns.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostDatabase.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostCustomizationEnablementService.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostContributions.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostCommitOperationHandler.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostChangesetStrategy.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostChangesetCoordinator.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostCatalogSyncService.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​node/​agentHostCatalogReconciliationService.test.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​test/​common/​sessionTestHelpers.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​shared/​sessionAdditionalWorktrees.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​shared/​persistSessionMetadata.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​sessionStorageIdentity.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​missionControl/​missionControlSdkEventSource.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​compatibleSessionDatabase.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​compatibleAgentHostDatabase.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​chatContributions/​worktreeAnnouncement/​worktreeAnnouncementContribution.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​chatContributions/​sessionWorkspaceConversion/​sessionWorkspaceConversionService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​chatContributions/​sessionFlags/​sessionFlagsContribution.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​chatContributions/​persistedFailedTurns/​persistedFailedTurnsContribution.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​chatContributions/​chatDraft/​chatDraftContribution.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​chatContributions/​additionalWorktreeLifecycle/​additionalWorktreeLifecycleService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentSideEffects.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentSessionRegistry.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentServiceComposition.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostUtilityModelService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostTurnStarter.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostSkillCompletionProvider.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostSessionTitleController.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostServices.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostSavedChatService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostReviewService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostPullRequestOperationProvider.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostLocalTurns.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostGitStateService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostDatabase.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostCustomizationEnablementService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostChatInputService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostChatCatalogV2.md Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostChangesetCoordinator.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostCatalogSourceResolver.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostCatalogReconciliationService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentHostBootstrap.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​node/​agentChatContext.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​common/​sessionDataService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​common/​meta/​vscode/​agentDevContainerWorktreeMeta.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​common/​meta/​agentDevContainerWorktreeMeta.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​common/​agentHostCheckpointService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​common/​agentHostChangesetService.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​common/​agent.ts Updated as part of this pull request.
src/​vs/​platform/​agentHost/​AGENTS.md Updated as part of this pull request.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Base: 53da99bc Current: be4c63b7

No screenshot changes.

Test-only fixtures for Block 3a. writeLegacySessionState writes the
session.db, peer db and agent-host.db state a 1.142, 1.143 or 2b build
leaves for a Copilot session with a default chat and peers in the same
and a different folder (drafts, local and failed turns, checkpoint refs,
git/gitData, changes, titles, peerChats, storage identities, legacy chat
catalog and catalog payload). readOldBuildView reads back exactly what
those builds read, so later tests can assert an old build still sees the
same state after a newer build writes it. InMemorySessionDataService
keeps real in-memory SessionDatabases alive across simulated builds.

Co-authored-by: Copilot <[email protected]>
…w filter

Block 3a C1. agent-host.db migration 15 adds the session state tables
(session_state, session_state_values, session_folder_state,
session_branch_changesets, session_chat_state, chat_turn_checkpoints,
session_checkpoint_repositories, chat_row_mirror). They are additive;
older builds skip the version and never read them. IAgentHostDatabase
gains their API (import, CAS write, mirror and row acknowledgements,
checkpoint index and sequence, row mirror bases, storage references,
garbage), translated to storage spelling by CompatibleAgentHostDatabase.
Tombstone, exclusion and both unregistrations delete a session's rows and
markers; a provider-absent exclusion keeps them.

session.db gets no schema change. setForeignRows records the row owner
and the turn ids an older build kept for other chats; turn scans,
truncation and the conversation check ignore them (read from the
persisted keys in each statement, so every connection agrees), while
getAllCheckpointRefs still returns every ref. A fork remap drops them
from the copy, and the checkpoint parent fallback skips foreign refs.

Co-authored-by: Copilot <[email protected]>
Block 3a C2. IAgentHostSessionStateStore owns session-level values,
per-folder git state, branch-changes blobs and legacy-catalog chat
summaries, authoritative in agent-host.db.

- load imports a session once from the old format older builds keep in
  session.db (values, git maps, base branch, blobs, chat titles, read
  flag, directories, changes), lazily and without creating storage. On
  the first load in a process it reconciles: per entry, a mirror that
  differs from the recorded merge base was edited by an older build and
  wins; otherwise central state wins and stale mirrors are rewritten,
  which also repairs a crash between the two writes.
- Writes go to agent-host.db first; their old format is written per
  entry, coalesced per session (250 ms), and the revision acknowledged
  only once every entry is mirrored. noteMirrored lets callers that wrote
  the mirror themselves skip the rewrite.
- Operations on a session share one exclusive section keyed by its
  storage directory; re-entrant calls throw instead of deadlocking.
- readWithoutImport and refreshFromMirror serve sweeps and provider
  writes the host cannot route.

The registry in agentHostSessionStateMirror.ts is the frozen key format.
The node layer may now import async_hooks for the re-entrancy guard.

Co-authored-by: Copilot <[email protected]>
Block 3a C3.1. Readers can keep their old-format parsing while their
source becomes central:

- legacyMetadata renders what session.db would hold for given keys if
  every mirror were current, and names the keys the store does not own
  (provider data, blobs, membership) for callers to read as before.
- catalogMetadataReference serves the catalog projection: owned keys
  centrally, the rest from session.db.
- readWithoutImport renders central state for imported sessions that are
  not loaded and never imports; readValuesWithoutImport serves sweeps
  over many sessions with one central read.
- readSessionStateValues reads any number of sessions in two statements.

Co-authored-by: Copilot <[email protected]>
…rol writers through the session state store

Co-authored-by: Copilot <[email protected]>
Worktree isolation, workspace conversion quarantine and CopilotAgent
session-level owned keys now use store.writeMetadata with an Immediate
mirror. Adds gitState delete test, per-group tests, and hardens
fire-and-forget project resolution writes.

Co-authored-by: Copilot <[email protected]>
…e store

Whole folder-map writes (agentHost.gitData / agentHost.githubData) now map to
per-folder central entries, and the migration writer uses the store with an
Immediate mirror. The unowned single-folder key stays deleted until C4 renders it.

Co-authored-by: Copilot <[email protected]>
… repair earlier imports

The session state import read the Copilot launch pin (copilot.workingDirectory(ies)) only when the session URI's provider was `copilot`, which is never the case for `copilotcli:` or `ahp-session:` sessions. Sessions without agentHost.sessionWorkingDirectories (most real ones) were imported with no launch folders, so their peers could not resume.

- Resolve launch folders from the chat's own Copilot pin, else the session db's, regardless of the URI scheme.
- Version the launch-directory backfill marker ('2'); sessions imported with the earlier marker get their empty launch folders resolved again on their next load, once.
- The compatibility fixture can omit agentHost.sessionWorkingDirectories, and tests cover copilotcli: and ahp-session: sessions without it.

Co-authored-by: Copilot <[email protected]>
…s on main

A cold peer resume compared its folder with central defaultChatWorkingDirectory and had no fallback to the session db's Copilot pin, so a peer without its own pin failed with "missing working directory", and a peer of an archived session resolved as its own workspace: worktree isolation then read the peer's (unset) archived state and tried to recreate the session's deleted worktree.

- Fall back to the session db's copilot.workingDirectory, and compare with it when the host supplies no default-chat folder (read lazily).
- A peer of an archived session resumes through the session, so it gets the repository root for history and never recreates the worktree.

Co-authored-by: Copilot <[email protected]>
…log is normalized

The session state store fixed a session's catalog authority when it loaded it. A new session is loaded before its normalized catalog is registered, and a legacy session can be loaded before its catalog is migrated, so the store kept mirroring such a session's chat fields the legacy way: title writes landed as customChatTitle:<defaultChat> in session.db (main writes no such key there). Under slow I/O the coalesced mirror flush lands inside "rename_chat replaces live and persisted default and peer chat titles", which then fails.

- IAgentHostSessionStateStore.noteCatalogNormalized: under the session's lock, flushes what was written while the catalog was a legacy one, then reloads the model with the normalized authority and drops its legacy chat mirror entries.
- AgentService calls it after a new session's catalog is registered and after a catalog migration.
- The rename test drains the store's mirrors before reading session.db, so it fails without the fix at any I/O speed; the sole-default-chat rename test is back to main's expectation.

Co-authored-by: Copilot <[email protected]>
An annotation change is written to session.db in the background. When the session was dropped from memory and restored before that write landed, the restore read the previous annotations and the change disappeared from live state (pre-existing on main, intermittent under slow I/O in "annotations survive session state restoration"). A restore now waits for the latest write of the same annotations.

Co-authored-by: Copilot <[email protected]>
…added lines as zero in session diffs

The file-edit aggregation diffed a created file against empty content, and the line diff counts that content's single empty line, so a new one-line file reported +1 -1, while the file-edit tracker and Git report +1 -0. The session changeset therefore changed counts depending on which computation ran last, and "session changeset aggregates provider edits from default and peer chats" failed whenever a later recompute replaced the one it sampled (pre-existing on main; failing on Windows CI).

Co-authored-by: Copilot <[email protected]>
…instead of computing

When the live branch diff is unavailable (Git fails or returns nothing in a Git repository), the changeset service keeps the earlier result. Main seeded that result from the stored branch diff blob, so a failed refresh showed the stored files as ready. This build no longer reads those blobs back (decision D3), so after a restart there is no earlier result and the changeset stayed computing forever, logging nothing. With no earlier ready or error result, the failure is now reported as a computeFailed error; a later successful computation replaces it.

Co-authored-by: Copilot <[email protected]>
…branch diffs

The failed-first-computation test also runs with the branch diff blobs an older build left in session.db (plain, folder-scoped and legacy keys): they are not read back, and the changeset still ends in an error instead of computing.

Co-authored-by: Copilot <[email protected]>
…lemetry test

Each send follows its chat's asynchronous preparation, and the test gave the three sends a budget of 50 macrotask ticks. On a loaded macOS runner the peer chat had not sent within that budget, so its sent context was missing (CI failure on 775e668). The test now waits for the third send itself.

Co-authored-by: Copilot <[email protected]>
…me folder precedence

Review follow-ups for the 3a fixes:
- noteCatalogNormalized is a cache refresh that never fails its caller: a failed refresh is logged and retried by the session's next locked load, so a committed migration no longer fails on it. The migration notes in a finally, so one that committed and then stopped still refreshes.
- A missing session state after the flush is logged instead of silently keeping the legacy authority.
- A cold peer without its own pin resumes in the live default session's folder before the host-supplied launch folder, as on main; a test pins that precedence.

Co-authored-by: Copilot <[email protected]>
…tore test

The test asserted session.db 50 ms after a coalesced write to a store with a 5 ms flush delay. On a loaded macOS runner the timed flush had started its write but not finished it (CI failure on 4b989f9). The test now waits for the timed write to start and then for that write.

Co-authored-by: Copilot <[email protected]>
… terminal state

An archived session's worktree is removed, so its branch computation finds no Git repository (nonGit) without logging, and the status was restored to the previous one: computing, because stored branch diffs are not read back after a restart (D3). Main showed the stored diffs as ready; this build stayed computing. 69f2120 ended only the 'failed' kind. Now every branch computation without a result (failed, nonGit, or a session database that cannot be opened) restores an earlier ready or error result, and otherwise ends in a computeFailed error with a warning.

Co-authored-by: Copilot <[email protected]>
…write per publish

Publishing a legacy-catalog session's peers wrote each peer's working directories to the session state store in its own transaction with an immediate mirror flush, for every peer and on every membership change, also when nothing changed. With 1001 peers a single upsert made about 10,000 SQLite statements (0.2 s on main, 1.3 s here, and a timeout under slow I/O in "does not truncate authoritative current membership writes"). The peers' working directories are now recorded in one exclusive write per publish, only for peers whose central directories differ, and not at all when no peer changed. Each peer's own database is still written as on main.

Co-authored-by: Copilot <[email protected]>
…he session flag tests

The session flag and sandbox config tests waited 25 ms for the store's background write and then read session.db. On a loaded Windows runner the write had not landed (CI failure on ac9beb4), and with slowed SQLite all five fail. The writes are queued on the store synchronously when the action is dispatched, so the tests now await the store's whenIdle instead.

Co-authored-by: Copilot <[email protected]>

@deepak1556 Robo (deepak1556) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Would be a good candidate to use stacked PR.

@sandy081
Sandeep Somavarapu (sandy081) merged commit 83caa64 into main Oct 15, 2026
36 of 38 checks passed
@sandy081
Sandeep Somavarapu (sandy081) deleted the agents/block3a-session-state-authority branch October 15, 2026 07:06
Alexandru Dima (alexdima) added a commit that referenced this pull request Oct 18, 2026
… restoreSession tests (#342389)

`a queued toggle still publishes when the session was evicted while it
waited` dispatched two archive toggles and then waited a fixed 30
`timeout(0)` ticks (~120 ms in the Electron renderer, where chained
zero-delay timers are clamped to ~4 ms) before asserting. The first,
queue-holding toggle awaits a session-state-store write and a catalog
write; on a slow Windows runner those outlasted the tick budget, so the
queued second toggle had not run yet and both the eviction and the
publish were still missing.

The test was also vacuous: since agent-host.db became authoritative for
session state (#341626), passive toggles write through the session state
store, so the `HookedDb.setMetadataValues` hook that was meant to evict
the live session while the second toggle waited never fired. The second
toggle took the live path, and residency released the newly archived
session afterwards, which still satisfied the assertion.

Evict the live session from the holder's session-state-store write and
await that eviction and the session's `root/sessionSummaryChanged`
notification instead of counting ticks, and also assert that the
eviction happened while the toggle was queued.

Apply the same treatment to the remaining tick-counted waits in
`restoreSession`: `passive metadata publishes before central catalog
synchronization completes` now awaits the publish, and the
`StartupRaceAgent` tests await signals for migration start and the
first metadata read instead of a 50-tick `advanceUntil`.

Co-authored-by: Copilot <[email protected]>
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.

6 participants