Skip to content

auth: let Copilot sessions renew GitHub tokens [7/10] - #22942

Merged
sergiou87 merged 10 commits into
developmentfrom
short-lived-tokens-7-copilot
Oct 7, 2026
Merged

sergiou87 merged 10 commits into
developmentfrom
short-lived-tokens-7-copilot

Conversation

@sergiou87

@sergiou87 sergiou87 commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Part of the refreshable OAuth credential stack in #22919.

Description

Enable Copilot SDK sessions to obtain fresh GitHub access tokens while keeping
refresh tokens inside Desktop and authentication bound to the originating sign-in.

  • Static client authentication and the SDK token provider capture the same
    credential session before asynchronous preparation. Commit-message generation
    binds that context before model discovery, and client creation resolves the
    static access token after runtime preparation.
  • SDK providers answer only for the account's own host. They request more than
    61 minutes of validity and subtract a 60-second safety buffer from the lifetime
    reported to the SDK, preserving fractional seconds. This aligns the SDK's
    one-hour cached-token preflight with Desktop's renewal deadline. Unknown expiry
    or a buffered lifetime of an hour or less fails explicitly.
  • Providers follow rotation within their originating credential session.
    Retirement permanently rejects old providers and attempts to create providers
    from stale account snapshots, including when the same identity signs in again
    with the same access-token string. Owner-held account-snapshot/session
    associations preserve this identity through token, lease, profile, and redacted
    account copies. A new sign-in requires a new account snapshot and client.
  • Model metadata and quota requests retain the ordinary ten-minute renewal margin.
    Quota authentication stays bound to the originating session across SDK startup.
  • Commit-message generation and conflict resolution can cancel client preparation
    and session creation while another operation holds a token lease. Generation
    can also cancel its wait for shared model discovery. Cancellation affects only
    the caller: shared discovery and renewal continue, and another operation's
    lease remains held. Late clients are stopped and late sessions are disconnected
    once. Conflict cancellation remains an abort, not a transport failure or retry;
    an operation with no resolvable files remains a successful no-op.
  • Plain-token accounts retain static authentication without an SDK token provider.
    SDK session credentials contain only access tokens and remaining lifetimes.

Copilot does not hold a token lease for an entire invocation. Preflight alignment
does not protect a request already running when another consumer rotates and
invalidates its cached access token.

Screenshots

Not applicable: authentication and lifecycle changes only; no UI layout changes.

Stack

Merge in order; each PR builds on the preceding one.

  1. auth: add OAuth refresh-token protocol primitives [1/10] #22917 - OAuth protocol primitives
  2. auth: handle rejected API tokens in AccountsStore [2/10] #22937 - Token invalidation in AccountsStore
  3. auth: add versioned secure-storage format for credentials [3/10] #22938 - Versioned credential storage
  4. auth: coordinate OAuth token renewal in AccountsStore [4/10] #22939 - Coordinated token renewal
  5. auth: hand Git fresh credentials [5/10] #22940 - Git credentials
  6. auth: resolve private image tokens through the renderer [6/10] #22941 - Private images
  7. auth: let Copilot sessions renew GitHub tokens [7/10] #22942 - Copilot SDK sessions (this PR)
  8. auth: request refreshable OAuth tokens at sign-in [8/10] #22943 - Sign-in with refreshable tokens (behind flag)
  9. docs: describe refresh-token rollout and recovery [9/10] #22919 - Rollout and recovery documentation
  10. auth: log automatic sign-outs [10/10] #22959 - Log automatic sign-outs

Validation

Automated coverage includes the staggered 3661/3659-second preflight boundary,
fractional lifetimes, session retirement and same-token re-sign-in, production
client/session wiring, legacy authentication, cancellation with a held credential
lease, unaffected shared consumers, and exactly-once late-resource cleanup.
SDK-boundary tests exercise normal store wiring with public SDK methods mocked;
the staggered-session test models the SDK's cached-token preflight.

