From 0f30ace2091e8325e1b3e6cfe938c387fbc709ca Mon Sep 17 00:00:00 2001 From: QQ Date: Tue, 17 Nov 2026 08:50:59 +0800 Subject: [PATCH] Import packages/plugin/tests/multi-client-runtime.test.ts --- .../plugin/tests/multi-client-runtime.test.ts | 158 +++++++++++++++++- 1 file changed, 152 insertions(+), 6 deletions(-) diff --git a/packages/plugin/tests/multi-client-runtime.test.ts b/packages/plugin/tests/multi-client-runtime.test.ts index 238632e..ac2de9a 100644 --- a/packages/plugin/tests/multi-client-runtime.test.ts +++ b/packages/plugin/tests/multi-client-runtime.test.ts @@ -14,7 +14,7 @@ import { HostServerConnection } from '../src/server-connection.js' import { CodexRemoteDomain } from '../src/codex/domain.js' import { CodexAppServerError, type CodexAppServerLike } from '../src/codex/app-server.js' import type { AuthenticatedPeerChannel } from '../src/types.js' -import type { LocalTypertGateway } from '../src/typert-gateway-contract.js' +import type { LocalTypertGateway, TypertRpcResult } from '../src/typert-gateway-contract.js' describe('HostPluginRuntime multi-Client routing', () => { it('does not start inbound Host authorization when control is disabled at startup', async () => { @@ -123,8 +123,11 @@ describe('HostPluginRuntime multi-Client routing', () => { 'codex.appserver.v1', 'codex.appserver.transfer.v1', 'remote.history.compact.v1', + 'remote.compaction.async.v1', + 'workspace.upload.binary.v1', + 'workspace.upload.lan.v1', ] - : ['workspace.upload.v1', 'remote.history.compact.v1'], + : ['workspace.upload.v1', 'remote.history.compact.v1', 'remote.compaction.async.v1', 'workspace.upload.binary.v1', 'workspace.upload.lan.v1'], ) expect(result.workspaceTypes).toEqual( scenario === 'ready' @@ -211,7 +214,7 @@ describe('HostPluginRuntime multi-Client routing', () => { return ((response!.payload as RpcResponsePayload).result as { capabilities: string[] }).capabilities } const missing = await describe() - expect(dispatch).toHaveBeenCalledWith('session/list', { args: { _request: {} } }, expect.any(AbortSignal)) + expect(dispatch).toHaveBeenCalledWith('session/list', { args: { __remoteCapabilityProbe: true } }, expect.any(AbortSignal)) expect(missing.some(value => value.startsWith('harness.remote.'))).toBe(false) expect(missing).not.toContain('harness.remote.stream.transfer.v1') await expect(probeRemoteHostFeatures({ rpc: async () => ({ capabilities: missing }) } as never)) @@ -223,14 +226,97 @@ describe('HostPluginRuntime multi-Client routing', () => { } finally { await runtime.close() } }) + it('discovers capabilities for concurrent Clients without reading persisted sessions', async () => { + const gateway = localGateway() + const readSessions = vi.fn(() => new Promise(() => {})) + vi.mocked(gateway.dispatch).mockImplementation(async (endpoint, payload) => { + if (endpoint === 'session/list' && (payload as { args: object }).args + && '__remoteCapabilityProbe' in (payload as { args: object }).args) { + return { ok: false, error: { code: 'gateway/arguments-invalid', message: 'Unknown argument', details: {} } } + } + return readSessions() + }) + const runtime = new HostPluginRuntime(config(), identities(), logger(), gateway) + const channels = [fakeChannel('slow-history-phone', 'phone'), fakeChannel('slow-history-tablet', 'tablet')] + try { + await runtime.start() + for (const channel of channels) await runtime.acceptAuthenticatedPeer(channel) + const requests = channels.map(channel => { + const request = createRpcRequest('harness.transport.describe', {}) + channel.push(request) + return request + }) + await vi.waitFor(() => { + for (const [index, channel] of channels.entries()) { + const response = channel.sent().find(row => row.type === 'rpc.response' + && (row.payload as RpcResponsePayload).requestId === requests[index]!.id) + expect(response).toBeDefined() + const capabilities = ((response!.payload as RpcResponsePayload).result as { capabilities: string[] }).capabilities + expect(capabilities.some(value => value === 'harness.remote.v1' || value === 'harness.remote.v3')).toBe(true) + } + }) + expect(readSessions).not.toHaveBeenCalled() + } finally { await runtime.close() } + }) + + it('runs /compact as a Host-owned operation with idempotent submission and status', async () => { + const gateway = localGateway() + let release!: (value: TypertRpcResult) => void + vi.mocked(gateway.dispatch).mockImplementation(async (endpoint: string) => { + if (endpoint === 'session/list') return { ok: false as const, error: { code: 'gateway/arguments-invalid', message: 'Unknown argument', details: {} } } + if (endpoint === 'commands/execute') { + return await new Promise(resolve => { release = resolve }) + } + return { ok: true as const } + }) + const runtime = new HostPluginRuntime(config(), identities(), logger(), gateway) + const channel = fakeChannel('compaction-client', 'client-phone') + const rpc = async (method: string, params: unknown): Promise> => { + const request = createRpcRequest(method as never, params) + channel.push(request) + let response: RemoteMessage | undefined + await vi.waitFor(() => { + response = channel.sent().find(message => message.type === 'rpc.response' + && (message.payload as RpcResponsePayload).requestId === request.id) + expect(response).toBeDefined() + }) + return (response!.payload as RpcResponsePayload).result as Record + } + try { + await runtime.start() + await runtime.acceptAuthenticatedPeer(channel) + + const submitted = await rpc('harness.remote.compaction.submit', { sessionId: 'session-1', requestId: 'request-1' }) + expect(submitted.state).toBe('accepted') + const duplicate = await rpc('harness.remote.compaction.submit', { sessionId: 'session-1', requestId: 'request-1' }) + expect(duplicate.operationId).toBe(submitted.operationId) + expect(vi.mocked(gateway.dispatch).mock.calls.filter(([endpoint]) => endpoint === 'commands/execute')).toHaveLength(1) + + const first = await rpc('harness.remote.compaction.status', { + sessionId: 'session-1', operationId: submitted.operationId, + }) + expect(['accepted', 'running']).toContain(first.state) + + release({ ok: true, value: { result: { kind: 'success', text: 'Compacted.' } } }) + await vi.waitFor(async () => { + const status = await rpc('harness.remote.compaction.status', { + sessionId: 'session-1', operationId: submitted.operationId, + }) + expect(status).toMatchObject({ state: 'succeeded', message: 'Compacted.' }) + }) + } finally { await runtime.close() } + }) + + it('reports an unready or unverified Session API as a retryable discovery failure', async () => { await runScenarios([ { name: 'service unavailable', answer: { ok: false as const, error: { code: 'gateway/service-unavailable', message: 'Service unavailable', details: {}, } }, message: 'The Host Session API is not ready.' }, - { name: 'invalid arguments', answer: { ok: false as const, error: { - code: 'gateway/arguments-invalid', message: 'Invalid arguments', details: {}, + { name: 'internal failure', answer: { ok: false as const, error: { + code: 'gateway/internal', message: 'Internal failure', details: {}, } }, message: 'Cannot verify the Host Session API.' }, + { name: 'unexpected success', answer: { ok: true as const }, message: 'The Host Gateway did not reject the Session API probe.' }, { name: 'timeout', answer: new DOMException('Timed out', 'TimeoutError'), message: 'Cannot verify the Host Session API.' }, ].map(({ name, answer, message }) => ({ name, run: async () => { const gateway = localGateway() @@ -293,6 +379,64 @@ describe('HostPluginRuntime multi-Client routing', () => { ) }) + it('advertises remote.session.events.v1 only when DSH >= 0.2.0 and $events opens live', async () => { + await runScenarios([ + { + name: 'live DSH 0.2.2 host', + version: '0.2.2-rc.1', + open: async () => (async function* () { + yield { type: 'ready', clientId: 'c1', host: { home: '/tmp' } } + })(), + expected: true, + }, + { + name: 'missing dsh-api-remotes ($events service unavailable)', + version: '0.2.2-rc.1', + open: async () => { throw Object.assign(new Error('unavailable'), { code: 'gateway/service-unavailable' }) }, + expected: false, + }, + { + name: 'older 0.1.5 host', + version: '0.1.5-rc.1', + open: async () => (async function* () { + yield { type: 'ready', clientId: 'c1', host: { home: '/tmp' } } + })(), + expected: false, + }, + ].map(({ name, version, open, expected }) => ({ + name, + run: async () => { + const gateway = localGateway() + gateway.open = vi.fn(open) as unknown as LocalTypertGateway['open'] + const runtime = new HostPluginRuntime(config(), identities(), logger(), gateway) + const internal = runtime as unknown as { + readHarnessVersion(): Promise + createServerConnection(): unknown + } + vi.spyOn(internal, 'readHarnessVersion').mockResolvedValue(version) + vi.spyOn(internal, 'createServerConnection').mockReturnValue({ start: vi.fn(), stop: vi.fn(async () => undefined), isOnline: () => true, lastError: () => undefined }) + const channel = fakeChannel('events-cap-' + name, 'client-phone') + try { + await runtime.start() + ;(runtime as unknown as { harnessVersion: string }).harnessVersion = version + await runtime.acceptAuthenticatedPeer(channel) + const request = createRpcRequest('harness.transport.describe', {}) + channel.push(request) + let response: RemoteMessage | undefined + await vi.waitFor(() => { + response = channel.sent().find(row => row.type === 'rpc.response' + && (row.payload as RpcResponsePayload).requestId === request.id) + expect(response).toBeDefined() + }) + const capabilities = ((response!.payload as RpcResponsePayload).result as { capabilities: string[] }).capabilities + expect(capabilities.includes('remote.session.events.v1')).toBe(expected) + } finally { + await runtime.close() + } + }, + }))) + }) + it('allows identical stream ids on different Client connections without crossing frames', async () => { const streamSignals: AbortSignal[] = [] const gateway = localGateway() @@ -556,7 +700,9 @@ function identities(): IdentityStore { function localGateway(): LocalTypertGateway { return { invoke: vi.fn(async () => undefined), - dispatch: vi.fn(async () => ({ ok: true as const })), + dispatch: vi.fn(async (endpoint: string) => endpoint === 'session/list' + ? { ok: false as const, error: { code: 'gateway/arguments-invalid', message: 'Unknown argument', details: {} } } + : { ok: true as const }), open: vi.fn(async () => (async function* () { return })()), failure: vi.fn(() => ({ code: 'internal', message: 'failed', details: {} })), supportsCarrier: true,