style: 完成所有文件的lint

This commit is contained in:
claude-code-best
2026-05-01 21:39:30 +08:00
parent d136872cc9
commit 6182015005
1333 changed files with 68255 additions and 77882 deletions

View File

@@ -1,30 +1,34 @@
import { useState, useEffect, useCallback, lazy, Suspense } from "react";
import { Navbar } from "./components/Navbar";
import { IdentityPanel } from "./components/IdentityPanel";
import { TokenManagerDialog } from "./components/TokenManagerDialog";
import { ThemeProvider } from "./lib/theme";
import { getUuid, setUuid, apiBind, setActiveApiToken } from "./api/client";
import { ACPDirectView } from "./components/ACPDirectView";
import { useTokens } from "./hooks/useTokens";
import { useState, useEffect, useCallback, lazy, Suspense } from 'react';
import { Navbar } from './components/Navbar';
import { IdentityPanel } from './components/IdentityPanel';
import { TokenManagerDialog } from './components/TokenManagerDialog';
import { ThemeProvider } from './lib/theme';
import { getUuid, setUuid, apiBind, setActiveApiToken } from './api/client';
import { ACPDirectView } from './components/ACPDirectView';
import { useTokens } from './hooks/useTokens';
const Dashboard = lazy(() => import("./pages/Dashboard").then((m) => ({ default: m.Dashboard })));
const SessionDetail = lazy(() => import("./pages/SessionDetail").then((m) => ({ default: m.SessionDetail })));
const Dashboard = lazy(() => import('./pages/Dashboard').then(m => ({ default: m.Dashboard })));
const SessionDetail = lazy(() => import('./pages/SessionDetail').then(m => ({ default: m.SessionDetail })));
export default function App() {
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
const [identityOpen, setIdentityOpen] = useState(false);
const [tokenDialogOpen, setTokenDialogOpen] = useState(false);
const [acpDirect, setAcpDirect] = useState<{ url: string; token: string } | null>(null);
const { tokens, activeTokenId, activeLabel, activeTokenValue, setActiveTokenId, addToken, removeToken, updateToken } = useTokens();
const { tokens, activeTokenId, activeLabel, activeTokenValue, setActiveTokenId, addToken, removeToken, updateToken } =
useTokens();
// Sync active token to API client
useEffect(() => {
setActiveApiToken(activeTokenValue);
}, [activeTokenValue]);
const handleSetActiveToken = useCallback((id: string) => {
setActiveTokenId(id);
}, [setActiveTokenId]);
const handleSetActiveToken = useCallback(
(id: string) => {
setActiveTokenId(id);
},
[setActiveTokenId],
);
// Simple hash-based router
const parseRoute = useCallback(() => {
@@ -35,46 +39,46 @@ export default function App() {
// Check for UUID import from QR scan (?uuid=xxx)
const params = new URLSearchParams(window.location.search);
const importUuid = params.get("uuid");
const importUuid = params.get('uuid');
if (importUuid) {
setUuid(importUuid);
const url = new URL(window.location.href);
url.searchParams.delete("uuid");
window.history.replaceState(null, "", url);
url.searchParams.delete('uuid');
window.history.replaceState(null, '', url);
}
// Check for ACP direct connection (?acp=1)
const acpParam = params.get("acp");
if (acpParam === "1") {
const stored = sessionStorage.getItem("acp_connection");
const acpParam = params.get('acp');
if (acpParam === '1') {
const stored = sessionStorage.getItem('acp_connection');
if (stored) {
try {
const acpData = JSON.parse(stored);
if (acpData.url && acpData.token) {
setAcpDirect({ url: acpData.url, token: acpData.token });
sessionStorage.removeItem("acp_connection");
sessionStorage.removeItem('acp_connection');
// Clean URL
const url = new URL(window.location.href);
url.searchParams.delete("acp");
window.history.replaceState(null, "", url);
url.searchParams.delete('acp');
window.history.replaceState(null, '', url);
return;
}
} catch {
sessionStorage.removeItem("acp_connection");
sessionStorage.removeItem('acp_connection');
}
}
}
// Check for CLI session bind (?sid=xxx) — bind session to current UUID
const sid = params.get("sid");
const sid = params.get('sid');
if (sid) {
const url = new URL(window.location.href);
url.searchParams.delete("sid");
window.history.replaceState(null, "", `/code/${sid}`);
url.searchParams.delete('sid');
window.history.replaceState(null, '', `/code/${sid}`);
setCurrentSessionId(sid);
// Bind this session to the current user's UUID for ownership
apiBind(sid).catch((err: unknown) => {
console.warn("Failed to bind session:", err);
console.warn('Failed to bind session:', err);
});
return;
}
@@ -90,17 +94,17 @@ export default function App() {
useEffect(() => {
parseRoute();
window.addEventListener("popstate", parseRoute);
return () => window.removeEventListener("popstate", parseRoute);
window.addEventListener('popstate', parseRoute);
return () => window.removeEventListener('popstate', parseRoute);
}, [parseRoute]);
const navigateToSession = useCallback((sessionId: string) => {
window.history.pushState(null, "", `/code/${sessionId}`);
window.history.pushState(null, '', `/code/${sessionId}`);
setCurrentSessionId(sessionId);
}, []);
const navigateToDashboard = useCallback(() => {
window.history.pushState(null, "", "/code/");
window.history.pushState(null, '', '/code/');
setCurrentSessionId(null);
setAcpDirect(null);
}, []);
@@ -112,8 +116,8 @@ export default function App() {
onIdentityClick={() => setIdentityOpen(true)}
onTokenClick={() => setTokenDialogOpen(true)}
activeTokenLabel={currentSessionId ? undefined : activeLabel}
sessionTitle={currentSessionId || (acpDirect ? "ACP" : undefined)}
onBack={(currentSessionId || acpDirect) ? navigateToDashboard : undefined}
sessionTitle={currentSessionId || (acpDirect ? 'ACP' : undefined)}
onBack={currentSessionId || acpDirect ? navigateToDashboard : undefined}
/>
<Suspense fallback={<div className="flex flex-1 items-center justify-center text-text-muted">Loading...</div>}>

View File

@@ -1,172 +1,192 @@
import { describe, test, expect, mock, beforeEach } from "bun:test";
import { describe, test, expect, mock, beforeEach } from 'bun:test'
// In-memory localStorage mock
let store: Record<string, string> = {};
let store: Record<string, string> = {}
beforeEach(() => {
store = {};
(globalThis as any).localStorage = {
store = {}
;(globalThis as any).localStorage = {
getItem: (k: string) => store[k] ?? null,
setItem: (k: string, v: string) => { store[k] = v; },
removeItem: (k: string) => { delete store[k]; },
clear: () => { store = {}; },
get length() { return Object.keys(store).length; },
setItem: (k: string, v: string) => {
store[k] = v
},
removeItem: (k: string) => {
delete store[k]
},
clear: () => {
store = {}
},
get length() {
return Object.keys(store).length
},
key: () => null,
};
});
}
})
// Mock fetch
const fetchMock = {
lastUrl: "",
lastUrl: '',
lastOpts: {} as RequestInit,
response: { ok: true, status: 200, statusText: "OK" },
response: { ok: true, status: 200, statusText: 'OK' },
responseData: {} as any,
};
}
beforeEach(() => {
fetchMock.lastUrl = "";
fetchMock.lastOpts = {};
fetchMock.response = { ok: true, status: 200, statusText: "OK" };
fetchMock.responseData = {};
client.setActiveApiToken(null);
});
fetchMock.lastUrl = ''
fetchMock.lastOpts = {}
fetchMock.response = { ok: true, status: 200, statusText: 'OK' }
fetchMock.responseData = {}
client.setActiveApiToken(null)
})
(globalThis as any).fetch = async (url: string, opts: RequestInit) => {
fetchMock.lastUrl = url;
fetchMock.lastOpts = opts;
;(globalThis as any).fetch = async (url: string, opts: RequestInit) => {
fetchMock.lastUrl = url
fetchMock.lastOpts = opts
return {
ok: fetchMock.response.ok,
status: fetchMock.response.status,
statusText: fetchMock.response.statusText,
json: async () => fetchMock.responseData,
} as Response;
};
} as Response
}
const { getUuid, setUuid } = await import("../api/client");
const { getUuid, setUuid } = await import('../api/client')
// Import api* functions - they depend on getUuid and fetch
const client = await import("../api/client");
const relayClient = await import("../acp/relay-client");
const client = await import('../api/client')
const relayClient = await import('../acp/relay-client')
// =============================================================================
// getUuid()
// =============================================================================
describe("getUuid", () => {
test("returns existing UUID from localStorage", () => {
store["rcs_uuid"] = "existing-uuid";
expect(getUuid()).toBe("existing-uuid");
});
describe('getUuid', () => {
test('returns existing UUID from localStorage', () => {
store['rcs_uuid'] = 'existing-uuid'
expect(getUuid()).toBe('existing-uuid')
})
test("generates and stores new UUID when none exists", () => {
const uuid = getUuid();
test('generates and stores new UUID when none exists', () => {
const uuid = getUuid()
expect(uuid).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
expect(store["rcs_uuid"]).toBe(uuid);
});
)
expect(store['rcs_uuid']).toBe(uuid)
})
test("returns same UUID on subsequent calls", () => {
const a = getUuid();
const b = getUuid();
expect(a).toBe(b);
});
});
test('returns same UUID on subsequent calls', () => {
const a = getUuid()
const b = getUuid()
expect(a).toBe(b)
})
})
// =============================================================================
// setUuid()
// =============================================================================
describe("setUuid", () => {
test("writes UUID to localStorage", () => {
setUuid("custom-uuid-999");
expect(store["rcs_uuid"]).toBe("custom-uuid-999");
});
describe('setUuid', () => {
test('writes UUID to localStorage', () => {
setUuid('custom-uuid-999')
expect(store['rcs_uuid']).toBe('custom-uuid-999')
})
test("getUuid returns the set UUID", () => {
setUuid("my-uuid");
expect(getUuid()).toBe("my-uuid");
});
});
test('getUuid returns the set UUID', () => {
setUuid('my-uuid')
expect(getUuid()).toBe('my-uuid')
})
})
// =============================================================================
// api() — tested via apiFetchSession (GET) and apiBind (POST)
// =============================================================================
describe("api functions", () => {
test("GET request appends uuid to URL", async () => {
store["rcs_uuid"] = "test-uuid";
fetchMock.responseData = [];
await client.apiFetchSessions();
expect(fetchMock.lastUrl).toContain("uuid=test-uuid");
expect(fetchMock.lastOpts.method).toBe("GET");
});
describe('api functions', () => {
test('GET request appends uuid to URL', async () => {
store['rcs_uuid'] = 'test-uuid'
fetchMock.responseData = []
await client.apiFetchSessions()
expect(fetchMock.lastUrl).toContain('uuid=test-uuid')
expect(fetchMock.lastOpts.method).toBe('GET')
})
test("GET request uses ? for URL without existing query params", async () => {
store["rcs_uuid"] = "test-uuid";
fetchMock.responseData = [];
await client.apiFetchSessions();
expect(fetchMock.lastUrl).toContain("?uuid=");
});
test('GET request uses ? for URL without existing query params', async () => {
store['rcs_uuid'] = 'test-uuid'
fetchMock.responseData = []
await client.apiFetchSessions()
expect(fetchMock.lastUrl).toContain('?uuid=')
})
test("GET request uses & for URL with existing query params", async () => {
store["rcs_uuid"] = "test-uuid";
fetchMock.responseData = [];
await client.apiFetchAllSessions();
test('GET request uses & for URL with existing query params', async () => {
store['rcs_uuid'] = 'test-uuid'
fetchMock.responseData = []
await client.apiFetchAllSessions()
// apiFetchAllSessions calls GET /web/sessions/all
expect(fetchMock.lastUrl).toContain("?uuid=");
});
expect(fetchMock.lastUrl).toContain('?uuid=')
})
test("POST request includes JSON body", async () => {
store["rcs_uuid"] = "test-uuid";
fetchMock.responseData = {};
await client.apiBind("sess-1");
expect(fetchMock.lastOpts.method).toBe("POST");
expect(fetchMock.lastOpts.body).toBe(JSON.stringify({ sessionId: "sess-1" }));
expect(fetchMock.lastOpts.headers).toEqual({ "Content-Type": "application/json" });
});
test("active API token is sent only in Authorization header", async () => {
store["rcs_uuid"] = "browser-uuid";
fetchMock.responseData = [];
client.setActiveApiToken("secret-token");
await client.apiFetchSessions();
expect(fetchMock.lastUrl).toContain("uuid=browser-uuid");
expect(fetchMock.lastUrl).not.toContain("secret-token");
test('POST request includes JSON body', async () => {
store['rcs_uuid'] = 'test-uuid'
fetchMock.responseData = {}
await client.apiBind('sess-1')
expect(fetchMock.lastOpts.method).toBe('POST')
expect(fetchMock.lastOpts.body).toBe(
JSON.stringify({ sessionId: 'sess-1' }),
)
expect(fetchMock.lastOpts.headers).toEqual({
"Content-Type": "application/json",
Authorization: "Bearer secret-token",
});
});
'Content-Type': 'application/json',
})
})
test("throws error on non-ok response", async () => {
store["rcs_uuid"] = "test-uuid";
fetchMock.response = { ok: false, status: 401, statusText: "Unauthorized" };
fetchMock.responseData = { error: { type: "auth", message: "Invalid UUID" } };
await expect(client.apiFetchSessions()).rejects.toThrow("Invalid UUID");
});
test('active API token is sent only in Authorization header', async () => {
store['rcs_uuid'] = 'browser-uuid'
fetchMock.responseData = []
client.setActiveApiToken('secret-token')
test("throws with statusText when error message is missing", async () => {
store["rcs_uuid"] = "test-uuid";
fetchMock.response = { ok: false, status: 500, statusText: "Internal Server Error" };
fetchMock.responseData = {};
await expect(client.apiFetchSessions()).rejects.toThrow("Internal Server Error");
});
});
await client.apiFetchSessions()
describe("ACP relay client", () => {
test("builds relay URLs without UUID or token query params", () => {
(globalThis as any).window = {
expect(fetchMock.lastUrl).toContain('uuid=browser-uuid')
expect(fetchMock.lastUrl).not.toContain('secret-token')
expect(fetchMock.lastOpts.headers).toEqual({
'Content-Type': 'application/json',
Authorization: 'Bearer secret-token',
})
})
test('throws error on non-ok response', async () => {
store['rcs_uuid'] = 'test-uuid'
fetchMock.response = { ok: false, status: 401, statusText: 'Unauthorized' }
fetchMock.responseData = {
error: { type: 'auth', message: 'Invalid UUID' },
}
await expect(client.apiFetchSessions()).rejects.toThrow('Invalid UUID')
})
test('throws with statusText when error message is missing', async () => {
store['rcs_uuid'] = 'test-uuid'
fetchMock.response = {
ok: false,
status: 500,
statusText: 'Internal Server Error',
}
fetchMock.responseData = {}
await expect(client.apiFetchSessions()).rejects.toThrow(
'Internal Server Error',
)
})
})
describe('ACP relay client', () => {
test('builds relay URLs without UUID or token query params', () => {
;(globalThis as any).window = {
location: {
protocol: "https:",
host: "rcs.example.test",
protocol: 'https:',
host: 'rcs.example.test',
},
};
}
expect(relayClient.buildRelayUrl("agent_123")).toBe(
"wss://rcs.example.test/acp/relay/agent_123",
);
});
});
expect(relayClient.buildRelayUrl('agent_123')).toBe(
'wss://rcs.example.test/acp/relay/agent_123',
)
})
})

View File