Validation commands and results:

  • yarn test app/test/unit/stores/copilot-store-test.ts app/test/unit/stores/copilot-store-credentials-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/credential-sessions-test.ts - passed: 98 tests, 0 failures.
  • yarn test on the final stacked branch - failed with the same four pre-existing
    bare-repository Git failures associated with safe.bareRepository=explicit:
    2,123 passed, 4 failed, 1 skipped.
  • yarn -s lint:fix - passed.
  • yarn lint on the final stacked branch - passed.
  • npx --no-install tsc -p . --noEmit --skipLibCheck - passed. Dependency
    declaration checking is excluded because of pre-existing WeakMap declaration
    conflicts; application and test sources are checked.
  • git diff --check - passed.

Live CLI cached-token rollover and long-running invocations have not been
validated against the real service and remain rollout-validation requirements.

Release notes

Notes: no-notes

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.

Copilot review overview

🟡 Changes recommended

The session wiring and quota-renewal paths need direct regression tests.

Review effort: Balanced
Findings: 2 Low severity

Open (2)
What changed in this PR

Adds renewable OAuth credentials to Copilot SDK sessions while preserving static-token behavior.

Changes:

  • Adds a host-restricted Copilot token provider with a 61-minute renewal margin.
  • Refreshes credentials before client creation and quota requests.
  • Adds unit coverage for provider renewal, host validation, and sign-out.
File Description
app/​src/​lib/​stores/​copilot-store.ts Integrates fresh tokens and session token providers.
app/​test/​unit/​refresh-token-consumers-test.ts Tests Copilot credential-provider behavior.

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

Comment thread app/src/lib/stores/copilot-store.ts Resolved
Comment thread app/src/lib/stores/copilot-store.ts Resolved

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.

Copilot review overview

🟢 Approval recommended

The token renewal behavior is correctly integrated and adequately covered by focused tests.

Review effort: Balanced
Findings: None

Resolved since last review (2)

@sergiou87
sergiou87 marked this pull request as ready for review September 28, 2026 15:36
@sergiou87
sergiou87 requested a review from a team as a code owner September 28, 2026 15:36
@sergiou87
sergiou87 requested a review from tidy-dev September 28, 2026 15:36
@sergiou87
sergiou87 force-pushed the short-lived-tokens-7-copilot branch from c71dcf0 to 1802c67 Compare October 2, 2026 11:28
@sergiou87
sergiou87 force-pushed the short-lived-tokens-7-copilot branch from 1802c67 to fefb9d4 Compare October 2, 2026 11:42
@sergiou87 sergiou87 changed the title auth: let Copilot sessions renew GitHub tokens [7/9] auth: let Copilot sessions renew GitHub tokens [7/10] Oct 2, 2026
@sergiou87
sergiou87 force-pushed the short-lived-tokens-7-copilot branch from fefb9d4 to 9f8cbf6 Compare October 2, 2026 12:18

@niik niik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The provider is carefully host-restricted and keeps refresh tokens inside Desktop, but the three independent reviews now agree on two lifecycle issues.

First, Desktop requests 61 minutes of validity but advertises the token’s full remaining lifetime to the SDK, whose preflight threshold is 60 minutes. Session A can receive T with 3661 seconds reported; two seconds later Session B’s initial acquisition falls inside Desktop’s 61-minute margin and rotates to N, immediately invalidating T. A still believes T has 3659 seconds remaining, so its next credential-consuming operation can use T without invoking the provider. The SDK does not perform rejection-driven retry, so the turn fails.

Please align the lifetime advertised to the SDK with Desktop’s safety margin—for example, retain the raw lifetime for the <=3600 validation, but subtract the 60-second buffer from expiresIn returned to the SDK. That makes every session’s preflight deadline coincide with the point where any provider call may rotate, allowing CredentialSessions’ existing single-flight renewal to coalesce them. Add a deterministic staggered two-session test around 3661/3659 seconds.

Second, providers are bound by endpoint plus numeric account ID, not by the credential-session instance that created them. After sign-out and re-sign-in as the same GitHub identity, an old provider can adopt the replacement session’s token and continue. This conflicts with the explicit “never adopt a later sign-in’s token” contract already implemented by resolveToken/trackToken. Please bind Copilot providers to the originating credential session or token lineage so retirement remains permanent, and add a remove/re-add-same-ID regression test where the old provider rejects and a newly created provider succeeds.

