Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

refactor: trim model and experimental internals (#813)

Mao Mreef148b237ad
diff --git a/docs/audit/pkg-model-experimental.md b/docs/audit/pkg-model-experimental.md
index 6c9cae75..a74e3545 100644
--- a/docs/audit/pkg-model-experimental.md
+++ b/docs/audit/pkg-model-experimental.md
@@ -8,7 +8,7 @@
### dsh-tauri-model
-`shrink: modelStyles / welcomeStyles / onboardingStyles / onboardingDialogStyles 是 84 行人工维护的「键 → 哈希类名」映射表,必须与上面的 CSS 模板字符串手工对齐;四张表都能从 CSS 文本推导。` 写法:`const modelStyles = Object.fromEntries([...MODELS_CSS.matchAll(/\.(zGbnIq_\w+)/g)].map(m => [m[1].slice(7), m[1]]))`(`prefix` 换成 `zGbnIqw_`/`zGbnIqo_`/`zGbnIqd_` 各 1 行;`hiddenLabel` 这类驼峰键与类名本来就一一对应)。漂移已经发生过:`org`/`w3` 两个键指向的类名在 CSS 里根本不存在,`hiddenLabel`/`switchThumb` 两个键(规则在 `styles.ts:611`、`styles.ts:622` 的 media 块内)零消费者。 [packages/dsh-tauri-model/src/client/models/styles.ts:779-868] (-80 LOC)
+`shrink: modelStyles / welcomeStyles / onboardingStyles / onboardingDialogStyles 是 84 行人工维护的「键 → 哈希类名」映射表,必须与上面的 CSS 模板字符串手工对齐;四张表都能从 CSS 文本推导。` 写法:`const modelStyles = Object.fromEntries([...MODELS_CSS.matchAll(/\.(zGbnIq_(\w+))/g)].map(([, className, key]) => [key, className]))`(`prefix` 换成 `zGbnIqw_`/`zGbnIqo_`/`zGbnIqd_` 各 1 行;`hiddenLabel` 这类驼峰键与类名本来就一一对应)。漂移已经发生过:`org`/`w3` 两个键指向的类名在 CSS 里根本不存在,`hiddenLabel`/`switchThumb` 两个键(规则在 `styles.ts:611`、`styles.ts:622` 的 media 块内)零消费者。 [packages/dsh-tauri-model/src/client/models/styles.ts:779-868] (-80 LOC)
`shrink: packages/dsh-tauri-model/src/client/types/remotes.ts 前 10 行 + LlmModelDiscoveryRequest + LlmDiscoveredModel 是对 packages/dsh-tauri-ui/src/client/types/remotes.ts 的逐字重复。` `dsh-tauri-ui/client` 已经发布这几张类型(`packages/dsh-tauri-ui/src/client/index.ts:23` 的 `export * from './types/remotes'`),且已是本包的直接依赖(`packages/dsh-tauri-model/package.json:73`)与本包 src 里到处在 import 的入口(`ModelInputTypes.tsx:4` 等 13 处)。改成 `export type { JsonValue, RemoteFailure, RemoteResult, LlmModelDiscoveryRequest } from 'dsh-tauri-ui/client'`,`LlmDiscoveredModel` 换成 `interface LlmDiscoveredModel extends UILlmDiscoveredModel { inputModalities?: readonly string[] }`(本包只多这一个字段)。检索式:`JsonValue|RemoteFailure|RemoteResult|LlmModelDiscoveryRequest`(全仓)。 [packages/dsh-tauri-model/src/client/types/remotes.ts:1-10,52-57] (-14 LOC)
@@ -77,4 +77,15 @@ $body = ($files | Where-Object { $_ -notmatch 'styles\.ts$' -and $_ -notmatch '\
# 对每个候选 key 判 $body -notmatch "\b$k\b"
```
-net: -456 lines, -2 deps possible.
+## 执行复核(2026-09-30)
+
+- 已执行:CSS 派生类名映射、复用远端/领域类型、组件 props 就地声明、测试夹具迁入 test-only 目录、删除内部 `withPath`/`presetTableSize`;既有组件类型出口名称保留。
+- 已执行:删除从未 arm 的客户端摘要重试及其孤立的 service/store 子树(`fetchSummary` 唯一调用者是该调度器和无人调用的 `expectTurn`);保留实时读数轮询、`getSummary` HTTP API 及宿主账本能力。
+- 已执行:删除无生产调用的回滚写盘辅助实现、`capture.begin/pending`、`snapshot.generation/read`、`retention.describe` 与孤儿注释;测试改走生产 `start/awaitBegin`、账本、refs 与持久化结果,未删除生产行为断言。
+- 协议修正:`TurnSummary.hasBaseline` 现有契约为可选,而生成 DTO 为必选。复用 DTO 时仍保留可选字段和 interface 形状;不得按原建议直接 alias 收窄。增加旧/新载荷编译检查。
+- `keep:` `MODEL_EXTRAS_KEYS` 与组件 props 类型仍有 UI barrel 出口;`runningChangesHooks`/`turn:captured` 注释明确承诺扩展生命周期事件;共享原因码 `RUNNING_CHANGES_REASON_UNSAFE_PATH` 仍保留协议定义,`hookable` 依赖不删。
+- `keep:` `createSettingsSchemaOperations` 提供可脱离接收者调用的函数,原 service 的 `hasPath/deletePath` 使用 `this`。直接替换会破坏公开注入面的调用语义。
+- `keep:` `CaptureLimits` 用小夹具验证真实容量边界;`queue.size`/`lock.lockPath` 守护尾链清理与旧锁围栏安全;`commonDir` 省略值确有调用/测试,fallback 负责继承源仓排除规则。
+- `keep:` `retention.measure` 的原逐目录 best-effort 遍历。原建议递归 `readdir` 后只取 `isFile()` 会改变符号链接计量与子目录读取失败语义,已有回归覆盖,不为少几行改行为。
+
+原 `net: -456 lines, -2 deps possible` 是审计预估(包含上述撤回项及重叠),不是执行结果;本次未删依赖。
diff --git a/packages/dsh-tauri-experimental/src/client/constants/index.ts b/packages/dsh-tauri-experimental/src/client/constants/index.ts
index c878d2f5..b9ed8c85 100644
--- a/packages/dsh-tauri-experimental/src/client/constants/index.ts
+++ b/packages/dsh-tauri-experimental/src/client/constants/index.ts
@@ -26,7 +26,6 @@ export const RUNNING_CHANGES_COUNTS_STYLE_ID = `${PLUGIN_ID}/ChangeCounts.module
/** effect 标签(诊断/日志)。 */
export const RUNNING_CHANGES_LOCALE_EFFECT = `${PLUGIN_ID}: locale`
-export const RUNNING_CHANGES_SUMMARY_EFFECT = `${PLUGIN_ID}: summary retry`
export const RUNNING_CHANGES_RUNNING_CHIP_EFFECT = `${PLUGIN_ID}: running chip`
export const PASTE_COLLAPSE_EFFECT = `${PLUGIN_ID}: paste collapse`
@@ -35,19 +34,3 @@ export const PASTE_COLLAPSE_EFFECT = `${PLUGIN_ID}: paste collapse`
* `data-composer-chip` 值(C 浏览器层的断言锚点)。
*/
export const PASTE_CHIP_SOURCE = `${PLUGIN_ID}-paste`
-
-/**
- * 「该轮已结束但账本还没有记录」时的重试参数(指数退避:700ms → 1.4s → 2.8s → 5s 封顶,
- * 12 次累计约 50s)。
- *
- * after 快照在 turn/end 之后**后台结算**:先是队列里可能在飞的实时读数,再是 after 自身的
- * `git add --all`。实测大仓库上首次 add 要 6–20s,因此短窗口会让手动停止以及首次快照的 turn
- * 迟迟等不到账本落定。退避到 5s 既覆盖慢仓库,又不会在常见情况下持续打请求——一旦账本出现
- * 该轮的记录就立刻停止重试。
- */
-export const RUNNING_CHANGES_SUMMARY_RETRY_DELAY_MS = 700
-export const RUNNING_CHANGES_SUMMARY_RETRY_MAX_DELAY_MS = 5000
-export const RUNNING_CHANGES_SUMMARY_MAX_RETRIES = 12
-
-/** 重试调度的检查节拍(由 register 的 controller.interval 承担)。 */
-export const RUNNING_CHANGES_SUMMARY_TICK_MS = 400
diff --git a/packages/dsh-tauri-experimental/src/client/index.ts b/packages/dsh-tauri-experimental/src/client/index.ts
index 91d8867f..2e299fd6 100644
--- a/packages/dsh-tauri-experimental/src/client/index.ts
+++ b/packages/dsh-tauri-experimental/src/client/index.ts
@@ -13,12 +13,10 @@ import {
PLUGIN_ID,
RUNNING_CHANGES_LOCALE_EFFECT,
RUNNING_CHANGES_RUNNING_CHIP_EFFECT,
- RUNNING_CHANGES_SUMMARY_EFFECT,
} from './constants'
import { locale } from './locales'
import { pasteCollapseFeature } from './register/paste-collapse'
import { runningChipFeature } from './register/running-chip'
-import { summaryFeature } from './register/summary'
export type * from './types'
@@ -30,7 +28,6 @@ export const inject = ['slots', 'locale', 'sessions']
export function apply(ctx: ClientContext): void {
ctx.effect(locale.registerLocale, RUNNING_CHANGES_LOCALE_EFFECT)
- ctx.effect(summaryFeature, RUNNING_CHANGES_SUMMARY_EFFECT)
ctx.effect(runningChipFeature, RUNNING_CHANGES_RUNNING_CHIP_EFFECT)
ctx.effect(pasteCollapseFeature, PASTE_COLLAPSE_EFFECT)
}
diff --git a/packages/dsh-tauri-experimental/src/client/register/summary.ts b/packages/dsh-tauri-experimental/src/client/register/summary.ts
deleted file mode 100644
index 1e125c5f..00000000
--- a/packages/dsh-tauri-experimental/src/client/register/summary.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * client/register/summary.ts — 摘要重试调度(副作用由 controller 托管)。
- *
- * after 快照在 turn/end 之后**后台结算**(大仓库可能十几秒才落账),因此刚结束的这一轮
- * 可能暂时没有账本记录。判据是「账本还没有这一轮」而不是「读数看不到」:该轮确实没有改动时
- * 账本会写一条空记录,那种情况不该继续重试。
- *
- * 定时器与重试记账都属于 controller 的可托管资源,组件里不再裸写 `setTimeout`。
- */
-
-import type { ClientContext } from 'dsh-tauri/client'
-import { defineRegister } from 'dsh-tauri/client'
-import {
- RUNNING_CHANGES_SUMMARY_MAX_RETRIES,
- RUNNING_CHANGES_SUMMARY_RETRY_DELAY_MS,
- RUNNING_CHANGES_SUMMARY_RETRY_MAX_DELAY_MS,
- RUNNING_CHANGES_SUMMARY_TICK_MS,
-} from '../constants'
-import { fetchSummary } from '../service/summary'
-import { store } from '../store'
-import { hasTurnRecord, summaryRetryDelayMs } from '../utils/format'
-
-export const summaryFeature = defineRegister<ClientContext>((controller) => {
- /** 每会话已重试次数与下次允许时刻(controller 闭包状态,卸载即丢弃)。 */
- const attempts = new Map<string, number>()
- const nextAt = new Map<string, number>()
-
- const forget = (sessionId: string): void => {
- attempts.delete(sessionId)
- nextAt.delete(sessionId)
- }
-
- controller.interval(() => {
- const now = Date.now()
- for (const [sessionId, state] of Object.entries(store.runningChanges.$state.bySession)) {
- const turn = state.awaitingTurn
- if (turn === null || state.status !== 'ready' || state.summary === null || !state.summary.isGit) {
- forget(sessionId)
- continue
- }
- if (hasTurnRecord(state.summary, turn)) {
- forget(sessionId)
- continue
- }
- const count = attempts.get(sessionId) ?? 0
- if (count >= RUNNING_CHANGES_SUMMARY_MAX_RETRIES || now < (nextAt.get(sessionId) ?? 0))
- continue
- attempts.set(sessionId, count + 1)
- nextAt.set(sessionId, now + summaryRetryDelayMs(count, RUNNING_CHANGES_SUMMARY_RETRY_DELAY_MS, RUNNING_CHANGES_SUMMARY_RETRY_MAX_DELAY_MS))
- void fetchSummary({ sessionId, force: true })
- }
- }, RUNNING_CHANGES_SUMMARY_TICK_MS)
-})
diff --git a/packages/dsh-tauri-experimental/src/client/service/summary.ts b/packages/dsh-tauri-experimental/src/client/service/summary.ts
deleted file mode 100644
index c91ded4c..00000000
--- a/packages/dsh-tauri-experimental/src/client/service/summary.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * client/service/summary.ts — 摘要 Query/Action(唯一与 store 的状态迁移出口)。
- */
-
-import { getSummary } from '../apis'
-import { store } from '../store'
-import { sessionStateOf } from '../store/modules/session.utils'
-
-/**
- * 拉取(或强制刷新)某会话摘要并写入 store。
- *
- * 不做在飞请求合并:`status === 'loading'` 本身就是合并判据,同一会话的并发请求
- * 因此只会打同一份摘要,且 service 不持有模块级可变状态。
- */
-export async function fetchSummary(input: { sessionId: string | undefined, force?: boolean }): Promise<void> {
- const { sessionId, force = false } = input
- if (sessionId === undefined)
- return
- const current = sessionStateOf(store.runningChanges.$state, sessionId)
- if (!force && (current.status === 'ready' || current.status === 'loading'))
- return
- store.runningChanges.patch(sessionId, { status: 'loading', error: null })
- try {
- const summary = await getSummary({ sessionId })
- store.runningChanges.patch(sessionId, { status: 'ready', summary, error: null })
- }
- catch (error) {
- store.runningChanges.patch(sessionId, { status: 'error', error: messageOf(error) })
- }
-}
-
-/**
- * 登记「本轮在等账本落定」,并在该会话尚未取过摘要时拉一次。
- *
- * after 快照在 turn/end 之后后台结算,读数可能先于账本落地;
- * 后续重试由 `register/summary.ts` 的调度器按账本是否已有该轮决定。
- */
-export async function expectTurn(input: { sessionId: string | undefined, turn: number | undefined }): Promise<void> {
- const { sessionId, turn } = input
- if (sessionId === undefined)
- return
- const awaitingTurn = turn ?? null
- const current = sessionStateOf(store.runningChanges.$state, sessionId)
- if (current.awaitingTurn !== awaitingTurn)
- store.runningChanges.patch(sessionId, { awaitingTurn })
- // 已有摘要或正在取就不重复请求(并发调用因此只打一份摘要)。
- if (current.status !== 'ready' && current.status !== 'loading')
- await fetchSummary({ sessionId })
-}
-
-// --- internal ---
-
-/** 错误归一:`Error` 取 message,其余 `String()`(含响应体错误)。 */
-function messageOf(error: unknown): string {
- return error instanceof Error ? error.message : String(error)
-}
diff --git a/packages/dsh-tauri-experimental/src/client/store/index.ts b/packages/dsh-tauri-experimental/src/client/store/index.ts
deleted file mode 100644
index e498337d..00000000
--- a/packages/dsh-tauri-experimental/src/client/store/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { runningChanges } from './modules/session'
-
-export const store = {
- runningChanges,
-}
diff --git a/packages/dsh-tauri-experimental/src/client/store/modules/session.ts b/packages/dsh-tauri-experimental/src/client/store/modules/session.ts
deleted file mode 100644
index 680d2e77..00000000
--- a/packages/dsh-tauri-experimental/src/client/store/modules/session.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * store/modules/session.ts — 每会话摘要缓存(valtio-define 协议)。
- *
- * 状态只放数据与同步迁移;请求与重试记账分别在 `service/` 与 `register/`。
- */
-
-import type { RunningChangesSessionState, RunningChangesUiState } from './session.types'
-import { defineStore } from 'dsh-tauri/client'
-import { EMPTY_SESSION_STATE } from './session.utils'
-
-export const runningChanges = defineStore({
- state: (): RunningChangesUiState => ({ bySession: {} }),
- actions: {
- /** 更新某会话状态(merge 语义)。 */
- patch(sessionId: string | undefined, patch: Partial<RunningChangesSessionState>): void {
- if (sessionId === undefined)
- return
- this.bySession[sessionId] = { ...(this.bySession[sessionId] ?? EMPTY_SESSION_STATE), ...patch }
- },
- },
-})
diff --git a/packages/dsh-tauri-experimental/src/client/store/modules/session.types.ts b/packages/dsh-tauri-experimental/src/client/store/modules/session.types.ts
deleted file mode 100644
index 7d35cb16..00000000
--- a/packages/dsh-tauri-experimental/src/client/store/modules/session.types.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { SessionSummary } from '../../types'
-
-/** 每会话客户端状态(只放数据;请求与重试记账在 service/ 与 register/)。 */
-export interface RunningChangesSessionState {
- status: 'idle' | 'loading' | 'ready' | 'error'
- summary: SessionSummary | null
- error: string | null
- /**
- * 已结束、正等账本落定的 turn 号;账本尚无该轮记录时由 register 的调度器重拉。
- * null 表示当前没有在等账本(例如非 Git 工作区)。
- */
- awaitingTurn: number | null
-}
-
-/** 每会话状态容器。 */
-export interface RunningChangesUiState {
- bySession: Record<string, RunningChangesSessionState>
-}
diff --git a/packages/dsh-tauri-experimental/src/client/store/modules/session.utils.ts b/packages/dsh-tauri-experimental/src/client/store/modules/session.utils.ts
deleted file mode 100644
index 752a71c2..00000000
--- a/packages/dsh-tauri-experimental/src/client/store/modules/session.utils.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { RunningChangesSessionState } from './session.types'
-
-/**
- * 无缓存会话的空白态。
- *
- * 引用必须稳定(模块级常量):每次对缺席会话都返回同一个对象,订阅方才不会因为
- * 「每次读到新对象」而无休止重渲染。
- */
-export const EMPTY_SESSION_STATE: RunningChangesSessionState = {
- status: 'idle',
- summary: null,
- error: null,
- awaitingTurn: null,
-}
-
-/** 取某会话的状态切片(无则空白态)。对状态容器结构开放,调用方无需断言。 */
-export function sessionStateOf<C extends { bySession: Record<string, unknown> }>(
- state: C,
- sessionId: string | undefined,
-): RunningChangesSessionState {
- if (sessionId === undefined)
- return EMPTY_SESSION_STATE
- return (state.bySession[sessionId] as RunningChangesSessionState | undefined) ?? EMPTY_SESSION_STATE
-}
diff --git a/packages/dsh-tauri-experimental/src/client/types/index.test.ts b/packages/dsh-tauri-experimental/src/client/types/index.test.ts
new file mode 100644
index 00000000..05703a4b
--- /dev/null
+++ b/packages/dsh-tauri-experimental/src/client/types/index.test.ts
@@ -0,0 +1,25 @@
+import type { SessionSummary, TurnSummary } from './index'
+import { expect, it } from 'vitest'
+
+it('accepts legacy summary payloads without hasBaseline and current payloads with it', () => {
+ const turn: TurnSummary = {
+ turn: 1,
+ fileCount: 0,
+ insertions: 0,
+ deletions: 0,
+ unavailable: null,
+ truncated: false,
+ files: [],
+ skippedOversized: [],
+ skippedNestedRepos: [],
+ }
+ const summary: SessionSummary = {
+ sessionId: 'session-1',
+ isGit: true,
+ workspaceRoot: '/workspace',
+ unavailableReason: null,
+ turns: [turn, { ...turn, hasBaseline: false }],
+ }
+
+ expect(summary.turns.map(item => item.hasBaseline)).toEqual([undefined, false])
+})
diff --git a/packages/dsh-tauri-experimental/src/client/types/index.ts b/packages/dsh-tauri-experimental/src/client/types/index.ts
index 58da6b8d..ad07261c 100644
--- a/packages/dsh-tauri-experimental/src/client/types/index.ts
+++ b/packages/dsh-tauri-experimental/src/client/types/index.ts
@@ -1,62 +1,19 @@
-/**
- * client/types/index.ts — 客户端跨模块共享的线协议与领域模型。
- *
- * 单一模块专属的类型与所属模块同目录同名(`store/modules/session.types.ts`、
- * `components/running-changes-chip.types.ts`…),此目录只留被多个模块共享的类型。
- */
+import type { LiveSnapshot as ApiLiveSnapshot, TurnFileChange as ApiTurnFileChange, SummaryPayload } from '../apis/index.type'
-/** 单文件变更状态:本 turn 新增 / 修改 / 删除。 */
-export type TurnFileStatus = 'A' | 'M' | 'D'
+export type { TurnFileStatus } from '../apis/index.type'
-/** 宿主 summary 路由返回的单文件差异。 */
-export interface TurnFileChange {
- path: string
- status: TurnFileStatus
- insertions: number | null
- deletions: number | null
- binary: boolean
-}
+export interface TurnFileChange extends ApiTurnFileChange {}
-/** 宿主 summary 路由返回的单 turn 记录。 */
-export interface TurnSummary {
- turn: number
- fileCount: number
- insertions: number
- deletions: number
- unavailable: string | null
- /** 该轮是否建立过快照基线(旧宿主不带该字段时视为 true,即保守地照常呈现)。 */
+export interface TurnSummary extends Omit<SummaryPayload['turns'][number], 'hasBaseline'> {
hasBaseline?: boolean
- truncated: boolean
- files: TurnFileChange[]
- /**
- * 因超过单文件上限而未纳入快照的路径。
- * 宿主只回传前若干条(载荷有界),因此必须按「计数」而不是「长度」呈现。
- */
- skippedOversized: string[]
- /** 被跳过的嵌套仓库目录(gitlink 内容未纳入快照)。 */
- skippedNestedRepos: string[]
}
-/** 宿主 summary 路由的完整载荷。 */
-export interface SessionSummary {
- sessionId: string
- isGit: boolean
- workspaceRoot: string | null
- unavailableReason: string | null
+export interface SessionSummary extends Omit<SummaryPayload, 'turns'> {
turns: TurnSummary[]
}
-/** 运行中实时读数(宿主 live 路由的载荷)。 */
-export interface LiveSnapshot {
- /** 是否有正在进行的 turn。 */
- active: boolean
- turn: number | null
- fileCount: number
- insertions: number
- deletions: number
-}
+export interface LiveSnapshot extends ApiLiveSnapshot {}
-/** 界面文案键(zh 为权威键集,en 必须逐键对齐)。 */
export type LocaleKey
= | 'runningChanged'
| 'binary'
diff --git a/packages/dsh-tauri-experimental/src/client/utils/format.test.ts b/packages/dsh-tauri-experimental/src/client/utils/format.test.ts
index 9085cdbe..f26f3396 100644
--- a/packages/dsh-tauri-experimental/src/client/utils/format.test.ts
+++ b/packages/dsh-tauri-experimental/src/client/utils/format.test.ts
@@ -1,32 +1,5 @@
-import type { SessionSummary, TurnSummary } from '../types'
import { describe, expect, it } from 'vitest'
-import { formatCounts, hasTurnRecord, summaryRetryDelayMs } from './format'
-
-function turnSummary(patch: Partial<TurnSummary> = {}): TurnSummary {
- return {
- turn: 1,
- fileCount: 1,
- insertions: 4,
- deletions: 3,
- unavailable: null,
- truncated: false,
- files: [{ path: 'src/driver.ts', status: 'M', insertions: 4, deletions: 3, binary: false }],
- skippedOversized: [],
- skippedNestedRepos: [],
- ...patch,
- }
-}
-
-function summary(patch: Partial<SessionSummary> = {}): SessionSummary {
- return {
- sessionId: 'session-1',
- isGit: true,
- workspaceRoot: 'C:/proj',
- unavailableReason: null,
- turns: [turnSummary()],
- ...patch,
- }
-}
+import { formatCounts } from './format'
describe('formatCounts', () => {
it('renders +N -M and falls back to the binary label', () => {
@@ -35,26 +8,3 @@ describe('formatCounts', () => {
expect(formatCounts({ insertions: null, deletions: null, binary: false }, 'binary')).toBe('+0 -0')
})
})
-
-describe('hasTurnRecord / summaryRetryDelayMs', () => {
- it('只看账本有没有这一轮的记录,不看界面是否可见', () => {
- expect(hasTurnRecord(null, 1)).toBe(false)
- expect(hasTurnRecord(summary(), undefined)).toBe(false)
- expect(hasTurnRecord(summary(), 1)).toBe(true)
- expect(hasTurnRecord(summary(), 7)).toBe(false)
- // 空记录(该轮确实没有改动)也算「已落账」:重试窗口据此停止,不再白等。
- expect(hasTurnRecord(summary({ turns: [turnSummary({ files: [], fileCount: 0 })] }), 1)).toBe(true)
- })
-
- it('重试等待时间 700ms 起指数退避、5s 封顶', () => {
- expect(summaryRetryDelayMs(0, 700, 5000)).toBe(700)
- expect(summaryRetryDelayMs(1, 700, 5000)).toBe(1400)
- expect(summaryRetryDelayMs(2, 700, 5000)).toBe(2800)
- expect(summaryRetryDelayMs(3, 700, 5000)).toBe(5000)
- expect(summaryRetryDelayMs(11, 700, 5000)).toBe(5000)
- // 异常入参(负数/非整数/NaN)不能算出荒唐的等待时间。
- expect(summaryRetryDelayMs(-1, 700, 5000)).toBe(700)
- expect(summaryRetryDelayMs(Number.NaN, 700, 5000)).toBe(700)
- expect(summaryRetryDelayMs(1.9, 700, 5000)).toBe(1400)
- })
-})
diff --git a/packages/dsh-tauri-experimental/src/client/utils/format.ts b/packages/dsh-tauri-experimental/src/client/utils/format.ts
index 760ec87e..561f274e 100644
--- a/packages/dsh-tauri-experimental/src/client/utils/format.ts
+++ b/packages/dsh-tauri-experimental/src/client/utils/format.ts
@@ -1,14 +1,5 @@
-/**
- * client/utils/format.ts — 纯函数:计数文本与账本落定判定。
- *
- * 全部为纯函数,便于单测直接锁定(plugin.baisc.md「优先测试纯函数」)。
- * 计数文本供 `ChangeCounts` 的 `title` 使用:视觉是分开着色的两个 span,
- * 但读屏/悬浮提示要拿到同一条「+N -M」文本。
- */
+import type { TurnFileChange } from '../types'
-import type { SessionSummary, TurnFileChange } from '../types'
-
-/** 单行 `+N -M` 文本;二进制显示 binaryLabel。 */
export function formatCounts(file: Pick<TurnFileChange, 'insertions' | 'deletions' | 'binary'>, binaryLabel: string): string {
if (file.binary)
return binaryLabel
@@ -16,28 +7,3 @@ export function formatCounts(file: Pick<TurnFileChange, 'insertions' | 'deletion
const deletions = file.deletions ?? 0
return `+${insertions} -${deletions}`
}
-
-/**
- * 账本里是否已经有这一轮的记录(**任何**记录,包括「文件数为 0」与「不可用」)。
- *
- * 重试窗口只该盯住「账本还没有这一轮」,而不是「界面暂时看不到」:
- * 前者是 after 快照还在后台结算(要等),后者可能是「这一轮确实没有改动」(等也没用,
- * 而且会把重试预算白白烧掉)。
- */
-export function hasTurnRecord(summary: SessionSummary | null, turn: number | undefined): boolean {
- if (summary === null || turn === undefined)
- return false
- return summary.turns.some(item => item.turn === turn)
-}
-
-/**
- * 第 `attempt` 次重试(0 起)的等待时间:700ms 起指数退避、封顶 5s。
- * @param attempt - 已失败的重试次数。
- * @param baseMs - 首次等待。
- * @param maxMs - 单次等待上限。
- * @returns 毫秒。
- */
-export function summaryRetryDelayMs(attempt: number, baseMs: number, maxMs: number): number {
- const safe = Number.isFinite(attempt) && attempt > 0 ? Math.floor(attempt) : 0
- return Math.min(baseMs * 2 ** safe, maxMs)
-}
diff --git a/packages/dsh-tauri-experimental/src/host/config/constants.ts b/packages/dsh-tauri-experimental/src/host/config/constants.ts
index a051e91a..217a30af 100644
--- a/packages/dsh-tauri-experimental/src/host/config/constants.ts
+++ b/packages/dsh-tauri-experimental/src/host/config/constants.ts
@@ -10,11 +10,9 @@ import {
RUNNING_CHANGES_REASON_EXPIRED,
RUNNING_CHANGES_REASON_GIT_REQUIRED,
RUNNING_CHANGES_REASON_SNAPSHOT_FAILED,
- RUNNING_CHANGES_REASON_UNSAFE_PATH,
RUNNING_CHANGES_REASON_WORKSPACE_BUSY,
} from '../../shared/constants'
-/** 私有快照仓中快照 ref 的命名空间前缀。 */
/** 每个工作区私有快照仓与每会话账本的存放目录(DSH_HOME 下)。 */
export const SNAPSHOT_FEATURE_DIR = PLUGIN_ID
@@ -36,41 +34,21 @@ export const MAX_TURN_RECORDS = 200
*/
export const MAX_FILE_BYTES = 64 * 1024 * 1024
-/** 单次快照的聚合字节上限;超过则该 turn 记 unavailable。 */
-/** 单 turn 允许纳入快照的最大文件数;超过即该 turn 记 unavailable。 */
-/** 一次预扫最多排除多少个超限文件;超过则该 turn 记 unavailable(避免 argv 爆炸)。 */
-/** 私有快照仓容量上限(MB);超过即整仓隔离重建(旧 turn 全部转过期)。 */
/** 单条 git 子进程的墙钟超时(快照/差异统计等重活)。 */
export const GIT_TIMEOUT_MS = 5 * 60 * 1000
-/** 资格探测的墙钟超时:探测结果挂在 pre-step 执行屏障上,不能用重活预算。 */
-/** 工作区解析结果缓存 TTL(冷未命中才同步探测,过期先回缓存值再后台刷新)。 */
-/** 工作区解析缓存的条目上限。 */
-/** 摘要路由返回给客户端的文件明细上限(更大的会话只给汇总与截断标记)。 */
-/** 摘要路由每条 turn 最多回传多少个「未纳入快照范围」的路径。 */
-/** 运行中实时读数的宿主端刷新间隔(客户端只读缓存值,轮询频率与 git 调用解耦)。 */
/** 会话 cwd 不在 Git worktree 内:不做快照。 */
export const REASON_GIT_REQUIRED = RUNNING_CHANGES_REASON_GIT_REQUIRED
-/** PATH 上没有 git:必须与「不是 Git 仓库」区分,否则用户会去 git init 一个不存在的 git。 */
/** 会话 cwd 是家目录/家目录祖先/盘根等系统目录:拒绝快照。 */
export const REASON_UNSAFE_WORKSPACE = 'RUNNING_CHANGES_UNSAFE_WORKSPACE'
-/** 快照文件数超限。 */
-/** 快照聚合字节超限。 */
-/** 超限文件太多,无法逐个排除(该轮不提供变更明细)。 */
/** 快照或统计过程失败(git 异常、仓库损坏等)。 */
export const REASON_SNAPSHOT_FAILED = RUNNING_CHANGES_REASON_SNAPSHOT_FAILED
/** 快照仓被隔离重建 / 手工删除,该 turn 的 refs 已不存在。 */
export const REASON_EXPIRED = RUNNING_CHANGES_REASON_EXPIRED
-/** 目标路径的父级是符号链接/junction,拒绝穿透(防路径逃逸)。 */
-export const REASON_UNSAFE_PATH = RUNNING_CHANGES_REASON_UNSAFE_PATH
-
-/** 目标路径当前是非空目录:不递归删除目录。 */
-export const REASON_NON_EMPTY_DIR = 'RUNNING_CHANGES_NON_EMPTY_DIR'
-
/** 工作区被另一个宿主进程占用(跨进程锁等待超时)。 */
export const REASON_WORKSPACE_BUSY = RUNNING_CHANGES_REASON_WORKSPACE_BUSY
diff --git a/packages/dsh-tauri-experimental/src/host/service/capture.test.ts b/packages/dsh-tauri-experimental/src/host/service/capture.test.ts
index 08049e18..668cc93e 100644
--- a/packages/dsh-tauri-experimental/src/host/service/capture.test.ts
+++ b/packages/dsh-tauri-experimental/src/host/service/capture.test.ts
@@ -164,7 +164,8 @@ describe('turn 结算编排', () => {
const { worktree } = await fixture()
captureFor()
- await capture.begin('s5', 1)
+ capture.start('s5', 1)
+ await capture.awaitBegin('s5', 1)
await writeFile(join(worktree, 'a.txt'), 'one\ntwo\nthree\n', 'utf8')
await capture.settle('s5', 1)
@@ -181,7 +182,8 @@ describe('turn 结算编排', () => {
// 用户手动停止就发生在这个窗口里:`agent/pre-step` 的屏障还没回来(before 快照在跑
// `git add`),而 `turn/end` 已经到达。变更前这种 turn 会**整个消失**——账本里没有行,
// 直到很久以后某个 idle 才被顺手收掉(实测有 30 分钟后才落账的)。
- const beginning = capture.begin('s1', 1)
+ capture.start('s1', 1)
+ const beginning = capture.awaitBegin('s1', 1)
await capture.settle('s1', 1)
await beginning
@@ -196,7 +198,8 @@ describe('turn 结算编排', () => {
await fixture()
captureFor()
- const beginning = capture.begin('s2', 1)
+ capture.start('s2', 1)
+ const beginning = capture.awaitBegin('s2', 1)
await capture.settleIdle('s2')
await beginning
@@ -208,7 +211,8 @@ describe('turn 结算编排', () => {
const captured: number[] = []
captureFor(captured)
- const beginning = capture.begin('s3', 1)
+ capture.start('s3', 1)
+ const beginning = capture.awaitBegin('s3', 1)
await Promise.all([capture.settle('s3', 1), capture.settleIdle('s3')])
await beginning
@@ -221,11 +225,13 @@ describe('turn 结算编排', () => {
await fixture()
captureFor()
- const first = capture.begin('s6', 1)
+ capture.start('s6', 1)
+ const first = capture.awaitBegin('s6', 1)
const idle = capture.settleIdle('s6')
// idle 之后(用户重新发消息)立刻开始的新一轮:这次兜底不能把它一起结算掉,
// 否则它的 after 会在 before 刚结束时被拍下来,那一轮的真实改动就永远拿不到了。
- const second = capture.begin('s6', 2)
+ capture.start('s6', 2)
+ const second = capture.awaitBegin('s6', 2)
await Promise.all([first, second, idle])
expect((await ledger.load('s6')).turns.map(turn => turn.turn)).toEqual([1])
@@ -246,7 +252,8 @@ describe('turn 结算编排', () => {
// 复现 git/IO 抛错:runBeginTurn 里的 queue.run 直接拒绝,before 快照连结果对象都没有。
setFailing(true)
- await capture.begin('s7', 1)
+ capture.start('s7', 1)
+ await capture.awaitBegin('s7', 1)
setFailing(false)
// 结算没有条目可结算,但不能因此把这一轮从账本里抹掉(客户端靠账本行停止重试)。
await capture.settleIdle('s7')
@@ -262,7 +269,8 @@ describe('turn 结算编排', () => {
const { setFailing } = faultyQueue()
captureFor()
- await capture.begin('s8', 1)
+ capture.start('s8', 1)
+ await capture.awaitBegin('s8', 1)
await writeFile(join(worktree, 'a.txt'), 'one\ntwo\nthree\n', 'utf8')
// after 快照这一步抛错:账本还没有这一轮。
@@ -284,12 +292,14 @@ describe('运行中提示条的读数生命周期', () => {
await fixture()
captureFor()
- await capture.begin('s9', 1)
+ capture.start('s9', 1)
+ await capture.awaitBegin('s9', 1)
expect(capture.live('s9')).toMatchObject({ active: true, turn: 1 })
// 第 1 轮还在后台结算(after 快照排队),用户已经发了新消息:
// 此时若还报第 1 轮的读数,客户端提示条就会显示跨轮的累加数字。
- await capture.begin('s9', 2)
+ capture.start('s9', 2)
+ await capture.awaitBegin('s9', 2)
expect(capture.live('s9')).toMatchObject({ active: true, turn: 2 })
})
@@ -297,7 +307,8 @@ describe('运行中提示条的读数生命周期', () => {
const { worktree } = await fixture()
captureFor()
- await capture.begin('s10', 1)
+ capture.start('s10', 1)
+ await capture.awaitBegin('s10', 1)
await writeFile(join(worktree, 'a.txt'), 'one\ntwo\nthree\n', 'utf8')
// 会话结束:读数归零,客户端提示条立刻消失。
capture.resetLive('s10')
@@ -314,8 +325,10 @@ describe('运行中提示条的读数生命周期', () => {
await fixture()
captureFor()
- await capture.begin('s11', 1)
- await capture.begin('s12', 1)
+ capture.start('s11', 1)
+ await capture.awaitBegin('s11', 1)
+ capture.start('s12', 1)
+ await capture.awaitBegin('s12', 1)
capture.resetLive('s11')
expect(capture.live('s11').active).toBe(false)
@@ -331,7 +344,8 @@ describe('运行中提示条的读数生命周期', () => {
const gate = gatedQueue()
captureFor()
- await capture.begin('s13', 1)
+ capture.start('s13', 1)
+ await capture.awaitBegin('s13', 1)
expect(capture.live('s13')).toMatchObject({ active: true, turn: 1 })
// 关上闸门后,下一次定时刷新(1.5s)会挂在队列里 —— 等它真的开始。
@@ -350,26 +364,23 @@ describe('运行中提示条的读数生命周期', () => {
expect(capture.live('s13').active).toBe(false)
})
- it('读数归零不等于这一轮已落定:撤销判定仍然看结算状态', async () => {
- await fixture()
- captureFor()
-
- expect(capture.pending('s14', 1)).toBe(false)
-
- await capture.begin('s14', 1)
- expect(capture.pending('s14', 1)).toBe(true)
- expect(capture.pending('s14')).toBe(true)
- expect(capture.pending('s14', 2)).toBe(false)
- expect(capture.pending('s15')).toBe(false)
+ it('resetLive stops live readings without settling or losing the turn', async () => {
+ const { worktree } = await fixture()
+ capture.start('s14', 1)
+ await capture.awaitBegin('s14', 1)
+ await writeFile(join(worktree, 'a.txt'), 'one\ntwo\nthree\n', 'utf8')
- // 会话结束(读数归零)之后这一轮仍在后台结算:撤销必须继续被拒绝。
capture.resetLive('s14')
- expect(capture.live('s14').active).toBe(false)
- expect(capture.pending('s14', 1)).toBe(true)
+ expect(capture.live('s14')).toEqual({ active: false, turn: null, fileCount: 0, insertions: 0, deletions: 0 })
+ expect((await ledger.load('s14')).turns).toEqual([])
await capture.settle('s14', 1)
- expect(capture.pending('s14', 1)).toBe(false)
- expect(capture.pending('s14')).toBe(false)
+ const current = await ledger.load('s14')
+ expect(current.turns.map(turn => turn.turn)).toEqual([1])
+ expect(current.turns[0]?.files).toEqual([{ path: 'a.txt', status: 'M', insertions: 1, deletions: 0, binary: false }])
+ await writeFile(join(worktree, 'a.txt'), 'later\n', 'utf8')
+ await capture.settle('s14', 1)
+ expect(await ledger.load('s14')).toEqual(current)
})
it('工作区里的嵌套仓库不会让运行中读数凭空多出文件(提示条假报 +N)', async () => {
@@ -389,7 +400,8 @@ describe('运行中提示条的读数生命周期', () => {
await run('git', ['-C', worktree, ...identity, 'add', 'source/react-use'], { windowsHide: true })
captureFor()
- await capture.begin('s16', 1)
+ capture.start('s16', 1)
+ await capture.awaitBegin('s16', 1)
await writeFile(join(worktree, 'a.txt'), 'one\ntwo\nthree\n', 'utf8')
// 等第一次定时刷新(1.5s 起)落地:读数出现就必须正好是 a.txt 这一处改动。
@@ -420,7 +432,8 @@ describe('工作区被带外换提交世代(新建工作树 / checkout 到 ori
const older = await gitAt('rev-parse', 'HEAD~1')
captureFor()
- await capture.begin('s-head', 1)
+ capture.start('s-head', 1)
+ await capture.awaitBegin('s-head', 1)
expect(capture.live('s-head')).toMatchObject({ active: true, turn: 1 })
await gitAt('checkout', '--quiet', older)
@@ -462,7 +475,8 @@ describe('工作区被带外换提交世代(新建工作树 / checkout 到 ori
return result
})
try {
- await capture.begin('s-race', 1)
+ capture.start('s-race', 1)
+ await capture.awaitBegin('s-race', 1)
}
finally {
spy.mockRestore()
@@ -492,7 +506,8 @@ describe('屏障等待预算(容量治理与 before 一次持锁)', () => {
const recorded = recordingQueue()
const startedAt = Date.now()
- await capture.begin('s-barrier', 1)
+ capture.start('s-barrier', 1)
+ await capture.awaitBegin('s-barrier', 1)
expect(recorded).toHaveLength(1)
expect(recorded[0]).toMatchObject({ lockTimeoutMs: LOCK_BARRIER_TIMEOUT_MS })
expect(recorded[0]!.waitDeadline).toBeGreaterThanOrEqual(startedAt + LOCK_BARRIER_TIMEOUT_MS)
@@ -515,7 +530,8 @@ describe('屏障等待预算(容量治理与 before 一次持锁)', () => {
const ensure = vi.spyOn(retention, 'ensure')
const captureSnapshot = vi.spyOn(snapshot, 'capture')
try {
- await capture.begin('s-busy', 1)
+ capture.start('s-busy', 1)
+ await capture.awaitBegin('s-busy', 1)
expect(calls).toBe(1)
expect(ensure).not.toHaveBeenCalled()
expect(captureSnapshot).not.toHaveBeenCalled()
@@ -545,11 +561,12 @@ describe('屏障等待预算(容量治理与 before 一次持锁)', () => {
})
const captureSnapshot = vi.spyOn(snapshot, 'capture')
try {
- await capture.begin('s-slow-retention', 1)
+ capture.start('s-slow-retention', 1)
+ await capture.awaitBegin('s-slow-retention', 1)
expect(recorded).toHaveLength(1)
expect(Date.now()).toBeGreaterThan(recorded[0]!.waitDeadline!)
expect(captureSnapshot).toHaveBeenCalledTimes(1)
- expect(capture.pending('s-slow-retention', 1)).toBe(true)
+ expect((await ledger.load('s-slow-retention')).turns).toEqual([])
expect(capture.live('s-slow-retention')).toMatchObject({ active: true, turn: 1 })
}
finally {
@@ -571,7 +588,8 @@ describe('屏障等待预算(容量治理与 before 一次持锁)', () => {
const ensure = vi.spyOn(retention, 'ensure').mockRejectedValueOnce(new Error('retention failed'))
const captureSnapshot = vi.spyOn(snapshot, 'capture')
try {
- await capture.begin('s-retention-failed', 1)
+ capture.start('s-retention-failed', 1)
+ await capture.awaitBegin('s-retention-failed', 1)
expect(recorded).toHaveLength(1)
expect(captureSnapshot).toHaveBeenCalledTimes(1)
expect(captureSnapshot.mock.calls[0]?.[3]?.exclude).toEqual([])
diff --git a/packages/dsh-tauri-experimental/src/host/service/capture.ts b/packages/dsh-tauri-experimental/src/host/service/capture.ts
index 265e9927..1a590a81 100644
--- a/packages/dsh-tauri-experimental/src/host/service/capture.ts
+++ b/packages/dsh-tauri-experimental/src/host/service/capture.ts
@@ -86,12 +86,6 @@ export const capture = defineService({
await Promise.all(inflight)
},
- /** 起快照并同步等它落地:生产路径由 start / awaitBegin 分挂两个钩子,这里保留合并形态。 */
- async begin(sessionId: string, turn: number): Promise<void> {
- capture.start(sessionId, turn)
- await capture.awaitBegin(sessionId, turn)
- },
-
/**
* 结算一轮:等 before 快照落地 → 捕 after → 差异 → 写账本。
*
@@ -223,28 +217,6 @@ export const capture = defineService({
}
},
- /**
- * 该轮是否仍未落定:before 快照还在飞,或 after 尚未结算。
- * 不能用实时读数是否 active(读数是提示条的过程态,`turn/end` 一到就归零,
- * 而这一轮此后还要在后台结算)。
- * @param sessionId - 会话 id。
- * @param turn - 省略即该会话是否有任何未落定的轮次。
- */
- pending(sessionId: string, turn?: number): boolean {
- for (const entry of activeTurns.values()) {
- if (entry.sessionId === sessionId && (turn === undefined || entry.turn === turn))
- return true
- }
- if (turn === undefined) {
- for (const item of beginningTurns.values()) {
- if (item.sessionId === sessionId)
- return true
- }
- return false
- }
- return beginningTurns.has(activeKey(sessionId, turn))
- },
-
/**
* 运行中实时读数;没有正在进行的 turn 时返回 active: false。
* 同一会话可能同时留着多条(旧轮还在后台结算,新一轮已经开始):只认**轮次最新**的
diff --git a/packages/dsh-tauri-experimental/src/host/service/retention.test.ts b/packages/dsh-tauri-experimental/src/host/service/retention.test.ts
index db3d52d6..223cec79 100644
--- a/packages/dsh-tauri-experimental/src/host/service/retention.test.ts
+++ b/packages/dsh-tauri-experimental/src/host/service/retention.test.ts
@@ -1,7 +1,7 @@
import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
import { existsSync, rmSync } from 'node:fs'
-import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readFile, rename, rm, stat, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { promisify } from 'node:util'
import { join } from 'pathe'
@@ -147,20 +147,31 @@ describe('容量治理', () => {
})
})
-describe('describeRepository', () => {
- it('汇总 ref 数、体积与隔离残骸', async () => {
- const { store } = await fixture()
- const captured = await snapshot.capture(store, snapshot.ref('s1', 1, 'before'), 'turn 1 before')
- expect(captured.ok).toBe(true)
+describe('retention.measure', () => {
+ it('counts nested file bytes and treats a missing directory as empty', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'dsh-running-changes-measure-'))
+ temporaryDirectories.push(root)
+ await mkdir(join(root, 'nested'))
+ await writeFile(join(root, 'a.bin'), Buffer.alloc(7))
+ await writeFile(join(root, 'nested', 'b.bin'), Buffer.alloc(11))
- const described = await retention.describe(store)
- expect(described.refs).toBeGreaterThan(0)
- expect(described.sizeMb).toBeGreaterThanOrEqual(0)
- expect(described.quarantineLeftover).toBe(false)
+ expect(await retention.measure(root)).toBe(18 / (1024 * 1024))
+ expect(await retention.measure(join(root, 'absent'))).toBe(0)
+ })
- // 未初始化的仓(git 命令失败)不应抛,只是 ref 数为 0。
- const empty = snapshot.resolve(join(store.gitDir, '..', 'absent-home'), store.worktree)
- await expect(retention.describe(empty)).resolves.toMatchObject({ refs: 0, quarantineLeftover: false })
+ it('stats directory links without traversing their target files', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'dsh-running-changes-measure-link-'))
+ temporaryDirectories.push(root)
+ const measured = join(root, 'measured')
+ const outside = join(root, 'outside')
+ const link = join(measured, 'linked')
+ await mkdir(measured)
+ await mkdir(outside)
+ await writeFile(join(outside, 'large.bin'), Buffer.alloc(4096))
+ await symlink(outside, link, 'junction')
+
+ const target = await stat(outside)
+ expect(await retention.measure(measured)).toBe(target.size / (1024 * 1024))
})
})
diff --git a/packages/dsh-tauri-experimental/src/host/service/retention.ts b/packages/dsh-tauri-experimental/src/host/service/retention.ts
index b20adcea..752b18a8 100644
--- a/packages/dsh-tauri-experimental/src/host/service/retention.ts
+++ b/packages/dsh-tauri-experimental/src/host/service/retention.ts
@@ -18,7 +18,7 @@ import { defineService } from 'dsh-tauri'
import { dirname, join } from 'pathe'
import { MAX_FILE_BYTES } from '../config/constants'
import { retainedWorkspaces } from '../config/runtime'
-import { gitInSnapshot, pruneLooseObjects } from '../utils/git'
+import { pruneLooseObjects } from '../utils/git'
import { resolveInsideWorkspace } from '../utils/paths'
import { snapshot } from './snapshot'
@@ -141,17 +141,6 @@ export const retention = defineService({
await walk(dir)
return total / (1024 * 1024)
},
-
- /** 私有仓健康摘要(诊断:ref 数 + 体积 + 是否有残留隔离目录)。 */
- async describe(store: SnapshotStore): Promise<{ refs: number, sizeMb: number, quarantineLeftover: boolean }> {
- const listed = await gitInSnapshot(store, ['for-each-ref', '--format=%(refname)'])
- const refs = listed.ok ? listed.out.split('\n').filter(line => line.trim().length > 0).length : 0
- return {
- refs,
- sizeMb: Math.round(await retention.measure(store.gitDir)),
- quarantineLeftover: existsSync(`${store.gitDir}.retention-quarantine`),
- }
- },
})
// --- internal ---
diff --git a/packages/dsh-tauri-experimental/src/host/service/snapshot.test.ts b/packages/dsh-tauri-experimental/src/host/service/snapshot.test.ts
index 849644e2..8a918909 100644
--- a/packages/dsh-tauri-experimental/src/host/service/snapshot.test.ts
+++ b/packages/dsh-tauri-experimental/src/host/service/snapshot.test.ts
@@ -1,7 +1,7 @@
import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
import { rmSync } from 'node:fs'
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { promisify } from 'node:util'
import { join } from 'pathe'
@@ -52,7 +52,6 @@ describe('会话独占 index', () => {
expect(first.indexFile).toBeDefined()
expect(first.indexFile).not.toBe(second.indexFile)
expect(first.indexFile?.startsWith(first.gitDir)).toBe(true)
- // 不给会话 id 的调用面(如按路径取代数)仍退回私有仓自带的 index。
expect(snapshot.resolve(worktree).indexFile).toBeUndefined()
})
})
@@ -77,6 +76,20 @@ afterEach(async () => {
})
describe('captureSnapshot + diffTurnChanges', () => {
+ it('mirrors source info/exclude when commonDir was omitted', async () => {
+ const { worktree } = await fixture()
+ await writeFile(join(worktree, '.git', 'info', 'exclude'), 'local-only.txt\n', 'utf8')
+ await writeFile(join(worktree, 'local-only.txt'), 'must not enter the snapshot\n', 'utf8')
+ const store = snapshot.resolve(worktree)
+
+ const captured = await snapshot.capture(store, snapshot.ref('source-exclude', 1, 'before'), 'before')
+ expect(captured.ok).toBe(true)
+ expect(await readFile(join(store.gitDir, 'info', 'exclude'), 'utf8')).toBe('local-only.txt\n')
+ const listed = await gitInSnapshot(store, ['ls-files'])
+ expect(listed).toEqual({ ok: true, out: '.gitignore\na.txt\ngone.txt\n' })
+ expect(await readFile(join(worktree, 'local-only.txt'), 'utf8')).toBe('must not enter the snapshot\n')
+ })
+
it('reports added / modified / deleted files with per-file line counts', async () => {
const { worktree } = await fixture()
const store = snapshot.resolve(worktree)
@@ -234,6 +247,19 @@ describe('liveDiff(运行中实时读数)', () => {
})
describe('捕获限额(超限文件 / 嵌套仓库)', () => {
+ it('accepts the file-count limit and rejects one file above it without publishing a ref', async () => {
+ const { worktree } = await fixture()
+ const store = snapshot.resolve(worktree)
+ const beforeRef = snapshot.ref('file-count', 1, 'before')
+ const accepted = await snapshot.capture(store, beforeRef, 'before', { limits: { maxFiles: 3 } })
+ expect(accepted.ok).toBe(true)
+
+ const afterRef = snapshot.ref('file-count', 1, 'after')
+ expect(await snapshot.capture(store, afterRef, 'after', { limits: { maxFiles: 2 } })).toEqual({ ok: false, reason: 'RUNNING_CHANGES_TOO_MANY_FILES' })
+ const refs = await gitInSnapshot(store, ['for-each-ref', '--format=%(refname)'])
+ expect(refs).toEqual({ ok: true, out: `${beforeRef}\n` })
+ })
+
it('超限时排除最大的文件后重试,并把它记进跳过明细', async () => {
const { worktree } = await fixture()
const store = snapshot.resolve(worktree)
@@ -410,7 +436,7 @@ describe('快照仓代数', () => {
expect(first.ok).toBe(true)
const firstGeneration = store.generation
expect(firstGeneration).toBeTypeOf('string')
- expect(await snapshot.generation(worktree)).toBe(firstGeneration)
+ expect(JSON.parse(await readFile(`${store.gitDir}.json`, 'utf8'))).toMatchObject({ generation: firstGeneration })
// 整仓消失(被隔离重建 / 用户清理):下一次捕获必须换一代。
await rm(store.gitDir, { recursive: true, force: true })
@@ -418,9 +444,11 @@ describe('快照仓代数', () => {
expect(second.ok).toBe(true)
expect(store.generation).toBeTypeOf('string')
expect(store.generation).not.toBe(firstGeneration)
- expect(await snapshot.generation(worktree)).toBe(store.generation)
+ expect(JSON.parse(await readFile(`${store.gitDir}.json`, 'utf8'))).toMatchObject({ generation: store.generation })
// 老 ref 随旧仓一起消失:旧代数记录不存在「指向别人对象」的错乱。
- expect(await snapshot.read(store, snapshot.ref('s12', 1, 'before'))).toBeNull()
+ const oldRef = await gitInSnapshot(store, ['rev-parse', '--verify', '--quiet', snapshot.ref('s12', 1, 'before')])
+ expect(oldRef.ok).toBe(false)
+ expect(oldRef.out).toBe('')
})
})
diff --git a/packages/dsh-tauri-experimental/src/host/service/snapshot.ts b/packages/dsh-tauri-experimental/src/host/service/snapshot.ts
index cf28134e..3b7f3aca 100644
--- a/packages/dsh-tauri-experimental/src/host/service/snapshot.ts
+++ b/packages/dsh-tauri-experimental/src/host/service/snapshot.ts
@@ -6,7 +6,6 @@
* - 私有仓自带 index(stat 缓存让 `add --all` 后续轮次天然增量);
* - 源仓库只做只读探测:镜像 core.autocrlf / core.eol / core.symlinks 与 info/exclude;
* - **快照仓代数(generation)**:整仓被隔离重建或被删后轮换,账本记录据此判定过期;
- * - 越界与不安全路径:所有写盘路径都过 `utils/paths.ts` 的词法 + 父级符号链接校验;
* - 不在快照范围内却不该静默漏掉的东西(超大文件、嵌套 Git 仓库)排除并记录进账本。
*/
@@ -79,12 +78,6 @@ export const snapshot = defineService({
return scanNestedRepos(worktree)
},
- /** 读取某工作区当前代数(不存在返回 null)。 */
- async generation(worktree: string): Promise<string | null> {
- const marker = await readMarker(workspaceMarkerPath(snapshot.resolve(worktree)))
- return marker?.generation ?? null
- },
-
/** 轮换快照仓代数:整仓被删/被隔离重建后调用,旧记录据此自然过期。 */
async rotate(store: SnapshotStore, reason?: string): Promise<string> {
const generation = randomUUID()
@@ -204,17 +197,6 @@ export const snapshot = defineService({
}
},
- /** 解析 ref 指向的 commit;不存在返回 null。 */
- async read(store: SnapshotStore, ref: string): Promise<string | null> {
- if (!isSafeRef(ref))
- return null
- const result = await gitInSnapshot(store, ['rev-parse', '--verify', '--quiet', ref])
- if (!result.ok)
- return null
- const oid = result.out.trim()
- return oid.length > 0 ? oid : null
- },
-
/**
* 读源仓库当前 HEAD(只读探测,绝不写用户仓库)。
*
diff --git a/packages/dsh-tauri-experimental/src/host/utils/paths.test.ts b/packages/dsh-tauri-experimental/src/host/utils/paths.test.ts
index a64f72db..3be9872b 100644
--- a/packages/dsh-tauri-experimental/src/host/utils/paths.test.ts
+++ b/packages/dsh-tauri-experimental/src/host/utils/paths.test.ts
@@ -1,97 +1,16 @@
-import { existsSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs'
-import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
-import process from 'node:process'
import { join } from 'pathe'
-import { afterEach, describe, expect, it } from 'vitest'
-import { REASON_NON_EMPTY_DIR, REASON_UNSAFE_PATH } from '../config/constants'
-import { assertSafeParents, removeCreatedPath, resolveInsideWorkspace } from './paths'
+import { describe, expect, it } from 'vitest'
+import { resolveInsideWorkspace } from './paths'
-const temporaryDirectories: string[] = []
-
-async function tempRoot(): Promise<string> {
- const root = await mkdtemp(join(tmpdir(), 'dsh-running-changes-paths-'))
- temporaryDirectories.push(root)
- return root
-}
-
-/** 建一个指向工作区外部的目录链接(Windows 用 junction,无需开发者模式)。 */
-function linkOutside(linkPath: string, target: string): boolean {
- try {
- symlinkSync(target, linkPath, process.platform === 'win32' ? 'junction' : 'dir')
- return true
- }
- catch {
- // 无权限建链接(Windows 未开开发者模式等):调用方改走「父级不是目录」的等价输入。
- return false
- }
-}
-
-afterEach(async () => {
- await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })))
-})
+const worktree = join(tmpdir(), 'dsh-running-changes-paths')
describe('resolveInsideWorkspace', () => {
- it('接受嵌套路径,拒绝逃逸与绝对路径', async () => {
- const root = await tempRoot()
- expect(resolveInsideWorkspace(root, 'src/a.ts')).not.toBeNull()
- expect(resolveInsideWorkspace(root, '../outside.txt')).toBeNull()
- expect(resolveInsideWorkspace(root, 'a/../../outside.txt')).toBeNull()
- expect(resolveInsideWorkspace(root, 'C:\\Other\\file.txt')).toBeNull()
- expect(resolveInsideWorkspace(root, '')).toBeNull()
- })
-})
-
-describe('assertSafeParents(撤销写盘前的最后一道防线)', () => {
- it('普通父目录通过;父级是文件则拒绝', async () => {
- const root = await tempRoot()
- mkdirSync(join(root, 'sub'), { recursive: true })
- expect(assertSafeParents(root, join(root, 'sub', 'a.txt')).ok).toBe(true)
- writeFileSync(join(root, 'plain.txt'), 'x')
- expect(assertSafeParents(root, join(root, 'plain.txt', 'a.txt')).ok).toBe(false)
- })
-
- it('父级是指向工作区外部的链接时拒绝(词法检查看不到这一层)', async () => {
- const root = await tempRoot()
- const outside = join(root, '..', `outside-${Date.now()}`)
- mkdirSync(outside, { recursive: true })
- temporaryDirectories.push(outside)
- const link = join(root, 'linked')
- if (!linkOutside(link, outside))
- writeFileSync(link, 'not-a-directory')
- // 词法上 `linked/evil.txt` 在工作区内——正因如此才必须按文件系统事实再判一次。
- const lexical = resolveInsideWorkspace(root, 'linked/evil.txt')
- expect(lexical).not.toBeNull()
- const safe = assertSafeParents(root, lexical as string)
- expect(safe).toEqual({ ok: false, reason: REASON_UNSAFE_PATH })
- expect(existsSync(join(outside, 'evil.txt'))).toBe(false)
- })
-
- it('父级尚未存在时通过(新增文件的正常路径由恢复过程创建)', async () => {
- const root = await tempRoot()
- expect(assertSafeParents(root, join(root, 'not', 'yet', 'a.txt')).ok).toBe(true)
- })
-})
-
-describe('removeCreatedPath', () => {
- it('删除文件与空目录,拒绝非空目录', async () => {
- const root = await tempRoot()
- writeFileSync(join(root, 'a.txt'), 'x')
- expect(removeCreatedPath(join(root, 'a.txt'))).toEqual({ ok: true })
- expect(existsSync(join(root, 'a.txt'))).toBe(false)
-
- mkdirSync(join(root, 'empty'))
- expect(removeCreatedPath(join(root, 'empty'))).toEqual({ ok: true })
-
- mkdirSync(join(root, 'full'))
- writeFileSync(join(root, 'full', 'keep.txt'), 'important')
- // 递归删除可能毁掉本 turn 从未碰过、也不在快照里的文件:只拒绝,绝不递归删。
- expect(removeCreatedPath(join(root, 'full'))).toEqual({ ok: false, reason: REASON_NON_EMPTY_DIR })
- expect(existsSync(join(root, 'full', 'keep.txt'))).toBe(true)
+ it('resolves nested paths inside the workspace', () => {
+ expect(resolveInsideWorkspace(worktree, 'src/a.ts')).toBe(join(worktree, 'src/a.ts'))
})
- it('路径已消失按成功结算', async () => {
- const root = await tempRoot()
- expect(removeCreatedPath(join(root, 'gone.txt'))).toEqual({ ok: true })
+ it.each(['', '.', '..', '../outside.txt', 'a/../../outside.txt', '/outside.txt', 'C:\\Other\\file.txt', 'src/\0a.ts'])('rejects unsafe path %j', (path) => {
+ expect(resolveInsideWorkspace(worktree, path)).toBeNull()
})
})
diff --git a/packages/dsh-tauri-experimental/src/host/utils/paths.ts b/packages/dsh-tauri-experimental/src/host/utils/paths.ts
index a4703986..2b2a7fb9 100644
--- a/packages/dsh-tauri-experimental/src/host/utils/paths.ts
+++ b/packages/dsh-tauri-experimental/src/host/utils/paths.ts
@@ -1,20 +1,5 @@
-import type { PathSafety } from './paths.types'
-import { lstatSync, rmdirSync, unlinkSync } from 'node:fs'
-import { isAbsolute, join, relative, resolve } from 'pathe'
-import { REASON_NON_EMPTY_DIR, REASON_UNSAFE_PATH } from '../config/constants'
+import { isAbsolute, relative, resolve } from 'pathe'
-/**
- * 恢复路径的安全解析与删除。
- *
- * 撤销是唯一会写用户工作区的动作,因此路径判定必须在词法之上再加一层文件系统事实校验:
- * `sub/file.txt` 词法上在工作区内,但 `sub` 若是指向外部的符号链接或 Windows junction,
- * `git checkout` / `unlink` 就会写到工作区外面去。
- *
- * 只检查**父级**(目标自身是符号链接时 unlink/覆盖只作用于链接本身,不会穿透),
- * 且用 `lstat` 而非 `existsSync` 预检(后者对悬空链接返回 false)。
- */
-
-/** 词法包含检查:越界(绝对路径、`..` 逃逸、NUL)返回 null。 */
export function resolveInsideWorkspace(worktree: string, path: string): string | null {
if (path.length === 0 || path.includes('\0') || isAbsolute(path))
return null
@@ -24,58 +9,3 @@ export function resolveInsideWorkspace(worktree: string, path: string): string |
return null
return absolute
}
-
-/** 校验某个已解析的工作区内绝对路径:任一路径组件(除目标自身)都不得是符号链接/junction。 */
-export function assertSafeParents(worktree: string, absolutePath: string): PathSafety {
- const root = resolve(worktree)
- const rel = relative(root, absolutePath)
- if (rel.length === 0 || rel.startsWith('..') || isAbsolute(rel))
- return { ok: false, reason: REASON_UNSAFE_PATH }
- const segments = rel.split('/')
- let current = root
- for (const segment of segments.slice(0, -1)) {
- current = join(current, segment)
- let stats
- try {
- stats = lstatSync(current)
- }
- catch {
- // 父级还不存在(A 型新增文件的常见情形):恢复时由 git/写盘自行创建,安全。
- return { ok: true }
- }
- if (stats.isSymbolicLink() || !stats.isDirectory())
- return { ok: false, reason: REASON_UNSAFE_PATH }
- }
- return { ok: true }
-}
-
-/**
- * 撤销 A 型(本 turn 新增)路径:文件或符号链接直接删除;空目录删除;
- * **非空目录拒绝**(递归删除可能毁掉本 turn 从未碰过、且不在快照里的文件)。
- */
-export function removeCreatedPath(absolutePath: string): PathSafety {
- let stats
- try {
- stats = lstatSync(absolutePath)
- }
- catch {
- // 已经不在了:按「已删除」结算,不算失败。
- return { ok: true }
- }
- try {
- if (stats.isDirectory()) {
- rmdirSync(absolutePath)
- return { ok: true }
- }
- unlinkSync(absolutePath)
- return { ok: true }
- }
- catch (error) {
- const code = (error as NodeJS.ErrnoException).code
- if (code === 'ENOENT')
- return { ok: true }
- if (stats.isDirectory())
- return { ok: false, reason: REASON_NON_EMPTY_DIR }
- return { ok: false, reason: `${REASON_UNSAFE_PATH}: ${String((error as Error)?.message ?? error)}` }
- }
-}
diff --git a/packages/dsh-tauri-experimental/src/host/utils/paths.types.ts b/packages/dsh-tauri-experimental/src/host/utils/paths.types.ts
deleted file mode 100644
index b9da5db7..00000000
--- a/packages/dsh-tauri-experimental/src/host/utils/paths.types.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-/** 一次路径安全校验的结果。 */
-export type PathSafety = { ok: true } | { ok: false, reason: string }
diff --git a/packages/dsh-tauri-model/src/client/models/operations.ts b/packages/dsh-tauri-model/src/client/models/operations.ts
index 09aba8ca..d6014de2 100644
--- a/packages/dsh-tauri-model/src/client/models/operations.ts
+++ b/packages/dsh-tauri-model/src/client/models/operations.ts
@@ -1,7 +1,7 @@
+import type { ModelDiscoveryOutcome } from '../service/model-config.ts'
import type {
ClientRemote,
CredentialInfo,
- LlmDiscoveredModel,
LlmModelDiscoveryRequest,
SettingsNamespaceView,
SettingsPathOpView,
@@ -12,9 +12,7 @@ export type SettingsWriteOutcome
| { readonly kind: 'conflict', readonly message: string }
| { readonly kind: 'refused', readonly message: string }
-export type ModelDiscoveryOutcome
- = | { readonly kind: 'found', readonly models: readonly LlmDiscoveredModel[] }
- | { readonly kind: 'refused', readonly message: string }
+export type { ModelDiscoveryOutcome } from '../service/model-config.ts'
export interface ModelsOperations {
describeCredential: (ref: string) => Promise<CredentialInfo | undefined>
diff --git a/packages/dsh-tauri-model/src/client/models/settings-forms.ts b/packages/dsh-tauri-model/src/client/models/settings-forms.ts
index 8c7766af..b69006e5 100644
--- a/packages/dsh-tauri-model/src/client/models/settings-forms.ts
+++ b/packages/dsh-tauri-model/src/client/models/settings-forms.ts
@@ -1,4 +1,5 @@
import type { SettingsDescribeFace } from '@deepseek-ai/dsh-client-ui-settings/client'
+import type { ServiceLookup } from './remote.ts'
import type { WelcomeSettingsForm } from './welcome-store.ts'
import {
WELCOME_NOTICE_SETTINGS_NAMESPACE,
@@ -21,9 +22,7 @@ export interface ModelsForms {
welcome: WelcomeSettingsForm
}
-export interface ServiceLookup {
- get: (name: string) => unknown
-}
+export type { ServiceLookup } from './remote.ts'
export function resolveModelsForms(ctx: ServiceLookup): ModelsForms | undefined {
const forms = ctx.get('configForms') as ConfigFormsLike | undefined
diff --git a/packages/dsh-tauri-model/src/client/models/styles.test.ts b/packages/dsh-tauri-model/src/client/models/styles.test.ts
new file mode 100644
index 00000000..5752c92d
--- /dev/null
+++ b/packages/dsh-tauri-model/src/client/models/styles.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, expectTypeOf, it, vi } from 'vitest'
+import { modelStyles, onboardingDialogStyles, onboardingStyles, welcomeStyles } from './styles'
+
+vi.mock('dsh-tauri-ui/client', async () => await import('../../../../dsh-tauri-ui/src/client/utils/cssr'))
+
+const MODEL_KEYS = 'addActions addBlock addButton addCard addModelButton addModes addPanel advancedHint candidate candidateActive candidateEmpty candidateId candidateLabel candidateList candidateSearch candidateToolbar credentialDot credentialDotConfigured credentialDotMissing customized customizedBody customizedSummary dangerButton deleteConfirm deleteDialog editor editorActions editorHeader editorRoute editorTitle error fetchDialog field fieldLabel hiddenLabel iconButton iconButtonDanger input intro linkButton modelAdvanced modelCatalog modelCatalogHeading modelCatalogMeta modelCatalogTitle modelEmpty modelEntry modelField modelFieldLabel modelInputChoices modelInputTypes modelList modelListHead modelRow notice primaryButton rowActions rowCard rowHead rowIdentity rowName rows rowTag savedNotice secondaryButton section selectInput setupCard switchThumb title'.split(' ')
+
+function expected(prefix: string, keys: string[]): Record<string, string> {
+ return Object.fromEntries(keys.map(key => [key, `${prefix}${key}`]))
+}
+
+describe('css class maps', () => {
+ it('preserves every model class including compound, camel-case and media selectors', () => {
+ expect(modelStyles).toEqual(expected('zGbnIq_', MODEL_KEYS))
+ expectTypeOf(modelStyles).toEqualTypeOf<Record<string, string>>()
+ })
+
+ it('preserves welcome classes without leaking other prefixes', () => {
+ expect(welcomeStyles).toEqual(expected('zGbnIqw_', ['actions', 'copy', 'error', 'primary']))
+ expectTypeOf(welcomeStyles).toEqualTypeOf<Record<string, string>>()
+ })
+
+ it('preserves onboarding classes with their longer prefix', () => {
+ expect(onboardingStyles).toEqual(expected('zGbnIqo_', ['body', 'content', 'dialog', 'title']))
+ expectTypeOf(onboardingStyles).toEqualTypeOf<Record<string, string>>()
+ })
+
+ it('preserves onboarding editor classes with duplicate media rules', () => {
+ expect(onboardingDialogStyles).toEqual(expected('zGbnIqd_', ['description', 'editor']))
+ expectTypeOf(onboardingDialogStyles).toEqualTypeOf<Record<string, string>>()
+ })
+})
diff --git a/packages/dsh-tauri-model/src/client/models/styles.ts b/packages/dsh-tauri-model/src/client/models/styles.ts
index 7a534ad5..13bb4661 100644
--- a/packages/dsh-tauri-model/src/client/models/styles.ts
+++ b/packages/dsh-tauri-model/src/client/models/styles.ts
@@ -776,95 +776,9 @@ const ONBOARDING_DIALOG_CSS = `.zGbnIqd_description {
}
}`
-export const modelStyles: Record<string, string> = {
- addActions: 'zGbnIq_addActions',
- addBlock: 'zGbnIq_addBlock',
- addButton: 'zGbnIq_addButton',
- addCard: 'zGbnIq_addCard',
- addModelButton: 'zGbnIq_addModelButton',
- addModes: 'zGbnIq_addModes',
- addPanel: 'zGbnIq_addPanel',
- advancedHint: 'zGbnIq_advancedHint',
- candidate: 'zGbnIq_candidate',
- candidateActive: 'zGbnIq_candidateActive',
- candidateEmpty: 'zGbnIq_candidateEmpty',
- candidateId: 'zGbnIq_candidateId',
- candidateLabel: 'zGbnIq_candidateLabel',
- candidateList: 'zGbnIq_candidateList',
- candidateSearch: 'zGbnIq_candidateSearch',
- candidateToolbar: 'zGbnIq_candidateToolbar',
- credentialDot: 'zGbnIq_credentialDot',
- credentialDotConfigured: 'zGbnIq_credentialDotConfigured',
- credentialDotMissing: 'zGbnIq_credentialDotMissing',
- customized: 'zGbnIq_customized',
- customizedBody: 'zGbnIq_customizedBody',
- customizedSummary: 'zGbnIq_customizedSummary',
- dangerButton: 'zGbnIq_dangerButton',
- deleteConfirm: 'zGbnIq_deleteConfirm',
- deleteDialog: 'zGbnIq_deleteDialog',
- editor: 'zGbnIq_editor',
- editorActions: 'zGbnIq_editorActions',
- editorHeader: 'zGbnIq_editorHeader',
- editorRoute: 'zGbnIq_editorRoute',
- editorTitle: 'zGbnIq_editorTitle',
- error: 'zGbnIq_error',
- fetchDialog: 'zGbnIq_fetchDialog',
- field: 'zGbnIq_field',
- fieldLabel: 'zGbnIq_fieldLabel',
- hiddenLabel: 'zGbnIq_hiddenLabel',
- iconButton: 'zGbnIq_iconButton',
- iconButtonDanger: 'zGbnIq_iconButtonDanger',
- input: 'zGbnIq_input',
- intro: 'zGbnIq_intro',
- linkButton: 'zGbnIq_linkButton',
- modelAdvanced: 'zGbnIq_modelAdvanced',
- modelCatalog: 'zGbnIq_modelCatalog',
- modelCatalogHeading: 'zGbnIq_modelCatalogHeading',
- modelCatalogMeta: 'zGbnIq_modelCatalogMeta',
- modelCatalogTitle: 'zGbnIq_modelCatalogTitle',
- modelEmpty: 'zGbnIq_modelEmpty',
- modelEntry: 'zGbnIq_modelEntry',
- modelField: 'zGbnIq_modelField',
- modelFieldLabel: 'zGbnIq_modelFieldLabel',
- modelInputChoices: 'zGbnIq_modelInputChoices',
- modelInputTypes: 'zGbnIq_modelInputTypes',
- modelList: 'zGbnIq_modelList',
- modelListHead: 'zGbnIq_modelListHead',
- modelRow: 'zGbnIq_modelRow',
- notice: 'zGbnIq_notice',
- org: 'zGbnIq_org',
- primaryButton: 'zGbnIq_primaryButton',
- rowActions: 'zGbnIq_rowActions',
- rowCard: 'zGbnIq_rowCard',
- rowHead: 'zGbnIq_rowHead',
- rowIdentity: 'zGbnIq_rowIdentity',
- rowName: 'zGbnIq_rowName',
- rows: 'zGbnIq_rows',
- rowTag: 'zGbnIq_rowTag',
- savedNotice: 'zGbnIq_savedNotice',
- secondaryButton: 'zGbnIq_secondaryButton',
- section: 'zGbnIq_section',
- selectInput: 'zGbnIq_selectInput',
- setupCard: 'zGbnIq_setupCard',
- switchThumb: 'zGbnIq_switchThumb',
- title: 'zGbnIq_title',
- w3: 'zGbnIq_w3',
-}
-export const welcomeStyles: Record<string, string> = {
- actions: 'zGbnIqw_actions',
- copy: 'zGbnIqw_copy',
- error: 'zGbnIqw_error',
- primary: 'zGbnIqw_primary',
-}
-export const onboardingStyles: Record<string, string> = {
- body: 'zGbnIqo_body',
- content: 'zGbnIqo_content',
- dialog: 'zGbnIqo_dialog',
- title: 'zGbnIqo_title',
-}
-export const onboardingDialogStyles: Record<string, string> = {
- description: 'zGbnIqd_description',
- editor: 'zGbnIqd_editor',
-}
+export const modelStyles: Record<string, string> = Object.fromEntries([...MODELS_CSS.matchAll(/\.(zGbnIq_(\w+))/g)].map(([, className, key]) => [key, className]))
+export const welcomeStyles: Record<string, string> = Object.fromEntries([...WELCOME_CSS.matchAll(/\.(zGbnIqw_(\w+))/g)].map(([, className, key]) => [key, className]))
+export const onboardingStyles: Record<string, string> = Object.fromEntries([...ONBOARDING_CSS.matchAll(/\.(zGbnIqo_(\w+))/g)].map(([, className, key]) => [key, className]))
+export const onboardingDialogStyles: Record<string, string> = Object.fromEntries([...ONBOARDING_DIALOG_CSS.matchAll(/\.(zGbnIqd_(\w+))/g)].map(([, className, key]) => [key, className]))
export const modelsStylesNode = c([MODELS_CSS, WELCOME_CSS, ONBOARDING_CSS, ONBOARDING_DIALOG_CSS])
diff --git a/packages/dsh-tauri-model/src/client/service/model-preset-fixtures.ts b/packages/dsh-tauri-model/src/client/service/__tests__/model-preset-fixtures.ts
similarity index 85%
rename from packages/dsh-tauri-model/src/client/service/model-preset-fixtures.ts
rename to packages/dsh-tauri-model/src/client/service/__tests__/model-preset-fixtures.ts
index 9449aa38..2f6701b5 100644
--- a/packages/dsh-tauri-model/src/client/service/model-preset-fixtures.ts
+++ b/packages/dsh-tauri-model/src/client/service/__tests__/model-preset-fixtures.ts
@@ -1,4 +1,4 @@
-import type { PresetTable } from '../../shared/model-presets'
+import type { PresetTable } from '../../../shared/model-presets'
export const PRESET_FIXTURE: PresetTable = {
'claude-3-5-sonnet': [1, 0, 200000, 8192],
diff --git a/packages/dsh-tauri-model/src/client/service/model-config.utils.test.ts b/packages/dsh-tauri-model/src/client/service/model-config.utils.test.ts
index 40bc395e..b7a7c0ba 100644
--- a/packages/dsh-tauri-model/src/client/service/model-config.utils.test.ts
+++ b/packages/dsh-tauri-model/src/client/service/model-config.utils.test.ts
@@ -1,14 +1,13 @@
import type { LlmDiscoveredModel } from '../types/remotes.ts'
import { beforeEach, describe, expect, it } from 'vitest'
+import { PRESET_FIXTURE } from './__tests__/model-preset-fixtures'
import {
hasModelConfig,
mergeModelCards,
modelConfigNotice,
withCount,
withDetail,
- withPath,
} from './model-config.utils'
-import { PRESET_FIXTURE } from './model-preset-fixtures'
import { setPresetTable } from './model-presets'
const found = (id: string, extra: Partial<LlmDiscoveredModel> = {}): LlmDiscoveredModel => ({ id, ...extra })
@@ -163,7 +162,6 @@ describe('mergeModelCards with presets', () => {
describe('copy placeholders', () => {
it('substitutes one placeholder without treating the rest as patterns', () => {
expect(withDetail('failed: {detail}', '$&')).toBe('failed: $&')
- expect(withPath('opened {path}', 'C:\\a\\b')).toBe('opened C:\\a\\b')
expect(withCount('applied to {n} models', 3)).toBe('applied to 3 models')
})
})
diff --git a/packages/dsh-tauri-model/src/client/service/model-config.utils.ts b/packages/dsh-tauri-model/src/client/service/model-config.utils.ts
index 12a0c073..ee37da07 100644
--- a/packages/dsh-tauri-model/src/client/service/model-config.utils.ts
+++ b/packages/dsh-tauri-model/src/client/service/model-config.utils.ts
@@ -66,10 +66,6 @@ export function withDetail(template: string, detail: string): string {
return template.replace('{detail}', () => detail)
}
-export function withPath(template: string, path: string): string {
- return template.replace('{path}', () => path)
-}
-
export function withCount(template: string, count: number): string {
return template.replace('{n}', () => String(count))
}
diff --git a/packages/dsh-tauri-model/src/client/service/model-presets.test.ts b/packages/dsh-tauri-model/src/client/service/model-presets.test.ts
index 41dea2cf..21586287 100644
--- a/packages/dsh-tauri-model/src/client/service/model-presets.test.ts
+++ b/packages/dsh-tauri-model/src/client/service/model-presets.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it } from 'vitest'
-import { PRESET_FIXTURE } from './model-preset-fixtures'
-import { presetFor, presetTableSize, setPresetTable } from './model-presets'
+import { PRESET_FIXTURE } from './__tests__/model-preset-fixtures'
+import { presetFor, setPresetTable } from './model-presets'
const GRADED = { off: null, low: 'low', medium: 'medium', high: 'high' }
const VISION = ['text', 'image']
@@ -51,10 +51,6 @@ describe('presetFor with the downloaded table', () => {
it('hands out a fresh effort map so one row cannot mutate another', () => {
expect(presetFor('o3')?.efforts).not.toBe(presetFor('o3')?.efforts)
})
-
- it('reports how many rows are loaded', () => {
- expect(presetTableSize()).toBe(Object.keys(PRESET_FIXTURE).length)
- })
})
describe('presetFor without the table', () => {
diff --git a/packages/dsh-tauri-model/src/client/service/model-presets.ts b/packages/dsh-tauri-model/src/client/service/model-presets.ts
index bef830ed..e017c48a 100644
--- a/packages/dsh-tauri-model/src/client/service/model-presets.ts
+++ b/packages/dsh-tauri-model/src/client/service/model-presets.ts
@@ -39,10 +39,6 @@ export function setPresetTable(next: PresetTable): void {
table = next
}
-export function presetTableSize(): number {
- return Object.keys(table).length
-}
-
function ruleFacts(id: string): { vision: boolean, reasoning: boolean } | undefined {
let vision = false
let reasoning = false
diff --git a/packages/dsh-tauri-model/src/client/types/remotes.ts b/packages/dsh-tauri-model/src/client/types/remotes.ts
index 716cc803..25c919c8 100644
--- a/packages/dsh-tauri-model/src/client/types/remotes.ts
+++ b/packages/dsh-tauri-model/src/client/types/remotes.ts
@@ -1,13 +1,6 @@
-export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
+import type { JsonValue, LlmModelDiscoveryRequest, RemoteResult, LlmDiscoveredModel as UILlmDiscoveredModel } from 'dsh-tauri-ui/client'
-export interface RemoteFailure {
- code: string
- message: string
-}
-
-export type RemoteResult<T>
- = | { ok: true, value: T }
- | { ok: false, error: RemoteFailure }
+export type { JsonValue, LlmModelDiscoveryRequest, RemoteFailure, RemoteResult } from 'dsh-tauri-ui/client'
export interface CredentialInfo {
configured: boolean
@@ -49,13 +42,6 @@ export interface LlmConfigurableProvider {
error?: string
}
-export interface LlmModelDiscoveryRequest {
- provider?: string
- baseURL?: string
- api?: string
- apiKey?: string
-}
-
export interface LlmCatalogModel {
id: string
name: string
@@ -74,11 +60,7 @@ export interface LlmModelCatalog {
groups: readonly LlmCatalogGroup[]
}
-export interface LlmDiscoveredModel {
- id: string
- name?: string
- contextWindow?: number
- maxTokens?: number
+export interface LlmDiscoveredModel extends UILlmDiscoveredModel {
inputModalities?: readonly string[]
}
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.tsx b/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.tsx
index 0cf79941..0a454be0 100644
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.tsx
+++ b/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.tsx
@@ -1,8 +1,19 @@
import type { ReactElement } from 'react'
-import type { AutoConfigAllButtonProps } from './auto-config-all-button.types'
+import type { ModelDiscoveryChannel } from '../../service/model-config'
+import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar'
+import type { Translate } from './types'
import { Action, Text } from 'dsh-tauri-ui/client'
import { useModelConfigFetch } from './use-model-config-fetch'
+export interface AutoConfigAllButtonProps {
+ t: Translate
+ models: readonly ModelDraft[]
+ probe: ModelProbeTarget
+ operations?: ModelDiscoveryChannel
+ disabled?: boolean
+ onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
+}
+
export function AutoConfigAllButton({ t, models, probe, operations, disabled, onApply }: AutoConfigAllButtonProps): ReactElement {
const { busy, failure, notice, run } = useModelConfigFetch({ t, models, probe, operations, onApply })
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.types.ts b/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.types.ts
deleted file mode 100644
index 3a1d452c..00000000
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/auto-config-all-button.types.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import type { ModelDiscoveryChannel } from '../../service/model-config'
-import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar'
-import type { Translate } from './types'
-
-export interface AutoConfigAllButtonProps {
- t: Translate
- models: readonly ModelDraft[]
- probe: ModelProbeTarget
- operations?: ModelDiscoveryChannel
- disabled?: boolean
- onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
-}
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/index.ts b/packages/dsh-tauri-model/src/client/ui/model-extras/index.ts
index 39c06fa8..28064689 100644
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/index.ts
+++ b/packages/dsh-tauri-model/src/client/ui/model-extras/index.ts
@@ -1,11 +1,11 @@
export { AutoConfigAllButton } from './auto-config-all-button'
-export type { AutoConfigAllButtonProps } from './auto-config-all-button.types'
+export type { AutoConfigAllButtonProps } from './auto-config-all-button'
export { ModelCompatFields } from './model-compat-fields'
export type { ModelCompatFieldsProps } from './model-compat-fields'
export { ModelConfigToolbar } from './model-config-toolbar'
export type { ModelConfigToolbarProps, ModelDraft, ModelProbeTarget } from './model-config-toolbar'
export { ModelFetchConfigButton } from './model-fetch-config-button'
-export type { ModelFetchConfigButtonProps } from './model-fetch-config-button.types'
+export type { ModelFetchConfigButtonProps } from './model-fetch-config-button'
export { MODEL_EXTRAS_KEYS, modelExtrasTranslate } from './translate'
export type { Translate } from './types'
export { useModelConfigFetch } from './use-model-config-fetch'
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.tsx b/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.tsx
index 121f7836..0e44d98a 100644
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.tsx
+++ b/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.tsx
@@ -1,9 +1,21 @@
import type { ReactElement } from 'react'
-import type { ModelFetchConfigButtonProps } from './model-fetch-config-button.types'
+import type { ModelDiscoveryChannel } from '../../service/model-config'
+import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar'
+import type { Translate } from './types'
import { Action, Text } from 'dsh-tauri-ui/client'
import { hasModelConfig } from '../../service/model-config.utils'
import { useModelConfigFetch } from './use-model-config-fetch'
+export interface ModelFetchConfigButtonProps {
+ t: Translate
+ modelId: string
+ models: readonly ModelDraft[]
+ probe: ModelProbeTarget
+ operations?: ModelDiscoveryChannel
+ disabled?: boolean
+ onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
+}
+
export function ModelFetchConfigButton({
t,
modelId,
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.types.ts b/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.types.ts
deleted file mode 100644
index b404b6c6..00000000
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/model-fetch-config-button.types.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { ModelDiscoveryChannel } from '../../service/model-config'
-import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar'
-import type { Translate } from './types'
-
-export interface ModelFetchConfigButtonProps {
- t: Translate
- modelId: string
- models: readonly ModelDraft[]
- probe: ModelProbeTarget
- operations?: ModelDiscoveryChannel
- disabled?: boolean
- onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
-}