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): 访客可在文件浏览器读写本任务工作目录

david097220711e3b
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
index 72754970e3..69ab93924a 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
@@ -194,6 +194,37 @@ describe('sharedTask dispatch scope', () => {
setSharedTaskQueueReader(() => undefined);
expect(() => assertSharedTaskInvoke(capture(), payload, undefined, 'result')).not.toThrow();
});
+ it('lets guests read and write task files like the owner, but never run export jobs', () => {
+ const channel = 'file-browser:remote-op';
+ const call = (request: unknown, peer = capture(), extra: unknown[] = []) =>
+ () => assertSharedTaskInvoke(peer, { channel, args: [request, ...extra] });
+ for (const op of ['caps', 'listDir', 'listAllFiles', 'readFile', 'stat', 'searchCollect', 'thumbnail', 'fileUrl',
+ 'writeFile', 'createFile', 'createFolder', 'renameEntry', 'deleteEntry']) {
+ expect(call({ op, workdir: '/host/task' })).not.toThrow();
+ }
+ for (const op of ['exportFileStart', 'exportFileStatus', 'exportDirStart', 'exportDirStatus', 'unknown']) {
+ expect(call({ op, workdir: '/host/task' })).toThrow('PERMISSION_DENIED');
+ }
+ expect(call({ op: 'listDir' })).toThrow('PERMISSION_DENIED');
+ expect(call({ op: 'listDir', workdir: '/host/task' }, capture(), ['extra'])).toThrow('PERMISSION_DENIED');
+ const readOnly: SharedTaskPeerCapture = { ...capture(), authorize: (operation) => operation !== 'file.write' };
+ expect(call({ op: 'readFile', workdir: '/host/task' }, readOnly)).not.toThrow();
+ expect(call({ op: 'writeFile', workdir: '/host/task' }, readOnly)).toThrow('PERMISSION_DENIED');
+ expect(call({ op: 'listDir', workdir: '/host/task' }, { ...capture(), isCurrent: () => false })).toThrow();
+ });
+ it('subscribes a workdir watch only after async admission, including merged reconnect frames', () => {
+ const subscribe = (topics: string[], verified: string[] = [], peer = capture()) =>
+ () => assertSharedTaskInvoke(peer, { channel: 'device-link:subscribe', args: [{ topics }] }, undefined, 'invoke', new Set(verified));
+ expect(subscribe(['fs-watch:/host/task'])).toThrow('PERMISSION_DENIED');
+ expect(subscribe(['fs-watch:/host/task'], ['fs-watch:/host/task'])).not.toThrow();
+ expect(subscribe(['session:task', 'fs-watch:/host/task'], ['fs-watch:/host/task'])).not.toThrow();
+ expect(subscribe(['session:other', 'fs-watch:/host/task'], ['fs-watch:/host/task'])).toThrow('PERMISSION_DENIED');
+ expect(subscribe(['fs-watch:/host/task'], ['fs-watch:/host/task'], { ...capture(), authorize: (operation) => operation !== 'file.read' }))
+ .toThrow('PERMISSION_DENIED');
+ // Results and unsubscribes carry no file data, so they only re-check access.
+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'device-link:subscribe', args: [{ topics: ['fs-watch:/host/task'] }] }, undefined, 'result')).not.toThrow();
+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'device-link:unsubscribe', args: [{ topics: ['fs-watch:/host/task'] }] })).not.toThrow();
+ });
it('rejects expired captured authorization and unbound sharedTask pushes without changing same-account traffic', () => {
expect(() => assertSharedTaskInvoke({ ...capture(), isCurrent: () => false }, { channel: 'local-db:messages:list', args: ['task'] })).toThrow();
expect(captureSharedTaskPush(sharedTaskGuestPeer('m', 'g', 'd'), 'maker:event', { sessionId: 'task' })).toBeNull();
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
new file mode 100644
index 0000000000..5968e304dc
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { SharedTaskPeerCapture } from '../sharedTaskDispatch.js';
+
+const snapshot = vi.hoisted(() => vi.fn());
+vi.mock('../../localDb/ipc/sessions.js', () => ({ getSessionFsSnapshot: snapshot }));
+
+import { admitSharedTaskFsWatchTopics, assertSharedTaskWorkdir } from '../sharedTaskFileAccess.js';
+
+function capture(overrides: Partial<SharedTaskPeerCapture> = {}): SharedTaskPeerCapture {
+ return {
+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'member', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => true,
+ authorize: () => true,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ snapshot.mockReset();
+ snapshot.mockResolvedValue({ workingDir: '/host/task', remoteHostId: null, permissionMode: 'default', planModeEnabled: false });
+});
+
+describe('shared task workdir binding', () => {
+ it('accepts only the host-recorded task workdir and returns its endpoint', async () => {
+ await expect(assertSharedTaskWorkdir(capture(), '/host/task', 'file.write')).resolves.toEqual({ remoteHostId: null });
+ await expect(assertSharedTaskWorkdir(capture(), '/host/task/', 'file.read')).resolves.toEqual({ remoteHostId: null });
+ await expect(assertSharedTaskWorkdir(capture(), '/host/other', 'file.read')).rejects.toThrow('PERMISSION_DENIED');
+ await expect(assertSharedTaskWorkdir(capture(), '/host', 'file.read')).rejects.toThrow('PERMISSION_DENIED');
+ expect(snapshot).toHaveBeenCalledWith('task');
+ snapshot.mockResolvedValue({ workingDir: '/srv/task', remoteHostId: 'ssh-1', permissionMode: 'default', planModeEnabled: false });
+ await expect(assertSharedTaskWorkdir(capture(), '/srv/task', 'file.read')).resolves.toEqual({ remoteHostId: 'ssh-1' });
+ });
+
+ it('fails closed without a workdir, without the operation, or when revoked during the lookup', async () => {
+ snapshot.mockResolvedValueOnce(null);
+ await expect(assertSharedTaskWorkdir(capture(), '/host/task', 'file.read')).rejects.toThrow('PERMISSION_DENIED');
+ await expect(assertSharedTaskWorkdir(capture({ authorize: (op) => op !== 'file.write' }), '/host/task', 'file.write'))
+ .rejects.toThrow('PERMISSION_DENIED');
+ let current = true;
+ snapshot.mockImplementationOnce(async () => {
+ current = false;
+ return { workingDir: '/host/task', remoteHostId: null };
+ });
+ await expect(assertSharedTaskWorkdir(capture({ isCurrent: () => current }), '/host/task', 'file.read'))
+ .rejects.toThrow('PERMISSION_DENIED');
+ });
+
+ it('admits only the task workdir watch and keeps other topics for the synchronous gate', async () => {
+ const admitted = await admitSharedTaskFsWatchTopics(capture(), ['session:task', 'fs-watch:/host/task', 'fs-watch:/host/other']);
+ expect(admitted.topics).toEqual(['session:task', 'fs-watch:/host/task']);
+ expect([...admitted.verified]).toEqual(['fs-watch:/host/task']);
+ const denied = await admitSharedTaskFsWatchTopics(capture({ authorize: () => false }), ['session:task', 'fs-watch:/host/task']);
+ expect(denied).toEqual({ topics: ['session:task'], verified: new Set() });
+ });
+});
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 9aac65e527..1cd5aa2b04 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
@@ -41,7 +41,7 @@ beforeEach(() => {
__testing.reset();
grants.clear();
grants.set(guestA, 'task-a'); grants.set(guestB, 'task-b');
- setSharedTaskDispatchHost({ capturePeer(source: string) {
+ setSharedTaskDispatchHost({ peerStatus: (source: string) => grants.has(source) ? 'available' : 'revoked', capturePeer(source: string) {
const sessionId = grants.get(source);
if (!sessionId) return null;
const current = () => grants.get(source) === sessionId;
@@ -309,3 +309,27 @@ describe('shared task guests never see the owner private message sources', () =>
expect(results.get('r3').result.pendingQueue[0].origin).toEqual({ kind: 'session', senderSessionId: '', displayText: 'please review' });
});
});
+
+describe('shared task workdir watch', () => {
+ it('delivers file tree events only to the guest whose admitted watch matches, and stops after revoke', async () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ const watch = 'fs-watch:/host/task-a';
+ // Without admission the watch is refused; the task stream in the same frame survives only if admitted.
+ expect(__testing.handleSubscriptionFrame(guestA, { channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: [watch] }] }).ok).toBe(false);
+ expect(__testing.handleSubscriptionFrame(guestA, {
+ channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: ['session:task-a', watch] }],
+ }, new Set([watch])).ok).toBe(true);
+ subscriptions.subscribe(guestB, ['session:task-b']);
+ subscriptions.subscribe('own-task', [watch]);
+ const event = { workdir: '/host/task-a', type: 'add', relPath: 'a.ts' };
+ __testing.forwardPush('maker:file-browser:event', event);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(transport.sendPush.mock.calls.map((call) => call[0]).sort()).toEqual([guestA, 'own-task'].sort());
+ transport.sendPush.mockClear();
+ grants.delete(guestA);
+ __testing.forwardPush('maker:file-browser:event', event);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(transport.sendPush.mock.calls.map((call) => call[0])).toEqual(['own-task']);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 4cca06fccd..e53f509f5a 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -122,6 +122,7 @@ import { captureSharedTaskPeer, captureSharedTaskPush, assertSharedTaskInvoke, s
import { runAsBackgroundDbRpc } from '../localDb/client/rpcAdmission.js';
import { fetchLocalMediaToOss } from './mediaFetch';
import { refreshSharedTaskPeer } from './sharedTaskDispatch.js';
+import { admitSharedTaskFsWatchTopics } from './sharedTaskFileAccess.js';
import { transcribeRemoteVoiceInput } from './voiceTranscribe';
import { readTelegramRemoteStatus, setTelegramRemoteOnline } from './telegramRemoteControl';
import { adviseAndRecordVoiceInputDictionaryLearning } from '../voice-input/index.js';
@@ -2820,7 +2821,12 @@ async function handleInvoke(
return;
}
if (payload && (payload.channel === DL_SUBSCRIBE_CHANNEL || payload.channel === DL_UNSUBSCRIBE_CHANNEL)) {
- const result = handleSubscriptionFrame(src, payload);
+ // Only a shared-task workdir watch awaits; every other frame stays synchronous.
+ const admitting = admitSharedTaskSubscription(src, payload);
+ const admission = admitting ? await admitting : null;
+ // The workdir lookup is an await boundary; a frame from a replaced link must not subscribe.
+ if (admission && (remoteInvokeLinkEpoch.get(src) ?? 0) !== invokeLinkEpoch) return;
+ const result = handleSubscriptionFrame(src, admission?.payload ?? payload, admission?.verifiedFsWatchTopics);
if (!await sendAuthorizedInvokeResultSafe(
client,
src,
@@ -3874,14 +3880,50 @@ function isRemoteSubscriptionTopic(value: unknown): value is Topic {
return parseFsWatchTopic(value) !== null;
}
-function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeResultPayload {
+/**
+ * Shared-task guests may watch only their task workdir. That binding needs the
+ * host DB, so it runs before the synchronous frame handler. Returns null when
+ * no admission is needed, so ordinary frames never cross an await.
+ */
+function admitSharedTaskSubscription(
+ src: string,
+ payload: InvokePayload,
+): Promise<{ payload: InvokePayload; verifiedFsWatchTopics: ReadonlySet<string> }> | null {
+ const rawArg = (payload.args ?? [])[0];
+ const arg = rawArg && typeof rawArg === 'object' && !Array.isArray(rawArg)
+ ? rawArg as Record<string, unknown> : null;
+ const topics = arg?.topics;
+ if (!isSharedTaskPeer(src) || payload.channel !== DL_SUBSCRIBE_CHANNEL || !Array.isArray(topics)
+ || !topics.some((topic) => typeof topic === 'string' && parseFsWatchTopic(topic) !== null)) {
+ return null;
+ }
+ const sharedTask = captureSharedTaskPeer(src);
+ // The synchronous gate reports the access failure.
+ if (!sharedTask) return null;
+ return admitSharedTaskFsWatchTopics(sharedTask, topics).then(
+ (admitted) => ({
+ payload: { ...payload, args: [{ ...arg, topics: admitted.topics }, ...(payload.args ?? []).slice(1)] },
+ verifiedFsWatchTopics: admitted.verified,
+ }),
+ (error: unknown) => {
+ log.warn(`shared task fs-watch admission failed for ${shortId(src)}: ${String(error)}`);
+ return { payload, verifiedFsWatchTopics: new Set<string>() };
+ },
+ );
+}
+
+function handleSubscriptionFrame(
+ src: string,
+ payload: InvokePayload,
+ verifiedFsWatchTopics: ReadonlySet<string> = new Set(),
+): InvokeResultPayload {
// Provider-share guests never subscribe: the remote agent is poll-only.
if (isProviderSharePeer(src)) return PROVIDER_SHARE_ACCESS_FAILURE;
if (isSharedTaskPeer(src)) {
const sharedTask = captureSharedTaskPeer(src);
try {
if (!sharedTask) throw new Error('SharedTask unavailable');
- assertSharedTaskInvoke(sharedTask, payload);
+ assertSharedTaskInvoke(sharedTask, payload, undefined, 'invoke', verifiedFsWatchTopics);
} catch {
return sharedTaskAccessFailure(src, sharedTask);
}
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index 7e2ad3e1db..989adf7cdd 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -1,5 +1,6 @@
-import { isSharedTaskPeer, parseSharedTaskPeer, isSharedTaskAttachment, type InvokePayload, type InvokeResultPayload, type SharedTaskQueueItem } from '@cindy/device-link';
+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';
export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;
export interface SharedTaskInteractionCapture {
@@ -73,6 +74,17 @@ const sessionReads = new Set([
const inputEdits = new Set(['maker:input:update-text', 'maker:input:update-content', 'maker:input:set-edit-lock']);
// Model, Agent and reasoning changes belong to the owner, including result replay.
const interactionDecisionKinds = new Set(['permission', 'ask_user_question', 'plan_review']);
+// Guests browse and edit the task workdir like the owner. Export jobs stay
+// same-account only: they stage bytes under the owner's transfer paths.
+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 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;
+}
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
@@ -182,10 +194,14 @@ export function assertSharedTaskReferences(value: unknown, sessionId: string, de
}
}
-/** Validate the actual channel shape; unknown channels fail closed. */
+/**
+ * Validate the actual channel shape; unknown channels fail closed.
+ * `verifiedFsWatchTopics` comes from the async workdir admission in
+ * sharedTaskFileAccess; a new fs-watch subscription is rejected without it.
+ */
export function assertSharedTaskInvoke(
capture: SharedTaskPeerCapture, payload: InvokePayload, queueItem?: SharedTaskQueueItem,
- phase: 'invoke' | 'result' = 'invoke',
+ phase: 'invoke' | 'result' = 'invoke', verifiedFsWatchTopics: ReadonlySet<string> = new Set(),
): void {
if (!capture.isCurrent()) deny();
const { channel } = payload;
@@ -222,8 +238,25 @@ export function assertSharedTaskInvoke(
}
if (channel === 'device-link:subscribe' || channel === 'device-link:unsubscribe') {
const topics = record(args[0])?.topics;
- if (!Array.isArray(topics) || topics.length > 1 || topics.some((topic) => topic !== `session:${sessionId}`)) deny();
- if (!capture.authorize('events.subscribe')) deny();
+ if (!Array.isArray(topics) || topics.length > MAX_SHARED_TASK_TOPICS) deny();
+ if (topics.length === 0 && !capture.authorize('events.subscribe')) deny();
+ for (const topic of topics) {
+ if (topic === `session:${sessionId}`) {
+ if (!capture.authorize('events.subscribe')) deny();
+ continue;
+ }
+ if (typeof topic !== 'string' || parseFsWatchTopic(topic) === null || !capture.authorize('file.read')) deny();
+ // Results and unsubscribes carry no file data; only new watches need the workdir binding.
+ if (phase === 'invoke' && channel === 'device-link:subscribe' && !verifiedFsWatchTopics.has(topic)) deny();
+ }
+ return;
+ }
+ if (channel === FILE_BROWSER_REMOTE_OP_CHANNEL) {
+ // Workdir ownership needs the host DB; device-op binds it before any file access.
+ const request = record(args[0]);
+ const operation = sharedTaskFileOperation(request?.op);
+ if (args.length !== 1 || !request || !operation || typeof request.workdir !== 'string' ||
+ !request.workdir || !capture.authorize(operation)) deny();
return;
}
if (channel === 'maker:resolve-interaction') {
@@ -256,6 +289,14 @@ export function captureSharedTaskPush(source: string, channel: string, payload:
if (!capture || !capture.authorize('events.subscribe')) return null;
const sessionId = capture.author.sessionId;
const row = record(payload);
+ if (channel === FILE_BROWSER_EVENT_CHANNEL) {
+ // Workdir-scoped and carries no sessionId; the subscription itself was
+ // admitted only for this task's workdir.
+ const workdir = row?.workdir;
+ if (typeof workdir !== 'string' || !capture.authorize('file.read') ||
+ !subscriptions.controllerHasTopic(source, fsWatchTopic(workdir))) return null;
+ return () => capture.isCurrent() && capture.authorize('file.read');
+ }
if (row?.sessionId !== sessionId) return null;
// Never forward a device/account projection just because it has a sessionId.
if (!(channel.startsWith('maker:') || channel.startsWith('local-db:messages:') ||
diff --git a/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts b/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts
new file mode 100644
index 0000000000..9e70a3300f
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts
@@ -0,0 +1,48 @@
+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';
+
+function deny(): never { throw new Error('[PERMISSION_DENIED] Working directory does not belong to this shared task'); }
+
+/** The task workdir as recorded on this host; guest-supplied paths are only compared to it. */
+async function sharedTaskWorkdir(capture: SharedTaskPeerCapture): Promise<{ workingDir: string; remoteHostId: string | null } | null> {
+ const snapshot = await getSessionFsSnapshot(capture.author.sessionId);
+ const workingDir = normalizeWorkingDirForStorage(snapshot?.workingDir);
+ return snapshot && workingDir ? { workingDir, remoteHostId: snapshot.remoteHostId } : null;
+}
+
+/**
+ * Run before any file access for a shared-task guest: the requested workdir
+ * must be this task's own workdir, and membership is rechecked after the DB read.
+ * Returns the task's SSH host so the caller can refuse a different endpoint.
+ */
+export async function assertSharedTaskWorkdir(
+ capture: SharedTaskPeerCapture, workdir: string, operation: 'file.read' | 'file.write',
+): Promise<{ remoteHostId: string | null }> {
+ if (!capture.isCurrent() || !capture.authorize(operation)) deny();
+ const own = await sharedTaskWorkdir(capture);
+ if (!own || normalizeWorkingDirForStorage(workdir) !== own.workingDir ||
+ !capture.isCurrent() || !capture.authorize(operation)) deny();
+ return { remoteHostId: own.remoteHostId };
+}
+
+/**
+ * Admit fs-watch topics only for this task's workdir. Mismatches are dropped
+ * rather than failing the frame: reconnect replay merges them with the task
+ * stream, which must keep working if the watch is no longer valid.
+ */
+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() };
+ 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[]) {
+ if (normalizeWorkingDirForStorage(parseFsWatchTopic(topic)) === own.workingDir) verified.add(topic);
+ }
+ }
+ return { topics: topics.filter((topic) => !watched.includes(topic) || verified.has(topic as string)), verified };
+}
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 5ebf1089ac..60393b8703 100644
--- a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
@@ -94,6 +94,14 @@ vi.mock('../../localDb/client/current.js', () => ({
},
}),
}));
+const sharedWorkdirMock = vi.hoisted(() =>
+ vi.fn<(...args: unknown[]) => Promise<{ remoteHostId: string | null }>>(async () => ({
+ remoteHostId: null,
+ })),
+);
+vi.mock('../../device-link/sharedTaskFileAccess.js', () => ({
+ assertSharedTaskWorkdir: sharedWorkdirMock,
+}));
const startDirExportMock = vi.hoisted(() => vi.fn<(...args: unknown[]) => string>(() => 'dir_1'));
vi.mock('../dir-export.js', () => ({
createDirExportDeps: () => ({}),
@@ -241,6 +249,76 @@ describe('file-browser device-op', () => {
});
});
+ describe('shared task guest', () => {
+ let current = true;
+ const sharedTask = {
+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'm', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => current,
+ authorize: () => current,
+ };
+ const asGuest = <T>(fn: () => Promise<T>) =>
+ runDeviceLinkInvokeContext(
+ { controllerDeviceId: 'guest', channel: 'file-browser:remote-op', sharedTask },
+ fn,
+ );
+
+ beforeEach(() => {
+ current = true;
+ sharedWorkdirMock.mockResolvedValue({ remoteHostId: null });
+ });
+
+ it('reads and writes the task workdir like the owner after binding it', async () => {
+ const entries = (await asGuest(() => handleRemoteOp({ op: 'listDir', workdir }))) as Array<{
+ name: string;
+ }>;
+ expect(entries.map((e) => e.name)).toContain('src');
+ expect(sharedWorkdirMock).toHaveBeenCalledWith(sharedTask, workdir, 'file.read');
+ expect(
+ await asGuest(() =>
+ handleRemoteOp({ op: 'writeFile', workdir, relPath: 'src/a.ts', content: 'guest\n' }),
+ ),
+ ).toMatchObject({ ok: true });
+ expect(sharedWorkdirMock).toHaveBeenLastCalledWith(sharedTask, workdir, 'file.write');
+ const read = (await handleRemoteOp({ op: 'readFile', workdir, relPath: 'src/a.ts' })) as {
+ data: { content: string };
+ };
+ expect(read.data.content).toBe('guest\n');
+ });
+
+ it('refuses export jobs, foreign workdirs and a different execution endpoint', async () => {
+ expect(
+ await asGuest(() => handleRemoteOp({ op: 'exportFileStart', workdir, relPath: 'src/a.ts' })),
+ ).toEqual({ ok: false, message: 'REMOTE_UNSUPPORTED' });
+ expect(uploadMock).not.toHaveBeenCalled();
+ sharedWorkdirMock.mockRejectedValueOnce(new Error('[PERMISSION_DENIED] not this task'));
+ await expect(asGuest(() => handleRemoteOp({ op: 'listDir', workdir }))).rejects.toThrow(
+ 'PERMISSION_DENIED',
+ );
+ expect(guardMock).not.toHaveBeenCalled();
+ // The task lives on an SSH host, but this path resolves locally: never guess.
+ sharedWorkdirMock.mockResolvedValueOnce({ remoteHostId: 'ssh-1' });
+ await expect(asGuest(() => handleRemoteOp({ op: 'listDir', workdir }))).rejects.toThrow(
+ 'PERMISSION_DENIED',
+ );
+ });
+
+ it('does not write when membership ends during the endpoint checks', async () => {
+ guardMock.mockImplementationOnce(async () => {
+ current = false;
+ return { allowed: true, source: 'filesystem' };
+ });
+ await expect(
+ asGuest(() =>
+ handleRemoteOp({ op: 'writeFile', workdir, relPath: 'src/a.ts', content: 'late\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 () => {
await fsWriteFile(path.join(workdir, 'docs', 'x.md'), 'big\n', 'utf8').catch(async () => {
await mkdir(path.join(workdir, 'docs'), { recursive: true });
diff --git a/apps/desktop/src/main/file-browser/device-op.ts b/apps/desktop/src/main/file-browser/device-op.ts
index f95dd39d00..53dd700dc7 100644
--- a/apps/desktop/src/main/file-browser/device-op.ts
+++ b/apps/desktop/src/main/file-browser/device-op.ts
@@ -73,6 +73,8 @@ import { throwIpcError } from '../utils/ipcValidate.js';
import { uploadLocalFile } from '../device-link/mediaTransfer.js';
import { pushToTopicSubscribers } from '../device-link/dispatch.js';
import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
+import { sharedTaskFileOperation } from '../device-link/sharedTaskDispatch.js';
+import { assertSharedTaskWorkdir } from '../device-link/sharedTaskFileAccess.js';
import { getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap.js';
import * as subscriptions from '../device-link/subscriptions.js';
import { getRipgrepBinaryPath } from '../maker-host/runtime-configs.js';
@@ -402,6 +404,15 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
if (!args || typeof args.op !== 'string' || typeof args.workdir !== 'string' || !args.workdir) {
return bad('invalid remote-op args');
}
+ // 共享任务访客:只放行本任务工作目录内的读写(与房主一致);导出类长任务仍只给
+ // 同账号控制端。workdir 必须与本机记录的任务目录一致,先于任何 fs 访问校验。
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ const sharedTaskOperation = sharedTask ? sharedTaskFileOperation(args.op) : null;
+ if (sharedTask && !sharedTaskOperation) return bad('REMOTE_UNSUPPORTED');
+ const sharedTaskEndpoint =
+ sharedTask && sharedTaskOperation && args.op !== 'caps'
+ ? await assertSharedTaskWorkdir(sharedTask, args.workdir, sharedTaskOperation)
+ : null;
// 能力探测:与 workdir 无关、零 fs 访问,放在 guard 之前。老被控端没有
// 这个分支,会走到 default 返回 `unknown op: caps`——控制端把它当确定性
// 的"不支持压缩"信号(见 fileBrowserTransport 的 caps 缓存)。
@@ -463,6 +474,19 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
}
}
+ if (sharedTaskEndpoint) {
+ // 访客只能落到任务自己的执行端点(本地或任务所属 SSH 主机),不按路径反查到别的会话主机。
+ const expected = sharedTaskEndpoint.remoteHostId;
+ const sameEndpoint = 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 路由 ——
if (exec.kind === 'ssh') {
const mgr = getRemoteFileBrowser();
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index cb20575668..13451803b2 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -39,6 +39,7 @@
- Agent 工具、shell、已有插件/MCP 沿用任务现有权限,Full Access 语义不变;任务内 Agent 的 permission、ask_user_question、plan_review 交互由房主和协作者都可决策,其他房主管理确认仍由房主处理。不添加访客专属沙箱、per-turn 权限或工具审批。邀请意味着房主信任访客使用该任务的 Agent 能力。
- 房主保留共享管理、归档/删除/导出/分支、权限模式、工作目录、插件/MCP 配置和后台/定时任务管理权限。
- 访客通过客户端接口只能直接访问共享任务及其资源,不能调用全局凭证、其他任务或任意主机文件接口。Agent 原生工具不承诺工作目录硬隔离。
+- 文件浏览器(2026-10-10 用户裁决):访客可在文件浏览器中浏览和编辑本任务工作目录,读写权限与房主一致:列目录、读取、搜索、缩略图、保存、新建、重命名、删除,以及文件变化监听。主机只认本机记录的任务工作目录与执行端点(本地或任务所属 SSH 主机),访客传入的路径只用于比对;读写前复核成员资格。文件导出/文件夹下载这类导出任务仍只限同账号(它们走房主的同账号中转路径),工作目录本身的管理(更换目录)仍归房主。实现见 `sharedTaskDispatch.ts`(通道与操作)、`sharedTaskFileAccess.ts`(目录绑定)与 `file-browser/device-op.ts`。
- 消息按主机现有输入队列顺序处理,保留 clientId 幂等。访客仅编辑/撤回自己未处理消息,房主可处理全部未处理消息;直接更新内容,不显示“已编辑”。
- 发言者身份来自经过验证的账号和成员关系,不能信任消息正文或客户端自报的身份。
diff --git a/packages/device-link/src/__tests__/sharedTask.test.ts b/packages/device-link/src/__tests__/sharedTask.test.ts
index a7a71e0c29..9da3932b30 100644
--- a/packages/device-link/src/__tests__/sharedTask.test.ts
+++ b/packages/device-link/src/__tests__/sharedTask.test.ts
@@ -48,7 +48,7 @@ describe('sharedTask authorization', () => {
}
expect(isSharedTaskAttachment('file:///private/file.png', 'shared')).toBe(false);
});
- it.each(['history.read', 'attachment.read', 'attachment.upload', 'input.send', 'agent.stop', 'approval.resolve'])(
+ it.each(['history.read', 'attachment.read', 'attachment.upload', 'file.read', 'file.write', 'input.send', 'agent.stop', 'approval.resolve'])(
'lets an approved guest %s without treating them as the owner', (operation) => {
expect(authorize(parse(snapshot()), guest, 'session-1', operation)).toMatchObject({ allowed: true, role: 'guest', memberId: 'member-a' });
},
diff --git a/packages/device-link/src/sharedTask.ts b/packages/device-link/src/sharedTask.ts
index 2a45d339bd..542a913e2d 100644
--- a/packages/device-link/src/sharedTask.ts
+++ b/packages/device-link/src/sharedTask.ts
@@ -51,7 +51,7 @@ export interface SharedTaskSnapshot extends SharedTaskIdentity {
export type SharedTaskOperation =
| 'history.read' | 'events.subscribe' | 'attachment.read' | 'attachment.upload'
- | 'file.read' | 'input.send' | 'input.edit' | 'input.withdraw' | 'agent.stop'
+ | 'file.read' | 'file.write' | 'input.send' | 'input.edit' | 'input.withdraw' | 'agent.stop'
| 'agent.configure' | 'approval.resolve' | 'permission.configure'
| 'workdir.configure' | 'plugins.configure' | 'history.delete'
| 'session.archive' | 'session.export' | 'session.fork'
@@ -81,7 +81,8 @@ export type SharedTaskDecision =
const sharedOperations: ReadonlySet<string> = new Set<SharedTaskOperation>([
'history.read', 'events.subscribe', 'attachment.read', 'attachment.upload',
- 'file.read', 'input.send', 'agent.stop', 'approval.resolve',
+ // Task workdir files follow the owner's read/write access (2026-10-10 product decision).
+ 'file.read', 'file.write', 'input.send', 'agent.stop', 'approval.resolve',
]);
const ownerOperations: ReadonlySet<string> = new Set<SharedTaskOperation>([
'agent.configure', 'permission.configure', 'workdir.configure', 'plugins.configure',