This commit is contained in:
Oleg Maslov
2026-09-02 10:14:22 +02:00
parent 0c3e2ead3b
commit b20b138fe4
771 changed files with 161561 additions and 9027 deletions

View File

@@ -17,6 +17,7 @@ import LocalAdapter, {
adapter as singletonAdapter,
resolveDefaultServerUrl,
} from './adapter';
import { fetchWithTimeout } from './fetch-utils';
const BASE = 'http://test-server:4242';
@@ -25,6 +26,38 @@ const jsonRes = (body: unknown, status = 200) =>
const HEALTH = { status: 'ok', mode: 'local' };
const TOKEN_PATH = '/api/auth/session-token';
const DESKTOP_A = { port: 49151, instanceId: 'desktop-instance-a' };
const DESKTOP_B = { port: 49152, instanceId: 'desktop-instance-b' };
const desktopHealth = (endpoint = DESKTOP_A) => ({
...HEALTH,
port: endpoint.port,
instanceId: endpoint.instanceId,
});
const enableTauri = () => {
(window as unknown as { __TAURI_INTERNALS__: unknown }).__TAURI_INTERNALS__ = {};
};
const flush = () => new Promise<void>(resolve => setTimeout(resolve, 0));
class FakeEventSource {
static instances: FakeEventSource[] = [];
readonly url: string;
onmessage: ((event: MessageEvent) => void) | null = null;
onerror: (() => void) | null = null;
onopen: (() => void) | null = null;
closed = false;
constructor(url: string) {
this.url = url;
FakeEventSource.instances.push(this);
}
addEventListener(): void { /* listeners are irrelevant to the identity gate */ }
close(): void { this.closed = true; }
fireError(): void { this.onerror?.(); }
}
/** Route-style fetch mock: dispatch on URL substring, in registration order. */
function routeMock(fetchSpy: ReturnType<typeof vi.spyOn>, routes: Array<[string, () => Response | Promise<Response>]>) {
@@ -49,6 +82,8 @@ describe('P1b auth gate', () => {
});
afterEach(() => {
delete (window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
vi.unstubAllGlobals();
fetchSpy.mockRestore();
vi.useRealTimers();
});
@@ -204,6 +239,408 @@ describe('P1b auth gate', () => {
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(0);
});
// ── Rust-owned desktop endpoint gate ─────────────────────────────────────
it('managed desktop stays network-cold and hides default/stored URLs until Rust binds an endpoint', async () => {
enableTauri();
localStorage.setItem('waggle:server-url', 'http://stale-or-hostile:9999');
const a = new LocalAdapter('http://constructor-override:8888');
const gateId = a.armDesktopServiceGate();
const request = a.getWorkspaces();
const healthRequest = a.getSystemHealth();
const rejected = expect(request).rejects.toThrow('desktop boot stopped');
const healthRejected = expect(healthRequest).rejects.toThrow('desktop boot stopped');
await Promise.resolve();
expect(fetchSpy).not.toHaveBeenCalled();
expect(() => a.getServerUrl()).toThrow(/not ready/);
a.failDesktopServiceGate(new Error('desktop boot stopped'), gateId);
await Promise.all([rejected, healthRejected]);
expect(fetchSpy).not.toHaveBeenCalled();
expect(localStorage.getItem('waggle:server-url')).toBe('http://stale-or-hostile:9999');
});
it('managed desktop uses only the matching Rust-owned endpoint and never persists it', async () => {
enableTauri();
localStorage.setItem('waggle:server-url', 'http://stale-or-hostile:9999');
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
['/health', () => jsonRes(desktopHealth(DESKTOP_A))],
[TOKEN_PATH, () => jsonRes({ token: 'desktop-token-a' })],
['/api/workspaces', () => jsonRes([])],
]);
const gateId = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_A, gateId);
await a.getWorkspaces();
expect(a.getServerUrl()).toBe(`http://127.0.0.1:${DESKTOP_A.port}`);
expect(localStorage.getItem('waggle:server-url')).toBe('http://stale-or-hostile:9999');
expect(callsTo(fetchSpy, '/health')).toHaveLength(2);
const [workspaceUrl, workspaceInit] = callsTo(fetchSpy, '/api/workspaces')[0];
expect(workspaceUrl).toBe(`http://127.0.0.1:${DESKTOP_A.port}/api/workspaces`);
expect((workspaceInit.headers as Record<string, string>).Authorization)
.toBe('Bearer desktop-token-a');
});
it('managed 401 recovery revalidates identity before retrying on the same port', async () => {
enableTauri();
const a = new LocalAdapter(BASE);
let health = desktopHealth(DESKTOP_A);
let token = 'desktop-token-a';
let workspaceCalls = 0;
routeMock(fetchSpy, [
['/health', () => jsonRes(health)],
[TOKEN_PATH, () => jsonRes({ token })],
['/api/workspaces', () => {
workspaceCalls++;
return jsonRes({ error: 'Unauthorized' }, 401);
}],
]);
const gateId = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_A, gateId);
health = { ...desktopHealth(DESKTOP_B), port: DESKTOP_A.port };
token = 'desktop-token-b';
await expect(a.getWorkspaces()).rejects.toThrow(/identity/);
expect(workspaceCalls).toBe(1);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(2);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('a post-ready managed health failure closes the verified desktop gate', async () => {
enableTauri();
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
['/health', () => jsonRes(desktopHealth(DESKTOP_A))],
[TOKEN_PATH, () => jsonRes({ token: 'desktop-token-a' })],
]);
const gateId = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_A, gateId);
fetchSpy.mockRejectedValue(new TypeError('managed sidecar disappeared'));
await expect(a.getSystemHealth()).rejects.toThrow();
expect(a.isConnected).toBe(false);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('wrong desktop identity rejects the binding, shared connect, and queued request without token leakage', async () => {
enableTauri();
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
['/health', () => jsonRes(desktopHealth(DESKTOP_B))],
[TOKEN_PATH, () => jsonRes({ token: 'must-not-be-fetched' })],
['/api/workspaces', () => jsonRes([])],
]);
const gateId = a.armDesktopServiceGate();
const binding = a.connectDesktopService(DESKTOP_A, gateId);
const sharedConnect = a.connect();
const queuedRequest = a.getWorkspaces();
await Promise.all([
expect(binding).rejects.toThrow(/identity/),
expect(sharedConnect).rejects.toThrow(/identity/),
expect(queuedRequest).rejects.toThrow(/identity/),
]);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(0);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(0);
expect(a.isConnected).toBe(false);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('failing the desktop gate while token bootstrap is pending cannot be reopened by its late completion', async () => {
enableTauri();
const a = new LocalAdapter(BASE);
let releaseToken!: (response: Response) => void;
const tokenGate = new Promise<Response>(resolve => { releaseToken = resolve; });
routeMock(fetchSpy, [
['/health', () => jsonRes(desktopHealth(DESKTOP_A))],
[TOKEN_PATH, () => tokenGate],
['/api/workspaces', () => jsonRes([])],
]);
const gateId = a.armDesktopServiceGate();
const binding = a.connectDesktopService(DESKTOP_A, gateId);
const sharedConnect = a.connect();
const queuedRequest = a.getWorkspaces();
await vi.waitFor(() => expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1));
const bindingRejected = expect(binding).rejects.toThrow(/shell stopped|generation changed/);
const sharedRejected = expect(sharedConnect).rejects.toThrow(/superseded|generation changed/);
const queuedRejected = expect(queuedRequest).rejects.toThrow('shell stopped');
a.failDesktopServiceGate(new Error('shell stopped'), gateId);
releaseToken(jsonRes({ token: 'late-token' }));
await Promise.all([bindingRejected, sharedRejected, queuedRejected]);
expect(a.isConnected).toBe(false);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(0);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('superseding a token-pending launch rejects stale consumers and releases work only on the newer endpoint', async () => {
enableTauri();
const a = new LocalAdapter(BASE);
let releaseOldToken!: (response: Response) => void;
const oldTokenGate = new Promise<Response>(resolve => { releaseOldToken = resolve; });
fetchSpy.mockImplementation(async (url: unknown) => {
const value = String(url);
if (value === `http://127.0.0.1:${DESKTOP_A.port}/health`) {
return jsonRes(desktopHealth(DESKTOP_A));
}
if (value === `http://127.0.0.1:${DESKTOP_A.port}${TOKEN_PATH}`) return oldTokenGate;
if (value === `http://127.0.0.1:${DESKTOP_B.port}/health`) {
return jsonRes(desktopHealth(DESKTOP_B));
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}${TOKEN_PATH}`) {
return jsonRes({ token: 'desktop-token-b' });
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}/api/workspaces`) return jsonRes([]);
throw new Error(`unmocked fetch: ${value}`);
});
const firstGate = a.armDesktopServiceGate();
const staleBinding = a.connectDesktopService(DESKTOP_A, firstGate);
const staleConsumer = a.connect();
await vi.waitFor(() => expect(
callsTo(fetchSpy, `:${DESKTOP_A.port}${TOKEN_PATH}`),
).toHaveLength(1));
const staleBindingRejected = expect(staleBinding).rejects.toThrow(/superseded|changed/);
const staleConsumerRejected = expect(staleConsumer).rejects.toThrow(/superseded|changed/);
const secondGate = a.armDesktopServiceGate();
const queuedRequest = a.getWorkspaces();
await a.connectDesktopService(DESKTOP_B, secondGate);
await queuedRequest;
releaseOldToken(jsonRes({ token: 'stale-token-a' }));
await Promise.all([staleBindingRejected, staleConsumerRejected]);
expect(a.getServerUrl()).toBe(`http://127.0.0.1:${DESKTOP_B.port}`);
expect(a.isConnected).toBe(true);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(1);
});
it('same-gate competing bindings let only the newest endpoint commit or fail the gate', async () => {
enableTauri();
const a = new LocalAdapter(BASE);
let releaseOldHealth!: (response: Response) => void;
const oldHealthGate = new Promise<Response>(resolve => { releaseOldHealth = resolve; });
fetchSpy.mockImplementation(async (url: unknown) => {
const value = String(url);
if (value === `http://127.0.0.1:${DESKTOP_A.port}/health`) return oldHealthGate;
if (value === `http://127.0.0.1:${DESKTOP_B.port}/health`) {
return jsonRes(desktopHealth(DESKTOP_B));
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}${TOKEN_PATH}`) {
return jsonRes({ token: 'desktop-token-b' });
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}/api/workspaces`) return jsonRes([]);
throw new Error(`unmocked fetch: ${value}`);
});
const gateId = a.armDesktopServiceGate();
const staleBinding = a.connectDesktopService(DESKTOP_A, gateId);
const staleRejected = expect(staleBinding).rejects.toThrow(/identity|superseded|changed/);
await vi.waitFor(() => expect(callsTo(fetchSpy, `:${DESKTOP_A.port}/health`)).toHaveLength(1));
await a.connectDesktopService(DESKTOP_B, gateId);
await a.getWorkspaces();
releaseOldHealth(jsonRes(desktopHealth(DESKTOP_A)));
await staleRejected;
expect(a.getServerUrl()).toBe(`http://127.0.0.1:${DESKTOP_B.port}`);
expect(a.isConnected).toBe(true);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(1);
});
it('a current managed health deadline fails closed instead of releasing queued work', async () => {
vi.useFakeTimers();
enableTauri();
const a = new LocalAdapter(BASE);
fetchSpy.mockImplementation(() => new Promise<Response>(() => { /* never */ }));
const gateId = a.armDesktopServiceGate();
const binding = a.connectDesktopService(DESKTOP_A, gateId);
const queuedRequest = a.getWorkspaces();
const bindingRejected = expect(binding).rejects.toThrow(/timed out/);
const queuedRejected = expect(queuedRequest).rejects.toThrow(/timed out/);
await vi.advanceTimersByTimeAsync(16000);
await Promise.all([bindingRejected, queuedRejected]);
expect(a.isConnected).toBe(false);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('the outer connect watchdog fails closed when token bootstrap body stalls after healthy identity', async () => {
vi.useFakeTimers();
enableTauri();
const a = new LocalAdapter(BASE);
const hangingTokenBody = {
ok: true,
status: 200,
statusText: 'OK',
json: () => new Promise(() => { /* never */ }),
clone() { return this; },
} as unknown as Response;
routeMock(fetchSpy, [
['/health', () => jsonRes(desktopHealth(DESKTOP_A))],
[TOKEN_PATH, () => hangingTokenBody],
]);
const gateId = a.armDesktopServiceGate();
const binding = a.connectDesktopService(DESKTOP_A, gateId);
const queuedRequest = a.getWorkspaces();
const bindingRejected = expect(binding).rejects.toThrow(/timed out/);
const queuedRejected = expect(queuedRequest).rejects.toThrow(/timed out/);
await vi.advanceTimersByTimeAsync(16000);
await Promise.all([bindingRejected, queuedRejected]);
expect(callsTo(fetchSpy, '/health')).toHaveLength(1);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
expect(a.isConnected).toBe(false);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('managed 401 token-body timeout rejects once and closes the verified gate', async () => {
vi.useFakeTimers();
enableTauri();
const a = new LocalAdapter(BASE);
let tokenCalls = 0;
let workspaceCalls = 0;
const hangingTokenBody = {
ok: true,
status: 200,
statusText: 'OK',
json: () => new Promise(() => { /* never */ }),
clone() { return this; },
} as unknown as Response;
routeMock(fetchSpy, [
['/health', () => jsonRes(desktopHealth(DESKTOP_A))],
[TOKEN_PATH, () => (++tokenCalls === 1
? jsonRes({ token: 'desktop-token-a' })
: hangingTokenBody)],
['/api/workspaces', () => {
workspaceCalls++;
return jsonRes({ error: 'Unauthorized' }, 401);
}],
]);
const gateId = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_A, gateId);
const request = a.getWorkspaces();
const rejected = expect(request).rejects.toThrow(/timed out/);
await vi.advanceTimersByTimeAsync(16000);
await rejected;
expect(tokenCalls).toBe(2);
expect(workspaceCalls).toBe(1);
expect(a.isConnected).toBe(false);
expect(() => a.getServerUrl()).toThrow(/not ready/);
});
it('a stale managed deadline cannot poison a newer verified generation', async () => {
vi.useFakeTimers();
enableTauri();
const a = new LocalAdapter(BASE);
fetchSpy.mockImplementation(async (url: unknown) => {
const value = String(url);
if (value === `http://127.0.0.1:${DESKTOP_A.port}/health`) {
return new Promise<Response>(() => { /* never */ });
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}/health`) {
return jsonRes(desktopHealth(DESKTOP_B));
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}${TOKEN_PATH}`) {
return jsonRes({ token: 'desktop-token-b' });
}
if (value === `http://127.0.0.1:${DESKTOP_B.port}/api/workspaces`) return jsonRes([]);
throw new Error(`unmocked fetch: ${value}`);
});
const firstGate = a.armDesktopServiceGate();
const staleBinding = a.connectDesktopService(DESKTOP_A, firstGate);
const staleRejected = expect(staleBinding).rejects.toThrow(/timed out/);
await Promise.resolve();
expect(callsTo(fetchSpy, `:${DESKTOP_A.port}/health`)).toHaveLength(1);
const secondGate = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_B, secondGate);
await a.getWorkspaces();
await vi.advanceTimersByTimeAsync(16000);
await staleRejected;
expect(a.getServerUrl()).toBe(`http://127.0.0.1:${DESKTOP_B.port}`);
expect(a.isConnected).toBe(true);
});
it('desktop gate APIs are inert in the browser and cannot change browser routing', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/workspaces', () => jsonRes([])]]);
expect(a.armDesktopServiceGate()).toBe(0);
a.failDesktopServiceGate(new Error('ignored'), 0);
await a.getWorkspaces();
await expect(a.connectDesktopService(DESKTOP_A, 0)).rejects.toThrow(/only available inside Tauri/);
expect(a.getServerUrl()).toBe(BASE);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(1);
});
it('managed SSE initial open revalidates identity and never opens on a same-port replacement', async () => {
enableTauri();
FakeEventSource.instances = [];
vi.stubGlobal('EventSource', FakeEventSource);
const a = new LocalAdapter(BASE);
let health = desktopHealth(DESKTOP_A);
routeMock(fetchSpy, [
['/health', () => jsonRes(health)],
[TOKEN_PATH, () => jsonRes({ token: 'desktop-token-a' })],
]);
const gateId = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_A, gateId);
health = { ...desktopHealth(DESKTOP_B), port: DESKTOP_A.port };
const unsubscribe = a.subscribeNotifications(() => {});
await flush();
expect(FakeEventSource.instances).toHaveLength(0);
expect(() => a.getServerUrl()).toThrow(/not ready/);
unsubscribe();
});
it('managed SSE retry revalidates identity after token refresh and refuses an unverified replacement', async () => {
vi.useFakeTimers();
enableTauri();
FakeEventSource.instances = [];
vi.stubGlobal('EventSource', FakeEventSource);
const a = new LocalAdapter(BASE);
let health = desktopHealth(DESKTOP_A);
let token = 'desktop-token-a';
routeMock(fetchSpy, [
['/health', () => jsonRes(health)],
[TOKEN_PATH, () => jsonRes({ token })],
]);
const gateId = a.armDesktopServiceGate();
await a.connectDesktopService(DESKTOP_A, gateId);
const unsubscribe = a.subscribeNotifications(() => {});
await vi.advanceTimersByTimeAsync(0);
expect(FakeEventSource.instances).toHaveLength(1);
health = { ...desktopHealth(DESKTOP_B), port: DESKTOP_A.port };
token = 'desktop-token-b';
FakeEventSource.instances[0].fireError();
await vi.advanceTimersByTimeAsync(1100);
expect(FakeEventSource.instances).toHaveLength(1);
expect(FakeEventSource.instances[0].closed).toBe(true);
expect(() => a.getServerUrl()).toThrow(/not ready/);
unsubscribe();
});
// ── setServerUrl epoch guard ─────────────────────────────────────────────
it('setServerUrl mid-flight: the stale connect cannot set connected state or the token', async () => {
@@ -288,6 +725,72 @@ describe('P1b auth gate', () => {
await expect(consume()).rejects.toThrow(AdapterHttpError);
});
it('fetchWithTimeout preserves fresh and pre-aborted caller cancellation without AbortSignal.any', async () => {
const anyDescriptor = Object.getOwnPropertyDescriptor(AbortSignal, 'any');
Object.defineProperty(AbortSignal, 'any', { configurable: true, value: undefined });
vi.useFakeTimers();
const caller = new AbortController();
fetchSpy.mockImplementation(async (_url, init) => new Promise<Response>((_resolve, reject) => {
const signal = (init as RequestInit | undefined)?.signal;
if (!(signal instanceof AbortSignal)) throw new Error('missing request signal');
if (signal.aborted) {
reject(new DOMException('The operation was aborted', 'AbortError'));
return;
}
signal.addEventListener(
'abort',
() => reject(new DOMException('The operation was aborted', 'AbortError')),
{ once: true },
);
}));
try {
const request = fetchWithTimeout(`${BASE}/slow`, { signal: caller.signal });
caller.abort();
await expect(request).rejects.toMatchObject({ name: 'AbortError' });
const preAborted = new AbortController();
preAborted.abort();
await expect(fetchWithTimeout(`${BASE}/already-stopped`, {
signal: preAborted.signal,
})).rejects.toMatchObject({ name: 'AbortError' });
expect(vi.getTimerCount()).toBe(0);
} finally {
if (anyDescriptor) Object.defineProperty(AbortSignal, 'any', anyDescriptor);
else Reflect.deleteProperty(AbortSignal, 'any');
}
});
it('abortAgent cancels only the requested chat session', async () => {
const a = new LocalAdapter(BASE);
const requestSignals: AbortSignal[] = [];
fetchSpy.mockImplementation(async (_url, init) => new Promise<Response>((_resolve, reject) => {
const signal = (init as RequestInit | undefined)?.signal;
if (!(signal instanceof AbortSignal)) throw new Error('missing request signal');
requestSignals.push(signal);
signal.addEventListener(
'abort',
() => reject(new DOMException('The operation was aborted', 'AbortError')),
{ once: true },
);
}));
const sessionA = a.sendMessage('ws1', 'first', 'session-a');
const sessionB = a.sendMessage('ws1', 'second', 'session-b');
const resultA = sessionA.next().catch((error: unknown) => error);
const resultB = sessionB.next().catch((error: unknown) => error);
await vi.waitFor(() => expect(requestSignals).toHaveLength(2));
await a.abortAgent('ws1', 'session-a');
expect(requestSignals[0].aborted).toBe(true);
expect(requestSignals[1].aborted).toBe(false);
await expect(resultA).resolves.toMatchObject({ name: 'AbortError' });
await a.abortAgent('ws1');
expect(requestSignals[1].aborted).toBe(true);
await expect(resultB).resolves.toMatchObject({ name: 'AbortError' });
});
// ── Body-envelope getters (fetchRaw contract — ApprovalModal flow et al) ──
it('installMcp resolves the 422 SecurityGate envelope (requiresApproval) instead of throwing', async () => {

View File

@@ -30,4 +30,41 @@ describe('model router request deadlines', () => {
45_000,
]);
});
it('allows chat time-to-first-token to exceed the generic request timeout', async () => {
const fetchSpy = vi.spyOn(client, 'fetch').mockResolvedValue(new Response([
'event: done',
'data: {"content":"ok"}',
'',
'',
].join('\n'), {
status: 200,
headers: { 'content-type': 'text/event-stream' },
}));
const events = [];
for await (const event of client.sendMessage(
'workspace-1',
'hello',
'session-1',
'writer',
undefined,
undefined,
'openai/requested-model',
)) {
events.push(event);
}
expect(fetchSpy).toHaveBeenCalledOnce();
expect(fetchSpy.mock.calls[0]?.[2]).toBe(45_000);
const request = fetchSpy.mock.calls[0]?.[1] as RequestInit;
expect(JSON.parse(request.body as string)).toMatchObject({
workspaceId: 'workspace-1',
message: 'hello',
sessionId: 'session-1',
persona: 'writer',
model: 'openai/requested-model',
});
expect(events).toEqual([{ type: 'done', data: { content: 'ok' } }]);
});
});

