Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

Merge upstream/main into bot-working-ledger

zqchris302d45b5bdbe
diff --cc apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index c5125ec8b4,27c6d376c9..82c42f5bb1
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@@ -3461,62 -3615,81 +3615,141 @@@ it('persists coordination audit metadat
});
});
+describe('working memory refresh after native compaction', () => {
+ const note = '[Working memory refresh · internal context]\n- 周五前改完周报模板';
+
+ it('prepends the refresh note once and consumes that generation only after the engine accepted the turn', async () => {
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ peekWorkingMemoryRefresh: vi.fn(async () => ({ generation: 7, note })),
+ consumeWorkingMemoryRefresh: vi.fn(),
+ });
+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello');
+ expect(vi.mocked(session.send).mock.calls[0]?.[0]).toBe(`${uiLanguageNote()}\n\n${note}\n\nhello`);
+ expect(deps.consumeWorkingMemoryRefresh).toHaveBeenCalledWith('session-1', 7);
+
+ const rejecting = createSession({ agentKind: 'codex', send: vi.fn(async () => ({ accepted: false }) as SessionSendResult) });
+ const { deps: rejectedDeps } = createDeps({
+ getSession: vi.fn(() => rejecting),
+ peekWorkingMemoryRefresh: vi.fn(async () => ({ generation: 7, note })),
+ consumeWorkingMemoryRefresh: vi.fn(),
+ });
+ await createMakerSendTransaction(rejectedDeps).sendToAgentAccepted('session-1', 'hello').catch(() => undefined);
+ expect(rejectedDeps.consumeWorkingMemoryRefresh).not.toHaveBeenCalled();
+ });
+
+ it('skips the refresh when a rebuild handoff already carries the ledger, but still consumes that generation', async () => {
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ peekPendingHandoff: vi.fn(async () => 'HANDOFF'),
+ peekWorkingMemoryRefresh: vi.fn(async () => ({ generation: 3, note })),
+ consumeWorkingMemoryRefresh: vi.fn(),
+ });
+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello');
+ const sent = vi.mocked(session.send).mock.calls[0]?.[0] as string;
+ expect(sent).toContain('HANDOFF');
+ expect(sent).not.toContain('Working memory refresh');
+ expect(deps.consumeWorkingMemoryRefresh).toHaveBeenCalledWith('session-1', 3);
+ });
+
+ it('consumes the marker even when the session has no ledger, and nothing when none is pending', async () => {
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ peekWorkingMemoryRefresh: vi.fn(async () => ({ generation: 2, note: null })),
+ consumeWorkingMemoryRefresh: vi.fn(),
+ });
+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello');
+ expect(vi.mocked(session.send).mock.calls[0]?.[0]).toBe(withUiLanguageNote('hello'));
+ expect(deps.consumeWorkingMemoryRefresh).toHaveBeenCalledWith('session-1', 2);
+
+ const { deps: idle, session: idleSession } = createDeps({
+ peekWorkingMemoryRefresh: vi.fn(async () => null),
+ consumeWorkingMemoryRefresh: vi.fn(),
+ });
+ await createMakerSendTransaction(idle).sendToAgentAccepted('session-1', 'hello');
+ expect(idleSession.send).toHaveBeenCalledOnce();
+ expect(idle.consumeWorkingMemoryRefresh).not.toHaveBeenCalled();
+ });
+});
++
+ describe('repeatable environment notes are sent only when they change', () => {
+ const host = { deviceId: 'mac-1', name: 'Mac' };
+ const phone = { deviceId: 'phone-1', name: 'iPhone', platform: 'mobile' as const };
+ const pc = { deviceId: 'pc-1', name: 'Office PC', platform: 'desktop' as const };
+
+ function setup(overrides: Partial<MakerSendTransactionDeps> = {}) {
+ const memory = createWireNoteMemory();
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ readHostDeviceIdentity: vi.fn(() => host),
+ planRepeatableWireNotes: (sessionId, notes, opts) => memory.plan(sessionId, notes, opts),
+ ...overrides,
+ });
+ return { session, deps, memory, transaction: createMakerSendTransaction(deps) };
+ }
+ const sentAt = (session: MakerSendTransactionSession, index: number) =>
+ vi.mocked(session.send).mock.calls[index]?.[0] as string;
+
+ it('drops the UI language and device notes on the second turn from the same device', async () => {
+ const { session, transaction } = setup();
+ const opts = { sourceDevice: phone, persistUserMessage: { clientId: 'm-1', content: 'hello' } };
+ await transaction.sendToAgentAccepted('session-1', 'hello', undefined, opts);
+ await transaction.sendToAgentAccepted('session-1', 'again', undefined, { ...opts, persistUserMessage: { clientId: 'm-2', content: 'again' } });
+
+ expect(sentAt(session, 0)).toContain(uiLanguageNote());
+ expect(sentAt(session, 0)).toContain('[客户端说明]');
+ expect(sentAt(session, 1)).toBe('again');
+ });
+
+ it('resends just the device note when the controller changes, and the full set after a handoff', async () => {
+ const { session, transaction } = setup({
+ peekPendingHandoff: vi.fn(async () => null),
+ });
+ await transaction.sendToAgentAccepted('session-1', 'a', undefined, { sourceDevice: phone });
+ await transaction.sendToAgentAccepted('session-1', 'b', undefined, { sourceDevice: pc });
+ expect(sentAt(session, 1)).not.toContain(uiLanguageNote());
+ expect(sentAt(session, 1)).toContain('另一台电脑「Office PC」');
+
+ vi.mocked(session.send).mockClear();
+ const { session: fresh, transaction: afterHandoff } = setup({
+ peekPendingHandoff: vi.fn(async () => 'HANDOFF'),
+ });
+ await afterHandoff.sendToAgentAccepted('session-1', 'c', undefined, { sourceDevice: pc });
+ expect(sentAt(fresh, 0)).toContain(uiLanguageNote());
+ expect(sentAt(fresh, 0)).toContain('HANDOFF');
+ });
+
+ it('keeps resending while the engine has not accepted the turn', async () => {
+ const session = createSession({
+ agentKind: 'codex',
+ send: vi.fn(async () => ({ accepted: false }) as SessionSendResult),
+ });
+ const { transaction } = setup({ getSession: vi.fn(() => session) });
+ await transaction.sendToAgentAccepted('session-1', 'a').catch(() => undefined);
+ await transaction.sendToAgentAccepted('session-1', 'b').catch(() => undefined);
+ expect(sentAt(session, 0)).toContain(uiLanguageNote());
+ expect(sentAt(session, 1)).toContain(uiLanguageNote());
+ });
+
+ it('leaves slash-command turns alone without marking the notes as seen', async () => {
+ const session = createSession({ agentKind: 'claude-code' });
+ const { transaction } = setup({ getSession: vi.fn(() => session) });
+ await transaction.sendToAgentAccepted('session-1', '/compact');
+ await transaction.sendToAgentAccepted('session-1', 'hello');
+ expect(sentAt(session, 0)).toBe('/compact');
+ expect(sentAt(session, 1)).toContain(uiLanguageNote());
+ });
+
+ it('sends every note each turn when no memory is wired (legacy behaviour)', async () => {
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({ getSession: vi.fn(() => session) });
+ const transaction = createMakerSendTransaction(deps);
+ await transaction.sendToAgentAccepted('session-1', 'a');
+ await transaction.sendToAgentAccepted('session-1', 'b');
+ expect(sentAt(session, 1)).toBe(withUiLanguageNote('b'));
+ });
+ });
diff --cc apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 639dea62c6,7b1f96672c..bbc2cc9e11
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@@ -252,7 -252,7 +252,8 @@@ function harness()
onUnsuccessfulProductTurn: vi.fn(async () => {}),
log,
botCompactRuntimeRefreshCoordinator: { noteBoundary: vi.fn() },
+ workingMemoryRefresh: { markCompacted: vi.fn() },
+ wireNoteMemory: { reset: vi.fn() },
attemptBotCompactRuntimeRefresh: vi.fn(),
botDelegationServiceHolder: { settleSession: vi.fn(async () => {}) },
isFencedStaleSessionTerminal: vi.fn(() => false),
@@@ -1885,8 -1885,8 +1886,10 @@@ describe('Bot adapters in the shared ev
const h = harness();
h.emit(event('compact_boundary'));
expect(h.deps.botCompactRuntimeRefreshCoordinator.noteBoundary).toHaveBeenCalledWith(h.session);
+ // 原生摘要可能丢掉账本内容:下一次发送补一份工作记忆。
+ expect(h.deps.workingMemoryRefresh.markCompacted).toHaveBeenCalledWith('task');
+ // 原生摘要可能丢掉了环境说明:下一轮整体重发。
+ expect(h.deps.wireNoteMemory.reset).toHaveBeenCalledWith('task');
expect(h.deps.attemptBotCompactRuntimeRefresh).not.toHaveBeenCalled();
h.deps.agentInputCoordinatorHolder.getQueueControlSnapshot.mockReturnValue({ pendingQueue: [{}] });
h.emit(event('done', { result: 'first result' }));
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 3fe266032a,42355f12e0..770ce9eefd
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -595,12 -600,7 +600,13 @@@ import
type BotCompactRuntimeRefreshOutcome,
type BotCompactRuntimeSession,
} from './botCompactRuntimeRefresh.js';
+import {
+ buildWorkingMemoryRefreshNote,
+ createWorkingMemoryRefreshRegistry,
+ pruneWorkingMemoryForSession,
+ readWorkingMemoryNoteForSession,
+} from './botWorkingMemory.js';
+ import { createWireNoteMemory } from './wireNoteMemory.js';
import { isBotCanonicalReplacementBusy } from './botCanonicalReplacementGuard.js';
import { configureBotCanonicalReplacementCoordinator } from './botCanonicalReplacementCoordinator.js';
import { botSessionInputBlockReason, isShadowedCompanionCanonical, SHADOWED_COMPANION_INPUT_MESSAGE } from './botSessionInputGuard.js';
@@@ -3260,13 -3261,11 +3267,18 @@@ type BotCompactRuntimeRefreshHandler =
* and let the instance-scoped coordinator own all compact settle signals.
*/
let botCompactRuntimeRefreshHandler: BotCompactRuntimeRefreshHandler | null = null;
+/**
+ * 伙伴工作记忆账本(botWorkingMemory):换窗交接带账本;原生压缩后下一次发送补一份。
+ * 登记对所有会话生效,真正注入只在伙伴主对话且有账本时发生。
+ */
+const workingMemoryRefresh = createWorkingMemoryRefreshRegistry();
+const readWorkingMemoryNote = (sessionId: string): Promise<string | null> =>
+ readWorkingMemoryNoteForSession(sessionId, ownerScopedUserDataPath());
+ /**
+ * 逐轮环境说明(界面语言 / 客户端设备 / 个人版制作说明)的去重记忆:同一原生上下文里内容
+ * 没变就不重复前置。原生压缩边界、`/clear`、换窗重建后整体重发一次(见 wireNoteMemory.ts)。
+ */
+ const wireNoteMemory = createWireNoteMemory();
const botCompactRuntimeRefreshCoordinator = createBotCompactRuntimeRefreshCoordinator({
hasPendingInteraction: hasPendingAgentInteractionForSession,
refresh: (session, boundary) =>
@@@ -5482,7 -5483,7 +5496,8 @@@ const sessionEventDependencies: Session
onUnsuccessfulProductTurn: interruptProductTurn,
deferUnsuccessfulProductTurn: (owner) => deferredProductTurnFailureGate.defer(owner),
get botCompactRuntimeRefreshCoordinator() { return botCompactRuntimeRefreshCoordinator; },
+ get workingMemoryRefresh() { return workingMemoryRefresh; },
+ get wireNoteMemory() { return wireNoteMemory; },
get attemptBotCompactRuntimeRefresh() { return attemptBotCompactRuntimeRefresh; },
get botDelegationServiceHolder() { return botDelegationServiceHolder; },
get botGroupChatServiceHolder() { return botGroupChatServiceHolder; },
@@@ -16173,17 -16249,19 +16268,28 @@@ export function registerMakerIpc(maker
// 调用方自报;与手机说明同层(只进 wire 消息)。
isCindyMakeSession: async (sessionId) =>
(await readSessionSource(sessionId)) === CINDY_MAKE_SESSION_SOURCE,
+ // 原生压缩后的账本刷新:只对伙伴主对话且有账本的会话真正注入;读不到按无账本,
+ // 标记仍由事务在 accepted 后按代次消费。
+ peekWorkingMemoryRefresh: async (sessionId) => {
+ const generation = workingMemoryRefresh.pendingGeneration(sessionId);
+ if (generation === null) return null;
+ const rendered = await readWorkingMemoryNote(sessionId);
+ return { generation, note: rendered ? buildWorkingMemoryRefreshNote(rendered) : null };
+ },
+ consumeWorkingMemoryRefresh: (sessionId, generation) => workingMemoryRefresh.consume(sessionId, generation),
+ planRepeatableWireNotes: (sessionId, notes, opts) => wireNoteMemory.plan(sessionId, notes, opts),
applyPendingAgentSwitch: async (sessionId, options) => {
await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId);
+ // Queued Orca delivery and resume both use this transaction. A failed
+ // cross-engine preparation may retain its intent without throwing.
+ if (agentSwitchPending.get(sessionId)) {
+ const row = await getSessionRowSnapshotStrict(sessionId);
+ // Execution-device Workers have an authoritative remote Lead binding,
+ // not an orca_role. Do not use the incoming message's origin as identity.
+ if (row?.orcaRole || parseOrcaRemoteLead(row?.orcaRemoteLead)) {
+ throwIpcError('PRECONDITION_FAILED', 'Agent switch is still pending; retry the send after recovery');
+ }
+ }
// 已归组的任务所在那台现在不能用时,先换到组里下一台再发(失败不影响这次发送);离线时先等它恢复,
// 等的时候进行中行显示「重新连接中 n/5」。
await providerGroupService?.beforeSend(sessionId, {
diff --cc apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
index 8bfd826c1f,65a6699ac8..b2b83af09d
--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
@@@ -129,11 -129,11 +129,16 @@@ export interface PrepareSessionEventDep
event: AgentEvent,
) => boolean;
readonly isGatewayProxyTokenRecoveryErrorEvent: (sessionId: string, event: AgentEvent) => boolean;
+ /**
+ * 伙伴工作记忆刷新登记(botWorkingMemory):原生自动压缩后,下一次发送前置一次账本。
+ * 对所有会话登记,发送时再按伙伴主对话 / 有无账本决定是否真的注入。
+ */
+ readonly workingMemoryRefresh?: { markCompacted(sessionId: string): void };
+ /**
+ * 逐轮环境说明的去重记忆(wireNoteMemory.ts)。原生自动压缩后摘要可能已丢掉旧说明,
+ * 下一轮要整体重发一次;缺省(未注入)不去重,行为同旧版。
+ */
+ readonly wireNoteMemory?: { reset(sessionId: string): void };
}
export function prepareSessionEvent(
@@@ -146,7 -146,7 +151,8 @@@
// potentially multi-megabyte payload to every renderer and device-link controller.
if (event.type === 'turn_diff') return;
if (event.type === 'compact_boundary') deps.botCompactRuntimeRefreshCoordinator.noteBoundary(session);
+ if (event.type === 'compact_boundary') deps.workingMemoryRefresh?.markCompacted(session.id);
+ if (event.type === 'compact_boundary') deps.wireNoteMemory?.reset(session.id);
if (
event.turnScope === 'background' &&
Object.prototype.hasOwnProperty.call(event, 'backgroundTurnStartedAt') &&