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。

fix(shared-task): 文件访问前重新绑定任务目录,目录变更后释放访客监听

david5a05294dcc0b
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
index 5968e304dc..aa79af02f8 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
@@ -52,4 +52,12 @@ describe('shared task workdir binding', () => {
const denied = await admitSharedTaskFsWatchTopics(capture({ authorize: () => false }), ['session:task', 'fs-watch:/host/task']);
expect(denied).toEqual({ topics: ['session:task'], verified: new Set() });
});
+
+ it('never looks up an oversized topic frame', async () => {
+ snapshot.mockClear();
+ const topics = Array.from({ length: 5000 }, (_, i) => `fs-watch:/host/task-${i}`);
+ const admitted = await admitSharedTaskFsWatchTopics(capture(), topics);
+ expect(admitted.verified.size).toBe(0);
+ expect(snapshot).not.toHaveBeenCalled();
+ });
});
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 1cd5aa2b04..eeb6cafcae 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
@@ -332,4 +332,37 @@ describe('shared task workdir watch', () => {
await vi.advanceTimersByTimeAsync(300);
expect(transport.sendPush.mock.calls.map((call) => call[0])).toEqual(['own-task']);
});
+
+ it('releases a guest watch on the old workdir when the owner moves the task', async () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ const oldWatch = 'fs-watch:/host/task-a';
+ expect(__testing.handleSubscriptionFrame(guestA, {
+ channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: ['session:task-a', oldWatch] }],
+ }, new Set([oldWatch])).ok).toBe(true);
+ subscriptions.subscribe(guestB, ['session:task-b', 'fs-watch:/host/task-b']);
+ subscriptions.subscribe('own-task', [oldWatch]);
+ // Same workdir (normalized) and unrelated patches keep the watch.
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 'task-a', patch: { workingDir: '/host/task-a/' } });
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 'task-a', patch: { title: 'Renamed' } });
+ expect(subscriptions.controllerHasTopic(guestA, oldWatch)).toBe(true);
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 'task-a', patch: { workingDir: '/host/moved' } });
+ expect(subscriptions.controllerHasTopic(guestA, oldWatch)).toBe(false);
+ expect(subscriptions.controllerHasTopic(guestA, 'session:task-a')).toBe(true);
+ // Another task's guest and same-account controllers are untouched.
+ expect(subscriptions.controllerHasTopic(guestB, 'fs-watch:/host/task-b')).toBe(true);
+ expect(subscriptions.controllerHasTopic('own-task', oldWatch)).toBe(true);
+ transport.sendPush.mockClear();
+ __testing.forwardPush('maker:file-browser:event', { workdir: '/host/task-a', type: 'add', relPath: 'a.ts' });
+ await vi.advanceTimersByTimeAsync(300);
+ expect(transport.sendPush.mock.calls.map((call) => call[0])).toEqual(['own-task']);
+ });
+
+ it('rejects an oversized topic frame without admitting it', async () => {
+ const frame = await __testing.handleSubscriptionFrame(guestA, {
+ channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: Array.from({ length: 50 }, (_, i) => `fs-watch:/host/x-${i}`) }],
+ });
+ expect(frame.ok).toBe(false);
+ expect(subscriptions.getControllerTopics(guestA)).toEqual([]);
+ });
});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index e53f509f5a..f74c7a6f4b 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -121,7 +121,7 @@ import { isProviderSharePeer, isSharedTaskPeer, parseProviderSharePeer, PROVIDER
import { captureSharedTaskPeer, captureSharedTaskPush, assertSharedTaskInvoke, sharedTaskMetadataTopic, sharedTaskAccessFailure } from './sharedTaskDispatch.js';
import { runAsBackgroundDbRpc } from '../localDb/client/rpcAdmission.js';
import { fetchLocalMediaToOss } from './mediaFetch';
-import { refreshSharedTaskPeer } from './sharedTaskDispatch.js';
+import { MAX_SHARED_TASK_TOPICS, refreshSharedTaskPeer, releaseSharedTaskWatchesOnWorkdirChange } from './sharedTaskDispatch.js';
import { admitSharedTaskFsWatchTopics } from './sharedTaskFileAccess.js';
import { transcribeRemoteVoiceInput } from './voiceTranscribe';
import { readTelegramRemoteStatus, setTelegramRemoteOnline } from './telegramRemoteControl';
@@ -1937,6 +1937,7 @@ function listMessagePayload(dst: string, sessionId: string, payload: unknown): u
}
function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {
+ releaseSharedTaskWatchesOnWorkdirChange(channel, payload);
if (!activeClient) return;
const topic = topicForPush(channel, payload);
if (!topic) return;
@@ -3893,7 +3894,9 @@ function admitSharedTaskSubscription(
const arg = rawArg && typeof rawArg === 'object' && !Array.isArray(rawArg)
? rawArg as Record<string, unknown> : null;
const topics = arg?.topics;
+ // Oversized frames skip the DB lookup; the synchronous gate rejects them.
if (!isSharedTaskPeer(src) || payload.channel !== DL_SUBSCRIBE_CHANNEL || !Array.isArray(topics)
+ || topics.length > MAX_SHARED_TASK_TOPICS
|| !topics.some((topic) => typeof topic === 'string' && parseFsWatchTopic(topic) !== null)) {
return null;
}
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index 989adf7cdd..adf952d3a0 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -1,6 +1,7 @@
import { FILE_BROWSER_EVENT_CHANNEL, FILE_BROWSER_REMOTE_OP_CHANNEL, fsWatchTopic, isSharedTaskPeer, parseFsWatchTopic, parseSharedTaskPeer, isSharedTaskAttachment, type InvokePayload, type InvokeResultPayload, type SharedTaskQueueItem } from '@cindy/device-link';
import type { SharedTaskHost } from './sharedTaskHost.js';
import * as subscriptions from './subscriptions.js';
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;
export interface SharedTaskInteractionCapture {
@@ -79,13 +80,36 @@ const interactionDecisionKinds = new Set(['permission', 'ask_user_question', 'pl
const fileReadOps = new Set(['caps', 'listDir', 'listAllFiles', 'readFile', 'stat', 'searchCollect', 'thumbnail', 'fileUrl']);
const fileWriteOps = new Set(['writeFile', 'createFile', 'createFolder', 'renameEntry', 'deleteEntry']);
/** A frame carries at most the task stream plus its workdir watch (reconnect replay merges them). */
-const MAX_SHARED_TASK_TOPICS = 4;
+export const MAX_SHARED_TASK_TOPICS = 4;
export function sharedTaskFileOperation(op: unknown): 'file.read' | 'file.write' | null {
if (typeof op !== 'string') return null;
return fileReadOps.has(op) ? 'file.read' : fileWriteOps.has(op) ? 'file.write' : null;
}
+/**
+ * A watch was admitted for the task workdir at subscribe time. When the owner
+ * moves the task, release guest watches on any other directory so they stop
+ * streaming the old one; the guest client re-subscribes to the new workdir
+ * through the normal admission.
+ */
+export function releaseSharedTaskWatchesOnWorkdirChange(channel: string, payload: unknown): void {
+ if (channel !== 'local-db:sessions:patched') return;
+ const row = record(payload);
+ const patch = record(row?.patch);
+ if (typeof row?.sessionId !== 'string' || !patch || !Object.prototype.hasOwnProperty.call(patch, 'workingDir')) return;
+ const next = normalizeWorkingDirForStorage(typeof patch.workingDir === 'string' ? patch.workingDir : null);
+ const peers = new Set([...subscriptions.getControllerIds(), ...subscriptions.getKnownControllerIds()]);
+ for (const peer of peers) {
+ if (!isSharedTaskPeer(peer) || captureSharedTaskPeer(peer)?.author.sessionId !== row.sessionId) continue;
+ const stale = subscriptions.getControllerTopics(peer).filter((topic) => {
+ const watched = parseFsWatchTopic(topic);
+ return watched !== null && normalizeWorkingDirForStorage(watched) !== next;
+ });
+ if (stale.length > 0) subscriptions.unsubscribe(peer, stale);
+ }
+}
+
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
}
diff --git a/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts b/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts
index 9e70a3300f..1029fd7fe5 100644
--- a/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts
@@ -1,7 +1,7 @@
import { parseFsWatchTopic } from '@cindy/device-link';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
-import type { SharedTaskPeerCapture } from './sharedTaskDispatch.js';
+import { MAX_SHARED_TASK_TOPICS, type SharedTaskPeerCapture } from './sharedTaskDispatch.js';
function deny(): never { throw new Error('[PERMISSION_DENIED] Working directory does not belong to this shared task'); }
@@ -35,14 +35,16 @@ export async function assertSharedTaskWorkdir(
export async function admitSharedTaskFsWatchTopics(
capture: SharedTaskPeerCapture, topics: readonly unknown[],
): Promise<{ topics: unknown[]; verified: Set<string> }> {
- const watched = topics.filter((topic) => typeof topic === 'string' && parseFsWatchTopic(topic) !== null);
- if (watched.length === 0) return { topics: [...topics], verified: new Set() };
+ // Oversized frames are rejected by the synchronous gate; never look them up.
+ if (topics.length > MAX_SHARED_TASK_TOPICS) return { topics: [...topics], verified: new Set() };
+ const watched = new Set(topics.filter((topic): topic is string => typeof topic === 'string' && parseFsWatchTopic(topic) !== null));
+ if (watched.size === 0) return { topics: [...topics], verified: new Set() };
const own = capture.isCurrent() && capture.authorize('file.read') ? await sharedTaskWorkdir(capture) : null;
const verified = new Set<string>();
if (own && capture.isCurrent()) {
- for (const topic of watched as string[]) {
+ for (const topic of watched) {
if (normalizeWorkingDirForStorage(parseFsWatchTopic(topic)) === own.workingDir) verified.add(topic);
}
}
- return { topics: topics.filter((topic) => !watched.includes(topic) || verified.has(topic as string)), verified };
+ return { topics: topics.filter((topic) => typeof topic !== 'string' || !watched.has(topic) || verified.has(topic)), verified };
}
diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.ts
index ca4d2294e0..ebf66657ba 100644
--- a/apps/desktop/src/main/device-link/subscriptions.ts
+++ b/apps/desktop/src/main/device-link/subscriptions.ts
@@ -201,6 +201,14 @@ export function controllerHasTopic(deviceId: string, topic: string): boolean {
return registry.get(deviceId)?.topics.has(topic as StoredTopic) === true;
}
+/** 该控制端当前持有及断线恢复记住的全部 topic(去重)。 */
+export function getControllerTopics(deviceId: string): string[] {
+ return [...new Set([
+ ...(registry.get(deviceId)?.topics ?? []),
+ ...(rememberedTopicsByController.get(deviceId) ?? []),
+ ])];
+}
+
/** 取消订阅指定 topics;该控制端 topic 清空后整条移除。空 topics 为 no-op。 */
export function unsubscribe(deviceId: string, topics: readonly string[]): void {
for (const topic of topics) {
diff --git a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
index 60393b8703..89409211f3 100644
--- a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
@@ -264,7 +264,11 @@ describe('file-browser device-op', () => {
beforeEach(() => {
current = true;
- sharedWorkdirMock.mockResolvedValue({ remoteHostId: null });
+ // Mirrors the real binding: membership is rechecked on every call.
+ sharedWorkdirMock.mockImplementation(async () => {
+ if (!current) throw new Error('[PERMISSION_DENIED] Shared task access changed');
+ return { remoteHostId: null };
+ });
});
it('reads and writes the task workdir like the owner after binding it', async () => {
@@ -317,6 +321,34 @@ describe('file-browser device-op', () => {
};
expect(read.data.content).toBe('export const a = 1;\n');
});
+
+ it('rebinds the task workdir and endpoint after the endpoint checks, before touching files', async () => {
+ // The owner moves the task while this write is in flight.
+ guardMock.mockImplementationOnce(async () => {
+ sharedWorkdirMock.mockRejectedValueOnce(new Error('[PERMISSION_DENIED] moved'));
+ return { allowed: true, source: 'filesystem' };
+ });
+ await expect(
+ asGuest(() =>
+ handleRemoteOp({ op: 'writeFile', workdir, relPath: 'src/a.ts', content: 'moved\n' }),
+ ),
+ ).rejects.toThrow('PERMISSION_DENIED');
+ expect(sharedWorkdirMock).toHaveBeenCalledTimes(2);
+ // The task switches to an SSH endpoint for the same path mid-request.
+ guardMock.mockImplementationOnce(async () => {
+ sharedWorkdirMock.mockResolvedValueOnce({ remoteHostId: 'ssh-1' });
+ return { allowed: true, source: 'filesystem' };
+ });
+ await expect(
+ asGuest(() =>
+ handleRemoteOp({ op: 'writeFile', workdir, relPath: 'src/a.ts', content: 'moved\n' }),
+ ),
+ ).rejects.toThrow('PERMISSION_DENIED');
+ const read = (await handleRemoteOp({ op: 'readFile', workdir, relPath: 'src/a.ts' })) as {
+ data: { content: string };
+ };
+ expect(read.data.content).toBe('export const a = 1;\n');
+ });
});
it('exportFile two-phase: start/status lifecycle and traversal rejection', async () => {
diff --git a/apps/desktop/src/main/file-browser/device-op.ts b/apps/desktop/src/main/file-browser/device-op.ts
index 53dd700dc7..cc83d04a07 100644
--- a/apps/desktop/src/main/file-browser/device-op.ts
+++ b/apps/desktop/src/main/file-browser/device-op.ts
@@ -474,17 +474,16 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
}
}
- if (sharedTaskEndpoint) {
+ if (sharedTask && sharedTaskEndpoint) {
+ // 上面的 guard / 端点判定 / 解压都是 await 边界:房主可能已撤权或移动任务目录。
+ // 落盘或读出前按最新任务记录重新绑定目录与端点(内含成员资格复核)。
+ const current = await assertSharedTaskWorkdir(sharedTask, args.workdir, sharedTaskOperation!);
// 访客只能落到任务自己的执行端点(本地或任务所属 SSH 主机),不按路径反查到别的会话主机。
- const expected = sharedTaskEndpoint.remoteHostId;
- const sameEndpoint = expected
- ? exec.kind === 'ssh' && exec.hostId === expected
- : exec.kind === 'local';
+ const expected = current.remoteHostId;
+ const sameEndpoint =
+ expected === sharedTaskEndpoint.remoteHostId &&
+ (expected ? exec.kind === 'ssh' && exec.hostId === expected : exec.kind === 'local');
if (!sameEndpoint) throw new Error('[PERMISSION_DENIED] Shared task working directory endpoint mismatch');
- // 上面的 guard / 端点判定 / 解压都是 await 边界:撤权后不得再落盘或读出。
- if (!sharedTask?.isCurrent() || !sharedTask.authorize(sharedTaskOperation!)) {
- throw new Error('[PERMISSION_DENIED] Shared task access changed');
- }
}
// —— SSH 二跳:直接透传给本机的 SSH file-service 路由 ——