-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSettings.tsx
More file actions
2972 lines (2775 loc) · 142 KB
/
Copy pathSettings.tsx
File metadata and controls
2972 lines (2775 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { ArrowLeft, Check, X, Eye, EyeOff, Star, RefreshCw, Download, RotateCw, GitPullRequest, DownloadCloud, Keyboard, RotateCcw, Terminal as TerminalIcon, Palette, BookOpen, Code2, GitBranch, Plus, Trash2, LifeBuoy, Bug, Lightbulb, FlaskConical, Copy, CopyCheck, ExternalLink, CalendarDays, FileText, FolderOpen } from 'lucide-react'
import { openReportIssue } from './ReportIssueScreen'
import { HARNESS_ISSUES_URL, HARNESS_RELEASES_URL, harnessReleaseNotesUrl } from '../../shared/constants'
import { useSettings, useUpdater, useRepoConfigs, useHooks } from '../store'
import { useBackend } from '../backend'
import type { UpdaterStatus, MergeStrategy, RepoConfig } from '../types'
import { DEFAULT_HOTKEYS, ACTION_LABELS, bindingToString, eventToBinding, resolveHotkeys, type Action, type HotkeyBinding } from '../hotkeys'
import { Tooltip } from './Tooltip'
import { AGENT_REGISTRY, agentDisplayName, CLAUDE_MODELS, CODEX_MODELS } from '../../shared/agent-registry'
import { AgentIcon } from './AgentIcon'
import { InterfaceToggle } from './InterfaceToggle'
import { BUILT_IN_THEMES_BY_MODE, type ThemeOption } from '../themes'
import { SEMANTIC_KEYS } from '../theme-apply'
import type { CustomTheme } from '../../shared/state/settings'
import { QRCodeSVG } from 'qrcode.react'
interface SettingsProps {
onClose: () => void
onOpenGuide: () => void
onOpenMyWeek: () => void
initialSection?: SectionId
}
type SectionId = 'appearance' | 'agent' | 'worktrees' | 'editor' | 'github' | 'hotkeys' | 'updates' | 'support' | 'experimental'
type SubSectionId = 'agent-general' | 'agent-claude' | 'agent-codex'
interface SubSection {
id: SubSectionId
label: string
}
interface Section {
id: SectionId
label: string
icon: React.ComponentType<{ size?: number; className?: string }>
children?: SubSection[]
}
const SECTIONS: Section[] = [
{ id: 'appearance', label: 'Appearance', icon: Palette },
{ id: 'agent', label: 'Agent', icon: TerminalIcon, children: [
{ id: 'agent-general', label: 'General' },
{ id: 'agent-claude', label: 'Claude' },
{ id: 'agent-codex', label: 'Codex' }
]},
{ id: 'worktrees', label: 'Worktrees', icon: GitBranch },
{ id: 'editor', label: 'Editor', icon: Code2 },
{ id: 'github', label: 'GitHub', icon: GitPullRequest },
{ id: 'hotkeys', label: 'Hotkeys', icon: Keyboard },
{ id: 'updates', label: 'Updates', icon: DownloadCloud },
{ id: 'support', label: 'Support', icon: LifeBuoy },
{ id: 'experimental', label: 'Experimental', icon: FlaskConical }
]
export function Settings({ onClose, onOpenGuide, onOpenMyWeek, initialSection }: SettingsProps): JSX.Element {
const backend = useBackend()
const [activeSection, setActiveSection] = useState<SectionId>(initialSection ?? 'appearance')
const [activeSubSection, setActiveSubSection] = useState<SubSectionId | null>(null)
const scrollRef = useRef<HTMLDivElement>(null)
const sectionRefs = useRef<Record<SectionId, HTMLElement | null>>({
appearance: null,
agent: null,
worktrees: null,
editor: null,
github: null,
hotkeys: null,
updates: null,
support: null,
experimental: null
})
const subSectionRefs = useRef<Record<SubSectionId, HTMLElement | null>>({
'agent-general': null,
'agent-claude': null,
'agent-codex': null
})
const isProgrammaticScroll = useRef(false)
const scrollToSection = useCallback((id: SectionId) => {
setActiveSection(id)
const section = SECTIONS.find((s) => s.id === id)
setActiveSubSection(section?.children?.[0]?.id ?? null)
isProgrammaticScroll.current = true
const el = sectionRefs.current[id]
if (el && scrollRef.current) {
scrollRef.current.scrollTo({ top: el.offsetTop - 24, behavior: 'smooth' })
}
}, [])
const scrollToSubSection = useCallback((id: SubSectionId) => {
setActiveSubSection(id)
isProgrammaticScroll.current = true
const el = subSectionRefs.current[id]
if (el && scrollRef.current) {
scrollRef.current.scrollTo({ top: el.offsetTop - 24, behavior: 'smooth' })
}
}, [])
// Honor `initialSection` once the section refs are wired up.
useEffect(() => {
if (!initialSection) return
const el = sectionRefs.current[initialSection]
if (el && scrollRef.current) {
scrollRef.current.scrollTo({ top: el.offsetTop - 24 })
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
const container = scrollRef.current
if (!container) return
const onScrollEnd = (): void => { isProgrammaticScroll.current = false }
const onScroll = (): void => {
if (isProgrammaticScroll.current) return
const scrollTop = container.scrollTop
let current: SectionId = 'appearance'
for (const section of SECTIONS) {
const el = sectionRefs.current[section.id]
if (el && el.offsetTop - 48 <= scrollTop) {
current = section.id
}
}
setActiveSection(current)
const currentSection = SECTIONS.find((s) => s.id === current)
if (currentSection?.children) {
let currentSub: SubSectionId | null = currentSection.children[0].id
for (const child of currentSection.children) {
const el = subSectionRefs.current[child.id]
if (el && el.offsetTop - 48 <= scrollTop) {
currentSub = child.id
}
}
setActiveSubSection(currentSub)
} else {
setActiveSubSection(null)
}
}
container.addEventListener('scroll', onScroll)
container.addEventListener('scrollend', onScrollEnd)
return () => {
container.removeEventListener('scroll', onScroll)
container.removeEventListener('scrollend', onScrollEnd)
}
}, [])
// GitHub state
const [token, setToken] = useState('')
const [showToken, setShowToken] = useState(false)
const [saving, setSaving] = useState(false)
const [tokenResult, setTokenResult] = useState<{ ok: boolean; message: string } | null>(null)
const [showPatForm, setShowPatForm] = useState(false)
// Updates state — updaterStatus lives in the main-process store
const [version, setVersion] = useState<string>('')
const updaterStatus = useUpdater().status
const [checking, setChecking] = useState(false)
// All long-lived settings live in the main-process store; this hook
// re-renders Settings whenever any client updates any of them.
const settings = useSettings()
const {
themeMode,
themeLight,
themeDark,
customThemes,
hotkeys: hotkeyOverrides,
defaultAgent,
claudeCommand,
codexCommand,
harnessMcpEnabled,
claudeEnvVars,
codexEnvVars,
nameClaudeSessions,
claudeModel,
codexModel,
terminalFontFamily,
terminalFontSize,
editor: editorId,
worktreeBase,
mergeStrategy,
hasGithubToken: settingsHasToken,
githubAuthSource: authSource,
harnessStarred,
worktreeScripts,
shareClaudeSettings,
autoUpdateEnabled,
harnessSystemPromptEnabled,
harnessSystemPrompt,
harnessSystemPromptMain,
prReviewPrompt,
claudeTuiFullscreen,
browserToolsEnabled,
browserToolsMode,
wsTransportEnabled,
wsTransportPort,
wsTransportHost,
defaultClaudeTabType,
jsonModeChatDensity,
jsonModeSendOnEnter,
jsonModeDefaultPermissionMode,
autoSleepMinutes,
autoApprovePermissions,
autoApproveSteerInstructions,
snoozeDefaultDays,
expandedDiagnosticLoggingEnabled
} = settings
const setupScript = worktreeScripts.setup
const teardownScript = worktreeScripts.teardown
const [rebindingAction, setRebindingAction] = useState<Action | null>(null)
const [defaultClaudeCommand, setDefaultClaudeCommand] = useState<string>('')
const [claudeSaveResult, setClaudeSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
// Alias settings.hasGithubToken to the legacy local name so existing JSX
// stays unchanged.
const hasToken = settingsHasToken
// Claude env var state. Stored as an ordered list of [key, value] pairs so
// the user can edit a blank row without it collapsing in a Record. Seeded
// from settings on mount; edits live locally until "Save" dispatches through
// the setter IPC.
const [claudeEnvRows, setClaudeEnvRows] = useState<{ key: string; value: string }[]>(() =>
Object.entries(claudeEnvVars).map(([key, value]) => ({ key, value }))
)
const [envSaveResult, setEnvSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
const [revealedEnvRows, setRevealedEnvRows] = useState<Set<number>>(new Set())
// Custom Claude endpoint helper — drafts for ANTHROPIC_BASE_URL/_AUTH_TOKEN.
// Saves by patching claudeEnvRows + persisting via setClaudeEnvVars, so the
// env-vars editor below shares one source of truth with this helper.
const [litellmBaseUrl, setLitellmBaseUrl] = useState<string>(
() => claudeEnvVars['ANTHROPIC_BASE_URL'] ?? ''
)
const [litellmAuthToken, setLitellmAuthToken] = useState<string>(
() => claudeEnvVars['ANTHROPIC_AUTH_TOKEN'] ?? ''
)
const [litellmAuthRevealed, setLitellmAuthRevealed] = useState(false)
const [litellmSaveResult, setLitellmSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
const [codexCommandDraft, setCodexCommandDraft] = useState<string>(codexCommand)
useEffect(() => { setCodexCommandDraft(codexCommand) }, [codexCommand])
const [codexSaveResult, setCodexSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
const [codexEnvRows, setCodexEnvRows] = useState<{ key: string; value: string }[]>(() =>
Object.entries(codexEnvVars).map(([key, value]) => ({ key, value }))
)
const [codexEnvSaveResult, setCodexEnvSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
const [codexRevealedEnvRows, setCodexRevealedEnvRows] = useState<Set<number>>(new Set())
const [systemPromptDraft, setSystemPromptDraft] = useState<string>(harnessSystemPrompt)
useEffect(() => { setSystemPromptDraft(harnessSystemPrompt) }, [harnessSystemPrompt])
const [systemPromptMainDraft, setSystemPromptMainDraft] = useState<string>(harnessSystemPromptMain)
useEffect(() => { setSystemPromptMainDraft(harnessSystemPromptMain) }, [harnessSystemPromptMain])
const [systemPromptSaveResult, setSystemPromptSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
const [prReviewPromptDraft, setPrReviewPromptDraft] = useState<string>(prReviewPrompt)
useEffect(() => { setPrReviewPromptDraft(prReviewPrompt) }, [prReviewPrompt])
const [prReviewPromptSaveResult, setPrReviewPromptSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
const [defaultTerminalFontFamily, setDefaultTerminalFontFamily] = useState<string>('')
const [availableEditors, setAvailableEditors] = useState<{ id: string; name: string }[]>([])
const [scriptsSaveResult, setScriptsSaveResult] = useState<{ ok: boolean; message: string } | null>(null)
// Per-repo scope state for scopable worktree settings. scopeRepoRoot === null
// means the controls bind to global config; otherwise they bind to the
// repo-scoped .harness.json at that repoRoot. The configs map itself
// lives in the main-process store.
const repoConfigs = useRepoConfigs()
const repoList = useMemo(() => Object.keys(repoConfigs), [repoConfigs])
const [scopeRepoRoot, setScopeRepoRoot] = useState<string | null>(null)
// Hooks consent — drives the copy in the "Status hooks" card below.
const { consent: hooksConsent } = useHooks()
// WS transport: wsInfo reflects the live server (null when off or not
// yet started after enabling — the server only binds at app launch).
const [wsInfo, setWsInfo] = useState<{ port: number; token: string; host: string } | null>(null)
const [showWsToken, setShowWsToken] = useState(false)
const [wsUrlCopied, setWsUrlCopied] = useState(false)
// True after the user rotates the token in this session. The running
// servers still use the old token until the app relaunches, so we
// surface a relaunch hint — same pattern as changing port/host.
const [wsTokenRotated, setWsTokenRotated] = useState(false)
const [wsPortDraft, setWsPortDraft] = useState<string>(String(wsTransportPort))
useEffect(() => { setWsPortDraft(String(wsTransportPort)) }, [wsTransportPort])
// LAN addresses for QR-code / scannable URL generation. A machine can
// have several (WiFi + ethernet + VPN), so we surface a picker when
// more than one is present and default to the first.
const [lanAddresses, setLanAddresses] = useState<Array<{ iface: string; address: string }>>([])
const [selectedLanAddress, setSelectedLanAddress] = useState<string | null>(null)
const [debugLogError, setDebugLogError] = useState<string | null>(null)
// Constants and non-settings state load once; live settings are already
// hydrated via useSettings() above.
useEffect(() => {
void backend.getVersion().then(setVersion).catch(() => setVersion(''))
backend.getDefaultClaudeCommand().then(setDefaultClaudeCommand)
backend.getDefaultTerminalFontFamily().then(setDefaultTerminalFontFamily)
backend.getAvailableEditors().then(setAvailableEditors)
backend.getWsTransportInfo().then(setWsInfo)
backend.getLanAddresses().then((addrs) => {
setLanAddresses(addrs)
if (addrs.length > 0) setSelectedLanAddress(addrs[0].address)
})
}, [])
useEffect(() => {
backend.getWsTransportInfo().then(setWsInfo)
}, [wsTransportEnabled])
// Whenever claudeEnvVars in the store changes (e.g. another window saved),
// re-seed the local editable rows. Local edits between loads are lost —
// same as before the migration, where Settings only read on mount.
useEffect(() => {
setClaudeEnvRows(Object.entries(claudeEnvVars).map(([key, value]) => ({ key, value })))
setLitellmBaseUrl(claudeEnvVars['ANTHROPIC_BASE_URL'] ?? '')
setLitellmAuthToken(claudeEnvVars['ANTHROPIC_AUTH_TOKEN'] ?? '')
}, [claudeEnvVars])
const updateRepoConfig = useCallback(
async (repoRoot: string, patch: Record<string, unknown>) => {
// Main dispatches repoConfigs/changed after saveRepoConfig commits;
// useRepoConfigs() re-renders us automatically.
await backend.setRepoConfig(repoRoot, patch)
},
[]
)
const repoBasename = useCallback((repoRoot: string): string => {
const parts = repoRoot.split('/').filter(Boolean)
return parts[parts.length - 1] || repoRoot
}, [])
const [setupDraft, setSetupDraft] = useState<string>('')
const [teardownDraft, setTeardownDraft] = useState<string>('')
// Editable draft for the Claude command input. Hydrated from the store and
// re-synced whenever the store value changes (e.g. another window edited it).
// The `Save` button commits the draft via the setter IPC.
const [claudeCommandDraft, setClaudeCommandDraft] = useState<string>(claudeCommand)
useEffect(() => {
setClaudeCommandDraft(claudeCommand)
}, [claudeCommand])
const handleSelectThemeMode = useCallback((mode: 'light' | 'dark' | 'system') => {
void backend.setThemeMode(mode)
}, [backend])
const handleSelectLightTheme = useCallback((id: string) => {
void backend.setThemeLight(id)
}, [backend])
const handleSelectDarkTheme = useCallback((id: string) => {
void backend.setThemeDark(id)
}, [backend])
const handleTerminalFontFamilyChange = useCallback((value: string) => {
void backend.setTerminalFontFamily(value)
}, [])
const handleResetTerminalFontFamily = useCallback(() => {
void backend.setTerminalFontFamily(defaultTerminalFontFamily)
}, [defaultTerminalFontFamily])
const handleTerminalFontSizeChange = useCallback((value: number) => {
if (!Number.isFinite(value)) return
const clamped = Math.max(8, Math.min(48, Math.round(value)))
void backend.setTerminalFontSize(clamped)
}, [])
const [autoSleepDraft, setAutoSleepDraft] = useState<string>(
String(autoSleepMinutes)
)
useEffect(() => {
setAutoSleepDraft(String(autoSleepMinutes))
}, [autoSleepMinutes])
const commitAutoSleepMinutes = useCallback(() => {
const n = Number(autoSleepDraft)
if (!Number.isFinite(n) || n < 0) {
setAutoSleepDraft(String(autoSleepMinutes))
return
}
const clamped = Math.max(0, Math.min(24 * 60, Math.floor(n)))
if (clamped !== autoSleepMinutes) {
void backend.setAutoSleepMinutes(clamped)
} else {
setAutoSleepDraft(String(clamped))
}
}, [autoSleepDraft, autoSleepMinutes])
const handleSelectEditor = useCallback(async (id: string) => {
await backend.setEditor(id)
}, [])
const handleSelectWorktreeBase = useCallback(async (mode: 'remote' | 'local') => {
await backend.setWorktreeBase(mode)
}, [])
const handleSelectMergeStrategy = useCallback(
async (strategy: MergeStrategy) => {
if (scopeRepoRoot) {
await updateRepoConfig(scopeRepoRoot, { mergeStrategy: strategy })
} else {
await backend.setMergeStrategy(strategy)
}
},
[scopeRepoRoot, updateRepoConfig]
)
// Resolve what each control should display for the active scope.
const scopedRepoCfg = scopeRepoRoot ? repoConfigs[scopeRepoRoot] || {} : null
const displayedMergeStrategy: MergeStrategy = scopedRepoCfg
? (scopedRepoCfg.mergeStrategy || mergeStrategy)
: mergeStrategy
const scopedMergeStrategyIsOverride = !!(scopedRepoCfg && scopedRepoCfg.mergeStrategy)
const displayedSetupScript = scopedRepoCfg
? (scopedRepoCfg.setupCommand ?? '')
: setupScript
const displayedTeardownScript = scopedRepoCfg
? (scopedRepoCfg.teardownCommand ?? '')
: teardownScript
const scopedSetupIsOverride = !!(scopedRepoCfg && scopedRepoCfg.setupCommand)
const scopedTeardownIsOverride = !!(scopedRepoCfg && scopedRepoCfg.teardownCommand)
// Reset the scoped script drafts whenever the active scope (or persisted
// value for that scope) changes, so the textareas show what's on disk.
useEffect(() => {
setSetupDraft(displayedSetupScript)
setTeardownDraft(displayedTeardownScript)
}, [scopeRepoRoot, displayedSetupScript, displayedTeardownScript])
const handleSaveWorktreeScripts = useCallback(async () => {
if (scopeRepoRoot) {
await updateRepoConfig(scopeRepoRoot, {
setupCommand: setupDraft.trim() || null,
teardownCommand: teardownDraft.trim() || null
})
} else {
await backend.setWorktreeScripts({ setup: setupDraft, teardown: teardownDraft })
}
setScriptsSaveResult({ ok: true, message: 'Saved' })
setTimeout(() => setScriptsSaveResult(null), 2000)
}, [scopeRepoRoot, setupDraft, teardownDraft, updateRepoConfig])
const handleResetSetupToGlobal = useCallback(async () => {
if (!scopeRepoRoot) return
await updateRepoConfig(scopeRepoRoot, { setupCommand: null })
setSetupDraft('')
}, [scopeRepoRoot, updateRepoConfig])
const handleResetTeardownToGlobal = useCallback(async () => {
if (!scopeRepoRoot) return
await updateRepoConfig(scopeRepoRoot, { teardownCommand: null })
setTeardownDraft('')
}, [scopeRepoRoot, updateRepoConfig])
const handleResetMergeStrategyToGlobal = useCallback(async () => {
if (!scopeRepoRoot) return
await updateRepoConfig(scopeRepoRoot, { mergeStrategy: null })
}, [scopeRepoRoot, updateRepoConfig])
// Repos that override a given key — used to decorate global-scope controls
// with a "Overridden in N repo(s)" badge.
const reposOverridingKey = useCallback(
(key: keyof RepoConfig): string[] => {
return repoList.filter((r) => {
const cfg = repoConfigs[r]
if (!cfg) return false
const v = cfg[key]
return typeof v === 'string' ? v.length > 0 : v != null
})
},
[repoList, repoConfigs]
)
const handleSave = useCallback(async () => {
setSaving(true)
setTokenResult(null)
try {
const res = await backend.setGithubToken(token)
if (res.ok) {
const message = res.username ? `Connected as @${res.username}` : 'Token saved'
setTokenResult({ ok: true, message })
setToken('')
} else {
setTokenResult({ ok: false, message: `Invalid token: ${res.error || 'unknown error'}` })
}
} finally {
setSaving(false)
}
}, [token])
const handleClear = useCallback(async () => {
await backend.clearGithubToken()
setTokenResult({ ok: true, message: 'Token removed' })
}, [])
const handleCheckForUpdates = useCallback(async () => {
setChecking(true)
try {
// Main dispatches the resulting updater/statusChanged event itself —
// we just await the call so we know when to clear the spinner.
await backend.checkForUpdates()
} finally {
setChecking(false)
}
}, [])
const handleRestart = useCallback(() => {
backend.quitAndInstall()
}, [])
// Capture a key press while rebinding
useEffect(() => {
if (!rebindingAction) return
const handler = (e: KeyboardEvent): void => {
e.preventDefault()
e.stopPropagation()
if (e.key === 'Escape') {
setRebindingAction(null)
return
}
const binding = eventToBinding(e)
if (!binding) return // ignore pure modifier presses
const shortcut = bindingToString(binding)
const next = { ...(hotkeyOverrides || {}), [rebindingAction]: shortcut }
void backend.setHotkeyOverrides(next)
setRebindingAction(null)
}
window.addEventListener('keydown', handler, true)
return () => window.removeEventListener('keydown', handler, true)
}, [rebindingAction, hotkeyOverrides])
useEffect(() => {
const handler = (e: KeyboardEvent): void => {
if (e.key !== 'Escape') return
if (e.defaultPrevented) return
onClose()
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [onClose])
const resolvedHotkeys = resolveHotkeys(hotkeyOverrides || undefined)
const handleResetHotkey = useCallback(async (action: Action) => {
const next = { ...(hotkeyOverrides || {}) }
delete next[action]
await backend.setHotkeyOverrides(next)
}, [hotkeyOverrides])
const handleResetAllHotkeys = useCallback(async () => {
await backend.resetHotkeyOverrides()
}, [])
const handleSaveClaudeCommand = useCallback(async () => {
setClaudeSaveResult(null)
await backend.setClaudeCommand(claudeCommandDraft)
setClaudeSaveResult({ ok: true, message: 'Saved · new tabs will use this command' })
}, [claudeCommandDraft])
const handleToggleHarnessMcp = useCallback(async (enabled: boolean) => {
await backend.setHarnessMcpEnabled(enabled)
}, [])
const handleToggleAutoApprovePermissions = useCallback(async (enabled: boolean) => {
await backend.setAutoApprovePermissions(enabled)
}, [])
const [autoApproveSteerDraft, setAutoApproveSteerDraft] = useState<string>(autoApproveSteerInstructions)
useEffect(() => {
setAutoApproveSteerDraft(autoApproveSteerInstructions)
}, [autoApproveSteerInstructions])
const [autoApproveSteerSaveResult, setAutoApproveSteerSaveResult] = useState<
{ ok: boolean; message: string } | null
>(null)
const handleSaveAutoApproveSteer = useCallback(async () => {
setAutoApproveSteerSaveResult(null)
await backend.setAutoApproveSteerInstructions(autoApproveSteerDraft)
setAutoApproveSteerSaveResult({ ok: true, message: 'Saved · used on next auto-review' })
}, [autoApproveSteerDraft])
const handleToggleAutoUpdate = useCallback(async (enabled: boolean) => {
await backend.setAutoUpdateEnabled(enabled)
}, [])
const handleToggleWsTransport = useCallback(async (enabled: boolean) => {
await backend.setWsTransportEnabled(enabled)
}, [])
const handleSaveWsPort = useCallback(async () => {
const parsed = Number.parseInt(wsPortDraft, 10)
if (!Number.isFinite(parsed)) return
await backend.setWsTransportPort(parsed)
}, [wsPortDraft])
const handleSelectWsHost = useCallback(async (host: string) => {
await backend.setWsTransportHost(host)
}, [])
// Build the display URL from the live server when it's running; fall back
// to the configured host/port (with a blank token) so the user can see
// roughly what the URL *will* be after restart.
const effectiveWsHost = wsInfo?.host ?? wsTransportHost
const effectiveWsPort = wsInfo?.port ?? wsTransportPort
const effectiveWsToken = wsInfo?.token ?? ''
const wsUrl = `http://${effectiveWsHost}:${effectiveWsPort}/?token=${effectiveWsToken}`
const wsUrlMasked = `http://${effectiveWsHost}:${effectiveWsPort}/?token=${'•'.repeat(8)}`
// URL aimed at a phone/other device: substitutes the machine's actual
// LAN IP for 0.0.0.0 so scanning the QR actually resolves. Only usable
// once the server is running (needs the real token).
const scannableLanUrl = selectedLanAddress && wsInfo
? `http://${selectedLanAddress}:${wsInfo.port}/?token=${wsInfo.token}`
: null
const handleCopyWsUrl = useCallback(async () => {
try {
await navigator.clipboard.writeText(wsUrl)
setWsUrlCopied(true)
setTimeout(() => setWsUrlCopied(false), 1500)
} catch {
// clipboard writes can reject when the window isn't focused
}
}, [wsUrl])
const handleOpenWsUrl = useCallback(() => {
backend.openExternal(wsUrl)
}, [wsUrl])
// The WS server is only constructed at app launch, so any divergence
// between config and the live wsInfo surfaces as "relaunch required".
const wsNeedsRestart = ((): string | null => {
if (wsTransportEnabled && !wsInfo) return 'Quit and relaunch Harness to start the server.'
if (!wsTransportEnabled && wsInfo) return 'Server is still running — quit and relaunch Harness to stop it.'
if (wsInfo && wsTransportEnabled) {
if (wsInfo.port !== wsTransportPort) return `Quit and relaunch Harness to switch to port ${wsTransportPort}.`
if (wsInfo.host !== wsTransportHost) return 'Quit and relaunch Harness to rebind the server.'
if (wsTokenRotated) return 'Token rotated — quit and relaunch Harness. Any pinned/bookmarked URLs will need to be replaced.'
}
return null
})()
const handleRotateWsToken = useCallback(async () => {
const ok = window.confirm(
'Rotate the web-client auth token?\n\nAll existing URLs — bookmarks, home-screen pins, open browser tabs — will stop working after you quit and relaunch Harness. You will need to re-share the new URL with any device you want to reconnect.'
)
if (!ok) return
await backend.rotateWsToken()
setWsTokenRotated(true)
}, [])
const handleSaveSystemPrompt = useCallback(async () => {
await backend.setHarnessSystemPrompt(systemPromptDraft)
await backend.setHarnessSystemPromptMain(systemPromptMainDraft)
setSystemPromptSaveResult({ ok: true, message: 'Saved · new sessions will use this prompt' })
setTimeout(() => setSystemPromptSaveResult(null), 2000)
}, [systemPromptDraft, systemPromptMainDraft])
const handleResetSystemPrompt = useCallback(async () => {
await backend.setHarnessSystemPrompt('')
await backend.setHarnessSystemPromptMain('')
setSystemPromptSaveResult({ ok: true, message: 'Reset to defaults' })
setTimeout(() => setSystemPromptSaveResult(null), 2000)
}, [])
const handleSavePrReviewPrompt = useCallback(async () => {
await backend.setPrReviewPrompt(prReviewPromptDraft)
setPrReviewPromptSaveResult({ ok: true, message: 'Saved' })
setTimeout(() => setPrReviewPromptSaveResult(null), 2000)
}, [prReviewPromptDraft])
const handleResetPrReviewPrompt = useCallback(async () => {
await backend.setPrReviewPrompt('')
setPrReviewPromptSaveResult({ ok: true, message: 'Reset to default' })
setTimeout(() => setPrReviewPromptSaveResult(null), 2000)
}, [])
const effectiveClaudeCommand = claudeCommandDraft.trim() || defaultClaudeCommand
const modelPart = claudeModel && !effectiveClaudeCommand.includes('--model') ? ` --model ${claudeModel}` : ''
const mcpPart = harnessMcpEnabled ? ' --mcp-config <per-session>' : ''
const previewInner = `${effectiveClaudeCommand}${modelPart}${mcpPart} --session-id <uuid>`
const commandPreview = `<shell> -ilc "${previewInner}"`
const handleResetClaudeCommand = useCallback(async () => {
setClaudeCommandDraft(defaultClaudeCommand)
await backend.setClaudeCommand(defaultClaudeCommand)
setClaudeSaveResult({ ok: true, message: 'Reset to default' })
}, [defaultClaudeCommand])
const handleAddEnvRow = useCallback(() => {
setClaudeEnvRows((prev) => [...prev, { key: '', value: '' }])
setEnvSaveResult(null)
}, [])
const handleRemoveEnvRow = useCallback((index: number) => {
setClaudeEnvRows((prev) => prev.filter((_, i) => i !== index))
setRevealedEnvRows((prev) => {
const next = new Set<number>()
prev.forEach((i) => { if (i < index) next.add(i); else if (i > index) next.add(i - 1) })
return next
})
setEnvSaveResult(null)
}, [])
const handleUpdateEnvRow = useCallback((index: number, field: 'key' | 'value', value: string) => {
setClaudeEnvRows((prev) => prev.map((row, i) => (i === index ? { ...row, [field]: value } : row)))
setEnvSaveResult(null)
}, [])
const handleToggleRevealEnvRow = useCallback((index: number) => {
setRevealedEnvRows((prev) => {
const next = new Set(prev)
if (next.has(index)) next.delete(index); else next.add(index)
return next
})
}, [])
const handleSaveClaudeEnvVars = useCallback(async () => {
const vars: Record<string, string> = {}
const seen = new Set<string>()
const invalidNames: string[] = []
const duplicates: string[] = []
for (const { key, value } of claudeEnvRows) {
const k = key.trim()
if (!k) continue
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {
invalidNames.push(k)
continue
}
if (seen.has(k)) {
duplicates.push(k)
continue
}
seen.add(k)
vars[k] = value
}
if (invalidNames.length > 0) {
setEnvSaveResult({ ok: false, message: `Invalid name(s): ${invalidNames.join(', ')}` })
return
}
if (duplicates.length > 0) {
setEnvSaveResult({ ok: false, message: `Duplicate name(s): ${duplicates.join(', ')}` })
return
}
await backend.setClaudeEnvVars(vars)
setEnvSaveResult({ ok: true, message: 'Saved · new Claude tabs will see these' })
}, [claudeEnvRows])
const handleSaveLitellm = useCallback(async () => {
const url = litellmBaseUrl.trim()
const token = litellmAuthToken.trim()
if (!url) {
setLitellmSaveResult({ ok: false, message: 'Base URL is required' })
return
}
const filtered = claudeEnvRows.filter(({ key }) => {
const k = key.trim()
return k !== 'ANTHROPIC_BASE_URL' && k !== 'ANTHROPIC_AUTH_TOKEN'
})
const newRows: { key: string; value: string }[] = [
...filtered,
{ key: 'ANTHROPIC_BASE_URL', value: url }
]
if (token) newRows.push({ key: 'ANTHROPIC_AUTH_TOKEN', value: token })
setClaudeEnvRows(newRows)
const vars: Record<string, string> = {}
const seen = new Set<string>()
for (const { key, value } of newRows) {
const k = key.trim()
if (!k || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || seen.has(k)) continue
seen.add(k)
vars[k] = value
}
await backend.setClaudeEnvVars(vars)
setLitellmSaveResult({ ok: true, message: 'Saved · new Claude tabs will use this endpoint' })
setEnvSaveResult(null)
}, [litellmBaseUrl, litellmAuthToken, claudeEnvRows])
const handleClearLitellm = useCallback(async () => {
setLitellmBaseUrl('')
setLitellmAuthToken('')
const newRows = claudeEnvRows.filter(({ key }) => {
const k = key.trim()
return k !== 'ANTHROPIC_BASE_URL' && k !== 'ANTHROPIC_AUTH_TOKEN'
})
setClaudeEnvRows(newRows)
const vars: Record<string, string> = {}
const seen = new Set<string>()
for (const { key, value } of newRows) {
const k = key.trim()
if (!k || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || seen.has(k)) continue
seen.add(k)
vars[k] = value
}
await backend.setClaudeEnvVars(vars)
setLitellmSaveResult({ ok: true, message: 'Cleared' })
setEnvSaveResult(null)
}, [claudeEnvRows])
const handleSaveCodexCommand = useCallback(async () => {
setCodexSaveResult(null)
await backend.setCodexCommand(codexCommandDraft)
setCodexSaveResult({ ok: true, message: 'Saved · new tabs will use this command' })
}, [codexCommandDraft])
const handleResetCodexCommand = useCallback(async () => {
setCodexCommandDraft('codex')
await backend.setCodexCommand('codex')
setCodexSaveResult({ ok: true, message: 'Reset to default' })
}, [])
const handleSaveCodexEnvVars = useCallback(async () => {
const vars: Record<string, string> = {}
const seen = new Set<string>()
const invalidNames: string[] = []
const duplicates: string[] = []
for (const { key, value } of codexEnvRows) {
const k = key.trim()
if (!k) continue
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) { invalidNames.push(k); continue }
if (seen.has(k)) { duplicates.push(k); continue }
seen.add(k)
vars[k] = value
}
if (invalidNames.length > 0) { setCodexEnvSaveResult({ ok: false, message: `Invalid name(s): ${invalidNames.join(', ')}` }); return }
if (duplicates.length > 0) { setCodexEnvSaveResult({ ok: false, message: `Duplicate name(s): ${duplicates.join(', ')}` }); return }
await backend.setCodexEnvVars(vars)
setCodexEnvSaveResult({ ok: true, message: 'Saved · new Codex tabs will see these' })
}, [codexEnvRows])
const isOverridden = (action: Action): boolean => {
if (!hotkeyOverrides || !(action in hotkeyOverrides)) return false
const defaultStr = bindingToString(DEFAULT_HOTKEYS[action])
return hotkeyOverrides[action] !== defaultStr
}
const renderUpdaterStatus = (): JSX.Element | null => {
if (!updaterStatus) return null
switch (updaterStatus.state) {
case 'checking':
return (
<div className="flex items-center gap-2 text-xs text-muted">
<RefreshCw size={12} className="animate-spin" />
Checking for updates...
</div>
)
case 'not-available':
return (
<div className="flex items-center gap-2 text-xs text-success">
<Check size={12} />
You're up to date
</div>
)
case 'available':
return (
<div className="flex items-center gap-2 text-xs text-warning">
<Download size={12} />
<span>
<a
onClick={() => backend.openExternal(harnessReleaseNotesUrl(updaterStatus.version))}
className="underline hover:text-fg-bright cursor-pointer"
>
Harness {updaterStatus.version}
</a>{' '}
available — downloading...
</span>
</div>
)
case 'downloading':
return (
<div className="flex items-center gap-2 text-xs text-warning">
<Download size={12} />
<span>
Downloading{' '}
<a
onClick={() => backend.openExternal(harnessReleaseNotesUrl(updaterStatus.version))}
className="underline hover:text-fg-bright cursor-pointer"
>
Harness {updaterStatus.version}
</a>
... {Math.round(updaterStatus.percent)}%
</span>
</div>
)
case 'downloaded':
return (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 text-xs text-success">
<Check size={12} />
<span>
<a
onClick={() => backend.openExternal(harnessReleaseNotesUrl(updaterStatus.version))}
className="underline hover:text-fg-bright cursor-pointer"
>
Harness {updaterStatus.version}
</a>{' '}
ready to install
</span>
</div>
<button
onClick={handleRestart}
className="self-start flex items-center gap-1.5 px-3 py-1.5 bg-success/20 hover:bg-success/30 rounded text-xs text-success transition-colors cursor-pointer"
>
<RotateCw size={12} />
Restart & install
</button>
</div>
)
case 'error':
return (
<div className="flex items-center gap-2 text-xs text-danger">
<X size={12} />
{updaterStatus.error}
</div>
)
}
}
return (
<div className="flex flex-col h-full bg-panel">
{/* Title bar (drag region) */}
<div className="drag-region h-10 shrink-0 border-b border-border relative">
<button
onClick={onClose}
className="no-drag absolute left-20 top-1/2 -translate-y-1/2 flex items-center gap-1.5 text-xs text-muted hover:text-fg-bright transition-colors cursor-pointer"
>
<ArrowLeft size={14} />
Back
<kbd className="text-[10px] text-faint bg-bg px-1.5 py-0.5 rounded border border-border font-mono">ESC</kbd>
</button>
<span className="absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2 text-sm font-medium text-fg pointer-events-none">
Settings
</span>
</div>
<div className="flex flex-1 min-h-0">
{/* Left sidebar */}
<div className="w-56 border-r border-border bg-panel flex flex-col shrink-0">
<div className="px-3 py-2">
<span className="text-xs font-medium text-dim">SECTIONS</span>
</div>
{SECTIONS.map((section) => {
const Icon = section.icon
const isActive = activeSection === section.id
const needsAttention = section.id === 'github' && !hasToken && authSource !== 'gh-cli'
const className = needsAttention
? `flex items-center gap-2 px-3 py-2 text-left text-sm transition-colors cursor-pointer ${
isActive ? 'bg-info/25 text-info' : 'bg-info/10 text-info hover:bg-info/20'
}`
: `flex items-center gap-2 px-3 py-2 text-left text-sm transition-colors cursor-pointer ${
isActive
? 'bg-surface text-fg-bright'
: 'text-muted hover:bg-panel-raised hover:text-fg-bright'
}`
return (
<div key={section.id}>
<button
onClick={() => scrollToSection(section.id)}
className={`w-full ${className}`}
>
<Icon size={14} className="shrink-0" />
<span>{section.label}</span>
</button>
{section.children && (
<div
className="overflow-hidden transition-all duration-200"
style={{
maxHeight: isActive ? `${section.children.length * 36}px` : '0px',
opacity: isActive ? 1 : 0
}}
>
{section.children.map((child) => {
const isSubActive = activeSubSection === child.id
return (
<button
key={child.id}
onClick={() => scrollToSubSection(child.id)}
className={`w-full pl-9 pr-3 py-1.5 text-left text-xs transition-colors cursor-pointer ${
isSubActive
? 'text-fg-bright bg-surface/60'
: 'text-muted hover:text-fg-bright hover:bg-panel-raised'
}`}
>
{child.label}
</button>
)
})}
</div>
)}
</div>