A direct CopilotStore test that verifies gitHubTokenProvider is actually attached to created sessions would also protect this integration point.

@sergiou87
sergiou87 force-pushed the short-lived-tokens-7-copilot branch from dcc11e9 to 21bc8d8 Compare October 5, 2026 11:35
@tidy-dev
tidy-dev removed their request for review October 5, 2026 15:18
@sergiou87
sergiou87 requested a balanced review from Copilot October 5, 2026 17:05

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.

Copilot review overview

🔵 Needs a closer look

Credential-session isolation needs correction, and live SDK renewal still requires human validation.

Review effort: Balanced
Findings: 1 High severity

Open (1)

Comment thread app/src/lib/credential-sessions.ts Resolved
@sergiou87
sergiou87 requested a balanced review from Copilot October 6, 2026 07:36

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.

Copilot review overview

🔵 Needs a closer look

Credential lifecycle and SDK renewal timing need human validation, and cancellation gaps remain unresolved.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
Resolved since last review (1)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Make session creation cancellation-aware to prevent pending chunks and leaks

app/​src/​lib/​stores/​copilot-store.ts:1499

This session-creation wait does not observe cancellation. With a Git lease and 45 minutes left on the token, client creation succeeds with the ten-minute margin, but the new session provider waits for renewal with its 61-minute margin. Cancelling then leaves the chunk pending and delays client cleanup because the abort check below cannot run yet. Use createCancellableSession here too, translate its cancellation error to CopilotConflictResolutionAbortError, and preserve its cleanup of sessions returned after cancellation.

Comment thread app/src/lib/stores/copilot-store.ts Resolved

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.

Copilot review overview

🔵 Needs a closer look

Security-sensitive token renewal and SDK cancellation behavior warrant final human review and live integration validation.

Review effort: Balanced
Findings: None

Resolved since last review (1)

@sergiou87

Copy link
Copy Markdown
Member Author

Hopefully both lifecycle issues are addressed in the pushed changes, along with the session-wiring coverage. Summary by Copilot:

  1. Align the SDK’s cached-token deadline — 35e1c96efc

    Desktop still requests more than 61 minutes of validity, but now subtracts the 60-second safety buffer from the lifetime returned to the SDK, preserving fractional seconds.

    The deterministic staggered-session regression covers your 3661/3659-second scenario: Session A receives an advertised lifetime of 3601 seconds, which becomes 3599 seconds two seconds later. Its modeled SDK preflight therefore invokes the provider rather than reusing the revoked token. Both providers receive the replacement through one shared renewal.

  2. Bind providers to their originating credential session — 8fcbe7555d, strengthened in fc9d34c9b7 and 575c6d779f

    Providers follow rotation within their original session, but retirement permanently prevents them from adopting a later sign-in. Binding uses owner-held account-snapshot/session identity, not endpoint/account ID or token-string equality, and happens before asynchronous preparation.

    Regressions cover sign-out/re-sign-in with the same identity, including reuse of the exact access-token string. The old provider rejects, a provider from the new account snapshot succeeds, and creating a provider from a stale snapshot also rejects.

  3. Test production session wiring — b9ab8c33b8

    Integration tests exercise normal client/session creation and capture configuration at the public SDK boundary. They verify that gitHubTokenProvider is attached, callable, follows rotation, and never exposes refresh tokens. Legacy static-token authentication remains unchanged.

@sergiou87
sergiou87 requested a review from niik October 6, 2026 11:35
niik
niik previously approved these changes Oct 7, 2026

@niik niik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the current changes against the review requirements. The implementation and regression coverage address the requested token lifetime alignment, credential-session binding, quota authentication, and cancellation cleanup. Live SDK rollover remains a rollout-validation item as documented.

@sergiou87
sergiou87 dismissed niik’s stale review October 7, 2026 12:37

The merge-base changed after approval.

