Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 统一 @ 资源引用与搜索 (#1557)
DavidShenXDc1e8c3b9458e
diff --git a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.tsindex e34b993521..d62afb9d4f 100644--- a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts+++ b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts@@ -113,6 +113,28 @@ describe('computer use plugin IPC invariants', () => {);});+ it('keeps the @ desktop-window gate machine-scoped', () => {+ const registerSource = fs.readFileSync(+ path.resolve(__dirname, '../maker-ipc/register.ts'),+ 'utf-8',+ );+ const handlerStart = registerSource.indexOf(+ 'ipcMain.handle(MAKER_INVOKE.AT_CONTEXT_LIST',+ );+ const handlerEnd = registerSource.indexOf(+ 'ipcMain.handle(MAKER_INVOKE.LIST_CUSTOMIZATIONS',+ handlerStart,+ );+ const handlerBody = registerSource.slice(handlerStart, handlerEnd);++ expect(handlerStart).toBeGreaterThanOrEqual(0);+ expect(handlerEnd).toBeGreaterThan(handlerStart);+ expect(handlerBody).toContain("getPluginRegistry().isEnabled('computer')");+ expect(handlerBody).not.toContain(+ "getPluginRegistry().isEnabled('computer', request.workingDir)",+ );+ });+it('revalidates Computer Use guide requests at the Main IPC boundary', () => {const registerSource = fs.readFileSync(path.resolve(__dirname, '../maker-ipc/register.ts'),diff --git a/apps/desktop/src/main/__tests__/nativeAtResourcePicker.test.ts b/apps/desktop/src/main/__tests__/nativeAtResourcePicker.test.tsnew file mode 100644index 0000000000..488066d3ea--- /dev/null+++ b/apps/desktop/src/main/__tests__/nativeAtResourcePicker.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it, vi } from 'vitest';++import { pickNativeAtResource } from '../nativeAtResourcePicker.js';++describe('pickNativeAtResource', () => {+ it('opens a combined file and directory picker on macOS', async () => {+ const showOpenDialog = vi.fn().mockResolvedValue({+ canceled: false,+ filePaths: ['/repo/docs'],+ });++ await expect(pickNativeAtResource({+ platform: 'darwin',+ showOpenDialog,+ isDirectory: () => true,+ }, '/repo')).resolves.toEqual({ path: '/repo/docs', kind: 'directory' });+ expect(showOpenDialog).toHaveBeenCalledWith({+ properties: ['openFile', 'openDirectory'],+ defaultPath: '/repo',+ });+ });++ it('opens a file picker on Windows', async () => {+ const showOpenDialog = vi.fn().mockResolvedValue({+ canceled: false,+ filePaths: ['D:\\repo\\README.md'],+ });++ await expect(pickNativeAtResource({+ platform: 'win32',+ showOpenDialog,+ isDirectory: () => false,+ }, 'D:\\repo')).resolves.toEqual({+ path: 'D:\\repo\\README.md',+ kind: 'file',+ });+ expect(showOpenDialog).toHaveBeenCalledWith({+ properties: ['openFile'],+ defaultPath: 'D:\\repo',+ });+ });++ it('returns an empty result when the user cancels', async () => {+ await expect(pickNativeAtResource({+ platform: 'win32',+ showOpenDialog: vi.fn().mockResolvedValue({ canceled: true, filePaths: [] }),+ isDirectory: vi.fn(),+ })).resolves.toEqual({ path: null, kind: null });+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex d416bf9e2d..c665d9e0ab 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -667,7 +667,8 @@ import { findCindyFileInArgv } from './cindy-brain/argv.js';import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';import { registerCindyFileAssociation } from './cindy-brain/fileAssociation.js';import { setMainLocale, t } from './i18n.js';-import { throwIpcError } from './utils/ipcValidate.js';+import { requireObject, throwIpcError } from './utils/ipcValidate.js';+import { pickNativeAtResource } from './nativeAtResourcePicker.js';// Scheduler (Phase 3) — 启动单例需要 maker / localDb / mainWindow 都 ready,但// splash check-environment / user login (触发 ensureReady) 谁先到不固定。// 通过 attemptStartScheduler 在两个就绪事件源各调一次幂等 startScheduler,最后到的@@ -4645,6 +4646,45 @@ const registerIpcHandlers = () => {},);+ // ── Dialog: @ 资源入口的系统选择器 ──+ ipcMain.handle(+ 'dialog:show-open-resource',+ async (+ event: Electron.IpcMainInvokeEvent,+ payload: unknown = {},+ ): Promise<{+ success: true;+ path: string | null;+ kind: 'file' | 'directory' | null;+ }> => {+ assertTrustedAppRendererEvent(event);+ const params = requireObject(payload);+ const defaultPathValue = params.defaultPath;+ if (+ defaultPathValue !== undefined+ && (+ typeof defaultPathValue !== 'string'+ || defaultPathValue.length > 4096+ || !path.isAbsolute(defaultPathValue)+ )+ ) {+ throwIpcError('INVALID_PARAMS', 'defaultPath must be an absolute path');+ }+ const owner = BrowserWindow.fromWebContents(event.sender);+ if (!owner) return { success: true, path: null, kind: null };+ try {+ const picked = await pickNativeAtResource({+ platform: process.platform,+ showOpenDialog: (options) => dialog.showOpenDialog(owner, options),+ isDirectory: (selectedPath) => fs.statSync(selectedPath).isDirectory(),+ }, defaultPathValue);+ return { success: true, ...picked };+ } catch {+ throwIpcError('INTERNAL', 'unable to open resource picker');+ }+ },+ );+// (api-key:test-connection 已随手填录入链路移除,2026-07-17:XD 网关 key 一律由// model-access 自动下发,连通性由同步状态机负责。)diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 036ef5cb18..e13774adf9 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -44,9 +44,14 @@ export const MAX_BASIC_ZIP_ENTRIES = 256;export const MAX_NODE_ZIP_ENTRIES = 2_048;/** 停用标记文件名(安装目录内;存在即停用)。 */const DISABLED_MARKER_FILE = '.disabled';-/** 安装时已验证的信任结果快照(作者包不能提供,staging 阶段由主机写)。 */+/** 安装时由主机写入的信任快照与权限 receipt;作者包不能提供。 */const TRUST_METADATA_FILE = '.cindy-trust.json';+interface GhostInstalledHostMetadata {+ trust: GhostTrustInfo;+ approvedAtResourceProviderTool?: string;+}+/** 注入式日志接口 —— manager 不直接依赖 main/logger,单测零 electron。 */export interface GhostManagerLogger {info(message: string, meta?: Record<string, unknown>): void;@@ -138,15 +143,26 @@ export class GhostManager {});continue;}+ const hostMetadata = this.readInstalledHostMetadata(dir);+ // atResourceProvider 在旧版宿主里只是未知顶层元数据。只有新版宿主在+ // install/update 审阅后写下的精确 receipt 才把它提升为运行时入口;旧安装+ // 没 receipt 时 fail closed,但插件本体与已批准 tool 仍照旧可用。+ const manifest =+ v.manifest.atResourceProvider+ && hostMetadata?.approvedAtResourceProviderTool !== v.manifest.atResourceProvider.tool+ ? (() => {+ const { atResourceProvider: _ignored, ...rest } = v.manifest;+ return rest;+ })()+ : v.manifest;// icon 读失败只降级为无图标(warn),不影响意识本体可用。- const iconDataUrl = this.readInstalledIconDataUrl(dir, v.manifest);- const localizedManifest = this.readInstalledLocalizedManifest(dir, v.manifest);- const trust = this.readInstalledTrust(dir);+ const iconDataUrl = this.readInstalledIconDataUrl(dir, manifest);+ const localizedManifest = this.readInstalledLocalizedManifest(dir, manifest);result.push({manifest: localizedManifest,dir,enabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),- ...(trust ? { trust } : {}),+ ...(hostMetadata ? { trust: hostMetadata.trust } : {}),...(iconDataUrl !== null ? { iconDataUrl } : {}),});}@@ -247,21 +263,44 @@ export class GhostManager {}}- /** 读取主机安装时写下的签名验证快照;坏文件只降级未显示,不信作者自报。 */- private readInstalledTrust(dir: string): GhostTrustInfo | null {+ /** 读取主机安装时写下的信任快照与权限 receipt;坏文件一律 fail closed。 */+ private readInstalledHostMetadata(dir: string): GhostInstalledHostMetadata | null {try {const bytes = readBoundedFileNoFollowSync(path.join(dir, TRUST_METADATA_FILE), 64 * 1024);if (bytes === null) return null;- const raw = JSON.parse(bytes.toString('utf8')) as GhostTrustInfo;+ const raw = JSON.parse(bytes.toString('utf8')) as Record<string, unknown>;if (!raw ||typeof raw !== 'object' ||+ typeof raw.level !== 'string' ||!['cindy-official', 'reviewed', 'verified-publisher', 'unverified'].includes(raw.level) ||typeof raw.publisherSigned !== 'boolean' ||typeof raw.publisherVerified !== 'boolean' ||typeof raw.reviewed !== 'boolean') return null;- return raw;+ const trust: GhostTrustInfo = {+ level: raw.level as GhostTrustInfo['level'],+ publisherSigned: raw.publisherSigned,+ publisherVerified: raw.publisherVerified,+ reviewed: raw.reviewed,+ ...(typeof raw.publisherName === 'string' ? { publisherName: raw.publisherName } : {}),+ ...(typeof raw.publisherKeyId === 'string' ? { publisherKeyId: raw.publisherKeyId } : {}),+ ...(typeof raw.reviewerName === 'string' ? { reviewerName: raw.reviewerName } : {}),+ ...(typeof raw.unknownReviewer === 'boolean' ? { unknownReviewer: raw.unknownReviewer } : {}),+ };+ const approval = raw.approvedAtResourceProvider;+ const approvedAtResourceProviderTool =+ approval+ && typeof approval === 'object'+ && !Array.isArray(approval)+ && Object.keys(approval).length === 1+ && typeof (approval as Record<string, unknown>).tool === 'string'+ ? (approval as Record<string, string>).tool+ : undefined;+ return {+ trust,+ ...(approvedAtResourceProviderTool ? { approvedAtResourceProviderTool } : {}),+ };} catch {return null;}@@ -642,6 +681,9 @@ export class GhostManager {? MAX_NODE_UNCOMPRESSED_BYTES: MAX_BASIC_UNCOMPRESSED_BYTES,trust,+ ...(manifest.atResourceProvider+ ? { approvedAtResourceProviderTool: manifest.atResourceProvider.tool }+ : {}),});await fs.promises.rename(stagingDir, finalDir);} catch (err) {@@ -729,6 +771,9 @@ export class GhostManager {? MAX_NODE_UNCOMPRESSED_BYTES: MAX_BASIC_UNCOMPRESSED_BYTES,trust,+ ...(manifest.atResourceProvider+ ? { approvedAtResourceProviderTool: manifest.atResourceProvider.tool }+ : {}),});} catch (err) {await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});@@ -771,7 +816,12 @@ export class GhostManager {allEntries: JSZip.JSZipObject[],prefix: string,stagingDir: string,- opts: { disabled: boolean; maxUncompressedBytes: number; trust: GhostTrustInfo },+ opts: {+ disabled: boolean;+ maxUncompressedBytes: number;+ trust: GhostTrustInfo;+ approvedAtResourceProviderTool?: string;+ },): Promise<void> {await fs.promises.mkdir(stagingDir, { recursive: true });let totalBytes = 0;@@ -797,7 +847,12 @@ export class GhostManager {}await fs.promises.writeFile(path.join(stagingDir, TRUST_METADATA_FILE),- `${JSON.stringify(opts.trust, null, 2)}\n`,+ `${JSON.stringify({+ ...opts.trust,+ ...(opts.approvedAtResourceProviderTool+ ? { approvedAtResourceProvider: { tool: opts.approvedAtResourceProviderTool } }+ : {}),+ }, null, 2)}\n`,);}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 7c6f46eeb0..396768c2a3 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -45,6 +45,13 @@ function goodManifest(id = 'hello'): Record<string, unknown> {};}+function atResourceManifest(id = 'hello'): Record<string, unknown> {+ return {+ ...goodManifest(id),+ atResourceProvider: { tool: 'do_thing' },+ };+}+/** 带显式指令的芯片型清单(command 查重用例)。 */function chipManifestWithCommand(id: string, command: string): Record<string, unknown> {return {@@ -230,6 +237,30 @@ describe('GhostManager · install', () => {expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);});+ it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {+ const cindy = await makeCindy('at-resource.cindy', atResourceManifest());+ const installed = await manager.install(cindy);+ expect(installed).toMatchObject({+ ghost: { manifest: { atResourceProvider: { tool: 'do_thing' } } },+ });+ expect(manager.list()[0].manifest.atResourceProvider).toEqual({ tool: 'do_thing' });++ const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;+ expect(metadata.approvedAtResourceProvider).toEqual({ tool: 'do_thing' });++ delete metadata.approvedAtResourceProvider;+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ expect(manager.list()[0].manifest.atResourceProvider).toBeUndefined();+ expect(manager.list()[0].manifest.tools).toEqual([+ { name: 'do_thing', description: '做点事' },+ ]);++ metadata.approvedAtResourceProvider = { tool: 'other_tool' };+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ expect(manager.list()[0].manifest.atResourceProvider).toBeUndefined();+ });+it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {const cindy = await makeCindy('hello.cindy', goodManifest());const result = await manager.install(cindy, { initiallyEnabled: false });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/atResourceProvider.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/atResourceProvider.test.tsnew file mode 100644index 0000000000..7e526e911e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/atResourceProvider.test.ts@@ -0,0 +1,183 @@+import { describe, expect, it, vi } from 'vitest';++import type { InstalledGhost } from '../../../shared/ghost.js';+import {+ GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS,+ GhostAtResourceQueryScheduler,+ listGhostAtResourceProviders,+ queryGhostAtResources,+ resolveGhostAtResourceWorkingDir,+ type GhostAtResourceProviderDeps,+} from '../atResourceProvider.js';++function ghost(overrides: Partial<InstalledGhost> = {}): InstalledGhost {+ return {+ dir: '/plugins/issues',+ enabled: true,+ manifest: {+ schemaVersion: 2,+ id: 'issues',+ name: 'Issue Tracker',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool'],+ tools: [{ name: 'search_issues', description: 'Search issues without side effects' }],+ atResourceProvider: { tool: 'search_issues' },+ },+ ...overrides,+ };+}++function deps(overrides: Partial<GhostAtResourceProviderDeps> = {}): GhostAtResourceProviderDeps {+ return {+ listGhosts: () => [ghost()],+ isAvailable: () => true,+ isDisabledForWorkdir: () => false,+ getSetupAssessment: () => ({ state: 'ready', revision: 1, groups: [] }),+ callTool: vi.fn(async () => ({+ ok: true as const,+ result: {+ items: [{ id: 'ISSUE-1', label: ' Fix\u202e\nlogin ', description: ' Open\tissue ' }],+ },+ })),+ ...overrides,+ };+}++describe('Plugin @ resource providers', () => {+ it('uses authoritative local session scope and rejects draft paths', async () => {+ const getSessionSnapshot = vi.fn(async (sessionId: string) => {+ if (sessionId === 'local') return { workingDir: '/db/repo', remoteHostId: null };+ if (sessionId === 'remote') return { workingDir: '/remote/repo', remoteHostId: 'host-1' };+ return null;+ });++ await expect(resolveGhostAtResourceWorkingDir({+ sessionId: 'local',+ workingDir: '/spoofed/repo',+ }, getSessionSnapshot)).resolves.toEqual({ allowed: true, workingDir: '/db/repo' });+ await expect(resolveGhostAtResourceWorkingDir({+ sessionId: 'remote',+ workingDir: '/spoofed/repo',+ }, getSessionSnapshot)).resolves.toEqual({ allowed: false });+ await expect(resolveGhostAtResourceWorkingDir({ sessionId: 'missing' }, getSessionSnapshot))+ .resolves.toEqual({ allowed: false });+ await expect(resolveGhostAtResourceWorkingDir({ workingDir: '/draft/repo' }, getSessionSnapshot))+ .resolves.toEqual({ allowed: false });+ await expect(resolveGhostAtResourceWorkingDir({}, getSessionSnapshot))+ .resolves.toEqual({ allowed: false });+ });++ it('lists eligible metadata without dispatching a tool', () => {+ const harness = deps();+ expect(listGhostAtResourceProviders(harness, '/repo')).toEqual([+ { ghostId: 'issues', name: 'Issue Tracker' },+ ]);+ expect(harness.callTool).not.toHaveBeenCalled();+ });++ it('fails closed when disabled, workdir-disabled or setup is not ready', async () => {+ const disabled = deps({ listGhosts: () => [ghost({ enabled: false })] });+ const workdirDisabled = deps({ isDisabledForWorkdir: () => true });+ const setupRequired = deps({+ getSetupAssessment: () => ({ state: 'required', revision: 1, groups: [] }),+ });++ expect(listGhostAtResourceProviders(disabled)).toEqual([]);+ expect(listGhostAtResourceProviders(workdirDisabled, '/repo')).toEqual([]);+ await expect(queryGhostAtResources(setupRequired, { ghostId: 'issues' })).resolves+ .toMatchObject({ success: false });+ expect(setupRequired.callTool).not.toHaveBeenCalled();+ });++ it('dispatches only the fixed query contract with a short host timeout', async () => {+ const harness = deps();+ const result = await queryGhostAtResources(harness, {+ ghostId: 'issues',+ query: ` login\n${'x'.repeat(200)}`,+ limit: 100,+ });++ expect(harness.callTool).toHaveBeenCalledWith({+ ghostId: 'issues',+ tool: 'search_issues',+ args: { query: `login ${'x'.repeat(122)}`, limit: 20 },+ timeoutMs: GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS,+ });+ expect(result).toMatchObject({+ success: true,+ pluginName: 'Issue Tracker',+ items: [{+ id: 'ISSUE-1',+ label: 'Fix login',+ description: 'Open issue',+ }],+ });+ expect(result.items[0]?.href).toBe(+ 'cindy://plugin-resource/issues/search_issues/ISSUE-1',+ );+ });++ it('drops malformed, duplicate and excess result rows', async () => {+ const harness = deps({+ callTool: vi.fn(async () => ({+ ok: true as const,+ result: {+ items: [+ { id: 'A', label: 'First' },+ { id: 'A', label: 'Duplicate' },+ { id: 'BAD\u0000', label: 'Control' },+ { id: 'B', label: '' },+ { id: '😀'.repeat(128), label: 'Encoded href too long' },+ { id: 'C', label: 'Third' },+ ],+ },+ })),+ });+ const result = await queryGhostAtResources(harness, { ghostId: 'issues', limit: 2 });+ expect(result.success && result.items.map((item) => item.id)).toEqual(['A', 'C']);+ expect(result.truncated).toBe(true);+ });++ it('allows one running query per Plugin and coalesces pending work to the latest query', async () => {+ const deliveries: Array<(result: { ok: true; result: unknown }) => void> = [];+ const callTool = vi.fn(() => new Promise<{ ok: true; result: unknown }>((resolve) => {+ deliveries.push(resolve);+ }));+ const scheduler = new GhostAtResourceQueryScheduler(deps({ callTool }));++ const first = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'first' });+ const superseded = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'second' });+ const latest = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'latest' });+ expect(callTool).toHaveBeenCalledTimes(1);+ await expect(superseded).resolves.toMatchObject({+ success: false,+ error: 'Plugin resource search superseded',+ });++ deliveries[0]({ ok: true, result: { items: [] } });+ await expect(first).resolves.toMatchObject({ success: true });+ await vi.waitFor(() => expect(callTool).toHaveBeenCalledTimes(2));+ expect(callTool).toHaveBeenNthCalledWith(2, expect.objectContaining({+ args: { query: 'latest', limit: 20 },+ }));+ deliveries[1]({ ok: true, result: { items: [] } });+ await expect(latest).resolves.toMatchObject({ success: true });+ });++ it('does not coalesce the same Plugin across window/task scopes', async () => {+ const deliveries: Array<(result: { ok: true; result: unknown }) => void> = [];+ const callTool = vi.fn(() => new Promise<{ ok: true; result: unknown }>((resolve) => {+ deliveries.push(resolve);+ }));+ const scheduler = new GhostAtResourceQueryScheduler(deps({ callTool }));++ const first = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'one' });+ const second = scheduler.query('window-2:session-2', { ghostId: 'issues', query: 'two' });+ expect(callTool).toHaveBeenCalledTimes(2);+ deliveries[0]({ ok: true, result: { items: [] } });+ deliveries[1]({ ok: true, result: { items: [] } });+ await expect(Promise.all([first, second])).resolves.toHaveLength(2);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.tsindex 4809cd0b0f..d5744c3427 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts@@ -277,6 +277,24 @@ describe('超时与收卷', () => {expect(late.accepted).toBe(false);});+ it('可信宿主可为 UI 查询单独收短超时,不改变普通调用默认档', async () => {+ const h = makeHarness({ timeoutMs: 1000 });+ const short = h.dispatcher.callGhostTool({ ...CALL, timeoutMs: 50 });+ const normal = h.dispatcher.callGhostTool(CALL);+ expect(h.sent).toHaveLength(2);++ vi.advanceTimersByTime(40);+ expect(h.dispatcher.handleToolProgress('art', {+ callId: h.sent[0].callId,+ }).accepted).toBe(true);+ vi.advanceTimersByTime(10);+ await expect(short).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });+ expect(h.dispatcher.pendingCount()).toBe(1);++ vi.advanceTimersByTime(950);+ await expect(normal).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });+ });+it('崩溃收卷 → GHOST_CRASHED;熄灯收卷 → GHOST_ASLEEP;只收本意识的', async () => {const h = makeHarness();const p1 = h.dispatcher.callGhostTool(CALL);diff --git a/apps/desktop/src/main/cindy-brain/atResourceProvider.ts b/apps/desktop/src/main/cindy-brain/atResourceProvider.tsnew file mode 100644index 0000000000..cf9b150f37--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/atResourceProvider.ts@@ -0,0 +1,276 @@+import { buildPluginResourceReferenceHref } from '@cindy/maker-shared/agent-input-projection';++import type {+ GhostSetupAssessment,+ GhostToolCallResult,+ InstalledGhost,+} from '../../shared/ghost.js';++const QUERY_MAX_CHARS = 128;+const RESULT_LIMIT_MAX = 20;+const RESULT_MAX_BYTES = 64 * 1024;+const PROVIDER_LIMIT_MAX = 40;+const RESOURCE_HREF_MAX_CHARS = 1_500;+export const GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS = 4_000;++export interface GhostAtResourceProviderItem {+ ghostId: string;+ name: string;+ description?: string;+}++export interface GhostAtResourceItem {+ id: string;+ label: string;+ description?: string;+ href: string;+}++export interface GhostAtResourceProviderDeps {+ listGhosts(): InstalledGhost[];+ isAvailable(ghostId: string): boolean;+ isDisabledForWorkdir(ghostId: string, workingDir?: string): boolean;+ getSetupAssessment(ghostId: string): GhostSetupAssessment;+ callTool(request: {+ ghostId: string;+ tool: string;+ args: Record<string, unknown>;+ timeoutMs: number;+ }): Promise<GhostToolCallResult>;+}++export type GhostAtResourceQueryResult =+ | { success: true; pluginName: string; items: GhostAtResourceItem[]; truncated: boolean }+ | { success: false; error: string; items: []; truncated: false };++interface ScheduledQuery {+ request: Parameters<typeof queryGhostAtResources>[1];+ resolve: (result: GhostAtResourceQueryResult) => void;+}++/** One running call plus one coalesced latest query per window/task/Plugin scope. */+export class GhostAtResourceQueryScheduler {+ private readonly states = new Map<string, { pending?: ScheduledQuery }>();++ constructor(private readonly deps: GhostAtResourceProviderDeps) {}++ query(+ scopeKey: string,+ request: Parameters<typeof queryGhostAtResources>[1],+ ): Promise<GhostAtResourceQueryResult> {+ return new Promise((resolve) => {+ const key = `${scopeKey}\u0000${request.ghostId}`;+ const active = this.states.get(key);+ if (active) {+ active.pending?.resolve({+ success: false,+ error: 'Plugin resource search superseded',+ items: [],+ truncated: false,+ });+ active.pending = { request, resolve };+ return;+ }+ const state: { pending?: ScheduledQuery } = {};+ this.states.set(key, state);+ void this.run(key, { request, resolve }, state);+ });+ }++ private async run(+ key: string,+ scheduled: ScheduledQuery,+ state: { pending?: ScheduledQuery },+ ): Promise<void> {+ let result: GhostAtResourceQueryResult;+ try {+ result = await queryGhostAtResources(this.deps, scheduled.request);+ } catch {+ result = {+ success: false,+ error: 'Plugin resource search failed',+ items: [],+ truncated: false,+ };+ }+ scheduled.resolve(result);+ const next = state.pending;+ if (next) {+ state.pending = undefined;+ void this.run(key, next, state);+ return;+ }+ this.states.delete(key);+ }+}++export interface GhostAtResourceSessionSnapshot {+ workingDir?: string | null;+ remoteHostId?: string | null;+}++/** Resolve Plugin execution scope without trusting a renderer-provided session workdir. */+export async function resolveGhostAtResourceWorkingDir(+ raw: Record<string, unknown>,+ getSessionSnapshot: (+ sessionId: string,+ ) => Promise<GhostAtResourceSessionSnapshot | null | undefined>,+): Promise<{ allowed: boolean; workingDir?: string }> {+ if (typeof raw.sessionId === 'string' && raw.sessionId.length > 0) {+ const snapshot = await getSessionSnapshot(raw.sessionId.slice(0, 256));+ // Local Plugin tools never run on behalf of remote execution contexts.+ if (!snapshot || snapshot.remoteHostId) return { allowed: false };+ return {+ allowed: true,+ ...(snapshot.workingDir ? { workingDir: snapshot.workingDir } : {}),+ };+ }+ // New-task drafts have no persisted session yet. The renderer's workingDir+ // cannot be used as a Plugin policy scope because it is not authoritative.+ return { allowed: false };+}++function oneLine(value: unknown, maxLength: number): string {+ return typeof value === 'string'+ ? value+ .replace(/[\u0000-\u001f\u007f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, maxLength)+ : '';+}++function eligibleGhost(+ deps: GhostAtResourceProviderDeps,+ ghostId: string,+ workingDir?: string,+ candidate?: InstalledGhost,+): InstalledGhost | null {+ if (!deps.isAvailable(ghostId)) return null;+ const ghost = candidate?.manifest.id === ghostId+ ? candidate+ : deps.listGhosts().find((item) => item.manifest.id === ghostId);+ if (+ !ghost?.enabled+ || !ghost.manifest.atResourceProvider+ || deps.isDisabledForWorkdir(ghostId, workingDir)+ ) return null;+ const tool = ghost.manifest.atResourceProvider.tool;+ if (!ghost.manifest.tools?.some((candidate) => candidate.name === tool)) return null;+ try {+ if (deps.getSetupAssessment(ghostId).state !== 'ready') return null;+ } catch {+ return null;+ }+ return ghost;+}++/** List metadata only. No Plugin tool runs until the user selects one provider. */+export function listGhostAtResourceProviders(+ deps: GhostAtResourceProviderDeps,+ workingDir?: string,+): GhostAtResourceProviderItem[] {+ const items: GhostAtResourceProviderItem[] = [];+ for (const ghost of deps.listGhosts()) {+ if (items.length >= PROVIDER_LIMIT_MAX) break;+ if (!eligibleGhost(deps, ghost.manifest.id, workingDir, ghost)) continue;+ const name = oneLine(ghost.manifest.name, 128);+ if (!name) continue;+ const description = oneLine(ghost.manifest.description, 256);+ items.push({+ ghostId: ghost.manifest.id,+ name,+ ...(description ? { description } : {}),+ });+ }+ return items;+}++export async function queryGhostAtResources(+ deps: GhostAtResourceProviderDeps,+ request: {+ ghostId: string;+ workingDir?: string;+ query?: string;+ limit?: number;+ },+): Promise<GhostAtResourceQueryResult> {+ const ghostId = oneLine(request.ghostId, 32);+ const ghost = ghostId ? eligibleGhost(deps, ghostId, request.workingDir) : null;+ if (!ghost) {+ return { success: false, error: 'Plugin resource provider unavailable', items: [], truncated: false };+ }++ const query = oneLine(request.query ?? '', QUERY_MAX_CHARS);+ const limit = Number.isFinite(request.limit)+ ? Math.max(1, Math.min(RESULT_LIMIT_MAX, Math.floor(request.limit as number)))+ : RESULT_LIMIT_MAX;+ const tool = ghost.manifest.atResourceProvider!.tool;+ const result = await deps.callTool({+ ghostId,+ tool,+ args: { query, limit },+ timeoutMs: GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS,+ });+ if (!result.ok) {+ return {+ success: false,+ error: oneLine(result.message, 256) || 'Plugin resource search failed',+ items: [],+ truncated: false,+ };+ }++ if (!result.result || typeof result.result !== 'object' || Array.isArray(result.result)) {+ return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };+ }+ let encoded: string | undefined;+ try {+ encoded = JSON.stringify(result.result);+ } catch {+ return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };+ }+ if (!encoded) {+ return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };+ }+ if (Buffer.byteLength(encoded, 'utf8') > RESULT_MAX_BYTES) {+ return { success: false, error: 'Plugin resource list is too large', items: [], truncated: false };+ }+ const rawItems = (result.result as Record<string, unknown>).items;+ if (!Array.isArray(rawItems)) {+ return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };+ }++ const items: GhostAtResourceItem[] = [];+ const seen = new Set<string>();+ for (const rawItem of rawItems) {+ if (items.length >= limit) break;+ if (!rawItem || typeof rawItem !== 'object' || Array.isArray(rawItem)) continue;+ const record = rawItem as Record<string, unknown>;+ const id = typeof record.id === 'string' ? record.id : '';+ const label = oneLine(record.label, 128);+ if (+ !id.trim()+ || id.length > 256+ || /[\u0000-\u001f\u007f\u2028\u2029]/.test(id)+ || !label+ || seen.has(id)+ ) continue;+ seen.add(id);+ const description = oneLine(record.description, 256);+ const href = buildPluginResourceReferenceHref({ ghostId, tool, resourceId: id });+ if (href.length > RESOURCE_HREF_MAX_CHARS) continue;+ items.push({+ id,+ label,+ ...(description ? { description } : {}),+ href,+ });+ }+ return {+ success: true,+ pluginName: oneLine(ghost.manifest.name, 128) || ghostId,+ items,+ truncated: rawItems.length > items.length,+ };+}diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 2741303881..7adaf5fe7f 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1064,6 +1064,7 @@ my-ghost/// (仅检查插件启用状态与 tools 声明)。除非你的插件完全靠 panel 或 subscribe 驱动,// 否则请始终声明一个 command。"tools": [ /* 见 §3 */ ],+ "atResourceProvider": { "tool": "search_resources" }, // 可选:把一个已声明、无副作用的搜索工具接入 @,见 §3.1"cindy": { "image": ["generate", "edit"] }, // 声明了 cindy 槽时必写:能力详单,见下// 三个类目:image / video 的动作是 "generate" | "edit";media 的动作只有// "deposit"(把你手里的媒体字节寄存进总仓换指纹,见 §4.0.1)。按需申请,@@ -1327,6 +1328,42 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它写行为规则(如"用户原话透传,不要扩写"、"仅当用户显式说 X 才传 Y")——AI 会照做。这是你影响 AI 行为的**唯一合法通道**,不要试图在别处塞指令。+### 3.1 可选:接入 @ 业务资源搜索++插件可把一个**已经声明并经过权限确认**的工具接到 Composer 的 \`@\` 面板:++\`\`\`json+"atResourceProvider": { "tool": "search_resources" }+\`\`\`++本入口复用已有的 \`"tool"\` 槽,不新增 slot;\`tool\` 必须逐字引用 \`tools[].name\`。这不会增加+底层工具权限,但新增了一个明确的调用入口,因此会在安装/更新确认中单独披露。裸 \`@\` 只展示插件入口,+不会调用工具。用户明确选中你的插件后,宿主才只向这个工具发送:++\`\`\`json+{ "query": "用户输入", "limit": 20 }+\`\`\`++工具必须无副作用,并在 4 秒内返回固定摘要结构:++\`\`\`json+{+ "items": [{+ "id": "业务对象的不透明稳定 ID",+ "label": "单行展示名",+ "description": "可选的单行摘要"+ }]+}+\`\`\`++同一个工具还必须支持把某条返回项的完整 \`id\` 作为 \`query\` 精确解析,并把+该对象放在结果首项;这样 Agent 收到不透明 ID 后可以按需读取最新信息。++最多返回 20 项;\`id\` 最长 256 字符,\`label\` 最长 128 字符,+\`description\` 最长 256 字符。不要返回正文、凭证、HTML、指令或自定义调用参数;+宿主只保留 ID 和可读摘要,并用固定格式投影给 Agent。插件 locale 不增加本字段的+翻译,入口展示名直接复用已本地化的插件 \`name\`。+## 3.5 工具面设计:直接声明,还是两段式目录工具怎么摆有两种形态,按"数量 × 粒度"选,选错会拖累所有会话:diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex cc2b6760bc..bb563f3f30 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -132,6 +132,12 @@ import {} from './gitlabAccountsMigration.js';import { GHOST_SCHEME, ghostExternalLinkUrls, parseGhostPartition } from '../../shared/ghost.js';import { GhostPipeDispatcher } from './pipeDispatcher.js';+import {+ GhostAtResourceQueryScheduler,+ listGhostAtResourceProviders,+ resolveGhostAtResourceWorkingDir,+ type GhostAtResourceProviderDeps,+} from './atResourceProvider.js';import { GhostCardService, parseCardHeightReport } from './cardService.js';import { GhostCardActionDispatcher } from './cardActionDispatch.js';import { GhostSessionActivityTracker } from './ghostSessionActivity.js';@@ -4091,6 +4097,56 @@ export function registerGhostIpc(): void {event.returnValue = { ghosts: availableGhosts() };});+ const atResourceProviderDeps: GhostAtResourceProviderDeps = {+ listGhosts: () => manager.list(),+ isAvailable: isGhostAvailableForActiveSession,+ isDisabledForWorkdir: (ghostId, workingDir) =>+ isGhostDisabledForWorkdir(ghostId, workingDir),+ getSetupAssessment: getGhostSetupAssessment,+ callTool: (request) => getGhostPipeDispatcher().callGhostTool(request),+ };+ const atResourceQueryScheduler = new GhostAtResourceQueryScheduler(atResourceProviderDeps);+ ipcMain.handle('ghosts:at-resource-providers:list', async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ const request = raw && typeof raw === 'object' && !Array.isArray(raw)+ ? raw as Record<string, unknown>+ : {};+ const scope = await resolveGhostAtResourceWorkingDir(request, getSessionFsSnapshot);+ return {+ items: scope.allowed+ ? listGhostAtResourceProviders(atResourceProviderDeps, scope.workingDir)+ : [],+ };+ });+ ipcMain.handle('ghosts:at-resources:query', async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ throwIpcError('INVALID_PARAMS', 'Plugin resource query must be an object');+ }+ const request = raw as Record<string, unknown>;+ if (typeof request.ghostId !== 'string') {+ throwIpcError('INVALID_PARAMS', 'ghostId is required');+ }+ const scope = await resolveGhostAtResourceWorkingDir(request, getSessionFsSnapshot);+ if (!scope.allowed) {+ return {+ success: false,+ error: 'Plugin resource provider unavailable',+ items: [],+ truncated: false,+ };+ }+ const requestScope = typeof request.sessionId === 'string' && request.sessionId.length > 0+ ? `session:${request.sessionId.slice(0, 256)}`+ : `draft:${scope.workingDir ?? ''}`;+ return atResourceQueryScheduler.query(`${event.sender.id}:${requestScope}`, {+ ghostId: request.ghostId,+ ...(scope.workingDir ? { workingDir: scope.workingDir } : {}),+ ...(typeof request.query === 'string' ? { query: request.query } : {}),+ ...(typeof request.limit === 'number' ? { limit: request.limit } : {}),+ });+ });+// Plugin 页的已安装快捷行按最近成功使用排序。历史是主机 UI 状态,不写入// publisher-owned manifest;同步读保证列表首帧不先按扫描序再跳成最近序。ipcMain.on('ghosts:recent-usage', (event) => {diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.tsindex 436e33a7ac..2a6c7513c0 100644--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts@@ -55,6 +55,10 @@ interface PendingCall {timer: ReturnType<typeof setTimeout> | undefined;/** 派发时刻(续命天花板从这里起算)。 */startedAt: number;+ /** 本次调用的基础超时档;默认沿用全局档,宿主 UI 查询可显式收短。 */+ baseTimeoutMs: number;+ /** 显式短超时是绝对窗口,不接受 hold / tool-progress 续命。 */+ timeoutExtensionsAllowed: boolean;/** 当前生效的超时时刻(hold / 心跳只延不缩,release 才收)。 */deadlineAt: number;/** 在途代办 hold 计数(同一卷可并发多单代办,全部收工才收窗)。 */@@ -124,6 +128,8 @@ export class GhostPipeDispatcher {* callId,故由它铸好传入;缺省自铸,老调用方零改动)。*/callId?: string;+ /** 仅供可信宿主内部调用方收短等待时间;插件不能控制该值。 */+ timeoutMs?: number;}): Promise<GhostToolCallResult> {const { ghostId, tool, args } = request;@@ -157,13 +163,16 @@ export class GhostPipeDispatcher {return new Promise<GhostToolCallResult>((resolve) => {const startedAt = Date.now();+ const baseTimeoutMs = this.baseTimeoutMs(request.timeoutMs);const entry: PendingCall = {ghostId,tool,resolve,timer: undefined,startedAt,- deadlineAt: startedAt + this.baseTimeoutMs(),+ baseTimeoutMs,+ timeoutExtensionsAllowed: request.timeoutMs === undefined,+ deadlineAt: startedAt + baseTimeoutMs,holds: 0,};this.pending.set(callId, entry);@@ -177,8 +186,11 @@ export class GhostPipeDispatcher {}/** 基础超时档(注入值钳到天花板内,保证初始 deadline 不越过绝对上限)。 */- private baseTimeoutMs(): number {- return Math.min(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS, GHOST_PIPE_CALL_MAX_TOTAL_MS);+ private baseTimeoutMs(override?: number): number {+ const requested = Number.isFinite(override)+ ? Math.max(1, Math.floor(override as number))+ : this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ return Math.min(requested, GHOST_PIPE_CALL_MAX_TOTAL_MS);}/** 按 entry.deadlineAt 重挂超时闹钟(旧闹钟一并清掉)。 */@@ -232,6 +244,7 @@ export class GhostPipeDispatcher {holdCall(ghostId: string, callId: string, budgetMs: number): void {const entry = this.pending.get(callId);if (!entry || entry.ghostId !== ghostId) return;+ if (!entry.timeoutExtensionsAllowed) return;entry.holds += 1;this.extendDeadline(callId, entry, Date.now() + budgetMs + HOLD_SETTLE_GRACE_MS);}@@ -246,7 +259,7 @@ export class GhostPipeDispatcher {if (!entry || entry.ghostId !== ghostId) return;entry.holds = Math.max(0, entry.holds - 1);if (entry.holds > 0) return;- const target = Math.max(entry.startedAt + this.baseTimeoutMs(), Date.now() + HOLD_SETTLE_GRACE_MS);+ const target = Math.max(entry.startedAt + entry.baseTimeoutMs, Date.now() + HOLD_SETTLE_GRACE_MS);if (target < entry.deadlineAt) {entry.deadlineAt = target;this.armTimer(callId, entry);@@ -270,7 +283,9 @@ export class GhostPipeDispatcher {if (entry.ghostId !== senderGhostId) {return { accepted: false, reason: '不是你的卷子' };}- this.extendDeadline(p.callId, entry, Date.now() + this.baseTimeoutMs());+ if (entry.timeoutExtensionsAllowed) {+ this.extendDeadline(p.callId, entry, Date.now() + entry.baseTimeoutMs);+ }return { accepted: true };}diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex 0ffedf33a9..4c88ecd81a 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@ -69,6 +69,23 @@ function row(id: string, createdAt: string, extra: Record<string, unknown> = {})return { id, clientId: `c-${id}`, role: 'user', content: `body-${id}`, createdAt, ...extra };}+async function seedMessageFiles(+ entries: Array<{ sessionId: string; messages: ReturnType<typeof row>[]; mtime: Date }>,+): Promise<void> {+ await fsp.mkdir(messagesDir(), { recursive: true });+ // These files are only the on-disk fixture for an eviction test. Going through+ // writeMessages for every filler would rescan the growing directory each time.+ for (const { sessionId, messages, mtime } of entries) {+ const file = path.join(messagesDir(), messageFileName('dev-1', sessionId));+ await fsp.writeFile(+ file,+ JSON.stringify({ version: 1, updatedAt: mtime.getTime(), messages }),+ 'utf8',+ );+ await fsp.utimes(file, mtime, mtime);+ }+}+beforeEach(() => {root = fs.mkdtempSync(path.join(os.tmpdir(), 'mirror-cache-test-'));});@@ -388,17 +405,19 @@ describe('readMessages / writeMessages', () => {it('超文件数上限 → 按 mtime 逐出最旧,新写入的留下', async () => {const c = cache();- for (let i = 0; i < MAX_MESSAGE_FILES + 5; i += 1) {- await c.writeMessages('dev-1', `sess-${i}`, [row(`m${i}`, '2026-01-01T00:00:00.000Z')]);- // mtime 分辨率有限:显式回拨保证 LRU 顺序确定(越早写的越旧)。- const file = path.join(messagesDir(), messageFileName('dev-1', `sess-${i}`));- const stamp = new Date(2026, 0, 1, 0, 0, i);- await fsp.utimes(file, stamp, stamp);- }+ await seedMessageFiles(+ Array.from({ length: MAX_MESSAGE_FILES }, (_, i) => ({+ sessionId: `sess-${i}`,+ messages: [row(`m${i}`, '2026-01-01T00:00:00.000Z')],+ // mtime 分辨率有限:显式回拨保证 LRU 顺序确定(越早写的越旧)。+ mtime: new Date(2026, 0, 1, 0, 0, i),+ })),+ );+ await c.writeMessages('dev-1', 'sess-new', [row('m-new', '2026-02-01T00:00:00.000Z')]);const files = await fsp.readdir(messagesDir());- expect(files.length).toBeLessThanOrEqual(MAX_MESSAGE_FILES);+ expect(files).toHaveLength(MAX_MESSAGE_FILES);expect(await c.readMessages('dev-1', 'sess-0')).toEqual([]);- expect(await c.readMessages('dev-1', `sess-${MAX_MESSAGE_FILES + 4}`)).not.toEqual([]);+ expect(await c.readMessages('dev-1', 'sess-new')).not.toEqual([]);});});@@ -470,9 +489,16 @@ describe('重复写入去重', () => {const old = new Date(2020, 0, 1);await fsp.utimes(victimFile, old, old);// 灌满到逐出:victim 是 mtime 最旧的那个,必然先走。- for (let i = 0; i < MAX_MESSAGE_FILES + 2; i += 1) {- await c.writeMessages('dev-1', `sess-${i}`, [row(`m${i}`, '2026-02-01T00:00:00.000Z')]);- }+ await seedMessageFiles(+ Array.from({ length: MAX_MESSAGE_FILES - 1 }, (_, i) => ({+ sessionId: `sess-${i}`,+ messages: [row(`m${i}`, '2026-02-01T00:00:00.000Z')],+ mtime: new Date(2026, 1, 1, 0, 0, i),+ })),+ );+ await c.writeMessages('dev-1', 'sess-trigger', [+ row('trigger', '2026-03-01T00:00:00.000Z'),+ ]);expect(fs.existsSync(victimFile)).toBe(false);await c.writeMessages('dev-1', 'sess-victim', victim);diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.tsindex 9e731d68e4..6f1cf55e0a 100644--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts@@ -1127,7 +1127,7 @@ describe('GoalController', () => {'```json\n{"goal_status":"continue","reason":"clarified with user","refined_objective":"梳理当前工作:列出待办并标注优先级"}\n```',tokens: 50,});- await tick();+ await vi.waitFor(() => expect(h.session.sends).toHaveLength(sendsAfterFirst + 1));const st = await h.storage.get('s1');expect(st?.objective).toBe('梳理当前工作:列出待办并标注优先级'); // 目标被确定性改写expect(st?.status).toBe('active');@@ -1137,7 +1137,6 @@ describe('GoalController', () => {h.userMessages.some((m) => m.updated === true && m.content === '梳理当前工作:列出待办并标注优先级'),).toBe(true);// 续轮已发,且用的是改写后的目标- expect(h.session.sends.length).toBe(sendsAfterFirst + 1);expect(h.session.sends.at(-1)?.content).toContain('梳理当前工作:列出待办并标注优先级');});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/atAgentCatalog.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/atAgentCatalog.test.tsnew file mode 100644index 0000000000..d1ba919d9f--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/atAgentCatalog.test.ts@@ -0,0 +1,131 @@+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import {+ finalizeAtProjectAgentResources,+ listAtProjectAgentResources,+ mergeAtProjectAgentResources,+ supportsAtProjectAgentResources,+} from '../atAgentCatalog.js';++const root = path.resolve('C:/workspace/demo');++describe('atAgentCatalog', () => {+ it('projects only safe project-scoped Claude Agent definitions', () => {+ const items = listAtProjectAgentResources([+ {+ engine: 'claude-code',+ kind: 'agent',+ scope: 'project',+ name: ' reviewer ',+ description: 'Reviews\nchanges',+ absolutePath: path.join(root, '.claude', 'agents', 'reviewer.md'),+ workingDir: root,+ },+ {+ engine: 'claude-code',+ kind: 'agent',+ scope: 'global',+ name: 'global-agent',+ absolutePath: path.resolve('C:/Users/demo/.claude/agents/global-agent.md'),+ },+ {+ engine: 'claude-code',+ kind: 'agent',+ scope: 'project',+ name: 'escape',+ absolutePath: path.resolve(root, '..', 'escape.md'),+ },+ ], root);++ expect(items).toEqual([{+ type: 'agent',+ name: 'reviewer',+ description: 'Reviews changes',+ relPath: '.claude/agents/reviewer.md',+ }]);+ });++ it('filters, deduplicates and keeps project agents ahead of workspace files', () => {+ const projectAgents = listAtProjectAgentResources([{+ engine: 'claude-code',+ kind: 'agent',+ scope: 'project',+ name: 'reviewer',+ absolutePath: path.join(root, '.claude', 'agents', 'reviewer.md'),+ }], root, 'review');+ const merged = mergeAtProjectAgentResources([+ projectAgents[0],+ { type: 'file', name: 'README.md', relPath: 'README.md' },+ ], projectAgents, 2);++ expect(merged).toEqual({+ items: [+ projectAgents[0],+ { type: 'file', name: 'README.md', relPath: 'README.md' },+ ],+ capped: false,+ });+ });++ it('exposes project Agents only for Claude Code', () => {+ expect(supportsAtProjectAgentResources('claude-code')).toBe(true);+ expect(supportsAtProjectAgentResources('codex')).toBe(false);+ expect(supportsAtProjectAgentResources('pi')).toBe(false);+ });++ it.each(['codex', 'pi'] as const)(+ 'hides Agent entries and their backing .claude files for %s',+ (agentKind) => {+ const result = finalizeAtProjectAgentResources(+ agentKind,+ [+ { type: 'dir', name: '.claude', relPath: '.claude' },+ { type: 'dir', name: 'agents', relPath: '.claude/agents' },+ {+ type: 'file',+ name: 'reviewer.md',+ relPath: '.claude\\agents\\reviewer.md',+ },+ {+ type: 'agent',+ name: 'reviewer',+ relPath: '.claude/agents/reviewer.md',+ },+ { type: 'file', name: 'README.md', relPath: 'README.md' },+ ],+ [{+ type: 'agent',+ name: 'reviewer',+ relPath: '.claude/agents/reviewer.md',+ }],+ );++ expect(result).toEqual({+ items: [+ { type: 'dir', name: '.claude', relPath: '.claude' },+ { type: 'file', name: 'README.md', relPath: 'README.md' },+ ],+ capped: false,+ });+ },+ );++ it('keeps Claude Code project Agents ahead of ordinary resources', () => {+ const agent = {+ type: 'agent' as const,+ name: 'reviewer',+ relPath: '.claude/agents/reviewer.md',+ };++ expect(finalizeAtProjectAgentResources(+ 'claude-code',+ [{ type: 'file', name: 'README.md', relPath: 'README.md' }],+ [agent],+ )).toEqual({+ items: [agent, { type: 'file', name: 'README.md', relPath: 'README.md' }],+ capped: false,+ });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/atContextCatalog.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/atContextCatalog.test.tsnew file mode 100644index 0000000000..74083d3262--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/atContextCatalog.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it, vi } from 'vitest';++import {+ listAtBrowserTabs,+ parseAtContextCatalogRequest,+ readAtDesktopWindows,+ resolveAtBrowserTabSessionId,+} from '../atContextCatalog.js';++describe('at context catalog', () => {+ it('derives browser-tab scope from the sender WebContents route', () => {+ const sessionUrl = 'file:///app/index.html#/cc-agent/session-1';+ expect(resolveAtBrowserTabSessionId('session-1', sessionUrl)).toBe('session-1');+ expect(resolveAtBrowserTabSessionId('session-2', sessionUrl)).toBeUndefined();+ expect(resolveAtBrowserTabSessionId(undefined, sessionUrl)).toBeUndefined();+ expect(resolveAtBrowserTabSessionId('session-1', 'file:///app/index.html#/settings')).toBeUndefined();+ expect(resolveAtBrowserTabSessionId('session-1', 'not a url')).toBeUndefined();+ });++ it('accepts the visible Orca worker but rejects non-session routes', () => {+ const workerUrl = 'https://localhost:5173/#/cc-agent/lead-1?worker=worker-1';+ expect(resolveAtBrowserTabSessionId('lead-1', workerUrl)).toBe('lead-1');+ expect(resolveAtBrowserTabSessionId('worker-1', workerUrl)).toBe('worker-1');+ expect(resolveAtBrowserTabSessionId('other', workerUrl)).toBeUndefined();+ expect(resolveAtBrowserTabSessionId(+ 'session-1',+ 'file:///app/index.html#/cc-agent/files/session-1',+ )).toBeUndefined();+ expect(resolveAtBrowserTabSessionId(+ 'session-1',+ 'file:///app/index.html#/cc-agent/orca/session-1',+ )).toBe('session-1');+ });++ it('reads only live public browser tabs from the requested task', () => {+ const registry = {+ listBySession: vi.fn(() => [+ { sessionId: 'session-1', tabId: 'tab-1', webContentsId: 1 },+ { sessionId: 'session-1', tabId: 'tab-2', webContentsId: 2 },+ ]),+ getWebContentsByTabId: vi.fn((tabId: string) => tabId === 'tab-1'+ ? {+ getURL: () => 'https://user:[email protected]/docs?token=private#section',+ getTitle: () => ' Docs\nHome ',+ }+ : { getURL: () => 'file:///secret', getTitle: () => 'Secret' }),+ };++ expect(listAtBrowserTabs(registry as never, 'session-1', 'docs', 10)).toEqual([+ {+ tabId: 'tab-1',+ title: 'Docs Home',+ url: 'https://example.com/docs',+ },+ ]);+ });++ it('sanitizes, filters and caps desktop windows', () => {+ const raw = {+ windows: [+ { window_id: 1, pid: 10, app_name: 'Code.exe', title: ' Cindy ' },+ { window_id: 2, pid: 11, app_name: 'Terminal.exe', title: 'PowerShell\nProject' },+ { window_id: 3, pid: 12, app_name: 'Hidden.exe', title: 'Hidden', is_visible: false },+ { window_id: 'bad', pid: 13, app_name: 'Bad.exe', title: 'Bad' },+ ],+ };++ expect(readAtDesktopWindows(raw, 'project', 1, 10)).toEqual([+ {+ windowId: 2,+ pid: 11,+ appName: 'Terminal.exe',+ title: 'PowerShell Project',+ },+ ]);+ });++ it('falls back to the application name instead of exposing a broken window title', () => {+ expect(readAtDesktopWindows({+ windows: [{ window_id: 7, pid: 17, app_name: 'chrome.exe', title: 'Issue ���' }],+ }, 'chrome', 10, 10)).toEqual([{+ windowId: 7,+ pid: 17,+ appName: 'chrome.exe',+ title: 'chrome.exe',+ }]);+ });++ it('hides Cindy, minimized and off-screen windows and de-duplicates stable ids', () => {+ expect(readAtDesktopWindows({+ windows: [+ { window_id: 1, pid: 11, app_name: 'Cindy.exe', title: 'Cindy' },+ { window_id: 2, pid: 12, app_name: 'electron.exe', title: 'CindyDev' },+ { window_id: 3, pid: 13, app_name: 'chrome.exe', title: 'Minimized', is_minimized: true },+ { window_id: 4, pid: 14, app_name: 'Code.exe', title: 'Off screen', is_on_screen: false },+ { window_id: 5, pid: 15, app_name: 'WindowsTerminal.exe', title: 'PowerShell' },+ { window_id: 5, pid: 15, app_name: 'WindowsTerminal.exe', title: 'Duplicate' },+ ],+ }, '', 10, 10)).toEqual([{+ windowId: 5,+ pid: 15,+ appName: 'WindowsTerminal.exe',+ title: 'PowerShell',+ }]);+ });++ it('rejects malformed requests and bounds optional text', () => {+ expect(parseAtContextCatalogRequest(null)).toBeNull();+ expect(parseAtContextCatalogRequest({ limit: 0 })).toBeNull();+ expect(parseAtContextCatalogRequest({+ sessionId: ' session-1 ',+ workingDir: ' D:\\repo ',+ query: 'x'.repeat(300),+ limit: 25,+ })).toEqual({+ sessionId: 'session-1',+ workingDir: 'D:\\repo',+ query: 'x'.repeat(200),+ limit: 25,+ });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/atAgentCatalog.ts b/apps/desktop/src/main/maker-ipc/atAgentCatalog.tsnew file mode 100644index 0000000000..63c92ec4f3--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/atAgentCatalog.ts@@ -0,0 +1,105 @@+import path from 'node:path';++import type { AgentCustomization, AgentKind, AtResourceItem } from '@cindy/maker-core';++function oneLine(value: unknown, maxLength: number): string {+ return typeof value === 'string'+ ? value.replace(/\s+/g, ' ').trim().slice(0, maxLength)+ : '';+}++function isInsideProjectAgentDirectory(workingDir: string, absolutePath: string): string | null {+ const relative = path.relative(workingDir, absolutePath);+ if (!relative || path.isAbsolute(relative)) return null;+ const relPath = relative.replace(/\\/g, '/');+ if (relPath === '..' || relPath.startsWith('../')) return null;+ if (!relPath.startsWith('.claude/agents/') || !relPath.endsWith('.md')) return null;+ return relPath;+}++/** Project Agent definitions are engine-independent @ candidates, even while Codex or Pi is active. */+export function listAtProjectAgentResources(+ items: readonly AgentCustomization[],+ workingDir: string,+ query?: string,+): AtResourceItem[] {+ if (!path.isAbsolute(workingDir)) return [];+ const normalizedQuery = oneLine(query, 500).toLowerCase();+ const resources: AtResourceItem[] = [];+ const seen = new Set<string>();++ for (const item of items) {+ if (+ item.engine !== 'claude-code'+ || item.kind !== 'agent'+ || item.scope !== 'project'+ ) continue;+ const relPath = isInsideProjectAgentDirectory(workingDir, item.absolutePath);+ const name = oneLine(item.name, 200);+ if (!relPath || !name || seen.has(relPath)) continue;+ const description = oneLine(item.description, 500);+ if (+ normalizedQuery+ && !name.toLowerCase().includes(normalizedQuery)+ && !relPath.toLowerCase().includes(normalizedQuery)+ && !description.toLowerCase().includes(normalizedQuery)+ ) continue;+ seen.add(relPath);+ resources.push({+ type: 'agent',+ name,+ relPath,+ ...(description ? { description } : {}),+ });+ }++ return resources;+}++export function mergeAtProjectAgentResources(+ base: readonly AtResourceItem[],+ projectAgents: readonly AtResourceItem[],+ cap?: number,+): { items: AtResourceItem[]; capped: boolean } {+ const merged: AtResourceItem[] = [];+ const seen = new Set<string>();+ for (const item of [...projectAgents, ...base]) {+ const key = `${item.type}:${item.relPath}`;+ if (seen.has(key)) continue;+ seen.add(key);+ merged.push(item);+ }+ const limit = typeof cap === 'number' && Number.isFinite(cap)+ ? Math.max(0, Math.floor(cap))+ : merged.length;+ return {+ items: merged.slice(0, limit),+ capped: merged.length > limit,+ };+}++/** Native project Agents are an executable capability of Claude Code only. */+export function supportsAtProjectAgentResources(agentKind: AgentKind): boolean {+ return agentKind === 'claude-code';+}++function isProjectAgentPath(relPath: string): boolean {+ const normalized = relPath.replace(/\\/g, '/').replace(/\/$/, '');+ return normalized === '.claude/agents' || normalized.startsWith('.claude/agents/');+}++/** Apply the engine boundary and keep Claude Agent definitions out of ordinary file results. */+export function finalizeAtProjectAgentResources(+ agentKind: AgentKind,+ base: readonly AtResourceItem[],+ projectAgents: readonly AtResourceItem[],+ cap?: number,+): { items: AtResourceItem[]; capped: boolean } {+ if (!supportsAtProjectAgentResources(agentKind)) {+ return {+ items: base.filter((item) => item.type !== 'agent' && !isProjectAgentPath(item.relPath)),+ capped: false,+ };+ }+ return mergeAtProjectAgentResources(base, projectAgents, cap);+}diff --git a/apps/desktop/src/main/maker-ipc/atContextCatalog.ts b/apps/desktop/src/main/maker-ipc/atContextCatalog.tsnew file mode 100644index 0000000000..6cbafda56d--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/atContextCatalog.ts@@ -0,0 +1,188 @@+import { BRAND_NAME } from '@cindy/maker-shared/branding';++import { atContextVisibleSessionIdsFromRendererUrl } from '../../shared/atContextRouteScope.js';+import type { TabRegistry } from '../rsb-browser-bridge/registry.js';++export interface AtBrowserTabCandidate {+ tabId: string;+ title: string;+ url: string;+}++export interface AtDesktopWindowCandidate {+ windowId: number;+ pid: number;+ appName: string;+ title: string;+}++/**+ * Browser-tab metadata is task-scoped. Main reads the sender WebContents URL+ * and derives the currently visible task from its HashRouter location; the+ * renderer payload is only an assertion. Missing, stale or mismatched values+ * fail closed instead of exposing another task's tabs.+ */+export function resolveAtBrowserTabSessionId(+ requestedSessionId: string | undefined,+ rendererUrl: string,+): string | undefined {+ if (!requestedSessionId) return undefined;+ return atContextVisibleSessionIdsFromRendererUrl(rendererUrl).has(requestedSessionId)+ ? requestedSessionId+ : undefined;+}++function oneLine(value: unknown, maxLength: number): string {+ if (typeof value !== 'string') return '';+ return value.replace(/\s+/g, ' ').trim().slice(0, maxLength);+}++function executableStem(value: string): string {+ const basename = value.replace(/\\/g, '/').split('/').pop() ?? value;+ return basename.replace(/\.(?:exe|app)$/i, '').trim().toLowerCase();+}++const CINDY_APP_STEMS = new Set([+ executableStem(BRAND_NAME),+ 'cindy',+ 'cindydev',+ 'cindyglobal',+ 'xdmaker',+ 'xdmakerdev',+]);++function isCindyWindow(appName: string, title: string): boolean {+ const appStem = executableStem(appName);+ if (CINDY_APP_STEMS.has(appStem)) return true;+ if (appStem !== 'electron') return false;+ const normalizedTitle = title.trim().toLowerCase();+ return normalizedTitle === BRAND_NAME.toLowerCase() || normalizedTitle === 'cindydev';+}++function searchable(values: string[], query: string): boolean {+ const needle = query.trim().toLowerCase();+ return !needle || values.some((value) => value.toLowerCase().includes(needle));+}++function publicReferenceUrl(value: string): string | null {+ try {+ const url = new URL(value);+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;+ // A tab id is sufficient for browser automation. Keep the readable page+ // location but never persist credentials, query tokens or fragments into+ // Composer drafts/messages.+ url.username = '';+ url.password = '';+ url.search = '';+ url.hash = '';+ return url.toString();+ } catch {+ return null;+ }+}++export function listAtBrowserTabs(+ registry: TabRegistry,+ sessionId: string | undefined,+ query: string,+ limit: number,+): AtBrowserTabCandidate[] {+ if (!sessionId) return [];+ const items: AtBrowserTabCandidate[] = [];+ for (const record of registry.listBySession(sessionId)) {+ const contents = registry.getWebContentsByTabId(record.tabId);+ if (!contents) continue;+ let rawUrl = '';+ let rawTitle = '';+ try {+ rawUrl = contents.getURL?.() ?? '';+ } catch {+ // Guest disappeared between registry lookup and metadata read.+ }+ try {+ rawTitle = contents.getTitle?.() ?? '';+ } catch {+ // Same race as URL above; an empty title has a safe URL fallback.+ }+ const url = publicReferenceUrl(oneLine(rawUrl, 4_096));+ if (!url) continue;+ const title = oneLine(rawTitle, 200) || url;+ const tabId = oneLine(record.tabId, 256);+ if (!tabId || !searchable([title, url], query)) continue;+ items.push({ tabId, title, url });+ if (items.length >= limit) break;+ }+ return items;+}++function objectValue(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null;+}++export function readAtDesktopWindows(+ value: unknown,+ query: string,+ limit: number,+ ownPid = process.pid,+): AtDesktopWindowCandidate[] {+ const root = objectValue(value);+ const rows = root && Array.isArray(root.windows) ? root.windows : [];+ const items: AtDesktopWindowCandidate[] = [];+ const seenWindows = new Set<string>();+ for (const row of rows) {+ const candidate = objectValue(row);+ if (+ !candidate+ || candidate.is_visible === false+ || candidate.is_minimized === true+ || candidate.is_on_screen === false+ ) continue;+ const windowId = Number(candidate.window_id ?? candidate.hwnd);+ const pid = Number(candidate.pid);+ if (+ !Number.isSafeInteger(windowId)+ || windowId < 0+ || !Number.isSafeInteger(pid)+ || pid <= 0+ || pid === ownPid+ ) continue;+ const appName = oneLine(candidate.app_name, 200) || `PID ${pid}`;+ const rawTitle = oneLine(candidate.title, 200);+ if (isCindyWindow(appName, rawTitle)) continue;+ const title = rawTitle.includes('\uFFFD') ? appName : rawTitle;+ if (!title || !searchable([title, appName], query)) continue;+ const windowKey = `${pid}:${windowId}`;+ if (seenWindows.has(windowKey)) continue;+ seenWindows.add(windowKey);+ items.push({ windowId, pid, appName, title });+ if (items.length >= limit) break;+ }+ return items;+}++export function parseAtContextCatalogRequest(value: unknown): {+ sessionId?: string;+ workingDir?: string;+ query: string;+ limit: number;+} | null {+ const candidate = objectValue(value);+ if (!candidate) return null;+ const sessionId = oneLine(candidate.sessionId, 256);+ const workingDir = typeof candidate.workingDir === 'string'+ ? candidate.workingDir.trim().slice(0, 32_768)+ : '';+ const query = oneLine(candidate.query, 200);+ const requestedLimit = Number(candidate.limit ?? 40);+ if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 1 || requestedLimit > 50) {+ return null;+ }+ return {+ ...(sessionId ? { sessionId } : {}),+ ...(workingDir ? { workingDir } : {}),+ query,+ limit: requestedLimit,+ };+}diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 76e1513a45..c4d5ea8026 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -596,6 +596,8 @@ export const MAKER_INVOKE = {ANDROID_PREPARE_ADB: 'maker:android:prepare-adb',// Local desktop computer-use driver detection for Settings →「电脑使用」COMPUTER_STATUS: 'maker:computer:status',+ // Read-only Composer `@` candidates: current-task browser tabs + OS windows.+ AT_CONTEXT_LIST: 'maker:at-context:list',// cua-driver installer for direct computer control.COMPUTER_INSTALL_DRIVER: 'maker:computer:install-driver',// Quiet cua-driver update check (Settings-open triggered only, never polls).diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4db33a8093..19c0119ecb 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -106,9 +106,11 @@ import {getComputerDriverStatus,grantComputerDriverPermissions,installComputerDriver,+ listComputerWindowsForAtMention,pauseComputerDriverPermissionProbe,updateComputerDriver,} from '../mcp-integrations/computer.js';+import { getRsbBrowserBridge } from '../rsb-browser-bridge/index.js';import {closeComputerPermissionGuideWindow,finishComputerPermissionAppDrag,@@ -122,6 +124,17 @@ import {} from '../computer-permission-guide/window.js';import { parseComputerPermissionGrantRequest } from '../computer-permission-guide/request.js';import { shouldUseComputerPermissionGuide } from './computerPermissionGuideEligibility.js';+import {+ listAtBrowserTabs,+ parseAtContextCatalogRequest,+ readAtDesktopWindows,+ resolveAtBrowserTabSessionId,+} from './atContextCatalog.js';+import {+ finalizeAtProjectAgentResources,+ listAtProjectAgentResources,+ supportsAtProjectAgentResources,+} from './atAgentCatalog.js';import * as imageCacheStore from '../imageCacheStore.js';import { collectCindyMediaUrls, commitChatImageUrls } from '../cindy-media/chatAttachments.js';import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';@@ -4967,8 +4980,39 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)try {const resourceParams = params as { workingDir: string; cap?: number; query?: string };await prepareProjectSkillLinksFailSoft(resourceParams?.workingDir);- const result = await maker.scanAtResources(requireAgentKind(agentKind), resourceParams);- return { success: true, ...result };+ const kind = requireAgentKind(agentKind);+ const includeProjectAgents = supportsAtProjectAgentResources(kind);+ const [result, customizationResult] = await Promise.all([+ maker.scanAtResources(kind, resourceParams),+ includeProjectAgents+ ? maker.listCustomizations({+ agentKind: 'claude-code',+ workingDirs: [resourceParams.workingDir],+ kinds: ['agent'],+ }).catch((err: unknown) => {+ log.warn('Project Agent @ catalog failed; keeping workspace resources available', err);+ return null;+ })+ : Promise.resolve(null),+ ]);+ const projectAgents = customizationResult+ ? listAtProjectAgentResources(+ customizationResult.items,+ resourceParams.workingDir,+ resourceParams.query,+ )+ : [];+ const merged = finalizeAtProjectAgentResources(+ kind,+ result.items,+ projectAgents,+ resourceParams.cap,+ );+ return {+ success: true,+ items: merged.items,+ truncated: result.truncated || merged.capped,+ };} catch (err) {return {success: false,@@ -4979,6 +5023,50 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}});+ ipcMain.handle(MAKER_INVOKE.AT_CONTEXT_LIST, async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);+ const request = parseAtContextCatalogRequest(payload);+ if (!request) {+ throwIpcError('INVALID_PARAMS', 'Invalid @ context catalog request');+ }++ const unavailable: Array<'browser-tabs' | 'desktop-windows'> = [];+ let browserTabs: ReturnType<typeof listAtBrowserTabs> = [];+ let desktopWindows: ReturnType<typeof readAtDesktopWindows> = [];+ try {+ const browserTabSessionId = resolveAtBrowserTabSessionId(+ request.sessionId,+ event.sender.getURL(),+ );+ browserTabs = listAtBrowserTabs(+ getRsbBrowserBridge(),+ browserTabSessionId,+ request.query,+ request.limit,+ );+ } catch (err) {+ unavailable.push('browser-tabs');+ log.warn('@ context browser-tab catalog failed', err);+ }++ // Computer Use is machine-scoped. Do not let renderer-provided project+ // metadata appear to participate in its enablement decision.+ if (request.query && getPluginRegistry().isEnabled('computer')) {+ try {+ desktopWindows = readAtDesktopWindows(+ await listComputerWindowsForAtMention(),+ request.query,+ request.limit,+ );+ } catch (err) {+ unavailable.push('desktop-windows');+ log.warn('@ context desktop-window catalog failed', err);+ }+ }++ return { success: true, browserTabs, desktopWindows, unavailable };+ });+ipcMain.handle(MAKER_INVOKE.LIST_CUSTOMIZATIONS, async (_e, params: unknown) => {try {const p = (params ?? {}) as {diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.tsindex 44bb392241..8d059434a0 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts@@ -88,9 +88,11 @@ import {getComputerDriverStatus,grantComputerDriverPermissions,installComputerDriver,+ listComputerWindowsForAtMention,pauseComputerDriverPermissionProbe,pickLatestCuaDriverVersion,resetComputerDriverPermissionProbeCacheForTests,+ resetAtMentionWindowCacheForTests,resetComputerDriverUpdateStateForTests,runProcessWithActivityTimeout,sampleInstallProcessTree,@@ -298,6 +300,7 @@ describe('computer mcp integration', () => {setPlatform(originalPlatform);await cleanupAllComputerDriverSessions();resetComputerDriverPermissionProbeCacheForTests();+ resetAtMentionWindowCacheForTests();existsSyncMock.mockReset().mockReturnValue(false);spawnMock.mockReset();driverStdinWrites.length = 0;@@ -526,6 +529,7 @@ describe('computer mcp integration', () => {const scriptArgs = spawnMock.mock.calls.find(isWin32FallbackSpawnCall)?.[1] as unknown[] | undefined;const script = scriptArgs?.find((part): part is string => typeof part === 'string' && part.includes('XdtWin32WindowSnapshot'));+ expect(script).toContain('[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)');expect(script).toContain('$procId');expect(script).not.toMatch(/\$pid\b/i);});@@ -2540,6 +2544,58 @@ describe('computer mcp integration', () => {);});+ it('bootstraps macOS @ windows from the passive permission status after restart', async () => {+ setPlatform('darwin');+ mockDriverSpawn({ stdout: 'cua-driver 0.12.2\n' });+ mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n pid: 4242\n' });+ mockDriverSpawn({+ stdout:+ '{"accessibility":true,"screen_recording":true,"screen_recording_capturable":true,"source":{"attribution":"driver-daemon"}}\n',+ });+ mockDriverSpawn({ stdout: '{"ok":true,"windows":[{"window_id":7,"pid":70}]}\n' });++ await expect(listComputerWindowsForAtMention()).resolves.toEqual({+ ok: true,+ windows: [{ window_id: 7, pid: 70 }],+ });+ expect(spawnMock.mock.calls.map((call) => call[1])).toEqual([+ ['--version'],+ ['status'],+ ['permissions', 'status', '--json'],+ ['call', 'list_windows'],+ ]);+ });++ it('keeps macOS @ windows hidden without probing on older drivers', async () => {+ setPlatform('darwin');+ mockDriverSpawn({ stdout: 'cua-driver 0.12.1\n' });+ mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n pid: 4242\n' });++ await expect(listComputerWindowsForAtMention()).resolves.toEqual({+ ok: true,+ windows: [],+ });+ expect(spawnMock.mock.calls.map((call) => call[1])).toEqual([+ ['--version'],+ ['status'],+ ]);+ });++ it('does not autostart the macOS permission daemon from the @ palette', async () => {+ setPlatform('darwin');+ mockDriverSpawn({ stdout: 'cua-driver 0.12.2\n' });+ mockDriverSpawn({ stderr: 'Cua Driver daemon is not running\n', exitCode: 1 });++ await expect(listComputerWindowsForAtMention()).resolves.toEqual({+ ok: true,+ windows: [],+ });+ expect(spawnMock.mock.calls.map((call) => call[1])).toEqual([+ ['--version'],+ ['status'],+ ]);+ });+it('can force a macOS permission probe even when the daemon status is stopped', async () => {if (process.platform !== 'darwin') return;diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.tsindex 9e53958d5c..2c6870c203 100644--- a/apps/desktop/src/main/mcp-integrations/computer.ts+++ b/apps/desktop/src/main/mcp-integrations/computer.ts@@ -28,6 +28,7 @@ const CALL_TIMEOUT_MS = 45_000;const LIGHTWEIGHT_CALL_TIMEOUT_MS = 10_000;const CLI_FALLBACK_TIMEOUT_MS = 8_000;const WINDOWS_WIN32_FALLBACK_TIMEOUT_MS = 4_000;+const AT_MENTION_WINDOW_CACHE_MS = 3_000;// 安装/更新超时按「活动」而非总时长计:上游安装脚本要从 GitHub Releases// 下载数十 MB 二进制,慢网下总时长不可预算(2026-07-02 实测固定 180s 超时// 误杀安装、还把内层脚本的安装锁留成死锁)。活动信号 = stdout/stderr 输出@@ -154,6 +155,8 @@ export function getComputerDriverAppBundlePath(): string | null {const WINDOWS_WIN32_WINDOW_SNAPSHOT_SCRIPT = String.raw`$ErrorActionPreference = 'Stop'+[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)+$OutputEncoding = [Console]::OutputEncodingAdd-Type -TypeDefinition @'using System;using System.Text;@@ -309,6 +312,8 @@ let cachedProcessSnapshot: {result: ProcessSnapshotResult;} | null = null;+let cachedAtMentionWindows: { expiresAt: number; result: unknown } | null = null;+function clearProcessSnapshotCache(): void {cachedProcessSnapshot = null;}@@ -1762,6 +1767,66 @@ async function buildWindowsWin32ListAppsFallback(): Promise<unknown> {};}+/**+ * Cheap, read-only window catalog for the Composer's `@` palette.+ *+ * Windows uses the bounded Win32 snapshot directly instead of starting a CUA+ * MCP session. On macOS a cold app cache first refreshes permission state via+ * the driver's strictly read-only status command; unsupported/older drivers+ * fail closed, so opening the palette can never become a permission prompt.+ * Results are briefly cached because the palette rescans while the user types.+ */+export async function listComputerWindowsForAtMention(): Promise<unknown> {+ const now = Date.now();+ if (cachedAtMentionWindows && cachedAtMentionWindows.expiresAt > now) {+ return cachedAtMentionWindows.result;+ }++ let result: unknown;+ if (process.platform === 'win32') {+ result = await buildWindowsWin32ListWindowsFallback({});+ } else {+ if (process.platform === 'darwin' && cachedPermissionProbe === null) {+ // App restarts clear the in-memory permission cache even when TCC still+ // grants Accessibility. Bootstrap it once through the read-only status+ // command; older drivers fail closed without probing or prompting.+ await getComputerDriverStatus({+ passivePermissionProbeOnly: true,+ });+ }+ if (+ process.platform === 'darwin'+ && cachedPermissionProbe?.state.accessibility !== 'granted'+ ) {+ result = { ok: true, windows: [] };+ } else {+ const response = await runDriver(+ ['call', 'list_windows'],+ WINDOWS_WIN32_FALLBACK_TIMEOUT_MS,+ { stdin: '{}\n' },+ );+ if (response.exitCode !== 0) {+ throw new ComputerDriverError(+ response.stderr.trim()+ || response.stdout.trim()+ || `cua-driver call list_windows exited ${response.exitCode}`,+ );+ }+ result = parseJsonOutput(response.stdout);+ }+ }++ cachedAtMentionWindows = {+ expiresAt: Date.now() + AT_MENTION_WINDOW_CACHE_MS,+ result,+ };+ return result;+}++export function resetAtMentionWindowCacheForTests(): void {+ cachedAtMentionWindows = null;+}+function normalizeToolArgsForDriver(name: ComputerMcpToolName,args: Record<string, unknown>,diff --git a/apps/desktop/src/main/nativeAtResourcePicker.ts b/apps/desktop/src/main/nativeAtResourcePicker.tsnew file mode 100644index 0000000000..1949d6fcae--- /dev/null+++ b/apps/desktop/src/main/nativeAtResourcePicker.ts@@ -0,0 +1,39 @@+import type { OpenDialogOptions, OpenDialogReturnValue } from 'electron';++export type NativeAtResourceKind = 'file' | 'directory';++export interface NativeAtResourcePickerResult {+ path: string | null;+ kind: NativeAtResourceKind | null;+}++interface NativeAtResourcePickerDeps {+ platform: NodeJS.Platform;+ showOpenDialog: (options: OpenDialogOptions) => Promise<OpenDialogReturnValue>;+ isDirectory: (selectedPath: string) => boolean;+}++/**+ * Open the platform-native picker used by the fixed @ resource action.+ * macOS supports a combined file/directory dialog; Windows and Linux do not,+ * so those platforms intentionally match Codex by opening a file dialog.+ */+export async function pickNativeAtResource(+ deps: NativeAtResourcePickerDeps,+ defaultPath?: string,+): Promise<NativeAtResourcePickerResult> {+ const properties: NonNullable<OpenDialogOptions['properties']> =+ deps.platform === 'darwin'+ ? ['openFile', 'openDirectory']+ : ['openFile'];+ const result = await deps.showOpenDialog({+ properties,+ ...(defaultPath ? { defaultPath } : {}),+ });+ const selectedPath = result.canceled ? undefined : result.filePaths[0];+ if (!selectedPath) return { path: null, kind: null };+ return {+ path: selectedPath,+ kind: deps.isDirectory(selectedPath) ? 'directory' : 'file',+ };+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 3f8e134128..af96b0206e 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -914,6 +914,22 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 配置就绪检查(插件页「使用」前置门;main 现查凭证/账号/连接/kv)。 */setupStatus: (id: string): Promise<unknown> =>ipcRenderer.invoke('ghosts:setup-status', id),+ listAtResourceProviders: (params: { sessionId?: string; workingDir?: string }): Promise<{+ items: Array<{ ghostId: string; name: string; description?: string }>;+ }> => ipcRenderer.invoke('ghosts:at-resource-providers:list', params),+ queryAtResources: (params: {+ ghostId: string;+ sessionId?: string;+ workingDir?: string;+ query?: string;+ limit?: number;+ }): Promise<{+ success: boolean;+ error?: string;+ pluginName?: string;+ items: Array<{ id: string; label: string; description?: string; href: string }>;+ truncated: boolean;+ }> => ipcRenderer.invoke('ghosts:at-resources:query', params),install: (lizFilePath: string,opts: { enable?: boolean; expectedPackageSha256: string },@@ -2671,6 +2687,12 @@ contextBridge.exposeInMainWorld('electronAPI', {success: boolean;path: string | null;}> => ipcRenderer.invoke('dialog:show-open-file', params ?? {}),+ /** 打开 @ 资源系统选择器;macOS 可选文件或目录,Windows/Linux 选择文件。 */+ showOpenResource: (params?: { defaultPath?: string }): Promise<{+ success: true;+ path: string | null;+ kind: 'file' | 'directory' | null;+ }> => ipcRenderer.invoke('dialog:show-open-resource', params ?? {}),},// Open URL in system default browser@@ -4601,6 +4623,23 @@ contextBridge.exposeInMainWorld('electronAPI', {truncated?: boolean;}> => ipcRenderer.invoke('maker:scan-at-resources', agentKind, params),+ listAtContext: (params: {+ sessionId?: string;+ workingDir?: string;+ query?: string;+ limit?: number;+ }): Promise<{+ success: true;+ browserTabs: Array<{ tabId: string; title: string; url: string }>;+ desktopWindows: Array<{+ windowId: number;+ pid: number;+ appName: string;+ title: string;+ }>;+ unavailable: Array<'browser-tabs' | 'desktop-windows'>;+ }> => ipcRenderer.invoke('maker:at-context:list', params),+createSession: (opts: {/** 可选: 复用外部 sessionId(本端 chat 用 local-db:sessions:create 拿到的 id) */id?: string;diff --git a/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts b/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.tsnew file mode 100644index 0000000000..9444e05d0f--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts@@ -0,0 +1,30 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++const chatInputSource = readFileSync(+ resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),+ 'utf8',+);++describe('@ native resource picker wiring', () => {+ it('opens the native picker from the fixed resource row', () => {+ expect(chatInputSource).toContain("selectedItem.type === 'file-picker'");+ expect(chatInputSource).toContain('window.electronAPI.dialog.showOpenResource(');+ expect(chatInputSource).toContain(+ 'filePickerEnabled={!!workingDir && localAttachmentPickerEnabled}',+ );+ });++ it('does not fall back to the removed in-composer file browser scope', () => {+ expect(chatInputSource).not.toContain('atFileBrowserScopeFrom');+ expect(chatInputSource).not.toContain('setAtFileBrowserScopeFrom');+ });++ it('drops a late picker result after the composer target changes', () => {+ expect(chatInputSource).toContain('const originDoc = editor.state.doc;');+ expect(chatInputSource).toContain('const originStorageKey = storageKey;');+ expect(chatInputSource).toContain('isAtResourceInsertTargetCurrent(');+ expect(chatInputSource).toContain('currentStorageKeyRef.current');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/atResourceService.test.ts b/apps/desktop/src/renderer/__tests__/atResourceService.test.tsnew file mode 100644index 0000000000..6e66d2ce49--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/atResourceService.test.ts@@ -0,0 +1,625 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ parseBrowserTabReferenceHref,+ parseDesktopWindowReferenceHref,+} from '@cindy/maker-shared/agent-input-projection';++import {+ AT_FILE_PICKER_RESOURCE,+ createAtResourceFromNativePath,+ filterAtResources,+ getAtDirectoryCompletionQuery,+ mergeAtResourceItems,+ scanAtResources,+ scanPluginAtResources,+} from '@/lib/atResourceService';++function stubApi(options: {+ workspace?: unknown;+ context?: unknown;+ tasks?: unknown;+ taskSearch?: unknown;+ deviceTasks?: unknown;+ deviceTaskSearch?: unknown;+ deviceTaskSearchError?: Error;+ workspaceError?: Error;+ contextError?: Error;+ taskError?: Error;+ pluginProviders?: unknown;+ pluginResources?: unknown;+}) {+ vi.stubGlobal('window', {+ electronAPI: {+ maker: {+ scanAtResources: options.workspaceError+ ? vi.fn().mockRejectedValue(options.workspaceError)+ : vi.fn().mockResolvedValue(options.workspace),+ listAtContext: options.contextError+ ? vi.fn().mockRejectedValue(options.contextError)+ : vi.fn().mockResolvedValue(options.context),+ },+ deviceLink: {+ invoke: vi.fn((_deviceId: string, channel: string) => {+ if (channel === 'local-db:sessions:list') return Promise.resolve(options.deviceTasks);+ if (channel === 'local-db:conversations:search') {+ if (options.deviceTaskSearchError) return Promise.reject(options.deviceTaskSearchError);+ return Promise.resolve(options.deviceTaskSearch);+ }+ return Promise.resolve(options.workspace);+ }),+ },+ localDb: {+ sessions: {+ list: options.taskError+ ? vi.fn().mockRejectedValue(options.taskError)+ : vi.fn().mockResolvedValue(options.tasks),+ },+ conversations: {+ search: options.taskError+ ? vi.fn().mockRejectedValue(options.taskError)+ : vi.fn().mockResolvedValue(options.taskSearch),+ },+ },+ ghosts: {+ listAtResourceProviders: vi.fn().mockResolvedValue(+ options.pluginProviders ?? { items: [] },+ ),+ queryAtResources: vi.fn().mockResolvedValue(+ options.pluginResources ?? { success: true, items: [], truncated: false },+ ),+ },+ },+ });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, resolve, reject };+}++describe('filterAtResources', () => {+ const items = [+ AT_FILE_PICKER_RESOURCE,+ { type: 'file' as const, name: 'README.md', relPath: 'README.md' },+ { type: 'dir' as const, name: 'apps', relPath: 'apps' },+ { type: 'session' as const, name: 'Release planning', relPath: 'cindy://session/1' },+ { type: 'agent' as const, name: 'reviewer', relPath: '.claude/agents/reviewer.md' },+ { type: 'plugin-provider' as const, name: 'Issues', relPath: 'issues' },+ ];++ it('hides files and directories until the user types a query', () => {+ expect(filterAtResources(items, '').map((item) => item.type)).toEqual([+ 'file-picker',+ 'agent',+ 'plugin-provider',+ ]);+ });++ it('keeps each empty-query source compact', () => {+ const providers = Array.from({ length: 5 }, (_, index) => ({+ type: 'plugin-provider' as const,+ name: `Provider ${index}`,+ relPath: `provider-${index}`,+ }));++ expect(filterAtResources(providers, '')).toHaveLength(3);+ });++ it('shows browser tabs immediately but searches desktop windows on demand', () => {+ const contextual = [+ { type: 'browser-tab' as const, name: 'Docs', relPath: 'cindy://browser-tab/tab-1' },+ { type: 'desktop-window' as const, name: 'Editor', relPath: 'cindy://desktop-window/1/2' },+ ];++ expect(filterAtResources(contextual, '').map((item) => item.type)).toEqual([+ 'browser-tab',+ ]);+ expect(filterAtResources(contextual, 'editor').map((item) => item.type)).toEqual([+ 'desktop-window',+ ]);+ });++ it('searches historical tasks after the user types a query', () => {+ expect(filterAtResources(items, 'release').map((item) => item.type)).toEqual([+ 'session',+ ]);+ });++ it('searches files and directories and caps the global result list', () => {+ const files = Array.from({ length: 12 }, (_, index) => ({+ type: 'file' as const,+ name: `file-${index}.ts`,+ relPath: `src/file-${index}.ts`,+ }));+ const results = filterAtResources(files, 'file');++ expect(results).toHaveLength(8);+ expect(results.every((item) => item.type === 'file')).toBe(true);+ });+});++describe('createAtResourceFromNativePath', () => {+ it('stores project files as workdir-relative POSIX paths on Windows', () => {+ expect(createAtResourceFromNativePath(+ 'D:\\Repo\\src\\main.ts',+ 'file',+ 'd:\\repo',+ )).toEqual({+ type: 'file',+ name: 'main.ts',+ relPath: 'src/main.ts',+ });+ });++ it('keeps files outside the workdir as absolute paths', () => {+ expect(createAtResourceFromNativePath(+ 'D:\\Downloads\\notes.txt',+ 'file',+ 'D:\\Repo',+ )).toEqual({+ type: 'file',+ name: 'notes.txt',+ relPath: 'D:\\Downloads\\notes.txt',+ });+ });++ it('creates directory resources selected in the macOS picker', () => {+ expect(createAtResourceFromNativePath('/repo/docs', 'directory', '/repo')).toEqual({+ type: 'dir',+ name: 'docs',+ relPath: 'docs',+ });+ });++ it('rejects an empty picker result', () => {+ expect(createAtResourceFromNativePath(' ', 'file', 'D:\\Repo')).toBeNull();+ });+});++describe('getAtDirectoryCompletionQuery', () => {+ it('turns a directory into a path prefix for continued search', () => {+ expect(getAtDirectoryCompletionQuery({+ type: 'dir',+ name: 'desktop',+ relPath: 'apps/desktop',+ })).toBe('apps/desktop/');+ });++ it('falls back to a mention for directory paths that cannot stay in an @ query', () => {+ expect(getAtDirectoryCompletionQuery({+ type: 'dir',+ name: 'design notes',+ relPath: 'docs/design notes',+ })).toBeNull();+ expect(getAtDirectoryCompletionQuery({+ type: 'dir',+ name: 'design notes',+ relPath: 'docs/design notes',+ }, true)).toBe('docs/design notes/');+ });+});++describe('mergeAtResourceItems', () => {+ it('keeps previous candidates while preferring refreshed duplicates', () => {+ const previous = [+ { type: 'dir' as const, name: 'prompts', relPath: 'packages/prompts' },+ { type: 'file' as const, name: 'profile.ts', relPath: 'src/profile.ts' },+ ];+ const incoming = [+ { type: 'dir' as const, name: 'prompts', relPath: 'packages/prompts', description: 'new' },+ { type: 'session' as const, name: 'PR review', relPath: 'cindy://session/pr-review' },+ ];++ expect(mergeAtResourceItems(previous, incoming)).toEqual([+ incoming[0],+ incoming[1],+ previous[1],+ ]);+ });+});++describe('scanAtResources context providers', () => {+ it('emits workspace results without waiting for slower context providers', async () => {+ const slowContext = deferred<{+ success: boolean;+ browserTabs: never[];+ desktopWindows: never[];+ unavailable: never[];+ }>();+ stubApi({+ workspace: {+ success: true,+ items: [{ type: 'dir', name: 'prompts', relPath: 'packages/prompts' }],+ },+ context: slowContext.promise,+ });+ const partials: Array<{ items: Array<{ type: string; name: string }> }> = [];++ const resultPromise = scanAtResources('D:\\repo', 'codex', 2000, 'pr', undefined, {+ includeLocalContext: true,+ onPartial: (result) => partials.push(result),+ });+ await vi.waitFor(() => {+ expect(partials.some((result) => result.items.some((item) => item.name === 'prompts')))+ .toBe(true);+ });++ slowContext.resolve({+ success: true,+ browserTabs: [],+ desktopWindows: [],+ unavailable: [],+ });+ const result = await resultPromise;+ expect(result.items).toEqual(expect.arrayContaining([+ expect.objectContaining({ type: 'dir', name: 'prompts' }),+ ]));+ });++ it('prepends browser tabs and desktop windows without treating them as files', async () => {+ stubApi({+ workspace: {+ success: true,+ items: [{ type: 'file', name: 'README.md', relPath: 'README.md' }],+ },+ context: {+ success: true,+ browserTabs: [{ tabId: 'tab-1', title: 'Docs', url: 'https://example.com/docs' }],+ desktopWindows: [+ {+ windowId: 21,+ pid: 10,+ appName: 'chrome.exe',+ title: 'Docs - Google Chrome',+ },+ {+ windowId: 22,+ pid: 11,+ appName: 'Code.exe',+ title: 'Cindy',+ },+ ],+ unavailable: [],+ },+ });++ const result = await scanAtResources('D:\\repo', 'codex', 2000, undefined, undefined, {+ sessionId: 'session-1',+ includeLocalContext: true,+ });++ expect(result.success).toBe(true);+ expect(result.items.map((item) => item.type)).toEqual([+ 'browser-tab',+ 'desktop-window',+ 'file',+ ]);+ expect(result.items[0].relPath).toBe(+ 'cindy://browser-tab/tab-1?url=https%3A%2F%2Fexample.com%2Fdocs',+ );+ expect(result.items[1].relPath).toBe(+ 'cindy://desktop-window/11/22?app=Code.exe',+ );+ });++ it('strictly encodes Markdown delimiters in context reference links', async () => {+ const tabId = "tab-('!*)";+ const url = "https://example.com/docs_(v1)!'";+ const appName = "Cindy ('!*)";+ stubApi({+ workspace: { success: true, items: [] },+ context: {+ success: true,+ browserTabs: [{ tabId, title: 'Docs', url }],+ desktopWindows: [{ windowId: 22, pid: 11, appName, title: 'Cindy' }],+ unavailable: [],+ },+ });++ const result = await scanAtResources('D:\\repo', 'codex', 2000, undefined, undefined, {+ sessionId: 'session-1',+ includeLocalContext: true,+ });+ const browserTab = result.items.find((item) => item.type === 'browser-tab');+ const desktopWindow = result.items.find((item) => item.type === 'desktop-window');++ expect(browserTab?.relPath).not.toMatch(/[!'()*]/);+ expect(desktopWindow?.relPath).not.toMatch(/[!'()*]/);+ expect(parseBrowserTabReferenceHref(browserTab?.relPath ?? '')).toEqual({ tabId, url });+ expect(parseDesktopWindowReferenceHref(desktopWindow?.relPath ?? '')).toEqual({+ pid: 11,+ windowId: 22,+ appName,+ });+ });++ it('keeps local context when the workspace provider fails', async () => {+ stubApi({+ workspaceError: new Error('workspace unavailable'),+ context: {+ success: true,+ browserTabs: [{ tabId: 'tab-1', title: 'Docs', url: 'https://example.com' }],+ desktopWindows: [],+ unavailable: [],+ },+ });++ const result = await scanAtResources('D:\\repo', 'codex', 2000, undefined, undefined, {+ sessionId: 'session-1',+ includeLocalContext: true,+ });++ expect(result.success).toBe(true);+ expect(result.items).toHaveLength(1);+ expect(result.items[0].type).toBe('browser-tab');+ });++ it('keeps workspace resources when the local context provider fails', async () => {+ stubApi({+ workspace: {+ success: true,+ items: [{ type: 'dir', name: 'src', relPath: 'src' }],+ },+ contextError: new Error('context unavailable'),+ });++ const result = await scanAtResources('D:\\repo', 'codex', 2000, undefined, undefined, {+ includeLocalContext: true,+ });++ expect(result.success).toBe(true);+ expect(result.items.map((item) => item.type)).toEqual(['dir']);+ });++ it('lists only active historical tasks without a workspace', async () => {+ stubApi({+ tasks: [+ {+ id: 'current',+ title: 'Current',+ status: 'active',+ userSendAt: '2026-08-03T00:00:00.000Z',+ },+ {+ id: 'history-1',+ title: ' Release\nplanning ',+ status: 'active',+ userSendAt: '2026-08-02T00:00:00.000Z',+ summary: 'Plan\nthe release',+ workingDir: 'D:\\repo',+ },+ {+ id: 'archived-history',+ title: 'Archived release planning',+ status: 'archived',+ userSendAt: '2026-08-01T00:00:00.000Z',+ },+ {+ id: 'empty-draft',+ title: 'Empty',+ status: 'active',+ userSendAt: null,+ _count: { messages: 0 },+ },+ ],+ });++ const result = await scanAtResources('', 'codex', 2000, undefined, undefined, {+ sessionId: 'current',+ includeTaskHistory: true,+ });++ expect(result).toMatchObject({+ success: true,+ items: [+ {+ type: 'session',+ name: 'Release planning',+ relPath: 'cindy://session/history-1',+ description: 'Plan the release',+ },+ ],+ });+ expect(window.electronAPI.localDb.sessions.list).toHaveBeenCalledWith(100, 'active');+ });++ it('lists device-link task history on the controlled device and freezes its device id', async () => {+ stubApi({+ deviceTasks: [{+ id: 'remote-history',+ title: 'Remote task',+ status: 'active',+ userSendAt: '2026-08-03T00:00:00.000Z',+ }],+ });++ const result = await scanAtResources('', 'codex', 2000, undefined, 'device-1', {+ includeTaskHistory: true,+ });++ expect(result.items).toMatchObject([+ {+ type: 'session',+ relPath: 'cindy://session/remote-history?device=device-1',+ },+ ]);+ expect(window.electronAPI.deviceLink.invoke).toHaveBeenCalledWith(+ 'device-1',+ 'local-db:sessions:list',+ [100, 'active'],+ );+ });++ it('searches all active task history through the indexed conversation search', async () => {+ stubApi({+ taskSearch: {+ query: '未命名',+ results: [{+ session: {+ id: 'older-than-sidebar-cap',+ title: 'New Maker',+ status: 'active',+ workingDir: 'D:\\repo',+ },+ contentHit: null,+ }],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ },+ });++ const result = await scanAtResources('', 'codex', 2000, '未命名', undefined, {+ includeTaskHistory: true,+ unnamedLabel: '未命名任务',+ });++ expect(result.items).toMatchObject([{+ type: 'session',+ name: '未命名任务',+ relPath: 'cindy://session/older-than-sidebar-cap',+ }]);+ expect(window.electronAPI.localDb.conversations.search).toHaveBeenCalledWith({+ query: '未命名',+ limit: 20,+ sortBy: 'relevance',+ semanticMode: 'keyword',+ filters: { status: 'active' },+ unnamedLabel: '未命名任务',+ });+ expect(window.electronAPI.localDb.sessions.list).not.toHaveBeenCalled();+ });++ it('uses indexed task search on the controlled device', async () => {+ stubApi({+ deviceTaskSearch: {+ query: 'untitled',+ results: [{+ session: {+ id: 'remote-history',+ title: 'New Maker',+ status: 'active',+ workingDir: '/repo',+ },+ contentHit: null,+ }],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ },+ });++ const result = await scanAtResources('', 'codex', 2000, 'untitled', 'device-1', {+ includeTaskHistory: true,+ unnamedLabel: 'Untitled session',+ });++ expect(result.items).toMatchObject([{+ type: 'session',+ name: 'Untitled session',+ relPath: 'cindy://session/remote-history?device=device-1',+ }]);+ expect(window.electronAPI.deviceLink.invoke).toHaveBeenCalledWith(+ 'device-1',+ 'local-db:conversations:search',+ [{+ query: 'untitled',+ limit: 20,+ sortBy: 'relevance',+ semanticMode: 'keyword',+ filters: { status: 'active' },+ unnamedLabel: 'Untitled session',+ }],+ );+ });++ it('falls back to the bounded task list for an older controlled device', async () => {+ stubApi({+ deviceTaskSearchError: new Error('CHANNEL_NOT_ALLOWED'),+ deviceTasks: [{+ id: 'legacy-remote-history',+ title: 'Legacy remote task',+ status: 'active',+ userSendAt: '2026-08-03T00:00:00.000Z',+ }],+ });++ const result = await scanAtResources('', 'codex', 2000, 'legacy', 'device-1', {+ includeTaskHistory: true,+ });++ expect(result.items).toMatchObject([{+ type: 'session',+ relPath: 'cindy://session/legacy-remote-history?device=device-1',+ }]);+ expect(window.electronAPI.deviceLink.invoke).toHaveBeenNthCalledWith(+ 2,+ 'device-1',+ 'local-db:sessions:list',+ [100, 'active'],+ );+ });++ it('lists Plugin entries without running them, then searches only the selected provider', async () => {+ stubApi({+ workspace: { success: true, items: [] },+ pluginProviders: {+ items: [{ ghostId: 'issues', name: 'Issue Tracker', description: 'Project issues' }],+ },+ pluginResources: {+ success: true,+ pluginName: 'Issue Tracker',+ items: [{+ id: 'ISSUE-1',+ label: 'Fix login',+ description: 'Open issue',+ href: 'cindy://plugin-resource/issues/search_issues/ISSUE-1',+ }],+ truncated: false,+ },+ });++ const catalog = await scanAtResources(+ 'D:\\repo',+ 'codex',+ 2000,+ undefined,+ undefined,+ { sessionId: 'session-1' },+ );+ expect(catalog.items).toMatchObject([{+ type: 'plugin-provider',+ name: 'Issue Tracker',+ pluginId: 'issues',+ }]);+ expect(window.electronAPI.ghosts.queryAtResources).not.toHaveBeenCalled();++ const searched = await scanPluginAtResources(+ catalog.items[0],+ 'login',+ 'D:\\repo',+ 'session-1',+ );+ expect(window.electronAPI.ghosts.queryAtResources).toHaveBeenCalledWith({+ ghostId: 'issues',+ sessionId: 'session-1',+ workingDir: 'D:\\repo',+ query: 'login',+ limit: 20,+ });+ expect(searched.items).toMatchObject([{+ type: 'plugin-resource',+ name: 'Fix login',+ sourceLabel: 'Issue Tracker',+ }]);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.tsindex f7784ff23d..1a606b1752 100644--- a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts@@ -17,4 +17,31 @@ describe('composer quote palette boundary wiring', () => {);expect(triggerSource).toContain("textSoFar = ''; // chips reset the @ / slash run");});++ it('keeps Plugin scope out of persisted composer text', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),+ 'utf8',+ );++ expect(source).toContain('const activeAtScopeFrom = atPluginScope?.triggerFrom;');+ expect(source).toContain('detectTrigger(editor, activeAtScopeFrom)');+ expect(source).toContain("tr.replaceWith(from, to, editor.schema.text('@'));");+ expect(source).not.toContain('editor.schema.text(`@${item.pluginId}:`)');+ expect(source).toMatch(/if \(atPluginScope\) \{\r?\n\s+atScanSeqRef\.current \+= 1;/);+ });++ it('records a scheduled mention query before reserving its scan sequence', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),+ 'utf8',+ );+ const guard = 'if (normalizedQuery === atLastScanQueryRef.current) return;';+ const record = 'atLastScanQueryRef.current = normalizedQuery;';+ const reserve = 'const seq = ++atScanSeqRef.current;';+ const effectStart = source.indexOf(guard, source.indexOf('// Derive query string'));++ expect(effectStart).toBeGreaterThan(-1);+ expect(source.indexOf(record, effectStart)).toBeLessThan(source.indexOf(reserve, effectStart));+ });});diff --git a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.tsindex e755ba2816..52ee371930 100644--- a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts@@ -37,6 +37,8 @@ const TestMentionChip = Node.create({titled: { default: false },agentText: { default: undefined },agentTextTruncated: { default: undefined },+ sourceLabel: { default: undefined },+ sourceDescription: { default: undefined },};},renderHTML({ HTMLAttributes }) {@@ -1704,4 +1706,89 @@ describe('composer structured list serialization', () => {},]);});++ it('serializes browser-tab and desktop-window chips as structured non-file references', () => {+ const tabHref = 'cindy://browser-tab/tab-1?url=https%3A%2F%2Fexample.com%2Fdocs';+ const windowHref = 'cindy://desktop-window/11/22?app=Code.exe';+ const editor = makeEditor({+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ {+ type: 'mentionChip',+ attrs: { kind: 'browser-tab', label: 'Docs', path: tabHref },+ },+ { type: 'text', text: ' and ' },+ {+ type: 'mentionChip',+ attrs: { kind: 'desktop-window', label: 'Editor', path: windowHref },+ },+ ],+ },+ ],+ });++ const serialized = serializeEditorContent(editor);+ expect(serialized.text).toBe(`[Docs](${tabHref}) and [Editor](${windowHref})`);+ expect(serialized.mentions).toEqual([]);+ expect(serialized.agentReferences).toEqual([+ {+ kind: 'browser-tab',+ start: 0,+ end: `[Docs](${tabHref})`.length,+ href: tabHref,+ tabId: 'tab-1',+ url: 'https://example.com/docs',+ title: 'Docs',+ },+ {+ kind: 'desktop-window',+ start: `[Docs](${tabHref}) and `.length,+ end: serialized.text.length,+ href: windowHref,+ windowId: 22,+ pid: 11,+ appName: 'Code.exe',+ title: 'Editor',+ },+ ]);+ });++ it('serializes Plugin business resources as opaque structured references', () => {+ const href = 'cindy://plugin-resource/issues/search_issues/ISSUE-1';+ const editor = makeEditor({+ type: 'doc',+ content: [{+ type: 'paragraph',+ content: [{+ type: 'mentionChip',+ attrs: {+ kind: 'plugin-resource',+ label: 'Fix login',+ path: href,+ sourceLabel: 'Issue Tracker',+ sourceDescription: 'Open issue',+ },+ }],+ }],+ });++ const serialized = serializeEditorContent(editor);+ expect(serialized.text).toBe(`[Fix login](${href})`);+ expect(serialized.mentions).toEqual([]);+ expect(serialized.agentReferences).toEqual([{+ kind: 'plugin-resource',+ start: 0,+ end: serialized.text.length,+ href,+ ghostId: 'issues',+ tool: 'search_issues',+ resourceId: 'ISSUE-1',+ pluginName: 'Issue Tracker',+ label: 'Fix login',+ description: 'Open issue',+ }]);+ });});diff --git a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.tsindex 18fa8fbeae..1423a8ef60 100644--- a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts+++ b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts@@ -33,7 +33,9 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =expect(userMessageSource).toContain("longMessageCollapsed && (automationOrigin ? 'line-clamp-3' : 'line-clamp-10')",);- expect(userMessageSource).toContain('longMessageCollapsed\n ? segment.text');+ expect(userMessageSource).toMatch(+ /longMessageCollapsed\n\s+\? projectSentInlinePlainText\(\n\s+segment\.text,/,+ );});it('keeps right-click Add to chat enabled while suppressing the floating button', () => {diff --git a/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsx b/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsxnew file mode 100644index 0000000000..4df46324d6--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsx@@ -0,0 +1,126 @@+// @vitest-environment jsdom++import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';++import type { AgentInputReference } from '../../shared/agentInputQueue';+import {+ buildSentInlineTokens,+ locateChatQuoteTextSegmentStarts,+ projectSentInlinePlainText,+ projectSentRanges,+} from '@/components/chat/UserMessage';+import { SentAgentReferenceChip } from '@/components/chat/SentAgentReferenceChip';+import { formatQuoteForSend, parseChatQuoteSegments } from '@/lib/chatQuotes';++afterEach(cleanup);++function browserReference(label = 'Cindy issue #1462') {+ const href = 'cindy://browser-tab/tab-1?url=https%3A%2F%2Fgithub.com%2Fmakecindy%2Fcindy%2Fissues%2F1462';+ const wire = `[${label}](${href})`;+ const reference: AgentInputReference = {+ kind: 'browser-tab',+ start: 0,+ end: wire.length,+ href,+ tabId: 'tab-1',+ url: 'https://github.com/makecindy/cindy/issues/1462',+ title: label,+ };+ return { href, label, reference, wire };+}++describe('sent structured reference ranges', () => {+ it('replaces the exact browser Markdown span and preserves surrounding prose', () => {+ const { reference, wire } = browserReference();+ const content = `看下 ${wire},总结下`;+ const start = content.indexOf(wire);+ const projected = { ...reference, start, end: start + wire.length };++ expect(buildSentInlineTokens(content, [], [], [projected])).toEqual([+ { kind: 'text', text: '看下 ' },+ { kind: 'agent-reference', text: wire, reference: projected },+ { kind: 'text', text: ',总结下' },+ ]);+ expect(projectSentInlinePlainText(content, [], [projected])).toBe(+ '看下 Cindy issue #1462,总结下',+ );+ });++ it('projects a reference after an inline quote to the correct text island', () => {+ const quote = formatQuoteForSend({ text: 'quoted selection' });+ const { reference, wire } = browserReference();+ const content = `${quote}\n\n${wire} 总结下`;+ const start = content.indexOf(wire);+ const projected = { ...reference, start, end: start + wire.length };+ const segments = parseChatQuoteSegments(content);+ const starts = locateChatQuoteTextSegmentStarts(content, segments);+ const textIndex = segments.findIndex((segment) => segment.kind === 'text');+ const segment = segments[textIndex];++ expect(segment.kind).toBe('text');+ if (segment.kind !== 'text') return;+ const localReferences = projectSentRanges(+ [projected],+ starts[textIndex],+ segment.text.length,+ );+ expect(buildSentInlineTokens(segment.text, [], [], localReferences)).toEqual([+ { kind: 'agent-reference', text: wire, reference: { ...projected, start: 0, end: wire.length } },+ { kind: 'text', text: ' 总结下' },+ ]);+ });++ it('keeps raw text when a persisted range is stale or out of bounds', () => {+ const { reference, wire } = browserReference();+ const stale = { ...reference, start: wire.length + 1, end: wire.length + 20 };++ expect(buildSentInlineTokens(wire, [], [], [stale])).toEqual([+ { kind: 'text', text: wire },+ ]);+ });+});++describe('sent structured reference chips', () => {+ it.each([+ {+ label: 'Cindy issue #1462',+ reference: browserReference().reference,+ },+ {+ label: 'Cindy Dev',+ reference: {+ kind: 'desktop-window',+ start: 0,+ end: 5,+ href: 'cindy://desktop-window/42/7?app=Cindy',+ windowId: 7,+ pid: 42,+ appName: 'Cindy',+ title: 'Cindy Dev',+ } satisfies AgentInputReference,+ },+ {+ label: '客户 ACME',+ reference: {+ kind: 'plugin-resource',+ start: 0,+ end: 5,+ href: 'cindy://plugin-resource/crm/search/customer-1',+ ghostId: 'crm',+ tool: 'search',+ resourceId: 'customer-1',+ pluginName: 'CRM',+ label: '客户 ACME',+ } satisfies AgentInputReference,+ },+ ])('renders $label with the same inline reference shell as the composer', ({ label, reference }) => {+ const { container } = render(<SentAgentReferenceChip reference={reference} />);+ const chip = container.querySelector('[data-inline-reference-chip]');++ expect(chip).not.toBeNull();+ expect(chip?.textContent).toBe(label);+ expect(chip?.querySelector('svg')).not.toBeNull();+ expect(container.textContent).not.toContain('cindy://');+ });+});diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex e8ba4fc94f..322aaa727f 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -27,6 +27,7 @@ import {MessageCircleQuestion,PanelLeft,PanelRight,+ Plug,Sparkles,ShieldAlert,Terminal,@@ -48,6 +49,7 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {agent: Bot,node: Cpu,tool: Wrench,+ 'at-resource': Plug,command: Terminal,panel: PanelRight,code: FileCode2,diff --git a/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx b/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsxnew file mode 100644index 0000000000..ea40c69f5e--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx@@ -0,0 +1,73 @@+import {+ Globe2,+ Monitor,+ Plug,+} from 'lucide-react';++import type { AgentInputReference } from '../../../shared/agentInputQueue';+import { InlineReferenceChip } from './InlineReferenceChip';+import { ProjectLinkChip } from './ProjectLinkChip';+import { SessionLinkChip } from './SessionLinkChip';++const MESSAGE_REFERENCE_LABEL_MAX = 240;++function oneLine(value: string): string {+ return value.replace(/\s+/g, ' ').trim();+}++/** The compact label shared by the rich chip and collapsed-message projection. */+export function sentAgentReferenceDisplayLabel(reference: AgentInputReference): string {+ if (reference.kind === 'message') {+ const text = oneLine(reference.text ?? '') || reference.messageClientId;+ return text.length <= MESSAGE_REFERENCE_LABEL_MAX+ ? text+ : `${text.slice(0, MESSAGE_REFERENCE_LABEL_MAX - 1)}…`;+ }+ if (reference.kind === 'session') return oneLine(reference.title ?? '') || reference.sessionId;+ if (reference.kind === 'project') return oneLine(reference.name) || reference.workingDir;+ if (reference.kind === 'browser-tab') return oneLine(reference.title ?? '') || reference.url;+ if (reference.kind === 'desktop-window') {+ return oneLine(reference.title ?? '') || oneLine(reference.appName);+ }+ return oneLine(reference.label) || reference.resourceId;+}++/** Render one persisted Composer reference with the same visual shell as the input chip. */+export function SentAgentReferenceChip({ reference }: { reference: AgentInputReference }) {+ if (reference.kind === 'message') {+ return (+ <SessionLinkChip+ href={reference.href}+ {...(reference.text?.trim() ? { label: reference.text } : {})}+ />+ );+ }+ if (reference.kind === 'session') {+ return (+ <SessionLinkChip+ href={reference.href}+ {...(reference.title?.trim() ? { label: reference.title } : {})}+ />+ );+ }+ if (reference.kind === 'project') {+ return <ProjectLinkChip href={reference.href} label={reference.name} />;+ }++ const label = sentAgentReferenceDisplayLabel(reference);+ const icon = reference.kind === 'browser-tab'+ ? <Globe2 aria-hidden />+ : reference.kind === 'desktop-window'+ ? <Monitor aria-hidden />+ : <Plug aria-hidden />;++ return (+ <InlineReferenceChip+ label={label}+ icon={icon}+ tooltip={label}+ ariaLabel={label}+ className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"+ />+ );+}diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex a04b712b10..406db6b5ba 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -25,6 +25,7 @@ import {Sparkles,Target,} from 'lucide-react';+import { readAgentInputReferences } from '@cindy/maker-shared/agent-input-projection';import { useTranslation } from 'react-i18next';import type { TFunction } from 'i18next';import { cn } from '@/lib/utils';@@ -100,6 +101,10 @@ import { AutomationOriginBadge } from './AutomationOriginBadge';import { UserMessageUrlLink } from './UserMessageUrlLink';import { InlineReferenceChip } from './InlineReferenceChip';import { QuoteChip } from './QuoteChip';+import {+ SentAgentReferenceChip,+ sentAgentReferenceDisplayLabel,+} from './SentAgentReferenceChip';import { parseOrcaCommunicationContent, resolveUserDisplayText } from './userMessageDisplayText';/**@@ -509,18 +514,50 @@ function renderContentWithoutPastedText(export type SentInlineToken =| { kind: 'text'; text: string }| { kind: 'slash'; text: string }- | { kind: 'pasted'; text: string; display: string };+ | { kind: 'pasted'; text: string; display: string }+ | { kind: 'agent-reference'; text: string; reference: AgentInputReference };++type SentInlineRange =+ | { tokenKind: 'pasted'; start: number; end: number; display: string }+ | { tokenKind: 'slash'; start: number; end: number }+ | {+ tokenKind: 'agent-reference';+ start: number;+ end: number;+ reference: AgentInputReference;+ };/** Split exact persisted ranges without guessing from repeated text. */export function buildSentInlineTokens(content: string,pastedTextRanges: readonly PastedTextRange[] = [],slashCommandRanges: readonly SlashCommandRange[] = [],+ agentReferences: readonly AgentInputReference[] = [],): SentInlineToken[] {- const ranges = [- ...pastedTextRanges.map((range) => ({ ...range, kind: 'pasted' as const })),- ...slashCommandRanges.map((range) => ({ ...range, kind: 'slash' as const })),- ].sort((a, b) => a.start - b.start || a.end - b.end);+ const ranges: SentInlineRange[] = [+ ...pastedTextRanges.map(({ start, end, display }): SentInlineRange => ({+ tokenKind: 'pasted',+ start,+ end,+ display,+ })),+ ...slashCommandRanges.map(({ start, end }): SentInlineRange => ({+ tokenKind: 'slash',+ start,+ end,+ })),+ ...agentReferences.map((reference): SentInlineRange => ({+ tokenKind: 'agent-reference',+ start: reference.start,+ end: reference.end,+ reference,+ })),+ ].sort((a, b) => {+ if (a.start !== b.start) return a.start - b.start;+ if (a.tokenKind === 'agent-reference' && b.tokenKind !== 'agent-reference') return -1;+ if (b.tokenKind === 'agent-reference' && a.tokenKind !== 'agent-reference') return 1;+ return a.end - b.end;+ });const tokens: SentInlineToken[] = [];let cursor = 0;for (const range of ranges) {@@ -535,10 +572,12 @@ export function buildSentInlineTokens(if (range.start > cursor)tokens.push({ kind: 'text', text: content.slice(cursor, range.start) });const text = content.slice(range.start, range.end);- if (range.kind === 'pasted') {+ if (range.tokenKind === 'pasted') {tokens.push({ kind: 'pasted', text, display: range.display });- } else {+ } else if (range.tokenKind === 'slash') {tokens.push({ kind: 'slash', text });+ } else {+ tokens.push({ kind: 'agent-reference', text, reference: range.reference });}cursor = range.end;}@@ -568,6 +607,24 @@ export function projectSentPastedPlainText(.join('');}+/** Project rich inline ranges to the labels users see when a long message is collapsed. */+export function projectSentInlinePlainText(+ content: string,+ pastedTextRanges: readonly PastedTextRange[] = [],+ agentReferences: readonly AgentInputReference[] = [],+): string {+ if (pastedTextRanges.length === 0 && agentReferences.length === 0) return content;+ return buildSentInlineTokens(content, pastedTextRanges, [], agentReferences)+ .map((token) =>+ token.kind === 'pasted'+ ? token.display+ : token.kind === 'agent-reference'+ ? sentAgentReferenceDisplayLabel(token.reference)+ : token.text,+ )+ .join('');+}+/** Locate each parsed text island in the original quote wire text. */export function locateChatQuoteTextSegmentStarts(content: string,@@ -621,8 +678,14 @@ function renderContent(* tooltip —— 那正是"发出去就再也看不到全文"的旧行为,新调用点都应该传。*/onPastedTextChipClick?: (text: string, chip: HTMLElement) => void,+ agentReferences: readonly AgentInputReference[] = [],): React.ReactNode[] {- const tokens = buildSentInlineTokens(content, pastedTextRanges, slashCommandRanges ?? []);+ const tokens = buildSentInlineTokens(+ content,+ pastedTextRanges,+ slashCommandRanges ?? [],+ agentReferences,+ );const useLegacySlashHeuristic = slashCommandRanges === undefined;return tokens.map((token, index) => {if (token.kind === 'slash') {@@ -658,6 +721,14 @@ function renderContent(/>);}+ if (token.kind === 'agent-reference') {+ return (+ <SentAgentReferenceChip+ key={`agent-reference-chip-${index}`}+ reference={token.reference}+ />+ );+ }return (<span key={`text-${index}`}>{renderContentWithoutPastedText(@@ -763,6 +834,10 @@ export function UserMessage({// 与提问导航条预览共用同一实现,规则见 userMessageDisplayText.ts;上面已// 解析过的 Orca 结果传入复用,渲染热路径不重复 JSON.parse(Copilot review)。const displayContent = resolveUserDisplayText({ content, hookSource }, orcaCommunication);+ const validAgentReferences = useMemo(+ () => readAgentInputReferences(agentReferences, content),+ [agentReferences, content],+ );// ghost-summon-card:意识指令/提示的机器追加段从气泡正文尾部剥离,交给// GhostSummonCard 渲染(splitGhostDirective 与 expandGhostCommand 同模板,// 对不上模板按普通文本原样显示)。copy / fork / rewind / 编辑预填全部用@@ -858,6 +933,11 @@ export function UserMessage({projectSentRanges(pastedTextRanges ?? [], displayBubbleSourceStart, displayBubbleBody.length),[displayBubbleBody.length, displayBubbleSourceStart, pastedTextRanges],);+ const bubbleAgentReferences = useMemo(+ () =>+ projectSentRanges(validAgentReferences, displayBubbleSourceStart, displayBubbleBody.length),+ [displayBubbleBody.length, displayBubbleSourceStart, validAgentReferences],+ );// 测量与收起态渲染共用的投影正文:粘贴段按胶囊文案计量,不再拿被折叠掉的// 几百行原文去撞收起阈值(issue #946)。偏移只在 bubbleBody 与 ghostBody 同源// (无引用交错)时精确 —— quote 块被 join 掉的消息偏移会整体前移,保持原文@@ -865,9 +945,13 @@ export function UserMessage({const collapseMeasureBody = useMemo(() =>bubbleBody === ghostBody- ? projectSentPastedPlainText(displayBubbleBody, bubblePastedRanges)+ ? projectSentInlinePlainText(+ displayBubbleBody,+ bubblePastedRanges,+ bubbleAgentReferences,+ ): displayBubbleBody,- [bubbleBody, ghostBody, displayBubbleBody, bubblePastedRanges],+ [bubbleAgentReferences, bubbleBody, bubblePastedRanges, displayBubbleBody, ghostBody],);const collapseMeasureEnabled =!orcaCommunication &&@@ -1333,7 +1417,25 @@ export function UserMessage({key={index}>{longMessageCollapsed- ? segment.text+ ? projectSentInlinePlainText(+ segment.text,+ projectSentRanges(+ pastedTextRanges ?? [],+ quoteTextSegmentStarts[index] === null ||+ ghostBodySourceStart === null+ ? null+ : ghostBodySourceStart + quoteTextSegmentStarts[index]!,+ segment.text.length,+ ),+ projectSentRanges(+ validAgentReferences,+ quoteTextSegmentStarts[index] === null ||+ ghostBodySourceStart === null+ ? null+ : ghostBodySourceStart + quoteTextSegmentStarts[index]!,+ segment.text.length,+ ),+ ): renderContent(segment.text,workingDir,@@ -1372,6 +1474,14 @@ export function UserMessage({),sessionReferences,handlePastedTextChipClick,+ projectSentRanges(+ validAgentReferences,+ quoteTextSegmentStarts[index] === null ||+ ghostBodySourceStart === null+ ? null+ : ghostBodySourceStart + quoteTextSegmentStarts[index]!,+ segment.text.length,+ ),)}</span>),@@ -1417,6 +1527,7 @@ export function UserMessage({),sessionReferences,handlePastedTextChipClick,+ bubbleAgentReferences,)}</div>) : null}diff --git a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsxindex 0ec41c5ab2..f622660da3 100644--- a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx@@ -13,11 +13,23 @@*/import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { File as FileIcon, Folder as FolderIcon, Sparkles } from 'lucide-react';+import {+ ArrowLeft,+ File as FileIcon,+ Folder as FolderIcon,+ Globe2,+ History,+ Monitor,+ Paperclip,+ Plug,+ Sparkles,+} from 'lucide-react';import { cn } from '@/lib/utils';import { Tip } from '@/components/ui/tooltip';import {+ AT_FILE_PICKER_RESOURCE,+ AT_MENTION_SEARCH_RESULT_LIMIT,filterAtResources,type AtResourceItem,} from '@/lib/atResourceService';@@ -45,6 +57,11 @@ interface AtMentionPanelProps {onSelect: (item: AtResourceItem) => void;onClose: () => void;onRetry: () => void;+ /** Selected Plugin provider; its query is scoped and never broadcast. */+ scopedProviderName?: string;+ /** Whether the local task can launch the native file picker. */+ filePickerEnabled?: boolean;+ onBack?: () => void;/** Panel max-height in px. Defaults to 400 (chat view); NewMaker passes a smaller value so the popover doesn't cover the logo. */maxHeight?: number;}@@ -57,6 +74,9 @@ export function AtMentionPanel({onSelect,onClose,onRetry,+ scopedProviderName,+ filePickerEnabled = false,+ onBack,maxHeight = 400,}: AtMentionPanelProps) {const { t } = useTranslation();@@ -73,8 +93,14 @@ export function AtMentionPanel({const filtered = useMemo(() => {if (state.kind !== 'ready') return [];- return filterAtResources(state.items, query);- }, [state, query]);+ if (scopedProviderName) return state.items.slice(0, AT_MENTION_SEARCH_RESULT_LIMIT);+ const items = filePickerEnabled+ ? [AT_FILE_PICKER_RESOURCE, ...state.items]+ : state.items;+ return filterAtResources(items, query);+ }, [state, query, scopedProviderName, filePickerEnabled]);+ const hasScope = !!scopedProviderName;+ const isEmptyRootQuery = !hasScope && !query.trim();useEffect(() => {if (filtered.length === 0) return;@@ -99,8 +125,7 @@ export function AtMentionPanel({}, [onClose]);const focusedItem = filtered[focusedIndex];- // Show tooltip only for agent items with a description- const showTooltip = focusedItem?.type === 'agent' && !!focusedItem.description;+ const showTooltip = !!focusedItem?.description;const tooltipKey = showTooltip? `${focusedItem.type}:${focusedItem.relPath}:${focusedItem.name}:${focusedItem.description ?? ''}`: null;@@ -121,7 +146,7 @@ export function AtMentionPanel({const bottomBoundary = Math.min(panelRect.bottom, window.innerHeight - VIEWPORT_PAD);const maxTooltipHeight = Math.max(1, Math.min(maxHeight, bottomBoundary - VIEWPORT_PAD));const measuredHeight = Math.min(tooltipHeight, maxTooltipHeight);- const rawTop = 6 + focusedIndex * 44 - panelScroll; // 44px row height+ const rawTop = (hasScope ? 46 : 6) + focusedIndex * 44 - panelScroll;const minTop = VIEWPORT_PAD - rootRect.top;const bottomBoundaryInRoot = bottomBoundary - rootRect.top;const top = Math.max(minTop, Math.min(rawTop, bottomBoundaryInRoot - measuredHeight));@@ -129,7 +154,7 @@ export function AtMentionPanel({top: Math.round(top),maxHeight: Math.round(maxTooltipHeight),});- }, [showTooltip, focusedIndex, panelScroll, maxHeight, tooltipHeight]);+ }, [showTooltip, focusedIndex, panelScroll, maxHeight, tooltipHeight, hasScope]);const tooltipVisible = showTooltip && !!tooltipPos;useLayoutEffect(() => {@@ -153,14 +178,44 @@ export function AtMentionPanel({const renderItemRow = (item: AtResourceItem, idx: number) => {const focused = idx === focusedIndex;let meta: string;- if (item.type === 'agent') {+ if (item.type === 'file-picker') {+ meta = '';+ } else if (item.type === 'agent') {meta = 'Agent';+ } else if (item.type === 'browser-tab') {+ meta = t('newChat.atMention.browserTab');+ } else if (item.type === 'desktop-window') {+ meta = item.description || t('newChat.atMention.desktopWindow');+ } else if (item.type === 'session') {+ meta = t('newChat.atMention.task');+ } else if (item.type === 'plugin-provider') {+ meta = t('newChat.atMention.pluginResources');+ } else if (item.type === 'plugin-resource') {+ meta = item.sourceLabel || t('newChat.atMention.pluginResource');} else {const lastSlash = item.relPath.lastIndexOf('/');meta = lastSlash >= 0 ? item.relPath.slice(0, lastSlash) : '';}- const displayName = item.type === 'dir' ? `${item.name}/` : item.name;- const Icon = item.type === 'agent' ? Sparkles : item.type === 'dir' ? FolderIcon : FileIcon;+ const displayName = item.type === 'file-picker'+ ? t('newChat.atMention.filesAndFolders')+ : item.type === 'dir'+ ? `${item.name}/`+ : item.name;+ const Icon = item.type === 'file-picker'+ ? Paperclip+ : item.type === 'agent'+ ? Sparkles+ : item.type === 'dir'+ ? FolderIcon+ : item.type === 'browser-tab'+ ? Globe2+ : item.type === 'desktop-window'+ ? Monitor+ : item.type === 'session'+ ? History+ : item.type === 'plugin-provider' || item.type === 'plugin-resource'+ ? Plug+ : FileIcon;return (<button@@ -221,6 +276,32 @@ export function AtMentionPanel({)}style={{ boxShadow: 'var(--cmd-palette-shadow)', maxHeight }}>+ {hasScope && (+ <div className="sticky top-0 z-10 flex h-[40px] items-center gap-2 bg-[var(--cmd-palette-bg)] px-[4px]">+ <button+ type="button"+ aria-label={t('newChat.atMention.backToAll')}+ onMouseDown={(event) => {+ event.preventDefault();+ onBack?.();+ }}+ className={cn(+ 'flex size-[32px] shrink-0 items-center justify-center rounded-[6px]',+ 'text-[var(--cmd-palette-item-meta)] hover:bg-[var(--cmd-palette-item-hover)]',+ )}+ >+ <ArrowLeft size={16} />+ </button>+ <span className="min-w-0 truncate text-[13px] font-medium text-[var(--cmd-palette-item-text)]">+ {scopedProviderName}+ </span>+ {scopedProviderName && (+ <span className="ml-auto shrink-0 text-[12px] text-[var(--cmd-palette-item-meta)]">+ {t('newChat.atMention.pluginResources')}+ </span>+ )}+ </div>+ )}{state.kind === 'loading' && (<div className="space-y-[4px] p-[4px]">{[0, 1, 2].map((i) => (@@ -258,20 +339,34 @@ export function AtMentionPanel({<divclassName={cn('flex items-center justify-center',- 'h-[40px] text-[13px]',+ 'select-none h-[40px] text-[13px]','text-[var(--cmd-palette-empty)]',)}>- {state.searching ? t('newChat.atMention.searching') : t('newChat.atMention.noMatch')}+ {state.searching+ ? t('newChat.atMention.searching')+ : isEmptyRootQuery+ ? t('newChat.atMention.typeToSearchFiles')+ : t('newChat.atMention.noMatch')}</div>)}{state.kind === 'ready' && filtered.length > 0 && (<>{filtered.map((item, idx) => renderItemRow(item, idx))}- {state.truncated && (+ {isEmptyRootQuery && (+ <div+ className={cn(+ 'select-none px-[10px] py-[8px] text-[12px]',+ 'text-[var(--cmd-palette-item-meta)]',+ )}+ >+ {t('newChat.atMention.typeToSearchFiles')}+ </div>+ )}+ {!isEmptyRootQuery && state.truncated && (<divclassName={cn(- 'px-[10px] py-[8px] text-[12px]',+ 'select-none px-[10px] py-[8px] text-[12px]','text-[var(--cmd-palette-item-meta)]',)}>diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 6ed2fa75e7..d3cc90485a 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -162,6 +162,7 @@ import {pastedSessionChipAttrs,resolveSessionMessageReferencesForSend,resolveSessionChipTitles,+ sanitizeSessionChipTitle,} from './sessionLinkPaste';import {isLongPasteText,@@ -188,11 +189,23 @@ import {import { QuickStartPillMark } from './QuickStartPillMark';import { ToolPayloadLightbox } from '@/components/chat/ToolPayloadLightbox';import { Fragment, Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';-import { Selection, TextSelection } from '@tiptap/pm/state';+import { Selection, TextSelection, type Transaction } from '@tiptap/pm/state';import * as sessionService from '@/lib/sessionService';import { getModelById } from '@/lib/modelDefinitions';import { loadAllCommands, filterSlashCommands, type UnifiedCommand } from '@/lib/slashCommands';-import { scanAtResources, filterAtResources, type AtResourceItem } from '@/lib/atResourceService';+import {+ AT_FILE_PICKER_RESOURCE,+ AT_MENTION_EMPTY_WORKSPACE_SCAN_CAP,+ AT_MENTION_SEARCH_RESULT_LIMIT,+ createAtResourceFromNativePath,+ getAtDirectoryCompletionQuery,+ mergeAtResourceItems,+ scanAtResources,+ scanPluginAtResources,+ filterAtResources,+ type AtResourceItem,+} from '@/lib/atResourceService';+import { isAtResourceInsertTargetCurrent } from '@/lib/atResourceInsertionGuard';import { applyListBackspace, applyListContinuation } from '@/lib/composerListContinuation';import type { Effort, PermissionMode } from '@/lib/userPreferences.types';import { getAppShortcutCombos } from '@/lib/appShortcutStore';@@ -750,7 +763,7 @@ type TriggerState = TriggerSlash | TriggerAt | { kind: 'none' };*/const GHOST_SIGIL_CHARS = ['$', '$', '¥', '¥'] as const;-function detectTrigger(editor: Editor): TriggerState {+function detectTrigger(editor: Editor, activeAtScopeFrom?: number): TriggerState {const { state } = editor;const { selection } = state;if (!selection.empty) return { kind: 'none' };@@ -836,11 +849,19 @@ function detectTrigger(editor: Editor): TriggerState {const before = atIdx === 0 ? '' : textSoFar[atIdx - 1];const allowed = atIdx === 0 || /\s/.test(before);const after = textSoFar.slice(atIdx + 1);+ const from = pos - (textSoFar.length - atIdx);+ if (allowed && activeAtScopeFrom === from && !/[\r\n]/.test(after)) {+ return {+ kind: 'at',+ query: after,+ from,+ };+ }if (allowed && !/\s/.test(after)) {return {kind: 'at',query: after,- from: pos - (textSoFar.length - atIdx),+ from,};}}@@ -2454,6 +2475,8 @@ export function ChatInput({const disableAutofocusRef = useRef(disableAutofocus);const focusOnStorageKeyChangeRef = useRef(focusOnStorageKeyChange);const latestStorageKeyRef = useRef<string | undefined>(storageKey);+ const currentStorageKeyRef = useRef<string | undefined>(storageKey);+ currentStorageKeyRef.current = storageKey;const storageKeyTransitionSeqRef = useRef(0);const sendButtonRef = useRef<HTMLElement | null>(null);const voiceShortcutPressRef = useRef<{@@ -3179,7 +3202,14 @@ export function ChatInput({);// ── Slash / At panel state ─────────────────────────────────────────- const trigger: TriggerState = editor ? detectTrigger(editor) : { kind: 'none' };+ const [atPluginScope, setAtPluginScope] = useState<{+ provider: AtResourceItem;+ triggerFrom: number;+ } | null>(null);+ const activeAtScopeFrom = atPluginScope?.triggerFrom;+ const trigger: TriggerState = editor+ ? detectTrigger(editor, activeAtScopeFrom)+ : { kind: 'none' };// Slash commands — palette refactor 后改成 loadAllCommands 一次性拉三源(desktop +// agent-builtin + agent-skill); 内部并发, mergeCommands 按优先级合并去重。@@ -3256,29 +3286,33 @@ export function ChatInput({// At-panel scan stateconst [atState, setAtState] = useState<AtPanelState>({ kind: 'loading' });const atScanSeqRef = useRef(0);- const atFallbackScanTimerRef = useRef<number | null>(null);+ const atLastScanQueryRef = useRef('');+ const atQueryScanTimerRef = useRef<number | null>(null);useEffect(() => () => {atScanSeqRef.current += 1;- if (atFallbackScanTimerRef.current !== null) {- window.clearTimeout(atFallbackScanTimerRef.current);+ if (atQueryScanTimerRef.current !== null) {+ window.clearTimeout(atQueryScanTimerRef.current);}},[],);const runAtScan = useCallback(- (query?: string) => {+ (query?: string, reservedSeq?: number) => {// SSH 远端会话不扫 @ 资源(无隧道);atOpen 也已对其关闭面板,这里再兜一层。- if (!workingDir || isRemoteSession) return;+ if (isRemoteSession) return;// device-link 远程会话:带 deviceId 经隧道在被控端扫描(workingDir 是被控端路径);// 本机会话 deviceId 为 undefined → 本地扫描。// 远程**草稿**(NewMakerDraftRoute)此时 sessionId 还是 undefined、但 deviceLinkDeviceId prop 已设——// 必须优先用 prop,否则 @ 扫描落到控制端本机 FS(扫到同名目录的错文件),插进首条远程消息的 mention 不可用。const remoteDeviceId =deviceLinkDeviceId ?? (sessionId ? getSessionDeviceId(sessionId) : undefined);- const seq = ++atScanSeqRef.current;+ const seq = reservedSeq ?? ++atScanSeqRef.current;+ if (atScanSeqRef.current !== seq) return;const normalizedQuery = query?.trim() ?? '';+ const preservePreviousItems = reservedSeq !== undefined && !!normalizedQuery;+ atLastScanQueryRef.current = normalizedQuery;setAtState((prev) => {if (prev.kind === 'ready' && normalizedQuery) {return { ...prev, searching: true };@@ -3286,11 +3320,28 @@ export function ChatInput({return { kind: 'loading' };});scanAtResources(- workingDir,+ workingDir ?? '',paletteAgentKind,- 2000,+ normalizedQuery ? 2000 : AT_MENTION_EMPTY_WORKSPACE_SCAN_CAP,normalizedQuery || undefined,remoteDeviceId,+ {+ sessionId,+ includeLocalContext: !remoteDeviceId,+ includeTaskHistory: !!normalizedQuery,+ unnamedLabel: t('ccAgent.common.unnamedSession'),+ onPartial: (partial) => {+ if (atScanSeqRef.current !== seq || !partial.success) return;+ setAtState((prev) => ({+ kind: 'ready',+ items: preservePreviousItems && prev.kind === 'ready'+ ? mergeAtResourceItems(prev.items, partial.items)+ : partial.items,+ truncated: partial.truncated || (prev.kind === 'ready' && prev.truncated),+ searching: true,+ }));+ },+ },).then((res) => {if (atScanSeqRef.current !== seq) return;@@ -3306,25 +3357,98 @@ export function ChatInput({setAtState({ kind: 'error', message: m });});},- [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId],+ [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId, t],+ );++ useEffect(() => {+ if (!editor || !atPluginScope) return;+ const handleTransaction = ({ transaction }: { transaction: Transaction }) => {+ // A caret-only move makes the end of a multi-word query ambiguous.+ // Leave Plugin scope before the user can select a row against a prefix+ // and accidentally leave the query suffix behind.+ if (!transaction.docChanged && transaction.selectionSet) {+ atScanSeqRef.current += 1;+ setAtPluginScope(null);+ runAtScan();+ }+ };+ editor.on('transaction', handleTransaction);+ return () => {+ editor.off('transaction', handleTransaction);+ };+ }, [editor, atPluginScope, runAtScan]);++ const runAtPluginScan = useCallback(+ (provider: AtResourceItem, query: string, reservedSeq?: number) => {+ const seq = reservedSeq ?? ++atScanSeqRef.current;+ if (atScanSeqRef.current !== seq) return;+ setAtState((prev) => prev.kind === 'ready'+ ? { ...prev, searching: true }+ : { kind: 'loading' });+ scanPluginAtResources(provider, query, workingDir ?? undefined, sessionId)+ .then((res) => {+ if (atScanSeqRef.current !== seq) return;+ if (!res.success) {+ setAtState({ kind: 'error', message: res.error ?? 'Plugin resource search failed' });+ return;+ }+ setAtState({ kind: 'ready', items: res.items, truncated: res.truncated });+ })+ .catch((error: unknown) => {+ if (atScanSeqRef.current !== seq) return;+ setAtState({+ kind: 'error',+ message: error instanceof Error ? error.message : String(error),+ });+ });+ },+ [workingDir, sessionId],);const atQuery = trigger.kind === 'at' ? trigger.query : '';+ const atTriggerFrom = trigger.kind === 'at' ? trigger.from : null;// When `@` panel opens, rescan so newly created files/agents show immediately.useEffect(() => {if (trigger.kind !== 'at') return;- if (!workingDir) return;runAtScan();}, [trigger.kind, workingDir, runAtScan]);+ useEffect(() => {+ if (+ !atPluginScope+ || trigger.kind !== 'at'+ || atTriggerFrom !== atPluginScope.triggerFrom+ ) {+ if (atPluginScope) {+ atScanSeqRef.current += 1;+ setAtPluginScope(null);+ if (trigger.kind === 'at') runAtScan(atQuery);+ }+ return;+ }+ // Never leave stale results selectable while a new scoped query is waiting+ // for its debounce or network response.+ const seq = ++atScanSeqRef.current;+ setAtState({ kind: 'ready', items: [], truncated: false, searching: true });+ const timer = window.setTimeout(+ () => runAtPluginScan(atPluginScope.provider, atQuery, seq),+ atQuery ? 200 : 0,+ );+ return () => window.clearTimeout(timer);+ }, [atPluginScope, trigger.kind, atTriggerFrom, atQuery, runAtPluginScan, runAtScan]);+// Derive query string for stable memo deps — avoids re-filtering on// every editor tick when only the caret moved but the query didn't change.const filteredAt = useMemo(() => {if (!atQuery && trigger.kind !== 'at') return [];if (atState.kind !== 'ready') return [];- return filterAtResources(atState.items, atQuery);- }, [atState, atQuery, trigger.kind]);+ if (atPluginScope) return atState.items.slice(0, AT_MENTION_SEARCH_RESULT_LIMIT);+ const items = workingDir && localAttachmentPickerEnabled+ ? [AT_FILE_PICKER_RESOURCE, ...atState.items]+ : atState.items;+ return filterAtResources(items, atQuery);+ }, [atState, atQuery, trigger.kind, atPluginScope, workingDir, localAttachmentPickerEnabled]);// Focused row index for each paletteconst [slashFocus, setSlashFocus] = useState(0);@@ -3337,28 +3461,35 @@ export function ChatInput({useEffect(() => {if (atFocus >= filteredAt.length) setAtFocus(0);}, [filteredAt.length, atFocus]);+ useEffect(() => {+ if (atPluginScope) setAtFocus(0);+ }, [atPluginScope?.provider.pluginId, atQuery]);useEffect(() => {- if (atFallbackScanTimerRef.current !== null) {- window.clearTimeout(atFallbackScanTimerRef.current);- atFallbackScanTimerRef.current = null;+ if (atQueryScanTimerRef.current !== null) {+ window.clearTimeout(atQueryScanTimerRef.current);+ atQueryScanTimerRef.current = null;}if (trigger.kind !== 'at') return;- if (!workingDir) return;- if (!atQuery.trim()) return;- if (atState.kind !== 'ready') return;- if (filteredAt.length > 0) return;- atFallbackScanTimerRef.current = window.setTimeout(() => {- atFallbackScanTimerRef.current = null;- runAtScan(atQuery);- }, 200);+ if (atPluginScope) return;+ const normalizedQuery = atQuery.trim();+ if (normalizedQuery === atLastScanQueryRef.current) return;+ atLastScanQueryRef.current = normalizedQuery;+ const seq = ++atScanSeqRef.current;+ setAtState((prev) => prev.kind === 'ready'+ ? { ...prev, searching: true }+ : prev);+ atQueryScanTimerRef.current = window.setTimeout(() => {+ atQueryScanTimerRef.current = null;+ runAtScan(normalizedQuery, seq);+ }, normalizedQuery ? 200 : 0);return () => {- if (atFallbackScanTimerRef.current !== null) {- window.clearTimeout(atFallbackScanTimerRef.current);- atFallbackScanTimerRef.current = null;+ if (atQueryScanTimerRef.current !== null) {+ window.clearTimeout(atQueryScanTimerRef.current);+ atQueryScanTimerRef.current = null;}};- }, [trigger.kind, workingDir, atQuery, atState.kind, filteredAt.length, runAtScan]);+ }, [trigger.kind, workingDir, atQuery, runAtScan, atPluginScope]);// ── Panel-close flags (Esc cancelation) ────────────────────────────// Once the user cancels a panel (Esc), we must NOT reopen it until the@@ -3385,7 +3516,7 @@ export function ChatInput({const slashOpen = trigger.kind === 'slash' && suppressedSlashAt !== trigger.from;const atOpen =- trigger.kind === 'at' && !!workingDir && !isRemoteSession && suppressedAtAt !== trigger.from;+ trigger.kind === 'at' && !isRemoteSession && suppressedAtAt !== trigger.from;useEffect(() => {if (!slashOpen) return;@@ -3434,6 +3565,9 @@ export function ChatInput({insertAtResource(filteredAt[atFocus]);return true;}+ // A scoped Plugin search owns Enter/Tab even while loading or+ // empty; keep accidental sends from bypassing resource selection.+ if (atOpen && atPluginScope) return true;return false;case 'Escape':if (slashOpen && trigger.kind === 'slash') {@@ -3441,10 +3575,21 @@ export function ChatInput({return true;}if (atOpen && trigger.kind === 'at') {+ if (atPluginScope) {+ exitAtPluginScope(true);+ return true;+ }setSuppressedAtAt(trigger.from);return true;}return false;+ case 'ArrowLeft':+ case 'Backspace':+ if (atOpen && atPluginScope && !atQuery) {+ exitAtPluginScope(false);+ return true;+ }+ return false;default:return false;}@@ -3503,7 +3648,7 @@ export function ChatInput({);const insertAtResource = useCallback(- (item: AtResourceItem) => {+ async (item: AtResourceItem) => {if (!editor || trigger.kind !== 'at') return;const { from } = trigger;// Extend replace-range to the end of the @-run (up to whitespace /@@ -3512,36 +3657,123 @@ export function ChatInput({const $from = editor.state.doc.resolve(from);const parent = $from.parent;const parentStart = $from.start();- let runEnd = from + 1; // skip the `@` itself+ // Scoped Plugin queries may contain spaces. Their explicit end is the+ // current caret, so ordinary composer text after the caret is preserved.+ const isAtScoped = activeAtScopeFrom === from;+ let runEnd = isAtScoped ? editor.state.selection.from : from + 1;const offset = from - parentStart + 1;- parent.forEach((child, childOffset) => {- if (childOffset + child.nodeSize <= offset) return;- if (child.type.name === 'mentionChip') return;- if (!child.isText) return;- const localStart = Math.max(0, offset - childOffset);- const text = child.text ?? '';- for (let i = localStart; i < text.length; i++) {- if (/\s/.test(text[i])) {- runEnd = parentStart + childOffset + i;+ if (!isAtScoped) {+ let stopped = false;+ parent.forEach((child, childOffset) => {+ if (stopped || childOffset + child.nodeSize <= offset) return;+ if (child.type.name === 'mentionChip' || !child.isText) {+ stopped = true;return;}- }- runEnd = parentStart + childOffset + text.length;- });+ const localStart = Math.max(0, offset - childOffset);+ const text = child.text ?? '';+ for (let i = localStart; i < text.length; i++) {+ if (/\s/.test(text[i])) {+ runEnd = parentStart + childOffset + i;+ stopped = true;+ return;+ }+ }+ runEnd = parentStart + childOffset + text.length;+ });+ }const to = runEnd;+ let selectedItem = item;+ let selectedByNativePicker = false;+ if (selectedItem.type === 'file-picker') {+ const originDoc = editor.state.doc;+ const originStorageKey = storageKey;+ try {+ const picked = await window.electronAPI.dialog.showOpenResource(+ workingDir ? { defaultPath: workingDir } : undefined,+ );+ if (!picked.success || !picked.path || !picked.kind) return;+ if (!isAtResourceInsertTargetCurrent(+ editor,+ editorRef.current,+ originDoc,+ originStorageKey,+ currentStorageKeyRef.current,+ )) return;+ const nativeResource = createAtResourceFromNativePath(+ picked.path,+ picked.kind,+ workingDir,+ );+ if (!nativeResource) return;+ selectedItem = nativeResource;+ selectedByNativePicker = true;+ } catch (error) {+ log.warn(+ 'native @ file picker failed:',+ error instanceof Error ? error.message : String(error),+ );+ return;+ }+ }+ // The synthetic action must always resolve to a concrete file/directory+ // before it can reach mention serialization.+ if (selectedItem.type === 'file-picker') return;+ if (selectedItem.type === 'plugin-provider') {+ if (!selectedItem.pluginId) return;+ editor+ .chain()+ .focus()+ .command(({ tr }) => {+ // The provider lives only in React state. Keeping ordinary `@`+ // text means drafts and sends can never leak an internal sentinel.+ tr.replaceWith(from, to, editor.schema.text('@'));+ return true;+ })+ .run();+ atScanSeqRef.current += 1;+ setAtPluginScope({ provider: selectedItem, triggerFrom: from });+ setAtState({ kind: 'loading' });+ return;+ }+ const directoryQuery = selectedByNativePicker+ ? null+ : getAtDirectoryCompletionQuery(selectedItem);+ if (directoryQuery) {+ editor+ .chain()+ .focus()+ .command(({ tr }) => {+ tr.replaceWith(from, to, editor.schema.text(`@${directoryQuery}`));+ return true;+ })+ .run();+ setAtFocus(0);+ setAtPluginScope(null);+ return;+ }const attrs: MentionChipAttrs = {- kind: item.type,- label: item.name.replace(/\.md$/, ''),+ kind: selectedItem.type,+ label: selectedItem.name.replace(/\.md$/, ''),// For agent chips we stash the bare name so serialization can// degrade to `@{name}` if the host can't map it; for files/dirs// we stash the relative path as-is.- path: item.type === 'agent' ? item.name : item.relPath,+ path: selectedItem.type === 'agent' ? selectedItem.name : selectedItem.relPath,+ ...(selectedItem.type === 'plugin-resource' && selectedItem.sourceLabel+ ? { sourceLabel: selectedItem.sourceLabel }+ : {}),+ ...(selectedItem.type === 'plugin-resource' && selectedItem.description+ ? { sourceDescription: selectedItem.description }+ : {}),};// For agent: store final canonical path in `path` if we know it maps// to an existing file. Here we DO know (we just scanned), so use the// canonical form.- if (item.type === 'agent') {- attrs.path = item.relPath; // .claude/agents/<name>.md+ if (selectedItem.type === 'agent') {+ attrs.path = selectedItem.relPath; // .claude/agents/<name>.md+ } else if (selectedItem.type === 'session') {+ attrs.label = sanitizeSessionChipTitle(selectedItem.name);+ attrs.titled = true;}editor.chain()@@ -3553,10 +3785,35 @@ export function ChatInput({return true;}).run();+ setAtPluginScope(null);},- [editor, trigger],+ [editor, trigger, activeAtScopeFrom, workingDir, storageKey],);+ const exitAtPluginScope = useCallback((closePanel: boolean) => {+ if (!editor || trigger.kind !== 'at') return;+ const { from } = trigger;+ if (!closePanel) {+ const runEnd = editor.state.selection.from;+ editor+ .chain()+ .focus()+ .command(({ tr }) => {+ tr.replaceWith(from, runEnd, editor.schema.text('@'));+ return true;+ })+ .run();+ }+ setAtPluginScope(null);+ atScanSeqRef.current += 1;+ if (closePanel) {+ setAtState({ kind: 'loading' });+ setSuppressedAtAt(from);+ } else {+ runAtScan();+ }+ }, [editor, trigger, runAtScan]);+// ── Send / Stop wiring ─────────────────────────────────────────────const dispatchSendInFlightRef = useRef(false);const dispatchSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(@@ -3570,6 +3827,10 @@ export function ChatInput({// 语音发送等所有入口,确保 host 已登记切换意图后才允许 maker:send。if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;if (dispatchSendInFlightRef.current) return;+ if (atPluginScope) {+ atScanSeqRef.current += 1;+ setAtPluginScope(null);+ }const sourceSessionId = sessionId;const finishAgentSendDispatch = sourceSessionId? tryBeginAgentSendDispatch(sourceSessionId)@@ -3819,7 +4080,7 @@ export function ChatInput({remoteModelListStatus,confirmDialog,navigate,- sessionId,+ atPluginScope,],);useEffect(() => {@@ -5961,9 +6222,21 @@ export function ChatInput({onFocusedIndexChange={setAtFocus}onSelect={(item) => insertAtResource(item)}onClose={() => {- if (trigger.kind === 'at') setSuppressedAtAt(trigger.from);+ if (trigger.kind !== 'at') return;+ if (atPluginScope) {+ exitAtPluginScope(true);+ } else {+ setSuppressedAtAt(trigger.from);+ }}}- onRetry={() => runAtScan(atQuery)}+ onRetry={() => atPluginScope+ ? runAtPluginScan(atPluginScope.provider, atQuery)+ : runAtScan(atQuery)}+ scopedProviderName={atPluginScope?.provider.name}+ filePickerEnabled={!!workingDir && localAttachmentPickerEnabled}+ onBack={atPluginScope+ ? () => exitAtPluginScope(false)+ : undefined}maxHeight={paletteMaxHeight}/>)}diff --git a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsxindex a37b3cbca0..b11d40f1fe 100644--- a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx+++ b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx@@ -12,7 +12,10 @@ import {File,Folder,FolderOpen,+ Globe2,MessageSquareQuote,+ Monitor,+ Plug,Sparkles,} from 'lucide-react';@@ -23,7 +26,16 @@ import { resolvePastedSessionMessageText } from './sessionLinkPaste';export interface MentionChipAttrs {/** Chip kind — decides icon + trailing slash behaviour + serialization. */- kind: 'file' | 'dir' | 'agent' | 'slash' | 'session' | 'project';+ kind:+ | 'file'+ | 'dir'+ | 'agent'+ | 'slash'+ | 'session'+ | 'project'+ | 'browser-tab'+ | 'desktop-window'+ | 'plugin-resource';/** Visible basename, Agent name, command, conversation title/message or project name. */label: string;/** Serialization path/deep-link. */@@ -33,6 +45,10 @@ export interface MentionChipAttrs {/** Readable target message body for the agent-facing projection. */agentText?: string;agentTextTruncated?: boolean;+ /** Plugin display name for an opaque business-resource reference. */+ sourceLabel?: string;+ /** Plugin-provided one-line resource summary. */+ sourceDescription?: string;}function displayLabel(attrs: MentionChipAttrs): string {@@ -47,6 +63,9 @@ function MentionIcon({ attrs }: { attrs: MentionChipAttrs }) {if (attrs.kind === 'dir') return <Folder aria-hidden />;if (attrs.kind === 'agent') return <Sparkles aria-hidden />;if (attrs.kind === 'project') return <FolderOpen aria-hidden />;+ if (attrs.kind === 'browser-tab') return <Globe2 aria-hidden />;+ if (attrs.kind === 'desktop-window') return <Monitor aria-hidden />;+ if (attrs.kind === 'plugin-resource') return <Plug aria-hidden />;return parseSessionDeepLinkHref(attrs.path)?.messageClientId ? (<MessageSquareQuote aria-hidden />) : (@@ -89,6 +108,8 @@ function MentionChipNodeView({ node, selected }: NodeViewProps) {data-titled={attrs.titled ? 'true' : undefined}data-agent-text={attrs.agentText}data-agent-text-truncated={attrs.agentTextTruncated ? 'true' : undefined}+ data-source-label={attrs.sourceLabel}+ data-source-description={attrs.sourceDescription}data-drag-handle=""draggable={true}contentEditable={false}@@ -159,6 +180,22 @@ export const MentionChipNode = Node.create<Record<string, never>, Record<string,attrs.agentTextTruncated ? { 'data-agent-text-truncated': 'true' } : {}),},+ sourceLabel: {+ default: undefined,+ parseHTML: (element) => element.getAttribute('data-source-label'),+ renderHTML: (attrs) => (+ typeof attrs.sourceLabel === 'string' ? { 'data-source-label': attrs.sourceLabel } : {}+ ),+ },+ sourceDescription: {+ default: undefined,+ parseHTML: (element) => element.getAttribute('data-source-description'),+ renderHTML: (attrs) => (+ typeof attrs.sourceDescription === 'string'+ ? { 'data-source-description': attrs.sourceDescription }+ : {}+ ),+ },};},@@ -230,6 +267,22 @@ const ICON_PATHS: Record<Exclude<MentionChipAttrs['kind'], 'slash'>, string[]> =project: ['m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2',],+ 'browser-tab': [+ 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20Z',+ 'M2 12h20',+ 'M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10Z',+ ],+ 'desktop-window': [+ 'M20 3H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2Z',+ 'M8 21h8',+ 'M12 17v4',+ ],+ 'plugin-resource': [+ 'M12 22v-5',+ 'M9 8V2',+ 'M15 8V2',+ 'M18 8v5a6 6 0 0 1-12 0V8Z',+ ],};const SESSION_MESSAGE_ICON_PATHS = [diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.tsindex 59f768f0d5..cdb8c9ec6f 100644--- a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts@@ -1,7 +1,12 @@import type { Editor } from '@tiptap/core';import { Fragment, Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';import { EditorState } from '@tiptap/pm/state';-import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';+import {+ parseBrowserTabReferenceHref,+ parseDesktopWindowReferenceHref,+ parsePluginResourceReferenceHref,+ type AgentInputReference,+} from '@cindy/maker-shared/agent-input-projection';import type { MentionedResource } from '@/lib/fileTypes';import { formatQuoteForSend } from '@/lib/chatQuotes';@@ -102,7 +107,14 @@ function serializeComposerDocument(const addMention = (attrs: MentionChipAttrs) => {// Slash commands and deep links are represented in the wire text but are// not filesystem resources.- if (attrs.kind === 'slash' || attrs.kind === 'session' || attrs.kind === 'project') return;+ if (+ attrs.kind === 'slash'+ || attrs.kind === 'session'+ || attrs.kind === 'project'+ || attrs.kind === 'browser-tab'+ || attrs.kind === 'desktop-window'+ || attrs.kind === 'plugin-resource'+ ) return;const key = `${attrs.kind}:${attrs.path}`;if (seenMentions.has(key)) return;seenMentions.add(key);@@ -267,6 +279,65 @@ function serializeComposerDocument(}return;}+ if (attrs.kind === 'browser-tab') {+ const label = attrs.label.replace(/\s+/g, ' ').trim().replace(/([\\\[\]])/g, '\\$1');+ const wire = `[${label || 'Browser tab'}](${attrs.path})`;+ const start = buffer.length;+ buffer += wire;+ const target = parseBrowserTabReferenceHref(attrs.path);+ if (target) {+ bufferAgentReferences.push({+ kind: 'browser-tab',+ start,+ end: buffer.length,+ href: attrs.path,+ tabId: target.tabId,+ url: target.url,+ ...(attrs.label ? { title: attrs.label } : {}),+ });+ }+ return;+ }+ if (attrs.kind === 'desktop-window') {+ const label = attrs.label.replace(/\s+/g, ' ').trim().replace(/([\\\[\]])/g, '\\$1');+ const wire = `[${label || 'Desktop window'}](${attrs.path})`;+ const start = buffer.length;+ buffer += wire;+ const target = parseDesktopWindowReferenceHref(attrs.path);+ if (target) {+ bufferAgentReferences.push({+ kind: 'desktop-window',+ start,+ end: buffer.length,+ href: attrs.path,+ windowId: target.windowId,+ pid: target.pid,+ appName: target.appName,+ ...(attrs.label ? { title: attrs.label } : {}),+ });+ }+ return;+ }+ if (attrs.kind === 'plugin-resource') {+ const label = attrs.label.replace(/\s+/g, ' ').trim().replace(/([\\\[\]])/g, '\\$1');+ const wire = `[${label || 'Plugin resource'}](${attrs.path})`;+ const start = buffer.length;+ buffer += wire;+ const target = parsePluginResourceReferenceHref(attrs.path);+ if (target) {+ bufferAgentReferences.push({+ kind: 'plugin-resource',+ start,+ end: buffer.length,+ href: attrs.path,+ ...target,+ pluginName: attrs.sourceLabel || target.ghostId,+ label: attrs.label || target.resourceId,+ ...(attrs.sourceDescription ? { description: attrs.sourceDescription } : {}),+ });+ }+ return;+ }if (attrs.kind === 'dir') {buffer += `@${formatMentionRef(`${attrs.path}/`)}`;return;diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex f8798d5742..6650728465 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -32,6 +32,7 @@ import {MoreVertical,PanelLeft,PanelRight,+ Plug,Radio,Sparkles,Terminal,@@ -98,6 +99,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {agent: Bot,node: Cpu,tool: Wrench,+ 'at-resource': Plug,command: Terminal,panel: PanelRight,code: FileCode2,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a987adfd48..930d9ef9da 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3380,6 +3380,8 @@"nodeResident": "The Node program can stay running in the background","nodeResidentDetail": "Runs while the plugin is enabled and stops when disabled, updated, uninstalled, or when Cindy exits.","tool": "Tool \"{{name}}\"",+ "atResourceProvider": "Can search Plugin resources in @ using \"{{name}}\"",+ "atResourceProviderDetail": "The tool runs only after you explicitly select this Plugin in @. Plugin authors must keep this search free of side effects.","command": "Chat command ${{command}}","panelLeft": "Panel \"{{title}}\" · docked left of the chat","panelTab": "Panel \"{{title}}\" · opens inside the Plugins page",@@ -5278,10 +5280,18 @@}},"atMention": {- "scanFailed": "Failed to scan working directory",+ "filesAndFolders": "Files and folders",+ "browserTab": "Browser tab",+ "desktopWindow": "App window",+ "task": "Task",+ "pluginResources": "Plugin resources",+ "pluginResource": "Plugin resource",+ "backToAll": "Back to all @ resources",+ "scanFailed": "Failed to load @ resources","retry": "Retry","searching": "Searching…",- "noMatch": "No matching files",+ "noMatch": "No matching items",+ "typeToSearchFiles": "Type a keyword to search files and sessions","keepTyping": "Keep typing to narrow down…"},"planReview": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 26d377c3b0..9819ec525e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3379,6 +3379,8 @@"nodeResident": "Node プログラムをバックグラウンドで常駐実行できます","nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。","tool": "ツール「{{name}}」",+ "atResourceProvider": "@ で「{{name}}」を使ってプラグインリソースを検索できます",+ "atResourceProviderDetail": "@ でこのプラグインを明示的に選択した後にのみツールが実行されます。プラグイン作者は検索に副作用がないことを保証する必要があります。","command": "チャット指令 ${{command}}","panelLeft": "パネル「{{title}}」· チャットの左側にドッキング","panelTab": "パネル「{{title}}」· プラグインページ内で開く",@@ -5276,10 +5278,18 @@}},"atMention": {- "scanFailed": "作業ディレクトリのスキャンに失敗しました",+ "filesAndFolders": "ファイルとフォルダ",+ "browserTab": "ブラウザタブ",+ "desktopWindow": "アプリウィンドウ",+ "task": "タスク",+ "pluginResources": "プラグインリソース",+ "pluginResource": "プラグインリソース",+ "backToAll": "すべての @ コンテンツに戻る",+ "scanFailed": "@ コンテンツの読み込みに失敗しました","retry": "再試行","searching": "検索中…",- "noMatch": "一致するファイルがありません",+ "noMatch": "一致する項目がありません",+ "typeToSearchFiles": "キーワードを入力してファイルとセッションを検索","keepTyping": "入力を続けて絞り込み…"},"planReview": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 8bda4d7b42..ce2bff6476 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3379,6 +3379,8 @@"nodeResident": "Node 프로그램을 백그라운드에서 계속 실행할 수 있음","nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.","tool": "도구 \"{{name}}\"",+ "atResourceProvider": "@에서 \"{{name}}\"으로 플러그인 리소스를 검색할 수 있음",+ "atResourceProviderDetail": "@에서 이 플러그인을 명시적으로 선택한 뒤에만 도구가 실행됩니다. 플러그인 작성자는 검색에 부작용이 없도록 해야 합니다.","command": "채팅 명령 ${{command}}","panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹","panelTab": "패널 \"{{title}}\" · 플러그인 페이지에서 열기",@@ -5276,10 +5278,18 @@}},"atMention": {- "scanFailed": "작업 디렉터리 스캔 실패",+ "filesAndFolders": "파일 및 폴더",+ "browserTab": "브라우저 탭",+ "desktopWindow": "앱 창",+ "task": "작업",+ "pluginResources": "플러그인 리소스",+ "pluginResource": "플러그인 리소스",+ "backToAll": "모든 @ 콘텐츠로 돌아가기",+ "scanFailed": "@ 콘텐츠를 불러오지 못했습니다","retry": "재시도","searching": "검색 중…",- "noMatch": "일치하는 파일 없음",+ "noMatch": "일치하는 항목 없음",+ "typeToSearchFiles": "키워드를 입력해 파일과 세션 검색","keepTyping": "계속 입력하여 범위 좁히기…"},"planReview": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b3c3f2ec2a..79532e727e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3379,6 +3379,8 @@"nodeResident": "Node 程序可常驻后台","nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。","tool": "工具「{{name}}」",+ "atResourceProvider": "可在 @ 中用「{{name}}」搜索插件资源",+ "atResourceProviderDetail": "只有你在 @ 中明确选中这个插件后才会调用该工具;插件作者必须保证搜索没有副作用。","command": "对话指令 ${{command}}","panelLeft": "面板「{{title}}」· 停靠主对话区左侧","panelTab": "面板「{{title}}」· 插件页内打开",@@ -5276,10 +5278,18 @@}},"atMention": {- "scanFailed": "扫描工作目录失败",+ "filesAndFolders": "文件和文件夹",+ "browserTab": "浏览器标签",+ "desktopWindow": "应用窗口",+ "task": "任务",+ "pluginResources": "插件资源",+ "pluginResource": "插件资源",+ "backToAll": "返回全部 @ 内容",+ "scanFailed": "加载 @ 内容失败","retry": "重试","searching": "搜索中…",- "noMatch": "没有匹配的文件",+ "noMatch": "没有匹配的内容",+ "typeToSearchFiles": "输入关键字搜索文件和任务","keepTyping": "继续输入以缩小范围…"},"planReview": {diff --git a/apps/desktop/src/renderer/lib/__tests__/atResourceInsertionGuard.test.ts b/apps/desktop/src/renderer/lib/__tests__/atResourceInsertionGuard.test.tsnew file mode 100644index 0000000000..c3640147fe--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/atResourceInsertionGuard.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { isAtResourceInsertTargetCurrent } from '@/lib/atResourceInsertionGuard';++function editorWithDoc(doc: unknown) {+ return {+ isDestroyed: false,+ state: { doc },+ };+}++describe('isAtResourceInsertTargetCurrent', () => {+ it('accepts the picker result while the originating document is unchanged', () => {+ const doc = {};+ const editor = editorWithDoc(doc);++ expect(isAtResourceInsertTargetCurrent(editor, editor, doc, 'task-a', 'task-a')).toBe(true);+ });++ it('rejects a late picker result after the composer document changes', () => {+ const originDoc = {};+ const editor = editorWithDoc(originDoc);+ editor.state.doc = {};++ expect(isAtResourceInsertTargetCurrent(editor, editor, originDoc, 'task-a', 'task-a')).toBe(+ false,+ );+ });++ it('rejects a result after the composer switches tasks with the same document', () => {+ const doc = {};+ const editor = editorWithDoc(doc);++ expect(isAtResourceInsertTargetCurrent(editor, editor, doc, 'task-a', 'task-b')).toBe(false);+ });++ it('rejects a result after the composer switches editors or is destroyed', () => {+ const doc = {};+ const editor = editorWithDoc(doc);++ expect(+ isAtResourceInsertTargetCurrent(editor, editorWithDoc(doc), doc, 'task-a', 'task-a'),+ ).toBe(false);+ editor.isDestroyed = true;+ expect(isAtResourceInsertTargetCurrent(editor, editor, doc, 'task-a', 'task-a')).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/lib/atResourceInsertionGuard.ts b/apps/desktop/src/renderer/lib/atResourceInsertionGuard.tsnew file mode 100644index 0000000000..5223fc0e36--- /dev/null+++ b/apps/desktop/src/renderer/lib/atResourceInsertionGuard.ts@@ -0,0 +1,25 @@+interface AtResourceInsertEditor {+ isDestroyed: boolean;+ state: { doc: unknown };+}++/**+ * Native resource picking is asynchronous. Only apply its result while the+ * originating editor and document are still current, so a late picker result+ * cannot replace text typed after the picker opened or content from another+ * task that reused the composer.+ */+export function isAtResourceInsertTargetCurrent(+ originEditor: AtResourceInsertEditor,+ currentEditor: AtResourceInsertEditor | null,+ originDoc: unknown,+ originStorageKey: string | undefined,+ currentStorageKey: string | undefined,+): boolean {+ return (+ currentEditor === originEditor &&+ !originEditor.isDestroyed &&+ originEditor.state.doc === originDoc &&+ currentStorageKey === originStorageKey+ );+}diff --git a/apps/desktop/src/renderer/lib/atResourceService.ts b/apps/desktop/src/renderer/lib/atResourceService.tsindex 325faa981e..b12f83a3f5 100644--- a/apps/desktop/src/renderer/lib/atResourceService.ts+++ b/apps/desktop/src/renderer/lib/atResourceService.ts@@ -1,4 +1,10 @@import { createLogger } from '@/lib/logger';+import type { Session } from '@/lib/ccAgent.types';+import { buildSessionDeepLink, strictEncodeURIComponent } from '@/lib/deepLink';+import {+ conversationSearchTitle,+ type ConversationSearchResponse,+} from '../../shared/conversationSearch';const log = createLogger('AtResourceService');/**@@ -13,7 +19,16 @@ const log = createLogger('AtResourceService');* This module is pure TS, no React. The panel component consumes it.*/-export type AtResourceType = 'file' | 'dir' | 'agent';+export type AtResourceType =+ | 'file-picker'+ | 'file'+ | 'dir'+ | 'agent'+ | 'browser-tab'+ | 'desktop-window'+ | 'session'+ | 'plugin-provider'+ | 'plugin-resource';export interface AtResourceItem {type: AtResourceType;@@ -23,13 +38,17 @@ export interface AtResourceItem {* - agent → filename without `.md`*/name: string;- /** workingDir-relative path, POSIX style. Used for:+ /** Workspace-relative path, an explicitly picked absolute path, or a stable Cindy context deep link. Used for:* - display "apps/server/src/routes" (minus basename) in right column* - serialization on submit: `@relPath` / `@relPath/` / `@.claude/agents/<name>.md`*/relPath: string;/** Agent description from YAML frontmatter (agents only). */description?: string;+ /** Plugin display name for provider/resource rows and Agent projection. */+ sourceLabel?: string;+ /** Stable Plugin id. Present on provider/resource rows only. */+ pluginId?: string;/** @internal Pre-computed lowercase for filter performance. */_nameLower?: string;/** @internal Pre-computed lowercase for filter performance. */@@ -43,12 +62,291 @@ export interface ScanResult {truncated: boolean;}+export const AT_MENTION_SEARCH_RESULT_LIMIT = 8;+export const AT_MENTION_EMPTY_WORKSPACE_SCAN_CAP = 2000;+export const AT_FILE_PICKER_RESOURCE: AtResourceItem = {+ type: 'file-picker',+ name: '',+ relPath: 'cindy://file-picker',+};++const EMPTY_QUERY_SECTION_LIMIT = 3;+const EMPTY_QUERY_RESULT_LIMIT = 12;+const TASK_SEARCH_CANDIDATE_LIMIT = 20;+const EMPTY_QUERY_SECTIONS: ReadonlyArray<ReadonlySet<AtResourceType>> = [+ new Set(['file-picker']),+ new Set(['browser-tab']),+ new Set(['agent']),+ new Set(['plugin-provider']),+];+export type PaletteAgentKind = 'claude-code' | 'codex' | 'pi';+export interface AtResourceScanContext {+ /** Current local task. Its built-in browser tabs are the only tabs exposed. */+ sessionId?: string;+ /** False for SSH/device-link so candidates never leak from the controller machine. */+ includeLocalContext?: boolean;+ /** Historical tasks are read from the execution device's local database. */+ includeTaskHistory?: boolean;+ /** Resolved i18n label used to match and display untitled tasks. */+ unnamedLabel?: string;+ /** Emit usable sources immediately while slower providers are still loading. */+ onPartial?: (result: ScanResult) => void;+}++function browserTabReference(tabId: string, url: string): string {+ return `cindy://browser-tab/${strictEncodeURIComponent(tabId)}?url=${strictEncodeURIComponent(url)}`;+}++function desktopWindowReference(+ pid: number,+ windowId: number,+ appName: string,+): string {+ return `cindy://desktop-window/${pid}/${windowId}?app=${strictEncodeURIComponent(appName)}`;+}++function oneLineText(value: unknown, maxLength: number): string {+ return typeof value === 'string'+ ? value.replace(/\s+/g, ' ').trim().slice(0, maxLength)+ : '';+}++const BROWSER_APP_STEMS = new Set([+ 'arc',+ 'brave',+ 'chrome',+ 'firefox',+ 'msedge',+ 'opera',+]);++function applicationStem(value: string): string {+ const basename = value.replace(/\\/g, '/').split('/').pop() ?? value;+ return basename.replace(/\.(?:exe|app)$/i, '').trim().toLowerCase();+}++function isBrowserApplication(value: string): boolean {+ return BROWSER_APP_STEMS.has(applicationStem(value));+}++function normalizedBrowserPageTitle(value: string): string {+ return oneLineText(value, 240)+ .replace(+ /\s+[-–—]\s+(?:google chrome|chrome|microsoft edge|mozilla firefox|firefox|brave|opera|arc)$/i,+ '',+ )+ .toLowerCase();+}++type RawWorkspaceScan = Awaited<ReturnType<typeof window.electronAPI.maker.scanAtResources>>;+type RawContextScan = Awaited<ReturnType<typeof window.electronAPI.maker.listAtContext>>;+type RawPluginProviders = Awaited<ReturnType<typeof window.electronAPI.ghosts.listAtResourceProviders>>;++function normalizeWorkspaceResources(res: RawWorkspaceScan | null): AtResourceItem[] {+ const agents: AtResourceItem[] = [];+ const files: AtResourceItem[] = [];+ const dirs: AtResourceItem[] = [];+ const agentNames = new Set<string>();++ for (const item of res?.items ?? []) {+ if (item.type !== 'agent') continue;+ agentNames.add(item.name);+ agents.push({+ type: 'agent', name: item.name, relPath: item.relPath,+ description: item.description,+ _nameLower: item.name.toLowerCase(),+ _relPathLower: item.relPath.toLowerCase(),+ });+ }+ for (const item of res?.items ?? []) {+ if (item.type === 'file') {+ const bare = item.name.replace(/\.md$/, '');+ if (agentNames.has(bare)) {+ log.warn(`File "${item.relPath}" conflicts with agent "${bare}"; agent wins.`);+ continue;+ }+ files.push({+ type: 'file', name: item.name, relPath: item.relPath,+ _nameLower: item.name.toLowerCase(),+ _relPathLower: item.relPath.toLowerCase(),+ });+ } else if (item.type === 'dir') {+ dirs.push({+ type: 'dir', name: item.name, relPath: item.relPath,+ _nameLower: item.name.toLowerCase(),+ _relPathLower: item.relPath.toLowerCase(),+ });+ }+ }+ return [...agents, ...dirs, ...files];+}++function normalizeContextResources(contextResult: RawContextScan | null): AtResourceItem[] {+ const contextual: AtResourceItem[] = [];+ const browserTabTitleKeys = new Set<string>();+ for (const tab of contextResult?.browserTabs ?? []) {+ const relPath = browserTabReference(tab.tabId, tab.url);+ const titleKey = normalizedBrowserPageTitle(tab.title);+ if (titleKey) browserTabTitleKeys.add(titleKey);+ contextual.push({+ type: 'browser-tab',+ name: tab.title,+ relPath,+ description: tab.url,+ _nameLower: tab.title.toLowerCase(),+ _relPathLower: `${tab.url} ${tab.tabId}`.toLowerCase(),+ });+ }+ const seenDesktopWindows = new Set<string>();+ for (const appWindow of contextResult?.desktopWindows ?? []) {+ const windowKey = `${appWindow.pid}:${appWindow.windowId}`;+ if (seenDesktopWindows.has(windowKey)) continue;+ seenDesktopWindows.add(windowKey);+ if (+ isBrowserApplication(appWindow.appName)+ && browserTabTitleKeys.has(normalizedBrowserPageTitle(appWindow.title))+ ) continue;+ const relPath = desktopWindowReference(+ appWindow.pid,+ appWindow.windowId,+ appWindow.appName,+ );+ contextual.push({+ type: 'desktop-window',+ name: appWindow.title,+ relPath,+ description: appWindow.appName,+ _nameLower: appWindow.title.toLowerCase(),+ _relPathLower: `${appWindow.appName} ${appWindow.pid} ${appWindow.windowId}`.toLowerCase(),+ });+ }+ return contextual;+}++function normalizeHistoricalTaskResources(+ sessions: Session[] | null,+ currentSessionId: string | undefined,+ deviceId: string | undefined,+ unnamedLabel: string | undefined,+): AtResourceItem[] {+ const historicalTasks: AtResourceItem[] = [];+ for (const session of sessions ?? []) {+ const taskId = oneLineText(session.id, 256);+ if (+ !taskId+ || taskId === currentSessionId+ || session.status !== 'active'+ || (!session.userSendAt && (session._count?.messages ?? 0) === 0)+ ) continue;+ const title = oneLineText(conversationSearchTitle(session.title, unnamedLabel), 240);+ if (!title) continue;+ const description = oneLineText(session.summary || session.preview, 300);+ const relPath = buildSessionDeepLink(taskId, { deviceId });+ historicalTasks.push({+ type: 'session',+ name: title,+ relPath,+ ...(description ? { description } : {}),+ _nameLower: title.toLowerCase(),+ _relPathLower: `${title} ${description} ${oneLineText(session.workingDir, 2_000)}`+ .toLowerCase(),+ });+ }+ return historicalTasks;+}++function normalizeHistoricalTaskSearchResources(+ response: ConversationSearchResponse | null,+ currentSessionId: string | undefined,+ deviceId: string | undefined,+ unnamedLabel: string | undefined,+): AtResourceItem[] {+ const historicalTasks: AtResourceItem[] = [];+ for (const result of response?.results ?? []) {+ const session = result.session;+ const taskId = oneLineText(session.id, 256);+ if (!taskId || taskId === currentSessionId || session.status !== 'active') continue;+ const title = oneLineText(conversationSearchTitle(session.title, unnamedLabel), 240);+ if (!title) continue;+ const description = oneLineText(result.contentHit?.preview, 300);+ historicalTasks.push({+ type: 'session',+ name: title,+ relPath: buildSessionDeepLink(taskId, { deviceId }),+ ...(description ? { description } : {}),+ _nameLower: title.toLowerCase(),+ _relPathLower: `${title} ${description} ${oneLineText(session.workingDir, 2_000)}`+ .toLowerCase(),+ });+ }+ return historicalTasks;+}++async function searchRemoteHistoricalTasks(+ deviceId: string,+ query: string,+ currentSessionId: string | undefined,+ unnamedLabel: string | undefined,+): Promise<AtResourceItem[]> {+ try {+ const response = await window.electronAPI.deviceLink.invoke(+ deviceId,+ 'local-db:conversations:search',+ [{+ query,+ limit: TASK_SEARCH_CANDIDATE_LIMIT,+ sortBy: 'relevance',+ semanticMode: 'keyword',+ filters: { status: 'active' },+ ...(unnamedLabel ? { unnamedLabel } : {}),+ }],+ ) as ConversationSearchResponse;+ return normalizeHistoricalTaskSearchResources(+ response,+ currentSessionId,+ deviceId,+ unnamedLabel,+ );+ } catch {+ // Older controlled clients do not allow the conversation-search channel.+ const sessions = await window.electronAPI.deviceLink.invoke(+ deviceId,+ 'local-db:sessions:list',+ [100, 'active'],+ ) as Session[];+ return normalizeHistoricalTaskResources(sessions, currentSessionId, deviceId, unnamedLabel);+ }+}++function normalizePluginProviderResources(+ result: RawPluginProviders | null,+): AtResourceItem[] {+ const pluginProviders: AtResourceItem[] = [];+ for (const provider of result?.items ?? []) {+ const ghostId = oneLineText(provider.ghostId, 32);+ const name = oneLineText(provider.name, 128);+ if (!ghostId || !name) continue;+ const description = oneLineText(provider.description, 256);+ pluginProviders.push({+ type: 'plugin-provider',+ name,+ relPath: ghostId,+ pluginId: ghostId,+ sourceLabel: name,+ ...(description ? { description } : {}),+ _nameLower: name.toLowerCase(),+ _relPathLower: `${ghostId} ${name} ${description}`.toLowerCase(),+ });+ }+ return pluginProviders;+}+/**- * Load candidate @-resources from the active agent/workspace. Returns `success:false`- * when workingDir is missing or IPC fails; panel should render the error- * state with a retry action in that case.+ * Load candidate @-resources from independent workspace/context providers.+ * Partial provider failures keep the remaining candidates usable; the caller+ * receives `success:false` only when every applicable provider failed.** De-dup rule (F5 spec): when an agent and a file share the same `name`,* the agent wins. This is extremely rare in practice but we log a warning@@ -64,75 +362,246 @@ export async function scanAtResources(* (workingDir 是被控端路径)。不传 = 本机扫描。channel 与本地完全一致,被控端跑同一 handler。*/deviceId?: string,+ context?: AtResourceScanContext,): Promise<ScanResult> {- if (!workingDir) {+ const includeLocalContext = context?.includeLocalContext === true;+ const includeTaskHistory = context?.includeTaskHistory === true;+ if (!workingDir && !includeLocalContext && !includeTaskHistory) {return { success: false, error: 'workingDir not bound', items: [], truncated: false };}- type RawScan = Awaited<ReturnType<typeof window.electronAPI.maker.scanAtResources>>;- const res: RawScan = deviceId- ? ((await window.electronAPI.deviceLink.invoke(deviceId, 'maker:scan-at-resources', [- agentKind,- { workingDir, cap, query },- ])) as RawScan)- : await window.electronAPI.maker.scanAtResources(agentKind, { workingDir, cap, query });- if (!res.success || !res.items) {+ const workspacePromise: Promise<RawWorkspaceScan | null> = workingDir+ ? deviceId+ ? (window.electronAPI.deviceLink.invoke(deviceId, 'maker:scan-at-resources', [+ agentKind,+ { workingDir, cap, query },+ ]) as Promise<RawWorkspaceScan>)+ : window.electronAPI.maker.scanAtResources(agentKind, { workingDir, cap, query })+ : Promise.resolve(null);+ const contextPromise = includeLocalContext+ ? window.electronAPI.maker.listAtContext({+ sessionId: context?.sessionId,+ workingDir: workingDir || undefined,+ query,+ limit: 40,+ })+ : Promise.resolve(null);+ const normalizedTaskQuery = query?.trim() ?? '';+ const taskHistoryPromise: Promise<AtResourceItem[] | null> = includeTaskHistory+ ? normalizedTaskQuery+ ? deviceId+ ? searchRemoteHistoricalTasks(+ deviceId,+ normalizedTaskQuery,+ context?.sessionId,+ context?.unnamedLabel,+ )+ : window.electronAPI.localDb.conversations.search({+ query: normalizedTaskQuery,+ limit: TASK_SEARCH_CANDIDATE_LIMIT,+ sortBy: 'relevance',+ semanticMode: 'keyword',+ filters: { status: 'active' },+ ...(context?.unnamedLabel ? { unnamedLabel: context.unnamedLabel } : {}),+ }).then((response) => normalizeHistoricalTaskSearchResources(+ response,+ context?.sessionId,+ undefined,+ context?.unnamedLabel,+ ))+ : deviceId+ ? (window.electronAPI.deviceLink.invoke(+ deviceId,+ 'local-db:sessions:list',+ [100, 'active'],+ ) as Promise<Session[]>).then((sessions) => normalizeHistoricalTaskResources(+ sessions,+ context?.sessionId,+ deviceId,+ context?.unnamedLabel,+ ))+ : window.electronAPI.localDb.sessions.list(100, 'active').then(+ (sessions) => normalizeHistoricalTaskResources(+ sessions,+ context?.sessionId,+ undefined,+ context?.unnamedLabel,+ ),+ )+ : Promise.resolve(null);+ const pluginProvidersPromise = !deviceId+ ? window.electronAPI.ghosts.listAtResourceProviders({+ ...(context?.sessionId ? { sessionId: context.sessionId } : {}),+ ...(workingDir ? { workingDir } : {}),+ })+ : Promise.resolve(null);++ const partial = {+ contextual: [] as AtResourceItem[],+ historicalTasks: [] as AtResourceItem[],+ pluginProviders: [] as AtResourceItem[],+ workspace: [] as AtResourceItem[],+ truncated: false,+ };+ const emitPartial = () => {+ if (!context?.onPartial) return;+ try {+ context.onPartial({+ success: true,+ items: [+ ...partial.contextual,+ ...partial.historicalTasks,+ ...partial.pluginProviders,+ ...partial.workspace,+ ],+ truncated: partial.truncated,+ });+ } catch (err) {+ log.warn('@ resource partial callback failed; continuing scan.', err);+ }+ };+ void workspacePromise.then((value) => {+ if (!value?.success || !value.items) return;+ partial.workspace = normalizeWorkspaceResources(value);+ partial.truncated = !!value.truncated;+ emitPartial();+ }, () => undefined);+ void contextPromise.then((value) => {+ if (!value) return;+ partial.contextual = normalizeContextResources(value);+ emitPartial();+ }, () => undefined);+ void taskHistoryPromise.then((value) => {+ if (!value) return;+ partial.historicalTasks = value;+ emitPartial();+ }, () => undefined);+ void pluginProvidersPromise.then((value) => {+ if (!value) return;+ partial.pluginProviders = normalizePluginProviderResources(value);+ emitPartial();+ }, () => undefined);++ const [workspaceSettled, contextSettled, taskHistorySettled, pluginProvidersSettled] = await Promise.allSettled([+ workspacePromise,+ contextPromise,+ taskHistoryPromise,+ pluginProvidersPromise,+ ]);+ const res = workspaceSettled.status === 'fulfilled' ? workspaceSettled.value : null;+ const contextResult = contextSettled.status === 'fulfilled' ? contextSettled.value : null;+ const workspaceFailed = !!workingDir && (+ workspaceSettled.status === 'rejected' || !res?.success || !res.items+ );+ const contextFailed = includeLocalContext && contextSettled.status === 'rejected';+ const taskHistoryFailed = includeTaskHistory && taskHistorySettled.status === 'rejected';+ const pluginProvidersFailed = !deviceId && pluginProvidersSettled.status === 'rejected';+ if (workspaceFailed) {+ log.warn(+ 'Workspace @ resource scan failed; keeping other providers available.',+ workspaceSettled.status === 'rejected' ? workspaceSettled.reason : res?.error,+ );+ }+ if (contextFailed) {+ log.warn(+ 'Local @ context scan failed; keeping other providers available.',+ contextSettled.status === 'rejected' ? contextSettled.reason : undefined,+ );+ }+ if (taskHistoryFailed) {+ log.warn(+ 'Historical @ task scan failed; keeping other providers available.',+ taskHistorySettled.status === 'rejected' ? taskHistorySettled.reason : undefined,+ );+ }+ if (pluginProvidersFailed) {+ log.warn(+ 'Plugin @ provider listing failed; keeping other providers available.',+ pluginProvidersSettled.status === 'rejected' ? pluginProvidersSettled.reason : undefined,+ );+ }+ if (+ (!workingDir || workspaceFailed)+ && (!includeLocalContext || contextFailed)+ && (!includeTaskHistory || taskHistoryFailed)+ && (deviceId !== undefined || pluginProvidersFailed)+ ) {return {success: false,- error: res.error ?? 'scan failed',+ error: res?.error ?? 'scan failed',items: [],- truncated: !!res.truncated,+ truncated: !!res?.truncated,};}// Split into buckets so we can apply the agent-wins rule, then// reassemble in a deterministic order (agents first in the raw list —// the UI will re-rank during filtering anyway).- const agents: AtResourceItem[] = [];- const files: AtResourceItem[] = [];- const dirs: AtResourceItem[] = [];- const agentNames = new Set<string>();+ const workspace = normalizeWorkspaceResources(res);- for (const item of res.items) {- if (item.type === 'agent') {- agentNames.add(item.name);- agents.push({- type: 'agent', name: item.name, relPath: item.relPath,- description: item.description,- _nameLower: item.name.toLowerCase(),- _relPathLower: item.relPath.toLowerCase(),- });- }- }- for (const item of res.items) {- if (item.type === 'file') {- const bare = item.name.replace(/\.md$/, '');- if (agentNames.has(bare)) {- log.warn(- `File "${item.relPath}" conflicts with agent "${bare}"; agent wins.`,- );- continue;- }- files.push({- type: 'file', name: item.name, relPath: item.relPath,- _nameLower: item.name.toLowerCase(),- _relPathLower: item.relPath.toLowerCase(),- });- } else if (item.type === 'dir') {- dirs.push({- type: 'dir', name: item.name, relPath: item.relPath,- _nameLower: item.name.toLowerCase(),- _relPathLower: item.relPath.toLowerCase(),- });- }- }+ const contextual = normalizeContextResources(contextResult);+ const historicalTasks = taskHistorySettled.status === 'fulfilled'+ && Array.isArray(taskHistorySettled.value)+ ? taskHistorySettled.value+ : [];+ const pluginProviders = normalizePluginProviderResources(+ pluginProvidersSettled.status === 'fulfilled' ? pluginProvidersSettled.value : null,+ );return {success: true,- items: [...agents, ...dirs, ...files],- truncated: !!res.truncated,+ items: [...contextual, ...historicalTasks, ...pluginProviders, ...workspace],+ truncated: !!res?.truncated,};}+/** Search exactly one provider after the user explicitly selected it. */+export async function scanPluginAtResources(+ provider: AtResourceItem,+ query: string,+ workingDir?: string,+ sessionId?: string,+): Promise<ScanResult> {+ if (provider.type !== 'plugin-provider' || !provider.pluginId) {+ return { success: false, error: 'Plugin resource provider unavailable', items: [], truncated: false };+ }+ const result = await window.electronAPI.ghosts.queryAtResources({+ ghostId: provider.pluginId,+ ...(sessionId ? { sessionId } : {}),+ ...(workingDir ? { workingDir } : {}),+ query: query.trim(),+ limit: 20,+ });+ if (!result.success) {+ return {+ success: false,+ error: result.error ?? 'Plugin resource search failed',+ items: [],+ truncated: false,+ };+ }+ const sourceLabel = oneLineText(result.pluginName || provider.sourceLabel || provider.name, 128);+ const items: AtResourceItem[] = [];+ for (const row of result.items) {+ const name = oneLineText(row.label, 128);+ const relPath = typeof row.href === 'string' && row.href.length <= 1_500+ ? oneLineText(row.href, 1_500)+ : '';+ if (!name || !relPath) continue;+ const description = oneLineText(row.description, 256);+ items.push({+ type: 'plugin-resource',+ name,+ relPath,+ pluginId: provider.pluginId,+ sourceLabel,+ ...(description ? { description } : {}),+ _nameLower: name.toLowerCase(),+ _relPathLower: `${name} ${description}`.toLowerCase(),+ });+ }+ return { success: true, items, truncated: result.truncated };+}+/*** Lightweight fuzzy scorer. Returns a positive number (higher = better) if* the query characters appear in order inside `name` or `relPath`. Returns@@ -169,26 +638,102 @@ function fuzzyInOrder(hay: string, needle: string): boolean {return i === needle.length;}+function emptyQueryResources(items: AtResourceItem[], limit: number): AtResourceItem[] {+ const selected: AtResourceItem[] = [];+ for (const types of EMPTY_QUERY_SECTIONS) {+ let sectionCount = 0;+ for (const item of items) {+ if (!types.has(item.type)) continue;+ selected.push(item);+ sectionCount += 1;+ if (selected.length >= limit) return selected;+ if (sectionCount >= EMPTY_QUERY_SECTION_LIMIT) break;+ }+ }+ return selected;+}++/** Return a path prefix when a directory can remain inside the active @ query. */+export function getAtDirectoryCompletionQuery(+ item: AtResourceItem,+ allowWhitespace = false,+): string | null {+ if (item.type !== 'dir') return null;+ const relPath = item.relPath.replace(/\\/g, '/').replace(/\/+$/, '');+ if (!relPath || relPath.includes('@') || (!allowWhitespace && /\s/.test(relPath))) return null;+ return `${relPath}/`;+}++/** Build an item returned by the native picker without importing Node path APIs. */+export function createAtResourceFromNativePath(+ selectedPath: string,+ kind: 'file' | 'directory',+ workingDir?: string | null,+): AtResourceItem | null {+ const trimmedPath = selectedPath.trim();+ if (!trimmedPath) return null;++ const normalizedPath = trimmedPath.replace(/\\/g, '/');+ const normalizedWorkingDir = workingDir?.trim().replace(/\\/g, '/').replace(/\/+$/, '') ?? '';+ const windowsPath = /^[A-Za-z]:\//.test(normalizedWorkingDir);+ const comparablePath = windowsPath ? normalizedPath.toLowerCase() : normalizedPath;+ const comparableWorkingDir = windowsPath+ ? normalizedWorkingDir.toLowerCase()+ : normalizedWorkingDir;+ const isInsideWorkingDir = !!comparableWorkingDir+ && comparablePath.startsWith(`${comparableWorkingDir}/`);+ const relPath = isInsideWorkingDir+ ? normalizedPath.slice(normalizedWorkingDir.length + 1)+ : trimmedPath;+ const name = normalizedPath.split('/').filter(Boolean).pop() ?? trimmedPath;++ return { type: kind === 'directory' ? 'dir' : 'file', name, relPath };+}++/** Keep usable candidates visible while a narrower async query is still loading. */+export function mergeAtResourceItems(+ previous: readonly AtResourceItem[],+ incoming: readonly AtResourceItem[],+): AtResourceItem[] {+ const merged: AtResourceItem[] = [];+ const seen = new Set<string>();+ for (const item of [...incoming, ...previous]) {+ const key = `${item.type}:${item.pluginId ?? ''}:${item.relPath}`;+ if (seen.has(key)) continue;+ seen.add(key);+ merged.push(item);+ }+ return merged;+}+/**- * Filter + rank against a query. Agents and files are ranked together in- * the same pool (F5: "agent 项与文件项完全平铺"), no artificial boost for- * one type over the other — the raw scorer already privileges name matches- * and agents tend to have short memorable names so they naturally rise.+ * Empty queries expose only a small curated set of contextual resources.+ * Once the user types, every source — including files and directories — is+ * ranked in the same pool and capped to a compact global result list.*/export function filterAtResources(items: AtResourceItem[],query: string,- limit = 25,+ limit?: number,): AtResourceItem[] {const q = query.trim().toLowerCase();+ const resultLimit = limit ?? (+ q ? AT_MENTION_SEARCH_RESULT_LIMIT : EMPTY_QUERY_RESULT_LIMIT+ );+ if (!q) return emptyQueryResources(items, resultLimit);const scored: Array<{ item: AtResourceItem; score: number }> = [];for (const item of items) {+ if (item.type === 'file-picker') continue;const s = scoreItem(item, q);if (s >= 0) scored.push({ item, score: s });}- scored.sort((a, b) => b.score - a.score);+ scored.sort((a, b) => (+ b.score - a.score+ || a.item.name.localeCompare(b.item.name)+ || a.item.relPath.localeCompare(b.item.relPath)+ ));// Cap rendered items — the panel is max ~9 visible rows; rendering- // beyond `limit` wastes DOM nodes and causes jank on large projects.- if (scored.length > limit) scored.length = limit;+ // beyond `resultLimit` wastes DOM nodes and causes jank on large projects.+ if (scored.length > resultLimit) scored.length = resultLimit;return scored.map((s) => s.item);}diff --git a/apps/desktop/src/renderer/lib/deepLink.ts b/apps/desktop/src/renderer/lib/deepLink.tsindex 55a96dab10..55f2192211 100644--- a/apps/desktop/src/renderer/lib/deepLink.ts+++ b/apps/desktop/src/renderer/lib/deepLink.ts@@ -61,7 +61,7 @@ export function buildSessionMessageDeepLink(* (review P2)。构建端把五个字符也转成 %XX,生成的深链永不含裸定界符;* decodeURIComponent 对 %21 %27 %28 %29 %2A 原生可解,解析端零改动。*/-function strictEncodeURIComponent(value: string): string {+export function strictEncodeURIComponent(value: string): string {return encodeURIComponent(value).replace(/[!'()*]/g,(ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`,diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 4706dd2fbe..da32617222 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1121,6 +1121,24 @@ interface ElectronAPI {* 引导去配置。未装 NOT_FOUND。*/setupStatus: (id: string) => Promise<import('../shared/ghost').GhostSetupStatus>;+ /** 只列入口元数据,不运行插件工具;远程/device-link 不暴露。 */+ listAtResourceProviders: (params: { sessionId?: string; workingDir?: string }) => Promise<{+ items: Array<{ ghostId: string; name: string; description?: string }>;+ }>;+ /** 用户选定一个入口后,按固定只读摘要契约搜索该插件。 */+ queryAtResources: (params: {+ ghostId: string;+ sessionId?: string;+ workingDir?: string;+ query?: string;+ limit?: number;+ }) => Promise<{+ success: boolean;+ error?: string;+ pluginName?: string;+ items: Array<{ id: string; label: string; description?: string; href: string }>;+ truncated: boolean;+ }>;/** 最近使用顺序变化(发送 /卸载),多窗口同步。 */onRecentUsageChanged: (callback: (payload: { ids: string[] }) => void,@@ -3971,6 +3989,12 @@ interface ElectronAPI {success: boolean;path: string | null;}>;+ /** 打开 @ 资源系统选择器;macOS 可选文件或目录,Windows/Linux 选择文件。 */+ showOpenResource: (params?: { defaultPath?: string }) => Promise<{+ success: true;+ path: string | null;+ kind: 'file' | 'directory' | null;+ }>;};// electronAPI.codex 已退役 —— auth / binary status / usage / OAuth 登录进度 全部@@ -4280,6 +4304,22 @@ interface ElectronAPI {>;truncated?: boolean;}>;+ listAtContext: (params: {+ sessionId?: string;+ workingDir?: string;+ query?: string;+ limit?: number;+ }) => Promise<{+ success: true;+ browserTabs: Array<{ tabId: string; title: string; url: string }>;+ desktopWindows: Array<{+ windowId: number;+ pid: number;+ appName: string;+ title: string;+ }>;+ unavailable: Array<'browser-tabs' | 'desktop-windows'>;+ }>;createSession: (opts: {/** 可选: 复用外部 sessionId(本端 chat 用 local-db:sessions:create 拿到的 id) */diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 6b7f97d71b..1cd3620c40 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import {GHOST_CARD_ACTION_ID_RE,GHOST_CINDY_DEPOSIT_QUOTA_BYTES,+ GHOST_SLOTS,deriveGhostSessionContext,diffGhostPermissionItems,ghostContentKeys,@@ -10,6 +11,7 @@ import {ghostLocalePathFor,ghostNetworkHostMatches,ghostPanelKind,+ ghostPermissionBaselineKey,ghostPreviewUrlAllowed,parseGhostNodeChildToHostMessage,ghostPartition,@@ -1011,6 +1013,91 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {).toBe(false);});+ it('@ 资源入口只可引用一个已声明工具,并按已知字段收窄', () => {+ const base = {+ ...goodChipManifest(),+ slots: ['panel', 'tool'],+ tools: [{ name: 'search_issues', description: '只读搜索议题' }],+ };+ const valid = validateGhostManifest({+ ...base,+ atResourceProvider: { tool: 'search_issues' },+ });+ expect(valid.ok).toBe(true);+ expect(valid.ok && valid.manifest.atResourceProvider).toEqual({ tool: 'search_issues' });++ const missing = validateGhostManifest({+ ...base,+ atResourceProvider: { tool: 'missing' },+ });+ const extraField = validateGhostManifest({+ ...base,+ atResourceProvider: { tool: 'search_issues', label: 'Issues' },+ });+ expect(missing.ok).toBe(true);+ expect(extraField.ok).toBe(true);+ expect(missing.ok ? missing.manifest.atResourceProvider : null).toBeUndefined();+ expect(extraField.ok ? extraField.manifest.atResourceProvider : null).toBeUndefined();+ });++ it('忽略旧 manifest 中无效的同名未知字段', () => {+ const base = {+ ...goodChipManifest(),+ slots: ['panel', 'tool'],+ tools: [{ name: 'search_issues', description: '只读搜索议题' }],+ };+ for (const legacyValue of [+ null,+ true,+ 'legacy',+ [],+ {},+ { label: 'Issues' },+ ]) {+ const result = validateGhostManifest({+ ...base,+ atResourceProvider: legacyValue,+ });+ expect(result.ok, JSON.stringify(legacyValue)).toBe(true);+ expect(result.ok && result.manifest.atResourceProvider).toBeUndefined();+ }+ });++ it('@ 资源入口复用 tool 槽,不新增硬白名单 slot', () => {+ expect(GHOST_SLOTS).not.toContain('at-resource');+ expect(validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'tool', 'at-resource'],+ tools: [{ name: 'search_issues', description: '只读搜索议题' }],+ atResourceProvider: { tool: 'search_issues' },+ }).ok).toBe(false);+ });++ it('@ 资源入口复用原工具执行权,但作为新增调用入口单独披露', () => {+ const raw = {+ ...goodChipManifest(),+ slots: ['panel', 'tool'],+ tools: [{ name: 'search_issues', description: '只读搜索议题' }],+ };+ const before = validateGhostManifest(raw);+ const after = validateGhostManifest({+ ...raw,+ atResourceProvider: { tool: 'search_issues' },+ });+ expect(before.ok && after.ok).toBe(true);+ if (!before.ok || !after.ok) return;+ expect(ghostPermissionBaselineKey(after.manifest)).not.toBe(+ ghostPermissionBaselineKey(before.manifest),+ );+ expect(diffGhostPermissionItems(before.manifest, after.manifest).added).toEqual([+ expect.objectContaining({+ key: 'at-resource:search_issues',+ kind: 'at-resource',+ labelKey: 'atResourceProvider',+ }),+ ]);+ });+it('会进入 locale 对象索引的清单 key 统一拒绝对象保留键名', () => {const reservedKeys = ['__proto__', 'constructor', 'prototype'];const withoutPanel = (manifest: Record<string, unknown>) => {diff --git a/apps/desktop/src/shared/atContextRouteScope.ts b/apps/desktop/src/shared/atContextRouteScope.tsnew file mode 100644index 0000000000..772ffe7287--- /dev/null+++ b/apps/desktop/src/shared/atContextRouteScope.ts@@ -0,0 +1,44 @@+const NON_SESSION_CC_AGENT_ROUTES = new Set([+ 'boot',+ 'files',+ 'new',+ 'new-dialogue',+ 'orca',+ 'scheduled',+]);++function routeSessionId(value: string | null): string | null {+ const sessionId = value?.trim() ?? '';+ if (+ !sessionId+ || sessionId.length > 256+ || sessionId.includes('/')+ || NON_SESSION_CC_AGENT_ROUTES.has(sessionId)+ ) return null;+ return sessionId;+}++export function atContextVisibleSessionIdsFromRendererUrl(rendererUrl: string): Set<string> {+ const sessionIds = new Set<string>();+ try {+ const appUrl = new URL(rendererUrl);+ const route = appUrl.hash.startsWith('#') ? appUrl.hash.slice(1) : '';+ if (!route.startsWith('/')) return sessionIds;+ const routeUrl = new URL(route, 'cindy://renderer');+ const segments = routeUrl.pathname.split('/').filter(Boolean);+ if (segments[0] !== 'cc-agent') return sessionIds;++ if (segments.length === 2) {+ const primary = routeSessionId(decodeURIComponent(segments[1] ?? ''));+ if (primary) sessionIds.add(primary);+ const worker = routeSessionId(routeUrl.searchParams.get('worker'));+ if (worker) sessionIds.add(worker);+ } else if (segments.length === 3 && segments[1] === 'orca') {+ const legacyOrcaSession = routeSessionId(decodeURIComponent(segments[2] ?? ''));+ if (legacyOrcaSession) sessionIds.add(legacyOrcaSession);+ }+ } catch {+ // Invalid or transient renderer locations fail closed.+ }+ return sessionIds;+}diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 153f5c8367..b9417371b6 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -388,6 +388,19 @@ export interface GhostToolDecl {parameters?: Record<string, unknown>;}+/**+ * 把一个已经声明、已经过权限确认的工具接入 Composer `@` 资源搜索。+ *+ * 这不是新卡槽,也不扩大底层工具权限:旧宿主会按顶层未知字段兼容忽略;新版宿主+ * 仅在用户明确选中该插件的资源入口后,以固定 `{ query, limit }` 参数调用该工具。+ * 调用入口会单独进入安装/更新权限清单;工具必须无副作用,返回值由宿主按固定+ * 资源摘要协议裁剪。+ */+export interface GhostAtResourceProviderDecl {+ /** 必须逐字引用同一 manifest 的 tools[].name。 */+ tool: string;+}+/** cindy 槽·图像类可申请的动作(主机代办菜单的"图像"类目)。 */export const GHOST_MODEL_IMAGE_ACTIONS = ['generate', 'edit'] as const;export type GhostModelImageAction = (typeof GHOST_MODEL_IMAGE_ACTIONS)[number];@@ -1212,6 +1225,8 @@ export interface GhostManifest {card?: GhostCardNeeds;/** 注册给 agent 的工具声明(与 slots 含 'tool' 成对)。 */tools?: GhostToolDecl[];+ /** 可选的 `@` 业务资源搜索入口;复用已声明工具并单独披露调用入口。 */+ atResourceProvider?: GhostAtResourceProviderDecl;/*** cindy 槽能力详单(与 slots 含 'cindy' 成对;缺省 = 零能力,任何代办* 都会被拒并提示作者补声明)。清单里的旧字段名 model 在校验层作别名@@ -1423,7 +1438,7 @@ export interface GhostPermissionItem {/** 稳定键:更新 diff 按它对齐(内容变化视为移除+新增,如面板换边)。 */key: string;/** 图标分组(renderer 按 kind 选图标)。 */- kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'confirm' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill' | 'workspace';+ kind: 'cindy' | 'agent' | 'node' | 'tool' | 'at-resource' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'confirm' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill' | 'workspace';/** i18n key 后缀,消费方拼 `settings.ghosts.perm.<labelKey>`。 */labelKey: string;/** i18n 插值参数(工具名、指令名、面板标题等)。 */@@ -1693,6 +1708,15 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetail: tool.description,});}+ if (manifest.atResourceProvider) {+ items.push({+ key: `at-resource:${manifest.atResourceProvider.tool}`,+ kind: 'at-resource',+ labelKey: 'atResourceProvider',+ labelArgs: { name: manifest.atResourceProvider.tool },+ detailKey: 'atResourceProviderDetail',+ });+ }if (manifest.command) {items.push({key: `command:${manifest.command}`,@@ -2836,6 +2860,25 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'slots 声明了 "tool" 但缺少 tools(注册什么工具要写清楚)' };}+ /**+ * `@` 资源入口复用 `tool` 槽,不另造硬白名单 slot:旧版宿主会接受这类包,+ * 并像其它未知顶层字段一样忽略 atResourceProvider。这个字段在本版之前也可能被+ * 存量包当作自定义元数据使用,因此这里仅收窄出待审声明;安装运行时还必须命中+ * Main 在 install/update 后写下的 host receipt。其它历史形态继续忽略,避免客户端+ * 升级后让已安装插件消失或凭字段形状自动扩权。+ */+ let atResourceProvider: GhostAtResourceProviderDecl | undefined;+ if (isPlainObject(raw.atResourceProvider)) {+ const providerRaw = raw.atResourceProvider as Record<string, unknown>;+ if (+ Object.keys(providerRaw).length === 1+ && typeof providerRaw.tool === 'string'+ && tools?.some((tool) => tool.name === providerRaw.tool)+ ) {+ atResourceProvider = { tool: providerRaw.tool };+ }+ }+// cindy 槽能力详单:与 slots 含 'cindy' 成对(有详单必有槽;有槽无详单// 允许装入但运行时零能力——老包不消失,只是代办被拒并提示作者更新)。// 字段旧名 model 作别名收入(两个都写以 cindy 为准)。@@ -4192,6 +4235,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),slots,...(tools !== undefined ? { tools } : {}),+ ...(atResourceProvider !== undefined ? { atResourceProvider } : {}),...(card !== undefined ? { card } : {}),...(cindy !== undefined ? { cindy } : {}),...(agent !== undefined ? { agent } : {}),diff --git a/apps/mobile/src/__tests__/composerDocument.test.ts b/apps/mobile/src/__tests__/composerDocument.test.tsindex 24ae6346b8..fbf55d38f8 100644--- a/apps/mobile/src/__tests__/composerDocument.test.ts+++ b/apps/mobile/src/__tests__/composerDocument.test.ts@@ -215,6 +215,30 @@ describe('mobile composer document', () => {expect(serializeComposerDocument(restored)).toEqual(serialized);});+ it('keeps unsupported Desktop Plugin references as exact editable wire text', () => {+ const href = 'cindy://plugin-resource/issues/search_issues/ISSUE-1';+ const text = `[Fix login](${href})`;+ const restored = composerDocumentFromSerializedMessage(text, {+ agentReferences: [{+ kind: 'plugin-resource',+ start: 0,+ end: text.length,+ href,+ ghostId: 'issues',+ tool: 'search_issues',+ resourceId: 'ISSUE-1',+ pluginName: 'Issue Tracker',+ label: 'Fix login',+ }],+ });++ expect(composerDocumentProjectedText(restored)).toBe(text);+ expect(serializeComposerDocument(restored)).toMatchObject({+ text,+ agentReferences: [],+ });+ });+it('replaces projected text without changing the surrounding atom', () => {const document = {version: 1 as const,diff --git a/apps/mobile/src/session/composerDocument.ts b/apps/mobile/src/session/composerDocument.tsindex 5f4249fba7..3c5d95e23b 100644--- a/apps/mobile/src/session/composerDocument.ts+++ b/apps/mobile/src/session/composerDocument.ts@@ -614,14 +614,20 @@ function composerNodeFromAgentReference(titled: Boolean(reference.title),});}- return {- type: 'mention',- kind: 'project',- label: reference.name,- raw,- href: reference.href,- workingDir: reference.workingDir,- };+ if (reference.kind === 'project') {+ return {+ type: 'mention',+ kind: 'project',+ label: reference.name,+ raw,+ href: reference.href,+ workingDir: reference.workingDir,+ };+ }+ // Desktop-only live context and Plugin resources have no Mobile atom yet.+ // Preserve the exact wire span as editable text instead of miscasting it as+ // a project mention or dropping user-visible content.+ return { type: 'text', text: raw };}function composerNodesFromTextSegment(diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 87a3efe95f..cdc4083313 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -114,7 +114,7 @@- **Quota** — 周期内的使用上限用「配额」(现状已有 3 处这么写)。与 credits 条目一起裁决:「额度」原先同时表示 Balance / Credits / Quota,三个概念在计费与限额提示里互相污染。「额度」的 forbidden 统一登记在 credits 条目下,不在这里重复——一个词只归属一个术语,否则同一处违规会被两个术语各报一次。(2026-07 修正:ko 原声明 쿼터 在全仓零出现,属凭空造词;ja 原声明 クォータ 仅 desktop 用、mobile 用 残量。定为 ja クォータ / ko 할당량——残量 语义偏 Balance 会与 残高 混淆,而 ko 的 사용량 正是 Usage 的标准词,让 Quota 占用它会重演 zh「额度」三义合一的错误。)- **Running** — 状态标签用「运行中」(现状 16:9)。条件禁用是必需的——「进行中」是 In Progress 的正确译法、「执行中」在别处也可能对,无条件禁会大面积误伤。mobile/devices 的自动化面板上「运行中 / 执行中 / 重跑中」三种写法同屏出现。- **Session** — 面向用户叫「任务」——它是左侧列表里可单独打开/删除/分享的条目,有自己的独立空间、可以同时跑多个;「对话」表达不出这个并行性(2026-07-31 裁决,替代此前的「对话」)。任务内人与 AI 交流的过程与内容仍叫「对话」,见 alsoAllowed 与 chat 条目。「会话」继续禁用于产品概念。但英文的 session 在本仓实际承载**五个**不同概念,其中最容易译错、也最影响用户行为的是 Agent 运行时会话——已单独立为 agent-session 条目,中文叫「Agent 会话」,务必先读它再改这类文案;余下三类(登录/绑定校验、SSH 远程与传输、操作系统桌面)与 mobile 语音连接会话都与产品无关,存量译法不在本条约束内,见本条 exempt。代码与内部标识仍用 Session,本条只约束 UI 文案。ja / ko 用音译 `セッション` / `세션`,本次一并收敛:改名前这两种语言就在混用(音译 271 / 277 处 vs `会話`・`대화` 16 / 11 处),改完英文后不一致放大到 133 处,2026-07-31 逐条判断后统一到音译(详见 docs/product-rules/task-and-conversation-naming.md §5.1)。日韩不存在中文那种一词多义问题,所以 `タスク` / `작업`(task)无需像中文那样改写成「自动化」。交流过程仍用 `会話` / `대화`,chat history 仍用 `チャット履歴` / `채팅 기록`。概念分层与判定规则见 docs/product-rules/task-and-conversation-naming.md。- - 豁免范围:`desktop:settings.providers.custom.fields.modelSupportsReasoningHelp`、`desktop:chat.backgroundActivity.stopBashTitle`、`desktop:chat.remoteError.REMOTE_COMPAT_MODE_UNSUPPORTED`、`desktop:chat.rewind.errors.remoteNotSupported`、`desktop:chat.systemCard.context.noLiveSession`、`desktop:chat.userMessage.forkErrors.codexStateUnavailable`、`desktop:chat.rewind.errors.noLiveQuery`、`desktop:chat.userMessage.forkErrors.unsupportedHistory`、`desktop:login.errors.INVALID_BIND_TICKET`、`desktop:login.errors.INVALID_LOGIN_TICKET`、`desktop:newChat.chatInput.agentSwitch.confirmation.description`、`desktop:newChat.collaboration.archiveWorkerConfirmDesc`、`desktop:newChat.collaboration.stopConfirmDesc`、`desktop:settings.about.debugLogDescription`、`desktop:settings.builtinTools.toast.disabled`、`desktop:settings.builtinTools.toast.enabled`、`desktop:settings.builtinTools.toggleHint`、`desktop:settings.builtinTools.description`、`desktop:settings.builtinTools.scopePicker.userDefault`、`desktop:settings.builtinTools.scopePicker.userDefaultDescription`、`desktop:settings.builtinTools.source.userTooltip`、`desktop:settings.computerUse.android.toggleHint`、`desktop:settings.computerUse.browser.toggleHint`、`desktop:settings.computerUse.codexRefreshDeferred`、`desktop:settings.computerUse.directControl.permissions.linuxHint`、`desktop:settings.computerUse.directControl.toggleHint`、`desktop:settings.lspMode.toast.disabled`、`desktop:settings.memory.agent.toast.takesEffectSuffix`、`desktop:settings.sessionImport.description`、`desktop:settings.sessionImport.summary.filteredHint`、`desktop:settings.mcp.dialog.desc`、`desktop:settings.mcp.deleteConfirm.message`、`desktop:settings.memory.description`、`desktop:settings.lspMode.toast.enabled`、`desktop:settings.personalization.placeholder`、`desktop:settings.subagentModels.hint`、`desktop:newChat.modelSelector.subscriptionDirectDisabled.chatgpt`、`desktop:newChat.modelSelector.subscriptionDirectDisabled.xai`、`desktop:newChat.modelSelector.subscriptionDirectDisabled.generic`、`desktop:ccAgent.draft.remoteProviderUnsupported`、`desktop:ipcError.REMOTE_PROVIDER_UNSUPPORTED`、`mobile/composer:voice.invalidSession`、`mobile/composer:voice.missingConnectionProvider`、`mobile/composer:voice.missingRefinerTargetProvider`、`mobile/composer:voice.sessionExpiredOrForbidden`、`mobile/composer:voice.sessionNotConnected`+ - 豁免范围:`desktop:settings.providers.custom.fields.modelSupportsReasoningHelp`、`desktop:chat.backgroundActivity.stopBashTitle`、`desktop:chat.remoteError.REMOTE_COMPAT_MODE_UNSUPPORTED`、`desktop:chat.rewind.errors.remoteNotSupported`、`desktop:chat.systemCard.context.noLiveSession`、`desktop:chat.userMessage.forkErrors.codexStateUnavailable`、`desktop:chat.rewind.errors.noLiveQuery`、`desktop:chat.userMessage.forkErrors.unsupportedHistory`、`desktop:login.errors.INVALID_BIND_TICKET`、`desktop:login.errors.INVALID_LOGIN_TICKET`、`desktop:newChat.atMention.typeToSearchFiles`、`desktop:newChat.chatInput.agentSwitch.confirmation.description`、`desktop:newChat.collaboration.archiveWorkerConfirmDesc`、`desktop:newChat.collaboration.stopConfirmDesc`、`desktop:settings.about.debugLogDescription`、`desktop:settings.builtinTools.toast.disabled`、`desktop:settings.builtinTools.toast.enabled`、`desktop:settings.builtinTools.toggleHint`、`desktop:settings.builtinTools.description`、`desktop:settings.builtinTools.scopePicker.userDefault`、`desktop:settings.builtinTools.scopePicker.userDefaultDescription`、`desktop:settings.builtinTools.source.userTooltip`、`desktop:settings.computerUse.android.toggleHint`、`desktop:settings.computerUse.browser.toggleHint`、`desktop:settings.computerUse.codexRefreshDeferred`、`desktop:settings.computerUse.directControl.permissions.linuxHint`、`desktop:settings.computerUse.directControl.toggleHint`、`desktop:settings.lspMode.toast.disabled`、`desktop:settings.memory.agent.toast.takesEffectSuffix`、`desktop:settings.sessionImport.description`、`desktop:settings.sessionImport.summary.filteredHint`、`desktop:settings.mcp.dialog.desc`、`desktop:settings.mcp.deleteConfirm.message`、`desktop:settings.memory.description`、`desktop:settings.lspMode.toast.enabled`、`desktop:settings.personalization.placeholder`、`desktop:settings.subagentModels.hint`、`desktop:newChat.modelSelector.subscriptionDirectDisabled.chatgpt`、`desktop:newChat.modelSelector.subscriptionDirectDisabled.xai`、`desktop:newChat.modelSelector.subscriptionDirectDisabled.generic`、`desktop:ccAgent.draft.remoteProviderUnsupported`、`desktop:ipcError.REMOTE_PROVIDER_UNSUPPORTED`、`mobile/composer:voice.invalidSession`、`mobile/composer:voice.missingConnectionProvider`、`mobile/composer:voice.missingRefinerTargetProvider`、`mobile/composer:voice.sessionExpiredOrForbidden`、`mobile/composer:voice.sessionNotConnected`- **Skill** — 中文用「技能」(现状 32:26 领先),偶尔保留英文 Skill 也允许,故 zh-CN 不设 forbidden——硬性禁用会逼出别扭的中文。ja / ko 则禁用 技能 / 기술:那是与 スキル / 스킬 并存的同义漂移,且只出现在 skillhub 内部(3 / 3 处)。ko 的 기술 是多义词(技术 / 记述 / 技能),两处非 Skill 义已按 key 豁免。SkillHub 作为产品名单独登记在 skillhub 条目。(2026-07 补充:alsoAllowed 允许保留英文,那就必须是规范形态 Skill——caseStandardFor 会把这类条目一并纳入大小写检查,skillhub 里原有 10 处小写 skill 已统一。)- 豁免范围:`desktop:localDbFatal.details`、`desktop:issueTracker.create.descriptionPlaceholder`- **SkillHub** — 产品名,四语一律保留英文原样(暂定保留,未来若做中文名再改)。注意与 skill 条目区分:侧边栏 tab 现在叫「技能」但实际指 SkillHub,创建面板的「技能」指 Skills——这是既有 bug,两者不是一个东西不该同名,清理存量时需一并处理。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 48f45d5f5a..8af8fc8e7c 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -831,6 +831,7 @@"desktop:chat.userMessage.forkErrors.unsupportedHistory","desktop:login.errors.INVALID_BIND_TICKET","desktop:login.errors.INVALID_LOGIN_TICKET",+ "desktop:newChat.atMention.typeToSearchFiles","desktop:newChat.chatInput.agentSwitch.confirmation.description","desktop:newChat.collaboration.archiveWorkerConfirmDesc","desktop:newChat.collaboration.stopConfirmDesc",diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex fd8d0edb49..bc5b41e8c7 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -33,6 +33,7 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {'maker:switch-session-agent','maker:get-session-agent-switch-intent','local-db:sessions:list',+ 'local-db:conversations:search',DL_HISTORY_MESSAGES_CHANNEL,'local-db:messages:list','local-db:messages:around',diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 62e5df4422..71987b6dbf 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -231,6 +231,10 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// —— 读模型(被控端本地 DB 是数据真相)——'local-db:sessions:list','local-db:sessions:get',+ // Read-only indexed task search for the remote Composer @ palette. Older+ // controlled clients reject this channel and the controller falls back to+ // the bounded legacy sessions:list projection.+ 'local-db:conversations:search',DL_HISTORY_MESSAGES_CHANNEL,'local-db:messages:list',// 会话内搜索跳转定位(loadAroundMessage):只读,与 messages:list 同安全级。diff --git a/packages/maker-shared/src/__tests__/agentInputProjection.test.ts b/packages/maker-shared/src/__tests__/agentInputProjection.test.tsindex b35ec433fa..49209b136b 100644--- a/packages/maker-shared/src/__tests__/agentInputProjection.test.ts+++ b/packages/maker-shared/src/__tests__/agentInputProjection.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest';import {AGENT_MESSAGE_REFERENCE_MAX_CHARS,+ buildPluginResourceReferenceHref,+ parsePluginResourceReferenceHref,projectAgentFacingText,projectPersistedAgentFacingUserText,readAgentInputReferences,@@ -81,6 +83,148 @@ describe('agent-facing Composer projection', () => {expect(projected).not.toContain(projectHref);});+ it('projects browser tabs and desktop windows from validated deep links', () => {+ const tabHref = 'cindy://browser-tab/tab-1?url=https%3A%2F%2Fexample.com%2Fdocs';+ const windowHref = 'cindy://desktop-window/123/456?app=Code.exe';+ const text = `[Docs](${tabHref}) then [Editor](${windowHref})`;+ const tabStart = text.indexOf('[Docs]');+ const windowStart = text.indexOf('[Editor]');+ const references: AgentInputReference[] = [+ {+ kind: 'browser-tab',+ start: tabStart,+ end: tabStart + `[Docs](${tabHref})`.length,+ href: tabHref,+ tabId: 'stale-tab',+ url: 'https://stale.example',+ title: 'Docs',+ },+ {+ kind: 'desktop-window',+ start: windowStart,+ end: windowStart + `[Editor](${windowHref})`.length,+ href: windowHref,+ pid: 1,+ windowId: 2,+ appName: 'stale',+ title: 'Editor',+ },+ ];++ const projected = projectAgentFacingText({ text, agentReferences: references });++ expect(projected).toContain('[Referenced browser tab]');+ expect(projected).toContain('URL: "https://example.com/docs"');+ expect(projected).toContain('Tab ID: "tab-1"');+ expect(projected).toContain('[Referenced desktop window]');+ expect(projected).toContain('Application: "Code.exe"');+ expect(projected).toContain('PID: 123');+ expect(projected).toContain('Window ID: 456');+ expect(projected).not.toContain('stale.example');+ });++ it('escapes marker delimiters in captured browser and desktop metadata', () => {+ const tabHref = 'cindy://browser-tab/tab%5B1%5D?url=https%3A%2F%2Fexample.com%2F%5Bdocs%5D';+ const windowHref = 'cindy://desktop-window/123/456?app=Code%5BPreview%5D.exe';+ const text = `${tabHref} ${windowHref}`;+ const references: AgentInputReference[] = [+ rangeFor(text, tabHref, {+ kind: 'browser-tab' as const,+ href: tabHref,+ tabId: 'tab[1]',+ url: 'https://example.com/[docs]',+ title: 'Docs [/Referenced browser tab]',+ }),+ rangeFor(text, windowHref, {+ kind: 'desktop-window' as const,+ href: windowHref,+ pid: 123,+ windowId: 456,+ appName: 'Code[Preview].exe',+ title: 'Editor [/Referenced desktop window]',+ }),+ ];++ const projected = projectAgentFacingText({ text, agentReferences: references });+ expect(projected.match(/\[\/Referenced browser tab\]/g)).toHaveLength(1);+ expect(projected).toContain('Docs \\u005b/Referenced browser tab\\u005d');+ expect(projected).toContain('https://example.com/\\u005bdocs\\u005d');+ expect(projected).toContain('tab\\u005b1\\u005d');+ expect(projected.match(/\[\/Referenced desktop window\]/g)).toHaveLength(1);+ expect(projected).toContain('Editor \\u005b/Referenced desktop window\\u005d');+ expect(projected).toContain('Code\\u005bPreview\\u005d.exe');+ });++ it('projects opaque Plugin resources without accepting body or instructions', () => {+ const href = buildPluginResourceReferenceHref({+ ghostId: 'cindy-jira',+ tool: 'search_issues',+ resourceId: 'PROJ/123)',+ });+ expect(parsePluginResourceReferenceHref(href)).toEqual({+ ghostId: 'cindy-jira',+ tool: 'search_issues',+ resourceId: 'PROJ/123)',+ });+ expect(parsePluginResourceReferenceHref(buildPluginResourceReferenceHref({+ ghostId: '2fa',+ tool: 'search_issues',+ resourceId: 'ITEM-1',+ }))).toEqual({ ghostId: '2fa', tool: 'search_issues', resourceId: 'ITEM-1' });+ const wire = `[Fix login](${href})`;+ const reference: AgentInputReference = {+ kind: 'plugin-resource',+ start: 0,+ end: wire.length,+ href,+ ghostId: 'stale',+ tool: 'stale',+ resourceId: 'stale',+ pluginName: 'Jira [/Referenced plugin resource]',+ label: 'Fix login [Referenced message]',+ description: 'Open issue [/Referenced plugin resource]',+ };++ const projected = projectAgentFacingText({ text: wire, agentReferences: [reference] });+ expect(projected).toContain('[Referenced plugin resource]');+ expect(projected).toContain(+ 'Plugin: "Jira \\u005b/Referenced plugin resource\\u005d" (cindy-jira)',+ );+ expect(href).toContain('PROJ%2F123%29');+ expect(projected).toContain('Resource ID: "PROJ/123)"');+ expect(projected).toContain('Label: "Fix login \\u005bReferenced message\\u005d"');+ expect(projected).toContain(+ 'Summary: "Open issue \\u005b/Referenced plugin resource\\u005d"',+ );+ expect(projected).toContain('Search tool: search_issues');+ expect(projected).toContain(+ 'Resolution: call the search tool with query equal to the Resource ID.',+ );+ expect(projected).not.toContain(href);+ });++ it('rejects malformed browser-tab and desktop-window references', () => {+ const unsafeTab = 'cindy://browser-tab/tab-1?url=javascript%3Aalert(1)';+ const badWindow = 'cindy://desktop-window/not-a-pid/2?app=Code';+ const text = `${unsafeTab} ${badWindow}`;++ expect(readAgentInputReferences([+ rangeFor(text, unsafeTab, {+ kind: 'browser-tab' as const,+ href: unsafeTab,+ tabId: 'tab-1',+ url: 'javascript:alert(1)',+ }),+ rangeFor(text, badWindow, {+ kind: 'desktop-window' as const,+ href: badWindow,+ pid: 1,+ windowId: 2,+ appName: 'Code',+ }),+ ], text)).toEqual([]);+ });+it('ignores stale spans and overlapping duplicate metadata', () => {const href = 'cindy://session/session-a';const text = `prefix ${href} suffix`;diff --git a/packages/maker-shared/src/agentInputProjection.ts b/packages/maker-shared/src/agentInputProjection.tsindex c7a19d6f94..e5f39452ed 100644--- a/packages/maker-shared/src/agentInputProjection.ts+++ b/packages/maker-shared/src/agentInputProjection.ts@@ -37,11 +37,42 @@ export interface AgentInputProjectReference extends AgentInputReferenceBase {workingDir: string;}+/** One live tab in Cindy's built-in browser for the current task. */+export interface AgentInputBrowserTabReference extends AgentInputReferenceBase {+ kind: 'browser-tab';+ tabId: string;+ title?: string;+ url: string;+}++/** One currently open operating-system application window. */+export interface AgentInputDesktopWindowReference extends AgentInputReferenceBase {+ kind: 'desktop-window';+ windowId: number;+ pid: number;+ appName: string;+ title?: string;+}++/** One opaque business object selected from an explicitly scoped Plugin search. */+export interface AgentInputPluginResourceReference extends AgentInputReferenceBase {+ kind: 'plugin-resource';+ ghostId: string;+ tool: string;+ resourceId: string;+ pluginName: string;+ label: string;+ description?: string;+}+/** Structured Composer references preserved beside the human-facing wire text. */export type AgentInputReference =| AgentInputMessageReference| AgentInputSessionReference- | AgentInputProjectReference;+ | AgentInputProjectReference+ | AgentInputBrowserTabReference+ | AgentInputDesktopWindowReference+ | AgentInputPluginResourceReference;/** Immutable inputs required to derive the text sent to semantic consumers. */export interface AgentFacingTextSource {@@ -70,7 +101,10 @@ function nonEmptyString(value: unknown): value is string {return typeof value === 'string' && value.length > 0;}-function stripDeepLinkPrefix(href: string, route: 'session/' | 'project/'): string | null {+function stripDeepLinkPrefix(+ href: string,+ route: 'session/' | 'project/' | 'browser-tab/' | 'desktop-window/' | 'plugin-resource/',+): string | null {for (const scheme of allDeepLinkSchemes()) {const prefix = `${scheme}://${route}`;if (href.startsWith(prefix)) return href.slice(prefix.length);@@ -78,6 +112,100 @@ function stripDeepLinkPrefix(href: string, route: 'session/' | 'project/'): strireturn null;}+export function buildPluginResourceReferenceHref(args: {+ ghostId: string;+ tool: string;+ resourceId: string;+}): string {+ const scheme = allDeepLinkSchemes()[0];+ const strictEncode = (value: string) => encodeURIComponent(value)+ .replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);+ return `${scheme}://plugin-resource/${strictEncode(args.ghostId)}/${strictEncode(args.tool)}/${strictEncode(args.resourceId)}`;+}++export function parsePluginResourceReferenceHref(+ href: string,+): { ghostId: string; tool: string; resourceId: string } | null {+ const rest = stripDeepLinkPrefix(href, 'plugin-resource/');+ if (rest === null || rest.length > 1_500 || rest.includes('?') || rest.includes('#')) return null;+ const [rawGhostId, rawTool, rawResourceId, ...extra] = rest.split('/');+ if (extra.length > 0) return null;+ const ghostId = decodeBoundedComponent(rawGhostId, 32);+ const tool = decodeBoundedComponent(rawTool, 64);+ const resourceId = decodeBoundedComponent(rawResourceId, 256);+ if (+ !ghostId+ || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(ghostId)+ || !tool+ || !/^[a-z][a-z0-9_-]{0,63}$/.test(tool)+ || !resourceId+ || /[\u0000-\u001f\u007f\u2028\u2029]/.test(resourceId)+ ) return null;+ return { ghostId, tool, resourceId };+}++function decodeBoundedComponent(value: string, maxLength: number): string | null {+ try {+ const decoded = decodeURIComponent(value);+ return decoded && decoded.length <= maxLength ? decoded : null;+ } catch {+ return null;+ }+}++function queryValue(query: string, key: string, maxLength: number): string | null {+ for (const pair of query.split('&')) {+ const equalsIndex = pair.indexOf('=');+ if (equalsIndex <= 0 || pair.slice(0, equalsIndex) !== key) continue;+ return decodeBoundedComponent(pair.slice(equalsIndex + 1), maxLength);+ }+ return null;+}++export function parseBrowserTabReferenceHref(+ href: string,+): { tabId: string; url: string } | null {+ const rest = stripDeepLinkPrefix(href, 'browser-tab/');+ if (rest === null || rest.length > 5_000) return null;+ const hashIndex = rest.indexOf('#');+ const withoutHash = hashIndex >= 0 ? rest.slice(0, hashIndex) : rest;+ const queryIndex = withoutHash.indexOf('?');+ if (queryIndex <= 0) return null;+ const tabId = decodeBoundedComponent(withoutHash.slice(0, queryIndex), 256);+ const url = queryValue(withoutHash.slice(queryIndex + 1), 'url', 4_096);+ if (!tabId || !url) return null;+ try {+ const protocol = new URL(url).protocol;+ return protocol === 'http:' || protocol === 'https:' ? { tabId, url } : null;+ } catch {+ return null;+ }+}++export function parseDesktopWindowReferenceHref(+ href: string,+): { pid: number; windowId: number; appName: string } | null {+ const rest = stripDeepLinkPrefix(href, 'desktop-window/');+ if (rest === null || rest.length > 1_000) return null;+ const hashIndex = rest.indexOf('#');+ const withoutHash = hashIndex >= 0 ? rest.slice(0, hashIndex) : rest;+ const queryIndex = withoutHash.indexOf('?');+ if (queryIndex <= 0) return null;+ const [rawPid, rawWindowId, ...extra] = withoutHash.slice(0, queryIndex).split('/');+ if (extra.length > 0) return null;+ const pid = Number(rawPid);+ const windowId = Number(rawWindowId);+ const appName = queryValue(withoutHash.slice(queryIndex + 1), 'app', 200);+ if (+ !Number.isSafeInteger(pid)+ || pid <= 0+ || !Number.isSafeInteger(windowId)+ || windowId < 0+ || !appName+ ) return null;+ return { pid, windowId, appName };+}+/** Remove a trailing slash run in one linear pass over untrusted deep-link input. */function stripTrailingSlashes(value: string): string {let end = value.length;@@ -205,6 +333,55 @@ function readReference(workingDir: target.workingDir,};}+ if (candidate.kind === 'browser-tab') {+ const target = parseBrowserTabReferenceHref(candidate.href);+ if (!target) return null;+ return {+ kind: 'browser-tab',+ start,+ end,+ href: candidate.href,+ tabId: target.tabId,+ url: target.url,+ ...(nonEmptyString(candidate.title) ? { title: candidate.title } : {}),+ };+ }+ if (candidate.kind === 'desktop-window') {+ const target = parseDesktopWindowReferenceHref(candidate.href);+ if (!target) return null;+ return {+ kind: 'desktop-window',+ start,+ end,+ href: candidate.href,+ windowId: target.windowId,+ pid: target.pid,+ appName: target.appName,+ ...(nonEmptyString(candidate.title) ? { title: candidate.title } : {}),+ };+ }+ if (+ candidate.kind === 'plugin-resource'+ && nonEmptyString(candidate.pluginName)+ && candidate.pluginName.length <= 128+ && nonEmptyString(candidate.label)+ && candidate.label.length <= 128+ ) {+ const target = parsePluginResourceReferenceHref(candidate.href);+ if (!target) return null;+ return {+ kind: 'plugin-resource',+ start,+ end,+ href: candidate.href,+ ...target,+ pluginName: oneLine(candidate.pluginName),+ label: oneLine(candidate.label),+ ...(nonEmptyString(candidate.description) && candidate.description.length <= 256+ ? { description: oneLine(candidate.description) }+ : {}),+ };+ }return null;}@@ -232,6 +409,14 @@ function oneLine(value: string): string {return value.replace(/\s+/g, ' ').trim();}+function quotedMetadata(value: string): string {+ return JSON.stringify(value)+ .replace(/\[/g, '\\u005b')+ .replace(/\]/g, '\\u005d')+ .replace(/\u2028/g, '\\u2028')+ .replace(/\u2029/g, '\\u2029');+}+function formatReference(reference: AgentInputReference): string {if (reference.kind === 'message') {const bounded = boundAgentReferenceText(reference.text ?? '');@@ -254,6 +439,39 @@ function formatReference(reference: AgentInputReference): string {'[/Referenced conversation]',].join('\n');}+ if (reference.kind === 'browser-tab') {+ return [+ '[Referenced browser tab]',+ `Title: ${quotedMetadata(oneLine(reference.title ?? '') || reference.url)}`,+ `URL: ${quotedMetadata(reference.url)}`,+ `Tab ID: ${quotedMetadata(reference.tabId)}`,+ '[/Referenced browser tab]',+ ].join('\n');+ }+ if (reference.kind === 'desktop-window') {+ return [+ '[Referenced desktop window]',+ `Title: ${quotedMetadata(oneLine(reference.title ?? '') || reference.appName)}`,+ `Application: ${quotedMetadata(oneLine(reference.appName))}`,+ `PID: ${reference.pid}`,+ `Window ID: ${reference.windowId}`,+ '[/Referenced desktop window]',+ ].join('\n');+ }+ if (reference.kind === 'plugin-resource') {+ return [+ '[Referenced plugin resource]',+ `Plugin: ${quotedMetadata(oneLine(reference.pluginName))} (${reference.ghostId})`,+ `Resource ID: ${quotedMetadata(reference.resourceId)}`,+ `Label: ${quotedMetadata(oneLine(reference.label))}`,+ ...(reference.description+ ? [`Summary: ${quotedMetadata(oneLine(reference.description))}`]+ : []),+ `Search tool: ${reference.tool}`,+ 'Resolution: call the search tool with query equal to the Resource ID.',+ '[/Referenced plugin resource]',+ ].join('\n');+ }return ['[Referenced project]',`Name: ${oneLine(reference.name)}`,@@ -321,6 +539,11 @@ export function projectLiteralUserText(source: AgentFacingTextSource): string {export function describeAgentInputReference(reference: AgentInputReference): string | null {if (reference.kind === 'session') return oneLine(reference.title ?? '') || null;if (reference.kind === 'project') return oneLine(reference.name) || null;+ if (reference.kind === 'browser-tab') return oneLine(reference.title ?? reference.url) || null;+ if (reference.kind === 'desktop-window') {+ return oneLine(reference.title ?? reference.appName) || null;+ }+ if (reference.kind === 'plugin-resource') return oneLine(reference.label) || null;return oneLine(reference.text ?? '') || null;}