diff --git a/cli/src/integrations/installed-projection.ts b/cli/src/integrations/installed-projection.ts index a1c31e11e..98dd449dd 100644 --- a/cli/src/integrations/installed-projection.ts +++ b/cli/src/integrations/installed-projection.ts @@ -16,18 +16,23 @@ const itemSchema = z.object({ registry: text, namespace: text, slug: text, targe /** Read only the selected Registry's DSH records in Host-approved roots; never repair or hash all files. */ export async function readInstalledProjection(inventory: Pick, registry: string, + targets: readonly InstalledProjectionTarget[]): Promise { + let records: unknown[] + try { + const raw: unknown = await inventory.read() + records = z.object({ items: z.array(z.unknown()) }).parse(raw).items + } catch { return { items: [], complete: false, issues: ['inventory-unreadable'] } } + return readInstalledProjectionRecords(records, registry, targets) +} + +/** Internal projection primitive: callers must obtain records from a trusted inventory snapshot. */ +export async function readInstalledProjectionRecords(records: readonly unknown[], registry: string, targets: readonly InstalledProjectionTarget[]): Promise { const result: InstalledProjection = { items: [], complete: true, issues: [] } const issue = (code: InstalledProjection['issues'][number]) => { result.complete = false if (!result.issues.includes(code)) result.issues.push(code) } - let records: unknown[] - try { - const raw: unknown = await inventory.read() - const parsed = z.object({ items: z.array(z.unknown()) }).parse(raw) - records = parsed.items - } catch { issue('inventory-unreadable'); return result } const roots = targets.map(target => { if (!isAbsolute(target.root)) throw new Error('Installed projection requires absolute Host roots') return { ...target, root: resolve(target.root) } @@ -86,3 +91,44 @@ export async function readInstalledProjection(inventory: Pick, + registry: string, targets: readonly InstalledProjectionTarget[]) { + const identity = async () => { + const stat = await lstat(inventory.path, { bigint: true }).catch(error => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined + throw error + }) + if (!stat) return 'absent' + if (!stat.isFile()) throw new Error('Inventory is not a regular file') + return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(':') + } + const revision = await identity() + const records = (await inventory.read()).items + const assertCurrent = async () => { + if (await identity() !== revision) throw new Error('Inventory changed during update scan') + } + await assertCurrent() + const projection = await readInstalledProjectionRecords(records, registry, targets) + await assertCurrent() + const key = (item: Pick) => JSON.stringify([item.namespace, item.slug, item.scope]) + const index = new Map() + for (const record of records) { + for (const target of targets) { + const entries = record.targets.filter(entry => isAbsolute(entry.rootDir) && resolve(entry.rootDir) === resolve(target.root) && entry.agent === 'dsh') + if (!entries.length) continue + const id = key({ ...record, scope: target.scope }) + const bucket = index.get(id) ?? [] + bucket.push({ ...record, targets: entries }); index.set(id, bucket) + } + } + return { projection, async read(item: InstalledProjectionItem) { + await assertCurrent() + const result = await readInstalledProjectionRecords(index.get(key(item)) ?? [], registry, targets.filter(target => target.scope === item.scope)) + await assertCurrent() + const current = result.items.find(value => value.targetPath === item.targetPath) + if (!current || JSON.stringify(current) !== JSON.stringify(item)) throw new Error('Installed target changed during update scan') + return current + } } +} diff --git a/cli/src/integrations/native-contract.d.ts b/cli/src/integrations/native-contract.d.ts index 2ac698f55..c626d5f38 100644 --- a/cli/src/integrations/native-contract.d.ts +++ b/cli/src/integrations/native-contract.d.ts @@ -81,6 +81,7 @@ export interface NativeRuntime { acceptUpgrade(request: NativeOperationRequest, validateNew: () => Promise): Promise inspectUpgrade(selected: UpgradeSelection, targets: readonly InstalledProjectionTarget[]): Promise assessUpdate(installed: UpdateIdentity, candidate: UpdateIdentity): UpdateAssessment + openInstalledSnapshot(registry: string, targets: readonly InstalledProjectionTarget[]): Promise<{ projection: InstalledProjection; read(item: InstalledProjectionItem): Promise }> listInstalled(registry: string, targets: readonly InstalledProjectionTarget[]): Promise readonly hostInstanceId: string listPending(): Promise diff --git a/cli/src/integrations/native-runtime.ts b/cli/src/integrations/native-runtime.ts index b3e1b89ef..98294a520 100644 --- a/cli/src/integrations/native-runtime.ts +++ b/cli/src/integrations/native-runtime.ts @@ -5,7 +5,7 @@ import { isDeepStrictEqual } from 'node:util' import { inspectToggle, executeNativeToggle, recoverToggle } from './native-toggle' import { readSkillExamples } from '../services/skill-examples' import { observeInstallationDiscovery } from './install-discovery' -import { readInstalledProjection } from './installed-projection' +import { readInstalledProjection, openInstalledProjectionSnapshot } from './installed-projection' import { assessSkillUpdate } from './update-assessment' import { inspectUpgradeBaseline } from './upgrade-baseline' import { inspectRemovalBaseline } from './removal-baseline' @@ -115,6 +115,7 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven }, assessUpdate: assessSkillUpdate, inspectUpgrade: (selected, targets) => inspectUpgradeBaseline(inventory, { ...selected }, targets.map(target => ({ ...target }))), + openInstalledSnapshot: (registry, targets) => openInstalledProjectionSnapshot(inventory, registry, targets), listInstalled: (registry, targets) => readInstalledProjection(inventory, registry, targets.map(target => ({ ...target }))), executeInstall: async request => { await ensureCompatible() diff --git a/cli/test/unit/integrations/installed-update-snapshot.test.ts b/cli/test/unit/integrations/installed-update-snapshot.test.ts new file mode 100644 index 000000000..42b4b0bd9 --- /dev/null +++ b/cli/test/unit/integrations/installed-update-snapshot.test.ts @@ -0,0 +1,79 @@ +import { expect, spyOn, test } from 'bun:test' +import * as fs from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { InventoryStore } from '../../../src/stores/inventory-store' +import { openInstalledProjectionSnapshot } from '../../../src/integrations/installed-projection' + +const registry = 'https://registry.example' +async function fixture(count: number, run: (inventory: InventoryStore, targets: { scope: 'user' | 'project'; root: string }[]) => Promise) { + const root = await fs.realpath(await fs.mkdtemp(join(tmpdir(), 'skillhub-update-scan-'))) + try { + const inventory = new InventoryStore(root) + const targets = [{ scope: 'user' as const, root: join(root, 'user') }, { scope: 'project' as const, root: join(root, 'project') }] + const items = [] + for (let index = 0; index < count / 2; index++) { + const slug = `skill-${index}` + const entries = targets.map(target => ({ rootDir: target.root, installDir: join(target.root, slug), agent: 'dsh', version: '1.0.0', installedAt: '2026-10-28', fingerprint: 'original' })) + for (const entry of entries) { + await fs.mkdir(join(entry.installDir, '.skillhub'), { recursive: true }) + await fs.writeFile(join(entry.installDir, 'SKILL.md'), 'local content') + await fs.writeFile(join(entry.installDir, '.skillhub/metadata.json'), JSON.stringify({ registry, namespace: 'demo', slug, ...entry })) + } + items.push({ registry, namespace: 'demo', slug, targets: entries }) + } + await inventory.write({ items }) + await run(inventory, targets) + } finally { await fs.rm(root, { recursive: true, force: true }) } +} + +for (const size of [10, 100, 500]) test(`snapshot ${size} real filesystem targets has linear reads`, async () => { + await fixture(size, async (inventory, targets) => { + const read = spyOn(inventory, 'read') + const files = spyOn(fs, 'readFile') + const stats = spyOn(fs, 'lstat') + const started = performance.now() + try { + const snapshot = await openInstalledProjectionSnapshot(inventory, registry, targets) + expect(snapshot.projection.items).toHaveLength(size) + expect(snapshot.projection.complete).toBe(true) + for (const item of snapshot.projection.items) { await snapshot.read(item); await snapshot.read(item) } + const metadataReads = files.mock.calls.filter(([path]) => String(path).endsWith('/metadata.json')).length + const inventoryStats = stats.mock.calls.filter(([path]) => path === inventory.path).length + expect(read).toHaveBeenCalledTimes(1) + expect(metadataReads).toBe(size * 3) + expect(inventoryStats).toBe(size * 4 + 3) + console.info(JSON.stringify({ targets: size, inventoryReads: read.mock.calls.length, metadataReads, inventoryStats, elapsedMs: Math.round(performance.now() - started) })) + } finally { read.mockRestore(); files.mockRestore(); stats.mockRestore() } + }) +}) + +test('snapshot rejects inventory ABA, atomic replacement and target metadata changes', async () => { + await fixture(2, async (inventory, targets) => { + let snapshot = await openInstalledProjectionSnapshot(inventory, registry, targets) + const original = await fs.readFile(inventory.path, 'utf8') + const before = await fs.stat(inventory.path) + await fs.writeFile(inventory.path, original.replace('demo', 'evil')) + await fs.writeFile(inventory.path, original) + await fs.utimes(inventory.path, before.atime, before.mtime) + await expect(snapshot.read(snapshot.projection.items[0]!)).rejects.toThrow('Inventory changed') + snapshot = await openInstalledProjectionSnapshot(inventory, registry, targets) + await fs.writeFile(inventory.path + '.replacement', original) + await fs.rename(inventory.path + '.replacement', inventory.path) + await expect(snapshot.read(snapshot.projection.items[0]!)).rejects.toThrow('Inventory changed') + snapshot = await openInstalledProjectionSnapshot(inventory, registry, targets) + await fs.writeFile(join(snapshot.projection.items[0]!.targetPath, '.skillhub/metadata.json'), '{}') + await expect(snapshot.read(snapshot.projection.items[0]!)).rejects.toThrow('Installed target changed') + }) +}) + +test('absent inventory is an empty snapshot; creation invalidates it', async () => { + await fixture(2, async (inventory, targets) => { + const existing = await openInstalledProjectionSnapshot(inventory, registry, targets) + await fs.unlink(inventory.path) + const empty = await openInstalledProjectionSnapshot(inventory, registry, targets) + expect(empty.projection).toEqual({ items: [], complete: true, issues: [] }) + await inventory.write({ items: [] }) + await expect(empty.read(existing.projection.items[0]!)).rejects.toThrow('Inventory changed') + }) +}) diff --git a/openspec/changes/add-dsh-native-plugin/README.md b/openspec/changes/add-dsh-native-plugin/README.md index 627c0fdad..a37c57305 100644 --- a/openspec/changes/add-dsh-native-plugin/README.md +++ b/openspec/changes/add-dsh-native-plugin/README.md @@ -56,8 +56,10 @@ 首期功能范围以本目录规范为准。当前研发基线为 DSH 0.2.0-rc.2,包名为 `@astron-team/skillhub-dsh`;正式平台支持与发布决定按验收门禁执行。过程日志、截图批次和临时研究材料在仓库外留档,仓库仅保留正式规格、验证摘要及可复用测试。 -## 后续增量:安装级技能启停(设计阶段) +## 后续增量:安装级技能启停 -[安装级启停设计](skill-toggle-design.md)定义受管理安装的停用、恢复、更新与卸载联动;正式验收见消费规范,执行拆分见 tasks.md 第44节。此增量尚未实现,不属于已发布0.5.0的能力。 +[安装级启停设计](skill-toggle-design.md)定义受管理安装的停用、恢复、更新与卸载联动;正式验收见消费规范,执行拆分见 tasks.md 第44节。此增量已随 PR #1025 合并,npm 发布与原生平台发布验收另行安排。 - [使用优先页面与二级安装管理](skill-use-first-design.md):日常动作、只读安装选择及精确管理边界。 + +- [已安装技能统一检查更新](installed-update-check-design.md):用户主动检查、技能级汇总筛选与逐位置更新,第46节跟踪验收。 diff --git a/openspec/changes/add-dsh-native-plugin/installed-update-check-design.md b/openspec/changes/add-dsh-native-plugin/installed-update-check-design.md new file mode 100644 index 000000000..6c5c34bed --- /dev/null +++ b/openspec/changes/add-dsh-native-plugin/installed-update-check-design.md @@ -0,0 +1,23 @@ +# 已安装技能统一检查更新 + +## 范围 +用户主动检查当前来源、当前工作区可见的受管理安装。无进入页面自动扫描、后台轮询、批量执行、自动覆盖或新增Registry/SaaS协议。日常仍按技能聚合;实际检查/更新以精确itemKey为单位。 + +## 交互 +已安装页提供检查更新与进度n/m;结果渐进呈现,不逐项弹通知,不阻断浏览。汇总可更新技能数与检查失败项,支持全部/可更新/检查失败筛选和失败重试,关键词可叠加。已最新无卡片冗余文字;可更新显示目标版本摘要或多位置有更新,查看更新进入现有详情右侧,保持使用技能主动作。位置结果独立:同技能只计一个可更新技能,但不同位置版本与确认分开。blocked显示需处理,不算可执行更新;unavailable/错误算检查失败,不伪报已最新。 + +## 技术边界 +统一检查使用DSH私有只读检查轮次;保留原单项checkUpdate和精确位置prepareUpgrade事务,不另造批量写入API。客户端有界并发只读检查;重入禁用,取消/离开/切来源/会话/工作区时中止在途并丢弃迟到结果。结果仅适用于同一来源会话及同一安装引用。库存变更、更新/卸载/启停导致旧itemKey失效时清除对应结果。详情返回保留仍有效结果与筛选;详情更新执行始终重新核验,不把检查结果当授权。错误/空库存/不完整库存明确表达,不能全局显示全部已最新。 + +## 验收 +覆盖空安装、单份、同技能多位置不同结果、全部最新、可升级、本地修改blocked、网络失败重试、混合结果、扫描中切换与重复点击、迟到结果、安装变化后结果失效。确认没有任何扫描触发写操作。真实DSH检查进度与汇总筛选、详情返回、逐位置升级确认取消、深浅色与窄屏,原安装不变;本轮不需模型调用。 + +## 工具栏展示约定 +搜索和检查操作在同一响应式工具栏,筛选采用与页面一致的紧凑按钮组(全部/可更新/检查失败),不使用平台原生下拉菜单。筛选和单行摘要放在第二行;未检查仅显示技能数量,运行中明确进度,完成后仅显示有意义的更新与失败计数,零失败隐藏。不重复显示列表数量段落;窄屏允许自然换行,保留可见焦点和选中语义。 + +## 规模与资源边界 +每轮仅建立一次可信库存快照并索引目标,逐项只核验对应目标与库存文件版本;不能将全量库存读取/解析或全安装目录核验放入逐项循环。库存文件变更使本轮失效,重新检查建立新快照。快照建立前后需核验文件版本,避免跨变更读取。每轮同来源同技能共用远端resolve;不同安装位置仍独立判断版本结果。失败重试新建轮次,不永久缓存失败或版本。 + +轮次引用只由Host生成并绑定真实会话/工作区/来源/文件服务/运行时,客户端不提供路径。数量、生命周期和并发有界,结束、取消、过期和销毁释放资源;单个位置等待取消不误杀同技能其他位置共享请求。旧轮次结果不得流入新上下文,检查快照不能作为写入授权。 + +性能验收覆盖10/100/500处安装,分别记录库存读取、目标核验、远端请求次数和耗时;以读取次数和工作量接近线性为主要回归断言,不使用机器相关固定耗时阈值。真实DSH验证新私有协议、渐进结果、取消和原逐项更新确认。 diff --git a/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md b/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md index 0f31e899c..6a6fae077 100644 --- a/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md +++ b/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md @@ -436,3 +436,25 @@ Daily catalog, installed-skill groups, conversation inventory cards and default #### Scenario: Explicit installation management - **WHEN** the user selects a particular installation in secondary management or uses an exact operation receipt - **THEN** its exact reference remains authoritative for that request and is never silently replaced by the skill-level selector's winner + + +### Requirement: User-triggered installed update overview +The installed view SHALL check current managed installations only on explicit user action, aggregate results by skill, and retain exact installation identity for individual updates. It SHALL NOT execute updates during the scan. + +#### Scenario: Mixed installation results +- **WHEN** installations of one skill return different update states +- **THEN** the view counts the skill once as upgradable if any location can upgrade, and the detail exposes each location independently +- **AND** blocked or unavailable results are not represented as current or executable upgrades + +#### Scenario: Context or inventory changes during a scan +- **WHEN** the source, session, workspace, or installation reference changes +- **THEN** stale results cannot populate the current overview or authorize an update + +#### Scenario: Retry and individual confirmation +- **WHEN** a user retries failed checks or opens an upgradable skill +- **THEN** checks remain read-only and the existing precise per-installation update confirmation is required before mutation + +#### Scenario: Large inventory update checking +- **WHEN** a user checks many installations, including several locations of the same skill +- **THEN** a bounded Host-owned scan reads and indexes the trusted inventory once, validates only the requested target and inventory revision per result, and shares remote version resolution for the same source and skill within that scan +- **AND** inventory or context changes invalidate the scan, scan resources expire or are released on cancellation, and mutation preparation retains its independent full validation diff --git a/openspec/changes/add-dsh-native-plugin/tasks.md b/openspec/changes/add-dsh-native-plugin/tasks.md index 1be87d5d9..c72a5cd3b 100644 --- a/openspec/changes/add-dsh-native-plugin/tasks.md +++ b/openspec/changes/add-dsh-native-plugin/tasks.md @@ -396,3 +396,13 @@ - [ ] 45.4 独立评审、插件检查和真实DSH新对话/案例取消/填入/管理验证已通过;原安装保留。旧草稿往返人工核对受宿主侧栏隔离会话不可见限制,自动保护测试已通过,待补人工证据。 - [x] 45.5 按人工反馈取消管理弹窗,统一详情内联管理,修复确认层被背景卡片覆盖并验证。 + +## 46. 已安装技能统一检查更新 + +- [x] 46.1 确定主动统一检查、逐项更新与位置边界。 +- [x] 46.2 实现有界只读检查、上下文失效、进度汇总与筛选。 +- [x] 46.3 接入详情逐位置更新,保持原确认与库存变更失效。 +- [x] 46.4 测试、独立评审与真实DSH预览验收。 + +- [x] 46.5 优化统一检查的全量库存重复读取与同技能resolve重复请求,保留精确目标与上下文保护。 +- [x] 46.6 完成10/100/500位置规模测量、独立复审和真实DSH新协议回归。 diff --git a/openspec/changes/add-dsh-native-plugin/verification.md b/openspec/changes/add-dsh-native-plugin/verification.md index 4b4fff4cd..edd9cd397 100644 --- a/openspec/changes/add-dsh-native-plugin/verification.md +++ b/openspec/changes/add-dsh-native-plugin/verification.md @@ -519,3 +519,30 @@ CLI 全量结果与后续专项分开记录,不声称最终新增用例都来 管理安装改为进入对应详情,右侧直接展示各位置管理;对话入口沿已有详情导航。安装与危险操作确认保留。修复portal位于卡片操作区z-index上下文导致背景按钮盖过确认框的问题;共享确认层移出卡片,原生dialog内保留top layer。 最终插件619项测试/12357断言、build/typecheck/lint通过。新版真实DSH市场/已安装详情、两位置、深浅色/360窄屏、确认取消和elementFromPoint背景遮挡验证通过,50份技能文件SHA不变。旧历史会话引用按预期拒绝,重新读取后进入详情。无模型调用、未重验旧RC;搜索drawer嵌套确认本轮未独立点击。外部证据real/inline-management-acceptance.md,包SHA256 de575972578be50f4860472cb436111467c0bf9f8dc66ebd6401871b7aa73f03。未提交或发布。 + + +### 已安装技能统一检查更新(2026-10-28) + +已实现用户主动发起的只读检查,最多3个并发、逐位置进度、技能级汇总、可更新/失败筛选及失败重试。进入页面不自动扫描,不提供批量更新。有效结果按itemKey传入详情,更新仍走原逐位置准备与确认;库存和来源/会话/工作区变化使旧引用失效。 + +最终 build/typecheck/lint、626项测试(12392次断言,89个文件)通过,独立复审无阻断发现。真实DSH预览检查12个安装位置,发现4个可更新技能;实际1.2.0→1.3.0进入原确认并取消。受控只读响应覆盖混合状态、并发、筛选重试、详情返回、取消与迟到响应;明暗主题及360窄屏无横向溢出。 + +来源/会话/同会话工作区切换、ABA和库存替换由真实React组件浏览器夹具验证;本轮未完成真实Host跨会话或工作区切换验收,不将组件证据扩大为Host实测。无模型调用、无安装执行写入,47份技能/项目/配置文件前后哈希一致。未提交、推送或发布。 + +外部证据:`dsh-update-overview-20261028/acceptance.md`、`review.md`、`final-check.log`、`browser-result.json`、`component-result.json`。运行包SHA256:`ec70b36c4629e2f8552dfc70c14f2e495f5cf2e2ca9d16e236c81ae3efec7cd6`;97个部署文件与最终包一致。 + +### 人工反馈:更新检查工具栏样式 + +搜索与操作同行,筛选改为紧凑按钮组,摘要合并且隐藏初始零统计与零失败。定向7项测试/33断言、build/typecheck/lint通过;真实DSH验证12处安装检查、筛选、失败重试、升级确认取消,以及键盘和明暗/窄屏布局。截图在主题切换稳定后采集并人工查看。无模型调用、无安装执行。补充证据见外部 `dsh-update-overview-20261028/toolbar/`;此前跨工作区Host验收边界不变。 + +### 统一检查更新:性能整改 + +统一检查改为DSH私有begin/check/end轮次,可信库存每轮读取一次并索引;逐目标复核保留,库存文件身份或上下文变化使整轮失效。同技能远端resolve每轮去重,Host实际并发最多3。轮次数量最多4、空闲60秒/硬上限30分钟;取消初始化时保留槽至真实构建结束,避免槽外堆积。原单项检查与升级准备完整验证不变;不新增Registry/SaaS协议或CLI命令。 + +真实临时文件系统10/100/500处安装:库存读取均1次,metadata读取30/300/1500次,库存stat43/403/2003次;快照与核验耗时35/186/838ms,仅为本机观测,不包含网络。Host受控远端对应resolve5/50/250次(每技能两位置),额外验证12并发调用实际远端不超过3;未测旧版500项墙钟耗时或生产SaaS负载。 + +最终插件build/typecheck/lint和636测试/12451断言通过;CLI共享核心build/typecheck/lint和809测试/3578断言通过。独立复审18项定向测试通过,无剩余阻断。覆盖库存ABA/原子替换/metadata变化、会话与来源上下文、TTL、取消和初始化槽位保护。 + +真实DSH最终包两轮12/12扫描通过;等待begin返回时取消,迟到响应不启动检查,随后重扫成功。混合结果/失败重试/详情往返/原升级确认取消及主题窄屏在同逻辑候选包验证,最终补丁只修初始化取消槽位。实际Host跨工作区切换仍未完成,组件竞态验证单独记录。无模型调用、无安装执行,47份本轮基线文件不变;历史release-checklist已在本轮前被调整,未覆盖用户状态。 + +最终包SHA256 `2befcc2fd11e9da294183afe8b9e5c3f3d9dfb291b0c0072114fc22e76fce130`,97个运行文件与包一致。外部证据 `dsh-update-overview-20261028/performance/summary.md`、`review.md`、`browser/acceptance.md`、`browser/final-validation.md`。未提交、推送或发布。 diff --git a/plugins/dsh/README.en.md b/plugins/dsh/README.en.md index ce204ede5..84d0b326c 100644 --- a/plugins/dsh/README.en.md +++ b/plugins/dsh/README.en.md @@ -238,3 +238,5 @@ Installation locations in the detail view expose secondary actions through a Mor Detail installation checks use a dismissible top-right notification. Ordinary success expires after five seconds; conflicts and failures remain dismissible. Repeated checks replace the notification, and leaving the skill clears it. Upgrade candidates and safety blocks stay in the installation row. Check notifications use a scope/version heading and one concise conclusion. Installation scope is directly visible without an advanced disclosure. Confirmation, progress and completion share a stable two-column layout (stacked on narrow screens), with a separate use action after completion. Default scope selection is unchanged. + +The installed page supports an explicit update check with up to three concurrent read-only requests and a 30-second timeout per installation. Progress, distinct upgradable skill counts, failed installation counts, filters, and failed-only retry are shown progressively. Opening details or leaving the list cancels pending checks; returning from details retains valid completed results. Source, session, workspace, or installation-reference changes invalidate old results. Details show checked target versions per location; execution still revalidates the target. Updates still require confirmation for the exact installation in details. diff --git a/plugins/dsh/README.md b/plugins/dsh/README.md index 613e6944e..f6130313f 100644 --- a/plugins/dsh/README.md +++ b/plugins/dsh/README.md @@ -239,3 +239,5 @@ dsh plugin --profile skillhub-test remove @astron-team/skillhub-dsh 详情标题旁“在官网查看”仅使用详情API返回的可选`webUrl`。字段缺失、null、空白或不安全时隐藏按钮,详情与安装照常使用。插件不再提供网站地址配置、不拼路由、不从Registry回退;旧`websiteUrl`配置忽略。开源服务端复用可信`SKILLHUB_PUBLIC_BASE_URL`生成完整地址,未配置合法网站基址则返回null。SaaS需单独同步此可选字段。 安装确认直接展示安装范围,默认范围规则不变。确认、进行中与成功共用稳定的双栏布局,小屏自动纵排;右侧在提交前显示等待提示,完成后使用按钮与进度条分开显示。 + +已安装页可主动“检查更新”,以最多 3 个并发检查当前可见的安装位置,并渐进显示进度、可更新技能数与失败位置数;支持关键词叠加全部/可更新/检查失败筛选及失败重试。每项检查最多等待 30 秒,失败不会视为已最新。打开详情或离开列表会取消在途检查,详情返回保留仍有效的结果;来源、会话、工作区或安装引用变化后旧结果失效;进入详情后按位置展示已检查的目标版本,执行前仍重新核验。检查只读,更新仍需在详情按具体位置确认。 diff --git a/plugins/dsh/src/client/index.tsx b/plugins/dsh/src/client/index.tsx index 005b30a95..298eb2a27 100644 --- a/plugins/dsh/src/client/index.tsx +++ b/plugins/dsh/src/client/index.tsx @@ -1,3 +1,4 @@ +import { installedContext } from './installed-context.js'; import { ManagementToolView, type ManagementViewServices } from './management-tool-view.js'; import { SkillDraftRetentions } from './use-skill-drafts.js'; import { newSkillConversation } from './use-skill-navigation.js'; @@ -255,7 +256,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { }, ({ renderSlot }) => renderSlot('skillhub.catalog', {}))); ctx.slots.inject('skillhub.catalog', () => ctx.slots.register({ name: 'skillhub.catalog', inject: sessionId => ({ installation: sessionId ? installationFor(sessionId, true) : undefined, - installed: sessionId ? { sessionId, management: managementFor(sessionId), skillUse: useSkills.catalogServices(sessionId), upgradeRequests, removalRequests, compatibility: () => ctx.remote.skillhub.getCompatibility(), + installed: sessionId ? { sessionId, context: installedContext(() => ({ scope: ctx.sessions.scope(SessionId(sessionId)), cwd: ctx.sessions.list.getSnapshot().byId[SessionId(sessionId)]?.cwd, active: !!ctx.sessions.list.getSnapshot().byId[SessionId(sessionId)]?.retainedBy.mainView }), listener => ctx.sessions.list.subscribe(listener)), get management() { return managementFor(sessionId); }, skillUse: useSkills.catalogServices(sessionId), upgradeRequests, removalRequests, compatibility: () => ctx.remote.skillhub.getCompatibility(), operation: installationFor(sessionId).operation, recoverOperation: async input => { const scope = ctx.sessions.scope(SessionId(sessionId)); @@ -284,6 +285,18 @@ export async function apply(ctx: Context): Promise<() => Promise> { const scope = ctx.sessions.scope(SessionId(sessionId)); if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); return withSessionRemote(scope, remote => remote.skillhub.getInstalledDetail(revision, itemKey, signal)); + }, beginInstalledUpdateScan: async (revision, signal) => { + const scope = ctx.sessions.scope(SessionId(sessionId)); + if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); + return withSessionRemote(scope, remote => remote.skillhub.beginInstalledUpdateScan(revision, signal)); + }, checkInstalledUpdateScan: async (revision, scanId, itemKey, signal) => { + const scope = ctx.sessions.scope(SessionId(sessionId)); + if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); + return withSessionRemote(scope, remote => remote.skillhub.checkInstalledUpdateScan(revision, scanId, itemKey, signal)); + }, endInstalledUpdateScan: async (revision, scanId) => { + const scope = ctx.sessions.scope(SessionId(sessionId)); + if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); + return withSessionRemote(scope, remote => remote.skillhub.endInstalledUpdateScan(revision, scanId)); }, checkUpdate: async (revision, itemKey, signal) => { const scope = ctx.sessions.scope(SessionId(sessionId)); if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); diff --git a/plugins/dsh/src/client/installed-context.ts b/plugins/dsh/src/client/installed-context.ts new file mode 100644 index 000000000..a4bf173a0 --- /dev/null +++ b/plugins/dsh/src/client/installed-context.ts @@ -0,0 +1,13 @@ +/** A monotonic read context prevents A → B → A from reviving earlier scans. */ +export function installedContext(read: () => { scope: unknown; cwd: string | undefined; active: boolean }, subscribe: (listener: () => void) => () => void) { + let previous = read(); + let generation = 0; + const getSnapshot = () => { + const next = read(); + if (next.scope !== previous.scope || next.cwd !== previous.cwd || next.active !== previous.active) { + previous = next; generation++; + } + return generation; + }; + return { getSnapshot, subscribe: (listener: () => void) => subscribe(() => { getSnapshot(); listener(); }) }; +} diff --git a/plugins/dsh/src/client/installed-skills.tsx b/plugins/dsh/src/client/installed-skills.tsx index d446cf78d..420ed12b7 100644 --- a/plugins/dsh/src/client/installed-skills.tsx +++ b/plugins/dsh/src/client/installed-skills.tsx @@ -1,9 +1,10 @@ +import { checkInstalledUpdates, updateFailed, type UpdateResult } from './update-overview.js'; import { SkillWebsiteLink } from './skill-website-link.js'; import { groupManagementItems, InstallationManagement, type ManagementViewServices } from './management-tool-view.js'; import { SkillPrimaryActions, skillInstallationSummary } from './skill-primary-actions.js'; import type { SkillUseServices } from './use-skill.js'; import { CardSkeletons } from './loading-layout.js'; -import { useState, useRef, useLayoutEffect, type RefObject } from 'react'; +import { useState, useRef, useLayoutEffect, useSyncExternalStore, type RefObject } from 'react'; import { useQuery } from '@tanstack/react-query'; import type { RemoteResult, TypertRemoteNamespaceMap } from '@deepseek-ai/dsh-typert-protocol'; import type { InstalledSkillList, InstalledSkillDetail, InstalledUpdateCheck, SkillHubConfig } from '../host/types.js'; @@ -19,16 +20,25 @@ import { SkillAvatar } from './skill-card.js'; export interface InstalledServices extends UpgradeServices, RemovalServices { management?: ManagementViewServices; sessionId: string; + context?: { getSnapshot(): number; subscribe(listener: () => void): () => void }; skillUse?: SkillUseServices; list(sourceRevision: string, signal: AbortSignal): Promise>; detail(sourceRevision: string, itemKey: string, signal: AbortSignal): Promise>; + beginInstalledUpdateScan(sourceRevision: string, signal: AbortSignal): Promise>; + checkInstalledUpdateScan(sourceRevision: string, scanId: string, itemKey: string, signal: AbortSignal): Promise>; + endInstalledUpdateScan(sourceRevision: string, scanId: string): Promise>; checkUpdate(sourceRevision: string, itemKey: string, signal: AbortSignal): Promise>; } type Item = InstalledSkillList['items'][number]; +const noContext = { getSnapshot: () => 0, subscribe: () => () => {} }; export function InstalledSkills({ services, sourceRevision, source, remote, modes, scrollContainer, navigation, onInstall }: { services: InstalledServices; sourceRevision: string; source: string; remote: TypertRemoteNamespaceMap['skillhub']; modes: SkillHubConfig['detailTabs']; scrollContainer: RefObject; navigation: InstalledNavigation; onInstall?(item: Item): void; onRemove?(item: Item): void; onUpgrade?(item: Item): void; }) { + const context = services.context ?? noContext; + const generation = useSyncExternalStore(context.subscribe, context.getSnapshot, context.getSnapshot); + const contextKey = JSON.stringify([services.sessionId, sourceRevision, generation]); + const resultContext = useRef(contextKey); const [keyword, setKeyword] = useState(navigation.keyword); const [selected, setSelected] = useState(navigation.selected); const heading = useRef(null); @@ -44,13 +54,13 @@ export function InstalledSkills({ services, sourceRevision, source, remote, mode if (scrollContainer.current) scrollContainer.current.scrollTop = listScroll.current; } }, [selected, scrollContainer]); - const query = useQuery({ queryKey: ['skillhub-installed', services.sessionId, sourceRevision], retry: false, + const query = useQuery({ queryKey: ['skillhub-installed', services.sessionId, sourceRevision, ...(services.context ? [generation] : [])], retry: false, queryFn: async ({ signal }) => { const response = await services.list(sourceRevision, signal); if (!response.ok) throw new Error('会话或来源已变化,请重新读取已安装技能。'); return response.value; } }); - const detail = useQuery({ ...readCacheOptions, queryKey: ['skillhub-installed-detail', services.sessionId, sourceRevision, selected?.itemKey], + const detail = useQuery({ ...readCacheOptions, queryKey: ['skillhub-installed-detail', services.sessionId, sourceRevision, selected?.itemKey, ...(services.context ? [generation] : [])], enabled: !!selected, retry: false, queryFn: async ({ signal }) => { const response = await services.detail(sourceRevision, selected!.itemKey, signal); if (!response.ok) throw new Error('安装记录已变化或暂时无法读取,请返回列表刷新。'); @@ -61,6 +71,73 @@ export function InstalledSkills({ services, sourceRevision, source, remote, mode const actions = (items: Item[], label?: string) => { const identity = items[0]; if (identity) { listScroll.current = scrollContainer.current?.scrollTop ?? 0; setSelected(identity); } } : undefined} label={label} summaryVisible={!label} />; + const [results, setResults] = useState>({}); + const [filter, setFilter] = useState('all'); + const [progress, setProgress] = useState({ done: 0, total: 0, running: false }); + const scan = useRef(null); + const inventoryKey = JSON.stringify((query.data?.items ?? []).map(item => item.itemKey).sort()); + useLayoutEffect(() => { + scan.current?.abort(); scan.current = null; + const contextChanged = resultContext.current !== contextKey; + resultContext.current = contextKey; + if (contextChanged) { setSelected(null); setKeyword(''); setFilter('all'); } + setResults(previous => contextChanged ? {} : Object.fromEntries(Object.entries(previous).filter(([key]) => (query.data?.items ?? []).some(item => item.itemKey === key)))); + setProgress({ done: 0, total: 0, running: false }); + return () => { scan.current?.abort(); scan.current = null; }; + }, [inventoryKey, contextKey]); + useLayoutEffect(() => { + if (selected) { scan.current?.abort(); scan.current = null; setProgress(previous => ({ ...previous, running: false })); } + }, [selected]); + const startCheck = (retry = false) => { + if (scan.current || query.isFetching || query.isError) return; + const keys = (query.data?.items ?? []).map(item => item.itemKey).filter(key => !retry || updateFailed(results[key])); + if (!keys.length) return; + const controller = new AbortController(); scan.current = controller; + const scanGeneration = context.getSnapshot(); + setResults(previous => Object.fromEntries(Object.entries(previous).filter(([key]) => !keys.includes(key)))); + setProgress({ done: 0, total: keys.length, running: true }); + void (async () => { + let scanId: string | undefined; + const end = () => { if (scanId) void services.endInstalledUpdateScan(sourceRevision, scanId).catch(() => {}); }; + controller.signal.addEventListener('abort', end, { once: true }); + try { + const begun = await services.beginInstalledUpdateScan(sourceRevision, controller.signal); + if (!begun.ok) throw new Error('scan failed'); + scanId = begun.value.scanId; + controller.signal.throwIfAborted(); + const accepted = new Set(begun.value.itemKeys); + const stale = () => { + controller.abort(); + if (scan.current === controller && context.getSnapshot() === scanGeneration) { + setResults(Object.fromEntries(keys.map(key => [key, { state: 'failed' as const }]))); + setProgress({ done: keys.length, total: keys.length, running: false }); + } + }; + await checkInstalledUpdates(keys, async (key, signal) => { + if (context.getSnapshot() !== scanGeneration) { controller.abort(); throw new Error('context changed'); } + if (!accepted.has(key)) { stale(); throw new Error('installed record changed'); } + const response = await services.checkInstalledUpdateScan(sourceRevision, scanId!, key, signal); + if (!response.ok) { if (response.error.code === 'skillhub/context-stale') stale(); throw new Error('check failed'); } + return response.value; + }, controller.signal, (key, result) => { + if (scan.current !== controller || context.getSnapshot() !== scanGeneration) return; + setResults(previous => ({ ...previous, [key]: result })); + setProgress(previous => ({ ...previous, done: previous.done + 1 })); + }); + } catch { + if (scan.current === controller && !controller.signal.aborted) { + setResults(previous => ({ ...previous, ...Object.fromEntries(keys.map(key => [key, { state: 'failed' as const }])) })); + setProgress(previous => ({ ...previous, done: keys.length })); + } + } finally { controller.signal.removeEventListener('abort', end); end(); } + })().finally(() => { + if (scan.current === controller) { scan.current = null; setProgress(previous => ({ ...previous, running: false })); } + }); + }; + const allGroups = groupManagementItems(query.data?.items ?? []); + const upgradable = allGroups.filter(items => items.some(item => results[item.itemKey]?.state === 'upgradable')).length; + const failures = (query.data?.items ?? []).filter(item => updateFailed(results[item.itemKey])).length; + const detailVerified = !!detail.data && !detail.isError && !detail.isFetching; if (selected) return
@@ -73,29 +150,42 @@ export function InstalledSkills({ services, sourceRevision, source, remote, mode : detail.isError ?

{detail.error.message}

: detail.data.content.state === 'local-only' ?

远端说明暂不可用,可在管理安装中查看本地状态。

: { void detail.refetch(); }} cacheIdentity={JSON.stringify([services.sessionId, sourceRevision, selected.namespace, selected.slug, detail.data.content.detail.version])} onContextStale={() => { void detail.refetch(); }} />} - +
; const term = keyword.trim().toLocaleLowerCase(); - const groups = groupManagementItems(query.data?.items ?? []).filter(items => !term || items.some(item => `@${item.namespace}/${item.slug} ${item.version}`.toLocaleLowerCase().includes(term))); + const groups = allGroups.filter(items => filter === 'all' || items.some(item => filter === 'updates' ? results[item.itemKey]?.state === 'upgradable' : updateFailed(results[item.itemKey]))).filter(items => !term || items.some(item => `@${item.namespace}/${item.slug} ${item.version}`.toLocaleLowerCase().includes(term))); return
-
+
+
+ {([['all', '全部'], ['updates', '可更新'], ['failed', '检查失败']] as const).map(([value, label]) => )} +
+

{progress.total > 0 ? `${progress.running ? '检查中' : progress.done < progress.total ? '已停止' : '已检查'} ${progress.done}/${progress.total}${upgradable ? ` · ${upgradable} 个技能可更新` : ''}${failures ? ` · ${failures} 处检查失败` : ''}` : `${groups.length} 个技能`}

+
{query.isPending ? : query.isError ?

{query.error.message}

: <> {(!query.data.complete || query.data.unavailable.length > 0) &&

部分安装记录无法读取,列表可能不完整。

} -

当前显示 {groups.length} 个技能。

- {!groups.length ?

{term ? '没有匹配的技能。' : verified ? '当前来源暂无已安装技能。' : '暂未读取到安装记录。'}

+ {!groups.length ?

{term || filter !== 'all' ? '没有匹配的技能。' : verified ? '当前来源暂无已安装技能。' : '暂未读取到安装记录。'}

:
{groups.map(items => { const identity = items[0]!; return

{identity.slug}

@{identity.namespace}/{identity.slug}
- {skillInstallationSummary(items)} + {skillInstallationSummary(items)} + {items.some(item => results[item.itemKey]?.state === 'upgradable') &&

{items.length > 1 ? '多位置安装有更新' : `可更新至 ${(() => { const result = results[identity.itemKey]; return result && 'candidateVersion' in result ? result.candidateVersion ?? '新版本' : '新版本'; })()}`}

} + {items.some(item => results[item.itemKey]?.state === 'blocked') &&

更新需处理,请查看安装状态。

} + {items.some(item => updateFailed(results[item.itemKey])) &&

部分安装位置检查失败,可重试。

} +
{actions(items)} + }}>{items.some(item => results[item.itemKey]?.state === 'upgradable') ? '查看更新' : '详情'}
; })}
} } diff --git a/plugins/dsh/src/client/installed-styles.tsx b/plugins/dsh/src/client/installed-styles.tsx index 9b92aae67..f38504466 100644 --- a/plugins/dsh/src/client/installed-styles.tsx +++ b/plugins/dsh/src/client/installed-styles.tsx @@ -3,9 +3,15 @@ import { NativeControlStyles } from './native-control-styles.js'; export function InstalledStyles() { return <>