@sergiou87
sergiou87 force-pushed the short-lived-tokens-7-copilot branch from b844d98 to 7be33ea Compare October 7, 2026 12:37
Base automatically changed from short-lived-tokens-6-images to development October 7, 2026 12:55
sergiou87 and others added 10 commits October 7, 2026 14:55
Copilot features (commit message generation, conflict resolution,
quota) run in the Copilot SDK runtime, which gets a GitHub token when
the client is created. A short-lived token can expire while a client
or session is still in use, and the runtime can't renew it by itself.

CopilotStore now:

- gets a fresh token from AccountsStore before creating a
  CopilotClient and before requesting quota;
- remembers which account created each client, and when creating a
  session for a refreshable account, passes a `gitHubTokenProvider`
  built by `createCopilotTokenProvider`.

The SDK calls that provider for the session's first token
("initial") and again when the current one nears expiry ("refresh").
It stores `now + expiresIn` as the token's deadline and asks again
once an hour or less remains. It never calls back because a token was
rejected, and it rejects any token with an hour or less left, failing
the session with no fallback. So the provider:

- only answers for the account's own GitHub host;
- renews with a 61-minute margin, which clears the SDK's one-hour
  threshold with room for IPC transit;
- returns the access token and its remaining lifetime, never the
  refresh token;
- throws a clear error when the lifetime is still an hour or less, or
  unknown. Guessing a lifetime could leave the SDK using a dead token
  until the guessed deadline.

Accounts with plain tokens get no provider, so the SDK keeps using the
static token as before and nothing changes for existing accounts.

Tests cover keeping the static token mode for plain accounts, meeting
the one-hour margin without exposing refresh tokens, and refusing
other hosts and signed-out accounts.

Co-authored-by: Copilot <[email protected]>
`fetchQuotaSnapshots` receives the caller's `Account` snapshot, whose
token can be one that has since been rotated away or is about to
expire. This branch changed it to ask `AccountsStore` for a fresh
account right before calling `client.rpc.account.getQuota` and to send
that token instead of `account.token`. The existing quota test uses a
plain, non-refreshable token and ignores the request argument, so
reverting that line would not fail any test.

The new test "requests quota with a renewed token for an expiring
account" in `copilot-store-test.ts` (inside "CopilotStore quota
snapshots", which already enables the preview feature):

- Builds an `AccountsStore` whose renewal returns `new-access`, and a
  `CopilotStore` on top of it with `createClient` replaced by a fake
  whose `getQuota` records the `gitHubToken` it is called with.
- Adds the account with a refreshable credential that expires now, so
  any request for a fresh token must renew it.
- Asserts the quota is returned and that `getQuota` was called exactly
  once, with `new-access`.

Because the fake `createClient` skips the renewal the real one does,
the call inside `fetchQuotaSnapshots` is the only thing that can
produce the renewed token: the test fails when that line is reverted
to `account.token` and passes with it. No source changes.

Addresses review feedback on #22942. The other finding (a test for
attaching the token provider to sessions) is intentionally not
addressed here.

Co-authored-by: Copilot <[email protected]>
The shared setup helper in refresh-token-consumers-test now takes the
initial credential instead of only its expiry, since the Git credential
tests also need plain tokens and long-lived refreshable ones. Update the
Copilot provider test that still passed an expiry timestamp, which no
longer type-checks after merging that change.

Also cover the case leases are most likely to affect for Copilot. Its token
provider asks for more than an hour of validity, because the SDK only asks
for a new token once less than an hour remains. If a Copilot session starts
during the token's last hour while a Git operation holds a lease on it, the
provider must wait for Git to release the token and then return a renewed
one, rather than receive the held token and fail with "GitHub returned
credentials without enough lifetime for a Copilot session". The new test
leases the token, checks that the provider neither resolves nor renews while
the lease is held, then releases it and expects the renewed token after a
single renewal.

Co-authored-by: Copilot <[email protected]>
Desktop requires 61 minutes of remaining validity for Copilot, while the SDK refreshes cached credentials at its one-hour preflight margin. Reporting the full lifetime left a one-minute interval in which a second session could rotate the token while the first session still considered the old, revoked token reusable.

