Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(protocol): add conversationId compatibility across hub/client
Jiayuan Zhang754e604a40bb
diff --git a/apps/web/components/pages/chat-page.tsx b/apps/web/components/pages/chat-page.tsxindex db365885c6..67c7bb788d 100644--- a/apps/web/components/pages/chat-page.tsx+++ b/apps/web/components/pages/chat-page.tsx@@ -37,6 +37,7 @@ const ChatPage = () => {client={client}hubId={identity.hubId}agentId={identity.agentId}+ conversationId={identity.conversationId}onDisconnect={disconnect}/>)}@@ -49,14 +50,16 @@ function ConnectedChat({client,hubId,agentId,+ conversationId,onDisconnect,}: {client: NonNullable<ReturnType<typeof useGatewayConnection>["client"]>;hubId: string;agentId: string;+ conversationId?: string;onDisconnect: () => void;}) {- const chat = useGatewayChat({ client, hubId, agentId });+ const chat = useGatewayChat({ client, hubId, agentId, conversationId });return <ChatView {...chat} onDisconnect={onDisconnect} />;}diff --git a/packages/core/src/agent/tools/exec-approval-types.ts b/packages/core/src/agent/tools/exec-approval-types.tsindex 9b1ab44982..a3275a7b4e 100644--- a/packages/core/src/agent/tools/exec-approval-types.ts+++ b/packages/core/src/agent/tools/exec-approval-types.ts@@ -24,6 +24,8 @@ export interface ExecApprovalRequest {approvalId: string;/** Agent that initiated the command */agentId: string;+ /** Optional conversation ID. Falls back to agentId in legacy mode. */+ conversationId?: string;/** Shell command to execute */command: string;/** Working directory */diff --git a/packages/core/src/channels/manager.ts b/packages/core/src/channels/manager.tsindex cbe7800dff..fc62f78650 100644--- a/packages/core/src/channels/manager.ts+++ b/packages/core/src/channels/manager.ts@@ -526,6 +526,7 @@ export class ChannelManager {// Broadcast inbound message to local listeners (Desktop UI)this.hub.broadcastInbound({agentId: agent.sessionId,+ conversationId: agent.sessionId,content: combinedText,source: source!,timestamp: Date.now(),diff --git a/packages/core/src/client/actions/exec-approval.ts b/packages/core/src/client/actions/exec-approval.tsindex cd098273d2..3c4d6dd952 100644--- a/packages/core/src/client/actions/exec-approval.ts+++ b/packages/core/src/client/actions/exec-approval.ts@@ -14,6 +14,8 @@ export interface ExecApprovalRequestPayload {approvalId: string;/** Agent that initiated the command */agentId: string;+ /** Optional conversation ID. Falls back to agentId in legacy mode. */+ conversationId?: string;/** Shell command requiring approval */command: string;/** Working directory */diff --git a/packages/core/src/client/actions/rpc.ts b/packages/core/src/client/actions/rpc.tsindex ddbc78f74a..0e3948d352 100644--- a/packages/core/src/client/actions/rpc.ts+++ b/packages/core/src/client/actions/rpc.ts@@ -66,6 +66,8 @@ export const DEFAULT_MESSAGES_LIMIT = 200;/** getAgentMessages - request params */export interface GetAgentMessagesParams {agentId: string;+ /** Optional conversation ID. Falls back to agent main conversation when omitted. */+ conversationId?: string;offset?: number;limit?: number;}@@ -82,6 +84,10 @@ export interface GetAgentMessagesResult {total: number;offset: number;limit: number;+ /** Resolved conversation ID used by the server */+ conversationId?: string;+ /** Context window size (tokens) used by this session */+ contextWindowTokens?: number;}/** getHubInfo - no params needed */@@ -145,4 +151,6 @@ export interface VerifyParams {export interface VerifyResult {hubId: string;agentId: string;+ /** Main conversation for this agent. Defaults to agentId in legacy mode. */+ mainConversationId?: string;}diff --git a/packages/core/src/client/actions/stream.ts b/packages/core/src/client/actions/stream.tsindex cf1349d3c9..e40afaece4 100644--- a/packages/core/src/client/actions/stream.ts+++ b/packages/core/src/client/actions/stream.ts@@ -62,6 +62,8 @@ export type AgentErrorEvent = {export interface StreamPayload {streamId: string;agentId: string;+ /** Optional conversation ID. Falls back to agentId in legacy mode. */+ conversationId?: string;event: AgentEvent | CompactionEvent | AgentErrorEvent;}diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.tsindex cf7bf932b9..d03f14c008 100644--- a/packages/core/src/client/client.ts+++ b/packages/core/src/client/client.ts@@ -234,7 +234,7 @@ export class GatewayClient {}/** Hub 验证成功回调 */- onVerified(callback: (result: { hubId: string; agentId: string; isNewDevice?: boolean }) => void): this {+ onVerified(callback: (result: { hubId: string; agentId: string; mainConversationId?: string; isNewDevice?: boolean }) => void): this {this.callbacks.onVerified = callback;return this;}@@ -318,7 +318,7 @@ export class GatewayClient {platform: navigator.platform,language: navigator.language,} : undefined;- this.request<{ hubId: string; agentId: string; isNewDevice?: boolean }>(+ this.request<{ hubId: string; agentId: string; mainConversationId?: string; isNewDevice?: boolean }>(this.options.hubId,"verify",{ token: this.options.token, meta },diff --git a/packages/core/src/client/types.ts b/packages/core/src/client/types.tsindex f8a3f69337..5eb13bc2c9 100644--- a/packages/core/src/client/types.ts+++ b/packages/core/src/client/types.ts@@ -110,7 +110,7 @@ export interface GatewayClientCallbacks {onConnect?: (socketId: string) => void;onDisconnect?: (reason: string) => void;onRegistered?: (deviceId: string) => void;- onVerified?: (result: { hubId: string; agentId: string; isNewDevice?: boolean }) => void;+ onVerified?: (result: { hubId: string; agentId: string; mainConversationId?: string; isNewDevice?: boolean }) => void;onMessage?: (message: RoutedMessage) => void;onSendError?: (error: SendErrorResponse) => void;onPong?: (data: string) => void;diff --git a/packages/core/src/hub/exec-approval-manager.ts b/packages/core/src/hub/exec-approval-manager.tsindex e3028b9a4f..d2208bdb5e 100644--- a/packages/core/src/hub/exec-approval-manager.ts+++ b/packages/core/src/hub/exec-approval-manager.ts@@ -24,7 +24,7 @@ interface PendingEntry {* The Hub wires this to Gateway message sending.*/export type SendApprovalToClient = (- agentId: string,+ conversationId: string,payload: ExecApprovalRequest,) => void;@@ -42,6 +42,7 @@ export class ExecApprovalManager {*/requestApproval(params: {agentId: string;+ conversationId?: string;command: string;cwd?: string;riskLevel: "safe" | "needs-review" | "dangerous";@@ -53,10 +54,12 @@ export class ExecApprovalManager {const approvalId = uuidv7();const timeoutMs = params.timeoutMs ?? this.defaultTimeoutMs;const expiresAtMs = timeoutMs >= 0 ? Date.now() + timeoutMs : -1;+ const conversationId = params.conversationId ?? params.agentId;const request: ExecApprovalRequest = {approvalId,agentId: params.agentId,+ conversationId,command: params.command,cwd: params.cwd,riskLevel: params.riskLevel,@@ -85,7 +88,7 @@ export class ExecApprovalManager {// Send to client via Gatewaytry {- this.sendToClient(params.agentId, request);+ this.sendToClient(conversationId, request);} catch (err) {// If sending fails, auto-deny (fail-closed)if (timer) clearTimeout(timer);@@ -121,7 +124,8 @@ export class ExecApprovalManager {*/cancelPending(agentId: string): void {for (const [id, entry] of this.pending) {- if (entry.request.agentId === agentId) {+ const requestConversationId = entry.request.conversationId ?? entry.request.agentId;+ if (entry.request.agentId === agentId || requestConversationId === agentId) {if (entry.timer) clearTimeout(entry.timer);this.pending.delete(id);entry.resolve({ approved: false, decision: "deny" });diff --git a/packages/core/src/hub/hub.ts b/packages/core/src/hub/hub.tsindex bafa255355..9d838b2c75 100644--- a/packages/core/src/hub/hub.ts+++ b/packages/core/src/hub/hub.ts@@ -64,6 +64,8 @@ export type MessageSource =/** Inbound message event broadcast to all listeners */export interface InboundMessageEvent {agentId: string;+ /** Optional conversation ID. Falls back to agentId in legacy mode. */+ conversationId?: string;content: string;source: MessageSource;timestamp: number;@@ -74,7 +76,7 @@ export class Hub {private readonly agentSenders = new Map<string, string>();private readonly agentStreamIds = new Map<string, string>();private readonly agentStreamCounters = new Map<string, number>();- private readonly pendingAssistantStarts = new Map<string, { agentId: string; event: unknown }>();+ private readonly pendingAssistantStarts = new Map<string, { agentId: string; conversationId: string; event: unknown }>();private readonly suppressedStreamAgents = new Set<string>();private readonly localApprovalHandlers = new Map<string, (payload: ExecApprovalRequest) => void>();private readonly inboundListeners = new Set<(event: InboundMessageEvent) => void>();@@ -127,17 +129,17 @@ export class Hub {this.rpc.register("wake-heartbeat", createWakeHeartbeatHandler(this));// Initialize exec approval manager- this.approvalManager = new ExecApprovalManager((agentId, payload) => {+ this.approvalManager = new ExecApprovalManager((conversationId, payload) => {// Check local IPC handler first (for desktop direct chat)- const localHandler = this.localApprovalHandlers.get(agentId);+ const localHandler = this.localApprovalHandlers.get(conversationId);if (localHandler) {localHandler(payload);return;}// Remote: send via Gateway- const targetDeviceId = this.agentSenders.get(agentId);+ const targetDeviceId = this.agentSenders.get(conversationId);if (!targetDeviceId) {- throw new Error(`No client device found for agent ${agentId}`);+ throw new Error(`No client device found for conversation ${conversationId}`);}this.client.send(targetDeviceId, "exec-approval-request", payload);});@@ -276,27 +278,29 @@ export class Hub {}// Regular chat message- const payload = msg.payload as { agentId?: string; content?: string } | undefined;+ const payload = msg.payload as { agentId?: string; conversationId?: string; content?: string } | undefined;const agentId = payload?.agentId;+ const conversationId = this.resolveConversationId(agentId, payload?.conversationId);const content = payload?.content;if (!agentId || !content) {console.warn(`[Hub] Invalid payload, missing agentId or content`);return;}- const agent = this.agents.get(agentId);+ const agent = this.agents.get(conversationId);if (agent && !agent.closed) {- this.agentSenders.set(agentId, msg.from);+ this.agentSenders.set(conversationId, msg.from);this.channelManager.clearLastRoute();const source: MessageSource = { type: "gateway", deviceId: msg.from };this.broadcastInbound({agentId,+ conversationId,content,source,timestamp: Date.now(),});agent.write(content, { source });} else {- console.warn(`[Hub] Agent not found or closed: ${agentId}`);+ console.warn(`[Hub] Conversation not found or closed: ${conversationId} (agent=${agentId})`);}});@@ -395,6 +399,19 @@ export class Hub {return agent;}+ /**+ * Create a new conversation runtime.+ *+ * Semantics:+ * - Agent = capability/profile definition+ * - Conversation = one isolated runtime/session thread+ *+ * Current runtime stores one AsyncAgent per conversation.+ */+ createConversation(id?: string, options?: { persist?: boolean; profileId?: string }): AsyncAgent {+ return this.createAgent(id, options);+ }+private getMessageIdFromEvent(event: unknown): string | undefined {if (!event || typeof event !== "object") return undefined;const maybeMsg = (event as { message?: unknown }).message;@@ -403,6 +420,13 @@ export class Hub {return typeof id === "string" && id.length > 0 ? id : undefined;}+ private resolveConversationId(agentId: string | undefined, conversationId?: string): string {+ const fallback = (agentId ?? "").trim();+ if (!fallback) return "";+ const normalizedConversationId = (conversationId ?? "").trim();+ return normalizedConversationId || fallback;+ }+private beginStream(agentId: string, event: unknown): string {const explicitId = this.getMessageIdFromEvent(event);if (explicitId) {@@ -426,7 +450,7 @@ export class Hub {private clearPendingAssistantStarts(agentId: string): void {for (const [streamId, pending] of this.pendingAssistantStarts) {- if (pending.agentId === agentId) {+ if (pending.agentId === agentId || pending.conversationId === agentId) {this.pendingAssistantStarts.delete(streamId);}}@@ -434,28 +458,31 @@ export class Hub {/** Internally read agent output and send via Gateway */private async consumeAgent(agent: AsyncAgent): Promise<void> {+ const conversationId = agent.sessionId;+ const agentId = agent.sessionId;for await (const item of agent.read()) {- const targetDeviceId = this.agentSenders.get(agent.sessionId);+ const targetDeviceId = this.agentSenders.get(conversationId);if (!targetDeviceId) continue;if ("content" in item) {// Legacy Message (error fallback)- console.log(`[${agent.sessionId}] ${item.content}`);+ console.log(`[${conversationId}] ${item.content}`);this.client.send(targetDeviceId, "message", {- agentId: agent.sessionId,+ agentId,+ conversationId,content: item.content,});} else {- const suppressForAgent = this.suppressedStreamAgents.has(agent.sessionId);+ const suppressForAgent = this.suppressedStreamAgents.has(conversationId);// Suppress all user-visible stream events during silent heartbeat runs.if (suppressForAgent) {if (item.type === "message_start") {- this.beginStream(agent.sessionId, item);+ this.beginStream(conversationId, item);} else if (item.type === "message_end") {- const streamId = this.getActiveStreamId(agent.sessionId, item);+ const streamId = this.getActiveStreamId(conversationId, item);this.pendingAssistantStarts.delete(streamId);- this.endStream(agent.sessionId);+ this.endStream(conversationId);}continue;}@@ -465,8 +492,9 @@ export class Hub {item.type === "compaction_start" || item.type === "compaction_end" || item.type === "agent_error";if (isPassthroughEvent) {this.client.send(targetDeviceId, StreamAction, {- streamId: `system:${agent.sessionId}`,- agentId: agent.sessionId,+ streamId: `system:${conversationId}`,+ agentId,+ conversationId,event: item,});continue;@@ -489,17 +517,17 @@ export class Hub {// This lets us suppress pure HEARTBEAT_OK acknowledgements end-to-end.if (isAssistantMessageEvent && isAssistantMessage) {if (item.type === "message_start") {- const streamId = this.beginStream(agent.sessionId, item);- this.pendingAssistantStarts.set(streamId, { agentId: agent.sessionId, event: item });+ const streamId = this.beginStream(conversationId, item);+ this.pendingAssistantStarts.set(streamId, { agentId, conversationId, event: item });continue;}- const streamId = this.getActiveStreamId(agent.sessionId, item);+ const streamId = this.getActiveStreamId(conversationId, item);const isHeartbeatAck = isHeartbeatAckEvent(item);if (isHeartbeatAck) {if (item.type === "message_end") {this.pendingAssistantStarts.delete(streamId);- this.endStream(agent.sessionId);+ this.endStream(conversationId);}continue;}@@ -508,7 +536,8 @@ export class Hub {if (pendingStart) {this.client.send(targetDeviceId, StreamAction, {streamId,- agentId: agent.sessionId,+ agentId: pendingStart.agentId,+ conversationId: pendingStart.conversationId,event: pendingStart.event,});this.pendingAssistantStarts.delete(streamId);@@ -516,19 +545,21 @@ export class Hub {this.client.send(targetDeviceId, StreamAction, {streamId,- agentId: agent.sessionId,+ agentId,+ conversationId,event: item,});if (item.type === "message_end") {- this.endStream(agent.sessionId);+ this.endStream(conversationId);}continue;}- const streamId = this.getActiveStreamId(agent.sessionId, item);+ const streamId = this.getActiveStreamId(conversationId, item);this.client.send(targetDeviceId, StreamAction, {streamId,- agentId: agent.sessionId,+ agentId,+ conversationId,event: item,});}@@ -582,7 +613,7 @@ export class Hub {* Create an exec approval callback for an agent.* This wires the safety evaluation + Hub approval manager together.*/- private createExecApprovalCallback(sessionId: string, profileId: string): ExecApprovalCallback {+ private createExecApprovalCallback(conversationId: string, profileId: string): ExecApprovalCallback {return async (command: string, cwd: string | undefined): Promise<ApprovalResult> => {// Load exec approval config from profilelet config: ExecApprovalConfig = {};@@ -636,7 +667,8 @@ export class Hub {// Request approval via Hub → Gateway → Clientconst result = await this.approvalManager.requestApproval({- agentId: sessionId,+ agentId: conversationId,+ conversationId,command,...(cwd !== undefined ? { cwd } : {}),riskLevel: evaluation.riskLevel,@@ -705,12 +737,20 @@ export class Hub {return this.agents.get(id);}+ getConversation(id: string): AsyncAgent | undefined {+ return this.getAgent(id);+ }+listAgents(): string[] {return Array.from(this.agents.entries()).filter(([, a]) => !a.closed).map(([id]) => id);}+ listConversations(): string[] {+ return this.listAgents();+ }+/** Subscribe heartbeat state updates. Returns unsubscribe callback. */onHeartbeatEvent(callback: (event: HeartbeatEventPayload) => void): () => void {this.heartbeatListeners.add(callback);@@ -785,6 +825,10 @@ export class Hub {return true;}+ closeConversation(id: string): boolean {+ return this.closeAgent(id);+ }+shutdown(): void {// Stop all channel connectionsthis.channelManager.stopAll();diff --git a/packages/core/src/hub/rpc/handlers/get-agent-messages.ts b/packages/core/src/hub/rpc/handlers/get-agent-messages.tsindex 3a008c706e..e5a164da53 100644--- a/packages/core/src/hub/rpc/handlers/get-agent-messages.ts+++ b/packages/core/src/hub/rpc/handlers/get-agent-messages.ts@@ -8,6 +8,7 @@ const DEFAULT_LIMIT = 200;interface GetAgentMessagesParams {agentId: string;+ conversationId?: string;offset?: number;limit?: number;}@@ -17,18 +18,19 @@ export function createGetAgentMessagesHandler(): RpcHandler {if (!params || typeof params !== "object") {throw new RpcError("INVALID_PARAMS", "params must be an object");}- const { agentId, limit = DEFAULT_LIMIT } = params as GetAgentMessagesParams;+ const { agentId, conversationId, limit = DEFAULT_LIMIT } = params as GetAgentMessagesParams;let { offset } = params as GetAgentMessagesParams;if (!agentId) {throw new RpcError("INVALID_PARAMS", "Missing required param: agentId");}+ const resolvedConversationId = (conversationId ?? "").trim() || agentId;- const sessionPath = resolveSessionPath(agentId);+ const sessionPath = resolveSessionPath(resolvedConversationId);if (!existsSync(sessionPath)) {- throw new RpcError("AGENT_NOT_FOUND", `No session found for agent: ${agentId}`);+ throw new RpcError("AGENT_NOT_FOUND", `No session found for conversation: ${resolvedConversationId}`);}- const session = new SessionManager({ sessionId: agentId });+ const session = new SessionManager({ sessionId: resolvedConversationId });const allMessages = session.loadMessagesForDisplay();const total = allMessages.length;const contextWindowTokens = session.getMeta()?.contextWindowTokens ?? session.getContextWindowTokens();@@ -40,6 +42,6 @@ export function createGetAgentMessagesHandler(): RpcHandler {const sliced = allMessages.slice(offset, offset + limit);- return { messages: sliced, total, offset, limit, contextWindowTokens };+ return { messages: sliced, total, offset, limit, conversationId: resolvedConversationId, contextWindowTokens };};}diff --git a/packages/core/src/hub/rpc/handlers/verify.ts b/packages/core/src/hub/rpc/handlers/verify.tsindex 67bcfda892..68c6a9d37a 100644--- a/packages/core/src/hub/rpc/handlers/verify.ts+++ b/packages/core/src/hub/rpc/handlers/verify.ts@@ -21,7 +21,12 @@ export function createVerifyHandler(ctx: VerifyContext): RpcHandler {// 1. Already in whitelist → pass through (reconnection, no confirmation needed)const allowed = ctx.deviceStore.isAllowed(from);if (allowed) {- return { hubId: ctx.hubId, agentId: allowed.agentId, isNewDevice: false };+ return {+ hubId: ctx.hubId,+ agentId: allowed.agentId,+ mainConversationId: allowed.agentId,+ isNewDevice: false,+ };}// 2. Validate token@@ -42,6 +47,11 @@ export function createVerifyHandler(ctx: VerifyContext): RpcHandler {// 4. User confirmed → add to whitelist (with device metadata)ctx.deviceStore.allowDevice(from, result.agentId, meta);- return { hubId: ctx.hubId, agentId: result.agentId, isNewDevice: true };+ return {+ hubId: ctx.hubId,+ agentId: result.agentId,+ mainConversationId: result.agentId,+ isNewDevice: true,+ };};}diff --git a/packages/hooks/src/use-chat.ts b/packages/hooks/src/use-chat.tsindex 3bf344e260..0528335a5d 100644--- a/packages/hooks/src/use-chat.ts+++ b/packages/hooks/src/use-chat.ts@@ -56,6 +56,7 @@ export interface Message {role: "user" | "assistant" | "toolResult" | "system";content: ContentBlock[];agentId: string;+ conversationId?: string;stopReason?: string;toolCallId?: string;toolName?: string;@@ -174,8 +175,21 @@ export function useChat() {const isStreaming = streamingIds.size > 0;+ const reset = useCallback(() => {+ setMessages([]);+ setStreamingIds(new Set());+ setPendingApprovals([]);+ setError(null);+ setHasMore(false);+ setContextWindowTokens(undefined);+ }, []);+/** Convert raw AgentMessageItem[] → Message[] */- const convertMessages = useCallback((raw: AgentMessageItem[], agentId: string): Message[] => {+ const convertMessages = useCallback((+ raw: AgentMessageItem[],+ agentId: string,+ conversationId = agentId,+ ): Message[] => {const toolCallArgsMap = new Map<string, { name: string; args: Record<string, unknown> }>();for (const m of raw) {if (m.role === "assistant") {@@ -190,9 +204,23 @@ export function useChat() {const loaded: Message[] = [];for (const m of raw) {if (m.role === "user") {- loaded.push({ id: uuidv7(), role: "user", content: toContentBlocks(m.content), agentId, source: m.source });+ loaded.push({+ id: uuidv7(),+ role: "user",+ content: toContentBlocks(m.content),+ agentId,+ conversationId,+ source: m.source,+ });} else if (m.role === "assistant") {- loaded.push({ id: uuidv7(), role: "assistant", content: toContentBlocks(m.content), agentId, stopReason: m.stopReason });+ loaded.push({+ id: uuidv7(),+ role: "assistant",+ content: toContentBlocks(m.content),+ agentId,+ conversationId,+ stopReason: m.stopReason,+ });} else if (m.role === "toolResult") {const callInfo = toolCallArgsMap.get(m.toolCallId);loaded.push({@@ -200,6 +228,7 @@ export function useChat() {role: "toolResult",content: toContentBlocks(m.content),agentId,+ conversationId,toolCallId: m.toolCallId,toolName: m.toolName,toolArgs: callInfo?.args,@@ -216,8 +245,9 @@ export function useChat() {raw: AgentMessageItem[],agentId: string,meta?: { total: number; offset: number; contextWindowTokens?: number },+ conversationId?: string,) => {- const loaded = convertMessages(raw, agentId);+ const loaded = convertMessages(raw, agentId, conversationId ?? agentId);setMessages(loaded);if (meta) {setHasMore(meta.offset > 0);@@ -232,8 +262,9 @@ export function useChat() {raw: AgentMessageItem[],agentId: string,meta: { total: number; offset: number; contextWindowTokens?: number },+ conversationId?: string,) => {- const older = convertMessages(raw, agentId);+ const older = convertMessages(raw, agentId, conversationId ?? agentId);setMessages((prev) => [...older, ...prev]);setHasMore(meta.offset > 0);if (meta.contextWindowTokens !== undefined) {@@ -242,16 +273,29 @@ export function useChat() {}, [convertMessages]);/** Add a user message */- const addUserMessage = useCallback((text: string, agentId: string, source?: MessageSource) => {+ const addUserMessage = useCallback((+ text: string,+ agentId: string,+ source?: MessageSource,+ conversationId?: string,+ ) => {setMessages((prev) => [...prev,- { id: uuidv7(), role: "user", content: [{ type: "text", text }], agentId, source },+ {+ id: uuidv7(),+ role: "user",+ content: [{ type: "text", text }],+ agentId,+ conversationId: conversationId ?? agentId,+ source,+ },]);}, []);/** Process a StreamPayload → update messages + streamingIds */const handleStream = useCallback((payload: StreamPayload) => {const { event } = payload;+ const conversationId = payload.conversationId ?? payload.agentId;switch (event.type) {case "message_start": {@@ -260,6 +304,7 @@ export function useChat() {role: "assistant",content: [],agentId: payload.agentId,+ conversationId,};const content = extractContent(event);if (content.length) newMsg.content = content;@@ -285,7 +330,12 @@ export function useChat() {setMessages((prev) =>prev.map((m) => {if (m.id === payload.streamId) return { ...m, content, stopReason };- if (m.role === "toolResult" && m.toolStatus === "running" && m.agentId === payload.agentId) {+ if (+ m.role === "toolResult"+ && m.toolStatus === "running"+ && m.agentId === payload.agentId+ && (m.conversationId ?? m.agentId) === conversationId+ ) {return { ...m, toolStatus: "interrupted" as ToolStatus };}return m;@@ -306,6 +356,7 @@ export function useChat() {role: "toolResult",content: [],agentId: payload.agentId,+ conversationId,toolCallId: event.toolCallId,toolName: event.toolName,toolArgs: event.args as Record<string, unknown> | undefined,@@ -358,6 +409,7 @@ export function useChat() {role: "system",content: [],agentId: payload.agentId,+ conversationId,systemType: "compaction",compaction: {removed: ce.removed,@@ -394,6 +446,7 @@ export function useChat() {error,// State control (for transport layer to call)setError,+ reset,setHistory,prependHistory,addUserMessage,diff --git a/packages/hooks/src/use-gateway-chat.ts b/packages/hooks/src/use-gateway-chat.tsindex 5b98efa8b8..bf8e94d989 100644--- a/packages/hooks/src/use-gateway-chat.ts+++ b/packages/hooks/src/use-gateway-chat.ts@@ -17,10 +17,12 @@ interface UseGatewayChatOptions {client: GatewayClient;hubId: string;agentId: string;+ conversationId?: string;}-export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptions) {+export function useGatewayChat({ client, hubId, agentId, conversationId }: UseGatewayChatOptions) {const chat = useChat();+ const resolvedConversationId = conversationId ?? agentId;const [isLoading, setIsLoading] = useState(false);const [isLoadingHistory, setIsLoadingHistory] = useState(true);const [isLoadingMore, setIsLoadingMore] = useState(false);@@ -32,6 +34,7 @@ export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptionsclient.request<GetAgentMessagesResult>(hubId, "getAgentMessages", {agentId,+ conversationId: resolvedConversationId,limit: DEFAULT_MESSAGES_LIMIT,}).then((result) => {@@ -39,18 +42,22 @@ export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptionstotal: result.total,offset: result.offset,contextWindowTokens: result.contextWindowTokens,- });+ }, result.conversationId ?? resolvedConversationId);offsetRef.current = result.offset;}).catch(() => {}).finally(() => setIsLoadingHistory(false));- }, [client, hubId, agentId]);+ }, [client, hubId, agentId, resolvedConversationId]);// Subscribe to eventsuseEffect(() => {client.onMessage((msg) => {if (msg.action === StreamAction) {const payload = msg.payload as StreamPayload;+ const payloadConversationId = payload.conversationId ?? payload.agentId;+ if (payload.agentId !== agentId || payloadConversationId !== resolvedConversationId) {+ return;+ }if (payload.event.type === "agent_error") {const errorMsg = (payload.event as { message?: string }).message ?? "Unknown error";chat.setError({ code: "AGENT_ERROR", message: errorMsg });@@ -63,7 +70,12 @@ export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptionsreturn;}if (msg.action === ExecApprovalRequestAction) {- chat.addApproval(msg.payload as ExecApprovalRequestPayload);+ const approval = msg.payload as ExecApprovalRequestPayload;+ const approvalConversationId = approval.conversationId ?? approval.agentId;+ if (approval.agentId !== agentId || approvalConversationId !== resolvedConversationId) {+ return;+ }+ chat.addApproval(approval);return;}if (msg.action === "error") {@@ -72,18 +84,18 @@ export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptions}});return () => { client.onMessage(() => {}); };- }, [client]);+ }, [client, agentId, resolvedConversationId]);const sendMessage = useCallback((text: string) => {const trimmed = text.trim();if (!trimmed) return;- chat.addUserMessage(trimmed, agentId);+ chat.addUserMessage(trimmed, agentId, { type: "local" }, resolvedConversationId);chat.setError(null);- client.send(hubId, "message", { agentId, content: trimmed });+ client.send(hubId, "message", { agentId, conversationId: resolvedConversationId, content: trimmed });setIsLoading(true);},- [client, hubId, agentId],+ [client, hubId, agentId, resolvedConversationId],);const loadMore = useCallback(async () => {@@ -96,13 +108,13 @@ export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptionsconst newOffset = Math.max(0, currentOffset - DEFAULT_MESSAGES_LIMIT);const limit = currentOffset - newOffset;const result = await client.request<GetAgentMessagesResult>(- hubId, "getAgentMessages", { agentId, offset: newOffset, limit },+ hubId, "getAgentMessages", { agentId, conversationId: resolvedConversationId, offset: newOffset, limit },);chat.prependHistory(result.messages, agentId, {total: result.total,offset: result.offset,contextWindowTokens: result.contextWindowTokens,- });+ }, result.conversationId ?? resolvedConversationId);offsetRef.current = result.offset;} catch {// Best-effort — pagination failure does not block chat@@ -110,7 +122,7 @@ export function useGatewayChat({ client, hubId, agentId }: UseGatewayChatOptionsisLoadingMoreRef.current = false;setIsLoadingMore(false);}- }, [client, hubId, agentId]);+ }, [client, hubId, agentId, resolvedConversationId]);const resolveApproval = useCallback((approvalId: string, decision: ApprovalDecision) => {diff --git a/packages/hooks/src/use-gateway-connection.ts b/packages/hooks/src/use-gateway-connection.tsindex 525b512bf6..85d9d98989 100644--- a/packages/hooks/src/use-gateway-connection.ts+++ b/packages/hooks/src/use-gateway-connection.ts@@ -14,6 +14,7 @@ export interface ConnectionIdentity {gateway: string;hubId: string;agentId: string;+ conversationId?: string;}function loadIdentity(): ConnectionIdentity | null {@@ -21,7 +22,14 @@ function loadIdentity(): ConnectionIdentity | null {const raw = localStorage.getItem(STORAGE_KEY);if (!raw) return null;const parsed = JSON.parse(raw);- if (parsed.gateway && parsed.hubId && parsed.agentId) return parsed;+ if (+ parsed.gateway+ && parsed.hubId+ && parsed.agentId+ && (parsed.conversationId === undefined || typeof parsed.conversationId === "string")+ ) {+ return parsed;+ }return null;} catch {return null;diff --git a/packages/sdk/src/actions/exec-approval.ts b/packages/sdk/src/actions/exec-approval.tsindex cd098273d2..3c4d6dd952 100644--- a/packages/sdk/src/actions/exec-approval.ts+++ b/packages/sdk/src/actions/exec-approval.ts@@ -14,6 +14,8 @@ export interface ExecApprovalRequestPayload {approvalId: string;/** Agent that initiated the command */agentId: string;+ /** Optional conversation ID. Falls back to agentId in legacy mode. */+ conversationId?: string;/** Shell command requiring approval */command: string;/** Working directory */diff --git a/packages/sdk/src/actions/rpc.ts b/packages/sdk/src/actions/rpc.tsindex a49f1579a2..8a665a3e61 100644--- a/packages/sdk/src/actions/rpc.ts+++ b/packages/sdk/src/actions/rpc.ts@@ -66,6 +66,8 @@ export const DEFAULT_MESSAGES_LIMIT = 200;/** getAgentMessages - request params */export interface GetAgentMessagesParams {agentId: string;+ /** Optional conversation ID. Falls back to agent main conversation when omitted. */+ conversationId?: string;offset?: number;limit?: number;}@@ -91,6 +93,8 @@ export interface GetAgentMessagesResult {total: number;offset: number;limit: number;+ /** Resolved conversation ID used by the server */+ conversationId?: string;/** Context window size (tokens) used by this session */contextWindowTokens?: number;}@@ -157,4 +161,6 @@ export interface VerifyParams {export interface VerifyResult {hubId: string;agentId: string;+ /** Main conversation for this agent. Defaults to agentId in legacy mode. */+ mainConversationId?: string;}diff --git a/packages/sdk/src/actions/stream.ts b/packages/sdk/src/actions/stream.tsindex cf1349d3c9..e40afaece4 100644--- a/packages/sdk/src/actions/stream.ts+++ b/packages/sdk/src/actions/stream.ts@@ -62,6 +62,8 @@ export type AgentErrorEvent = {export interface StreamPayload {streamId: string;agentId: string;+ /** Optional conversation ID. Falls back to agentId in legacy mode. */+ conversationId?: string;event: AgentEvent | CompactionEvent | AgentErrorEvent;}diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.tsindex cf7bf932b9..d03f14c008 100644--- a/packages/sdk/src/client.ts+++ b/packages/sdk/src/client.ts@@ -234,7 +234,7 @@ export class GatewayClient {}/** Hub 验证成功回调 */- onVerified(callback: (result: { hubId: string; agentId: string; isNewDevice?: boolean }) => void): this {+ onVerified(callback: (result: { hubId: string; agentId: string; mainConversationId?: string; isNewDevice?: boolean }) => void): this {this.callbacks.onVerified = callback;return this;}@@ -318,7 +318,7 @@ export class GatewayClient {platform: navigator.platform,language: navigator.language,} : undefined;- this.request<{ hubId: string; agentId: string; isNewDevice?: boolean }>(+ this.request<{ hubId: string; agentId: string; mainConversationId?: string; isNewDevice?: boolean }>(this.options.hubId,"verify",{ token: this.options.token, meta },diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.tsindex f8a3f69337..5eb13bc2c9 100644--- a/packages/sdk/src/types.ts+++ b/packages/sdk/src/types.ts@@ -110,7 +110,7 @@ export interface GatewayClientCallbacks {onConnect?: (socketId: string) => void;onDisconnect?: (reason: string) => void;onRegistered?: (deviceId: string) => void;- onVerified?: (result: { hubId: string; agentId: string; isNewDevice?: boolean }) => void;+ onVerified?: (result: { hubId: string; agentId: string; mainConversationId?: string; isNewDevice?: boolean }) => void;onMessage?: (message: RoutedMessage) => void;onSendError?: (error: SendErrorResponse) => void;onPong?: (data: string) => void;diff --git a/packages/store/src/connection.ts b/packages/store/src/connection.tsindex ca820c0d42..726cb39b99 100644--- a/packages/store/src/connection.ts+++ b/packages/store/src/connection.ts@@ -3,6 +3,7 @@ export interface ConnectionInfo {gateway: stringhubId: stringagentId: string+ conversationId?: stringtoken: stringexpires: number}@@ -15,12 +16,13 @@ function isConnectionInfo(obj: unknown): obj is ConnectionInfo {typeof o.gateway === "string" &&typeof o.hubId === "string" &&typeof o.agentId === "string" &&+ (o.conversationId === undefined || typeof o.conversationId === "string") &&typeof o.token === "string" &&typeof o.expires === "number")}-// Parse multica://connect?gateway=...&hub=...&agent=...&token=...&exp=... URL format+// Parse multica://connect?gateway=...&hub=...&agent=...&conversation=...&token=...&exp=... URL format// Uses string prefix + URLSearchParams to avoid cross-engine URL hostname differencesfunction parseConnectionUrl(input: string): ConnectionInfo | null {const prefix = "multica://connect?"@@ -30,6 +32,7 @@ function parseConnectionUrl(input: string): ConnectionInfo | null {const gateway = params.get("gateway")const hubId = params.get("hub")const agentId = params.get("agent")+ const conversationId = params.get("conversation")const token = params.get("token")const exp = params.get("exp")if (!gateway || !hubId || !agentId || !token || !exp) return null@@ -38,6 +41,7 @@ function parseConnectionUrl(input: string): ConnectionInfo | null {gateway,hubId,agentId,+ ...(conversationId ? { conversationId } : {}),token,expires: Number(exp),}diff --git a/packages/store/src/types.ts b/packages/store/src/types.tsindex 213b3046a2..7b070adb63 100644--- a/packages/store/src/types.ts+++ b/packages/store/src/types.ts@@ -44,6 +44,7 @@ export interface Message {role: "user" | "assistant" | "toolResult" | "system"content: ContentBlock[]agentId: string+ conversationId?: stringstopReason?: stringtoolCallId?: stringtoolName?: stringdiff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex bbf154f496..1abe607069 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -170,6 +170,7 @@ export type StreamEventType =export interface StreamEvent {type: StreamEventTypeagentId: string+ conversationId?: stringstreamId?: stringdata?: unknown}@@ -185,6 +186,7 @@ export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'export interface ExecApprovalRequest {approvalId: stringagentId: string+ conversationId?: stringcommand: stringcwd?: stringriskLevel: RiskLeveldiff --git a/packages/ui/src/components/device-pairing.tsx b/packages/ui/src/components/device-pairing.tsxindex afae275fc0..ec68c05f10 100644--- a/packages/ui/src/components/device-pairing.tsx+++ b/packages/ui/src/components/device-pairing.tsx@@ -37,6 +37,7 @@ export interface ConnectionIdentity {gateway: string;hubId: string;agentId: string;+ conversationId?: string;}export interface DevicePairingProps {@@ -150,7 +151,12 @@ export function DevicePairing({navigator.vibrate?.(50);setTimeout(() => {onConnect(- { gateway: info.gateway, hubId: info.hubId, agentId: info.agentId },+ {+ gateway: info.gateway,+ hubId: info.hubId,+ agentId: info.agentId,+ ...(info.conversationId ? { conversationId: info.conversationId } : {}),+ },info.token,);}, 600);@@ -183,7 +189,12 @@ export function DevicePairing({async (data: string) => {const info = parseConnectionCode(data);onConnect(- { gateway: info.gateway, hubId: info.hubId, agentId: info.agentId },+ {+ gateway: info.gateway,+ hubId: info.hubId,+ agentId: info.agentId,+ ...(info.conversationId ? { conversationId: info.conversationId } : {}),+ },info.token,);},