feat(web): open the local settings file

This commit is contained in:
Yichen Jiang
2026-08-04 16:33:35 +08:00
parent 828cb2ae20
commit e31b7221e7
61 changed files with 939 additions and 98 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-settings-general/README.md
README.md: 0202d596f509feeba39a38254e8bab2fae27b649
README.zh.md: adec73edda00d34e209772f0bcc54a994f593997
README.md: d9aeaa37b3953f586821871118b009abd72b896d
README.zh.md: 96666e2d4d2087ca9579a1bcdd6a00ccfdaaa90d

View File

@@ -2,7 +2,9 @@
English | [中文](README.zh.md)
Settings ownerless-copy and product-onboarding plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the General section and its `settings.general.item` slot, the `settings` dictionaries, and the first ordered welcome step. Feature-owned rows (Permission, Language, Appearance), sections (Models), and conditional onboarding steps stay with their feature packages.
Settings ownerless-copy and product-onboarding plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the local configuration-file action, the General section and its `settings.general.item` slot, the `settings` dictionaries, and the first ordered welcome step. Feature-owned rows (Permission, Language, Appearance), sections (Models), and conditional onboarding steps stay with their feature packages.
A loopback browser loads the provider's optional `documentPath` through `settings.describe` and renders **Open configuration file** only when the Host confirms one local file. The action sends the pathless, loopback-only `settings.openDocument` request; the Host resolves the provider path again, materializes an absent document, and hands it to a native text editor (`open -t` on macOS, bypassing a browser file association; the desktop file association on Linux and Windows). Open failures keep the action available and render a localized error. Remote browsers never register the action and never issue the privileged settings read.
`src/onboarding-copy.ts` is the single editable owner of the complete notice plus `WELCOME_NOTICE_VERSION`; both supported GUI locales intentionally render the same Chinese copy. The Host half registers `ui-onboarding` in the user-settings seam. A loopback browser compares `welcomeNoticeVersion` for exact equality and writes the current value only after Continue succeeds. The path mutation is idempotent across tabs and preserves sibling settings, while `host/settings-changed` makes an externally acknowledged notice advance without a reload. A non-loopback browser cannot access the privileged settings API: it still presents the notice, but Continue advances only the current browser process and a reload presents the notice again. A different version deliberately presents the notice again. The welcome page preserves every authored paragraph, gives the requested clause in the final paragraph the sole emphasis, initially focuses the title, and has no close, Escape, mask-click, or secondary path. None of its copy or acknowledgement enters a Session log or model request. The notice identifies `DSH_TELEMETRY_DISABLED=1` as the telemetry opt-out.

View File

@@ -2,7 +2,9 @@
[English](README.md) | 中文
设置界面无特定功能归属的文案与产品引导插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容,「通用」分区及其 `settings.general.item` slot、`settings` 字典,以及第一个有序欢迎步骤。归具体功能所有的行(「权限」、「语言」、「外观」)、分区(「模型」)和条件式首次使用引导步骤仍由各自的功能包提供。
设置界面无特定功能归属的文案与产品引导插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容、本地配置文件操作,「通用」分区及其 `settings.general.item` slot、`settings` 字典,以及第一个有序欢迎步骤。归具体功能所有的行(「权限」、「语言」、「外观」)、分区(「模型」)和条件式首次使用引导步骤仍由各自的功能包提供。
回环浏览器通过 `settings.describe` 加载提供方可选的 `documentPath`,且只有在 Host 确认存在一个本地文件时才渲染**打开配置文件**。该操作发送无路径参数且仅限回环访问的 `settings.openDocument` 请求;Host 会再次解析提供方路径、在文档缺失时将其创建出来,并交给原生文本编辑器(macOS 上使用 `open -t`,绕过浏览器文件关联;Linux 和 Windows 上使用桌面文件关联)。打开失败时该操作仍可使用,并渲染本地化错误。远程浏览器从不注册该操作,也从不发起这项特权 settings 读取。
`src/onboarding-copy.ts` 是完整通知文案和 `WELCOME_NOTICE_VERSION` 的唯一可编辑来源;GUI 支持的两种 locale 都有意渲染同一份中文文案。宿主端在 user-settings seam 中注册 `ui-onboarding`。loopback 浏览器会比较 `welcomeNoticeVersion` 是否精确相等,仅在「继续」操作成功后写入当前值。该路径变更在不同标签页间幂等,并会保留同级设置;`host/settings-changed` 则让页面在通知被外部确认后,无需重新加载即可推进。非 loopback 浏览器不能访问受保护的 settings API:它仍会显示通知,但「继续」只推进当前浏览器进程,重新加载后会再次显示通知。版本不同时,系统也会有意重新显示通知。欢迎页保留原文的每个段落,仅强调最后一段中指定的句段,初始焦点落在标题上,并且没有关闭操作、Escape、点击遮罩或次要操作路径。其文案和确认状态均不会进入会话日志或模型请求。通知明确以 `DSH_TELEMETRY_DISABLED=1` 作为遥测关闭方式。

