pantheon-opencode 2.0.0-beta.2 → 2.0.0-beta.4

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.
@@ -3,58 +3,100 @@
3
3
  /** @jsxImportSource @opentui/solid */
4
4
 
5
5
  /**
6
- * pantheon-settings.tsx — the /pantheon-settings window.
6
+ * pantheon-settings.tsx — the /pantheon-settings window (2.0.0-beta.4).
7
7
  *
8
- * One section per page, keyboard-first: `tab` cycles sections, `up`/`down`
9
- * select, `enter`/`space` dispatches the selected row (the Gates section
10
- * writes the GLOBAL overrides file — the same one the installer and doctor
11
- * consume; Updates runs a registry check). `escape`/`q` closes. The
12
- * gated-layer pattern mirrors the dispatch panel and whats-new windows.
13
- * Every failure path is silent (fail-open).
8
+ * A FULL-SCREEN settings window in the OpenCode Quota shape: a tab header,
9
+ * grouped setting rows with ←/→ value cyclers, a note column, and a
10
+ * save/reset footer. The surface is a ROUTER PAGE (`ui.router.register` +
11
+ * `navigate({type:'plugin'})`) — true full-screen, reachable from the home
12
+ * route AND sessions, no focus dance (binary-verified precedent: the host's
13
+ * own opencode.diffs plugin). Hosts without a router fall back to the old
14
+ * dialog with the same commands (fail-open).
15
+ *
16
+ * Edits stage into a DRAFT: ←/→ cycles a row's value, `ctrl+s` saves every
17
+ * staged row through the per-surface guards, `ctrl+r` resets the current
18
+ * tab, `esc`/`q` confirms before discarding. The disk never changes before
19
+ * save, and every refusal surfaces in the notice line — never silent.
20
+ *
21
+ * The keymap layer is registered ONCE at setup with `priority: 1` (the host
22
+ * resolves bind conflicts by priority then registration order — a stale
23
+ * dispatch-panel layer must never win while this window is open; field
24
+ * report beta.2: navigation "stopped working" was exactly that theft).
14
25
  */
15
26
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
16
27
  import { join } from 'node:path'
17
28
  import type { Context } from '@opencode/plugin/tui/context'
18
- import { createSignal, For, Show } from 'solid-js'
29
+ import { createSignal, For, onCleanup, Show } from 'solid-js'
19
30
  import {
20
- buildDecisionSection,
31
+ buildDecisionTab,
32
+ type DecisionConfigRead,
21
33
  readDecisionRouterConfig,
22
34
  setDecisionEnabled,
23
35
  writeDecisionRouterConfig,
24
36
  } from './decision-router-state.ts'
25
- import { buildDoctorSection } from './doctor-state.ts'
26
- import { buildJ1Section } from './j1-gate-status.ts'
37
+ import { buildDoctorTab } from './doctor-state.ts'
38
+ import { buildJ1Tab } from './j1-gate-status.ts'
27
39
  import {
28
- buildAboutSection,
29
- buildGatesSection,
40
+ applyDraft,
41
+ buildAboutTab,
42
+ buildGatesTab,
30
43
  canWriteOverrides,
44
+ type DraftWriter,
45
+ type DraftWriterResult,
46
+ draftCount,
47
+ draftDirty,
31
48
  type EffectiveOverrides,
32
- firstSelectableId,
33
- flatSelectableRows,
34
- isBehaviorDisabled,
35
- mergedOverrides,
49
+ EMPTY_TAB,
36
50
  type OverridesLoad,
51
+ resetTab,
52
+ type SettingsDraft,
37
53
  type SettingsRow,
38
- type SettingsSection,
54
+ type SettingsTab,
39
55
  serializeOverrides,
40
- toggledOverrides,
56
+ setOverrideState,
57
+ settledDraft,
58
+ stageValue,
59
+ tabDirty,
60
+ tabRows,
41
61
  } from './pantheon-settings-state.ts'
42
62
  import {
43
- buildPresetSection,
63
+ buildPresetTab,
44
64
  clearActivePreset,
45
65
  globalActivePresetPath,
66
+ PRESET_NONE,
46
67
  projectActivePresetPath,
47
68
  readActivePresetMarker,
48
69
  writeActivePreset,
49
70
  } from './preset-state.ts'
50
71
  import { nextCheckState, type UpdateCheckState } from './update-notice.ts'
51
72
  import {
52
- buildUpdatesSection,
73
+ buildUpdatesTab,
53
74
  registryUrlForChannel,
54
75
  type UpdatesSectionInput,
55
76
  updateChannelFor,
56
77
  } from './update-status.ts'
57
78
 
