Repository navigation
agentHost: make the orchestrator own session enumeration and chat lifecycle - #329633
Merged
Sandeep Somavarapu (sandy081) merged 86 commits intoAug 12, 2026
Merged
Conversation
Make the orchestrator (AgentService + AgentHostStateManager) own the Session
concept - identity, lifecycle, and grouping - so the agent harness talks only in
chats. Session provisioning stays agent-specific but is now invoked through the
chat surface instead of a Session-typed method, honoring "represent, don't
orchestrate".
- Create: `_provisionSessionViaDefaultChat` allocates the session URI and drives
`chats.createChat(defaultChatUri, { provisionSession })`; the agent's
provisioning runs inside creating the default chat and returns
`IAgentCreateChatResult.provision`.
- Dispose: routes to `chats.disposeChat(defaultChatUri)`.
- Enumerate: `_enumerateProviderSessions` groups `listConversations()` into
sessions via the default-chat URI convention.
Gated per harness by `IAgent.orchestratorOwnsSession` (Codex, Claude, Copilot all
opt in). Storage-preserving: session URIs and the derived `sdkSessionId == session
raw id` (I3) are unchanged, agents read/write the same SDK stores, and
providerData / PEER_CHATS_METADATA_KEY / protocol types are untouched. The legacy
createSession/disposeSession/listSessions remain as the delegated fallback.
Co-authored-by: Copilot <[email protected]>
…ingle path Address review feedback: the agent should not declare an orchestration policy, and the interface should not carry an optional flag that splits behavior. The opt-in was transitional scaffolding for a per-agent rollout; all harnesses have migrated, so remove it and make the orchestrator drive the chat surface unconditionally. - Remove `IAgent.orchestratorOwnsSession`; make `listConversations` required. - `AgentService` always provisions (non-fork/import) / disposes / enumerates through the chat surface; no per-agent branch. - Drop the flag from Claude/Copilot/Codex. - Make both test mocks first-class chat-surface agents (provisionSession bridge, default-chat disposeChat, listConversations) so their existing createSession/ disposeSession assertions still hold via the bridge. - Update the routing test to assert session create/dispose now also flow through the chat surface; refresh the architecture doc. Storage-preserving; no protocol/data change. Co-authored-by: Copilot <[email protected]>
Shorten the JSDoc/inline comments added for the session-ownership relocation to 1-2 sentences per the coding guidelines; drop obvious per-field comments. No behavior change. Co-authored-by: Copilot <[email protected]>
Remove `listSessions` and `getSessionMessages` from the IAgent contract - they are superseded by `listConversations` and `chats.getMessages`. Reroute the one remaining internal caller (the restore metadata catalog fallback) to `_enumerateProviderSessions` (which uses `listConversations`). The harnesses keep those methods privately as the implementation their chat/conversation bridges delegate to. `createSession`/`disposeSession` stay on IAgent as the session-lifecycle provisioning primitives the chat-surface bridge delegates to; `createSession` is also still used directly for fork/import, whose session id is minted server-side (sessions.fork) and so cannot fit the orchestrator-allocates-URI seam - left as a documented follow-up. No behavior change; storage-preserving. Co-authored-by: Copilot <[email protected]>
Align the single-item metadata lookup with the chat-addressed conversation surface: the method is now keyed by a chat URI and returns IAgentConversationMetadata, mirroring listConversations. All five implementers (Copilot, Claude, Codex, and both test mocks) derive the session from the chat URI and return chat-keyed metadata; the orchestrator maps the default-chat URI back to a session when hydrating restore metadata. Also reframe the fork/import createSession path in MULTI_CHAT_ARCHITECTURE.md from a deferred follow-up into a permanent, by-design exception (the fork id is minted server-side by the SDK, so the orchestrator cannot pre-allocate the URI). Co-authored-by: Copilot <[email protected]>
…sions-design-review # Conflicts: # src/vs/platform/agentHost/node/codex/codexAgent.ts
…c by design Document why the field keeps the SessionMeta alias rather than a conversation-specific type: _meta is the protocol's open property bag on SessionState / SessionSummary, carried through verbatim. Co-authored-by: Copilot <[email protected]>
…ssion URI Document that the session parameter is the provider's own SDK session (the SDK's terminology), NOT the AH-level Session grouping - that grouping lives in the orchestrator and the agent only ever deals in chats. The URI backs the default chat (invariant I3), so chats.disposeChat routes here when a default chat is disposed; peer chats go to _disposeChat. Teardown disposes that SDK session plus the peer-chat backings the agent parents under it. Co-authored-by: Copilot <[email protected]>
Add a 'session is overloaded' convention table to the Mental Model section: in the protocol/orchestrator 'session' means the AH grouping; inside an agent harness it means the provider's own SDK session (Codex: thread); at the IAgent seam the session URI is a shared identity (AH-minted, SDK-session-id raw id per I3). Explains why we do not rename the provider-internal 'session' symbols. Co-authored-by: Copilot <[email protected]>
…ession->chat) Revert the chat-keyed enumeration surface (listConversations / getConversationMetadata) back to session-keyed listSessions / getSessionMetadata on IAgent. Chat-keyed enumeration forced every harness to derive default-chat URIs via buildDefaultChatUri for cold (SDK-discovered) sessions it never created in-process - re-deriving the session<->default-chat encoding that belongs to the orchestrator/protocol. Now each agent returns its own SDK-session identity (AgentSession.uri: provider scheme + SDK id, no protocol-chat knowledge) and the orchestrator owns the session->chat mapping. Drops the orchestrator's _conversationToSessionMetadata bridge (the enumeration/restore round-trip) and deletes the now-unused IAgentConversationMetadata type. Co-authored-by: Copilot <[email protected]>
Agents no longer call buildDefaultChatUri. Outbound events, default-vs-peer comparisons, and session-or-chat normalizers now reuse the chat URI the agent was already given - read back from the session entry's stored defaultChatKey (new getter on AgentSessionEntry) or the live session's stored chat channel, or tested with isDefaultChatUri - instead of re-deriving it from the session URI. The one irreducible conversion (a session URI first born inside the agent: a freshly forked SDK-assigned id, or a cold-restore/create seed) is centralized in a single node-layer helper, defaultChatUriForSession, in agentPeerChats.ts. This is creation-time only; no runtime routing/event path derives chat URIs anymore. Co-authored-by: Copilot <[email protected]>
The provision (create) path already hands the agent the orchestrator-allocated
default-chat URI via createChat(defaultChatUri, { provisionSession }). Claude and
Codex decoded it to a session and then re-derived the identical URI inside
createSession. Thread the supplied chat URI straight through (createSession's new
optional defaultChat argument) so the agent seeds its entry with the URI it was
handed instead of re-deriving the session-to-default-chat mapping itself.
Copilot has no synchronous create seed (it stores a provisional session and
seeds the default-chat key at materialize/resume), so it has no provision
round-trip to thread; its derivations are the restart-lazy category.
The remaining defaultChatUriForSession callers are the restart-lazy paths (cold
resume, peer-send provisional default, fork/restore materialize) where the
orchestrator supplies no chat URI in-call; documented as the single sanctioned,
irreducible conversion. Behavior is unchanged (the mapping is deterministic);
two Claude tests that deep-equal the emitted URI object are aligned with the
file's toString-based convention since keying now populates the URI's cache.
Co-authored-by: Copilot <[email protected]>
Make Agent Host own chat membership and pass contextual data only for individual operations. Providers route exact chats to their SDK conversations without deriving default or peer roles. Co-authored-by: Copilot <[email protected]>
…sions-design-review Co-authored-by: Copilot <[email protected]>
Post-merge repairs and review follow-ups for the AH-owned multi-chat architecture, keeping providers on exact chat-to-SDK bindings: - Make `IAgentChats.releaseChat` mandatory so AgentService has one exact-chat release path with no optional legacy fallback; Claude, Copilot, Codex, and the test agents implement it explicitly. - Copilot chat disposal now propagates SDK deletion failures (preserving routing/state for retry) but tolerates an already-deleted session via an O(1) `getSessionMetadata` recheck, keeping a partially-completed multi-chat teardown retry-safe. - Claude: gate materialization on post-await cancellation, abort every live session's controller on dispose, and restore session-addressed resume without inferring chat membership from the URI. - Rename `IAgentCreateChatOptions.provisionSession` to `newSession` to state intent (this createChat creates the owning session). Verified typecheck, transpile, AgentService/Claude/Copilot/Codex unit suites, valid-layers, and hygiene.
Copilot's `chats.getMessages` routes to `_getChatMessages`, which lacked the
subagent-session-URI branch that only lived in the now-orphaned
`getSessionMessages`. On the persisted replay/restore path the orchestrator
loads a subagent's turns through the chat surface, so reopening a session
rebuilt an empty subagent transcript — failing the "reopening a session keeps
sub-agent messages out of the parent transcript (replay path)" E2E test on all
platforms. Extract a shared `_getSubagentMessages` helper and route subagent
URIs through it from both `_getChatMessages` and `getSessionMessages` (matching
Claude, which already shares one path).
Also address PR review feedback:
- `AgentService._releaseSession` releases every catalog chat even if one
rejects, then propagates the first error (idle eviction has already dropped
the session state, so a skipped leaf would stay resident indefinitely).
- `CopilotAgentSession` stores the host-supplied `IAgentChatContext.resource`
as its persistence scope instead of re-deriving it from the mutable chat
channel via `isDefaultChatUri`, so an explicitly chosen resource survives a
later `bindChatChannel`.
- MULTI_CHAT_ARCHITECTURE.md: correct the flat `IClaudeChatBinding` shape
(`{ sdkSessionId, model? }`, no retained session/storageUri).
Co-authored-by: Copilot <[email protected]>
… chats
Removes the `newSession` seam so an agent no longer distinguishes "a chat for a
new session" from "a chat for an existing session". Session provisioning now
always goes through the agent's dedicated `createSession` + `chats.bindSessionChat`
(the same path fork/import already used), and `chats.createChat` has exactly one
meaning: add an additional chat to an already-provisioned session.
Contract:
- Delete `IAgentProvisionSession`, `IAgentCreateChatOptions.newSession`,
`IAgentProvisionResult`, and `IAgentCreateChatResult.provision`.
- Add `IAgentCreateChatOptions.inheritedContext` ({ workingDirectory, config }):
the orchestrator supplies the owning session's resolved context when creating
an additional chat, so the agent never reads it back from the parent session.
Orchestrator:
- `_createProviderSession` always provisions via `createSession` +
`bindSessionChat`; delete `_provisionSessionViaDefaultChat`.
- `_buildInheritedChatContext` resolves the AH-owned worktree/folder + session
config values and passes them to `chats.createChat`/`fork`.
Agents (Claude, Copilot, Codex):
- Drop the `if (options.newSession)` branch and the `_provisionChat` method; the
chat surface handles additional chats only.
- Claude/Copilot consume `inheritedContext` for the additional-chat working
directory (and Claude for its permission mode) instead of resolving the parent
session; remove the now-dead `_createSession(target)` plumbing where the
provision path was its only caller.
Tests/docs:
- Rewrite the AgentService routing test to assert provisioning via
createSession + bindSessionChat.
- Update MULTI_CHAT_ARCHITECTURE.md §2/§7 to the new seam.
Co-authored-by: Copilot <[email protected]>
Adds Codex multi-chat support (parity with Claude/Copilot): the
`multipleChats: { fork: true }` capability, `chats.createChat`/`chats.fork`
minting a fresh backing Codex thread per chat, `materializeChat` restore, and a
providerData codec. This is committed as the base of the dedicated I3-removal
branch (it is intentionally not on the PR branch).
Co-authored-by: Copilot <[email protected]>
Introduce AgentSessionRegistry, a durable, orchestrator-owned index of the sessions that exist, keyed by session URI and persisted as a JSON blob in a reserved session database with serialized read-modify-write. Wire it into AgentService: register on every createSession success and on restoreSession, unregister on true delete (disposeSession). Add a Stage 1 validation surface (getRegisteredSessions) plus component and parity unit tests. This is additive and does NOT yet drive enumeration; listSessions still uses the provider-derived path. It is the foundation for switching enumeration off invariant I3 in stage 2. Co-authored-by: Copilot <[email protected]>
…moval stage 2) Switch AgentService.listSessions to iterate the orchestrator-owned session registry instead of unioning each provider's listSessions(). Per-session metadata still comes from the agent's direct getSessionMetadata lookup (I3 keeps the default chat's SDK id == session id, so it resolves), then flows through the existing DB and state-manager overlays unchanged. This decouples AH enumeration from the agents' SDK stores: peer-chat backings and subagent sessions never enter the registry (so they cannot leak as top-level entries), and a provider that transiently drops a session from its own snapshot no longer evicts it. Idle provisional sessions are suppressed explicitly via a new state-manager predicate (isIdleProvisionalSession), preserving #321269 now that the registry — not the provider snapshot — is the session source. A one-time, marker-gated backfill seeds the registry from the legacy provider enumeration so hosts created before the registry keep their on-disk sessions. I3 is unchanged; agents are untouched. Adds backfill and transient-drop tests. Co-authored-by: Copilot <[email protected]>
Codex's default chat does not actively satisfy I3: a fresh session's raw id is an AH-minted provisional UUID while its backing thread id is app-server-assigned, with the real mapping persisted in the per-session metadata overlay. The residual sessionId == threadId uses (_readSession's ?? sessionId fallback and listSessions' thread->URI mapping) are legacy-compat shims for pre-existing sessions whose persisted identity is the thread id; they cannot be removed without a data migration (disallowed), so Codex is treated as already I3-satisfied. Comment/doc-only: clarifies the two shim sites and adds a per-agent nuance note to the I3 invariant in MULTI_CHAT_ARCHITECTURE.md. No behavior change. The active I3 removal targets are Claude and Copilot. Co-authored-by: Copilot <[email protected]>
…onChat (I3 removal stage 4, step 1)
Add an optional chat-surface entry, chats.createSessionChat, that provisions a
session AND binds its session-backed (default) chat in one call — the
replacement for the IAgent.createSession + bindSessionChat provisioning pair.
The agent reuses the session id as its SDK id (id-reuse kept; no storage
change, no I7 for the default chat). The orchestrator mints the session URI,
derives the default-chat URI, and calls createSessionChat; agents that don't
implement it fall back to the create-then-bind pair.
Claude implements it via its existing { kind: 'chat' } provisioning path (also
used by truncate), so routing state is identical to create-then-bind. Only
fresh sessions collapse: fork and import mint a fresh SDK-assigned session id
inside the agent, so the orchestrator can't know the default-chat URI up front
and keeps them on the create-then-bind pair. bindSessionChat is now documented
as the restore-time counterpart.
Additive and always-green: Copilot/Codex still use createSession. Validated
typecheck, layers, eslint, hygiene; Claude units 206, AgentService 140, Claude
E2E replay 8.
Co-authored-by: Copilot <[email protected]>
… removal stage 4, step 2) Both agents now provision a fresh session and bind its session-backed (default) chat through the collapsed chats.createSessionChat entry, delegating to their existing _createSession and then binding the default chat (id-reuse; no storage change, no I7 for the default chat). The orchestrator already prefers this path for fresh sessions across all providers; fork/import still use createSession. Validated typecheck, layers, eslint, hygiene; Copilot 347, Codex 47, AgentService 140 units; E2E replay Copilot 15 / Codex 6 / Claude 8. Co-authored-by: Copilot <[email protected]>
…removal # Conflicts: # src/vs/platform/agentHost/test/node/agentService.test.ts # src/vs/platform/agentHost/test/node/copilotAgent.test.ts
…removal # Conflicts: # src/vs/platform/agentHost/node/agentSideEffects.ts # src/vs/platform/agentHost/node/copilot/copilotAgent.ts
…removal # Conflicts: # src/vs/platform/agentHost/node/agentPeerChats.ts
…removal # Conflicts: # src/vs/platform/agentHost/node/codex/codexAgent.ts
…removal # Conflicts: # .github/skills/sessions/SKILL.md # src/vs/platform/agentHost/MULTI_CHAT_ARCHITECTURE.md # src/vs/platform/agentHost/node/agentHostStateManager.ts # src/vs/platform/agentHost/node/agentService.ts # src/vs/platform/agentHost/node/copilot/copilotAgent.ts # src/vs/platform/agentHost/test/node/agentService.test.ts # src/vs/platform/agentHost/test/node/copilotAgent.test.ts
Member
|
useful summary I used to review |
Preserve upstream legacy-session adoption and read-state changes while keeping session ownership in Agent Host and provider operations exact-chat addressed. Co-authored-by: Copilot <[email protected]>
Sandeep Somavarapu (sandy081)
enabled auto-merge (squash)
August 12, 2026 09:22
Enrich generic legacy subagent summaries from reconstructed task descriptions while preserving persisted and user-defined chat titles. Co-authored-by: Copilot <[email protected]>
Dirk Bäumer (dbaeumer)
previously approved these changes
Aug 12, 2026
Prefer reconstructed task descriptions over generic migrated chat-summary labels while retaining catalog-title fallback for legacy records without tool metadata. Co-authored-by: Copilot <[email protected]>
Benjamin Christopher Simmonds (benibenj)
approved these changes
Aug 12, 2026
Misha Damjanic (mdamjanic7)
added a commit
to mdamjanic7/pihub
that referenced
this pull request
Aug 24, 2026
…d work - docs/pi/plans/peer-chat-fork-phantom-session.md: investigation, root cause (pi deferred-write forks), and the implemented design. - docs/upstream-watchlist.md: canonical registry for work waiting on upstream signals; first entry tracks adopting upstream's disposeChat ordering fix (microsoft#329633) and deleting the pre-fix phantom row once the delete guard is live. - architecture.md/invariants.md: peer-file ownership, relocation-only- after-confirmed-exit, and fail-closed deletion invariants.
Misha Damjanic (mdamjanic7)
added a commit
to mdamjanic7/pihub
that referenced
this pull request
Aug 24, 2026
Safe tip chosen per the 7-day library-age rule: the next upstream commit bumps @vscode/codicons to a build published 2026-08-19 (matures 2026-08-26); 213 deferred commits remain, also gated on vscode-json-languageservice 6.0.0-next.3 (matures 2026-08-28). Distro pointer moved (private repo — its deps verified separately). Key resolutions: - Core patches removed: management-channel thenable-trap workaround (upstream microsoft#330567 removed the async accessor; compactSession re-homed onto the synchronous _getManagementService), @xterm/* pins (upstream carets restored; all in-range versions mature), and the markdown-editor pin moved 0.0.2-59 -> 0.0.2-81 (still pinned: the caret's newest in-range builds are immature). - Chat-scoped IAgent migration (microsoft#329633): Pi/omp adapters moved to onDidChatProgress/onDidMaterializeChat/getChatMetadata/resolveChatConfig/ chatConfigCompletions/getChatCustomizations/listLegacyChatBackings; session enumeration now announces via onDidDiscoverChats; subagent restore is lazy via chats.getMessages with a peer-file claim-index fallback; default-chat disposeChat routes to session teardown; releaseChat/canReleaseChat wired for idle eviction; eager getSubagentSessions retired. Fork arrives via createChat options. - Fork patches kept and adapted: _resolveFreshestBranchRef worktree start point (track=true now keeps upstream's remote resolution), _filterStageablePaths retry, 30s diff-pipeline timeouts (extended upstream's _runGitStatus with a timeout pass-through), projectTrusted trust mirror via eagerCreate's canCreate + getProjectTrusted, utilityCompletion title seam (context-object signature), bare-layout getWorktreeLayout, model-config carry in chatWidget._acceptInput, untitled-draft sessions-list guard, ChatSummary.modelId init. - BYOK env override removed following upstream (root-config gated now); preferLongContext removal adopted (both context tiers always shown). - Copilot fire-and-forget project-resolution store now swallows session-teardown rejections (was an unhandled rejection racing dispose). Validation: compile-check-ts-native, pnpm rebuild, and pnpm run compile all green (0 errors); agentHost unit tests 6057 passing / 0 failing. Unit suites beyond agentHost not run; app not launched.
Misha Damjanic (mdamjanic7)
added a commit
to mdamjanic7/pihub
that referenced
this pull request
Aug 24, 2026
…ons) The orchestrator-owned registry (microsoft#329633) backfills via IAgent.listChatsToMigrate; returning undefined signals 'cannot enumerate yet', and the host retries the migration before EVERY protocol listSessions — so session listing (and opening any listed session) failed host-wide. pi and omp can always enumerate their on-disk catalogs: return them (one-time backfill; ongoing surfacing stays on onDidDiscoverChats). Adds a regression test pinning the never-undefined contract.
Misha Damjanic (mdamjanic7)
added a commit
to mdamjanic7/pihub
that referenced
this pull request
Aug 24, 2026
…oft#329633 fallout) The chat-scoped IAgent migration stopped calling `IAgent.createSession` on providers: the host now mints the session URI and provisions the session by creating its DEFAULT chat. Both native adapters still no-oped a default-chat `chats.createChat` (under the old contract that call was redundant), so after the merge NOTHING created the session. Two user-visible regressions followed from that single hole: - A composer draft surfaced in the Agents sidebar as soon as a folder was picked. The no-op returns no result, so `provisional` was lost, the host dispatched SessionReady and emitted `root/sessionAdded` immediately, and the idle-provisional filter (which requires lifecycle `Creating`) could not hide it. The row was announced with an empty title. - The first send failed with "Pi session not found" / "omp session not found", blocking every new chat, because the parent session was never registered. Route a default-chat create to the adapter's own session create instead — the exact inverse of `disposeChat`, where disposing the default chat already IS the session teardown — mapping the chat-create options onto a session-create config and the result back onto a chat-create result so the host receives `provisional`, the resolved working directory and the project again. `providerData` and `backingSession` stay unset: the default chat's backing IS the session, and reporting a backing session would suppress our own top-level row. Session-level fork (restore-checkpoint) also arrives as a default-chat create, so it was broken the same way. It is now forwarded, and `_createForkedSession` honors a caller-supplied session URI instead of always minting its own — the host commits to the URI before provisioning, so minting here would register the fork under an id the host never addresses. Re-provisioning an already-bound URI rebinds rather than forking twice, which would otherwise overwrite a live entry and orphan its child. A fork without a turn index falls through to a plain create, matching the pre-existing defensive fallback. Pi's imported conversations and omp's fork/import remain unsupported at the runtime level (unchanged behavior) but now log a warning instead of degrading silently. Regression tests pin default-chat provisioning and first-send materialization for both adapters, plus the fork identity and rebind behavior; this path had no coverage because the suites called the adapters' now-unreachable `createSession` directly. Also carries the one-line `onDidSessionProgress` -> `onDidChatProgress` rename the omp test file needed to compile. Known gap, tracked separately: `IAgentCreateChatOptions` carries no `projectTrusted`, so PiCode's Workspace-Trust mirror does not reach pi on this path and pi falls back to its own `defaultProjectTrust`.
Misha Damjanic (mdamjanic7)
added a commit
to mdamjanic7/pihub
that referenced
this pull request
Aug 24, 2026
…handoff Upstream microsoft#329633 routed session creation through chats.createChat, whose options bag never carried the fork-only projectTrusted field — so every newly created session silently lost the Workspace-Trust mirror and pi children spawned with neither --approve nor --no-approve. Symptoms: project skills (.pi/skills, .agents/skills) not loaded by pi and not advertised in slash completions (e.g. /upstream-sync-safe-commit), project-local pi inputs inert. Restored sessions with persisted trust were unaffected, which masked the break. (Verified in live logs: the renderer sent projectTrusted:true on createSession; the flag never reached the spawn.) The feature is fork-only (upstream has no projectTrusted anywhere), so this is a permanent product-intentional patch, recorded in docs/picode-patches.md: - IAgentCreateChatOptions gains the field (documented fork-only) - AgentService._toCreateChatOptions forwards it - PiAgent._createDefaultChat consumes it (stale NOTE removed) - MockAgent's test double mirrors it (it had replicated the drop) Tests: host-level handoff (trusted/untrusted/unspecified all cross) proven fail-before without the fix; spawn-level (createChat-created session with trust spawns pi with --approve).
Misha Damjanic (mdamjanic7)
added a commit
to mdamjanic7/pihub
that referenced
this pull request
Aug 24, 2026
Upstream microsoft#329633 collapsed session provisioning into chats.createChat on the default chat; both native adapters no-oped that call, so sessions were never created (premature sidebar row + every first send failing). The fix landed in f6d3f09 but the contract was only documented for the dispose direction. Record the symmetric create invariant so a future upstream refactor cannot quietly re-open the same hole.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This completes the Agent Host multi-chat ownership refactor:
createSessionChat); additional chats use exactcreateChat/forkoperations with transient host-owned context.AgentSessionRegistrydrives top-level enumeration and one-time legacy backfill, removing the host's dependency on I3/default-chat SDK-id reuse.Codex multi-chat
This PR enables multiple chats and chat forks for Codex in Agent Host. Live validation covered independent peer routing and transcript isolation, exact-chat sends, restart restoration, close/reopen, deletion isolation, and forking.
Known report-only model behavior: Codex can emit duplicate
create_chattool calls, andcreate_sessioncan select the wrong workspace. These do not change Agent Host chat routing or lifecycle ownership and are intentionally outside this PR.Codex E2E coverage
Codex host-only capability assertions and provider-independent conformance catalog/lifecycle scenarios are enabled and replay green.
Model-backed Codex peer/fork parity remains replay-gated with
supportsMultipleChatsE2E: false/supportsChatForkE2E: false. Focused live recording was attempted without accepting or hand-editing captures, but the current Codex live recording path fails before a usable model response (including the pre-existing simple-turn recording path). The focused reproduction and expected/observed behavior are recorded ine2e/KNOWN_ISSUES.md. Recording mode still enables these tests automatically once that environment defect is fixed.Validation and confidence
Validation was layered so protocol ownership, provider routing, persistence, and real UI behavior were checked independently.
Automated checks
npm run typecheck-client— passed after the final changes and after merging currentmain.npm run valid-layers-check— passed.git diff --check— passed.Authenticated live validation
The branch was run in Code OSS against real authenticated Copilot, Claude, and Codex providers. The following scenarios were exercised manually, one at a time, with exact AHP channels/provider/model routing checked in Agent Host logs rather than relying only on visible response text:
/btwside chats.session/chatAddedactions with no relevant resource, enrichment, unknown-chat, or restore errors.Regression comparison
Residual startup unknown-session actions and Codex model-readiness races were reproduced on current
main, classifying them as pre-existing rather than introduced by this refactor.Known limitations / report-only findings
create_chatcalls and selected the wrong repository forcreate_session.send_messagecalls; delivery to the child was deduplicated.These provider/model behaviors are recorded for follow-up and intentionally not changed by this ownership refactor.
Claude ownership audit
The Claude provider preserves the core invariant: each concrete AH chat maps to exactly one Claude SDK conversation. Its chat bindings retain only provider-owned backing data, exact-chat sends/forks/model changes target that binding, and default-chat lifecycle operations do not cascade to sibling chats.
ClaudeAgentSession/ SDKsessionIdterminology refers to Claude SDK conversations and is not itself an AH ownership leak.The audit did identify remaining session-neutrality debt in
claudeAgent.ts:AgentHostStateManagerto recover the child origin/parent chat. AgentService should eventually pass that origin/parent/tool-call context explicitly; Claude should only resolve the exact parent SDK backing to its child transcript._legacySessionChatBindingspreserves the historical AH-id-equals-SDK-id restore path. This is intentional compatibility debt, not sibling grouping or lifecycle cascading.These findings do not invalidate the PR’s tested exact-chat routing or lifecycle behavior, but they are called out explicitly as follow-up extraction work rather than claiming that Claude is already completely session-neutral.
Copilot ownership audit
Copilot’s chat-addressed surface is clean:
_chatBindingsmaps each concrete chat to one SDK conversation, opaqueproviderDataandbackingSessionare preserved, normallistSessions()is empty, legacy discovery is isolated, and create/send/fork/side-chat/dispose/release operations do not reconstruct or cascade through AH chat membership. Process-wide iterations are tied to the shared Copilot CLI process rather than an AH-session sibling cascade.Residual coupling is low severity:
AgentHostStateManagerfor narrow customization/session-metadata reads and prompt-cache metadata writes. This does not manipulate the catalog or infer default/peer membership, but it is an extra seam not represented by the desired transient-context boundary.chatId.startsWith("subagent/")as a restore fallback instead of relying exclusively onIAgentChatContext.origin. AgentService currently mirrors the same convention; longer term, origin should be supplied exhaustively and URI-shape checks centralized or removed._findAnySessionis an exact SDK-id lookup despite its broad name; renaming it would reduce future cascade risk.No Copilot catalog ownership, sibling lifecycle cascade, or provider-side default/peer grouping was found.
Codex ownership audit
Codex also keeps exact chat-to-thread bindings, round-trips opaque
providerData/backingSession, leaves catalog enumeration to Agent Host (listSessions()is empty; legacy listing is backfill-only), and disposes/releases only the addressed thread. It does not read Agent Host chat state for routing or construct subagent chat URIs; it emits provider signals and lets AgentService create catalog entries.One medium-severity boundary leak remains:
codexAgent.tscallsisDefaultChatUri(...)at three runtime gates (materialization, server-tool advertisement, andonDidMaterializeSessionemission). This decodes AH default-chat membership from URI shape inside the provider, contrary to the session-neutral boundary. The behavior should be driven by explicit transient provisioning intent from thecreateSessionChat/materialization path rather than parsing the chat URI.Additional observations:
disposeSession,releaseSession, and eager active-client defaults is confined to documented legacy compatibility paths.AgentHostStateManagertype only for session-title telemetry. It does not currently consume catalog state, but a narrower read-only title signal would better enforce the boundary structurally.The medium Codex finding does not change the tested exact-thread routing or lifecycle results, but is recorded as follow-up session-neutrality debt.
Audit follow-up scope
The remaining Claude, Copilot, and Codex session-neutrality gaps identified in the ownership audits are intentionally out of scope for this PR. I will address them in a separate follow-up PR so this ownership refactor can be reviewed against its tested routing, lifecycle, persistence, and restoration behavior without mixing in another boundary change.
Design notes
MULTI_CHAT_ARCHITECTURE.mddocuments the final ownership model, provider-specific I3 compatibility, registry/backfill behavior, multi-root/client-type propagation, and Codex capability status.Compatibility caveat
Subagent restoration is forward-compatible but not downgrade-compatible. Current code migrates legacy persisted subagent references to canonical
ahp-chat://subagent/...chats. If a profile that has persisted those canonical child-chat references is subsequently opened with an older Agent Host, the parent session and normal chats remain available, but that older host cannot resolve the canonical restored subagent chats because it only understands the former synthetic-session representation.