Repository navigation
agentHost: resolve chat owners from recorded ownership, not chat URIs - #341191
Conversation
Core of Block 1 (m1). The host no longer derives a chat's owning session, storage location or parent from the session encoded in its URI: - AgentHostStateManager records owner, storage resource and parent chat at registration (getChatOwner/requireChatOwner/getChatStorageResource/ getChatParent, findRetainedChatOwner for evicted/announced sessions). - AgentHostDatabase.findChatOwner reads the owner from the containing record (chats_v2 incl. tombstones, then session_chats, then the sessions_v2 payload); catalog chats expose ownerSession. Read-only, no schema change. - AgentService resolves cold chats via registry -> retained -> central DB -> registered-session default chats -> in-flight restores -> spawn edges in loaded chats; no URI fallback. Unknown-owner dispatch keeps today's IsRead/IsArchived rejections, otherwise a traced no-op. - Teardown uses owners captured at subscribe/request/registration time (subscriptions, GC, residency, input-request timing, workspace preparation, side-effect signals for removed chats). - Provider listings carry their session (IAgentListedChat). Behavior note: a canonical subagent chat whose parent is neither loaded, restoring, nor recorded in the catalog is now not found instead of restoring the parent decoded from its URI (agreed case C / D6). Clients restore the parent first; a subscribe joins an in-flight parent restore. Co-authored-by: Copilot <[email protected]>
Chat registration paths now accept an explicit storage resource. Restoring a session passes chats_v2.storage_resource from the normalized catalog for the default chat, peers and restored subagents, and threads it into hydration, provider chat contexts, history reads and workspace transitions. The owner+URI-shape rule is kept only as the creation-time rule (creationTimeChatStorageResource) for brand-new chats and legacy sources that record no storage. A recorded storage resource is never overwritten by re-registration or summary refresh. No behavior change for existing data: for unmoved chats the stored storage_resource equals what the creation-time rule computes. Co-authored-by: Copilot <[email protected]>
Node services and chat contributions take a chat's owning session from the in-memory registry, host-passed hook payloads, or owners captured at registration, instead of decoding the chat URI: - Telemetry reports, turn/tool-call trackers and session-open telemetry carry the recorded owner for attribution. - Chat contributions record the owner passed with every hook payload; `_owningSession` URI parsing is removed. - Turn service, chat input, automation, customization enablement, git state, completion provider, review, PR status, changeset services, session title, workspace context and input-needed use registry owners. - Teardown paths use captured owners: the changeset file monitor records each watch's session when tracking starts, workspace context records chat owners before release. - Persisted turn usage, turn delegation and the chat context use the recorded storage resource (hydration passes it explicitly). Legacy per-session peerChats entries now belong to the session whose database contains them. An entry is skipped when the live registry or the central catalog (chats_v2 incl. tombstones, then session_chats, then catalog payloads) records the chat under another session or as deleted. Behavior change: an entry whose URI encodes another session but has no central record is now accepted for its containing session instead of being skipped. No writer produces such entries, so the case is believed unreachable; unmoved chats behave as before. Co-authored-by: Copilot <[email protected]>
…hared code Providers and shared host code receive a chat's owning session and storage from the host instead of decoding the chat URI: - Copilot uses the session's recorded owner for server tools, MCP, edit tracking, discovery logging and history mapping (mapSessionEvents takes the routing session). - Claude sessions, pipelines and routers carry the owning configuration scope; subagent edit chats and retained terminal output use it. - Codex records each binding's storage resource from the host context and uses it, with the recorded configuration scope, for turn-id persistence and retained command output. - Subagent spawn events take the spawning chat's owner from a lookup (registry, Claude chat scope, Copilot recorded chat scope). - Server tools resolve the executing chat's owner from the registry; session server tools use an accessor owner lookup. - Local commands and Mission Control use registry owners. - Edit attribution, survival and arc telemetry take the owning session explicitly; storage-keyed tracking is unchanged. - MCP controllers take their owning session; channel parsing no longer checks the provider via the URI, since providers reject chats they do not host. - Changeset URIs report a session only for session- and folder-owned changesets; chat-owned changesets resolve their session through the recorded owner (changesetSession). Cold changeset subscriptions resolve and restore the owner through the host's cold owner resolution; session teardown disposes changesets of the chats registered to it. - Chat attachment links and plan links are built from the recorded owner. Unknown owners on non-teardown paths keep today's no-op outcomes. Existing chats keep today's behavior: their recorded owners and storage equal what the URI encoded. Co-authored-by: Copilot <[email protected]>
Client code takes a chat's owning session from session state, session catalogs or host session records instead of decoding the chat URI: - Sessions provider: a completed chat turn keeps alive the session whose catalog lists the chat; context-reference links use the session's backend resource. - Subagent opener: the owner is the session of the spawning chat (parentSessionResource) or the session whose chat maps to the backend subagent chat; legacy subagent-session parents are still supported. - Remote session source, inspector and router: a chat listed in the backend session's own catalog belongs to that session. - Session handler: tool confirmation metadata reads the chat from the subscribed session state that lists it; restored subagent chats use the catalog resource or the canonical chat minted under the parent. - Usage sidecar: the owner of a default chat comes from the emitting host's session records (recorded default chat, else the forward default chat). - Chat reference chips resolve the owner when clicked: held session state, then the local host's and each connected remote host's session records. buildOpenSessionLinkForChatResource is removed. Behavior changes, all for chats whose URI does not encode the session that lists them (none exist for VS Code hosts today): remote inspection and messaging use such a chat instead of rejecting it; host-assigned opaque chat URIs now resolve through session state, so tool confirmations keep the tool call metadata like VS Code-shaped chats; a chat reference to a chat no host lists does nothing instead of opening the session decoded from its URI. Co-authored-by: Copilot <[email protected]>
Removes parseRequiredSessionUriFromChatUri, parseDefaultChatUri, chatStorageUri and resolveChatUri, and narrows parseChatUri to the chat id: the session a chat URI was minted for is no longer readable, so a chat's owner and storage can only come from the records that contain it. Chat URIs are still minted from their session. Tests: - A mismatch oracle restores and creates chats whose URIs encode a session of an unregistered provider under another owner with recorded storage; ownership, configuration owner, cold owner resolution, provider routing, provider contexts and storage all follow the records, and the encoded session is never touched. - Cold subscribe restores the session whose normalized or legacy record contains the chat; a chat of a deleted session and an unknown chat are not found, and the encoded session is never restored. - Test fakes that emulate hosts use a shared test-only helper for the session they minted a chat URI for. Also restores import formatting that earlier milestone commits collapsed and documents chat ownership in the agent host AGENTS.md. Co-authored-by: Copilot <[email protected]>
Legacy per-session peerChats entries are owned by the session whose database holds them unless the live registry or the central catalog records the chat under another owner or as deleted. The central check now uses one batched read-only lookup (findChatOwners) for all entries of a catalog, bounded by the existing import limit, instead of one query per entry. findChatOwner delegates to it. The peer store test now covers: an entry recorded centrally under another owner (skipped), an entry tombstoned centrally (skipped), an entry live elsewhere (skipped), and an entry whose URI encodes another session with no central record (accepted for the reading session). The last case is the behavior change already noted in the m2 commit (no known writer produces such entries). The database test checks batched and single lookups agree. Co-authored-by: Copilot <[email protected]>
Usage sidecar: - An owner lookup returns the matching session directly instead of caching every listed session and reading the target back, so a target listed among more sessions than the cache holds is no longer evicted. Only resolved owners are cached. - Records are queued per host, and the cache is re-checked when a queued step runs, so a burst during the first lookup lists the sessions once and a slow host no longer blocks the others. - Each step catches and traces its failure, so a failing listing no longer stops later records. - Held session state is checked before listing the host's sessions. Chat reference owner resolution: - Hosts' session records are queried in parallel with a per-host timeout (traced), keeping a deterministic preference: held state, then local, then remotes in connection order. A failing host is traced and skipped. - A reference whose value is a bare session URI (not a chat channel) opens that session, as before. Co-authored-by: Copilot <[email protected]>
Fixes regressions for unmoved chats found in host review of the chat-owner work: - Sandbox temp dir: a ShellManager keeps the owner session for configuration and terminal ownership but keys its sandbox temp dir by the chat's recorded storage resource (the session for the default chat, the chat URI for peers, as before). Disposing a peer chat's ShellManager no longer deletes the directory the default chat uses. - Session-open telemetry: a cold chat subscribe hands its resolved owner to the telemetry scope, so the attempt is measured again. - Local commands capture the chat owner when they start and pass it through, so removing the chat mid-command no longer rejects and the turn still ends. - A chat subscribed before it registers gets its owner when it registers, so it counts for residency and last-unsubscribe GC. - Owner lookups: findChatOwners decodes only catalog payloads that contain a pending chat's JSON literal (an instr prefilter, batched). Chat-backing checks read the marker owner only for legacy markers without a recorded provider, and share one default-chat inventory read per discovery, migration or filter pass. - A cancelled turn is tracked only when its owner is known, and its checkpoint discard uses the recorded owner of a chat that already left the registry. - Restored subagents read their transcript from their recorded storage resource (registry, then the catalog row), and fall back to the creation-time rule only when nothing is recorded. - Removed the unused IChatOwnerResolution.deleted field. Tombstone handling is unchanged. No schema, protocol or persisted-data change. Co-authored-by: Copilot <[email protected]>
findChatOwners resolves a chat from a catalog payload only in the query batch that searched for it. Before, a payload matched for one batch also resolved pending chats of later batches, so a chat listed by two payloads could take the higher session instead of the lowest one that findChatOwner returns. Tests cover that shape with the lower owner live and deleted, a chat URI that needs JSON escaping, and a legacy peer-chat entry skipped because it is recorded under the reading session but tombstoned. Co-authored-by: Copilot <[email protected]>
IAgentService.resolveChatOwner and the AgentSideEffects resolveChatOwner option are required instead of optional, so callers no longer skip the recorded-owner lookup when an implementation omits it. The chat-backing owner lookup passed to _readSessionRegistrationFacts is required too. Co-authored-by: Copilot <[email protected]>
Optional members, optional parameters and default-value parameters that the
chat ownership work added are now required. Where absent is a real state the
caller decides, the type is `T | undefined`. A registration, chat context or
hydration now receives the chat's storage resource explicitly. A caller that
creates a new chat, or restores from a source that records no storage,
applies the creation-time rule itself instead of relying on a hidden default
in the API.
- AgentHostStateManager:
- addChat takes a required storageResource.
- registerRestoredChatSummary requires options.storageResource.
- restoreSession takes a required chatStorageResource(session, chat)
function instead of an optional storage map.
- _ensureDefaultChat requires its storage.
- IChatEntry.parentChat is a required `string | undefined`.
- createAgentChatContext and AgentService._chatContext require
storageResource.
- AgentService._getChatMessages and _loadWorkspaceTransitions require
storage.
- IHydrationContext.storageResource and restoreChatIsolation's
storageResource are required, so contributions no longer fall back.
- AgentService:
- _isChatBacking and _findRecordedChatOwner require their lookups.
- IChatOwnerResolution.spawnedBy and its title are required
`| undefined`.
- Session-open telemetry _start/_classify take a required
`URI | undefined` owner.
- AgentHostPeerChatStore requires its live-owner lookup.
- getRenameChatArgs takes a required `ProtocolURI | undefined`
currentChannel and `URI | undefined` currentSession.
- Client:
- findChatOwnerInSessionRecords requires defaultChatOnly.
- resolveAgentHostChatOwner requires timeoutMs
(AGENT_HOST_CHAT_OWNER_TIMEOUT_MS).
- The subagent opener target reuses the existing
IOpenSubagentChatContext shape.
No behavior change: every caller passes the value the removed default
produced.
Co-authored-by: Copilot <[email protected]>
Review follow-ups to the required-parameter change, with no behavior change for unmoved chats. - A legacy subagent-session restore reads from the subagent's recorded storage when it is registered. An unregistered one follows the creation-time rule and still skips workspace transitions. - Peer and subagent restore fall back from recorded storage directly to the creation-time rule, without inheriting a live entry of another session. - Default-chat adoption uses the storage the loaded catalog records before the creation-time rule, matching restore. - A normalized catalog row without recorded storage logs a trace when it falls back to the creation-time rule. - getRenameChatSession takes a required `ProtocolURI | undefined` currentChannel, like getRenameChatArgs. Co-authored-by: Copilot <[email protected]>
The subscription service indexes subscribed chat and chat-scoped canvas resources by their chat, so recording the owner of a newly registered chat and forgetting it after the chat's last subscription no longer scan every subscription. Owner semantics are unchanged: a registered owner is recorded only while the chat or one of its canvases is subscribed, and is forgotten when its last subscribed resource leaves. Co-authored-by: Copilot <[email protected]>
The state manager passes a restored chat's resolver the storage resource recorded on its entry when resolution starts, while the entry is valid. The restored peer and subagent resolvers use it for the provider chat context and the history read, so nothing looks up storage after registration. Resolution behaves as before: unmoved chats resolve with the same storage, and a chat invalidated mid-resolve still rejects with "Restored chat was invalidated while resolving" after its resolver completes. Co-authored-by: Copilot <[email protected]>
Chat ownership resolution moves out of AgentService into IAgentHostChatOwnershipService, a core node service that consumers inject. It delegates live lookups (owner, required owner, storage, parent, retained owner) to the state manager registry rather than duplicating it. It owns the cold resolution chain: registry and retained summaries, the central catalog, the registered default-chat inventory, tracked in-flight restores, then spawn edges. It also provides createRecordedOwnerLookup, a lookup that reads the inventory once per pass. Registration events now come from the service. onDidRegisterChat and the new onDidUnregisterChat carry the owner and storage captured from the registry entry; unregistration fires from the entry's invalidation. AgentService reports each session and subagent restore with trackRestore, so the service depends only on the state manager and the database, never on AgentService. Callbacks replaced by injection: - IAgentService.resolveChatOwner and the side-effects resolveChatOwner option are removed. ProtocolServerHandler and AgentSideEffects inject the service. - AgentHostPeerChatStore takes the service instead of a live-owner callback. - The subscription service back-fills owners for chats subscribed before they register by listening to onDidRegisterChat itself, using the chat index. recordChatOwner leaves its interface. No protocol, persisted-data or schema change; behavior is unchanged. Co-authored-by: Copilot <[email protected]>
Every DI-created consumer of chat ownership now injects IAgentHostChatOwnershipService instead of reading the state manager registry directly. This covers: - changeset coordinator, file monitor, operation and changeset services - chat input, customization enablement, Git state, pull request status, review, turn, utility model and session-open telemetry services - session residency and session permissions - local commands, Mission Control host and SDK event source - queue drain, turn delegation, persisted turn usage and workspace conversion contributions - AgentService, AgentSideEffects and ProtocolServerHandler - the server tool accessor wiring Contributions and telemetry that no longer need the state manager drop it. Non-DI helpers keep the state manager: chat context and turn-starter functions, branch changeset scope, the configuration service built before DI, the server tool host and the completion provider. Mechanical; behavior is unchanged. Co-authored-by: Copilot <[email protected]>
Reading or reconciling a session's legacy peer chats checked each entry against every cached catalog payload. Those entries are rarely in the central catalogs, so they all fell through to sessions_v2 table scans: one per 100 chats, about 10 for a full list of 999 peers. Cold owner lookups also scanned payloads before the registered session inventory. IAgentHostDatabase.findChatOwner/findChatOwners are split into: - findCentralChatOwners: chats_v2 (tombstones included), then session_chats; two indexed IN queries and no payload pass. - findCatalogPayloadChatOwners: the prefiltered sessions_v2 payload scan. The legacy peer-chat filter consults only findCentralChatOwners and the live registry. Per the agreed rule, an entry is skipped only when the central catalog or the live registry records it under another session or as tombstoned. A chat listed only in another session's cached payload is not a central record, so its entry now stays with the session whose database holds it. The cold owner chain is now: 1. live registry and retained summaries 2. central catalogs 3. registered default-chat inventory 4. catalog payloads 5. in-flight restores 6. spawn edges A legacy default chat resolves from the inventory without a payload scan. Tombstone dominance is unchanged because chats_v2 is still checked first. No schema change. Co-authored-by: Copilot <[email protected]>
Renames IAgentHostDatabase.findCatalogPayloadChatOwners to findPayloadChatOwners, the name the review asked for. Adds a real-database test that a chat listed only in a cached catalog payload still resolves through the ownership service, as the last recorded source. Co-authored-by: Copilot <[email protected]>
Restores the IAgentHostDatabase.findCatalogPayloadChatOwners name that was accepted in review. The only change left relative to the perf fix is the real-database test that a chat listed only in a cached catalog payload still resolves through the ownership service. Co-authored-by: Copilot <[email protected]>
A cold owner lookup that misses the live registry and the central catalogs rebuilt the registered default-chat inventory on every call. It listed both registration tables and minted up to three default-chat URIs per session, which costs tens of milliseconds of JavaScript at 10000 sessions on each cold subscribe of a legacy default chat or an unknown chat. The ownership service now keeps the index (default chat to registered session identity) and rebuilds it only when the registrations change. The database counts registration changes with connection-scoped TEMP triggers on sessions, sessions_v2 and the tombstone/exclusion metadata keys: - getRegistrationGeneration reads the count. - readSessionRegistrations returns both listings together with the count they reflect, read in one sequenced task. The count catches every writer of those tables, including discovery and migration, because this host's connection is the only writer of agent-host.db. TEMP objects never change the database file, so there is no schema change. A newly registered session's default chat resolves immediately, and an unregistered, tombstoned or excluded session stops resolving. createRecordedOwnerLookup uses the same index. The index mints standard default chats and checks each hit against the state manager's recorded default chat, so it answers exactly as the per-call inventory did. Co-authored-by: Copilot <[email protected]>
The default-chat index test counted registration listings from sqlite trace events, which can arrive after the awaited lookup resolves. It now counts calls to the listing methods, which is deterministic. Co-authored-by: Copilot <[email protected]>
createRecordedOwnerLookup holds the first default-chat index of its pass, so a pass builds it at most once, as before the index was cached, even when registrations change while the pass runs. Two fixes to the shared build: - A caller retries the shared build only when that build is older than the registration generation the caller read. - A finished build clears the shared slot only if the slot still holds that build. Co-authored-by: Copilot <[email protected]>
Adapts main's #340980 (preserve writable session downgrade compatibility) to Block 1. - SessionStorageIdentity translated a chat URI between the runtime and storage spellings of its session by reading the session from parseChatUri, which Block 1 no longer exposes. That address translation now lives in a private function inside sessionStorageIdentity.ts. It decodes the URI's encoded session, maps it through the identity records, and re-encodes it, keeping the chat id, the subagent tool-call form and any ?/# suffix. It never returns the decoded session and is never used to determine a chat's owner. - CompatibleAgentHostDatabase implements the Block 1 database members: - findCentralChatOwners and findCatalogPayloadChatOwners look up storage chats and return owners keyed by the caller's runtime chat. - getRegistrationGeneration passes the generation through. - readSessionRegistrations returns translated listings. - Main's new tests pass the arguments Block 1 made required: ownerSessionUri for edit attribution, and the ownership service for the peer chat store. Co-authored-by: Copilot <[email protected]>
Restoring a session read the catalog snapshot twice more than main to look up recorded chat storage: once for its peer chats and once for its restored subagents. Both now use storage from a snapshot the restore already reads: - Peer chats use the snapshot `_restorePeerChats` reads first. - Subagent admission and its retry receive the map the restore built from its own catalog snapshot. The map is a required parameter. A restore therefore reads the snapshot as often as on main. Storage values are unchanged. A restore never records storage other than the creation-time rule (a legacy migration records only that), so a chat without recorded storage in the snapshot falls back to the same value as before. Co-authored-by: Copilot <[email protected]>
📬 CODENOTIFYThe following users are being notified based on files changed in this PR: Ulugbek Abdullaev (@ulugbekna)Matched files:
Ben Villalobos (@benvillalobos)Matched files:
TylerLeonhardtMatched files:
|
There was a problem hiding this comment.
🟡 Changes recommended
Opaque remote chat URIs, remote connection routing, and chat-owned changeset subscription ownership are not handled correctly.
5 open findings
What changed in this PR
Moves Agent Host chat ownership and storage resolution from URI decoding to recorded catalog/state ownership.
Changes:
- Adds explicit chat owner/storage propagation across host services and telemetry.
- Updates Sessions/remote routing to trust containing session records.
- Expands regression fixtures for moved and opaque chat identities.
| File | Description |
|---|---|
resolveRestoredSubagentChatResource.test.ts |
Updates restored subagent URI expectations. |
agentHostClientTools.test.ts |
Replaces production owner parsing in fixtures. |
agentHostCustomizationSidecar.test.ts |
Completes connection mock contract. |
chatAttachmentWidgets.ts |
Resolves chat-reference owners through hosts. |
agentHostSessionHandler.ts |
Uses catalog ownership for chats and subagents. |
agentRemoteSessionMeta.test.ts |
Updates metadata URI assertions. |
remoteSessionMessageRouter.test.ts |
Tests catalog-authoritative routing. |
remoteSessionInspector.test.ts |
Tests catalog-authoritative inspection. |
remoteSessionSource.ts |
Resolves source chats from catalogs. |
remoteSessionMessageRouter.ts |
Routes messages using catalog records. |
remoteSessionInspector.ts |
Inspects catalog-recorded chats. |
openSubagentChat.test.ts |
Adds backend-chat provider fixtures. |
agentHostSessionChangesets.test.ts |
Updates test owner extraction. |
baseAgentHostSessionsProvider.ts |
Tracks backend chat ownership in adapters. |
mcpCustomizationController.test.ts |
Supplies explicit MCP provider/session identity. |
sessionStorageIdentity.test.ts |
Tests chat address translation. |
sessionPermissions.test.ts |
Tests permissions against recorded owners. |
sessionIsolationTools.test.ts |
Registers explicit chat storage. |
serverIntegrationTestHelpers.ts |
Updates test chat ownership helpers. |
pullRequestChatContribution.test.ts |
Injects ownership service into tests. |
agentHostTiming.test.ts |
Supplies explicit telemetry owner. |
missionControlSdkEventSource.test.ts |
Updates ownership-aware fixtures. |
missionControlHost.test.ts |
Adds ownership service and storage fixtures. |
mapSessionEvents.test.ts |
Passes explicit routing sessions. |
mapSessionEvents.perf.test.ts |
Updates benchmark invocation. |
historyRecordFixtures.test.ts |
Updates history routing fixtures. |
subagentSuite.ts |
Uses test-only minted-owner decoding. |
multiChatSuite.ts |
Uses test-only minted-owner decoding. |
copilotSessionLauncher.test.ts |
Completes updated service mocks. |
codexChatDiscovery.test.ts |
Passes explicit chat context. |
codexAgent.test.ts |
Updates test owner extraction. |
claudeTerminalOutput.test.ts |
Supplies owner session to terminal output. |
claudeSdkPipeline.test.ts |
Supplies owner session to pipelines. |
claudeSdkMessageRouter.test.ts |
Supplies explicit owner/storage resources. |
claudeFileEditObserver.test.ts |
Supplies owner session to observers. |
claudeAgent.integrationTest.ts |
Registers ownership service in test graphs. |
chatOwnershipTestUtils.ts |
Adds ownership test utilities. |
buildSessionEvents.test.ts |
Passes explicit routing sessions. |
artifactServerTools.test.ts |
Registers explicit chat storage. |
agentSessionResidency.test.ts |
Tests captured subscription ownership. |
agentSessionRegistry.test.ts |
Extends database ownership test doubles. |
agentHostUtilityModelService.test.ts |
Injects ownership service. |
agentHostTurnService.test.ts |
Injects ownership service. |
agentHostTurnHangTelemetry.test.ts |
Supplies captured telemetry owners. |
agentHostToolCallTelemetry.test.ts |
Supplies chat ownership and storage. |
agentHostSyncOperationHandler.test.ts |
Registers explicit peer storage. |
agentHostSubscriptionService.test.ts |
Tests captured chat/canvas ownership. |
agentHostReviewService.test.ts |
Adds ownership-aware review fixtures. |
agentHostReviewService.integrationTest.ts |
Injects ownership service. |
agentHostPullRequestStatusService.test.ts |
Adds ownership-aware PR fixtures. |
agentHostPullRequestOperationProvider.test.ts |
Updates restored chat storage fixtures. |
agentHostPullRequestAssociationResolver.test.ts |
Supplies restore storage resolver. |
agentHostProviderService.test.ts |
Supplies explicit MCP provider. |
agentHostDiscardChangesOperationHandler.test.ts |
Registers explicit peer storage. |
agentHostContributions.test.ts |
Registers ownership service. |
agentHostCommitOperationHandler.test.ts |
Registers explicit peer storage. |
agentHostCheckoutOperationHandler.test.ts |
Registers explicit peer storage. |
agentHostChatCompletionProvider.test.ts |
Adds fixture ownership lookup. |
agentHostChatCatalogMigration.test.ts |
Expects persisted owner metadata. |
agentHostChangesetStrategy.test.ts |
Adds ownership-aware fixtures. |
agentHostAutomationService.test.ts |
Supplies explicit owner/storage. |
agentFeedbackServerTools.test.ts |
Tests recorded-owner attribution. |
openSessionLink.test.ts |
Tests owner-explicit session links. |
mintedChatUri.ts |
Adds test-only URI decoding helpers. |
changesetUri.test.ts |
Tests recorded changeset ownership. |
agentSubscription.test.ts |
Tests owner lookup for subscriptions. |
agentService.test.ts |
Removes obsolete storage helper tests. |
fileEditTracker.ts |
Propagates owner session into edit telemetry. |
editSurvivalReporter.ts |
Uses recorded owner for telemetry identity. |
editArcReporter.ts |
Uses recorded owner for telemetry identity. |
artifactServerTools.ts |
Uses tool execution session ownership. |
agentServerToolHost.ts |
Resolves tool sessions from registry ownership. |
agentFeedbackServerTools.ts |
Attributes feedback to recorded owners. |
sessionStorageIdentity.ts |
Keeps URI decoding private to address translation. |
sessionSandbox.ts |
Resolves sandbox configuration ownership explicitly. |
missionControlSdkEventSource.ts |
Uses ownership service for SDK events. |
missionControlHost.ts |
Routes mirrored events through recorded owners. |
renameLocalCommand.ts |
Uses captured local-command owner. |
bangLocalCommand.ts |
Uses captured local-command owner. |
mapSessionEvents.ts |
Accepts explicit routing session identity. |
copilotShellTools.ts |
Separates owner and sandbox storage scope. |
compatibleAgentHostDatabase.ts |
Translates database ownership lookups. |
claudeSdkPipeline.ts |
Carries owner session into routing. |
claudeSdkMessageRouter.ts |
Uses explicit owner for subagents and outputs. |
claudeFileEditObserver.ts |
Propagates edit owner identity. |
claudeAgentSession.ts |
Captures configuration ownership at creation. |
workspaceContextContribution.ts |
Captures owners for cleanup. |
turnDelegationContribution.ts |
Uses recorded storage resources. |
sessionWorkspaceConversionContribution.ts |
Passes owner and storage during restore. |
queueDrainContribution.ts |
Routes queued turns by recorded owner. |
persistedTurnUsageContribution.ts |
Persists usage in recorded storage. |
markdownPlanRichLinksContribution.ts |
Builds links from explicit owners. |
chatReadContribution.ts |
Persists read state under dispatched owner. |
chatArchiveContribution.ts |
Persists archive state under dispatched owner. |
agentServiceComposition.ts |
Exposes and wires ownership service. |
agentHostUtilityModelService.ts |
Builds model contexts with recorded storage. |
agentHostTurnStarter.ts |
Passes owner/storage into telemetry and context. |
agentHostTurnService.ts |
Resolves turn owners through the service. |
agentHostToolCallTracker.ts |
Captures tool-call owner identity. |
agentHostServices.ts |
Registers the ownership service. |
agentHostPullRequestLifecycleOperationHandler.ts |
Adapts changeset session fallback. |
agentHostInputRequestTracker.ts |
Captures input-request owners. |
agentHostGitStateService.ts |
Resolves chat ownership for PR reconciliation. |
agentHostCustomizationEnablementService.ts |
Routes customization updates by owner. |
agentHostChatInputService.ts |
Prepares chat input using recorded ownership. |
agentHostChatCompletionProvider.ts |
Resolves completion sessions from registry ownership. |
agentHostChatCatalogMigration.ts |
Records migration-time storage explicitly. |
agentHostBranchChangesetScope.ts |
Resolves changeset scopes through registry ownership. |
agentHostAutomationService.ts |
Matches automation runs to recorded default chats. |
agentConfigurationService.ts |
Adds explicit configuration-owner resolution. |
agentChatContext.ts |
Accepts recorded storage resources. |
openSessionLink.ts |
Builds links from explicit owners. |
fileEditAttribution.ts |
Adds owner session attribution. |
agentHostSubscriptionService.ts |
Makes subscription resolution owner-driven. |
agentHostChatContributionsService.ts |
Adds hydration storage context. |
agent.ts |
Adds listed-chat ownership and owner-aware spawn mapping. |
AGENTS.md |
Documents recorded ownership architecture. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…owner A `<chat>/changeset/...` subscription was not associated with its chat, so no owner was recorded for it and hasSessionSubscribers/residency missed an active peer-chat changeset. Map a chat-owned changeset to its chat via the parsed changeset owner (no session decoding), so the registration back-fill and setSubscriptionOwner record its owner like the chat and its canvases. Co-authored-by: Copilot <[email protected]>
Connor Peet (connor4312)
left a comment
There was a problem hiding this comment.
Reviewed the recorded-ownership and storage changes, protocol/session ownership guards, permission and MCP routing, subscription/residency lifecycle, restoration paths, regression tests, and CI/history. No actionable new P1/P2 findings. The changeset subscription ownership issue is fixed in 460e610 with regression coverage; the remaining existing remote-link/opaque-URI comments describe pre-existing behavior and tracked follow-ups.
Written by Connor's agent running GPT-6.1 Sol
The node-runner-only test (skipped in the Electron runner, which lacks SharedArrayBuffer) used a peer chat URI that was never registered. The artifact tools resolve the chat's owner from recorded ownership rather than the chat URI, so register the chat under its session as the other tool tests do. Co-authored-by: Copilot <[email protected]>
d3526b4