@@ -1,4 +1,4 @@
import { afterEach, describe, test, expect } from "bun:test";
import { afterEach, describe, test, expect } from 'bun:test'
const {
formatTime,
@@ -8,273 +8,284 @@ const {
generateMessageUuid,
extractEventText,
isConversationClearedStatus,
} = await import("../lib/utils");
} = await import('../lib/utils')
type UuidCrypto = {
randomUUID?: () => string;
getRandomValues?: (array: Uint8Array) => Uint8Array;
};
randomUUID?: () => string
getRandomValues?: (array: Uint8Array) => Uint8Array
}
const originalCryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto");
const originalCryptoDescriptor = Object.getOwnPropertyDescriptor(
globalThis,
'crypto',
)
function setCryptoForTest(value: UuidCrypto): void {
Object.defineProperty(globalThis, "crypto", {
Object.defineProperty(globalThis, 'crypto', {
configurable: true,
writable: true,
value,
});
})
}
function restoreCryptoForTest(): void {
if (originalCryptoDescriptor) {
Object.defineProperty(globalThis, "crypto", originalCryptoDescriptor);
Object.defineProperty(globalThis, 'crypto', originalCryptoDescriptor)
} else {
Reflect.deleteProperty(globalThis, "crypto");
Reflect.deleteProperty(globalThis, 'crypto')
}
}
afterEach(() => {
restoreCryptoForTest();
});
restoreCryptoForTest()
})
// =============================================================================
// formatTime()
// =============================================================================
describe("formatTime", () => {
test("returns empty string for null", () => {
expect(formatTime(null)).toBe("");
});
describe('formatTime', () => {
test('returns empty string for null', () => {
expect(formatTime(null)).toBe('')
})
test("returns empty string for undefined", () => {
expect(formatTime(undefined)).toBe("");
});
test('returns empty string for undefined', () => {
expect(formatTime(undefined)).toBe('')
})
test("returns empty string for 0", () => {
expect(formatTime(0)).toBe("");
});
test('returns empty string for 0', () => {
expect(formatTime(0)).toBe('')
})
test("formats valid unix timestamp", () => {
const result = formatTime(1700000000);
expect(result).toContain("2023");
});
});
test('formats valid unix timestamp', () => {
const result = formatTime(1700000000)
expect(result).toContain('2023')
})
})
// =============================================================================
// statusClass()
// =============================================================================
describe("statusClass", () => {
test("maps known statuses correctly", () => {
expect(statusClass("active")).toBe("active");
expect(statusClass("running")).toBe("running");
expect(statusClass("idle")).toBe("idle");
expect(statusClass("inactive")).toBe("inactive");
expect(statusClass("requires_action")).toBe("requires_action");
expect(statusClass("archived")).toBe("archived");
expect(statusClass("error")).toBe("error");
});
describe('statusClass', () => {
test('maps known statuses correctly', () => {
expect(statusClass('active')).toBe('active')
expect(statusClass('running')).toBe('running')
expect(statusClass('idle')).toBe('idle')
expect(statusClass('inactive')).toBe('inactive')
expect(statusClass('requires_action')).toBe('requires_action')
expect(statusClass('archived')).toBe('archived')
expect(statusClass('error')).toBe('error')
})
test("returns default for unknown status", () => {
expect(statusClass("unknown")).toBe("default");
});
test('returns default for unknown status', () => {
expect(statusClass('unknown')).toBe('default')
})
test("returns default for null", () => {
expect(statusClass(null)).toBe("default");
});
test('returns default for null', () => {
expect(statusClass(null)).toBe('default')
})
test("returns default for undefined", () => {
expect(statusClass(undefined)).toBe("default");
});
test('returns default for undefined', () => {
expect(statusClass(undefined)).toBe('default')
})
test("returns default for empty string", () => {
expect(statusClass("")).toBe("default");
});
});
test('returns default for empty string', () => {
expect(statusClass('')).toBe('default')
})
})
// =============================================================================
// isClosedSessionStatus()
// =============================================================================
describe("isClosedSessionStatus", () => {
test("returns true for archived", () => {
expect(isClosedSessionStatus("archived")).toBe(true);
});
describe('isClosedSessionStatus', () => {
test('returns true for archived', () => {
expect(isClosedSessionStatus('archived')).toBe(true)
})
test("returns true for inactive", () => {
expect(isClosedSessionStatus("inactive")).toBe(true);
});
test('returns true for inactive', () => {
expect(isClosedSessionStatus('inactive')).toBe(true)
})
test("returns false for active", () => {
expect(isClosedSessionStatus("active")).toBe(false);
});
test('returns false for active', () => {
expect(isClosedSessionStatus('active')).toBe(false)
})
test("returns false for null", () => {
expect(isClosedSessionStatus(null)).toBe(false);
});
test('returns false for null', () => {
expect(isClosedSessionStatus(null)).toBe(false)
})
test("returns false for undefined", () => {
expect(isClosedSessionStatus(undefined)).toBe(false);
});
});
test('returns false for undefined', () => {
expect(isClosedSessionStatus(undefined)).toBe(false)
})
})
// =============================================================================
// truncate()
// =============================================================================
describe("truncate", () => {
test("returns empty string for null", () => {
expect(truncate(null, 10)).toBe("");
});
describe('truncate', () => {
test('returns empty string for null', () => {
expect(truncate(null, 10)).toBe('')
})
test("returns empty string for undefined", () => {
expect(truncate(undefined, 10)).toBe("");
});
test('returns empty string for undefined', () => {
expect(truncate(undefined, 10)).toBe('')
})
test("returns original string when shorter than max", () => {
expect(truncate("hello", 10)).toBe("hello");
});
test('returns original string when shorter than max', () => {
expect(truncate('hello', 10)).toBe('hello')
})
test("returns original string when exactly max length", () => {
expect(truncate("12345", 5)).toBe("12345");
});
test('returns original string when exactly max length', () => {
expect(truncate('12345', 5)).toBe('12345')
})
test("truncates and appends ... when longer than max", () => {
expect(truncate("hello world", 5)).toBe("hello...");
});
});
test('truncates and appends ... when longer than max', () => {
expect(truncate('hello world', 5)).toBe('hello...')
})
})
// =============================================================================
// generateMessageUuid()
// =============================================================================
describe("generateMessageUuid", () => {
test("returns an RFC 4122 v4 UUID", () => {
const uuid = generateMessageUuid();
expect(typeof uuid).toBe("string");
describe('generateMessageUuid', () => {
test('returns an RFC 4122 v4 UUID', () => {
const uuid = generateMessageUuid()
expect(typeof uuid).toBe('string')
expect(uuid).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
});
)
})
test("uses crypto.randomUUID when available", () => {
test('uses crypto.randomUUID when available', () => {
setCryptoForTest({
randomUUID: () => "11111111-1111-4111-8111-111111111111",
randomUUID: () => '11111111-1111-4111-8111-111111111111',
getRandomValues: () => {
throw new Error("getRandomValues should not be called");
throw new Error('getRandomValues should not be called')
},
});
})
expect(generateMessageUuid()).toBe("11111111-1111-4111-8111-111111111111");
});
expect(generateMessageUuid()).toBe('11111111-1111-4111-8111-111111111111')
})
test("uses crypto.getRandomValues when randomUUID is unavailable", () => {
test('uses crypto.getRandomValues when randomUUID is unavailable', () => {
setCryptoForTest({
getRandomValues: (array) => {
getRandomValues: array => {
for (let i = 0; i < array.length; i++) {
array[i] = i;
array[i] = i
}
return array;
return array
},
});
})
expect(generateMessageUuid()).toBe("00010203-0405-4607-8809-0a0b0c0d0e0f");
});
expect(generateMessageUuid()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f')
})
test("throws when no secure random source is available", () => {
setCryptoForTest({});
test('throws when no secure random source is available', () => {
setCryptoForTest({})
expect(() => generateMessageUuid()).toThrow("crypto.getRandomValues is required");
});
});
expect(() => generateMessageUuid()).toThrow(
'crypto.getRandomValues is required',
)
})
})
// =============================================================================
// extractEventText()
// =============================================================================
describe("extractEventText", () => {
test("returns empty string for null", () => {
expect(extractEventText(null)).toBe("");
});
describe('extractEventText', () => {
test('returns empty string for null', () => {
expect(extractEventText(null)).toBe('')
})
test("returns empty string for undefined", () => {
expect(extractEventText(undefined)).toBe("");
});
test('returns empty string for undefined', () => {
expect(extractEventText(undefined)).toBe('')
})
test("returns empty string for non-object", () => {
expect(extractEventText("string" as any)).toBe("");
});
test('returns empty string for non-object', () => {
expect(extractEventText('string' as any)).toBe('')
})
test("extracts payload.content string", () => {
expect(extractEventText({ content: "hello" })).toBe("hello");
});
test('extracts payload.content string', () => {
expect(extractEventText({ content: 'hello' })).toBe('hello')
})
test("extracts from message.content text blocks array", () => {
test('extracts from message.content text blocks array', () => {
const payload = {
message: {
content: [
{ type: "text", text: "line 1" },
{ type: "text", text: "line 2" },
{ type: 'text', text: 'line 1' },
{ type: 'text', text: 'line 2' },
],
},
};
expect(extractEventText(payload)).toBe("line 1\nline 2");
});
}
expect(extractEventText(payload)).toBe('line 1\nline 2')
})
test("ignores non-text blocks", () => {
test('ignores non-text blocks', () => {
const payload = {
message: {
content: [
{ type: "image", data: "base64..." },
{ type: "text", text: "only text" },
{ type: 'image', data: 'base64...' },
{ type: 'text', text: 'only text' },
],
},
};
expect(extractEventText(payload)).toBe("only text");
});
}
expect(extractEventText(payload)).toBe('only text')
})
test("returns empty string when message.content has no text blocks", () => {
test('returns empty string when message.content has no text blocks', () => {
const payload = {
message: { content: [{ type: "image", data: "base64" }] },
};
expect(extractEventText(payload)).toBe("");
});
message: { content: [{ type: 'image', data: 'base64' }] },
}
expect(extractEventText(payload)).toBe('')
})
test("returns empty string for empty object", () => {
expect(extractEventText({})).toBe("");
});
});
test('returns empty string for empty object', () => {
expect(extractEventText({})).toBe('')
})
})
// =============================================================================
// isConversationClearedStatus()
// =============================================================================
describe("isConversationClearedStatus", () => {
test("returns true when payload.status is conversation_cleared", () => {
expect(isConversationClearedStatus({ status: "conversation_cleared" })).toBe(true);
});
describe('isConversationClearedStatus', () => {
test('returns true when payload.status is conversation_cleared', () => {
expect(
isConversationClearedStatus({ status: 'conversation_cleared' }),
).toBe(true)
})
test("returns true when payload.raw.status is conversation_cleared", () => {
expect(isConversationClearedStatus({ raw: { status: "conversation_cleared" } })).toBe(true);
});
test('returns true when payload.raw.status is conversation_cleared', () => {
expect(
isConversationClearedStatus({ raw: { status: 'conversation_cleared' } }),
).toBe(true)
})
test("returns false for null", () => {
expect(isConversationClearedStatus(null)).toBe(false);
});
test('returns false for null', () => {
expect(isConversationClearedStatus(null)).toBe(false)
})
test("returns false for undefined", () => {
expect(isConversationClearedStatus(undefined)).toBe(false);
});
test('returns false for undefined', () => {
expect(isConversationClearedStatus(undefined)).toBe(false)
})
test("returns false for other status", () => {
expect(isConversationClearedStatus({ status: "active" })).toBe(false);
});
test('returns false for other status', () => {
expect(isConversationClearedStatus({ status: 'active' })).toBe(false)
})
test("returns false when raw has different status", () => {
expect(isConversationClearedStatus({ raw: { status: "running" } })).toBe(false);
});
test('returns false when raw has different status', () => {
expect(isConversationClearedStatus({ raw: { status: 'running' } })).toBe(
false,
)
})
test("returns false for empty object", () => {
expect(isConversationClearedStatus({})).toBe(false);
});
});
test('returns false for empty object', () => {
expect(isConversationClearedStatus({})).toBe(false)
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +1,2 @@
export * from "./types";
export * from "./client";
export * from './types'
export * from './client'

View File

@@ -1,14 +1,14 @@
import { ACPClient } from "./client";
import type { ACPSettings } from "./types";
import { getActiveApiToken } from "../api/client";
import { ACPClient } from './client'
import type { ACPSettings } from './types'
import { getActiveApiToken } from '../api/client'
/**
* Build the RCS relay WebSocket URL for a given agent.
* Uses UUID auth (same as /code/ pages).
*/
export function buildRelayUrl(agentId: string): string {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
return `${protocol}//${window.location.host}/acp/relay/${agentId}`;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
return `${protocol}//${window.location.host}/acp/relay/${agentId}`
}
/**
@@ -17,10 +17,10 @@ export function buildRelayUrl(agentId: string): string {
* the frontend and the target acp-link instance.
*/
export function createRelayClient(agentId: string): ACPClient {
const relayUrl = buildRelayUrl(agentId);
const token = getActiveApiToken();
const relayUrl = buildRelayUrl(agentId)
const token = getActiveApiToken()
const settings: ACPSettings = token
? { proxyUrl: relayUrl, token }
: { proxyUrl: relayUrl };
return new ACPClient(settings);
: { proxyUrl: relayUrl }
return new ACPClient(settings)
}

View File

@@ -1,33 +1,33 @@
// Permission option kinds (from ACP protocol)
export type PermissionOptionKind =
| "allow_once"
| "allow_always"
| "reject_once"
| "reject_always";
| 'allow_once'
| 'allow_always'
| 'reject_once'
| 'reject_always'
// Permission option (from ACP protocol)
export interface PermissionOption {
optionId: string;
name: string;
kind: PermissionOptionKind;
optionId: string
name: string
kind: PermissionOptionKind
}
// Permission request payload (sent from server to client)
export interface PermissionRequestPayload {
requestId: string; // Unique ID for this request (generated by server)
sessionId: string;
options: PermissionOption[];
requestId: string // Unique ID for this request (generated by server)
sessionId: string
options: PermissionOption[]
toolCall: {
toolCallId: string; // Tool call ID to match with existing tool calls
title?: string;
content?: ToolCallContent[];
};
toolCallId: string // Tool call ID to match with existing tool calls
title?: string
content?: ToolCallContent[]
}
}
// Permission response (sent from client to server)
export interface PermissionResponsePayload {
requestId: string;
outcome: { outcome: "cancelled" } | { outcome: "selected"; optionId: string };
requestId: string
outcome: { outcome: 'cancelled' } | { outcome: 'selected'; optionId: string }
}
// ============================================================================
@@ -38,129 +38,133 @@ export interface PermissionResponsePayload {
// ============================================================================
export interface BrowserToolParams {
action: "tabs" | "read" | "execute";
tabId?: number; // Required for read/execute
script?: string; // Required for execute
action: 'tabs' | 'read' | 'execute'
tabId?: number // Required for read/execute
script?: string // Required for execute
}
export interface BrowserTabInfo {
id: number;
url: string;
title: string;
active: boolean;
id: number
url: string
title: string
active: boolean
}
export interface BrowserTabsResult {
action: "tabs";
tabs: BrowserTabInfo[];
action: 'tabs'
tabs: BrowserTabInfo[]
}
export interface BrowserReadResult {
action: "read";
tabId: number;
url: string;
title: string;
dom: string;
action: 'read'
tabId: number
url: string
title: string
dom: string
viewport: {
width: number;
height: number;
scrollX: number;
scrollY: number;
};
selection: string | null;
width: number
height: number
scrollX: number
scrollY: number
}
selection: string | null
}
export interface BrowserExecuteResult {
action: "execute";
tabId: number;
url: string;
result?: unknown;
error?: string;
action: 'execute'
tabId: number
url: string
result?: unknown
error?: string
}
export type BrowserToolResult =
| BrowserTabsResult
| BrowserReadResult
| BrowserExecuteResult;
| BrowserExecuteResult
// Messages sent TO the proxy server
// Reference: Zed's MessageEditor.contents() builds Vec<acp::ContentBlock>
export type ProxyMessage =
| { type: "connect" }
| { type: "disconnect" }
| { type: "new_session"; payload?: { cwd?: string; permissionMode?: string } }
| { type: "prompt"; payload: { content: ContentBlock[] } } // Changed from { text: string } to match Zed
| { type: "cancel" }
| { type: "permission_response"; payload: PermissionResponsePayload }
| { type: "browser_tool_result"; callId: string; result: BrowserToolResult | { error: string } }
| { type: "set_session_model"; payload: { modelId: string } }
| { type: 'connect' }
| { type: 'disconnect' }
| { type: 'new_session'; payload?: { cwd?: string; permissionMode?: string } }
| { type: 'prompt'; payload: { content: ContentBlock[] } } // Changed from { text: string } to match Zed
| { type: 'cancel' }
| { type: 'permission_response'; payload: PermissionResponsePayload }
| {
type: 'browser_tool_result'
callId: string
result: BrowserToolResult | { error: string }
}
| { type: 'set_session_model'; payload: { modelId: string } }
// Session history operations - Reference: Zed's AgentSessionList trait
| { type: "list_sessions"; payload?: ListSessionsRequest }
| { type: "load_session"; payload: LoadSessionRequest }
| { type: "resume_session"; payload: ResumeSessionRequest }
| { type: 'list_sessions'; payload?: ListSessionsRequest }
| { type: 'load_session'; payload: LoadSessionRequest }
| { type: 'resume_session'; payload: ResumeSessionRequest }
// Heartbeat
| { type: "ping" };
| { type: 'ping' }
// Messages received FROM the proxy server
// Reference: Zed's AgentConnection stores agentCapabilities from initialize response
export interface ProxyStatusMessage {
type: "status";
type: 'status'
payload: {
connected: boolean;
agentInfo?: { name?: string; version?: string };
connected: boolean
agentInfo?: { name?: string; version?: string }
/** Full agent capabilities from initialize response */
capabilities?: AgentCapabilities;
};
capabilities?: AgentCapabilities
}
}
export interface ProxyErrorMessage {
type: "error";
payload: { message: string };
type: 'error'
payload: { message: string }
}
// Reference: Zed's session/initialize response includes promptCapabilities and models
export interface ProxySessionCreatedMessage {
type: "session_created";
type: 'session_created'
payload: {
sessionId: string;
promptCapabilities?: PromptCapabilities; // From agent's initialize response
models?: SessionModelState | null; // Model state if agent supports model selection
};
sessionId: string
promptCapabilities?: PromptCapabilities // From agent's initialize response
models?: SessionModelState | null // Model state if agent supports model selection
}
}
export interface ProxySessionUpdateMessage {
type: "session_update";
type: 'session_update'
payload: {
sessionId: string;
update: SessionUpdate;
};
sessionId: string
update: SessionUpdate
}
}
export interface ProxyPromptCompleteMessage {
type: "prompt_complete";
payload: { stopReason: string };
type: 'prompt_complete'
payload: { stopReason: string }
}
export interface ProxyPermissionRequestMessage {
type: "permission_request";
payload: PermissionRequestPayload;
type: 'permission_request'
payload: PermissionRequestPayload
}
export interface ProxyBrowserToolCallMessage {
type: "browser_tool_call";
callId: string;
params: BrowserToolParams;
type: 'browser_tool_call'
callId: string
params: BrowserToolParams
}
export interface ProxyPongMessage {
type: "pong";
type: 'pong'
}
export interface ProxyModelChangedMessage {
type: "model_changed";
type: 'model_changed'
payload: {
modelId: string;
};
modelId: string
}
}
// ============================================================================
@@ -173,8 +177,8 @@ export interface ProxyModelChangedMessage {
* Reference: Zed's AgentSessionListResponse
*/
export interface ProxySessionListMessage {
type: "session_list";
payload: ListSessionsResponse;
type: 'session_list'
payload: ListSessionsResponse
}
/**
@@ -182,12 +186,12 @@ export interface ProxySessionListMessage {
* Reference: Zed's load_session returns Entity<AcpThread>
*/
export interface ProxySessionLoadedMessage {
type: "session_loaded";
type: 'session_loaded'
payload: {
sessionId: string;
promptCapabilities?: PromptCapabilities;
models?: SessionModelState | null;
};
sessionId: string
promptCapabilities?: PromptCapabilities
models?: SessionModelState | null
}
}
/**
@@ -195,12 +199,12 @@ export interface ProxySessionLoadedMessage {
* Reference: Zed's resume_session returns Entity<AcpThread>
*/
export interface ProxySessionResumedMessage {
type: "session_resumed";
type: 'session_resumed'
payload: {
sessionId: string;
promptCapabilities?: PromptCapabilities;
models?: SessionModelState | null;
};
sessionId: string
promptCapabilities?: PromptCapabilities
models?: SessionModelState | null
}
}
export type ProxyResponse =
@@ -216,116 +220,123 @@ export type ProxyResponse =
// Session history responses
| ProxySessionListMessage
| ProxySessionLoadedMessage
| ProxySessionResumedMessage;
| ProxySessionResumedMessage
// Content block types (matches @agentclientprotocol/sdk ContentBlock)
// Reference: Zed's acp::ContentBlock in agent-client-protocol crate
export interface TextContent {
type: "text";
text: string;
type: 'text'
text: string
}
export interface ImageContent {
type: "image";
mimeType: string;
data: string; // base64 encoded image data
uri?: string; // optional URI for the image source
type: 'image'
mimeType: string
data: string // base64 encoded image data
uri?: string // optional URI for the image source
}
export interface ResourceLinkContent {
type: "resource_link";
uri: string;
name: string;
title?: string;
description?: string;
mimeType?: string;
size?: number;
type: 'resource_link'
uri: string
name: string
title?: string
description?: string
mimeType?: string
size?: number
}
export type ContentBlock = TextContent | ImageContent | ResourceLinkContent | { type: string; text?: string };
export type ContentBlock =
| TextContent
| ImageContent
| ResourceLinkContent
| { type: string; text?: string }
// Session update types from ACP
export interface AgentMessageChunkUpdate {
sessionUpdate: "agent_message_chunk";
content: ContentBlock;
sessionUpdate: 'agent_message_chunk'
content: ContentBlock
}
// Tool call content types from ACP
export interface ToolCallContentBlock {
type: "content";
content: ContentBlock;
type: 'content'
content: ContentBlock
}
export interface ToolCallDiffContent {
type: "diff";
path: string;
oldText?: string | null;
newText: string;
type: 'diff'
path: string
oldText?: string | null
newText: string
}
export interface ToolCallTerminalContent {
type: "terminal";
terminalId: string;
type: 'terminal'
terminalId: string
}
export type ToolCallContent = ToolCallContentBlock | ToolCallDiffContent | ToolCallTerminalContent;
export type ToolCallContent =
| ToolCallContentBlock
| ToolCallDiffContent
| ToolCallTerminalContent
export interface ToolCallUpdate {
sessionUpdate: "tool_call";
toolCallId: string;
title: string;
status: string;
content?: ToolCallContent[];
rawInput?: Record<string, unknown>;
rawOutput?: Record<string, unknown>;
sessionUpdate: 'tool_call'
toolCallId: string
title: string
status: string
content?: ToolCallContent[]
rawInput?: Record<string, unknown>
rawOutput?: Record<string, unknown>
}
export interface ToolCallStatusUpdate {
sessionUpdate: "tool_call_update";
toolCallId: string;
status?: string;
title?: string;
content?: ToolCallContent[];
rawInput?: Record<string, unknown>;
rawOutput?: Record<string, unknown>;
sessionUpdate: 'tool_call_update'
toolCallId: string
status?: string
title?: string
content?: ToolCallContent[]
rawInput?: Record<string, unknown>
rawOutput?: Record<string, unknown>
}
export interface AgentThoughtChunkUpdate {
sessionUpdate: "agent_thought_chunk";
content: ContentBlock;
sessionUpdate: 'agent_thought_chunk'
content: ContentBlock
}
export type PlanEntryPriority = "high" | "medium" | "low";
export type PlanEntryStatus = "pending" | "in_progress" | "completed";
export type PlanEntryPriority = 'high' | 'medium' | 'low'
export type PlanEntryStatus = 'pending' | 'in_progress' | 'completed'
export interface PlanEntry {
_meta?: Record<string, unknown> | null;
content: string;
priority: PlanEntryPriority;
status: PlanEntryStatus;
_meta?: Record<string, unknown> | null
content: string
priority: PlanEntryPriority
status: PlanEntryStatus
}
export interface PlanUpdate {
sessionUpdate: "plan";
_meta?: Record<string, unknown> | null;
entries: PlanEntry[];
sessionUpdate: 'plan'
_meta?: Record<string, unknown> | null
entries: PlanEntry[]
}
export interface UserMessageChunkUpdate {
sessionUpdate: "user_message_chunk";
content: ContentBlock;
sessionUpdate: 'user_message_chunk'
content: ContentBlock
}
// Available command from agent (matches ACP SDK AvailableCommand)
export interface AvailableCommand {
name: string;
description: string;
input?: { hint: string };
name: string
description: string
input?: { hint: string }
}
export interface AvailableCommandsUpdate {
sessionUpdate: "available_commands_update";
availableCommands: AvailableCommand[];
sessionUpdate: 'available_commands_update'
availableCommands: AvailableCommand[]
}
export type SessionUpdate =
@@ -335,22 +346,22 @@ export type SessionUpdate =
| AgentThoughtChunkUpdate
| PlanUpdate
| UserMessageChunkUpdate
| AvailableCommandsUpdate;
| AvailableCommandsUpdate
// Connection state
export type ConnectionState =
| "disconnected"
| "connecting"
| "connected"
| "error";
| 'disconnected'
| 'connecting'
| 'connected'
| 'error'
// PromptCapabilities from ACP protocol
// Reference: Zed's acp::PromptCapabilities in agent-client-protocol crate
// Used to check what content types the agent supports
export interface PromptCapabilities {
audio?: boolean; // Agent supports audio content
embeddedContext?: boolean; // Agent supports embedded context in prompts
image?: boolean; // Agent supports image content
audio?: boolean // Agent supports audio content
embeddedContext?: boolean // Agent supports embedded context in prompts
image?: boolean // Agent supports image content
}
// ============================================================================
@@ -365,9 +376,9 @@ export interface PromptCapabilities {
*/
export interface McpCapabilities {
/** Agent supports client-provided MCP servers */
clientServers?: boolean;
clientServers?: boolean
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
}
/**
@@ -377,7 +388,7 @@ export interface McpCapabilities {
*/
export interface SessionListCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
}
/**
@@ -387,7 +398,7 @@ export interface SessionListCapabilities {
*/
export interface SessionResumeCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
}
/**
@@ -397,7 +408,7 @@ export interface SessionResumeCapabilities {
*/
export interface SessionForkCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
}
/**
@@ -411,13 +422,13 @@ export interface SessionForkCapabilities {
*/
export interface SessionCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** @experimental Agent supports forking sessions via session/fork */
fork?: SessionForkCapabilities | null;
fork?: SessionForkCapabilities | null
/** @experimental Agent supports listing sessions via session/list */
list?: SessionListCapabilities | null;
list?: SessionListCapabilities | null
/** @experimental Agent supports resuming sessions via session/resume */
resume?: SessionResumeCapabilities | null;
resume?: SessionResumeCapabilities | null
}
/**
@@ -428,15 +439,15 @@ export interface SessionCapabilities {
*/
export interface AgentCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** Whether the agent supports session/load */
loadSession?: boolean;
loadSession?: boolean
/** MCP capabilities supported by the agent */
mcpCapabilities?: McpCapabilities;
mcpCapabilities?: McpCapabilities
/** Prompt capabilities supported by the agent */
promptCapabilities?: PromptCapabilities;
promptCapabilities?: PromptCapabilities
/** Session capabilities supported by the agent */
sessionCapabilities?: SessionCapabilities;
sessionCapabilities?: SessionCapabilities
}
// ============================================================================
@@ -454,15 +465,15 @@ export interface AgentCapabilities {
*/
export interface AgentSessionInfo {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** Working directory for the session (required per SDK) */
cwd: string;
cwd: string
/** Unique identifier for the session */
sessionId: string;
sessionId: string
/** Human-readable title for the session */
title?: string | null;
title?: string | null
/** ISO 8601 timestamp when the session was last updated */
updatedAt?: string | null;
updatedAt?: string | null
}
/**
@@ -471,11 +482,11 @@ export interface AgentSessionInfo {
*/
export interface ListSessionsRequest {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** Filter sessions by working directory */
cwd?: string;
cwd?: string
/** Pagination cursor for fetching more results */
cursor?: string;
cursor?: string
}
/**
@@ -484,11 +495,11 @@ export interface ListSessionsRequest {
*/
export interface ListSessionsResponse {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** Cursor for fetching the next page of results */
nextCursor?: string | null;
nextCursor?: string | null
/** Array of session info objects */
sessions: AgentSessionInfo[];
sessions: AgentSessionInfo[]
}
/**
@@ -497,11 +508,11 @@ export interface ListSessionsResponse {
*/
export interface LoadSessionRequest {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** Session ID to load */
sessionId: string;
sessionId: string
/** Working directory for the session */
cwd?: string;
cwd?: string
}
/**
@@ -510,11 +521,11 @@ export interface LoadSessionRequest {
*/
export interface ResumeSessionRequest {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
_meta?: Record<string, unknown> | null
/** Session ID to resume */
sessionId: string;
sessionId: string
/** Working directory for the session */
cwd?: string;
cwd?: string
}
// ============================================================================
@@ -528,11 +539,11 @@ export interface ResumeSessionRequest {
*/
export interface ModelInfo {
/** Unique identifier for the model */
modelId: string;
modelId: string
/** Human-readable name of the model */
name: string;
name: string
/** Optional description of the model */
description?: string | null;
description?: string | null
}
/**
@@ -541,20 +552,20 @@ export interface ModelInfo {
*/
export interface SessionModelState {
/** The set of models that the Agent can use */
availableModels: ModelInfo[];
availableModels: ModelInfo[]
/** The current model the Agent is using */
currentModelId: string;
currentModelId: string
}
// Settings
export interface ACPSettings {
proxyUrl: string;
proxyUrl: string
/** Auth token for remote access (sent via WebSocket subprotocol) */
token?: string;
token?: string
/** Working directory for the agent session */
cwd?: string;
cwd?: string
}
export const DEFAULT_SETTINGS: ACPSettings = {
proxyUrl: "ws://localhost:9315/ws",
};
proxyUrl: 'ws://localhost:9315/ws',
}

View File

@@ -1,90 +1,102 @@
import type { Session, Environment, ControlResponse, SessionEvent } from "../types";
import { generateMessageUuid } from "../lib/utils";
import type {
Session,
Environment,
ControlResponse,
SessionEvent,
} from '../types'
import { generateMessageUuid } from '../lib/utils'
const BASE = "";
const BASE = ''
export function getUuid(): string {
let uuid = localStorage.getItem("rcs_uuid");
let uuid = localStorage.getItem('rcs_uuid')
if (!uuid) {
uuid = generateMessageUuid();
localStorage.setItem("rcs_uuid", uuid);
uuid = generateMessageUuid()
localStorage.setItem('rcs_uuid', uuid)
}
return uuid;
return uuid
}
export function setUuid(uuid: string): void {
localStorage.setItem("rcs_uuid", uuid);
localStorage.setItem('rcs_uuid', uuid)
}
/** Active API token for Authorization header (set by useTokens) */
let _activeToken: string | null = null;
let _activeToken: string | null = null
export function setActiveApiToken(token: string | null): void {
_activeToken = token;
_activeToken = token
}
export function getActiveApiToken(): string | null {
return _activeToken;
return _activeToken
}
async function api<T>(method: string, path: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
async function api<T>(
method: string,
path: string,
body?: unknown,
): Promise<T> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (_activeToken) {
headers["Authorization"] = `Bearer ${_activeToken}`;
headers['Authorization'] = `Bearer ${_activeToken}`
}
const uuid = getUuid();
const sep = path.includes("?") ? "&" : "?";
const url = `${BASE}${path}${sep}uuid=${encodeURIComponent(uuid)}`;
const opts: RequestInit = { method, headers };
if (body !== undefined) opts.body = JSON.stringify(body);
const uuid = getUuid()
const sep = path.includes('?') ? '&' : '?'
const url = `${BASE}${path}${sep}uuid=${encodeURIComponent(uuid)}`
const opts: RequestInit = { method, headers }
if (body !== undefined) opts.body = JSON.stringify(body)
const res = await fetch(url, opts);
const data = await res.json();
const res = await fetch(url, opts)
const data = await res.json()
if (!res.ok) {
const err = data.error || { type: "unknown", message: res.statusText };
throw new Error(err.message || err.type);
const err = data.error || { type: 'unknown', message: res.statusText }
throw new Error(err.message || err.type)
}
return data as T;
return data as T
}
export function apiBind(sessionId: string) {
return api<void>("POST", "/web/bind", { sessionId });
return api<void>('POST', '/web/bind', { sessionId })
}
export function apiFetchSessions() {
return api<Session[]>("GET", "/web/sessions");
return api<Session[]>('GET', '/web/sessions')
}
export function apiFetchAllSessions() {
return api<Session[]>("GET", "/web/sessions/all");
return api<Session[]>('GET', '/web/sessions/all')
}
export function apiFetchSession(id: string) {
return api<Session>("GET", `/web/sessions/${id}`);
return api<Session>('GET', `/web/sessions/${id}`)
}
export function apiFetchSessionHistory(id: string) {
return api<{ events: SessionEvent[] }>("GET", `/web/sessions/${id}/history`);
return api<{ events: SessionEvent[] }>('GET', `/web/sessions/${id}/history`)
}
export function apiFetchEnvironments() {
return api<Environment[]>("GET", "/web/environments");
return api<Environment[]>('GET', '/web/environments')
}
export function apiSendEvent(sessionId: string, body: Record<string, unknown>) {
return api<void>("POST", `/web/sessions/${sessionId}/events`, body);
return api<void>('POST', `/web/sessions/${sessionId}/events`, body)
}
export function apiSendControl(sessionId: string, body: ControlResponse) {
return api<void>("POST", `/web/sessions/${sessionId}/control`, body);
return api<void>('POST', `/web/sessions/${sessionId}/control`, body)
}
export function apiInterrupt(sessionId: string) {
return api<void>("POST", `/web/sessions/${sessionId}/interrupt`);
return api<void>('POST', `/web/sessions/${sessionId}/interrupt`)
}
export function apiCreateSession(body: { title?: string; environment_id?: string }) {
return api<Session>("POST", "/web/sessions", body);
export function apiCreateSession(body: {
title?: string
environment_id?: string
}) {
return api<Session>('POST', '/web/sessions', body)
}

View File

@@ -1,41 +1,41 @@
import { getUuid } from "./client";
import type { SessionEvent } from "../types";
import { getUuid } from './client'
import type { SessionEvent } from '../types'
let currentEventSource: EventSource | null = null;
let currentEventSource: EventSource | null = null
export function connectSSE(
sessionId: string,
onEvent: (event: SessionEvent) => void,
fromSeqNum = 0,
): void {
disconnectSSE();
disconnectSSE()
const uuid = getUuid();
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
const es = new EventSource(url);
currentEventSource = es;
const uuid = getUuid()
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`
const es = new EventSource(url)
currentEventSource = es
let lastSeenSeq = fromSeqNum;
let lastSeenSeq = fromSeqNum
es.addEventListener("message", (e: MessageEvent) => {
es.addEventListener('message', (e: MessageEvent) => {
try {
const data = JSON.parse(e.data) as SessionEvent;
if (data.seqNum !== undefined && data.seqNum <= lastSeenSeq) return;
if (data.seqNum !== undefined) lastSeenSeq = data.seqNum;
onEvent(data);
const data = JSON.parse(e.data) as SessionEvent
if (data.seqNum !== undefined && data.seqNum <= lastSeenSeq) return
if (data.seqNum !== undefined) lastSeenSeq = data.seqNum
onEvent(data)
} catch {
// ignore parse errors
}
});
})
es.addEventListener("error", () => {
es.addEventListener('error', () => {
// EventSource auto-reconnects
});
})
}
export function disconnectSSE(): void {
if (currentEventSource) {
currentEventSource.close();
currentEventSource = null;
currentEventSource.close()
currentEventSource = null
}
}

View File

@@ -1,7 +1,7 @@
import { useState, useEffect, useRef } from "react";
import { ACPClient, DisconnectRequestedError } from "../acp/client";
import type { ConnectionState } from "../acp/types";
import { ACPMain } from "../../components/ACPMain";
import { useState, useEffect, useRef } from 'react';
import { ACPClient, DisconnectRequestedError } from '../acp/client';
import type { ConnectionState } from '../acp/types';
import { ACPMain } from '../../components/ACPMain';
interface ACPDirectViewProps {
url: string;
@@ -11,7 +11,7 @@ interface ACPDirectViewProps {
export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
const [client, setClient] = useState<ACPClient | null>(null);
const [connectionState, setConnectionState] = useState<ConnectionState>("disconnected");
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
const [error, setError] = useState<string | null>(null);
const clientRef = useRef<ACPClient | null>(null);
@@ -26,35 +26,32 @@ export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
clientRef.current = acpClient;
setClient(acpClient);
acpClient.connect().catch((e) => {
acpClient.connect().catch(e => {
if (e instanceof DisconnectRequestedError) return;
setError((e as Error).message);
setConnectionState("error");
setConnectionState('error');
});
return () => {
acpClient.disconnect();
clientRef.current = null;
setClient(null);
setConnectionState("disconnected");
setConnectionState('disconnected');
};
}, [url, token]);
return (
<div className="flex flex-1 flex-col overflow-hidden">
{error && connectionState === "error" && (
{error && connectionState === 'error' && (
<div className="px-4 py-2 bg-status-error/10 text-status-error text-sm border-b">
{error}
<button
onClick={onBack}
className="ml-3 underline hover:no-underline"
>
<button onClick={onBack} className="ml-3 underline hover:no-underline">
Back to Dashboard
</button>
</div>
)}
{connectionState === "connecting" && (
{connectionState === 'connecting' && (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<div className="animate-spin h-8 w-8 border-2 border-brand border-t-transparent rounded-full mx-auto mb-3" />
@@ -63,7 +60,7 @@ export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
</div>
)}
{connectionState === "error" && !client && (
{connectionState === 'error' && !client && (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<p className="font-medium mb-1">Connection Failed</p>
@@ -78,9 +75,7 @@ export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
</div>
)}
{client && connectionState === "connected" && (
<ACPMain client={client} />
)}
{client && connectionState === 'connected' && <ACPMain client={client} />}
</div>
);
}

View File

@@ -1,6 +1,6 @@
import { useState, useRef, useEffect } from "react";
import { cn, isClosedSessionStatus } from "../lib/utils";
import { Square, SendHorizonal } from "lucide-react";
import { useState, useRef, useEffect } from 'react';
import { cn, isClosedSessionStatus } from '../lib/utils';
import { Square, SendHorizonal } from 'lucide-react';
interface ControlBarProps {
sessionId: string;
@@ -10,22 +10,16 @@ interface ControlBarProps {
onInterrupt: () => Promise<void>;
}
export function ControlBar({
sessionId,
sessionStatus,
activityMode,
onSend,
onInterrupt,
}: ControlBarProps) {
const [text, setText] = useState("");
export function ControlBar({ sessionId, sessionStatus, activityMode, onSend, onInterrupt }: ControlBarProps) {
const [text, setText] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const closed = isClosedSessionStatus(sessionStatus);
const working = activityMode === "working";
const working = activityMode === 'working';
const handleSend = async () => {
const trimmed = text.trim();
if (!trimmed || closed) return;
setText("");
setText('');
try {
await onSend(trimmed);
} catch {
@@ -34,7 +28,7 @@ export function ControlBar({
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent?.isComposing) {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent?.isComposing) {
e.preventDefault();
handleSend();
}
@@ -51,9 +45,9 @@ export function ControlBar({
ref={inputRef}
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
onChange={e => setText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={closed ? "Session is closed" : "Type a message..."}
placeholder={closed ? 'Session is closed' : 'Type a message...'}
disabled={closed}
className="flex-1 rounded-lg border border-border bg-surface-2 px-4 py-2.5 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none focus:ring-1 focus:ring-brand/20 disabled:opacity-50 transition-colors"
/>
@@ -61,14 +55,14 @@ export function ControlBar({
onClick={working ? onInterrupt : handleSend}
disabled={closed}
className={cn(
"flex h-10 w-10 items-center justify-center rounded-lg transition-colors",
'flex h-10 w-10 items-center justify-center rounded-lg transition-colors',
working
? "bg-status-error/20 text-status-error hover:bg-status-error/30"
: "bg-brand text-white hover:bg-brand-light",
closed && "opacity-50 cursor-not-allowed",
? 'bg-status-error/20 text-status-error hover:bg-status-error/30'
: 'bg-brand text-white hover:bg-brand-light',
closed && 'opacity-50 cursor-not-allowed',
)}
aria-label={working ? "Stop" : "Send"}
title={closed ? "Session is closed" : working ? "Stop" : "Send"}
aria-label={working ? 'Stop' : 'Send'}
title={closed ? 'Session is closed' : working ? 'Stop' : 'Send'}
>
{working ? (
<Square className="h-4.5 w-4.5 fill-current" />

View File

@@ -1,6 +1,6 @@
import type { Environment } from "../types";
import { StatusBadge } from "./Navbar";
import { esc, formatTime } from "../lib/utils";
import type { Environment } from '../types';
import { StatusBadge } from './Navbar';
import { esc, formatTime } from '../lib/utils';
interface EnvironmentListProps {
environments: Environment[];
@@ -18,10 +18,10 @@ export function EnvironmentList({ environments, onSelectEnvironment }: Environme
return (
<div className="space-y-2">
{environments.map((env) => {
const isAcp = env.worker_type === "acp";
const typeLabel = isAcp ? "ACP Agent" : "Claude Code";
const typeColor = isAcp ? "bg-brand/15 text-brand" : "bg-status-running/15 text-status-running";
{environments.map(env => {
const isAcp = env.worker_type === 'acp';
const typeLabel = isAcp ? 'ACP Agent' : 'Claude Code';
const typeColor = isAcp ? 'bg-brand/15 text-brand' : 'bg-status-running/15 text-status-running';
return (
<button
@@ -29,26 +29,20 @@ export function EnvironmentList({ environments, onSelectEnvironment }: Environme
type="button"
onClick={() => onSelectEnvironment?.(env)}
disabled={isAcp}
className={`flex w-full items-center justify-between rounded-xl border border-border bg-surface-1 px-4 py-3 text-left transition-colors ${isAcp ? "cursor-default opacity-80" : "hover:border-border-light cursor-pointer"}`}
className={`flex w-full items-center justify-between rounded-xl border border-border bg-surface-1 px-4 py-3 text-left transition-colors ${isAcp ? 'cursor-default opacity-80' : 'hover:border-border-light cursor-pointer'}`}
>
<div className="flex items-center gap-3">
<div>
<div className="flex items-center gap-2">
<span className="font-medium text-text-primary">
{env.machine_name || env.id}
</span>
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${typeColor}`}>
{typeLabel}
</span>
<span className="font-medium text-text-primary">{env.machine_name || env.id}</span>
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${typeColor}`}>{typeLabel}</span>
</div>
<div className="text-sm text-text-muted">{env.directory || ""}</div>
<div className="text-sm text-text-muted">{env.directory || ''}</div>
</div>
</div>
<div className="text-right">
<StatusBadge status={env.status} />
<div className="mt-1 text-xs text-text-muted">
{env.branch || ""}
</div>
<div className="mt-1 text-xs text-text-muted">{env.branch || ''}</div>
</div>
</button>
);

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useRef } from "react";
import type { SessionEvent, EventPayload } from "../types";
import { esc, truncate, cn, extractEventText, isConversationClearedStatus } from "../lib/utils";
import { useState, useEffect, useRef } from 'react';
import type { SessionEvent, EventPayload } from '../types';
import { esc, truncate, cn, extractEventText, isConversationClearedStatus } from '../lib/utils';
// ============================================================
// Tool Trace State
@@ -8,9 +8,9 @@ import { esc, truncate, cn, extractEventText, isConversationClearedStatus } from
interface TraceHost {
id: string;
kind: "assistant" | "orphan";
kind: 'assistant' | 'orphan';
assistantContent: string;
entryKinds: ("use" | "result")[];
entryKinds: ('use' | 'result')[];
}
interface ToolTraceState {
@@ -26,7 +26,7 @@ function createTraceState(): ToolTraceState {
function addAssistantHost(state: ToolTraceState, content: string): { state: ToolTraceState; host: TraceHost } {
const host: TraceHost = {
id: `trace-${state.nextHostId}`,
kind: "assistant",
kind: 'assistant',
assistantContent: content,
entryKinds: [],
};
@@ -45,26 +45,29 @@ function clearActiveHost(state: ToolTraceState): ToolTraceState {
return { ...state, activeHostId: null };
}
function addTraceEntry(state: ToolTraceState, entryKind: "use" | "result"): {
function addTraceEntry(
state: ToolTraceState,
entryKind: 'use' | 'result',
): {
state: ToolTraceState;
host: TraceHost;
createdHost: TraceHost | null;
} {
let host = state.hosts.find((h) => h.id === state.activeHostId);
let host = state.hosts.find(h => h.id === state.activeHostId);
let createdHost: TraceHost | null = null;
if (!host) {
createdHost = {
id: `trace-${state.nextHostId}`,
kind: "orphan",
assistantContent: "",
kind: 'orphan',
assistantContent: '',
entryKinds: [],
};
host = createdHost;
}
const updatedHost = { ...host, entryKinds: [...host.entryKinds, entryKind] };
const newHosts = state.hosts.map((h) => (h.id === updatedHost.id ? updatedHost : h));
const newHosts = state.hosts.map(h => (h.id === updatedHost.id ? updatedHost : h));
if (createdHost) newHosts.push(createdHost);
return {
@@ -83,12 +86,12 @@ function addTraceEntry(state: ToolTraceState, entryKind: "use" | "result"): {
// ============================================================
interface UserMessage {
kind: "user";
kind: 'user';
content: string;
}
interface AssistantMessage {
kind: "assistant";
kind: 'assistant';
content: string;
traceEntries: TraceEntry[];
traceExpanded: boolean;
@@ -96,7 +99,7 @@ interface AssistantMessage {
}
interface TraceEntry {
entryKind: "use" | "result";
entryKind: 'use' | 'result';
toolName?: string;
toolInput?: unknown;
content?: string;
@@ -105,12 +108,12 @@ interface TraceEntry {
}
interface SystemMessage {
kind: "system";
kind: 'system';
content: string;
}
interface PermissionMessage {
kind: "permission";
kind: 'permission';
requestId: string;
toolName: string;
toolInput: unknown;
@@ -118,21 +121,21 @@ interface PermissionMessage {
}
interface AskUserMessage {
kind: "ask_user";
kind: 'ask_user';
requestId: string;
questions: import("../types").Question[];
questions: import('../types').Question[];
description: string;
}
interface PlanMessage {
kind: "plan";
kind: 'plan';
requestId: string;
planContent: string;
description: string;
}
interface LoadingMessage {
kind: "loading";
kind: 'loading';
verb: string;
startTime: number;
}
@@ -150,15 +153,40 @@ type DisplayMessage =
// Spinner
// ============================================================
const SPINNER_FRAMES = ["·", "✢", "✱", "✶", "✻", "✽"];
const SPINNER_FRAMES = ['·', '✢', '✱', '✶', '✻', '✽'];
const SPINNER_CYCLE = [...SPINNER_FRAMES, ...SPINNER_FRAMES.slice().reverse()];
const SPINNER_VERBS = [
"Accomplishing", "Baking", "Calculating", "Clauding", "Cogitating", "Computing",
"Considering", "Contemplating", "Cooking", "Crafting", "Creating", "Crunching",
"Deliberating", "Doing", "Effecting", "Generating", "Hatching", "Ideating",
"Imagining", "Inferring", "Manifesting", "Mulling", "Pondering", "Processing",
"Ruminating", "Simmering", "Synthesizing", "Thinking", "Tinkering", "Working",
'Accomplishing',
'Baking',
'Calculating',
'Clauding',
'Cogitating',
'Computing',
'Considering',
'Contemplating',
'Cooking',
'Crafting',
'Creating',
'Crunching',
'Deliberating',
'Doing',
'Effecting',
'Generating',
'Hatching',
'Ideating',
'Imagining',
'Inferring',
'Manifesting',
'Mulling',
'Pondering',
'Processing',
'Ruminating',
'Simmering',
'Synthesizing',
'Thinking',
'Tinkering',
'Working',
];
// ============================================================
@@ -169,7 +197,11 @@ interface EventStreamProps {
messages: DisplayMessage[];
onApprovePermission: (requestId: string) => void;
onRejectPermission: (requestId: string) => void;
onSubmitAnswers: (requestId: string, answers: Record<string, unknown>, questions: import("../types").Question[]) => void;
onSubmitAnswers: (
requestId: string,
answers: Record<string, unknown>,
questions: import('../types').Question[],
) => void;
onSubmitPlanResponse: (requestId: string, value: string, feedback?: string) => void;
}
@@ -192,28 +224,42 @@ export function EventStream({
<div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">
<div className="mx-auto max-w-5xl space-y-3">
{messages.map((msg, i) => (
<MessageRow key={i} message={msg} {...{ onApprovePermission, onRejectPermission, onSubmitAnswers, onSubmitPlanResponse }} />
<MessageRow
key={i}
message={msg}
{...{ onApprovePermission, onRejectPermission, onSubmitAnswers, onSubmitPlanResponse }}
/>
))}
</div>
</div>
);
}
function MessageRow({ message, onApprovePermission, onRejectPermission, onSubmitAnswers, onSubmitPlanResponse }: {
function MessageRow({
message,
onApprovePermission,
onRejectPermission,
onSubmitAnswers,
onSubmitPlanResponse,
}: {
message: DisplayMessage;
onApprovePermission: (requestId: string) => void;
onRejectPermission: (requestId: string) => void;
onSubmitAnswers: (requestId: string, answers: Record<string, unknown>, questions: import("../types").Question[]) => void;
onSubmitAnswers: (
requestId: string,
answers: Record<string, unknown>,
questions: import('../types').Question[],
) => void;
onSubmitPlanResponse: (requestId: string, value: string, feedback?: string) => void;
}) {
switch (message.kind) {
case "user":
case 'user':
return <UserBubble content={message.content} />;
case "assistant":
case 'assistant':
return <AssistantBubble content={message.content} traceEntries={message.traceEntries} />;
case "system":
case 'system':
return <SystemBubble content={message.content} />;
case "permission":
case 'permission':
return (
<PermissionPrompt
{...message}
@@ -221,22 +267,22 @@ function MessageRow({ message, onApprovePermission, onRejectPermission, onSubmit
onReject={() => onRejectPermission(message.requestId)}
/>
);
case "ask_user":
case 'ask_user':
return (
<AskUserPanel
{...message}
onSubmit={(answers) => onSubmitAnswers(message.requestId, answers, message.questions)}
onSubmit={answers => onSubmitAnswers(message.requestId, answers, message.questions)}
onSkip={() => onRejectPermission(message.requestId)}
/>
);
case "plan":
case 'plan':
return (
<PlanPanel
{...message}
onSubmit={(value, feedback) => onSubmitPlanResponse(message.requestId, value, feedback)}
/>
);
case "loading":
case 'loading':
return <LoadingIndicator verb={message.verb} />;
default:
return null;
@@ -266,7 +312,7 @@ function formatAssistantContent(content: string): string {
// Inline code
html = html.replace(/`([^`]+)`/g, '<code class="rounded bg-tool-card px-1.5 py-0.5 font-mono text-xs">$1</code>');
// Bold
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
return html;
}
@@ -279,6 +325,7 @@ function AssistantBubble({ content, traceEntries }: { content: string; traceEntr
{content && (
<div
className="rounded-2xl rounded-bl-md bg-surface-2 px-4 py-2.5 text-sm text-text-primary"
// biome-ignore lint/security/noDangerouslySetInnerHtml: content is sanitized by formatAssistantContent
dangerouslySetInnerHTML={{ __html: formatAssistantContent(content) }}
/>
)}
@@ -288,8 +335,10 @@ function AssistantBubble({ content, traceEntries }: { content: string; traceEntr
onClick={() => setExpanded(!expanded)}
className="flex items-center gap-1.5 text-xs text-text-muted hover:text-text-secondary transition-colors"
>
<span className={cn("transition-transform", expanded && "rotate-90")}></span>
<span>{traceEntries.length} tool {traceEntries.length === 1 ? "call" : "calls"}</span>
<span className={cn('transition-transform', expanded && 'rotate-90')}></span>
<span>
{traceEntries.length} tool {traceEntries.length === 1 ? 'call' : 'calls'}
</span>
</button>
{expanded && (
<div className="mt-1 space-y-1 pl-2">
@@ -308,8 +357,8 @@ function AssistantBubble({ content, traceEntries }: { content: string; traceEntr
function ToolCard({ entry }: { entry: TraceEntry }) {
const [expanded, setExpanded] = useState(false);
if (entry.entryKind === "use") {
const inputStr = typeof entry.toolInput === "string" ? entry.toolInput : JSON.stringify(entry.toolInput, null, 2);
if (entry.entryKind === 'use') {
const inputStr = typeof entry.toolInput === 'string' ? entry.toolInput : JSON.stringify(entry.toolInput, null, 2);
return (
<div
className="cursor-pointer rounded-lg border border-border bg-tool-card"
@@ -317,7 +366,7 @@ function ToolCard({ entry }: { entry: TraceEntry }) {
>
<div className="flex items-center gap-2 px-3 py-2 text-xs">
<span className="text-brand"></span>
<span className="font-medium text-text-primary">{entry.toolName || "tool"}</span>
<span className="font-medium text-text-primary">{entry.toolName || 'tool'}</span>
</div>
{expanded && (
<pre className="border-t border-border px-3 py-2 text-xs text-text-secondary overflow-x-auto">
@@ -328,22 +377,18 @@ function ToolCard({ entry }: { entry: TraceEntry }) {
);
}
const contentStr = typeof entry.output === "string" ? entry.output : JSON.stringify(entry.output, null, 2);
const contentStr = typeof entry.output === 'string' ? entry.output : JSON.stringify(entry.output, null, 2);
return (
<div
className={cn(
"cursor-pointer rounded-lg border bg-tool-card",
entry.isError ? "border-status-error/30" : "border-border",
'cursor-pointer rounded-lg border bg-tool-card',
entry.isError ? 'border-status-error/30' : 'border-border',
)}
onClick={() => setExpanded(!expanded)}
>
<div className="flex items-center gap-2 px-3 py-2 text-xs">
<span className={entry.isError ? "text-status-error" : "text-status-active"}>
{entry.isError ? "✕" : "✓"}
</span>
<span className="font-medium text-text-primary">
{entry.isError ? "Error" : "Result"}
</span>
<span className={entry.isError ? 'text-status-error' : 'text-status-active'}>{entry.isError ? '✕' : '✓'}</span>
<span className="font-medium text-text-primary">{entry.isError ? 'Error' : 'Result'}</span>
</div>
{expanded && (
<pre className="border-t border-border px-3 py-2 text-xs text-text-secondary overflow-x-auto">
@@ -357,9 +402,7 @@ function ToolCard({ entry }: { entry: TraceEntry }) {
function SystemBubble({ content }: { content: string }) {
return (
<div className="flex justify-center">
<div className="rounded-full bg-surface-2 px-4 py-1.5 text-xs text-text-muted">
{esc(content)}
</div>
<div className="rounded-full bg-surface-2 px-4 py-1.5 text-xs text-text-muted">{esc(content)}</div>
</div>
);
}
@@ -379,14 +422,14 @@ function PermissionPrompt({
onApprove: () => void;
onReject: () => void;
}) {
const inputStr = typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput, null, 2);
const inputStr = typeof toolInput === 'string' ? toolInput : JSON.stringify(toolInput, null, 2);
return (
<div className="rounded-xl border border-status-warning/30 bg-surface-1 p-4">
<div className="mb-2 text-sm font-semibold text-status-warning">Permission Request</div>
{description && <div className="mb-2 text-sm text-text-secondary">{esc(description)}</div>}
<div className="mb-2 font-mono text-xs font-bold text-text-primary">{esc(toolName)}</div>
{toolName !== "AskUserQuestion" && (
{toolName !== 'AskUserQuestion' && (
<pre className="mb-3 max-h-40 overflow-auto rounded-lg bg-tool-card p-2 text-xs text-text-secondary">
{truncate(inputStr, 500)}
</pre>
@@ -416,7 +459,7 @@ function AskUserPanel({
onSkip,
}: {
requestId: string;
questions: import("../types").Question[];
questions: import('../types').Question[];
description: string;
onSubmit: (answers: Record<string, unknown>) => void;
onSkip: () => void;
@@ -427,7 +470,7 @@ function AskUserPanel({
const handleSelect = (qIdx: number, oIdx: number, multiSelect: boolean) => {
if (multiSelect) {
const current = (answers[qIdx] as number[]) || [];
const next = current.includes(oIdx) ? current.filter((i) => i !== oIdx) : [...current, oIdx];
const next = current.includes(oIdx) ? current.filter(i => i !== oIdx) : [...current, oIdx];
setAnswers({ ...answers, [qIdx]: next });
} else {
setAnswers({ ...answers, [qIdx]: oIdx });
@@ -438,7 +481,7 @@ function AskUserPanel({
const text = otherTexts[qIdx]?.trim();
if (!text) return;
setAnswers({ ...answers, [qIdx]: text });
setOtherTexts({ ...otherTexts, [qIdx]: "" });
setOtherTexts({ ...otherTexts, [qIdx]: '' });
};
const handleSubmit = () => {
@@ -446,10 +489,10 @@ function AskUserPanel({
for (const [qIdx, val] of Object.entries(answers)) {
const q = questions[parseInt(qIdx, 10)];
if (!q) continue;
if (typeof val === "number") {
if (typeof val === 'number') {
mapped[qIdx] = q.options?.[val]?.label || String(val);
} else if (Array.isArray(val)) {
mapped[qIdx] = val.map((i) => q.options?.[i]?.label || String(i));
mapped[qIdx] = val.map(i => q.options?.[i]?.label || String(i));
} else {
mapped[qIdx] = val;
}
@@ -465,22 +508,20 @@ function AskUserPanel({
return (
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
<div className="mb-3 text-sm font-semibold text-text-primary">
{esc(description || q.question || "Question")}
{esc(description || q.question || 'Question')}
</div>
<div className="space-y-2">
{(q.options || []).map((opt, j) => {
const isSelected = multiSelect
? ((answers[0] as number[]) || []).includes(j)
: selectedIdx === j;
const isSelected = multiSelect ? ((answers[0] as number[]) || []).includes(j) : selectedIdx === j;
return (
<button
key={j}
onClick={() => handleSelect(0, j, multiSelect)}
className={cn(
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
isSelected
? "border-brand bg-brand/10 text-text-primary"
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
? 'border-brand bg-brand/10 text-text-primary'
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
)}
>
<div className="font-medium">{esc(opt.label)}</div>
@@ -491,11 +532,11 @@ function AskUserPanel({
<div className="flex gap-2">
<input
type="text"
value={otherTexts[0] || ""}
onChange={(e) => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
value={otherTexts[0] || ''}
onChange={e => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
placeholder="Other..."
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
onKeyDown={(e) => e.key === "Enter" && handleOtherSubmit(0)}
onKeyDown={e => e.key === 'Enter' && handleOtherSubmit(0)}
/>
<button
onClick={() => handleOtherSubmit(0)}
@@ -528,17 +569,15 @@ function AskUserPanel({
return (
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || "Questions")}</div>
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || 'Questions')}</div>
<div className="mb-3 flex gap-1 overflow-x-auto">
{questions.map((q, i) => (
<button
key={i}
onClick={() => setActiveTab(i)}
className={cn(
"rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors",
activeTab === i
? "bg-brand/20 text-brand"
: "text-text-muted hover:bg-surface-2",
'rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors',
activeTab === i ? 'bg-brand/20 text-brand' : 'text-text-muted hover:bg-surface-2',
)}
>
{q.header || `Q${i + 1}`}
@@ -557,7 +596,9 @@ function AskUserPanel({
/>
)}
<div className="mt-4 flex items-center justify-between">
<span className="text-xs text-text-muted">{activeTab + 1} / {questions.length}</span>
<span className="text-xs text-text-muted">
{activeTab + 1} / {questions.length}
</span>
<div className="flex gap-2">
<button
onClick={handleSubmit}
@@ -586,7 +627,7 @@ function QuestionTab({
onOtherTextChange,
onOtherSubmit,
}: {
question: import("../types").Question;
question: import('../types').Question;
qIdx: number;
answers: Record<string, unknown>;
otherTexts: Record<string, string>;
@@ -601,18 +642,16 @@ function QuestionTab({
<div className="mb-2 text-sm text-text-secondary">{esc(question.question)}</div>
<div className="space-y-2">
{(question.options || []).map((opt, j) => {
const isSelected = multiSelect
? ((answers[qIdx] as number[]) || []).includes(j)
: answers[qIdx] === j;
const isSelected = multiSelect ? ((answers[qIdx] as number[]) || []).includes(j) : answers[qIdx] === j;
return (
<button
key={j}
onClick={() => onSelect(qIdx, j, multiSelect)}
className={cn(
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
isSelected
? "border-brand bg-brand/10 text-text-primary"
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
? 'border-brand bg-brand/10 text-text-primary'
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
)}
>
<div className="font-medium">{esc(opt.label)}</div>
@@ -623,11 +662,11 @@ function QuestionTab({
<div className="flex gap-2">
<input
type="text"
value={otherTexts[qIdx] || ""}
onChange={(e) => onOtherTextChange(qIdx, e.target.value)}
value={otherTexts[qIdx] || ''}
onChange={e => onOtherTextChange(qIdx, e.target.value)}
placeholder="Other..."
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
onKeyDown={(e) => e.key === "Enter" && onOtherSubmit(qIdx)}
onKeyDown={e => e.key === 'Enter' && onOtherSubmit(qIdx)}
/>
<button
onClick={() => onOtherSubmit(qIdx)}
@@ -652,58 +691,59 @@ function PlanPanel({
onSubmit: (value: string, feedback?: string) => void;
}) {
const [selected, setSelected] = useState<string | null>(null);
const [feedback, setFeedback] = useState("");
const [feedback, setFeedback] = useState('');
const isEmpty = !planContent || !planContent.trim();
const handleSubmit = () => {
if (!selected) return;
onSubmit(selected, selected === "no" ? feedback : undefined);
onSubmit(selected, selected === 'no' ? feedback : undefined);
};
return (
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
<div className="mb-3 text-sm font-semibold text-text-primary">
{isEmpty ? "Exit plan mode?" : "Ready to code?"}
{isEmpty ? 'Exit plan mode?' : 'Ready to code?'}
</div>
{!isEmpty && (
<div
className="mb-4 max-h-64 overflow-auto rounded-lg bg-tool-card p-4 text-sm text-text-secondary prose prose-invert"
// biome-ignore lint/security/noDangerouslySetInnerHtml: content is sanitized by formatPlanContent
dangerouslySetInnerHTML={{ __html: formatPlanContent(planContent) }}
/>
)}
<div className="space-y-2">
{isEmpty ? (
<>
<PlanOption selected={selected === "yes-default"} onClick={() => setSelected("yes-default")} label="Yes" />
<PlanOption selected={selected === "no"} onClick={() => setSelected("no")} label="No" />
<PlanOption selected={selected === 'yes-default'} onClick={() => setSelected('yes-default')} label="Yes" />
<PlanOption selected={selected === 'no'} onClick={() => setSelected('no')} label="No" />
</>
) : (
<>
<PlanOption
selected={selected === "yes-accept-edits"}
onClick={() => setSelected("yes-accept-edits")}
selected={selected === 'yes-accept-edits'}
onClick={() => setSelected('yes-accept-edits')}
label="Yes, auto-accept edits"
desc="Approve plan and auto-accept file edits"
/>
<PlanOption
selected={selected === "yes-default"}
onClick={() => setSelected("yes-default")}
selected={selected === 'yes-default'}
onClick={() => setSelected('yes-default')}
label="Yes, manually approve edits"
desc="Approve plan but confirm each edit"
/>
<PlanOption
selected={selected === "no"}
onClick={() => setSelected("no")}
selected={selected === 'no'}
onClick={() => setSelected('no')}
label="No, keep planning"
desc="Provide feedback to refine the plan"
/>
</>
)}
</div>
{selected === "no" && (
{selected === 'no' && (
<textarea
value={feedback}
onChange={(e) => setFeedback(e.target.value)}
onChange={e => setFeedback(e.target.value)}
placeholder="Tell Claude what to change..."
className="mt-3 w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
rows={3}
@@ -737,10 +777,10 @@ function PlanOption({
<button
onClick={onClick}
className={cn(
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
selected
? "border-brand bg-brand/10 text-text-primary"
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
? 'border-brand bg-brand/10 text-text-primary'
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
)}
>
<div className="font-medium">{label}</div>
@@ -758,7 +798,7 @@ function formatPlanContent(content: string): string {
// Inline code
html = html.replace(/`([^`]+)`/g, '<code class="rounded bg-tool-card px-1.5 py-0.5 font-mono text-xs">$1</code>');
// Bold
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
return html;
}
@@ -767,8 +807,8 @@ function LoadingIndicator({ verb }: { verb: string }) {
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
const spinInterval = setInterval(() => setFrame((f) => (f + 1) % SPINNER_CYCLE.length), 120);
const timerInterval = setInterval(() => setElapsed((e) => e + 1), 1000);
const spinInterval = setInterval(() => setFrame(f => (f + 1) % SPINNER_CYCLE.length), 120);
const timerInterval = setInterval(() => setElapsed(e => e + 1), 1000);
return () => {
clearInterval(spinInterval);
clearInterval(timerInterval);
@@ -788,7 +828,17 @@ function LoadingIndicator({ verb }: { verb: string }) {
// Event Processing Hook
// ============================================================
export { type DisplayMessage, type TraceEntry, type UserMessage, type AssistantMessage, type SystemMessage, type PermissionMessage, type AskUserMessage, type PlanMessage, type LoadingMessage };
export type {
DisplayMessage,
TraceEntry,
UserMessage,
AssistantMessage,
SystemMessage,
PermissionMessage,
AskUserMessage,
PlanMessage,
LoadingMessage,
};
export function useEventProcessor() {
const [messages, setMessages] = useState<DisplayMessage[]>([]);
@@ -802,19 +852,19 @@ export function useEventProcessor() {
};
const removeLoading = () => {
setMessages((prev) => prev.filter((m) => m.kind !== "loading"));
setMessages(prev => prev.filter(m => m.kind !== 'loading'));
};
const showLoading = () => {
removeLoading();
const verb = SPINNER_VERBS[Math.floor(Math.random() * SPINNER_VERBS.length)];
setMessages((prev) => [...prev, { kind: "loading", verb, startTime: Date.now() }]);
setMessages(prev => [...prev, { kind: 'loading', verb, startTime: Date.now() }]);
};
const processEvent = (event: SessionEvent, replay = false) => {
const type = event.type;
const payload = event.payload || ({} as EventPayload);
const direction = event.direction || "inbound";
const direction = event.direction || 'inbound';
// Skip bridge init noise
const serialized = JSON.stringify(event);
@@ -826,14 +876,14 @@ export function useEventProcessor() {
}
switch (type) {
case "user": {
const toolResultBlocks = getEmbeddedToolBlocks(payload, "tool_result");
case 'user': {
const toolResultBlocks = getEmbeddedToolBlocks(payload, 'tool_result');
if (toolResultBlocks.length > 0) {
// Process tool results
for (const block of toolResultBlocks) {
addToolTraceEntry("result", {
content: block.content as string || "",
output: block.content as string || "",
addToolTraceEntry('result', {
content: (block.content as string) || '',
output: (block.content as string) || '',
is_error: !!block.is_error,
});
}
@@ -847,25 +897,25 @@ export function useEventProcessor() {
traceStateRef.current = clearActiveHost(traceStateRef.current);
const text = extractEventText(payload as Record<string, unknown>);
if (text) {
setMessages((prev) => [...prev, { kind: "user", content: text }]);
setMessages(prev => [...prev, { kind: 'user', content: text }]);
if (!replay) showLoading();
}
break;
}
case "partial_assistant":
case 'partial_assistant':
return;
case "assistant": {
case 'assistant': {
removeLoading();
const text = extractEventText(payload as Record<string, unknown>);
const toolUseBlocks = getEmbeddedToolBlocks(payload, "tool_use");
const toolUseBlocks = getEmbeddedToolBlocks(payload, 'tool_use');
if (text && text.trim()) {
const result = addAssistantHost(traceStateRef.current, text);
traceStateRef.current = result.state;
setMessages((prev) => [
setMessages(prev => [
...prev,
{
kind: "assistant",
kind: 'assistant',
content: text,
traceEntries: [],
traceExpanded: false,
@@ -875,169 +925,172 @@ export function useEventProcessor() {
}
for (const block of toolUseBlocks) {
addToolTraceEntry("use", {
tool_name: (block.name as string) || "tool",
addToolTraceEntry('use', {
tool_name: (block.name as string) || 'tool',
tool_input: block.input,
});
}
break;
}
case "task_state":
case "automation_state":
case 'task_state':
case 'automation_state':
return;
case "result":
case "result_success":
case 'result':
case 'result_success':
removeLoading();
return;
case "tool_use":
addToolTraceEntry("use", payload as Record<string, unknown> as { tool_name: string; tool_input: unknown });
case 'tool_use':
addToolTraceEntry('use', payload as Record<string, unknown> as { tool_name: string; tool_input: unknown });
break;
case "tool_result":
addToolTraceEntry("result", payload as Record<string, unknown> as { content: string; output: string; is_error: boolean });
case 'tool_result':
addToolTraceEntry(
'result',
payload as Record<string, unknown> as { content: string; output: string; is_error: boolean },
);
break;
case "control_request":
case "permission_request": {
case 'control_request':
case 'permission_request': {
const req = payload.request;
if (req && req.subtype === "can_use_tool") {
const toolName = req.tool_name || "unknown";
if (req && req.subtype === 'can_use_tool') {
const toolName = req.tool_name || 'unknown';
const toolInput = req.input || req.tool_input || {};
if (toolName === "AskUserQuestion") {
setMessages((prev) => [
if (toolName === 'AskUserQuestion') {
setMessages(prev => [
...prev,
{
kind: "ask_user",
requestId: payload.request_id || event.id || "",
questions: (toolInput as Record<string, unknown>).questions as import("../types").Question[] || [],
description: req.description || "",
kind: 'ask_user',
requestId: payload.request_id || event.id || '',
questions: ((toolInput as Record<string, unknown>).questions as import('../types').Question[]) || [],
description: req.description || '',
},
]);
} else if (toolName === "ExitPlanMode") {
setMessages((prev) => [
} else if (toolName === 'ExitPlanMode') {
setMessages(prev => [
...prev,
{
kind: "plan",
requestId: payload.request_id || event.id || "",
planContent: ((toolInput as Record<string, unknown>).plan as string) || "",
description: req.description || "",
kind: 'plan',
requestId: payload.request_id || event.id || '',
planContent: ((toolInput as Record<string, unknown>).plan as string) || '',
description: req.description || '',
},
]);
} else {
setMessages((prev) => [
setMessages(prev => [
...prev,
{
kind: "permission",
requestId: payload.request_id || event.id || "",
kind: 'permission',
requestId: payload.request_id || event.id || '',
toolName,
toolInput,
description: req.description || "",
description: req.description || '',
},
]);
}
}
break;
}
case "control_response":
case "permission_response":
case 'control_response':
case 'permission_response':
return;
case "status": {
case 'status': {
if (isConversationClearedStatus(payload as Record<string, unknown>)) {
reset();
return;
}
const rawMsg = payload.message;
const msg = (typeof rawMsg === "string" ? rawMsg : "") || payload.content || "";
const msg = (typeof rawMsg === 'string' ? rawMsg : '') || payload.content || '';
if (/connecting|waiting|initializing|Remote Control/i.test(msg)) return;
if (!msg.trim()) return;
setMessages((prev) => [...prev, { kind: "system", content: msg }]);
setMessages(prev => [...prev, { kind: 'system', content: msg }]);
break;
}
case "error":
case 'error':
removeLoading();
setMessages((prev) => [
setMessages(prev => [
...prev,
{ kind: "system", content: `Error: ${(typeof payload.message === "string" ? payload.message : "") || payload.content || "Unknown error"}` },
{
kind: 'system',
content: `Error: ${(typeof payload.message === 'string' ? payload.message : '') || payload.content || 'Unknown error'}`,
},
]);
break;
case "session_status":
if (payload.status === "archived" || payload.status === "inactive") {
case 'session_status':
if (payload.status === 'archived' || payload.status === 'inactive') {
removeLoading();
setMessages((prev) => [...prev, { kind: "system", content: `Session ${payload.status}` }]);
setMessages(prev => [...prev, { kind: 'system', content: `Session ${payload.status}` }]);
}
break;
case "interrupt":
case 'interrupt':
removeLoading();
setMessages((prev) => [...prev, { kind: "system", content: "Session interrupted" }]);
setMessages(prev => [...prev, { kind: 'system', content: 'Session interrupted' }]);
break;
case "system":
case 'system':
return;
default: {
const raw = JSON.stringify(payload);
if (/Remote Control connecting/i.test(raw)) return;
setMessages((prev) => [...prev, { kind: "system", content: `${type}: ${truncate(raw, 200)}` }]);
setMessages(prev => [...prev, { kind: 'system', content: `${type}: ${truncate(raw, 200)}` }]);
}
}
};
function processReplayEvent(type: string, payload: EventPayload, direction: string, event: SessionEvent) {
switch (type) {
case "user": {
case 'user': {
const text = extractEventText(payload as Record<string, unknown>);
if (text) {
traceStateRef.current = clearActiveHost(traceStateRef.current);
setMessages((prev) => [...prev, { kind: "user", content: text }]);
setMessages(prev => [...prev, { kind: 'user', content: text }]);
}
break;
}
case "assistant": {
case 'assistant': {
const text = extractEventText(payload as Record<string, unknown>);
if (text && text.trim()) {
const result = addAssistantHost(traceStateRef.current, text);
traceStateRef.current = result.state;
setMessages((prev) => [
setMessages(prev => [
...prev,
{ kind: "assistant", content: text, traceEntries: [], traceExpanded: false, traceId: result.host.id },
{ kind: 'assistant', content: text, traceEntries: [], traceExpanded: false, traceId: result.host.id },
]);
}
break;
}
case "error":
setMessages((prev) => [...prev, { kind: "system", content: `Error: ${payload.message || "Unknown error"}` }]);
case 'error':
setMessages(prev => [...prev, { kind: 'system', content: `Error: ${payload.message || 'Unknown error'}` }]);
break;
case "session_status":
if (payload.status === "archived" || payload.status === "inactive") {
setMessages((prev) => [...prev, { kind: "system", content: `Session ${payload.status}` }]);
case 'session_status':
if (payload.status === 'archived' || payload.status === 'inactive') {
setMessages(prev => [...prev, { kind: 'system', content: `Session ${payload.status}` }]);
}
break;
}
}
function addToolTraceEntry(entryKind: "use" | "result", payload: Record<string, unknown>) {
function addToolTraceEntry(entryKind: 'use' | 'result', payload: Record<string, unknown>) {
const result = addTraceEntry(traceStateRef.current, entryKind);
traceStateRef.current = result.state;
const entry: TraceEntry = entryKind === "use"
? {
entryKind: "use",
toolName: (payload.tool_name as string) || (payload.name as string) || "tool",
toolInput: payload.tool_input || payload.input,
}
: {
entryKind: "result",
content: (payload.content as string) || "",
output: (payload.output as string) || (payload.content as string) || "",
isError: !!payload.is_error,
};
const entry: TraceEntry =
entryKind === 'use'
? {
entryKind: 'use',
toolName: (payload.tool_name as string) || (payload.name as string) || 'tool',
toolInput: payload.tool_input || payload.input,
}
: {
entryKind: 'result',
content: (payload.content as string) || '',
output: (payload.output as string) || (payload.content as string) || '',
isError: !!payload.is_error,
};
// Add entry to the last assistant message
setMessages((prev) => {
setMessages(prev => {
for (let i = prev.length - 1; i >= 0; i--) {
if (prev[i].kind === "assistant") {
if (prev[i].kind === 'assistant') {
const msg = prev[i] as AssistantMessage;
return [
...prev.slice(0, i),
{ ...msg, traceEntries: [...msg.traceEntries, entry] },
...prev.slice(i + 1),
];
return [...prev.slice(0, i), { ...msg, traceEntries: [...msg.traceEntries, entry] }, ...prev.slice(i + 1)];
}
}
return prev;
@@ -1045,20 +1098,20 @@ export function useEventProcessor() {
}
function getUserUuid(payload: EventPayload): string | null {
if (!payload || typeof payload !== "object") return null;
if (typeof payload.uuid === "string" && payload.uuid) return payload.uuid;
if (payload.raw && typeof payload.raw === "object" && typeof payload.raw.uuid === "string" && payload.raw.uuid) {
if (!payload || typeof payload !== 'object') return null;
if (typeof payload.uuid === 'string' && payload.uuid) return payload.uuid;
if (payload.raw && typeof payload.raw === 'object' && typeof payload.raw.uuid === 'string' && payload.raw.uuid) {
return payload.raw.uuid;
}
return null;
}
function getEmbeddedToolBlocks(payload: EventPayload, blockType: string): import("../types").ContentBlock[] {
if (!payload || typeof payload !== "object") return [];
function getEmbeddedToolBlocks(payload: EventPayload, blockType: string): import('../types').ContentBlock[] {
if (!payload || typeof payload !== 'object') return [];
const msg = payload.message as Record<string, unknown> | undefined;
if (!msg || typeof msg !== "object" || !Array.isArray(msg.content)) return [];
return (msg.content as import("../types").ContentBlock[]).filter(
(b) => b && typeof b === "object" && b.type === blockType,
if (!msg || typeof msg !== 'object' || !Array.isArray(msg.content)) return [];
return (msg.content as import('../types').ContentBlock[]).filter(
b => b && typeof b === 'object' && b.type === blockType,
);
}

View File

@@ -1,16 +1,11 @@
import { useState, useRef, useEffect } from "react";
import QRCode from "qrcode";
import QrScanner from "qr-scanner";
import { getUuid, setUuid } from "../api/client";
import { cn } from "../lib/utils";
import { Scan } from "lucide-react";
import { useTheme } from "../lib/theme";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "../../components/ui/dialog";
import { useState, useRef, useEffect } from 'react';
import QRCode from 'qrcode';
import QrScanner from 'qr-scanner';
import { getUuid, setUuid } from '../api/client';
import { cn } from '../lib/utils';
import { Scan } from 'lucide-react';
import { useTheme } from '../lib/theme';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../components/ui/dialog';
interface IdentityPanelProps {
open: boolean;
@@ -26,9 +21,8 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
const uuid = getUuid();
const { resolvedTheme } = useTheme();
const qrColors = resolvedTheme === "dark"
? { dark: "#ECE9E0", light: "#1C1B18" }
: { dark: "#141413", light: "#FDFCF8" };
const qrColors =
resolvedTheme === 'dark' ? { dark: '#ECE9E0', light: '#1C1B18' } : { dark: '#141413', light: '#FDFCF8' };
useEffect(() => {
if (!open) return;
@@ -41,7 +35,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
margin: 1,
color: qrColors,
}).catch((err: unknown) => {
console.error("QR generation failed:", err);
console.error('QR generation failed:', err);
});
});
return () => cancelAnimationFrame(rafId);
@@ -71,7 +65,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
try {
const scanner = new QrScanner(
videoRef.current,
(result) => {
result => {
handleScannedData(result.data);
},
{ returnDetailedScanResult: true },
@@ -79,7 +73,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
scannerRef.current = scanner;
await scanner.start();
} catch (e) {
console.error("Camera error:", e);
console.error('Camera error:', e);
setScanning(false);
}
};
@@ -101,8 +95,8 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
// Store ACP connection data and navigate to ACP direct connect view
stopCamera();
onClose();
sessionStorage.setItem("acp_connection", JSON.stringify({ url: parsed.url, token: parsed.token }));
window.location.href = "/code/?acp=1";
sessionStorage.setItem('acp_connection', JSON.stringify({ url: parsed.url, token: parsed.token }));
window.location.href = '/code/?acp=1';
return;
}
} catch {
@@ -112,7 +106,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
// Try URL with uuid param
try {
const url = new URL(data);
const importedUuid = url.searchParams.get("uuid");
const importedUuid = url.searchParams.get('uuid');
if (importedUuid) {
setUuid(importedUuid);
stopCamera();
@@ -133,10 +127,10 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
};
const handleScanUpload = () => {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.onchange = async (e) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = async e => {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
try {
@@ -145,14 +139,19 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
});
handleScannedData(result.data);
} catch {
alert("No QR code found in image");
alert('No QR code found in image');
}
};
input.click();
};
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
<Dialog
open={open}
onOpenChange={o => {
if (!o) onClose();
}}
>
<DialogContent className="max-w-sm rounded-2xl border-border bg-surface-1 p-6 shadow-2xl">
<DialogHeader>
<DialogTitle className="font-display text-lg font-semibold text-text-primary">Identity</DialogTitle>
@@ -170,7 +169,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
onClick={handleCopy}
className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
{copied ? "Copied!" : "Copy"}
{copied ? 'Copied!' : 'Copy'}
</button>
</div>
</div>
@@ -206,14 +205,14 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
<button
onClick={scanning ? stopCamera : startCamera}
className={cn(
"flex items-center gap-2 rounded-lg border px-4 py-2 text-sm transition-colors",
'flex items-center gap-2 rounded-lg border px-4 py-2 text-sm transition-colors',
scanning
? "border-status-error/30 text-status-error hover:bg-status-error/10"
: "border-border text-text-secondary hover:bg-surface-2",
? 'border-status-error/30 text-status-error hover:bg-status-error/10'
: 'border-border text-text-secondary hover:bg-surface-2',
)}
>
<Scan className="h-4 w-4" />
{scanning ? "Stop Camera" : "Scan with Camera"}
{scanning ? 'Stop Camera' : 'Scan with Camera'}
</button>
<button
onClick={handleScanUpload}

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useRef } from "react";
import { useState, useEffect, useRef } from 'react';
const SPINNER_FRAMES = ["·", "✢", "✱", "✶", "✻", "✽"];
const SPINNER_FRAMES = ['·', '✢', '✱', '✶', '✻', '✽'];
const SPINNER_CYCLE = [...SPINNER_FRAMES, ...SPINNER_FRAMES.slice().reverse()];
interface LoadingIndicatorProps {
@@ -8,7 +8,7 @@ interface LoadingIndicatorProps {
stalled?: boolean;
}
export function LoadingIndicator({ verb = "Thinking", stalled = false }: LoadingIndicatorProps) {
export function LoadingIndicator({ verb = 'Thinking', stalled = false }: LoadingIndicatorProps) {
const [frame, setFrame] = useState(0);
const [elapsed, setElapsed] = useState(0);
const startTimeRef = useRef(Date.now());
@@ -16,7 +16,7 @@ export function LoadingIndicator({ verb = "Thinking", stalled = false }: Loading
// Spinner animation — 120ms per frame
useEffect(() => {
const id = setInterval(() => {
setFrame((f) => (f + 1) % SPINNER_CYCLE.length);
setFrame(f => (f + 1) % SPINNER_CYCLE.length);
}, 120);
return () => clearInterval(id);
}, []);
@@ -34,7 +34,7 @@ export function LoadingIndicator({ verb = "Thinking", stalled = false }: Loading
<div className="flex items-center gap-2.5 py-2">
<span
className="text-xl leading-none min-w-[1.2em] transition-colors duration-2000"
style={{ color: stalled ? "var(--color-status-error)" : "var(--color-brand)" }}
style={{ color: stalled ? 'var(--color-status-error)' : 'var(--color-brand)' }}
>
{SPINNER_CYCLE[frame]}
</span>
@@ -44,9 +44,7 @@ export function LoadingIndicator({ verb = "Thinking", stalled = false }: Loading
>
{verb}
</span>
<span className="ml-auto text-xs font-mono text-text-muted">
{elapsed}s
</span>
<span className="ml-auto text-xs font-mono text-text-muted">{elapsed}s</span>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import { cn } from "../lib/utils";
import { ThemeToggle } from "../../components/ui/theme-toggle";
import { ChevronLeft, LayoutGrid, UserPlus, KeyRound } from "lucide-react";
import { cn } from '../lib/utils';
import { ThemeToggle } from '../../components/ui/theme-toggle';
import { ChevronLeft, LayoutGrid, UserPlus, KeyRound } from 'lucide-react';
interface NavbarProps {
onIdentityClick: () => void;
@@ -27,16 +27,18 @@ export function Navbar({ onIdentityClick, onTokenClick, activeTokenLabel, sessio
</button>
<span className="text-text-muted/40">/</span>
<span className="text-sm font-display font-medium text-text-primary truncate">{sessionTitle}</span>
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-[10px] font-medium text-brand flex-shrink-0">ACP</span>
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-[10px] font-medium text-brand flex-shrink-0">
ACP
</span>
</div>
) : (
/* Dashboard 页面 — 品牌 */
<a href="/code/" className="flex items-center gap-2 font-display text-lg font-semibold text-text-primary no-underline">
<a
href="/code/"
className="flex items-center gap-2 font-display text-lg font-semibold text-text-primary no-underline"
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true" className="flex-shrink-0">
<path
d="M10 1L12.2 7.8L19 10L12.2 12.2L10 19L7.8 12.2L1 10L7.8 7.8L10 1Z"
fill="var(--color-brand)"
/>
<path d="M10 1L12.2 7.8L19 10L12.2 12.2L10 19L7.8 12.2L1 10L7.8 7.8L10 1Z" fill="var(--color-brand)" />
</svg>
<span className="hidden sm:inline">Remote Control</span>
</a>
@@ -56,15 +58,15 @@ export function Navbar({ onIdentityClick, onTokenClick, activeTokenLabel, sessio
<button
onClick={onTokenClick}
className={cn(
"flex items-center gap-1 rounded-md px-2 sm:px-3 py-1.5 text-sm transition-colors",
'flex items-center gap-1 rounded-md px-2 sm:px-3 py-1.5 text-sm transition-colors',
activeTokenLabel
? "bg-brand/10 text-brand hover:bg-brand/20"
: "text-text-secondary hover:bg-surface-2 hover:text-text-primary"
? 'bg-brand/10 text-brand hover:bg-brand/20'
: 'text-text-secondary hover:bg-surface-2 hover:text-text-primary',
)}
title="Token Manager"
>
<KeyRound className="h-4 w-4" />
<span className="hidden sm:inline max-w-24 truncate">{activeTokenLabel || "No Token"}</span>
<span className="hidden sm:inline max-w-24 truncate">{activeTokenLabel || 'No Token'}</span>
</button>
<button
onClick={onIdentityClick}
@@ -82,20 +84,20 @@ export function Navbar({ onIdentityClick, onTokenClick, activeTokenLabel, sessio
export function StatusBadge({ status }: { status: string }) {
const colorMap: Record<string, string> = {
active: "bg-status-active/20 text-status-active",
running: "bg-status-running/20 text-status-running",
idle: "bg-status-idle/20 text-status-idle",
inactive: "bg-text-muted/20 text-text-muted",
requires_action: "bg-status-warning/20 text-status-warning",
archived: "bg-text-muted/20 text-text-muted",
error: "bg-status-error/20 text-status-error",
active: 'bg-status-active/20 text-status-active',
running: 'bg-status-running/20 text-status-running',
idle: 'bg-status-idle/20 text-status-idle',
inactive: 'bg-text-muted/20 text-text-muted',
requires_action: 'bg-status-warning/20 text-status-warning',
archived: 'bg-text-muted/20 text-text-muted',
error: 'bg-status-error/20 text-status-error',
};
return (
<span
className={cn(
"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",
colorMap[status] || "bg-surface-3 text-text-secondary",
'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
colorMap[status] || 'bg-surface-3 text-text-secondary',
)}
>
{status}

View File

@@ -1,13 +1,7 @@
import { useState, useEffect } from "react";
import type { Environment, Session } from "../types";
import { apiCreateSession } from "../api/client";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "../../components/ui/dialog";
import { useState, useEffect } from 'react';
import type { Environment, Session } from '../types';
import { apiCreateSession } from '../api/client';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '../../components/ui/dialog';
interface NewSessionDialogProps {
open: boolean;
@@ -17,22 +11,22 @@ interface NewSessionDialogProps {
}
export function NewSessionDialog({ open, environments, onClose, onCreated }: NewSessionDialogProps) {
const [title, setTitle] = useState("");
const [envId, setEnvId] = useState("");
const [error, setError] = useState("");
const [title, setTitle] = useState('');
const [envId, setEnvId] = useState('');
const [error, setError] = useState('');
const [creating, setCreating] = useState(false);
useEffect(() => {
if (open) {
setTitle("");
setEnvId("");
setError("");
setTitle('');
setEnvId('');
setError('');
}
}, [open]);
const handleCreate = async () => {
setCreating(true);
setError("");
setError('');
try {
const body: Record<string, string> = {};
if (title.trim()) body.title = title.trim();
@@ -40,14 +34,19 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
const session = await apiCreateSession(body);
onCreated(session);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to create session");
setError(err instanceof Error ? err.message : 'Failed to create session');
} finally {
setCreating(false);
}
};
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
<Dialog
open={open}
onOpenChange={o => {
if (!o) onClose();
}}
>
<DialogContent className="max-w-md rounded-2xl border-border bg-surface-1 p-6 shadow-2xl">
<DialogHeader>
<DialogTitle className="font-display text-lg font-semibold text-text-primary">New Session</DialogTitle>
@@ -59,7 +58,7 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
onChange={e => setTitle(e.target.value)}
placeholder="My session"
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
/>
@@ -69,13 +68,13 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
<label className="mb-1 block text-sm text-text-secondary">Environment</label>
<select
value={envId}
onChange={(e) => setEnvId(e.target.value)}
onChange={e => setEnvId(e.target.value)}
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-brand focus:outline-none"
>
<option value="">-- None --</option>
{environments.map((env) => (
{environments.map(env => (
<option key={env.id} value={env.id}>
{env.machine_name || env.id} ({env.branch || "no branch"})
{env.machine_name || env.id} ({env.branch || 'no branch'})
</option>
))}
</select>
@@ -96,7 +95,7 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
disabled={creating}
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light disabled:opacity-50 transition-colors"
>
{creating ? "Creating..." : "Create"}
{creating ? 'Creating...' : 'Create'}
</button>
</DialogFooter>
</DialogContent>

View File

@@ -1,7 +1,7 @@
import { useState } from "react";
import type { Question } from "../types";
import { esc, cn, truncate } from "../lib/utils";
import { TriangleAlert, Check } from "lucide-react";
import { useState } from 'react';
import type { Question } from '../types';
import { esc, cn, truncate } from '../lib/utils';
import { TriangleAlert, Check } from 'lucide-react';
// ============================================================
// PermissionPromptView — simple approve/reject for tool use
@@ -22,7 +22,7 @@ export function PermissionPromptView({
onApprove: () => void;
onReject: () => void;
}) {
const inputStr = typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput, null, 2);
const inputStr = typeof toolInput === 'string' ? toolInput : JSON.stringify(toolInput, null, 2);
return (
<div className="rounded-xl border border-warning-border/30 bg-surface-1 p-4">
@@ -34,7 +34,7 @@ export function PermissionPromptView({
</div>
{description && <div className="mb-2 text-sm text-text-secondary">{esc(description)}</div>}
<div className="mb-2 font-mono text-xs font-bold text-text-primary">{esc(toolName)}</div>
{toolName !== "AskUserQuestion" && (
{toolName !== 'AskUserQuestion' && (
<pre className="mb-3 max-h-40 overflow-auto rounded-lg bg-surface-1 p-2 text-xs text-text-secondary font-mono">
{truncate(inputStr, 500)}
</pre>
@@ -80,7 +80,7 @@ export function AskUserPanelView({
const handleSelect = (qIdx: number, oIdx: number, multiSelect: boolean) => {
if (multiSelect) {
const current = (answers[qIdx] as number[]) || [];
const next = current.includes(oIdx) ? current.filter((i) => i !== oIdx) : [...current, oIdx];
const next = current.includes(oIdx) ? current.filter(i => i !== oIdx) : [...current, oIdx];
setAnswers({ ...answers, [qIdx]: next });
} else {
setAnswers({ ...answers, [qIdx]: oIdx });
@@ -91,7 +91,7 @@ export function AskUserPanelView({
const text = otherTexts[qIdx]?.trim();
if (!text) return;
setAnswers({ ...answers, [qIdx]: text });
setOtherTexts({ ...otherTexts, [qIdx]: "" });
setOtherTexts({ ...otherTexts, [qIdx]: '' });
};
const handleSubmit = () => {
@@ -99,8 +99,8 @@ export function AskUserPanelView({
for (const [qIdx, val] of Object.entries(answers)) {
const q = questions[parseInt(qIdx, 10)];
if (!q) continue;
if (typeof val === "number") mapped[qIdx] = q.options?.[val]?.label || String(val);
else if (Array.isArray(val)) mapped[qIdx] = val.map((i) => q.options?.[i]?.label || String(i));
if (typeof val === 'number') mapped[qIdx] = q.options?.[val]?.label || String(val);
else if (Array.isArray(val)) mapped[qIdx] = val.map(i => q.options?.[i]?.label || String(i));
else mapped[qIdx] = val;
}
onSubmit(mapped);
@@ -114,22 +114,20 @@ export function AskUserPanelView({
return (
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
<div className="mb-3 text-sm font-semibold text-text-primary">
{esc(description || q.question || "Question")}
{esc(description || q.question || 'Question')}
</div>
<div className="space-y-2">
{(q.options || []).map((opt, j) => {
const isSelected = multiSelect
? ((answers[0] as number[]) || []).includes(j)
: answers[0] === j;
const isSelected = multiSelect ? ((answers[0] as number[]) || []).includes(j) : answers[0] === j;
return (
<button
key={j}
onClick={() => handleSelect(0, j, multiSelect)}
className={cn(
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
isSelected
? "border-brand bg-brand/10 text-text-primary"
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
? 'border-brand bg-brand/10 text-text-primary'
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
)}
>
<div className="font-medium">{esc(opt.label)}</div>
@@ -140,20 +138,33 @@ export function AskUserPanelView({
<div className="flex gap-2">
<input
type="text"
value={otherTexts[0] || ""}
onChange={(e) => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
value={otherTexts[0] || ''}
onChange={e => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
placeholder="Other..."
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
onKeyDown={(e) => e.key === "Enter" && handleOtherSubmit(0)}
onKeyDown={e => e.key === 'Enter' && handleOtherSubmit(0)}
/>
<button onClick={() => handleOtherSubmit(0)} className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">
<button
onClick={() => handleOtherSubmit(0)}
className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Send
</button>
</div>
</div>
<div className="mt-4 flex gap-2">
<button onClick={handleSubmit} className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors">Submit</button>
<button onClick={onSkip} className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">Skip</button>
<button
onClick={handleSubmit}
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors"
>
Submit
</button>
<button
onClick={onSkip}
className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Skip
</button>
</div>
</div>
);
@@ -164,15 +175,15 @@ export function AskUserPanelView({
return (
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || "Questions")}</div>
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || 'Questions')}</div>
<div className="mb-3 flex gap-1 overflow-x-auto">
{questions.map((q, i) => (
<button
key={i}
onClick={() => setActiveTab(i)}
className={cn(
"rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors",
activeTab === i ? "bg-brand/20 text-brand" : "text-text-muted hover:bg-surface-2",
'rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors',
activeTab === i ? 'bg-brand/20 text-brand' : 'text-text-muted hover:bg-surface-2',
)}
>
{q.header || `Q${i + 1}`}
@@ -193,10 +204,22 @@ export function AskUserPanelView({
)}
<div className="mt-4 flex items-center justify-between">
<span className="text-xs text-text-muted">{activeTab + 1} / {questions.length}</span>
<span className="text-xs text-text-muted">
{activeTab + 1} / {questions.length}
</span>
<div className="flex gap-2">
<button onClick={handleSubmit} className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors">Submit All</button>
<button onClick={onSkip} className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">Skip</button>
<button
onClick={handleSubmit}
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors"
>
Submit All
</button>
<button
onClick={onSkip}
className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Skip
</button>
</div>
</div>
</div>
@@ -204,7 +227,13 @@ export function AskUserPanelView({
}
function QuestionTab({
question, qIdx, answers, otherTexts, onSelect, onOtherTextChange, onOtherSubmit,
question,
qIdx,
answers,
otherTexts,
onSelect,
onOtherTextChange,
onOtherSubmit,
}: {
question: Question;
qIdx: number;
@@ -221,18 +250,16 @@ function QuestionTab({
<div className="mb-2 text-sm text-text-secondary">{esc(question.question)}</div>
<div className="space-y-2">
{(question.options || []).map((opt, j) => {
const isSelected = multiSelect
? ((answers[qIdx] as number[]) || []).includes(j)
: answers[qIdx] === j;
const isSelected = multiSelect ? ((answers[qIdx] as number[]) || []).includes(j) : answers[qIdx] === j;
return (
<button
key={j}
onClick={() => onSelect(qIdx, j, multiSelect)}
className={cn(
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
isSelected
? "border-brand bg-brand/10 text-text-primary"
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
? 'border-brand bg-brand/10 text-text-primary'
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
)}
>
<div className="font-medium">{esc(opt.label)}</div>
@@ -243,13 +270,18 @@ function QuestionTab({
<div className="flex gap-2">
<input
type="text"
value={otherTexts[qIdx] || ""}
onChange={(e) => onOtherTextChange(qIdx, e.target.value)}
value={otherTexts[qIdx] || ''}
onChange={e => onOtherTextChange(qIdx, e.target.value)}
placeholder="Other..."
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
onKeyDown={(e) => e.key === "Enter" && onOtherSubmit(qIdx)}
onKeyDown={e => e.key === 'Enter' && onOtherSubmit(qIdx)}
/>
<button onClick={() => onOtherSubmit(qIdx)} className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">Send</button>
<button
onClick={() => onOtherSubmit(qIdx)}
className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Send
</button>
</div>
</div>
</div>
@@ -271,12 +303,12 @@ export function PlanPanelView({
onSubmit: (value: string, feedback?: string) => void;
}) {
const [selected, setSelected] = useState<string | null>(null);
const [feedback, setFeedback] = useState("");
const [feedback, setFeedback] = useState('');
const isEmpty = !planContent || !planContent.trim();
const handleSubmit = () => {
if (!selected) return;
onSubmit(selected, selected === "no" ? feedback : undefined);
onSubmit(selected, selected === 'no' ? feedback : undefined);
};
return (
@@ -286,33 +318,49 @@ export function PlanPanelView({
<Check className="h-3 w-3" strokeWidth={2.5} />
</span>
<span className="text-sm font-semibold text-text-primary">
{isEmpty ? "Exit plan mode?" : "Ready to code?"}
{isEmpty ? 'Exit plan mode?' : 'Ready to code?'}
</span>
</div>
{!isEmpty && (
<div
className="mb-4 max-h-64 overflow-auto rounded-lg bg-tool-card p-4 text-sm text-text-secondary"
// biome-ignore lint/security/noDangerouslySetInnerHtml: content is sanitized by formatPlanContent
dangerouslySetInnerHTML={{ __html: formatPlanContent(planContent) }}
/>
)}
<div className="space-y-2">
{isEmpty ? (
<>
<PlanOption selected={selected === "yes-default"} onClick={() => setSelected("yes-default")} label="Yes" />
<PlanOption selected={selected === "no"} onClick={() => setSelected("no")} label="No" />
<PlanOption selected={selected === 'yes-default'} onClick={() => setSelected('yes-default')} label="Yes" />
<PlanOption selected={selected === 'no'} onClick={() => setSelected('no')} label="No" />
</>
) : (
<>
<PlanOption selected={selected === "yes-accept-edits"} onClick={() => setSelected("yes-accept-edits")} label="Yes, auto-accept edits" desc="Approve plan and auto-accept file edits" />
<PlanOption selected={selected === "yes-default"} onClick={() => setSelected("yes-default")} label="Yes, manually approve edits" desc="Approve plan but confirm each edit" />
<PlanOption selected={selected === "no"} onClick={() => setSelected("no")} label="No, keep planning" desc="Provide feedback to refine the plan" />
<PlanOption
selected={selected === 'yes-accept-edits'}
onClick={() => setSelected('yes-accept-edits')}
label="Yes, auto-accept edits"
desc="Approve plan and auto-accept file edits"
/>
<PlanOption
selected={selected === 'yes-default'}
onClick={() => setSelected('yes-default')}
label="Yes, manually approve edits"
desc="Approve plan but confirm each edit"
/>
<PlanOption
selected={selected === 'no'}
onClick={() => setSelected('no')}
label="No, keep planning"
desc="Provide feedback to refine the plan"
/>
</>
)}
</div>
{selected === "no" && (
{selected === 'no' && (
<textarea
value={feedback}
onChange={(e) => setFeedback(e.target.value)}
onChange={e => setFeedback(e.target.value)}
placeholder="Tell Claude what to change..."
className="mt-3 w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
rows={3}
@@ -331,21 +379,35 @@ export function PlanPanelView({
);
}
function PlanOption({ selected, onClick, label, desc }: { selected: boolean; onClick: () => void; label: string; desc?: string }) {
function PlanOption({
selected,
onClick,
label,
desc,
}: {
selected: boolean;
onClick: () => void;
label: string;
desc?: string;
}) {
return (
<button
onClick={onClick}
className={cn(
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
selected ? "border-brand bg-brand/10 text-text-primary" : "border-border bg-surface-2 text-text-secondary hover:border-border-light",
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
selected
? 'border-brand bg-brand/10 text-text-primary'
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
)}
>
<div className="flex items-center gap-2">
<span className={cn(
"flex h-4 w-4 items-center justify-center rounded-full border text-[10px] transition-colors",
selected ? "border-brand bg-brand text-white" : "border-border",
)}>
{selected && "\u2713"}
<span
className={cn(
'flex h-4 w-4 items-center justify-center rounded-full border text-[10px] transition-colors',
selected ? 'border-brand bg-brand text-white' : 'border-border',
)}
>
{selected && '\u2713'}
</span>
<span className="font-medium">{label}</span>
</div>
@@ -356,10 +418,12 @@ function PlanOption({ selected, onClick, label, desc }: { selected: boolean; onC
function formatPlanContent(content: string): string {
let html = esc(content);
html = html.replace(/```(\w*)\n?([\s\S]*?)```/g, (_, _l, code) =>
`<pre class="my-2 overflow-x-auto rounded-lg bg-tool-card p-3 font-mono text-xs">${code.trim()}</pre>`
html = html.replace(
/```(\w*)\n?([\s\S]*?)```/g,
(_, _l, code) =>
`<pre class="my-2 overflow-x-auto rounded-lg bg-tool-card p-3 font-mono text-xs">${code.trim()}</pre>`,
);
html = html.replace(/`([^`]+)`/g, '<code class="rounded bg-tool-card px-1.5 py-0.5 font-mono text-xs">$1</code>');
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
return html;
}

View File

@@ -1,6 +1,6 @@
import type { Session } from "../types";
import { StatusBadge } from "./Navbar";
import { esc, formatTime } from "../lib/utils";
import type { Session } from '../types';
import { StatusBadge } from './Navbar';
import { esc, formatTime } from '../lib/utils';
interface SessionListProps {
sessions: Session[];
@@ -10,9 +10,7 @@ interface SessionListProps {
export function SessionList({ sessions, onSelect }: SessionListProps) {
if (!sessions || sessions.length === 0) {
return (
<div className="rounded-xl border border-border bg-surface-1 p-8 text-center text-text-muted">
No sessions
</div>
<div className="rounded-xl border border-border bg-surface-1 p-8 text-center text-text-muted">No sessions</div>
);
}
@@ -20,7 +18,7 @@ export function SessionList({ sessions, onSelect }: SessionListProps) {
return (
<div className="space-y-2">
{sorted.map((session) => (
{sorted.map(session => (
<button
key={session.id}
type="button"
@@ -29,22 +27,16 @@ export function SessionList({ sessions, onSelect }: SessionListProps) {
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate font-medium text-text-primary">
{session.title || session.id}
</span>
{session.source === "acp" && (
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-xs font-medium text-brand">
ACP
</span>
<span className="truncate font-medium text-text-primary">{session.title || session.id}</span>
{session.source === 'acp' && (
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-xs font-medium text-brand">ACP</span>
)}
</div>
<div className="truncate text-xs text-text-muted">{session.id}</div>
</div>
<div className="flex items-center gap-3">
<StatusBadge status={session.status} />
<span className="text-xs text-text-muted">
{formatTime(session.created_at || session.updated_at)}
</span>
<span className="text-xs text-text-muted">{formatTime(session.created_at || session.updated_at)}</span>
</div>
</button>
))}

View File

@@ -1,9 +1,4 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "../../components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../components/ui/dialog';
interface TaskPanelProps {
onClose: () => void;
@@ -11,7 +6,12 @@ interface TaskPanelProps {
export function TaskPanel({ onClose }: TaskPanelProps) {
return (
<Dialog open={true} onOpenChange={(o) => { if (!o) onClose(); }}>
<Dialog
open={true}
onOpenChange={o => {
if (!o) onClose();
}}
>
<DialogContent
showCloseButton={false}
className="fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-80 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-sm"

View File

@@ -1,13 +1,7 @@
import { useState } from "react";
import type { TokenEntry } from "../hooks/useTokens";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "../../components/ui/dialog";
import { Check, Copy, Eye, EyeOff, Pencil, Plus, Trash2, X } from "lucide-react";
import { useState } from 'react';
import type { TokenEntry } from '../hooks/useTokens';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../../components/ui/dialog';
import { Check, Copy, Eye, EyeOff, Pencil, Plus, Trash2, X } from 'lucide-react';
interface TokenManagerDialogProps {
open: boolean;
@@ -30,11 +24,11 @@ export function TokenManagerDialog({
onRemove,
onUpdate,
}: TokenManagerDialogProps) {
const [newToken, setNewToken] = useState("");
const [newLabel, setNewLabel] = useState("");
const [addError, setAddError] = useState("");
const [newToken, setNewToken] = useState('');
const [newLabel, setNewLabel] = useState('');
const [addError, setAddError] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [editLabel, setEditLabel] = useState("");
const [editLabel, setEditLabel] = useState('');
const [visibleTokenId, setVisibleTokenId] = useState<string | null>(null);
const [copiedId, setCopiedId] = useState<string | null>(null);
@@ -51,9 +45,9 @@ export function TokenManagerDialog({
setAddError(error);
return;
}
setNewToken("");
setNewLabel("");
setAddError("");
setNewToken('');
setNewLabel('');
setAddError('');
};
const handleStartEdit = (entry: TokenEntry) => {
@@ -62,7 +56,7 @@ export function TokenManagerDialog({
};
const handleSaveEdit = (id: string) => {
onUpdate(id, editLabel.trim() || "Unnamed");
onUpdate(id, editLabel.trim() || 'Unnamed');
setEditingId(null);
};
@@ -72,12 +66,15 @@ export function TokenManagerDialog({
};
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
<Dialog
open={open}
onOpenChange={o => {
if (!o) onClose();
}}
>
<DialogContent className="max-w-md rounded-2xl border-border bg-surface-1 p-6 shadow-2xl">
<DialogHeader>
<DialogTitle className="font-display text-lg font-semibold text-text-primary">
Token Manager
</DialogTitle>
<DialogTitle className="font-display text-lg font-semibold text-text-primary">Token Manager</DialogTitle>
<DialogDescription className="text-sm text-text-muted">
Manage API tokens for RCS authentication.
</DialogDescription>
@@ -85,16 +82,16 @@ export function TokenManagerDialog({
{/* Token list */}
<div className="space-y-1 max-h-64 overflow-y-auto">
{tokens.map((entry) => (
{tokens.map(entry => (
<div key={entry.id} className="group flex items-center gap-1">
{editingId === entry.id ? (
<div className="flex flex-1 items-center gap-2 rounded-lg bg-surface-2 px-3 py-1.5">
<input
value={editLabel}
onChange={(e) => setEditLabel(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleSaveEdit(entry.id);
if (e.key === "Escape") setEditingId(null);
onChange={e => setEditLabel(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') handleSaveEdit(entry.id);
if (e.key === 'Escape') setEditingId(null);
}}
className="flex-1 rounded border border-border bg-surface-1 px-2 py-1 text-sm text-text-primary focus:border-brand focus:outline-none"
autoFocus
@@ -117,17 +114,13 @@ export function TokenManagerDialog({
<button
onClick={() => handleSwitch(entry.id)}
className={`flex flex-1 items-center justify-between rounded-lg px-3 py-2 text-sm transition-colors ${
activeTokenId === entry.id
? "bg-brand/10 text-brand"
: "text-text-secondary hover:bg-surface-2"
activeTokenId === entry.id ? 'bg-brand/10 text-brand' : 'text-text-secondary hover:bg-surface-2'
}`}
>
<div className="flex flex-col items-start min-w-0">
<span className="font-medium truncate w-full">{entry.label}</span>
<span className="text-xs text-text-muted font-mono">
{visibleTokenId === entry.id
? entry.token
: `${entry.token.slice(0, 6)}${"\u2022".repeat(6)}`}
{visibleTokenId === entry.id ? entry.token : `${entry.token.slice(0, 6)}${'\u2022'.repeat(6)}`}
</span>
</div>
{activeTokenId === entry.id && <Check className="h-4 w-4 flex-shrink-0" />}
@@ -144,7 +137,11 @@ export function TokenManagerDialog({
className="rounded p-1 text-text-muted opacity-0 group-hover:opacity-100 hover:text-text-primary transition-all"
title="Copy token"
>
{copiedId === entry.id ? <Check className="h-3.5 w-3.5 text-status-active" /> : <Copy className="h-3.5 w-3.5" />}
{copiedId === entry.id ? (
<Check className="h-3.5 w-3.5 text-status-active" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</button>
<button
onClick={() => handleStartEdit(entry)}
@@ -166,9 +163,7 @@ export function TokenManagerDialog({
))}
{tokens.length === 0 && (
<div className="py-4 text-center text-sm text-text-muted">
No tokens saved yet. Add one below.
</div>
<div className="py-4 text-center text-sm text-text-muted">No tokens saved yet. Add one below.</div>
)}
</div>
@@ -179,25 +174,25 @@ export function TokenManagerDialog({
<input
type="text"
value={newToken}
onChange={(e) => {
onChange={e => {
setNewToken(e.target.value);
setAddError("");
setAddError('');
}}
placeholder="API Token"
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none font-mono"
onKeyDown={(e) => {
if (e.key === "Enter") handleAdd();
onKeyDown={e => {
if (e.key === 'Enter') handleAdd();
}}
/>
<div className="flex gap-2">
<input
type="text"
value={newLabel}
onChange={(e) => setNewLabel(e.target.value)}
onChange={e => setNewLabel(e.target.value)}
placeholder="Label (optional)"
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
onKeyDown={(e) => {
if (e.key === "Enter") handleAdd();
onKeyDown={e => {
if (e.key === 'Enter') handleAdd();
}}
/>
<button

View File

@@ -1,3 +1,8 @@
export { useModels, type UseModelsResult } from "./useModels";
export { useCommands, type UseCommandsResult } from "./useCommands";
export { useQRScanner, type QRCodeData, type UseQRScannerOptions, type UseQRScannerResult } from "./useQRScanner";
export { useModels, type UseModelsResult } from './useModels'
export { useCommands, type UseCommandsResult } from './useCommands'
export {
useQRScanner,
type QRCodeData,
type UseQRScannerOptions,
type UseQRScannerResult,
} from './useQRScanner'

View File

@@ -1,12 +1,12 @@
import { useState, useCallback } from "react";
import { getUuid, setUuid } from "../api/client";
import { useState, useCallback } from 'react'
import { getUuid, setUuid } from '../api/client'
export function useAuth() {
const [uuid] = useState(() => getUuid());
const [uuid] = useState(() => getUuid())
const importUuid = useCallback((newUuid: string) => {
setUuid(newUuid);
}, []);
setUuid(newUuid)
}, [])
return { uuid, importUuid };
return { uuid, importUuid }
}

View File

@@ -1,12 +1,12 @@
import { useState, useEffect, useMemo } from "react";
import type { ACPClient } from "../acp/client";
import type { AvailableCommand } from "../acp/types";
import { useState, useEffect, useMemo } from 'react'
import type { ACPClient } from '../acp/client'
import type { AvailableCommand } from '../acp/types'
export interface UseCommandsResult {
/** List of available slash commands from the agent */
commands: AvailableCommand[];
commands: AvailableCommand[]
/** Whether any commands are available */
hasCommands: boolean;
hasCommands: boolean
}
/**
@@ -16,24 +16,21 @@ export interface UseCommandsResult {
export function useCommands(client: ACPClient): UseCommandsResult {
const [commands, setCommands] = useState<AvailableCommand[]>(
client.availableCommands,
);
)
useEffect(() => {
const handleCommandsChanged = (newCommands: AvailableCommand[]) => {
setCommands(newCommands);
};
setCommands(newCommands)
}
client.setAvailableCommandsChangedHandler(handleCommandsChanged);
client.setAvailableCommandsChangedHandler(handleCommandsChanged)
return () => {
client.setAvailableCommandsChangedHandler(() => {});
};
}, [client]);
client.setAvailableCommandsChangedHandler(() => {})
}
}, [client])
const hasCommands = useMemo(
() => commands.length > 0,
[commands],
);
const hasCommands = useMemo(() => commands.length > 0, [commands])
return { commands, hasCommands };
return { commands, hasCommands }
}

View File

@@ -1,20 +1,20 @@
import { useState, useEffect, useMemo, useCallback } from "react";
import type { ACPClient } from "../acp/client";
import type { ModelInfo, SessionModelState } from "../acp/types";
import { useState, useEffect, useMemo, useCallback } from 'react'
import type { ACPClient } from '../acp/client'
import type { ModelInfo, SessionModelState } from '../acp/types'
export interface UseModelsResult {
/** Whether model selection is supported by the current agent */
supportsModelSelection: boolean;
supportsModelSelection: boolean
/** List of available models */
availableModels: ModelInfo[];
availableModels: ModelInfo[]
/** The currently selected model ID */
currentModelId: string | null;
currentModelId: string | null
/** The currently selected model info */
currentModel: ModelInfo | null;
currentModel: ModelInfo | null
/** Set the model for the current session */
setModel: (modelId: string) => Promise<void>;
setModel: (modelId: string) => Promise<void>
/** Whether a model change is in progress */
isLoading: boolean;
isLoading: boolean
}
/**
@@ -27,78 +27,81 @@ export interface UseModelsResult {
*/
export function useModels(client: ACPClient): UseModelsResult {
const [modelState, setModelState] = useState<SessionModelState | null>(
client.modelState
);
const [isLoading, setIsLoading] = useState(false);
client.modelState,
)
const [isLoading, setIsLoading] = useState(false)
// Subscribe to model state changes (session created/destroyed)
// This replaces the previous 500ms polling approach
useEffect(() => {
// Handler for when model state changes (session created or disconnected)
const handleModelStateChanged = (state: SessionModelState | null) => {
setModelState(state);
setModelState(state)
// Auto-restore previously selected model when a new session is created
if (state && state.availableModels.length > 0) {
const saved = localStorage.getItem("acp_model_id");
if (saved && saved !== state.currentModelId && state.availableModels.some((m) => m.modelId === saved)) {
client.setSessionModel(saved).catch(() => {});
const saved = localStorage.getItem('acp_model_id')
if (
saved &&
saved !== state.currentModelId &&
state.availableModels.some(m => m.modelId === saved)
) {
client.setSessionModel(saved).catch(() => {})
}
}
};
}
// Handler for when current model changes within a session
const handleModelChanged = (modelId: string) => {
setModelState((prev) => {
if (!prev) return null;
setModelState(prev => {
if (!prev) return null
return {
...prev,
currentModelId: modelId,
};
});
setIsLoading(false);
};
}
})
setIsLoading(false)
}
// Register handlers - setModelStateChangedHandler immediately calls with current state
client.setModelStateChangedHandler(handleModelStateChanged);
client.setModelChangedHandler(handleModelChanged);
client.setModelStateChangedHandler(handleModelStateChanged)
client.setModelChangedHandler(handleModelChanged)
return () => {
// Clear handlers on unmount
client.setModelStateChangedHandler(() => {});
client.setModelChangedHandler(() => {});
};
}, [client]);
client.setModelStateChangedHandler(() => {})
client.setModelChangedHandler(() => {})
}
}, [client])
const availableModels = useMemo(
() => modelState?.availableModels ?? [],
[modelState]
);
[modelState],
)
const currentModelId = modelState?.currentModelId ?? null;
const currentModelId = modelState?.currentModelId ?? null
const currentModel = useMemo(
() =>
availableModels.find((m) => m.modelId === currentModelId) ?? null,
[availableModels, currentModelId]
);
() => availableModels.find(m => m.modelId === currentModelId) ?? null,
[availableModels, currentModelId],
)
const setModel = useCallback(
async (modelId: string) => {
if (!modelState) {
throw new Error("Model selection not supported");
throw new Error('Model selection not supported')
}
setIsLoading(true);
setIsLoading(true)
try {
await client.setSessionModel(modelId);
localStorage.setItem("acp_model_id", modelId);
await client.setSessionModel(modelId)
localStorage.setItem('acp_model_id', modelId)
// The model_changed event will update the state
} catch (error) {
setIsLoading(false);
throw error;
setIsLoading(false)
throw error
}
},
[client, modelState]
);
[client, modelState],
)
return {
supportsModelSelection: modelState !== null && availableModels.length > 0,
@@ -107,5 +110,5 @@ export function useModels(client: ACPClient): UseModelsResult {
currentModel,
setModel,
isLoading,
};
}
}

View File

@@ -1,30 +1,30 @@
import { useState, useEffect, useRef, useCallback } from "react";
import QrScanner from "qr-scanner";
import { useState, useEffect, useRef, useCallback } from 'react'
import QrScanner from 'qr-scanner'
/** QR code data format for scanning */
export interface QRCodeData {
url: string;
token: string;
url: string
token: string
}
export interface UseQRScannerOptions {
/** Called when a valid QR code is scanned */
onScan: (data: QRCodeData) => void;
onScan: (data: QRCodeData) => void
/** Called when an error occurs */
onError?: (error: string) => void;
onError?: (error: string) => void
}
export interface UseQRScannerResult {
/** Whether the scanner is currently active */
isScanning: boolean;
isScanning: boolean
/** Ref to attach to the video element */
videoRef: React.RefObject<HTMLVideoElement | null>;
videoRef: React.RefObject<HTMLVideoElement | null>
/** Start scanning */
startScanning: () => void;
startScanning: () => void
/** Stop scanning */
stopScanning: () => void;
stopScanning: () => void
/** Scan QR code from a file (e.g., from photo album) */
scanFromFile: (file: File) => Promise<void>;
scanFromFile: (file: File) => Promise<void>
}
/**
@@ -35,74 +35,74 @@ export function useQRScanner({
onScan,
onError,
}: UseQRScannerOptions): UseQRScannerResult {
const [isScanning, setIsScanning] = useState(false);
const videoRef = useRef<HTMLVideoElement | null>(null);
const qrScannerRef = useRef<QrScanner | null>(null);
const [isScanning, setIsScanning] = useState(false)
const videoRef = useRef<HTMLVideoElement | null>(null)
const qrScannerRef = useRef<QrScanner | null>(null)
// Store callbacks in refs to avoid re-creating scanner when callbacks change
// This allows callers to pass inline functions without causing re-renders
const onScanRef = useRef(onScan);
const onErrorRef = useRef(onError);
const onScanRef = useRef(onScan)
const onErrorRef = useRef(onError)
// Keep refs up to date
useEffect(() => {
onScanRef.current = onScan;
onErrorRef.current = onError;
}, [onScan, onError]);
onScanRef.current = onScan
onErrorRef.current = onError
}, [onScan, onError])
const startScanning = useCallback(() => {
setIsScanning(true);
}, []);
setIsScanning(true)
}, [])
const stopScanning = useCallback(() => {
if (qrScannerRef.current) {
qrScannerRef.current.stop();
qrScannerRef.current.destroy();
qrScannerRef.current = null;
qrScannerRef.current.stop()
qrScannerRef.current.destroy()
qrScannerRef.current = null
}
setIsScanning(false);
}, []);
setIsScanning(false)
}, [])
// Scan QR code from a file (photo album)
const scanFromFile = useCallback(async (file: File) => {
try {
const result = await QrScanner.scanImage(file, {
returnDetailedScanResult: true,
});
})
const data = JSON.parse(result.data) as QRCodeData;
const data = JSON.parse(result.data) as QRCodeData
if (data.url && data.token) {
onScanRef.current(data);
onScanRef.current(data)
} else {
onErrorRef.current?.("Invalid QR code: missing url or token");
onErrorRef.current?.('Invalid QR code: missing url or token')
}
} catch (e) {
const message = e instanceof Error ? e.message : "No QR code found";
onErrorRef.current?.(message);
const message = e instanceof Error ? e.message : 'No QR code found'
onErrorRef.current?.(message)
}
}, []);
}, [])
// Initialize scanner when isScanning becomes true
useEffect(() => {
if (!isScanning || !videoRef.current) return;
if (!isScanning || !videoRef.current) return
let isCancelled = false;
let scanner: QrScanner | null = null;
let isCancelled = false
let scanner: QrScanner | null = null
const initScanner = async () => {
try {
const newScanner = new QrScanner(
videoRef.current!,
(result) => {
result => {
try {
const data = JSON.parse(result.data) as QRCodeData;
const data = JSON.parse(result.data) as QRCodeData
if (data.url && data.token) {
// Stop scanning and notify
newScanner.stop();
newScanner.destroy();
qrScannerRef.current = null;
setIsScanning(false);
onScanRef.current(data);
newScanner.stop()
newScanner.destroy()
qrScannerRef.current = null
setIsScanning(false)
onScanRef.current(data)
}
} catch {
// Not valid JSON, ignore
@@ -112,46 +112,46 @@ export function useQRScanner({
returnDetailedScanResult: true,
highlightScanRegion: true,
highlightCodeOutline: true,
}
);
},
)
if (isCancelled) {
newScanner.destroy();
return;
newScanner.destroy()
return
}
scanner = newScanner;
qrScannerRef.current = newScanner;
await newScanner.start();
scanner = newScanner
qrScannerRef.current = newScanner
await newScanner.start()
if (isCancelled) {
newScanner.stop();
newScanner.destroy();
qrScannerRef.current = null;
newScanner.stop()
newScanner.destroy()
qrScannerRef.current = null
}
} catch (e) {
if (!isCancelled) {
onErrorRef.current?.(`Camera error: ${(e as Error).message}`);
setIsScanning(false);
onErrorRef.current?.(`Camera error: ${(e as Error).message}`)
setIsScanning(false)
}
}
};
}
initScanner();
initScanner()
return () => {
isCancelled = true;
isCancelled = true
if (scanner) {
scanner.stop();
scanner.destroy();
scanner.stop()
scanner.destroy()
}
if (qrScannerRef.current) {
qrScannerRef.current.stop();
qrScannerRef.current.destroy();
qrScannerRef.current = null;
qrScannerRef.current.stop()
qrScannerRef.current.destroy()
qrScannerRef.current = null
}
};
}, [isScanning]); // Only depend on isScanning, callbacks are accessed via refs
}
}, [isScanning]) // Only depend on isScanning, callbacks are accessed via refs
return {
isScanning,
@@ -159,5 +159,5 @@ export function useQRScanner({
startScanning,
stopScanning,
scanFromFile,
};
}
}

View File

@@ -1,25 +1,25 @@
import { useEffect, useRef, useCallback } from "react";
import { connectSSE, disconnectSSE } from "../api/sse";
import type { SessionEvent } from "../types";
import { useEffect, useRef, useCallback } from 'react'
import { connectSSE, disconnectSSE } from '../api/sse'
import type { SessionEvent } from '../types'
export function useSSE(
sessionId: string | null,
onEvent: (event: SessionEvent) => void,
) {
const onEventRef = useRef(onEvent);
onEventRef.current = onEvent;
const onEventRef = useRef(onEvent)
onEventRef.current = onEvent
const stableCallback = useCallback((event: SessionEvent) => {
onEventRef.current(event);
}, []);
onEventRef.current(event)
}, [])
useEffect(() => {
if (!sessionId) return;
if (!sessionId) return
connectSSE(sessionId, stableCallback);
connectSSE(sessionId, stableCallback)
return () => {
disconnectSSE();
};
}, [sessionId, stableCallback]);
disconnectSSE()
}
}, [sessionId, stableCallback])
}

View File

@@ -1,110 +1,126 @@
import { useState, useCallback } from "react";
import { useState, useCallback } from 'react'
export interface TokenEntry {
id: string;
token: string;
label: string;
id: string
token: string
label: string
}
const TOKENS_KEY = "rcs_tokens";
const ACTIVE_TOKEN_KEY = "rcs_uuid";
const DEFAULT_ID = "__default__";
const TOKENS_KEY = 'rcs_tokens'
const ACTIVE_TOKEN_KEY = 'rcs_uuid'
const DEFAULT_ID = '__default__'
function generateId(): string {
return `tk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
return `tk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`
}
/** Ensure the existing rcs_uuid is present as the default token entry */
function ensureDefault(tokens: TokenEntry[]): TokenEntry[] {
if (tokens.some((t) => t.id === DEFAULT_ID)) return tokens;
let uuid: string | null = null;
if (tokens.some(t => t.id === DEFAULT_ID)) return tokens
let uuid: string | null = null
try {
uuid = localStorage.getItem("rcs_uuid");
uuid = localStorage.getItem('rcs_uuid')
} catch {
// ignore
}
if (!uuid) return tokens;
return [{ id: DEFAULT_ID, token: uuid, label: "Default" }, ...tokens];
if (!uuid) return tokens
return [{ id: DEFAULT_ID, token: uuid, label: 'Default' }, ...tokens]
}
function loadTokens(): TokenEntry[] {
let tokens: TokenEntry[] = [];
let tokens: TokenEntry[] = []
try {
const raw = localStorage.getItem(TOKENS_KEY);
const raw = localStorage.getItem(TOKENS_KEY)
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) tokens = parsed;
const parsed = JSON.parse(raw)
if (Array.isArray(parsed)) tokens = parsed
}
} catch {
// ignore
}
return ensureDefault(tokens);
return ensureDefault(tokens)
}
function loadActiveTokenId(tokens: TokenEntry[]): string {
// Try saved active token
try {
const saved = localStorage.getItem(ACTIVE_TOKEN_KEY);
if (saved && tokens.some((t) => t.id === saved)) return saved;
const saved = localStorage.getItem(ACTIVE_TOKEN_KEY)
if (saved && tokens.some(t => t.id === saved)) return saved
} catch {
// ignore
}
// Fall back to default (rcs_uuid) entry
const defaultEntry = tokens.find((t) => t.id === DEFAULT_ID);
if (defaultEntry) return defaultEntry.id;
const defaultEntry = tokens.find(t => t.id === DEFAULT_ID)
if (defaultEntry) return defaultEntry.id
// Fall back to first entry
return tokens[0]?.id ?? DEFAULT_ID;
return tokens[0]?.id ?? DEFAULT_ID
}
export function useTokens() {
const [tokens, setTokens] = useState<TokenEntry[]>(loadTokens);
const [activeTokenId, setActiveTokenIdState] = useState<string>(() => loadActiveTokenId(loadTokens()));
const [tokens, setTokens] = useState<TokenEntry[]>(loadTokens)
const [activeTokenId, setActiveTokenIdState] = useState<string>(() =>
loadActiveTokenId(loadTokens()),
)
const persistTokens = useCallback((next: TokenEntry[]) => {
setTokens(next);
setTokens(next)
try {
localStorage.setItem(TOKENS_KEY, JSON.stringify(next));
localStorage.setItem(TOKENS_KEY, JSON.stringify(next))
} catch {
// ignore
}
}, []);
}, [])
const setActiveTokenId = useCallback((id: string) => {
setActiveTokenIdState(id);
setActiveTokenIdState(id)
try {
localStorage.setItem(ACTIVE_TOKEN_KEY, id);
location.reload(); // Reload to ensure api client picks up new token from localStorage
localStorage.setItem(ACTIVE_TOKEN_KEY, id)
location.reload() // Reload to ensure api client picks up new token from localStorage
} catch {
// ignore
}
}, []);
}, [])
const addToken = useCallback((token: string, label: string): string | null => {
const trimmed = token.trim();
if (!trimmed) return "Token is required";
const entry: TokenEntry = { id: generateId(), token: trimmed, label: label.trim() || trimmed.slice(0, 8) };
const next = [...tokens, entry];
persistTokens(next);
return null;
}, [tokens, persistTokens]);
const addToken = useCallback(
(token: string, label: string): string | null => {
const trimmed = token.trim()
if (!trimmed) return 'Token is required'
const entry: TokenEntry = {
id: generateId(),
token: trimmed,
label: label.trim() || trimmed.slice(0, 8),
}
const next = [...tokens, entry]
persistTokens(next)
return null
},
[tokens, persistTokens],
)
const removeToken = useCallback((id: string) => {
if (id === DEFAULT_ID) return; // Cannot remove default
const next = tokens.filter((t) => t.id !== id);
persistTokens(next);
if (activeTokenId === id) {
setActiveTokenId(DEFAULT_ID);
}
}, [tokens, persistTokens, activeTokenId, setActiveTokenId]);
const removeToken = useCallback(
(id: string) => {
if (id === DEFAULT_ID) return // Cannot remove default
const next = tokens.filter(t => t.id !== id)
persistTokens(next)
if (activeTokenId === id) {
setActiveTokenId(DEFAULT_ID)
}
},
[tokens, persistTokens, activeTokenId, setActiveTokenId],
)
const updateToken = useCallback((id: string, label: string) => {
const next = tokens.map((t) => t.id === id ? { ...t, label } : t);
persistTokens(next);
}, [tokens, persistTokens]);
const updateToken = useCallback(
(id: string, label: string) => {
const next = tokens.map(t => (t.id === id ? { ...t, label } : t))
persistTokens(next)
},
[tokens, persistTokens],
)
const activeToken = tokens.find((t) => t.id === activeTokenId) ?? tokens[0] ?? null;
const activeLabel = activeToken?.label ?? "Default";
const activeTokenValue = activeToken?.token ?? null;
const activeToken =
tokens.find(t => t.id === activeTokenId) ?? tokens[0] ?? null
const activeLabel = activeToken?.label ?? 'Default'
const activeTokenValue = activeToken?.token ?? null
return {
tokens,
@@ -116,5 +132,5 @@ export function useTokens() {
addToken,
removeToken,
updateToken,
};
}
}

View File

@@ -3,8 +3,6 @@
@import "tailwindcss";
/* ============================================================
Theme — Refined stone palette (warm gray, not beige)
Hue shifted from 85 (yellow-cream) to 65 (warm stone)
@@ -17,43 +15,43 @@
--font-mono: "JetBrains Mono", monospace;
/* Brand — signature orange (unchanged) */
--color-brand: #C96442;
--color-brand-light: #B55838;
--color-brand: #c96442;
--color-brand-light: #b55838;
--color-brand-subtle: oklch(0.65 0.12 30 / 0.08);
/* Surfaces — warm stone gray (not yellow-beige) */
--color-surface-0: #EFEEE9;
--color-surface-1: #F6F5F2;
--color-surface-2: #FBFAF8;
--color-surface-3: #DFDDD8;
--color-surface-0: #efeee9;
--color-surface-1: #f6f5f2;
--color-surface-2: #fbfaf8;
--color-surface-3: #dfddd8;
/* Text — warm near-black tones */
--color-text-primary: #1A1917;
--color-text-secondary: #5E5A54;
--color-text-primary: #1a1917;
--color-text-secondary: #5e5a54;
--color-text-muted: #969088;
/* Inverted — for user message bubbles */
--color-bg-inverted: #2C2A27;
--color-text-inverted: #F6F5F2;
--color-bg-inverted: #2c2a27;
--color-text-inverted: #f6f5f2;
/* User bubble — brand-tinted surface */
--color-user-bubble: #C96442;
--color-user-bubble-border: #B55838;
--color-user-bubble: #c96442;
--color-user-bubble-border: #b55838;
/* Warning — refined amber (less construction-zone) */
--color-warning-bg: oklch(0.96 0.02 85);
--color-warning-border: oklch(0.75 0.14 75);
--color-warning-text: oklch(0.40 0.08 60);
--color-warning-text: oklch(0.4 0.08 60);
/* Status */
--color-status-active: #5D8A3C;
--color-status-running: #3D72A8;
--color-status-idle: #7C3aed;
--color-status-error: #B83B31;
--color-status-warning: #B88630;
--color-status-active: #5d8a3c;
--color-status-running: #3d72a8;
--color-status-idle: #7c3aed;
--color-status-error: #b83b31;
--color-status-warning: #b88630;
/* Tool card */
--color-tool-card: #F6F5F2;
--color-tool-card: #f6f5f2;
/* shadcn/ui tokens (oklch — warm stone hue ~65) */
--color-background: oklch(0.955 0.006 65);
@@ -74,9 +72,9 @@
/* Border / Input / Ring */
--color-border: oklch(0.905 0.008 65);
--color-border-light: #DFDDD8;
--color-border-light: #dfddd8;
--color-input: oklch(0.905 0.008 65);
--color-ring: oklch(0.65 0.10 40);
--color-ring: oklch(0.65 0.1 40);
/* Default utility values */
--default-border-color: var(--color-border);
@@ -90,20 +88,20 @@
Dark mode — warm stone dark palette
============================================================ */
.dark {
--color-surface-0: #1A1917;
--color-surface-0: #1a1917;
--color-surface-1: #222120;
--color-surface-2: #2C2A28;
--color-surface-3: #3A3835;
--color-text-primary: #EFEEE9;
--color-surface-2: #2c2a28;
--color-surface-3: #3a3835;
--color-text-primary: #efeee9;
--color-text-secondary: #969088;
--color-text-muted: #5E5A54;
--color-bg-inverted: #F6F5F2;
--color-text-inverted: #2C2A28;
--color-user-bubble: #C96442;
--color-user-bubble-border: #B55838;
--color-border: #3A3835;
--color-border-light: #2C2A28;
--color-tool-card: #2C2A28;
--color-text-muted: #5e5a54;
--color-bg-inverted: #f6f5f2;
--color-text-inverted: #2c2a28;
--color-user-bubble: #c96442;
--color-user-bubble-border: #b55838;
--color-border: #3a3835;
--color-border-light: #2c2a28;
--color-tool-card: #2c2a28;
--color-warning-bg: oklch(0.22 0.03 75);
--color-warning-border: oklch(0.62 0.12 75);
--color-warning-text: oklch(0.82 0.08 85);
@@ -149,8 +147,13 @@
}
@keyframes glimmer-pulse {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
0%,
100% {
opacity: 0.5;
}
50% {
opacity: 1;
}
}
/* ============================================================
@@ -159,7 +162,7 @@
/* Chat input — warm orange focus ring */
.chat-input-focus:focus-within {
box-shadow: 0 0 0 2px oklch(0.65 0.12 30 / 0.20);
box-shadow: 0 0 0 2px oklch(0.65 0.12 30 / 0.2);
}
/* Markdown content in message bubbles */
@@ -190,9 +193,9 @@
*,
::before,
::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
animation-duration: 0.01ms;
animation-iteration-count: 1;
transition-duration: 0.01ms;
}
}
@@ -200,13 +203,27 @@
Animations — Anthropic entrance effects
============================================================ */
@keyframes fadeUp {
from { opacity: 0; transform: translateY(24px); }
to { opacity: 1; transform: translateY(0); }
from {
opacity: 0;
transform: translateY(24px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes typing-bounce {
0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
30% { transform: translateY(-5px); opacity: 1; }
0%,
60%,
100% {
transform: translateY(0);
opacity: 0.5;
}
30% {
transform: translateY(-5px);
opacity: 1;
}
}
/* Typing indicator dots */
@@ -223,5 +240,9 @@
background: var(--color-brand);
animation: typing-bounce 1.2s ease-in-out infinite;
}
.chat-typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
.chat-typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
.chat-typing-indicator span:nth-child(2) {
animation-delay: 0.2s;
}
.chat-typing-indicator span:nth-child(3) {
animation-delay: 0.4s;
}

View File

@@ -1,4 +1,4 @@
import type { SetStateAction } from "react";
import type { SetStateAction } from 'react'
import {
apiFetchSession,
apiFetchSessionHistory,
@@ -7,9 +7,9 @@ import {
apiSendControl,
apiInterrupt,
getUuid,
} from "../api/client";
import { generateMessageUuid } from "./utils";
import type { SessionEvent, EventPayload } from "../types";
} from '../api/client'
import { generateMessageUuid } from './utils'
import type { SessionEvent, EventPayload } from '../types'
import type {
ThreadEntry,
ToolCallData,
@@ -19,352 +19,405 @@ import type {
ToolCallEntry,
UserMessageImage,
PendingPermission,
} from "./types";
} from './types'
// SSE Event Bus — 复用自 rcs-transport.ts仅保留连接管理
type SSEEventHandler = (event: SessionEvent) => void;
type SSEEventHandler = (event: SessionEvent) => void
class SSEBus {
private listeners: Set<SSEEventHandler> = new Set();
private eventSource: EventSource | null = null;
private listeners: Set<SSEEventHandler> = new Set()
private eventSource: EventSource | null = null
onEvent(handler: SSEEventHandler): () => void {
this.listeners.add(handler);
return () => this.listeners.delete(handler);
this.listeners.add(handler)
return () => this.listeners.delete(handler)
}
connect(sessionId: string): void {
this.disconnect();
const uuid = getUuid();
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
const es = new EventSource(url);
this.eventSource = es;
this.disconnect()
const uuid = getUuid()
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`
const es = new EventSource(url)
this.eventSource = es
es.addEventListener("message", (e: MessageEvent) => {
es.addEventListener('message', (e: MessageEvent) => {
try {
const data = JSON.parse(e.data) as SessionEvent;
const data = JSON.parse(e.data) as SessionEvent
for (const handler of this.listeners) {
handler(data);
handler(data)
}
} catch {
// ignore parse errors
}
});
})
}
disconnect(): void {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
this.eventSource.close()
this.eventSource = null
}
}
}
// 全局 SSE bus 实例
export const sseBus = new SSEBus();
export const sseBus = new SSEBus()
// =============================================================================
// RCS Chat Adapter — 将 SSE 事件转为 ThreadEntry
// =============================================================================
function mapToolStatus(status: string): ToolCallStatus {
if (status === "completed") return "complete";
if (status === "failed") return "error";
return "running";
if (status === 'completed') return 'complete'
if (status === 'failed') return 'error'
return 'running'
}
function extractEventText(payload: EventPayload): string {
if (typeof payload.content === "string") return payload.content;
if (payload.message && typeof payload.message === "object") {
const msg = payload.message as Record<string, unknown>;
if (typeof msg.content === "string") return msg.content;
if (typeof payload.content === 'string') return payload.content
if (payload.message && typeof payload.message === 'object') {
const msg = payload.message as Record<string, unknown>
if (typeof msg.content === 'string') return msg.content
if (Array.isArray(msg.content)) {
return (msg.content as Array<Record<string, unknown>>)
.filter((b) => b.type === "text" && typeof b.text === "string")
.map((b) => b.text as string)
.join("");
.filter(b => b.type === 'text' && typeof b.text === 'string')
.map(b => b.text as string)
.join('')
}
}
return "";
return ''
}
function findToolCallIndex(entries: ThreadEntry[], toolCallId: string): number {
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
if (entry && entry.type === "tool_call" && entry.toolCall.id === toolCallId) {
return i;
const entry = entries[i]
if (
entry &&
entry.type === 'tool_call' &&
entry.toolCall.id === toolCallId
) {
return i
}
}
return -1;
return -1
}
export class RCSChatAdapter {
private sessionId: string;
private setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>;
private unsub: (() => void) | null = null;
private onStatusChange?: (status: string) => void;
private onError?: (error: string) => void;
private onPermissionRequest?: (permission: PendingPermission) => void;
private sessionId: string
private setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>
private unsub: (() => void) | null = null
private onStatusChange?: (status: string) => void
private onError?: (error: string) => void
private onPermissionRequest?: (permission: PendingPermission) => void
constructor(
sessionId: string,
setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>,
options?: {
onStatusChange?: (status: string) => void;
onError?: (error: string) => void;
onPermissionRequest?: (permission: PendingPermission) => void;
onStatusChange?: (status: string) => void
onError?: (error: string) => void
onPermissionRequest?: (permission: PendingPermission) => void
},
) {
this.sessionId = sessionId;
this.setEntries = setEntries;
this.onStatusChange = options?.onStatusChange;
this.onError = options?.onError;
this.onPermissionRequest = options?.onPermissionRequest;
this.sessionId = sessionId
this.setEntries = setEntries
this.onStatusChange = options?.onStatusChange
this.onError = options?.onError
this.onPermissionRequest = options?.onPermissionRequest
}
/** 初始化:绑定会话、加载历史、连接 SSE */
async init(): Promise<void> {
try {
await apiBind(this.sessionId);
await apiBind(this.sessionId)
} catch {
// may already be bound
}
await this.loadHistory();
this.connectSSE();
await this.loadHistory()
this.connectSSE()
}
/** 加载历史事件并转为 ThreadEntry */
async loadHistory(): Promise<void> {
const { events } = await apiFetchSessionHistory(this.sessionId);
if (!events || events.length === 0) return;
const { events } = await apiFetchSessionHistory(this.sessionId)
if (!events || events.length === 0) return
const historyEntries: ThreadEntry[] = [];
let currentAssistant: AssistantMessageEntry | null = null;
const historyEntries: ThreadEntry[] = []
let currentAssistant: AssistantMessageEntry | null = null
const flushAssistant = () => {
if (currentAssistant) {
historyEntries.push(currentAssistant);
currentAssistant = null;
historyEntries.push(currentAssistant)
currentAssistant = null
}
};
}
for (const event of events) {
const payload = event.payload || ({} as EventPayload);
const payload = event.payload || ({} as EventPayload)
if (event.type === "user") {
if (event.direction === "outbound") continue; // skip echoed user messages
flushAssistant();
const text = extractEventText(payload);
if (event.type === 'user') {
if (event.direction === 'outbound') continue // skip echoed user messages
flushAssistant()
const text = extractEventText(payload)
if (text) {
historyEntries.push({
type: "user_message",
type: 'user_message',
id: event.id || `hist-user-${historyEntries.length}`,
content: text,
});
})
}
} else if (event.type === "assistant") {
flushAssistant();
const text = extractEventText(payload);
const toolParts: ThreadEntry[] = [];
} else if (event.type === 'assistant') {
flushAssistant()
const text = extractEventText(payload)
const toolParts: ThreadEntry[] = []
const msg = payload.message as Record<string, unknown> | undefined;
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
const msg = payload.message as Record<string, unknown> | undefined
if (msg && typeof msg === 'object' && Array.isArray(msg.content)) {
for (const block of msg.content as Array<Record<string, unknown>>) {
if (block.type === "tool_use") {
if (block.type === 'tool_use') {
toolParts.push({
type: "tool_call",
type: 'tool_call',
toolCall: {
id: (block.id as string) || `hist-tool-${historyEntries.length}`,
title: (block.name as string) || "tool",
status: "complete",
id:
(block.id as string) ||
`hist-tool-${historyEntries.length}`,
title: (block.name as string) || 'tool',
status: 'complete',
rawInput: (block.input as Record<string, unknown>) || {},
},
});
})
}
}
}
if (text || toolParts.length > 0) {
currentAssistant = {
type: "assistant_message",
type: 'assistant_message',
id: event.id || `hist-asst-${historyEntries.length}`,
chunks: text ? [{ type: "message", text }] : [],
};
historyEntries.push(currentAssistant);
chunks: text ? [{ type: 'message', text }] : [],
}
historyEntries.push(currentAssistant)
// Push tool calls after assistant message
for (const tp of toolParts) {
historyEntries.push(tp);
historyEntries.push(tp)
}
currentAssistant = null; // Tool calls are separate entries
currentAssistant = null // Tool calls are separate entries
}
} else if (event.type === "tool_use") {
const p = payload as Record<string, unknown>;
} else if (event.type === 'tool_use') {
const p = payload as Record<string, unknown>
const tc: ToolCallEntry = {
type: "tool_call",
type: 'tool_call',
toolCall: {
id: (p.tool_call_id as string) || `hist-tool-${historyEntries.length}`,
title: (p.tool_name as string) || "tool",
status: "complete",
id:
(p.tool_call_id as string) ||
`hist-tool-${historyEntries.length}`,
title: (p.tool_name as string) || 'tool',
status: 'complete',
rawInput: (p.tool_input as Record<string, unknown>) || {},
},
};
historyEntries.push(tc);
} else if (event.type === "tool_result") {
const p = payload as Record<string, unknown>;
}
historyEntries.push(tc)
} else if (event.type === 'tool_result') {
const p = payload as Record<string, unknown>
// Find last tool call and update with output
const idx = findToolCallIndex(historyEntries, (p.tool_call_id as string) || "");
const idx = findToolCallIndex(
historyEntries,
(p.tool_call_id as string) || '',
)
if (idx >= 0) {
const entry = historyEntries[idx] as ToolCallEntry;
const entry = historyEntries[idx] as ToolCallEntry
historyEntries[idx] = {
type: "tool_call",
type: 'tool_call',
toolCall: {
...entry.toolCall,
rawOutput: { output: p.content || p.output || "" },
rawOutput: { output: p.content || p.output || '' },
},
};
}
}
}
}
flushAssistant();
this.setEntries(historyEntries);
flushAssistant()
this.setEntries(historyEntries)
}
/** 连接 SSE 事件流 */
connectSSE(): void {
sseBus.connect(this.sessionId);
this.unsub = sseBus.onEvent((event) => this.handleEvent(event));
sseBus.connect(this.sessionId)
this.unsub = sseBus.onEvent(event => this.handleEvent(event))
}
/** 断开 SSE */
disconnect(): void {
if (this.unsub) {
this.unsub();
this.unsub = null;
this.unsub()
this.unsub = null
}
sseBus.disconnect();
sseBus.disconnect()
}
/** 处理 SSE 事件 */
handleEvent(event: SessionEvent): void {
const type = event.type;
const payload = event.payload || ({} as EventPayload);
const type = event.type
const payload = event.payload || ({} as EventPayload)
// Skip bridge init noise
const serialized = JSON.stringify(event);
if (/Remote Control connecting/i.test(serialized)) return;
const serialized = JSON.stringify(event)
if (/Remote Control connecting/i.test(serialized)) return
switch (type) {
// ---- 助手消息 ----
case "assistant": {
const content = typeof payload.content === "string" ? payload.content : "";
this.setEntries((prev) => {
const lastEntry = prev[prev.length - 1];
case 'assistant': {
const content =
typeof payload.content === 'string' ? payload.content : ''
this.setEntries(prev => {
const lastEntry = prev[prev.length - 1]
// If last entry is AssistantMessage, append to it
if (lastEntry?.type === "assistant_message") {
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1];
if (lastChunk?.type === "message") {
if (lastEntry?.type === 'assistant_message') {
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1]
if (lastChunk?.type === 'message') {
return [
...prev.slice(0, -1),
{ ...lastEntry, chunks: [...lastEntry.chunks.slice(0, -1), { type: "message", text: lastChunk.text + content }] },
];
{
...lastEntry,
chunks: [
...lastEntry.chunks.slice(0, -1),
{ type: 'message', text: lastChunk.text + content },
],
},
]
}
return [
...prev.slice(0, -1),
{ ...lastEntry, chunks: [...lastEntry.chunks, { type: "message", text: content }] },
];
{
...lastEntry,
chunks: [
...lastEntry.chunks,
{ type: 'message', text: content },
],
},
]
}
// Create new AssistantMessage
if (content && content.trim()) {
const newEntry: AssistantMessageEntry = {
type: "assistant_message",
type: 'assistant_message',
id: `assistant-${Date.now()}`,
chunks: [{ type: "message", text: content }],
};
return [...prev, newEntry];
chunks: [{ type: 'message', text: content }],
}
return [...prev, newEntry]
}
return prev;
});
return prev
})
// Check for embedded tool_use blocks
const msg = payload.message as Record<string, unknown> | undefined;
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
const toolBlocks = (msg.content as Array<Record<string, unknown>>).filter((b) => b.type === "tool_use");
const msg = payload.message as Record<string, unknown> | undefined
if (msg && typeof msg === 'object' && Array.isArray(msg.content)) {
const toolBlocks = (
msg.content as Array<Record<string, unknown>>
).filter(b => b.type === 'tool_use')
for (const block of toolBlocks) {
const toolCallId = (block.id as string) || `call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
const toolCallId =
(block.id as string) ||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
const toolData: ToolCallData = {
id: toolCallId,
title: (block.name as string) || "tool",
status: "running",
title: (block.name as string) || 'tool',
status: 'running',
rawInput: (block.input as Record<string, unknown>) || {},
};
this.setEntries((prev) => [...prev, { type: "tool_call", toolCall: toolData }]);
}
this.setEntries(prev => [
...prev,
{ type: 'tool_call', toolCall: toolData },
])
}
}
break;
break
}
// ---- 工具调用 ----
case "tool_use": {
const p = payload as Record<string, unknown>;
const toolCallId = (p.tool_call_id as string) || `call-${Date.now()}`;
case 'tool_use': {
const p = payload as Record<string, unknown>
const toolCallId = (p.tool_call_id as string) || `call-${Date.now()}`
const toolData: ToolCallData = {
id: toolCallId,
title: (p.tool_name as string) || "tool",
status: "running",
title: (p.tool_name as string) || 'tool',
status: 'running',
rawInput: (p.tool_input as Record<string, unknown>) || {},
};
this.setEntries((prev) => [...prev, { type: "tool_call", toolCall: toolData }]);
break;
}
this.setEntries(prev => [
...prev,
{ type: 'tool_call', toolCall: toolData },
])
break
}
// ---- 工具结果 ----
case "tool_result": {
const p = payload as Record<string, unknown>;
const callId = (p.tool_call_id as string) || "";
this.setEntries((prev) => {
const idx = findToolCallIndex(prev, callId);
if (idx < 0) return prev;
const entry = prev[idx] as ToolCallEntry;
case 'tool_result': {
const p = payload as Record<string, unknown>
const callId = (p.tool_call_id as string) || ''
this.setEntries(prev => {
const idx = findToolCallIndex(prev, callId)
if (idx < 0) return prev
const entry = prev[idx] as ToolCallEntry
return prev.map((e, i) =>
i === idx
? { type: "tool_call", toolCall: { ...entry.toolCall, status: "complete" as ToolCallStatus, rawOutput: { output: p.content || p.output || "" } } }
? {
type: 'tool_call',
toolCall: {
...entry.toolCall,
status: 'complete' as ToolCallStatus,
rawOutput: { output: p.content || p.output || '' },
},
}
: e,
);
});
break;
)
})
break
}
// ---- 权限请求 ----
case "control_request":
case "permission_request": {
const req = payload.request as Record<string, unknown> | undefined;
if (req && req.subtype === "can_use_tool") {
const requestId = payload.request_id || "";
const toolName = (req.tool_name as string) || "unknown";
const toolInput = (req.input || req.tool_input || {}) as Record<string, unknown>;
const description = (req.description as string) || "";
case 'control_request':
case 'permission_request': {
const req = payload.request as Record<string, unknown> | undefined
if (req && req.subtype === 'can_use_tool') {
const requestId = payload.request_id || ''
const toolName = (req.tool_name as string) || 'unknown'
const toolInput = (req.input || req.tool_input || {}) as Record<
string,
unknown
>
const description = (req.description as string) || ''
// Update tool call status
this.setEntries((prev) => {
this.setEntries(prev => {
// Find matching tool call
const idx = [...prev].reverse().findIndex((e) => e.type === "tool_call");
const idx = [...prev]
.reverse()
.findIndex(e => e.type === 'tool_call')
if (idx >= 0) {
const realIdx = prev.length - 1 - idx;
const entry = prev[realIdx] as ToolCallEntry;
if (entry.toolCall.status === "running") {
const realIdx = prev.length - 1 - idx
const entry = prev[realIdx] as ToolCallEntry
if (entry.toolCall.status === 'running') {
return prev.map((e, i) =>
i === realIdx
? { type: "tool_call", toolCall: { ...entry.toolCall, status: "waiting_for_confirmation" as ToolCallStatus, permissionRequest: { requestId, options: [] } } }
? {
type: 'tool_call',
toolCall: {
...entry.toolCall,
status: 'waiting_for_confirmation' as ToolCallStatus,
permissionRequest: { requestId, options: [] },
},
}
: e,
);
)
}
}
return prev;
});
return prev
})
// Notify parent
this.onPermissionRequest?.({
@@ -372,102 +425,117 @@ export class RCSChatAdapter {
toolName,
toolInput,
description,
});
})
}
break;
break
}
// ---- 会话状态 ----
case "session_status": {
if (typeof payload.status === "string") {
this.onStatusChange?.(payload.status);
case 'session_status': {
if (typeof payload.status === 'string') {
this.onStatusChange?.(payload.status)
}
break;
break
}
// ---- 错误 ----
case "error": {
const errorMsg = String(payload.message || payload.content || "Unknown error");
this.onError?.(errorMsg);
break;
case 'error': {
const errorMsg = String(
payload.message || payload.content || 'Unknown error',
)
this.onError?.(errorMsg)
break
}
// ---- 忽略的事件类型 ----
case "partial_assistant":
case "result":
case "result_success":
case "control_response":
case "permission_response":
case "system":
case "task_state":
case "automation_state":
case "status":
break;
case 'partial_assistant':
case 'result':
case 'result_success':
case 'control_response':
case 'permission_response':
case 'system':
case 'task_state':
case 'automation_state':
case 'status':
break
}
}
/** 发送用户消息 */
async sendMessage(text: string, images?: UserMessageImage[]): Promise<void> {
if (!text.trim() && (!images || images.length === 0)) return;
if (!text.trim() && (!images || images.length === 0)) return
// Add user message to entries
const userEntry: UserMessageEntry = {
type: "user_message",
type: 'user_message',
id: `user-${Date.now()}`,
content: text,
images: images && images.length > 0 ? images : undefined,
};
this.setEntries((prev) => [...prev, userEntry]);
}
this.setEntries(prev => [...prev, userEntry])
// Send to backend
await apiSendEvent(this.sessionId, {
type: "user",
type: 'user',
uuid: generateMessageUuid(),
content: text,
message: { content: text },
});
})
}
/** 响应权限请求 */
async respondPermission(requestId: string, approved: boolean, extra?: Record<string, unknown>): Promise<void> {
async respondPermission(
requestId: string,
approved: boolean,
extra?: Record<string, unknown>,
): Promise<void> {
await apiSendControl(this.sessionId, {
type: "permission_response",
type: 'permission_response',
approved,
request_id: requestId,
...extra,
});
})
// Update tool call status
this.setEntries((prev) =>
prev.map((entry) => {
if (entry.type !== "tool_call") return entry;
if (entry.toolCall.permissionRequest?.requestId !== requestId) return entry;
this.setEntries(prev =>
prev.map(entry => {
if (entry.type !== 'tool_call') return entry
if (entry.toolCall.permissionRequest?.requestId !== requestId)
return entry
return {
type: "tool_call",
type: 'tool_call',
toolCall: {
...entry.toolCall,
status: approved ? "running" : ("rejected" as ToolCallStatus),
status: approved ? 'running' : ('rejected' as ToolCallStatus),
permissionRequest: undefined,
},
};
}
}),
);
)
}
/** 中断当前操作 */
async interrupt(): Promise<void> {
// Mark running tools as canceled
this.setEntries((prev) =>
prev.map((entry) => {
if (entry.type !== "tool_call") return entry;
if (entry.toolCall.status !== "running" && entry.toolCall.status !== "waiting_for_confirmation") return entry;
this.setEntries(prev =>
prev.map(entry => {
if (entry.type !== 'tool_call') return entry
if (
entry.toolCall.status !== 'running' &&
entry.toolCall.status !== 'waiting_for_confirmation'
)
return entry
return {
type: "tool_call",
toolCall: { ...entry.toolCall, status: "canceled" as ToolCallStatus, permissionRequest: undefined },
};
type: 'tool_call',
toolCall: {
...entry.toolCall,
status: 'canceled' as ToolCallStatus,
permissionRequest: undefined,
},
}
}),
);
)
await apiInterrupt(this.sessionId);
await apiInterrupt(this.sessionId)
}
}

View File

@@ -1,336 +1,363 @@
import type { ChatTransport, UIMessage, UIMessageChunk } from "ai";
import { getUuid } from "../api/client";
import { generateMessageUuid } from "./utils";
import type { SessionEvent, EventPayload } from "../types";
import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'
import { getUuid } from '../api/client'
import { generateMessageUuid } from './utils'
import type { SessionEvent, EventPayload } from '../types'
// ============================================================
// SSE Event Bus — shared between SSE listener and transport
// ============================================================
type SSEEventHandler = (event: SessionEvent) => void;
type SSEEventHandler = (event: SessionEvent) => void
class SSEEventBus {
private listeners: Set<SSEEventHandler> = new Set();
private eventSource: EventSource | null = null;
private _lastSeqNum = 0;
private listeners: Set<SSEEventHandler> = new Set()
private eventSource: EventSource | null = null
private _lastSeqNum = 0
get lastSeqNum() {
return this._lastSeqNum;
return this._lastSeqNum
}
/** Register a listener for SSE events */
onEvent(handler: SSEEventHandler): () => void {
this.listeners.add(handler);
return () => this.listeners.delete(handler);
this.listeners.add(handler)
return () => this.listeners.delete(handler)
}
/** Connect to the SSE stream for a session */
connect(sessionId: string): void {
this.disconnect();
const uuid = getUuid();
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
const es = new EventSource(url);
this.eventSource = es;
this.disconnect()
const uuid = getUuid()
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`
const es = new EventSource(url)
this.eventSource = es
es.addEventListener("message", (e: MessageEvent) => {
es.addEventListener('message', (e: MessageEvent) => {
try {
const data = JSON.parse(e.data) as SessionEvent;
if (data.seqNum !== undefined && data.seqNum <= this._lastSeqNum) return;
if (data.seqNum !== undefined) this._lastSeqNum = data.seqNum;
const data = JSON.parse(e.data) as SessionEvent
if (data.seqNum !== undefined && data.seqNum <= this._lastSeqNum) return
if (data.seqNum !== undefined) this._lastSeqNum = data.seqNum
for (const handler of this.listeners) {
handler(data);
handler(data)
}
} catch {
// ignore parse errors
}
});
})
}
/** Disconnect the SSE stream */
disconnect(): void {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
this.eventSource.close()
this.eventSource = null
}
this._lastSeqNum = 0;
this._lastSeqNum = 0
}
}
// Singleton event bus
export const sseBus = new SSEEventBus();
export const sseBus = new SSEEventBus()
// ============================================================
// RCS ChatTransport — bridges RCS SSE to AI SDK UIMessageChunk
// ============================================================
interface RCSTransportOptions {
sessionId: string;
onPermissionRequest?: (event: SessionEvent) => void;
onSessionStatus?: (status: string) => void;
onError?: (error: string) => void;
sessionId: string
onPermissionRequest?: (event: SessionEvent) => void
onSessionStatus?: (status: string) => void
onError?: (error: string) => void
}
export class RCSTransport implements ChatTransport<UIMessage> {
private sessionId: string;
private onPermissionRequest?: (event: SessionEvent) => void;
private onSessionStatus?: (status: string) => void;
private onError?: (error: string) => void;
private unsub: (() => void) | null = null;
private sessionId: string
private onPermissionRequest?: (event: SessionEvent) => void
private onSessionStatus?: (status: string) => void
private onError?: (error: string) => void
private unsub: (() => void) | null = null
constructor(options: RCSTransportOptions) {
this.sessionId = options.sessionId;
this.onPermissionRequest = options.onPermissionRequest;
this.onSessionStatus = options.onSessionStatus;
this.onError = options.onError;
this.sessionId = options.sessionId
this.onPermissionRequest = options.onPermissionRequest
this.onSessionStatus = options.onSessionStatus
this.onError = options.onError
}
async sendMessages({
messages,
abortSignal,
}: Parameters<ChatTransport<UIMessage>["sendMessages"]>[0]): Promise<ReadableStream<UIMessageChunk>> {
const lastMessage = messages[messages.length - 1];
if (!lastMessage || lastMessage.role !== "user") {
}: Parameters<ChatTransport<UIMessage>['sendMessages']>[0]): Promise<
ReadableStream<UIMessageChunk>
> {
const lastMessage = messages[messages.length - 1]
if (!lastMessage || lastMessage.role !== 'user') {
// Return empty stream if no user message
return new ReadableStream({ start: (c) => c.close() });
return new ReadableStream({ start: c => c.close() })
}
// Extract text from the user message parts
const text = lastMessage.parts
.filter((p: UIMessage["parts"][number]): p is Extract<typeof p, { type: "text" }> => p.type === "text")
.filter(
(
p: UIMessage['parts'][number],
): p is Extract<typeof p, { type: 'text' }> => p.type === 'text',
)
.map((p: { text: string }) => p.text)
.join("");
.join('')
if (!text.trim()) {
return new ReadableStream({ start: (c) => c.close() });
return new ReadableStream({ start: c => c.close() })
}
// POST user message to the RCS backend
const uuid = getUuid();
const uuid = getUuid()
const response = await fetch(
`/web/sessions/${this.sessionId}/events?uuid=${encodeURIComponent(uuid)}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: "user",
type: 'user',
uuid: generateMessageUuid(),
content: text,
message: { content: text },
}),
signal: abortSignal,
},
);
)
if (!response.ok) {
const data = await response.json().catch(() => ({ error: { message: response.statusText } }));
throw new Error(data.error?.message || "Failed to send message");
const data = await response
.json()
.catch(() => ({ error: { message: response.statusText } }))
throw new Error(data.error?.message || 'Failed to send message')
}
// Create a ReadableStream from the SSE event bus
// Collects events until the assistant turn is complete
return new ReadableStream<UIMessageChunk>({
start: (controller) => {
let textId = `text-${Date.now()}`;
let started = false;
start: controller => {
let textId = `text-${Date.now()}`
let started = false
const ensureStarted = () => {
if (!started) {
started = true;
controller.enqueue({ type: "start", messageId: `msg-${Date.now()}` });
started = true
controller.enqueue({
type: 'start',
messageId: `msg-${Date.now()}`,
})
}
};
}
const handler = (event: SessionEvent) => {
const type = event.type;
const payload = event.payload || ({} as EventPayload);
const type = event.type
const payload = event.payload || ({} as EventPayload)
// Skip bridge init noise
const serialized = JSON.stringify(event);
if (/Remote Control connecting/i.test(serialized)) return;
const serialized = JSON.stringify(event)
if (/Remote Control connecting/i.test(serialized)) return
switch (type) {
// ---- Assistant text ----
case "assistant": {
case 'assistant': {
const content =
typeof payload.content === "string"
? payload.content
: "";
typeof payload.content === 'string' ? payload.content : ''
if (content && content.trim()) {
ensureStarted();
controller.enqueue({ type: "text-start", id: textId });
controller.enqueue({ type: "text-delta", id: textId, delta: content });
controller.enqueue({ type: "text-end", id: textId });
ensureStarted()
controller.enqueue({ type: 'text-start', id: textId })
controller.enqueue({
type: 'text-delta',
id: textId,
delta: content,
})
controller.enqueue({ type: 'text-end', id: textId })
}
// Check for embedded tool_use blocks
const msg = payload.message as Record<string, unknown> | undefined;
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
const toolBlocks = (msg.content as Array<Record<string, unknown>>).filter(
(b) => b.type === "tool_use",
);
const msg = payload.message as Record<string, unknown> | undefined
if (
msg &&
typeof msg === 'object' &&
Array.isArray(msg.content)
) {
const toolBlocks = (
msg.content as Array<Record<string, unknown>>
).filter(b => b.type === 'tool_use')
for (const block of toolBlocks) {
ensureStarted();
const toolCallId = (block.id as string) || `call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
ensureStarted()
const toolCallId =
(block.id as string) ||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
controller.enqueue({
type: "tool-input-available",
type: 'tool-input-available',
toolCallId,
toolName: (block.name as string) || "tool",
toolName: (block.name as string) || 'tool',
input: block.input || {},
});
})
}
}
// Finish after assistant message
ensureStarted();
controller.enqueue({ type: "finish", finishReason: "stop" });
controller.close();
cleanup();
break;
ensureStarted()
controller.enqueue({ type: 'finish', finishReason: 'stop' })
controller.close()
cleanup()
break
}
// ---- Tool use events ----
case "tool_use": {
ensureStarted();
case 'tool_use': {
ensureStarted()
const toolCallId =
(payload as Record<string, unknown>).tool_call_id as string ||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
((payload as Record<string, unknown>).tool_call_id as string) ||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
controller.enqueue({
type: "tool-input-available",
type: 'tool-input-available',
toolCallId,
toolName: (payload as Record<string, unknown>).tool_name as string || "tool",
toolName:
((payload as Record<string, unknown>).tool_name as string) ||
'tool',
input: (payload as Record<string, unknown>).tool_input || {},
});
break;
})
break
}
// ---- Tool result events ----
case "tool_result": {
ensureStarted();
case 'tool_result': {
ensureStarted()
const resultCallId =
(payload as Record<string, unknown>).tool_call_id as string ||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
((payload as Record<string, unknown>).tool_call_id as string) ||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
const output =
typeof (payload as Record<string, unknown>).output === "string"
typeof (payload as Record<string, unknown>).output === 'string'
? (payload as Record<string, unknown>).output
: (payload as Record<string, unknown>).content || "";
: (payload as Record<string, unknown>).content || ''
controller.enqueue({
type: "tool-output-available",
type: 'tool-output-available',
toolCallId: resultCallId,
output: output as string,
});
break;
})
break
}
// ---- Permission / control requests ----
case "control_request":
case "permission_request": {
const req = payload.request as Record<string, unknown> | undefined;
if (req && req.subtype === "can_use_tool") {
case 'control_request':
case 'permission_request': {
const req = payload.request as Record<string, unknown> | undefined
if (req && req.subtype === 'can_use_tool') {
// Forward to the UI layer for handling
this.onPermissionRequest?.(event);
this.onPermissionRequest?.(event)
}
// Don't close the stream — wait for the response
break;
break
}
// ---- Status events ----
case "status": {
case 'status': {
const msg =
(typeof payload.message === "string" ? payload.message : "") ||
(typeof payload.message === 'string' ? payload.message : '') ||
payload.content ||
"";
if (/connecting|waiting|initializing|Remote Control/i.test(msg)) return;
break;
''
if (/connecting|waiting|initializing|Remote Control/i.test(msg))
return
break
}
// ---- Session status ----
case "session_status": {
if (typeof payload.status === "string") {
this.onSessionStatus?.(payload.status);
case 'session_status': {
if (typeof payload.status === 'string') {
this.onSessionStatus?.(payload.status)
if (
payload.status === "archived" ||
payload.status === "inactive"
payload.status === 'archived' ||
payload.status === 'inactive'
) {
ensureStarted();
controller.enqueue({ type: "finish", finishReason: "stop" });
controller.close();
cleanup();
ensureStarted()
controller.enqueue({ type: 'finish', finishReason: 'stop' })
controller.close()
cleanup()
}
}
break;
break
}
// ---- Errors ----
case "error": {
ensureStarted();
case 'error': {
ensureStarted()
controller.enqueue({
type: "error",
errorText: String(payload.message || payload.content || "Unknown error"),
});
controller.enqueue({ type: "finish", finishReason: "error" });
controller.close();
cleanup();
break;
type: 'error',
errorText: String(
payload.message || payload.content || 'Unknown error',
),
})
controller.enqueue({ type: 'finish', finishReason: 'error' })
controller.close()
cleanup()
break
}
// ---- Interrupt ----
case "interrupt": {
ensureStarted();
controller.enqueue({ type: "abort", reason: "Session interrupted" });
controller.close();
cleanup();
break;
case 'interrupt': {
ensureStarted()
controller.enqueue({
type: 'abort',
reason: 'Session interrupted',
})
controller.close()
cleanup()
break
}
// ---- Skip noise ----
case "partial_assistant":
case "result":
case "result_success":
case "control_response":
case "permission_response":
case "system":
case "task_state":
case "automation_state":
return;
case 'partial_assistant':
case 'result':
case 'result_success':
case 'control_response':
case 'permission_response':
case 'system':
case 'task_state':
case 'automation_state':
return
default:
return;
return
}
};
}
const cleanup = () => {
if (this.unsub) {
this.unsub();
this.unsub = null;
this.unsub()
this.unsub = null
}
};
}
this.unsub = sseBus.onEvent(handler);
this.unsub = sseBus.onEvent(handler)
// Handle abort
if (abortSignal) {
const onAbort = () => {
controller.enqueue({ type: "abort", reason: "Aborted" });
controller.close();
cleanup();
abortSignal.removeEventListener("abort", onAbort);
};
abortSignal.addEventListener("abort", onAbort);
controller.enqueue({ type: 'abort', reason: 'Aborted' })
controller.close()
cleanup()
abortSignal.removeEventListener('abort', onAbort)
}
abortSignal.addEventListener('abort', onAbort)
}
},
});
})
}
/** Not supported — RCS doesn't have stream resumption */
reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {
return Promise.resolve(null);
return Promise.resolve(null)
}
/** Clean up listeners */
destroy(): void {
if (this.unsub) {
this.unsub();
this.unsub = null;
this.unsub()
this.unsub = null
}
}
}

View File

@@ -1,97 +1,110 @@
import React, { createContext, useContext, useEffect, useState, useCallback } from "react";
import React, {
createContext,
useContext,
useEffect,
useState,
useCallback,
} from 'react'
export type Theme = "light" | "dark" | "system";
export type Theme = 'light' | 'dark' | 'system'
interface ThemeContextValue {
theme: Theme;
resolvedTheme: "light" | "dark";
setTheme: (theme: Theme) => void;
theme: Theme
resolvedTheme: 'light' | 'dark'
setTheme: (theme: Theme) => void
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined)
const STORAGE_KEY = "theme";
const STORAGE_KEY = 'theme'
function getSystemTheme(): "light" | "dark" {
if (typeof window === "undefined") return "light";
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
function getSystemTheme(): 'light' | 'dark' {
if (typeof window === 'undefined') return 'light'
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
function getStoredTheme(): Theme {
if (typeof window === "undefined") return "system";
if (typeof window === 'undefined') return 'system'
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === "light" || stored === "dark" || stored === "system") {
return stored;
const stored = localStorage.getItem(STORAGE_KEY)
if (stored === 'light' || stored === 'dark' || stored === 'system') {
return stored
}
} catch {
// localStorage not available
}
return "system";
return 'system'
}
function applyTheme(theme: "light" | "dark") {
const root = document.documentElement;
root.classList.remove("light", "dark");
root.classList.add(theme);
function applyTheme(theme: 'light' | 'dark') {
const root = document.documentElement
root.classList.remove('light', 'dark')
root.classList.add(theme)
}
export function useTheme() {
const context = useContext(ThemeContext);
const context = useContext(ThemeContext)
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
throw new Error('useTheme must be used within a ThemeProvider')
}
return context;
return context
}
interface ThemeProviderProps {
children: React.ReactNode;
defaultTheme?: Theme;
children: React.ReactNode
defaultTheme?: Theme
}
export function ThemeProvider({ children, defaultTheme = "system" }: ThemeProviderProps) {
const [theme, setThemeState] = useState<Theme>(() => getStoredTheme() || defaultTheme);
const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">(() => {
const stored = getStoredTheme() || defaultTheme;
return stored === "system" ? getSystemTheme() : stored;
});
export function ThemeProvider({
children,
defaultTheme = 'system',
}: ThemeProviderProps) {
const [theme, setThemeState] = useState<Theme>(
() => getStoredTheme() || defaultTheme,
)
const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>(() => {
const stored = getStoredTheme() || defaultTheme
return stored === 'system' ? getSystemTheme() : stored
})
const setTheme = useCallback((newTheme: Theme) => {
setThemeState(newTheme);
setThemeState(newTheme)
try {
localStorage.setItem(STORAGE_KEY, newTheme);
localStorage.setItem(STORAGE_KEY, newTheme)
} catch {
// localStorage not available
}
}, []);
}, [])
// Apply theme on mount and when theme changes
useEffect(() => {
const resolved = theme === "system" ? getSystemTheme() : theme;
setResolvedTheme(resolved);
applyTheme(resolved);
}, [theme]);
const resolved = theme === 'system' ? getSystemTheme() : theme
setResolvedTheme(resolved)
applyTheme(resolved)
}, [theme])
// Listen for system theme changes
useEffect(() => {
if (theme !== "system") return;
if (theme !== 'system') return
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
const handleChange = (e: MediaQueryListEvent) => {
const newTheme = e.matches ? "dark" : "light";
setResolvedTheme(newTheme);
applyTheme(newTheme);
};
const newTheme = e.matches ? 'dark' : 'light'
setResolvedTheme(newTheme)
applyTheme(newTheme)
}
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [theme]);
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}, [theme])
const value: ThemeContextValue = {
theme,
resolvedTheme,
setTheme,
};
}
return React.createElement(ThemeContext.Provider, { value }, children);
return React.createElement(ThemeContext.Provider, { value }, children)
}

View File

@@ -2,71 +2,71 @@
// Unified Chat Data Model — shared between ACP and RCS chat interfaces
// =============================================================================
import type { ToolCallContent, PermissionOption, PlanEntry } from "../acp/types";
import type { ToolCallContent, PermissionOption, PlanEntry } from '../acp/types'
// 工具调用状态
export type ToolCallStatus =
| "running"
| "complete"
| "error"
| "waiting_for_confirmation"
| "rejected"
| "canceled";
| 'running'
| 'complete'
| 'error'
| 'waiting_for_confirmation'
| 'rejected'
| 'canceled'
// 工具调用数据
export interface ToolCallData {
id: string;
title: string;
status: ToolCallStatus;
content?: ToolCallContent[];
rawInput?: Record<string, unknown>;
rawOutput?: Record<string, unknown>;
id: string
title: string
status: ToolCallStatus
content?: ToolCallContent[]
rawInput?: Record<string, unknown>
rawOutput?: Record<string, unknown>
// 权限请求(仅当 status === "waiting_for_confirmation"
permissionRequest?: {
requestId: string;
options: PermissionOption[];
};
requestId: string
options: PermissionOption[]
}
// 独立权限请求(无匹配工具调用时创建)
isStandalonePermission?: boolean;
isStandalonePermission?: boolean
}
// 助手消息块 — 普通消息或思考过程
export type AssistantChunk =
| { type: "message"; text: string }
| { type: "thought"; text: string };
| { type: 'message'; text: string }
| { type: 'thought'; text: string }
// 用户消息中的图片
export interface UserMessageImage {
mimeType: string;
data: string; // base64 encoded
mimeType: string
data: string // base64 encoded
}
// 用户消息条目
export interface UserMessageEntry {
type: "user_message";
id: string;
content: string;
images?: UserMessageImage[];
type: 'user_message'
id: string
content: string
images?: UserMessageImage[]
}
// 助手消息条目
export interface AssistantMessageEntry {
type: "assistant_message";
id: string;
chunks: AssistantChunk[];
type: 'assistant_message'
id: string
chunks: AssistantChunk[]
}
// 工具调用条目
export interface ToolCallEntry {
type: "tool_call";
toolCall: ToolCallData;
type: 'tool_call'
toolCall: ToolCallData
}
// Plan 展示条目Agent 执行计划)
export interface PlanDisplayEntry {
type: "plan";
id: string;
entries: PlanEntry[];
type: 'plan'
id: string
entries: PlanEntry[]
}
// 统一聊天条目类型
@@ -74,7 +74,7 @@ export type ThreadEntry =
| UserMessageEntry
| AssistantMessageEntry
| ToolCallEntry
| PlanDisplayEntry;
| PlanDisplayEntry
// =============================================================================
// Chat 组件 Props 类型
@@ -82,23 +82,23 @@ export type ThreadEntry =
// ChatInput 提交消息
export interface ChatInputMessage {
text: string;
images?: UserMessageImage[];
text: string
images?: UserMessageImage[]
}
// 权限请求条目(用于 PermissionPanel
export interface PendingPermission {
requestId: string;
toolName: string;
toolInput: Record<string, unknown>;
description?: string;
options?: PermissionOption[];
requestId: string
toolName: string
toolInput: Record<string, unknown>
description?: string
options?: PermissionOption[]
}
// 会话列表条目(用于 SessionSidebar
export interface SessionListItem {
id: string;
title?: string | null;
updatedAt?: string | null;
isActive?: boolean;
id: string
title?: string | null
updatedAt?: string | null
isActive?: boolean
}

View File

@@ -1,91 +1,102 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
return twMerge(clsx(inputs))
}
export function esc(str: string | null | undefined): string {
if (!str) return "";
const value = String(str);
const div = document.createElement("div");
div.textContent = value;
return div.innerHTML;
if (!str) return ''
const value = String(str)
const div = document.createElement('div')
div.textContent = value
return div.innerHTML
}
export function formatTime(ts: number | null | undefined): string {
if (!ts) return "";
return new Date(ts * 1000).toLocaleString();
if (!ts) return ''
return new Date(ts * 1000).toLocaleString()
}
export function statusClass(status: string | null | undefined): string {
const map: Record<string, string> = {
active: "active",
running: "running",
idle: "idle",
inactive: "inactive",
requires_action: "requires_action",
archived: "archived",
error: "error",
};
return map[status || ""] || "default";
active: 'active',
running: 'running',
idle: 'idle',
inactive: 'inactive',
requires_action: 'requires_action',
archived: 'archived',
error: 'error',
}
return map[status || ''] || 'default'
}
export function isClosedSessionStatus(status: string | null | undefined): boolean {
return status === "archived" || status === "inactive";
export function isClosedSessionStatus(
status: string | null | undefined,
): boolean {
return status === 'archived' || status === 'inactive'
}
export function truncate(str: string | null | undefined, max: number): string {
if (!str) return "";
const s = String(str);
return s.length > max ? s.slice(0, max) + "..." : s;
if (!str) return ''
const s = String(str)
return s.length > max ? s.slice(0, max) + '...' : s
}
function formatUuidV4(bytes: Uint8Array): string {
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'))
return [
hex.slice(0, 4).join(""),
hex.slice(4, 6).join(""),
hex.slice(6, 8).join(""),
hex.slice(8, 10).join(""),
hex.slice(10, 16).join(""),
].join("-");
hex.slice(0, 4).join(''),
hex.slice(4, 6).join(''),
hex.slice(6, 8).join(''),
hex.slice(8, 10).join(''),
hex.slice(10, 16).join(''),
].join('-')
}
export function generateMessageUuid(): string {
const cryptoApi = globalThis.crypto;
if (cryptoApi && typeof cryptoApi.randomUUID === "function") {
return cryptoApi.randomUUID();
const cryptoApi = globalThis.crypto
if (cryptoApi && typeof cryptoApi.randomUUID === 'function') {
return cryptoApi.randomUUID()
}
if (!cryptoApi || typeof cryptoApi.getRandomValues !== "function") {
throw new Error("crypto.getRandomValues is required to generate message UUIDs");
if (!cryptoApi || typeof cryptoApi.getRandomValues !== 'function') {
throw new Error(
'crypto.getRandomValues is required to generate message UUIDs',
)
}
const bytes = new Uint8Array(16);
cryptoApi.getRandomValues(bytes);
return formatUuidV4(bytes);
const bytes = new Uint8Array(16)
cryptoApi.getRandomValues(bytes)
return formatUuidV4(bytes)
}
export function extractEventText(payload: Record<string, unknown> | null | undefined): string {
if (!payload || typeof payload !== "object") return "";
if (typeof payload.content === "string") return payload.content;
const msg = payload.message as Record<string, unknown> | undefined;
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
export function extractEventText(
payload: Record<string, unknown> | null | undefined,
): string {
if (!payload || typeof payload !== 'object') return ''
if (typeof payload.content === 'string') return payload.content
const msg = payload.message as Record<string, unknown> | undefined
if (msg && typeof msg === 'object' && Array.isArray(msg.content)) {
const texts = msg.content
.filter((b: Record<string, unknown>) => b && b.type === "text" && typeof b.text === "string")
.map((b: Record<string, unknown>) => b.text as string);
if (texts.length > 0) return texts.join("\n");
.filter(
(b: Record<string, unknown>) =>
b && b.type === 'text' && typeof b.text === 'string',
)
.map((b: Record<string, unknown>) => b.text as string)
if (texts.length > 0) return texts.join('\n')
}
return "";
return ''
}
export function isConversationClearedStatus(
payload: Record<string, unknown> | null | undefined,
): boolean {
if (!payload || typeof payload !== "object") return false;
if (payload.status === "conversation_cleared") return true;
const raw = payload.raw as Record<string, unknown> | undefined;
return !!raw && typeof raw === "object" && raw.status === "conversation_cleared";
if (!payload || typeof payload !== 'object') return false
if (payload.status === 'conversation_cleared') return true
const raw = payload.raw as Record<string, unknown> | undefined
return (
!!raw && typeof raw === 'object' && raw.status === 'conversation_cleared'
)
}

View File

@@ -1,9 +1,9 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';
createRoot(document.getElementById("root")!).render(
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,

View File

@@ -1,9 +1,9 @@
import { useState, useEffect, useCallback } from "react";
import { apiFetchAllSessions, apiFetchEnvironments } from "../api/client";
import type { Session, Environment } from "../types";
import { EnvironmentList } from "../components/EnvironmentList";
import { SessionList } from "../components/SessionList";
import { NewSessionDialog } from "../components/NewSessionDialog";
import { useState, useEffect, useCallback } from 'react';
import { apiFetchAllSessions, apiFetchEnvironments } from '../api/client';
import type { Session, Environment } from '../types';
import { EnvironmentList } from '../components/EnvironmentList';
import { SessionList } from '../components/SessionList';
import { NewSessionDialog } from '../components/NewSessionDialog';
interface DashboardProps {
onNavigateSession: (sessionId: string) => void;
@@ -20,7 +20,7 @@ export function Dashboard({ onNavigateSession }: DashboardProps) {
setSessions(sess || []);
setEnvironments(envs || []);
} catch (err) {
console.error("Dashboard render error:", err);
console.error('Dashboard render error:', err);
}
}, []);
@@ -40,9 +40,12 @@ export function Dashboard({ onNavigateSession }: DashboardProps) {
// Bridge environments: no direct navigation (sessions are listed below)
}, []);
const handleSelectSession = useCallback((sessionId: string) => {
onNavigateSession(sessionId);
}, [onNavigateSession]);
const handleSelectSession = useCallback(
(sessionId: string) => {
onNavigateSession(sessionId);
},
[onNavigateSession],
);
return (
<div className="mx-auto max-w-5xl px-4 py-8">

View File

@@ -1,31 +1,23 @@
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import {
apiFetchSession,
apiSendControl,
apiInterrupt,
} from "../api/client";
import type { Session, SessionEvent } from "../types";
import { isClosedSessionStatus, formatTime, cn } from "../lib/utils";
import { Info } from "lucide-react";
import { RCSChatAdapter } from "../lib/rcs-chat-adapter";
import type { ThreadEntry, PendingPermission } from "../lib/types";
import { StatusBadge } from "../components/Navbar";
import { TaskPanel } from "../components/TaskPanel";
import {
PermissionPromptView,
AskUserPanelView,
PlanPanelView,
} from "../components/PermissionViews";
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { apiFetchSession, apiSendControl, apiInterrupt } from '../api/client';
import type { Session, SessionEvent } from '../types';
import { isClosedSessionStatus, formatTime, cn } from '../lib/utils';
import { Info } from 'lucide-react';
import { RCSChatAdapter } from '../lib/rcs-chat-adapter';
import type { ThreadEntry, PendingPermission } from '../lib/types';
import { StatusBadge } from '../components/Navbar';
import { TaskPanel } from '../components/TaskPanel';
import { PermissionPromptView, AskUserPanelView, PlanPanelView } from '../components/PermissionViews';
// Unified chat components
import { ChatView } from "../../components/chat/ChatView";
import { ChatInput } from "../../components/chat/ChatInput";
import { TooltipProvider } from "../../components/ui/tooltip";
import { ChatView } from '../../components/chat/ChatView';
import { ChatInput } from '../../components/chat/ChatInput';
import { TooltipProvider } from '../../components/ui/tooltip';
// ACP chat components
import { ACPClient, DisconnectRequestedError } from "../acp/client";
import { createRelayClient } from "../acp/relay-client";
import { ACPMain } from "../../components/ACPMain";
import { ACPClient, DisconnectRequestedError } from '../acp/client';
import { createRelayClient } from '../acp/relay-client';
import { ACPMain } from '../../components/ACPMain';
interface SessionDetailProps {
sessionId: string;
@@ -34,7 +26,7 @@ interface SessionDetailProps {
export function SessionDetail({ sessionId }: SessionDetailProps) {
const [session, setSession] = useState<Session | null>(null);
const [sessionStatus, setSessionStatus] = useState<string | null>(null);
const [error, setError] = useState("");
const [error, setError] = useState('');
const [taskPanelOpen, setTaskPanelOpen] = useState(false);
const [showMeta, setShowMeta] = useState(false);
const [entries, setEntries] = useState<ThreadEntry[]>([]);
@@ -46,15 +38,15 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
const adapter = useMemo(
() =>
new RCSChatAdapter(sessionId, setEntries, {
onStatusChange: (status) => {
onStatusChange: status => {
setSessionStatus(status);
},
onError: (err) => {
console.error("[RCSChatAdapter] error:", err);
onError: err => {
console.error('[RCSChatAdapter] error:', err);
},
onPermissionRequest: (permission) => {
setPendingPermissions((prev) => {
if (prev.some((p) => p.requestId === permission.requestId)) return prev;
onPermissionRequest: permission => {
setPendingPermissions(prev => {
if (prev.some(p => p.requestId === permission.requestId)) return prev;
return [...prev, permission];
});
},
@@ -74,7 +66,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
let cancelled = false;
async function load() {
setError("");
setError('');
try {
const sess = await apiFetchSession(sessionId);
@@ -83,14 +75,14 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
setSessionStatus(sess.status);
} catch (err) {
if (cancelled) return;
setError(err instanceof Error ? err.message : "Failed to load session");
setError(err instanceof Error ? err.message : 'Failed to load session');
return;
}
try {
await adapter.init();
} catch (err) {
console.warn("Failed to init adapter:", err);
console.warn('Failed to init adapter:', err);
}
}
@@ -104,14 +96,14 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
// Send message via ChatInput
const handleSubmit = useCallback(
async (message: import("../../src/lib/types").ChatInputMessage) => {
async (message: import('../../src/lib/types').ChatInputMessage) => {
const text = message.text.trim();
if (!text || closed) return;
setIsLoading(true);
try {
await adapter.sendMessage(text, message.images);
} catch (err) {
console.error("Send failed:", err);
console.error('Send failed:', err);
}
},
[adapter, closed],
@@ -122,7 +114,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
try {
await adapter.interrupt();
} catch (err) {
console.error("Interrupt failed:", err);
console.error('Interrupt failed:', err);
} finally {
setIsLoading(false);
}
@@ -132,9 +124,9 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
useEffect(() => {
if (entries.length === 0) return;
const last = entries[entries.length - 1];
if (last?.type === "assistant_message" || last?.type === "tool_call") {
if (last?.type === 'assistant_message' || last?.type === 'tool_call') {
// If the last entry is no longer a streaming tool, consider loading done
if (last.type === "tool_call" && last.toolCall.status === "running") return;
if (last.type === 'tool_call' && last.toolCall.status === 'running') return;
setIsLoading(false);
}
}, [entries]);
@@ -145,9 +137,9 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
try {
await adapter.respondPermission(requestId, true);
} catch (err) {
console.error("Failed to approve:", err);
console.error('Failed to approve:', err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
},
[adapter],
);
@@ -157,30 +149,26 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
try {
await adapter.respondPermission(requestId, false);
} catch (err) {
console.error("Failed to reject:", err);
console.error('Failed to reject:', err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
},
[adapter],
);
const handleSubmitAnswers = useCallback(
async (
requestId: string,
answers: Record<string, unknown>,
questions: import("../types").Question[],
) => {
async (requestId: string, answers: Record<string, unknown>, questions: import('../types').Question[]) => {
try {
await apiSendControl(sessionId, {
type: "permission_response",
type: 'permission_response',
approved: true,
request_id: requestId,
updated_input: { questions, answers },
});
} catch (err) {
console.error("Failed to submit answers:", err);
console.error('Failed to submit answers:', err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
},
[sessionId],
);
@@ -188,31 +176,29 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
const handleSubmitPlanResponse = useCallback(
async (requestId: string, value: string, feedback?: string) => {
try {
if (value === "no") {
if (value === 'no') {
await apiSendControl(sessionId, {
type: "permission_response",
type: 'permission_response',
approved: false,
request_id: requestId,
...(feedback ? { message: feedback } : {}),
});
} else {
const modeMap: Record<string, string> = {
"yes-accept-edits": "acceptEdits",
"yes-default": "default",
'yes-accept-edits': 'acceptEdits',
'yes-default': 'default',
};
await apiSendControl(sessionId, {
type: "permission_response",
type: 'permission_response',
approved: true,
request_id: requestId,
updated_permissions: [
{ type: "setMode", mode: modeMap[value] || "default", destination: "session" },
],
updated_permissions: [{ type: 'setMode', mode: modeMap[value] || 'default', destination: 'session' }],
});
}
} catch (err) {
console.error("Failed to submit plan response:", err);
console.error('Failed to submit plan response:', err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
},
[sessionId],
);
@@ -239,7 +225,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
}
// ACP session — render ACP relay chat
if (session.source === "acp" && session.environment_id) {
if (session.source === 'acp' && session.environment_id) {
return <ACPSessionDetail sessionId={sessionId} agentId={session.environment_id} />;
}
@@ -260,14 +246,10 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
</div>
<div className="flex items-start justify-between">
<div className="min-w-0">
<h2 className="font-display text-lg font-semibold text-text-primary">
{session.title || session.id}
</h2>
<h2 className="font-display text-lg font-semibold text-text-primary">{session.title || session.id}</h2>
<div className="mt-1 flex flex-wrap items-center gap-2">
{sessionStatus && <StatusBadge status={sessionStatus} />}
<span className="text-xs text-text-muted">
{formatTime(session.created_at)}
</span>
<span className="text-xs text-text-muted">{formatTime(session.created_at)}</span>
</div>
</div>
<div className="flex items-center gap-2">
@@ -288,9 +270,14 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
</div>
{showMeta && (
<div className="mt-2 rounded-md bg-surface-2 px-3 py-2 text-xs text-text-muted space-y-1 font-mono">
<div><span className="text-text-secondary font-sans font-medium">Session</span> {session.id}</div>
<div>
<span className="text-text-secondary font-sans font-medium">Session</span> {session.id}
</div>
{session.environment_id && (
<div><span className="text-text-secondary font-sans font-medium">Environment</span> {session.environment_id}</div>
<div>
<span className="text-text-secondary font-sans font-medium">Environment</span>{' '}
{session.environment_id}
</div>
)}
</div>
)}
@@ -298,18 +285,13 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
</div>
{/* Chat messages — unified ChatView */}
<ChatView
entries={entries}
isLoading={isLoading}
emptyTitle="开始对话"
emptyDescription="输入消息开始聊天"
/>
<ChatView entries={entries} isLoading={isLoading} emptyTitle="开始对话" emptyDescription="输入消息开始聊天" />
{/* Unified Permission Panel — above input */}
{pendingPermissions.length > 0 && (
<div className="border-t bg-surface-1 px-4 py-3">
<div className="mx-auto max-w-3xl space-y-3">
{pendingPermissions.map((req) => (
{pendingPermissions.map(req => (
<PermissionEventView
key={req.requestId}
request={req}
@@ -329,7 +311,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
isLoading={isLoading}
onInterrupt={handleInterrupt}
disabled={closed}
placeholder={closed ? "会话已关闭" : "输入消息..."}
placeholder={closed ? '会话已关闭' : '输入消息...'}
/>
{/* Task Panel */}
@@ -353,28 +335,32 @@ function PermissionEventView({
request: PendingPermission;
onApprove: () => void;
onReject: () => void;
onSubmitAnswers: (requestId: string, answers: Record<string, unknown>, questions: import("../types").Question[]) => void;
onSubmitAnswers: (
requestId: string,
answers: Record<string, unknown>,
questions: import('../types').Question[],
) => void;
onSubmitPlan: (requestId: string, value: string, feedback?: string) => void;
}) {
const toolName = request.toolName;
const toolInput = request.toolInput;
const description = request.description || "";
const description = request.description || '';
if (toolName === "AskUserQuestion") {
const questions = (toolInput.questions as import("../types").Question[]) || [];
if (toolName === 'AskUserQuestion') {
const questions = (toolInput.questions as import('../types').Question[]) || [];
return (
<AskUserPanelView
requestId={request.requestId}
questions={questions}
description={description}
onSubmit={(answers) => onSubmitAnswers(request.requestId, answers, questions)}
onSubmit={answers => onSubmitAnswers(request.requestId, answers, questions)}
onSkip={onReject}
/>
);
}
if (toolName === "ExitPlanMode") {
const planContent = (toolInput.plan as string) || "";
if (toolName === 'ExitPlanMode') {
const planContent = (toolInput.plan as string) || '';
return (
<PlanPanelView
requestId={request.requestId}
@@ -403,7 +389,9 @@ function PermissionEventView({
function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId: string }) {
const [client, setClient] = useState<ACPClient | null>(null);
const [connectionState, setConnectionState] = useState<"disconnected" | "connecting" | "connected" | "error">("disconnected");
const [connectionState, setConnectionState] = useState<'disconnected' | 'connecting' | 'connected' | 'error'>(
'disconnected',
);
const [error, setError] = useState<string | null>(null);
const clientRef = useRef<ACPClient | null>(null);
@@ -418,30 +406,28 @@ function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId:
clientRef.current = relayClient;
setClient(relayClient);
relayClient.connect().catch((e) => {
relayClient.connect().catch(e => {
if (e instanceof DisconnectRequestedError) return;
setError((e as Error).message);
setConnectionState("error");
setConnectionState('error');
});
return () => {
relayClient.disconnect();
clientRef.current = null;
setClient(null);
setConnectionState("disconnected");
setConnectionState('disconnected');
};
}, [agentId]);
return (
<TooltipProvider>
<div className="flex flex-1 flex-col overflow-hidden">
{error && connectionState === "error" && (
<div className="px-4 py-2 bg-destructive/10 text-destructive text-sm border-b">
{error}
</div>
{error && connectionState === 'error' && (
<div className="px-4 py-2 bg-destructive/10 text-destructive text-sm border-b">{error}</div>
)}
{connectionState === "connecting" && (
{connectionState === 'connecting' && (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<div className="animate-spin h-8 w-8 border-2 border-brand border-t-transparent rounded-full mx-auto mb-3" />
@@ -450,7 +436,7 @@ function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId:
</div>
)}
{connectionState === "error" && !client && (
{connectionState === 'error' && !client && (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<p className="font-medium mb-1">Connection Failed</p>
@@ -459,7 +445,7 @@ function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId:
</div>
)}
{client && connectionState === "connected" && (
{client && connectionState === 'connected' && (
<div className="flex-1 min-h-0">
<ACPMain client={client} agentId={agentId} />
</div>

View File

@@ -1,100 +1,100 @@
export interface Environment {
id: string;
machine_name?: string;
directory?: string;
status: string;
branch?: string;
worker_type?: string;
channel_group_id?: string | null;
capabilities?: Record<string, unknown> | null;
id: string
machine_name?: string
directory?: string
status: string
branch?: string
worker_type?: string
channel_group_id?: string | null
capabilities?: Record<string, unknown> | null
}
export interface Session {
id: string;
title?: string;
status: string;
environment_id?: string;
source?: string;
created_at?: number;
updated_at?: number;
automation_state?: unknown;
id: string
title?: string
status: string
environment_id?: string
source?: string
created_at?: number
updated_at?: number
automation_state?: unknown
}
export interface SessionEvent {
type: string;
payload?: EventPayload;
direction?: "inbound" | "outbound";
seqNum?: number;
id?: string;
type: string
payload?: EventPayload
direction?: 'inbound' | 'outbound'
seqNum?: number
id?: string
}
export interface EventPayload {
content?: string;
message?: unknown;
status?: string;
uuid?: string;
content?: string
message?: unknown
status?: string
uuid?: string
raw?: {
uuid?: string;
status?: string;
};
request_id?: string;
request?: PermissionRequest;
tool_name?: string;
tool_input?: unknown;
input?: unknown;
description?: string;
uuid?: string
status?: string
}
request_id?: string
request?: PermissionRequest
tool_name?: string
tool_input?: unknown
input?: unknown
description?: string
}
export interface ContentBlock {
type: string;
text?: string;
name?: string;
input?: unknown;
content?: unknown;
is_error?: boolean;
type: string
text?: string
name?: string
input?: unknown
content?: unknown
is_error?: boolean
}
export interface PermissionRequest {
subtype?: string;
tool_name?: string;
input?: unknown;
tool_input?: unknown;
description?: string;
subtype?: string
tool_name?: string
input?: unknown
tool_input?: unknown
description?: string
}
export interface Question {
question: string;
header?: string;
multiSelect?: boolean;
options?: QuestionOption[];
metadata?: Record<string, unknown>;
question: string
header?: string
multiSelect?: boolean
options?: QuestionOption[]
metadata?: Record<string, unknown>
}
export interface QuestionOption {
label: string;
description?: string;
label: string
description?: string
}
export interface ControlResponse {
type: "permission_response";
approved: boolean;
request_id: string;
message?: string;
updated_input?: Record<string, unknown>;
updated_permissions?: PermissionUpdate[];
type: 'permission_response'
approved: boolean
request_id: string
message?: string
updated_input?: Record<string, unknown>
updated_permissions?: PermissionUpdate[]
}
export interface PermissionUpdate {
type: string;
mode: string;
destination: string;
type: string
mode: string
destination: string
}
export type ActivityMode = "working" | "idle" | "standby" | "sleeping";
export type ActivityMode = 'working' | 'idle' | 'standby' | 'sleeping'
export interface AutomationActivity {
mode: ActivityMode;
iconVariant: string;
label: string;
endsAt?: number;
mode: ActivityMode
iconVariant: string
label: string
endsAt?: number
}