Share the SDK margin and IPC safety-buffer constants between token acquisition and lifetime reporting. Subtract the 60-second buffer from expiresIn, so both consumers reach the same renewal deadline. Preserve fractional seconds instead of flooring: a token with 3660.5 seconds remaining must still advertise 3600.5 seconds rather than fall onto the SDK rejection boundary.

Reject credentials whose buffered lifetime is unknown or no longer exceeds one hour. Keep Desktop as the renewal owner and continue returning only an access token and lifetime, never refresh credentials.

Add deterministic coverage for staggered sessions, the fractional boundary, inclusive renewal at 61 minutes, undersized renewed credentials, and missing lifetime metadata. The three new bug reproductions failed before the fix; all 14 consumer tests now pass.

Validation: yarn test app/test/unit/refresh-token-consumers-test.ts passed (14 tests); yarn -s lint:fix passed; npx --no-install tsc -p . --noEmit --skipLibCheck passed. skipLibCheck avoids existing dependency declaration conflicts without skipping application type checking.
Matching an endpoint and numeric account ID allowed an existing Copilot provider to adopt credentials from a later sign-in as the same user. Looking up the original token on every callback would also be insufficient if a subsequent sign-in reused that token string.

Add a credential-session-bound access-token getter that captures the actual issuing session once. It follows normal rotation within that session, permanently rejects retirement, and returns an access token and expiry from one coherent credential snapshot. Recheck after asynchronous acquisition so concurrent renewal cannot hand out an obsolete token or pair it with replacement metadata. Replace the now-unused separate expiry lookup with this bounded API.

Construct each client's Copilot provider before asynchronous credential acquisition and retain it for all SDK sessions created by that client. Do not reconstruct the provider from account identity at session creation. Preserve generic fresh-account lookup semantics and the legacy static-token authentication mode. This does not introduce a lease for an entire Copilot invocation.

Cover normal renewal, same-user sign-in with different and identical token strings, obsolete account snapshots, retirement while waiting for a Git lease, concurrent renewal during handoff, and retirement during handoff. Three provider regressions failed before the fix and now pass.

Validation: yarn test app/test/unit/credential-sessions-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/stores/copilot-store-test.ts passed (80 tests); yarn test app/test/unit/accounts-store-test.ts passed (4 tests); yarn -s lint:fix passed; npx --no-install tsc -p . --noEmit --skipLibCheck passed.
Provider-only tests cannot prove that CopilotStore actually passes the callback to SDK-created sessions. Add isolated store coverage that runs the public commit-message entry point through the real client-creation and session-wiring code, without replacing private methods or manually populating the provider map.

Capture constructor options while returning real SDK client instances, then intercept SDK session creation at its configuration boundary. A sentinel error stops execution before runtime startup. Keep module mocks in a separate test file so existing statically imported store tests are unaffected. A BYOK model request bypasses unrelated model discovery, not authentication or production client/session construction.

Verify that refreshable credentials attach an invokable callback, advertise the buffered lifetime, rotate within the same sign-in, and never expose a refresh token. Verify that legacy credentials retain the static client token and attach no callback. Simulate same-user sign-in with the same token string during asynchronous credential lookup: the pending client's provider must remain retired, while a newly created client's provider succeeds.

Mutation checks proved these tests exercise the production wiring: omitting gitHubTokenProvider failed both refreshable tests, and moving provider binding after asynchronous credential lookup failed the pending-client test. Both temporary mutations were removed, with no remaining production diff.

Validation: yarn test app/test/unit/accounts-store-test.ts app/test/unit/credential-sessions-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/stores/copilot-store-test.ts app/test/unit/stores/copilot-store-credentials-test.ts passed (87 tests); yarn -s lint:fix passed; npx --no-install tsc -p . --noEmit --skipLibCheck passed.
A provider created after a same-user sign-in can otherwise adopt the new
credential session when GitHub reuses the access-token text. Looking up
historical tokens protects providers that were already bound, but cannot
identify which sign-in an older Account snapshot originally represented.

Associate Account objects with their originating credential session in an
owner-held WeakMap. Each snapshot keeps its first association permanently.
Restore returns a distinct installed snapshot when given an already-known
object, and adding an account does not reassign a previously bound input.
No session marker is added to Account fields or persisted account JSON.