Goal
This is Block 1 of moving chats between sessions. No production code derives a chat's owning session, storage location, or parent session by decoding a chat URI anymore.
Chat URIs are still generated the same way (
buildChatUri,buildDefaultChatUri,buildSubagentChatUri); nothing reads the embedded session back. There is no schema, persisted-data, or AHP protocol change.Design
Owner from the containing record. A chat's owner is the record that holds it:
chats_v2.owner_session_uri,session_chats.session_uri, the session'ssessions_v2payload, or the session record itself for a legacy default chat. Every chat the database and the legacy readers return carries that owner.IAgentHostChatOwnershipService(node/agentHostChatOwnershipService.ts) is the single ownership surface for DI-created consumers. It provides:chats_v2, thensession_chats) → registered default-chat index → catalog payload scan → restores in flight → spawn edges;onDidRegisterChatandonDidUnregisterChatevents, which carry the owner and storage captured from the registry entry.AgentServicereports restores withtrackRestore, so the service never depends onAgentService.Recorded storage. Each chat registers with an explicit storage resource. On restore that is
chats_v2.storage_resource. The creation-time rule applies only to new chats and to legacy data that records no storage. A recorded storage resource is never recomputed from the owner or the URI.Captured owners for cleanup. Teardown and lifetime paths use the owner captured at registration, subscribe, or request time, never a lookup after the entry is gone. This covers GC and residency, input timing, workspace preparation, local commands, and cancelled turns.
Removed helpers.
parseRequiredSessionUriFromChatUri,parseDefaultChatUri,chatStorageUri,resolveChatUri, andbuildOpenSessionLinkForChatResourceare deleted.parseChatUrinow returns only the chat id.All APIs added or changed by this work are required: no optional members or default parameters.
Behavior changes
None of these affect chats VS Code creates today.
#chat:chip that references a chat no host lists does nothing._meta.Compatibility
Main's #340980 storage/runtime identity translation of chat URIs is kept as a private address-translation function in
sessionStorageIdentity.ts. It is never used for ownership.Scope note (D7)
Other URIs that embed a session are intentionally unchanged: folder changeset owners, annotations, subagent session URIs, non-PTY terminals, and resource watch. Folder owners and reviewed refs move to a later change.
Performance
Measured on abe74073738 vs main 8b21e52.
Method: real
AgentHostDatabaseon an on-disk seed copy, realAgentServicewith a mock provider. Seed: 60% normalized, 30% legacy peers, 10% legacy default-only, plus tombstones; 2,000 and 10,000 sessions. Main and branch interleaved round by round, 15 runs per side, load average 9–15. Median ms, main → branch.Improvements
Remaining costs (accepted)
session_chatsowner IN-query has no index onchat_uri; follow-up candidateNo change
listSessions: −3% (2k), −9–10% (10k); CPU profiles show no extra work.Restore fix confirmation (3c4715da2a8; three-way vs old base 8b21e52 and new base 1576464, plain Node, load 8–10)
chats_v2 WHERE chat_uri IN (?)+ deleted-session check). A 200-chat restore issues identical statements to the new base (the earlier +8 is gone).Restore no longer adds catalog snapshot reads: 14 → 12 reads per restore of a normalized session with peers and a restored subagent, i.e. zero added vs main.
Accepted legacy-only costs:
session_chats(chat_uri)).v2 data shows no consistent regression.
How to test
Live validation with real Copilot in Code OSS. All passing:
!sleep 20runs.#chatchip.The post-restart warnings
setChangesets: unknown chatandAction for unknown sessionalready occur on main.Validation
All on a clean tree at the rebased HEAD (base
4dff635e5a3).npm run typecheck-clientnpm run eslint -- <205 .ts files changed vs main>./scripts/test.sh --reporter dot --runGlob "vs/platform/agentHost/test/**/*.test.js"./scripts/test.sh --reporter dot --runGlob "vs/{workbench/contrib/chat/test/browser,sessions/contrib/providers,sessions/contrib/remoteSessions}/**/*.test.js"~/.copilotenvironment tests and an order-dependent Voice test; none new)npm run valid-layers-checknpm run check-cyclic-dependenciessrcparseChatUri(...).session