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): 准入期间目录移动不再装上旧监听,SSH 搜索也走发送前门

david9a50dfb201ef
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 aa79af02f8..c5812f82f8 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskFileAccess.test.ts
@@ -5,6 +5,7 @@ const snapshot = vi.hoisted(() => vi.fn());
vi.mock('../../localDb/ipc/sessions.js', () => ({ getSessionFsSnapshot: snapshot }));
import { admitSharedTaskFsWatchTopics, assertSharedTaskWorkdir } from '../sharedTaskFileAccess.js';
+import { releaseSharedTaskWatchesOnWorkdirChange } from '../sharedTaskDispatch.js';
function capture(overrides: Partial<SharedTaskPeerCapture> = {}): SharedTaskPeerCapture {
return {
@@ -50,7 +51,24 @@ describe('shared task workdir binding', () => {
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() });
+ expect(denied).toMatchObject({ topics: ['session:task'], verified: new Set() });
+ });
+
+ it('marks an admission stale when the task workdir moves during the lookup', async () => {
+ const steady = await admitSharedTaskFsWatchTopics(capture(), ['fs-watch:/host/task']);
+ expect(steady.isFresh()).toBe(true);
+ snapshot.mockImplementationOnce(async () => {
+ // The owner moves the task while the guest's admission reads the DB.
+ releaseSharedTaskWatchesOnWorkdirChange('local-db:sessions:patched', { sessionId: 'task', patch: { workingDir: '/host/moved' } });
+ return { workingDir: '/host/task', remoteHostId: null };
+ });
+ const raced = await admitSharedTaskFsWatchTopics(capture(), ['fs-watch:/host/task']);
+ expect([...raced.verified]).toEqual(['fs-watch:/host/task']);
+ expect(raced.isFresh()).toBe(false);
+ // An unrelated task's move does not invalidate this one.
+ const other = await admitSharedTaskFsWatchTopics(capture(), ['fs-watch:/host/task']);
+ releaseSharedTaskWatchesOnWorkdirChange('local-db:sessions:patched', { sessionId: 'other', patch: { workingDir: '/x' } });
+ expect(other.isFresh()).toBe(true);
});
it('never looks up an oversized topic frame', async () => {
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index f74c7a6f4b..a2d1c80a62 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -2824,9 +2824,11 @@ async function handleInvoke(
if (payload && (payload.channel === DL_SUBSCRIBE_CHANNEL || payload.channel === DL_UNSUBSCRIBE_CHANNEL)) {
// Only a shared-task workdir watch awaits; every other frame stays synchronous.
const admitting = admitSharedTaskSubscription(src, payload);
- const admission = admitting ? await admitting : null;
+ const settle = 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;
+ if (settle && (remoteInvokeLinkEpoch.get(src) ?? 0) !== invokeLinkEpoch) return;
+ // Settled synchronously with the install below: no workdir move can slip between them.
+ const admission = settle?.();
const result = handleSubscriptionFrame(src, admission?.payload ?? payload, admission?.verifiedFsWatchTopics);
if (!await sendAuthorizedInvokeResultSafe(
client,
@@ -3884,12 +3886,14 @@ function isRemoteSubscriptionTopic(value: unknown): value is Topic {
/**
* 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.
+ * no admission is needed, so ordinary frames never cross an await. The result
+ * is settled synchronously at install time: if the task workdir moved during
+ * the lookup, the watch topics are dropped and the rest of the frame proceeds.
*/
function admitSharedTaskSubscription(
src: string,
payload: InvokePayload,
-): Promise<{ payload: InvokePayload; verifiedFsWatchTopics: ReadonlySet<string> }> | null {
+): 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;
@@ -3903,14 +3907,19 @@ function admitSharedTaskSubscription(
const sharedTask = captureSharedTaskPeer(src);
// The synchronous gate reports the access failure.
if (!sharedTask) return null;
+ const withTopics = (next: unknown[]): InvokePayload =>
+ ({ ...payload, args: [{ ...arg, topics: next }, ...(payload.args ?? []).slice(1)] });
return admitSharedTaskFsWatchTopics(sharedTask, topics).then(
- (admitted) => ({
- payload: { ...payload, args: [{ ...arg, topics: admitted.topics }, ...(payload.args ?? []).slice(1)] },
- verifiedFsWatchTopics: admitted.verified,
- }),
+ (admitted) => () => admitted.isFresh()
+ ? { payload: withTopics(admitted.topics), verifiedFsWatchTopics: admitted.verified }
+ : {
+ payload: withTopics(admitted.topics.filter((topic) =>
+ typeof topic !== 'string' || parseFsWatchTopic(topic) === null)),
+ verifiedFsWatchTopics: new Set<string>(),
+ },
(error: unknown) => {
log.warn(`shared task fs-watch admission failed for ${shortId(src)}: ${String(error)}`);
- return { payload, verifiedFsWatchTopics: new Set<string>() };
+ return () => ({ payload, verifiedFsWatchTopics: new Set<string>() });
},
);
}
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index adf952d3a0..8f8eba7c6e 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -87,17 +87,26 @@ export function sharedTaskFileOperation(op: unknown): 'file.read' | 'file.write'
return fileReadOps.has(op) ? 'file.read' : fileWriteOps.has(op) ? 'file.write' : null;
}
+// Bumped synchronously on every workdir patch. Watch admission captures it
+// before its DB read and re-checks it at install time, so a move that lands
+// during the lookup cannot install a watch on the former directory.
+const workdirGenerations = new Map<string, number>();
+export function sharedTaskWorkdirGeneration(sessionId: string): number {
+ return workdirGenerations.get(sessionId) ?? 0;
+}
+
/**
* 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.
+ * through the normal admission. (`remoteHostId` never changes after creation.)
*/
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;
+ workdirGenerations.set(row.sessionId, sharedTaskWorkdirGeneration(row.sessionId) + 1);
const next = normalizeWorkingDirForStorage(typeof patch.workingDir === 'string' ? patch.workingDir : null);
const peers = new Set([...subscriptions.getControllerIds(), ...subscriptions.getKnownControllerIds()]);
for (const peer of peers) {
diff --git a/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts b/apps/desktop/src/main/device-link/sharedTaskFileAccess.ts
index 1029fd7fe5..1a3aa46201 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 { MAX_SHARED_TASK_TOPICS, type SharedTaskPeerCapture } from './sharedTaskDispatch.js';
+import { MAX_SHARED_TASK_TOPICS, sharedTaskWorkdirGeneration, type SharedTaskPeerCapture } from './sharedTaskDispatch.js';
function deny(): never { throw new Error('[PERMISSION_DENIED] Working directory does not belong to this shared task'); }
@@ -31,14 +31,18 @@ export async function assertSharedTaskWorkdir(
* 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.
+ * `isFresh` must be checked synchronously right before installing the topics:
+ * it turns false when the task workdir changed during the lookup.
*/
export async function admitSharedTaskFsWatchTopics(
capture: SharedTaskPeerCapture, topics: readonly unknown[],
-): Promise<{ topics: unknown[]; verified: Set<string> }> {
+): Promise<{ topics: unknown[]; verified: Set<string>; isFresh: () => boolean }> {
+ const generation = sharedTaskWorkdirGeneration(capture.author.sessionId);
+ const isFresh = () => sharedTaskWorkdirGeneration(capture.author.sessionId) === generation;
// 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() };
+ if (topics.length > MAX_SHARED_TASK_TOPICS) return { topics: [...topics], verified: new Set(), isFresh };
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() };
+ if (watched.size === 0) return { topics: [...topics], verified: new Set(), isFresh };
const own = capture.isCurrent() && capture.authorize('file.read') ? await sharedTaskWorkdir(capture) : null;
const verified = new Set<string>();
if (own && capture.isCurrent()) {
@@ -46,5 +50,5 @@ export async function admitSharedTaskFsWatchTopics(
if (normalizeWorkingDirForStorage(parseFsWatchTopic(topic)) === own.workingDir) verified.add(topic);
}
}
- return { topics: topics.filter((topic) => typeof topic !== 'string' || !watched.has(topic) || verified.has(topic)), verified };
+ return { topics: topics.filter((topic) => typeof topic !== 'string' || !watched.has(topic) || verified.has(topic)), verified, isFresh };
}
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 1fe24e80fc..c14b1a414b 100644
--- a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
@@ -301,6 +301,34 @@ describe('file-browser device-op', () => {
expect(guardMock).not.toHaveBeenCalled();
});
+ it('gates an SSH search start like every other SSH request', async () => {
+ sharedWorkdirMock.mockImplementation(async () => {
+ if (!current) throw new Error('[PERMISSION_DENIED] Shared task access changed');
+ return { remoteHostId: 'host-1' };
+ });
+ const started = vi.fn();
+ sshRequestMock.mockImplementation(
+ async (
+ _h: string,
+ method: string,
+ _p: unknown,
+ options?: { beforeSend?: () => void | Promise<void> },
+ ) => {
+ current = false;
+ await options?.beforeSend?.();
+ started(method);
+ return { searchId: 's-1' };
+ },
+ );
+ await expect(
+ asGuest(() =>
+ handleRemoteOp({ op: 'searchCollect', workdir: '/remote/proj', query: 'needle' }),
+ ),
+ ).rejects.toThrow('PERMISSION_DENIED');
+ expect(started).not.toHaveBeenCalled();
+ sshRequestMock.mockReset();
+ });
+
it('routes by the recorded task endpoint instead of reverse-resolving the path', async () => {
// The path exists locally and is also recorded for an SSH session: same-account
// controllers still see an ambiguous endpoint, a guest of the local task does not.
diff --git a/apps/desktop/src/main/file-browser/device-op.ts b/apps/desktop/src/main/file-browser/device-op.ts
index ea1a8bb186..d129a3d60c 100644
--- a/apps/desktop/src/main/file-browser/device-op.ts
+++ b/apps/desktop/src/main/file-browser/device-op.ts
@@ -282,6 +282,7 @@ function setExportJobTerminal(transferId: string, job: ExportJob): void {
async function sshSearchCollect(
hostId: string,
q: { workdir: string; query: string; caseSensitive: boolean; maxMatches: number },
+ gate?: { beforeSend: () => void | Promise<void> },
): Promise<{
matches: SearchMatch[];
truncated: boolean;
@@ -343,8 +344,10 @@ async function sshSearchCollect(
resolve({ matches, truncated: true, totalMatches: matches.length, totalFiles: 0 });
}, SEARCH_COLLECT_TIMEOUT_MS);
timer.unref?.();
- void mgr
- .request(hostId, 'searchStart', q)
+ // 同账号调用保持原三参数形状;共享访客在真正发起搜索前复核授权。
+ void (
+ gate ? mgr.request(hostId, 'searchStart', q, gate) : mgr.request(hostId, 'searchStart', q)
+ )
.then((r) => {
searchId = r.searchId;
// 回放启动窗口内缓冲到的本次事件(可能已含终态)。
@@ -591,15 +594,19 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
message: 'nested SSH workdir',
};
case 'searchCollect':
- return sshSearchCollect(hostId, {
- workdir,
- query: args.query ?? '',
- caseSensitive: args.caseSensitive === true,
- maxMatches: Math.min(
- args.maxMatches ?? SEARCH_COLLECT_MAX_MATCHES,
- SEARCH_COLLECT_MAX_MATCHES,
- ),
- });
+ return sshSearchCollect(
+ hostId,
+ {
+ workdir,
+ query: args.query ?? '',
+ caseSensitive: args.caseSensitive === true,
+ maxMatches: Math.min(
+ args.maxMatches ?? SEARCH_COLLECT_MAX_MATCHES,
+ SEARCH_COLLECT_MAX_MATCHES,
+ ),
+ },
+ gate,
+ );
default:
return bad(`unknown op: ${args.op}`);
}