@linxin666/dsh-client-ui-task-board-ssh 0.0.0-stage → 0.4.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +85 -2
  4. package/README.zh.md +86 -0
  5. package/cordis.patch.yml +15 -0
  6. package/icon.svg +5 -0
  7. package/lib/client.js +4429 -0
  8. package/lib/index.js +6100 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +255 -0
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/index.d.ts +100 -0
  13. package/lib/types/client/locales.d.ts +125 -0
  14. package/lib/types/client/seat-props.d.ts +53 -0
  15. package/lib/types/client/settings-entry-form.d.ts +49 -0
  16. package/lib/types/client/settings-form.d.ts +237 -0
  17. package/lib/types/client/ssh/card-decoration.d.ts +23 -0
  18. package/lib/types/client/ssh/compose-section.d.ts +7 -0
  19. package/lib/types/client/ssh/detail-section.d.ts +7 -0
  20. package/lib/types/client/ssh/extension.d.ts +54 -0
  21. package/lib/types/client/ssh/log-buffer.d.ts +128 -0
  22. package/lib/types/client/ssh/log-view.d.ts +37 -0
  23. package/lib/types/client/ssh/model.d.ts +130 -0
  24. package/lib/types/client/ssh/settings-section.d.ts +134 -0
  25. package/lib/types/client/ssh/summary.d.ts +160 -0
  26. package/lib/types/client/ssh/target-form.d.ts +60 -0
  27. package/lib/types/core/action.d.ts +89 -0
  28. package/lib/types/core/adapters/claude.d.ts +15 -0
  29. package/lib/types/core/adapters/codex.d.ts +15 -0
  30. package/lib/types/core/adapters/custom.d.ts +29 -0
  31. package/lib/types/core/adapters/dsh.d.ts +21 -0
  32. package/lib/types/core/adapters/index.d.ts +25 -0
  33. package/lib/types/core/adapters/types.d.ts +76 -0
  34. package/lib/types/core/contract.d.ts +445 -0
  35. package/lib/types/core/launcher-script.d.ts +13 -0
  36. package/lib/types/core/launcher.d.ts +153 -0
  37. package/lib/types/core/ledger.d.ts +123 -0
  38. package/lib/types/core/shell.d.ts +61 -0
  39. package/lib/types/core/target.d.ts +143 -0
  40. package/lib/types/core/task-record.d.ts +63 -0
  41. package/lib/types/core/workspace.d.ts +74 -0
  42. package/lib/types/host/board.d.ts +71 -0
  43. package/lib/types/host/engine.d.ts +418 -0
  44. package/lib/types/host/extension.d.ts +59 -0
  45. package/lib/types/host/logs.d.ts +135 -0
  46. package/lib/types/host/payload.d.ts +75 -0
  47. package/lib/types/host/prompt.d.ts +44 -0
  48. package/lib/types/host/queue.d.ts +53 -0
  49. package/lib/types/host/remote.d.ts +120 -0
  50. package/lib/types/host/settings.d.ts +149 -0
  51. package/lib/types/host/timers.d.ts +20 -0
  52. package/lib/types/host/tools.d.ts +15 -0
  53. package/lib/types/host/workspace/errors.d.ts +29 -0
  54. package/lib/types/host/workspace/git.d.ts +108 -0
  55. package/lib/types/host/workspace/in-place.d.ts +36 -0
  56. package/lib/types/host/workspace/index.d.ts +28 -0
  57. package/lib/types/host/workspace/layout.d.ts +62 -0
  58. package/lib/types/host/workspace/local-git.d.ts +72 -0
  59. package/lib/types/host/workspace/remote-git.d.ts +111 -0
  60. package/lib/types/host/workspace/remote.d.ts +85 -0
  61. package/lib/types/host/workspace/types.d.ts +28 -0
  62. package/lib/types/host/workspace-seam.d.ts +100 -0
  63. package/lib/types/index.d.ts +97 -0
  64. package/lib/types/mount-once.d.ts +55 -0
  65. package/locale/en.json +6 -0
  66. package/locale/zh.json +6 -0
  67. package/package.json +89 -3
  68. package/src/client/PluginSettingsCard.tsx +838 -0
  69. package/src/client/RangeBubble.tsx +164 -0
  70. package/src/client/SegmentGroup.tsx +93 -0
  71. package/src/client/css-modules.d.ts +5 -0
  72. package/src/client/index.ts +195 -0
  73. package/src/client/locales.ts +257 -0
  74. package/src/client/seat-props.ts +58 -0
  75. package/src/client/settings-card.module.css +821 -0
  76. package/src/client/settings-entry-form.ts +141 -0
  77. package/src/client/settings-form.ts +529 -0
  78. package/src/client/ssh/card-decoration.tsx +55 -0
  79. package/src/client/ssh/compose-section.tsx +147 -0
  80. package/src/client/ssh/detail-section.tsx +345 -0
  81. package/src/client/ssh/extension.ts +271 -0
  82. package/src/client/ssh/log-buffer.ts +224 -0
  83. package/src/client/ssh/log-view.tsx +149 -0
  84. package/src/client/ssh/model.ts +299 -0
  85. package/src/client/ssh/settings-section.tsx +401 -0
  86. package/src/client/ssh/summary.ts +388 -0
  87. package/src/client/ssh/target-form.tsx +380 -0
  88. package/src/client/ssh.module.css +617 -0
  89. package/src/core/action.ts +270 -0
  90. package/src/core/adapters/claude.ts +64 -0
  91. package/src/core/adapters/codex.ts +83 -0
  92. package/src/core/adapters/custom.ts +88 -0
  93. package/src/core/adapters/dsh.ts +87 -0
  94. package/src/core/adapters/index.ts +74 -0
  95. package/src/core/adapters/types.ts +95 -0
  96. package/src/core/contract.ts +510 -0
  97. package/src/core/launcher-script.ts +313 -0
  98. package/src/core/launcher.ts +283 -0
  99. package/src/core/ledger.ts +372 -0
  100. package/src/core/shell.ts +77 -0
  101. package/src/core/target.ts +413 -0
  102. package/src/core/task-record.ts +65 -0
  103. package/src/core/workspace.ts +78 -0
  104. package/src/host/board.ts +103 -0
  105. package/src/host/engine.ts +1602 -0
  106. package/src/host/extension.ts +304 -0
  107. package/src/host/logs.ts +297 -0
  108. package/src/host/payload.ts +134 -0
  109. package/src/host/prompt.ts +89 -0
  110. package/src/host/queue.ts +73 -0
  111. package/src/host/remote.ts +328 -0
  112. package/src/host/settings.ts +294 -0
  113. package/src/host/timers.ts +33 -0
  114. package/src/host/tools.ts +259 -0
  115. package/src/host/workspace/errors.ts +43 -0
  116. package/src/host/workspace/git.ts +305 -0
  117. package/src/host/workspace/in-place.ts +58 -0
  118. package/src/host/workspace/index.ts +37 -0
  119. package/src/host/workspace/layout.ts +122 -0
  120. package/src/host/workspace/local-git.ts +164 -0
  121. package/src/host/workspace/remote-git.ts +244 -0
  122. package/src/host/workspace/remote.ts +181 -0
  123. package/src/host/workspace/types.ts +34 -0
  124. package/src/host/workspace-seam.ts +132 -0
  125. package/src/index.ts +243 -0
  126. package/src/mount-once.ts +142 -0
