Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(auth): survive a dropped sign-in stream instead of failing (#803) (#2928)
mike-inkeep5aa1fc26ef52
diff --git a/.changeset/wild-pears-shave.md b/.changeset/wild-pears-shave.mdnew file mode 100644index 000000000..f0dbf4a06--- /dev/null+++ b/.changeset/wild-pears-shave.md@@ -0,0 +1,9 @@+---+'@inkeep/open-knowledge': patch+---++Fix GitHub sign-in failing with "Sign-in stream ended without confirmation" when the connection to the local server blips (#803).++The sign-in stream between the browser and the local OpenKnowledge server sat completely idle from the moment the device code appeared until authorization finished, which is exactly what security software, VPN proxies, and browser tab-backgrounding cut off. Worse, that disconnect terminated the sign-in itself, so authorizing on github.com afterwards stored nothing.++Sign-in now survives those blips: the stream is kept alive with a periodic keepalive, a dropped connection no longer cancels the sign-in in progress, and the app reconnects to pick up a sign-in that completed while it was disconnected. Closing the dialog still cancels immediately. The countdown also shows the code's real expiry (about 15 minutes) instead of claiming it expired after 2.diff --git a/knip.config.ts b/knip.config.tsindex 563d574d8..64bfa20a9 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -122,7 +122,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/src/components/AuthModal.tsx b/packages/app/src/components/AuthModal.tsxindex 24e27f850..6746550a9 100644--- a/packages/app/src/components/AuthModal.tsx+++ b/packages/app/src/components/AuthModal.tsx@@ -1,7 +1,8 @@/*** AuthModal — GitHub sign-in dialog.*- * Device Flow: shows user_code, polls for completion, 2-minute timeout.+ * Device Flow: shows user_code and counts down to the deadline GitHub actually+ * issued (`expires_in`, ~15 min), not a local guess.* Calls POST /api/local-op/auth/login (streaming JSONL).** Entry patterns (what happens on open):@@ -125,15 +126,18 @@ interface DeviceFlowPanelProps {startFlow: () => AuthTransportHandle;}-const DEVICE_TIMEOUT_MS = 2 * 60 * 1000; // 2 minutes-function DeviceFlowPanel({ onSuccess, startFlow }: DeviceFlowPanelProps) {const { t } = useLingui();const [userCode, setUserCode] = useState<string | null>(null);const [verificationUri, setVerificationUri] = useState('https://github.com/login/device');const [copied, setCopied] = useState(false);const [error, setError] = useState<string | null>(null);- const [timeLeft, setTimeLeft] = useState(DEVICE_TIMEOUT_MS);+ // Wall-clock deadline from the `verification` event's `expires_in`. Driving+ // the countdown off a local constant instead told users the code died at 2:00+ // when GitHub had issued it for ~15 minutes, and "Code expired" at 2:00 was+ // also the point past which a dropped stream could no longer be recovered.+ const [expiresAt, setExpiresAt] = useState<number | null>(null);+ const [timeLeft, setTimeLeft] = useState(0);const cancelRef = useRef<(() => void) | null>(null);const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);@@ -153,6 +157,7 @@ function DeviceFlowPanel({ onSuccess, startFlow }: DeviceFlowPanelProps) {if (event.type === 'verification') {setUserCode(event.user_code);setVerificationUri(event.verification_uri);+ setExpiresAt(Date.now() + event.expires_in * 1000);setTimeLeft(event.expires_in * 1000);void copyToClipboard(event.user_code).then(() => {setCopied(true);@@ -208,13 +213,11 @@ function DeviceFlowPanel({ onSuccess, startFlow }: DeviceFlowPanelProps) {};}, []);- // Countdown timer+ // Countdown to the code's real deadline.useEffect(() => {- if (!userCode) return;- const start = Date.now();+ if (expiresAt === null) return;timerRef.current = setInterval(() => {- const elapsed = Date.now() - start;- const remaining = DEVICE_TIMEOUT_MS - elapsed;+ const remaining = expiresAt - Date.now();if (remaining <= 0) {setTimeLeft(0);if (timerRef.current) clearInterval(timerRef.current);@@ -226,7 +229,7 @@ function DeviceFlowPanel({ onSuccess, startFlow }: DeviceFlowPanelProps) {return () => {if (timerRef.current) clearInterval(timerRef.current);};- }, [userCode, t]);+ }, [expiresAt, t]);const minutesLeft = Math.floor(timeLeft / 60_000);const secondsLeft = Math.floor((timeLeft % 60_000) / 1000);diff --git a/packages/app/src/lib/transports/auth-transport.test.ts b/packages/app/src/lib/transports/auth-transport.test.tsindex 4a39fd95e..65edfac29 100644--- a/packages/app/src/lib/transports/auth-transport.test.ts+++ b/packages/app/src/lib/transports/auth-transport.test.ts@@ -125,20 +125,203 @@ describe('httpAuthTransport().start / ghLogin (streamAuthEndpoint)', () => {expect(events).toEqual([{ type: 'error', message: 'Device flow was denied' }]);});- test('a stream that ends without a terminal event surfaces the no-confirmation error', async () => {+ test('a stream that ends before any code is issued surfaces the no-confirmation error', async () => {+ // Nothing to recover: without a `verification` event there is no in-flight+ // device flow on the server to rejoin, so failing fast is correct.+ globalThis.fetch = vi.fn(async () => ndjsonResponse([])) as unknown as typeof fetch;++ const events = await collectEvents(httpAuthTransport().start() as never);+ expect(events.map((e) => e.type)).toEqual(['error']);+ expect(events[0]?.message).toContain('without confirmation');+ });++ test('keepalive ping lines are ignored — not surfaced, not terminal', async () => {globalThis.fetch = vi.fn(async () =>ndjsonResponse([+ JSON.stringify({ type: 'ping' }),JSON.stringify({type: 'verification',user_code: 'AB-12',verification_uri: 'https://github.com/login/device',expires_in: 900,}),+ JSON.stringify({ type: 'ping' }),+ JSON.stringify({ type: 'ping' }),+ JSON.stringify({ type: 'complete', host: 'github.com', login: 'octocat' }),]),) as unknown as typeof fetch;+ const events = await collectEvents(httpAuthTransport().start() as never);+ expect(events.map((e) => e.type)).toEqual(['verification', 'complete']);+ });+});++/**+ * Issue #803. The device code is on screen and still valid, then the loopback+ * stream is severed by something outside OpenKnowledge (AV/EDR inspection, VPN+ * proxy, tab-backgrounding). The server keeps the flow alive across the drop,+ * so the client's job is to notice the authorization landing anyway instead of+ * declaring an unrecoverable failure.+ */+describe('streamAuthEndpoint — recovery after a mid-flow stream drop', () => {+ const VERIFICATION = JSON.stringify({+ type: 'verification',+ user_code: 'AB-12',+ verification_uri: 'https://github.com/login/device',+ expires_in: 900,+ });++ /** A body that yields the verification line, then errors mid-stream. */+ function severedAfterVerification(): Response {+ let sent = false;+ return new Response(+ new ReadableStream<Uint8Array>({+ pull(controller) {+ if (!sent) {+ sent = true;+ controller.enqueue(new TextEncoder().encode(`${VERIFICATION}\n`));+ return;+ }+ controller.error(new TypeError('network error'));+ },+ }),+ { status: 200 },+ );+ }++ test('a severed stream recovers via the status poll once the token lands', async () => {+ let statusCalls = 0;+ globalThis.fetch = vi.fn(async (url: string) => {+ if (String(url).endsWith('/auth/status')) {+ statusCalls++;+ // Not signed in yet on the first probe; the user finishes authorizing+ // on github.com between polls.+ return new Response(+ JSON.stringify(+ statusCalls === 1+ ? { authenticated: false }+ : { authenticated: true, host: 'github.com', login: 'octocat', name: 'Mona' },+ ),+ { status: 200 },+ );+ }+ return severedAfterVerification();+ }) as unknown as typeof fetch;++ const events = await collectEvents(httpAuthTransport().start() as never);+ expect(events.map((e) => e.type)).toEqual(['verification', 'complete']);+ expect(events[1]?.login).toBe('octocat');+ expect(events[1]?.name).toBe('Mona');+ expect(statusCalls).toBeGreaterThanOrEqual(2);+ }, 20_000);++ test('a clean stream end after the code was issued also recovers rather than failing', async () => {+ // Some intermediaries close the connection tidily (FIN, no reset), so the+ // reader sees a normal end-of-stream with no terminal event.+ globalThis.fetch = vi.fn(async (url: string) => {+ if (String(url).endsWith('/auth/status')) {+ return new Response(+ JSON.stringify({ authenticated: true, host: 'github.com', login: 'octocat' }),+ { status: 200 },+ );+ }+ return ndjsonResponse([VERIFICATION]);+ }) as unknown as typeof fetch;++ const events = await collectEvents(httpAuthTransport().start() as never);+ expect(events.map((e) => e.type)).toEqual(['verification', 'complete']);+ expect(events[1]?.login).toBe('octocat');+ }, 20_000);++ test('an expired code ends recovery with the expiry error, not a stream error', async () => {+ globalThis.fetch = vi.fn(async (url: string) => {+ if (String(url).endsWith('/auth/status')) {+ return new Response(JSON.stringify({ authenticated: false }), { status: 200 });+ }+ // `expires_in: 0` — the code is already dead when the stream drops, so+ // recovery must not spin.+ return ndjsonResponse([+ JSON.stringify({+ type: 'verification',+ user_code: 'AB-12',+ verification_uri: 'https://github.com/login/device',+ expires_in: 0,+ }),+ ]);+ }) as unknown as typeof fetch;+const events = await collectEvents(httpAuthTransport().start() as never);expect(events.map((e) => e.type)).toEqual(['verification', 'error']);- expect(events[1]?.message).toContain('without confirmation');+ expect(events[1]?.message).toContain('expired');+ });++ test('user cancel stops recovery and tells the server it was intentional', async () => {+ const cancelCalls: unknown[] = [];+ globalThis.fetch = vi.fn(async (url: string, init?: RequestInit) => {+ if (String(url).endsWith('/auth/cancel')) {+ cancelCalls.push(JSON.parse(String(init?.body)));+ return new Response('{}', { status: 200 });+ }+ if (String(url).endsWith('/auth/status')) {+ return new Response(JSON.stringify({ authenticated: false }), { status: 200 });+ }+ return ndjsonResponse([VERIFICATION]);+ }) as unknown as typeof fetch;++ const handle = httpAuthTransport().start();+ const iter = handle.events[Symbol.asyncIterator]();+ const first = await iter.next();+ expect((first.value as { type: string }).type).toBe('verification');++ // The user closes the modal while recovery is polling.+ handle.cancel();++ // Iteration ends with no error event — a deliberate cancel is not a failure.+ expect((await iter.next()).done).toBe(true);+ expect(cancelCalls).toEqual([{ channel: 'login' }]);+ });++ test('cancel after a completed flow does not tell the server to cancel', async () => {+ // The modal unmounts on success and calls `cancel()` in cleanup; firing a+ // cancel there could displace a NEW flow the user has since started.+ const cancelCalls: unknown[] = [];+ globalThis.fetch = vi.fn(async (url: string) => {+ if (String(url).endsWith('/auth/cancel')) {+ cancelCalls.push(url);+ return new Response('{}', { status: 200 });+ }+ return ndjsonResponse([+ VERIFICATION,+ JSON.stringify({ type: 'complete', host: 'github.com', login: 'octocat' }),+ ]);+ }) as unknown as typeof fetch;++ const handle = httpAuthTransport().start();+ await collectEvents(handle as never);+ handle.cancel();+ expect(cancelCalls).toEqual([]);+ });++ test('the gh-login flow cancels its own channel, not the device-flow slot', async () => {+ const cancelBodies: unknown[] = [];+ globalThis.fetch = vi.fn(async (url: string, init?: RequestInit) => {+ if (String(url).endsWith('/auth/cancel')) {+ cancelBodies.push(JSON.parse(String(init?.body)));+ return new Response('{}', { status: 200 });+ }+ if (String(url).endsWith('/auth/status')) {+ return new Response(JSON.stringify({ authenticated: false }), { status: 200 });+ }+ return ndjsonResponse([VERIFICATION]);+ }) as unknown as typeof fetch;++ const handle = httpAuthTransport().ghLogin?.('ghes.acme.test') as never as {+ events: AsyncIterable<unknown>;+ cancel: () => void;+ };+ const iter = handle.events[Symbol.asyncIterator]();+ await iter.next();+ handle.cancel();+ expect(cancelBodies).toEqual([{ channel: 'gh-login' }]);});});diff --git a/packages/app/src/lib/transports/auth-transport.ts b/packages/app/src/lib/transports/auth-transport.tsindex 61b58dcb7..ee15bbb69 100644--- a/packages/app/src/lib/transports/auth-transport.ts+++ b/packages/app/src/lib/transports/auth-transport.ts@@ -15,8 +15,10 @@*/import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';+import { t } from '@lingui/core/macro';import { consumeAuthEventStream } from '@/components/auth-event-stream';import type { OkDesktopBridge, OkLocalOpAuthEvent } from '@/lib/desktop-bridge-types';+import { httpAuthQueryTransport } from './auth-query-transport';import { createBufferedAsyncStream } from './buffered-async-stream';/**@@ -27,6 +29,23 @@ import { createBufferedAsyncStream } from './buffered-async-stream';*/type AuthEvent = OkLocalOpAuthEvent;+/**+ * Which streaming flow a handle is driving. The server holds one concurrency+ * slot per flow, so an explicit cancel has to name the one it means.+ */+type AuthStreamChannel = 'login' | 'gh-login';++/**+ * Poll cadence while recovering a sign-in whose event stream dropped, backing+ * off from the first value to the second. Each poll spawns an `auth status`+ * subprocess server-side, so a fixed tight interval would cost ~300 spawns+ * across a code's full 15-minute life. Backing off keeps that under ~100 while+ * still closing the modal within ~10s of the user authorizing — and the early+ * polls, when the user is most likely to be finishing up, stay fast.+ */+const RECOVERY_POLL_INITIAL_MS = 2_000;+const RECOVERY_POLL_MAX_MS = 10_000;+export interface AuthTransportHandle {/** Async iterable of events. Iteration ends after `complete` / `error` / `cancel()`. */readonly events: AsyncIterable<AuthEvent>;@@ -62,14 +81,128 @@ export interface AuthTransport {ghLogin?(host: string): AuthTransportHandle;}+/** Resolve after `ms`, or as soon as `signal` aborts. */+function delay(ms: number, signal: AbortSignal): Promise<void> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ signal.removeEventListener('abort', onAbort);+ resolve();+ }, ms);+ function onAbort(): void {+ clearTimeout(timer);+ resolve();+ }+ signal.addEventListener('abort', onAbort, { once: true });+ });+}++/**+ * Tell the server the user backed out. The server deliberately keeps a flow+ * alive across a transport drop (a severed loopback stream is not intent), so+ * closing the modal has to say so explicitly or the device-flow child would+ * keep polling and could land a token nobody is waiting for. Best-effort: the+ * flow's own timeout and the fresh-start displacement both bound it anyway.+ */+function postAuthCancel(channel: AuthStreamChannel): void {+ void fetch('/api/local-op/auth/cancel', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ channel }),+ }).catch((err: unknown) => {+ // Best-effort — the flow's own timeout and fresh-start displacement are the+ // backstops. Still worth surfacing: a cancel that never lands leaves a+ // device-flow child running for up to 16 minutes, and the environments this+ // fix targets are exactly the ones where a loopback POST might not make it.+ console.warn(+ '[auth-transport] Cancel request failed (best-effort):',+ err instanceof Error ? err.message : err,+ );+ });+}++/**+ * The event stream ended before the flow reached a terminal event.+ *+ * That is the #803 failure: on Windows the idle loopback stream gets severed by+ * an intermediary (AV/EDR inspection, VPN proxy, tab-backgrounding) while the+ * device code is still perfectly valid. The server keeps the flow running+ * across the drop, so the authorization the user is finishing on github.com can+ * still land — poll the status relay until it does, or until the code the user+ * is looking at expires.+ *+ * Caveat worth knowing: on the re-authenticate path, a still-valid existing+ * token makes the first poll report `authenticated` immediately, so recovery+ * can conclude "connected" from the old credential rather than the new grant.+ * `auth status` validates live against GitHub, so a revoked or expired token+ * still reads as unauthenticated — the residue is a user re-authing purely to+ * widen scopes, who is told they are connected (which they are) a grant early.+ */+async function recoverAfterStreamDrop(+ push: (event: AuthEvent) => void,+ signal: AbortSignal,+ codeExpiresAt: number,+ host: string | undefined,+): Promise<void> {+ const query = httpAuthQueryTransport();+ let interval = RECOVERY_POLL_INITIAL_MS;+ while (!signal.aborted && Date.now() < codeExpiresAt) {+ try {+ const status = await query.status(host ? { host } : undefined);+ if (signal.aborted) return;+ if (status.authenticated) {+ push({+ type: 'complete',+ host: status.host,+ login: status.login,+ name: status.name,+ email: status.email,+ });+ return;+ }+ } catch (err) {+ // Keep polling — a probe failure is usually transient. Surface it though:+ // otherwise a recovery that was broken the whole time is indistinguishable+ // from a user who simply never authorized, since both end at the same+ // expiry error 15 minutes later. Matches the bounded-warn pattern the+ // NDJSON line-drop above uses.+ console.warn(+ '[auth-transport] Recovery probe failed:',+ err instanceof Error ? err.message : err,+ );+ }+ await delay(interval, signal);+ interval = Math.min(interval * 1.5, RECOVERY_POLL_MAX_MS);+ }+ if (signal.aborted) return;+ // Same deadline the modal's countdown reached, so the two agree.+ push({ type: 'error', message: t`Code expired — please try again` });+}+/*** Shared streaming client for the two device-flow endpoints (`auth/login` and* `auth/gh-login`). Both stream the same NDJSON AuthEvent shape; only the URL +* body differ, so the reader/parser lives here once.*/-function streamAuthEndpoint(url: string, requestBody: unknown): AuthTransportHandle {- return createBufferedAsyncStream<AuthEvent>((push, signal) => {+function streamAuthEndpoint(+ url: string,+ requestBody: { host?: string; json: true },+ channel: AuthStreamChannel,+): AuthTransportHandle {+ // Latches once a terminal event is pushed, so `cancel()` can tell "the user+ // backed out of a live flow" (tell the server) from "the flow already+ // finished and the component is unmounting" (nothing to cancel).+ let settled = false;++ const stream = createBufferedAsyncStream<AuthEvent>((rawPush, signal) => {+ const push = (event: AuthEvent): void => {+ if (event.type === 'complete' || event.type === 'error') settled = true;+ rawPush(event);+ };void (async () => {+ // Set once the device code is on screen. Its presence is what makes a+ // dropped stream recoverable: before it there is no flow to rejoin, and+ // after it we know exactly how long the code stays good.+ let codeExpiresAt: number | null = null;try {const res = await fetch(url, {method: 'POST',@@ -80,7 +213,7 @@ function streamAuthEndpoint(url: string, requestBody: unknown): AuthTransportHanif (!res.ok) {// Pre-stream RFC 9457 problem+json: the server emitted an error before// committing to the NDJSON stream. Surface the typed `title`.- let message = 'Failed to start sign-in — try again';+ let message = t`Failed to start sign-in — try again`;try {const result = ProblemDetailsSchema.safeParse((await res.json()) as unknown);if (result.success) message = result.data.title;@@ -91,7 +224,7 @@ function streamAuthEndpoint(url: string, requestBody: unknown): AuthTransportHanreturn;}if (!res.body) {- push({ type: 'error', message: 'Failed to start sign-in — try again' });+ push({ type: 'error', message: t`Failed to start sign-in — try again` });return;}const terminatedByEvent = await consumeAuthEventStream(@@ -117,27 +250,53 @@ function streamAuthEndpoint(url: string, requestBody: unknown): AuthTransportHan'problem' in parsed) {const p = (parsed as { problem: { title?: string; detail?: string } }).problem;- push({ type: 'error', message: p?.detail || p?.title || 'Unknown error' });+ push({ type: 'error', message: p?.detail || p?.title || t`Unknown error` });return 'terminal';}+ // Idle keepalive from `streamAuthFlow` — carries no meaning, exists+ // only so the connection never sits at zero bytes long enough for a+ // reaper to close it. Not an AuthEvent; never terminal.+ if ((parsed as { type?: unknown }).type === 'ping') return 'continue';const event = parsed as AuthEvent;+ if (event.type === 'verification') {+ codeExpiresAt = Date.now() + event.expires_in * 1000;+ }push(event);if (event.type === 'complete' || event.type === 'error') return 'terminal';return 'continue';},);- if (!terminatedByEvent && !signal.aborted) {+ if (terminatedByEvent || signal.aborted) return;+ if (codeExpiresAt === null) {+ // The stream died before a code was ever issued: nothing is in flight+ // to rejoin, so there is nothing to recover.push({type: 'error',- message: 'Sign-in stream ended without confirmation — please try again',+ message: t`Sign-in stream ended without confirmation — please try again`,});+ return;}+ await recoverAfterStreamDrop(push, signal, codeExpiresAt, requestBody.host);} catch (err) {if (err instanceof Error && err.name === 'AbortError') return;- push({ type: 'error', message: 'Connection error — try again' });+ // A severed connection usually lands here rather than as a clean end,+ // so this is the primary #803 recovery entry point, not the tidy one.+ if (codeExpiresAt !== null) {+ await recoverAfterStreamDrop(push, signal, codeExpiresAt, requestBody.host);+ return;+ }+ push({ type: 'error', message: t`Connection error — try again` });}})();});++ return {+ events: stream.events,+ cancel: (): void => {+ if (!settled) postAuthCancel(channel);+ stream.cancel();+ },+ };}/**@@ -147,10 +306,10 @@ function streamAuthEndpoint(url: string, requestBody: unknown): AuthTransportHanexport function httpAuthTransport(): AuthTransport {return {start(): AuthTransportHandle {- return streamAuthEndpoint('/api/local-op/auth/login', { json: true });+ return streamAuthEndpoint('/api/local-op/auth/login', { json: true }, 'login');},ghLogin(host: string): AuthTransportHandle {- return streamAuthEndpoint('/api/local-op/auth/gh-login', { host, json: true });+ return streamAuthEndpoint('/api/local-op/auth/gh-login', { host, json: true }, 'gh-login');},async pat(host: string, token: string): Promise<PatResult> {try {@@ -165,7 +324,7 @@ export function httpAuthTransport(): AuthTransport {}// The relay returns RFC 9457 problem+json on a rejected token / TLS /// network error; surface the bounded `detail` (the CLI's real reason).- let error = 'Failed to store the token — try again';+ let error = t`Failed to store the token — try again`;try {const result = ProblemDetailsSchema.safeParse(await res.json());if (result.success) error = result.data.detail || result.data.title;@@ -174,7 +333,7 @@ export function httpAuthTransport(): AuthTransport {}return { ok: false, error };} catch {- return { ok: false, error: 'Connection error — try again' };+ return { ok: false, error: t`Connection error — try again` };}},};@@ -183,6 +342,12 @@ export function httpAuthTransport(): AuthTransport {/*** IPC transport — wraps `bridge.localOp.auth.start()`. The bridge stream's* event type IS this transport's event type, so no adaptation is needed.+ *+ * No stream-drop recovery here, and none needed: the IPC channel is in-process,+ * so there is no idle connection for an intermediary to sever, and the main+ * process already keeps the flow alive when a renderer goes away — only an+ * explicit `:cancel` stops it. That is the lifetime model `streamAuthFlow` now+ * matches on the HTTP side.*/export function ipcAuthTransport(bridge: OkDesktopBridge): AuthTransport {return {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex ee087292e..5f85c8598 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1162,6 +1162,7 @@"LiAw2k": ["What this changes"],"LlHqdU": ["Initializing project"],"Llyqvo": ["This usually means one of:"],+ "LnVIW4": ["Failed to start sign-in — try again"],"LpB85N": ["Plain"],"LtI9AS": ["Owner"],"LtSYdi": ["Reveal in Finder"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 060e41038..dbcc5f187 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1901,6 +1901,7 @@ msgid "Code copied to clipboard"msgstr "Code copied to clipboard"#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Code expired — please try again"msgstr "Code expired — please try again"@@ -2155,6 +2156,7 @@ msgid "Connection dropped"msgstr "Connection dropped"#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Connection error — try again"msgstr "Connection error — try again"@@ -4025,7 +4027,12 @@ msgstr "Failed to save the schema field"msgid "Failed to save theme setting"msgstr "Failed to save theme setting"+#: src/lib/transports/auth-transport.ts+msgid "Failed to start sign-in — try again"+msgstr "Failed to start sign-in — try again"+#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Failed to store the token — try again"msgstr "Failed to store the token — try again"@@ -8539,6 +8546,7 @@ msgid "Sign in to {agentName} first"msgstr "Sign in to {agentName} first"#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Sign-in stream ended without confirmation — please try again"msgstr "Sign-in stream ended without confirmation — please try again"@@ -9885,6 +9893,7 @@ msgid "Unknown component: {unregisteredComponentName}"msgstr "Unknown component: {unregisteredComponentName}"#: src/components/DocumentErrorBoundary.tsx+#: src/lib/transports/auth-transport.tsmsgid "Unknown error"msgstr "Unknown error"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 602c273ea..dc933c14e 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1162,6 +1162,7 @@"LiAw2k": ["Ŵĥàţ ţĥĩś ćĥàńĝēś"],"LlHqdU": ["Ĩńĩţĩàĺĩźĩńĝ ƥŕōĴēćţ"],"Llyqvo": ["Ţĥĩś ũśũàĺĺŷ ḿēàńś ōńē ōƒ:"],+ "LnVIW4": ["Ƒàĩĺēď ţō śţàŕţ śĩĝń-ĩń — ţŕŷ àĝàĩń"],"LpB85N": ["Ƥĺàĩń"],"LtI9AS": ["Ōŵńēŕ"],"LtSYdi": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 3be750309..53d5cf494 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1897,6 +1897,7 @@ msgid "Code copied to clipboard"msgstr ""#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Code expired — please try again"msgstr ""@@ -2151,6 +2152,7 @@ msgid "Connection dropped"msgstr ""#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Connection error — try again"msgstr ""@@ -4021,7 +4023,12 @@ msgstr ""msgid "Failed to save theme setting"msgstr ""+#: src/lib/transports/auth-transport.ts+msgid "Failed to start sign-in — try again"+msgstr ""+#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Failed to store the token — try again"msgstr ""@@ -8535,6 +8542,7 @@ msgid "Sign in to {agentName} first"msgstr ""#: src/components/AuthModal.tsx+#: src/lib/transports/auth-transport.tsmsgid "Sign-in stream ended without confirmation — please try again"msgstr ""@@ -9881,6 +9889,7 @@ msgid "Unknown component: {unregisteredComponentName}"msgstr ""#: src/components/DocumentErrorBoundary.tsx+#: src/lib/transports/auth-transport.tsmsgid "Unknown error"msgstr ""diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.tsindex a53190f30..172dd32c6 100644--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts@@ -242,6 +242,9 @@ const EXEMPT_HANDLERS = new Set([// thread.'handleLocalOpAuthPat','handleLocalOpAuthGhLogin',+ // POST /api/local-op/auth/cancel — user-initiated stop for an in-flight+ // device flow. Terminates a subprocess on the local machine; writes nothing.+ 'handleLocalOpAuthCancel',// POST /api/local-op/embeddings/{set-key,clear-key} — loopback-gated writes of// the machine-global embeddings key to ~/.ok/secrets.yml. Operate on the local// user's credential file, not agent-authored content — same rationale as thediff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.tsindex 1b698c030..c6caa87c9 100644--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts@@ -196,6 +196,9 @@ const EXEMPT_HANDLERS = new Set([// gate doesn't apply.'handleLocalOpAuthPat','handleLocalOpAuthGhLogin',+ // Stops an in-flight device-flow subprocess. Terminates a child and frees a+ // concurrency slot — no Y.Doc target at all.+ 'handleLocalOpAuthCancel',// Loopback-gated writes of the machine-global embeddings key to the user's// secrets file, plus the read-only endpoint probe — no Y.Doc mutation, so the// conflict-refusal gate doesn't apply.diff --git a/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts b/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.tsindex 8314ffe47..ad8d7c717 100644--- a/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts+++ b/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts@@ -1,11 +1,18 @@/*** HTTP auth-login concurrency-slot lifecycle — the cancel→reopen contract.*- * Invariant under test: a cancelled / disconnected auth-login must immediately- * free or displace the concurrency slot, so a fresh login attempt is always+ * Invariant under test: a cancelled / disconnected auth-login must never leave+ * the concurrency slot permanently pinned, so a fresh login attempt is always* admittable. Closing the device-flow modal without completing must NOT block* the next start.*+ * Two admission routes satisfy that, and which one applies depends on how the+ * flow ended. An EXPLICIT cancel (`POST /api/local-op/auth/cancel`, or a flow+ * that ran to completion) frees the slot synchronously. A bare transport+ * disconnect does not: the flow deliberately survives it (see+ * `local-op-auth-stream-resilience.test.ts`), so the slot stays held and the+ * next start is admitted by displacing the stale controller.+ ** The desktop editor window drives `POST /api/local-op/auth/login` over HTTP* (the Navigator window uses the IPC twin, hardened separately). These tests* exercise the real `createApiExtension` route handler over a real@@ -125,8 +132,9 @@ async function openLoginUntilVerification(): Promise<{return { status: res.status, verification: null, controller };}-/** Simulate the client closing the modal: abort the in-flight login fetch.- * The handler wires `res.on('close')` → `flow.cancel()`. */+/** Simulate the transport dropping: abort the in-flight login fetch. The+ * handler treats this as a detach, not a cancel — the flow keeps running and+ * keeps its slot, so the next start is admitted via displacement. */function disconnect(controller: AbortController): void {controller.abort();}@@ -140,14 +148,14 @@ describe('HTTP auth-login cancel→reopen concurrency-slot contract', () => {expect(first.status).toBe(200);expect(first.verification?.type).toBe('verification');- // Client closes the modal. The child swallows SIGTERM and is still alive.+ // The transport drops. The flow survives (by design), so the slot is still+ // held by a child that also swallows SIGTERM.disconnect(first.controller);- // Reopen: a fresh login must NOT be rejected with 429. The slot has to be- // freed (synchronous release on disconnect) or displaced (fresh-start- // backstop). On the unfixed handler the slot is still held by the lingering- // child, so this reopen gets 429 "An auth login operation is already in- // progress." and the assertions below fail.+ // Reopen: a fresh login must NOT be rejected with 429. The slot is still+ // held, so admission rides on the fresh-start displacement backstop.+ // Without it the lingering child pins the slot and this reopen gets 429+ // "An auth login operation is already in progress."const second = await openLoginUntilVerification();expect(second.status).not.toBe(429);expect(second.status).toBe(200);@@ -173,20 +181,19 @@ describe('HTTP auth-login cancel→reopen concurrency-slot contract', () => {});test("a cancelled login's late child-exit does not release the successor's slot (ownership-guarded release)", async () => {- // Pins the subtle correctness property a synchronous-free + displacement- // fix still needs: object-identity ownership on the slot release. After a- // login is cancelled and a FRESH login is admitted, the OLD (cancelled)- // device-flow child eventually exits — and its `done.finally` must NOT- // release the slot the successor now owns. Without the ownership guard- // (`authLoginInFlight === flow`), the stale child's late `done.finally`- // deletes the Set key the successor holds, so a third start no longer- // displaces the live login but spuriously acquires a "free" slot — leaking- // the second login's child as an orphaned background poller (the exact- // "don't leave a poller writing an unconfirmed token" property the- // disconnect handler exists for).+ // Pins the subtle correctness property the displacement backstop needs:+ // object-identity ownership on the slot release. After a login is displaced+ // and a FRESH login owns the slot, the OLD device-flow child eventually+ // exits — and its `done.finally` must NOT release the slot the successor+ // now owns. Without the ownership guard (`authLoginInFlight === flow`), the+ // stale child's late `done.finally` deletes the Set key the successor+ // holds, so a third start no longer displaces the live login but spuriously+ // acquires a "free" slot — leaving the second login's child running as an+ // orphaned background poller alongside the third. Single-flight per channel+ // is what stops two children from racing to store a token.//// The fake CLI here exits SOON after SIGTERM (not after a long linger) so- // the cancelled child's `done.finally` fires DURING the measurement window,+ // the displaced child's `done.finally` fires DURING the measurement window,// while the successor owns the slot. To remove timing flakiness the exit is// gated on a `go` file the test writes only after the successor is admitted:// child exit (and therefore the late release) is ordered strictly after the@@ -201,12 +208,7 @@ describe('HTTP auth-login cancel→reopen concurrency-slot contract', () => {// without displacing, #2's child is never terminated, and only one prior// child records an exit.//- // RED status: on the CURRENT (unfixed) handler this test fails earlier, at- // the "#2 admitted" step, for the same reason the two tests above fail (the- // slot stays pinned → reopen 429s). The ownership property it isolates is- // only reachable once the synchronous-free + displacement halves land; it- // then PASSES, and regresses to RED if the ownership guard on the release is- // later removed.+ // Regresses to RED if the ownership guard on the release is removed.const dir = mkdtempSync(join(tmpdir(), 'ok-auth-ownership-'));tmpDirs.push(dir);const exitMarker = join(dir, 'child-exits.log');@@ -260,17 +262,17 @@ describe('HTTP auth-login cancel→reopen concurrency-slot contract', () => {expect(first.status).toBe(200);expect(first.verification?.type).toBe('verification');- // Client closes the modal → res.on('close') → flow.cancel() → SIGTERM to- // child #1. The child does not exit yet (no go-signal).+ // The transport drops. Child #1 keeps running and keeps the slot.disconnect(first.controller);- // Login #2 (reopen) must be admitted and now OWNS the slot. (Unfixed code- // 429s here — the masked failure shared with the tests above.)+ // Login #2 (reopen) must be admitted and now OWNS the slot — admission+ // displaces #1, SIGTERM-ing its child. The child does not exit yet (no+ // go-signal).const second = await openLoginUntilVerification();expect(second.status).toBe(200);expect(second.verification?.type).toBe('verification');- // Now let the cancelled child #1 exit — strictly after #2 claimed the slot.+ // Now let the displaced child #1 exit — strictly after #2 claimed the slot.// Its `done.finally` fires here; the ownership guard must stop it from// releasing #2's slot.writeFileSync(goSignal, '1', 'utf-8');@@ -289,7 +291,7 @@ describe('HTTP auth-login cancel→reopen concurrency-slot contract', () => {expect(third.status).toBe(200);expect(third.verification?.type).toBe('verification');- // Contract: two prior children (#1 cancelled, #2 displaced) must have been+ // Contract: two prior children (#1 and #2, both displaced) must have been// terminated. If #1's late release freed #2's slot, #2 is orphaned and only// one child ever records an exit → this times out (RED).await pollUntil(() => markerCount() >= 2, 4000, 20);@@ -300,7 +302,7 @@ describe('HTTP auth-login cancel→reopen concurrency-slot contract', () => {test('a login that completes normally releases the slot, and the next login is admitted via normal acquisition (not displacement)', async () => {// Pins the happy-path release. The three tests above all exercise the- // cancel / displace paths; none covers a login that COMPLETES. When a+ // displacement path; none covers a login that COMPLETES. When a// device flow completes, `flow.done` resolves and the ownership-guarded// `done.finally` must release the slot so the next login acquires it via// the normal `tryAcquire` path.diff --git a/packages/app/tests/integration/local-op-auth-stream-resilience.test.ts b/packages/app/tests/integration/local-op-auth-stream-resilience.test.tsnew file mode 100644index 000000000..b80931e60--- /dev/null+++ b/packages/app/tests/integration/local-op-auth-stream-resilience.test.ts@@ -0,0 +1,366 @@+/**+ * HTTP auth-login stream resilience — a dropped connection must not lose a+ * sign-in that is still completing.+ *+ * Reported as inkeep/open-knowledge#803: on Windows, "Connect GitHub" shows a+ * device code and then fails with "Sign-in stream ended without confirmation".+ * The severed hop is the LOOPBACK one (browser ↔ local OK server), cut by an+ * intermediary the user never sees — an AV/EDR SSL-inspection agent, a VPN+ * local proxy, a backgrounded tab. Two properties turn that blip into a+ * permanent failure, and both are pinned here:+ *+ * 1. The stream sat at zero bytes for the whole authorization wait, which is+ * what an idle-connection reaper looks for. The server now heartbeats.+ * 2. The disconnect SIGTERM'd the device-flow child, so authorizing on+ * github.com afterwards stored nothing and there was nothing to recover.+ * A disconnect is now a detach; only an EXPLICIT cancel kills the flow.+ *+ * These exercise the real `createApiExtension` route handlers over a real+ * `http.Server` via `createTestServer`, with fake device-flow CLIs injected+ * through `localOpCliArgs` — no real GitHub, no real `auth login` child. Each+ * fake records its own fate (SIGTERM vs ran-to-completion) in a marker file, so+ * the assertions are about observable subprocess lifetime rather than handler+ * internals.+ */++import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { createTestServer, pollUntil, type TestServer, wait } from './test-harness';++let server: TestServer;+const openControllers: AbortController[] = [];+const tmpDirs: string[] = [];++afterEach(async () => {+ for (const c of openControllers) c.abort();+ openControllers.length = 0;+ if (server) await server.cleanup();+ for (const dir of tmpDirs) rmSync(dir, { recursive: true, force: true });+ tmpDirs.length = 0;+});++function scratchDir(): { sigtermMarker: string; completedMarker: string } {+ const dir = mkdtempSync(join(tmpdir(), 'ok-auth-resilience-'));+ tmpDirs.push(dir);+ return { sigtermMarker: join(dir, 'sigterm'), completedMarker: join(dir, 'completed') };+}++/**+ * Fake device-flow CLI that models the #803 timeline: emit a code, then have+ * the user authorize `authorizeAfterMs` later. It records which way it ended —+ * `sigterm` if it was killed, `completed` if it lived long enough to store a+ * token — so a test can assert the flow's fate with the client long gone.+ */+function timedDeviceFlowCli(opts: {+ sigtermMarker: string;+ completedMarker: string;+ authorizeAfterMs: number;+}): string[] {+ return [+ process.execPath,+ '-e',+ `+ const fs = require('node:fs');+ process.on('SIGTERM', () => {+ try { fs.writeFileSync(${JSON.stringify(opts.sigtermMarker)}, '1'); } catch (e) {}+ process.exit(0);+ });+ console.log(JSON.stringify({type:'verification', user_code:'WDJB-MJHT', verification_uri:'https://github.com/login/device', expires_in:900}));+ setTimeout(() => {+ try { fs.writeFileSync(${JSON.stringify(opts.completedMarker)}, '1'); } catch (e) {}+ console.log(JSON.stringify({type:'complete', host:'github.com', login:'octocat'}));+ process.exit(0);+ }, ${opts.authorizeAfterMs});+ `,+ ];+}++/**+ * POST a login and read until the first `verification` event. Leaves the+ * response stream open so the caller can sever it via the returned controller.+ * Returns the reader too, for tests that keep consuming (heartbeats).+ */+async function openLoginUntilVerification(): Promise<{+ status: number;+ sawVerification: boolean;+ controller: AbortController;+ reader: ReadableStreamDefaultReader<Uint8Array> | null;+}> {+ const controller = new AbortController();+ openControllers.push(controller);++ const res = await fetch(`http://127.0.0.1:${server.port}/api/local-op/auth/login`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ signal: controller.signal,+ });+ if (res.status !== 200 || !res.body) {+ await res.text().catch(() => {});+ return { status: res.status, sawVerification: false, controller, reader: null };+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ buffer = lines.pop() ?? '';+ for (const line of lines) {+ if (!line.trim()) continue;+ if ((JSON.parse(line) as { type?: string }).type === 'verification') {+ return { status: res.status, sawVerification: true, controller, reader };+ }+ }+ }+ return { status: res.status, sawVerification: false, controller, reader };+}++/**+ * Capture the structured `console.warn` events the handler emits. The server+ * runs in this process, so its `console.warn` is ours.+ */+function captureServerWarns(): { events: string[]; restore: () => void } {+ const events: string[] = [];+ const orig = console.warn;+ console.warn = (...args: unknown[]): void => {+ if (typeof args[0] === 'string') events.push(args[0]);+ };+ return {+ events,+ restore: () => {+ console.warn = orig;+ },+ };+}++async function postAuthCancel(channel?: 'login' | 'gh-login'): Promise<number> {+ const res = await fetch(`http://127.0.0.1:${server.port}/api/local-op/auth/cancel`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(channel ? { channel } : {}),+ });+ await res.text().catch(() => {});+ return res.status;+}++describe('auth-login survives a transport drop (#803)', () => {+ test('a disconnected client does not kill the device flow — the token still lands', async () => {+ // The core regression. The user has the code on screen, the loopback stream+ // is severed, and the user then authorizes on github.com. If the disconnect+ // kills the child, that authorization stores nothing and the sign-in is+ // unrecoverable no matter what the UI does next.+ const { sigtermMarker, completedMarker } = scratchDir();+ server = await createTestServer({+ localOpCliArgs: timedDeviceFlowCli({+ sigtermMarker,+ completedMarker,+ authorizeAfterMs: 600,+ }),+ });++ const login = await openLoginUntilVerification();+ expect(login.status).toBe(200);+ expect(login.sawVerification).toBe(true);++ const warns = captureServerWarns();+ try {+ // The stream is severed while the user is still on github.com.+ login.controller.abort();++ // A flow left running with nobody attached is logged, so the "it detached+ // rather than died" path is visible in a support bundle instead of only+ // being inferable later from a displacement warn.+ await pollUntil(() => warns.events.some((e) => e.includes('auth-stream-detached')), 5000, 20);+ expect(warns.events.some((e) => e.includes('auth-stream-detached'))).toBe(true);++ // The flow must run to completion anyway.+ await pollUntil(() => existsSync(completedMarker), 5000, 20);+ } finally {+ warns.restore();+ }+ expect(existsSync(completedMarker)).toBe(true);+ expect(existsSync(sigtermMarker)).toBe(false);+ });++ test('an explicit cancel does kill the flow — backing out still means backing out', async () => {+ // The property the old kill-on-disconnect protected. It did not disappear;+ // it moved onto a signal that actually means intent.+ const { sigtermMarker, completedMarker } = scratchDir();+ server = await createTestServer({+ localOpCliArgs: timedDeviceFlowCli({+ sigtermMarker,+ completedMarker,+ authorizeAfterMs: 3000,+ }),+ });++ const login = await openLoginUntilVerification();+ expect(login.sawVerification).toBe(true);++ const warns = captureServerWarns();+ try {+ expect(await postAuthCancel('login')).toBe(200);+ // Mirror the real client: `AuthTransportHandle.cancel()` POSTs the cancel+ // and THEN aborts the stream, so the socket closes while the child is+ // still winding down from the SIGTERM. That ordering is what makes the+ // slot-ownership check in `onClientClose` load-bearing.+ login.controller.abort();+ await pollUntil(() => existsSync(sigtermMarker), 5000, 20);+ // Give a would-be spurious detach log time to fire.+ await wait(150);+ } finally {+ warns.restore();+ }+ expect(existsSync(sigtermMarker)).toBe(true);+ // The child died well before its "user authorized" timer, so no token was+ // ever stored.+ expect(existsSync(completedMarker)).toBe(false);+ // A deliberate cancel is NOT a detach. The socket closes here too, so+ // without the slot-ownership check in `onClientClose` this would log one —+ // and a detach event that fires on every normal cancel tells an operator+ // nothing about whether an intermediary is cutting streams.+ expect(warns.events.some((e) => e.includes('auth-stream-detached'))).toBe(false);+ });++ test('cancel frees the slot synchronously — the next login acquires it without displacement', async () => {+ // A cancel that killed the child but left the slot held would 429 the very+ // next attempt during the SIGTERM-to-exit window. Isolation: displacement+ // would ALSO admit the next login, so "200" alone can't tell a working+ // release from one masked by the backstop — assert the displacement warn+ // never fired. The server runs in-process, so its `console.warn` is ours.+ const { sigtermMarker, completedMarker } = scratchDir();+ server = await createTestServer({+ localOpCliArgs: timedDeviceFlowCli({+ sigtermMarker,+ completedMarker,+ authorizeAfterMs: 5000,+ }),+ });++ const first = await openLoginUntilVerification();+ expect(first.sawVerification).toBe(true);+ expect(await postAuthCancel('login')).toBe(200);++ const displacementWarns: string[] = [];+ const origWarn = console.warn;+ console.warn = (...args: unknown[]): void => {+ const head = typeof args[0] === 'string' ? args[0] : '';+ if (head.includes('idempotent-start-replaced-stale-slot')) displacementWarns.push(head);+ };+ try {+ const second = await openLoginUntilVerification();+ expect(second.status).toBe(200);+ expect(second.sawVerification).toBe(true);+ second.controller.abort();+ } finally {+ console.warn = origWarn;+ }+ expect(displacementWarns).toHaveLength(0);+ });++ test('cancel is idempotent — cancelling with nothing in flight is a 200, not an error', async () => {+ // The client fires this on modal close without knowing the server's state.+ server = await createTestServer({});+ expect(await postAuthCancel('login')).toBe(200);+ expect(await postAuthCancel()).toBe(200);+ });++ test('cancelling the gh-login channel leaves an in-flight device-flow login alone', async () => {+ // Each streaming flow owns its own concurrency slot; a cancel names one.+ const { sigtermMarker, completedMarker } = scratchDir();+ server = await createTestServer({+ localOpCliArgs: timedDeviceFlowCli({+ sigtermMarker,+ completedMarker,+ authorizeAfterMs: 800,+ }),+ });++ const login = await openLoginUntilVerification();+ expect(login.sawVerification).toBe(true);++ expect(await postAuthCancel('gh-login')).toBe(200);++ await pollUntil(() => existsSync(completedMarker), 5000, 20);+ expect(existsSync(completedMarker)).toBe(true);+ expect(existsSync(sigtermMarker)).toBe(false);+ });+});++describe('auth-login stream keepalive', () => {+ test('an idle stream emits periodic ping lines and stays open', async () => {+ // Between `verification` and `complete` the flow writes nothing for as long+ // as the user takes to authorize. A connection carrying zero bytes is what+ // an idle reaper severs, so the envelope keeps bytes moving. Cadence is+ // shortened here; production is 15s.+ const { sigtermMarker, completedMarker } = scratchDir();+ server = await createTestServer({+ authStreamHeartbeatMs: 100,+ localOpCliArgs: timedDeviceFlowCli({+ sigtermMarker,+ completedMarker,+ authorizeAfterMs: 60_000,+ }),+ });++ const login = await openLoginUntilVerification();+ expect(login.sawVerification).toBe(true);+ const reader = login.reader;+ expect(reader).not.toBeNull();+ if (!reader) return;++ const decoder = new TextDecoder();+ const types: string[] = [];+ let buffer = '';+ const deadline = Date.now() + 3000;+ while (types.filter((t) => t === 'ping').length < 3 && Date.now() < deadline) {+ const { done, value } = await reader.read();+ // A terminated stream is the failure this guards: pings must never end it.+ expect(done).toBe(false);+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ buffer = lines.pop() ?? '';+ for (const line of lines) {+ if (!line.trim()) continue;+ types.push((JSON.parse(line) as { type?: string }).type ?? '');+ }+ }++ expect(types.filter((t) => t === 'ping').length).toBeGreaterThanOrEqual(3);+ // The keepalive carries no meaning of its own — no terminal event snuck in.+ expect(types).not.toContain('complete');+ expect(types).not.toContain('error');++ login.controller.abort();+ });++ test('the keepalive stops when the client goes away', async () => {+ // A detached flow must not keep writing to a dead socket for the rest of+ // the code's 15-minute life.+ const { sigtermMarker, completedMarker } = scratchDir();+ server = await createTestServer({+ authStreamHeartbeatMs: 50,+ localOpCliArgs: timedDeviceFlowCli({+ sigtermMarker,+ completedMarker,+ authorizeAfterMs: 60_000,+ }),+ });++ const login = await openLoginUntilVerification();+ expect(login.sawVerification).toBe(true);+ login.controller.abort();++ // Many heartbeat periods pass with no attached client. If the interval kept+ // firing at a destroyed response the writes would throw past the guard.+ await wait(400);+ expect(existsSync(sigtermMarker)).toBe(false);+ });+});diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.tsindex 7aece65be..d6be09e83 100644--- a/packages/app/tests/integration/test-harness.ts+++ b/packages/app/tests/integration/test-harness.ts@@ -143,6 +143,11 @@ export interface CreateTestServerOptions {* the mid-stream error path without requiring a real CLI install.*/localOpCliArgs?: string[];+ /**+ * Keepalive cadence for the streaming auth flows, in ms. Tests that assert+ * the heartbeat shorten it so an idle stream is observable quickly.+ */+ authStreamHeartbeatMs?: number;/*** Override `os.homedir()` for user-global resolution (`~/.ok/global.yml` and* global-scope skills at `<home>/.ok/skills`). Pass a tempdir so global@@ -287,6 +292,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): PcontentRoot: options.gitEnabled === true ? '.' : undefined,enableTestRoutes: true,localOpCliArgs: options.localOpCliArgs,+ authStreamHeartbeatMs: options.authStreamHeartbeatMs,configHomedirOverride: homeOverride,mdManager: options.mdManager,pullIntervalSeconds: options.pullIntervalSeconds,diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex c014b1413..8f9d95287 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8890f6739..c18c086d5 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 3d5fd0771..f06c1614e 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,6 +65,7 @@ export function tryLineLevelCombine(return { clean: true, merged };}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex 4b8890476..3f0880aa5 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 596f8320e..99156c1f5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -805,6 +805,8 @@ export {LinkPreviewResponseSchema,type LintViolationWarning,LintViolationWarningSchema,+ type LocalOpAuthCancelRequest,+ LocalOpAuthCancelRequestSchema,type LocalOpAuthEmptySuccess,LocalOpAuthEmptySuccessSchema,type LocalOpAuthHostRequest,diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 9807a7e82..4499dbc92 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,3 +1,4 @@+export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 193e286b0..47f0d07e4 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex c7518d614..fb5ac8e8a 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex f55912407..6319f264f 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex b1f252c31..8dc3a81b5 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Root as HastRoot } from 'hast';import type { List, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -85,7 +86,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 8b36807fd..fc30bda02 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -196,6 +197,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -244,6 +246,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -263,6 +266,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -331,6 +335,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -577,6 +582,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -657,6 +663,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -935,6 +942,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1060,6 +1068,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex fa0be9e86..b79e9aef7 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,3 +1,4 @@+import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex 3162881fc..d41c42367 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex 74226af8e..113eca075 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,3 +1,4 @@+import { DRAFT07_SCHEMA_URIS } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex 176822faf..b49bc9fd2 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,3 +1,4 @@+import Ajv, { type ValidateFunction } from 'ajv';import addFormats from 'ajv-formats';import { isMap, isScalar, parseDocument } from 'yaml';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex d458fea1f..0ae95da09 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 5e832aa19..be5871ed9 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -13,6 +14,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex da6c477e9..772183427 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -69,6 +70,7 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 679c72ef7..f84967798 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 9864b3b60..7e4a9a48b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 7f2d5adca..e9e507469 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 5a5e4c42a..f8f5e8530 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 0dd54070e..96304e7a5 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,3 +1,4 @@+import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 46cc6a074..542204403 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex be97d4d62..fe73659e6 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 7f6dfcfc3..fd22d2c7b 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex cd245c38c..c5bfd2386 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/core/src/schemas/api/local-op.ts b/packages/core/src/schemas/api/local-op.tsindex 544f08ce7..b2c305522 100644--- a/packages/core/src/schemas/api/local-op.ts+++ b/packages/core/src/schemas/api/local-op.ts@@ -223,8 +223,28 @@ export const LocalOpAuthStatusSuccessSchema = zexport type LocalOpAuthStatusSuccess = z.infer<typeof LocalOpAuthStatusSuccessSchema>;/**- * Success body for `POST /api/local-op/auth/signout` and- * `POST /api/local-op/auth/set-identity`. Empty object — clients only branch+ * Request body for `POST /api/local-op/auth/cancel` — the explicit,+ * user-initiated stop for a streaming device-flow sign-in. `channel` picks+ * which of the two streaming flows to cancel (`/auth/login` vs+ * `/auth/gh-login`), since each holds its own concurrency slot. Defaults to+ * `login`, the flow every non-enterprise client runs.+ *+ * This exists because a transport disconnect is deliberately NOT treated as a+ * cancel: on loopback the stream can be severed by an inspection proxy or a+ * backgrounded tab, and killing the flow there strands a sign-in the user is+ * still completing on github.com. Intent needs its own signal.+ */+export const LocalOpAuthCancelRequestSchema = z+ .object({+ channel: z.enum(['login', 'gh-login']).default('login'),+ })+ .loose() satisfies StandardSchemaV1;+export type LocalOpAuthCancelRequest = z.infer<typeof LocalOpAuthCancelRequestSchema>;++/**+ * Success body for `POST /api/local-op/auth/signout`,+ * `POST /api/local-op/auth/set-identity`, and+ * `POST /api/local-op/auth/cancel`. Empty object — clients only branch* on HTTP status (200 = success). `.loose()` for forward-compat (e.g., a* future `signedOutAt: ISO` echo).*/diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 21c24c934..b8bdf4d12 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -125,6 +125,7 @@ import {LintFixRequestSchema,LintFixResultSchema,type LintViolationWarning,+ LocalOpAuthCancelRequestSchema,LocalOpAuthEmptySuccessSchema,type LocalOpAuthHostRequest,LocalOpAuthHostRequestSchema,@@ -2781,6 +2782,12 @@ export interface ApiExtensionOptions {* ['open-knowledge'] in production.*/localOpCliArgs?: string[];+ /**+ * Keepalive cadence for the streaming auth flows, in ms. Production uses the+ * 15s default; tests override it so the heartbeat is observable inside a+ * normal test budget without faking timers around a real HTTP stream.+ */+ authStreamHeartbeatMs?: number;/*** Path to the project's parent git working tree (i.e. the repo root, not* the shadow git dir). Used for upload tmp-file placement, git-relative@@ -3045,6 +3052,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {onAgentWrite,getSyncEngine,localOpCliArgs = ['open-knowledge'],+ authStreamHeartbeatMs,projectDir,getPrincipal,homeDirOverride,@@ -12631,6 +12639,27 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {const LOCAL_OP_AUTH_PAT_KEY = '/api/local-op/auth/pat';const LOCAL_OP_AUTH_GH_LOGIN_KEY = '/api/local-op/auth/gh-login';+ /**+ * Keepalive cadence for the two streaming auth flows. Between `verification`+ * and `complete` the device flow writes nothing for as long as the user takes+ * to authorize — up to the code's ~15-minute life — and a loopback connection+ * carrying zero bytes is exactly what an idle-connection reaper severs+ * (AV/EDR SSL-inspection agents, VPN local proxies, some tab-backgrounding).+ * A periodic no-op line keeps bytes flowing. `{ type: 'ping' }` is not an+ * `AuthEvent`: consumers skip it, it never terminates the stream, and it does+ * not touch the code's expiry.+ */+ const AUTH_STREAM_HEARTBEAT_MS = authStreamHeartbeatMs ?? 15_000;++ /**+ * Wall-clock cap on a device-flow child, deliberately longer than the generic+ * `LOCAL_OP_TIMEOUT_MS`. GitHub issues codes with `expires_in: 899` (~15 min)+ * and the UI now counts down to that real deadline, so a 10-minute SIGTERM+ * would kill the flow while the code on the user's screen is still good. The+ * CLI's own poller gives up first at `expired_token`; this is only a backstop.+ */+ const AUTH_DEVICE_FLOW_TIMEOUT_MS = 16 * 60 * 1000;+/*** Default host for the auth relay endpoints when the request omits `host`.* Read per-request (not cached): the origin remote can change over the@@ -12655,8 +12684,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {* OK's store) while gh-login runs `gh auth login --web` (gh's OAuth app, works* on GHES, token → gh keyring → tier A) — so the caller supplies `makeFlow`.* Everything else is identical and lives here once: the concurrency slot with- * displace-on-restart, NDJSON streaming, client-disconnect cancel, sync-resume,- * and the ownership-guarded slot release.+ * displace-on-restart, NDJSON streaming, the idle keepalive, disconnect+ * detach, sync-resume, and the ownership-guarded slot release.*/function streamAuthFlow(cfg: {res: ServerResponse;@@ -12717,6 +12746,28 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// Wrap raw `error` events in the RFC 9457 streaming envelope.const writeStreamError = createStreamingErrorWriter(res, handler);+ // Three-way guard + try-catch matches the writer's race-window defense; a+ // lost progress event is not crashworthy.+ const writeLine = (line: string): void => {+ if (res.writableEnded || res.destroyed) return;+ try {+ res.write(line);+ } catch {+ /* socket destroyed between guard and write — line lost */+ }+ };++ let heartbeat: ReturnType<typeof setInterval> | null = setInterval(() => {+ writeLine(`${JSON.stringify({ type: 'ping' })}\n`);+ }, AUTH_STREAM_HEARTBEAT_MS);+ // A keepalive must never be the reason the process stays up.+ heartbeat.unref();+ const stopHeartbeat = (): void => {+ if (heartbeat === null) return;+ clearInterval(heartbeat);+ heartbeat = null;+ };+const flow = makeFlow((event: AuthEvent) => {if (event.type === 'error') {writeStreamError(500, 'urn:ok:error:auth-failed', streamErrorMessage, {@@ -12726,38 +12777,63 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}// On `complete`, resume a SyncEngine parked in `auth-error` so a reconnect// restores sync without an app restart. Server-authoritative: works- // regardless of which UI surface ran the sign-in.+ // regardless of which UI surface ran the sign-in — and, since the flow now+ // outlives its client connection, regardless of whether anyone is still+ // listening when the token lands.resumeSyncOnAuthEvent(event, getSyncEngine);- // Three-way guard + try-catch matches the writer's race-window defense; a- // lost progress event is not crashworthy.- if (!res.writableEnded && !res.destroyed) {- try {- res.write(`${JSON.stringify(event)}\n`);- } catch {- /* socket destroyed between guard and write — event lost */- }- }+ writeLine(`${JSON.stringify(event)}\n`);});inFlight.current = flow;- // Kill the child if the client disconnects so the flow doesn't keep polling- // and write a token the user never saw confirmed. Free the slot synchronously- // (ownership-guarded) rather than waiting for the SIGTERM'd child to exit —- // that window would otherwise 429 a reopen.+ // A transport disconnect is NOT a cancel, and must not kill the flow.+ //+ // On loopback the stream gets severed by things the user never sees — an+ // AV/EDR inspection agent, a VPN local proxy, a backgrounded tab. Killing+ // the child there turns a blip into an unrecoverable sign-in: the user+ // finishes authorizing on github.com and no token is ever stored, with no+ // way back except starting over for a fresh code. So a disconnect only+ // stops the writer; the flow runs on to its own timeout (or the code's+ // expiry) and a reconnecting client picks the outcome up from+ // `POST /api/local-op/auth/status`.+ //+ // What the old kill-on-disconnect protected — don't land a token after the+ // user backed out — rides on an EXPLICIT signal instead: `POST+ // /api/local-op/auth/cancel` when the modal closes, or displacement by a+ // fresh start. That is the lifetime model the IPC twin has always had+ // (`handleAuthStart` in desktop/src/main/ipc/local-op.ts), where a vanished+ // renderer never killed the flow either and only `:cancel` did; HTTP was+ // the outlier purely because a socket close was the only signal it had.+ //+ // The slot stays HELD here. Releasing it on disconnect would let a+ // concurrent start spawn a second device-flow child alongside the live one;+ // a genuine restart still gets in via the stale-slot displacement above.const onClientClose = () => {- flow.cancel();- if (inFlight.current === flow) {- inFlight.current = null;- localOpGuard.release(guardKey);- }+ stopHeartbeat();+ // Log only a GENUINE detach — a flow left running with nobody attached.+ // An explicit cancel already cleared the slot synchronously before the+ // client's socket closed, and a displaced flow no longer owns it either,+ // so this identity check is what separates "an intermediary cut us off"+ // from routine teardown. Without it this fires on every normal cancel and+ // the signal is worthless. Completion needs no check: `flow.done.finally`+ // removes this listener before ending the response.+ if (inFlight.current !== flow) return;+ console.warn(+ JSON.stringify({+ event: 'ok-local-op:auth-stream-detached',+ channel: 'auth',+ transport: 'http',+ handler,+ }),+ );};res.on('close', onClientClose);// `flow.done` cannot reject (`proc.done` only resolves; the onEvent callback// is throw-safe), so `.finally` needs no IIFE-level try/catch. The release is- // ownership-guarded: a displaced/disconnected flow that already freed or+ // ownership-guarded: a displaced/cancelled flow that already freed or// handed off the slot must not release a successor's when its child exits.void flow.done.finally(() => {+ stopHeartbeat();res.off('close', onClientClose);if (!res.writableEnded && !res.destroyed) {try {@@ -12815,7 +12891,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {runDeviceFlowSubprocess({cliArgs: localOpCliArgs,host,- timeoutMs: LOCAL_OP_TIMEOUT_MS,+ timeoutMs: AUTH_DEVICE_FLOW_TIMEOUT_MS,onEvent,}),});@@ -12858,7 +12934,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {concurrentMessage: 'A gh sign-in is already in progress.',streamErrorMessage: 'gh sign-in reported an error.',makeFlow: (onEvent) =>- runGhDeviceLoginSubprocess({ host, ghPath, timeoutMs: LOCAL_OP_TIMEOUT_MS, onEvent }),+ runGhDeviceLoginSubprocess({+ host,+ ghPath,+ timeoutMs: AUTH_DEVICE_FLOW_TIMEOUT_MS,+ onEvent,+ }),});},{@@ -12869,6 +12950,68 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {},);+ /**+ * POST /api/local-op/auth/cancel+ *+ * Body: { channel?: 'login' | 'gh-login' }+ * Explicit, user-initiated stop for a streaming sign-in — the intent signal+ * that a transport disconnect deliberately is not (see `streamAuthFlow`).+ * SIGTERMs the device-flow child so it can't land a token the user backed out+ * of, and frees the concurrency slot synchronously so a reopen right behind+ * the cancel isn't 429'd during the SIGTERM-to-exit window.+ *+ * Idempotent by construction: the client fires this on modal close without+ * knowing whether a flow is still running, so "nothing in flight" is a 200,+ * not an error.+ *+ * Deliberately has no `localOpGuard` slot of its own, unlike its sibling+ * local-op endpoints. Those guard a subprocess spawn; this one spawns+ * nothing and does no IO, so the body runs to completion with no `await` in+ * it — two concurrent cancels cannot interleave, and the second reads a+ * null slot and no-ops. A guard here would buy nothing and add a failure+ * mode that inverts the endpoint's purpose: a 429'd cancel leaves the flow+ * running, which is precisely what the caller asked to stop.+ */+ const HANDLE_LOCAL_OP_AUTH_CANCEL = 'local-op-auth-cancel';+ const handleLocalOpAuthCancel = withValidation(+ LocalOpAuthCancelRequestSchema,+ // Wrapped so an unexpected throw still lands as a typed 500. The body+ // itself has no failure mode — hence no `errorResponse` of its own.+ catchErrors(+ async (_req, res, body) => {+ const target =+ body.channel === 'gh-login'+ ? { inFlight: authGhLoginInFlight, guardKey: LOCAL_OP_AUTH_GH_LOGIN_KEY }+ : { inFlight: authLoginInFlight, guardKey: LOCAL_OP_AUTH_LOGIN_KEY };+ const flow = target.inFlight.current;+ if (flow) {+ flow.cancel();+ // Free the slot rather than waiting for the SIGTERM'd child to exit,+ // so a reopen right behind the cancel isn't 429'd during that window.+ // Ownership-guarded by construction: we clear the same reference we+ // just read, and the cancelled flow's own `done.finally` re-checks+ // identity, so its late exit can't free a successor's slot.+ target.inFlight.current = null;+ localOpGuard.release(target.guardKey);+ }+ successResponse(+ res,+ 200,+ LocalOpAuthEmptySuccessSchema,+ {},+ { handler: HANDLE_LOCAL_OP_AUTH_CANCEL },+ );+ },+ { handler: HANDLE_LOCAL_OP_AUTH_CANCEL, title: 'Failed to cancel the sign-in.' },+ ),+ {+ handler: HANDLE_LOCAL_OP_AUTH_CANCEL,+ method: 'POST',+ preBodyGate: (req, res) =>+ checkLocalOpSecurity(req, res, { handler: HANDLE_LOCAL_OP_AUTH_CANCEL }),+ },+ );+/*** POST /api/local-op/auth/status*@@ -20176,6 +20319,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {'/api/local-op/auth/status': handleLocalOpAuthStatus,'/api/local-op/auth/pat': handleLocalOpAuthPat,'/api/local-op/auth/gh-login': handleLocalOpAuthGhLogin,+ '/api/local-op/auth/cancel': handleLocalOpAuthCancel,'/api/local-op/auth/repos': handleLocalOpAuthRepos,'/api/local-op/auth/signout': handleLocalOpAuthSignout,'/api/local-op/auth/set-identity': handleLocalOpAuthSetIdentity,diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex dc6e1e3b0..e57e5b534 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -208,6 +208,7 @@ export interface BootServerOptions| 'wipRef'| 'destroyTimeoutMs'| 'localOpCliArgs'+ | 'authStreamHeartbeatMs'| 'onAgentWrite'| 'shadowRepo'| 'enableTestRoutes'@@ -674,6 +675,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {shadowRepo: opts.shadowRepo,destroyTimeoutMs: opts.destroyTimeoutMs,localOpCliArgs: opts.localOpCliArgs,+ authStreamHeartbeatMs: opts.authStreamHeartbeatMs,onAgentWrite: opts.onAgentWrite,lockKind,skipStateManifestCheck: opts.skipStateManifestCheck,diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex ba585c1e8..c393bcfac 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -251,6 +251,12 @@ export interface ServerOptions {* runtime that launched this server — necessary in dev (bun + .ts entry).*/localOpCliArgs?: string[];+ /**+ * Keepalive cadence for the streaming auth flows, in ms. Defaults to 15s in+ * `createApiExtension`; tests shorten it so an idle stream's heartbeat is+ * observable inside a normal test budget.+ */+ authStreamHeartbeatMs?: number;/*** Server kind written into the lock metadata. `interactive` (default) for* user-facing boots; `mcp-spawned` for the MCP detach-spawn path. Desktop@@ -591,6 +597,7 @@ export function createServer(options: ServerOptions): ServerInstance {contentRoot,destroyTimeoutMs = 10_000,localOpCliArgs,+ authStreamHeartbeatMs,skipStateManifestCheck = false,singleDocRelPath,ephemeral = false,@@ -1838,6 +1845,7 @@ export function createServer(options: ServerOptions): ServerInstance {onAgentWrite: options.onAgentWrite,getSyncEngine: () => syncEngine,localOpCliArgs,+ authStreamHeartbeatMs,projectDir,resolveEmbed,getPrincipal: () => loadedPrincipal,