View File

@@ -14,6 +14,7 @@ import {
type FrameImportance,
type FrameSource,
type IdentityResponse,
type DesktopServiceEndpoint,
} from './tauri-bindings';
import type {
Workspace, WorkspaceContext, ChatMessage, MemoryFrame, Memory,
@@ -64,6 +65,31 @@ export interface AgentGroupRunResult {
message?: string;
}
export interface ManagedLocalRuntimeStatus {
source: 'waggle-managed';
supported: boolean;
installed: boolean;
running: boolean;
targetVersion: string | null;
version: string | null;
artifactSizeBytes: number | null;
downloadRequired: boolean;
dockerRequired: false;
reason?: string;
}
export interface LocalInferenceStatus {
servers: Array<Record<string, unknown>>;
ollamaInstalled: boolean;
ollamaRunning: boolean;
totalLocalModels: number;
offlineReady: boolean;
dockerRequired: false;
managedRuntime: ManagedLocalRuntimeStatus;
setupRequired: boolean;
setupMessage: string | null;
}
/**
* CC Sesija A §2.2 — map adapter `MemoryFrame.importance` (number 1-4) to the
* Tauri command's string enum. Inverse of IMPORTANCE_MAP.
@@ -97,6 +123,12 @@ export interface ChannelPairedSender {
export type ChannelPairings = Partial<Record<ChannelPlatform, ChannelPairedSender[]>>;
export interface BrowserCompanionPairingStatus {
paired: boolean;
extensionId: string | null;
pairedAt: string | null;
}
export function resolveDefaultServerUrl(
locationLike: Pick<Location, 'protocol' | 'hostname' | 'port' | 'origin'> | undefined =
typeof window !== 'undefined' ? window.location : undefined,
@@ -249,10 +281,28 @@ export interface EmbeddingRoutingStatus {
class LocalAdapter {
private baseUrl: string;
private readonly managedDesktop: boolean;
private desktopEndpoint: DesktopServiceEndpoint | null = null;
private desktopEndpointReady = false;
private desktopGateId = 0;
private desktopGate: {
id: number;
promise: Promise<void>;
resolve: () => void;
reject: (error: Error) => void;
status: 'pending' | 'ready' | 'failed';
error: Error | null;
} | null = null;
private authToken: string | null = null;
private ws: WebSocket | null = null;
/** P1b-SSE: one ref-counted reconnecting stream per (path, eventName). */
private sseStreams = new Map<string, { close: () => void; listeners: Set<(data: unknown) => void> }>();
/** Active chat requests, session-scoped with workspace-wide Stop fallback. */
private activeChatControllers = new Map<string, Set<AbortController>>();
private chatControllerKey(workspaceId: string, sessionId?: string): string {
return `${workspaceId}\u0000${sessionId ?? ''}`;
}
private _connected = false;
private _connectAttempted = false;
// P1b D3 gate state. _connectPromise doubles as the deferral gate: kept
@@ -267,13 +317,19 @@ class LocalAdapter {
private _epoch = 0;
constructor(serverUrl?: string) {
this.baseUrl = serverUrl || localStorage.getItem('waggle:server-url') || resolveDefaultServerUrl();
this.managedDesktop = isTauri();
this.baseUrl = this.managedDesktop
? resolveDefaultServerUrl()
: serverUrl || localStorage.getItem('waggle:server-url') || resolveDefaultServerUrl();
}
get isConnected() { return this._connected; }
get hasAttemptedConnect() { return this._connectAttempted; }
setServerUrl(url: string) {
if (this.managedDesktop) {
throw new Error('The desktop service endpoint is managed by Waggle');
}
this._epoch++;
this.baseUrl = url;
localStorage.setItem('waggle:server-url', url);
@@ -290,9 +346,147 @@ class LocalAdapter {
}
getServerUrl() {
if (this.managedDesktop && (!this.desktopEndpoint || !this.desktopEndpointReady)) {
throw new Error('The managed desktop service endpoint is not ready');
}
return this.baseUrl;
}
armDesktopServiceGate(): number {
if (!this.managedDesktop) return 0;
if (this.desktopGate?.status === 'pending') {
const superseded = new Error('The managed desktop service launch was superseded');
this.desktopGate.status = 'failed';
this.desktopGate.error = superseded;
this.desktopGate.reject(superseded);
}
this._epoch++;
this.desktopEndpoint = null;
this.desktopEndpointReady = false;
this.authToken = null;
this._connected = false;
this._connectAttempted = false;
this._connectPromise = null;
this._healthProbePromise = null;
this._refreshPromise = null;
const id = ++this.desktopGateId;
let resolve!: () => void;
let reject!: (error: Error) => void;
const promise = new Promise<void>((resolveGate, rejectGate) => {
resolve = resolveGate;
reject = rejectGate;
});
void promise.catch(() => { /* future requests observe the same failure */ });
this.desktopGate = {
id,
promise,
resolve,
reject,
status: 'pending',
error: null,
};
return id;
}
async connectDesktopService(
endpoint: DesktopServiceEndpoint,
gateId: number,
): Promise<SystemHealth> {
if (!this.managedDesktop) {
throw new Error('Desktop service binding is only available inside Tauri');
}
if (!Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535
|| typeof endpoint.instanceId !== 'string' || endpoint.instanceId.trim().length === 0) {
throw new Error('Tauri returned an invalid desktop service endpoint');
}
if (!this.desktopGate || this.desktopGate.id !== gateId
|| this.desktopGate.status !== 'pending') {
throw new Error('Ignoring a stale desktop service endpoint');
}
const bindEpoch = ++this._epoch;
this.baseUrl = `http://127.0.0.1:${endpoint.port}`;
this.desktopEndpoint = {
port: endpoint.port,
instanceId: endpoint.instanceId,
...(endpoint.bootstrapToken ? { bootstrapToken: endpoint.bootstrapToken } : {}),
};
this.desktopEndpointReady = false;
this.authToken = null;
this._connected = false;
this._connectAttempted = false;
this._connectPromise = null;
this._healthProbePromise = null;
this._refreshPromise = null;
try {
const health = await this.connect();
const record = health as SystemHealth & { instanceId?: unknown; port?: unknown };
if (record.instanceId !== endpoint.instanceId || record.port !== endpoint.port) {
throw new Error('Desktop service health identity does not match the Tauri endpoint');
}
if (!this.desktopGate || this.desktopGate.id !== gateId
|| bindEpoch !== this._epoch
|| this.desktopGate.status !== 'pending'
|| this.desktopEndpoint?.port !== endpoint.port
|| this.desktopEndpoint?.instanceId !== endpoint.instanceId) {
throw new Error('Desktop service launch changed during connection');
}
this.desktopGate.status = 'ready';
this.desktopGate.error = null;
this.desktopEndpointReady = true;
this.desktopGate.resolve();
return health;
} catch (error) {
this.failCurrentDesktopGeneration(error, bindEpoch);
throw error;
}
}
failDesktopServiceGate(error: unknown, gateId: number): void {
if (!this.managedDesktop || !this.desktopGate || this.desktopGate.id !== gateId) return;
if (this.desktopGate.status === 'failed') return;
const failure = error instanceof Error ? error : new Error(String(error));
this._epoch++;
this.desktopEndpoint = null;
this.desktopEndpointReady = false;
this.authToken = null;
this._connected = false;
this._connectPromise = null;
this._healthProbePromise = null;
this._refreshPromise = null;
this.desktopGate.status = 'failed';
this.desktopGate.error = failure;
this.desktopGate.reject(failure);
}
private failCurrentDesktopGeneration(error: unknown, epoch: number): void {
if (!this.managedDesktop || epoch !== this._epoch) return;
const gateId = this.desktopGate?.id;
if (gateId !== undefined) this.failDesktopServiceGate(error, gateId);
}
private async awaitDesktopServiceGate(): Promise<void> {
if (!this.managedDesktop) return;
while (true) {
const gate = this.desktopGate;
if (!gate) {
throw new Error('The managed desktop service gate was not armed');
}
try {
await gate.promise;
} catch (error) {
if (this.desktopGate !== gate) continue;
throw error;
}
if (this.desktopGate !== gate) continue;
if (gate.status === 'failed') {
throw gate.error ?? new Error('The managed desktop service failed');
}
if (gate.status === 'ready') return;
}
}
/**
* P1b D3: explicit re-probe that bypasses the retained settled-success
* memo. `connect()` deliberately dedups onto a successful attempt (the
@@ -315,10 +509,15 @@ class LocalAdapter {
* gated request via ensureReady's re-arm) starts a fresh attempt.
*/
connect(): Promise<SystemHealth> {
if (this.managedDesktop && !this.desktopEndpoint) {
return this.awaitDesktopServiceGate().then(() => this.connect());
}
if (this._connectPromise) return this._connectPromise;
const p = this.doConnect(this._epoch);
const epoch = this._epoch;
const p = this.doConnect(epoch);
this._connectPromise = p;
p.catch(() => {
p.catch((error) => {
this.failCurrentDesktopGeneration(error, epoch);
if (this._connectPromise === p) this._connectPromise = null;
});
return p;
@@ -339,18 +538,27 @@ class LocalAdapter {
try {
const data = await Promise.race([
(async () => {
const health = await this.healthProbe(epoch);
let health = await this.healthProbe(epoch);
if (this.managedDesktop && epoch !== this._epoch) {
throw new Error('Connection attempt was superseded by a newer desktop generation');
}
// D1: the sidecar requires a bearer token even on loopback. Fetch it
// from the auth-exempt, same-origin-gated bootstrap. (R1-001: it is
// NOT served by the unauthenticated /health.) Best-effort — if the
// bootstrap is unreachable we proceed token-less; the 401-refresh
// retry leg recovers as soon as the endpoint is reachable.
await this.fetchSessionToken(epoch);
if (this.managedDesktop) {
health = await this.revalidateDesktopEndpoint(epoch);
}
return health;
})(),
deadline,
]);
if (epoch === this._epoch) this._connected = true;
if (epoch !== this._epoch) {
throw new Error('Connection attempt was superseded by a newer desktop generation');
}
this._connected = true;
return data;
} catch (e) {
if (epoch === this._epoch) this._connected = false;
@@ -361,8 +569,8 @@ class LocalAdapter {
}
/**
* P1b D3: the deferral gate awaited by every non-exempt request.
* Four states:
* P1b D3: the connection gate awaited by every non-exempt request.
* Browser mode retains four states:
* - never attempted → pass through (keeps the adapter unit-test files,
* which construct LocalAdapter and call methods directly, gate-free;
* production arms the gate via boot-connect.ts, main.tsx's first import)
@@ -372,10 +580,13 @@ class LocalAdapter {
* onto it. This makes the gate self-healing on the default desktop path
* (webview up before the sidecar listens: the boot kickoff fails fast
* with ECONNREFUSED and must not permanently disarm the gate).
* A FAILED attempt always releases the gate — the request proceeds and
* fails loudly with its own cause rather than hanging.
* A failed browser attempt releases the gate so the request fails with its
* own cause rather than hanging. Managed desktop mode first awaits the
* separate Rust-owned endpoint gate; a failed identity handshake stays
* closed until a newer lifecycle generation rearms it.
*/
private async ensureReady(): Promise<void> {
await this.awaitDesktopServiceGate();
if (!this._connectAttempted) return;
const gate = this._connectPromise ?? this.connect();
try { await gate; } catch { /* released — request fails with its own cause */ }
@@ -386,7 +597,7 @@ class LocalAdapter {
* null. The 401-refresh leg (refreshSessionToken) is the LOUD variant. */
private async fetchSessionToken(epoch: number): Promise<void> {
try {
const res = await this.request('/api/auth/session-token');
const res = await this.request('/api/auth/session-token', undefined, undefined, false, true);
if (res.ok) {
const body = (await res.json()) as { token?: string };
if (epoch === this._epoch) this.authToken = body.token ?? null;
@@ -419,6 +630,9 @@ class LocalAdapter {
if (epoch === this._epoch) this.authToken = body.token;
})(), CONNECT_DEADLINE_MS, 'session-token refresh');
this._refreshPromise = p;
if (this.managedDesktop) {
void p.catch((error) => this.failCurrentDesktopGeneration(error, epoch));
}
p.finally(() => {
if (this._refreshPromise === p) this._refreshPromise = null;
}).catch(() => { /* settled via callers */ });
@@ -451,18 +665,53 @@ class LocalAdapter {
if (this._healthProbePromise) return this._healthProbePromise;
const p = deadlined(this.doHealthProbe(epoch), CONNECT_DEADLINE_MS, 'health probe');
this._healthProbePromise = p;
void p.catch((error) => this.failCurrentDesktopGeneration(error, epoch));
p.finally(() => {
if (this._healthProbePromise === p) this._healthProbePromise = null;
}).catch(() => { /* settled via callers */ });
return p;
}
/**
* A managed token is process-scoped. Always perform a fresh, non-memoized
* identity probe after obtaining one so a same-port sidecar replacement
* cannot inherit the previous Rust-verified generation's trust.
*/
private async revalidateDesktopEndpoint(epoch: number): Promise<SystemHealth> {
if (epoch !== this._epoch) {
throw new Error('Desktop service generation changed before revalidation');
}
try {
const health = await deadlined(
this.doHealthProbe(epoch),
CONNECT_DEADLINE_MS,
'desktop health revalidation',
);
if (epoch !== this._epoch) {
throw new Error('Desktop service generation changed during revalidation');
}
return health;
} catch (error) {
this.failCurrentDesktopGeneration(error, epoch);
throw error;
}
}
private async doHealthProbe(epoch: number): Promise<SystemHealth> {
try {
const res = await this.request('/health');
const res = await this.request('/health', undefined, undefined, false, true);
if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined));
return await res.json();
const data = await res.json() as SystemHealth & { instanceId?: unknown; port?: unknown };
if (this.managedDesktop && (
!this.desktopEndpoint
|| data.instanceId !== this.desktopEndpoint.instanceId
|| data.port !== this.desktopEndpoint.port
)) {
throw new Error('Desktop service health identity does not match the Tauri endpoint');
}
return data;
} catch (firstErr) {
if (this.managedDesktop) throw firstErr;
const fallbackServer = resolveDefaultServerUrl();
if (this.baseUrl === fallbackServer) throw firstErr;
try {
@@ -510,10 +759,21 @@ class LocalAdapter {
/** Shared request core: deferral gate → headers/token → fetch → 403 tier
* dispatch → 401 refresh-retry (token-versioned, once per request). */
private async request(path: string, init?: RequestInit, timeoutMs?: number, isRetry = false): Promise<Response> {
private async request(
path: string,
init?: RequestInit,
timeoutMs?: number,
isRetry = false,
bypassDesktopGate = false,
): Promise<Response> {
const purePath = path.split('?')[0];
const exempt = AUTH_EXEMPT_PATHS.has(purePath);
if (!bypassDesktopGate) await this.awaitDesktopServiceGate();
if (!exempt) await this.ensureReady();
// A restart can rearm the desktop gate while ensureReady() is awaiting an
// older connect attempt. Recheck immediately before the synchronous fetch
// call so that attempt cannot release a request onto the superseded port.
if (!bypassDesktopGate) await this.awaitDesktopServiceGate();
const issuedToken = this.authToken;
const headers: Record<string, string> = {
@@ -535,6 +795,13 @@ class LocalAdapter {
if (issuedToken) {
headers['Authorization'] = `Bearer ${issuedToken}`;
}
if (
this.managedDesktop
&& purePath === '/api/auth/session-token'
&& this.desktopEndpoint?.bootstrapToken
) {
headers['X-Waggle-Desktop-Bootstrap'] = this.desktopEndpoint.bootstrapToken;
}
const res = await fetchWithTimeout(`${this.baseUrl}${path}`, { ...init, headers }, timeoutMs);
if (res.status === 403) {
const clone = res.clone();
@@ -557,7 +824,11 @@ class LocalAdapter {
if (this.authToken === issuedToken) {
await this.refreshSessionToken();
}
return this.request(path, init, timeoutMs, true);
if (this.managedDesktop) {
await this.awaitDesktopServiceGate();
await this.revalidateDesktopEndpoint(this._epoch);
}
return this.request(path, init, timeoutMs, true, bypassDesktopGate);
}
return res;
}
@@ -634,12 +905,12 @@ class LocalAdapter {
return res.json();
}
async updateWorkspace(id: string, data: Partial<Workspace>): Promise<Workspace> {
async updateWorkspace(id: string, data: Partial<Pick<Workspace, 'persona' | 'agentGroupId' | 'templateId' | 'name' | 'group' | 'model' | 'status' | 'description' | 'type'>>): Promise<Workspace> {
const res = await this.fetch(`/api/workspaces/${id}`, { method: 'PUT', body: JSON.stringify(data) });
return res.json();
}
async patchWorkspace(id: string, data: Partial<Pick<Workspace, 'persona' | 'agentGroupId' | 'templateId' | 'name' | 'group' | 'model' | 'status' | 'description'>>): Promise<Workspace> {
async patchWorkspace(id: string, data: Partial<Pick<Workspace, 'persona' | 'agentGroupId' | 'templateId' | 'name' | 'group' | 'model' | 'status' | 'description' | 'type'>>): Promise<Workspace> {
const res = await this.fetch(`/api/workspaces/${id}`, { method: 'PATCH', body: JSON.stringify(data) });
return res.json();
}
@@ -795,59 +1066,97 @@ class LocalAdapter {
persona?: string,
autonomy?: { level: 'normal' | 'trusted' | 'yolo'; expiresAt?: number },
retry?: boolean,
model?: string,
): AsyncGenerator<StreamEvent> {
// CC Sesija A §2.2 — thread the user-selected Faza 1 GEPA shape into the
// chat body. Sidecar /api/chat ignores `shape` until A3.1 wires it into
// runRetrievalAgentLoop; carrying it now means A3.1 is a one-line server
// change with no client redeploy needed.
const shape = getSelectedShape();
const res = await this.fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ workspaceId, message, sessionId, persona, autonomy, shape, retry }),
});
const controller = new AbortController();
const chatControllerKey = this.chatControllerKey(workspaceId, sessionId);
let controllers = this.activeChatControllers.get(chatControllerKey);
if (!controllers) {
controllers = new Set();
this.activeChatControllers.set(chatControllerKey, controllers);
}
controllers.add(controller);
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
if (!res.body) return;
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let currentEventType = '';
try {
const res = await this.fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ workspaceId, message, sessionId, persona, autonomy, shape, retry, model }),
signal: controller.signal,
}, MODEL_ROUTER_REQUEST_TIMEOUT_MS);
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.startsWith('event: ')) {
currentEventType = line.slice(7).trim();
} else if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
// Map SSE event types to StreamEvent types expected by useChat
let type = currentEventType;
if (type === 'token') type = 'token';
else if (type === 'tool') type = 'tool_start';
else if (type === 'tool_result') type = 'tool_end';
else if (type === 'done') type = 'done';
else if (type === 'error') type = 'error';
else if (type === 'step') type = 'step';
else if (type === 'approval_request') type = 'approval_request';
if (!res.body) return;
reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let currentEventType = '';
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.startsWith('event: ')) {
currentEventType = line.slice(7).trim();
} else if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
// Map SSE event types to StreamEvent types expected by useChat
let type = currentEventType;
if (type === 'token') type = 'token';
else if (type === 'tool') type = 'tool_start';
else if (type === 'tool_result') type = 'tool_end';
else if (type === 'done') type = 'done';
else if (type === 'error') type = 'error';
else if (type === 'step') type = 'step';
else if (type === 'approval_request') type = 'approval_request';
yield { type, data } as StreamEvent;
currentEventType = '';
} catch { /* skip malformed */ }
yield { type, data } as StreamEvent;
currentEventType = '';
} catch { /* skip malformed */ }
}
}
}
} finally {
controller.abort();
controllers.delete(controller);
if (controllers.size === 0 && this.activeChatControllers.get(chatControllerKey) === controllers) {
this.activeChatControllers.delete(chatControllerKey);
}
if (reader) {
try { await reader.cancel(); } catch { /* stream already closed */ }
try { reader.releaseLock(); } catch { /* reader already released */ }
}
}
}
async abortAgent(workspaceId: string): Promise<void> {
await this.fetch(`/api/agent/abort`, { method: 'POST', body: JSON.stringify({ workspaceId }) });
async abortAgent(workspaceId: string, sessionId?: string): Promise<void> {
const controllerKeys = sessionId !== undefined
? [this.chatControllerKey(workspaceId, sessionId)]
: [...this.activeChatControllers.keys()].filter(
key => key.startsWith(`${workspaceId}\u0000`),
);
for (const controllerKey of controllerKeys) {
const controllers = this.activeChatControllers.get(controllerKey);
if (!controllers) continue;
this.activeChatControllers.delete(controllerKey);
for (const controller of controllers) controller.abort();
}
}
async clearHistory(sessionId: string): Promise<void> {
await this.fetch(`/api/chat/history?session=${sessionId}`, { method: 'DELETE' });
async clearHistory(
workspaceId: string | null,
sessionId: string,
): Promise<void> {
const params = new URLSearchParams({ session: sessionId });
if (workspaceId) params.set('workspace', workspaceId);
await this.fetch(`/api/chat/history?${params.toString()}`, { method: 'DELETE' });
}
async getHistory(workspaceId: string, sessionId: string): Promise<ChatMessage[]> {
@@ -1202,13 +1511,32 @@ class LocalAdapter {
return res.json();
}
async getLocalInferenceStatus(): Promise<{ servers: Array<Record<string, unknown>>; ollamaInstalled: boolean; totalLocalModels: number }> {
async getLocalInferenceStatus(): Promise<LocalInferenceStatus> {
const res = await this.fetch('/api/local-inference/status');
return res.json();
}
async pullLocalModel(model: string): Promise<{ ok: boolean }> {
const res = await this.fetch('/api/local-inference/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model }) });
async bootstrapLocalRuntime(): Promise<{
ok: boolean;
installedNow: boolean;
startedNow: boolean;
endpoint: string;
dockerRequired: false;
}> {
const res = await this.fetch(
'/api/local-inference/bootstrap',
{ method: 'POST' },
45 * 60_000,
);
return res.json();
}
async pullLocalModel(model: string): Promise<{ ok: boolean; model: string; verifiedGeneration: boolean }> {
const res = await this.fetch(
'/api/local-inference/pull',
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model }) },
50 * 60_000,
);
return res.json();
}
@@ -2141,6 +2469,20 @@ class LocalAdapter {
return res.json();
}
async getBrowserCompanionPairing(): Promise<BrowserCompanionPairingStatus> {
const res = await this.fetch('/api/browser-ext/pairing');
return res.json();
}
async createBrowserCompanionPairingCode(): Promise<{ code: string; expiresAt: number }> {
const res = await this.fetch('/api/browser-ext/pairing-code', { method: 'POST' });
return res.json();
}
async revokeBrowserCompanionPairing(): Promise<void> {
await this.fetch('/api/browser-ext/pairing', { method: 'DELETE' });
}
async saveChannelConfig(
platform: ChannelPlatform,
config: {
@@ -2456,6 +2798,7 @@ class LocalAdapter {
// --- Health ---
async getSystemHealth(): Promise<SystemHealth> {
if (this.managedDesktop) await this.awaitDesktopServiceGate();
// Use the same auto-discovery fallback as connect() so the offline pill
// converges on the working URL even if useOfflineStatus polls before
// ServiceProvider's connect() effect runs (FR #10).
@@ -2480,7 +2823,7 @@ class LocalAdapter {
async connectConnector(id: string, credentials?: {
token?: string; apiKey?: string; refreshToken?: string;
expiresAt?: string; scopes?: string[]; email?: string;
expiresAt?: string; scopes?: string[]; email?: string; baseUrl?: string; instanceUrl?: string;
}): Promise<void> {
await this.fetch(`/api/connectors/${id}/connect`, {
method: 'POST',
@@ -3173,22 +3516,50 @@ class LocalAdapter {
es.onerror = () => {
es?.close();
if (cancelled) return;
const delay = Math.min(30000, 1000 * 2 ** attempt++);
retryTimer = setTimeout(() => {
// Sidecar restart rotates the token; the URL-baked one is then
// permanently stale. Best-effort refresh before each reopen —
// single-flighted, and a failure just means the next backoff round.
void this.refreshSessionToken().catch(() => { /* server still down */ })
.then(() => { if (!cancelled) open(); });
}, delay);
scheduleRetry();
};
};
const scheduleRetry = () => {
if (cancelled) return;
const delay = Math.min(30000, 1000 * 2 ** attempt++);
retryTimer = setTimeout(() => {
// Sidecar restart rotates the token; wait for the current desktop gate
// and a fresh token before constructing a URL for the replacement
// generation. Failed refreshes stay closed and back off again.
void this.refreshSessionToken()
.then(() => this.awaitDesktopServiceGate())
.then(async () => {
if (this.managedDesktop) {
await this.revalidateDesktopEndpoint(this._epoch);
}
})
.then(() => { if (!cancelled) open(); })
.catch(() => {
if (cancelled) return;
if (this.managedDesktop) scheduleRetry();
else open();
});
}, delay);
};
// Lazy-open: wait for the connect attempt to settle so the token exists.
// Never-attempted (unit tests) passes through immediately; a FAILED
// connect also releases — the stream 401s and enters the retry loop,
// which doubles as the recovery path.
void this.ensureReady().then(() => { if (!cancelled) open(); });
void this.ensureReady()
.then(() => this.awaitDesktopServiceGate())
.then(async () => {
if (this.managedDesktop) {
await this.revalidateDesktopEndpoint(this._epoch);
}
})
.then(() => { if (!cancelled) open(); })
.catch(() => {
if (cancelled) return;
if (this.managedDesktop) scheduleRetry();
else open();
});
return () => {
cancelled = true;
@@ -3641,6 +4012,9 @@ class LocalAdapter {
// --- WebSocket ---
connectWebSocket(onMessage: (data: unknown) => void): () => void {
if (this.managedDesktop && (!this.desktopEndpoint || !this.desktopEndpointReady)) {
throw new Error('The managed desktop service endpoint is not ready');
}
const wsUrl = this.baseUrl.replace('http', 'ws') + `/ws?token=${this.authToken}`;
this.ws = new WebSocket(wsUrl);
this.ws.onmessage = (e) => {

View File

@@ -12,6 +12,29 @@ export class NetworkError extends Error {
}
}
function combineAbortSignals(signals: AbortSignal[]): {
signal: AbortSignal;
cleanup: () => void;
} {
if (typeof AbortSignal.any === 'function') {
return { signal: AbortSignal.any(signals), cleanup: () => {} };
}
const controller = new AbortController();
const abort = () => controller.abort();
if (signals.some(signal => signal.aborted)) {
abort();
} else {
for (const signal of signals) signal.addEventListener('abort', abort, { once: true });
}
return {
signal: controller.signal,
cleanup: () => {
for (const signal of signals) signal.removeEventListener('abort', abort);
},
};
}
export async function fetchWithTimeout(
url: string,
options: RequestInit = {},
@@ -19,19 +42,26 @@ export async function fetchWithTimeout(
): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
const combined = options.signal
? combineAbortSignals([options.signal, controller.signal])
: { signal: controller.signal, cleanup: () => {} };
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
signal: combined.signal,
});
return response;
} catch (err: unknown) {
if (err instanceof Error && err.name === 'AbortError') {
if (controller.signal.aborted && !options.signal?.aborted) {
throw new TimeoutError(url, timeoutMs);
}
// Caller cancellation (for example Chat Stop) is control flow, not a
// timeout/network outage. Preserve the native AbortError for the caller.
if (options.signal?.aborted) throw err;
throw new NetworkError(url, err instanceof Error ? err : undefined);
} finally {
clearTimeout(timeout);
combined.cleanup();
}
}

View File

@@ -57,17 +57,15 @@ describe('promptArgsForTool', () => {
});
describe('hermes', () => {
it('passes prompt as positional argument (best-effort convention)', () => {
expect(promptArgsForTool('hermes', 'summarize todays standup')).toEqual([
'summarize todays standup',
]);
it('does not send an unverified positional prompt during interactive launch', () => {
expect(promptArgsForTool('hermes', 'summarize todays standup')).toBeNull();
});
});
// ── GUI / folder-based tools ───────────────────────────────────────
describe('GUI-only / folder-based tools return null', () => {
it.each(['cursor', 'claude-desktop', 'codex-desktop'])(
it.each(['cursor', 'claude-desktop', 'codex-desktop', 'hermes-desktop'])(
'%s — no CLI prompt surface',
(toolId) => {
expect(promptArgsForTool(toolId, 'anything')).toBeNull();
@@ -87,7 +85,8 @@ describe('toolAcceptsInlinePrompt', () => {
['claude-code', true],
['openclaw', true],
['codex', true],
['hermes', true],
['hermes', false],
['hermes-desktop', false],
['cursor', false],
['claude-desktop', false],
['codex-desktop', false],

View File

@@ -12,7 +12,8 @@
* claude-code → ['--print', prompt]
* openclaw → ['--print', prompt] (Claude Code fork)
* codex → [prompt] (positional arg)
* hermes → [prompt] (positional arg — best-effort)
* hermes → null (captured-task API only)
* hermes-desktop → null (GUI only)
* cursor → null (folder-based; no CLI prompt)
* claude-desktop → null (GUI only)
* codex-desktop → null (GUI only)
@@ -63,20 +64,17 @@ export function promptArgsForTool(toolId: string, prompt: string): string[] | nu
case 'codex':
return [p];
// Hermes Agent CLI: positional-arg convention by analogy. The
// hive-mind-hooks-hermes package is a Wave 2/3 stub; this entry
// is documented as best-effort and should be verified once the
// Hermes CLI is exercised against a real binary.
case 'hermes':
return [p];
// GUI-only tools: no CLI prompt surface.
// GUI-only tools and Hermes interactive launch: no verified inline-prompt
// surface. Hermes captured tasks use the shared headless task contract,
// not this dock-launch helper.
// cursor: opens a folder (`cursor /path`), no --prompt flag.
// claude-desktop / codex-desktop: GUI binaries with no
// prompt-from-CLI handoff documented.
case 'cursor':
case 'claude-desktop':
case 'codex-desktop':
case 'hermes':
case 'hermes-desktop':
return null;
default:

View File

@@ -74,4 +74,63 @@ describe('renderChatMarkdown', () => {
const html = renderChatMarkdown('a\n\nb');
expect(html).toContain('<span class="block h-2">');
});
it('preserves wildcard operators inside inline code', () => {
const host = document.createElement('div');
host.innerHTML = renderChatMarkdown('Run `search_files("**/*")` without editing.');
expect(host.querySelector('code')?.textContent).toBe('search_files("**/*")');
expect(host.querySelector('code strong, code em')).toBeNull();
});
it('preserves emphasis and safe links wrapped around inline code', () => {
const host = document.createElement('div');
host.innerHTML = renderChatMarkdown('Use **`npm test`** or [`npm run build`](https://example.com).');
expect(host.querySelector('strong code')?.textContent).toBe('npm test');
expect(host.querySelector('a[href="https://example.com"] code')?.textContent).toBe('npm run build');
});
it('never restores an inline code tag inside a link attribute', () => {
const host = document.createElement('div');
host.innerHTML = renderChatMarkdown('[x](https://example.com/`fragment`)');
expect(host.querySelector('a')).toBeNull();
expect(host.querySelector('code')?.textContent).toBe('fragment');
});
it('preserves indentation and operators inside fenced code', () => {
const source = [
'```python',
'def retry(attempt: int) -> float:',
' return base_backoff_s * (2 ** attempt)',
'```',
].join('\n');
const host = document.createElement('div');
host.innerHTML = renderChatMarkdown(source);
expect(host.querySelector('pre code')?.textContent).toBe([
'def retry(attempt: int) -> float:',
' return base_backoff_s * (2 ** attempt)',
].join('\n'));
expect(host.querySelector('pre code strong, pre code em')).toBeNull();
});
it('renders an unfinished streaming fence as safe preformatted code', () => {
const host = document.createElement('div');
host.innerHTML = renderChatMarkdown('```python\nvalue = 2 ** attempt');
expect(host.querySelector('pre code')?.textContent).toBe('value = 2 ** attempt');
});
it('keeps fenced HTML inert and refuses unsafe language metadata', () => {
const safeHost = document.createElement('div');
safeHost.innerHTML = renderChatMarkdown('```html\n<script>alert(1)</script>\n```');
expect(safeHost.querySelector('script')).toBeNull();
expect(safeHost.querySelector('pre code')?.textContent).toBe('<script>alert(1)</script>');
const unsafeHtml = renderChatMarkdown('```\"><img src=x onerror=alert(1)>\nbody');
expect(unsafeHtml).not.toContain('<img');
expect(unsafeHtml).not.toContain('onerror="');
});
});

View File

@@ -21,21 +21,48 @@ function escapeHtml(text: string): string {
.replace(/"/g, '&quot;');
}
/** Inline rules (bold/italic/code/safe links) over ALREADY-ESCAPED text. */
function applyInline(escaped: string): string {
/** Non-code inline rules over ALREADY-ESCAPED text. */
function applyStyledText(escaped: string, protectedHrefToken = ''): string {
return escaped
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>')
.replace(/`(.+?)`/g, '<code class="px-1 py-0.5 rounded bg-muted text-xs font-mono">$1</code>')
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label: string, url: string) => {
const u = String(url).trim();
const safe = /^https?:\/\//i.test(u) || u.startsWith('/') || u.startsWith('#');
const safeScheme = /^https?:\/\//i.test(u) || u.startsWith('/') || u.startsWith('#');
// A protected inline-code token is valid in link text, but never in an
// href: restoring a <code> tag inside an attribute would be unsafe.
const safe = safeScheme && (!protectedHrefToken || !u.includes(protectedHrefToken));
return safe
? `<a href="${u}" class="text-honey underline" target="_blank" rel="noopener noreferrer">${label}</a>`
: `${label} (${u})`;
});
}
/** Inline rules over ALREADY-ESCAPED text, with code isolated first. */
function applyInline(escaped: string): string {
let placeholderPrefix = '\uE000WAGGLE_CODE_';
while (escaped.includes(placeholderPrefix)) placeholderPrefix = `\uE000${placeholderPrefix}`;
const codeSegments: string[] = [];
const codePattern = /`([^`\n]+)`/g;
const protectedText = escaped.replace(codePattern, (_match, code: string) => {
const index = codeSegments.push(code) - 1;
return `${placeholderPrefix}${index}\uE001`;
});
let rendered = applyStyledText(protectedText, placeholderPrefix);
for (let index = 0; index < codeSegments.length; index++) {
const token = `${placeholderPrefix}${index}\uE001`;
const code = `<code class="px-1 py-0.5 rounded bg-muted text-xs font-mono">${codeSegments[index]}</code>`;
rendered = rendered.split(token).join(code);
}
return rendered;
}
function renderCodeBlock(lines: string[], language: string): string {
const languageAttribute = language ? ` data-language="${language}"` : '';
return `<pre class="my-2 max-w-full overflow-x-auto rounded-lg bg-muted p-3 text-xs leading-relaxed"><code class="font-mono whitespace-pre"${languageAttribute}>${lines.join('\n')}</code></pre>`;
}
export function renderSimpleMarkdown(text: string): string {
return applyInline(escapeHtml(text)).replace(/\n/g, '<br />');
}
@@ -51,7 +78,25 @@ export function renderSimpleMarkdown(text: string): string {
export function renderChatMarkdown(text: string): string {
const lines = escapeHtml(text).split('\n');
const out: string[] = [];
let fence: { language: string; lines: string[] } | null = null;
for (const line of lines) {
if (fence) {
if (/^\s*```\s*$/.test(line)) {
out.push(renderCodeBlock(fence.lines, fence.language));
fence = null;
} else {
fence.lines.push(line);
}
continue;
}
const fenceStart = /^\s*```\s*([A-Za-z0-9_+-]*)\s*$/.exec(line);
if (fenceStart) {
fence = { language: fenceStart[1], lines: [] };
continue;
}
const h3 = /^###\s+(.*)$/.exec(line);
const h2 = /^##\s+(.*)$/.exec(line);
const h1 = /^#\s+(.*)$/.exec(line);
@@ -75,5 +120,10 @@ export function renderChatMarkdown(text: string): string {
out.push(`<span class="block">${applyInline(line)}</span>`);
}
}
// During streaming, an opening fence may arrive before its closing marker.
// Render the partial body as code now; the next full-source render will close it.
if (fence) out.push(renderCodeBlock(fence.lines, fence.language));
return out.join('');
}

View File

@@ -31,6 +31,8 @@ import {
isFirstLaunch,
markFirstLaunchComplete,
resetFirstLaunch,
ensureDesktopService,
listenDesktopServiceLifecycle,
} from './tauri-bindings';
const mockedInvoke = vi.mocked(invoke);
@@ -51,6 +53,102 @@ describe('isTauri() runtime detection', () => {
});
});
describe('managed desktop service bindings', () => {
beforeEach(() => {
mockedInvoke.mockReset();
mockedListen.mockReset();
(window as unknown as { __TAURI_INTERNALS__: unknown }).__TAURI_INTERNALS__ = {};
});
afterEach(() => {
delete (window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
});
it('returns the exact validated endpoint from ensure_service', async () => {
mockedInvoke.mockResolvedValue({ port: 49151, instanceId: 'desktop-instance-a' });
await expect(ensureDesktopService()).resolves.toEqual({
port: 49151,
instanceId: 'desktop-instance-a',
});
expect(mockedInvoke).toHaveBeenCalledWith('ensure_service');
});
it.each([
[{ port: 0, instanceId: 'desktop-instance-a' }],
[{ port: 65536, instanceId: 'desktop-instance-a' }],
[{ port: 49151.5, instanceId: 'desktop-instance-a' }],
[{ port: 49151, instanceId: ' ' }],
[{ port: 49151 }],
])('rejects malformed ensure_service endpoint %#', async (endpoint) => {
mockedInvoke.mockResolvedValue(endpoint);
await expect(ensureDesktopService()).rejects.toThrow(/invalid desktop service endpoint/);
});
it('deduplicates paired restart signals, resets on ready, rejects malformed ready, and disposes both listeners', async () => {
const handlers = new Map<string, (event: { payload: unknown }) => void>();
const unlisteners = [vi.fn(), vi.fn()];
mockedListen.mockImplementation(async (eventName, eventHandler) => {
handlers.set(String(eventName), eventHandler as (event: { payload: unknown }) => void);
return unlisteners[handlers.size - 1];
});
const onEvent = vi.fn();
const dispose = await listenDesktopServiceLifecycle(onEvent);
expect([...handlers.keys()]).toEqual([
'waggle://service-status',
'waggle://service-restart-needed',
]);
handlers.get('waggle://service-restart-needed')?.({ payload: undefined });
handlers.get('waggle://service-status')?.({ payload: { status: 'restarting' } });
expect(onEvent).toHaveBeenCalledTimes(1);
expect(onEvent).toHaveBeenLastCalledWith({ status: 'restarting' });
handlers.get('waggle://service-status')?.({
payload: {
status: 'ready',
endpoint: { port: 49151, instanceId: 'desktop-instance-a' },
},
});
expect(onEvent).toHaveBeenLastCalledWith({
status: 'ready',
endpoint: { port: 49151, instanceId: 'desktop-instance-a' },
});
handlers.get('waggle://service-restart-needed')?.({ payload: undefined });
expect(onEvent).toHaveBeenLastCalledWith({ status: 'restarting' });
expect(onEvent).toHaveBeenCalledTimes(3);
handlers.get('waggle://service-status')?.({
payload: { status: 'ready', endpoint: { port: 0, instanceId: '' } },
});
expect(onEvent).toHaveBeenLastCalledWith({
status: 'failed',
error: 'Tauri emitted an invalid desktop service endpoint',
});
dispose();
expect(unlisteners[0]).toHaveBeenCalledOnce();
expect(unlisteners[1]).toHaveBeenCalledOnce();
});
it.each([
'waggle://service-status',
'waggle://service-restart-needed',
] as const)('disposes the surviving listener when %s registration fails', async (failedEvent) => {
const registrationError = new Error(`${failedEvent} registration failed`);
const survivingUnlisten = vi.fn();
mockedListen.mockImplementation(async (eventName) => {
if (eventName === failedEvent) throw registrationError;
return survivingUnlisten;
});
await expect(listenDesktopServiceLifecycle(vi.fn())).rejects.toBe(registrationError);
expect(survivingUnlisten).toHaveBeenCalledOnce();
});
});
describe('desktop shell event bindings', () => {
beforeEach(() => {
mockedListen.mockReset();
@@ -132,6 +230,20 @@ describe('desktop shell event bindings', () => {
expect(unlisten).toHaveBeenCalled();
}
});
it('disposes fulfilled listeners when a sibling shell registration rejects', async () => {
const firstUnlisten = vi.fn();
const thirdUnlisten = vi.fn();
const registrationError = new Error('shell listener registration failed');
mockedListen
.mockResolvedValueOnce(firstUnlisten)
.mockRejectedValueOnce(registrationError)
.mockResolvedValueOnce(thirdUnlisten);
await expect(listenDesktopShellEvents(vi.fn())).rejects.toBe(registrationError);
expect(firstUnlisten).toHaveBeenCalledOnce();
expect(thirdUnlisten).toHaveBeenCalledOnce();
});
});
describe('memory + identity bindings', () => {

View File

@@ -313,6 +313,90 @@ export function resetFirstLaunch(): Promise<void> {
// Desktop shell events
export interface DesktopServiceEndpoint {
port: number;
instanceId: string;
/** Per-launch secret delivered only through Tauri IPC. */
bootstrapToken?: string;
}
export type DesktopServiceLifecycleEvent =
| { status: 'restarting' }
| { status: 'ready'; endpoint: DesktopServiceEndpoint }
| { status: 'failed'; error?: string };
function parseDesktopServiceEndpoint(value: unknown): DesktopServiceEndpoint | null {
const record = recordPayload(value);
const port = record?.port;
const instanceId = record?.instanceId;
const bootstrapToken = record?.bootstrapToken;
return Number.isInteger(port) && (port as number) > 0 && (port as number) <= 65535
&& typeof instanceId === 'string' && instanceId.trim().length > 0
? {
port: port as number,
instanceId,
...(typeof bootstrapToken === 'string'
&& bootstrapToken.length >= 32
&& bootstrapToken.length <= 200
? { bootstrapToken }
: {}),
}
: null;
}
export async function ensureDesktopService(): Promise<DesktopServiceEndpoint> {
if (!isTauri()) throw new Error('Desktop service IPC is unavailable outside Tauri');
const endpoint = parseDesktopServiceEndpoint(await invoke<unknown>('ensure_service'));
if (!endpoint) throw new Error('Tauri returned an invalid desktop service endpoint');
return endpoint;
}
export async function listenDesktopServiceLifecycle(
onEvent: (event: DesktopServiceLifecycleEvent) => void,
): Promise<UnlistenFn> {
let restartPending = false;
const emitRestarting = () => {
if (restartPending) return;
restartPending = true;
onEvent({ status: 'restarting' });
};
const statusListener = listen<unknown>('waggle://service-status', (event) => {
const payload = recordPayload(event.payload);
if (payload?.status === 'restarting') {
emitRestarting();
} else if (payload?.status === 'failed') {
restartPending = false;
onEvent({ status: 'failed' });
} else if (payload?.status === 'ready') {
restartPending = false;
const endpoint = parseDesktopServiceEndpoint(payload.endpoint);
onEvent(endpoint
? { status: 'ready', endpoint }
: { status: 'failed', error: 'Tauri emitted an invalid desktop service endpoint' });
}
});
const restartListener = listen<unknown>('waggle://service-restart-needed', () => {
emitRestarting();
});
const [statusResult, restartResult] = await Promise.allSettled([
statusListener,
restartListener,
]);
if (statusResult.status === 'rejected') {
if (restartResult.status === 'fulfilled') restartResult.value();
throw statusResult.reason;
}
if (restartResult.status === 'rejected') {
statusResult.value();
throw restartResult.reason;
}
return () => {
statusResult.value();
restartResult.value();
};
}
export type DesktopNavigationPath = '/settings';
const DESKTOP_NAVIGATION_PATHS = new Set<DesktopNavigationPath>(['/settings']);
@@ -402,7 +486,7 @@ export function describeDesktopShellNotice(
export async function listenDesktopShellEvents(
onNotice: (notice: DesktopShellNotice) => void,
): Promise<UnlistenFn> {
const unlisteners = await Promise.all(
const listenerResults = await Promise.allSettled(
DESKTOP_SHELL_EVENTS.map((eventName) =>
listen<unknown>(eventName, (event) => {
const notice = describeDesktopShellNotice(eventName, event.payload);
@@ -412,6 +496,21 @@ export async function listenDesktopShellEvents(
}),
),
);
const unlisteners: UnlistenFn[] = [];
let registrationError: PromiseRejectedResult | undefined;
for (const result of listenerResults) {
if (result.status === 'fulfilled') {
unlisteners.push(result.value);
} else if (!registrationError) {
registrationError = result;
}
}
if (registrationError) {
for (const unlisten of unlisteners) {
unlisten();
}
throw registrationError.reason;
}
return () => {
for (const unlisten of unlisteners) {

View File

@@ -435,6 +435,8 @@ export interface ChatMessage {
feedback?: 'up' | 'down' | null;
pinned?: boolean;
persona?: string;
/** The model that actually produced this turn, as reported by the server. */
model?: string;
/**
* Lane C (Pillar 2.2/2.5): an optimistic user turn that was typed+sent while a
* previous reply was still streaming. It renders immediately with a truthful
@@ -442,6 +444,18 @@ export interface ChatMessage {
* never errors, never drops. Cleared to `false`/absent once dispatched.
*/
queued?: boolean;
/**
* Non-authoritative streaming preview. Draft text is display-only: it must
* never feed copy/pin/feedback, conversation context, or the settled cache.
* `done.content` is authoritative; legacy token streams that omit it settle
* from their accumulated token preview for backward compatibility.
*/
draft?: {
turnId: string;
revision: number;
content: string;
status: 'streaming' | 'stopped';
};
}
export interface ToolExecution {
@@ -724,7 +738,7 @@ export interface SystemHealth {
// `@waggle/shared` instead (richer status union incl. 'expired', category, authType).
export interface StreamEvent {
type: 'token' | 'step' | 'tool_start' | 'tool_end' | 'done' | 'error' | 'approval_request' | 'approval_required' | 'model_switch' | 'notification';
type: 'token' | 'draft_update' | 'step' | 'tool_start' | 'tool_end' | 'done' | 'error' | 'approval_request' | 'approval_required' | 'model_switch' | 'notification';
data: unknown;
}