Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 支持插件声明一级主视图 (#3219)

xutianqic8e62f4efbd8
diff --git a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
index 2569c031a0..1d4a4a5a97 100644
--- a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
+++ b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
@@ -133,12 +133,19 @@ async function hiddenHandler(payload: unknown): Promise<boolean> {
return (await handler?.({}, payload)) as boolean;
}
+async function mainViewHiddenHandler(payload: unknown): Promise<string[]> {
+ const handler = harness.handlers.get('sidebar-settings:set-main-view-hidden');
+ expect(handler).toBeDefined();
+ return (await handler?.({}, payload)) as string[];
+}
+
function loadSnapshot(): {
dataOwnerId: string | null;
ownerGeneration: number;
pinnedOrderIsAuthoritative: boolean;
pinnedOrder: string[];
hiddenProjectKeys: string[];
+ hiddenMainViewGhostIds: string[];
} {
const listener = harness.listeners.get('sidebar-settings:load-snapshot-sync');
const event: { returnValue?: ReturnType<typeof loadSnapshot> } = {};
@@ -202,10 +209,12 @@ describe('sidebarSettingsStore', () => {
}),
);
await hiddenHandler(request({ projectKey: 'C:\\workspace\\alpha\\', hidden: true }));
+ await mainViewHiddenHandler(request({ ghostId: 'xd-sites', hidden: true }));
expect(loadSnapshot()).toMatchObject({
dataOwnerId: 'owner-a',
pinnedOrder: ['project:local:/workspace/a', 'session-a'],
hiddenProjectKeys: ['local:C:/workspace/alpha'],
+ hiddenMainViewGhostIds: ['xd-sites'],
});
setSession('cloud', 'owner-b');
@@ -214,6 +223,7 @@ describe('sidebarSettingsStore', () => {
dataOwnerId: 'owner-b',
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
});
await pinnedHandler(request({ mutation: { kind: 'migrate-legacy', order: ['session-b'] } }));
@@ -223,6 +233,7 @@ describe('sidebarSettingsStore', () => {
dataOwnerId: 'owner-a',
pinnedOrder: ['project:local:/workspace/a', 'session-a'],
hiddenProjectKeys: ['local:C:/workspace/alpha'],
+ hiddenMainViewGhostIds: ['xd-sites'],
});
expect(JSON.parse(fs.readFileSync(ownerFile('owner-b'), 'utf-8'))).toMatchObject({
pinnedOrder: ['session-b'],
@@ -577,6 +588,87 @@ describe('sidebarSettingsStore', () => {
);
});
+ it('merges main-view visibility writes and broadcasts the durable snapshot', async () => {
+ await expect(
+ mainViewHiddenHandler(request({ ghostId: 'xd-sites', hidden: true })),
+ ).resolves.toEqual(['xd-sites']);
+ await expect(
+ mainViewHiddenHandler(request({ ghostId: 'workspace-tools', hidden: true })),
+ ).resolves.toEqual(['xd-sites', 'workspace-tools']);
+
+ expect(loadSnapshot().hiddenMainViewGhostIds).toEqual(['xd-sites', 'workspace-tools']);
+ const stamp = { dataOwnerId: 'owner-a', ownerGeneration: 1 };
+ expect(harness.send).toHaveBeenLastCalledWith(
+ 'sidebar-settings:hidden-main-view-ghost-ids-changed',
+ ['xd-sites', 'workspace-tools'],
+ stamp,
+ );
+ expect(harness.sendSecond).toHaveBeenLastCalledWith(
+ 'sidebar-settings:hidden-main-view-ghost-ids-changed',
+ ['xd-sites', 'workspace-tools'],
+ stamp,
+ );
+ expect(harness.untrustedSend).not.toHaveBeenCalled();
+ expect(harness.destroyedSend).not.toHaveBeenCalled();
+ });
+
+ it('removes the hidden main-view override while preserving the scoped tombstone', async () => {
+ await mainViewHiddenHandler(request({ ghostId: 'xd-sites', hidden: true }));
+ harness.send.mockClear();
+ harness.sendSecond.mockClear();
+
+ await expect(
+ mainViewHiddenHandler(request({ ghostId: 'xd-sites', hidden: false })),
+ ).resolves.toEqual([]);
+ expect(loadSnapshot().hiddenMainViewGhostIds).toEqual([]);
+ expect(JSON.parse(fs.readFileSync(ownerFile(), 'utf-8'))).toMatchObject({
+ hiddenMainViewGhostIds: [],
+ });
+ expect(harness.send).toHaveBeenCalledWith(
+ 'sidebar-settings:hidden-main-view-ghost-ids-changed',
+ [],
+ { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ );
+ });
+
+ it('rejects malformed and stale main-view visibility mutations', async () => {
+ await expect(
+ mainViewHiddenHandler(request({ ghostId: 'XD Sites', hidden: true })),
+ ).rejects.toThrow('[INVALID_PARAMS] invalid main-view plugin id');
+ await expect(
+ mainViewHiddenHandler(request({ ghostId: 'xd-sites', hidden: 'yes' })),
+ ).rejects.toThrow('[INVALID_PARAMS] invalid main-view hidden state');
+
+ const staleRequest = request({ ghostId: 'xd-sites', hidden: true });
+ setSession('cloud', 'owner-b');
+ await expect(mainViewHiddenHandler(staleRequest)).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(fs.existsSync(ownerFile('owner-a'))).toBe(false);
+ expect(fs.existsSync(ownerFile('owner-b'))).toBe(false);
+ expect(harness.send).not.toHaveBeenCalled();
+ });
+
+ it('drops a queued main-view write when the same owner advances generation', async () => {
+ const file = ownerFile('owner-a');
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(
+ `${file}.lock`,
+ JSON.stringify({ pid: process.pid, startedAt: Date.now() }),
+ 'utf-8',
+ );
+
+ const writing = mainViewHiddenHandler(
+ request({ ghostId: 'xd-sites', hidden: true }),
+ );
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ setSession('cloud', 'owner-a');
+ fs.unlinkSync(`${file}.lock`);
+
+ await expect(writing).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(fs.readFileSync(file, 'utf-8')).toBe('{}');
+ expect(harness.send).not.toHaveBeenCalled();
+ expect(harness.sendSecond).not.toHaveBeenCalled();
+ });
+
it('merges concurrent promote intents against the latest pinned order', async () => {
await expect(
pinnedHandler(request({ mutation: { kind: 'promote', entryId: 'project:a' } })),
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 2d39ea1ebc..fd72105c8a 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -2673,6 +2673,14 @@ export class GhostManager {
},
};
}
+ if (v.manifest.mainView && !zip.file(`${prefix}${v.manifest.mainView.html}`)) {
+ return {
+ rejection: {
+ code: 'file-invalid',
+ reason: `清单声明了 mainView.html,但压缩包内缺少 ${v.manifest.mainView.html}`,
+ },
+ };
+ }
let localizedManifest = withGhostResolvedLocale(v.manifest, this.options.getLocale?.());
const localeResources: Record<string, GhostManifestLocaleResource> = {};
if (v.manifest.locales !== undefined) {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 9cf5d73509..840820cb57 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -2938,6 +2938,26 @@ describe('GhostManager · install', () => {
await expectRejection(await manager.install(cindy), 'file-invalid');
});
+ it('main-view 清单声明的 HTML 不在包内 → inspect/install 都拒绝', async () => {
+ const manifest = {
+ ...goodManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['tool', 'main-view'],
+ mainView: { html: 'ui/main-view.html' },
+ };
+ const cindy = await makeCindy('missing-main-view.cindy', manifest, {
+ 'main.js': '// browser entry',
+ });
+
+ expect(await manager.inspect(cindy)).toMatchObject({
+ rejection: {
+ code: 'file-invalid',
+ reason: expect.stringContaining('ui/main-view.html'),
+ },
+ });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ });
+
it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(
'包不能自带主机保留文件 %s',
async (reservedFile) => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index fdb297bccf..5087888e62 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -70,7 +70,9 @@ async function testScaffoldWriter(request: ForgeScaffoldWriteRequest) {
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
- const staging = await fs.promises.mkdtemp(path.join(request.parentDir, `.${request.targetName}-scaffold-`));
+ const staging = await fs.promises.mkdtemp(
+ path.join(request.parentDir, `.${request.targetName}-scaffold-`),
+ );
try {
for (const file of request.files) {
const abs = path.join(staging, file.path);
@@ -80,7 +82,10 @@ async function testScaffoldWriter(request: ForgeScaffoldWriteRequest) {
try {
await fs.promises.rename(staging, target);
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'EEXIST' || (error as NodeJS.ErrnoException).code === 'ENOTEMPTY') {
+ if (
+ (error as NodeJS.ErrnoException).code === 'EEXIST' ||
+ (error as NodeJS.ErrnoException).code === 'ENOTEMPTY'
+ ) {
return { ok: false as const, errorCode: 'TARGET_EXISTS' as const, message: 'exists' };
}
throw error;
@@ -107,8 +112,7 @@ function packGhostDir(
}
async function expectSameExistingRealPath(actual: string, expected: string): Promise<void> {
- const normalize = (value: string) =>
- process.platform === 'win32' ? value.toLowerCase() : value;
+ const normalize = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value);
const [actualReal, expectedReal] = await Promise.all([
fs.promises.realpath(actual),
fs.promises.realpath(expected),
@@ -231,7 +235,9 @@ describe('packGhostDir', () => {
packed.cindyPath,
path.join(sourceTarget, 'inside-1.0.0.cindy'),
);
- await expect(fs.promises.access(path.join(sourceTarget, 'inside-1.0.0.cindy'))).resolves.toBeUndefined();
+ await expect(
+ fs.promises.access(path.join(sourceTarget, 'inside-1.0.0.cindy')),
+ ).resolves.toBeUndefined();
});
it('rejects a file replaced by a link after classification', async () => {
@@ -244,23 +250,28 @@ describe('packGhostDir', () => {
await fs.promises.writeFile(outsideFile, 'outside-secret');
const originalLstat = fs.promises.lstat.bind(fs.promises);
let swapped = false;
- const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
- // 忠实转发 options:readBoundedFileNoFollow 在 Windows 走 lstat(path,{bigint:true}),
- // 丢掉 options 会返回非 bigint stat、令 sameInode 误判,破坏无关的 ghost.json 读取。
- const result = await (
- originalLstat as (p: fs.PathLike, o?: fs.StatOptions) => Promise<fs.Stats & fs.BigIntStats>
- )(file, options);
- if (!swapped && path.basename(String(file)) === 'main.js') {
- swapped = true;
- await fs.promises.rm(String(file), { force: true });
- await fs.promises.symlink(
- outsideFile,
- String(file),
- process.platform === 'win32' ? 'file' : undefined,
- );
- }
- return result;
- });
+ const lstatSpy = vi
+ .spyOn(fs.promises, 'lstat')
+ .mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
+ // 忠实转发 options:readBoundedFileNoFollow 在 Windows 走 lstat(path,{bigint:true}),
+ // 丢掉 options 会返回非 bigint stat、令 sameInode 误判,破坏无关的 ghost.json 读取。
+ const result = await (
+ originalLstat as (
+ p: fs.PathLike,
+ o?: fs.StatOptions,
+ ) => Promise<fs.Stats & fs.BigIntStats>
+ )(file, options);
+ if (!swapped && path.basename(String(file)) === 'main.js') {
+ swapped = true;
+ await fs.promises.rm(String(file), { force: true });
+ await fs.promises.symlink(
+ outsideFile,
+ String(file),
+ process.platform === 'win32' ? 'file' : undefined,
+ );
+ }
+ return result;
+ });
try {
const packed = await packGhostDir(dir);
expect(packed).toMatchObject({ ok: false, errorCode: 'ENTRY_MISSING' });
@@ -284,23 +295,28 @@ describe('packGhostDir', () => {
const assetsDir = path.join(dir, 'assets');
const originalLstat = fs.promises.lstat.bind(fs.promises);
let swapped = false;
- const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
- // 忠实转发 options:readBoundedFileNoFollow 在 Windows 走 lstat(path,{bigint:true}),
- // 丢掉 options 会返回非 bigint stat、令 sameInode 误判,破坏无关的 ghost.json 读取。
- const result = await (
- originalLstat as (p: fs.PathLike, o?: fs.StatOptions) => Promise<fs.Stats & fs.BigIntStats>
- )(file, options);
- if (!swapped && path.resolve(String(file)) === path.resolve(assetsDir)) {
- swapped = true;
- await fs.promises.rm(assetsDir, { recursive: true, force: true });
- await fs.promises.symlink(
- outsideDir,
- assetsDir,
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- }
- return result;
- });
+ const lstatSpy = vi
+ .spyOn(fs.promises, 'lstat')
+ .mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
+ // 忠实转发 options:readBoundedFileNoFollow 在 Windows 走 lstat(path,{bigint:true}),
+ // 丢掉 options 会返回非 bigint stat、令 sameInode 误判,破坏无关的 ghost.json 读取。
+ const result = await (
+ originalLstat as (
+ p: fs.PathLike,
+ o?: fs.StatOptions,
+ ) => Promise<fs.Stats & fs.BigIntStats>
+ )(file, options);
+ if (!swapped && path.resolve(String(file)) === path.resolve(assetsDir)) {
+ swapped = true;
+ await fs.promises.rm(assetsDir, { recursive: true, force: true });
+ await fs.promises.symlink(
+ outsideDir,
+ assetsDir,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ }
+ return result;
+ });
try {
const packed = await packGhostDir(dir);
expect(packed).toMatchObject({ ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR' });
@@ -331,10 +347,12 @@ describe('packGhostDir', () => {
try {
const outsideDir = path.join(outsideRoot, 'src');
await fs.promises.cp(dir, outsideDir, { recursive: true });
- await expect(packGhostDirRaw(outsideDir, { sessionWorkdir: workDir })).resolves.toMatchObject({
- ok: false,
- errorCode: 'SOURCE_OUTSIDE_WORKDIR',
- });
+ await expect(packGhostDirRaw(outsideDir, { sessionWorkdir: workDir })).resolves.toMatchObject(
+ {
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ },
+ );
const alias = path.join(workDir, 'outside-alias');
await fs.promises.symlink(outsideDir, alias, 'junction');
@@ -391,9 +409,7 @@ describe('packGhostDir', () => {
} catch {
return;
}
- await expect(
- packGhostDir(alias, { forbiddenRootDirs: [managedRoot] }),
- ).resolves.toMatchObject({
+ await expect(packGhostDir(alias, { forbiddenRootDirs: [managedRoot] })).resolves.toMatchObject({
ok: false,
errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
});
@@ -410,10 +426,7 @@ describe('packGhostDir', () => {
path.join(managedRoot, 'receipt.json'),
JSON.stringify({ secret: 'approved state' }),
);
- await fs.promises.writeFile(
- path.join(ownerData, 'ghost.json'),
- JSON.stringify(GOOD_MANIFEST),
- );
+ await fs.promises.writeFile(path.join(ownerData, 'ghost.json'), JSON.stringify(GOOD_MANIFEST));
await fs.promises.writeFile(path.join(ownerData, 'main.js'), '// authoring source');
await expect(
@@ -475,6 +488,32 @@ describe('packGhostDir', () => {
});
});
+ it('requires and packs the declared main-view HTML entry', async () => {
+ const manifest = {
+ ...GOOD_MANIFEST,
+ minCindyVersion: '1.2.3',
+ slots: ['tool', 'main-view'],
+ mainView: { title: 'Workspace', html: 'ui/main-view.html' },
+ };
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// authoring source',
+ });
+
+ await expect(packGhostDir(dir)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ });
+
+ await fs.promises.mkdir(path.join(dir, 'ui'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'ui', 'main-view.html'), '<main>workspace</main>');
+ const packed = await packGhostDir(dir);
+ expect(packed.ok, JSON.stringify(packed)).toBe(true);
+ if (!packed.ok) return;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));
+ expect(Object.keys(zip.files)).toContain('ui/main-view.html');
+ });
+
it('rejects a declared file below a linked ancestor instead of omitting it from the package', async () => {
const manifest = {
...GOOD_MANIFEST,
@@ -509,12 +548,18 @@ describe('packGhostDir', () => {
const declaredEntry = path.join(dir, 'Main.js');
const actualEntry = path.join(dir, 'main.js');
const originalLstat = fs.promises.lstat.bind(fs.promises);
- const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
- const target = path.resolve(String(file)) === path.resolve(declaredEntry) ? actualEntry : file;
- return (
- originalLstat as (p: fs.PathLike, o?: fs.StatOptions) => Promise<fs.Stats & fs.BigIntStats>
- )(target, options);
- });
+ const lstatSpy = vi
+ .spyOn(fs.promises, 'lstat')
+ .mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
+ const target =
+ path.resolve(String(file)) === path.resolve(declaredEntry) ? actualEntry : file;
+ return (
+ originalLstat as (
+ p: fs.PathLike,
+ o?: fs.StatOptions,
+ ) => Promise<fs.Stats & fs.BigIntStats>
+ )(target, options);
+ });
try {
await expect(packGhostDir(dir)).resolves.toMatchObject({
ok: false,
@@ -599,17 +644,19 @@ describe('packGhostDir', () => {
});
const originalReaddir = fs.promises.readdir.bind(fs.promises);
let mutated = false;
- const readdirSpy = vi.spyOn(fs.promises, 'readdir').mockImplementation(async (directory, options) => {
- const entries = await originalReaddir(directory, options as never);
- if (!mutated && path.resolve(String(directory)) === path.resolve(dir)) {
- mutated = true;
- await fs.promises.writeFile(
- path.join(dir, 'ghost.json'),
- JSON.stringify({ ...GOOD_MANIFEST, id: 'bravo', version: '9.0.0' }),
- );
- }
- return entries as never;
- });
+ const readdirSpy = vi
+ .spyOn(fs.promises, 'readdir')
+ .mockImplementation(async (directory, options) => {
+ const entries = await originalReaddir(directory, options as never);
+ if (!mutated && path.resolve(String(directory)) === path.resolve(dir)) {
+ mutated = true;
+ await fs.promises.writeFile(
+ path.join(dir, 'ghost.json'),
+ JSON.stringify({ ...GOOD_MANIFEST, id: 'bravo', version: '9.0.0' }),
+ );
+ }
+ return entries as never;
+ });
try {
const packed = await packGhostDir(dir);
expect(packed).toMatchObject({ ok: true, manifest: GOOD_MANIFEST });
@@ -1184,9 +1231,7 @@ describe('scaffoldGhostDir', () => {
it('fails closed when the scaffold parent has no trustworthy filesystem identity', async () => {
const parentStat = await fs.promises.lstat(workDir, { bigint: true });
const realPath = await fs.promises.realpath(workDir);
- expect(
- sameForgeScaffoldParentIdentity(parentStat, { realPath, dev: 0n, ino: 0n }),
- ).toBe(false);
+ expect(sameForgeScaffoldParentIdentity(parentStat, { realPath, dev: 0n, ino: 0n })).toBe(false);
const zeroIdentityStat = new Proxy(parentStat, {
get(target, key) {
@@ -1334,9 +1379,10 @@ describe('scaffoldGhostDir', () => {
ok: false,
errorCode: 'INVALID_INPUT',
});
- expect(
- await scaffold(path.join(installedDir, 'src'), [managedRoot]),
- ).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ expect(await scaffold(path.join(installedDir, 'src'), [managedRoot])).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ });
expect(fs.existsSync(path.join(installedDir, 'src'))).toBe(false);
// 状态根还没建出来也要挡住(首次装入前就该拒)。
@@ -1348,9 +1394,7 @@ describe('scaffoldGhostDir', () => {
if (process.platform === 'win32') {
expect(
- await scaffold(path.join(managedRoot.toUpperCase(), 'fresh'), [
- managedRoot.toLowerCase(),
- ]),
+ await scaffold(path.join(managedRoot.toUpperCase(), 'fresh'), [managedRoot.toLowerCase()]),
).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
}
@@ -1450,7 +1494,8 @@ describe('FORGE_GUIDE', () => {
expect(FORGE_GUIDE).not.toContain('至少读完"沙箱红线"与"打包与测试"两章');
});
- it('documents installed-directory isolation and the structured refusal', () => { expect(FORGE_GUIDE).toContain('已安装插件目录');
+ it('documents installed-directory isolation and the structured refusal', () => {
+ expect(FORGE_GUIDE).toContain('已安装插件目录');
expect(FORGE_GUIDE).toContain('SOURCE_IS_INSTALLED_PLUGIN');
// 脚手架侧的同一禁区也要写进手册,否则 agent 会先把骨架建进安装目录再撞墙。
expect(FORGE_GUIDE).toContain('也不能落在已安装插件目录或 Host 状态目录内');
@@ -1549,9 +1594,7 @@ describe('FORGE_GUIDE', () => {
expect(FORGE_GUIDE).toContain(
'`list_tools(category)` 返回工具明细时,必须在同一份结果里一并下发该类目的',
);
- expect(FORGE_GUIDE).toContain(
- '传 category 返回该类目下所有操作的名称、说明与该类目 RULES',
- );
+ expect(FORGE_GUIDE).toContain('传 category 返回该类目下所有操作的名称、说明与该类目 RULES');
expect(FORGE_GUIDE).toContain('`rules: [规则键]`');
expect(FORGE_GUIDE).toContain('参数 schema **和本次自纠必需的规则**');
expect(FORGE_GUIDE).toContain('`list_tools` 是插件声明的顶层工具,不是 Host 固定工具');
@@ -1782,8 +1825,8 @@ describe('FORGE_GUIDE', () => {
'minimize',
'最小化面板',
// 2026-07-25 skill 槽:随包捆绑 Agent Skills,声明一致性 + 全局作用域披露。
- // 卡槽总数标记随 ios-simulator 槽合入更新为十八个。
- '十八个卡槽',
+ // 卡槽总数标记随 main-view 槽合入更新为二十个。
+ '二十个卡槽',
'捆绑 Agent Skills(skill 槽)',
'skill.items',
'SKILL.md',
@@ -1801,6 +1844,14 @@ describe('FORGE_GUIDE', () => {
'caps.capabilities.pluginVideo === false',
'caps.capabilities.pluginInput === false',
'声明 `ios-simulator` 时必须同时声明 `minCindyVersion`',
+ // 2026-08-21 一级插件主视图:独立 slot、最低版本、locale 与沙箱边界。
+ '一级主视图(main-view 槽)',
+ '"mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }',
+ '声明 main-view 时 minCindyVersion 必填',
+ '`mainView.title`',
+ '`mainView.icon`',
+ '`puzzle`、`globe`、`code`、`folder`、`database`、`chart-column`',
+ '只控制主视图的侧边栏入口',
// 2026-07-28 图标与官方仓门禁(#809):§1/§2 的 icon 字段说明、
// §8.1 官方插件仓的四语言 locale 与 assets/icon.png 惯例。
'"icon": "assets/icon.png"',
@@ -1856,6 +1907,8 @@ describe('FORGE_GUIDE', () => {
]) {
expect(FORGE_GUIDE).toContain(marker);
}
+ expect(FORGE_GUIDE).not.toContain('十八个卡槽');
+ expect(FORGE_GUIDE).not.toContain('十九个卡槽');
});
it('打包前仅轻提醒一次图标选择,AI 生成有固定提示词且失败不阻塞', () => {
@@ -2072,14 +2125,15 @@ describe('packGhostDir · manual 渐进披露手册', () => {
const lowercaseEntry = path.join(dir, 'manual/manual.md');
const uppercaseEntry = path.join(dir, 'manual/MANUAL.md');
const originalLstat = fs.promises.lstat.bind(fs.promises);
- const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(
- ((target: fs.PathLike, options?: fs.StatOptions) => {
- if (String(target) === uppercaseEntry) {
- return originalLstat(lowercaseEntry, options as never);
- }
- return originalLstat(target, options as never);
- }) as typeof fs.promises.lstat,
- );
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(((
+ target: fs.PathLike,
+ options?: fs.StatOptions,
+ ) => {
+ if (String(target) === uppercaseEntry) {
+ return originalLstat(lowercaseEntry, options as never);
+ }
+ return originalLstat(target, options as never);
+ }) as typeof fs.promises.lstat);
expect(await packGhostDir(dir)).toMatchObject({
ok: false,
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 002088a1c3..331ed7ad6a 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -227,8 +227,7 @@ export interface ForgeScaffoldWriteRequest {
}
export type ForgeScaffoldWriteResult =
- | { ok: true }
- | { ok: false; errorCode: 'TARGET_EXISTS' | 'INTERNAL'; message: string };
+ { ok: true } | { ok: false; errorCode: 'TARGET_EXISTS' | 'INTERNAL'; message: string };
export type ForgeScaffoldWriter = (
request: ForgeScaffoldWriteRequest,
@@ -574,7 +573,11 @@ export async function scaffoldGhostDir(
const resolved = path.resolve(input.dir);
const workdir = options?.sessionWorkdir;
if (!workdir) {
- return { ok: false, errorCode: 'INVALID_INPUT', message: '没有会话工作目录,无法确定骨架输出位置' };
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: '没有会话工作目录,无法确定骨架输出位置',
+ };
}
// 字面 startsWith 不设防软链:工作目录里若有 out -> /tmp/out 之类的软链祖先,
// 字面在内、实际在外。两边都按 realpath 对账——目标还不存在,就取「已存在的最深
@@ -583,13 +586,21 @@ export async function scaffoldGhostDir(
try {
realWorkdir = await realpathNative(path.resolve(workdir));
} catch {
- return { ok: false, errorCode: 'INVALID_INPUT', message: '会话工作目录不存在,无法确定骨架输出位置' };
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: '会话工作目录不存在,无法确定骨架输出位置',
+ };
}
let realTarget: string;
try {
realTarget = await resolveThroughExistingAncestor(resolved);
} catch (err) {
- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
}
if (!realTarget.startsWith(`${realWorkdir}${path.sep}`) && realTarget !== realWorkdir) {
return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 必须在当前会话工作目录内' };
@@ -599,7 +610,11 @@ export async function scaffoldGhostDir(
try {
resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
} catch (err) {
- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
}
// 与打包侧同形的双向判定:骨架目标既不能落进受管根(已装插件 / 状态根 / seed 根),
// 也不能是它们的祖先。祖先方向此处是纵深防御(该目录必已存在,最终 rename 会
@@ -624,7 +639,11 @@ export async function scaffoldGhostDir(
}
const validation = validateGhostManifest(JSON.parse(manifestRaw));
if (!validation.ok) {
- return { ok: false, errorCode: 'INVALID_INPUT', message: `插件信息不合格:${validation.reason}` };
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: `插件信息不合格:${validation.reason}`,
+ };
}
const brokerPortIssue = brokerRedirectPortDeclarationIssue(validation.manifest);
if (brokerPortIssue) {
@@ -633,10 +652,18 @@ export async function scaffoldGhostDir(
try {
await fs.promises.lstat(targetDir);
- return { ok: false, errorCode: 'TARGET_EXISTS', message: `目标已经存在,不会覆盖:${targetDir}` };
+ return {
+ ok: false,
+ errorCode: 'TARGET_EXISTS',
+ message: `目标已经存在,不会覆盖:${targetDir}`,
+ };
} catch (err) {
if (!hasFsErrorCode(err, 'ENOENT')) {
- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
}
}
@@ -646,13 +673,14 @@ export async function scaffoldGhostDir(
try {
parentStat = await fs.promises.lstat(parentDir, { bigint: true });
if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
- return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 的父目录必须是工作目录内已存在的普通目录' };
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: 'dir 的父目录必须是工作目录内已存在的普通目录',
+ };
}
parentRealPath = await realpathNative(parentDir);
- if (
- (await pathHasLinkSegment(parentDir)) ||
- !isPathInsideDir(realWorkdir, parentRealPath)
- ) {
+ if ((await pathHasLinkSegment(parentDir)) || !isPathInsideDir(realWorkdir, parentRealPath)) {
return {
ok: false,
errorCode: 'INVALID_INPUT',
@@ -667,7 +695,11 @@ export async function scaffoldGhostDir(
message: 'dir 的父目录必须先创建,并且必须位于当前工作目录内',
};
}
- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
}
// 实际落盘委托给隔离的稳定父目录写入器(C-4):forge.ts 只生成内容,不直接写盘。
@@ -684,7 +716,9 @@ export async function scaffoldGhostDir(
expectedParent: { realPath: parentRealPath, dev: parentStat.dev, ino: parentStat.ino },
files: Object.entries(files).map(([rel, content]) => ({
path: rel,
- base64: (typeof content === 'string' ? Buffer.from(content, 'utf8') : content).toString('base64'),
+ base64: (typeof content === 'string' ? Buffer.from(content, 'utf8') : content).toString(
+ 'base64',
+ ),
})),
});
if (!writeResult.ok) {
@@ -838,6 +872,7 @@ async function buildGhostPackage(
mustExist.push(manifest.node.entry, ...(manifest.node.entries ?? []));
}
if (manifest.panel?.html) mustExist.push(manifest.panel.html);
+ if (manifest.mainView?.html) mustExist.push(manifest.mainView.html);
if (manifest.settingsHtml) mustExist.push(manifest.settingsHtml);
for (const item of manifest.skill?.items ?? []) mustExist.push(`${item.dir}/SKILL.md`);
if (iconPng === undefined && manifest.icon) mustExist.push(manifest.icon);
@@ -891,10 +926,7 @@ async function buildGhostPackage(
// Markdown 文件;逐文件限量、严格 UTF-8,并拒绝并发截短与二进制内容。
// 缓存本次校验过的字节,生成 zip 时直接使用同一份快照,避免“预检一份、
// 入包时又读到另一份”的竞态。嵌套单元共享缓存,同一物理文件只校验一次。
- const manualFileSnapshots = new Map<
- string,
- { bytes: Buffer; unixPermissions: number }
- >();
+ const manualFileSnapshots = new Map<string, { bytes: Buffer; unixPermissions: number }>();
for (const item of manifest.manual?.items ?? []) {
const unitRoot = path.join(dir, ...item.dir.split('/'));
const validateManualDir = async (
@@ -950,14 +982,10 @@ async function buildGhostPackage(
if (manualFileSnapshots.has(logicalPath)) continue;
let read;
try {
- read = await readBoundedFileNoFollowWithStat(
- absolutePath,
- GHOST_MANUAL_MD_MAX_BYTES,
- {
- containWithin: realDir,
- verifyContentStability: true,
- },
- );
+ read = await readBoundedFileNoFollowWithStat(absolutePath, GHOST_MANUAL_MD_MAX_BYTES, {
+ containWithin: realDir,
+ verifyContentStability: true,
+ });
} catch {
return {
ok: false,
@@ -1048,7 +1076,11 @@ async function buildGhostPackage(
} catch {
// 分类时条目已消失(并发删除):声明入口 → ENTRY_MISSING,其它跳过。
if (requiredPackPaths.has(foldedRel)) {
- return { ok: false, errorCode: 'ENTRY_MISSING', message: `清单声明的文件不存在:${rel}` };
+ return {
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ message: `清单声明的文件不存在:${rel}`,
+ };
}
continue;
}
@@ -1098,7 +1130,11 @@ async function buildGhostPackage(
}
} else if (requiredPackPaths.has(foldedRel)) {
// 声明入口是块/字符设备、FIFO 等非常规条目 → 视为缺失。
- return { ok: false, errorCode: 'ENTRY_MISSING', message: `清单声明的文件不是普通文件:${rel}` };
+ return {
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ message: `清单声明的文件不是普通文件:${rel}`,
+ };
}
}
return null;
@@ -1269,20 +1305,32 @@ async function buildGhostPackage(
*/
export async function packGhostDir(
dir: string,
- options?: { sessionWorkdir?: string | null; forbiddenRootDirs?: readonly string[]; iconPng?: Buffer },
+ options?: {
+ sessionWorkdir?: string | null;
+ forbiddenRootDirs?: readonly string[];
+ iconPng?: Buffer;
+ },
): Promise<ForgePackResult> {
// Forge 打包出口专属安全门(C-4 + #7):source 必须在会话 workdir 内、且不得是受管根
//(已装插件 / 批准状态根 / seed 根,双向判定)。算出的 realSourceDir 作为
// buildGhostPackage 的 expectedRealDir 上游锚点——正是它要求"由上游校验后传入"的那份。
const workdir = options?.sessionWorkdir;
if (!workdir) {
- return { ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR', message: 'Forge pack requires an active session workdir' };
+ return {
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ message: 'Forge pack requires an active session workdir',
+ };
}
let realWorkdir: string;
try {
realWorkdir = await realpathNative(path.resolve(workdir));
} catch {
- return { ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR', message: 'The current session workdir does not exist' };
+ return {
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ message: 'The current session workdir does not exist',
+ };
}
let realSourceDir: string;
try {
@@ -1291,7 +1339,11 @@ export async function packGhostDir(
return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `目录不存在:${dir}` };
}
if (!isPathInsideDir(realWorkdir, realSourceDir)) {
- return { ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR', message: 'Forge source must be inside the current session workdir' };
+ return {
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ message: 'Forge source must be inside the current session workdir',
+ };
}
for (const forbiddenRoot of options?.forbiddenRootDirs ?? []) {
const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
@@ -1310,7 +1362,11 @@ export async function packGhostDir(
};
}
}
- const built = await buildGhostPackage(dir, realSourceDir, options ? { iconPng: options.iconPng } : undefined);
+ const built = await buildGhostPackage(
+ dir,
+ realSourceDir,
+ options ? { iconPng: options.iconPng } : undefined,
+ );
if (!built.ok) return built;
const authoringIssue = firstGhostAuthoringIssue(built.manifestRaw);
if (authoringIssue) {
@@ -1320,7 +1376,10 @@ export async function packGhostDir(
// + shouldSkip 跳过 *.cindy,自身产物不会进包;同名覆盖。
// 落地到**规范源码目录**(realpath 产物)而非可能是符号链接/别名的入参 `dir`:
// 产物必须写进真实目录,别名只是通往它的一条路径。
- const cindyPath = path.join(realSourceDir, `${built.manifest.id}-${built.manifest.version}.cindy`);
+ const cindyPath = path.join(
+ realSourceDir,
+ `${built.manifest.id}-${built.manifest.version}.cindy`,
+ );
try {
await fs.promises.writeFile(cindyPath, built.buf);
} catch (err) {
@@ -1418,8 +1477,9 @@ ghost_forge_pack 打包 → 用户在弹窗上确认装入;需要发布时改
值得主动摆出来让用户选的"隐藏"设计选项(详见对应章节):
-- **界面形态**:无界面(纯工具)/ 聊天卡片(card 槽,§4.5)/ 停靠面板(panel.position
- left,§5)/ 插件页内独占面板(position "tab",从插件页「使用」打开、离开即关,§5)。
+- **界面形态**:无界面(纯工具)/ 聊天卡片(card 槽,§4.5)/ Cindy 一级主视图
+ (main-view 槽,§4.20)/ 停靠面板(panel.position left,§5)/ 插件页内独占面板
+ (position "tab",从插件页「使用」打开、离开即关,§5)。
- **唤起方式**:只靠 AI 按 whenToUse 自动想起,还是同时声明 \`command\` 点名词让用户
显式点名(推荐,§2)。
- **启动模式**:on-demand 按需拉起(缺省,推荐)/ resident 常驻(仅订阅型、要秒响应
@@ -1457,6 +1517,7 @@ my-ghost/
├── panel.html ← 面板界面(声明了 panel.html 时必须)
├── panel.css
├── panel.js
+├── main-view.html ← 一级主视图(声明了 mainView.html 时必须,见 §4.20)
└── settings.html ← 自定义设置区(声明了 settingsHtml 时必须,见 §4.8)
\`\`\`
@@ -1517,6 +1578,9 @@ my-ghost/
// 窗口中打开)、minimize(最小化面板;恢复入口由用户偏好决定为浮动气泡或
// 左侧栏)。标题条本体恒由主机绘制、
// 关不掉;未知键拒装;position:"tab" 时声明本字段拒装
+ // 一级主视图是独立能力,见 §4.20。使用时在 slots 加 "main-view",并声明:
+ // "mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }
+ // 声明 main-view 时 minCindyVersion 必填。
"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时仍必填,用于长期管理/替换/清除;调用前缺失时主机也会在统一 Setup 卡内联收单,见 §4.7)
"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动
}
@@ -1583,6 +1647,7 @@ tool name 对齐,协议键、工具名和参数名不翻译:
}
},
"panel": { "title": "Plugin panel" },
+ "mainView": { "title": "Workspace" },
"network": {
"secrets": {
"api_key": { "label": "API key", "hint": "Create one in account settings." }
@@ -1605,7 +1670,7 @@ tool name 对齐,协议键、工具名和参数名不翻译:
\`\`\`
可翻译字段:\`name\`、\`description\`、\`whenToUse\`、\`tools\`(工具 description 与参数
-文案)、\`panel.title\`、\`network.secrets / connections\`、\`node.secretBindings\`、
+文案)、\`panel.title\`、\`mainView.title\`、\`network.secrets / connections\`、\`node.secretBindings\`、
\`setup\` 的 kv 标签;凭证、连接、Node 凭证和 kv 项按稳定 key 对齐(提供某个 key 的
条目时 label 必填,hint 可选)。工具参数 schema 中已有的 \`title / description\` 用
JSON Pointer 对齐(如 \`/properties/query\`;根节点用空字符串 \`""\`),参数名、类型、
@@ -1618,10 +1683,11 @@ key、未知字段、原清单没有的条目、类型或长度不合格、文
node secretBindings key、setup kv key——都不能使用 \`__proto__\`、\`constructor\` 或
\`prototype\`;这些名称是宿主保留键,打包时会直接拒绝。
-十八个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图/快问快答,
+二十个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图/快问快答,
见 §4 与 §4.0.2)、\`agent\`(让
-当前 Agent 开始一个普通用户回合,或派活取回结果,见 §4.11 / §4.11.1)、\`panel\`(常驻
-面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话
+当前 Agent 开始一个普通用户回合,或派活取回结果,见 §4.11 / §4.11.1)、
+\`main-view\`(Cindy 一级侧边栏入口与完整页面,见 §4.20)、\`panel\`(常驻面板)、
+\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话
事件 + 拦截用户消息,见 §4.6)、\`network\`(访问自带服务的域名白名单 HTTP,主机代发,
见 §4.7)、\`notify\`(弹系统轻提示,主机画壳带你的身份头,见 §4.9)、\`badge\`
(在插件入口留一颗持久的未读绿点,与 notify 并列、互不为前置,见 §4.9.1)、\`confirm\`(弹主机
@@ -3937,7 +4003,7 @@ SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):
信任与作用域(如实告知用户,也请作者自重):
- 技能指令由**主 Agent 以用户全部权限执行**,对所有项目、所有会话生效,
- **不受插件沙箱约束**——这是十八个卡槽里信任面最高的能力,装入确认框会把
+ **不受插件沙箱约束**——这是二十个卡槽里信任面最高的能力,装入确认框会把
每个技能置顶逐条列出;
- 技能跟随插件的**全局**启用状态:仅在某个工作目录停用插件**不会**隐藏技能,
只有全局停用或卸载才撤链(本期只有全局作用域);
@@ -4092,6 +4158,41 @@ const opened = await cindy.iosSimulator.request({
Skill 在 MCP 不存在时必须说明内嵌路线不可用;如果用户目标不依赖 Cindy viewer,
可以继续使用正常的外部工具链,否则再引导用户升级 Cindy。
+## 4.20 一级主视图(main-view 槽)
+
+插件需要一个从 Cindy 一级侧边栏进入的完整页面时,声明独立的 \`main-view\` 槽。下例
+\`1.2.3\` 只演示 SemVer 格式,不代表 main-view 的首发版本已经裁决:
+
+\`\`\`json
+{
+ "minCindyVersion": "1.2.3",
+ "slots": ["main-view"],
+ "mainView": {
+ "title": "工作台",
+ "icon": "puzzle",
+ "html": "main-view.html"
+ }
+}
+\`\`\`
+
+- \`mainView.html\` 必须是包内安全相对路径且文件真实存在;\`title\` 可省略,省略时
+ 回退插件 \`name\`。声明过基础 title 后,locale 文件可用
+ \`"mainView": { "title": "Workspace" }\` 翻译;没有基础 title 时不要声明该翻译;
+- \`mainView.icon\` 可省略,省略时使用 \`puzzle\`。它只控制主视图的侧边栏入口,不会
+ 替代或修改根级 \`icon\` 品牌图片。可用值与 Cindy 系统图标名完全一致:
+ \`puzzle\`、\`globe\`、\`code\`、\`folder\`、\`database\`、\`chart-column\`、
+ \`image\`、\`message-circle\`、\`calendar-days\`;不接受别名、任意图标名或图片路径;
+- \`main-view\` 与 \`panel\` 是两种独立权限。可以让两者指向同一 HTML,但必须分别
+ 申请 slot;主视图不接受 position、宽度或 systemButtons;
+- 声明该槽必须同时声明 \`minCindyVersion\`,填写首个正式提供 main-view Host 能力的
+ Cindy 版本。不要填写当前 \`0.0.0\` 开发版本,也不要在正式发布版本尚未裁决时猜测;
+- 插件批准并启用后,入口默认显示。用户可以在插件详情关闭“显示在侧边栏”;这只隐藏
+ 导航入口,不停用插件,也不关闭 tool、network、panel 或后台能力;
+- 主视图与 panel 共用同一 Ghost WebView 沙箱:零 Node、零通用 preload、每插件专属
+ partition、CSP 和导航守门不变。\`main-view\` 本身不附赠联网、文件、凭证或其它能力;
+- 页面需要电子脑逻辑时仍先 \`fetch('/wake')\`,通信和媒体协议与 §5 完全相同。插件停用、
+ 卸载或失去批准后,Host 会卸载页面并退出该路由。
+
## 5. 面板(panel.html/css/js)
- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= 停靠主聊天窗左侧的常驻
@@ -4282,6 +4383,8 @@ const opened = await cindy.iosSimulator.request({
· **未声明 command**:不拒装,但插件页"使用"按钮禁用,用户无法通过插件页一键启用
或用 $command 点名;AI 工具调用不受影响(见 §2 说明)
- 声明了 tool 槽但缺 tools(或反之)· panel.html 声明了但 slots 没有 "panel"
+- mainView 与 main-view 槽没有成对、mainView.html 文件缺失/路径不安全、icon 不在系统
+ 图标白名单、含未知字段,或声明 main-view 时漏了 minCindyVersion
- settingsHtml 路径不合法/文件不在包里 · settingsHeight 越界(160–800)或没配 settingsHtml 单独声明
- panel.systemButtons 格式错(不是对象、未知键、值非布尔,或 position:"tab" 时声明——插件页内面板没有标准头)
- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 2
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index e7853b3e90..842dea66ac 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -7941,7 +7941,7 @@ export function handleGhostExternalLinkNavigation(
* 意识 webview 附加验证(webview-security 的意识分区白名单口子):
* renderer 声明了意识分区的 <webview> 想要附加时,这里验明正身——
* 分区 id 合法、意识已装且唤醒、src 指向它自己协议下的自绘入口白名单
- * (面板 panel.html 或设置区 settingsHtml,声明哪个放行哪个;白名单真身
+ * (面板 panel.html、主视图 mainView.html 或设置区 settingsHtml,声明哪个放行哪个;白名单真身
* 是 shared 的 ghostWebviewEntryPaths,纯函数已单测)。全过才放行,顺手
* 把协议 handler 挂好(必须先于 webview 首次加载)。任何一条不满足返回
* null(闸口拒附加)。
diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.ts
index a7ec3c4a77..53a16faa42 100644
--- a/apps/desktop/src/main/sidebarSettingsStore.ts
+++ b/apps/desktop/src/main/sidebarSettingsStore.ts
@@ -16,8 +16,11 @@ import { isIpcError } from '../shared/ipc-errors.js';
import { normalizeProjectKey, projectKeyComparisonKey } from '../shared/projectKeys.js';
import {
normalizeSidebarPinnedOrder,
+ SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES,
SIDEBAR_PINNED_ORDER_ENTRY_MAX_LENGTH,
SIDEBAR_PINNED_ORDER_MAX_ENTRIES,
+ isSidebarGhostId,
+ type SidebarMainViewHiddenWriteRequest,
type SidebarPinnedOrderMutation,
type SidebarPinnedOrderWriteRequest,
type SidebarLegacyRendererOwnerClaim,
@@ -48,9 +51,14 @@ import { isAppContentWindow } from './windowFocusClassifier.js';
interface SidebarSettingsShape {
pinnedOrder: string[];
hiddenProjectKeys: string[];
+ hiddenMainViewGhostIds: string[];
}
-const DEFAULTS: SidebarSettingsShape = { pinnedOrder: [], hiddenProjectKeys: [] };
+const DEFAULTS: SidebarSettingsShape = {
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
+};
const MAX_HIDDEN_PROJECT_ENTRIES = 10_000;
const MAX_PROJECT_KEY_LENGTH = 4_096;
const MAX_SETTINGS_BYTES = 4 * 1024 * 1024;
@@ -90,11 +98,25 @@ function normalizeHiddenProjectKeys(raw: unknown): string[] {
return normalized;
}
+function normalizeHiddenMainViewGhostIds(raw: unknown): string[] {
+ if (!Array.isArray(raw)) return [];
+ const seen = new Set<string>();
+ const normalized: string[] = [];
+ for (const entry of raw) {
+ if (!isSidebarGhostId(entry) || seen.has(entry)) continue;
+ seen.add(entry);
+ normalized.push(entry);
+ if (normalized.length >= SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES) break;
+ }
+ return normalized;
+}
+
function normalizeSettings(raw: unknown): SidebarSettingsShape {
const value = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
return {
pinnedOrder: normalizeSidebarPinnedOrder(value.pinnedOrder),
hiddenProjectKeys: normalizeHiddenProjectKeys(value.hiddenProjectKeys),
+ hiddenMainViewGhostIds: normalizeHiddenMainViewGhostIds(value.hiddenMainViewGhostIds),
};
}
@@ -196,6 +218,7 @@ export function loadSidebarSettingsSnapshot(): SidebarSettingsSnapshot {
pinnedOrderIsAuthoritative: current.pinnedOrderIsAuthoritative,
pinnedOrder: Array.from(current.settings.pinnedOrder),
hiddenProjectKeys: Array.from(current.settings.hiddenProjectKeys),
+ hiddenMainViewGhostIds: Array.from(current.settings.hiddenMainViewGhostIds),
};
}
@@ -310,6 +333,13 @@ function requireProjectKey(raw: unknown): string {
return projectKey;
}
+function requireGhostId(raw: unknown): string {
+ if (!isSidebarGhostId(raw)) {
+ throwIpcError('INVALID_PARAMS', 'invalid main-view plugin id');
+ }
+ return raw;
+}
+
function requireWriteRequest(raw: unknown): Record<string, unknown> & DataOwnerPushStamp {
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !isDataOwnerPushStamp(raw)) {
throwIpcError('INVALID_PARAMS', 'invalid sidebar owner stamp');
@@ -375,6 +405,20 @@ function broadcastHiddenProjectKeysChanged(
}
}
+function broadcastHiddenMainViewGhostIdsChanged(
+ ghostIds: readonly string[],
+ ownerStamp: DataOwnerPushStamp,
+): void {
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (!isAppContentWindow(window)) continue;
+ window.webContents.send(
+ 'sidebar-settings:hidden-main-view-ghost-ids-changed',
+ Array.from(ghostIds),
+ ownerStamp,
+ );
+ }
+}
+
async function savePinnedOrder(rawRequest: unknown): Promise<string[]> {
const request = requireWriteRequest(rawRequest);
const mutation = requirePinnedMutation(request.mutation);
@@ -472,6 +516,57 @@ async function setProjectHidden(rawRequest: unknown): Promise<boolean> {
return changed;
}
+/** Persist one plugin main-view visibility override in Main's owner-scoped store. */
+async function setMainViewHidden(rawRequest: unknown): Promise<string[]> {
+ const request = requireWriteRequest(rawRequest);
+ const ghostId = requireGhostId(request.ghostId);
+ if (typeof request.hidden !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'invalid main-view hidden state');
+ }
+ const hidden = request.hidden;
+ assertRequestedOwner(request);
+ const scopeKey = activeOwnerScopeKey();
+ const ownerStamp: DataOwnerPushStamp = {
+ dataOwnerId: request.dataOwnerId,
+ ownerGeneration: request.ownerGeneration,
+ };
+ requireSidebarStoreAccess();
+ const store = currentStore();
+ let changed = false;
+ let nextSettings: SidebarSettingsShape;
+ try {
+ nextSettings = await enqueueWrite(scopeKey, () =>
+ store.updateAtomic((current) => {
+ requireSidebarStoreAccess({ rejectSnapshotChange: true });
+ const currentIds = current.value.hiddenMainViewGhostIds;
+ const alreadyHidden = currentIds.includes(ghostId);
+ if (alreadyHidden === hidden) return { hiddenMainViewGhostIds: currentIds };
+ if (hidden && currentIds.length >= SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES) {
+ throwIpcError('INVALID_PARAMS', 'too many hidden main-view plugins');
+ }
+ changed = true;
+ return {
+ hiddenMainViewGhostIds: hidden
+ ? [...currentIds, ghostId]
+ : currentIds.filter((entry) => entry !== ghostId),
+ };
+ }, SIDEBAR_WRITE_OPTIONS),
+ );
+ assertScopeCurrent(scopeKey);
+ } catch (err) {
+ if (isIpcError(err)) throw err;
+ if (activeOwnerScopeKey() !== scopeKey || isAppSessionBoundaryPending()) {
+ throwIpcError('PRECONDITION_FAILED', 'active account changed during sidebar mutation');
+ }
+ log.error('failed to persist hidden main-view plugins', err);
+ throwIpcError('INTERNAL', 'failed to persist sidebar settings');
+ }
+ if (changed) {
+ broadcastHiddenMainViewGhostIdsChanged(nextSettings.hiddenMainViewGhostIds, ownerStamp);
+ }
+ return Array.from(nextSettings.hiddenMainViewGhostIds);
+}
+
type SidebarPathState = 'missing' | 'regular-file' | 'blocked';
function sidebarPathState(file: string): SidebarPathState {
@@ -768,6 +863,10 @@ export function registerSidebarSettingsIpc(): void {
assertTrustedAppRendererEvent(event);
return setProjectHidden(request as SidebarProjectHiddenWriteRequest);
});
+ ipcMain.handle('sidebar-settings:set-main-view-hidden', (event, request) => {
+ assertTrustedAppRendererEvent(event);
+ return setMainViewHidden(request as SidebarMainViewHiddenWriteRequest);
+ });
}
export const __testing = {
@@ -775,5 +874,6 @@ export const __testing = {
MAX_SETTINGS_BYTES,
LEGACY_RENDERER_OWNER_MARKER_FILE,
MAX_LEGACY_RENDERER_OWNER_MARKER_BYTES,
+ SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES,
pendingWriteChainCount: () => writeChains.size,
};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b1216da582..77111a9e6f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -135,6 +135,7 @@ import type {
} from '../shared/voiceInputRefinerProfiles';
import { isIpcErrorCode, type IpcErrorCode } from '../shared/ipc-errors';
import {
+ isSidebarGhostId,
isSidebarLegacyRendererOwnerClaim,
isSidebarSettingsSnapshot,
type SidebarLegacyRendererOwnerClaim,
@@ -482,6 +483,9 @@ const fanOutSidebarPinnedOrderChanged = createIpcFanOut('sidebar-settings:pinned
const fanOutSidebarHiddenProjectKeysChanged = createIpcFanOut(
'sidebar-settings:hidden-project-keys-changed',
);
+const fanOutSidebarHiddenMainViewGhostIdsChanged = createIpcFanOut(
+ 'sidebar-settings:hidden-main-view-ghost-ids-changed',
+);
const fanOutSidebarProjectOrderChanged = createIpcFanOut(SIDEBAR_PROJECT_ORDER_CHANGED_CHANNEL);
// Workdir File Browser — push events from chokidar (add/change/unlink/...)
const fanOutFileBrowserEvent = createIpcFanOut('maker:file-browser:event');
@@ -4715,6 +4719,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
pinnedOrderIsAuthoritative: value.pinnedOrderIsAuthoritative,
pinnedOrder: Array.from(value.pinnedOrder),
hiddenProjectKeys: Array.from(value.hiddenProjectKeys),
+ hiddenMainViewGhostIds: Array.from(value.hiddenMainViewGhostIds),
}
: {
dataOwnerId: null,
@@ -4722,6 +4727,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
};
},
mutatePinnedOrder: async (
@@ -4771,6 +4777,33 @@ contextBridge.exposeInMainWorld('electronAPI', {
cb(Array.from(payload), ownerStamp);
}
}),
+ setMainViewHidden: async (
+ ghostId: string,
+ hidden: boolean,
+ ownerStamp: DataOwnerPushStamp,
+ ): Promise<string[]> => {
+ const result: unknown = await ipcRenderer.invoke('sidebar-settings:set-main-view-hidden', {
+ ...ownerStamp,
+ ghostId,
+ hidden,
+ });
+ if (!Array.isArray(result) || !result.every(isSidebarGhostId)) {
+ throw new Error('invalid hidden main-view plugin response');
+ }
+ return Array.from(result);
+ },
+ onHiddenMainViewGhostIdsChanged: (
+ cb: (ghostIds: string[], ownerStamp: DataOwnerPushStamp) => void,
+ ): (() => void) =>
+ fanOutSidebarHiddenMainViewGhostIdsChanged((payload, ownerStamp) => {
+ if (
+ Array.isArray(payload) &&
+ payload.every(isSidebarGhostId) &&
+ isDataOwnerPushStamp(ownerStamp)
+ ) {
+ cb(Array.from(payload), ownerStamp);
+ }
+ }),
getProjectOrder: async (): Promise<SyncedProjectOrderSnapshot> =>
parseProjectOrderSnapshot(await ipcRenderer.invoke(SIDEBAR_GET_PROJECT_ORDER_CHANNEL)),
applyProjectOrder: async (request: {
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts
index 372a69dc90..066be1d661 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts
@@ -85,9 +85,11 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
expect(scrollableRowsIdx).toBeGreaterThan(scrollRefIdx);
// 搜索打开时搜索行作为滚动容器直接子项 sticky;打开查询时记下并复位滚动,
// 清查询时还原,不再用 overlay 盖住输入框。
- expect(topNavSource).toContain("const pinSearch = section === 'scrollable' && search.query.trim().length > 0");
+ expect(topNavSource).toContain(
+ "const pinSearch = section === 'scrollable' && search.query.trim().length > 0",
+ );
expect(topNavSource).toContain("pinSearch && 'sticky top-0 z-30 bg-[var(--cmd-palette-bg)]'");
- expect(topNavSource).toContain('if (section === \'scrollable\')');
+ expect(topNavSource).toContain("if (section === 'scrollable')");
expect(sidebarUpperSource).toContain('lastListScrollTopRef.current = el.scrollTop');
expect(sidebarUpperSource).toContain(
'sidebarScrollRef.current?.scrollTo({ top: lastListScrollTopRef.current })',
@@ -96,12 +98,16 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
expect(sidebarUpperSource).toContain('searchProjectKey');
expect(sidebarUpperSource).toContain('onContextMenu={(event) => event.stopPropagation()}');
expect(sidebarUpperSource).toContain('{searchActive ? (');
- expect(sidebarUpperSource).toContain('<div hidden={searchActive} className="flex flex-col gap-2">');
+ expect(sidebarUpperSource).toContain(
+ '<div hidden={searchActive} className="flex flex-col gap-2">',
+ );
expect(sidebarUpperSource).toContain('freezeListScrollOnOpenRef.current = true');
expect(sidebarUpperSource).toContain('const restoreListScroll = useCallback');
expect(sidebarUpperSource).toContain('const restoreListScrollAfterPointer = useCallback');
expect(sidebarUpperSource).toContain('restoreListScrollAfterPointer()');
- expect(sidebarUpperSource).toContain("window.addEventListener('pointerup', onPointerEnd, true)");
+ expect(sidebarUpperSource).toContain(
+ "window.addEventListener('pointerup', onPointerEnd, true)",
+ );
expect(sidebarUpperSource).toContain("document.addEventListener('focusin', onFocusIn)");
const inlineSearchSource = read('features', 'cc-agent', 'sidebar', 'SidebarInlineSearch.tsx');
expect(inlineSearchSource).toContain('inputRef.current?.focus({ preventScroll: true })');
@@ -115,19 +121,25 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
expect(featureContextSource).toContain('export function useOwnsTopNavScrollableRows');
});
- it('插件面板恢复入口在展开态和 rail 态都位于插件与搜索之间', () => {
+ it('插件主视图紧随插件入口,面板恢复入口仍位于插件区与搜索之间', () => {
const expandedPluginsIdx = topNavSource.indexOf('{pluginsRow}');
+ const expandedMainViewsIdx = topNavSource.indexOf('{mainViewRows}', expandedPluginsIdx);
const expandedRestoreIdx = topNavSource.indexOf('{restoreRow}', expandedPluginsIdx);
const expandedSearchIdx = topNavSource.indexOf('{searchRow}', expandedRestoreIdx);
expect(expandedPluginsIdx).toBeGreaterThanOrEqual(0);
- expect(expandedRestoreIdx).toBeGreaterThan(expandedPluginsIdx);
+ expect(expandedMainViewsIdx).toBeGreaterThan(expandedPluginsIdx);
+ expect(expandedRestoreIdx).toBeGreaterThan(expandedMainViewsIdx);
expect(expandedSearchIdx).toBeGreaterThan(expandedRestoreIdx);
+ const persistentPluginsIdx = topNavSource.lastIndexOf('{pluginsRow}');
+ const persistentMainViewsIdx = topNavSource.indexOf('{mainViewRows}', persistentPluginsIdx);
+ const persistentRestoreIdx = topNavSource.indexOf('{restoreRow}', persistentMainViewsIdx);
+ expect(persistentPluginsIdx).toBeGreaterThan(expandedPluginsIdx);
+ expect(persistentMainViewsIdx).toBeGreaterThan(persistentPluginsIdx);
+ expect(persistentRestoreIdx).toBeGreaterThan(persistentMainViewsIdx);
+
const railPluginsIdx = sidebarUpperSource.indexOf("label={t('sidebar.tabs.plugins')}");
- const railRestoreIdx = sidebarUpperSource.indexOf(
- '<GhostPanelRestoreEntry',
- railPluginsIdx,
- );
+ const railRestoreIdx = sidebarUpperSource.indexOf('<GhostPanelRestoreEntry', railPluginsIdx);
const railSearchIdx = sidebarUpperSource.indexOf('<ConversationSearchBox', railRestoreIdx);
expect(railPluginsIdx).toBeGreaterThanOrEqual(0);
expect(railRestoreIdx).toBeGreaterThan(railPluginsIdx);
@@ -255,9 +267,9 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
it('列表行也接收来源标签(平铺时项目会话不再丢项目名)', () => {
const entryListSource = read('features', 'cc-agent', 'sidebar', 'SessionEntryList.tsx');
expect(entryListSource).toContain('sourceLabel={sourceLabelMap?.get(entry.session.id)}');
- expect(entryListSource.match(/sourceLabel=\{sourceLabelMap\?\.get\(entry\.session\.id\)\}/g)).toHaveLength(
- 2,
- );
+ expect(
+ entryListSource.match(/sourceLabel=\{sourceLabelMap\?\.get\(entry\.session\.id\)\}/g),
+ ).toHaveLength(2);
const automationGroupSource = read(
'features',
'cc-agent',
@@ -671,8 +683,10 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
it('项目顺序菜单勾选跟 resolveDisplayedProjectOrder,不回退查看端偏好', () => {
const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');
expect(filterSource).toContain('resolveDisplayedProjectOrder(');
- expect(filterSource).toContain('scopedProjectOrder: FilterProjectOrder = resolveDisplayedProjectOrder(');
- expect(filterSource).not.toContain('hostCustom ? \'custom\' : projectOrder');
+ expect(filterSource).toContain(
+ 'scopedProjectOrder: FilterProjectOrder = resolveDisplayedProjectOrder(',
+ );
+ expect(filterSource).not.toContain("hostCustom ? 'custom' : projectOrder");
});
it('远程 GET 用 fetch fence,本机播种只在成功后按 owner 锁定', () => {
@@ -683,6 +697,8 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
expect(hookSource).toContain('seededLocalHostOwners.add');
expect(hookSource).not.toContain('localHostSeedStarted = true');
expect(hookSource).toContain('void load(1)');
- expect(hookSource).toContain('attempt < 3 && entries.some(([, result]) => result.kind === \'transient\')');
+ expect(hookSource).toContain(
+ "attempt < 3 && entries.some(([, result]) => result.kind === 'transient')",
+ );
});
});
diff --git a/apps/desktop/src/renderer/__tests__/sidebarOwnerStorage.test.ts b/apps/desktop/src/renderer/__tests__/sidebarOwnerStorage.test.ts
index c2c9c21870..780ad7eec4 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarOwnerStorage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sidebarOwnerStorage.test.ts
@@ -139,9 +139,7 @@ describe('sidebar owner-scoped renderer storage', () => {
it('blocks a first scoped write while shared legacy ownership is unresolved', () => {
localStorage.setItem(PROJECTS_KEY, '["legacy"]');
__testing.setOwnerAuthorityReader((ownerId) =>
- ownerId === 'owner-a'
- ? { ...OWNER_A, claimed: false, canInitialize: false }
- : null,
+ ownerId === 'owner-a' ? { ...OWNER_A, claimed: false, canInitialize: false } : null,
);
expect(writeSidebarOwnerStorage(PROJECTS_KEY, 'owner-a', '["default-derived"]')).toBe(false);
@@ -155,9 +153,7 @@ describe('sidebar owner-scoped renderer storage', () => {
expect(readSidebarOwnerStorage(PROJECTS_KEY, 'owner-a')).toBe('["legacy"]');
__testing.setOwnerAuthorityReader((ownerId) =>
- ownerId === 'owner-a'
- ? { ...OWNER_A, claimed: false, canInitialize: false }
- : null,
+ ownerId === 'owner-a' ? { ...OWNER_A, claimed: false, canInitialize: false } : null,
);
expect(readSidebarOwnerStorage(PROJECTS_KEY, 'owner-a')).toBeNull();
expect(writeSidebarOwnerStorage(PROJECTS_KEY, 'owner-a', '["default-derived"]')).toBe(false);
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
index 6cd6ba6c9a..54cbbdd9bb 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
@@ -49,6 +49,7 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {
tool: Wrench,
command: Terminal,
panel: PanelRight,
+ 'main-view': AppWindow,
code: FileCode2,
subscribe: Bell,
card: LayoutTemplate,
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts
new file mode 100644
index 0000000000..63f3b3bcd9
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+
+import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
+import { projectGhostMainViews } from '../ghostMainViews';
+
+function ghost(
+ id: string,
+ overrides: Omit<Partial<InstalledGhost>, 'manifest'> & { manifest?: Partial<GhostManifest> } = {},
+): InstalledGhost {
+ return {
+ dir: `/plugins/${id}`,
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ ...overrides,
+ manifest: {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['main-view'],
+ minCindyVersion: '1.0.0',
+ mainView: { html: 'main-view.html' },
+ ...overrides.manifest,
+ },
+ };
+}
+
+describe('projectGhostMainViews', () => {
+ it('keeps declared, route-capable and sidebar-visible layers separate', () => {
+ const hidden = new Set(['hidden']);
+ const projection = projectGhostMainViews(
+ [
+ ghost('visible'),
+ ghost('hidden'),
+ ghost('disabled', { enabled: false }),
+ ghost('unapproved', { approval: { state: 'invalid' } }),
+ ghost('panel-only', { manifest: { slots: ['panel'], mainView: undefined } }),
+ ],
+ { locale: 'en', isSidebarVisible: (id) => !hidden.has(id) },
+ );
+
+ expect(projection.declared.map((item) => item.ghostId)).toEqual([
+ 'disabled',
+ 'hidden',
+ 'unapproved',
+ 'visible',
+ ]);
+ expect(projection.routeCapable.map((item) => item.ghostId)).toEqual(['hidden', 'visible']);
+ expect(projection.sidebarVisible.map((item) => item.ghostId)).toEqual(['visible']);
+ });
+
+ it('uses the localized main-view title, falls back to plugin name and sorts stably', () => {
+ const projection = projectGhostMainViews(
+ [
+ ghost('z-id', {
+ manifest: {
+ name: 'Beta',
+ mainView: { html: 'view.html', title: 'Alpha', icon: 'globe' },
+ },
+ }),
+ ghost('a-id', { manifest: { name: 'alpha' } }),
+ ],
+ { locale: 'en', isSidebarVisible: () => true },
+ );
+
+ expect(projection.declared.map(({ ghostId, title }) => [ghostId, title])).toEqual([
+ ['a-id', 'alpha'],
+ ['z-id', 'Alpha'],
+ ]);
+ expect(projection.declared.map(({ ghostId, icon }) => [ghostId, icon])).toEqual([
+ ['a-id', 'puzzle'],
+ ['z-id', 'globe'],
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
index 94edc63adb..4c83b39813 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
@@ -10,7 +10,7 @@ import type { PluginMarketItem } from '../../../shared/pluginMarket';
import {
filterGhostPluginItems,
ghostFallbackIconKind,
- ghostPanelOwnerKey,
+ ghostWebviewOwnerKey,
ghostPrimaryAction,
marketPresentationForInstalledGhost,
nextOpenPanelIdForOwner,
@@ -112,6 +112,8 @@ describe('ghostPluginViewModel', () => {
approvalState: 'approved',
builtin: false,
tabPanel: false,
+ hasMainView: false,
+ mainViewTitle: null,
hostCapability: null,
},
{
@@ -124,6 +126,8 @@ describe('ghostPluginViewModel', () => {
approvalState: 'approved',
builtin: false,
tabPanel: false,
+ hasMainView: false,
+ mainViewTitle: null,
hostCapability: null,
},
{
@@ -136,6 +140,8 @@ describe('ghostPluginViewModel', () => {
approvalState: 'approved',
builtin: false,
tabPanel: false,
+ hasMainView: false,
+ mainViewTitle: null,
hostCapability: null,
},
] satisfies GhostPluginListItem[];
@@ -248,6 +254,24 @@ describe('ghostPluginViewModel', () => {
expect(ghostPrimaryAction(item)).toBe('capability');
});
+ it('projects main-view metadata without overriding the existing panel action', () => {
+ const item = toGhostPluginListItem(
+ installed({
+ enabled: false,
+ approval: { state: 'invalid' },
+ manifest: manifest({
+ slots: ['main-view', 'panel'],
+ minCindyVersion: '1.2.3',
+ mainView: { html: 'main-view.html', title: 'Workspace' },
+ panel: { html: 'panel.html', position: 'tab' },
+ }),
+ }),
+ );
+
+ expect(item).toMatchObject({ hasMainView: true, mainViewTitle: 'Workspace', enabled: false });
+ expect(ghostPrimaryAction(item)).toBe('panel');
+ });
+
it('overlays exact installed market presentation without changing runtime facts', () => {
const ghost = installed({
iconDataUrl: 'data:image/png;base64,OLD',
@@ -339,9 +363,9 @@ describe('ghostPluginViewModel', () => {
expect(
toGhostPluginListItem(installed({ approval: { state: 'legacy-unapproved' } })).approvalState,
).toBe('legacy-unapproved');
- expect(
- toGhostPluginDetail(installed({ approval: { state: 'invalid' } })).approvalState,
- ).toBe('invalid');
+ expect(toGhostPluginDetail(installed({ approval: { state: 'invalid' } })).approvalState).toBe(
+ 'invalid',
+ );
});
it('derives detail permissions and runtime declarations from the manifest', () => {
@@ -401,28 +425,28 @@ describe('ghostPluginViewModel', () => {
});
});
-describe('plugin panel owner isolation', () => {
- it('gives each data owner its own panel host key and stays stable within one', () => {
- const cloudA = ghostPanelOwnerKey('cloud', 'owner-a');
- const cloudB = ghostPanelOwnerKey('cloud', 'owner-b');
- const local = ghostPanelOwnerKey('local', null);
+describe('plugin webview owner isolation', () => {
+ it('gives each data owner its own webview host key and stays stable within one', () => {
+ const cloudA = ghostWebviewOwnerKey('cloud', 'owner-a');
+ const cloudB = ghostWebviewOwnerKey('cloud', 'owner-b');
+ const local = ghostWebviewOwnerKey('local', null);
// 账号 A 与 B 即便装了同 id / 同版本 / 同入口的插件,宿主 key 也必须不同——
// 否则 React 复用同一 webview 实例,A 的 DOM 与内存态会留在 B 面前。
expect(new Set([cloudA, cloudB, local]).size).toBe(3);
// 同一身份内稳定,不会无谓重挂面板。
- expect(ghostPanelOwnerKey('cloud', 'owner-a')).toBe(cloudA);
+ expect(ghostWebviewOwnerKey('cloud', 'owner-a')).toBe(cloudA);
});
it('closes an open panel when the data owner changes, keeps it otherwise', () => {
- const a = ghostPanelOwnerKey('cloud', 'owner-a');
- const b = ghostPanelOwnerKey('cloud', 'owner-b');
+ const a = ghostWebviewOwnerKey('cloud', 'owner-a');
+ const b = ghostWebviewOwnerKey('cloud', 'owner-b');
// A 打开着面板 → 切到 B:必须关掉,不许因为 B 也装了同 id 的插件就留着。
expect(nextOpenPanelIdForOwner(a, b, 'ghost-shared')).toBeNull();
// 云 → 本地同样算换身份。
expect(
- nextOpenPanelIdForOwner(a, ghostPanelOwnerKey('local', null), 'ghost-shared'),
+ nextOpenPanelIdForOwner(a, ghostWebviewOwnerKey('local', null), 'ghost-shared'),
).toBeNull();
// 身份没变则原样保留(别把用户正在用的面板关掉)。
expect(nextOpenPanelIdForOwner(a, a, 'ghost-shared')).toBe('ghost-shared');
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
new file mode 100644
index 0000000000..2e9e2d1400
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
@@ -0,0 +1,89 @@
+/** @vitest-environment jsdom */
+
+import { fireEvent, render, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../ghostPanelTheme', () => ({
+ createGhostThemeInjector: () => ({
+ inject: vi.fn(),
+ onDomReady: vi.fn(),
+ dispose: vi.fn(),
+ }),
+ observeHostTheme: () => vi.fn(),
+}));
+
+import { GhostWebviewBody } from '../ghostPanelBody';
+import type { GhostManifest } from '../../../shared/ghost';
+
+const manifest: GhostManifest = {
+ schemaVersion: 2,
+ id: 'workspace',
+ name: 'Workspace',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['main-view'],
+ minCindyVersion: '1.2.3',
+ mainView: { html: 'main-view.html' },
+};
+
+describe('GhostWebviewBody', () => {
+ it('keeps the existing per-plugin partition and approved cindy-ghost entry shape', async () => {
+ const { container } = render(
+ <GhostWebviewBody manifest={manifest} html={manifest.mainView?.html} />,
+ );
+
+ await waitFor(() => expect(container.querySelector('webview')).not.toBeNull());
+ const webview = container.querySelector('webview');
+ expect(webview?.getAttribute('partition')).toBe('cindy-ghost-workspace');
+ expect(webview?.getAttribute('src')).toBe('cindy-ghost://workspace/main-view.html');
+ expect(webview?.hasAttribute('preload')).toBe(false);
+ });
+
+ it('shows the recoverable error state when the main document fails to load', async () => {
+ const { container, getByRole } = render(
+ <GhostWebviewBody manifest={manifest} html={manifest.mainView?.html} />,
+ );
+ const webview = await waitFor(() => {
+ const node = container.querySelector('webview');
+ expect(node).not.toBeNull();
+ return node as HTMLElement;
+ });
+
+ const event = new Event('did-fail-load') as Electron.DidFailLoadEvent;
+ Object.defineProperties(event, {
+ errorCode: { value: -6 },
+ isMainFrame: { value: true },
+ });
+ fireEvent(webview, event);
+
+ expect(getByRole('button', { name: 'settings.ghosts.panelError.reload' })).toBeTruthy();
+ expect(container.querySelector('webview')).toBeNull();
+ });
+
+ it('ignores aborted navigation and subframe load failures', async () => {
+ const { container, queryByRole } = render(
+ <GhostWebviewBody manifest={manifest} html={manifest.mainView?.html} />,
+ );
+ const webview = await waitFor(() => {
+ const node = container.querySelector('webview');
+ expect(node).not.toBeNull();
+ return node as HTMLElement;
+ });
+
+ for (const [errorCode, isMainFrame] of [
+ [-3, true],
+ [-6, false],
+ ] as const) {
+ const event = new Event('did-fail-load') as Electron.DidFailLoadEvent;
+ Object.defineProperties(event, {
+ errorCode: { value: errorCode },
+ isMainFrame: { value: isMainFrame },
+ });
+ fireEvent(webview, event);
+ }
+
+ expect(queryByRole('button', { name: 'settings.ghosts.panelError.reload' })).toBeNull();
+ expect(container.querySelector('webview')).toBe(webview);
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/mainViewVisibilityStore.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/mainViewVisibilityStore.test.ts
new file mode 100644
index 0000000000..8759e514e3
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/mainViewVisibilityStore.test.ts
@@ -0,0 +1,165 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ __testing as ownerGenerationTesting,
+ getDataOwnerGeneration,
+ setDataOwnerGeneration,
+} from '@/contexts/dataOwnerGeneration';
+import type { DataOwnerPushStamp } from '../../../shared/dataOwnerPush';
+import type { SidebarSettingsSnapshot } from '../../../shared/sidebarSettings';
+import {
+ __testing,
+ readMainViewSidebarVisible,
+ useMainViewVisibilityRevision,
+ writeMainViewSidebarVisible,
+} from '../mainViewVisibilityStore';
+
+type VisibilityListener = (ghostIds: string[], ownerStamp: DataOwnerPushStamp) => void;
+
+let currentSnapshot: SidebarSettingsSnapshot;
+let visibilityListeners: VisibilityListener[];
+let setMainViewHidden: ReturnType<typeof vi.fn>;
+
+function snapshot(
+ dataOwnerId: string | null,
+ ownerGeneration: number,
+ hiddenMainViewGhostIds: string[] = [],
+): SidebarSettingsSnapshot {
+ return {
+ dataOwnerId,
+ ownerGeneration,
+ pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds,
+ };
+}
+
+beforeEach(() => {
+ setDataOwnerGeneration('owner-a', 4);
+ currentSnapshot = snapshot('owner-a', 4);
+ visibilityListeners = [];
+ setMainViewHidden = vi
+ .fn()
+ .mockImplementation(
+ async (ghostId: string, hidden: boolean, ownerStamp: DataOwnerPushStamp) => {
+ currentSnapshot = snapshot(
+ ownerStamp.dataOwnerId,
+ ownerStamp.ownerGeneration,
+ hidden
+ ? [...currentSnapshot.hiddenMainViewGhostIds, ghostId]
+ : currentSnapshot.hiddenMainViewGhostIds.filter((id) => id !== ghostId),
+ );
+ for (const listener of visibilityListeners) {
+ listener(Array.from(currentSnapshot.hiddenMainViewGhostIds), ownerStamp);
+ }
+ return Array.from(currentSnapshot.hiddenMainViewGhostIds);
+ },
+ );
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ sidebarSettings: {
+ loadSnapshot: () => ({
+ ...currentSnapshot,
+ hiddenMainViewGhostIds: Array.from(currentSnapshot.hiddenMainViewGhostIds),
+ }),
+ setMainViewHidden,
+ onHiddenMainViewGhostIdsChanged: (listener: VisibilityListener) => {
+ visibilityListeners.push(listener);
+ return () => {
+ visibilityListeners = visibilityListeners.filter((entry) => entry !== listener);
+ };
+ },
+ },
+ };
+});
+
+afterEach(() => {
+ __testing.reset();
+ ownerGenerationTesting.reset();
+ vi.unstubAllGlobals();
+});
+
+describe('main-view sidebar visibility', () => {
+ it('defaults to visible and persists only the hidden override in Main', async () => {
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(true);
+
+ await expect(
+ writeMainViewSidebarVisible(getDataOwnerGeneration(), 'workspace', false),
+ ).resolves.toBe(true);
+ expect(setMainViewHidden).toHaveBeenLastCalledWith('workspace', true, {
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 4,
+ });
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(false);
+
+ await expect(
+ writeMainViewSidebarVisible(getDataOwnerGeneration(), 'workspace', true),
+ ).resolves.toBe(true);
+ expect(setMainViewHidden).toHaveBeenLastCalledWith('workspace', false, {
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 4,
+ });
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(true);
+ });
+
+ it('rejects a write captured before an owner-generation boundary', async () => {
+ const staleOwner = getDataOwnerGeneration();
+ setDataOwnerGeneration('owner-a', 5);
+ currentSnapshot = snapshot('owner-a', 5);
+
+ await expect(writeMainViewSidebarVisible(staleOwner, 'workspace', false)).resolves.toBe(false);
+ expect(setMainViewHidden).not.toHaveBeenCalled();
+ });
+
+ it('ignores a completed write after the same owner advances generation', async () => {
+ let resolveWrite!: (ids: string[]) => void;
+ setMainViewHidden.mockReturnValueOnce(
+ new Promise<string[]>((resolve) => {
+ resolveWrite = resolve;
+ }),
+ );
+ const oldOwner = getDataOwnerGeneration();
+ const writing = writeMainViewSidebarVisible(oldOwner, 'workspace', false);
+
+ setDataOwnerGeneration('owner-a', 5);
+ currentSnapshot = snapshot('owner-a', 5);
+ resolveWrite(['workspace']);
+
+ await expect(writing).resolves.toBe(false);
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(true);
+ });
+
+ it('reacts to current-owner broadcasts and ignores stale-owner broadcasts', () => {
+ const view = renderHook(() => useMainViewVisibilityRevision());
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(true);
+
+ act(() => {
+ visibilityListeners[0]?.(['workspace'], {
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 4,
+ });
+ });
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(false);
+
+ act(() => {
+ visibilityListeners[0]?.([], {
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 3,
+ });
+ });
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(false);
+ view.unmount();
+ });
+
+ it('loads the new owner snapshot instead of retaining the previous owner state', () => {
+ currentSnapshot = snapshot('owner-a', 4, ['workspace']);
+ expect(readMainViewSidebarVisible('owner-a', 'workspace')).toBe(false);
+
+ setDataOwnerGeneration('owner-b', 7);
+ currentSnapshot = snapshot('owner-b', 7);
+ expect(readMainViewSidebarVisible('owner-b', 'workspace')).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts b/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts
new file mode 100644
index 0000000000..7cdde0998b
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts
@@ -0,0 +1,81 @@
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAuth } from '@/contexts/AuthContext';
+
+import type { GhostMainViewIcon, GhostManifest, InstalledGhost } from '../../shared/ghost';
+import { useInstalledGhosts } from './useInstalledGhosts';
+import {
+ readMainViewSidebarVisible,
+ useMainViewVisibilityRevision,
+} from './mainViewVisibilityStore';
+
+export interface GhostMainViewItem {
+ ghostId: string;
+ title: string;
+ icon: GhostMainViewIcon;
+ manifest: GhostManifest;
+ installedGhost: InstalledGhost;
+}
+
+export interface GhostMainViewProjection {
+ declared: GhostMainViewItem[];
+ routeCapable: GhostMainViewItem[];
+ sidebarVisible: GhostMainViewItem[];
+}
+
+function mainViewDeclared(ghost: InstalledGhost): boolean {
+ return ghost.manifest.slots.includes('main-view') && ghost.manifest.mainView !== undefined;
+}
+
+export function projectGhostMainViews(
+ ghosts: readonly InstalledGhost[],
+ {
+ locale,
+ isSidebarVisible,
+ }: {
+ locale: string | undefined;
+ isSidebarVisible: (ghostId: string) => boolean;
+ },
+): GhostMainViewProjection {
+ const declared = ghosts
+ .filter(mainViewDeclared)
+ .map((installedGhost): GhostMainViewItem => {
+ const { manifest } = installedGhost;
+ return {
+ ghostId: manifest.id,
+ title: manifest.mainView?.title ?? manifest.name,
+ icon: manifest.mainView?.icon ?? 'puzzle',
+ manifest,
+ installedGhost,
+ };
+ })
+ .sort(
+ (left, right) =>
+ left.title.localeCompare(right.title, locale, { sensitivity: 'base' }) ||
+ left.ghostId.localeCompare(right.ghostId),
+ );
+ const routeCapable = declared.filter(
+ ({ installedGhost }) => installedGhost.enabled && installedGhost.approval.state === 'approved',
+ );
+ const sidebarVisible = routeCapable.filter(({ ghostId }) => isSidebarVisible(ghostId));
+ return { declared, routeCapable, sidebarVisible };
+}
+
+/** One reactive projection shared by the expanded sidebar, rail and route host. */
+export function useGhostMainViews(): GhostMainViewProjection {
+ const ghosts = useInstalledGhosts();
+ const { dataOwnerId } = useAuth();
+ const { i18n } = useTranslation();
+ const visibilityRevision = useMainViewVisibilityRevision();
+ const locale = i18n.resolvedLanguage ?? i18n.language;
+
+ return useMemo(
+ () =>
+ projectGhostMainViews(ghosts, {
+ locale,
+ isSidebarVisible: (ghostId) => readMainViewSidebarVisible(dataOwnerId, ghostId),
+ }),
+ [dataOwnerId, ghosts, locale, visibilityRevision],
+ );
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
index 8009280e41..27989d735d 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
@@ -44,12 +44,17 @@ export function GhostPanelError({
onReload?: () => void;
}): ReactNode {
const { t } = useTranslation();
- const reload = onReload ?? (() => void window.electronAPI.ghosts.reload(manifest.id).catch(() => {}));
+ const reload =
+ onReload ?? (() => void window.electronAPI.ghosts.reload(manifest.id).catch(() => {}));
return (
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-4">
<CircleAlert size={22} className="text-[var(--error-fg)]" />
<p className="text-center text-12 leading-relaxed text-[var(--text-secondary)]">
- {t(state === 'fused' ? 'settings.ghosts.panelError.fused' : 'settings.ghosts.panelError.crashed')}
+ {t(
+ state === 'fused'
+ ? 'settings.ghosts.panelError.fused'
+ : 'settings.ghosts.panelError.crashed',
+ )}
</p>
<div className="flex items-center gap-2">
<button
@@ -62,7 +67,9 @@ export function GhostPanelError({
{/* 关闭 = 转沉睡,可逆动作,按 docs/design-rules/cindy-design-system.md 红色纪律走灰度次按钮(红只留错误图标)。 */}
<button
type="button"
- onClick={() => void window.electronAPI.ghosts.setEnabled(manifest.id, false).catch(() => {})}
+ onClick={() =>
+ void window.electronAPI.ghosts.setEnabled(manifest.id, false).catch(() => {})
+ }
className="rounded-full border border-[var(--border-default)] px-3.5 py-1.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-chip)]"
>
{t('settings.ghosts.panelError.close')}
@@ -172,61 +179,40 @@ export function pickGhostPanelMediaUri(
}
/**
- * 芯片型意识的自绘面板体:一块沙箱 webview 装载意识自己的
- * panel.html——分区/地址由 main 侧 webview 附加闸验明正身(webview-security),
+ * 插件自绘页面的通用 webview 体:装载调用方已经从批准 manifest 选定的入口。
+ * panel 与 main-view 只在 Host 入口和生命周期上不同,安全装载内核保持一份。
+ * 分区/地址由 main 侧 webview 附加闸验明正身(webview-security),
* 主题 token 在 dom-ready 注入、主机换肤时重灌(ghostPanelTheme)。
* webview 崩溃 = 本地错误接管态(重载 = 原地重挂载,不经主机)。
*/
-export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): ReactNode {
+export function GhostWebviewBody({
+ manifest,
+ html,
+ onHostNode,
+}: {
+ manifest: GhostManifest;
+ html: string | undefined;
+ onHostNode?: (node: HTMLDivElement | null) => void;
+}): ReactNode {
const [crashed, setCrashed] = useState(false);
const [generation, setGeneration] = useState(0);
const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
-
- /**
- * 面板体挂载 = 未读已读(badge 槽的 explicit 清零)。
- *
- * 清零收在这里而不是各宿主的"打开"动作里:面板体有三个宿主(插件页页签
- * GhostPagePanelHost、布局停靠 ghostPanels、独立窗口 GhostPanelWindowLayout),
- * 挂载到本组件才是"内容确实在用户眼前"的唯一判据,三处天然对称。
- * unread 进依赖:面板**已经开着**时插件又点亮一次(后台拿到新内容),用户
- * 正看着它,不该留一颗清不掉的点。
- *
- * 清零的必要条件是**两层可见性同时成立**,缺一层都会把用户没看见的未读吞掉:
- * 1. `foreground` —— 宿主窗口可见且聚焦。停靠面板与独立面板窗口长期挂着,
- * 只看挂载的话,窗口最小化 / 失焦期间到来的未读会被一律清掉,常开面板的
- * 用户从此收不到这个插件的提醒(codex review P1)。
- * 2. `visible` —— 本面板**自己**占着可见面积。光有第 1 层还不够:同一个前台
- * 窗口里,另一个停靠面板被最大化时本面板仍然挂载,却被压成零宽/隐藏,
- * 用户根本没看到内容(codex review)。
- * 两层都满足的那一刻 effect 重跑并清零,语义正是「他看的时候才算看过」。
- */
- const unread = useGhostUnread(manifest.id);
- const foreground = useHostWindowForeground();
- const { ref: observeHost, visible } = useElementVisible();
- // 同一个 div 既要给 webview 挂载用(命令式 hostRef),又要被可见性观察器盯住。
- // 合成一个 callback ref:崩溃走 fallback 时它带 null 触发(观察器解绑),
- // 用户「重载」生成新 div 时又带新节点触发(观察器重挂)——正是 ref 对象做不到的。
const setHostNode = useCallback(
(el: HTMLDivElement | null) => {
hostRef.current = el;
- observeHost(el);
+ onHostNode?.(el);
},
- [observeHost],
+ [onHostNode],
);
- useEffect(() => {
- if (!unread || !foreground || !visible) return;
- clearGhostUnread(manifest.id);
- }, [manifest.id, unread, foreground, visible]);
- const panelHtml = manifest.panel?.html;
useEffect(() => {
- if (crashed || !panelHtml) return;
+ if (crashed || !html) return;
const host = hostRef.current;
if (!host) return;
const webview = document.createElement('webview') as WebviewTag;
webview.setAttribute('partition', ghostPartition(manifest.id));
- webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${panelHtml}`);
+ webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${html}`);
webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;');
let disposed = false;
let themeTimer: ReturnType<typeof setTimeout> | null = null;
@@ -245,6 +231,12 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
const onGone = () => {
if (!disposed) setCrashed(true);
};
+ // 主文档缺失、协议供片失败等必须进入可恢复错误态,不能留下白屏。
+ // -3 = ABORTED(导航中断);子 frame 失败也不代表主页面已经失效。
+ const onFailLoad = (event: Electron.DidFailLoadEvent) => {
+ if (disposed || event.errorCode === -3 || !event.isMainFrame) return;
+ setCrashed(true);
+ };
// 右键产物 cell → 宿主自绘菜单(复制文件 / 打开所在目录,与聊天媒体同款)。
// context-menu 是 Chromium 对真实右键的原生上报,guest 脚本 dispatchEvent
// 触发不了;地址过 main 闸(形状/归属/mime)换发 cindy-media:// 后才弹,
@@ -272,6 +264,7 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
};
webview.addEventListener('dom-ready', onDomReady);
webview.addEventListener('render-process-gone', onGone);
+ webview.addEventListener('did-fail-load', onFailLoad);
webview.addEventListener('context-menu', onContextMenu);
const unobserveTheme = observeHostTheme(scheduleInjectTheme);
host.appendChild(webview);
@@ -282,6 +275,7 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
unobserveTheme();
webview.removeEventListener('dom-ready', onDomReady);
webview.removeEventListener('render-process-gone', onGone);
+ webview.removeEventListener('did-fail-load', onFailLoad);
webview.removeEventListener('context-menu', onContextMenu);
webview.remove();
// 菜单与 webview 同生共死:原位升级/重载导致的重挂载把开着的旧菜单
@@ -290,14 +284,7 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
};
// version 入依赖:原位更新换版后 webview 重挂载,面板立刻跑新代码
// (供片协议直读安装目录,不重挂会一直渲染旧版缓存的页面)。
- }, [
- crashed,
- generation,
- manifest.id,
- manifest.version,
- manifest.resolvedLocale,
- panelHtml,
- ]);
+ }, [crashed, generation, manifest.id, manifest.version, manifest.resolvedLocale, html]);
if (crashed) {
return (
@@ -322,3 +309,39 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
</>
);
}
+
+/**
+ * 芯片型意识面板 wrapper。未读清零刻意留在 panel 生命周期,main-view
+ * 即使展示同一个插件也不能误清 panel 的 badge。
+ */
+export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): ReactNode {
+ /**
+ * 面板体挂载 = 未读已读(badge 槽的 explicit 清零)。
+ *
+ * 清零收在这里而不是各宿主的"打开"动作里:面板体有三个宿主(插件页页签
+ * GhostPagePanelHost、布局停靠 ghostPanels、独立窗口 GhostPanelWindowLayout),
+ * 挂载到本组件才是"内容确实在用户眼前"的唯一判据,三处天然对称。
+ * unread 进依赖:面板**已经开着**时插件又点亮一次(后台拿到新内容),用户
+ * 正看着它,不该留一颗清不掉的点。
+ *
+ * 清零的必要条件是**两层可见性同时成立**,缺一层都会把用户没看见的未读吞掉:
+ * 1. `foreground` —— 宿主窗口可见且聚焦。停靠面板与独立面板窗口长期挂着,
+ * 只看挂载的话,窗口最小化 / 失焦期间到来的未读会被一律清掉,常开面板的
+ * 用户从此收不到这个插件的提醒(codex review P1)。
+ * 2. `visible` —— 本面板**自己**占着可见面积。光有第 1 层还不够:同一个前台
+ * 窗口里,另一个停靠面板被最大化时本面板仍然挂载,却被压成零宽/隐藏,
+ * 用户根本没看到内容(codex review)。
+ * 两层都满足的那一刻 effect 重跑并清零,语义正是「他看的时候才算看过」。
+ */
+ const unread = useGhostUnread(manifest.id);
+ const foreground = useHostWindowForeground();
+ const { ref: observeHost, visible } = useElementVisible();
+ useEffect(() => {
+ if (!unread || !foreground || !visible) return;
+ clearGhostUnread(manifest.id);
+ }, [manifest.id, unread, foreground, visible]);
+
+ return (
+ <GhostWebviewBody manifest={manifest} html={manifest.panel?.html} onHostNode={observeHost} />
+ );
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/mainViewVisibilityStore.ts b/apps/desktop/src/renderer/cindy-brain/mainViewVisibilityStore.ts
new file mode 100644
index 0000000000..f38e4cb321
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/mainViewVisibilityStore.ts
@@ -0,0 +1,148 @@
+import { useSyncExternalStore } from 'react';
+
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+ isDataOwnerPushStampCurrent,
+ type DataOwnerGeneration,
+} from '@/contexts/dataOwnerGeneration';
+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush';
+
+interface MainViewVisibilitySnapshot extends DataOwnerPushStamp {
+ readonly hiddenGhostIds: ReadonlySet<string>;
+}
+
+let snapshot: MainViewVisibilitySnapshot | null = null;
+let revision = 0;
+let unsubscribeFromMain: (() => void) | null = null;
+const listeners = new Set<() => void>();
+
+function sameIds(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
+ if (left.size !== right.size) return false;
+ for (const id of left) {
+ if (!right.has(id)) return false;
+ }
+ return true;
+}
+
+function emitChange(): void {
+ revision += 1;
+ listeners.forEach((listener) => listener());
+}
+
+function reconcile(
+ hiddenGhostIds: readonly string[],
+ ownerStamp: DataOwnerPushStamp,
+ notify: boolean,
+): boolean {
+ if (!isDataOwnerPushStampCurrent(ownerStamp)) return false;
+ const nextIds = new Set(hiddenGhostIds);
+ if (
+ snapshot?.dataOwnerId === ownerStamp.dataOwnerId &&
+ snapshot.ownerGeneration === ownerStamp.ownerGeneration &&
+ sameIds(snapshot.hiddenGhostIds, nextIds)
+ ) {
+ return false;
+ }
+ snapshot = { ...ownerStamp, hiddenGhostIds: nextIds };
+ if (notify) emitChange();
+ else revision += 1;
+ return true;
+}
+
+function refreshFromMain(notify: boolean): void {
+ const latest = window.electronAPI.sidebarSettings.loadSnapshot();
+ reconcile(latest.hiddenMainViewGhostIds, latest, notify);
+}
+
+function ensureCurrentSnapshot(): void {
+ const owner = getDataOwnerGeneration();
+ if (
+ snapshot?.dataOwnerId === owner.dataOwnerId &&
+ snapshot.ownerGeneration === owner.generation
+ ) {
+ return;
+ }
+ refreshFromMain(false);
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ if (!unsubscribeFromMain) {
+ unsubscribeFromMain = window.electronAPI.sidebarSettings.onHiddenMainViewGhostIdsChanged(
+ (hiddenGhostIds, ownerStamp) => {
+ reconcile(hiddenGhostIds, ownerStamp, true);
+ },
+ );
+ }
+ // Subscribe before re-reading so a write racing the first render is observed
+ // either through the broadcast or through this authoritative snapshot.
+ refreshFromMain(true);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ unsubscribeFromMain?.();
+ unsubscribeFromMain = null;
+ }
+ };
+}
+
+function getSnapshot(): number {
+ ensureCurrentSnapshot();
+ return revision;
+}
+
+/** Unknown owners and absent overrides preserve the default-visible behavior. */
+export function readMainViewSidebarVisible(ownerId: string | null, ghostId: string): boolean {
+ ensureCurrentSnapshot();
+ const owner = getDataOwnerGeneration();
+ if (
+ !snapshot ||
+ snapshot.dataOwnerId !== ownerId ||
+ snapshot.dataOwnerId !== owner.dataOwnerId ||
+ snapshot.ownerGeneration !== owner.generation
+ ) {
+ return true;
+ }
+ return !snapshot.hiddenGhostIds.has(ghostId);
+}
+
+/** Persist through Main so concurrent windows and account generations cannot overwrite each other. */
+export async function writeMainViewSidebarVisible(
+ owner: DataOwnerGeneration,
+ ghostId: string,
+ visible: boolean,
+): Promise<boolean> {
+ if (!owner.dataOwnerId || !isDataOwnerGenerationCurrent(owner)) return false;
+ const ownerStamp: DataOwnerPushStamp = {
+ dataOwnerId: owner.dataOwnerId,
+ ownerGeneration: owner.generation,
+ };
+ const hiddenGhostIds = await window.electronAPI.sidebarSettings.setMainViewHidden(
+ ghostId,
+ !visible,
+ ownerStamp,
+ );
+ if (!isDataOwnerGenerationCurrent(owner)) return false;
+ reconcile(hiddenGhostIds, ownerStamp, true);
+ return true;
+}
+
+/** Re-render every main-view projection after the authoritative preference changes. */
+export function useMainViewVisibilityRevision(): number {
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
+
+export function currentMainViewVisibilityOwner(): DataOwnerGeneration {
+ return getDataOwnerGeneration();
+}
+
+export const __testing = {
+ reset(): void {
+ unsubscribeFromMain?.();
+ unsubscribeFromMain = null;
+ snapshot = null;
+ revision = 0;
+ listeners.clear();
+ },
+};
diff --git a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
new file mode 100644
index 0000000000..3ff6ce9091
--- /dev/null
+++ b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
@@ -0,0 +1,117 @@
+import {
+ CalendarDays,
+ ChartColumn,
+ Code,
+ Database,
+ Folder,
+ Globe,
+ Image,
+ MessageCircle,
+ Puzzle,
+ SlidersHorizontal,
+ type LucideIcon,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useMatch, useNavigate } from 'react-router-dom';
+
+import { useGhostMainViews } from '@/cindy-brain/ghostMainViews';
+import { cn } from '@/lib/utils';
+import type { GhostMainViewIcon } from '../../../shared/ghost';
+
+import { SIDEBAR_RAIL_ICON_BUTTON_CLASS } from './SidebarIconButton';
+import { Tip } from '../ui/tooltip';
+
+const ROW_CLASS =
+ 'flex h-8 w-full items-center gap-2.5 rounded-full px-3 text-sm font-normal text-[var(--sidebar-nav-text)] transition-colors hover:bg-sidebar-item-hover';
+const ROW_ACTIVE_CLASS =
+ 'bg-sidebar-item-active font-medium text-sidebar-item-active-foreground shadow-[inset_0_0_0_1px_var(--sidebar-item-active-border)] hover:bg-sidebar-item-active';
+const RAIL_ACTIVE_CLASS =
+ 'bg-[var(--chat-input-chip-bg)] text-[var(--msg-assistant-text)] hover:bg-[var(--chat-input-chip-bg)]';
+
+const MAIN_VIEW_ICONS: Record<GhostMainViewIcon, LucideIcon> = {
+ puzzle: Puzzle,
+ globe: Globe,
+ code: Code,
+ folder: Folder,
+ database: Database,
+ 'chart-column': ChartColumn,
+ image: Image,
+ 'message-circle': MessageCircle,
+ 'calendar-days': CalendarDays,
+};
+
+/** Expanded and rail variants consume the exact same sorted visibility projection. */
+export function GhostMainViewNavEntries({ variant }: { variant: 'row' | 'rail' }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const activeMatch = useMatch('/apps/:ghostId');
+ const activeGhostId = activeMatch?.params.ghostId;
+ const { sidebarVisible } = useGhostMainViews();
+
+ return sidebarVisible.map((item) => {
+ const active = activeGhostId === item.ghostId;
+ const Icon = MAIN_VIEW_ICONS[item.icon];
+ const icon = (
+ <Icon
+ aria-hidden="true"
+ size={variant === 'row' ? 15 : 18}
+ strokeWidth={1.8}
+ className="shrink-0"
+ />
+ );
+ const open = () => navigate(`/apps/${encodeURIComponent(item.ghostId)}`);
+ const openDetails = () =>
+ navigate(`/settings?tab=ghosts&ghost=${encodeURIComponent(item.ghostId)}`);
+
+ if (variant === 'rail') {
+ return (
+ <Tip key={item.ghostId} text={item.title} side="right">
+ <button
+ type="button"
+ aria-label={item.title}
+ aria-current={active ? 'page' : undefined}
+ onClick={open}
+ className={cn(SIDEBAR_RAIL_ICON_BUTTON_CLASS, active && RAIL_ACTIVE_CLASS)}
+ >
+ {icon}
+ </button>
+ </Tip>
+ );
+ }
+
+ return (
+ <div
+ key={item.ghostId}
+ className={cn(ROW_CLASS, 'group/main-view gap-0 px-0', active && ROW_ACTIVE_CLASS)}
+ >
+ <button
+ type="button"
+ aria-label={item.title}
+ title={item.title}
+ data-native-title="truncated-text"
+ aria-current={active ? 'page' : undefined}
+ onClick={open}
+ className="flex min-w-0 flex-1 items-center gap-2.5 self-stretch rounded-full pl-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {icon}
+ <span className="min-w-0 truncate leading-none">{item.title}</span>
+ </button>
+ <Tip text={t('settings.ghosts.page.manageAria', { name: item.manifest.name })} side="right">
+ <button
+ type="button"
+ onClick={openDetails}
+ aria-label={t('settings.ghosts.page.manageAria', { name: item.manifest.name })}
+ className={cn(
+ 'pointer-events-none mr-1.5 grid size-6 shrink-0 place-items-center rounded-full opacity-0 transition-[background-color,color,opacity] duration-150 focus-visible:pointer-events-auto focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] group-hover/main-view:pointer-events-auto group-hover/main-view:opacity-100 group-focus-within/main-view:pointer-events-auto group-focus-within/main-view:opacity-100',
+ active
+ ? 'text-sidebar-item-active-foreground hover:bg-[var(--sidebar-item-active-border)] hover:text-sidebar-item-active-foreground'
+ : 'text-[var(--sidebar-nav-text)] hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
+ )}
+ >
+ <SlidersHorizontal size={14} aria-hidden="true" />
+ </button>
+ </Tip>
+ </div>
+ );
+ });
+}
diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
index 026fc91acf..3244e8fb30 100644
--- a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
@@ -31,6 +31,7 @@ import { GhostPanelRestoreEntry } from '@/cindy-brain/GhostPanelRestoreEntry';
import { useActiveMainView } from '@/hooks/useActiveMainView';
import { SidebarInlineSearch } from '@/features/cc-agent/sidebar/SidebarInlineSearch';
import { useConversationSearchContext } from '@/features/cc-agent/sidebar/conversationSearchContext';
+import { GhostMainViewNavEntries } from './GhostMainViewNavEntries';
/** 列表行通用样式 —— 各行同款 pill 行。 */
const ROW_CLASS =
@@ -126,6 +127,7 @@ export function SidebarTopNav({
{hasGhostUnread && <AttentionDot size={6} className="ml-auto mr-0.5" />}
</button>
) : null;
+ const mainViewRows = showScrollable ? <GhostMainViewNavEntries variant="row" /> : null;
const restoreRow = showScrollable ? (
<GhostPanelRestoreEntry variant="row" className={ROW_CLASS} />
) : null;
@@ -146,6 +148,7 @@ export function SidebarTopNav({
<div className="flex flex-col gap-0.5 pr-3 pl-3">
{automationsRow}
{pluginsRow}
+ {mainViewRows}
{restoreRow}
</div>
<div
@@ -186,6 +189,7 @@ export function SidebarTopNav({
)}
{automationsRow}
{pluginsRow}
+ {mainViewRows}
{restoreRow}
{searchRow}
</div>
diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
new file mode 100644
index 0000000000..68e28ca03e
--- /dev/null
+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
@@ -0,0 +1,89 @@
+/** @vitest-environment jsdom */
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { describe, expect, it, vi } from 'vitest';
+
+const items = [
+ {
+ ghostId: 'alpha',
+ title: 'Alpha',
+ icon: 'puzzle',
+ manifest: { id: 'alpha', name: 'Alpha Plugin' },
+ installedGhost: {},
+ },
+ {
+ ghostId: 'workspace',
+ title: 'Workspace',
+ icon: 'globe',
+ manifest: { id: 'workspace', name: 'Workspace Plugin' },
+ installedGhost: {},
+ },
+];
+
+vi.mock('@/cindy-brain/ghostMainViews', () => ({
+ useGhostMainViews: () => ({ declared: items, routeCapable: items, sidebarVisible: items }),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { name?: string }) =>
+ key === 'settings.ghosts.page.manageAria' ? `Manage ${options?.name}` : key,
+ }),
+}));
+
+import { GhostMainViewNavEntries } from '../GhostMainViewNavEntries';
+
+function LocationProbe() {
+ const location = useLocation();
+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;
+}
+
+describe('GhostMainViewNavEntries', () => {
+ it('renders the shared order, active state and encoded navigation', () => {
+ render(
+ <MemoryRouter initialEntries={['/apps/alpha']}>
+ <Routes>
+ <Route
+ path="*"
+ element={
+ <>
+ <GhostMainViewNavEntries variant="row" />
+ <LocationProbe />
+ </>
+ }
+ />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const alphaButton = screen.getByRole('button', { name: 'Alpha' });
+ const workspaceButton = screen.getByRole('button', { name: 'Workspace' });
+ expect(alphaButton.getAttribute('aria-current')).toBe('page');
+ expect(alphaButton.getAttribute('title')).toBe('Alpha');
+ expect(alphaButton.getAttribute('data-native-title')).toBe('truncated-text');
+ expect(alphaButton.querySelector('.lucide-puzzle')).toBeTruthy();
+ expect(workspaceButton.querySelector('.lucide-globe')).toBeTruthy();
+ expect(alphaButton.querySelector('svg')?.getAttribute('width')).toBe('15');
+ expect(alphaButton.querySelector('img')).toBeNull();
+
+ fireEvent.click(workspaceButton);
+ expect(screen.getByTestId('location').textContent).toBe('/apps/workspace');
+
+ const manageAlphaButton = screen.getByRole('button', { name: 'Manage Alpha Plugin' });
+ expect(manageAlphaButton.querySelector('.lucide-sliders-horizontal')).toBeTruthy();
+ fireEvent.click(manageAlphaButton);
+ expect(screen.getByTestId('location').textContent).toBe('/settings?tab=ghosts&ghost=alpha');
+ });
+
+ it('uses the native 18px rail icon geometry without a fallback tile', () => {
+ render(
+ <MemoryRouter initialEntries={['/apps/alpha']}>
+ <GhostMainViewNavEntries variant="rail" />
+ </MemoryRouter>,
+ );
+
+ const railIcon = screen.getByRole('button', { name: 'Alpha' }).querySelector('svg');
+ expect(railIcon?.classList.contains('lucide-puzzle')).toBe(true);
+ expect(railIcon?.getAttribute('width')).toBe('18');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 1934d9d681..6b373559c5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -97,6 +97,7 @@ import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
import { useActiveMainView } from '@/hooks/useActiveMainView';
import { useAnyGhostUnread } from '@/cindy-brain/ghostUnreadStore';
import { GhostPanelRestoreEntry } from '@/cindy-brain/GhostPanelRestoreEntry';
+import { GhostMainViewNavEntries } from '@/components/sidebar/GhostMainViewNavEntries';
import { getNotificationsEnabled } from '@/hooks/useNotificationSettings';
import { getFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSettings';
import { getAgentIslandEnabled, isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
@@ -3947,6 +3948,7 @@ function CollapsedView({
onClick={handleNavScheduled}
onContextMenu={onAutomationsContextMenu}
/>
+ <GhostMainViewNavEntries variant="rail" />
{/* 插件 rail 入口 —— 未读绿点与展开态 SidebarTopNav 对称(同一聚合语义:
任一插件有未读就点亮,静态不呼吸)。 */}
<SidebarIconButton
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useHiddenProjectsFilterSync.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useHiddenProjectsFilterSync.test.tsx
index bf1d7d59d0..19e60466a2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useHiddenProjectsFilterSync.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useHiddenProjectsFilterSync.test.tsx
@@ -47,6 +47,7 @@ beforeEach(() => {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [],
hiddenProjectKeys: initialHiddenProjectKeys,
+ hiddenMainViewGhostIds: [],
}),
onHiddenProjectKeysChanged: (listener: HiddenProjectsListener) => {
if (hiddenProjectKeysBeforeListenerRegistration !== null) {
@@ -178,6 +179,7 @@ describe('hidden-project filter synchronization', () => {
pinnedOrderIsAuthoritative: true,
pinnedOrder: ['owner-b-session'],
hiddenProjectKeys: [PROJECT_A],
+ hiddenMainViewGhostIds: [],
});
const view = renderHook(() => useHiddenProjects());
@@ -188,6 +190,7 @@ describe('hidden-project filter synchronization', () => {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
});
});
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx
index 7e784c5a6d..2ea54c5fff 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx
@@ -21,6 +21,7 @@ const SNAPSHOT = {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [] as string[],
hiddenProjectKeys: [] as string[],
+ hiddenMainViewGhostIds: [] as string[],
};
type PinnedListener = (order: string[], ownerStamp: DataOwnerPushStamp) => void;
@@ -435,6 +436,7 @@ describe('pinned sidebar persistence', () => {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
});
const view = renderFilter();
@@ -494,6 +496,7 @@ describe('pinned sidebar persistence', () => {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
};
window.electronAPI.sidebarSettings.loadSnapshot = () => ownerBSnapshot;
mutatePinnedOrder.mockClear();
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useHiddenProjects.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useHiddenProjects.ts
index 107ad45c33..5adc6c320b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useHiddenProjects.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useHiddenProjects.ts
@@ -39,6 +39,7 @@ export function useHiddenProjects(): UseHiddenProjectsReturn {
pinnedOrderIsAuthoritative: false,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
};
});
const [hiddenProjectKeys, setHiddenProjectKeys] = useState<Set<string>>(() =>
diff --git a/apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx b/apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx
new file mode 100644
index 0000000000..d9f7414d36
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx
@@ -0,0 +1,12 @@
+import { useAuth } from '@/contexts/AuthContext';
+import { useRegisterCCAgentSidebar } from '@/features/cc-agent/useRegisterCCAgentSidebar';
+
+import { GhostMainViewHost } from './GhostMainViewHost';
+import { ghostWebviewOwnerKey } from './lib/ghostPluginViewModel';
+
+/** Seeds the shared app sidebar even on a cold deep link to /apps/:ghostId. */
+export function GhostMainViewFeatureLayout() {
+ useRegisterCCAgentSidebar();
+ const { mode, dataOwnerId } = useAuth();
+ return <GhostMainViewHost key={ghostWebviewOwnerKey(mode, dataOwnerId)} />;
+}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx b/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx
new file mode 100644
index 0000000000..288a8a37e6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx
@@ -0,0 +1,36 @@
+import { useEffect } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import { useGhostMainViews } from '@/cindy-brain/ghostMainViews';
+import { GhostPanelError, GhostWebviewBody } from '@/cindy-brain/ghostPanelBody';
+import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';
+
+/** Route boundary that resolves only an approved, enabled manifest main-view entry. */
+export function GhostMainViewHost() {
+ const { ghostId = '' } = useParams<{ ghostId: string }>();
+ const navigate = useNavigate();
+ const { routeCapable } = useGhostMainViews();
+ const item = routeCapable.find((candidate) => candidate.ghostId === ghostId);
+ const runtimeState = useGhostRuntimeState(ghostId);
+
+ useEffect(() => {
+ if (!item) navigate('/plugins', { replace: true });
+ }, [item, navigate]);
+
+ if (!item) return <div className="h-full w-full bg-content-area" />;
+
+ const { manifest } = item;
+ const broken = runtimeState === 'crashed' || runtimeState === 'fused';
+ return (
+ <section
+ className="flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden bg-content-area"
+ aria-label={item.title}
+ >
+ {broken ? (
+ <GhostPanelError manifest={manifest} state={runtimeState} />
+ ) : (
+ <GhostWebviewBody key={manifest.id} manifest={manifest} html={manifest.mainView?.html} />
+ )}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 77be862c14..e1803d48c8 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -84,6 +84,9 @@ interface GhostPluginDetailViewProps {
onToggle: (enabled: boolean) => void;
/** 主动作:面板型「使用」/ 指令或 Host 能力型「对话」;纯工具型不渲染主按钮。 */
onUse: () => void;
+ /** main-view 入口偏好只影响侧边栏,不改变插件启用态或路由资格。 */
+ mainViewSidebarVisible?: boolean;
+ onMainViewSidebarVisibleChange?: (visible: boolean) => void;
/** 头部更新 CTA:市场有新版本时走市场更新确认流。 */
onUpdate: () => void;
/**
@@ -110,6 +113,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {
tool: Wrench,
command: Terminal,
panel: PanelRight,
+ 'main-view': AppWindow,
code: FileCode2,
subscribe: Radio,
card: LayoutTemplate,
@@ -158,6 +162,8 @@ export function GhostPluginDetailView({
onBack,
onToggle,
onUse,
+ mainViewSidebarVisible = true,
+ onMainViewSidebarVisibleChange,
onUpdate,
onReapprove,
onUpdateFromFile,
@@ -174,7 +180,7 @@ export function GhostPluginDetailView({
const [descriptionOverflows, setDescriptionOverflows] = useState(false);
const descriptionRef = useRef<HTMLParagraphElement>(null);
// 未批准的安装不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它
- // 看起来只是"被关掉了"),再喂 main 改版的 primaryAction/primaryEnabled。
+ // 看起来只是"被关掉了"),再喂既有 primaryAction/primaryEnabled。
const needsReapproval = detail.approvalState !== 'approved';
const enabled = (enabledOverride ?? detail.enabled) && !needsReapproval;
const primaryAction = ghostPrimaryAction(detail);
@@ -184,7 +190,8 @@ export function GhostPluginDetailView({
primaryAction === 'capability' ||
(primaryAction === 'command' && detail.canUse));
const cindyCapabilities = detail.cindyCapabilities;
- const hasConfiguration = detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;
+ const hasConfiguration =
+ detail.hasMainView || detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;
const summary = ghostPluginSummary(detail.description, detail.id);
/**
* 「从 .cindy 文件更新」是否可用。官方保留前缀(cindy- / filo- / xd-)在**非 dev
@@ -456,13 +463,7 @@ export function GhostPluginDetailView({
</div>
{needsReapproval ? (
- <div
- className={cn(
- 'mt-5 rounded-xl px-4 py-3.5',
- DETAIL_SURFACE_CLASS,
- )}
- role="status"
- >
+ <div className={cn('mt-5 rounded-xl px-4 py-3.5', DETAIL_SURFACE_CLASS)} role="status">
<p className="text-13 font-medium text-[var(--text-primary)]">
{t('settings.ghosts.reapproval.noticeTitle')}
</p>
@@ -486,6 +487,35 @@ export function GhostPluginDetailView({
title={t('settings.ghosts.detail.configurationTitle')}
/>
<div className={cn(DETAIL_SECTION_CONTENT_CLASS, 'space-y-3')}>
+ {detail.hasMainView ? (
+ <div
+ className={cn(
+ DETAIL_SURFACE_CLASS,
+ 'flex min-h-20 items-center gap-3 rounded-xl px-5 py-4',
+ )}
+ >
+ <AppWindow
+ size={18}
+ className="shrink-0 text-[var(--text-tertiary)]"
+ aria-hidden="true"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="text-14 font-medium leading-[1.571] text-[var(--text-primary)]">
+ {t('settings.ghosts.detail.sidebarEntryTitle')}
+ </p>
+ <p className="mt-0.5 text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.detail.sidebarEntryDescription', {
+ title: detail.mainViewTitle ?? detail.name,
+ })}
+ </p>
+ </div>
+ <Switch
+ checked={mainViewSidebarVisible}
+ onCheckedChange={onMainViewSidebarVisibleChange}
+ aria-label={t('settings.ghosts.detail.showInSidebar')}
+ />
+ </div>
+ ) : null}
{detail.hasSettingsUi ? (
ghost ? (
<>
@@ -763,7 +793,9 @@ export function PermissionSummary({ items }: { items: readonly GhostPermissionIt
function PermissionDetailRow({ item }: { item: GhostPermissionItem }) {
const { t } = useTranslation();
const Icon = permissionItemIcon(item);
- const hostDescription = item.detailKey ? t(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs) : null;
+ const hostDescription = item.detailKey
+ ? t(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs)
+ : null;
return (
<div className="flex items-start gap-3 py-4 first:pt-0 last:pb-0">
<Icon
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index c3e66f35cb..c66a08710e 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -98,7 +98,7 @@ import {
toGhostPluginDetail,
toGhostPluginListItem,
filterGhostPluginItems,
- ghostPanelOwnerKey,
+ ghostWebviewOwnerKey,
ghostPrimaryAction,
marketPresentationForInstalledGhost,
installedVisibleCount,
@@ -126,6 +126,12 @@ import {
} from './PluginManagementLayout';
import { GhostPagePanelHost } from './GhostPagePanelHost';
import { GhostPluginDetailView } from './GhostPluginDetailView';
+import {
+ currentMainViewVisibilityOwner,
+ readMainViewSidebarVisible,
+ useMainViewVisibilityRevision,
+ writeMainViewSidebarVisible,
+} from '@/cindy-brain/mainViewVisibilityStore';
import { UpdateAllDialog } from './UpdateAllDialog';
import { GhostPluginIcon } from './GhostPluginIcon';
import { MarketPluginDetailView } from './MarketPluginDetailView';
@@ -419,6 +425,7 @@ export function GhostPluginPage({
const { user, mode, dataOwnerId } = useAuth();
const showEnterprise = user?.membershipKind === 'org';
const ghosts = useInstalledGhosts();
+ useMainViewVisibilityRevision();
const installedGhostIds = useMemo(() => ghosts.map((ghost) => ghost.manifest.id), [ghosts]);
const installedGhostIdsKey = useMemo(
() => [...installedGhostIds].sort().join('\0'),
@@ -435,7 +442,7 @@ export function GhostPluginPage({
const [marketSnapshot, setMarketSnapshot] = useState<PluginMarketSnapshot | null>(null);
const [openPanelId, setOpenPanelId] = useState<string | null>(null);
// 数据归属键:面板宿主按它失效(定义要早于消费点)。
- const panelOwnerKey = ghostPanelOwnerKey(mode, dataOwnerId);
+ const panelOwnerKey = ghostWebviewOwnerKey(mode, dataOwnerId);
const ignoredRoundKey = ignoredRoundStorageKey(mode, dataOwnerId);
const [ignoredRound, setIgnoredRound] = useState(() => readIgnoredRound(ignoredRoundKey));
// 账号 / 本地云模式切换:换桶重读,不把上一个身份的「忽略本轮」带进来。
@@ -840,6 +847,9 @@ export function GhostPluginPage({
const selectedMarketUpdate = selectedDetail
? pluginUpdateForInstalledVersion(selectedMarketInstall)
: null;
+ const selectedMainViewSidebarVisible = selectedDetail?.hasMainView
+ ? readMainViewSidebarVisible(dataOwnerId, selectedDetail.id)
+ : true;
// ── 面板收束:页面独占的插件面板宿主;停用/卸载/换形态自动失效 ──
const openPanelGhost = useMemo(() => {
@@ -988,10 +998,7 @@ export function GhostPluginPage({
to: next.version,
}),
content: (
- <GhostUpdateReview
- diff={diff}
- manualCount={next.manifest.manual?.items.length ?? 0}
- />
+ <GhostUpdateReview diff={diff} manualCount={next.manifest.manual?.items.length ?? 0} />
),
maxWidth: 520,
confirmText: t('settings.ghosts.updateConfirm.confirm'),
@@ -1208,7 +1215,7 @@ export function GhostPluginPage({
[confirm, ghosts, navigate, openGhostConfiguration, t],
);
- /** 卡片胶囊/详情主动作分发:面板型开页面内面板,指令/Host 能力型起对话,工具型进管理。整卡点击不走这里。 */
+ /** 卡片胶囊/详情主动作分发:面板型开页面内面板,指令/Host 能力起对话。 */
const handlePrimaryAction = useCallback(
(item: Pick<GhostPluginListItem, 'id' | 'name' | 'tabPanel' | 'canUse' | 'hostCapability'>) => {
const action = ghostPrimaryAction(item);
@@ -1225,6 +1232,22 @@ export function GhostPluginPage({
[handleUseGhost],
);
+ const handleMainViewSidebarVisibleChange = useCallback(
+ (visible: boolean) => {
+ const selected = selectedDetail;
+ if (!selected?.hasMainView) return;
+ const owner = currentMainViewVisibilityOwner();
+ void writeMainViewSidebarVisible(owner, selected.id, visible)
+ .then((persisted) => {
+ if (!persisted) toast.error(t('settings.ghosts.errors.generic'));
+ })
+ .catch(() => {
+ toast.error(t('settings.ghosts.errors.generic'));
+ });
+ },
+ [selectedDetail, t],
+ );
+
const handleUse = useCallback(() => {
if (selectedGhost && selectedDetail) {
handlePrimaryAction(selectedDetail);
@@ -1377,9 +1400,7 @@ export function GhostPluginPage({
...(isUpdate && installedGhost
? { expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval) }
: {}),
- ...(isUpdate &&
- (diff!.added.length > 0 ||
- installedGhost?.approval.state !== 'approved')
+ ...(isUpdate && (diff!.added.length > 0 || installedGhost?.approval.state !== 'approved')
? {
allowPermissionExpansion: true,
...(installedGhost
@@ -1548,6 +1569,8 @@ export function GhostPluginPage({
void handleToggle(selectedDetail.id, enabled, selectedDetail.name)
}
onUse={handleUse}
+ mainViewSidebarVisible={selectedMainViewSidebarVisible}
+ onMainViewSidebarVisibleChange={handleMainViewSidebarVisibleChange}
onUpdate={() => void handleUpdate()}
onUpdateFromFile={() => void handleUpdateFromFile()}
// 受体模型的 §5 恢复入口:缺批准的安装在详情页重新确认(市场包重装 /
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
new file mode 100644
index 0000000000..8c371f0464
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
@@ -0,0 +1,134 @@
+/** @vitest-environment jsdom */
+
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ ghostId: 'workspace',
+ routeCapable: [] as Array<Record<string, unknown>>,
+ runtimeState: 'running',
+ registerSidebar: vi.fn(),
+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
+ dataOwnerId: 'owner-a' as string | null,
+}));
+
+vi.mock('react-router-dom', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('react-router-dom')>()),
+ useNavigate: () => mocks.navigate,
+ useParams: () => ({ ghostId: mocks.ghostId }),
+}));
+vi.mock('@/cindy-brain/ghostMainViews', () => ({
+ useGhostMainViews: () => ({ declared: [], routeCapable: mocks.routeCapable, sidebarVisible: [] }),
+}));
+vi.mock('@/cindy-brain/runtimeStates', () => ({
+ useGhostRuntimeState: () => mocks.runtimeState,
+}));
+vi.mock('@/cindy-brain/ghostPanelBody', () => ({
+ GhostWebviewBody: ({ html }: { html?: string }) => <div data-testid="webview">{html}</div>,
+ GhostPanelError: ({ state }: { state: string }) => <div data-testid="error">{state}</div>,
+}));
+vi.mock('@/features/cc-agent/useRegisterCCAgentSidebar', () => ({
+ useRegisterCCAgentSidebar: () => mocks.registerSidebar(),
+}));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ mode: mocks.mode, dataOwnerId: mocks.dataOwnerId }),
+}));
+
+import { GhostMainViewFeatureLayout } from '../GhostMainViewFeatureLayout';
+import { GhostMainViewHost } from '../GhostMainViewHost';
+
+const manifest = {
+ schemaVersion: 2,
+ id: 'workspace',
+ name: 'Workspace',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['main-view'],
+ minCindyVersion: '1.2.3',
+ mainView: { html: 'main-view.html' },
+};
+
+beforeEach(() => {
+ mocks.navigate.mockReset();
+ mocks.registerSidebar.mockReset();
+ mocks.ghostId = 'workspace';
+ mocks.runtimeState = 'running';
+ mocks.mode = 'cloud';
+ mocks.dataOwnerId = 'owner-a';
+ mocks.routeCapable = [
+ {
+ ghostId: 'workspace',
+ title: 'Workspace',
+ manifest,
+ installedGhost: {
+ manifest,
+ dir: '/plugins/workspace',
+ enabled: true,
+ approval: { state: 'approved', revision: 'revision' },
+ },
+ },
+ ];
+});
+
+describe('GhostMainViewHost', () => {
+ it('loads only the entry resolved from the route-capable manifest', () => {
+ render(<GhostMainViewHost />);
+ expect(screen.getByTestId('webview').textContent).toBe('main-view.html');
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('replaces an unavailable route with the Plugin page before mounting a webview', () => {
+ mocks.routeCapable = [];
+ render(<GhostMainViewHost />);
+ expect(screen.queryByTestId('webview')).toBeNull();
+ expect(mocks.navigate).toHaveBeenCalledWith('/plugins', { replace: true });
+ });
+
+ it('unmounts the webview and replaces the route when capability is revoked in place', () => {
+ const { rerender } = render(<GhostMainViewHost />);
+ expect(screen.getByTestId('webview')).toBeTruthy();
+
+ mocks.routeCapable = [];
+ rerender(<GhostMainViewHost />);
+
+ expect(screen.queryByTestId('webview')).toBeNull();
+ expect(mocks.navigate).toHaveBeenCalledWith('/plugins', { replace: true });
+ });
+
+ it.each(['crashed', 'fused'])('reuses the existing %s recovery state', (state) => {
+ mocks.runtimeState = state;
+ render(<GhostMainViewHost />);
+ expect(screen.getByTestId('error').textContent).toBe(state);
+ expect(screen.queryByTestId('webview')).toBeNull();
+ });
+
+ it('remounts the approved view after runtime recovery', () => {
+ mocks.runtimeState = 'crashed';
+ const { rerender } = render(<GhostMainViewHost />);
+ expect(screen.getByTestId('error')).toBeTruthy();
+
+ mocks.runtimeState = 'running';
+ rerender(<GhostMainViewHost />);
+
+ expect(screen.queryByTestId('error')).toBeNull();
+ expect(screen.getByTestId('webview').textContent).toBe('main-view.html');
+ });
+
+ it('registers the shared CC Agent sidebar on cold main-view entry', () => {
+ render(<GhostMainViewFeatureLayout />);
+ expect(mocks.registerSidebar).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId('webview')).toBeTruthy();
+ });
+
+ it('recreates the main-view host when the data owner changes', () => {
+ const { rerender } = render(<GhostMainViewFeatureLayout />);
+ const ownerAWebview = screen.getByTestId('webview');
+
+ mocks.dataOwnerId = 'owner-b';
+ rerender(<GhostMainViewFeatureLayout />);
+
+ expect(screen.getByTestId('webview')).not.toBe(ownerAWebview);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index 4cfb0bed21..2ebfbecbec 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -226,6 +226,8 @@ const commandPlugin: GhostPluginListItem = {
approvalState: 'approved',
builtin: false,
tabPanel: false,
+ hasMainView: false,
+ mainViewTitle: null,
hostCapability: null,
oauthAuthorizationExpired: false,
};
@@ -251,6 +253,14 @@ const simulatorPlugin: GhostPluginListItem = {
hostCapability: 'ios-simulator',
};
+const mainViewPlugin: GhostPluginListItem = {
+ ...panelPlugin,
+ id: 'workspace',
+ name: 'Workspace',
+ hasMainView: true,
+ mainViewTitle: 'Workspace',
+};
+
const marketPlugin: PluginMarketItem = {
pluginId: 'release-google-calendar',
ghostId: 'google-calendar',
@@ -354,6 +364,32 @@ describe('GhostPluginCard', () => {
expect(screen.queryByText('settings.ghosts.page.agentInvoked')).toBeNull();
});
+ it('keeps the tab-panel action when the plugin also declares main-view', () => {
+ const onPrimary = vi.fn();
+ render(<GhostPluginCard item={mainViewPlugin} onPrimary={onPrimary} onManage={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.page.useAria' }));
+ expect(onPrimary).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.page.openAria' })).toBeNull();
+ });
+
+ it('does not add a primary action for a main-view-only tool plugin', () => {
+ render(
+ <GhostPluginCard
+ item={{
+ ...toolPlugin,
+ hasMainView: true,
+ mainViewTitle: 'Workspace',
+ }}
+ onPrimary={vi.fn()}
+ onManage={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText('settings.ghosts.page.agentInvoked')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.page.openAria' })).toBeNull();
+ });
+
it('routes the manage icon to detail without firing the primary action', () => {
const onPrimary = vi.fn();
const onManage = vi.fn();
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 3df4df5e92..8d6e9e0827 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -29,8 +29,7 @@ vi.mock('react-i18next', () => ({
'settings.ghosts.detail.closeDialog': 'Close dialog',
'settings.ghosts.perm.networkHost': `Access ${String(options?.host ?? '')}`,
'settings.ghosts.perm.networkHostDetail': 'Can access this declared domain.',
- 'settings.ghosts.perm.cindyTextOneshotModelDetail':
- `Takes effect when the model (${String(options?.model ?? '')}) is available in the catalog.`,
+ 'settings.ghosts.perm.cindyTextOneshotModelDetail': `Takes effect when the model (${String(options?.model ?? '')}) is available in the catalog.`,
'settings.ghosts.perm.command': `Command ${String(options?.command ?? '')}`,
'settings.ghosts.perm.tool': `Tool ${String(options?.name ?? '')}`,
'settings.ghosts.perm.cindyImageGenerate': 'Generate images',
@@ -118,6 +117,8 @@ const detail: GhostPluginDetail = {
approvalState: 'approved',
builtin: false,
tabPanel: false,
+ hasMainView: false,
+ mainViewTitle: null,
hostCapability: null,
author: 'XD',
contents: ['code'],
@@ -146,6 +147,96 @@ afterEach(() => {
});
describe('Ghost plugin detail sections', () => {
+ it('shows the main-view preference alongside the plugin settings UI', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onVisibilityChange = vi.fn();
+ render(
+ <GhostPluginDetailView
+ ghost={{
+ manifest: {
+ schemaVersion: 2,
+ id: detail.id,
+ name: detail.name,
+ version: detail.version,
+ kind: 'chip',
+ entry: 'main.js',
+ minCindyVersion: '1.2.3',
+ slots: ['main-view'],
+ settingsHtml: 'settings.html',
+ mainView: { html: 'main-view.html', title: 'Workspace' },
+ },
+ dir: detail.installDir ?? '/tmp/plugin',
+ enabled: true,
+ approval: { state: 'approved', revision: 'rev-1' },
+ }}
+ detail={{
+ ...detail,
+ hasMainView: true,
+ mainViewTitle: 'Workspace',
+ hasSettingsUi: true,
+ }}
+ panelStatus={null}
+ mainViewSidebarVisible
+ onMainViewSidebarVisibleChange={onVisibilityChange}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ const toggle = screen.getByRole('switch', {
+ name: 'settings.ghosts.detail.showInSidebar',
+ });
+ expect(toggle.getAttribute('data-state')).toBe('checked');
+ fireEvent.click(toggle);
+ expect(onVisibilityChange).toHaveBeenCalledWith(false);
+ expect(screen.getByText('settings.ghosts.detail.sidebarEntryTitle')).toBeTruthy();
+ expect(screen.getByTestId('ghost-settings-webview')).toBeTruthy();
+ });
+
+ it('keeps the existing command action when the plugin also declares main-view', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onUse = vi.fn();
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={{ ...detail, hasMainView: true, mainViewTitle: 'Workspace' }}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={onUse}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ const chat = screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' });
+ expect((chat as HTMLButtonElement).disabled).toBe(false);
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.detail.openAction' })).toBeNull();
+ fireEvent.click(chat);
+ expect(onUse).toHaveBeenCalledTimes(1);
+ });
+
it('shows a non-blocking stale OAuth scope badge inside the configuration section', () => {
vi.stubGlobal(
'ResizeObserver',
@@ -341,58 +432,64 @@ describe('Ghost plugin detail sections', () => {
it.each([
['legacy-unapproved', 'settings.ghosts.reapproval.bodyLegacy'],
['invalid', 'settings.ghosts.reapproval.bodyInvalid'],
- ] as const)('explains the %s approval state and routes to a fresh review', (approvalState, bodyKey) => {
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- );
- const onReapprove = vi.fn();
- const onUpdate = vi.fn();
- const onToggle = vi.fn();
- render(
- <GhostPluginDetailView
- ghost={null}
- detail={{ ...detail, approvalState }}
- panelStatus="Docked"
- onBack={vi.fn()}
- onToggle={onToggle}
- onUse={vi.fn()}
- onUpdate={onUpdate}
- onReapprove={onReapprove}
- onUpdateFromFile={vi.fn()}
- updateVersion="1.2.4"
- onUninstall={vi.fn()}
- toggleDisabled={false}
- />,
- );
-
- expect(screen.getByText('settings.ghosts.reapproval.noticeTitle')).toBeTruthy();
- expect(screen.getByText(bodyKey)).toBeTruthy();
- // 缺批准时"使用"与"更新"都不该顶在最前面,主动作是重新确认。
- expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
- // detail fixture 是指令型插件(canUse:true / tabPanel:false → 'command'),主动作按钮
- // 标 chatAction;缺批准时 primaryEnabled=false → 禁用。
- expect(
- (screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' }) as HTMLButtonElement)
- .disabled,
- ).toBe(true);
-
- // 启用开关(改版为带 aria-pressed 的按钮,非原生 switch)缺批准时禁用,点了不触发 onToggle。
- const toggle = screen.getByRole('button', {
- name: 'settings.ghosts.enableAria',
- }) as HTMLButtonElement;
- expect(toggle.disabled).toBe(true);
- fireEvent.click(toggle);
- expect(onToggle).not.toHaveBeenCalled();
-
- fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.reapproval.action' }));
- expect(onReapprove).toHaveBeenCalledTimes(1);
- expect(onUpdate).not.toHaveBeenCalled();
- });
+ ] as const)(
+ 'explains the %s approval state and routes to a fresh review',
+ (approvalState, bodyKey) => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onReapprove = vi.fn();
+ const onUpdate = vi.fn();
+ const onToggle = vi.fn();
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={{ ...detail, approvalState }}
+ panelStatus="Docked"
+ onBack={vi.fn()}
+ onToggle={onToggle}
+ onUse={vi.fn()}
+ onUpdate={onUpdate}
+ onReapprove={onReapprove}
+ onUpdateFromFile={vi.fn()}
+ updateVersion="1.2.4"
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ expect(screen.getByText('settings.ghosts.reapproval.noticeTitle')).toBeTruthy();
+ expect(screen.getByText(bodyKey)).toBeTruthy();
+ // 缺批准时"使用"与"更新"都不该顶在最前面,主动作是重新确认。
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
+ // detail fixture 是指令型插件(canUse:true / tabPanel:false → 'command'),主动作按钮
+ // 标 chatAction;缺批准时 primaryEnabled=false → 禁用。
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'settings.ghosts.detail.chatAction',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+
+ // 启用开关(改版为带 aria-pressed 的按钮,非原生 switch)缺批准时禁用,点了不触发 onToggle。
+ const toggle = screen.getByRole('button', {
+ name: 'settings.ghosts.enableAria',
+ }) as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ fireEvent.click(toggle);
+ expect(onToggle).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.reapproval.action' }));
+ expect(onReapprove).toHaveBeenCalledTimes(1);
+ expect(onUpdate).not.toHaveBeenCalled();
+ },
+ );
it('disables every market update entry while an update is busy', async () => {
vi.stubGlobal(
@@ -725,7 +822,11 @@ describe('Ghost plugin detail sections', () => {
});
render(
- <CindyCapabilityPrefs ghostId="xdt-knowledge" capabilities={['text.oneshot']} appearance="plugin" />,
+ <CindyCapabilityPrefs
+ ghostId="xdt-knowledge"
+ capabilities={['text.oneshot']}
+ appearance="plugin"
+ />,
);
fireEvent.click(
screen.getByRole('button', { name: 'settings.ghosts.detail.cindyPrefs.cap.text.oneshot' }),
@@ -741,7 +842,9 @@ describe('Ghost plugin detail sections', () => {
);
// 折扣徽标只出现在预算行;订阅徽标只出现在订阅行。
const budgetRow = within(listbox).getByText('GPT 5.5 折扣').closest('button')!;
- expect(within(budgetRow).getByText('settings.ghosts.detail.cindyPrefs.budgetBadge')).toBeTruthy();
+ expect(
+ within(budgetRow).getByText('settings.ghosts.detail.cindyPrefs.budgetBadge'),
+ ).toBeTruthy();
const plainRow = within(listbox).getByText('GPT 5.5', { exact: true }).closest('button')!;
expect(
within(plainRow).queryByText('settings.ghosts.detail.cindyPrefs.budgetBadge'),
@@ -802,7 +905,11 @@ describe('Ghost plugin detail sections', () => {
});
render(
- <CindyCapabilityPrefs ghostId="xdt-knowledge" capabilities={['text.oneshot']} appearance="plugin" />,
+ <CindyCapabilityPrefs
+ ghostId="xdt-knowledge"
+ capabilities={['text.oneshot']}
+ appearance="plugin"
+ />,
);
const trigger = screen.getByRole('button', {
name: 'settings.ghosts.detail.cindyPrefs.cap.text.oneshot',
@@ -858,7 +965,11 @@ describe('Ghost plugin detail sections', () => {
});
render(
- <CindyCapabilityPrefs ghostId="xdt-knowledge" capabilities={['text.oneshot']} appearance="plugin" />,
+ <CindyCapabilityPrefs
+ ghostId="xdt-knowledge"
+ capabilities={['text.oneshot']}
+ appearance="plugin"
+ />,
);
fireEvent.click(
screen.getByRole('button', { name: 'settings.ghosts.detail.cindyPrefs.cap.text.oneshot' }),
@@ -1018,7 +1129,9 @@ describe('Ghost plugin detail sections', () => {
expect(within(dialog).getByText('Generate images')).toBeTruthy();
// detailArgs 的 model 插值必须替换占位符,不能显示裸 {{model}}(Greptile 2026-08-07)。
expect(
- within(dialog).getByText('Takes effect when the model (codex/gpt-5.5) is available in the catalog.'),
+ within(dialog).getByText(
+ 'Takes effect when the model (codex/gpt-5.5) is available in the catalog.',
+ ),
).toBeTruthy();
expect(within(dialog).queryByText(/Takes effect when the model \(\{\{model\}\}\)/)).toBeNull();
});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginManagementLayout.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginManagementLayout.test.tsx
index f7fdfdb4cd..9725578577 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/PluginManagementLayout.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginManagementLayout.test.tsx
@@ -5,7 +5,7 @@
*/
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { MemoryRouter, useLocation } from 'react-router-dom';
+import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('react-i18next', () => ({
@@ -44,6 +44,18 @@ function ActiveMainView() {
return <output data-testid="active-main-view">{useActiveMainView().activeKey}</output>;
}
+function ActiveMainViewNavigationProbe() {
+ const navigate = useNavigate();
+ return (
+ <>
+ <ActiveMainView />
+ <button type="button" onClick={() => navigate('/apps/workspace')}>
+ Open main view
+ </button>
+ </>
+ );
+}
+
describe('PluginManagementLayout', () => {
it('presents Plugins and Skills as peer tabs and navigates to the skill home', async () => {
render(
@@ -89,6 +101,20 @@ describe('PluginManagementLayout', () => {
expect(screen.getByTestId('active-main-view').textContent).toBe('plugins');
});
+ it('clears the sticky Plugin active state when entering a plugin main view', async () => {
+ render(
+ <MemoryRouter initialEntries={['/plugins']}>
+ <ActiveMainViewNavigationProbe />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId('active-main-view').textContent).toBe('plugins');
+ fireEvent.click(screen.getByRole('button', { name: 'Open main view' }));
+ await waitFor(() => {
+ expect(screen.getByTestId('active-main-view').textContent).toBe('');
+ });
+ });
+
it('uses the same constrained frame for the tab row and page content', () => {
render(
<MemoryRouter>
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index 13ee3340e4..62f883d6a1 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -44,6 +44,10 @@ export interface GhostPluginListItem {
builtin: boolean;
/** 声明了插件页内独占面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */
tabPanel: boolean;
+ /** 声明了应用级主视图;只用于侧边栏与详情配置,不参与插件主动作。 */
+ hasMainView: boolean;
+ /** 本地化后的主视图标题;未声明时为 null。 */
+ mainViewTitle: string | null;
/** 声明了由 Host 承载、但可从插件 UI 主动进入的能力。 */
hostCapability: 'ios-simulator' | null;
oauthAuthorizationExpired?: boolean;
@@ -52,7 +56,7 @@ export interface GhostPluginListItem {
}
/**
- * 卡片主动作的四分法(只驱动右下角胶囊;整卡点击一律进详情):
+ * 卡片主动作(只驱动右下角胶囊;整卡点击一律进详情):
* - `panel`:有页签面板 → 「使用」直接打开面板;
* - `command`:只有 $指令 → 「对话」把指令插进输入框起话题;
* - `capability`:Host 承载的能力 → 「对话」进入该能力的工作流;
@@ -275,6 +279,8 @@ export function toGhostPluginListItem(
approvalState: ghost.approval.state,
builtin: ghost.builtin === true,
tabPanel: manifest.panel?.position === 'tab',
+ hasMainView: manifest.slots.includes('main-view') && manifest.mainView !== undefined,
+ mainViewTitle: manifest.mainView ? (manifest.mainView.title ?? manifest.name) : null,
hostCapability: manifest.slots.includes('ios-simulator') ? 'ios-simulator' : null,
oauthAuthorizationExpired: ghost.oauthAuthorizationExpired !== undefined,
trust: ghost.trust ?? {
@@ -315,14 +321,14 @@ export function toGhostPluginDetail(
}
/**
- * 插件页内面板宿主的数据归属键。
+ * 插件可见 WebView 宿主的数据归属键(panel / main-view 共用)。
*
* 面板承载的是 webview,里面可能存着账号 A 的登录态、表单、已加载数据。
* 两个账号装了**同 id、同版本、同入口**的插件时,只按 ghostId 做宿主 key
* 会让 React 复用同一实例——切到账号 B 后 A 的 DOM 与内存态原样留着。
- * 所以 key 必须含 owner 代际:换身份即卸载重建。
+ * 所以 key 必须含 owner 身份:换身份即卸载重建。
*/
-export function ghostPanelOwnerKey(
+export function ghostWebviewOwnerKey(
mode: 'signed-out' | 'local' | 'cloud',
dataOwnerId: string | null,
): string {
diff --git a/apps/desktop/src/renderer/hooks/useActiveMainView.ts b/apps/desktop/src/renderer/hooks/useActiveMainView.ts
index 1167658e17..1aca43a54f 100644
--- a/apps/desktop/src/renderer/hooks/useActiveMainView.ts
+++ b/apps/desktop/src/renderer/hooks/useActiveMainView.ts
@@ -4,8 +4,9 @@
* 推导主区域当前激活的 View(Chat / Issues / Plugins),并返回 navigateToView 切换函数。
*
* 激活态由 URL 派生:pathname === prefix || pathname.startsWith(prefix + '/')。
- * 当 pathname 不匹配任何 view prefix 时(如 /settings),保留最近一次匹配过的 key —
- * 否则 tabbar 会在打开 Settings 等"非 view 页面"时整体失去选中态。
+ * 当 pathname 不匹配任何 view prefix 时(如 /settings),通常保留最近一次匹配过的 key —
+ * 否则 tabbar 会在打开 Settings 等"非 view 页面"时整体失去选中态。插件 `/apps/*`
+ * 主视图是例外:它有自己的一级侧边栏入口,因此不沿用 Plugins 的 sticky active。
*
* navigateToView 内部做同源去重,避免重复 navigate 触发 FadeSwitcher
* 不必要的子树重挂载。
@@ -57,7 +58,9 @@ export function useActiveMainView() {
}
}, [matchedKey, location.pathname, location.search]);
- const activeKey: MainViewKey = matchedKey ?? lastMatchedRef.current;
+ const isGhostMainView = location.pathname === '/apps' || location.pathname.startsWith('/apps/');
+ const activeKey: MainViewKey | null =
+ matchedKey ?? (isGhostMainView ? null : lastMatchedRef.current);
const navigateToView = useCallback(
(key: MainViewKey) => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 065847c093..e461bd7066 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1792,15 +1792,23 @@
"invalidLibraryName": "Enter an Ollama library name, or paste a huggingface.co model page URL",
"advancedExactName": "Advanced: exact library name",
"models": {
- "qwen38-27b": { "blurb": "The strongest dense model you can run locally. Best for coding and long tasks." },
+ "qwen38-27b": {
+ "blurb": "The strongest dense model you can run locally. Best for coding and long tasks."
+ },
"gpt-oss-20b": { "blurb": "OpenAI’s open 20B. The usual pick for 16 GB machines." },
"gemma4-e2b": { "blurb": "Smallest Gemma 4. Light machines, with vision." },
"gemma4-e4b": { "blurb": "Google Gemma 4 small. Light daily use, with vision." },
"gemma4-12b": { "blurb": "Gemma 4 mid-size. Steadier chat and multimodal." },
"gemma4-31b": { "blurb": "Gemma 4 large. Stronger chat and multimodal, more memory." },
- "gemma4-26b": { "blurb": "Gemma 4 mid-large MoE. Fewer active parameters, mid-to-high-end machines." },
- "ornith15-35b": { "blurb": "Ornith 1.5 mid-size MoE. The local coding and agent backup." },
- "glm-47-flash": { "blurb": "Zhipu’s current coding model. 30B MoE, good for code and agents." }
+ "gemma4-26b": {
+ "blurb": "Gemma 4 mid-large MoE. Fewer active parameters, mid-to-high-end machines."
+ },
+ "ornith15-35b": {
+ "blurb": "Ornith 1.5 mid-size MoE. The local coding and agent backup."
+ },
+ "glm-47-flash": {
+ "blurb": "Zhipu’s current coding model. 30B MoE, good for code and agents."
+ }
},
"onboardingTitle": "Install the Ollama runtime",
"onboardingBody": "After you install Ollama, you can download and use local models in Cindy without opening the Ollama app. Ollama is a free, open-source third-party runtime.",
@@ -4376,6 +4384,8 @@
"command": "Chat command ${{command}}",
"panelLeft": "Panel \"{{title}}\" · docked left of the chat",
"panelTab": "Panel \"{{title}}\" · opens inside the Plugins page",
+ "mainView": "Can add a “{{title}}” entry to Cindy's sidebar",
+ "mainViewDetail": "Opening it displays the main view in the plugin sandbox and does not grant file, network, or credential access.",
"code": "Executable code",
"codeDetail": "Runs in an isolated sandbox with no access to your files or network.",
"resident": "Always-on (starts when enabled, keeps a background process even when idle)",
@@ -4530,6 +4540,9 @@
"settingsUnavailableUntilRestore": "Restore the plugin to use this configuration again.",
"oauthScopeStale": "This authorization does not include newly added permissions. Reconnect to grant them.",
"configurationTitle": "Configuration",
+ "sidebarEntryTitle": "Sidebar entry",
+ "showInSidebar": "Show in sidebar",
+ "sidebarEntryDescription": "When turned on, “{{title}}” appears in the sidebar. Hiding it does not disable the plugin.",
"openTool": "View details for Tool {{name}}",
"noToolDescription": "No description is available for this Tool.",
"viewAllTools": "See All",
@@ -4539,6 +4552,7 @@
"closeDialog": "Close Dialog"
},
"contents": {
+ "mainView": "Main view",
"panel": "Panel",
"settingsUi": "Custom settings UI",
"code": "Executable code",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f7958a843d..2029b607ca 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1791,15 +1791,23 @@
"invalidLibraryName": "Ollama のライブラリ名を入力するか、huggingface.co のモデルページ URL を貼り付けてください",
"advancedExactName": "上級:正確なライブラリ名",
"models": {
- "qwen38-27b": { "blurb": "ローカルで動かせる最強クラスの密モデル。コーディングと長時間タスク向け。" },
+ "qwen38-27b": {
+ "blurb": "ローカルで動かせる最強クラスの密モデル。コーディングと長時間タスク向け。"
+ },
"gpt-oss-20b": { "blurb": "OpenAI のオープン 20B。16GB 級マシンの定番。" },
"gemma4-e2b": { "blurb": "Gemma 4 の最小。軽いマシンでも動く。ビジョン付き。" },
"gemma4-e4b": { "blurb": "Google Gemma 4 の小型。日常使いでビジョン付き。" },
"gemma4-12b": { "blurb": "Gemma 4 の中型。日常会話とマルチモーダル向け。" },
- "gemma4-31b": { "blurb": "Gemma 4 の大型。会話とマルチモーダルがより強く、メモリもより食う。" },
+ "gemma4-31b": {
+ "blurb": "Gemma 4 の大型。会話とマルチモーダルがより強く、メモリもより食う。"
+ },
"gemma4-26b": { "blurb": "Gemma 4 の中大型 MoE。有効パラメータは少なめ。" },
- "ornith15-35b": { "blurb": "Ornith 1.5 の中型 MoE。ローカルのコーディングと Agent の控え。" },
- "glm-47-flash": { "blurb": "智譜の新しいコーディングモデル。30B MoE で、コードと Agent 向き。" }
+ "ornith15-35b": {
+ "blurb": "Ornith 1.5 の中型 MoE。ローカルのコーディングと Agent の控え。"
+ },
+ "glm-47-flash": {
+ "blurb": "智譜の新しいコーディングモデル。30B MoE で、コードと Agent 向き。"
+ }
},
"onboardingTitle": "先に Ollama ランタイムをインストール",
"onboardingBody": "Ollama をインストールすれば、Ollama アプリを開かなくても Cindy 内でローカルモデルをダウンロードして使えます。Ollama は無料のオープンソース製サードパーティランタイムです。",
@@ -4375,6 +4383,8 @@
"command": "チャット指令 ${{command}}",
"panelLeft": "パネル「{{title}}」· チャットの左側にドッキング",
"panelTab": "パネル「{{title}}」· プラグインページ内で開く",
+ "mainView": "Cindy のサイドバーに「{{title}}」への入口を追加できます",
+ "mainViewDetail": "クリックするとプラグインのサンドボックス内でメインビューが開き、ファイル、ネットワーク、認証情報へのアクセスが追加で付与されることはありません。",
"code": "実行コード",
"codeDetail": "独立したサンドボックスで実行され、ファイルやネットワークにはアクセスできません。",
"resident": "常駐実行(有効化すると起動し、呼び出されなくてもバックグラウンドプロセスを維持)",
@@ -4529,6 +4539,9 @@
"settingsUnavailableUntilRestore": "この設定を再び使用するには、プラグインを復元してください。",
"oauthScopeStale": "現在の認証には新しく追加された権限が含まれていません。再接続して権限を取得してください。",
"configurationTitle": "設定",
+ "sidebarEntryTitle": "サイドバー項目",
+ "showInSidebar": "サイドバーに表示",
+ "sidebarEntryDescription": "オンにすると、サイドバーに「{{title}}」が表示されます。非表示にしてもプラグインは無効になりません。",
"openTool": "Tool {{name}} の詳細を表示",
"noToolDescription": "この Tool には説明がありません。",
"viewAllTools": "さらに表示",
@@ -4538,6 +4551,7 @@
"closeDialog": "ダイアログを閉じる"
},
"contents": {
+ "mainView": "メインビュー",
"panel": "パネル",
"settingsUi": "カスタム設定画面",
"code": "実行コード",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6041d52d6c..41269d536f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1791,13 +1791,21 @@
"invalidLibraryName": "Ollama 라이브러리 이름을 입력하거나 huggingface.co 모델 페이지 URL을 붙여넣으세요",
"advancedExactName": "고급: 정확한 라이브러리 이름",
"models": {
- "qwen38-27b": { "blurb": "로컬에서 돌릴 수 있는 가장 강한 밀집 모델. 코딩과 긴 작업에 적합합니다." },
+ "qwen38-27b": {
+ "blurb": "로컬에서 돌릴 수 있는 가장 강한 밀집 모델. 코딩과 긴 작업에 적합합니다."
+ },
"gpt-oss-20b": { "blurb": "OpenAI 오픈 20B. 16GB급 기기에서 가장 무난한 선택." },
- "gemma4-e2b": { "blurb": "Gemma 4 최소형. 가벼운 기기에서도 돌아가며 비전을 지원합니다." },
+ "gemma4-e2b": {
+ "blurb": "Gemma 4 최소형. 가벼운 기기에서도 돌아가며 비전을 지원합니다."
+ },
"gemma4-e4b": { "blurb": "Google Gemma 4 소형. 가벼운 일상용이며 비전을 지원합니다." },
"gemma4-12b": { "blurb": "Gemma 4 중형. 일상 대화와 멀티모달에 더 안정적입니다." },
- "gemma4-31b": { "blurb": "Gemma 4 대형. 대화와 멀티모달이 더 강하고, 메모리도 더 듭니다." },
- "gemma4-26b": { "blurb": "Gemma 4 중대형 MoE. 활성 파라미터가 적어 중고사양에 맞습니다." },
+ "gemma4-31b": {
+ "blurb": "Gemma 4 대형. 대화와 멀티모달이 더 강하고, 메모리도 더 듭니다."
+ },
+ "gemma4-26b": {
+ "blurb": "Gemma 4 중대형 MoE. 활성 파라미터가 적어 중고사양에 맞습니다."
+ },
"ornith15-35b": { "blurb": "Ornith 1.5 중형 MoE. 로컬 코딩과 에이전트 대안." },
"glm-47-flash": { "blurb": "Zhipu의 최신 코딩 모델. 30B MoE로 코드와 에이전트에 맞음." }
},
@@ -4375,6 +4383,8 @@
"command": "채팅 명령 ${{command}}",
"panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹",
"panelTab": "패널 \"{{title}}\" · 플러그인 페이지에서 열기",
+ "mainView": "Cindy 사이드바에 “{{title}}” 항목을 추가할 수 있음",
+ "mainViewDetail": "클릭하면 플러그인 샌드박스에서 메인 보기가 열리며 파일, 네트워크 또는 자격 증명 접근 권한이 추가로 부여되지 않습니다.",
"code": "실행 코드",
"codeDetail": "격리된 샌드박스에서 실행되며 파일과 네트워크에 접근할 수 없습니다.",
"resident": "상주 실행(활성화하면 시작되며 호출이 없어도 백그라운드 프로세스 유지)",
@@ -4529,6 +4539,9 @@
"settingsUnavailableUntilRestore": "이 설정을 다시 사용하려면 플러그인을 복원하세요.",
"oauthScopeStale": "현재 인증에 새로 추가된 권한이 포함되어 있지 않습니다. 다시 연결해 권한을 받으세요.",
"configurationTitle": "설정",
+ "sidebarEntryTitle": "사이드바 항목",
+ "showInSidebar": "사이드바에 표시",
+ "sidebarEntryDescription": "켜면 사이드바에 “{{title}}” 항목이 표시됩니다. 숨겨도 플러그인이 비활성화되지는 않습니다.",
"openTool": "Tool {{name}} 세부 정보 보기",
"noToolDescription": "이 Tool에는 설명이 없습니다.",
"viewAllTools": "더 보기",
@@ -4538,6 +4551,7 @@
"closeDialog": "대화 상자 닫기"
},
"contents": {
+ "mainView": "메인 보기",
"panel": "패널",
"settingsUi": "사용자 정의 설정 화면",
"code": "실행 코드",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index d8ce79624c..f592b92d98 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4375,6 +4375,8 @@
"command": "对话指令 ${{command}}",
"panelLeft": "面板「{{title}}」· 停靠主对话区左侧",
"panelTab": "面板「{{title}}」· 插件页内打开",
+ "mainView": "可在 Cindy 侧边栏添加“{{title}}”入口",
+ "mainViewDetail": "点击后将在插件沙箱中打开主视图,不会因此获得文件、网络或凭证访问权限。",
"code": "可执行代码",
"codeDetail": "在独立沙箱中运行,无法访问你的文件与网络。",
"resident": "常驻运行(生效后即启动,不调用也保持后台进程)",
@@ -4529,6 +4531,9 @@
"settingsUnavailableUntilRestore": "恢复插件后可继续使用这项配置。",
"oauthScopeStale": "当前授权未包含插件新增权限,请重新连接补齐授权。",
"configurationTitle": "配置",
+ "sidebarEntryTitle": "侧边栏入口",
+ "showInSidebar": "显示在侧边栏",
+ "sidebarEntryDescription": "开启后,侧边栏会显示“{{title}}”。隐藏入口不会停用插件。",
"openTool": "查看 Tool {{name}} 的详情",
"noToolDescription": "该 Tool 暂无描述。",
"viewAllTools": "查看更多",
@@ -4538,6 +4543,7 @@
"closeDialog": "关闭弹窗"
},
"contents": {
+ "mainView": "主视图",
"panel": "面板",
"settingsUi": "自定义设置界面",
"code": "可执行代码",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 2f64b44fdb..e128e5e36f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4375,6 +4375,8 @@
"command": "對話指令 ${{command}}",
"panelLeft": "面板「{{title}}」· 停靠主對話區左側",
"panelTab": "面板「{{title}}」· 插件頁內開啟",
+ "mainView": "可在 Cindy 側邊欄新增「{{title}}」入口",
+ "mainViewDetail": "點擊後將在插件沙箱中開啟主視圖,不會因此取得檔案、網路或憑證存取權限。",
"code": "可執行程式碼",
"codeDetail": "在獨立沙箱中執行,無法訪問你的檔案與網路。",
"resident": "常駐執行(生效後即啟動,不呼叫也保持後臺處理程序)",
@@ -4529,6 +4531,9 @@
"settingsUnavailableUntilRestore": "恢復插件後可繼續使用這項配置。",
"oauthScopeStale": "當前授權未包含插件新增權限,請重新連線補齊授權。",
"configurationTitle": "配置",
+ "sidebarEntryTitle": "側邊欄入口",
+ "showInSidebar": "顯示在側邊欄",
+ "sidebarEntryDescription": "開啟後,側邊欄會顯示「{{title}}」。隱藏入口不會停用插件。",
"openTool": "檢視 Tool {{name}} 的詳情",
"noToolDescription": "該 Tool 暫無描述。",
"viewAllTools": "檢視更多",
@@ -4538,6 +4543,7 @@
"closeDialog": "關閉彈窗"
},
"contents": {
+ "mainView": "主視圖",
"panel": "面板",
"settingsUi": "自定義設定介面",
"code": "可執行程式碼",
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index 1416c23c3f..9c755e19dd 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -24,6 +24,7 @@ import { SkillhubMarketListView } from '@/features/skillhub/SkillhubMarketListVi
import { MakerExperimentalView } from '@/features/maker-experimental/MakerExperimentalView';
import { SchedulerPage } from '@/features/scheduler';
import { GhostPluginPage } from '@/features/plugin/GhostPluginPage';
+import { GhostMainViewFeatureLayout } from '@/features/plugin/GhostMainViewFeatureLayout';
/**
* 三层路由架构:
@@ -153,6 +154,7 @@ export const router = createHashRouter([
},
{ path: 'settings', element: <SettingsView /> },
{ path: 'plugins', element: <GhostPluginPage /> },
+ { path: 'apps/:ghostId', element: <GhostMainViewFeatureLayout /> },
{
path: 'billing',
element: <Navigate to="/settings?tab=billing" replace />,
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index d4192dba0e..235e65ba1f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4178,6 +4178,17 @@ interface ElectronAPI {
ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp,
) => void,
) => () => void;
+ setMainViewHidden: (
+ ghostId: string,
+ hidden: boolean,
+ ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp,
+ ) => Promise<string[]>;
+ onHiddenMainViewGhostIdsChanged: (
+ cb: (
+ ghostIds: string[],
+ ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp,
+ ) => void,
+ ) => () => void;
getProjectOrder: () => Promise<import('../shared/projectOrderSettings').SyncedProjectOrderSnapshot>;
applyProjectOrder: (request: {
manualProjectOrder: readonly string[];
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 4d41ee7a5c..cc28c96230 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -5,6 +5,7 @@ import {
GHOST_CINDY_DEPOSIT_QUOTA_BYTES,
GHOST_CINDY_EMBED_MAX_TEXTS,
GHOST_MANIFEST_SUMMARY_MAX_CHARS,
+ GHOST_MAIN_VIEW_ICONS,
GHOST_SLOTS,
changedBuiltinOauthClientSecretKeys,
deriveGhostSessionContext,
@@ -343,10 +344,12 @@ describe('ghost · 清单校验', () => {
locales: { en: 'GHOST.JSON' },
}).ok,
).toBe(false);
- expect(validateGhostManifest({
- ...goodManifest(),
- locales: { en: 'locales/en.json', 'zh-TW': 'locales/zh-TW.json' },
- }).ok).toBe(false);
+ expect(
+ validateGhostManifest({
+ ...goodManifest(),
+ locales: { en: 'locales/en.json', 'zh-TW': 'locales/zh-TW.json' },
+ }).ok,
+ ).toBe(false);
});
it('无 manual 时保持 origin/main 的 locale 路径兼容语义', () => {
@@ -757,10 +760,12 @@ describe('ghost · 清单校验', () => {
id: 'localized-labels',
name: 'Base',
version: '1.0.0',
+ minCindyVersion: '1.2.3',
entry: 'main.js',
settingsHtml: 'settings.html',
- slots: ['panel', 'network', 'node'],
+ slots: ['panel', 'main-view', 'network', 'node'],
panel: { title: 'Base panel', html: 'panel.html' },
+ mainView: { title: 'Base workspace', html: 'main-view.html' },
network: {
hosts: ['api.example.com'],
secrets: [
@@ -802,6 +807,7 @@ describe('ghost · 清单校验', () => {
{
name: 'Localized',
panel: { title: 'Localized panel' },
+ mainView: { title: 'Localized workspace' },
network: {
secrets: {
api_key: { label: 'Localized API key', hint: 'Localized secret hint' },
@@ -827,6 +833,7 @@ describe('ghost · 清单校验', () => {
if (!resource.ok) return;
expect(resolveGhostManifestLocale(parsed.manifest, resource.resource)).toMatchObject({
panel: { title: 'Localized panel' },
+ mainView: { title: 'Localized workspace', html: 'main-view.html' },
network: {
secrets: [
{
@@ -872,6 +879,7 @@ describe('ghost · 清单校验', () => {
if (!panelOnly.ok) return;
expect(resolveGhostManifestLocale(parsed.manifest, panelOnly.resource)).toMatchObject({
panel: { title: 'Localized panel' },
+ mainView: { title: 'Base workspace', html: 'main-view.html' },
network: {
secrets: [{ key: 'api_key', label: 'Base API key', hint: 'Base secret hint' }],
connections: [{ key: 'instance', label: 'Base instance' }],
@@ -881,6 +889,12 @@ describe('ghost · 清单校验', () => {
requires: [{ anyOf: [{ kind: 'kv', key: 'default_repo', label: 'Base repository' }] }],
},
});
+ expect(
+ validateGhostManifestLocaleResource(
+ { mainView: { title: 'Unexpected' } },
+ { ...parsed.manifest, mainView: { html: 'main-view.html' } },
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('mainView.title') });
// 提供的标签条目 label 必填、hint 可省(缺 hint 回退原文);未知 key 仍拒。
const labelNoHint = validateGhostManifestLocaleResource(
{
@@ -1599,6 +1613,95 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {
expect(validateGhostManifest(noHtml).ok).toBe(false);
});
+ it('mainView 与 main-view 槽严格成对,并强制最低 Cindy 版本', () => {
+ expect(GHOST_MAIN_VIEW_ICONS).toEqual([
+ 'puzzle',
+ 'globe',
+ 'code',
+ 'folder',
+ 'database',
+ 'chart-column',
+ 'image',
+ 'message-circle',
+ 'calendar-days',
+ ]);
+ const valid = validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { title: '工作台', icon: 'globe', html: 'ui/main-view.html' },
+ });
+ expect(valid.ok).toBe(true);
+ if (valid.ok)
+ expect(valid.manifest.mainView).toEqual({
+ title: '工作台',
+ icon: 'globe',
+ html: 'ui/main-view.html',
+ });
+
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'main-view.html' },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('minCindyVersion') });
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ mainView: { html: 'main-view.html' },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('main-view') });
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('mainView') });
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: '../escape.html' },
+ }).ok,
+ ).toBe(false);
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'assets/AUX.html' },
+ }).ok,
+ ).toBe(false);
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'main-view.html', position: 'left' },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('不允许的字段') });
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'main-view.html', icon: 'plugin' },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('mainView.icon') });
+ expect(
+ validateGhostManifest({
+ ...goodChipManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'main-view.html', icon: 'globe-2' },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('puzzle / globe / code') });
+ });
+
it('显式指令 command:字符规则 + 必须有工具可干活', () => {
const chipWithTool = () => ({
...goodChipManifest(),
@@ -2392,6 +2495,23 @@ describe('ghost · 逐项权限清单', () => {
expect(d.builtinOauthClientChanged).toBe(false);
});
+ it('diff:新增 main-view 作为独立权限进入更新确认', () => {
+ const previous = fullChip();
+ const next: GhostManifest = {
+ ...previous,
+ version: '2.0.0',
+ minCindyVersion: '1.2.3',
+ slots: [...previous.slots, 'main-view'],
+ mainView: { title: '工作台', html: 'main-view.html' },
+ };
+
+ const diff = diffGhostPermissionItems(previous, next);
+ expect(diff.added).toEqual([
+ expect.objectContaining({ key: 'main-view', kind: 'main-view', labelKey: 'mainView' }),
+ ]);
+ expect(diff.removed).toEqual([]);
+ });
+
it('diff:同一凭证槽的内置直连 OAuth clientId 变化会标记授权失效风险', () => {
const oauthManifest = (clientId: string): GhostManifest => ({
schemaVersion: 2,
@@ -3543,7 +3663,7 @@ describe('ghost · settingsHtml 自绘设置区 + settingsHeight', () => {
expect(r.ok && 'settingsHeight' in r.manifest).toBe(false);
});
- it('ghostWebviewEntryPaths:只 panel / 只 settings / 双声明 / 都无 / 同文件去重', () => {
+ it('ghostWebviewEntryPaths:panel / mainView / settings 只放行声明入口并去重', () => {
const both = validateGhostManifest({ ...goodManifest(), settingsHtml: 'settings.html' });
expect(both.ok && ghostWebviewEntryPaths(both.manifest)).toEqual([
'/panel.html',
@@ -3574,6 +3694,28 @@ describe('ghost · settingsHtml 自绘设置区 + settingsHeight', () => {
const same = validateGhostManifest({ ...goodManifest(), settingsHtml: 'panel.html' });
expect(same.ok && ghostWebviewEntryPaths(same.manifest)).toEqual(['/panel.html']);
+
+ const mainView = validateGhostManifest({
+ ...goodManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'main-view.html' },
+ settingsHtml: 'settings.html',
+ });
+ expect(mainView.ok && ghostWebviewEntryPaths(mainView.manifest)).toEqual([
+ '/panel.html',
+ '/main-view.html',
+ '/settings.html',
+ ]);
+
+ const sharedEntry = validateGhostManifest({
+ ...goodManifest(),
+ minCindyVersion: '1.2.3',
+ slots: ['panel', 'main-view'],
+ mainView: { html: 'panel.html' },
+ settingsHtml: 'panel.html',
+ });
+ expect(sharedEntry.ok && ghostWebviewEntryPaths(sharedEntry.manifest)).toEqual(['/panel.html']);
});
it('内容清单:声明 settingsHtml 的意识含 settingsUi,排在 panel 后 code 前', () => {
@@ -3727,11 +3869,20 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / pre
expect(withPreview({ hosts: ['a.example.com'], extra: 1 }).ok).toBe(false);
});
- it('session-context / pick / workspace / ios-simulator 槽可装入并生成权限项', () => {
+ it('main-view / session-context / pick / workspace / ios-simulator 槽可装入并生成权限项', () => {
const r = validateGhostManifest({
...goodChipManifest(),
minCindyVersion: '1.2.3',
- slots: ['panel', 'session-context', 'pick', 'preview', 'workspace', 'ios-simulator'],
+ slots: [
+ 'panel',
+ 'main-view',
+ 'session-context',
+ 'pick',
+ 'preview',
+ 'workspace',
+ 'ios-simulator',
+ ],
+ mainView: { title: '工作台', html: 'main-view.html' },
preview: { hosts: ['example.com'] },
});
expect(r.ok).toBe(true);
@@ -3739,10 +3890,17 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / pre
expect(r.manifest.minCindyVersion).toBe('1.2.3');
expect(ghostContentKeys(r.manifest)).toContain('slotWorkspace');
expect(ghostContentKeys(r.manifest)).toContain('slotIOSSimulator');
+ expect(ghostContentKeys(r.manifest)).toContain('mainView');
const items = ghostPermissionItems(r.manifest);
expect(items).toEqual(
expect.arrayContaining([
expect.objectContaining({ key: 'pick', kind: 'pick', labelKey: 'pick' }),
+ expect.objectContaining({
+ key: 'main-view',
+ kind: 'main-view',
+ labelKey: 'mainView',
+ detailKey: 'mainViewDetail',
+ }),
expect.objectContaining({
key: 'session-context',
kind: 'session-context',
@@ -4135,9 +4293,9 @@ describe('ghostPermissionProjectionFingerprint', () => {
expect.objectContaining({ key: expect.stringMatching(/^panel:/) }),
]);
expect(diff.unchanged.some((item) => item.key.startsWith('panel:'))).toBe(false);
- expect(
- unreviewedGhostPermissionItems(reviewed.manifest, undefined, actual.manifest),
- ).toEqual([expect.objectContaining({ key: expect.stringMatching(/^panel:/) })]);
+ expect(unreviewedGhostPermissionItems(reviewed.manifest, undefined, actual.manifest)).toEqual([
+ expect.objectContaining({ key: expect.stringMatching(/^panel:/) }),
+ ]);
});
it('same-key/different-detail 必须判不同(preview hosts / 工具描述都在 detail 侧)', () => {
@@ -4155,8 +4313,12 @@ describe('ghostPermissionProjectionFingerprint', () => {
});
expect(a.ok && b.ok).toBe(true);
if (!a.ok || !b.ok) return;
- const keysA = ghostPermissionItems(a.manifest).map((i) => i.key).sort();
- const keysB = ghostPermissionItems(b.manifest).map((i) => i.key).sort();
+ const keysA = ghostPermissionItems(a.manifest)
+ .map((i) => i.key)
+ .sort();
+ const keysB = ghostPermissionItems(b.manifest)
+ .map((i) => i.key)
+ .sort();
expect(keysA).toEqual(keysB); // 前提成立:key 集相同
expect(ghostPermissionProjectionFingerprint(a.manifest)).not.toBe(
ghostPermissionProjectionFingerprint(b.manifest),
diff --git a/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts b/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts
index 24c9157417..4d26778a37 100644
--- a/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts
+++ b/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts
@@ -14,6 +14,7 @@ describe('sidebar settings snapshot validation', () => {
pinnedOrderIsAuthoritative,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
}),
).toBe(true);
},
@@ -26,6 +27,7 @@ describe('sidebar settings snapshot validation', () => {
pinnedOrderIsAuthoritative: true,
pinnedOrder: ['session-a'],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
}),
).toBe(true);
expect(
@@ -34,6 +36,7 @@ describe('sidebar settings snapshot validation', () => {
pinnedOrderIsAuthoritative: false,
pinnedOrder: ['session-a'],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
}),
).toBe(false);
});
@@ -44,6 +47,7 @@ describe('sidebar settings snapshot validation', () => {
...OWNER_STAMP,
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
}),
).toBe(false);
expect(
@@ -52,6 +56,37 @@ describe('sidebar settings snapshot validation', () => {
pinnedOrderIsAuthoritative: 'yes',
pinnedOrder: [],
hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: [],
+ }),
+ ).toBe(false);
+ });
+
+ it('requires bounded unique Ghost ids for hidden main views', () => {
+ expect(
+ isSidebarSettingsSnapshot({
+ ...OWNER_STAMP,
+ pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: ['xd-sites'],
+ }),
+ ).toBe(true);
+ expect(
+ isSidebarSettingsSnapshot({
+ ...OWNER_STAMP,
+ pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: ['xd-sites', 'xd-sites'],
+ }),
+ ).toBe(false);
+ expect(
+ isSidebarSettingsSnapshot({
+ ...OWNER_STAMP,
+ pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: ['XD Sites'],
}),
).toBe(false);
});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 0fdfd4da57..040453b923 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -100,6 +100,9 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
* plan/只读拒)、save 票据目录(主 agent 过户,复用 saveDeposit 预算)。
* 字节永远由主机落盘,沙箱本身仍无 fs——本槽是"申请主机代写"的资格,
* 不是文件系统访问权。
+ * 'main-view' = 应用级插件主视图:宿主从已批准 manifest 解析包内
+ * HTML 入口,并提供 Cindy 一级侧边栏与路由。它与会话内 panel
+ * 独立授权,本身不附赠网络、文件或凭证能力。
* 'library' = 持久作品库(2026-08-20):用户作品级存储(画布/素材/数据库),
* 与 'fs' 私有储物柜(配额封顶、卸载回收)语义不同:不受 ghost-fs 配额约束,
* 卸载插件**不删**(标 orphaned,删除必须走设置页独立确认)。字节与 SQL
@@ -141,6 +144,7 @@ export const GHOST_SLOTS = [
'tool',
'card',
'panel',
+ 'main-view',
'cindy',
'agent',
'node',
@@ -420,6 +424,30 @@ export interface GhostPanelDecl {
systemButtons?: { maximize?: boolean; detach?: boolean; minimize?: boolean };
}
+/** 应用级插件主视图可用的 Cindy 系统线性图标。枚举值与图标名保持一致。 */
+export const GHOST_MAIN_VIEW_ICONS = [
+ 'puzzle',
+ 'globe',
+ 'code',
+ 'folder',
+ 'database',
+ 'chart-column',
+ 'image',
+ 'message-circle',
+ 'calendar-days',
+] as const;
+export type GhostMainViewIcon = (typeof GHOST_MAIN_VIEW_ICONS)[number];
+
+/** 应用级插件主视图;与会话内 panel 分开声明和批准。 */
+export interface GhostMainViewDecl {
+ /** 侧边栏与页面标题;缺省回退插件 name。 */
+ title?: string;
+ /** 侧边栏使用的 Cindy 系统线性图标;缺省为 puzzle。 */
+ icon?: GhostMainViewIcon;
+ /** 主视图界面入口(安装目录内安全相对路径)。 */
+ html: string;
+}
+
/**
* 芯片型意识注册给 agent 的工具声明(卡槽②)。
* 声明式而非运行时动态注册(规则 9:确定性;且会话中途增删工具会破坏
@@ -1452,6 +1480,8 @@ export interface GhostManifest {
keywords?: string[];
/** 面板声明;没有面板的意识(如纯工具意识)可省略。 */
panel?: GhostPanelDecl;
+ /** 应用级主视图声明;须与 slots 中的 `main-view` 成对。 */
+ mainView?: GhostMainViewDecl;
}
/**
@@ -1472,6 +1502,7 @@ export interface GhostManifestLocaleResource {
}
>;
panel?: { title: string };
+ mainView?: { title: string };
network?: {
secrets?: Record<string, { label: string; hint?: string }>;
connections?: Record<string, { label: string; hint?: string }>;
@@ -1494,9 +1525,7 @@ export const GHOST_LOCALE_MAX_BYTES = 64 * 1024;
* 都不构成运行授权,更新 UI 必须把目标包的全部权限按新增项重新展示。
*/
export type GhostInstallApproval =
- | { state: 'approved'; revision: string }
- | { state: 'legacy-unapproved' }
- | { state: 'invalid' };
+ { state: 'approved'; revision: string } | { state: 'legacy-unapproved' } | { state: 'invalid' };
/** 把批准态投影成跨进程更新事务使用的稳定 token。 */
export function ghostInstallApprovalToken(approval: GhostInstallApproval | undefined): string {
@@ -1510,9 +1539,7 @@ export function isGhostInstallApprovalToken(value: unknown): value is string {
value === 'legacy-unapproved' ||
value === 'invalid' ||
(typeof value === 'string' &&
- /^approved:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
- value,
- ))
+ /^approved:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value))
);
}
@@ -1587,6 +1614,7 @@ export function ghostPanelKind(id: string): `ghost:${string}` {
*/
export function ghostContentKeys(manifest: GhostManifest): string[] {
const keys: string[] = [];
+ if (manifest.mainView) keys.push('mainView');
if (manifest.panel) keys.push('panel');
if (manifest.settingsHtml) keys.push('settingsUi');
keys.push('code');
@@ -1703,6 +1731,7 @@ export interface GhostPermissionItem {
| 'tool'
| 'command'
| 'panel'
+ | 'main-view'
| 'code'
| 'subscribe'
| 'card'
@@ -2112,6 +2141,15 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
labelArgs: { title: manifest.panel.title ?? manifest.name },
});
}
+ if (manifest.mainView) {
+ items.push({
+ key: 'main-view',
+ kind: 'main-view',
+ labelKey: 'mainView',
+ labelArgs: { title: manifest.mainView.title ?? manifest.name },
+ detailKey: 'mainViewDetail',
+ });
+ }
for (const slot of manifest.slots) {
if (slot === 'subscribe') {
// 订阅两档分列:旁听(元数据)常规位;拦截是全部槽里权限最重的一档,
@@ -2444,14 +2482,34 @@ export function isSafeGhostRelativePath(p: unknown): p is string {
return segments.every((seg) => GHOST_PATH_SEGMENT_RE.test(seg) && seg !== '.' && seg !== '..');
}
+const WINDOWS_RESERVED_GHOST_PATH_SEGMENT_RE =
+ /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
+
+/**
+ * New cross-platform manifest paths must also be creatable on Windows.
+ * Keep the legacy helper above unchanged so an upgrade does not invalidate
+ * already-installed plugins that were previously accepted on macOS.
+ */
+function isPortableGhostRelativePath(p: unknown): p is string {
+ return (
+ isSafeGhostRelativePath(p) &&
+ p.split('/').every((segment) => !WINDOWS_RESERVED_GHOST_PATH_SEGMENT_RE.test(segment))
+ );
+}
+
/**
* 意识 webview 允许附加的入口 pathname 白名单(attach 闸的可测真身):
- * 面板 panel.html 与设置区 settingsHtml,声明哪个放行哪个;两者指向同一
+ * 面板 panel.html、主视图 mainView.html 与设置区 settingsHtml,声明哪个放行哪个;
+ * 多个能力指向同一
* 文件时去重。空数组 = 该意识没有任何可附加的自绘界面,闸口一律拒。
*/
export function ghostWebviewEntryPaths(manifest: GhostManifest): string[] {
const paths: string[] = [];
if (manifest.panel?.html) paths.push(`/${manifest.panel.html}`);
+ if (manifest.mainView?.html) {
+ const p = `/${manifest.mainView.html}`;
+ if (!paths.includes(p)) paths.push(p);
+ }
if (manifest.settingsHtml) {
const p = `/${manifest.settingsHtml}`;
if (!paths.includes(p)) paths.push(p);
@@ -2676,6 +2734,7 @@ export function validateGhostManifestLocaleResource(
'whenToUse',
'tools',
'panel',
+ 'mainView',
'network',
'node',
'setup',
@@ -2860,6 +2919,37 @@ export function validateGhostManifestLocaleResource(
panel = { title: raw.panel.title };
}
+ let mainView: GhostManifestLocaleResource['mainView'];
+ if (raw.mainView !== undefined) {
+ if (manifest.mainView?.title === undefined) {
+ return {
+ ok: false,
+ reason: 'locale.mainView 不应存在:原 manifest 未声明 mainView.title',
+ };
+ }
+ if (!isPlainObject(raw.mainView)) {
+ return { ok: false, reason: 'locale.mainView 必须是含 title 的对象' };
+ }
+ const unknownMainViewField = Object.keys(raw.mainView).find((field) => field !== 'title');
+ if (unknownMainViewField) {
+ return {
+ ok: false,
+ reason: `locale.mainView 含未知字段 ${JSON.stringify(unknownMainViewField)}`,
+ };
+ }
+ if (
+ typeof raw.mainView.title !== 'string' ||
+ raw.mainView.title.trim().length === 0 ||
+ raw.mainView.title.length > 64
+ ) {
+ return {
+ ok: false,
+ reason: 'locale.mainView.title 必须是 1–64 字符的非空字符串',
+ };
+ }
+ mainView = { title: raw.mainView.title };
+ }
+
const validateLocalizedLabels = (
rawValue: unknown,
fieldPath: string,
@@ -3022,6 +3112,7 @@ export function validateGhostManifestLocaleResource(
...(typeof whenToUse === 'string' ? { whenToUse } : {}),
...(tools !== undefined ? { tools } : {}),
...(panel !== undefined ? { panel } : {}),
+ ...(mainView !== undefined ? { mainView } : {}),
...(network !== undefined ? { network } : {}),
...(node !== undefined ? { node } : {}),
...(setup !== undefined ? { setup } : {}),
@@ -3060,6 +3151,9 @@ export function resolveGhostManifestLocale(
...(manifest.panel !== undefined && resource.panel !== undefined
? { panel: { ...manifest.panel, title: resource.panel.title } }
: {}),
+ ...(manifest.mainView !== undefined && resource.mainView !== undefined
+ ? { mainView: { ...manifest.mainView, title: resource.mainView.title } }
+ : {}),
...(manifest.network !== undefined && resource.network !== undefined
? {
network: {
@@ -3160,6 +3254,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
raw.icon,
raw.settingsHtml,
isPlainObject(raw.panel) ? raw.panel.html : undefined,
+ isPlainObject(raw.mainView) ? raw.mainView.html : undefined,
isPlainObject(raw.node) ? raw.node.entry : undefined,
...(isPlainObject(raw.node) && Array.isArray(raw.node.entries) ? raw.node.entries : []),
]
@@ -3365,6 +3460,50 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
+ let mainView: GhostMainViewDecl | undefined;
+ if (raw.mainView !== undefined) {
+ if (!isPlainObject(raw.mainView)) {
+ return { ok: false, reason: 'mainView 必须是对象' };
+ }
+ const unknownMainViewField = Object.keys(raw.mainView).find(
+ (field) => field !== 'html' && field !== 'title' && field !== 'icon',
+ );
+ if (unknownMainViewField) {
+ return {
+ ok: false,
+ reason: `mainView 含不允许的字段 ${JSON.stringify(unknownMainViewField)}`,
+ };
+ }
+ if (
+ raw.mainView.title !== undefined &&
+ (typeof raw.mainView.title !== 'string' ||
+ raw.mainView.title.trim().length === 0 ||
+ raw.mainView.title.length > 64)
+ ) {
+ return { ok: false, reason: 'mainView.title 必须是 1–64 字符的非空字符串' };
+ }
+ if (
+ raw.mainView.icon !== undefined &&
+ !(GHOST_MAIN_VIEW_ICONS as readonly unknown[]).includes(raw.mainView.icon)
+ ) {
+ return {
+ ok: false,
+ reason: `mainView.icon 必须是以下系统图标之一:${GHOST_MAIN_VIEW_ICONS.join(' / ')}`,
+ };
+ }
+ if (!isPortableGhostRelativePath(raw.mainView.html)) {
+ return {
+ ok: false,
+ reason: 'mainView.html 必填,且必须是安装目录内的安全相对路径',
+ };
+ }
+ mainView = {
+ ...(raw.mainView.title !== undefined ? { title: raw.mainView.title } : {}),
+ ...(raw.mainView.icon !== undefined ? { icon: raw.mainView.icon as GhostMainViewIcon } : {}),
+ html: raw.mainView.html,
+ };
+ }
+
if (!isSafeGhostRelativePath(raw.entry)) {
return { ok: false, reason: '必须提供 entry(安装目录内的安全相对路径,电子脑逻辑入口)' };
}
@@ -3413,10 +3552,14 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
// Host-native capabilities cannot be safely ignored by an older Cindy.
// Require an explicit installation/enablement floor for deterministic UX.
- if (slots.includes('ios-simulator') && raw.minCindyVersion === undefined) {
+ if (
+ (slots.includes('ios-simulator') || slots.includes('main-view')) &&
+ raw.minCindyVersion === undefined
+ ) {
+ const slot = slots.includes('main-view') ? 'main-view' : 'ios-simulator';
return {
ok: false,
- reason: 'slots 声明了 "ios-simulator" 时必须同时声明 minCindyVersion',
+ reason: `slots 声明了 ${JSON.stringify(slot)} 时必须同时声明 minCindyVersion`,
};
}
// 声明了面板却没申请 panel 槽(或反之有槽无面板)都是清单自相矛盾。
@@ -3426,6 +3569,15 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
if (slots.includes('panel') && panel === undefined) {
return { ok: false, reason: 'slots 声明了 "panel" 但缺少 panel(面板由意识自绘,html 必填)' };
}
+ if (mainView !== undefined && !slots.includes('main-view')) {
+ return { ok: false, reason: '声明了 mainView 但 slots 未包含 "main-view"' };
+ }
+ if (slots.includes('main-view') && mainView === undefined) {
+ return {
+ ok: false,
+ reason: 'slots 声明了 "main-view" 但缺少 mainView(html 必填)',
+ };
+ }
// card 槽详单:有详单必有槽;有槽无详单 = 纯渲染卡片(默认行为,向后兼容)。
let card: GhostCardNeeds | undefined;
@@ -5354,6 +5506,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
...(raw.command !== undefined ? { command: raw.command as string } : {}),
...(keywords !== undefined ? { keywords } : {}),
...(panel !== undefined ? { panel } : {}),
+ ...(mainView !== undefined ? { mainView } : {}),
},
};
}
@@ -7518,11 +7671,26 @@ export type GhostPipeFsResult =
* 宿主管理;首词白名单外的语句(ATTACH/PRAGMA/VACUUM/事务语句)一律拒。
*/
export const GHOST_LIBRARY_OPS = [
- 'open', 'status',
- 'read', 'write',
- 'writeBegin', 'writeChunk', 'writeCommit', 'writeAbort',
- 'list', 'stat', 'mkdir', 'delete', 'rename',
- 'db.open', 'db.exec', 'db.batch', 'db.migrate', 'db.backup', 'db.check', 'db.userVersion',
+ 'open',
+ 'status',
+ 'read',
+ 'write',
+ 'writeBegin',
+ 'writeChunk',
+ 'writeCommit',
+ 'writeAbort',
+ 'list',
+ 'stat',
+ 'mkdir',
+ 'delete',
+ 'rename',
+ 'db.open',
+ 'db.exec',
+ 'db.batch',
+ 'db.migrate',
+ 'db.backup',
+ 'db.check',
+ 'db.userVersion',
] as const;
export type GhostLibraryOp = (typeof GHOST_LIBRARY_OPS)[number];
@@ -7570,19 +7738,50 @@ export interface GhostPipeLibraryRequest {
* 修掉 fs 槽无错误码的缺口),对沙箱永不 reject。
*/
export type GhostPipeLibraryResult =
- | { ok: true; op: 'open' | 'status'; state: 'ready' | 'readonly' | 'unavailable'; reason?: string; usedBytes: number; fileCount: number; diskFreeBytes?: number | null; softLimitBytes?: number; softLimitExceeded?: boolean; location?: 'default' | 'custom' }
- | { ok: true; op: 'read'; path: string; content: string; encoding: 'utf8' | 'base64'; bytes: number; sha256: string }
+ | {
+ ok: true;
+ op: 'open' | 'status';
+ state: 'ready' | 'readonly' | 'unavailable';
+ reason?: string;
+ usedBytes: number;
+ fileCount: number;
+ diskFreeBytes?: number | null;
+ softLimitBytes?: number;
+ softLimitExceeded?: boolean;
+ location?: 'default' | 'custom';
+ }
+ | {
+ ok: true;
+ op: 'read';
+ path: string;
+ content: string;
+ encoding: 'utf8' | 'base64';
+ bytes: number;
+ sha256: string;
+ }
| { ok: true; op: 'write' | 'writeCommit'; path: string; bytes: number; sha256: string }
| { ok: true; op: 'writeBegin'; streamId: string }
| { ok: true; op: 'writeChunk'; accepted: number }
| { ok: true; op: 'writeAbort'; aborted: boolean }
- | { ok: true; op: 'list'; entries: Array<{ path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }>; hasMore: boolean; nextCursor: string | null }
+ | {
+ ok: true;
+ op: 'list';
+ entries: Array<{ path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }>;
+ hasMore: boolean;
+ nextCursor: string | null;
+ }
| { ok: true; op: 'stat'; path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }
| { ok: true; op: 'mkdir'; path: string; existed: boolean }
| { ok: true; op: 'delete'; path: string; existed: boolean }
| { ok: true; op: 'rename'; from: string; to: string }
| { ok: true; op: 'db.open'; opened: boolean }
- | { ok: true; op: 'db.exec'; rows?: unknown[]; changes?: number; lastInsertRowid?: string | number }
+ | {
+ ok: true;
+ op: 'db.exec';
+ rows?: unknown[];
+ changes?: number;
+ lastInsertRowid?: string | number;
+ }
| { ok: true; op: 'db.batch'; applied: number }
| { ok: true; op: 'db.migrate'; fromVersion: number; toVersion: number }
| { ok: true; op: 'db.backup'; backedUp: boolean }
diff --git a/apps/desktop/src/shared/sidebarSettings.ts b/apps/desktop/src/shared/sidebarSettings.ts
index e24fe98a30..9b7406f682 100644
--- a/apps/desktop/src/shared/sidebarSettings.ts
+++ b/apps/desktop/src/shared/sidebarSettings.ts
@@ -2,12 +2,20 @@ import { isDataOwnerPushStamp, type DataOwnerPushStamp } from './dataOwnerPush.j
export const SIDEBAR_PINNED_ORDER_MAX_ENTRIES = 10_000;
export const SIDEBAR_PINNED_ORDER_ENTRY_MAX_LENGTH = 4_096;
+export const SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES = 1_000;
+
+/** Matches the Ghost manifest id grammar without importing the large runtime contract. */
+export function isSidebarGhostId(value: unknown): value is string {
+ return typeof value === 'string' && /^[a-z0-9][a-z0-9-]{0,31}$/.test(value);
+}
export interface SidebarSettingsSnapshot extends DataOwnerPushStamp {
/** True when Main has a durable pinnedOrder override, including an explicit empty array. */
readonly pinnedOrderIsAuthoritative: boolean;
readonly pinnedOrder: string[];
readonly hiddenProjectKeys: string[];
+ /** Plugin ids with an explicit user override that hides their main-view sidebar entry. */
+ readonly hiddenMainViewGhostIds: string[];
}
/** Main's durable arbitration result for the one unscoped Renderer namespace. */
@@ -41,6 +49,11 @@ export interface SidebarProjectHiddenWriteRequest extends DataOwnerPushStamp {
readonly hidden: boolean;
}
+export interface SidebarMainViewHiddenWriteRequest extends DataOwnerPushStamp {
+ readonly ghostId: string;
+ readonly hidden: boolean;
+}
+
export function normalizeSidebarPinnedOrder(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
@@ -68,6 +81,7 @@ export function isSidebarSettingsSnapshot(value: unknown): value is SidebarSetti
typeof candidate.pinnedOrderIsAuthoritative === 'boolean' &&
isStringArray(candidate.pinnedOrder) &&
isStringArray(candidate.hiddenProjectKeys) &&
+ isHiddenMainViewGhostIds(candidate.hiddenMainViewGhostIds) &&
(candidate.pinnedOrderIsAuthoritative || candidate.pinnedOrder.length === 0)
);
}
@@ -86,3 +100,12 @@ export function isSidebarLegacyRendererOwnerClaim(
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
}
+
+function isHiddenMainViewGhostIds(value: unknown): value is string[] {
+ return (
+ Array.isArray(value) &&
+ value.length <= SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES &&
+ value.every(isSidebarGhostId) &&
+ new Set(value).size === value.length
+ );
+}
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 6982dbc843..fb73a8cb12 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -27,7 +27,8 @@
| 内容 | 权威来源 |
| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |
-| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |
+| `ghost.json` 身份卡字段与校验 | `packages/plugin-protocol/src/manifest.ts` 是跨消费者协议正本;`apps/desktop/src/shared/ghost.ts` 是 Desktop 运行时 validator。除下文登记的 Desktop-only 能力外,两端必须同步维护 |
+| 管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`cindy.send` / `cindy.onHostMessage` 类型) |
| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |
| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |
| 安装批准事实(receipt / 技能快照 / revision) | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,批准态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |
@@ -319,6 +320,23 @@
- (d) 面板供片协议与注入的主题 token(`cindy-ghost://` 分支、`ghostPanelTheme.ts` 白名单);
- (e) 打包限制(`forge.ts` 的 `packGhostDir`)。
+其中 `ghost.json` 属于 Ghost manifest 协议。新增或修改字段、slot 或枚举时,至少同步:
+
+1. 协议正本 `packages/plugin-protocol/src/manifest.ts` 及其测试;
+2. Desktop 完整镜像 `apps/desktop/src/shared/ghost.ts` 及其测试;
+3. 作者文档 `FORGE_GUIDE` 的对应章节及 Forge 测试。
+
+当前 `GHOST_SLOTS` 槽位集合中唯一登记的 Desktop-only 例外,是尚未进入跨消费者发布契约
+的 `library` 槽;在其首个正式支持版本确定并完成分发端兼容设计前,不得仅为同步数组而把
+它加入 `packages/plugin-protocol`。这里的「唯一」只描述槽位集合,不表示两套 validator 的
+其它历史字段语义已经完全同构;`main-view` 不属于该槽位例外,两端必须保持一致。
+
+`main-view` 的现行协议在 `FORGE_GUIDE` §4.20:`mainView.icon` 只接受 Cindy 系统线性图标
+`puzzle`、`globe`、`code`、`folder`、`database`、`chart-column`、`image`、
+`message-circle`、`calendar-days`,缺省回退 `puzzle`。枚举值直接等于图标名,不设别名;
+该字段只控制主视图侧边栏入口,不替代或修改根级 `icon` 品牌图片协议。后续扩展该枚举时也
+必须遵守第 5 节的存量兼容红线,并核对第 7 节的旧客户端降级缺口。
+
反向同样成立:改校验必须同步手册;改手册宣称的新能力必须真有实现。`forge.test.ts` 的
关键章节存在性测试只是最低闸,不替代逐条人工核对。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 928d78be56..75cf04160c 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -43,6 +43,27 @@
- 不要重新引入预装/播种机制或私有种子 submodule;需要推荐插件时走 SkillHub 的
分发与安装确认流程。
+## 3. Ghost manifest 与 Cindy 专属界面能力
+
+- `ghost.json` 的跨消费者字段、slot 与枚举属于 Ghost manifest 协议,客户端正本位于
+ `packages/plugin-protocol/src/manifest.ts`;Desktop 在
+ `apps/desktop/src/shared/ghost.ts` 维护运行时 validator。除明确登记的 Desktop-only
+ 能力外,两份实现及相同的有效/无效 fixture 必须同步,作者契约同时写入
+ `FORGE_GUIDE`。
+- 当前 `GHOST_SLOTS` 槽位集合中唯一登记的 Desktop-only 例外,是尚未进入跨消费者发布
+ 契约的 `library` 槽;在其首个正式支持版本确定并完成分发端兼容设计前,不得把它加入
+ `packages/plugin-protocol`。这里的「唯一」只描述槽位集合,不表示两套 validator 的其它
+ 历史字段语义已经完全同构;`main-view` 是跨消费者字段,不属于该槽位例外。
+- `main-view` / `mainView` 是通用的 Cindy Host 界面能力,不是 `xd-sites` 专用 API,协议中
+ 不出现 `xd-sites` 的端点、OIDC 流程或业务模型。具体插件可在它已获批准的其它 slot 内调用
+ 自己的服务,基座只负责声明校验、授权、导航和沙箱承载。
+- `mainView.icon` 是主视图入口的 Host 系统图标枚举,只作用于该入口;根级 `icon` 仍是插件
+ 品牌图片协议。字段白名单、默认回退与完整枚举见 `FORGE_GUIDE` §4.20,不能用图片路径或
+ 未声明别名绕过枚举。
+- 如果 Plugin Market/服务端仓会解析或严格校验新增的 manifest slot/枚举,发布使用新能力
+ 的插件前必须同步其本地 `plugin-protocol` 实现;这不要求 Cindy 客户端运行时依赖服务端,
+ 也不改变两仓独立发布边界。
+
## Review 清单
1. 改动是否触及跨端 wire protocol?是兼容独立升级,还是需要协调窗口的不兼容变更?
@@ -51,6 +72,8 @@
4. 客户端是否在 `packages/device-link` 之外另造了协议或绕过 relay 层定义?
5. 插件能力是否通过 `.cindy` 包和 SkillHub/手动安装分发,而不是重新引入预装、播种或
绕过插件权限边界?
+6. 修改 Ghost manifest 时,协议正本、Desktop 镜像、`FORGE_GUIDE` 与相关测试是否同步?
+ 若服务端严格校验该字段/枚举,发布顺序是否已协调?
协议改动按 [`desktop-development.md`](desktop-development.md) 跑相关测试,并与服务端确认
兼容。
diff --git a/docs/superpowers/specs/2026-08-22-device-link-windows-confirmation-retry-test-design.md b/docs/superpowers/specs/2026-08-22-device-link-windows-confirmation-retry-test-design.md
new file mode 100644
index 0000000000..adaee84e59
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-22-device-link-windows-confirmation-retry-test-design.md
@@ -0,0 +1,54 @@
+# Device Link 确认重试测试的 Windows 稳定性设计
+
+## 背景
+
+`packages/device-link/src/__tests__/client.test.ts` 的「确认 ACK 丢失后自动有界重发」用例在
+Windows CI 上重复超时。该用例使用 20ms 真实定时器驱动确认重试,同时用
+`MemoryRelay.settleUntil` 的 3 秒墙钟等待 host 进入 ready。Linux 及本地通过,而 Windows
+runner 在高负载下可能推迟真实定时器,使测试等待耗尽。失败没有证据指向生产状态机错误。
+
+## 方案选择
+
+采用 Vitest fake timers,仅确定化这条测试的重试时序。测试主动推进到下一次 20ms 重试,
+relay 仍负责投递协议帧。保持以下协议不变量:
+
+1. controller 发出的首个、带当前 `linkRequestId` 的确认 ACK 被丢弃;
+2. controller 无需等待后续业务流量,便按既有间隔重发确认 ACK;
+3. host 收到后续确认后进入 ready,`openLink` 正常完成;
+4. 发送业务流量前,定时确认的送达次数不超过首包丢失后的剩余重试预算,且全部属于同一个
+ request 代际;
+5. ready 后的可靠业务调用仍可往返完成;业务 ACK 可以正常刷新同代际确认,但不计入上述
+ 定时重试预算。
+
+不采用两个替代方案:单纯增加 `settleUntil` 超时只会放宽墙钟并掩盖调度抖动;修改生产重试
+状态机则会扩大风险面,目前没有确定性复现证明它存在缺陷。
+
+## 测试结构与清理
+
+用例在创建 client 前启用 fake timers,并在 `finally` 中停止两个 client、注销 frame
+listener、恢复真实定时器。`MemoryRelay.settle()` 增加一个仅供测试选择的 yield 参数,默认仍
+使用原来的零延迟 `setTimeout`;该用例传入 `Promise.resolve()` 作为微任务 yield,使 relay
+排空不依赖 fake clock。连接启动时只用 `vi.advanceTimersByTimeAsync(0)` 触发 websocket 的
+零延迟 open;需要触发确认重试时才单独推进 20ms,随后使用微任务模式排空 relay。这样不调用
+依赖墙钟轮询的 `settleUntil`,也不使用会把周期性 ping 等长生命周期任务一起跑完的
+`runAllTimersAsync()`。
+
+如果推进一个重试间隔后 host 仍未 ready,测试直接失败并保留协议帧断言;不再依赖 3 秒墙钟
+超时提供失败信号。
+
+## 兼容性与故障半径
+
+- 触发条件:测试环境的单个确认重试定时器被 Windows 调度推迟,不是线上 peer、relay 连接
+ 或聚合背压故障。
+- 恢复动作:仅替换测试时钟的驱动方式,不改变生产恢复动作、协议帧、重试预算或超时默认值。
+- 多 peer:生产逻辑零改动,因此不会改变 1:N 拓扑中其他 peer 的行为;现有多 peer 隔离用例
+ 继续由 package 全量测试覆盖,本修复无需新增生产恢复路径用例。
+
+## 验证
+
+1. 定向重复运行该测试,确认无墙钟竞态;
+2. 运行 `packages/device-link` 全量单测;
+3. 运行根目录 `pnpm test:unit:related`;
+4. 运行 `pnpm --filter @cindy/device-link run --if-present typecheck`(以实际 package name
+ 为准);
+5. review 最终 diff,确认没有生产代码与通用超时变化。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 9a43b13702..029eaf7dc5 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -287,6 +287,10 @@ WebAuthn 可发现凭证的用户可见名称,采用 Apple、Google 与 Micros
右侧栏插件面板页签的图钉:钉住 = 面板在所有对话中保留。动词对:Pin=钉住 / Unpin=取消钉住。2026-07-31 随图钉功能提出,待裁决。
+### Main view
+
+Plugin 声明的应用级完整页面能力;区别于会话内 Panel。V1 由 Cindy 侧边栏入口打开,manifest/代码标识固定为 main-view。
+
### Manual
插件随包提供、由 ghost_manual 按需读取的渐进披露长文资料。它不是权限项,也不等同于已停止新增的 Agent Skill;先登记为 proposed,待插件作者与用户实际使用后再固化。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 875e9cd46d..d3eded8994 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -13,6 +13,18 @@
"desktop:settings.help.qnaFeedbackBodyTemplate"
],
"terms": [
+ {
+ "id": "plugin-main-view",
+ "status": "proposed",
+ "en": "Main view",
+ "translations": {
+ "zh-CN": "主视图",
+ "zh-TW": "主視圖",
+ "ja": "メインビュー",
+ "ko": "메인 보기"
+ },
+ "note": "Plugin 声明的应用级完整页面能力;区别于会话内 Panel。V1 由 Cindy 侧边栏入口打开,manifest/代码标识固定为 main-view。"
+ },
{
"id": "active",
"status": "decided",
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 6b0cb2da26..2add2c80f6 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -106,7 +106,7 @@ function makeHarness(opts?: {
return { client, sockets, current: () => sockets[sockets.length - 1] };
}
-const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms));
+const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
let inboundLinkId = 0;
async function establishInboundReliableLink(
@@ -232,13 +232,13 @@ class MemoryRelay {
}
/** 按顺序逐帧投递直到静默;每帧之间让微任务(drain/ACK)跑完。 */
- async settle(): Promise<void> {
+ async settle(yieldControl: () => Promise<void> = () => tick()): Promise<void> {
let idle = 0;
while (idle < 3) {
const entry = this.queue.shift();
if (!entry) {
idle += 1;
- await tick();
+ await yieldControl();
continue;
}
idle = 0;
@@ -256,7 +256,7 @@ class MemoryRelay {
member.ws.push(entry.env);
}
}
- await tick();
+ await yieldControl();
}
}
@@ -5175,6 +5175,7 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {
}, 10_000);
it('新确认阶段:确认 ACK 丢失后自动有界重发,无需等待下一条控制端业务', async () => {
+ vi.useFakeTimers();
const relay = new MemoryRelay();
const host = makeRelayClient(relay, 'desktop', {
transportRetryIntervalMs: 20,
@@ -5196,49 +5197,75 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {
controller.sendInvokeResult(env.src, env.id, { ok: true, result: 'retry-confirmed' });
}
});
- host.start();
- controller.start();
- await relay.settleUntil(() => host.getStatus() === 'online' && controller.getStatus() === 'online');
-
- relay.dropNext((senderId, env) => (
- senderId === 'ios' && parseTransportAck(env)?.linkRequestId !== undefined
- ));
- const opened = controller.openLink('desktop', {
- controllerName: 'iPhone',
- protocolVersion: 1,
- appVersion: '1',
- }, 500);
- await relay.settleUntil(() => host.isLinkReady('ios'));
- await expect(opened).resolves.toBeTruthy();
- const linkRequestId = (relay.deliveredTo.get('desktop') ?? [])
- .filter((env) => env.kind === 'link-open')
- .at(-1)?.id;
- expect(linkRequestId).toBeTruthy();
+ const settleRelay = () => relay.settle(() => Promise.resolve());
+ try {
+ host.start();
+ controller.start();
+ await vi.advanceTimersByTimeAsync(0);
+ await settleRelay();
+ expect(host.getStatus()).toBe('online');
+ expect(controller.getStatus()).toBe('online');
- const liveInvoke = host.invoke('ios', {
- channel: 'maker:confirmed-by-retry',
- args: [],
- }, 500);
- await relay.settleUntil(() => receivedInvokes.length === 1);
- await expect(liveInvoke).resolves.toEqual({ ok: true, result: 'retry-confirmed' });
+ relay.dropNext((senderId, env) => (
+ senderId === 'ios' && parseTransportAck(env)?.linkRequestId !== undefined
+ ));
+ const opened = controller.openLink('desktop', {
+ controllerName: 'iPhone',
+ protocolVersion: 1,
+ appVersion: '1',
+ }, 500);
+ await settleRelay();
+ await expect(opened).resolves.toBeTruthy();
+ expect(host.isLinkReady('ios')).toBe(false);
+
+ const linkRequestId = (relay.deliveredTo.get('desktop') ?? [])
+ .filter((env) => env.kind === 'link-open')
+ .at(-1)?.id;
+ expect(linkRequestId).toBeTruthy();
+
+ await vi.advanceTimersByTimeAsync(20);
+ await settleRelay();
+ expect(host.isLinkReady('ios')).toBe(true);
+ const retryConfirmationAcks = (relay.deliveredTo.get('desktop') ?? []).filter((env) => (
+ parseTransportAck(env)?.linkRequestId !== undefined
+ ));
+ expect(retryConfirmationAcks).toHaveLength(1);
+ expect(parseTransportAck(retryConfirmationAcks[0])?.linkRequestId).toBe(linkRequestId);
+
+ // 首次立即发送已被丢弃,剩余预算只允许再发送两次。推进到第三次尝试后的
+ // 下一个重试窗口,确认计时器已经停止,且所有确认仍属于当前 request 代际。
+ await vi.advanceTimersByTimeAsync(40);
+ await settleRelay();
+ const boundedConfirmationAcks = (relay.deliveredTo.get('desktop') ?? []).filter((env) => (
+ parseTransportAck(env)?.linkRequestId !== undefined
+ ));
+ expect(boundedConfirmationAcks).toHaveLength(2);
+ expect(boundedConfirmationAcks.every((env) => (
+ parseTransportAck(env)?.linkRequestId === linkRequestId
+ ))).toBe(true);
- const confirmationAcks = (relay.deliveredTo.get('desktop') ?? []).filter((env) => (
- parseTransportAck(env)?.linkRequestId !== undefined
- ));
- // 第一包确认被丢弃后,host 收到首个重试便会恢复发送;但在其首个可靠业务帧
- // 回到 controller、取消确认计时器之前,下一次 20ms 重试可能已经进入 relay。
- // Windows runner 更容易命中这个合法竞态,因此这里只约束协议不变量:至少
- // 有一次确认送达,且不会超过首包丢失后的剩余重试预算,也不跨 request 代际。
- expect(confirmationAcks.length).toBeGreaterThanOrEqual(1);
- expect(confirmationAcks.length).toBeLessThanOrEqual(3);
- expect(confirmationAcks.every((env) => (
- parseTransportAck(env)?.linkRequestId === linkRequestId
- ))).toBe(true);
+ const liveInvoke = host.invoke('ios', {
+ channel: 'maker:confirmed-by-retry',
+ args: [],
+ }, 500);
+ await settleRelay();
+ expect(receivedInvokes).toHaveLength(1);
+ await expect(liveInvoke).resolves.toEqual({ ok: true, result: 'retry-confirmed' });
- offHost();
- offController();
- host.stop();
- controller.stop();
+ const confirmationAcks = (relay.deliveredTo.get('desktop') ?? []).filter((env) => (
+ parseTransportAck(env)?.linkRequestId !== undefined
+ ));
+ expect(confirmationAcks).toHaveLength(3);
+ expect(confirmationAcks.every((env) => (
+ parseTransportAck(env)?.linkRequestId === linkRequestId
+ ))).toBe(true);
+ } finally {
+ offHost();
+ offController();
+ host.stop();
+ controller.stop();
+ vi.useRealTimers();
+ }
}, 10_000);
it('新确认阶段:旧帧执行完才提交的新基线会刷新确认 ACK,不复用首次 stale ackSeq', async () => {
diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.ts
index 72a6cc3e7f..92d1096f55 100644
--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts
+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts
@@ -6,7 +6,9 @@ import {
GHOST_MANUAL_MD_MAX_BYTES,
GHOST_MANIFEST_SUMMARY_MAX_CHARS,
GHOST_MANIFEST_SCHEMA_VERSION,
+ GHOST_MAIN_VIEW_ICONS,
GHOST_OAUTH_SCOPES_MAX,
+ GHOST_SLOTS,
compareCindyVersions,
ghostManifestUsesOidcToken,
isSafeGhostRelativePath,
@@ -29,6 +31,21 @@ const validManifest = {
} as const;
describe('Ghost manifest contract', () => {
+ it('keeps host-owned application slots in the public contract', () => {
+ expect(GHOST_SLOTS).toContain('main-view');
+ expect(GHOST_MAIN_VIEW_ICONS).toEqual([
+ 'puzzle',
+ 'globe',
+ 'code',
+ 'folder',
+ 'database',
+ 'chart-column',
+ 'image',
+ 'message-circle',
+ 'calendar-days',
+ ]);
+ });
+
it('exports the manual authoring limits', () => {
expect(GHOST_MANUAL_MAX_ITEMS).toBe(8);
expect(GHOST_MANUAL_ENTRY_FILE).toBe('MANUAL.md');
@@ -42,7 +59,10 @@ describe('Ghost manifest contract', () => {
});
it('keeps minCindyVersion optional for old plugins and validates declared versions', () => {
- expect(validateGhostManifest(validManifest)).toEqual({ ok: true, manifest: validManifest });
+ expect(validateGhostManifest(validManifest)).toEqual({
+ ok: true,
+ manifest: validManifest,
+ });
expect(validateGhostManifest({ ...validManifest, minCindyVersion: '1.2.3' })).toEqual({
ok: true,
manifest: { ...validManifest, minCindyVersion: '1.2.3' },
@@ -177,34 +197,54 @@ describe('Ghost manifest contract', () => {
expect(
validateGhostManifest(
secret({
- inject: { header: 'X-Identity', format: 'Bearer {value}', hosts: ['api.example.com'] },
+ inject: {
+ header: 'X-Identity',
+ format: 'Bearer {value}',
+ hosts: ['api.example.com'],
+ },
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('Authorization: Bearer') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('Authorization: Bearer'),
+ });
expect(
validateGhostManifest(
secret({
inject: { header: 'Authorization', format: 'Basic {value}' },
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('Authorization: Bearer') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('Authorization: Bearer'),
+ });
expect(
validateGhostManifest(
secret(
{
- inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['*.example.com'] },
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['*.example.com'],
+ },
},
['*.example.com'],
),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('不允许通配') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许通配'),
+ });
expect(
validateGhostManifest(
secret({
inject: { header: 'Authorization', format: 'Bearer {value}' },
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('显式声明非空 inject.hosts') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('显式声明非空 inject.hosts'),
+ });
expect(validateGhostManifest(secret({ url: 'https://api.example.com/keys' }))).toMatchObject({
ok: false,
reason: expect.stringContaining('不允许声明 url'),
@@ -223,7 +263,10 @@ describe('Ghost manifest contract', () => {
input: 'ghost',
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('不允许标注 input') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许标注 input'),
+ });
});
it('accepts a gh-cli secret with a settings-managed fallback token', () => {
@@ -319,7 +362,10 @@ describe('Ghost manifest contract', () => {
},
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('Authorization: Bearer') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('Authorization: Bearer'),
+ });
expect(
validateGhostManifest(
secret({
@@ -330,14 +376,20 @@ describe('Ghost manifest contract', () => {
},
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('只能是 api.github.com') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('只能是 api.github.com'),
+ });
expect(
validateGhostManifest(
secret({
inject: { header: 'Authorization', format: 'Bearer {value}' },
}),
),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('只能是 api.github.com') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('只能是 api.github.com'),
+ });
expect(validateGhostManifest(secret({ exchange: {} }))).toMatchObject({
ok: false,
reason: expect.stringContaining('不允许声明 exchange'),
@@ -812,6 +864,83 @@ describe('Ghost manifest contract', () => {
});
});
+ it('round-trips a strict main-view declaration and requires a Cindy version floor', () => {
+ const manifest = {
+ ...validManifest,
+ minCindyVersion: '1.2.3',
+ slots: ['main-view'],
+ tools: undefined,
+ mainView: {
+ title: 'Workspace',
+ icon: 'globe',
+ html: 'ui/main-view.html',
+ },
+ } as const;
+
+ expect(validateGhostManifest(JSON.parse(JSON.stringify(manifest)))).toEqual({
+ ok: true,
+ manifest,
+ });
+
+ const withoutMin = { ...manifest } as Record<string, unknown>;
+ delete withoutMin.minCindyVersion;
+ expect(validateGhostManifest(withoutMin)).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('minCindyVersion'),
+ });
+ });
+
+ it('keeps main-view slot/detail paired and rejects unsafe or unknown fields', () => {
+ const base = {
+ ...validManifest,
+ minCindyVersion: '1.2.3',
+ slots: ['main-view'],
+ tools: undefined,
+ };
+ expect(validateGhostManifest(base)).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('mainView'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ minCindyVersion: '1.2.3',
+ mainView: { html: 'main-view.html' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('main-view'),
+ });
+ expect(validateGhostManifest({ ...base, mainView: { html: '../escape.html' } }).ok).toBe(false);
+ expect(
+ validateGhostManifest({
+ ...base,
+ mainView: { html: 'main-view.html', icon: 'plugin' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('mainView.icon'),
+ });
+ expect(
+ validateGhostManifest({
+ ...base,
+ mainView: { html: 'main-view.html', icon: 'globe-2' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('puzzle / globe / code'),
+ });
+ expect(
+ validateGhostManifest({
+ ...base,
+ mainView: { html: 'main-view.html', position: 'left' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许的字段'),
+ });
+ });
+
it('enforces node slot / detail pairing and entry discipline', () => {
const base = {
...validManifest,
@@ -833,16 +962,30 @@ describe('Ghost manifest contract', () => {
});
expect(withNode({ entry: 'node/a.cjs', protocol: 'bash' }).ok).toBe(false);
expect(
- withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', entries: ['node/a.cjs'] }),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('不能重复主入口') });
+ withNode({
+ entry: 'node/a.cjs',
+ protocol: 'mcp-stdio',
+ entries: ['node/a.cjs'],
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不能重复主入口'),
+ });
// 大小写不敏感文件系统上的同名变体必须按同一个文件拒绝。
expect(withNode({ entry: 'Index.js', protocol: 'mcp-stdio' })).toMatchObject({
ok: false,
reason: expect.stringContaining('不能与浏览器沙箱 entry'),
});
expect(
- withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', entries: ['node/A.cjs'] }),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('不能重复主入口') });
+ withNode({
+ entry: 'node/a.cjs',
+ protocol: 'mcp-stdio',
+ entries: ['node/A.cjs'],
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不能重复主入口'),
+ });
expect(
withNode({
entry: 'node/a.cjs',
@@ -858,8 +1001,15 @@ describe('Ghost manifest contract', () => {
}),
).toMatchObject({ ok: false, reason: expect.stringContaining('重复入口') });
expect(
- withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', childSpawn: 'yes' }),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('childSpawn 必须是布尔值') });
+ withNode({
+ entry: 'node/a.cjs',
+ protocol: 'mcp-stdio',
+ childSpawn: 'yes',
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('childSpawn 必须是布尔值'),
+ });
expect(
withNode({
entry: 'node/a.cjs',
@@ -867,7 +1017,10 @@ describe('Ghost manifest contract', () => {
lifecycle: 'resident',
idleTimeoutSeconds: 60,
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('resident 时不能再声明') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('resident 时不能再声明'),
+ });
});
it('accepts and normalizes method-scoped Node secret bindings', () => {
@@ -929,13 +1082,22 @@ describe('Ghost manifest contract', () => {
settingsHtml: undefined,
node: { ...base.node, secretBindings: [binding] },
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('需要 settingsHtml') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('需要 settingsHtml'),
+ });
expect(
validateGhostManifest({
...base,
- node: { ...base.node, secretBindings: [{ ...binding, methods: ['bad method'] }] },
+ node: {
+ ...base.node,
+ secretBindings: [{ ...binding, methods: ['bad method'] }],
+ },
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('安全方法名') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('安全方法名'),
+ });
expect(
validateGhostManifest({
...base,
@@ -945,7 +1107,10 @@ describe('Ghost manifest contract', () => {
secretBindings: [{ ...binding, methods: ['initialize'] }],
},
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('宿主保留的 MCP 方法') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('宿主保留的 MCP 方法'),
+ });
expect(
validateGhostManifest({
...base,
@@ -987,7 +1152,10 @@ describe('Ghost manifest contract', () => {
],
},
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('与 node.secretBindings 撞名') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与 node.secretBindings 撞名'),
+ });
expect(
validateGhostManifest({
...base,
@@ -1004,7 +1172,10 @@ describe('Ghost manifest contract', () => {
],
},
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('与 node.secretBindings') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与 node.secretBindings'),
+ });
for (const invalidBinding of [
{ ...binding, key: 'Bad-Key' },
@@ -1051,7 +1222,10 @@ describe('Ghost manifest contract', () => {
});
expect(validateGhostManifest({ ...base, preview: { hosts: [] } }).ok).toBe(false);
expect(
- validateGhostManifest({ ...base, preview: { hosts: ['https://x.example.com'] } }).ok,
+ validateGhostManifest({
+ ...base,
+ preview: { hosts: ['https://x.example.com'] },
+ }).ok,
).toBe(false);
expect(
validateGhostManifest({
@@ -1060,8 +1234,14 @@ describe('Ghost manifest contract', () => {
}),
).toMatchObject({ ok: false, reason: expect.stringContaining('重复域名') });
expect(
- validateGhostManifest({ ...validManifest, preview: { hosts: ['maker.taptap.cn'] } }),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('未包含 "preview"') });
+ validateGhostManifest({
+ ...validManifest,
+ preview: { hosts: ['maker.taptap.cn'] },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('未包含 "preview"'),
+ });
const loopback = validateGhostManifest({
...base,
preview: { hosts: ['localhost', '*.taptap.cn'] },
@@ -1082,8 +1262,14 @@ describe('Ghost manifest contract', () => {
reason: expect.stringContaining('未包含 "skill"'),
});
// 合法声明原样收录
- const good = validateGhostManifest({ ...base, skill: { items: goodItems } });
- expect(good).toMatchObject({ ok: true, manifest: { skill: { items: goodItems } } });
+ const good = validateGhostManifest({
+ ...base,
+ skill: { items: goodItems },
+ });
+ expect(good).toMatchObject({
+ ok: true,
+ manifest: { skill: { items: goodItems } },
+ });
// items 形状:空/超限/非对象/自造字段一律拒
expect(validateGhostManifest({ ...base, skill: { items: [] } }).ok).toBe(false);
expect(validateGhostManifest({ ...base, skill: {} }).ok).toBe(false);
@@ -1113,7 +1299,9 @@ describe('Ghost manifest contract', () => {
const item = (patch: Record<string, unknown>) =>
validateGhostManifest({
...base,
- skill: { items: [{ dir: 'skills/foo', name: 'foo', description: 'x', ...patch }] },
+ skill: {
+ items: [{ dir: 'skills/foo', name: 'foo', description: 'x', ...patch }],
+ },
});
// dir:必须是包内安全相对路径
expect(item({ dir: '../evil' }).ok).toBe(false);
@@ -1147,7 +1335,10 @@ describe('Ghost manifest contract', () => {
],
},
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 name') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('重复 name'),
+ });
expect(
validateGhostManifest({
...base,
@@ -1169,7 +1360,10 @@ describe('Ghost manifest contract', () => {
description: '按需读取的入门工作流',
},
];
- const result = validateGhostManifest({ ...validManifest, manual: { items } });
+ const result = validateGhostManifest({
+ ...validManifest,
+ manual: { items },
+ });
expect(result).toMatchObject({
ok: true,
manifest: {
@@ -1197,9 +1391,12 @@ describe('Ghost manifest contract', () => {
expect(validateGhostManifest({ ...validManifest, manual: { items: [] } }).ok).toBe(false);
expect(validateGhostManifest({ ...validManifest, manual: {} }).ok).toBe(false);
- expect(validateGhostManifest({ ...validManifest, manual: { items: [], extra: true } }).ok).toBe(
- false,
- );
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ manual: { items: [], extra: true },
+ }).ok,
+ ).toBe(false);
expect(item({ extra: true }).ok).toBe(false);
const nine = Array.from({ length: 9 }, (_, index) => ({
dir: `manual/unit-${index}`,
@@ -1232,7 +1429,10 @@ describe('Ghost manifest contract', () => {
],
},
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 name') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('重复 name'),
+ });
expect(
validateGhostManifest({
...validManifest,
@@ -1249,7 +1449,11 @@ describe('Ghost manifest contract', () => {
it('intentionally allows nested manual item directories with distinct logical names', () => {
const items = [
{ dir: 'manual', name: 'overview', description: 'Overview.' },
- { dir: 'manual/advanced', name: 'advanced', description: 'Advanced topics.' },
+ {
+ dir: 'manual/advanced',
+ name: 'advanced',
+ description: 'Advanced topics.',
+ },
];
expect(validateGhostManifest({ ...validManifest, manual: { items } })).toMatchObject({
@@ -1262,14 +1466,20 @@ describe('Ghost manifest contract', () => {
const withManual = (manifest: Record<string, unknown>, dir: string) =>
validateGhostManifest({
...manifest,
- manual: { items: [{ dir, name: 'guide', description: 'Manual guide.' }] },
+ manual: {
+ items: [{ dir, name: 'guide', description: 'Manual guide.' }],
+ },
});
const declaredFileCases: Array<{
label: string;
manifest: Record<string, unknown>;
dir: string;
}> = [
- { label: 'ghost.json', manifest: { ...validManifest }, dir: 'ghost.json' },
+ {
+ label: 'ghost.json',
+ manifest: { ...validManifest },
+ dir: 'ghost.json',
+ },
{
label: 'entry',
manifest: { ...validManifest, entry: 'manual/entry/main.js' },
@@ -1282,7 +1492,10 @@ describe('Ghost manifest contract', () => {
},
{
label: 'settingsHtml',
- manifest: { ...validManifest, settingsHtml: 'manual/settings/settings.html' },
+ manifest: {
+ ...validManifest,
+ settingsHtml: 'manual/settings/settings.html',
+ },
dir: 'manual/settings',
},
{
@@ -1341,7 +1554,13 @@ describe('Ghost manifest contract', () => {
ok: true,
manifest: expect.objectContaining({
manual: {
- items: [{ dir: 'manual/guide', name: 'guide', description: 'Manual guide.' }],
+ items: [
+ {
+ dir: 'manual/guide',
+ name: 'guide',
+ description: 'Manual guide.',
+ },
+ ],
},
}),
});
@@ -1356,8 +1575,14 @@ describe('Ghost manifest contract', () => {
}).ok,
).toBe(false);
expect(
- validateGhostManifest({ ...validManifest, card: { externalLinks: true } }),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('未包含 "card"') });
+ validateGhostManifest({
+ ...validManifest,
+ card: { externalLinks: true },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('未包含 "card"'),
+ });
const normalizedCard = validateGhostManifest({
...validManifest,
slots: ['tool', 'card'],
@@ -1372,7 +1597,10 @@ describe('Ghost manifest contract', () => {
slots: ['tool', 'agent'],
agent: { background: false },
}),
- ).toMatchObject({ ok: false, reason: expect.stringContaining('background: true') });
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('background: true'),
+ });
const backgroundAgent = validateGhostManifest({
...validManifest,
slots: ['tool', 'agent'],
@@ -1437,7 +1665,11 @@ describe('cindy 详单:media/text/embed/search 类目与 oneshotModel 校验', (
});
expect(r.ok, r.ok ? '' : String(r.reason)).toBe(true);
if (!r.ok) return;
- expect(r.manifest.cindy).toEqual({ media: ['deposit'], text: ['oneshot'], embed: ['text'] });
+ expect(r.manifest.cindy).toEqual({
+ media: ['deposit'],
+ text: ['oneshot'],
+ embed: ['text'],
+ });
});
it('text 与 embed 的动作集各归各(不接受串用)', () => {
@@ -1471,7 +1703,10 @@ describe('cindy 详单:media/text/embed/search 类目与 oneshotModel 校验', (
});
expect(ok.ok, ok.ok ? '' : String(ok.reason)).toBe(true);
if (ok.ok)
- expect(ok.manifest.cindy).toEqual({ text: ['oneshot'], oneshotModel: 'codex/gpt-5.5' });
+ expect(ok.manifest.cindy).toEqual({
+ text: ['oneshot'],
+ oneshotModel: 'codex/gpt-5.5',
+ });
for (const bad of [
{ text: ['oneshot'], oneshotModel: '' },
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index da8a1c24bd..e796fa9b63 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -51,6 +51,9 @@ function isWindowsReservedName(name: string): boolean {
* plan/只读拒)、save 票据目录(主 agent 过户,复用 saveDeposit 预算)。
* 字节永远由主机落盘,沙箱本身仍无 fs——本槽是"申请主机代写"的资格,
* 不是文件系统访问权。
+ * 'main-view' = 应用级插件主视图:宿主只挂载已批准 manifest 声明的包内
+ * HTML 入口。它与会话内 panel 独立授权,本身不附赠网络、文件或
+ * 凭证能力。
* 'session-context' = 会话上下文(2026-07-23):agent 派活(tool-call)时,主机把
* 当次会话的可信 {session_id, workdir, workdir_is_local} 注入 args.session_context。
* 只注入宿主认证过的事实,插件与 agent 自报的同名字段一律被剥除;远程工作区
@@ -84,6 +87,7 @@ export const GHOST_SLOTS = [
'tool',
'card',
'panel',
+ 'main-view',
'cindy',
'agent',
'node',
@@ -134,6 +138,33 @@ export interface GhostPanelDecl {
defaultFraction?: number;
}
+/** 应用级插件主视图可用的 Cindy 系统线性图标。枚举值与图标名保持一致。 */
+export const GHOST_MAIN_VIEW_ICONS = [
+ 'puzzle',
+ 'globe',
+ 'code',
+ 'folder',
+ 'database',
+ 'chart-column',
+ 'image',
+ 'message-circle',
+ 'calendar-days',
+] as const;
+export type GhostMainViewIcon = (typeof GHOST_MAIN_VIEW_ICONS)[number];
+
+/**
+ * 插件一级主视图声明。它是应用级导航能力,与会话内 panel 独立授权;
+ * Host 只会挂载这里声明且经过批准的包内 HTML 入口。
+ */
+export interface GhostMainViewDecl {
+ /** 侧边栏与主视图标题;缺省回退插件 name。 */
+ title?: string;
+ /** 侧边栏使用的 Cindy 系统线性图标;缺省为 puzzle。 */
+ icon?: GhostMainViewIcon;
+ /** 主视图界面入口(安装目录内安全相对路径)。 */
+ html: string;
+}
+
/**
* 芯片型意识注册给 agent 的工具声明(卡槽②)。
* 声明式而非运行时动态注册(规则 9:确定性;且会话中途增删工具会破坏
@@ -498,7 +529,7 @@ export interface GhostSecretOauthDecl {
* client 凭证**覆盖**内置值(清除自填 = 回落内置)。桌面应用的 client
* 凭证按 Google 官方口径本非机密(installed-app),写进包里不引入新泄露面;
* 授权仍需用户在浏览器里亲自同意,凭证本身访问不了任何数据。
- */
+ */
clientId?: string;
/** 可选:broker 模式下允许意识在单次连接时选择的备用客户端 ID。 */
clientIdAlternatives?: string[];
@@ -532,7 +563,12 @@ export interface GhostSecretOauthDecl {
* 为空(回落显示 labelPath 标签)。不声明 = 展示名就用 labelPath 的值
* (邮箱这类本身可读的服务商不需要它)。
*/
- identity?: { url: string; labelPath: string; displayTemplate?: string; avatarPath?: string };
+ identity?: {
+ url: string;
+ labelPath: string;
+ displayTemplate?: string;
+ avatarPath?: string;
+ };
/**
* 可选:loopback 回调固定端口(1024–65535)。Atlassian 这类服务商要求回调
* URI 与应用注册值精确匹配(含端口),声明后主机授权引擎钉死
@@ -895,6 +931,8 @@ export interface GhostManifest {
keywords?: string[];
/** 面板声明;没有面板的意识(如纯工具意识)可省略。 */
panel?: GhostPanelDecl;
+ /** 应用级主视图声明;须与 slots 中的 `main-view` 成对。 */
+ mainView?: GhostMainViewDecl;
/**
* preview 槽详单(与 slots 含 'preview' 严格成对):可在右侧栏内置浏览器
* 打开预览标签页的域名白名单。
@@ -1108,6 +1146,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
raw.icon,
raw.settingsHtml,
isPlainObject(raw.panel) ? raw.panel.html : undefined,
+ isPlainObject(raw.mainView) ? raw.mainView.html : undefined,
isPlainObject(raw.node) ? raw.node.entry : undefined,
...(isPlainObject(raw.node) && Array.isArray(raw.node.entries) ? raw.node.entries : []),
]
@@ -1120,7 +1159,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let locales: GhostManifest['locales'];
if (raw.locales !== undefined) {
if (!isPlainObject(raw.locales)) {
- return { ok: false, reason: 'locales 必须是语言到 locale JSON 路径的对象' };
+ return {
+ ok: false,
+ reason: 'locales 必须是语言到 locale JSON 路径的对象',
+ };
}
const unknownLocale = Object.keys(raw.locales).find(
(locale) => !(GHOST_LOCALES as readonly string[]).includes(locale),
@@ -1132,7 +1174,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (raw.locales.en === undefined) {
- return { ok: false, reason: 'locales 必须提供 en,作为所有不支持语言的固定回退' };
+ return {
+ ok: false,
+ reason: 'locales 必须提供 en,作为所有不支持语言的固定回退',
+ };
}
const normalized: Partial<Record<GhostLocale, string>> = {};
const seenPaths: string[] = [];
@@ -1178,7 +1223,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (seenPaths.includes(normalizedLocalePath)) {
- return { ok: false, reason: `locales 含重复路径 ${JSON.stringify(localePath)}` };
+ return {
+ ok: false,
+ reason: `locales 含重复路径 ${JSON.stringify(localePath)}`,
+ };
}
if (
seenPaths.some(
@@ -1246,7 +1294,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
// 面板一律由意识自绘(html 必填):declaration 时代的静态 body 面板已随
// 单形态定案(2026-07-12)移除。
if (!isSafeGhostRelativePath(p.html)) {
- return { ok: false, reason: 'panel.html 必填,且必须是安装目录内的安全相对路径' };
+ return {
+ ok: false,
+ reason: 'panel.html 必填,且必须是安装目录内的安全相对路径',
+ };
}
if (
p.minWidth !== undefined &&
@@ -1264,7 +1315,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
p.defaultFraction < 0.05 ||
p.defaultFraction > 0.8)
) {
- return { ok: false, reason: 'panel.defaultFraction 必须是 0.05–0.8 之间的数字' };
+ return {
+ ok: false,
+ reason: 'panel.defaultFraction 必须是 0.05–0.8 之间的数字',
+ };
}
if (p.position !== undefined) {
if (p.position === 'top' || p.position === 'bottom') {
@@ -1275,7 +1329,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {
- return { ok: false, reason: `panel.position 必须是 ${GHOST_PANEL_POSITIONS.join(' / ')}` };
+ return {
+ ok: false,
+ reason: `panel.position 必须是 ${GHOST_PANEL_POSITIONS.join(' / ')}`,
+ };
}
// 页签形态没有拖缝宽度语义:收词明确拒绝而非静默忽略(规则 9)。
if (p.position === 'tab' && (p.minWidth !== undefined || p.defaultFraction !== undefined)) {
@@ -1295,14 +1352,67 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
+ let mainView: GhostMainViewDecl | undefined;
+ if (raw.mainView !== undefined) {
+ if (!isPlainObject(raw.mainView)) {
+ return { ok: false, reason: 'mainView 必须是对象' };
+ }
+ const unknownMainViewField = Object.keys(raw.mainView).find(
+ (field) => field !== 'html' && field !== 'title' && field !== 'icon',
+ );
+ if (unknownMainViewField) {
+ return {
+ ok: false,
+ reason: `mainView 含不允许的字段 ${JSON.stringify(unknownMainViewField)}`,
+ };
+ }
+ if (
+ raw.mainView.title !== undefined &&
+ (typeof raw.mainView.title !== 'string' ||
+ raw.mainView.title.trim().length === 0 ||
+ raw.mainView.title.length > 64)
+ ) {
+ return {
+ ok: false,
+ reason: 'mainView.title 必须是 1–64 字符的非空字符串',
+ };
+ }
+ if (
+ raw.mainView.icon !== undefined &&
+ !(GHOST_MAIN_VIEW_ICONS as readonly unknown[]).includes(raw.mainView.icon)
+ ) {
+ return {
+ ok: false,
+ reason: `mainView.icon 必须是以下系统图标之一:${GHOST_MAIN_VIEW_ICONS.join(' / ')}`,
+ };
+ }
+ if (!isSafeGhostRelativePath(raw.mainView.html)) {
+ return {
+ ok: false,
+ reason: 'mainView.html 必填,且必须是安装目录内的安全相对路径',
+ };
+ }
+ mainView = {
+ ...(raw.mainView.title !== undefined ? { title: raw.mainView.title } : {}),
+ ...(raw.mainView.icon !== undefined ? { icon: raw.mainView.icon as GhostMainViewIcon } : {}),
+ html: raw.mainView.html,
+ };
+ }
+
if (!isSafeGhostRelativePath(raw.entry)) {
- return { ok: false, reason: '必须提供 entry(安装目录内的安全相对路径,电子脑逻辑入口)' };
+ return {
+ ok: false,
+ reason: '必须提供 entry(安装目录内的安全相对路径,电子脑逻辑入口)',
+ };
}
if (
raw.launch !== undefined &&
!(GHOST_LAUNCH_MODES as readonly string[]).includes(raw.launch as string)
) {
- return { ok: false, reason: `launch 必须是 ${GHOST_LAUNCH_MODES.join(' / ')}` };
+ return {
+ ok: false,
+ reason: `launch 必须是 ${GHOST_LAUNCH_MODES.join(' / ')}`,
+ };
}
if (raw.settingsHtml !== undefined && !isSafeGhostRelativePath(raw.settingsHtml)) {
return { ok: false, reason: 'settingsHtml 必须是安装目录内的安全相对路径' };
@@ -1344,10 +1454,14 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
// 该槽依赖新增的 Host 原生能力,旧 Cindy 不可能安全降级为“只装插件但忽略
// 模拟器”。强制声明最低版本,让 Plugin Server 在目录/详情/下载三条路径上
// 都不向旧客户端交付这份 Release。
- if (slots.includes('ios-simulator') && raw.minCindyVersion === undefined) {
+ if (
+ (slots.includes('ios-simulator') || slots.includes('main-view')) &&
+ raw.minCindyVersion === undefined
+ ) {
+ const slot = slots.includes('main-view') ? 'main-view' : 'ios-simulator';
return {
ok: false,
- reason: 'slots 声明了 "ios-simulator" 时必须同时声明 minCindyVersion',
+ reason: `slots 声明了 ${JSON.stringify(slot)} 时必须同时声明 minCindyVersion`,
};
}
// 声明了面板却没申请 panel 槽(或反之有槽无面板)都是清单自相矛盾。
@@ -1355,7 +1469,19 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
return { ok: false, reason: '声明了 panel 但 slots 未包含 "panel"' };
}
if (slots.includes('panel') && panel === undefined) {
- return { ok: false, reason: 'slots 声明了 "panel" 但缺少 panel(面板由意识自绘,html 必填)' };
+ return {
+ ok: false,
+ reason: 'slots 声明了 "panel" 但缺少 panel(面板由意识自绘,html 必填)',
+ };
+ }
+ if (mainView !== undefined && !slots.includes('main-view')) {
+ return { ok: false, reason: '声明了 mainView 但 slots 未包含 "main-view"' };
+ }
+ if (slots.includes('main-view') && mainView === undefined) {
+ return {
+ ok: false,
+ reason: 'slots 声明了 "main-view" 但缺少 mainView(html 必填)',
+ };
}
if (slots.includes('badge') && panel === undefined) {
return {
@@ -1368,15 +1494,24 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let card: GhostCardNeeds | undefined;
if (raw.card !== undefined) {
if (!isPlainObject(raw.card)) {
- return { ok: false, reason: 'card 能力详单必须是对象(如 { "externalLinks": true })' };
+ return {
+ ok: false,
+ reason: 'card 能力详单必须是对象(如 { "externalLinks": true })',
+ };
}
if (!slots.includes('card')) {
- return { ok: false, reason: '声明了 card 能力详单但 slots 未包含 "card"' };
+ return {
+ ok: false,
+ reason: '声明了 card 能力详单但 slots 未包含 "card"',
+ };
}
const cardRaw = raw.card as Record<string, unknown>;
const unknownCardField = Object.keys(cardRaw).find((key) => key !== 'externalLinks');
if (unknownCardField) {
- return { ok: false, reason: `card 含不允许的字段 ${JSON.stringify(unknownCardField)}` };
+ return {
+ ok: false,
+ reason: `card 含不允许的字段 ${JSON.stringify(unknownCardField)}`,
+ };
}
if (cardRaw.externalLinks !== undefined && typeof cardRaw.externalLinks !== 'boolean') {
return { ok: false, reason: 'card.externalLinks 必须是布尔值' };
@@ -1403,18 +1538,27 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (seenNames.has(t.name))
- return { ok: false, reason: `tools 含重名工具 ${JSON.stringify(t.name)}` };
+ return {
+ ok: false,
+ reason: `tools 含重名工具 ${JSON.stringify(t.name)}`,
+ };
seenNames.add(t.name);
if (
typeof t.description !== 'string' ||
t.description.trim().length === 0 ||
t.description.length > 1024
) {
- return { ok: false, reason: 'tools[].description 必须是 1–1024 字符的非空字符串' };
+ return {
+ ok: false,
+ reason: 'tools[].description 必须是 1–1024 字符的非空字符串',
+ };
}
if (t.parameters !== undefined) {
if (!isPlainObject(t.parameters))
- return { ok: false, reason: 'tools[].parameters 必须是对象(JSON Schema)' };
+ return {
+ ok: false,
+ reason: 'tools[].parameters 必须是对象(JSON Schema)',
+ };
try {
if (JSON.stringify(t.parameters).length > 16_384) {
return { ok: false, reason: 'tools[].parameters 过大(上限 16KB)' };
@@ -1436,7 +1580,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
return { ok: false, reason: '声明了 tools 但 slots 未包含 "tool"' };
}
if (slots.includes('tool') && tools === undefined) {
- return { ok: false, reason: 'slots 声明了 "tool" 但缺少 tools(注册什么工具要写清楚)' };
+ return {
+ ok: false,
+ reason: 'slots 声明了 "tool" 但缺少 tools(注册什么工具要写清楚)',
+ };
}
// cindy 槽能力详单:与 slots 含 'cindy' 成对(有详单必有槽;有槽无详单
@@ -1446,10 +1593,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let cindy: GhostCindyNeeds | undefined;
if (cindyRaw !== undefined) {
if (!isPlainObject(cindyRaw)) {
- return { ok: false, reason: 'cindy 能力详单必须是对象(如 { "image": ["generate"] })' };
+ return {
+ ok: false,
+ reason: 'cindy 能力详单必须是对象(如 { "image": ["generate"] })',
+ };
}
if (!slots.includes('cindy')) {
- return { ok: false, reason: '声明了 cindy 能力详单但 slots 未包含 "cindy"' };
+ return {
+ ok: false,
+ reason: '声明了 cindy 能力详单但 slots 未包含 "cindy"',
+ };
}
cindy = {};
// 类目 → 合法动作表(image / video / media / text / embed / search;动作集恰好
@@ -1483,7 +1636,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (actions.includes(a)) {
- return { ok: false, reason: `cindy.${category} 含重复动作 ${JSON.stringify(a)}` };
+ return {
+ ok: false,
+ reason: `cindy.${category} 含重复动作 ${JSON.stringify(a)}`,
+ };
}
actions.push(a);
}
@@ -1544,10 +1700,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let subscribe: GhostSubscribeNeeds | undefined;
if (raw.subscribe !== undefined) {
if (!isPlainObject(raw.subscribe)) {
- return { ok: false, reason: 'subscribe 订阅详单必须是对象(如 { "topics": ["turn"] })' };
+ return {
+ ok: false,
+ reason: 'subscribe 订阅详单必须是对象(如 { "topics": ["turn"] })',
+ };
}
if (!slots.includes('subscribe')) {
- return { ok: false, reason: '声明了 subscribe 订阅详单但 slots 未包含 "subscribe"' };
+ return {
+ ok: false,
+ reason: '声明了 subscribe 订阅详单但 slots 未包含 "subscribe"',
+ };
}
subscribe = {};
const subRaw = raw.subscribe as Record<string, unknown>;
@@ -1569,7 +1731,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (list.includes(item)) {
- return { ok: false, reason: `subscribe.${field} 含重复项 ${JSON.stringify(item)}` };
+ return {
+ ok: false,
+ reason: `subscribe.${field} 含重复项 ${JSON.stringify(item)}`,
+ };
}
list.push(item);
}
@@ -1595,10 +1760,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let network: GhostNetworkNeeds | undefined;
if (raw.network !== undefined) {
if (!isPlainObject(raw.network)) {
- return { ok: false, reason: 'network 详单必须是对象(如 { "hosts": ["api.example.com"] })' };
+ return {
+ ok: false,
+ reason: 'network 详单必须是对象(如 { "hosts": ["api.example.com"] })',
+ };
}
if (!slots.includes('network')) {
- return { ok: false, reason: '声明了 network 详单但 slots 未包含 "network"' };
+ return {
+ ok: false,
+ reason: '声明了 network 详单但 slots 未包含 "network"',
+ };
}
const n = raw.network as Record<string, unknown>;
// 连接声明在场性先探一眼(合法性下面细验):静态 hosts 的必填性依赖它——
@@ -1615,7 +1786,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
n.hosts !== undefined &&
(!Array.isArray(n.hosts) || n.hosts.length > GHOST_NETWORK_MAX_HOSTS)
) {
- return { ok: false, reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组` };
+ return {
+ ok: false,
+ reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组`,
+ };
}
if (Array.isArray(n.hosts) && n.hosts.length === 0 && !hasConnectionDecls) {
return {
@@ -1633,7 +1807,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
const host = h.trim().toLowerCase();
if (hosts.includes(host)) {
- return { ok: false, reason: `network.hosts 含重复条目 ${JSON.stringify(h)}` };
+ return {
+ ok: false,
+ reason: `network.hosts 含重复条目 ${JSON.stringify(h)}`,
+ };
}
hosts.push(host);
}
@@ -1660,11 +1837,17 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (seenKeys.has(s.key)) {
- return { ok: false, reason: `network.secrets 含重复 key ${JSON.stringify(s.key)}` };
+ return {
+ ok: false,
+ reason: `network.secrets 含重复 key ${JSON.stringify(s.key)}`,
+ };
}
seenKeys.add(s.key);
if (typeof s.label !== 'string' || s.label.trim().length === 0 || s.label.length > 64) {
- return { ok: false, reason: 'network.secrets[].label 必须是 1–64 字符的非空字符串' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].label 必须是 1–64 字符的非空字符串',
+ };
}
// 来源:缺省 'user';'login-email' = 主机登录邮箱派生(用户不填值)。
// 归一化:'user' 不落清单(与缺省同义,权限 diff 不 churn)。
@@ -1752,17 +1935,26 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
s.hint !== undefined &&
(typeof s.hint !== 'string' || s.hint.trim().length === 0 || s.hint.length > 200)
) {
- return { ok: false, reason: 'network.secrets[].hint 必须是 1–200 字符的非空字符串' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].hint 必须是 1–200 字符的非空字符串',
+ };
}
if (s.url !== undefined) {
if (typeof s.url !== 'string' || s.url.length === 0 || s.url.length > 200) {
- return { ok: false, reason: 'network.secrets[].url 必须是 1–200 字符的字符串' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].url 必须是 1–200 字符的字符串',
+ };
}
let parsed: URL;
try {
parsed = new URL(s.url);
} catch {
- return { ok: false, reason: 'network.secrets[].url 不是合法的绝对地址' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].url 不是合法的绝对地址',
+ };
}
if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
return {
@@ -1916,7 +2108,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
try {
parsed2 = new URL(raw2);
} catch {
- return { ok: false, reason: `network.secrets[].oauth.${field} 不是合法的绝对地址` };
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.${field} 不是合法的绝对地址`,
+ };
}
if (
parsed2.protocol !== 'https:' ||
@@ -2046,7 +2241,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
}
if (oa.pkce !== undefined && typeof oa.pkce !== 'boolean') {
- return { ok: false, reason: 'network.secrets[].oauth.pkce 必须是布尔值(缺省 true)' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.pkce 必须是布尔值(缺省 true)',
+ };
}
if (oa.scopeDelimiter !== undefined && oa.scopeDelimiter !== ',') {
return {
@@ -2145,7 +2343,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (!isPlainObject(oa.brokerBounce)) {
- return { ok: false, reason: 'network.secrets[].oauth.brokerBounce 必须是对象' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.brokerBounce 必须是对象',
+ };
}
const bb = oa.brokerBounce as Record<string, unknown>;
for (const field of ['path', 'callbackPath'] as const) {
@@ -2157,14 +2358,25 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
}
- oaBounce = { path: bb.path as string, callbackPath: bb.callbackPath as string };
+ oaBounce = {
+ path: bb.path as string,
+ callbackPath: bb.callbackPath as string,
+ };
}
let oaIdentity:
- | { url: string; labelPath: string; displayTemplate?: string; avatarPath?: string }
+ | {
+ url: string;
+ labelPath: string;
+ displayTemplate?: string;
+ avatarPath?: string;
+ }
| undefined;
if (oa.identity !== undefined) {
if (!isPlainObject(oa.identity)) {
- return { ok: false, reason: 'network.secrets[].oauth.identity 必须是对象' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.identity 必须是对象',
+ };
}
const idn = oa.identity as Record<string, unknown>;
const idnUrl = parseHostBoundUrl(idn.url, 'identity.url');
@@ -2279,7 +2491,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
try {
exUrl = new URL(ex.url);
} catch {
- return { ok: false, reason: 'network.secrets[].exchange.url 不是合法的绝对地址' };
+ return {
+ ok: false,
+ reason: 'network.secrets[].exchange.url 不是合法的绝对地址',
+ };
}
if (
exUrl.protocol !== 'https:' ||
@@ -2409,7 +2624,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (seenConnKeys.has(c.key)) {
- return { ok: false, reason: `network.connections 含重复 key ${JSON.stringify(c.key)}` };
+ return {
+ ok: false,
+ reason: `network.connections 含重复 key ${JSON.stringify(c.key)}`,
+ };
}
// 与 secrets 共用键命名空间(保险库派生键同一前缀),撞名拒装。
if (secretKeySet.has(c.key)) {
@@ -2420,13 +2638,19 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
seenConnKeys.add(c.key);
if (typeof c.label !== 'string' || c.label.trim().length === 0 || c.label.length > 64) {
- return { ok: false, reason: 'network.connections[].label 必须是 1–64 字符的非空字符串' };
+ return {
+ ok: false,
+ reason: 'network.connections[].label 必须是 1–64 字符的非空字符串',
+ };
}
if (
c.hint !== undefined &&
(typeof c.hint !== 'string' || c.hint.trim().length === 0 || c.hint.length > 200)
) {
- return { ok: false, reason: 'network.connections[].hint 必须是 1–200 字符的非空字符串' };
+ return {
+ ok: false,
+ reason: 'network.connections[].hint 必须是 1–200 字符的非空字符串',
+ };
}
if (!isPlainObject(c.inject)) {
return {
@@ -2501,10 +2725,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let agent: GhostAgentNeeds | undefined;
if (raw.agent !== undefined) {
if (!isPlainObject(raw.agent)) {
- return { ok: false, reason: 'agent 能力详单必须是对象(如 { "background": true })' };
+ return {
+ ok: false,
+ reason: 'agent 能力详单必须是对象(如 { "background": true })',
+ };
}
if (!slots.includes('agent')) {
- return { ok: false, reason: '声明了 agent 能力详单但 slots 未包含 "agent"' };
+ return {
+ ok: false,
+ reason: '声明了 agent 能力详单但 slots 未包含 "agent"',
+ };
}
const agentRaw = raw.agent as Record<string, unknown>;
const unknownAgentField = Object.keys(agentRaw).find(
@@ -2547,7 +2777,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
return { ok: false, reason: 'node 能力详单必须是对象' };
}
if (!slots.includes('node')) {
- return { ok: false, reason: '声明了 node 能力详单但 slots 未包含 "node"' };
+ return {
+ ok: false,
+ reason: '声明了 node 能力详单但 slots 未包含 "node"',
+ };
}
const nodeRaw = raw.node as Record<string, unknown>;
const allowedNodeFields = new Set([
@@ -2570,25 +2803,37 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
return { ok: false, reason: 'node.entry 必须是安装目录内的安全相对路径' };
}
if (!/\.(?:c?js)$/.test(nodeRaw.entry)) {
- return { ok: false, reason: 'node.entry 必须是 CommonJS .js / .cjs 文件' };
+ return {
+ ok: false,
+ reason: 'node.entry 必须是 CommonJS .js / .cjs 文件',
+ };
}
// 入口重合判定折叠大小写:Windows / macOS 默认文件系统大小写不敏感,
// main.js 与 Main.js 是同一个文件,原样比较会漏判。
if (nodeRaw.entry.toLowerCase() === (raw.entry as string).toLowerCase()) {
- return { ok: false, reason: 'node.entry 不能与浏览器沙箱 entry 使用同一个文件' };
+ return {
+ ok: false,
+ reason: 'node.entry 不能与浏览器沙箱 entry 使用同一个文件',
+ };
}
if (
typeof nodeRaw.protocol !== 'string' ||
!(GHOST_NODE_PROTOCOLS as readonly string[]).includes(nodeRaw.protocol)
) {
- return { ok: false, reason: `node.protocol 必须是 ${GHOST_NODE_PROTOCOLS.join(' / ')}` };
+ return {
+ ok: false,
+ reason: `node.protocol 必须是 ${GHOST_NODE_PROTOCOLS.join(' / ')}`,
+ };
}
if (
nodeRaw.lifecycle !== undefined &&
(typeof nodeRaw.lifecycle !== 'string' ||
!(GHOST_NODE_LIFECYCLES as readonly string[]).includes(nodeRaw.lifecycle))
) {
- return { ok: false, reason: `node.lifecycle 必须是 ${GHOST_NODE_LIFECYCLES.join(' / ')}` };
+ return {
+ ok: false,
+ reason: `node.lifecycle 必须是 ${GHOST_NODE_LIFECYCLES.join(' / ')}`,
+ };
}
if (
nodeRaw.idleTimeoutSeconds !== undefined &&
@@ -2597,40 +2842,64 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
nodeRaw.idleTimeoutSeconds < 30 ||
nodeRaw.idleTimeoutSeconds > 3600)
) {
- return { ok: false, reason: 'node.idleTimeoutSeconds 必须是 30–3600 的整数' };
+ return {
+ ok: false,
+ reason: 'node.idleTimeoutSeconds 必须是 30–3600 的整数',
+ };
}
if (nodeRaw.lifecycle === 'resident' && nodeRaw.idleTimeoutSeconds !== undefined) {
- return { ok: false, reason: 'node.lifecycle 为 resident 时不能再声明 idleTimeoutSeconds' };
+ return {
+ ok: false,
+ reason: 'node.lifecycle 为 resident 时不能再声明 idleTimeoutSeconds',
+ };
}
// 额外入口(多进程窄版):同一套入口纪律——包内安全相对路径、CJS 文件、
// 不与浏览器沙箱 entry / 主入口 / 彼此重复;条数封顶。
let nodeEntries: string[] | undefined;
if (nodeRaw.entries !== undefined) {
if (!Array.isArray(nodeRaw.entries) || nodeRaw.entries.length === 0) {
- return { ok: false, reason: 'node.entries 必须是非空数组(额外工作进程入口清单)' };
+ return {
+ ok: false,
+ reason: 'node.entries 必须是非空数组(额外工作进程入口清单)',
+ };
}
if (nodeRaw.entries.length > GHOST_NODE_MAX_EXTRA_ENTRIES) {
- return { ok: false, reason: `node.entries 最多 ${GHOST_NODE_MAX_EXTRA_ENTRIES} 条` };
+ return {
+ ok: false,
+ reason: `node.entries 最多 ${GHOST_NODE_MAX_EXTRA_ENTRIES} 条`,
+ };
}
// 同上折叠大小写:大小写变体在大小写不敏感文件系统上是同一个文件,
// 不能被当作不同入口通过查重。
const seen = new Set<string>();
for (const extra of nodeRaw.entries) {
if (!isSafeGhostRelativePath(extra)) {
- return { ok: false, reason: 'node.entries 每项必须是安装目录内的安全相对路径' };
+ return {
+ ok: false,
+ reason: 'node.entries 每项必须是安装目录内的安全相对路径',
+ };
}
if (!/\.(?:c?js)$/.test(extra)) {
- return { ok: false, reason: 'node.entries 每项必须是 CommonJS .js / .cjs 文件' };
+ return {
+ ok: false,
+ reason: 'node.entries 每项必须是 CommonJS .js / .cjs 文件',
+ };
}
const extraFold = extra.toLowerCase();
if (extraFold === (raw.entry as string).toLowerCase()) {
return { ok: false, reason: 'node.entries 不能包含浏览器沙箱 entry' };
}
if (extraFold === nodeRaw.entry.toLowerCase()) {
- return { ok: false, reason: 'node.entries 不能重复主入口 node.entry' };
+ return {
+ ok: false,
+ reason: 'node.entries 不能重复主入口 node.entry',
+ };
}
if (seen.has(extraFold)) {
- return { ok: false, reason: `node.entries 含重复入口 ${JSON.stringify(extra)}` };
+ return {
+ ok: false,
+ reason: `node.entries 含重复入口 ${JSON.stringify(extra)}`,
+ };
}
seen.add(extraFold);
}
@@ -2767,7 +3036,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
try {
parsed = new URL(binding.url);
} catch {
- return { ok: false, reason: 'node.secretBindings[].url 不是合法的绝对地址' };
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].url 不是合法的绝对地址',
+ };
}
if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
return {
@@ -2801,7 +3073,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
if (slots.includes('node') && node === undefined) {
- return { ok: false, reason: 'slots 声明了 "node" 但缺少 node 工作进程详单' };
+ return {
+ ok: false,
+ reason: 'slots 声明了 "node" 但缺少 node 工作进程详单',
+ };
}
if (node?.secretBindings) {
for (const binding of node.secretBindings) {
@@ -2826,21 +3101,36 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
let preview: GhostPreviewNeeds | undefined;
if (raw.preview !== undefined) {
if (!isPlainObject(raw.preview)) {
- return { ok: false, reason: 'preview 详单必须是对象(如 { "hosts": ["*.example.com"] })' };
+ return {
+ ok: false,
+ reason: 'preview 详单必须是对象(如 { "hosts": ["*.example.com"] })',
+ };
}
if (!slots.includes('preview')) {
- return { ok: false, reason: '声明了 preview 详单但 slots 未包含 "preview"' };
+ return {
+ ok: false,
+ reason: '声明了 preview 详单但 slots 未包含 "preview"',
+ };
}
const previewRaw = raw.preview as Record<string, unknown>;
const unknownPreviewField = Object.keys(previewRaw).find((key) => key !== 'hosts');
if (unknownPreviewField !== undefined) {
- return { ok: false, reason: `preview 含不允许的字段 ${JSON.stringify(unknownPreviewField)}` };
+ return {
+ ok: false,
+ reason: `preview 含不允许的字段 ${JSON.stringify(unknownPreviewField)}`,
+ };
}
if (!Array.isArray(previewRaw.hosts) || previewRaw.hosts.length === 0) {
- return { ok: false, reason: 'preview.hosts 必须是非空数组(可打开预览的域名白名单)' };
+ return {
+ ok: false,
+ reason: 'preview.hosts 必须是非空数组(可打开预览的域名白名单)',
+ };
}
if (previewRaw.hosts.length > GHOST_PREVIEW_MAX_HOSTS) {
- return { ok: false, reason: `preview.hosts 最多 ${GHOST_PREVIEW_MAX_HOSTS} 条` };
+ return {
+ ok: false,
+ reason: `preview.hosts 最多 ${GHOST_PREVIEW_MAX_HOSTS} 条`,
+ };
}
const seenPreviewHosts = new Set<string>();
for (const host of previewRaw.hosts) {
@@ -2848,10 +3138,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
!isValidGhostNetworkHostPattern(host) &&
!(typeof host === 'string' && GHOST_PREVIEW_LOOPBACK_HOSTS.has(host))
) {
- return { ok: false, reason: `preview.hosts 含不合法域名模式 ${JSON.stringify(host)}` };
+ return {
+ ok: false,
+ reason: `preview.hosts 含不合法域名模式 ${JSON.stringify(host)}`,
+ };
}
if (seenPreviewHosts.has(host)) {
- return { ok: false, reason: `preview.hosts 含重复域名 ${JSON.stringify(host)}` };
+ return {
+ ok: false,
+ reason: `preview.hosts 含重复域名 ${JSON.stringify(host)}`,
+ };
}
seenPreviewHosts.add(host);
}
@@ -2883,20 +3179,32 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
const skillRaw = raw.skill as Record<string, unknown>;
const unknownSkillField = Object.keys(skillRaw).find((key) => key !== 'items');
if (unknownSkillField !== undefined) {
- return { ok: false, reason: `skill 含不允许的字段 ${JSON.stringify(unknownSkillField)}` };
+ return {
+ ok: false,
+ reason: `skill 含不允许的字段 ${JSON.stringify(unknownSkillField)}`,
+ };
}
if (!Array.isArray(skillRaw.items) || skillRaw.items.length === 0) {
- return { ok: false, reason: 'skill.items 必须是非空数组(随包捆绑的技能清单)' };
+ return {
+ ok: false,
+ reason: 'skill.items 必须是非空数组(随包捆绑的技能清单)',
+ };
}
if (skillRaw.items.length > GHOST_SKILL_MAX_ITEMS) {
- return { ok: false, reason: `skill.items 最多 ${GHOST_SKILL_MAX_ITEMS} 条` };
+ return {
+ ok: false,
+ reason: `skill.items 最多 ${GHOST_SKILL_MAX_ITEMS} 条`,
+ };
}
const skillItems: GhostSkillItem[] = [];
const seenSkillNames = new Set<string>();
const seenSkillDirs = new Set<string>();
for (const item of skillRaw.items) {
if (!isPlainObject(item)) {
- return { ok: false, reason: 'skill.items 每项必须是对象({ dir, name, description })' };
+ return {
+ ok: false,
+ reason: 'skill.items 每项必须是对象({ dir, name, description })',
+ };
}
const itemRaw = item as Record<string, unknown>;
const unknownItemField = Object.keys(itemRaw).find(
@@ -2929,24 +3237,40 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
itemRaw.description.trim().length === 0 ||
itemRaw.description.length > 1024
) {
- return { ok: false, reason: 'skill.items[].description 必须是 1–1024 字符的非空字符串' };
+ return {
+ ok: false,
+ reason: 'skill.items[].description 必须是 1–1024 字符的非空字符串',
+ };
}
const nameFold = itemRaw.name.toLowerCase();
if (seenSkillNames.has(nameFold)) {
- return { ok: false, reason: `skill.items 含重复 name ${JSON.stringify(itemRaw.name)}` };
+ return {
+ ok: false,
+ reason: `skill.items 含重复 name ${JSON.stringify(itemRaw.name)}`,
+ };
}
seenSkillNames.add(nameFold);
const dirFold = itemRaw.dir.toLowerCase();
if (seenSkillDirs.has(dirFold)) {
- return { ok: false, reason: `skill.items 含重复 dir ${JSON.stringify(itemRaw.dir)}` };
+ return {
+ ok: false,
+ reason: `skill.items 含重复 dir ${JSON.stringify(itemRaw.dir)}`,
+ };
}
seenSkillDirs.add(dirFold);
- skillItems.push({ dir: itemRaw.dir, name: itemRaw.name, description: itemRaw.description });
+ skillItems.push({
+ dir: itemRaw.dir,
+ name: itemRaw.name,
+ description: itemRaw.description,
+ });
}
skill = { items: skillItems };
}
if (slots.includes('skill') && skill === undefined) {
- return { ok: false, reason: 'slots 声明了 "skill" 但缺少 skill 详单(items 技能清单必填)' };
+ return {
+ ok: false,
+ reason: 'slots 声明了 "skill" 但缺少 skill 详单(items 技能清单必填)',
+ };
}
// manual 是独立顶层字段,不是能力 slot 或授权项。这里只校验一级逻辑索引;
@@ -2963,20 +3287,29 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
const manualRaw = raw.manual as Record<string, unknown>;
const unknownManualField = Object.keys(manualRaw).find((key) => key !== 'items');
if (unknownManualField !== undefined) {
- return { ok: false, reason: `manual 含不允许的字段 ${JSON.stringify(unknownManualField)}` };
+ return {
+ ok: false,
+ reason: `manual 含不允许的字段 ${JSON.stringify(unknownManualField)}`,
+ };
}
if (!Array.isArray(manualRaw.items) || manualRaw.items.length === 0) {
return { ok: false, reason: 'manual.items 必须是非空数组(随包手册索引)' };
}
if (manualRaw.items.length > GHOST_MANUAL_MAX_ITEMS) {
- return { ok: false, reason: `manual.items 最多 ${GHOST_MANUAL_MAX_ITEMS} 条` };
+ return {
+ ok: false,
+ reason: `manual.items 最多 ${GHOST_MANUAL_MAX_ITEMS} 条`,
+ };
}
const manualItems: GhostManualItem[] = [];
const seenManualNames = new Set<string>();
const seenManualDirs = new Set<string>();
for (const item of manualRaw.items) {
if (!isPlainObject(item)) {
- return { ok: false, reason: 'manual.items 每项必须是对象({ dir, name, description })' };
+ return {
+ ok: false,
+ reason: 'manual.items 每项必须是对象({ dir, name, description })',
+ };
}
const itemRaw = item as Record<string, unknown>;
const unknownItemField = Object.keys(itemRaw).find(
@@ -3023,11 +3356,17 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
const nameFold = itemRaw.name.toLowerCase();
if (seenManualNames.has(nameFold)) {
- return { ok: false, reason: `manual.items 含重复 name ${JSON.stringify(itemRaw.name)}` };
+ return {
+ ok: false,
+ reason: `manual.items 含重复 name ${JSON.stringify(itemRaw.name)}`,
+ };
}
seenManualNames.add(nameFold);
if (seenManualDirs.has(dirFold)) {
- return { ok: false, reason: `manual.items 含重复 dir ${JSON.stringify(itemRaw.dir)}` };
+ return {
+ ok: false,
+ reason: `manual.items 含重复 dir ${JSON.stringify(itemRaw.dir)}`,
+ };
}
seenManualDirs.add(dirFold);
manualItems.push({
@@ -3048,10 +3387,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
raw.command.length > 32 ||
/[\s/]/.test(raw.command)
) {
- return { ok: false, reason: 'command 必须是 1–32 字符、不含空白与 "/" 的字符串' };
+ return {
+ ok: false,
+ reason: 'command 必须是 1–32 字符、不含空白与 "/" 的字符串',
+ };
}
if (tools === undefined) {
- return { ok: false, reason: '声明了 command 但没有 tools——没有工具的指令无事可做' };
+ return {
+ ok: false,
+ reason: '声明了 command 但没有 tools——没有工具的指令无事可做',
+ };
}
}
@@ -3063,7 +3408,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
return { ok: false, reason: 'keywords 必须是 1–8 项的数组' };
}
if (tools === undefined) {
- return { ok: false, reason: '声明了 keywords 但没有 tools——没有工具的触发词无事可做' };
+ return {
+ ok: false,
+ reason: '声明了 keywords 但没有 tools——没有工具的触发词无事可做',
+ };
}
const seen = new Set<string>();
keywords = [];
@@ -3114,6 +3462,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
...(raw.command !== undefined ? { command: raw.command as string } : {}),
...(keywords !== undefined ? { keywords } : {}),
...(panel !== undefined ? { panel } : {}),
+ ...(mainView !== undefined ? { mainView } : {}),
...(preview !== undefined ? { preview } : {}),
...(skill !== undefined ? { skill } : {}),
...(manual !== undefined ? { manual } : {}),