Skip to content

agentHost: discover external Copilot sessions - #331082

Merged
Benjamin Christopher Simmonds (benibenj) merged 2 commits into
mainfrom
benibenj/agents/copilot-agent-session-filtering
Aug 16, 2026
Merged

Benjamin Christopher Simmonds (benibenj) merged 2 commits into
mainfrom
benibenj/agents/copilot-agent-session-filtering

Conversation

@benibenj

Copy link
Copy Markdown
Contributor

Problem

Copilot sessions created outside the Agent Host never appeared in the Agents window, even with chat.agentHost.showExternalSessions set to all.

CopilotAgent had a single discovery path, _discoverExtHostChats(), which:

  1. only matched legacy VS Code extension-host CLI sessions, via a ~/.copilot/session-state/<id>/vscode.metadata.json sidecar with origin === 'vscode';
  2. hard-coded external: false on everything it emitted;
  3. was gated entirely behind chat.agentHost.migrateLegacyCopilotCli.enabled.

A session created by the standalone copilot CLI or the GitHub Copilot app — which all share ~/.copilot — has no such marker, so it was dropped at step 1 and never reached AgentService._registerDiscoveredChats. The registry therefore never held a Copilot row with external = true, and the setting had nothing to filter.

Claude (_emitClaudeCodeChats) and Codex (_emitCodexChats) both emit every unknown native chat as external: true. Copilot was the outlier, and AGENTS.md §3a documented the gap as intentional.

Change

_discoverCopilotChats() / _emitCopilotChats() enumerate the whole SDK catalog and classify each chat Agent Host does not already own:

  • legacy extension-host chat → external: false + ehcliAdoptable meta, still gated on migrate-legacy (unchanged behavior);
  • anything else → external: true, ungated.

"Already owns" is the presence of a per-session database under {userDataPath}/agentSessionData (never the shared Copilot home), which also keeps peer-chat backings out of the payload. Subagent sessions and marked chat backings are filtered centrally by AgentService as before.

Discovery now starts on first-listener attach behind a retry wrapper, mirroring Claude and Codex, so a cold CLI client doesn't lose the pass. The retry honors the file's existing _shutdownPromise / _store.isDisposed guard so teardown stops it rather than sleeping on a dead client.

Chats whose SDK context carries no working directory are still dropped. _doResumeSession requires one unconditionally and a discovered chat has no other source for it — _initializeExternalSessionReadState writes only agentHost.isRead — so surfacing one would list fine and then throw on open, with a plain Error rather than the SessionWorkingDirectoryMissingError the UI handles gracefully.

Logging

A session that was discovered but filtered out by the setting was previously indistinguishable from one that was never discovered. The pipeline is now traceable end to end at info:

[Copilot] Listed N SDK session(s) for <reason>
[Copilot] Chat discovery: N SDK session(s) -> X external, Y adoptable legacy extension-host, Z already known to Agent Host, W without a working directory
[Copilot] Chat discovery: emitting X of Y discovered chat(s) (adopt legacy extension-host chats: <bool>)
[AgentService] discovery for provider <id>: N candidate(s) (X external), Y registered, Z suppressed as subagent/chat backing
[AgentService] listSessions hid N of M session(s) (showExternalSessions: '<mode>')

The last line is deduped on hidden/total/mode so a steady state logs once instead of on every refresh. All lines carry only counts, a mode name and session URIs — no file paths, summaries or user content.

Notes

  • _registerDiscoveredChats now computes its return value from a counter instead of results.some(...). Semantically identical (booleans only); the value has no consumer today.
  • The "empty session DB counts as known" semantics of _readStoredSessionMetadata are deliberately left alone — an empty DB is how Agent Host records a chat it already touched, and the pre-existing test does not discover an extension-host chat with an empty Agent Host database asserts exactly that. The trade-off is now written down in AGENTS.md rather than silently relied upon.

Testing

Four new tests in a external chat discovery suite cover the standalone-CLI, GitHub-Copilot-app (origin: 'other'), adoptable-legacy, and already-owned / no-working-directory cases. writeExtensionHostMarker was hoisted out of the nested migration suite so both suites share it.

  • copilotAgent.test.ts — 267 passing (3 consecutive runs)
  • agentService.test.ts — 290 passing
  • tsc --project src/tsconfig.json --noEmit — clean apart from two pre-existing @github/copilot-sdk type-skew errors in copilotAgentSession.test.ts / copilotToolDisplay.test.ts