View File

@@ -0,0 +1,16 @@
.action {
display: flex;
min-width: 0;
align-items: center;
gap: 8px;
}
.error {
max-width: 180px;
overflow: hidden;
color: var(--dsw-alias-state-error-primary);
font-size: 12px;
line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
}

View File

@@ -0,0 +1,50 @@
/** Optional settings-header action for opening a file-backed Host document. */
import { useEffect } from 'react'
import type { ReactNode } from 'react'
import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react'
import type { SettingsDocumentState, SettingsDocumentStore } from './settings-document-store.ts'
import css from './SettingsDocumentAction.module.css'
/** Registrant-owned dependencies of {@link SettingsDocumentAction}. */
export interface SettingsDocumentActionInjected {
/** Provider metadata and action state owner. */
controller: SettingsDocumentStore
/** Bound selector hook for the controller snapshot. */
useSnapshot: SnapshotSelectorHook<SettingsDocumentState>
}
/** Header-action owner share, localized copy, and the registrant's state face. */
export type SettingsDocumentActionProps =
PropsRuntime<'settings.action'> & PropsLocale<'settings'> & SettingsDocumentActionInjected
/**
* Render the open-document action only after Host metadata confirms a local file.
* @param props - header owner props, localized copy, and injected document state.
* @returns the action, or null while unavailable or unresolved.
*/
export function SettingsDocumentAction({ controller, useSnapshot, t }: SettingsDocumentActionProps): ReactNode {
const state = useSnapshot(snapshot => snapshot)
useEffect(() => {
if (state.status === 'idle') void controller.load()
}, [controller, state.status])
if (state.status !== 'ready') return null
return (
<div className={css.action}>
{state.error === null ? null : <span className={css.error} role="alert">{t('openDocument.error')}</span>}
<Button
variant="outline"
size="sm"
disabled={state.opening}
onClick={() => { void controller.open() }}
>
{t('openDocument')}
</Button>
</div>
)
}

View File

@@ -1,8 +1,8 @@
/**
* Settings ownerless-copy plugin, browser half: registers everything on the
* Settings surface that belongs to no single feature — the trigger/header
* chrome content, the General section, and the `settings` dictionaries.
* Feature-owned rows and sections stay with their features.
* chrome content, local-document action, General section, and `settings`
* dictionaries. Feature-owned rows and sections stay with their features.
* Export discipline: packages/client/AGENTS.md.
*/
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
@@ -15,6 +15,9 @@ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import { CloseLabel, HeaderContent, TriggerContent } from './chrome.tsx'
import { GeneralSection } from './GeneralSection.tsx'
import { SettingsDocumentAction } from './SettingsDocumentAction.tsx'
import type { SettingsDocumentActionInjected } from './SettingsDocumentAction.tsx'
import { SettingsDocumentStore } from './settings-document-store.ts'
import type { WelcomeNoticeInjected } from './WelcomeNotice.tsx'
import { WelcomeNotice } from './WelcomeNotice.tsx'
import { refreshWelcomeIfLoaded, WelcomeNoticeStore } from './welcome-store.ts'
@@ -27,6 +30,9 @@ export type {
export type {
GeneralSectionComponentProps,
} from './GeneralSection.tsx'
export type { SettingsDocumentActionInjected, SettingsDocumentActionProps } from './SettingsDocumentAction.tsx'
export type { SettingsDocumentState } from './settings-document-store.ts'
export { SettingsDocumentStore } from './settings-document-store.ts'
export type { WelcomeNoticeInjected, WelcomeNoticeProps } from './WelcomeNotice.tsx'
export type { WelcomeNoticeState } from './welcome-store.ts'
export type { SettingsKey } from './locales.ts'
@@ -61,6 +67,15 @@ export function apply(ctx: ClientContext): void {
// locale/change re-registration wiring.
const t = ctx.locale.bind(NS)
const connection = ctx.get('connection') as ConnectionHandle
const documentController = connection.isLoopback
? new SettingsDocumentStore(connection.api)
: undefined
const documentInjected = documentController === undefined
? undefined
: (() => {
const useSnapshot = bindSnapshotSelector(documentController.store)
return (): SettingsDocumentActionInjected => ({ controller: documentController, useSnapshot })
})()
const welcomeController = new WelcomeNoticeStore(connection.api, connection.isLoopback ? 'host' : 'memory')
const useWelcomeSnapshot = bindSnapshotSelector(welcomeController.store)
const welcomeInjected = (): WelcomeNoticeInjected => ({
@@ -84,6 +99,16 @@ export function apply(ctx: ClientContext): void {
ctx.slots.register({ name: 'settings.trigger', locale: NS }, TriggerContent))
const header = deferRegistration(ctx.slots, 'settings.header', HeaderContent, () =>
ctx.slots.register({ name: 'settings.header', locale: NS }, HeaderContent))
const action = documentInjected === undefined
? undefined
: deferRegistration(ctx.slots, 'settings.action', SettingsDocumentAction, () =>
ctx.slots.register({
name: 'settings.action',
id: 'open-document',
order: 0,
locale: NS,
inject: documentInjected,
}, SettingsDocumentAction))
const close = deferRegistration(ctx.slots, 'settings.close', CloseLabel, () =>
ctx.slots.register({ name: 'settings.close', locale: NS }, CloseLabel))
const general = deferRegistration(ctx.slots, 'settings.section', GeneralSection, () =>
@@ -106,9 +131,10 @@ export function apply(ctx: ClientContext): void {
return () => {
trigger.dispose()
header.dispose()
action?.dispose()
close.dispose()
general.dispose()
welcome.dispose()
}
}, 'ui-settings-general: chrome, section, and onboarding registrations')
}, 'ui-settings-general: chrome, action, section, and onboarding registrations')
}

View File

@@ -6,6 +6,8 @@ export const zh = {
'trigger': '设置',
'title': '设置',
'close': '关闭',
'openDocument': '打开配置文件',
'openDocument.error': '无法打开配置文件',
'general.nav': '通用设置',
'welcome.title': WELCOME_NOTICE_COPY.zh.title,
'welcome.paragraph.0': WELCOME_NOTICE_COPY.zh.paragraphs[0],
@@ -24,6 +26,8 @@ export const en = {
'trigger': 'Settings',
'title': 'Settings',
'close': 'Close',
'openDocument': 'Open configuration file',
'openDocument.error': 'Could not open configuration file',
'general.nav': 'General',
'welcome.title': WELCOME_NOTICE_COPY.en.title,
'welcome.paragraph.0': WELCOME_NOTICE_COPY.en.paragraphs[0],

View File

@@ -0,0 +1,87 @@
/** State owner for the optional local settings-document action. */
import type { IApiClient } from '@deepseek-ai/dsh-client-connection/client'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
/** Browser state of the Host-owned settings document. */
export interface SettingsDocumentState {
/** Metadata-loading phase; unavailable means the provider has no local file or the read failed. */
status: 'idle' | 'loading' | 'ready' | 'unavailable'
/** Whether one native-open request is in flight. */
opening: boolean
/** Last metadata/native-open diagnostic; UI exposes only localized copy. */
error: string | null
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
/** Loads local-document availability and invokes the pathless Host-owned open operation. */
export class SettingsDocumentStore {
/** uSES-safe state source shared by the registered header action. */
readonly store: SnapshotStore<SettingsDocumentState> = createSnapshotStore({
status: 'idle', opening: false, error: null,
})
private generation = 0
/**
* @param api - loopback settings wire face that reports and opens the provider document.
*/
constructor(private readonly api: Pick<IApiClient, 'settings'>) {}
/**
* Load the current provider's optional local document path.
* @returns after the latest metadata response updates the store.
*/
async load(): Promise<void> {
const generation = ++this.generation
this.store.update((state) => {
state.status = 'loading'
state.error = null
})
try {
const { result } = await this.api.settings.describe({})
if (generation !== this.generation) return
if (!result.ok) {
this.store.update((state) => {
state.status = 'unavailable'
state.error = result.error.message
})
return
}
this.store.update((state) => {
state.status = result.value.documentPath === undefined ? 'unavailable' : 'ready'
state.error = null
})
} catch (error) {
if (generation !== this.generation) return
this.store.update((state) => {
state.status = 'unavailable'
state.error = messageOf(error)
})
}
}
/**
* Open the loaded document once; concurrent gestures collapse behind the in-flight action.
* @returns after the native-open request settles, or immediately when unavailable/already opening.
*/
async open(): Promise<void> {
const current = this.store.getSnapshot()
if (current.status !== 'ready' || current.opening) return
this.store.update((state) => {
state.opening = true
state.error = null
})
try {
const response = await this.api.settings.openDocument({})
if (!response.result.ok) throw new Error(response.result.error.message)
} catch (error) {
this.store.update((state) => { state.error = messageOf(error) })
} finally {
this.store.update((state) => { state.opening = false })
}
}
}

View File

@@ -16,8 +16,9 @@ export const inject = ['invariants']
/**
* No runtime invariant: the settings seam validates and publishes the durable
* welcome section, while slot conflicts fail loud in the slot core; this
* package owns no additional event/data relationship between those systems.
* welcome section, while slot conflicts fail loud in the slot core. The local
* document action is browser state over typed RPC responses and is covered by
* store/component tests rather than a Cordis runtime relationship.
*/
const install: InvariantInstaller = () => {}

View File

@@ -1,4 +1,4 @@
/** Ownerless-copy registrations: the four seats, the dictionaries, thunked labels, and HMR recovery. */
/** Ownerless-copy registrations: the six seats, dictionaries, thunked labels, and HMR recovery. */
import { Context } from 'cordis'
import { describe, expect, it, vi } from 'vitest'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
@@ -8,6 +8,8 @@ import { usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-general/client'
import { CloseLabel, HeaderContent, TriggerContent } from '../src/client/chrome.tsx'
import { GeneralSection } from '../src/client/GeneralSection.tsx'
import { SettingsDocumentAction } from '../src/client/SettingsDocumentAction.tsx'
import type { SettingsDocumentActionInjected } from '../src/client/SettingsDocumentAction.tsx'
import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx'
import type { WelcomeNoticeInjected } from '../src/client/WelcomeNotice.tsx'
import { WELCOME_NOTICE_SETTINGS_NAMESPACE } from '../src/onboarding-copy.ts'
@@ -16,10 +18,11 @@ import { WELCOME_NOTICE_SETTINGS_NAMESPACE } from '../src/onboarding-copy.ts'
// the shipped Chinese copy, so they state the browser they assume.
usePinnedBrowserLanguages('zh-CN')
/** The five seats this plugin fills (slot name → expected component). */
/** The seats this plugin fills for a loopback browser (slot name → expected component). */
const SEATS = [
['settings.trigger', TriggerContent],
['settings.header', HeaderContent],
['settings.action', SettingsDocumentAction],
['settings.close', CloseLabel],
['settings.section', GeneralSection],
['settings.onboarding', WelcomeNotice],
@@ -36,6 +39,7 @@ async function bench(isLoopback = true) {
ok: true as const,
value: {
writable: true,
documentPath: '/tmp/test-settings.yaml',
namespaces: [{
ns: WELCOME_NOTICE_SETTINGS_NAMESPACE,
schema: {},
@@ -47,11 +51,18 @@ async function bench(isLoopback = true) {
},
},
}))
ctx.provide('connection', { api: { settings: { describe: settingsDescribe } }, isLoopback } as never)
return { ctx, slots: ctx.get('slots') as SlotsService, locale, settingsDescribe }
const settingsOpenDocument = vi.fn(() => Promise.resolve({
rpcId: 'settings-open' as never,
result: { ok: true as const, value: { opened: true as const } },
}))
ctx.provide('connection', {
api: { settings: { describe: settingsDescribe, openDocument: settingsOpenDocument } },
isLoopback,
} as never)
return { ctx, slots: ctx.get('slots') as SlotsService, locale, settingsDescribe, settingsOpenDocument }
}
/** Declare the shell's four child slots the way ui-settings' entry does. */
/** Declare the shell's six child slots the way ui-settings' entry does. */
function declare(slots: SlotsService): () => void {
return slots.register(
{
@@ -59,6 +70,7 @@ function declare(slots: SlotsService): () => void {
children: {
'settings.trigger': { kind: 'single', scope: 'root' },
'settings.header': { kind: 'single', scope: 'root' },
'settings.action': { kind: 'list', scope: 'root' },
'settings.close': { kind: 'single', scope: 'root' },
'settings.section': { kind: 'list', scope: 'root' },
'settings.onboarding': { kind: 'list', scope: 'root' },
@@ -77,7 +89,7 @@ describe('ui-settings-general apply', () => {
expect(inject).toEqual(['slots', 'locale', 'connection'])
})
it('fills all five seats for declarations before or after apply', async () => {
it('fills all six seats for declarations before or after apply', async () => {
const before = await bench()
declare(before.slots)
await before.ctx.plugin({ inject: [...inject], apply }).await()
@@ -92,6 +104,10 @@ describe('ui-settings-general apply', () => {
expect(before.slots.entries('settings.general.item')).toEqual([])
const welcome = before.slots.entries('settings.onboarding')[0]!
expect(welcome.options).toMatchObject({ id: 'welcome-notice', order: -100 })
const action = before.slots.entries('settings.action')[0]!
const actionInjected = (action.inject as unknown as () => SettingsDocumentActionInjected)()
expect(actionInjected.controller.store.getSnapshot().status).toBe('idle')
expect(actionInjected.useSnapshot).toEqual(expect.any(Function))
// Copy rides the standard locale seat: every seat declares the namespace.
for (const [name] of SEATS) {
expect(before.slots.entries(name)[0]!.locale).toBe('settings')
@@ -170,6 +186,7 @@ describe('ui-settings-general apply', () => {
await expect(controller.acknowledge()).resolves.toBe(true)
expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true })
expect(b.settingsDescribe).not.toHaveBeenCalled()
expect(b.slots.entries('settings.action')).toEqual([])
})
it('re-registers after an HMR collapse of the declaring chain (stale disposers must not block)', async () => {

View File

@@ -1,10 +1,13 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import type { GeneralSectionComponentProps } from '../src/client/GeneralSection.tsx'
import { GeneralSection } from '../src/client/GeneralSection.tsx'
import { CloseLabel, HeaderContent, TriggerContent } from '../src/client/chrome.tsx'
import type { TriggerContentProps } from '../src/client/chrome.tsx'
import { SettingsDocumentAction } from '../src/client/SettingsDocumentAction.tsx'
import { SettingsDocumentStore } from '../src/client/settings-document-store.ts'
import { en } from '../src/client/locales.ts'
afterEach(cleanup)
@@ -54,3 +57,80 @@ describe('GeneralSection', () => {
expect(screen.getByTestId('slot-settings.general.item')).toBeTruthy()
})
})
describe('SettingsDocumentAction', () => {
it('appears only for a file-backed provider and requests its Host-owned document', async () => {
const openDocument = vi.fn(() => Promise.resolve({
rpcId: 'document-open' as never,
result: { ok: true as const, value: { opened: true as const } },
}))
const controller = new SettingsDocumentStore({
settings: {
describe: vi.fn(() => Promise.resolve({
rpcId: 'document-action' as never,
result: {
ok: true as const,
value: { writable: true, documentPath: '/tmp/custom.yaml', namespaces: [] },
},
})),
openDocument,
},
} as never)
render(<SettingsDocumentAction
{...kit}
t={t}
controller={controller}
useSnapshot={bindSnapshotSelector(controller.store)}
/>)
const action = await screen.findByRole('button', { name: 'Open configuration file' })
fireEvent.click(action)
await waitFor(() => { expect(openDocument).toHaveBeenCalledWith({}) })
})
it('stays absent when the provider has no local document', async () => {
const controller = new SettingsDocumentStore({
settings: {
describe: vi.fn(() => Promise.resolve({
rpcId: 'document-action' as never,
result: { ok: true as const, value: { writable: true, namespaces: [] } },
})),
openDocument: vi.fn(),
},
} as never)
render(<SettingsDocumentAction
{...kit}
t={t}
controller={controller}
useSnapshot={bindSnapshotSelector(controller.store)}
/>)
await waitFor(() => { expect(controller.store.getSnapshot().status).toBe('unavailable') })
expect(screen.queryByRole('button', { name: 'Open configuration file' })).toBeNull()
})
it('keeps the action available and reports a native-open failure', async () => {
const controller = new SettingsDocumentStore({
settings: {
describe: vi.fn(() => Promise.resolve({
rpcId: 'document-action' as never,
result: {
ok: true as const,
value: { writable: true, documentPath: '/tmp/settings.yaml', namespaces: [] },
},
})),
openDocument: vi.fn(() => Promise.resolve({
rpcId: 'document-open-failed' as never,
result: { ok: false as const, error: { code: 'internal' as const, message: 'xdg-open missing', details: {} } },
})),
},
} as never)
render(<SettingsDocumentAction
{...kit}
t={t}
controller={controller}
useSnapshot={bindSnapshotSelector(controller.store)}
/>)
fireEvent.click(await screen.findByRole('button', { name: 'Open configuration file' }))
expect((await screen.findByRole('alert')).textContent).toBe('Could not open configuration file')
expect(screen.getByRole('button', { name: 'Open configuration file' })).toBeTruthy()
})
})

View File

@@ -0,0 +1,132 @@
import { describe, expect, it, vi } from 'vitest'
import type { RpcResponse } from '@deepseek-ai/dsh-client-connection/client'
import { SettingsDocumentStore } from '../src/client/settings-document-store.ts'
function response(documentPath?: string): RpcResponse<{
writable: boolean
documentPath?: string
namespaces: []
}> {
return {
rpcId: 'settings-document' as never,
result: {
ok: true,
value: { writable: true, ...documentPath === undefined ? {} : { documentPath }, namespaces: [] },
},
}
}
function opened(): RpcResponse<{ opened: true }> {
return {
rpcId: 'settings-open' as never,
result: { ok: true, value: { opened: true } },
}
}
function describeFailed(message: string): RpcResponse<never> {
return {
rpcId: 'settings-document-failed' as never,
result: { ok: false, error: { code: 'internal', message, details: {} } },
}
}
describe('SettingsDocumentStore', () => {
it('loads provider metadata and asks the settings domain to open its document', async () => {
const describe = vi.fn(() => Promise.resolve(response('/home/test/settings.yaml')))
const openDocument = vi.fn(() => Promise.resolve(opened()))
const controller = new SettingsDocumentStore({ settings: { describe, openDocument } } as never)
await controller.load()
expect(controller.store.getSnapshot()).toEqual({
status: 'ready', opening: false, error: null,
})
await controller.open()
expect(openDocument).toHaveBeenCalledWith({})
})
it('marks absent or failed metadata unavailable without opening anything', async () => {
const openDocument = vi.fn(() => Promise.resolve(opened()))
const absent = new SettingsDocumentStore({
settings: { describe: () => Promise.resolve(response()), openDocument },
} as never)
await absent.load()
await absent.open()
expect(absent.store.getSnapshot().status).toBe('unavailable')
expect(openDocument).not.toHaveBeenCalled()
const failed = new SettingsDocumentStore({
settings: { describe: () => Promise.reject(new Error('offline')), openDocument },
} as never)
await failed.load()
expect(failed.store.getSnapshot()).toMatchObject({ status: 'unavailable', error: 'offline' })
const rejected = new SettingsDocumentStore({
settings: { describe: () => Promise.resolve(describeFailed('provider failed')), openDocument },
} as never)
await rejected.load()
expect(rejected.store.getSnapshot()).toMatchObject({
status: 'unavailable', error: 'provider failed',
})
})
it('collapses concurrent open gestures and recovers after a failure', async () => {
let resolveOpen!: (response: RpcResponse<{ opened: true }>) => void
const openDocument = vi.fn(() => new Promise<RpcResponse<{ opened: true }>>((resolve) => { resolveOpen = resolve }))
const controller = new SettingsDocumentStore({
settings: { describe: () => Promise.resolve(response('/tmp/settings.yaml')), openDocument },
} as never)
await controller.load()
const first = controller.open()
const second = controller.open()
expect(openDocument).toHaveBeenCalledOnce()
resolveOpen({
rpcId: 'settings-open-failed' as never,
result: { ok: false, error: { code: 'internal', message: 'no default editor', details: {} } },
})
await Promise.all([first, second])
expect(controller.store.getSnapshot()).toMatchObject({
status: 'ready', opening: false, error: 'no default editor',
})
})
it('ignores stale metadata completions and reports non-Error native failures', async () => {
let resolveFirst!: (value: ReturnType<typeof response>) => void
const first = new Promise<ReturnType<typeof response>>((resolve) => { resolveFirst = resolve })
const describe = vi.fn()
.mockReturnValueOnce(first)
.mockResolvedValueOnce(response('/tmp/current.yaml'))
let rejectOpen!: (reason?: unknown) => void
const controller = new SettingsDocumentStore({
settings: {
describe,
openDocument: () => new Promise((_, reject) => { rejectOpen = reject }),
},
} as never)
const stale = controller.load()
await controller.load()
resolveFirst(response())
await stale
expect(controller.store.getSnapshot().status).toBe('ready')
const opening = controller.open()
rejectOpen('native unavailable')
await opening
expect(controller.store.getSnapshot()).toMatchObject({
status: 'ready', opening: false, error: 'native unavailable',
})
let rejectFirst!: (error: Error) => void
const rejectedFirst = new Promise<ReturnType<typeof response>>((_, reject) => { rejectFirst = reject })
const caught = new SettingsDocumentStore({
settings: {
describe: vi.fn()
.mockReturnValueOnce(rejectedFirst)
.mockResolvedValueOnce(response('/tmp/current.yaml')),
openDocument: vi.fn(),
},
} as never)
const staleRejection = caught.load()
await caught.load()
rejectFirst(new Error('stale offline'))
await staleRejection
expect(caught.store.getSnapshot()).toMatchObject({ status: 'ready', error: null })
})
})