DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(dsh-tauri-session): reshape the routes into REST resources
hairyfbf1c0c1851b8
diff --git a/packages/dsh-tauri-session/src/client/constants/index.ts b/packages/dsh-tauri-session/src/client/constants/index.tsindex 736518b1..bbfae914 100644--- a/packages/dsh-tauri-session/src/client/constants/index.ts+++ b/packages/dsh-tauri-session/src/client/constants/index.ts@@ -1,6 +1,6 @@import { PLUGIN_ID } from '../../shared/constants'-export { SESSION_API_PREFIX, PLUGIN_ID, SESSION_SECTION_ORDER } from '../../shared/constants'+export { PLUGIN_ID, SESSION_SECTION_ORDER } from '../../shared/constants'export const SETTINGS_SECTION_SLOT = 'settings.section'export const SESSION_REGISTRANT = PLUGIN_IDdiff --git a/packages/dsh-tauri-session/src/client/service/archive.ts b/packages/dsh-tauri-session/src/client/service/archive.tsindex 97e05d22..f5abf185 100644--- a/packages/dsh-tauri-session/src/client/service/archive.ts+++ b/packages/dsh-tauri-session/src/client/service/archive.ts@@ -2,14 +2,14 @@ import type { ArchivedListPayload } from '../apis/index.type'import type { ActionOutcome, Resync } from './archive.types'import { uniq } from 'dsh-tauri/client'import {- deleteArchive,- deleteArchiveWorkspace,- getArchive,- postArchive,- postArchiveClear,- postArchiveWorkspace,- postOpenSessionDir,- postUnarchive,+ deleteSessionArchive,+ deleteSessionWorkspaceArchive,+ getSessionArchive,+ postSessionArchive,+ postSessionArchiveClear,+ postSessionArchiveRestore,+ postSessionOpenPath,+ postSessionWorkspaceArchive,} from '../apis'import { ARCHIVE_RESYNC_TIMEOUT_MS } from '../constants'import { locale } from '../locales'@@ -25,7 +25,7 @@ export async function fetchArchive(): Promise<ArchivedListPayload | null> {store.archive.loading = truestore.archive.error = ''try {- const payload = await getArchive()+ const payload = await getSessionArchive()if (!store.archive.isCurrentRefresh(generation))return nullstore.archive.archived = payload@@ -44,33 +44,33 @@ export async function fetchArchive(): Promise<ArchivedListPayload | null> {export function archiveSession(input: { sessionId: string }): Promise<ActionOutcome> {store.archive.suppressedSessionIds = store.archive.suppressedSessionIds.filter(id => id !== input.sessionId)- return runMutation({ mutate: () => postArchive({ sessionId: input.sessionId }) })+ return runMutation({ mutate: () => postSessionArchive({ sessionId: input.sessionId }) })}export function archiveWorkspace(input: { workspaceId: string, sessionIds: readonly string[] }): Promise<ActionOutcome> {- return runMutation({ mutate: () => postArchiveWorkspace({ workspaceId: input.workspaceId, sessionIds: input.sessionIds }) })+ return runMutation({ mutate: () => postSessionWorkspaceArchive({ workspaceId: input.workspaceId, sessionIds: [...input.sessionIds] }) })}export function unarchiveSession(input: { sessionId: string, resync?: Resync }): Promise<ActionOutcome> {- return runMutation({ mutate: () => postUnarchive({ sessionId: input.sessionId }), resync: input.resync, sessionIds: [input.sessionId] })+ return runMutation({ mutate: () => postSessionArchiveRestore({ sessionId: input.sessionId }), resync: input.resync, sessionIds: [input.sessionId] })}export function deleteSession(input: { sessionId: string, resync?: Resync }): Promise<ActionOutcome> {- return runMutation({ mutate: () => deleteArchive({ sessionId: input.sessionId }), resync: input.resync, sessionIds: [input.sessionId] })+ return runMutation({ mutate: () => deleteSessionArchive({ sessionId: input.sessionId }), resync: input.resync, sessionIds: [input.sessionId] })}export function deleteWorkspaceSessions(input: { sessionIds: readonly string[], resync?: Resync }): Promise<ActionOutcome> {- return runMutation({ mutate: () => deleteArchiveWorkspace({ sessionIds: input.sessionIds }), resync: input.resync, sessionIds: input.sessionIds })+ return runMutation({ mutate: () => deleteSessionWorkspaceArchive({ sessionIds: [...input.sessionIds] }), resync: input.resync, sessionIds: input.sessionIds })}export function clearArchive(input: { resync?: Resync } = {}): Promise<ActionOutcome> {const sessionIds = [...store.archive.archived.archivedSessionIds]- return runMutation({ mutate: () => postArchiveClear(), resync: input.resync, sessionIds })+ return runMutation({ mutate: () => postSessionArchiveClear(), resync: input.resync, sessionIds })}export async function openSessionDir(input: { sessionId: string }): Promise<ActionOutcome> {try {- const result = await postOpenSessionDir({ sessionId: input.sessionId })+ const result = await postSessionOpenPath({ sessionId: input.sessionId })if (!result.ok)throw new Error(locale.text('openFailed', { reason: result.error ?? '' }))return { ok: true }diff --git a/packages/dsh-tauri-session/src/client/service/archive.types.ts b/packages/dsh-tauri-session/src/client/service/archive.types.tsindex a5f051da..327696e9 100644--- a/packages/dsh-tauri-session/src/client/service/archive.types.ts+++ b/packages/dsh-tauri-session/src/client/service/archive.types.ts@@ -1,6 +1,7 @@-import type { ActionResult } from '../apis/index.type'-/** 变更后的宿主镜像重拉(工作区浏览器 / 会话列表),由组件侧装配。 */export type Resync = () => Promise<void>-export type ActionOutcome = ActionResult+export interface ActionOutcome {+ ok: boolean+ error?: string+}diff --git a/packages/dsh-tauri-session/src/host/apply.ts b/packages/dsh-tauri-session/src/host/apply.tsindex 76a50bd6..7ec20476 100644--- a/packages/dsh-tauri-session/src/host/apply.ts+++ b/packages/dsh-tauri-session/src/host/apply.ts@@ -1,5 +1,5 @@import type { HostContext } from 'dsh-tauri'-import type { SessionHost } from './config/runtime.types'+import type { SessionHost } from './types'import { PLUGIN_ID } from '../shared/constants'import { clearHostRuntime, setCurrentHostInstance } from './config/runtime'import { routes } from './routes'diff --git a/packages/dsh-tauri-session/src/host/config/constants.ts b/packages/dsh-tauri-session/src/host/config/constants.tsdeleted file mode 100644index 406c3e15..00000000--- a/packages/dsh-tauri-session/src/host/config/constants.ts+++ /dev/null@@ -1,10 +0,0 @@-export const SESSIONS_DIRECTORY = 'sessions'--export const SESSION_DIRECTORY_PREFIX = 'session-'--export const SESSION_ID_ESCAPE = '~'-export const DOT_SEGMENT = '.'-export const DOT_DOT_SEGMENT = '..'-export const DOT_ESCAPE = '~002E'--export const LOG_PREFIX = 'dsh-tauri-session'diff --git a/packages/dsh-tauri-session/src/host/config/runtime.ts b/packages/dsh-tauri-session/src/host/config/runtime.tsindex 6e96554a..cedcb419 100644--- a/packages/dsh-tauri-session/src/host/config/runtime.ts+++ b/packages/dsh-tauri-session/src/host/config/runtime.ts@@ -1,4 +1,4 @@-import type { SessionHost } from './runtime.types'+import type { SessionHost } from '../types'import { defineHostRuntime } from 'dsh-tauri'export const { setCurrentHostInstance, getCurrentHostInstance } = defineHostRuntime<SessionHost>()diff --git a/packages/dsh-tauri-session/src/host/routes/index.test.ts b/packages/dsh-tauri-session/src/host/routes/index.test.tsindex 6dbb319d..c7fc92dc 100644--- a/packages/dsh-tauri-session/src/host/routes/index.test.ts+++ b/packages/dsh-tauri-session/src/host/routes/index.test.ts@@ -2,7 +2,7 @@* host/routes/index.test.ts — 归档路由声明的协议回归(RESTful 资源化后)。** 覆盖(迁移契约):路由表的 (kind, path) 与声明方法、方法不符时 405 + allow 头、- * OPTIONS 预检 204、GET /session/archive 的载荷形状、POST /session/open-path 的 400+ * OPTIONS 预检 204、GET /session/archive 的载荷形状、POST /session/open/path 的 400* 领域错误、DELETE 路由的请求体仍按 JSON 解析、`/session/archive/clear` 的 POST 与* DELETE 双方法登记。*@@ -18,9 +18,10 @@ import type { AddressInfo } from 'node:net'import { createServer } from 'node:http'import { afterEach, describe, expect, it } from 'vitest'import { routes } from '.'-import { SESSION_API_PREFIX as P } from '../../shared/constants'import { setCurrentHostInstance } from '../config/runtime'+const P = '/api/desktop/dsh-tauri-session'+const routeKey = (kind: string, path: string): string => `${kind}\u0000${path}`/**@@ -35,8 +36,8 @@ const EXPECTED_ROUTES: ReadonlyArray<readonly [string, string]> = [['DELETE', `${P}/session/archive/clear`],['POST', `${P}/session/workspace/archive`],['DELETE', `${P}/session/workspace/archive`],- ['POST', `${P}/session/unarchive`],- ['POST', `${P}/session/open-path`],+ ['POST', `${P}/session/archive/restore`],+ ['POST', `${P}/session/open/path`],]/** 去重后的宿主注册行(同一路径的多个方法由 defineRoutes 收敛为一行)。 */@@ -50,8 +51,8 @@ const ALLOW_BY_PATH: Readonly<Record<string, string>> = {[`${P}/session/archive`]: 'GET, HEAD, POST, DELETE, OPTIONS',[`${P}/session/archive/clear`]: 'POST, DELETE, OPTIONS',[`${P}/session/workspace/archive`]: 'POST, DELETE, OPTIONS',- [`${P}/session/unarchive`]: 'POST, OPTIONS',- [`${P}/session/open-path`]: 'POST, OPTIONS',+ [`${P}/session/archive/restore`]: 'POST, OPTIONS',+ [`${P}/session/open/path`]: 'POST, OPTIONS',}/** 所有路径都未声明 PUT,用于统一验证 405 + allow。 */@@ -246,18 +247,18 @@ describe('归档路由声明', () => {dispose()})- it('pOST /session/open-path 缺少 sessionId 或目录不存在时返回 400 领域错误', async () => {+ it('pOST /session/open/path 缺少 sessionId 或目录不存在时返回 400 领域错误', async () => {const harness = createHarness()const dispose = mount(harness)const base = await listen(harness.registered)- const missing = await postJson(base, `${P}/session/open-path`, 'POST', '{}')+ const missing = await postJson(base, `${P}/session/open/path`, 'POST', '{}')expect(missing.status).toBe(400)expect(await missing.json()).toEqual({ ok: false, error: 'invalid-session-id' })const unknown = await postJson(base,- `${P}/session/open-path`,+ `${P}/session/open/path`,'POST',JSON.stringify({ sessionId: '__missing_session__' }),)@@ -272,14 +273,14 @@ describe('归档路由声明', () => {const dispose = mount(harness)const base = await listen(harness.registered)- const arrayBody = await postJson(base, `${P}/session/open-path`, 'POST', '[]')+ const arrayBody = await postJson(base, `${P}/session/open/path`, 'POST', '[]')expect(arrayBody.status).toBe(400)- const invalidJson = await postJson(base, `${P}/session/open-path`, 'POST', 'not-json')+ const invalidJson = await postJson(base, `${P}/session/open/path`, 'POST', 'not-json')expect(invalidJson.status).toBe(400)// 请求体一律按 JSON 解析:urlencoded 体不会被当成合法对象放行。- const urlencoded = await fetch(`${base}${P}/session/open-path`, {+ const urlencoded = await fetch(`${base}${P}/session/open/path`, {method: 'POST',headers: { 'content-type': 'application/x-www-form-urlencoded' },body: 'sessionId=archived-1',diff --git a/packages/dsh-tauri-session/src/host/routes/index.ts b/packages/dsh-tauri-session/src/host/routes/index.tsindex 7a4d2d4f..4207aeb9 100644--- a/packages/dsh-tauri-session/src/host/routes/index.ts+++ b/packages/dsh-tauri-session/src/host/routes/index.ts@@ -1,16 +1,15 @@import { defineRoutes } from 'dsh-tauri'-import { SESSION_API_PREFIX } from '../../shared/constants'import clearSessionArchive from './session/archive/clear/post'import deleteSessionArchive from './session/archive/delete'import getSessionArchive from './session/archive/get'import postSessionArchive from './session/archive/post'-import postSessionOpenPath from './session/open-path/post'-import postSessionUnarchive from './session/unarchive/post'+import postSessionUnarchive from './session/archive/restore/post'+import postSessionOpenPath from './session/open/path/post'import deleteSessionWorkspaceArchive from './session/workspace/archive/delete'import postSessionWorkspaceArchive from './session/workspace/archive/post'-const SESSION_ARCHIVE = `${SESSION_API_PREFIX}/session/archive`-const SESSION_WORKSPACE_ARCHIVE = `${SESSION_API_PREFIX}/session/workspace/archive`+const SESSION_ARCHIVE = '/api/desktop/dsh-tauri-session/session/archive'+const SESSION_WORKSPACE_ARCHIVE = '/api/desktop/dsh-tauri-session/session/workspace/archive'/*** 归档资源路由声明(文件路径 = URL 路径)。@@ -27,6 +26,6 @@ export const routes = defineRoutes((disposer) => {disposer.post({ kind: 'exact', path: SESSION_WORKSPACE_ARCHIVE }, postSessionWorkspaceArchive)disposer.delete({ kind: 'exact', path: SESSION_WORKSPACE_ARCHIVE }, deleteSessionWorkspaceArchive)- disposer.post({ kind: 'exact', path: `${SESSION_API_PREFIX}/session/unarchive` }, postSessionUnarchive)- disposer.post({ kind: 'exact', path: `${SESSION_API_PREFIX}/session/open-path` }, postSessionOpenPath)+ disposer.post({ kind: 'exact', path: `${SESSION_ARCHIVE}/restore` }, postSessionUnarchive)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-session/session/open/path' }, postSessionOpenPath)})diff --git a/packages/dsh-tauri-session/src/host/routes/index.types.ts b/packages/dsh-tauri-session/src/host/routes/index.types.tsnew file mode 100644index 00000000..0f5fe4cb--- /dev/null+++ b/packages/dsh-tauri-session/src/host/routes/index.types.ts@@ -0,0 +1,18 @@+/** 路由请求体契约:生成客户端据此产出 `Types.*Body`(形状校验仍在处理器内做)。 */++export interface SessionIdBody {+ sessionId: string+}++export interface SessionIdsBody {+ sessionIds: string[]+}++export interface WorkspaceArchiveBody extends SessionIdsBody {+ workspaceId?: string+}++export interface OpenSessionDirResult {+ ok: boolean+ error?: string+}diff --git a/packages/dsh-tauri-session/src/host/routes/session/archive/delete.ts b/packages/dsh-tauri-session/src/host/routes/session/archive/delete.tsindex 630de7ab..956ce6f6 100644--- a/packages/dsh-tauri-session/src/host/routes/session/archive/delete.ts+++ b/packages/dsh-tauri-session/src/host/routes/session/archive/delete.ts@@ -1,8 +1,9 @@+import type { SessionIdBody } from '../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../service/archive'export default defineEventHandler(async (event) => {- const body = await readBody<{ sessionId?: unknown }>(event, { type: 'json' })+ const body = await readBody<SessionIdBody>(event, { type: 'json' })const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''if (sessionId.length === 0) {event.res.status = 400diff --git a/packages/dsh-tauri-session/src/host/routes/session/archive/get.ts b/packages/dsh-tauri-session/src/host/routes/session/archive/get.tsindex 08d9d573..5c9bf33a 100644--- a/packages/dsh-tauri-session/src/host/routes/session/archive/get.ts+++ b/packages/dsh-tauri-session/src/host/routes/session/archive/get.ts@@ -1,4 +1,5 @@+import type { ArchivedListPayload } from '../../../service/ledger.types'import { defineEventHandler } from 'dsh-tauri'import { ledger } from '../../../service/ledger'-export default defineEventHandler(() => ledger.load())+export default defineEventHandler((): ArchivedListPayload => ledger.load())diff --git a/packages/dsh-tauri-session/src/host/routes/session/archive/post.ts b/packages/dsh-tauri-session/src/host/routes/session/archive/post.tsindex af6838c1..6fe31195 100644--- a/packages/dsh-tauri-session/src/host/routes/session/archive/post.ts+++ b/packages/dsh-tauri-session/src/host/routes/session/archive/post.ts@@ -1,8 +1,9 @@+import type { SessionIdBody } from '../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../service/archive'export default defineEventHandler(async (event) => {- const body = await readBody<{ sessionId?: unknown }>(event, { type: 'json' })+ const body = await readBody<SessionIdBody>(event, { type: 'json' })const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''if (sessionId.length === 0) {event.res.status = 400diff --git a/packages/dsh-tauri-session/src/host/routes/session/unarchive/post.ts b/packages/dsh-tauri-session/src/host/routes/session/archive/restore/post.tssimilarity index 66%rename from packages/dsh-tauri-session/src/host/routes/session/unarchive/post.tsrename to packages/dsh-tauri-session/src/host/routes/session/archive/restore/post.tsindex ee2400ea..2ff0dcd7 100644--- a/packages/dsh-tauri-session/src/host/routes/session/unarchive/post.ts+++ b/packages/dsh-tauri-session/src/host/routes/session/archive/restore/post.ts@@ -1,8 +1,9 @@+import type { SessionIdBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'-import { archive } from '../../../service/archive'+import { archive } from '../../../../service/archive'export default defineEventHandler(async (event) => {- const body = await readBody<{ sessionId?: unknown }>(event, { type: 'json' })+ const body = await readBody<SessionIdBody>(event, { type: 'json' })const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''if (sessionId.length === 0) {event.res.status = 400diff --git a/packages/dsh-tauri-session/src/host/routes/session/open-path/post.ts b/packages/dsh-tauri-session/src/host/routes/session/open-path/post.tsdeleted file mode 100644index 8358ebf1..00000000--- a/packages/dsh-tauri-session/src/host/routes/session/open-path/post.ts+++ /dev/null@@ -1,16 +0,0 @@-import { defineEventHandler, readBody } from 'dsh-tauri'-import { sessionFiles } from '../../../service/session-files'--export default defineEventHandler(async (event) => {- const body = await readBody<{ sessionId?: unknown }>(event, { type: 'json' })- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''- if (sessionId.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-id' }- }-- const result = await sessionFiles.open(sessionId)- if (!result.ok)- event.res.status = 400- return result-})diff --git a/packages/dsh-tauri-session/src/host/routes/session/open/path/post.ts b/packages/dsh-tauri-session/src/host/routes/session/open/path/post.tsnew file mode 100644index 00000000..19f24d61--- /dev/null+++ b/packages/dsh-tauri-session/src/host/routes/session/open/path/post.ts@@ -0,0 +1,18 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { OpenSessionDirResult, SessionIdBody } from '../../../index.types'+import { defineEventHandler, readBody } from 'dsh-tauri'+import { session } from '../../../../service/session'++export default defineEventHandler<EventHandlerRequest, Promise<OpenSessionDirResult>>(async (event) => {+ const body = await readBody<SessionIdBody>(event, { type: 'json' })+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''+ if (sessionId.length === 0) {+ event.res.status = 400+ return { ok: false as const, error: 'invalid-session-id' }+ }++ const result = await session.openDir(sessionId)+ if (!result.ok)+ event.res.status = 400+ return result+})diff --git a/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/delete.ts b/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/delete.tsindex 43762d48..2190d2e5 100644--- a/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/delete.ts+++ b/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/delete.ts@@ -1,8 +1,9 @@+import type { SessionIdsBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../../service/archive'export default defineEventHandler(async (event) => {- const body = await readBody<{ sessionIds?: unknown }>(event, { type: 'json' })+ const body = await readBody<SessionIdsBody>(event, { type: 'json' })const sessionIds = Array.isArray(body?.sessionIds)? body.sessionIds.map(String).filter(Boolean): []diff --git a/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/post.ts b/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/post.tsindex bcac18c4..efa32a5d 100644--- a/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/post.ts+++ b/packages/dsh-tauri-session/src/host/routes/session/workspace/archive/post.ts@@ -1,8 +1,9 @@+import type { WorkspaceArchiveBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../../service/archive'export default defineEventHandler(async (event) => {- const body = await readBody<{ sessionIds?: unknown }>(event, { type: 'json' })+ const body = await readBody<WorkspaceArchiveBody>(event, { type: 'json' })const sessionIds = Array.isArray(body?.sessionIds)? body.sessionIds.map(String).filter(Boolean): []diff --git a/packages/dsh-tauri-session/src/host/service/archive.ts b/packages/dsh-tauri-session/src/host/service/archive.tsindex fbbd0f88..81bc4bc5 100644--- a/packages/dsh-tauri-session/src/host/service/archive.ts+++ b/packages/dsh-tauri-session/src/host/service/archive.ts@@ -1,12 +1,12 @@import type { ArchivedListPayload } from './ledger.types'import { defineService } from 'dsh-tauri'import { compact, difference, isEmpty, uniq } from 'lodash-es'-import { LOG_PREFIX } from '../config/constants'import { getCurrentHostInstance } from '../config/runtime'import { archiveHooks } from '../events'import { ledger } from './ledger'-import { sessionFiles } from './session-files'-import { sessionStore } from './session-store'+import { session } from './session'++const LOG_PREFIX = 'dsh-tauri-session'export const archive = defineService({/** 归档一个会话并返回新的归档投影(幂等:已归档即无操作)。 */@@ -66,14 +66,14 @@ async function permanentlyDelete(rawIds: readonly string[]): Promise<{ ok: trueif (missing.length > 0)throw new Error(`会话 '${missing[0]}' 不在归档集合中,拒绝删除`)- const liveFailures = sessionStore.remove(ids)+ const liveFailures = session.remove(ids)for (const sessionId of liveFailures)host.logger?.warn?.(`[${LOG_PREFIX}] 会话 '${sessionId}' 无法从内存移除,刷新后消失`)let removed = 0for (const sessionId of ids) {try {- if (sessionFiles.remove(sessionId))+ if (session.removeDir(sessionId))removed += 1}catch (error) {diff --git a/packages/dsh-tauri-session/src/host/service/ledger.ts b/packages/dsh-tauri-session/src/host/service/ledger.tsindex f0327446..a9955c95 100644--- a/packages/dsh-tauri-session/src/host/service/ledger.ts+++ b/packages/dsh-tauri-session/src/host/service/ledger.ts@@ -1,9 +1,9 @@-import type { ArchiveRegistrySurface, ArchiveTableSurface, SessionLike, WorkspaceEntryLike } from '../config/runtime.types'+import type { ArchiveRegistrySurface, ArchiveTableSurface, SessionLike, WorkspaceEntryLike } from '../types'import type { ArchiveAccounting, ArchivedListPayload } from './ledger.types'import { defineService } from 'dsh-tauri'import { difference, keyBy, uniq } from 'lodash-es'import { getCurrentHostInstance } from '../config/runtime'-import { sessionStore } from './session-store'+import { session } from './session'export const ledger = defineService({/**@@ -22,14 +22,14 @@ export const ledger = defineService({const archivedSessionIds: string[] = []const meta: ArchivedListPayload['meta'] = {}for (const sessionId of getCurrentHostInstance().workspaceRegistry.archivedSessionIds ?? []) {- const session = sessionStore.load(sessionId)- if (session === null)+ const entry = session.get(sessionId)+ if (entry === null)continuearchivedSessionIds.push(sessionId)- const title = session.displayTitle ?? session.title+ const title = entry.displayTitle ?? entry.titlemeta[sessionId] = {- createdAt: session.header?.createdAt,- cwd: cwdOf(session),+ createdAt: entry.header?.createdAt,+ cwd: cwdOf(entry),...(title === undefined ? {} : { title }),}}@@ -107,7 +107,7 @@ async function restoreWorkspaceAccounting(registry: ArchiveRegistrySurface, sessreturnconst byPath = keyBy<WorkspaceEntryLike>(workspaces, 'path')for (const sessionId of sessionIds) {- const cwd = cwdOf(sessionStore.load(sessionId))+ const cwd = cwdOf(session.get(sessionId))const workspace = cwd ? byPath[cwd] : undefinedif (!workspace || workspace.sessionIds?.includes(sessionId))continuediff --git a/packages/dsh-tauri-session/src/host/service/ledger.types.ts b/packages/dsh-tauri-session/src/host/service/ledger.types.tsindex db62bf30..0189e25e 100644--- a/packages/dsh-tauri-session/src/host/service/ledger.types.ts+++ b/packages/dsh-tauri-session/src/host/service/ledger.types.ts@@ -1,4 +1,4 @@-/** `GET /api/dsh-session/session/archive` 的线上载荷。 */+/** `GET /api/desktop/dsh-tauri-session/session/archive` 的线上载荷。 */export interface ArchivedListPayload {archivedSessionIds: string[]meta: Record<string, { createdAt?: number, cwd?: string, title?: string }>diff --git a/packages/dsh-tauri-session/src/host/service/session-files.ts b/packages/dsh-tauri-session/src/host/service/session-files.tsdeleted file mode 100644index ede73766..00000000--- a/packages/dsh-tauri-session/src/host/service/session-files.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { OpenSessionDirectoryResult } from './session-files.types'-import { rmSync } from 'node:fs'-import { defineService, openDirectory } from 'dsh-tauri'-import { dirname, resolve } from 'pathe'-import { findSessionDataDir, isWithinRoot, readDirectory, sessionsRoot } from './session-files.utils'--export const sessionFiles = defineService({- /** 只读定位会话持久化数据目录;未找到返回 null。 */- load(sessionId: string): string | null {- if (!sessionId)- return null- return findSessionDataDir(sessionsRoot(), sessionId)- },-- /** 物理删除会话数据目录(找不到即 false),并清理删除后变空的父目录。 */- remove(sessionId: string): boolean {- const root = sessionsRoot()- const dir = sessionId ? findSessionDataDir(root, sessionId) : null- if (dir === null)- return false- rmSync(dir, { recursive: true, force: true })- pruneEmptyParents(root, dirname(dir))- return true- },-- /** 在系统文件管理器中打开会话数据目录(路径由 sessionId 有界解析,不接受客户端路径)。 */- async open(sessionId: string): Promise<OpenSessionDirectoryResult> {- const dir = sessionId ? findSessionDataDir(sessionsRoot(), sessionId) : null- if (dir === null)- return { ok: false, error: 'session-directory-not-found' }- try {- await openDirectory(dir)- }- catch {- return { ok: false, error: 'not-a-directory' }- }- return { ok: true }- },-})--// --- internal -----function pruneEmptyParents(root: string, parent: string): void {- if (!isWithinRoot(root, parent) || resolve(parent) === resolve(root))- return- const entries = readDirectory(parent)- if (entries === null || entries.length > 0)- return- rmSync(parent, { recursive: true, force: true })- pruneEmptyParents(root, dirname(parent))-}diff --git a/packages/dsh-tauri-session/src/host/service/session-store.ts b/packages/dsh-tauri-session/src/host/service/session-store.tsdeleted file mode 100644index 4ca3b28a..00000000--- a/packages/dsh-tauri-session/src/host/service/session-store.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { SessionLike } from '../config/runtime.types'-import { defineService } from 'dsh-tauri'-import { compact } from 'lodash-es'-import { getCurrentHostInstance } from '../config/runtime'--export const sessionStore = defineService({- /** 读宿主内存会话对象(get 缺失时回退到会话枚举)。 */- load(sessionId: string): SessionLike | null {- if (!sessionId)- return null- const sessions = getCurrentHostInstance().sessions- return sessions.get?.(sessionId)- ?? sessions.list?.().find(session => session.id === sessionId)- ?? null- },-- /**- * 从宿主内存会话 store 移除(best-effort),返回无法移除的 id。- * 删除所需面在触碰任何数据之前校验,缺失即抛错,保证失败可整体重试。- */- remove(sessionIds: readonly string[]): string[] {- const sessions = getCurrentHostInstance().sessions- const live = compact(sessionIds.map(sessionId => (sessions.get?.(sessionId) ? sessionId : null)))- if (live.length > 0 && !sessions.remove)- throw new Error('宿主未提供 SessionStore.remove,请先更新桌面壳')- return live.filter(sessionId => !sessions.remove?.(sessionId))- },-})diff --git a/packages/dsh-tauri-session/src/host/service/session-files.test.ts b/packages/dsh-tauri-session/src/host/service/session.test.tssimilarity index 73%rename from packages/dsh-tauri-session/src/host/service/session-files.test.tsrename to packages/dsh-tauri-session/src/host/service/session.test.tsindex 98fa5ef4..28717004 100644--- a/packages/dsh-tauri-session/src/host/service/session-files.test.ts+++ b/packages/dsh-tauri-session/src/host/service/session.test.ts@@ -2,7 +2,7 @@ import { existsSync, mkdirSync } from 'node:fs'import { join } from 'pathe'import { beforeEach, describe, expect, it, vi } from 'vitest'import { resetTestDshHome, testDshHome } from '../../../../.test/test-utils'-import { sessionFiles } from './session-files'+import { session } from './session'vi.mock('dsh-tauri', async (importOriginal) => {const actual = await importOriginal<typeof import('dsh-tauri')>()@@ -20,52 +20,52 @@ function makeSessionDir(group: string | undefined, marker: string): string {return dir}-describe('sessionFiles.load', () => {+describe('session.getDir', () => {it('finds a depth-2 session data directory (sessions/<group>/session-<id>)', () => {const dir = makeSessionDir('--project-a--', 'session-abc')- expect(sessionFiles.load('abc')).toBe(dir)+ expect(session.getDir('abc')).toBe(dir)})it('finds a depth-1 session data directory (sessions/session-<id>)', () => {const dir = makeSessionDir(undefined, 'session-xyz')- expect(sessionFiles.load('xyz')).toBe(dir)+ expect(session.getDir('xyz')).toBe(dir)})it('returns null when no session data directory exists', () => {- expect(sessionFiles.load('missing')).toBeNull()+ expect(session.getDir('missing')).toBeNull()})})-describe('sessionFiles.remove', () => {+describe('session.removeDir', () => {it('removes the located depth-2 directory', () => {makeSessionDir('--project-a--', 'session-abc')- expect(sessionFiles.remove('abc')).toBe(true)- expect(sessionFiles.load('abc')).toBeNull()+ expect(session.removeDir('abc')).toBe(true)+ expect(session.getDir('abc')).toBeNull()})it('prunes an empty parent group directory after removal', () => {makeSessionDir('--project-a--', 'session-abc')- expect(sessionFiles.remove('abc')).toBe(true)- expect(sessionFiles.load('abc')).toBeNull()+ expect(session.removeDir('abc')).toBe(true)+ expect(session.getDir('abc')).toBeNull()expect(existsSync(join(testDshHome, 'sessions', '--project-a--'))).toBe(false)})it('keeps a parent group directory that still holds other sessions', () => {makeSessionDir('--project-a--', 'session-abc')makeSessionDir('--project-a--', 'session-def')- expect(sessionFiles.remove('abc')).toBe(true)+ expect(session.removeDir('abc')).toBe(true)expect(existsSync(join(testDshHome, 'sessions', '--project-a--'))).toBe(true)- expect(sessionFiles.load('def')).toBe(join(testDshHome, 'sessions', '--project-a--', 'session-def'))+ expect(session.getDir('def')).toBe(join(testDshHome, 'sessions', '--project-a--', 'session-def'))})it('keeps the sessions root itself when a depth-1 directory is removed', () => {const dir = makeSessionDir(undefined, 'session-xyz')- expect(sessionFiles.remove('xyz')).toBe(true)+ expect(session.removeDir('xyz')).toBe(true)expect(existsSync(dir)).toBe(false)expect(existsSync(join(testDshHome, 'sessions'))).toBe(true)})it('reports false when the session has no data directory', () => {- expect(sessionFiles.remove('ghost')).toBe(false)+ expect(session.removeDir('ghost')).toBe(false)})})diff --git a/packages/dsh-tauri-session/src/host/service/session.ts b/packages/dsh-tauri-session/src/host/service/session.tsnew file mode 100644index 00000000..2668d3fe--- /dev/null+++ b/packages/dsh-tauri-session/src/host/service/session.ts@@ -0,0 +1,76 @@+import type { SessionLike } from '../types'+import type { OpenSessionDirectoryResult } from './session.types'+import { rmSync } from 'node:fs'+import { defineService, openDirectory } from 'dsh-tauri'+import { compact } from 'lodash-es'+import { dirname, resolve } from 'pathe'+import { getCurrentHostInstance } from '../config/runtime'+import { findSessionDataDir, isWithinRoot, readDirectory, sessionsRoot } from './session.utils'++export const session = defineService({+ /** 读宿主内存会话对象(get 缺失时回退到会话枚举)。 */+ get(id: string): SessionLike | null {+ if (!id)+ return null+ const sessions = getCurrentHostInstance().sessions+ return sessions.get?.(id)+ ?? sessions.list?.().find(item => item.id === id)+ ?? null+ },++ /**+ * 从宿主内存会话 store 移除(best-effort),返回无法移除的 id。+ * 删除所需面在触碰任何数据之前校验,缺失即抛错,保证失败可整体重试。+ */+ remove(ids: readonly string[]): string[] {+ const sessions = getCurrentHostInstance().sessions+ const live = compact(ids.map(id => (sessions.get?.(id) ? id : null)))+ if (live.length > 0 && !sessions.remove)+ throw new Error('宿主未提供 SessionStore.remove,请先更新桌面壳')+ return live.filter(id => !sessions.remove?.(id))+ },++ /** 只读定位会话持久化数据目录;未找到返回 null。 */+ getDir(id: string): string | null {+ if (!id)+ return null+ return findSessionDataDir(sessionsRoot(), id)+ },++ /** 物理删除会话数据目录(找不到即 false),并清理删除后变空的父目录。 */+ removeDir(id: string): boolean {+ const root = sessionsRoot()+ const dir = id ? findSessionDataDir(root, id) : null+ if (dir === null)+ return false+ rmSync(dir, { recursive: true, force: true })+ pruneEmptyParents(root, dirname(dir))+ return true+ },++ /** 在系统文件管理器中打开会话数据目录(路径由 id 有界解析,不接受客户端路径)。 */+ async openDir(id: string): Promise<OpenSessionDirectoryResult> {+ const dir = id ? findSessionDataDir(sessionsRoot(), id) : null+ if (dir === null)+ return { ok: false, error: 'session-directory-not-found' }+ try {+ await openDirectory(dir)+ }+ catch {+ return { ok: false, error: 'not-a-directory' }+ }+ return { ok: true }+ },+})++// --- internal ---++function pruneEmptyParents(root: string, parent: string): void {+ if (!isWithinRoot(root, parent) || resolve(parent) === resolve(root))+ return+ const entries = readDirectory(parent)+ if (entries === null || entries.length > 0)+ return+ rmSync(parent, { recursive: true, force: true })+ pruneEmptyParents(root, dirname(parent))+}diff --git a/packages/dsh-tauri-session/src/host/service/session-files.types.ts b/packages/dsh-tauri-session/src/host/service/session.types.tssimilarity index 100%rename from packages/dsh-tauri-session/src/host/service/session-files.types.tsrename to packages/dsh-tauri-session/src/host/service/session.types.tsdiff --git a/packages/dsh-tauri-session/src/host/service/session-files.utils.ts b/packages/dsh-tauri-session/src/host/service/session.utils.tssimilarity index 91%rename from packages/dsh-tauri-session/src/host/service/session-files.utils.tsrename to packages/dsh-tauri-session/src/host/service/session.utils.tsindex 847cad0b..0958ef33 100644--- a/packages/dsh-tauri-session/src/host/service/session-files.utils.ts+++ b/packages/dsh-tauri-session/src/host/service/session.utils.ts@@ -1,14 +1,18 @@import { readdirSync } from 'node:fs'import { DSH_HOME } from 'dsh-tauri'import { join, resolve, sep } from 'pathe'-import {- DOT_DOT_SEGMENT,- DOT_ESCAPE,- DOT_SEGMENT,- SESSION_DIRECTORY_PREFIX,- SESSION_ID_ESCAPE,- SESSIONS_DIRECTORY,-} from '../config/constants'++const SESSIONS_DIRECTORY = 'sessions'++const SESSION_DIRECTORY_PREFIX = 'session-'++const SESSION_ID_ESCAPE = '~'++const DOT_SEGMENT = '.'++const DOT_DOT_SEGMENT = '..'++const DOT_ESCAPE = '~002E'export function sessionsRoot(): string {return join(DSH_HOME, SESSIONS_DIRECTORY)diff --git a/packages/dsh-tauri-session/src/host/config/runtime.types.ts b/packages/dsh-tauri-session/src/host/types/index.tssimilarity index 100%rename from packages/dsh-tauri-session/src/host/config/runtime.types.tsrename to packages/dsh-tauri-session/src/host/types/index.tsdiff --git a/packages/dsh-tauri-session/src/index.ts b/packages/dsh-tauri-session/src/index.tsindex 56d3a9cb..5193e315 100644--- a/packages/dsh-tauri-session/src/index.ts+++ b/packages/dsh-tauri-session/src/index.ts@@ -1,11 +1,10 @@-import { SESSION_API_PREFIX, PLUGIN_ID } from './shared/constants'+import { PLUGIN_ID } from './shared/constants'export const name = PLUGIN_IDexport const inject = ['webServer', 'sessions', 'workspaceRegistry', 'connection']-export const API_PREFIX = SESSION_API_PREFIX-export { apply } from './host/apply'+export { archiveHooks } from './host/events'export type { ArchiveLifecycleHooks } from './host/events'diff --git a/packages/dsh-tauri-session/src/shared/constants.ts b/packages/dsh-tauri-session/src/shared/constants.tsindex 280d1696..744a1746 100644--- a/packages/dsh-tauri-session/src/shared/constants.ts+++ b/packages/dsh-tauri-session/src/shared/constants.ts@@ -3,8 +3,5 @@/** 插件名(诊断元数据 / registrant)。 */export const PLUGIN_ID = 'dsh-tauri-session'-/** HTTP 路由前缀(host route + client rpc 同源 fetch)。 */-export const SESSION_API_PREFIX = '/api/dsh-session'-/** 归档设置分区的导航顺序(settings.section 槽)。 */export const SESSION_SECTION_ORDER = 220