pantheon-opencode 2.0.0-beta.3 → 2.0.0-beta.5

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