Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Tag telemetry with the client surface (PRD-9145) (#5947)

Andrew Mikofalvye2bad6fb8ad8
diff --git a/.changeset/telemetry-client-surface.md b/.changeset/telemetry-client-surface.md
new file mode 100644
index 000000000..9e90a4180
--- /dev/null
+++ b/.changeset/telemetry-client-surface.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Local telemetry now records whether the editor ran in OK Desktop, a browser tab or an AI editor's browser pane, on server HTTP spans and logs and on opt-in frontend traces. The value leaves your machine only in a bug report you send or through OpenTelemetry export you enable.
diff --git a/packages/app/src/editor/provider-pool.test.ts b/packages/app/src/editor/provider-pool.test.ts
index 16a192cda..1182e4ed1 100644
--- a/packages/app/src/editor/provider-pool.test.ts
+++ b/packages/app/src/editor/provider-pool.test.ts
@@ -812,7 +812,7 @@ describe('buildAuthToken (MECHANISM-ONLY — CRDT restart recovery + client vers
if (!parsed) throw new Error('expected valid token');
expect(parsed.clientProtocolVersion).toBe(PROTOCOL_VERSION);
expect(typeof parsed.clientRuntimeVersion).toBe('string');
- expect(parsed.clientKind).toBe('web');
+ expect(parsed.clientKind).toBe('browser');
expect(parsed.principalId).toBeUndefined();
expect(parsed.expectedServerInstanceId).toBeUndefined();
});
@@ -824,7 +824,7 @@ describe('buildAuthToken (MECHANISM-ONLY — CRDT restart recovery + client vers
expect(parsed.principalId).toBe('p-1');
expect(parsed.tabSessionId).toBe('s-1');
expect(parsed.expectedServerInstanceId).toBe('server-instance-abc');
- expect(parsed.clientKind).toBe('web');
+ expect(parsed.clientKind).toBe('browser');
});
test('omits expectedServerInstanceId when the cache is null', () => {
diff --git a/packages/app/src/lib/client-fetch.test.ts b/packages/app/src/lib/client-fetch.test.ts
index 0f6afcb61..eb79d7f3c 100644
--- a/packages/app/src/lib/client-fetch.test.ts
+++ b/packages/app/src/lib/client-fetch.test.ts
@@ -55,17 +55,25 @@ describe('installClientFetchWrapper', () => {
await window.fetch('/api/documents');
expect(calls[0]?.input).toBe('/api/documents');
expect(header(calls[0], PROTOCOL)).toBe('2');
- expect(header(calls[0], KIND)).toBe('web');
+ expect(header(calls[0], KIND)).toBe('browser');
expect(typeof header(calls[0], RUNTIME)).toBe('string');
});
+ test('web mode passes an absolute same-origin /api/* string through unchanged with headers', async () => {
+ const { calls } = stubWindowFetch();
+ installClientFetchWrapper();
+ await window.fetch('http://localhost:5173/api/pages?depth=1');
+ expect(calls[0]?.input).toBe('http://localhost:5173/api/pages?depth=1');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
+ expect(header(calls[0], KIND)).toBe('browser');
+ });
+
test('desktop mode rewrites relative /api/* to apiOrigin AND injects headers', async () => {
const { calls } = stubWindowFetch();
installClientFetchWrapper({ apiOrigin: 'http://localhost:59534' });
await window.fetch('/api/document?docName=foo&cache=bust');
expect(calls[0]?.input).toBe('http://localhost:59534/api/document?docName=foo&cache=bust');
expect(header(calls[0], PROTOCOL)).toBe('2');
- expect(header(calls[0], KIND)).toBe('web');
});
test('absolute apiOrigin /api/* gets headers without double-rewrite', async () => {
@@ -74,7 +82,22 @@ describe('installClientFetchWrapper', () => {
await window.fetch('http://localhost:59534/api/install-skill', { method: 'POST' });
expect(calls[0]?.input).toBe('http://localhost:59534/api/install-skill');
expect(header(calls[0], PROTOCOL)).toBe('2');
- expect(header(calls[0], KIND)).toBe('web');
+ });
+
+ test('desktop mode rewrites an absolute file:///api/* string to apiOrigin', async () => {
+ const { calls } = stubWindowFetch();
+ installClientFetchWrapper({ apiOrigin: 'http://localhost:59534' });
+ await window.fetch('file:///api/documents?showAll=true&dir=&depth=1');
+ expect(calls[0]?.input).toBe('http://localhost:59534/api/documents?showAll=true&dir=&depth=1');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
+ });
+
+ test('desktop mode rewrites an absolute same-origin /api/* string to apiOrigin', async () => {
+ const { calls } = stubWindowFetch();
+ installClientFetchWrapper({ apiOrigin: 'http://localhost:59534' });
+ await window.fetch('http://localhost:5173/api/pages');
+ expect(calls[0]?.input).toBe('http://localhost:59534/api/pages');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
});
test('rewrites URL object with same-origin /api/* path + injects headers', async () => {
@@ -82,7 +105,7 @@ describe('installClientFetchWrapper', () => {
installClientFetchWrapper({ apiOrigin: 'http://localhost:59534' });
await window.fetch(new URL('/api/backlinks?docName=foo', 'http://localhost:5173'));
expect(calls[0]?.input).toBe('http://localhost:59534/api/backlinks?docName=foo');
- expect(header(calls[0], KIND)).toBe('web');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
});
test('passes absolute external http:// URLs through unchanged, no headers', async () => {
@@ -131,7 +154,7 @@ describe('installClientFetchWrapper', () => {
expect(rewritten).toBeInstanceOf(Request);
expect((rewritten as Request).url).toBe('http://localhost:59534/api/agent-write-md');
expect((rewritten as Request).method).toBe('POST');
- expect(header(calls[0], KIND)).toBe('web');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
expect(header(calls[0], 'content-type')).toBe('application/json');
});
diff --git a/packages/app/src/lib/client-fetch.ts b/packages/app/src/lib/client-fetch.ts
index 491022bc8..1d2d5fac3 100644
--- a/packages/app/src/lib/client-fetch.ts
+++ b/packages/app/src/lib/client-fetch.ts
@@ -50,7 +50,7 @@ function resolveApiTarget(input: RequestInfo | URL, apiOrigin: string | undefine
}
const parsed = tryParseUrl(input);
if (parsed && isLocalApiUrl(parsed, apiOrigin)) {
- return { isApi: true, url: input };
+ return { isApi: true, url: rewriteToApiOrigin(parsed, input, apiOrigin) };
}
return { isApi: false, url: input };
}
@@ -58,14 +58,18 @@ function resolveApiTarget(input: RequestInfo | URL, apiOrigin: string | undefine
const parsed = input instanceof URL ? input : tryParseUrl(input.url, window.location.origin);
if (parsed && isLocalApiUrl(parsed, apiOrigin)) {
const original = input instanceof URL ? input.href : input.url;
- if (apiOrigin && (parsed.origin === window.location.origin || parsed.protocol === 'file:')) {
- return { isApi: true, url: apiOrigin + parsed.pathname + parsed.search + parsed.hash };
- }
- return { isApi: true, url: original };
+ return { isApi: true, url: rewriteToApiOrigin(parsed, original, apiOrigin) };
}
return { isApi: false, url: input instanceof URL ? input.href : input.url };
}
+function rewriteToApiOrigin(parsed: URL, original: string, apiOrigin: string | undefined): string {
+ if (apiOrigin && (parsed.origin === window.location.origin || parsed.protocol === 'file:')) {
+ return apiOrigin + parsed.pathname + parsed.search + parsed.hash;
+ }
+ return original;
+}
+
function tryParseUrl(url: string, base?: string): URL | null {
try {
return new URL(url, base);
diff --git a/packages/app/src/lib/client-version.test.ts b/packages/app/src/lib/client-version.test.ts
index 56405a2bf..eec74ec02 100644
--- a/packages/app/src/lib/client-version.test.ts
+++ b/packages/app/src/lib/client-version.test.ts
@@ -1,31 +1,57 @@
-import { describe, expect, test } from 'vitest';
-import {
- BROWSER_RUNTIME_VERSION,
- browserClientVersionHeaders,
- browserClientVersionTokenFields,
-} from './client-version.ts';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+const CHROME_UA =
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36';
+const CURSOR_PANE_UA =
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Cursor/1.7.33 Chrome/138.0.7204.251 Electron/37.7.0 Safari/537.36';
+
+async function loadInSurface(env: { userAgent: string; okDesktop?: object }) {
+ vi.stubGlobal('navigator', { userAgent: env.userAgent });
+ vi.stubGlobal('window', env.okDesktop === undefined ? {} : { okDesktop: env.okDesktop });
+ vi.resetModules();
+ return import('./client-version.ts');
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.resetModules();
+});
describe('browser client-version reader', () => {
- test('headers carry kind=web and the resolved runtime', () => {
- expect(browserClientVersionHeaders()).toEqual({
+ test('a plain browser tab sends kind=browser on headers and the collab token', async () => {
+ const mod = await loadInSurface({ userAgent: CHROME_UA });
+ expect(mod.CLIENT_SURFACE).toBe('browser');
+ expect(mod.browserClientVersionHeaders()).toEqual({
'x-ok-client-protocol': '2',
- 'x-ok-client-runtime': BROWSER_RUNTIME_VERSION,
- 'x-ok-client-kind': 'web',
+ 'x-ok-client-runtime': mod.BROWSER_RUNTIME_VERSION,
+ 'x-ok-client-kind': 'browser',
});
- });
-
- test('token fields carry kind=web with a numeric protocol', () => {
- const fields = browserClientVersionTokenFields();
+ const fields = mod.browserClientVersionTokenFields();
expect(fields).toEqual({
clientProtocolVersion: 2,
- clientRuntimeVersion: BROWSER_RUNTIME_VERSION,
- clientKind: 'web',
+ clientRuntimeVersion: mod.BROWSER_RUNTIME_VERSION,
+ clientKind: 'browser',
});
expect(typeof fields.clientProtocolVersion).toBe('number');
});
- test('runtime resolves to a non-empty string', () => {
- expect(typeof BROWSER_RUNTIME_VERSION).toBe('string');
- expect(BROWSER_RUNTIME_VERSION.length).toBeGreaterThan(0);
+ test('the OK Desktop window sends kind=desktop', async () => {
+ const mod = await loadInSurface({ userAgent: CHROME_UA, okDesktop: {} });
+ expect(mod.CLIENT_SURFACE).toBe('desktop');
+ expect(mod.browserClientVersionHeaders()['x-ok-client-kind']).toBe('desktop');
+ expect(mod.browserClientVersionTokenFields().clientKind).toBe('desktop');
+ });
+
+ test('an agent host pane sends its embedded host', async () => {
+ const mod = await loadInSurface({ userAgent: CURSOR_PANE_UA });
+ expect(mod.CLIENT_SURFACE).toBe('embedded:cursor');
+ expect(mod.browserClientVersionHeaders()['x-ok-client-kind']).toBe('embedded:cursor');
+ expect(mod.browserClientVersionTokenFields().clientKind).toBe('embedded:cursor');
+ });
+
+ test('runtime resolves to a non-empty string', async () => {
+ const mod = await loadInSurface({ userAgent: CHROME_UA });
+ expect(typeof mod.BROWSER_RUNTIME_VERSION).toBe('string');
+ expect(mod.BROWSER_RUNTIME_VERSION.length).toBeGreaterThan(0);
});
});
diff --git a/packages/app/src/lib/client-version.ts b/packages/app/src/lib/client-version.ts
index 0dd49414f..e74222ea0 100644
--- a/packages/app/src/lib/client-version.ts
+++ b/packages/app/src/lib/client-version.ts
@@ -1,19 +1,30 @@
import {
CLIENT_RUNTIME_VERSION_FALLBACK,
+ type ClientSurface,
type ClientVersionTokenFields,
clientVersionHeaders,
clientVersionTokenFields,
+ deriveClientSurface,
} from '@inkeep/open-knowledge-core/client-version';
+import { detectEmbeddedHostFromBrowser } from '@inkeep/open-knowledge-core/constants/embedded-host';
const importMetaEnv = (import.meta as unknown as { env?: Record<string, string | undefined> }).env;
export const BROWSER_RUNTIME_VERSION: string =
importMetaEnv?.VITE_APP_VERSION ?? CLIENT_RUNTIME_VERSION_FALLBACK;
+export const CLIENT_SURFACE: ClientSurface = deriveClientSurface({
+ hasDesktopBridge: typeof window !== 'undefined' && window.okDesktop !== undefined,
+ embeddedHost: detectEmbeddedHostFromBrowser(),
+});
+
export function browserClientVersionHeaders(): Record<string, string> {
- return clientVersionHeaders({ kind: 'web', runtimeVersion: BROWSER_RUNTIME_VERSION });
+ return clientVersionHeaders({ kind: CLIENT_SURFACE, runtimeVersion: BROWSER_RUNTIME_VERSION });
}
export function browserClientVersionTokenFields(): ClientVersionTokenFields {
- return clientVersionTokenFields({ kind: 'web', runtimeVersion: BROWSER_RUNTIME_VERSION });
+ return clientVersionTokenFields({
+ kind: CLIENT_SURFACE,
+ runtimeVersion: BROWSER_RUNTIME_VERSION,
+ });
}
diff --git a/packages/app/src/telemetry-impl.ts b/packages/app/src/telemetry-impl.ts
index 1b014a410..b5fafe7f1 100644
--- a/packages/app/src/telemetry-impl.ts
+++ b/packages/app/src/telemetry-impl.ts
@@ -1,3 +1,4 @@
+import { CLIENT_SURFACE_ATTRIBUTE } from '@inkeep/open-knowledge-core/client-version';
import { trace } from '@opentelemetry/api';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
@@ -8,6 +9,7 @@ import { resourceFromAttributes } from '@opentelemetry/resources';
import { BatchSpanProcessor, WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
import { ATTR_DEPLOYMENT_ENVIRONMENT_NAME } from '@opentelemetry/semantic-conventions/incubating';
+import { CLIENT_SURFACE } from '@/lib/client-version';
const TRACER_NAME = 'open-knowledge-app';
@@ -32,6 +34,7 @@ export function install(): void {
[ATTR_SERVICE_NAME]: 'open-knowledge-app',
[ATTR_SERVICE_VERSION]: env?.VITE_APP_VERSION ?? 'dev',
[ATTR_DEPLOYMENT_ENVIRONMENT_NAME]: env?.MODE ?? 'dev',
+ [CLIENT_SURFACE_ATTRIBUTE]: CLIENT_SURFACE,
}),
spanProcessors: [
new BatchSpanProcessor(new OTLPTraceExporter({ url: `${baseUrl}/v1/traces` }), {
diff --git a/packages/core/src/client-version.test.ts b/packages/core/src/client-version.test.ts
index 11e975f74..b4484a079 100644
--- a/packages/core/src/client-version.test.ts
+++ b/packages/core/src/client-version.test.ts
@@ -1,12 +1,94 @@
import { describe, expect, test } from 'vitest';
import {
CLIENT_RUNTIME_VERSION_FALLBACK,
+ CLIENT_SURFACE_ATTRIBUTE,
CLIENT_VERSION_HEADER,
+ type ClientSurface,
clientVersionHeaders,
clientVersionTokenFields,
+ deriveClientSurface,
+ readClientSurface,
} from './client-version.ts';
+import { type EmbeddedHost, UA_PATTERNS } from './constants/embedded-host.ts';
import { PROTOCOL_VERSION } from './protocol-version.ts';
+const EMBEDDED_HOSTS = [
+ 'cursor',
+ 'codex',
+ 'claude-desktop',
+] as const satisfies readonly NonNullable<EmbeddedHost>[];
+
+const EVERY_SURFACE: readonly ClientSurface[] = [
+ deriveClientSurface({ hasDesktopBridge: true, embeddedHost: null }),
+ deriveClientSurface({ hasDesktopBridge: false, embeddedHost: null }),
+ ...EMBEDDED_HOSTS.map((embeddedHost) =>
+ deriveClientSurface({ hasDesktopBridge: false, embeddedHost }),
+ ),
+];
+
+describe('client surface derivation', () => {
+ test('covers every embedded host the user-agent detector knows', () => {
+ expect([...EMBEDDED_HOSTS].sort()).toEqual(Object.keys(UA_PATTERNS).sort());
+ });
+
+ test('the desktop bridge marks the OK Desktop window, whatever the user agent says', () => {
+ expect(deriveClientSurface({ hasDesktopBridge: true, embeddedHost: null })).toBe('desktop');
+ for (const host of EMBEDDED_HOSTS) {
+ expect(deriveClientSurface({ hasDesktopBridge: true, embeddedHost: host })).toBe('desktop');
+ }
+ });
+
+ test('an embedded agent pane is labelled with its host', () => {
+ expect(deriveClientSurface({ hasDesktopBridge: false, embeddedHost: 'cursor' })).toBe(
+ 'embedded:cursor',
+ );
+ expect(deriveClientSurface({ hasDesktopBridge: false, embeddedHost: 'codex' })).toBe(
+ 'embedded:codex',
+ );
+ expect(deriveClientSurface({ hasDesktopBridge: false, embeddedHost: 'claude-desktop' })).toBe(
+ 'embedded:claude-desktop',
+ );
+ });
+
+ test('a plain browser tab is the browser surface', () => {
+ expect(deriveClientSurface({ hasDesktopBridge: false, embeddedHost: null })).toBe('browser');
+ });
+
+ test('the shared attribute key is ok.client.surface', () => {
+ expect(CLIENT_SURFACE_ATTRIBUTE).toBe('ok.client.surface');
+ });
+});
+
+describe('server-side client surface reader', () => {
+ test('every surface a current client sends on the kind header reads back unchanged', () => {
+ for (const surface of EVERY_SURFACE) {
+ const headers = clientVersionHeaders({ kind: surface, runtimeVersion: '0.85.0' });
+ expect(readClientSurface(headers[CLIENT_VERSION_HEADER.kind])).toBe(surface);
+ }
+ });
+
+ test("an older client's kind=web still parses, as an unknown surface", () => {
+ expect(readClientSurface('web')).toBe('unknown');
+ });
+
+ test('a client that sends no kind has no surface', () => {
+ expect(readClientSurface(undefined)).toBeUndefined();
+ expect(readClientSurface('')).toBeUndefined();
+ });
+
+ test('non-app clients have no surface', () => {
+ expect(readClientSurface('mcp')).toBeUndefined();
+ expect(readClientSurface('cli')).toBeUndefined();
+ expect(readClientSurface('desktop-main')).toBeUndefined();
+ });
+
+ test('an unrecognized value collapses to unknown instead of passing through', () => {
+ expect(readClientSurface('embedded:windsurf')).toBe('unknown');
+ expect(readClientSurface('browser, desktop')).toBe('unknown');
+ expect(readClientSurface('x'.repeat(4096))).toBe('unknown');
+ });
+});
+
describe('client-version v1 wire contract', () => {
test('PROTOCOL_VERSION is a positive integer', () => {
expect(Number.isInteger(PROTOCOL_VERSION)).toBe(true);
@@ -32,11 +114,11 @@ describe('client-version v1 wire contract', () => {
});
test('clientVersionTokenFields keeps protocol as a JSON number', () => {
- const fields = clientVersionTokenFields({ kind: 'web', runtimeVersion: '0.8.1' });
+ const fields = clientVersionTokenFields({ kind: 'browser', runtimeVersion: '0.8.1' });
expect(fields).toEqual({
clientProtocolVersion: PROTOCOL_VERSION,
clientRuntimeVersion: '0.8.1',
- clientKind: 'web',
+ clientKind: 'browser',
});
expect(typeof fields.clientProtocolVersion).toBe('number');
});
diff --git a/packages/core/src/client-version.ts b/packages/core/src/client-version.ts
index 7ea230b9c..d18597e2c 100644
--- a/packages/core/src/client-version.ts
+++ b/packages/core/src/client-version.ts
@@ -1,6 +1,11 @@
+import type { EmbeddedHost } from './constants/embedded-host.ts';
import { PROTOCOL_VERSION } from './protocol-version.ts';
-export type ClientKind = 'web' | 'mcp' | 'desktop-main' | 'cli';
+export type ClientSurface = 'desktop' | 'browser' | `embedded:${NonNullable<EmbeddedHost>}`;
+
+export type ClientKind = ClientSurface | 'mcp' | 'desktop-main' | 'cli';
+
+export const CLIENT_SURFACE_ATTRIBUTE = 'ok.client.surface';
export const CLIENT_RUNTIME_VERSION_FALLBACK = '0.0.0-unknown';
@@ -21,6 +26,47 @@ export interface ClientVersionTokenFields {
readonly clientKind: ClientKind;
}
+interface ClientSurfaceSignals {
+ readonly hasDesktopBridge: boolean;
+ readonly embeddedHost: EmbeddedHost;
+}
+
+const KNOWN_CLIENT_SURFACES: Readonly<Record<ClientSurface, true>> = {
+ desktop: true,
+ browser: true,
+ 'embedded:cursor': true,
+ 'embedded:codex': true,
+ 'embedded:claude-desktop': true,
+};
+
+const NON_SURFACE_CLIENT_KINDS: Readonly<Record<Exclude<ClientKind, ClientSurface>, true>> = {
+ mcp: true,
+ 'desktop-main': true,
+ cli: true,
+};
+
+export type ClientSurfaceReading = ClientSurface | 'unknown' | undefined;
+
+function isClientSurface(value: string): value is ClientSurface {
+ return Object.hasOwn(KNOWN_CLIENT_SURFACES, value);
+}
+
+export function deriveClientSurface({
+ hasDesktopBridge,
+ embeddedHost,
+}: ClientSurfaceSignals): ClientSurface {
+ if (hasDesktopBridge) return 'desktop';
+ if (embeddedHost !== null) return `embedded:${embeddedHost}`;
+ return 'browser';
+}
+
+export function readClientSurface(kind: string | undefined): ClientSurfaceReading {
+ if (kind === undefined || kind.length === 0 || Object.hasOwn(NON_SURFACE_CLIENT_KINDS, kind)) {
+ return undefined;
+ }
+ return isClientSurface(kind) ? kind : 'unknown';
+}
+
export function clientVersionHeaders({
kind,
runtimeVersion,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 3998f83d1..e4e1166a7 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -161,12 +161,17 @@ export {
} from './checkpoint-kinds.ts';
export {
CLIENT_RUNTIME_VERSION_FALLBACK,
+ CLIENT_SURFACE_ATTRIBUTE,
CLIENT_VERSION_HEADER,
type ClientKind,
+ type ClientSurface,
+ type ClientSurfaceReading,
type ClientVersionInput,
type ClientVersionTokenFields,
clientVersionHeaders,
clientVersionTokenFields,
+ deriveClientSurface,
+ readClientSurface,
} from './client-version.ts';
export {
COMMAND_IDENTITIES,
diff --git a/packages/core/tests/contract/subpath-types/consumer.ts b/packages/core/tests/contract/subpath-types/consumer.ts
index 952385d23..f9ceb1fd2 100644
--- a/packages/core/tests/contract/subpath-types/consumer.ts
+++ b/packages/core/tests/contract/subpath-types/consumer.ts
@@ -49,9 +49,14 @@ export type {
export type { isSurfacedCheckpointKind } from '@inkeep/open-knowledge-core/checkpoint-kinds';
export type {
CLIENT_RUNTIME_VERSION_FALLBACK,
+ CLIENT_SURFACE_ATTRIBUTE,
+ ClientSurface,
+ ClientSurfaceReading,
ClientVersionTokenFields,
clientVersionHeaders,
clientVersionTokenFields,
+ deriveClientSurface,
+ readClientSurface,
} from '@inkeep/open-knowledge-core/client-version';
export type {
COMMAND_IDENTITIES,
diff --git a/packages/server/src/api-request-id.test.ts b/packages/server/src/api-request-id.test.ts
index 78725e66e..667a06189 100644
--- a/packages/server/src/api-request-id.test.ts
+++ b/packages/server/src/api-request-id.test.ts
@@ -167,6 +167,73 @@ describe('onRequest request identity + access log', () => {
expect((accessCalls[0]?.[0] as { route: string } | undefined)?.route).toBe('/api/*');
});
+ async function accessLineFor(headers: Record<string, string>) {
+ const log = loggerFactory.getLogger('api');
+ const infoSpy = vi.spyOn(log, 'info');
+ await callRoute('/api/history/', headers);
+ const accessCalls = infoSpy.mock.calls.filter(
+ (c) => (c[0] as { event?: string })?.event === 'api.access',
+ );
+ expect(accessCalls).toHaveLength(1);
+ infoSpy.mockRestore();
+ return accessCalls[0]?.[0] as { clientSurface?: string };
+ }
+
+ test('the access line carries the client surface the app sends on x-ok-client-kind', async () => {
+ for (const surface of [
+ 'desktop',
+ 'browser',
+ 'embedded:cursor',
+ 'embedded:codex',
+ 'embedded:claude-desktop',
+ ]) {
+ const line = await accessLineFor({ 'x-ok-client-kind': surface });
+ expect(line.clientSurface).toBe(surface);
+ }
+ });
+
+ test("an older client's kind=web is logged as an unknown surface", async () => {
+ const line = await accessLineFor({ 'x-ok-client-kind': 'web' });
+ expect(line.clientSurface).toBe('unknown');
+ });
+
+ test('requests without an app kind log no surface', async () => {
+ expect((await accessLineFor({})).clientSurface).toBeUndefined();
+ expect((await accessLineFor({ 'x-ok-client-kind': 'mcp' })).clientSurface).toBeUndefined();
+ expect((await accessLineFor({ 'x-ok-client-kind': 'cli' })).clientSurface).toBeUndefined();
+ expect(
+ (await accessLineFor({ 'x-ok-client-kind': 'desktop-main' })).clientSurface,
+ ).toBeUndefined();
+ });
+
+ test('the HTTP server span carries ok.client.surface', async () => {
+ const { context: apiContext, trace } = await import('@opentelemetry/api');
+ const { AsyncLocalStorageContextManager } = await import('@opentelemetry/context-async-hooks');
+ const { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } = await import(
+ '@opentelemetry/sdk-trace-base'
+ );
+ const exporter = new InMemorySpanExporter();
+ const provider = new BasicTracerProvider({
+ spanProcessors: [new SimpleSpanProcessor(exporter)],
+ });
+ trace.setGlobalTracerProvider(provider);
+ apiContext.setGlobalContextManager(new AsyncLocalStorageContextManager());
+ try {
+ await callRoute('/api/history/', { 'x-ok-client-kind': 'embedded:codex' });
+ await callRoute('/api/history/', { 'x-ok-client-kind': 'web' });
+ await callRoute('/api/history/');
+ const surfaces = exporter
+ .getFinishedSpans()
+ .filter((span) => span.name.startsWith('HTTP '))
+ .map((span) => span.attributes['ok.client.surface']);
+ expect(surfaces).toEqual(['embedded:codex', 'unknown', undefined]);
+ } finally {
+ await provider.shutdown();
+ trace.disable();
+ apiContext.disable();
+ }
+ });
+
test('non-API requests get no x-request-id echo and no access line', async () => {
const log = loggerFactory.getLogger('api');
const infoSpy = vi.spyOn(log, 'info');
diff --git a/packages/server/src/api-system-actions-composition.test.ts b/packages/server/src/api-system-actions-composition.test.ts
index 2604db048..f9475f643 100644
--- a/packages/server/src/api-system-actions-composition.test.ts
+++ b/packages/server/src/api-system-actions-composition.test.ts
@@ -2,9 +2,10 @@ import { mkdtempSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
-import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
import type { BootedServer } from './boot.ts';
import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';
+import { loggerFactory } from './logger.ts';
let tmpRoot: string;
let server: BootedServer;
@@ -67,6 +68,33 @@ describe('system-actions group over the composed listener — served natively',
expect(((await res.json()) as { accepted?: number }).accepted).toBe(1);
});
+ test('client-logs stamps the sending client surface on forwarded entries', async () => {
+ const infoSpy = vi.spyOn(loggerFactory.getLogger('renderer'), 'info');
+ try {
+ const post = (headers: Record<string, string>, message: string) =>
+ fetch(`http://127.0.0.1:${server.port}/api/client-logs`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ body: JSON.stringify({ entries: [{ level: 'info', message }] }),
+ });
+ expect((await post({ 'x-ok-client-kind': 'embedded:cursor' }, 'from-cursor')).status).toBe(
+ 200,
+ );
+ expect((await post({ 'x-ok-client-kind': 'web' }, 'from-older-client')).status).toBe(200);
+ expect((await post({}, 'from-no-kind')).status).toBe(200);
+ const fieldsOf = (message: string) => {
+ const call = infoSpy.mock.calls.find((c) => c[1] === message);
+ if (call === undefined) throw new Error(`no renderer log line for ${message}`);
+ return call[0];
+ };
+ expect(fieldsOf('from-cursor')).toMatchObject({ clientSurface: 'embedded:cursor' });
+ expect(fieldsOf('from-older-client')).toMatchObject({ clientSurface: 'unknown' });
+ expect(fieldsOf('from-no-kind')).not.toHaveProperty('clientSurface');
+ } finally {
+ infoSpy.mockRestore();
+ }
+ });
+
test('client-logs refuses a rebound Host before the verb check (403, no Allow leak)', async () => {
const res = await rawRequest(server.port, '/api/client-logs', {
headers: { Host: 'evil.example' },
diff --git a/packages/server/src/auth-token-schema.test.ts b/packages/server/src/auth-token-schema.test.ts
index 7490fe85b..eb94de45b 100644
--- a/packages/server/src/auth-token-schema.test.ts
+++ b/packages/server/src/auth-token-schema.test.ts
@@ -6,6 +6,7 @@ import {
type HocuspocusAuthRejectionReason,
isHocuspocusAuthRejectionReason,
parseAuthRejectionWire,
+ parseHocuspocusAuthToken,
} from './auth-token-schema.ts';
describe('HOCUSPOCUS_AUTH_REJECTION_REASONS', () => {
@@ -193,3 +194,33 @@ describe('HocuspocusAuthRejection', () => {
expect(caught?.reason).toBe('rename-redirect:target');
});
});
+
+describe('parseHocuspocusAuthToken client kind skew', () => {
+ it("an older client's kind=web token still parses", () => {
+ const parsed = parseHocuspocusAuthToken(
+ JSON.stringify({
+ clientProtocolVersion: 2,
+ clientRuntimeVersion: '0.84.0',
+ clientKind: 'web',
+ }),
+ );
+ expect(parsed?.clientKind).toBe('web');
+ });
+
+ it('a token carrying a client surface parses', () => {
+ const parsed = parseHocuspocusAuthToken(
+ JSON.stringify({
+ clientProtocolVersion: 2,
+ clientRuntimeVersion: '0.85.0',
+ clientKind: 'embedded:claude-desktop',
+ }),
+ );
+ expect(parsed?.clientKind).toBe('embedded:claude-desktop');
+ });
+
+ it('a token without a client kind parses', () => {
+ const parsed = parseHocuspocusAuthToken(JSON.stringify({ tabSessionId: 's-1' }));
+ expect(parsed).toBeDefined();
+ expect(parsed?.clientKind).toBeUndefined();
+ });
+});
diff --git a/packages/server/src/http/api-pipeline.ts b/packages/server/src/http/api-pipeline.ts
index 4199ad84f..c90993e7e 100644
--- a/packages/server/src/http/api-pipeline.ts
+++ b/packages/server/src/http/api-pipeline.ts
@@ -1,5 +1,9 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
-import { CLIENT_VERSION_HEADER } from '@inkeep/open-knowledge-core';
+import {
+ CLIENT_SURFACE_ATTRIBUTE,
+ CLIENT_VERSION_HEADER,
+ readClientSurface,
+} from '@inkeep/open-knowledge-core';
import { context, propagation, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import {
ATTR_HTTP_REQUEST_METHOD,
@@ -186,9 +190,10 @@ export function createApiRequestPipeline(opts: ApiPipelineOptions): ApiRequestPi
const method = request.method ?? 'GET';
const routeTemplate = resolution.template;
+ const clientSurface = readClientSurface(headerString(CLIENT_VERSION_HEADER.kind));
const requestId = url.startsWith('/api/') ? resolveRequestId(request) : undefined;
- stampIngressContext(request, { requestId });
+ stampIngressContext(request, { requestId, clientSurface });
if (requestId !== undefined) {
rememberRequestId(request, requestId);
if (typeof response.setHeader === 'function') {
@@ -208,6 +213,7 @@ export function createApiRequestPipeline(opts: ApiPipelineOptions): ApiRequestPi
route: routeTemplate,
status: response.statusCode,
durationMs: Date.now() - accessStarted,
+ ...(clientSurface === undefined ? {} : { clientSurface }),
...(response.writableFinished ? {} : { aborted: true }),
},
`${method} ${routeTemplate} ${response.statusCode}`,
@@ -324,6 +330,7 @@ export function createApiRequestPipeline(opts: ApiPipelineOptions): ApiRequestPi
[ATTR_URL_SCHEME]: 'http',
[ATTR_USER_AGENT_ORIGINAL]: request.headers['user-agent'] ?? '',
'ok.request.id': requestId,
+ [CLIENT_SURFACE_ATTRIBUTE]: clientSurface,
},
},
async (span) => {
diff --git a/packages/server/src/http/system-actions-routes.ts b/packages/server/src/http/system-actions-routes.ts
index 5274c6c06..d07e5f4b7 100644
--- a/packages/server/src/http/system-actions-routes.ts
+++ b/packages/server/src/http/system-actions-routes.ts
@@ -4,6 +4,7 @@ import type { AgentRegistryHostSeam } from '../agent-registry-apply.ts';
import { collectServerHostSnapshot } from '../agent-registry-probes.ts';
import type { createInstalledAgentsProbe } from '../handoff-api.ts';
import { handleHandoffDispatch } from '../handoff-dispatch-api.ts';
+import { getIngressContext } from '../ingress-policy.ts';
import { getLogger, type PinoLogger } from '../logger.ts';
import { handleSpawnCursor } from '../spawn-cursor-api.ts';
import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
@@ -71,14 +72,17 @@ export function createSystemActionsRoutes(deps: SystemActionsRouteDeps): ApiRout
const handleClientLogs = withValidation(
ClientLogsRequestSchema,
- async (_req, res, body) => {
+ async (req, res, body) => {
try {
const logger = getLogger('renderer');
+ const clientSurface = getIngressContext(req)?.clientSurface;
+ const surfaceField = clientSurface === undefined ? {} : { clientSurface };
if (body.droppedSinceLastFlush !== undefined && body.droppedSinceLastFlush > 0) {
logger.warn(
{
source: 'renderer-console',
transport: 'web',
+ ...surfaceField,
event: 'client-log-entries-dropped',
droppedSinceLastFlush: body.droppedSinceLastFlush,
},
@@ -92,6 +96,7 @@ export function createSystemActionsRoutes(deps: SystemActionsRouteDeps): ApiRout
...entry.fields,
source: 'renderer-console',
transport: 'web',
+ ...surfaceField,
...(entry.sourceId ? { sourceId: entry.sourceId } : {}),
...(entry.lineNumber !== undefined ? { lineNumber: entry.lineNumber } : {}),
...(entry.ts !== undefined ? { clientTs: entry.ts } : {}),
diff --git a/packages/server/src/ingress-policy.test.ts b/packages/server/src/ingress-policy.test.ts
index 85d34be14..567b5b7ae 100644
--- a/packages/server/src/ingress-policy.test.ts
+++ b/packages/server/src/ingress-policy.test.ts
@@ -301,9 +301,23 @@ describe('ingress request context', () => {
headers: {},
} as unknown as import('node:http').IncomingMessage;
const context = stampIngressContext(req, { requestId: 'r-1' });
- expect(context).toEqual({ requestId: 'r-1', peerClass: 'external', actor: undefined });
+ expect(context).toStrictEqual({
+ requestId: 'r-1',
+ peerClass: 'external',
+ clientSurface: undefined,
+ actor: undefined,
+ });
expect(getIngressContext(req)).toBe(context);
});
+
+ test('carries the client surface the pipeline read for the request', () => {
+ const req = {
+ socket: { remoteAddress: '127.0.0.1' },
+ headers: {},
+ } as unknown as import('node:http').IncomingMessage;
+ stampIngressContext(req, { requestId: 'r-2', clientSurface: 'embedded:codex' });
+ expect(getIngressContext(req)?.clientSurface).toBe('embedded:codex');
+ });
});
describe('admitRequestOrigin', () => {
diff --git a/packages/server/src/ingress-policy.ts b/packages/server/src/ingress-policy.ts
index 9c09c818b..7c6017069 100644
--- a/packages/server/src/ingress-policy.ts
+++ b/packages/server/src/ingress-policy.ts
@@ -1,5 +1,5 @@
import type { IncomingMessage } from 'node:http';
-import type { ServerRuntimeConfig } from '@inkeep/open-knowledge-core';
+import type { ClientSurfaceReading, ServerRuntimeConfig } from '@inkeep/open-knowledge-core';
import { isAllowedApiOrigin, isOpaqueOrigin, isSafeMethod } from './api-origin.ts';
import type { PinoLogger } from './logger.ts';
import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';
@@ -186,6 +186,7 @@ export function warnForwardedHeaderRefusalOnce(
export interface IngressRequestContext {
requestId: string | undefined;
peerClass: 'loopback' | 'external' | 'unknown';
+ clientSurface: ClientSurfaceReading;
actor: undefined;
}
@@ -193,12 +194,13 @@ const ingressContexts = new WeakMap<IncomingMessage, IngressRequestContext>();
export function stampIngressContext(
req: IncomingMessage,
- input: { requestId?: string | undefined },
+ input: { requestId?: string | undefined; clientSurface?: ClientSurfaceReading },
): IngressRequestContext {
const peer = req.socket?.remoteAddress;
const context: IngressRequestContext = {
requestId: input.requestId,
peerClass: peer === undefined ? 'unknown' : isLoopbackAddress(peer) ? 'loopback' : 'external',
+ clientSurface: input.clientSurface,
actor: undefined,
};
ingressContexts.set(req, context);