Preserve the association when publishing renewed tokens, returning fresh
or leased accounts, refreshing profile metadata, and emitting redacted
invalidation accounts. Reject copies that change account identity or are
already associated with another session. Refreshability and bound getters
now use this association rather than matching token text or current user.

Reject unknown and retired snapshots when creating a bound token getter,
including legacy Copilot authentication paths. Ordinary endpoint/user-ID
fresh-account lookup deliberately retains its current-session behavior.

Cover late getter/provider creation after same-token replacement, immutable
copy propagation and reassociation, and sign-in replacement while built-in
Copilot model discovery is pending. The three original reproductions failed
before this fix; all focused tests now pass.

Validation:
- yarn test app/test/unit/accounts-store-test.ts app/test/unit/account-token-lifecycle-test.ts app/test/unit/credential-sessions-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/stores/copilot-store-test.ts app/test/unit/stores/copilot-store-credentials-test.ts: 133 passed, 0 failed.
- yarn -s lint:fix: passed.
- npx --no-install tsc -p . --noEmit --skipLibCheck: passed; skipLibCheck avoids existing dependency declaration conflicts.
- git diff --check: passed.
Capture a coherent credential context at commit-message generation entry,
before model discovery or any other asynchronous preparation. The static
client token getter and SDK session provider both retain the originating
account session instead of resolving whichever same-user sign-in is current
when preparation eventually finishes.

Pass that context through client construction. Check the runtime path first,
then acquire the session-bound static token immediately before handing it to
the SDK constructor. Retirement during runtime preparation now rejects both
refreshable and legacy clients before any SDK client or session is created.
This ordering also avoids rotating credentials for an unavailable runtime.

Metadata clients capture their own context at creation. Quota retrieval keeps
that context across SDK startup and uses its bound getter for the quota RPC,
rather than adopting credentials from a replacement sign-in. Static and
metadata token acquisition retain the ordinary ten-minute refresh margin;
only SDK session providers use the existing sixty-one-minute margin.

Preserve cancellation priority for already-aborted generation, the existing
client/session teardown behavior, and no-op conflict resolution without any
resolvable files. Install real accounts in cancellation fixtures that had
previously bypassed credential setup through private client stubs.

Replace the old fresh-account lookup injection with a real runtime-path
preparation boundary, covering same-token replacement for both credential
modes and successful use of the newly signed-in snapshot afterward. Add
quota-startup retirement and metadata-margin coverage. Verify both getters
are bound before model discovery begins. Removing early operation binding
makes that assertion fail; the temporary mutation has been restored.

Validation:
- The three preparation/startup regressions failed before this change.
- yarn test app/test/unit/accounts-store-test.ts app/test/unit/account-token-lifecycle-test.ts app/test/unit/credential-sessions-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/stores/copilot-store-test.ts app/test/unit/stores/copilot-store-credentials-test.ts: 137 passed, 0 failed.
- yarn -s lint:fix: passed.
- npx --no-install tsc -p . --noEmit --skipLibCheck: passed; existing dependency declaration conflicts remain excluded.
- git diff --check: passed.

These changes do not add invocation-long Copilot token leases or claim to
validate native SDK cached-token rollover against the live service.
Commit-message cancellation previously could not finish while model discovery
or static client authentication awaited a token leased by Git. The abort check
only ran after initialization, leaving generation state and the commit button
blocked until the lease ended or approached expiry.

Extract the existing session-cancellation pattern into a private typed waiter.
Use it for model discovery, client construction, and session creation. Abort
rejects only this operation's wait; shared renewal and cached model discovery
continue for other consumers. Do not start work for an already-aborted signal.

Track result ownership across completion/abort races. Stop a client delivered
after cancellation and disconnect abandoned sessions exactly once. Observe
late failures without unhandled rejections and log abandoned-result cleanup
failures explicitly. Keep normal handoff and teardown behavior unchanged.