79
+ export const ROUTE_NAME = 'pantheon-settings'
80
+
81
+ /** Loose local shape of a host route (the real Route lives in the host typings). */
82
+ type WindowRoute =
83
+ | { type: 'home' }
84
+ | { type: 'session'; sessionID: string }
85
+ | { type: 'plugin'; name: string; data?: Record<string, unknown> }
86
+
87
+ // ── Shared blocking state (the dispatch panel gates on this) ───────────
88
+
89
+ const [blocking, setBlocking] = createSignal(false)
90
+
91
+ /** True while a Pantheon settings surface (page or fallback dialog) is open. */
92
+ export function pantheonSettingsBlocking(): boolean {
93
+ return blocking()
94
+ }
95
+
96
+ let routerAvailable = false
97
+
98
+ // ── Disk readers/writers (unchanged contracts from beta.2/3) ───────────
99
+
58
100
  function globalOverridesPath(): string {
59
101
  const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config')
60
102
  return join(xdgConfig, 'opencode', 'pantheon-overrides.json')
@@ -64,7 +106,6 @@ function projectOverridesPath(): string {
64
106
  return join(process.cwd(), '.pantheon', 'overrides.json')
65
107
  }
66
108
 
67
- /** Read one overrides file; a missing file is empty, an unreadable one is corrupt. */
68
109
  function readOneOverrides(path: string): { value: EffectiveOverrides; corrupt: boolean } {
69
110
  try {
70
111
  const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
@@ -104,10 +145,6 @@ function readUpdateCheckState(): UpdateCheckState {
104
145
  }
105
146
  }
106
147
 
107
- /**
108
- * Registry check for the RUNNING version's channel (beta installs ask the
109
- * beta dist-tag). Resolves with the latest version seen, or null offline.
110
- */
111
148
  async function fetchLatestForChannel(currentVersion: string): Promise<string | null> {
112
149
  try {
113
150
  const response = await fetch(registryUrlForChannel(updateChannelFor(currentVersion)), {
@@ -144,299 +181,596 @@ function resolveRunningVersion(): string {
144
181
  }
145
182
  }
146
183
 
147
- export function SettingsContent(props: {
148
- sections: () => SettingsSection[]
184
+ // ── The window view (presentational; both surfaces render it) ──────────
185
+
186
+ const NAME_WIDTH = 26
187
+ const VALUE_WIDTH = 22
188
+
189
+ export function SettingsWindow(props: {
190
+ version: string
191
+ tabs: () => SettingsTab[]
149
192
  page: () => number
150
- selectedId: () => string | undefined
193
+ selected: () => number
194
+ draft: () => SettingsDraft
195
+ notice: () => string | undefined
151
196
  fg?: any
152
197
  muted?: any
198
+ warn?: any
153
199
  }) {
154
- const section = () =>
155
- props.sections()[props.page()] ?? {
156
- id: 'empty',
157
- title: '',
158
- rows: [],
159
- }
200
+ const tab = () => props.tabs()[props.page()] ?? props.tabs()[0] ?? EMPTY_TAB
201
+ const rows = () => tabRows(tab())
160
202
  return (
161
203
  <box flexDirection="column" paddingLeft={1} paddingRight={1} paddingTop={1}>
162
- <text attributes={1} fg={props.fg}>
163
- {section().title}
164
- </text>
165
- <text fg={props.muted}>{'─'.repeat(38)}</text>
166
- <For each={section().rows}>
167
- {(row: SettingsRow) => {
168
- const isSelected = () => row.selectable !== false && row.id === props.selectedId()
169
- const marker = () => row.marker ?? (row.disabled ? '[x]' : '[ ]')
170
- return (
171
- <box flexDirection="column">
172
- <text
173
- fg={isSelected() ? props.fg : props.muted}
174
- {...(isSelected() ? { attributes: 1 } : {})}
175
- >
176
- {`${marker()} ${row.title}${isSelected() ? ' <-' : ''}`}
204
+ <box flexDirection="row">
205
+ <text attributes={1} fg={props.fg}>
206
+ {`Pantheon v${props.version}`}
207
+ </text>
208
+ <For each={props.tabs()}>
209
+ {(t, index) => (
210
+ <text
211
+ fg={index() === props.page() ? props.fg : props.muted}
212
+ {...(index() === props.page() ? { attributes: 1 } : {})}
213
+ >
214
+ {` ${t.title}${tabDirty(props.draft(), t) ? ' ●' : ''}`}
215
+ </text>
216
+ )}
217
+ </For>
218
+ <text fg={props.muted}>{' esc'}</text>
219
+ </box>
220
+ <text fg={props.muted}>{'─'.repeat(72)}</text>
221
+ <For each={tab().groups}>
222
+ {(group) => (
223
+ <box flexDirection="column">
224
+ <Show when={group.title !== undefined}>
225
+ <text attributes={1} fg={props.fg}>
226
+ {group.title}
177
227
  </text>
178
- <Show when={row.description !== ''}>
179
- <text fg={props.muted}>{` ${row.description}`}</text>
180
- </Show>
181
- </box>
182
- )
183
- }}
228
+ </Show>
229
+ <For each={group.rows}>
230
+ {(row: SettingsRow) => {
231
+ const isSelected = () => rows()[props.selected()]?.id === row.id
232
+ const display = () => props.draft()[row.id] ?? row.value
233
+ const staged = () => props.draft()[row.id] !== undefined
234
+ const gutter = () => (isSelected() ? '▸ ' : ' ')
235
+ const valueCell = () => (row.cycle !== undefined ? `< ${display()} >` : display())
236
+ return (
237
+ <box flexDirection="row">
238
+ <box width={NAME_WIDTH + 2}>
239
+ <text fg={props.fg} {...(isSelected() ? { attributes: 1 } : {})}>
240
+ {`${gutter()}${row.name}`.padEnd(NAME_WIDTH + 2)}
241
+ </text>
242
+ </box>
243
+ <box width={VALUE_WIDTH}>
244
+ <text
245
+ fg={isSelected() || staged() ? props.fg : props.muted}
246
+ {...(isSelected() ? { attributes: 1 } : {})}
247
+ >
248
+ {`${valueCell()}${staged() ? ' ●' : ''}`.padEnd(VALUE_WIDTH)}
249
+ </text>
250
+ </box>
251
+ <Show when={row.note !== undefined}>
252
+ <box flexGrow={1} flexShrink={1}>
253
+ <text fg={props.muted}>{row.note}</text>
254
+ </box>
255
+ </Show>
256
+ </box>
257
+ )
258
+ }}
259
+ </For>
260
+ <box height={1} />
261
+ </box>
262
+ )}
184
263
  </For>
185
- <box height={1} />
186
- <Show when={section().hint !== undefined}>
187
- <text fg={props.muted}>{section().hint}</text>
264
+ <Show when={props.notice() !== undefined}>
265
+ <text fg={props.warn ?? props.muted}>{`⚠ ${props.notice()}`}</text>
188
266
  </Show>
267
+ <text fg={draftDirty(props.draft()) ? (props.warn ?? props.fg) : props.muted}>
268
+ {draftDirty(props.draft())
269
+ ? `● unsaved (${draftCount(props.draft())}) — ctrl+s save · ctrl+r reset page`
270
+ : 'no staged changes'}
271
+ </text>
189
272
  <text fg={props.muted}>
190
- {`${props.page() + 1}/${props.sections().length} · `}tab: section · up/down: select · enter:
191
- apply · esc/q: close
273
+ {
274
+ '1-9 tab · ←/→ change value · enter apply · tab next tab · ctrl+s save · ctrl+r reset page · esc/q close'
275
+ }
192
276
  </text>
193
277
  </box>
194
278
  )
195
279
  }
196
280
 
197
- /**
198
- * Entry glue: read both overrides files, then show the window through the
199
- * host dialog stack once. The gated keymap layer is inert while the window
200
- * is closed. Never throws.
201
- */
202
- export async function maybeShowPantheonSettings(context: Context): Promise<void> {
203
- try {
204
- const [open, setOpen] = createSignal(false)
205
- const [page, setPage] = createSignal(0)
206
- const [load, setLoad] = createSignal<OverridesLoad>(readOverridesLoad())
207
- const [lastChecked, setLastChecked] = createSignal<string | undefined>(undefined)
208
- const [checking, setChecking] = createSignal(false)
209
- const [decision, setDecision] = createSignal(readDecisionRouterConfig())
210
- const [presetTick, setPresetTick] = createSignal(0)
211
-
212
- const currentVersion = resolveRunningVersion()
213
-
214
- const updatesInput = (): UpdatesSectionInput => {
215
- const input: UpdatesSectionInput = {
216
- currentVersion,
217
- state: readUpdateCheckState(),
218
- checking: checking(),
219
- nowMs: Date.now(),
220
- }
221
- const seen = lastChecked()
222
- if (seen !== undefined) input.lastCheckedVersion = seen
223
- return input
224
- }
281
+ // ── Shared window controller (signals + writers), mounted per surface ──
225
282
 
226
- const presetInput = () => {
227
- void presetTick()
228
- return {
229
- globalName: readActivePresetMarker(globalActivePresetPath())?.name ?? null,
230
- projectName: readActivePresetMarker(projectActivePresetPath())?.name ?? null,
231
- }
232
- }
283
+ interface PageApi {
284
+ move: (delta: number) => void
285
+ step: (direction: 1 | -1) => void
286
+ actuate: () => void
287
+ nextTab: () => void
288
+ jumpTab: (index: number) => void
289
+ save: () => void
290
+ resetPage: () => void
291
+ close: () => void
292
+ }
233
293
 
234
- const sections = (): SettingsSection[] => [
235
- buildGatesSection(load()),
236
- buildDecisionSection(decision()),
237
- buildPresetSection(presetInput()),
238
- buildJ1Section(process.env, isBehaviorDisabled(mergedOverrides(load()), 'gate-j1-risk-gate')),
239
- buildUpdatesSection(updatesInput()),
240
- buildDoctorSection({
241
- runningVersion: currentVersion,
242
- nodeVersion: process.versions.node,
243
- load: load(),
244
- }),
245
- buildAboutSection(currentVersion),
246
- ]
247
- const [selectedId, setSelectedId] = createSignal<string | undefined>(
248
- firstSelectableId(sections()),
249
- )
294
+ let pageApi: PageApi | undefined
250
295
 
251
- const move = (delta: number) => {
252
- const list = flatSelectableRows(sections())
253
- if (list.length === 0) return
254
- const current = list.findIndex((row) => row.id === selectedId())
255
- const nextIndex = current === -1 ? 0 : Math.min(Math.max(current + delta, 0), list.length - 1)
256
- setSelectedId(list[nextIndex]?.id)
296
+ function createWindowController(
297
+ context: Context,
298
+ exit: () => void,
299
+ ): {
300
+ tabs: () => SettingsTab[]
301
+ page: () => number
302
+ selected: () => number
303
+ draft: () => SettingsDraft
304
+ notice: () => string | undefined
305
+ api: PageApi
306
+ cleanup: () => void
307
+ } {
308
+ const [page, setPage] = createSignal(0)
309
+ const [selected, setSelected] = createSignal(0)
310
+ const [load, setLoad] = createSignal(readOverridesLoad())
311
+ const [decision, setDecision] = createSignal<DecisionConfigRead>(readDecisionRouterConfig())
312
+ const [presetTick, setPresetTick] = createSignal(0)
313
+ const [lastChecked, setLastChecked] = createSignal<string | undefined>(undefined)
314
+ const [checking, setChecking] = createSignal(false)
315
+ const [draft, setDraft] = createSignal<SettingsDraft>({})
316
+ const [notice, setNotice] = createSignal<string | undefined>(undefined)
317
+
318
+ const currentVersion = resolveRunningVersion()
319
+
320
+ const presetInput = () => {
321
+ void presetTick()
322
+ return {
323
+ globalName: readActivePresetMarker(globalActivePresetPath())?.name ?? null,
324
+ projectName: readActivePresetMarker(projectActivePresetPath())?.name ?? null,
257
325
  }
326
+ }
258
327
 
259
- const flipSection = () => {
260
- const count = sections().length
261
- const next = (page() + 1) % count
262
- setPage(next)
263
- const target = sections()[next]
264
- if (target === undefined) return
265
- const within = flatSelectableRows([target])[0]
266
- if (within) setSelectedId(within.id)
328
+ const updatesInput = (): UpdatesSectionInput => {
329
+ const input: UpdatesSectionInput = {
330
+ currentVersion,
331
+ state: readUpdateCheckState(),
332
+ checking: checking(),
333
+ nowMs: Date.now(),
267
334
  }
335
+ const seen = lastChecked()
336
+ if (seen !== undefined) input.lastCheckedVersion = seen
337
+ return input
338
+ }
268
339
 
269
- const toggleSelectedGate = () => {
270
- const id = selectedId()
271
- if (id === undefined || !id.startsWith('gate.')) return false
272
- if (!canWriteOverrides(load())) return undefined // corrupt file — writes refused
273
- const behaviorId = id.slice('gate.'.length)
274
- const next: OverridesLoad = {
275
- ...load(),
276
- global: toggledOverrides(load().global, behaviorId),
340
+ const tabs = (): SettingsTab[] => [
341
+ buildGatesTab(load()),
342
+ buildDecisionTab(decision()),
343
+ buildPresetTab(presetInput()),
344
+ buildJ1Tab(process.env, false),
345
+ buildUpdatesTab(updatesInput()),
346
+ buildDoctorTab({
347
+ runningVersion: currentVersion,
348
+ nodeVersion: process.versions.node,
349
+ load: load(),
350
+ }),
351
+ buildAboutTab(currentVersion),
352
+ ]
353
+
354
+ const rows = () => tabRows(tabs()[page()] ?? tabs()[0] ?? EMPTY_TAB)
355
+
356
+ const move = (delta: number) => {
357
+ const list = rows()
358
+ if (list.length === 0) return
359
+ setSelected((current) => Math.min(Math.max(current + delta, 0), list.length - 1))
360
+ }
361
+
362
+ const step = (direction: 1 | -1) => {
363
+ const row = rows()[selected()]
364
+ if (row === undefined) return
365
+ setNotice(undefined)
366
+ setDraft(stageValue(draft(), row, direction))
367
+ }
368
+
369
+ const checkUpdatesNow = () => {
370
+ if (checking()) return
371
+ setChecking(true)
372
+ setNotice(undefined)
373
+ void fetchLatestForChannel(currentVersion)
374
+ .then((latest) => {
375
+ if (latest) setLastChecked(latest)
376
+ persistUpdateCheckState(readUpdateCheckState(), latest)
377
+ })
378
+ .catch(() => {
379
+ /* offline — the row keeps the last known state */
380
+ })
381
+ .finally(() => setChecking(false))
382
+ }
383
+
384
+ const dispatchWrite = (id: string, value: string): DraftWriterResult => {
385
+ if (id.startsWith('gate.')) {
386
+ if (!canWriteOverrides(load())) {
387
+ return { ok: false, reason: 'overrides file unreadable — repair with `doctor --fix`' }
277
388
  }
389
+ const behaviorId = id.slice('gate.'.length)
390
+ const nextGlobal = setOverrideState(
391
+ load().global,
392
+ behaviorId,
393
+ value === 'disabled' ? 'disabled' : 'enabled',
394
+ )
395
+ if (nextGlobal === load().global) return { ok: true }
278
396
  try {
279
- writeOverridesToDisk(next)
280
- setLoad(next)
397
+ writeOverridesToDisk({ ...load(), global: nextGlobal })
398
+ setLoad({ ...load(), global: nextGlobal })
399
+ return { ok: true }
281
400
  } catch {
282
- /* disk write failed — keep the in-memory state, stay open */
401
+ return { ok: false, reason: 'overrides disk write failed' }
283
402
  }
284
- return undefined
285
403
  }
286
-
287
- const checkUpdatesNow = () => {
288
- if (checking()) return undefined
289
- setChecking(true)
290
- void fetchLatestForChannel(currentVersion)
291
- .then((latest) => {
292
- if (latest) setLastChecked(latest)
293
- persistUpdateCheckState(readUpdateCheckState(), latest)
294
- })
295
- .catch(() => {
296
- /* offline — the row keeps the last known state */
297
- })
298
- .finally(() => setChecking(false))
299
- return undefined
300
- }
301
-
302
- const toggleDecisionEnabled = () => {
404
+ if (id === 'decision.enabled') {
303
405
  const current = decision()
304
- if (current.corrupt) return undefined // invalid file — writes refused
305
- const next = setDecisionEnabled(current.config, !current.config.enabled)
306
- if (!next.ok) return undefined // guard refused (egress consent missing)
406
+ if (current.corrupt) {
407
+ return {
408
+ ok: false,
409
+ reason: 'decision-router.json unreadable — repair via `decision-router setup-model`',
410
+ }
411
+ }
412
+ const guarded = setDecisionEnabled(current.config, value === 'enabled')
413
+ if (!guarded.ok) return { ok: false, reason: guarded.reason }
307
414
  try {
308
- writeDecisionRouterConfig(next.config)
309
- setDecision({ config: next.config, corrupt: false })
415
+ writeDecisionRouterConfig(guarded.config)
416
+ setDecision({ config: guarded.config, corrupt: false })
417
+ return { ok: true }
310
418
  } catch {
311
- /* disk write failed — keep the in-memory state */
419
+ return { ok: false, reason: 'decision-router disk write failed' }
312
420
  }
313
- return undefined
314
421
  }
315
-
316
- const applySelectedPreset = () => {
317
- const id = selectedId()
318
- if (id === undefined) return undefined
319
- const name = id.startsWith('preset.') ? id.slice('preset.'.length) : null
320
- if (name === null || name === 'project') return undefined
321
- const path = globalActivePresetPath()
422
+ if (id === 'preset') {
322
423
  try {
323
- if (name === 'none') clearActivePreset(path)
324
- else writeActivePreset(path, name)
424
+ if (value === PRESET_NONE) clearActivePreset(globalActivePresetPath())
425
+ else writeActivePreset(globalActivePresetPath(), value)
325
426
  setPresetTick((tick) => tick + 1)
326
- } catch {
327
- /* disk write failed — the section keeps showing the last read state */
427
+ return { ok: true }
428
+ } catch (error) {
429
+ return {
430
+ ok: false,
431
+ reason: error instanceof Error ? error.message : 'preset marker write failed',
432
+ }
328
433
  }
329
- return undefined
330
434
  }
435
+ return { ok: false, reason: 'unknown staged row' }
436
+ }
331
437
 
332
- let dismiss: () => void = () => {}
333
- try {
334
- context.keymap.layer(() => ({
335
- mode: 'global',
336
- enabled: () => open(),
337
- commands: [
338
- {
339
- id: 'pantheon.settings.close',
340
- title: 'Close settings',
341
- bind: 'escape,q',
342
- run: () => {
343
- if (!open()) return false
344
- dismiss()
345
- return undefined
346
- },
347
- },
348
- {
349
- id: 'pantheon.settings.down',
350
- title: 'Select next',
351
- bind: 'down,j',
352
- run: () => {
353
- if (!open()) return false
354
- move(1)
355
- return undefined
356
- },
357
- },
358
- {
359
- id: 'pantheon.settings.up',
360
- title: 'Select previous',
361
- bind: 'up,k',
362
- run: () => {
363
- if (!open()) return false
364
- move(-1)
365
- return undefined
366
- },
367
- },
368
- {
369
- id: 'pantheon.settings.toggle',
370
- title: 'Apply the selected row',
371
- bind: 'enter,space',
372
- run: () => {
373
- if (!open()) return false
374
- const id = selectedId()
375
- if (id?.startsWith('gate.')) return toggleSelectedGate()
376
- if (id === 'decision.enabled') return toggleDecisionEnabled()
377
- if (id?.startsWith('preset.')) return applySelectedPreset()
378
- if (id === 'update.check') return checkUpdatesNow()
379
- return undefined
380
- },
381
- },
382
- {
383
- id: 'pantheon.settings.section',
384
- title: 'Next section',
385
- bind: 'tab',
386
- run: () => {
387
- if (!open()) return false
388
- flipSection()
389
- return undefined
390
- },
391
- },
392
- ],
393
- }))
394
- } catch {
395
- /* keymap API unavailable — the host dialog chrome still dismisses (ESC) */
438
+ const save = () => {
439
+ if (!draftDirty(draft())) {
440
+ setNotice('nothing staged — ←/→ stages a change first')
441
+ return
396
442
  }
397
-
398
- // The host may dismiss the dialog on its own and call this callback from
399
- // inside its dismissal; mutating the dialog stack there re-enters the host
400
- // mid-close and the swallowed failure leaves the window unclosable (the
401
- // whats-new split: clear() lives only in dismiss, never in close).
402
- const close = () => {
403
- setOpen(false)
443
+ const writer: DraftWriter = dispatchWrite
444
+ const { applied, failed } = applyDraft(draft(), writer)
445
+ if (applied.length > 0) {
446
+ setDraft(settledDraft(draft(), applied))
447
+ setLoad(readOverridesLoad())
448
+ setDecision(readDecisionRouterConfig())
449
+ setPresetTick((tick) => tick + 1)
404
450
  }
405
- dismiss = () => {
451
+ if (failed.length > 0) {
452
+ setNotice(`${failed.map((f) => `${f.id}: ${f.reason}`).join(' · ')} — staged changes kept`)
453
+ } else {
454
+ setNotice(`saved ${applied.length} change${applied.length === 1 ? '' : 's'}`)
455
+ }
456
+ }
457
+
458
+ const resetPage = () => {
459
+ const tab = tabs()[page()]
460
+ if (tab === undefined) return
461
+ setDraft(resetTab(draft(), tab))
462
+ setNotice(undefined)
463
+ }
464
+
465
+ const nextTab = () => {
466
+ setPage((current) => (current + 1) % tabs().length)
467
+ setSelected(0)
468
+ }
469
+
470
+ const close = () => {
471
+ if (draftDirty(draft())) {
406
472
  try {
407
- context.ui.dialog.clear()
473
+ void Promise.resolve(
474
+ context.ui.dialog.confirm({
475
+ title: 'Pantheon settings',
476
+ message: 'Discard unsaved settings changes?',
477
+ }),
478
+ ).then((confirmed) => {
479
+ if (confirmed === true) exit()
480
+ })
408
481
  } catch {
409
- /* already closed */
482
+ /* confirm unavailable — stay open; the user can ctrl+r first */
410
483
  }
411
- close()
484
+ return
412
485
  }
413
- setOpen(true)
414
- setPage(0)
486
+ exit()
487
+ }
488
+
489
+ const api: PageApi = {
490
+ move,
491
+ step,
492
+ actuate: () => {
493
+ const row = rows()[selected()]
494
+ if (row?.action === 'update-check') checkUpdatesNow()
495
+ else step(1)
496
+ },
497
+ nextTab,
498
+ jumpTab: (index) => {
499
+ if (index >= 0 && index < tabs().length) {
500
+ setPage(index)
501
+ setSelected(0)
502
+ }
503
+ },
504
+ save,
505
+ resetPage,
506
+ close,
507
+ }
508
+
509
+ return {
510
+ tabs,
511
+ page,
512
+ selected,
513
+ draft,
514
+ notice,
515
+ api,
516
+ cleanup: () => {
517
+ pageApi = undefined
518
+ setBlocking(false)
519
+ },
520
+ }
521
+ }
522
+
523
+ // ── The router page (the primary surface) ──────────────────────────────
524
+
525
+ function SettingsPage(props: { context: Context; data: Record<string, any> | undefined }) {
526
+ const returnRoute = (props.data as { returnRoute?: WindowRoute } | undefined)?.returnRoute
527
+ const context = props.context
528
+ const controller = createWindowController(context, () =>
529
+ navigateBack(context, returnRoute !== undefined ? { returnRoute } : {}),
530
+ )
531
+ const theme = context.theme?.text ?? {}
532
+ const warn = (theme?.feedback as any)?.warning?.base ?? theme.muted
533
+ onCleanup(controller.cleanup)
534
+ setBlocking(true)
535
+ pageApi = controller.api
536
+ return (
537
+ <SettingsWindow
538
+ version={resolveRunningVersion()}
539
+ tabs={controller.tabs}
540
+ page={controller.page}
541
+ selected={controller.selected}
542
+ draft={controller.draft}
543
+ notice={controller.notice}
544
+ fg={theme.base}
545
+ muted={theme.muted}
546
+ warn={warn}
547
+ />
548
+ )
549
+ }
550
+
551
+ function navigateBack(context: Context, data?: { returnRoute?: WindowRoute }): void {
552
+ try {
553
+ const fallback: WindowRoute = { type: 'home' }
554
+ context.ui.router.navigate(data?.returnRoute ?? fallback)
555
+ } catch {
556
+ /* router unavailable — nothing to navigate back to */
557
+ }
558
+ }
559
+
560
+ // ── The fallback dialog (hosts without a router) ───────────────────────
561
+
562
+ const [dialogOpen, setDialogOpen] = createSignal(false)
563
+ let dialogDismiss: () => void = () => {}
564
+
565
+ function openSettingsDialog(context: Context): void {
566
+ const controller = createWindowController(context, () => dialogDismiss())
567
+ const theme = context.theme?.text ?? {}
568
+ const warn = (theme?.feedback as any)?.warning?.base ?? theme.muted
569
+ controller.cleanup = () => {
570
+ pageApi = undefined
571
+ setBlocking(false)
572
+ setDialogOpen(false)
573
+ }
574
+ // The host may dismiss the dialog on its own and call this callback from
575
+ // inside its dismissal; clear() must never run there (the whats-new split).
576
+ const close = () => {
577
+ controller.cleanup()
578
+ }
579
+ dialogDismiss = () => {
415
580
  try {
416
- const theme = context.theme?.text ?? {}
417
- context.ui.dialog.show(
418
- () => (
419
- <SettingsContent
420
- sections={sections}
421
- page={page}
422
- selectedId={selectedId}
423
- fg={theme.base}
424
- muted={theme.muted}
425
- />
426
- ),
427
- close,
428
- )
429
- // Roomier chrome for the sectioned window; older hosts without `set`
430
- // keep the default size (fail-open).
581
+ context.ui.dialog.clear()
582
+ } catch {
583
+ /* already closed */
584
+ }
585
+ close()
586
+ }
587
+ setBlocking(true)
588
+ setDialogOpen(true)
589
+ pageApi = controller.api
590
+ try {
591
+ context.ui.dialog.show(
592
+ () => (
593
+ <SettingsWindow
594
+ version={resolveRunningVersion()}
595
+ tabs={controller.tabs}
596
+ page={controller.page}
597
+ selected={controller.selected}
598
+ draft={controller.draft}
599
+ notice={controller.notice}
600
+ fg={theme.base}
601
+ muted={theme.muted}
602
+ warn={warn}
603
+ />
604
+ ),
605
+ close,
606
+ )
607
+ } catch {
608
+ /* dialog stack unavailable — fail-open */
609
+ }
610
+ }
611
+
612
+ // ── Setup: register once, gate once, priority 1 (anti-theft) ───────────
613
+
614
+ export function setupPantheonSettings(context: Context): void {
615
+ try {
616
+ context.ui.router?.register?.({
617
+ name: ROUTE_NAME,
618
+ render: ({ data }) => <SettingsPage context={context} data={data} />,
619
+ })
620
+ routerAvailable = true
621
+ } catch {
622
+ routerAvailable = false
623
+ }
624
+
625
+ const routeGated = () => {
626
+ try {
627
+ const route = context.ui?.router?.current?.()
628
+ return route?.type === 'plugin' && route.name === ROUTE_NAME
629
+ } catch {
630
+ return false
631
+ }
632
+ }
633
+ const commands = [
634
+ {
635
+ id: 'pantheon.settings.close',
636
+ title: 'Close settings',
637
+ bind: 'escape,q',
638
+ run: () => {
639
+ pageApi?.close()
640
+ return undefined
641
+ },
642
+ },
643
+ {
644
+ id: 'pantheon.settings.down',
645
+ title: 'Select next row',
646
+ bind: 'down,j',
647
+ run: () => {
648
+ pageApi?.move(1)
649
+ return undefined
650
+ },
651
+ },
652
+ {
653
+ id: 'pantheon.settings.up',
654
+ title: 'Select previous row',
655
+ bind: 'up,k',
656
+ run: () => {
657
+ pageApi?.move(-1)
658
+ return undefined
659
+ },
660
+ },
661
+ {
662
+ id: 'pantheon.settings.cycle.next',
663
+ title: 'Stage the next value',
664
+ bind: 'right,l',
665
+ run: () => {
666
+ pageApi?.step(1)
667
+ return undefined
668
+ },
669
+ },
670
+ {
671
+ id: 'pantheon.settings.cycle.prev',
672
+ title: 'Stage the previous value',
673
+ bind: 'left,h',
674
+ run: () => {
675
+ pageApi?.step(-1)
676
+ return undefined
677
+ },
678
+ },
679
+ {
680
+ id: 'pantheon.settings.actuate',
681
+ title: 'Apply / act on the row',
682
+ bind: 'enter,space',
683
+ run: () => {
684
+ pageApi?.actuate()
685
+ return undefined
686
+ },
687
+ },
688
+ {
689
+ id: 'pantheon.settings.next.tab',
690
+ title: 'Next settings tab',
691
+ bind: 'tab',
692
+ run: () => {
693
+ pageApi?.nextTab()
694
+ return undefined
695
+ },
696
+ },
697
+ {
698
+ id: 'pantheon.settings.save',
699
+ title: 'Save staged changes',
700
+ bind: 'ctrl+s',
701
+ run: () => {
702
+ pageApi?.save()
703
+ return undefined
704
+ },
705
+ },
706
+ {
707
+ id: 'pantheon.settings.reset.page',
708
+ title: 'Reset this tab',
709
+ bind: 'ctrl+r',
710
+ run: () => {
711
+ pageApi?.resetPage()
712
+ return undefined
713
+ },
714
+ },
715
+ ...Array.from({ length: 9 }, (_, index) => ({
716
+ id: `pantheon.settings.tab.${index + 1}`,
717
+ title: `Jump to tab ${index + 1}`,
718
+ bind: String(index + 1),
719
+ run: () => {
720
+ pageApi?.jumpTab(index)
721
+ return undefined
722
+ },
723
+ })),
724
+ ]
725
+ // The PAGE layer: gated on the route, priority 1 beats any stale
726
+ // same-bind layer while the window is open (beta.2 field report).
727
+ try {
728
+ context.keymap.layer(() => ({
729
+ mode: 'global' as const,
730
+ priority: 1,
731
+ enabled: () => routeGated(),
732
+ commands,
733
+ }))
734
+ } catch {
735
+ /* keymap API unavailable — the fallback dialog below still works */
736
+ }
737
+ // The FALLBACK DIALOG layer: same commands, gated on the dialog signal.
738
+ try {
739
+ context.keymap.layer(() => ({
740
+ mode: 'global' as const,
741
+ priority: 1,
742
+ enabled: () => dialogOpen(),
743
+ commands,
744
+ }))
745
+ } catch {
746
+ /* keymap API unavailable — host chrome still dismisses (ESC) */
747
+ }
748
+ }
749
+
750
+ // ── The entry point (command run) ──────────────────────────────────────
751
+
752
+ export async function openPantheonSettings(context: Context): Promise<void> {
753
+ try {
754
+ if (routerAvailable && context.ui?.router?.navigate) {
755
+ let returnRoute: WindowRoute | undefined
431
756
  try {
432
- context.ui.dialog.set?.({ size: 'xlarge' })
757
+ const current = context.ui.router.current()
758
+ // Never return INTO the settings page itself.
759
+ if (!(current.type === 'plugin' && current.name === ROUTE_NAME)) {
760
+ returnRoute = current as WindowRoute
761
+ }
433
762
  } catch {
434
- /* size control unavailable */
763
+ returnRoute = undefined
435
764
  }
436
- } catch {
437
- /* dialog stack unavailable — fail-open */
765
+ context.ui.router.navigate({
766
+ type: 'plugin',
767
+ name: ROUTE_NAME,
768
+ ...(returnRoute !== undefined ? { data: { returnRoute } } : {}),
769
+ })
770
+ return
438
771
  }
439
772
  } catch {
440
- /* fail-open — the window must never block or break TUI startup */
773
+ /* router unusable — fall through to the dialog */
441
774
  }
775
+ openSettingsDialog(context)
442
776
  }