Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge upstream/main and retain work state with history cache revisions
Chrise14d56faa53f
diff --cc apps/desktop/src/main/maker-ipc/chatServer.tsindex be1553dea8,f0ba0055b8..b909b09068--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@@ -1414,9 -1498,9 +1501,9 @@@ function createChatServer(local: BotGroincomingMessageTimes: incomingMessageTimes(s.messages, s.members),...(unread ? { serverUnread: { count: Math.min(99, unread.length), mentioned: unread.some(m => m.mentions?.includes(selfId)) } } : {}),createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),- messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),+ messages, ...(projection ? { historyRevision: projection.generation, messageUpdates } : {}), executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),...(shares ? { threadShareVersion: shares.version } : {}), ...(threadList ? { threads: threadList } : {}), hasMoreBefore: page.length === (o.limit ?? 100), plans,- round: { status: deciding || executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers,+ round: { status: deciding || executions.some(e => ['queued', 'running', 'needs_input', 'stopping'].includes(e.status)) ? 'running' : 'idle', speakers,othersActive: executions.some(e => ['queued', 'running', 'needs_input'].includes(e.status) && e.requester_id !== selfId&& !localBot(e.bot_id) && !s.members.some(m => m.id === e.bot_id && m.ownerActorId === selfId)), canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || s.messages.some(discussionSource)) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };}diff --cc apps/mobile/src/__tests__/chatServerClient.test.tsindex 8a9f4c8f4d,aed21db3ec..deff8cbfc4--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@@ -2,6 -2,6 +2,7 @@@ import { describe, expect, it, vi } froimport { i18n } from '@/i18n';import { botGroupNewMessageCount } from '@cindy/maker-shared/botGroupPresentation';import { chatGroupView, chatRoomRow, chatReadAt, createChatServerClient, type ChatMessage, type ChatPage, type ChatRoom, type ChatSnapshot } from '@/chat/chatServerClient';++import type { ChatHistory } from '@cindy/maker-shared/chat-history';import { botGroupQuoteFromMessage, resolveBotGroupQuote, buildBotGroupQuoteCard, buildBotGroupTaskCard } from '@cindy/maker-shared/botGroupChat';const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;const room = (n = 1, state = 'joined'): ChatRoom => ({ id: id(n), name: 'Discussion', kind: 'group', state, archived: false,@@@ -13,6 -13,6 +14,29 @@@ const snapshot = (): ChatSnapshot => ({ id: id(10), kind: 'human', name: 'Other member', state: 'joined', ownerActorId: id(10), ownerName: '', avatar: null, role: 'member' },] });++// Merge regression: history generation changes while execution state is read.++// Production load must retry, retaining both the new revision and fresh work.++it('retains fresh executions when cached history changes during load', async () => {++ const stored = {++ snapshot: vi.fn().mockResolvedValueOnce({ ...snapshot(), cacheGeneration: 'old' })++ .mockResolvedValue({ ...snapshot(), cacheGeneration: 'current' }),++ page: vi.fn(async () => [message(20)]),++ projection: vi.fn(async () => ({ generation: 'current', messages: [] })),++ };++ let reads = 0;++ const request = vi.fn(async (path: string) => {++ if (path === '/me') return { actor: { id: id(11), kind: 'human' } };++ if (path.endsWith('/executions')) return [{ id: id(++reads === 1 ? 30 : 31), bot_id: id(12), status: 'stopping', epoch: 1, source_message_id: id(20) }];++ if (path.includes('/execution-failures?')) return [];++ throw new Error(path);++ });++ const client = createChatServerClient(request as any, undefined, async () => stored as unknown as ChatHistory);++ const page = await client.load(id(1));++ expect(stored.snapshot).toHaveBeenCalledTimes(2);++ expect(page.historyRevision).toBe('current');++ expect(chatGroupView(page, id(11)).round.speakers.map(speaker => [speaker.executionId, speaker.executionStatus])).toEqual([[id(31), 'stopping']]);++});++describe('direct Chat Server client', () => {// #6907: existing fixtures never pair a human's group name A with account ownerName B (unit tier).it('keeps owner labels scoped to each group and follows refreshed names without changing identities', () => {diff --cc apps/mobile/src/chat/chatServerClient.tsindex fa3d741389,103c0021b9..f89f5c4b68--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@@ -30,8 -31,7 +31,8 @@@ export interface ChatExecutionFailureid: string; conversation_id?: string; source_message_id: string; bot_id: string; epoch: number; status?: string;failure_code?: unknown; updated_at?: string; plan_id?: string | null;}-export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[]; historyRevision?: string }+export interface ChatExecution extends ChatExecutionFailure { requester_id?: string; created_at?: string; status: string }- export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[]; executions?: ChatExecution[] }++export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[]; executions?: ChatExecution[]; historyRevision?: string }/** `actorId` acts as one of the account's own actors (Chat Server `X-Chat-Actor`). */export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST' | 'PATCH', body?: unknown, actorId?: string, signal?: AbortSignal) => Promise<T>;/** An actor the account owns; a companion's `externalId` is its bot id on every computer. */@@@ -239,11 -234,18 +240,18 @@@ export function chatGroupView(page: ChaorganizerBotId: room.organizer_id ?? null, projectDir: null, projectDirName: null,createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),lastMessage: last ? { authorKind: last.authorKind, authorName: last.authorName, preview: mobileMarkdownPreviewText(botGroupMessageSummaryText(last)).slice(0, 80), createdAt: last.createdAt } : null,- speakingBotIds: [], planningBotId: null, openPlan: null, plans: [], messages: projectBotGroupExecutionFailures(messages, failures),- hasMoreBefore: page.before !== null, round: { status: 'idle', speakers: [], canContinue: false }, supportsAttachments: false };+ speakingBotIds: speakers.map(speaker => speaker.botId), planningBotId: null, openPlan: null, plans: [], messages: projectBotGroupExecutionFailures(messages, failures),+ hasMoreBefore: page.before !== null, round: { status: speakers.length ? 'running' : 'idle', speakers, canContinue: false }, supportsAttachments: false };}- export function createChatServerClient(request: ChatRequest, personalList = createConversationListState()) {+ export function createChatServerClient(request: ChatRequest, personalList = createConversationListState(),+ openHistory?: (human: string) => Promise<ChatHistory>) {+ let historyCache: Promise<ChatHistory> | undefined;+ const cache = () => openHistory ? historyCache ??= identity().then(openHistory).catch(error => { historyCache = undefined; throw error; }) : undefined;+ async function messagePage(room: string, query: string) {+ const stored = await cache();+ return stored ? stored.page<ChatMessage>(room, new URLSearchParams(query)) : request<ChatMessage[]>(`/conversations/${room}/messages?${query}`);+ }// Preserve the posted quote through a lost response. Retrying an operation must// not change its content/recipients if the original is subsequently edited or removed.const postedQuotes = new Map<string, { content: ChatMessage['content']; mentions: string[] }>();@@@ -432,36 -453,14 +459,43 @@@const root = await request<ChatMessage>(`/conversations/${room}/messages/${chatId(threadRootId)}`);messages.push(root);}+ // Use the same execution snapshot for running status and stop controls.+ const executions = await request<ChatExecution[]>(`/conversations/${room}/executions`);- return { snapshot, messages, before, ...(threadRootId ? { threadRootId } : {}), failures: await failures(room, messages),+ const executionFailures = await failures(room, messages);+ const projection = await stored?.projection<ChatMessage>(room, []);+ if (projection && snapshot.cacheGeneration !== projection.generation) {+ if (attempt >= 2) throw new Error('CHAT_HISTORY_CHANGED');+ return this.load(roomId, undefined, threadRootId, attempt + 1);+ }+ return { snapshot, messages, before, ...(projection ? { historyRevision: projection.generation } : {}),- ...(threadRootId ? { threadRootId } : {}), failures: executionFailures };++ ...(threadRootId ? { threadRootId } : {}), failures: executionFailures,+ ...(Array.isArray(executions) ? { executions } : {}) };+ },+ async stop(roomId: string, operationId: string) {+ const room = chatId(roomId);+ const self = await identity();+ const snapshot = await request<ChatSnapshot>(`/conversations/${room}/snapshot`);+ const ownBots = new Set(snapshot.members.filter(member => member.state === 'joined' && member.kind === 'bot' && member.ownerActorId === self).map(member => member.id));+ const plans = await request<Array<{ id: string; status: string; creator_id: string; revision: number }>>(`/conversations/${room}/plans`);+ const stoppedPlans = new Set<string>();+ const refused = (error: unknown) => !!error && typeof error === 'object' && 'status' in error && [403, 404, 409].includes(Number(error.status));+ for (const plan of plans.filter(plan => plan.creator_id === self && ['proposed', 'running', 'waiting'].includes(plan.status))) {+ try {+ await request(`/conversations/${room}/plans/${chatId(plan.id)}`, 'POST', { operationId: `${operationId}:plan:${plan.id}`, expectedRevision: plan.revision, action: 'stop' });+ stoppedPlans.add(plan.id);+ } catch (error) { if (!refused(error)) throw error; }+ }+ const executions = await request<ChatExecution[]>(`/conversations/${room}/executions`);+ for (const execution of executions.filter(execution => ['queued', 'running', 'needs_input'].includes(execution.status) && !(execution.plan_id && stoppedPlans.has(execution.plan_id)))) {+ const asBot = execution.requester_id !== self && ownBots.has(execution.bot_id);+ if (execution.requester_id !== self && !asBot) continue;+ try {+ await request(`/conversations/${room}/executions/${chatId(execution.id)}/control`, 'POST',+ { operationId: `${operationId}:execution:${execution.id}`, action: 'stop' }, asBot ? execution.bot_id : undefined);+ } catch (error) {+ if (!refused(error)) throw error;+ }+ }},async older(roomId: string, page: ChatPage): Promise<ChatPage> {if (!page.before) return page;