Add production-boundary coverage with a real credential lease: cancellation
settles while the lease remains held, no SDK client is constructed prematurely,
and an independent consumer still receives the shared renewed token. After
release, the abandoned client is stopped once without creating a session.
Cover late runtime-path failure and strengthen model-discovery coverage to
cancel before resolving its shared promise instead of masking the stalled wait.

Validation:
- Three regressions failed before implementation.
- yarn test app/test/unit/stores/copilot-store-test.ts app/test/unit/stores/copilot-store-credentials-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/credential-sessions-test.ts: 94 passed, 0 failed.
- yarn -s lint:fix: passed.
- npx --no-install tsc -p . --noEmit --skipLibCheck: passed; existing dependency declaration conflicts remain excluded.
- git diff --check: passed.
Conflict resolution previously waited for SDK session creation without
observing cancellation. A token with forty-five minutes remaining can satisfy
static client authentication yet block the session provider's sixty-one-minute
preflight behind a Git lease. Cancelling left the chunk pending and delayed
client/session cleanup until that unrelated lease ended.

Use the scoped cancellation waiter for conflict client initialization and the
cancellation-aware session creator for every chunk, including validation retries.
Stop abandoned clients and disconnect sessions delivered after cancellation.
Translate the shared helper's cancellation error into the conflict-specific
abort type so cancelled operations are never retried or reported as transport
failures. Normal failure stages and validation retry behavior remain unchanged.

Reject already-aborted work before credential preparation, but preserve the
existing empty result when all files are skipped, including aborted no-op calls.
Retain the post-handoff abort check for sessions the caller already owns.

Add production-boundary regressions for pending client preparation, an actual
credential lease during forty-five-minute session preflight, and already-aborted
requests with no installed account. Assert cancellation settles before lease
release, client shutdown is immediate, late session disconnection happens once,
no new chunk is attempted, and a parallel credential consumer still completes
through the shared renewal. Cover completion/abort races and aborted no-op work.

Validation:
- Three conflict regressions failed before implementation.
- yarn test app/test/unit/stores/copilot-store-test.ts app/test/unit/stores/copilot-store-credentials-test.ts app/test/unit/refresh-token-consumers-test.ts app/test/unit/credential-sessions-test.ts: 98 passed, 0 failed.
- yarn -s lint:fix: passed.
- npx --no-install tsc -p . --noEmit --skipLibCheck: passed; existing dependency declaration conflicts remain excluded.
- git diff --check: passed.
@sergiou87
sergiou87 force-pushed the short-lived-tokens-7-copilot branch from 7be33ea to 30176cb Compare October 7, 2026 12:55
@sergiou87
sergiou87 merged commit 08e2df9 into development Oct 7, 2026
9 checks passed
@sergiou87
sergiou87 deleted the short-lived-tokens-7-copilot branch October 7, 2026 13:16
sergiou87 added a commit that referenced this pull request Oct 7, 2026
`fetchQuotaSnapshots` receives the caller's `Account` snapshot, whose
token can be one that has since been rotated away or is about to
expire. This branch changed it to ask `AccountsStore` for a fresh
account right before calling `client.rpc.account.getQuota` and to send
that token instead of `account.token`. The existing quota test uses a
plain, non-refreshable token and ignores the request argument, so
reverting that line would not fail any test.

The new test "requests quota with a renewed token for an expiring
account" in `copilot-store-test.ts` (inside "CopilotStore quota
snapshots", which already enables the preview feature):

- Builds an `AccountsStore` whose renewal returns `new-access`, and a
  `CopilotStore` on top of it with `createClient` replaced by a fake
  whose `getQuota` records the `gitHubToken` it is called with.
- Adds the account with a refreshable credential that expires now, so
  any request for a fresh token must renew it.
- Asserts the quota is returned and that `getQuota` was called exactly
  once, with `new-access`.

Because the fake `createClient` skips the renewal the real one does,
the call inside `fetchQuotaSnapshots` is the only thing that can
produce the renewed token: the test fails when that line is reverted
to `account.token` and passes with it. No source changes.

Addresses review feedback on #22942. The other finding (a test for
attaching the token provider to sessions) is intentionally not
addressed here.

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.

4 participants