@@ -0,0 +1,141 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-entry-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-entry-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
3
+ /**
4
+ * Family settings form bound to the profile entry id a Host actually serves.
5
+ *
6
+ * Under the 0.1.7 settings model a form is addressed by PROFILE ENTRY ID, while
7
+ * a family card knows only its own settings namespace. The family binder
8
+ * (`ctx.get('webUiSettings')`, published by dsh-web-settings) resolves one onto
9
+ * the other and is the preferred transport; this module is the fallback for a
10
+ * page that serves no binder — the group plugin is not installed, or its client
11
+ * half has not applied yet (the aggregate mounts its children in order, and a
12
+ * child still waiting on its own injects publishes nothing).
13
+ *
14
+ * The shared describe mirror is the only local evidence of which row id this
15
+ * profile serves, but it answers asynchronously: at plugin activation it usually
16
+ * holds nothing yet. A one-shot guess therefore cannot be right for every
17
+ * deployment, and the form is bound once per session:
18
+ *
19
+ * - binding the bare namespace made every save answer `No configurable plugin
20
+ * entry "<namespace>"` on an aggregate install (the namespace is not an entry
21
+ * id there), which the card reported as "the deployment did not accept these
22
+ * values";
23
+ * - binding the aggregate row id would break a standalone install, whose row id
24
+ * is the namespace or the package's own `ui-*` row.
25
+ *
26
+ * So the fallback starts on the most likely row and REBINDS the moment the
27
+ * mirror names one of this package's rows. Until the mirror answers, the form
28
+ * reports the binding it holds (usually `loading`), which the card renders as an
29
+ * unavailable form rather than a doomed one.
30
+ */
31
+ import type { ConfigForm, ConfigFormSnapshot, ConfigForms } from '@deepseek-ai/dsh-client-ui-settings/client'
32
+
33
+ /** Options of {@link createServedEntryForm}. */
34
+ export interface ServedEntryFormOptions<_T> {
35
+ /** The shared configuration forms service (`ctx.configForms`). */
36
+ forms: ConfigForms
37
+ /**
38
+ * Profile entry ids this package's rows carry, most likely first: the
39
+ * aggregate's generated row, the package's own standalone row, then the bare
40
+ * namespace. The first is the fallback while the mirror has no answer; the
41
+ * last is the answer when the mirror serves none of them.
42
+ */
43
+ entryIds: readonly string[]
44
+ }
45
+
46
+ /** The snapshot a form reports before the Host has answered with this entry. */
47
+ function pendingSnapshot<T>(): ConfigFormSnapshot<T> {
48
+ return {
49
+ status: 'loading',
50
+ value: undefined,
51
+ base: undefined,
52
+ user: undefined,
53
+ revision: undefined,
54
+ writable: false,
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Create a settings form bound to the profile entry id this Host serves, and
60
+ * rebound whenever the shared describe mirror names a different one of this
61
+ * package's rows.
62
+ * @param options - the shared forms service and this package's candidate row ids.
63
+ * @returns a form delegating to the currently resolved entry's own form.
64
+ */
65
+ export function createServedEntryForm<T>(options: ServedEntryFormOptions<T>): ConfigForm<T> {
66
+ const { forms, entryIds } = options
67
+ const fallbackId = entryIds[0]
68
+ const namespaceId = entryIds[entryIds.length - 1]
69
+ const listeners = new Set<() => void>()
70
+ let boundId: string | undefined
71
+ let bound: ConfigForm<T> | undefined
72
+ let offBound: (() => void) | undefined
73
+ let snapshot: ConfigFormSnapshot<T> = pendingSnapshot<T>()
74
+
75
+ /** Republish: the delegated snapshot when one is bound, the pending one otherwise. */
76
+ const publish = (): void => {
77
+ if (bound !== undefined) snapshot = bound.getSnapshot()
78
+ for (const listener of [...listeners]) listener()
79
+ }
80
+
81
+ /**
82
+ * The entry id the mirror currently justifies. An unanswered or empty mirror
83
+ * is not evidence of absence, so it keeps the first candidate; a mirror that
84
+ * answers without any of this package's rows leaves the namespace itself.
85
+ * @returns the entry id to bind.
86
+ */
87
+ const resolve = (): string => {
88
+ let served: readonly string[] | undefined
89
+ try {
90
+ served = forms.describe().getSnapshot().view?.namespaces.map(row => row.ns)
91
+ } catch {
92
+ // A mirror that refuses the read is unanswered too, not absent.
93
+ served = undefined
94
+ }
95
+ if (served === undefined || served.length === 0) return fallbackId
96
+ return entryIds.find(id => served.includes(id)) ?? namespaceId
97
+ }
98
+
99
+ /** Bind (or rebind) the resolved entry's form; a no-op while it is unchanged. */
100
+ const bind = (): void => {
101
+ const target = resolve()
102
+ if (target === boundId) return
103
+ offBound?.()
104
+ offBound = undefined
105
+ let form: ConfigForm<T>
106
+ try {
107
+ form = forms.get<T>(target)
108
+ } catch {
109
+ // A service that refuses the id stays unbound; the next mirror answer
110
+ // retries rather than pinning a wrong entry for the session.
111
+ boundId = undefined
112
+ return
113
+ }
114
+ boundId = target
115
+ bound = form
116
+ offBound = form.subscribe(() => { publish() })
117
+ publish()
118
+ }
119
+
120
+ // The mirror subscription lives for the page: the card owns its form for the
121
+ // session, and the ConfigForm contract carries no disposer to hang it on. The
122
+ // callback is cheap (a resolve plus a no-op while the id is unchanged). A
123
+ // mirror without a subscription seat keeps the initial binding.
124
+ try {
125
+ forms.describe().subscribe(() => { bind() })
126
+ } catch {
127
+ // A describe face that refuses the subscription: the initial binding stands.
128
+ }
129
+ bind()
130
+
131
+ return {
132
+ getSnapshot: () => snapshot,
133
+ subscribe: (listener) => {
134
+ listeners.add(listener)
135
+ return () => { listeners.delete(listener) }
136
+ },
137
+ set: (field, value) => bound?.set(field, value) ?? Promise.resolve(false),
138
+ unset: (field) => bound?.unset(field) ?? Promise.resolve(false),
139
+ mutate: (ops, expectedRevision) => bound?.mutate(ops, expectedRevision) ?? Promise.resolve(false),
140
+ }
141
+ }
@@ -0,0 +1,529 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Form model behind the plugin settings card. Every control applies itself:
4
+ * a pick (a segment, a select option, a reset) writes the moment it is made,
5
+ * and typed text writes once typing pauses or the reader leaves the field.
6
+ * Between the edit and the write the edit is held here as a draft, so what is
7
+ * on screen is exactly what the write will store; a write the Host refuses
8
+ * puts a pick back to the stored value and keeps typed text for correcting.
9
+ * Family-shared slice inlined into each plugin's client bundle.
10
+ */
11
+
12
+ import type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'
13
+ import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
14
+ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
15
+
16
+ /** The write one field's draft text performs when it is applied. */
17
+ export type FieldWrite =
18
+ | { kind: 'set'; value: unknown }
19
+ | { kind: 'clear' }
20
+
21
+ /** How one field converts between its stored value and its draft text. */
22
+ export interface FieldSpec {
23
+ /** Field name inside the namespace section. */
24
+ field: string
25
+ /**
26
+ * How the reader enters a value, which decides when it is written: a `pick`
27
+ * is a whole value at once and applies immediately; `type` is text arriving
28
+ * a keystroke at a time and applies once typing pauses or the field is left.
29
+ */
30
+ entry: 'pick' | 'type'
31
+ /**
32
+ * Whether the Host treats this field as a secret and redacts its value from
33
+ * the read-back (role('secret') in the section schema). Redacted secrets are
34
+ * never compared against the draft on save: the Host strips them from every
35
+ * wire view layer, so the settled snapshot carries nothing to read back. A
36
+ * staged secret set is judged by the mutation settling; the rest of its
37
+ * batch, when one exists, is still judged by read-back, and the atomic
38
+ * mutation lands every write or none.
39
+ */
40
+ secret?: boolean
41
+ /** Render a stored value as draft text; the empty string when the section carries none. */
42
+ format: (value: unknown) => string
43
+ /**
44
+ * The write this draft text performs, or undefined when the text is not a
45
+ * value this field accepts — which holds the draft unwritten rather than
46
+ * discarding it.
47
+ */
48
+ parse: (text: string) => FieldWrite | undefined
49
+ }
50
+
51
+ /** One field as the card renders it. */
52
+ export interface FieldState {
53
+ /** Draft text the control renders. */
54
+ text: string
55
+ /** Whether the field leaves (or will leave) a user-layer entry. */
56
+ overridden: boolean
57
+ /** Whether the draft is not a value this field accepts, which holds it unwritten. */
58
+ invalid: boolean
59
+ }
60
+
61
+ /** Form state every plugin settings card shares. */
62
+ export interface CardShell {
63
+ /** False while the namespace is still loading; the card renders nothing. */
64
+ available: boolean
65
+ /**
66
+ * Whether the namespace is actually served to this client. False when the
67
+ * Host deployment does not expose it (e.g. the owning plugin's settings
68
+ * domain is not mounted): the card renders an explanation
69
+ * instead of its form, so a missing namespace never looks like a missing
70
+ * plugin.
71
+ */
72
+ exposed: boolean
73
+ /** Whether the Host document accepts writes. */
74
+ writable: boolean
75
+ /** Whether the form holds drafts not yet written (typed text waiting for its pause). */
76
+ dirty: boolean
77
+ /** Whether any draft is invalid, which holds it unwritten. */
78
+ invalid: boolean
79
+ /** Whether a write is crossing the wire. */
80
+ saving: boolean
81
+ /** Whether the last write did not land; cleared by the next edit or write. */
82
+ failed: boolean
83
+ /**
84
+ * The rejection code/message the Host returned for the last failed save,
85
+ * surfaced next to the generic failure text. Undefined while no save has
86
+ * failed (or the failure carried no server reason).
87
+ */
88
+ failedReason?: string
89
+ }
90
+
91
+ /** The write actions the card's slot entry injects. */
92
+ export interface CardActions {
93
+ /** Take draft text for one field; a pick writes at once, typed text after a pause. */
94
+ edit: (field: string, text: string) => void
95
+ /** Clear one field at once, so it re-inherits the composition layer. */
96
+ resetField: (field: string) => void
97
+ /** Write every pending draft now (a text field's Enter or blur), then re-seed from what the Host accepted. */
98
+ save: () => void
99
+ /** Drop every pending draft, putting each control back to the stored value (a text field's Escape). */
100
+ discard: () => void
101
+ }
102
+
103
+ /** How long typed text rests before it is written. */
104
+ export const TYPE_PAUSE_MS = 600
105
+
106
+ /** One field's staged edit. */
107
+ interface StagedEdit {
108
+ /** Draft text the control renders. */
109
+ text: string
110
+ /** True when this edit clears the field whatever text it shows. */
111
+ clear: boolean
112
+ }
113
+
114
+ /** One staged edit resolved into the write a save performs. */
115
+ interface PlannedWrite {
116
+ /** Field this entry writes. */
117
+ field: string
118
+ /** The durable write this entry performs, inside the save's one atomic mutation. */
119
+ op: BatchedWrite
120
+ /**
121
+ * Read the settled snapshot back and report whether the Host holds this
122
+ * write's effect. Undefined when the draft is not a value the field
123
+ * accepts: there is nothing to write, and the entry blocks the save.
124
+ */
125
+ judge: (() => boolean) | undefined
126
+ }
127
+
128
+ /** One durable write inside the save's atomic form mutation. */
129
+ export interface BatchedWrite {
130
+ /** Field this entry writes. */
131
+ field: string
132
+ /** set stores a value; unset drops the leaf. */
133
+ op: 'set' | 'unset'
134
+ /** Value for op set (absent for unset). */
135
+ value?: unknown
136
+ }
137
+
138
+ /** Constraints a numeric field's accepted drafts must satisfy, mirroring the host schema. */
139
+ export interface NumberConstraints {
140
+ /** The accepted value must be a whole number. */
141
+ integer?: boolean
142
+ /** The accepted value must be at least this. */
143
+ min?: number
144
+ /** The accepted value must be at most this. */
145
+ max?: number
146
+ }
147
+
148
+ /** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints stays unwritten. */
149
+ export function numberField(field: string, constraints: NumberConstraints = {}): FieldSpec {
150
+ const { integer = false, min, max } = constraints
151
+ return {
152
+ field,
153
+ entry: 'type',
154
+ format: value => typeof value === 'number' ? String(value) : '',
155
+ parse: (text) => {
156
+ const trimmed = text.trim()
157
+ if (trimmed === '') return { kind: 'clear' }
158
+ const parsed = Number(trimmed)
159
+ if (!Number.isFinite(parsed)) return undefined
160
+ if (integer && !Number.isInteger(parsed)) return undefined
161
+ if (min !== undefined && parsed < min) return undefined
162
+ if (max !== undefined && parsed > max) return undefined
163
+ return { kind: 'set', value: parsed }
164
+ },
165
+ }
166
+ }
167
+
168
+ /**
169
+ * A free-text field. An empty draft clears the field. `entry` is `pick` when
170
+ * the text arrives whole from a picker (a preset or a reasoning level).
171
+ */
172
+ export function textField(field: string, entry: FieldSpec['entry'] = 'type'): FieldSpec {
173
+ return {
174
+ field,
175
+ entry,
176
+ format: value => typeof value === 'string' ? value : '',
177
+ parse: (text) => {
178
+ const trimmed = text.trim()
179
+ return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed }
180
+ },
181
+ }
182
+ }
183
+
184
+ /**
185
+ * A free-text field the Host treats as a secret and redacts from the read-back
186
+ * (role('secret') in the section schema). The card still edits it like text,
187
+ * but a save never compares the redacted value back: the staged set is judged
188
+ * by the mutation settling (see {@link FieldSpec.secret}).
189
+ */
190
+ export function secretField(field: string): FieldSpec {
191
+ return { ...textField(field), secret: true }
192
+ }
193
+
194
+ /** A boolean field, edited through true/false draft text. */
195
+ export function booleanField(field: string): FieldSpec {
196
+ return {
197
+ field,
198
+ entry: 'pick',
199
+ format: value => typeof value === 'boolean' ? String(value) : '',
200
+ parse: (text) => {
201
+ const trimmed = text.trim()
202
+ if (trimmed === '') return { kind: 'clear' }
203
+ if (trimmed === 'true') return { kind: 'set', value: true }
204
+ if (trimmed === 'false') return { kind: 'set', value: false }
205
+ return undefined
206
+ },
207
+ }
208
+ }
209
+
210
+ /** An enumerated string field; only the listed choices are accepted. An empty draft clears the field. */
211
+ export function choiceField(field: string, choices: readonly string[]): FieldSpec {
212
+ return {
213
+ field,
214
+ entry: 'pick',
215
+ format: value => typeof value === 'string' && choices.includes(value) ? value : '',
216
+ parse: (text) => {
217
+ if (text === '') return { kind: 'clear' }
218
+ return choices.includes(text) ? { kind: 'set', value: text } : undefined
219
+ },
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Applies one card's edits to one settings namespace as the reader makes them.
225
+ *
226
+ * The Host is the only authority on whether a value was accepted — its
227
+ * validators own the constraints no schema can express — so the outcome is
228
+ * read back from the section rather than predicted here. A write that did not
229
+ * land puts each pick back to the stored value, the way a switch that could not
230
+ * flip springs back, and keeps typed text so the reader can correct it instead
231
+ * of retyping.
232
+ */
233
+ export class CardForm<T> {
234
+ private readonly specs: Map<string, FieldSpec>
235
+ private readonly staged = new Map<string, StagedEdit>()
236
+ private readonly listeners = new Set<() => void>()
237
+ /** The form subscription installed in the constructor; released by dispose(). */
238
+ private readonly disposeForm: () => void
239
+ private disposed = false
240
+ /** The pending write of typed text, waiting for typing to pause. */
241
+ private typePause: ReturnType<typeof setTimeout> | undefined
242
+ private saving = false
243
+ /** A save asked for while one was in flight; it runs once the first settles (#1754). */
244
+ private saveQueued = false
245
+ private failed = false
246
+ private failedReason: string | undefined
247
+
248
+ /** @param scope - the bound configuration form for this card's namespace. */
249
+ constructor(
250
+ private readonly scope: ConfigForm<T>,
251
+ specs: FieldSpec[],
252
+ ) {
253
+ this.specs = new Map(specs.map(spec => [spec.field, spec]))
254
+ this.disposeForm = scope.subscribe(() => { this.publish() })
255
+ }
256
+
257
+ /**
258
+ * Release the form subscription and every bound store listener. The card
259
+ * must call this on teardown; later calls are no-ops.
260
+ */
261
+ dispose(): void {
262
+ if (this.disposed) return
263
+ this.disposed = true
264
+ clearTimeout(this.typePause)
265
+ this.disposeForm()
266
+ this.listeners.clear()
267
+ }
268
+
269
+ /** Publish a projection of this form, rebuilt whenever the form or a draft changes. */
270
+ bind<S>(project: () => S): SnapshotStore<S> {
271
+ const store = createSnapshotStore(project())
272
+ this.listeners.add(() => { store.set(project()) })
273
+ return store
274
+ }
275
+
276
+ /** Read the card-level state: what the Host serves, and what is still waiting to be written. */
277
+ shell(): CardShell {
278
+ const snapshot = this.scope.getSnapshot()
279
+ const plan = this.plan()
280
+ return {
281
+ available: snapshot.status !== 'loading',
282
+ exposed: snapshot.status === 'ready',
283
+ writable: snapshot.writable,
284
+ dirty: plan.length > 0,
285
+ invalid: plan.some(item => item.judge === undefined),
286
+ saving: this.saving,
287
+ failed: this.failed,
288
+ ...this.failedReason === undefined ? {} : { failedReason: this.failedReason },
289
+ }
290
+ }
291
+
292
+ /** Read one field's state from the effective section and its staged draft. */
293
+ field(field: string): FieldState {
294
+ const spec = this.specOf(field)
295
+ const staged = this.staged.get(field)
296
+ if (staged === undefined) {
297
+ return { text: spec.format(this.sectionValue(field)), overridden: this.stored(field), invalid: false }
298
+ }
299
+ const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text)
300
+ return {
301
+ text: staged.text,
302
+ overridden: write?.kind === 'set',
303
+ invalid: write === undefined,
304
+ }
305
+ }
306
+
307
+ /** The actions the card's slot registration injects. */
308
+ actions(): CardActions {
309
+ return {
310
+ edit: (field, text) => { this.stage(field, { text, clear: false }) },
311
+ resetField: (field) => {
312
+ this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true })
313
+ },
314
+ save: () => { this.applyNow() },
315
+ discard: () => {
316
+ clearTimeout(this.typePause)
317
+ if (this.staged.size === 0 && !this.failed) return
318
+ this.staged.clear()
319
+ this.failed = false
320
+ this.failedReason = undefined
321
+ this.publish()
322
+ },
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Run one write, and re-run it once if another was asked for while this one
328
+ * was still in flight.
329
+ *
330
+ * A write is a Host round trip that also drives the profile reconcile, and
331
+ * the Host runs it inside one exclusive transaction. Answering an edit that
332
+ * arrives mid-flight by returning immediately dropped it with no explanation
333
+ * (#1754). Serializing instead means an edit made while another write is
334
+ * still settling is written against the settled state.
335
+ * @returns settlement after the mutation and the read-back.
336
+ */
337
+ async requestSave(): Promise<void> {
338
+ if (this.saving) {
339
+ this.saveQueued = true
340
+ return
341
+ }
342
+ await this.save()
343
+ if (!this.saveQueued) return
344
+ this.saveQueued = false
345
+ await this.requestSave()
346
+ }
347
+
348
+ /**
349
+ * Write every valid draft in one atomic form mutation, then re-seed from
350
+ * what the Host accepted. A draft the field does not accept stays on screen,
351
+ * unwritten, without holding the others back.
352
+ *
353
+ * The batch rides one mutate, so cross-field validate hooks (baseURL+model)
354
+ * judge it as a unit: the Host either applies every write or refuses the
355
+ * batch. The form contract answers a refusal or a skipped write with `false`
356
+ * (it recovers with a fresh Host view instead of throwing), so the outcome is
357
+ * judged twice: the answer itself, and then the settled snapshot read back
358
+ * one planned write at a time. One missed write fails the whole batch. A
359
+ * transport that rejects instead (the dsh-web bridge controller on a dead
360
+ * connection) reports through the same failure path with its rejection
361
+ * message. A batch that did not land puts its picks and clears back to the
362
+ * stored value and keeps its typed text, so the reader can correct it.
363
+ * @returns settlement after the mutation and the read-back.
364
+ */
365
+ async save(): Promise<void> {
366
+ const plan = this.plan()
367
+ const valid = plan.filter((item): item is PlannedWrite & { judge: () => boolean } => item.judge !== undefined)
368
+ if (valid.length === 0 || this.saving) return
369
+ // Snapshot the staged entries this write carries, so an edit staged while
370
+ // it is in flight (which replaces the same key) survives: only settle the
371
+ // key when the entry is still the one this write started from.
372
+ const pending = new Map<string, StagedEdit | undefined>()
373
+ for (const item of valid) pending.set(item.field, this.staged.get(item.field))
374
+ this.saving = true
375
+ this.failed = false
376
+ this.failedReason = undefined
377
+ this.publish()
378
+ // One atomic namespace mutation: the form contract takes ordered path
379
+ // operations, so the whole staged batch is validated, persisted, and
380
+ // recovered together — either every write lands or none does.
381
+ const ops: Array<{ op: 'set'; path: string[]; value: string | number | boolean } | { op: 'unset'; path: string[] }> = valid.map(item => item.op.op === 'set'
382
+ ? { op: 'set', path: [item.field], value: (item.op as { value: string | number | boolean }).value }
383
+ : { op: 'unset', path: [item.field] })
384
+ let failedReason: string | undefined
385
+ let accepted = false
386
+ try {
387
+ accepted = await this.scope.mutate(ops)
388
+ } catch (error) {
389
+ failedReason = error instanceof Error ? error.message : String(error)
390
+ }
391
+ // `false` is the contract's refusal/skip answer, and the form still
392
+ // resolves after a refusal (it recovers with a fresh view), so the answer
393
+ // alone is not enough: judge every planned write against the settled
394
+ // snapshot as well. The mutation is atomic, so one missed write fails the
395
+ // whole save and keeps the drafts.
396
+ const landed = accepted && failedReason === undefined && valid.every(item => item.judge())
397
+ for (const [field, before] of pending) {
398
+ if (this.staged.get(field) !== before) continue
399
+ if (landed || before === undefined || before.clear || this.specOf(field).entry === 'pick') this.staged.delete(field)
400
+ }
401
+ this.saving = false
402
+ this.failed = !landed
403
+ // A refused or unlanded batch carries no server reason: the card surfaces
404
+ // its generic failure copy; a rejecting transport (the bridge) adds its
405
+ // message.
406
+ this.failedReason = failedReason
407
+ this.publish()
408
+ }
409
+
410
+ /**
411
+ * Every staged edit a write would carry. An entry whose draft is not a value
412
+ * its field accepts carries no write: the form is still dirty, and the draft
413
+ * stays on screen rather than being dropped. A staged edit that matches the
414
+ * effective section is not a write at all.
415
+ * @returns the planned writes, in the order the fields were staged.
416
+ */
417
+ private plan(): PlannedWrite[] {
418
+ const plan: PlannedWrite[] = []
419
+ for (const [field, staged] of this.staged) {
420
+ const spec = this.specOf(field)
421
+ if (staged.clear) {
422
+ if (this.stored(field)) plan.push({ field, op: { field, op: 'unset' }, judge: () => this.landedUnset(field) })
423
+ continue
424
+ }
425
+ if (staged.text === spec.format(this.sectionValue(field))) continue
426
+ const write = spec.parse(staged.text)
427
+ if (write === undefined) plan.push({ field, op: { field, op: 'unset' }, judge: undefined })
428
+ else if (write.kind === 'clear') plan.push({ field, op: { field, op: 'unset' }, judge: () => this.landedUnset(field) })
429
+ else plan.push({ field, op: { field, op: 'set', value: write.value }, judge: () => this.landedSet(field, write.value) })
430
+ }
431
+ return plan
432
+ }
433
+
434
+ /**
435
+ * Read-back judgment for a planned set: the user layer must hold the
436
+ * intended value once the mutation has settled.
437
+ */
438
+ private landedSet(field: string, value: unknown): boolean {
439
+ // A redacted secret never appears in any wire view layer: the Host strips
440
+ // role('secret') fields and reports them through a sidecar the form
441
+ // snapshot does not expose, so there is nothing to compare the draft
442
+ // against. Settling is the only signal the form has; the rest of the
443
+ // batch, when one exists, still carries the atomic verdict by read-back.
444
+ if (this.specOf(field).secret) return true
445
+ return jsonValuesEqual(this.userLayer()?.[field], value)
446
+ }
447
+
448
+ /**
449
+ * Read-back judgment for a planned unset: the field must be gone from the
450
+ * user layer once the mutation has settled.
451
+ */
452
+ private landedUnset(field: string): boolean {
453
+ return !this.stored(field)
454
+ }
455
+
456
+ /**
457
+ * Take one edit and schedule its write: a pick or a clear is written now,
458
+ * typed text once typing has rested for TYPE_PAUSE_MS.
459
+ */
460
+ private stage(field: string, edit: StagedEdit): void {
461
+ this.staged.set(field, edit)
462
+ this.failed = false
463
+ this.failedReason = undefined
464
+ this.publish()
465
+ if (edit.clear || this.specOf(field).entry === 'pick') {
466
+ this.applyNow()
467
+ return
468
+ }
469
+ clearTimeout(this.typePause)
470
+ this.typePause = setTimeout(() => { this.applyNow() }, TYPE_PAUSE_MS)
471
+ }
472
+
473
+ /** Write every pending draft now, taking the place of a waiting pause. */
474
+ private applyNow(): void {
475
+ clearTimeout(this.typePause)
476
+ this.typePause = undefined
477
+ if (this.disposed) return
478
+ void this.requestSave()
479
+ }
480
+
481
+ private specOf(field: string): FieldSpec {
482
+ const spec = this.specs.get(field)
483
+ // Every call site names a field this card declared; a missing one is a
484
+ // wiring mistake that must not degrade into a silently inert control.
485
+ if (spec === undefined) throw new Error(`settings card has no field ${field}`)
486
+ return spec
487
+ }
488
+
489
+ private snapshotOf(): ConfigFormSnapshot<T> {
490
+ return this.scope.getSnapshot()
491
+ }
492
+
493
+ private sectionValue(field: string): unknown {
494
+ return (this.snapshotOf().value as Record<string, unknown> | undefined)?.[field]
495
+ }
496
+
497
+ private baseValue(field: string): unknown {
498
+ return (this.snapshotOf().base as Record<string, unknown> | undefined)?.[field]
499
+ }
500
+
501
+ private userLayer(): Record<string, unknown> | undefined {
502
+ return this.snapshotOf().user as Record<string, unknown> | undefined
503
+ }
504
+
505
+ private stored(field: string): boolean {
506
+ const user = this.userLayer()
507
+ return user !== undefined && Object.hasOwn(user, field)
508
+ }
509
+
510
+ private publish(): void {
511
+ for (const listener of this.listeners) listener()
512
+ }
513
+ }
514
+
515
+ /** Structural equality for JSON settings values (primitives, arrays, plain objects). */
516
+ function jsonValuesEqual(left: unknown, right: unknown): boolean {
517
+ if (Object.is(left, right)) return true
518
+ if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) return false
519
+ if (Array.isArray(left) || Array.isArray(right)) {
520
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
521
+ return left.every((item, index) => jsonValuesEqual(item, right[index]))
522
+ }
523
+ const a = left as Record<string, unknown>
524
+ const b = right as Record<string, unknown>
525
+ const keysA = Object.keys(a).filter(key => a[key] !== undefined)
526
+ const keysB = Object.keys(b).filter(key => b[key] !== undefined)
527
+ if (keysA.length !== keysB.length) return false
528
+ return keysA.every(key => Object.hasOwn(b, key) && jsonValuesEqual(a[key], b[key]))
529
+ }