provisional session anchors customization discovery to the additional roots (gated) is flaky against its 2000ms timeout on this branch's merge base (failed 2 of 3 baseline runs); it passed 3 of 3 with these changes applied.

Blast radius

Measured against a real ~/.copilot with 975 SDK sessions: 492 have no Agent Host DB, of which 453 carry an extension-host marker (still gated as adoptable-legacy), leaving ~39 true externals — only 20 within the default 7-day window.

Worth flagging: a few arrive in same-second triples that look like CLI-spawned sub-sessions and will surface as separate rows. The SDK's SessionMetadata exposes no parent/subagent field, so there is no signal to suppress them; Claude and Codex have the same exposure today.

`CopilotAgent` never emitted an external chat. Its only discovery path,
`_discoverExtHostChats()`, matched exclusively legacy VS Code
extension-host CLI sessions (a `vscode.metadata.json` sidecar with
`origin: 'vscode'`), hard-coded `external: false`, and was gated behind
`migrateLegacyCopilotCli.enabled`. A session created by the standalone
CLI or the GitHub Copilot app — which share `~/.copilot` — was dropped
before it ever reached the session registry, so `showExternalSessions`
had nothing to show even when set to `all`. Claude and Codex both emit
every unknown native chat as external; Copilot was the outlier.

Replace it with `_discoverCopilotChats()` / `_emitCopilotChats()`, which
enumerate the SDK catalog and classify each chat Agent Host does not
already own: a legacy extension-host chat stays internal and adoptable
in place (still gated on migrate-legacy), anything else is external and
ungated. Discovery starts on first-listener attach behind a `retry`
wrapper, mirroring Claude and Codex, so a cold CLI client does not lose
the pass; the retry honors `_shutdownPromise` so teardown stops it
rather than sleeping on a dead client.

Chats whose SDK context carries no working directory are still dropped:
`_doResumeSession` requires one and a discovered chat has no other
source for it, so surfacing one would produce a row that throws on open.

Add logging along the whole pipeline — provider enumeration, per-pass
classification counts, registry registration, and how many sessions the
`showExternalSessions` filter is holding back — since a session that was
discovered but filtered was previously indistinguishable from one that
was never discovered at all.

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

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.

Pull request overview

Adds discovery of external Copilot sessions to the Agent Host session catalog.

Changes:

  • Classifies unknown Copilot sessions as external or legacy-adoptable.
  • Adds discovery retrying, filtering diagnostics, and tests.
  • Updates Agent Host discovery documentation.
Show a summary per file
File Description
copilotAgent.ts Implements Copilot catalog discovery and classification.
agentService.ts Adds discovery and filtering diagnostics.
copilotAgent.test.ts Tests external-session discovery scenarios.
AGENTS.md Documents the revised discovery model.

Review details

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Suppressed comments (1)

src/vs/platform/agentHost/node/copilot/copilotAgent.ts:2230

  • The absence of the sidecar is racy evidence that a session is external. The extension creates the SDK session first and then fire-and-forgets setSessionOrigin (extensions/copilot/src/extension/chatSessions/copilotcli/node/copilotcliSessionService.ts:598-604), so discovery can observe the catalog entry before origin: 'vscode' is written. That missing result is also cached, and registration creates a session DB, making the incorrect external classification durable on later passes. Recheck/retry missing markers before classifying them, or otherwise synchronize with the marker write.
			const adoptable = await this._isExtensionHostCliSession(s.sessionId);
  • Files reviewed: 4/4 changed files
  • Comments generated: 5
  • Review effort level: Balanced

Comment thread src/vs/platform/agentHost/AGENTS.md Resolved
- Classify each discovered chat inside a try/catch so one unreadable
  session database no longer rejects the whole catalog scan (and fails
  every retry with it); the failing chat is logged and skipped instead.
- Count only mode-excluded rows in the hidden-sessions log. Adoptable
  legacy rows are withheld by migrate-legacy, so attributing them to
  showExternalSessions could report external filtering in 'all' mode.
- Await the memoized discovery pass in the test helper instead of
  polling for a non-empty result, so an expected-empty assertion can no
  longer pass before classification has run.
- Trim inline comments to one line per the coding guidelines.
- Describe discovery in AGENTS.md as emitting provider-classified
  provenance, matching the Copilot legacy exception documented above it.

Co-authored-by: Copilot <[email protected]>
@benibenj
Benjamin Christopher Simmonds (benibenj) merged commit 6f96a78 into main Aug 16, 2026
27 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants