DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh-ui): 添加机器改 Modal 表单 + 删除立即生效
Menghuan19188bb160b55549
diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsxindex 75b0bf98..fad37eae 100644--- a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx@@ -75,25 +75,48 @@ describe('machinesSection', () => {expect(fetchFn).toHaveBeenCalledWith('/api-ssh', expect.objectContaining({ method: 'POST' }))})- it('shows the empty state and adds a machine draft', async () => {- mount()+ it('opens the add dialog and saves the new machine immediately', async () => {+ const { fetchFn } = mount()await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())fireEvent.click(screen.getByText('Add machine'))- expect(screen.getByTestId('machine-')).toBeTruthy()- const idInput = screen.getByLabelText('ID')- fireEvent.change(idInput, { target: { value: 'n1' } })- fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'newton' } })- fireEvent.change(screen.getByLabelText('Host or config alias'), { target: { value: '10.1.1.1' } })- fireEvent.change(screen.getByLabelText('User (optional)'), { target: { value: 'ops' } })- expect(screen.getByText('Save').closest('button')?.hasAttribute('disabled')).toBe(false)+ // 表单在弹窗里:ID 由主机自动派生,提交即落盘(不需要再点 Save)+ await waitFor(() => expect(screen.getByRole('dialog', { name: 'Add machine' })).toBeTruthy())+ const dialog = within(screen.getByRole('dialog', { name: 'Add machine' }))+ fireEvent.change(dialog.getByLabelText('Host or config alias'), { target: { value: '[email protected]' } })+ fireEvent.change(dialog.getByLabelText('Name'), { target: { value: 'newton' } })+ fireEvent.change(dialog.getByLabelText('User (optional)'), { target: { value: 'ops' } })+ expect(dialog.getByLabelText('ID')).toHaveProperty('value', '10-1-1-1')+ fireEvent.click(dialog.getByText('Add & save'))+ await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))+ const payload = saveCalls(fetchFn)[0] as { machineId: string, row: Record<string, unknown> }+ expect(payload.machineId).toBe('10-1-1-1')+ expect(payload.row).toMatchObject({ name: 'newton', host: '[email protected]', user: 'ops' })+ await waitFor(() => expect(screen.getByTestId('machine-10-1-1-1')).toBeTruthy())})- it('blocks saving while a draft is incomplete', async () => {+ it('derives a unique auto id and validates taken ids inline', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ fireEvent.click(screen.getByText('Add machine'))+ await waitFor(() => expect(screen.getByRole('dialog', { name: 'Add machine' })).toBeTruthy())+ const dialog = within(screen.getByRole('dialog', { name: 'Add machine' }))+ // 自动 ID 从主机派生+ fireEvent.change(dialog.getByLabelText('Host or config alias'), { target: { value: 'alpha.internal' } })+ expect(dialog.getByLabelText('ID')).toHaveProperty('value', 'alpha-internal')+ // 手改 ID 撞已有:内联报错且提交禁用+ fireEvent.change(dialog.getByLabelText('ID'), { target: { value: 'a' } })+ await waitFor(() => expect(dialog.getByText('ID already in use')).toBeTruthy())+ expect(dialog.getByText('Add & save').closest('button')?.hasAttribute('disabled')).toBe(true)+ })++ it('blocks submit while the host is empty', async () => {mount()await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())fireEvent.click(screen.getByText('Add machine'))- expect(screen.getByText(/Fill in the machine ID, name, and host/)).toBeTruthy()- expect(screen.getByText('Save').closest('button')?.hasAttribute('disabled')).toBe(true)+ await waitFor(() => expect(screen.getByRole('dialog', { name: 'Add machine' })).toBeTruthy())+ const dialog = within(screen.getByRole('dialog', { name: 'Add machine' }))+ expect(dialog.getByText('Host is required')).toBeTruthy()+ expect(dialog.getByText('Add & save').closest('button')?.hasAttribute('disabled')).toBe(true)})it('persists edits through the store', async () => {@@ -108,7 +131,7 @@ describe('machinesSection', () => {expect(payload.secrets).toMatchObject({ password: 'sekrit' })})- it('removes a draft through the confirmation modal and removes the machine on save', async () => {+ it('removes a machine immediately through the confirmation modal', async () => {const { fetchFn } = mount({envelope: {ok: true,@@ -125,10 +148,10 @@ describe('machinesSection', () => {fireEvent.click(withinButton(betaCard, 'Remove'))await waitFor(() => expect(screen.getByText('Remove it')).toBeTruthy())fireEvent.click(screen.getByText('Remove it'))- await waitFor(() => expect(screen.queryByTestId('machine-b')).toBeNull())- fireEvent.click(screen.getByText('Save'))+ // 确认即删除:无需再点保存await waitFor(() => expect(removeCalls(fetchFn)).toHaveLength(1))expect(removeCalls(fetchFn)[0]).toEqual({ method: 'machine.remove', payload: { machineId: 'b' } })+ await waitFor(() => expect(screen.queryByTestId('machine-b')).toBeNull())})it('tests, connects, opens through the desktop bridge, and disconnects a machine', async () => {diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsxindex eca9941a..9281098c 100644--- a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx@@ -40,7 +40,7 @@ export interface MachinesSectionProps extends MachinesSectionInjected {t: (key: SshKey) => string}-/** One editable draft row (a `new-…` key marks an unsaved machine). */+/** One editable draft row (key is the machine id; rows always mirror saved machines). */interface Draft {key: stringrow: MachineRow@@ -65,6 +65,31 @@ interface RemoveTarget {const DEFAULT_PORT = 22const DEFAULT_REMOTE_PORT = 3080+/** Derive the machine id from a host: lowercase alnum-dash slug of the first label. */+function slugOf(host: string): string {+ return host+ .trim()+ .toLowerCase()+ .replace(/^.*@/u, '')+ .replace(/[^a-z0-9-]+/gu, '-')+ .replace(/^-+|-+$/gu, '')+}++/** The first free id: the slug itself, else slug-2, slug-3, … */+function freeIdOf(base: string, taken: ReadonlySet<string>): string {+ if (base !== '' && !taken.has(base))+ return base+ const stem = base === '' ? 'machine' : base+ for (let n = 2;; n += 1) {+ const candidate = `${stem}-${n}`+ if (!taken.has(candidate))+ return candidate+ }+}++/** The id vocabulary (starts lowercase alnum; dashes allowed inside). */+const ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/u+/** The identity-color palette (fits the DSH status hue family). */const COLOR_CHOICES = ['#4176E6',@@ -158,7 +183,7 @@ export function MachineCard(<InputclassName={moduleClass(css.fieldInput)}value={row.id}- disabled={!draft.key.startsWith('new-')}+ disabledonChange={event => onChange(draft.key, { id: event.target.value })}/></Field>@@ -550,6 +575,107 @@ function messageOf(error: unknown): string {return error instanceof Error ? error.message : String(error)}+/**+ * The add-machine dialog: one focused form, saved immediately on submit+ * (the parent appends the row to the store). The id auto-derives from the+ * host until the operator touches the field. Remount per open (the parent+ * keys it by the open flag) so every open starts from a clean form.+ */+function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {+ t: (key: SshKey) => string+ saving: boolean+ /** Ids the new machine must not collide with. */+ takenIds: ReadonlySet<string>+ onSubmit: (row: MachineRow) => void+ onClose: () => void+}): ReactNode {+ const [host, setHost] = useState('')+ const [name, setName] = useState('')+ const [id, setId] = useState('')+ const [idTouched, setIdTouched] = useState(false)+ const [port, setPort] = useState(String(DEFAULT_PORT))+ const [user, setUser] = useState('')+ const [remotePort, setRemotePort] = useState(String(DEFAULT_REMOTE_PORT))++ const slug = slugOf(host)+ const effectiveId = idTouched ? id.trim() : (slug === '' ? '' : freeIdOf(slug, takenIds))+ const trimmedHost = host.trim()+ const errorKey: SshKey | null+ = trimmedHost === '' ? 'add.host_required'+ : !ID_PATTERN.test(effectiveId) ? 'add.id_invalid'+ : takenIds.has(effectiveId) ? 'add.id_taken'+ : null++ function submit(): void {+ if (errorKey !== null || saving)+ return+ onSubmit({+ id: effectiveId,+ name: name.trim() === '' ? effectiveId : name.trim(),+ host: trimmedHost,+ port: numberOf(port, DEFAULT_PORT),+ user: user.trim(),+ hasPassword: false,+ hasPassphrase: false,+ remotePort: numberOf(remotePort, DEFAULT_REMOTE_PORT),+ })+ }++ return (+ <Modal+ open+ onClose={onClose}+ title={t('add.title')}+ closeLabel={t('add.cancel')}+ footer={(+ <>+ <Button variant="ghost" disabled={saving} onClick={onClose}>{t('add.cancel')}</Button>+ <Button variant="primary" disabled={saving || errorKey !== null} onClick={submit}>{t('add.submit')}</Button>+ </>+ )}+ >+ <div className={cls.grid}>+ <Field label={t('field.host')}>+ <Input+ className={cls.fieldInput}+ value={host}+ autoFocus+ disabled={saving}+ onChange={event => setHost(event.target.value)}+ />+ </Field>+ <Field label={t('field.name')}>+ <Input className={cls.fieldInput} value={name} disabled={saving} onChange={event => setName(event.target.value)} />+ </Field>+ <Field label={t('field.id')}>+ <Input+ className={cls.fieldInput}+ value={idTouched ? id : effectiveId}+ placeholder={t('add.id_auto')}+ disabled={saving}+ onChange={(event) => {+ setIdTouched(true)+ setId(event.target.value)+ }}+ />+ </Field>+ <Field label={t('field.user')}>+ <Input className={cls.fieldInput} value={user} disabled={saving} onChange={event => setUser(event.target.value)} />+ </Field>+ <Field label={t('field.port')}>+ <Input className={cls.fieldInput} value={port} disabled={saving} onChange={event => setPort(event.target.value)} />+ </Field>+ <Field label={t('field.remotePort')}>+ <Input className={cls.fieldInput} value={remotePort} disabled={saving} onChange={event => setRemotePort(event.target.value)} />+ </Field>+ </div>+ {errorKey === null+ ? <p className={cls.hint}>{t('add.id_auto')}</p>+ : <p className={cls.error} role="alert">{t(errorKey)}</p>}+ </Modal>+ )+}+/*** Render the SSH-machines settings page.* @returns the page element tree.@@ -558,7 +684,8 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Reaconst state = useSyncExternalStore(store.subscribe, store.getSnapshot)const [drafts, setDrafts] = useState<Record<string, Draft>>({})const [dirty, setDirty] = useState<DirtySecrets>({})- const [addCounter, setAddCounter] = useState(0)+ const [addOpen, setAddOpen] = useState(false)+ const [addSaving, setAddSaving] = useState(false)const [initialized, setInitialized] = useState(false)const [availability, setAvailability] = useState<BridgeAvailability>(() => bridge?.probe === undefined ? 'web' : 'unknown')const [bridgeErrors, setBridgeErrors] = useState<Record<string, string>>({})@@ -627,35 +754,40 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea}const addMachine = (): void => {- const key = `new-${addCounter}`- setAddCounter(addCounter + 1)- setDrafts(previous => ({- ...previous,- [key]: {- key,- row: {- id: '',- name: '',- host: '',- port: DEFAULT_PORT,- user: '',- hasPassword: false,- hasPassphrase: false,- remotePort: DEFAULT_REMOTE_PORT,- },- },- }))+ setAddOpen(true)+ }++ /** Add = create-and-save now: persist the saved set plus the new row; other+ * staged edits stay staged (we pass state.machines, not the drafts). */+ const submitAdd = async (row: MachineRow): Promise<void> => {+ setAddSaving(true)+ const ok = await store.persist([...store.getSnapshot().machines, row], {})+ setAddSaving(false)+ if (!ok)+ return+ setDrafts(previous => ({ ...previous, [row.id]: { key: row.id, row: { ...row } } }))+ setAddOpen(false)}const confirmRemove = (): void => {if (removeTarget === null)return- const key = removeTarget.key+ const { key, id } = removeTargetsetRemoveTarget(null)- setDrafts((previous) => {- const next = { ...previous }- delete next[key]- return next+ // 删除立即生效:确认即调 machine.remove,成功后摘掉草稿与脏密钥+ void store.remove(id).then((ok) => {+ if (!ok)+ return+ setDrafts((previous) => {+ const next = { ...previous }+ delete next[key]+ return next+ })+ setDirty((previous) => {+ const next = { ...previous }+ delete next[key]+ return next+ })})}@@ -782,6 +914,20 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea))}</ul><SyncPanel store={store} t={t} />+ {addOpen+ ? (+ <AddMachineDialog+ t={t}+ saving={addSaving}+ takenIds={new Set([...state.machines.map(row => row.id), ...Object.values(drafts).map(draft => draft.row.id)])}+ onSubmit={row => void submitAdd(row)}+ onClose={() => {+ if (!addSaving)+ setAddOpen(false)+ }}+ />+ )+ : null}<Modalopen={removeTarget !== null}onClose={() => setRemoveTarget(null)}diff --git a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts b/packages/dsh-tauri-ssh-ui/src/client/locales/index.tsindex 617c33cf..8765f4b2 100644--- a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts@@ -71,6 +71,13 @@ export const zh = {'progress.starting': '正在启动远端实例…','progress.probing': '健康检查 {attempt}/{total}…','open.probing': '正在探测桌面环境…',+ 'add.title': '添加机器',+ 'add.submit': '添加并保存',+ 'add.cancel': '取消',+ 'add.id_auto': '留空则按主机自动生成',+ 'add.id_invalid': 'ID 需以小写字母或数字开头,仅含小写字母、数字、连字符',+ 'add.id_taken': 'ID 已被占用',+ 'add.host_required': '主机不能为空','notice.probe_ok': '探测通过','notice.probe_failed': '探测失败','progress.installing': '正在安装 dsh(下载并校验官方打包运行时,通常 1–3 分钟)…',@@ -155,6 +162,13 @@ export const en = {'progress.starting': 'Starting the remote instance…','progress.probing': 'Health check {attempt}/{total}…','open.probing': 'Probing the desktop bridge…',+ 'add.title': 'Add machine',+ 'add.submit': 'Add & save',+ 'add.cancel': 'Cancel',+ 'add.id_auto': 'Leave empty to derive from the host',+ 'add.id_invalid': 'ID must start with a lowercase letter or digit and use only lowercase letters, digits, dashes',+ 'add.id_taken': 'ID already in use',+ 'add.host_required': 'Host is required','notice.probe_ok': 'Probe passed','notice.probe_failed': 'Probe failed','progress.installing': 'Installing dsh (downloading and verifying the official packaged runtime, usually 1–3 min)…',diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.tsindex c05ca621..d726aaad 100644--- a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts@@ -479,8 +479,9 @@ export class MachinesStore {* keep the stored value) and machine.remove for ids that vanished.* @param machines - the form's machine rows (id is the dict key).* @param secrets - secret values the operator typed, keyed by machine id.+ * @returns whether every write landed (failures surface as `state.error`).*/- async persist(machines: MachineRow[], secrets: Record<string, SecretValues>): Promise<void> {+ async persist(machines: MachineRow[], secrets: Record<string, SecretValues>): Promise<boolean> {const previous = this.store.getSnapshot().machinesconst previousIds = new Set(previous.map(row => row.id))try {@@ -496,11 +497,31 @@ export class MachinesStore {state.error = null})await this.load()+ return true}catch (error) {this.store.update((state) => {state.error = messageOf(error)})+ return false+ }+ }++ /** Remove one machine immediately (config + secrets); returns success. */+ async remove(id: string): Promise<boolean> {+ try {+ await this.callApi<Record<string, never>>('machine.remove', { machineId: id })+ this.store.update((state) => {+ state.error = null+ })+ await this.load()+ return true+ }+ catch (error) {+ this.store.update((state) => {+ state.error = messageOf(error)+ })+ return false}}