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。

feat(desktop): 支持远程消息文件与变更撤销 (#4879)

Dash929986ff5de2
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
index 18f233b219..fd543797d6 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -42,7 +42,7 @@ vi.mock('../settings-store', () => ({
readDeviceLinkSettings: () => deviceLinkSettings.value,
}));
-import { __testing, runInvoke, wireInboundDispatch } from '../dispatch';
+import { __testing, runInvoke, wireInboundDispatch, setRemoteTurnChangeAction } from '../dispatch';
import { __testing as registry } from '../invoke-registry';
import { setRemoteBotSessionLookup } from '../remoteBotSessionBoundary';
import { currentDbRpcAdmissionClass } from '../../localDb/client/rpcAdmission';
@@ -1150,3 +1150,37 @@ it('lets a controller fall back to individual reads when a detail batch exceeds
ok: false, error: { code: 'IPC_ERROR', message: '[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE' },
});
});
+
+
+describe('remote recorded-turn actions', () => {
+ const channel = 'maker:turn-change-set:apply';
+ it('uses the shared action without dispatching a synthetic renderer event', async () => {
+ const localHandler = vi.fn(() => { throw new Error('untrusted renderer'); });
+ registry.register(channel, localHandler);
+ const action = vi.fn(async (_session, _id, _action, assertAccess) => {
+ await assertAccess();
+ return { changed: true };
+ });
+ setRemoteTurnChangeAction(action);
+ expect(await runInvoke('ctrl', { channel, args: ['s1', 'change-1', 'undo'] }))
+ .toMatchObject({ ok: true, result: { changed: true } });
+ expect(action).toHaveBeenCalledWith('s1', 'change-1', 'undo', expect.any(Function));
+ expect(localHandler).not.toHaveBeenCalled();
+ });
+
+ it.each(['disabled', 'revoked', 'hidden'] as const)('rechecks %s access before the write', async (reason) => {
+ let hidden = false;
+ setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'ordinary');
+ const write = vi.fn();
+ setRemoteTurnChangeAction(async (_session, _id, _action, assertAccess) => {
+ if (reason === 'disabled') deviceLinkSettings.value.remoteControlEnabled = false;
+ if (reason === 'revoked') deviceLinkSettings.value.revokedControllers = ['ctrl'];
+ if (reason === 'hidden') hidden = true;
+ await assertAccess();
+ write();
+ });
+ expect(await runInvoke('ctrl', { channel, args: ['s1', 'change-1', 'undo'] }))
+ .toMatchObject({ ok: false });
+ expect(write).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
index 913b8608cb..85e1b12021 100644
--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
@@ -5,6 +5,15 @@ import {
afterEach(() => setRemoteBotSessionLookup(null));
+it.each(['turn-list', 'turn-get'])('rechecks nested %s targets before returning remote snapshots', async (op) => {
+ let hidden = false;
+ setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'visible');
+ const args = [{ op, payload: { sessionId: 'task', ids: ['set'] } }];
+ await assertRemoteBotInvocationAllowed(args, 'git-review:remote-op');
+ hidden = true;
+ await expect(assertRemoteBotInvocationAllowed(args, 'git-review:remote-op')).rejects.toThrow('[NOT_FOUND]');
+});
+
it('bounds single-lookup adapters, deduplicates checks and preserves collection order', async () => {
let active = 0;
let peak = 0;
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
index af9e8fe463..e23f7c6b0b 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
@@ -71,6 +71,27 @@ describe('shared task metadata uses only its authorized task subscription', () =
expect(transport.sendPush.mock.calls.every((call) => call[1] === channel && call[2].sessionId === 'task-a')).toBe(true);
});
+ it.each(['online', 'reconnecting'])('keeps turn-change updates same-account only while %s', async (status) => {
+ const transport = client();
+ transport.getStatus.mockReturnValue(status);
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ subscriptions.subscribe('own-task', ['session:task-a']);
+ const channel = 'maker:turn-change-set:updated';
+ const payload = { sessionId: 'task-a', changeSetId: 'change-a' };
+ __testing.forwardPush(channel, payload);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(__testing.queuedPushesFor(guestA)).toEqual([]);
+ if (status === 'online') {
+ expect(transport.sendPush).toHaveBeenCalledWith('own-task', channel, payload);
+ expect(transport.sendPush).toHaveBeenCalledTimes(1);
+ } else {
+ expect(transport.sendPush).not.toHaveBeenCalled();
+ // Same-account clients reread turn changes on reconnect instead of replaying notices.
+ expect(__testing.queuedPushesFor('own-task')).toEqual([]);
+ }
+ });
+
it('keeps offline metadata under the task topic and replays it after that topic is restored', async () => {
const transport = client();
__testing.setActiveClient(transport as never);
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 6cb317f826..14701eda83 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -313,6 +313,15 @@ export function setRemoteReviewInputGuard(guard: RemoteReviewInputGuard | null):
remoteReviewInputGuard = guard;
}
+// Local renderer IPC keeps its sender guard; remote mutations enter the shared action here.
+type RemoteTurnChangeAction = (
+ sessionId: unknown, id: unknown, action: unknown, assertAccess: () => Promise<void>,
+) => Promise<unknown>;
+let remoteTurnChangeAction: RemoteTurnChangeAction | null = null;
+export function setRemoteTurnChangeAction(handler: RemoteTurnChangeAction): void {
+ remoteTurnChangeAction = handler;
+}
+
/**
* xAI 订阅余量读取器(register.ts 在 usage 面就绪后注入)。该 channel 的 ipcMain
* handler 挂了 assertTrustedSender(合成 event 必然不可信,那道闸不为远程放宽),
@@ -3902,7 +3911,21 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin
},
// provider:list 的首参只承载隧道能力协商,不进入本机 IPC handler。
() =>
- payload.channel === TASK_TAG_CHANNEL
+ payload.channel === 'maker:turn-change-set:apply'
+ ? (() => {
+ if (!remoteTurnChangeAction) throw new Error('[UNSUPPORTED_CAPABILITY] Turn restore is unavailable');
+ return remoteTurnChangeAction(args[0], args[1], args[2], async () => {
+ // Recheck after queueing / Git preflight, immediately before the write.
+ await assertRemoteBotInvocationAllowed(args, payload.channel);
+ if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(invocationOwner)) {
+ throw new Error('[NOT_FOUND] Session does not exist');
+ }
+ if (!readDeviceLinkSettings().remoteControlEnabled || isControllerRevoked(src)) {
+ throw new Error('[ACCESS_REVOKED] Remote control is no longer allowed');
+ }
+ });
+ })()
+ : payload.channel === TASK_TAG_CHANNEL
? executeTaskTags(args[0] as TaskTagRequest)
: dispatchLocalInvoke(
payload.channel,
@@ -4038,6 +4061,7 @@ export const __testing = {
setBroadcastTapListener(null);
presenceOfflineCheck = null;
remoteReviewInputGuard = null;
+ remoteTurnChangeAction = null;
remoteXaiSubscriptionUsageReader = null;
remoteClaudeSubscriptionUsageReader = null;
},
diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
index 691b75dde2..d396d2f0b4 100644
--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
@@ -24,6 +24,18 @@ function sessionIds(value: unknown): string[] {
/** Resolve channel-specific Bot IDs before checking generic Session references. */
export async function assertRemoteBotInvocationAllowed(args: unknown[], channel = ''): Promise<void> {
+ // Review queries nest the target under payload; recheck it before execution
+ // and on cached/queued replies just like top-level Session reads.
+ if (channel === 'git-review:remote-op') {
+ const id = record(record(args[0])?.payload)?.sessionId;
+ if (typeof id !== 'string' || !id.trim() || id.length > 256) {
+ throw new Error('[INVALID_PARAMS] Invalid review session ID');
+ }
+ if (lookup && await lookup(id, 'session') === 'hidden') {
+ throw new Error('[NOT_FOUND] Session does not exist');
+ }
+ return;
+ }
if (channel === 'local-db:task-tags:execute') {
const request = record(args[0]);
const targets = request?.sessionIds;
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index 02a9b0c6e3..b7ab6358bd 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -163,6 +163,8 @@ export function assertSharedTaskInvoke(
/** Synchronous last-mile gate, including batches, delayed pushes and offline replay. */
export function captureSharedTaskPush(source: string, channel: string, payload: unknown): (() => boolean) | null {
if (!isSharedTaskPeer(source)) return () => true;
+ // Turn-change reads/actions are same-account only; do not expose an unusable guest card.
+ if (channel === 'maker:turn-change-set:updated') return null;
const capture = captureSharedTaskPeer(source);
if (!capture || !capture.authorize('events.subscribe')) return null;
const sessionId = capture.author.sessionId;
diff --git a/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts b/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts
index 14334bdc60..ba57fcb977 100644
--- a/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts
@@ -241,6 +241,19 @@ describe('statChatFile — chip 点亮预检', () => {
const ssh = { kind: 'ssh', remoteHostId: 'h1' } as const;
const dev = { kind: 'device', deviceId: 'd1' } as const;
+ it.each([ssh, dev])('checks command outputs against timestamps from the file-owning host (%j)', async (origin) => {
+ const deps = makeDeps();
+ const args = { origin, workdir: '/w', absPath: '/w/report.pdf' };
+ expect(await statChatFile({ ...args, modifiedWindow: { startMs: 900, endMs: 1100 } }, deps)).toBe('file');
+ expect(await statChatFile({ ...args, modifiedWindow: { startMs: 1001, endMs: null } }, deps)).toBe('nonfile');
+ expect(await statChatFile({ ...args, modifiedWindow: { startMs: 900, endMs: 1000 } }, deps)).toBe('nonfile');
+ const noTimestamp = makeDeps({
+ deviceStat: vi.fn().mockResolvedValue({ type: 'file', size: 10 }),
+ sshStat: vi.fn().mockResolvedValue({ type: 'file', size: 10 }),
+ });
+ expect(await statChatFile({ ...args, modifiedWindow: { startMs: 900, endMs: null } }, noTimestamp)).toBe('nonfile');
+ });
+
it('文件 → file;目录 → directory(chip 点亮,点击定位侧边栏文件浏览器)', async () => {
const deps = makeDeps();
expect(await statChatFile({ origin: ssh, workdir: '/w', absPath: '/w/a.txt' }, deps)).toBe('file');
diff --git a/apps/desktop/src/main/file-browser/chat-file.ts b/apps/desktop/src/main/file-browser/chat-file.ts
index 49b16538b9..abd99356e6 100644
--- a/apps/desktop/src/main/file-browser/chat-file.ts
+++ b/apps/desktop/src/main/file-browser/chat-file.ts
@@ -40,6 +40,8 @@ export interface ChatFileFetchArgs {
workdir: string;
/** 目标文件在远端机器上的绝对路径。 */
absPath: string;
+ /** Optional generated-command evidence window, using timestamps from the owning device. */
+ modifiedWindow?: { startMs: number; endMs: number | null };
}
/**
@@ -133,6 +135,27 @@ export async function statChatFile(
): Promise<ChatFileStatVerdict> {
const { origin, workdir, absPath } = args ?? ({} as ChatFileFetchArgs);
if (!workdir || !absPath || !origin) return 'nonfile';
+ const window = args.modifiedWindow;
+ if (
+ window &&
+ (!Number.isFinite(window.startMs) ||
+ (window.endMs !== null &&
+ (!Number.isFinite(window.endMs) || window.endMs <= window.startMs)))
+ ) {
+ return 'nonfile';
+ }
+ const verdictFor = (stat: ChatFileStat): ChatFileStatVerdict => {
+ if (
+ window &&
+ (stat.type !== 'file' ||
+ !Number.isFinite(stat.mtimeMs) ||
+ stat.mtimeMs < window.startMs ||
+ (window.endMs !== null && stat.mtimeMs >= window.endMs))
+ ) {
+ return 'nonfile';
+ }
+ return stat.type === 'file' ? 'file' : stat.type === 'directory' ? 'directory' : 'nonfile';
+ };
const relPath = toWorkdirRel(workdir, absPath);
if (origin.kind === 'ssh') {
if (!origin.remoteHostId) return 'nonfile';
@@ -140,7 +163,7 @@ export async function statChatFile(
if (!relPath) return 'nonfile';
try {
const stat = await deps.sshStat(origin.remoteHostId, workdir, relPath);
- return stat.type === 'file' ? 'file' : stat.type === 'directory' ? 'directory' : 'nonfile';
+ return verdictFor(stat);
} catch (err) {
return classifyStatError(err);
}
@@ -151,7 +174,7 @@ export async function statChatFile(
if (!relPath) return 'unknown';
try {
const stat = await deps.deviceStat(origin.deviceId, workdir, relPath);
- return stat.type === 'file' ? 'file' : stat.type === 'directory' ? 'directory' : 'nonfile';
+ return verdictFor(stat);
} catch (err) {
return classifyStatError(err);
}
diff --git a/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts b/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
index edcd4ad2b6..487d436170 100644
--- a/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
@@ -23,6 +23,12 @@ const readReviewFileDiffMock = vi.fn();
const readReviewImagePreviewMock = vi.fn();
const readReviewMarkdownPreviewMock = vi.fn();
const withSessionReviewExecutionMock = vi.hoisted(() => vi.fn());
+const turnStore = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn() }));
+vi.mock('../../turn-change-set/store.js', () => ({
+ listTurnChangeSets: turnStore.list,
+ getTurnChangeSets: turnStore.get,
+ TURN_CHANGE_SET_DETAIL_ID_LIMIT: 16,
+}));
vi.mock('electron', () => ({
ipcMain: { handle: vi.fn() },
@@ -60,6 +66,22 @@ beforeEach(() => {
});
describe('git-review device-op', () => {
+ it('reads historical snapshots from the host without running current-workspace Git', async () => {
+ turnStore.list.mockResolvedValue([{ id: 'set' }]);
+ turnStore.get.mockResolvedValue([{ id: 'set', diffs: [{ rawPatch: 'exact' }] }]);
+ expect(await handleRemoteOp({ op: 'turn-list', payload: { sessionId: 's1' } }))
+ .toEqual({ ok: true, result: [{ id: 'set' }] });
+ expect(await handleRemoteOp({ op: 'turn-get', payload: { sessionId: 's1', ids: ['set'] } }))
+ .toEqual({ ok: true, result: [{ id: 'set', diffs: [{ rawPatch: 'exact' }] }] });
+ expect(turnStore.get).toHaveBeenCalledWith('s1', ['set']);
+ expect(withSessionReviewExecutionMock).not.toHaveBeenCalled();
+ });
+
+ it.each([undefined, [''], [123], Array(17).fill('set')])('rejects invalid historical detail IDs (%#)', async (ids) => {
+ await expect(handleRemoteOp({ op: 'turn-get', payload: { sessionId: 's1', ids } }))
+ .rejects.toThrow('[INVALID_PARAMS]');
+ expect(turnStore.get).not.toHaveBeenCalled();
+ });
it('rejects invalid args deterministically', async () => {
expect(await handleRemoteOp(undefined as never)).toEqual({ ok: false, message: 'invalid remote-op args' });
expect(await handleRemoteOp({ payload: {} } as never)).toEqual({ ok: false, message: 'invalid remote-op args' });
diff --git a/apps/desktop/src/main/git-review/device-op.ts b/apps/desktop/src/main/git-review/device-op.ts
index 56eb8ccc89..86c99f8783 100644
--- a/apps/desktop/src/main/git-review/device-op.ts
+++ b/apps/desktop/src/main/git-review/device-op.ts
@@ -46,6 +46,12 @@ import {
readReviewSummary,
} from './ipc.js';
import { withSessionReviewExecution } from './sshReviewBackend.js';
+import {
+ getTurnChangeSets,
+ listTurnChangeSets,
+ TURN_CHANGE_SET_DETAIL_ID_LIMIT,
+} from '../turn-change-set/store.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
const log = createLogger('git-review/device-op');
@@ -91,6 +97,20 @@ async function encodeResult(result: unknown): Promise<GitReviewRemoteOpResult> {
async function dispatchRemoteOp(op: string, payload: unknown): Promise<unknown> {
switch (op) {
+ case 'turn-list':
+ return listTurnChangeSets(parseSessionId(payload));
+ case 'turn-get': {
+ const sessionId = parseSessionId(payload);
+ const ids = (payload as { ids?: unknown }).ids;
+ if (
+ !Array.isArray(ids) ||
+ ids.length > TURN_CHANGE_SET_DETAIL_ID_LIMIT ||
+ ids.some((id) => typeof id !== 'string' || id.length === 0 || id.length > 256)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'Invalid turn change-set ids');
+ }
+ return getTurnChangeSets(sessionId, ids as string[]);
+ }
case 'get': {
const { sessionId, options } = parseReviewDataPayload(payload);
return withSessionReviewExecution(sessionId, () => readReviewData(sessionId, options));
@@ -129,6 +149,8 @@ async function dispatchRemoteOp(op: string, payload: unknown): Promise<unknown>
}
const READ_OPS = new Set([
+ 'turn-list',
+ 'turn-get',
'get',
'summary',
'commits',
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ee21a13af4..dfb9521b0c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1047,6 +1047,7 @@ import { setBusyProbe as setDeviceLinkBusyProbe } from '../device-link/index.js'
import {
markRemoteSettingPersistedInsideHandler,
setSessionTextSnapshotReader,
+ setRemoteTurnChangeAction,
setRemoteReviewInputGuard as setDeviceLinkRemoteReviewInputGuard,
setRemoteWorkingDirGuard as setDeviceLinkRemoteWorkingDirGuard,
setRemoteSettingsPersist as setDeviceLinkRemoteSettingsPersist,
@@ -5087,59 +5088,80 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
);
+ const applyRecordedTurnChanges = async (
+ sessionId: unknown, id: unknown, action: unknown,
+ assertRemoteAccess?: () => Promise<void>,
+ ) => {
+ const ownerScope = captureDataOwnerBroadcastScope();
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256) {
+ throwIpcError('INVALID_PARAMS', 'Invalid sessionId');
+ }
+ if (typeof id !== 'string' || id.length === 0 || id.length > 256) {
+ throwIpcError('INVALID_PARAMS', 'Invalid turn change-set id');
+ }
+ if (action !== 'undo' && action !== 'reapply') {
+ throwIpcError('INVALID_PARAMS', 'Invalid turn change-set action');
+ }
+ const meta = await maker.getSessionMeta(sessionId);
+ if (!meta) throwIpcError('NOT_FOUND', 'Task not found.');
+ if (meta.remoteHostId) {
+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote workspace restore is not available.');
+ }
+ const normalizedWorkDir = normalizeTurnChangeSetWorkspaceKey(meta.workDir);
+ const workspaceIsBusy = (): boolean =>
+ maker.listActiveSessions().some((session) => {
+ if (session.remoteHostId) return false;
+ const currentWorkDir = normalizeTurnChangeSetWorkspaceKey(session.workDir);
+ return (
+ currentWorkDir === normalizedWorkDir &&
+ (session.isTurnRunning() || getClaudeSessionBackgroundActivity(session.id))
+ );
+ });
+ if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {
+ throwIpcError('SESSION_RUNNING', 'Wait for the current response to finish.');
+ }
+ await waitForTurnChangeSetSeal(sessionId);
+ if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {
+ throwIpcError('SESSION_RUNNING', 'Wait for the current response to finish.');
+ }
+ let accessFailure: { error: unknown } | undefined;
+ try {
+ return await applyTurnChangeSetAction(sessionId, id, action, ownerScope, async () => {
+ try {
+ await assertRemoteAccess?.();
+ } catch (error) {
+ accessFailure = { error };
+ throw error;
+ }
+ if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {
+ throw new TurnChangeSetActionError('busy', 'Wait for the current response to finish.');
+ }
+ });
+ } catch (error) {
+ // Preserve only errors from the trusted remote authorization callback; storage
+ // and Git errors still pass through the existing sanitized error mapping.
+ if (accessFailure && error === accessFailure.error) throw error;
+ if (!(error instanceof TurnChangeSetActionError)) {
+ log.warn('turn change-set action failed', { sessionId, id, action, error });
+ throwIpcError('INTERNAL', 'The recorded changes could not be applied.');
+ }
+ if (error.kind === 'not-found') throwIpcError('NOT_FOUND', error.message);
+ if (error.kind === 'busy') throwIpcError('SESSION_RUNNING', error.message);
+ if (error.kind === 'wrong-state') throwIpcError('PRECONDITION_FAILED', error.message);
+ if (error.kind === 'git-missing') {
+ throwIpcError('TURN_CHANGE_GIT_UNAVAILABLE', error.message);
+ }
+ if (error.kind === 'unsupported') throwIpcError('UNSUPPORTED_CAPABILITY', error.message);
+ if (error.kind === 'conflict') throwIpcError('STALE_DIFF', error.message);
+ throwIpcError('INTERNAL', error.message);
+ }
+ };
+ setRemoteTurnChangeAction(applyRecordedTurnChanges);
ipcMain.handle(
MAKER_INVOKE.TURN_CHANGE_SET_APPLY,
- async (event, sessionId: unknown, id: unknown, action: unknown) => {
+ (event, sessionId: unknown, id: unknown, action: unknown) => {
assertTrustedAppRendererEvent(event);
- const ownerScope = captureDataOwnerBroadcastScope();
- if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256) {
- throwIpcError('INVALID_PARAMS', 'Invalid sessionId');
- }
- if (typeof id !== 'string' || id.length === 0 || id.length > 256) {
- throwIpcError('INVALID_PARAMS', 'Invalid turn change-set id');
- }
- if (action !== 'undo' && action !== 'reapply') {
- throwIpcError('INVALID_PARAMS', 'Invalid turn change-set action');
- }
- const meta = await maker.getSessionMeta(sessionId);
- if (!meta) throwIpcError('NOT_FOUND', 'Task not found.');
- if (meta.remoteHostId) {
- throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote workspace restore is not available.');
- }
- const normalizedWorkDir = normalizeTurnChangeSetWorkspaceKey(meta.workDir);
- const workspaceIsBusy = (): boolean =>
- maker.listActiveSessions().some((session) => {
- if (session.remoteHostId) return false;
- const currentWorkDir = normalizeTurnChangeSetWorkspaceKey(session.workDir);
- return (
- currentWorkDir === normalizedWorkDir &&
- (session.isTurnRunning() || getClaudeSessionBackgroundActivity(session.id))
- );
- });
- if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {
- throwIpcError('SESSION_RUNNING', 'Wait for the current response to finish.');
- }
- await waitForTurnChangeSetSeal(sessionId);
- if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {
- throwIpcError('SESSION_RUNNING', 'Wait for the current response to finish.');
- }
- try {
- return await applyTurnChangeSetAction(sessionId, id, action, ownerScope);
- } catch (error) {
- if (!(error instanceof TurnChangeSetActionError)) {
- log.warn('turn change-set action failed', { sessionId, id, action, error });
- throwIpcError('INTERNAL', 'The recorded changes could not be applied.');
- }
- if (error.kind === 'not-found') throwIpcError('NOT_FOUND', error.message);
- if (error.kind === 'busy') throwIpcError('SESSION_RUNNING', error.message);
- if (error.kind === 'wrong-state') throwIpcError('PRECONDITION_FAILED', error.message);
- if (error.kind === 'git-missing') {
- throwIpcError('TURN_CHANGE_GIT_UNAVAILABLE', error.message);
- }
- if (error.kind === 'unsupported') throwIpcError('UNSUPPORTED_CAPABILITY', error.message);
- if (error.kind === 'conflict') throwIpcError('STALE_DIFF', error.message);
- throwIpcError('INTERNAL', error.message);
- }
+ return applyRecordedTurnChanges(sessionId, id, action);
},
);
diff --git a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
index bbd9d004dc..2088be10cc 100644
--- a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
@@ -113,6 +113,11 @@ describe('turn change-set sidecar store', () => {
await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
const [summary] = await listTurnChangeSets('session-1');
+ expect(mocks.send).toHaveBeenCalledWith(
+ 'maker:turn-change-set:updated',
+ expect.objectContaining({ sessionId: 'session-1', summary }),
+ undefined,
+ );
expect(summary).toMatchObject({
anchorClientId: 'user-1',
provider: 'codex',
@@ -476,6 +481,26 @@ describe('turn change-set sidecar store', () => {
expect(await fs.readFile(target, 'utf8')).toBe('head\ntail\n');
});
+ it('checks write admission after preflight and preserves files when access was revoked', async () => {
+ const target = path.join(workdir, 'access.txt');
+ await fs.writeFile(target, 'before\n');
+ await beginTurnChangeSet({ sessionId: 'session-1', anchorClientId: 'user-1', provider: 'pi', cwd: workdir });
+ await captureKnownFileBefore({ sessionId: 'session-1', provider: 'pi', cwd: workdir, targetPath: 'access.txt' });
+ await fs.writeFile(target, 'after\n');
+ await finalizeTurnChangeSet('session-1', null, 'complete');
+ const [recorded] = await listTurnChangeSets('session-1');
+ const assertAccess = vi.fn(async () => { throw new Error('access revoked'); });
+ await expect(applyTurnChangeSetAction('session-1', recorded!.id, 'undo', undefined, assertAccess))
+ .rejects.toThrow('access revoked');
+ expect(assertAccess).toHaveBeenCalledOnce();
+ expect(await fs.readFile(target, 'utf8')).toBe('after\n');
+ expect((await listTurnChangeSets('session-1'))[0]?.workspaceState).toBe('applied');
+ await applyTurnChangeSetAction('session-1', recorded!.id, 'undo');
+ expect(await fs.readFile(target, 'utf8')).toBe('before\n');
+ await applyTurnChangeSetAction('session-1', recorded!.id, 'reapply');
+ expect(await fs.readFile(target, 'utf8')).toBe('after\n');
+ });
+
it('reports a missing Git executable without changing the workspace', async () => {
const target = path.join(workdir, 'missing-git.ts');
await fs.writeFile(target, 'new\n', 'utf8');
@@ -760,6 +785,7 @@ describe('turn change-set sidecar store', () => {
await finalizeTurnChangeSet('session-1', 'turn-owner', 'complete');
const [recorded] = await listTurnChangeSets('session-1');
mocks.ownerCurrent = false;
+ mocks.send.mockClear();
await expect(applyTurnChangeSetAction('session-1', recorded!.id, 'undo'))
.rejects.toMatchObject({ kind: 'busy' } satisfies Partial<TurnChangeSetActionError>);
diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.ts
index f4ef9ab425..7a491769bd 100644
--- a/apps/desktop/src/main/turn-change-set/store.ts
+++ b/apps/desktop/src/main/turn-change-set/store.ts
@@ -765,6 +765,7 @@ function broadcastUpdated(
ownerScope = broadcastTap.captureDataOwnerBroadcastScope(),
): void {
if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(ownerScope)) return;
+ broadcastTap.tapWindowBroadcast(MAKER_PUSH.TURN_CHANGE_SET_UPDATED, payload, ownerScope.ownerStamp);
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
try {
@@ -1334,6 +1335,7 @@ export function applyTurnChangeSetAction(
id: string,
action: TurnChangeAction,
ownerScope = broadcastTap.captureDataOwnerBroadcastScope(),
+ assertCanApply?: () => Promise<void>,
): Promise<TurnChangeActionResult> {
const releaseSessionDir = retainSessionDir(sessionId);
const operation = (async () => {
@@ -1387,12 +1389,16 @@ export function applyTurnChangeSetAction(
'The workspace no longer matches the recorded patch.',
);
}
+ await assertCanApply?.();
+ assertOwnerScopeCurrent(ownerScope);
await persistWorkspaceState(sessionId, id, nextState);
const summary = toSummary(value, nextState);
broadcastUpdated({ sessionId, summary }, ownerScope);
return { action, changed: false, summary };
}
+ await assertCanApply?.();
+ assertOwnerScopeCurrent(ownerScope);
await applyRecordedPatch(value, revert);
await persistWorkspaceState(sessionId, id, nextState);
const summary = toSummary(value, nextState);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f1972d0b84..dea3ca8d69 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2865,6 +2865,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
workdir: string;
absPath: string;
+ modifiedWindow?: { startMs: number; endMs: number | null };
}): Promise<{ verdict: 'file' | 'directory' | 'nonfile' | 'unknown' }> =>
ipcRenderer.invoke('maker:chat-file:stat', params),
},
diff --git a/apps/desktop/src/renderer/__tests__/gitReviewTransport.test.ts b/apps/desktop/src/renderer/__tests__/gitReviewTransport.test.ts
index d34b9ec1ce..12bcaacc8c 100644
--- a/apps/desktop/src/renderer/__tests__/gitReviewTransport.test.ts
+++ b/apps/desktop/src/renderer/__tests__/gitReviewTransport.test.ts
@@ -35,6 +35,16 @@ afterEach(() => {
});
describe('gitReviewApiFor', () => {
+ it('routes historical summaries and exact patches to the owning device', async () => {
+ invokeMock.mockResolvedValue({ ok: true, result: [] });
+ const api = transport.turnChangeReadApiFor('device-1');
+ expect(await api.listTurnChangeSets('s1')).toEqual([]);
+ expect(await api.getTurnChangeSets('s1', ['set-1'])).toEqual([]);
+ expect(invokeMock.mock.calls).toEqual([
+ ['device-1', 'git-review:remote-op', [{ op: 'turn-list', payload: { sessionId: 's1' } }]],
+ ['device-1', 'git-review:remote-op', [{ op: 'turn-get', payload: { sessionId: 's1', ids: ['set-1'] } }]],
+ ]);
+ });
it('returns the local API untouched when deviceId is empty', () => {
expect(transport.gitReviewApiFor(null)).toBe(localGitReview);
expect(transport.gitReviewApiFor(undefined)).toBe(localGitReview);
diff --git a/apps/desktop/src/renderer/__tests__/remotePathVerdictCache.test.ts b/apps/desktop/src/renderer/__tests__/remotePathVerdictCache.test.ts
index 5ec58f7c49..8d4684f713 100644
--- a/apps/desktop/src/renderer/__tests__/remotePathVerdictCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remotePathVerdictCache.test.ts
@@ -55,6 +55,18 @@ afterEach(() => {
});
describe('unknown 的生命周期(不变量 A)', () => {
+ it('does not reuse plain existence or another turn window as command-generation evidence', async () => {
+ const stat = stubChatStat(async () => ({ verdict: 'file' }));
+ await verify();
+ const window = { startMs: 100, endMs: 200 };
+ await verifyRemotePathCached(ORIGIN, WORKDIR, ABS, window);
+ await verifyRemotePathCached(ORIGIN, WORKDIR, ABS, window);
+ await verifyRemotePathCached(ORIGIN, WORKDIR, ABS, { startMs: 100, endMs: 300 });
+ expect(stat).toHaveBeenCalledTimes(3);
+ expect(stat).toHaveBeenNthCalledWith(2, {
+ origin: ORIGIN, workdir: WORKDIR, absPath: ABS, modifiedWindow: window,
+ });
+ });
it('IPC 异常 → unknown,且**不进 peek**(peek 有值 ⇔ 有确定结论)', async () => {
stubChatStat(() => Promise.reject(new Error('link down')));
await expect(verify()).resolves.toBe('unknown');
diff --git a/apps/desktop/src/renderer/__tests__/turnChangePushRouting.test.ts b/apps/desktop/src/renderer/__tests__/turnChangePushRouting.test.ts
new file mode 100644
index 0000000000..8789ce388c
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/turnChangePushRouting.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { PUSH_FORWARD_ALLOWLIST, REMOTE_INVOKE_ALLOWLIST, topicForPush, isPeerResetRetryableReadChannel, isCompletedInvokeRetryableReadChannel, canCoalesceRemoteListing } from '@cindy/device-link';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { subscribeTurnChangeSetUpdated, makerApiForSticky } from '@/lib/makerTransport';
+import type { Session } from '@/lib/ccAgent.types';
+
+afterEach(() => vi.unstubAllGlobals());
+
+it('filters summary pushes by device, task and owner', () => {
+ const onRemotePush = vi.fn((_callback: (value: unknown, stamp: unknown) => void) => vi.fn());
+ const onTurnChangeSetUpdated = vi.fn();
+ vi.stubGlobal('window', {
+ electronAPI: {
+ deviceLink: { onRemotePush },
+ maker: { onTurnChangeSetUpdated },
+ },
+ });
+ setDataOwnerGeneration('owner', 1);
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [{ id: 'remote-task' } as Session]);
+ const callback = vi.fn();
+ const off = subscribeTurnChangeSetUpdated('remote-task', callback);
+ const push = onRemotePush.mock.calls[0][0];
+ const channel = 'maker:turn-change-set:updated';
+ const payload = { sessionId: 'remote-task', summary: { id: 'set', sessionId: 'remote-task' } };
+ const stamp = { dataOwnerId: 'owner', ownerGeneration: 1 };
+ expect(PUSH_FORWARD_ALLOWLIST.has(channel)).toBe(true);
+ expect(topicForPush(channel, payload)).toBe('session:remote-task');
+ push({ deviceId: 'other', channel, payload, ownerStamp: stamp }, stamp);
+ push(
+ { deviceId: 'host', channel, payload: { ...payload, sessionId: 'other' }, ownerStamp: stamp },
+ stamp,
+ );
+ push(
+ { deviceId: 'host', channel, payload, ownerStamp: { ...stamp, dataOwnerId: 'other' } },
+ stamp,
+ );
+ expect(callback).not.toHaveBeenCalled();
+ push({ deviceId: 'host', channel, payload, ownerStamp: stamp }, stamp);
+ expect(callback).toHaveBeenCalledWith(payload);
+ expect(onTurnChangeSetUpdated).not.toHaveBeenCalled();
+ off();
+});
+
+
+it('keeps undo/reapply on the owning device after the live listing disappears', async () => {
+ const invoke = vi.fn().mockResolvedValue({ changed: true });
+ const applyTurnChangeSet = vi.fn();
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke }, maker: { applyTurnChangeSet } } });
+ remoteProjectsStore.setDeviceSessions('restore-host', 'Host', [{ id: 'restore-task' } as Session]);
+ const api = makerApiForSticky('restore-task');
+ await api.applyTurnChangeSet('restore-task', 'change', 'undo');
+ remoteProjectsStore.setDeviceSessions('restore-host', 'Host', []);
+ await makerApiForSticky('restore-task').applyTurnChangeSet('restore-task', 'change', 'reapply');
+ expect(invoke.mock.calls).toEqual([
+ ['restore-host', 'maker:turn-change-set:apply', ['restore-task', 'change', 'undo']],
+ ['restore-host', 'maker:turn-change-set:apply', ['restore-task', 'change', 'reapply']],
+ ]);
+ expect(applyTurnChangeSet).not.toHaveBeenCalled();
+});
+
+it('admits explicit restore requests without enabling read retries or coalescing', () => {
+ const channel = 'maker:turn-change-set:apply';
+ expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);
+ expect(isPeerResetRetryableReadChannel(channel)).toBe(false);
+ expect(isCompletedInvokeRetryableReadChannel(channel)).toBe(false);
+ expect(canCoalesceRemoteListing({ channel, args: ['restore-task', 'change', 'undo'] })).toBe(false);
+});
diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
index d0bde7c6fa..037f129d5b 100644
--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
@@ -24,7 +24,8 @@
* (Write / file-change add)也不能只凭存在性:Write 可能覆盖既有文件,失败路径也可能
* 被后续轮次创建;因此它必须有落在窗口内的 birthtime,不可用时宁可不出。
* command 来源为兼容不提供 birthtime 的 Linux FS 允许 mtime 回退,但同样受完整
- * 时间窗约束。远程会话无法读取创建时间,维持远端 stat 的存在性复核。
+ * 时间窗约束。远程工具产物维持 stat 存在性复核;设备互联命令产物额外检查远端 mtime,
+ * 用远端消息时间窗判定,不使用控制端时钟,也不复用普通链接的存在性缓存;SSH 保持仅工具产物。
*/
import { CHAT_FOCUS_CLASS, CHAT_COLOR_TRANSITION_CLASS } from './chatChrome';
@@ -727,15 +728,26 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({
const watched = new Set(
files
.filter(
- (file) => file.source === 'tool' && isGeneratedFileStatable(file, turnEndMs, turnSealed),
+ (file) =>
+ isGeneratedFileStatable(file, turnEndMs, turnSealed) &&
+ (file.source === 'tool' || (remoteOrigin.kind === 'device' && turnStartMs !== null)),
)
- .map((file) => remotePathVerdictKey(remoteOrigin, fileCtx.workingDir, file.path)),
+ .map((file) =>
+ remotePathVerdictKey(
+ remoteOrigin,
+ fileCtx.workingDir,
+ file.path,
+ file.source === 'command' && turnStartMs !== null
+ ? { startMs: turnStartMs - TURN_START_SLACK_MS, endMs: turnEndMs }
+ : undefined,
+ ),
+ ),
);
if (watched.size === 0) return;
return subscribeRemotePathVerdictChange((key) => {
if (watched.has(key)) setRemoteVerdictGen((generation) => generation + 1);
});
- }, [remoteOrigin, fileCtx.workingDir, checkKey, files, turnEndMs, turnSealed]);
+ }, [remoteOrigin, fileCtx.workingDir, checkKey, files, turnStartMs, turnEndMs, turnSealed]);
useEffect(() => {
let cancelled = false;
@@ -772,7 +784,10 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({
}
const toStat = remoteOrigin
- ? plan.toStat.filter((file) => file.source === 'tool')
+ ? plan.toStat.filter(
+ (file) =>
+ file.source === 'tool' || (remoteOrigin.kind === 'device' && turnStartMs !== null),
+ )
: plan.toStat;
if (toStat.length === 0) {
return () => {
@@ -789,6 +804,9 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({
remoteOrigin,
fileCtx.workingDir,
file.path,
+ file.source === 'command' && turnStartMs !== null
+ ? { startMs: turnStartMs - TURN_START_SLACK_MS, endMs: turnEndMs }
+ : undefined,
);
return isConfirmedRemoteGeneratedFile(verdict);
}),
@@ -846,7 +864,11 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({
const hiddenPrimaryCount = primary.length - visiblePrimary.length;
return (
- <div data-render-item-key={renderItemKey} className="my-1 flex max-w-[680px] flex-col gap-2" data-testid="bot-generated-artifacts">
+ <div
+ data-render-item-key={renderItemKey}
+ className="my-1 flex max-w-[680px] flex-col gap-2"
+ data-testid="bot-generated-artifacts"
+ >
{primary.length > 0 ? (
<>
<span className="text-12 font-medium text-[var(--text-secondary)]">
diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
index 3bc2f714c5..b9b40aed3f 100644
--- a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
@@ -16,6 +16,10 @@ import { useSidebarHostSessionId } from '@/features/right-sidebar/lib/sidebarHos
import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
import { resolveToolFilePath } from '@/lib/localPathResolver';
import { toast } from '@/lib/toast';
+import { makerApiForSticky } from '@/lib/makerTransport';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { turnChangeReadApiFor } from '@/lib/gitReviewTransport';
import { basename, cn } from '@/lib/utils';
import { extractIpcError } from '@/utils/ipcError';
import { isBrowserOpenablePath } from '../../../shared/browserOpenableExts';
@@ -106,6 +110,13 @@ export function TurnChangesCard({
const [workspaceStateOverride, setWorkspaceStateOverride] = useState<
TurnChangeSetSummary['workspaceState'] | null
>(null);
+ const activeCard = useRef<string | null>(null);
+ const cardKey = JSON.stringify([sessionId, changeSet.id]);
+ activeCard.current = cardKey;
+ useEffect(() => {
+ activeCard.current = cardKey;
+ return () => { activeCard.current = null; };
+ }, [cardKey]);
const latestWorkspaceStateRef = useRef(changeSet.workspaceState);
latestWorkspaceStateRef.current = changeSet.workspaceState;
const files = changeSet.files;
@@ -116,9 +127,7 @@ export function TurnChangesCard({
const appliesCapturedSubset = changeSet.state === 'partial' && changeSet.isReversible;
useEffect(() => {
- setWorkspaceStateOverride((current) => (
- current === changeSet.workspaceState ? null : current
- ));
+ setWorkspaceStateOverride(null);
}, [changeSet.workspaceState]);
useEffect(() => {
@@ -139,28 +148,53 @@ export function TurnChangesCard({
const applyTurnChange = async (): Promise<void> => {
if (applying || !changeSet.isReversible) return;
const action = workspaceState === 'undone' ? 'reapply' : 'undo';
+ const owner = getDataOwnerGeneration();
+ const deviceId = getStickySessionDeviceId(sessionId);
+ const current = () => activeCard.current === cardKey &&
+ isDataOwnerGenerationCurrent(owner) && getStickySessionDeviceId(sessionId) === deviceId;
+ const notifyApplied = () => toast.success(t(
+ appliesCapturedSubset
+ ? action === 'undo'
+ ? 'chat.turnChanges.undoPartialSuccess'
+ : 'chat.turnChanges.reapplyPartialSuccess'
+ : action === 'undo'
+ ? 'chat.turnChanges.undoSuccess'
+ : 'chat.turnChanges.reapplySuccess',
+ ));
setApplying(true);
try {
- const result = await window.electronAPI.maker.applyTurnChangeSet(
+ const result = await makerApiForSticky(sessionId).applyTurnChangeSet(
sessionId,
changeSet.id,
action,
);
+ if (!current()) return;
setWorkspaceStateOverride(
result.summary.workspaceState === latestWorkspaceStateRef.current
? null
: result.summary.workspaceState,
);
- toast.success(t(
- appliesCapturedSubset
- ? action === 'undo'
- ? 'chat.turnChanges.undoPartialSuccess'
- : 'chat.turnChanges.reapplyPartialSuccess'
- : action === 'undo'
- ? 'chat.turnChanges.undoSuccess'
- : 'chat.turnChanges.reapplySuccess',
- ));
+ notifyApplied();
} catch (error) {
+ if (!current()) return;
+ // A lost response does not prove the host failed to write. Reconcile once;
+ // never replay the mutation. Reconnect also refreshes the cards.
+ if (deviceId) {
+ try {
+ const summaries = await turnChangeReadApiFor(deviceId).listTurnChangeSets(sessionId);
+ const summary = summaries.find((item) => item.id === changeSet.id);
+ if (current() && summary) {
+ setWorkspaceStateOverride(
+ summary.workspaceState === latestWorkspaceStateRef.current ? null : summary.workspaceState,
+ );
+ if (summary.workspaceState === (action === 'undo' ? 'undone' : 'applied')) {
+ notifyApplied();
+ return;
+ }
+ }
+ } catch { /* Reconnect refresh in useTurnChangeSets remains authoritative. */ }
+ }
+ if (!current()) return;
const code = extractIpcError(error)?.code;
const key = code === 'SESSION_RUNNING'
? 'chat.turnChanges.actionRunning'
@@ -173,7 +207,7 @@ export function TurnChangesCard({
: 'chat.turnChanges.actionFailed';
toast.error(t(key));
} finally {
- setApplying(false);
+ if (current()) setApplying(false);
}
};
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx
new file mode 100644
index 0000000000..888c7d65ca
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx
@@ -0,0 +1,96 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ChatSessionFileProvider } from '../ChatSessionFileContext';
+import { GeneratedFilesCard } from '../GeneratedFilesCard';
+import { _clearRemotePathVerdictCache } from '@/lib/remoteFileOpen';
+
+vi.mock('../useFileChipContextMenu', () => ({
+ useFileChipContextMenu: () => ({ menu: null, onContextMenu: vi.fn() }),
+}));
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('react-i18next')>()),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+afterEach(() => {
+ cleanup();
+ _clearRemotePathVerdictCache();
+ vi.unstubAllGlobals();
+});
+
+describe('remote generated files', () => {
+ it('shows a command artifact after remote verification and never stats the controller filesystem', async () => {
+ const chatStat = vi.fn().mockResolvedValue({ verdict: 'file' });
+ const statPath = vi.fn();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ fileBrowser: { chatStat },
+ fsBrowse: { statPath },
+ },
+ });
+ render(
+ <ChatSessionFileProvider
+ value={{
+ sessionId: 'remote-task',
+ workingDir: '/remote',
+ origin: { kind: 'device', deviceId: 'host' },
+ }}
+ >
+ <GeneratedFilesCard
+ files={[
+ { path: '/remote/report.zip', name: 'report.zip', source: 'command', ready: true },
+ ]}
+ turnStartMs={200_000}
+ turnEndMs={300_000}
+ turnSealed
+ />
+ </ChatSessionFileProvider>,
+ );
+ await waitFor(() => expect(screen.getByText('report.zip')).toBeTruthy());
+ expect(chatStat).toHaveBeenCalledWith({
+ origin: { kind: 'device', deviceId: 'host' },
+ workdir: '/remote',
+ absPath: '/remote/report.zip',
+ modifiedWindow: { startMs: 80_000, endMs: 300_000 },
+ });
+ expect(statPath).not.toHaveBeenCalled();
+ });
+ it('keeps SSH tool artifacts without applying the Desktop clock to SSH command artifacts', async () => {
+ const chatStat = vi.fn().mockResolvedValue({ verdict: 'file' });
+ const statPath = vi.fn();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { fileBrowser: { chatStat }, fsBrowse: { statPath } },
+ });
+ render(
+ <ChatSessionFileProvider
+ value={{
+ sessionId: 'ssh-task',
+ workingDir: '/remote',
+ origin: { kind: 'ssh', remoteHostId: 'host' },
+ }}
+ >
+ <GeneratedFilesCard
+ files={[
+ { path: '/remote/report.zip', name: 'report.zip', source: 'command', ready: true },
+ { path: '/remote/notes.txt', name: 'notes.txt', source: 'tool', ready: true },
+ ]}
+ turnStartMs={200_000}
+ turnEndMs={300_000}
+ turnSealed
+ />
+ </ChatSessionFileProvider>,
+ );
+ await waitFor(() => expect(screen.getByText('notes.txt')).toBeTruthy());
+ expect(screen.queryByText('report.zip')).toBeNull();
+ expect(chatStat).toHaveBeenCalledTimes(1);
+ expect(chatStat).toHaveBeenCalledWith({
+ origin: { kind: 'ssh', remoteHostId: 'host' },
+ workdir: '/remote',
+ absPath: '/remote/notes.txt',
+ });
+ expect(statPath).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
index 52985c0d88..2586aff3c0 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
@@ -43,6 +43,8 @@ vi.mock('../useFileChipContextMenu', () => ({
useFileChipContextMenu: mocks.useFileChipContextMenu,
}));
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import type { Session } from '@/lib/ccAgent.types';
import { SidebarHostSessionProvider } from '@/features/right-sidebar/lib/sidebarHostSession';
import { TurnChangesCard } from '../TurnChangesCard';
import type { TurnChangeSetSummary } from '../../../../shared/turnChangeSet';
@@ -259,6 +261,26 @@ describe('TurnChangesCard file actions', () => {
expect(screen.queryByRole('button', { name: 'chat.turnChanges.undoAria' })).toBeNull();
});
+ it('reconciles a lost remote undo response without replaying the write or touching local files', async () => {
+ const sessionId = 'remote-restore-card';
+ const remoteSummary = { ...CHANGE_SET, sessionId, workspaceState: 'undone' };
+ const invoke = vi.fn()
+ .mockRejectedValueOnce(new Error('request timed out'))
+ .mockResolvedValueOnce({ ok: true, result: [remoteSummary] });
+ Object.assign(window.electronAPI, { deviceLink: { invoke } });
+ remoteProjectsStore.setDeviceSessions('card-host', 'Host', [{ id: sessionId } as Session]);
+ render(<TurnChangesCard sessionId={sessionId} changeSet={{ ...CHANGE_SET, sessionId }} />);
+ fireEvent.click(screen.getByRole('button', { name: 'chat.turnChanges.undoAria' }));
+ await screen.findByRole('button', { name: 'chat.turnChanges.reapplyAria' });
+ expect(mocks.toastSuccess).toHaveBeenCalledWith('chat.turnChanges.undoSuccess');
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ expect(invoke.mock.calls).toEqual([
+ ['card-host', 'maker:turn-change-set:apply', [sessionId, CHANGE_SET.id, 'undo']],
+ ['card-host', 'git-review:remote-op', [{ op: 'turn-list', payload: { sessionId } }]],
+ ]);
+ expect(mocks.applyTurnChangeSet).not.toHaveBeenCalled();
+ });
+
it('does not offer undo for a non-reversible patch', () => {
render(
<TurnChangesCard
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/useTurnChangeSets.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/useTurnChangeSets.test.tsx
index 5551b5e92c..476485369e 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/useTurnChangeSets.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/useTurnChangeSets.test.tsx
@@ -13,9 +13,20 @@ const transport = vi.hoisted(() => ({
originListeners: new Set<() => void>(),
updates: new Map<string, (payload: TurnChangeSetUpdatedPayload) => void>(),
list: vi.fn(),
+ remoteList: vi.fn(),
+ connected: true,
+}));
+vi.mock('@/features/device-link/stickySessionOrigin', () => ({
+ getStickySessionDeviceId: (id: string) => transport.remote.has(id) ? 'device' : undefined,
+}));
+vi.mock('@/lib/gitReviewTransport', () => ({
+ turnChangeReadApiFor: (deviceId?: string) => ({
+ listTurnChangeSets: deviceId ? transport.remoteList : transport.list,
+ }),
}));
vi.mock('@/features/device-link/remoteProjectsStore', () => ({
remoteProjectsStore: {
+ getDeviceList: () => [{ deviceId: 'device', connected: transport.connected }],
subscribe: (listener: () => void) => {
transport.originListeners.add(listener);
return () => transport.originListeners.delete(listener);
@@ -64,7 +75,9 @@ let ownerNumber = 0;
beforeEach(() => {
setDataOwnerGeneration(`owner-${++ownerNumber}`);
transport.remote.clear();
+ transport.connected = true;
transport.list.mockReset().mockResolvedValue([]);
+ transport.remoteList.mockReset().mockResolvedValue([]);
vi.stubGlobal('electronAPI', undefined);
Object.defineProperty(window, 'electronAPI', {
configurable: true,
@@ -194,12 +207,66 @@ describe('turn change card cache', () => {
});
await act(async () => request.resolve([summary()]));
expect(view.result.current).toEqual([]);
- expect(transport.updates.has('a')).toBe(false);
+ expect(transport.updates.has('a')).toBe(true);
+ expect(transport.remoteList).toHaveBeenCalledWith('a');
const ssh = renderHook(() => useTurnChangeSets('ssh', 'host'));
expect(ssh.result.current).toEqual([]);
expect(transport.list).toHaveBeenCalledTimes(1);
});
+ it('loads remote history, preserves a newer remote push, and never reads local records', async () => {
+ transport.remote.add('a');
+ const request = deferred();
+ transport.remoteList.mockReturnValueOnce(request.promise);
+ const view = renderHook(() => useTurnChangeSets('a', null));
+ act(() => transport.updates.get('a')?.({ sessionId: 'a', summary: summary('change', 9) }));
+ await act(async () => request.resolve([summary()]));
+ expect(view.result.current[0]?.additions).toBe(9);
+ expect(transport.list).not.toHaveBeenCalled();
+ });
+
+ it('refreshes on reconnect without falling back to local reads while disconnected', async () => {
+ transport.remote.add('a');
+ transport.remoteList.mockResolvedValueOnce([summary()]);
+ const view = renderHook(() => useTurnChangeSets('a', null));
+ await act(async () => {});
+ act(() => {
+ transport.connected = false;
+ for (const notify of transport.originListeners) notify();
+ });
+ expect(view.result.current).toEqual([summary()]);
+ transport.remoteList.mockResolvedValueOnce([summary('change', 12)]);
+ act(() => {
+ transport.connected = true;
+ for (const notify of transport.originListeners) notify();
+ });
+ await act(async () => {});
+ expect(view.result.current[0]?.additions).toBe(12);
+ expect(transport.remoteList).toHaveBeenCalledTimes(2);
+ expect(transport.list).not.toHaveBeenCalled();
+ });
+
+ it.each([1, 2])('replaces pending reads across reconnect with %i mounted panes', async (panes) => {
+ transport.remote.add('a');
+ const old = deferred(), fresh = deferred();
+ transport.remoteList.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise);
+ const views = Array.from({ length: panes }, () => renderHook(() => useTurnChangeSets('a', null)));
+ // Each root can observe the connection transition separately while another
+ // pane still holds a subscription to the same cached entry.
+ transport.connected = false;
+ for (const notify of [...transport.originListeners]) act(() => notify());
+ transport.connected = true;
+ for (const notify of [...transport.originListeners]) act(() => notify());
+ expect(transport.remoteList).toHaveBeenCalledTimes(2);
+ await act(async () => old.resolve([summary()]));
+ expect(views[0].result.current).toEqual([]);
+ const updated = { ...summary(), workspaceState: 'undone' as const };
+ act(() => transport.updates.get('a')?.({ sessionId: 'a', summary: updated }));
+ await act(async () => fresh.resolve([summary()]));
+ for (const view of views) expect(view.result.current).toEqual([updated]);
+ expect(transport.list).not.toHaveBeenCalled();
+ });
+
it('keeps cached cards on refresh failure and shares live state across split panes', async () => {
transport.list.mockResolvedValueOnce([summary()]);
const first = renderHook(() => useTurnChangeSets('a', null));
diff --git a/apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts b/apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts
index cf8cc39d97..acdf516a0e 100644
--- a/apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts
+++ b/apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts
@@ -1,10 +1,9 @@
import { useMemo, useSyncExternalStore } from 'react';
-import {
- getDataOwnerGeneration,
- isDataOwnerIdCurrent,
-} from '@/contexts/dataOwnerGeneration';
+import { getDataOwnerGeneration, isDataOwnerIdCurrent } from '@/contexts/dataOwnerGeneration';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
-import { isRemoteSessionSticky, subscribeTurnChangeSetUpdated } from '@/lib/makerTransport';
+import { subscribeTurnChangeSetUpdated } from '@/lib/makerTransport';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
+import { turnChangeReadApiFor } from '@/lib/gitReviewTransport';
import type { TurnChangeSetSummary } from '../../../shared/turnChangeSet';
const EMPTY: TurnChangeSetSummary[] = [];
@@ -62,24 +61,41 @@ export function useTurnChangeSets(
sessionId: string | undefined,
remoteHostId: string | null | undefined,
) {
- const remote = useSyncExternalStore(
+ const deviceId = useSyncExternalStore(
remoteProjectsStore.subscribe,
- () => Boolean(sessionId && isRemoteSessionSticky(sessionId)),
+ () => (sessionId ? getStickySessionDeviceId(sessionId) : undefined),
+ () => undefined,
+ );
+ const enabled = Boolean(sessionId && remoteHostId === null);
+ const connected = useSyncExternalStore(
+ remoteProjectsStore.subscribe,
+ () =>
+ !deviceId ||
+ remoteProjectsStore
+ .getDeviceList()
+ .some((device) => device.deviceId === deviceId && device.connected),
() => false,
);
- const enabled = Boolean(sessionId && remoteHostId === null && !remote);
const owner = getDataOwnerGeneration();
const store = useMemo(() => {
if (!enabled || !sessionId) return { getSnapshot: () => EMPTY, subscribe: () => () => {} };
- const entry = entryFor(sessionId);
+ const cacheKey = JSON.stringify([deviceId ?? null, sessionId]);
+ const entry = entryFor(cacheKey);
const current = () =>
isDataOwnerIdCurrent(owner) &&
- cache.get(sessionId) === entry &&
- !isRemoteSessionSticky(sessionId);
+ cache.get(cacheKey) === entry &&
+ getStickySessionDeviceId(sessionId) === deviceId;
return {
getSnapshot: () => (current() ? entry.summaries : EMPTY),
subscribe: (listener: () => void) => {
entry.listeners.add(listener);
+ // Invalidate on disconnect even while another pane keeps this entry subscribed.
+ // A late pre-disconnect reply must neither publish nor clear the new request.
+ if (!connected && entry.pending) {
+ entry.generation += 1;
+ entry.pending = null;
+ entry.updates.clear();
+ }
if (!entry.unsubscribe) {
let subscribed = true;
const off = subscribeTurnChangeSetUpdated(sessionId, ({ summary }) => {
@@ -92,10 +108,10 @@ export function useTurnChangeSets(
off();
};
}
- if (!entry.pending && current()) {
+ if (connected && !entry.pending && current()) {
entry.updates.clear();
const generation = ++entry.generation;
- entry.pending = window.electronAPI.maker
+ entry.pending = turnChangeReadApiFor(deviceId)
.listTurnChangeSets(sessionId)
.then((summaries) => {
if (!current() || generation !== entry.generation) return;
@@ -128,6 +144,6 @@ export function useTurnChangeSets(
};
},
};
- }, [enabled, sessionId, owner]);
+ }, [enabled, sessionId, owner, deviceId, connected]);
return useSyncExternalStore(store.subscribe, store.getSnapshot, () => EMPTY);
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
index b65f7d44b7..6af144aded 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
@@ -1460,7 +1460,7 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {
desc={
error === REVIEW_TURN_LOCAL_ONLY_ERROR
? t('rightSidebar.review.turn.localOnly')
- : error
+ : localizeReviewError(error)
}
actionLabel={t('rightSidebar.review.refresh')}
onAction={refreshAll}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts
index 6dca28983f..5d26fe81c8 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
useReviewFileDiffs: vi.fn(),
useLastTurnFilter: vi.fn(),
getTurnChangeSets: vi.fn(),
+ invoke: vi.fn(),
}));
vi.mock('../useReviewGitState', () => ({
@@ -71,7 +72,7 @@ describe('useReviewSource', () => {
mocks.getTurnChangeSets.mockReset();
Object.defineProperty(window, 'electronAPI', {
configurable: true,
- value: { maker: { getTurnChangeSets: mocks.getTurnChangeSets } },
+ value: { maker: { getTurnChangeSets: mocks.getTurnChangeSets }, deviceLink: { invoke: mocks.invoke } },
});
});
@@ -120,6 +121,22 @@ describe('useReviewSource', () => {
expect(mocks.getTurnChangeSets).not.toHaveBeenCalled();
});
+ it('opens the selected remote message snapshot without reading local Git or local history', async () => {
+ const recordedDiff = diff('remote.txt');
+ mocks.invoke.mockResolvedValue({ ok: true, result: [{ id: 'set-1', state: 'complete', diffs: [recordedDiff] }] });
+ const { result } = renderHook(() => useReviewSource(
+ { kind: 'turn-set', targetSessionId: 'remote-task', changeSetIds: ['set-1'] },
+ 'host-session',
+ { hideWhitespace: false, deviceLinkDeviceId: 'device', remoteHostId: null },
+ ));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.diffs).toEqual([recordedDiff]);
+ expect(mocks.invoke).toHaveBeenCalledWith('device', 'git-review:remote-op', [
+ { op: 'turn-get', payload: { sessionId: 'remote-task', ids: ['set-1'] } },
+ ]);
+ expect(mocks.getTurnChangeSets).not.toHaveBeenCalled();
+ });
+
it('fails closed while device-link ownership is unresolved', async () => {
const { result } = renderHook(() =>
useReviewSource(
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts
index 64b2352dd9..247e835f4a 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts
@@ -10,6 +10,7 @@ import type {
ReviewFileDiffRequest,
} from '@/lib/gitReview.types';
import { extractIpcError } from '@/utils/ipcError';
+import { turnChangeReadApiFor } from '@/lib/gitReviewTransport';
import { buildCappedDiffData } from '../../../../../shared/gitReviewCapped';
import type { ReviewSourceDescriptor } from '../../../../../shared/reviewSource';
import type { TurnChangeSetDetail } from '../../../../../shared/turnChangeSet';
@@ -208,7 +209,7 @@ export function useReviewSource(
descriptor.kind === 'turn-set' ? descriptor.changeSetIds.join('\0') : '';
const turnKey =
descriptor.kind === 'turn-set'
- ? `${turnTargetSessionId ?? sessionId ?? ''}\0${turnChangeSetIdsKey}`
+ ? `${deviceLinkDeviceId ?? ''}\0${remoteHostId ?? ''}\0${turnTargetSessionId ?? sessionId ?? ''}\0${turnChangeSetIdsKey}`
: null;
const [turnReloadToken, setTurnReloadToken] = useState(0);
const [turnState, setTurnState] = useState<TurnLoadState>({
@@ -220,7 +221,7 @@ export function useReviewSource(
useEffect(() => {
if (descriptor.kind !== 'turn-set' || !turnKey) return;
let cancelled = false;
- if (!sessionId || remoteHostId !== null || deviceLinkDeviceId !== null) {
+ if (!sessionId || remoteHostId !== null || deviceLinkDeviceId === undefined) {
setTurnState({
key: turnKey,
changeSets: [],
@@ -236,7 +237,7 @@ export function useReviewSource(
error: null,
}));
const reviewSessionId = turnTargetSessionId ?? sessionId;
- void window.electronAPI.maker
+ void turnChangeReadApiFor(deviceLinkDeviceId)
.getTurnChangeSets(reviewSessionId, turnChangeSetIdsKey.split('\0'))
.then((changeSets) => {
if (!cancelled) setTurnState({ key: turnKey, changeSets, loading: false, error: null });
diff --git a/apps/desktop/src/renderer/lib/gitReviewTransport.ts b/apps/desktop/src/renderer/lib/gitReviewTransport.ts
index 6c9acf1e9a..e248f5bf72 100644
--- a/apps/desktop/src/renderer/lib/gitReviewTransport.ts
+++ b/apps/desktop/src/renderer/lib/gitReviewTransport.ts
@@ -23,6 +23,17 @@
import { gunzipBase64ToText } from './gzipBase64';
+/** Historical turn snapshots use the same read-only, size-checked review tunnel. */
+export function turnChangeReadApiFor(
+ deviceId: string | null | undefined,
+): Pick<typeof window.electronAPI.maker, 'listTurnChangeSets' | 'getTurnChangeSets'> {
+ if (!deviceId) return window.electronAPI.maker;
+ return {
+ listTurnChangeSets: (sessionId) => invokeOp(deviceId, 'turn-list', { sessionId }),
+ getTurnChangeSets: (sessionId, ids) => invokeOp(deviceId, 'turn-get', { sessionId, ids }),
+ };
+}
+
type LocalGitReview = typeof window.electronAPI.gitReview;
/** 只读子集:device-link 场景可用的查询面。 */
@@ -68,7 +79,8 @@ async function invokeOp<T>(deviceId: string, op: string, payload: object): Promi
if (res && res.ok === false && 'code' in res && res.code === 'OVERSIZE') {
throw new Error(`${OVERSIZE_MARKER}: review payload exceeds device-link frame budget`);
}
- const message = res && res.ok === false && 'message' in res ? res.message : 'git-review remote-op failed';
+ const message =
+ res && res.ok === false && 'message' in res ? res.message : 'git-review remote-op failed';
throw new Error(message);
}
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index 81547cb40d..181e95f76c 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -96,6 +96,7 @@ export interface RoutableMaker {
forkStripEncrypted: FullMaker['forkStripEncrypted'];
rewindPreview: FullMaker['rewindPreview'];
rewindCommit: FullMaker['rewindCommit'];
+ applyTurnChangeSet: FullMaker['applyTurnChangeSet'];
getContextUsage: FullMaker['getContextUsage'];
setExtraDirs: FullMaker['setExtraDirs'];
setWritableDirs: FullMaker['setWritableDirs'];
@@ -176,6 +177,7 @@ function remoteMakerApi(deviceId: string): RoutableMaker {
listBotDelegations: t('maker:bot-delegations:list') as FullMaker['listBotDelegations'],
cancelBotDelegation: t('maker:bot-delegation:cancel') as FullMaker['cancelBotDelegation'],
getBotDirectMessageThread: t('maker:bot-direct-message-thread:get') as FullMaker['getBotDirectMessageThread'],
+ applyTurnChangeSet: t('maker:turn-change-set:apply') as FullMaker['applyTurnChangeSet'],
send: t('maker:send') as FullMaker['send'],
setModel: (async (...args: SetModelArgs) =>
invokeRemote(
@@ -290,7 +292,7 @@ export function makerApiForSticky(sessionId: string): RoutableMaker {
return deviceId ? makerApiForDevice(deviceId) : window.electronAPI.maker;
}
-/** Subscribe to local exact-turn updates; remote sessions deliberately fail closed in this phase. */
+/** Subscribe to summaries from the owning device; exact patches are fetched on demand. */
export function subscribeTurnChangeSetUpdated(
sessionId: string,
cb: (payload: TurnChangeSetUpdatedPayload) => void,
@@ -304,9 +306,13 @@ export function subscribeTurnChangeSetUpdated(
cb(payload as TurnChangeSetUpdatedPayload);
});
}
- // Exact patches can exceed the 2 MiB device-link frame. This phase fails closed for
- // controlled sessions instead of truncating a patch and presenting it as exact.
- return () => {};
+ return window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {
+ if (push.deviceId !== deviceId || push.channel !== 'maker:turn-change-set:updated') return;
+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;
+ const payload = push.payload as Partial<TurnChangeSetUpdatedPayload> | null;
+ if (payload?.sessionId !== sessionId || payload.summary?.sessionId !== sessionId) return;
+ cb(payload as TurnChangeSetUpdatedPayload);
+ });
};
let currentDeviceId = getStickySessionDeviceId(sessionId);
diff --git a/apps/desktop/src/renderer/lib/remoteFileOpen.ts b/apps/desktop/src/renderer/lib/remoteFileOpen.ts
index 6d9e868461..63d8fdd452 100644
--- a/apps/desktop/src/renderer/lib/remoteFileOpen.ts
+++ b/apps/desktop/src/renderer/lib/remoteFileOpen.ts
@@ -125,6 +125,7 @@ export async function revealRemoteChatFile(
// 「把 unknown 当结论」这个错误在类型与结构上不可表达,比省一帧重绘值钱。
export type RemotePathVerdict = 'file' | 'directory' | 'nonfile' | 'unknown';
+export type RemoteModifiedWindow = { startMs: number; endMs: number | null };
const VERDICT_CACHE_CAP = 1000;
/** unknown 负缓存 TTL:链路差时同 key 最多每 30s 重验一次(与移动端同值)。 */
@@ -195,9 +196,18 @@ function scheduleStaleSweep(delayMs: number): void {
}, Math.max(1, delayMs));
}
-function verdictKey(origin: RemoteFileOrigin, workdir: string, absPath: string): string {
- const endpoint = origin.kind === 'device' ? `dev:${origin.deviceId}` : `ssh:${origin.remoteHostId}`;
- return `${endpoint}|${workdir}|${absPath}`;
+function verdictKey(
+ origin: RemoteFileOrigin,
+ workdir: string,
+ absPath: string,
+ modifiedWindow?: RemoteModifiedWindow,
+): string {
+ const endpoint =
+ origin.kind === 'device' ? `dev:${origin.deviceId}` : `ssh:${origin.remoteHostId}`;
+ return (
+ `${endpoint}|${workdir}|${absPath}` +
+ (modifiedWindow ? `|mtime:${modifiedWindow.startMs}:${modifiedWindow.endMs}` : '')
+ );
}
/** 缓存 key(供订阅方按 key 过滤变化通知)。 */
@@ -205,8 +215,9 @@ export function remotePathVerdictKey(
origin: RemoteFileOrigin,
workdir: string,
absPath: string,
+ modifiedWindow?: RemoteModifiedWindow,
): string {
- return verdictKey(origin, workdir, absPath);
+ return verdictKey(origin, workdir, absPath, modifiedWindow);
}
/**
@@ -251,8 +262,9 @@ export function verifyRemotePathCached(
origin: RemoteFileOrigin,
workdir: string,
absPath: string,
+ modifiedWindow?: RemoteModifiedWindow,
): Promise<RemotePathVerdict> {
- const key = verdictKey(origin, workdir, absPath);
+ const key = verdictKey(origin, workdir, absPath, modifiedWindow);
const hit = verdictCache.get(key);
if (hit) return Promise.resolve(hit);
const pending = verdictInflight.get(key);
@@ -268,7 +280,12 @@ export function verifyRemotePathCached(
? ({ kind: 'device', deviceId: origin.deviceId } as const)
: ({ kind: 'ssh', remoteHostId: origin.remoteHostId } as const);
const p = window.electronAPI.fileBrowser
- .chatStat({ origin: wireOrigin, workdir, absPath })
+ .chatStat({
+ origin: wireOrigin,
+ workdir,
+ absPath,
+ ...(modifiedWindow ? { modifiedWindow } : {}),
+ })
.then((res) => res.verdict)
.catch(() => 'unknown' as const)
.then((verdict) => {
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 24779b6785..5e47be9faa 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,25 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## 电脑互联的消息文件与历史变更
+
+设备互联生成文件沿用远端文件服务的 stat 与修改时间,控制端按被控端消息时间窗校验命令产物;
+仅有文件存在、缺失时间戳或读取失败不构成命令产物证据。不增加 relay 协议字段。
+SSH 保持仅展示经过存在性复核的工具产物,不把 Desktop 消息时间与 SSH 主机文件时间比较。
+历史变更在既有只读 `git-review:remote-op` 上追加 `turn-list` / `turn-get`,
+按被控端任务 ID 读取已保存的摘要和精确差异,沿用 gzip 与 OVERSIZE 边界,不截断补丁。
+`maker:turn-change-set:updated` 仅向同账号设备推摘要,归属 `session:<id>`,沿用账号和任务可见性复核。
+共享任务访客不接收该推送(含离线补发),其既有读取与操作权限不变。
+旧主机不认识新 op 时保留原无卡片行为,不回落读取控制端本机记录;完整历史变更展示需要两台
+电脑升级。旧控制端忽略新增摘要推送,原行为不变。
+撤销/重新应用追加独立写通道 `maker:turn-change-set:apply`,参数为任务 ID、变更 ID 和
+`undo` / `reapply`;只读 remote-op 不接收写操作。被控端复用本机冲突、运行状态、路径和
+快照状态校验,并在队列和 Git 预检后复核远程授权;本机 IPC 的受信窗口检查保持不变。
+旧主机拒绝新通道时显示操作失败,不回退本机。写请求不加入自动重试或读取合并白名单;
+摘要推送和重连后的重读恢复显示,超时不能证明操作未执行。
+本次覆盖 Desktop 设备互联;SSH 任务没有本机历史变更快照,仍不显示该卡片;
+Mobile 未新增卡片入口。服务端无需改动。
+
## 任务列表标签目录
`sessions:list` 第三个参数可追加 `tagCatalog: 1`。支持的主机仅对该请求返回
diff --git a/packages/device-link/src/__tests__/topics.test.ts b/packages/device-link/src/__tests__/topics.test.ts
index 433de88cb9..27ac85bcea 100644
--- a/packages/device-link/src/__tests__/topics.test.ts
+++ b/packages/device-link/src/__tests__/topics.test.ts
@@ -15,6 +15,10 @@ import {
} from '../topics.js';
describe('topicForPush', () => {
+ it('routes historical file summaries only to the owning task', () => {
+ expect(topicForPush('maker:turn-change-set:updated', { sessionId: 's1' })).toBe('session:s1');
+ expect(topicForPush('maker:turn-change-set:updated', {})).toBeNull();
+ });
it('delivers companion task state to the parent and private-thread changes to the account topic', () => {
expect(topicForPush('maker:bot-delegation:changed', { parentSessionId: 'parent', childSessionId: 'child' })).toBe('session:parent');
expect(topicForPush('maker:bot-delegation:changed', { parentSessionId: null })).toBeNull();
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index e73ec7e309..6f2e988629 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -390,6 +390,8 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// —— Rewind / Fork / Title / Context ——
'maker:rewind:preview',
'maker:rewind:commit',
+ // Shared action via dispatch injection; local IPC retains its trusted-renderer guard.
+ 'maker:turn-change-set:apply',
'maker:fork',
'maker:fork-strip-encrypted',
'maker:generate-title',
@@ -637,6 +639,8 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
'maker:orca:worker-changed',
// goal 状态变化(payload 顶层 sessionId → 路由到 session:<id> topic,打开该会话的控制端可见)
'maker:goal:status-changed',
+ // Bounded historical-turn summary only; full patches are fetched through git-review:remote-op.
+ 'maker:turn-change-set:updated',
'usage:message-turn-cost',
// 本轮模型降级标记(payload 顶层 sessionId → 默认路由到 session:<id> topic):
// 控制端把 agent_meta.modelMismatch 实时 patch 进已打开的远程会话消息流。
@@ -718,6 +722,8 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
* client-agnostic:mobile/web 控制端应使用同一映射(与 allowlist 同为协议契约)。
*/
export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {
+ // Two Git preflight/apply stages each allow 30s, plus snapshot and queue overhead.
+ 'maker:turn-change-set:apply': 90_000,
[FILE_PEER_CHANNEL]: 30_000,
// Capture renderer readiness + source enumeration + offer, then reply delivery.
"device-link:remote-desktop:v1": REMOTE_DESKTOP_INVOKE_MS,