-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpage.tsx
More file actions
1087 lines (1027 loc) · 43.1 KB
/
page.tsx
File metadata and controls
1087 lines (1027 loc) · 43.1 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
'use client'
import { useEffect, useState, useCallback, useRef, useLayoutEffect, useMemo } from 'react'
import dynamic from 'next/dynamic'
import { motion, AnimatePresence } from 'framer-motion'
import { Icon } from '@iconify/react'
import { useGateway } from '@/context/gateway-context'
import { useRepo } from '@/context/repo-context'
import { useEditor, detectFileKind, getMimeType } from '@/context/editor-context'
import { useLocal } from '@/context/local-context'
import { useView, type ViewId } from '@/context/view-context'
import { useLayout, usePanelResize } from '@/context/layout-context'
import { useAppMode } from '@/context/app-mode-context'
import { WorkspaceSidebar } from '@/components/workspace-sidebar'
import { FloatingPanel } from '@/components/floating-panel'
import { EditorTabs } from '@/components/editor-tabs'
import { formatShortcut } from '@/lib/platform'
import { isTauri } from '@/lib/tauri'
import {
fetchFileContentsByName as fetchFileContents,
commitFilesByName as commitFiles,
} from '@/lib/github-api'
import { usePlugins } from '@/context/plugin-context'
import { SpotifyPlugin } from '@/components/plugins/spotify/spotify-plugin'
import { YouTubePlugin } from '@/components/plugins/youtube/youtube-plugin'
import { isOnboardingComplete } from '@/components/onboarding-tour'
import { PreviewProvider } from '@/context/preview-context'
import { ViewRouter } from '@/components/view-router'
import { StatusBar } from '@/components/status-bar'
import { useKeyboardShortcuts } from '@/components/keyboard-handler'
import { emit, on } from '@/lib/events'
import { KnotLogo } from '@/components/knot-logo'
import type { AppMode } from '@/lib/mode-registry'
import { openNewEditorInstance } from '@/lib/tauri'
const GitSidebarPanel = dynamic(
() => import('@/components/git-sidebar-panel').then((m) => m.GitSidebarPanel),
{ ssr: false },
)
// Overlay modals — lazy loaded
const QuickOpen = dynamic(() => import('@/components/quick-open').then((m) => m.QuickOpen), {
ssr: false,
})
const GlobalSearch = dynamic(
() => import('@/components/global-search').then((m) => m.GlobalSearch),
{ ssr: false },
)
const CommandPalette = dynamic(
() => import('@/components/command-palette').then((m) => m.CommandPalette),
{ ssr: false },
)
const ShortcutsOverlay = dynamic(
() => import('@/components/shortcuts-overlay').then((m) => m.ShortcutsOverlay),
{ ssr: false },
)
const TerminalPanel = dynamic(
() => import('@/components/terminal-panel').then((m) => m.TerminalPanel),
{ ssr: false },
)
const GatewayTerminalLazy = dynamic(
() => import('@/components/gateway-terminal').then((m) => m.GatewayTerminal),
{ ssr: false },
)
const PipWindow = dynamic(
() => import('@/components/preview/pip-window').then((m) => m.PipWindow),
{ ssr: false },
)
const WidgetPipWindow = dynamic(
() => import('@/components/plugins/widget-pip-window').then((m) => m.WidgetPipWindow),
{ ssr: false },
)
const SettingsPanel = dynamic(
() => import('@/components/settings-panel').then((m) => m.SettingsPanel),
{ ssr: false },
)
const OnboardingTour = dynamic(
() => import('@/components/onboarding-tour').then((m) => m.OnboardingTour),
{ ssr: false },
)
const PluginSlotRenderer = dynamic(
() => import('@/context/plugin-context').then((m) => m.PluginSlotRenderer),
{ ssr: false },
)
const VIEW_ICONS: Record<string, { icon: string; label: string }> = {
chat: { icon: 'lucide:message-square', label: 'Chat' },
editor: { icon: 'lucide:code-2', label: 'Editor' },
preview: { icon: 'lucide:eye', label: 'Preview' },
diff: { icon: 'lucide:git-compare', label: 'Diff' },
git: { icon: 'lucide:git-branch', label: 'Git' },
skills: { icon: 'lucide:sparkles', label: 'Skills' },
settings: { icon: 'lucide:settings', label: 'Settings' },
terminal: { icon: 'lucide:terminal', label: 'Terminal' },
}
const MODE_BUTTONS: Array<{ id: AppMode; icon: string; label: string }> = [
{ id: 'classic', icon: 'lucide:code-2', label: 'Classic' },
{ id: 'chat', icon: 'lucide:message-square', label: 'Chat' },
{ id: 'tui', icon: 'lucide:terminal', label: 'TUI' },
]
const TERMINAL_SPRING = { type: 'spring' as const, stiffness: 500, damping: 35 }
export default function EditorLayout() {
const { status } = useGateway()
const { repo, setRepo } = useRepo()
const local = useLocal()
const { files, activeFile, openFile, setActiveFile, markClean, updateFileContent } = useEditor()
const {
localMode,
readFile: localReadFile,
readFileBase64: localReadFileBase64,
writeFile: localWriteFile,
rootPath: localRootPath,
gitInfo,
openFolder: localOpenFolder,
setRootPath: localSetRootPath,
commitFiles: localCommitFiles,
} = local
const { activeView, setView, direction } = useView()
const { mode, spec: modeSpec, setMode } = useAppMode()
const layout = useLayout()
const visibleViews = modeSpec.visibleViews
const isMobile = layout.isAtMost('lte768')
const [keyboardOffset, setKeyboardOffset] = useState(0)
const sidebarCollapsed = !layout.isVisible('sidebar')
const terminalVisible = layout.isVisible('terminal')
const terminalHeight = layout.getSize('terminal')
const terminalFloating = layout.isFloating('terminal')
const viewportHeight = layout.viewport.height
const terminalRefreshToken = mode
const useCenteredTerminal = modeSpec.terminalCenter && activeView === 'editor'
const terminalStartupCommand = useCenteredTerminal ? 'openclaw tui' : undefined
const mobileViewTabs = useMemo(() => {
// On mobile, curate tabs to useful views + always include settings
const mobile = visibleViews.filter((v) => !['preview', 'diff', 'skills'].includes(v))
if (!mobile.includes('terminal')) mobile.push('terminal')
return mobile.slice(0, 5)
}, [visibleViews])
const activeViewMeta = VIEW_ICONS[activeView] ?? {
icon: 'lucide:layout-panel-top',
label: 'Workspace',
}
const workspaceLabel = useMemo(
() => repo?.fullName?.split('/').pop() ?? localRootPath?.split('/').pop() ?? 'KnotCode',
[repo?.fullName, localRootPath],
)
const showMobileBottomTabs = isMobile && !modeSpec.terminalCenter && keyboardOffset === 0
const showMobileSidebarButton = isMobile && mode !== 'tui'
const showWorkflowEditorTabs = false
const mobileTerminalOffset = showMobileBottomTabs
? 'calc(env(safe-area-inset-bottom) + 5.75rem)'
: 'calc(env(safe-area-inset-bottom) + 0.5rem)'
// ─── Minimal state ──────────────────────────────────
const [isTauriDesktop, setIsTauriDesktop] = useState(false)
const [isMacTauri, setIsMacTauri] = useState(false)
const [flashedTab, setFlashedTab] = useState<ViewId | null>(null)
const [connectionAnim, setConnectionAnim] = useState<'pop' | 'pulse' | null>(null)
const prevStatusRef = useRef(status)
const tabRefs = useRef<(HTMLButtonElement | null)[]>([])
const tabContainerRef = useRef<HTMLDivElement>(null)
const [indicatorStyle, setIndicatorStyle] = useState<{ left: number; width: number }>({
left: 0,
width: 0,
})
const [agentActive, setAgentActive] = useState(false)
// Overlay modals
const [quickOpenVisible, setQuickOpenVisible] = useState(false)
const [globalSearchVisible, setGlobalSearchVisible] = useState(false)
const [commandPaletteVisible, setCommandPaletteVisible] = useState(false)
const [shortcutsVisible, setShortcutsVisible] = useState(false)
const [settingsVisible, setSettingsVisible] = useState(false)
const [settingsTab, setSettingsTab] = useState<
'general' | 'editor' | 'agent' | 'keybindings' | 'plugins' | undefined
>(undefined)
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
const [onboardingOpen, setOnboardingOpen] = useState(false)
const dirtyCount = useMemo(() => files.filter((f) => f.dirty).length, [files])
const ensureTuiTerminalVisible = useCallback(() => {
layout.setFloating('terminal', false)
layout.show('terminal')
}, [layout])
// Entering TUI should always surface the terminal view.
useEffect(() => {
if (!useCenteredTerminal) return
ensureTuiTerminalVisible()
}, [useCenteredTerminal, ensureTuiTerminalVisible])
// ─── Tauri detection ───────────────────────────────────
useEffect(() => {
setIsTauriDesktop(isTauri())
setIsMacTauri(isTauri() && navigator.platform?.includes('Mac'))
}, [])
useEffect(() => {
if (!isMobile || mode === 'tui') {
setMobileSidebarOpen(false)
}
}, [isMobile, mode])
// ─── iOS keyboard: shrink layout when virtual keyboard opens ───
useEffect(() => {
if (!isMobile) return
const vv = window.visualViewport
if (!vv) return
const onResize = () => {
const offset = window.innerHeight - vv.height
setKeyboardOffset(offset > 50 ? offset : 0) // only respond to real keyboard
}
vv.addEventListener('resize', onResize)
return () => vv.removeEventListener('resize', onResize)
}, [isMobile])
// ─── Onboarding ────────────────────────────────────────
useEffect(() => {
if (typeof window === 'undefined') return
if (!isOnboardingComplete()) setOnboardingOpen(true)
return on('open-onboarding' as keyof import('@/lib/events').AppEvents, () =>
setOnboardingOpen(true),
)
}, [])
// ─── Auto-populate RepoContext from local git remote ───
useEffect(() => {
if (local.remoteRepo && local.gitInfo?.branch) {
const [owner, repoName] = local.remoteRepo.split('/')
if (owner && repoName) {
if (repo?.fullName !== local.remoteRepo || repo?.branch !== local.gitInfo.branch) {
setRepo({
owner,
repo: repoName,
branch: local.gitInfo.branch,
fullName: local.remoteRepo,
})
}
}
}
}, [local.remoteRepo, local.gitInfo?.branch]) // eslint-disable-line react-hooks/exhaustive-deps
// ─── Sliding tab indicator measurement ─────────────────
useLayoutEffect(() => {
const idx = visibleViews.indexOf(activeView)
const tab = tabRefs.current[idx]
const container = tabContainerRef.current
if (tab && container) {
const cRect = container.getBoundingClientRect()
const tRect = tab.getBoundingClientRect()
setIndicatorStyle({ left: tRect.left - cRect.left, width: tRect.width })
}
}, [activeView, sidebarCollapsed, visibleViews])
// ─── Connection state transitions ─────────────────────
useEffect(() => {
const prev = prevStatusRef.current
prevStatusRef.current = status
if (status === 'connected' && prev !== 'connected') {
setConnectionAnim('pop')
const t = setTimeout(() => setConnectionAnim(null), 600)
return () => clearTimeout(t)
}
}, [status])
// ─── Agent activity detection ─────────────────────────
useEffect(() => {
return on('engine-status', (detail) => {
setAgentActive(detail?.running ?? false)
})
}, [])
// ─── Save file handler ─────────────────────────────────
const saveFile = useCallback(
async (path: string) => {
const file = files.find((f) => f.path === path)
if (!file || !file.dirty) return
if (localMode && localWriteFile && localRootPath) {
try {
await localWriteFile(path, file.content)
markClean(path)
return
} catch (err) {
console.error('Failed to save file:', path, err)
}
}
if (repo) {
try {
await commitFiles(
repo.fullName,
[{ path: file.path, content: file.content, sha: file.sha }],
`Update ${path.split('/').pop()}`,
repo.branch,
)
markClean(path)
} catch (err) {
console.error('Failed to save file to GitHub:', path, err)
}
}
},
[files, localMode, localRootPath, localWriteFile, markClean, repo],
)
// ─── Keyboard shortcuts ────────────────────────────────
useKeyboardShortcuts({
onQuickOpen: () => setQuickOpenVisible((v) => !v),
onCommandPalette: () => setCommandPaletteVisible((v) => !v),
onGlobalSearch: () => setGlobalSearchVisible((v) => !v),
onNewWindow: () => {
openNewEditorInstance().catch((err) => console.error('Failed to open new window:', err))
},
onFlashTab: (v) => {
setFlashedTab(v)
setTimeout(() => setFlashedTab(null), 400)
},
saveFile,
})
// ─── Event listeners ───────────────────────────────────
useEffect(() => {
const unsubs = [
on('open-settings', () => {
setSettingsTab(undefined)
setSettingsVisible(true)
}),
on('open-agent-settings', () => {
setSettingsTab('agent')
setSettingsVisible(true)
}),
on('open-folder', () => localOpenFolder()),
on('open-recent', (detail) => {
if (detail.path) localSetRootPath(detail.path)
}),
]
return () => unsubs.forEach((u) => u())
}, [localOpenFolder, localSetRootPath])
// ─── File open handler ─────────────────────────────────
useEffect(() => {
return on('file-select', async (detail) => {
const { path, sha, content: providedContent } = detail ?? {}
if (!path) return
const revealEditorFromChat = () => {
if (activeView === 'chat') {
layout.show('chat')
}
setView('editor')
}
const existing = files.find((f) => f.path === path)
if (existing) {
setActiveFile(path)
revealEditorFromChat()
return
}
if (providedContent != null) {
openFile(path, providedContent, sha ?? '')
revealEditorFromChat()
return
}
const fileKind = detectFileKind(path)
const isBinary = fileKind !== 'text'
if (localMode && localReadFile && localRootPath) {
try {
if (isBinary && localReadFileBase64) {
const base64 = await localReadFileBase64(path)
const mime = getMimeType(path)
const dataUrl = `data:${mime};base64,${base64}`
openFile(path, dataUrl, '', { kind: fileKind, mimeType: mime })
} else {
const content = await localReadFile(path)
openFile(path, content, '')
}
revealEditorFromChat()
return
} catch (err) {
console.error('Failed to read local file:', path, err)
}
}
if (repo) {
try {
const result = await fetchFileContents(repo.fullName, path, repo.branch)
if (isBinary && result.rawBase64) {
const mime = getMimeType(path)
const dataUrl = `data:${mime};base64,${result.rawBase64}`
openFile(path, dataUrl, result.sha ?? sha ?? '', { kind: fileKind, mimeType: mime })
} else {
openFile(path, result.content, result.sha ?? sha ?? '')
}
revealEditorFromChat()
} catch (err) {
console.error('Failed to open file:', path, err)
}
}
})
}, [
repo,
files,
openFile,
setActiveFile,
setView,
activeView,
layout,
localMode,
localRootPath,
localReadFile,
localReadFileBase64,
])
// ─── Commit handler ────────────────────────────────────
useEffect(() => {
return on('agent-commit', async (detail) => {
const { message } = detail ?? {}
if (!message) return
if (localMode && localRootPath && gitInfo?.is_repo) {
const dirtyFiles = files.filter((f) => f.dirty)
const gitPaths = gitInfo.status?.map((s) => s.path) ?? []
const allPaths = [...new Set([...dirtyFiles.map((f) => f.path), ...gitPaths])]
if (allPaths.length === 0) {
emit('agent-commit-result', { success: false, error: 'No changes to commit' })
return
}
try {
await localCommitFiles(message, allPaths)
dirtyFiles.forEach((f) => markClean(f.path))
emit('agent-commit-result', { success: true, fileCount: allPaths.length })
} catch (err) {
emit('agent-commit-result', { success: false, error: String(err) })
}
return
}
if (!repo) return
const dirtyFiles = files.filter((f) => f.dirty)
if (dirtyFiles.length === 0) return
try {
await commitFiles(
repo.fullName,
dirtyFiles.map((f) => ({ path: f.path, content: f.content, sha: f.sha })),
message,
repo.branch,
)
dirtyFiles.forEach((f) => markClean(f.path))
emit('agent-commit-result', { success: true, fileCount: dirtyFiles.length })
} catch (err) {
emit('agent-commit-result', { success: false, error: String(err) })
}
})
}, [repo, files, markClean, localMode, localRootPath, gitInfo, localCommitFiles])
// ─── Git panel navigation ───
useEffect(() => {
const unsubs = [
on('open-git-panel', () => {
setView('git')
layout.show('gitPanel')
}),
on('open-changes-panel', () => setView('git')),
]
return () => unsubs.forEach((u) => u())
}, [setView])
// ─── Push handler ─────────────────────────────────────
useEffect(() => {
return on('agent-push', async () => {
try {
await local.push()
emit('agent-push-result', { success: true })
} catch (err) {
emit('agent-push-result', { success: false, error: String(err) })
}
})
}, [local])
return (
<div
className={`app-shell flex h-full w-full overflow-hidden bg-[var(--bg)] text-[var(--text-primary)] ${
isMobile ? 'gap-0 p-0' : 'gap-1 p-1'
}`}
style={keyboardOffset > 0 ? { height: `calc(100% - ${keyboardOffset}px)` } : undefined}
>
{/* Tauri drag region */}
{isTauriDesktop && (
<div
data-tauri-drag-region
className="tauri-drag-region fixed top-0 left-0 right-0 h-10 z-[9999] pointer-events-none"
/>
)}
{/* Workspace Sidebar — always visible in chat mode, toggleable otherwise */}
{!isMobile && mode !== 'tui' && (
<WorkspaceSidebar
collapsed={mode !== 'chat' && sidebarCollapsed}
onToggle={() => layout.toggle('sidebar')}
repoName={repo?.fullName || localRootPath?.split('/').pop()}
/>
)}
{/* Main content area */}
<div
className={`shell-frame flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden ${
isMobile
? 'rounded-none border-0 shadow-none'
: 'border border-[var(--border)] shadow-[var(--shadow-sm)] rounded-xl'
}`}
>
{/* Mode accent line */}
<div
className="h-[2px] shrink-0 transition-colors duration-500"
style={{
background: `linear-gradient(90deg, transparent, var(--mode-accent, var(--brand)), transparent)`,
opacity: 0.4,
}}
/>
{/* View navigation bar — folder tabs */}
{isMobile ? (
<div
className="shrink-0 border-b border-[var(--border)] bg-[color-mix(in_srgb,var(--bg-elevated)_94%,black)] px-4 pb-1.5"
style={{ paddingTop: 'calc(env(safe-area-inset-top) + 0.25rem)', minHeight: 44 }}
>
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="text-[17px] font-semibold text-[var(--text-primary)] tracking-tight">
{workspaceLabel === 'KnotCode' ? 'Knot Code' : workspaceLabel}
</span>
<span
className={`h-1.5 w-1.5 rounded-full shrink-0 ${
status === 'connected'
? 'bg-emerald-400'
: status === 'connecting'
? 'bg-amber-400 animate-pulse'
: 'bg-[var(--text-disabled)]'
}`}
/>
</div>
</div>
{!modeSpec.terminalCenter && (
<button
type="button"
onClick={() => layout.toggle('terminal')}
className={`hidden sm:flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border transition ${
terminalVisible
? 'border-[color-mix(in_srgb,var(--brand)_36%,var(--border))] bg-[color-mix(in_srgb,var(--brand)_10%,transparent)] text-[var(--brand)]'
: 'border-[var(--border)] bg-[color-mix(in_srgb,var(--bg)_92%,transparent)] text-[var(--text-secondary)] hover:bg-[color-mix(in_srgb,var(--text-primary)_5%,transparent)] hover:text-[var(--text-primary)]'
}`}
title={`${terminalVisible ? 'Hide' : 'Show'} terminal`}
>
<Icon icon="lucide:terminal" width={18} height={18} />
</button>
)}
<button
type="button"
onClick={() => {
setSettingsTab(undefined)
setSettingsVisible(true)
}}
className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border border-[var(--border)] bg-[color-mix(in_srgb,var(--bg)_92%,transparent)] text-[var(--text-secondary)] transition hover:bg-[color-mix(in_srgb,var(--text-primary)_5%,transparent)] hover:text-[var(--text-primary)]"
title="Settings"
>
<Icon icon="lucide:settings-2" width={18} height={18} />
</button>
</div>
{/* Gateway status text removed — dot in header is sufficient */}
</div>
) : (
<div
data-tauri-drag-region
className={`shell-topbar flex items-center h-10 shrink-0 px-4 gap-2 tauri-drag-region ${isMacTauri && sidebarCollapsed ? 'pl-20' : ''}`}
>
{/* Folder-style tab strip — hidden in TUI mode */}
{!modeSpec.hideTabs && (
<div ref={tabContainerRef} className="folder-tab-strip tauri-no-drag">
{visibleViews.map((v, i) => {
const isActive = activeView === v
return (
<motion.button
key={v}
ref={(el) => {
tabRefs.current[i] = el
}}
onClick={() => setView(v)}
className={`folder-tab ${isActive ? 'folder-tab--active' : ''} ${flashedTab === v ? 'folder-tab--flash' : ''}`}
style={
{
'--color': isActive ? 'var(--text-primary)' : 'var(--text-disabled)',
} as React.CSSProperties
}
title={`${VIEW_ICONS[v].label} (\u2318${i + 1})`}
whileTap={{ scale: 0.95 }}
layout
>
<span className="flex items-center gap-2">
<Icon
icon={VIEW_ICONS[v].icon}
width={14}
height={14}
className="folder-tab__icon"
/>
<span className="hidden sm:inline">{VIEW_ICONS[v].label}</span>
{v === 'git' && dirtyCount > 0 && (
<span className="px-2 min-w-[22px] text-center rounded-full bg-[var(--brand)] text-[var(--brand-contrast)] text-[11px] leading-[22px] font-bold animate-badge-pop">
{dirtyCount}
</span>
)}
</span>
</motion.button>
)
})}
<motion.span
className="folder-tab-strip__slider"
animate={{
left: indicatorStyle.left + 6,
width: Math.max(0, indicatorStyle.width - 12),
}}
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
style={{ '--opacity': indicatorStyle.width > 0 ? 1 : 0 } as React.CSSProperties}
/>
</div>
)}
{/* Codex-style header with Open + Commit dropdowns when tabs are hidden */}
{modeSpec.hideTabs && (
<div className="flex items-center gap-1.5 tauri-no-drag">
{/* Open dropdown */}
<button
onClick={() => emit('open-folder')}
className="codex-header-btn flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-medium text-[var(--text-secondary)] hover:bg-[color-mix(in_srgb,var(--text-primary)_6%,transparent)] hover:text-[var(--text-primary)] transition-all cursor-pointer"
>
<Icon icon="lucide:folder-open" width={14} height={14} />
Open
<Icon icon="lucide:chevron-down" width={10} height={10} className="opacity-50" />
</button>
<span className="text-[var(--text-disabled)] text-[11px]">·</span>
{/* Commit dropdown */}
<button
onClick={() => setView('git')}
className="codex-header-btn flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-medium text-[var(--text-secondary)] hover:bg-[color-mix(in_srgb,var(--text-primary)_6%,transparent)] hover:text-[var(--text-primary)] transition-all cursor-pointer"
>
<Icon icon="lucide:git-commit-horizontal" width={14} height={14} />
Commit
<Icon icon="lucide:chevron-down" width={10} height={10} className="opacity-50" />
</button>
</div>
)}
<div className="flex-1 tauri-drag-region" data-tauri-drag-region />
{/* Mode switcher — 3D pill group */}
<div className="shell-mode-switcher tauri-no-drag">
{MODE_BUTTONS.map((m, index) => (
<button
key={m.id}
onClick={() => setMode(m.id)}
className={`shell-mode-button ${mode === m.id ? 'shell-mode-button--active' : ''}`}
title={`${m.label} mode (${formatShortcut(`meta+shift+${index + 1}`)})`}
>
<Icon icon={m.icon} width={13} height={13} />
</button>
))}
</div>
{/* Change count badges */}
{dirtyCount > 0 && (
<div className="tauri-no-drag flex items-center gap-1.5 mr-1">
<span className="codex-header-badge text-[10px] font-mono font-bold px-1.5 py-0.5 rounded text-[var(--color-additions,#22c55e)] bg-[color-mix(in_srgb,var(--color-additions,#22c55e)_10%,transparent)]">
+{dirtyCount}
</span>
<span className="codex-header-badge text-[10px] font-mono font-bold px-1.5 py-0.5 rounded text-[var(--color-deletions,#ef4444)] bg-[color-mix(in_srgb,var(--color-deletions,#ef4444)_10%,transparent)]">
-{dirtyCount}
</span>
</div>
)}
{/* Settings */}
<button
onClick={() => setSettingsVisible(true)}
className="shell-utility-button tauri-no-drag"
title="Settings"
>
<Icon icon="lucide:settings" width={15} height={15} className="animate-gear-sway" />
</button>
</div>
)}
{showWorkflowEditorTabs && <EditorTabs onTabSelect={() => setView('editor')} />}
{/* Mode transition wrapper */}
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={`mode-${mode}-${useCenteredTerminal && terminalVisible ? 'term' : activeView}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15, ease: [0.16, 1, 0.3, 1] }}
className="flex-1 flex flex-col min-h-0 min-w-0 overflow-hidden"
>
{/* TUI mode: gateway terminal fills center */}
{useCenteredTerminal ? (
<div className="flex-1 flex min-h-0 min-w-0 overflow-hidden rounded-xl border border-[var(--border)]">
<GatewayTerminalLazy />
</div>
) : (
<ViewRouter />
)}
</motion.div>
</AnimatePresence>
{/* Terminal — docked (desktop) / drawer (mobile) / floating */}
{!modeSpec.terminalCenter && !isMobile ? (
<motion.div
initial={false}
animate={{ height: terminalVisible && !terminalFloating ? terminalHeight + 3 : 0 }}
transition={TERMINAL_SPRING}
style={{ '--overflow': 'hidden' } as React.CSSProperties}
className="shrink-0"
>
<div
className="h-[3px] cursor-row-resize hover:bg-[var(--brand)] transition-colors opacity-0 hover:opacity-50 shrink-0"
onMouseDown={(e) => {
e.preventDefault()
const startY = e.clientY
const startH = terminalHeight
const onMove = (ev: MouseEvent) =>
layout.resize('terminal', startH - (ev.clientY - startY))
const onUp = () => {
document.removeEventListener('mousemove', onMove)
document.removeEventListener('mouseup', onUp)
}
document.addEventListener('mousemove', onMove)
document.addEventListener('mouseup', onUp)
}}
/>
{!terminalFloating && (
<div
className="shrink-0 border-t border-[var(--border)]"
style={{ height: terminalHeight }}
>
<TerminalPanel
visible={terminalVisible && !terminalFloating}
height={terminalHeight}
onHeightChange={(h: number) => layout.resize('terminal', h)}
floating={terminalFloating}
onToggleFloating={() => layout.setFloating('terminal', !terminalFloating)}
refreshOnOpenOrMode={true}
refreshToken={terminalRefreshToken}
startupCommand={terminalStartupCommand}
/>
</div>
)}
</motion.div>
) : !modeSpec.terminalCenter ? (
<AnimatePresence initial={false}>
{terminalVisible && !terminalFloating && (
<>
<motion.button
key="terminal-backdrop"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[70] bg-black/40"
onClick={() => layout.hide('terminal')}
aria-label="Close terminal"
/>
<motion.div
key="terminal-drawer"
initial={{ y: 520 }}
animate={{ y: 0 }}
exit={{ y: 520 }}
transition={{ type: 'spring', stiffness: 400, damping: 34 }}
className="fixed left-1.5 right-1.5 z-[80] overflow-hidden rounded-t-2xl border border-[var(--border)] bg-[var(--bg-elevated)] shadow-2xl flex flex-col"
style={
{
bottom: mobileTerminalOffset,
'--height': Math.min(
Math.max(terminalHeight, 260),
Math.floor(viewportHeight * 0.72),
),
} as React.CSSProperties
}
>
<div className="flex justify-center pt-2 pb-0.5">
<div className="w-9 h-1 rounded-full bg-[var(--text-disabled)] opacity-40" />
</div>
<div className="h-11 flex items-center justify-between px-4 border-b border-[var(--border)] bg-[var(--bg-secondary)]">
<span className="text-[13px] font-semibold text-[var(--text-primary)] flex items-center gap-2.5">
<Icon
icon="lucide:terminal"
width={16}
height={16}
className="text-[var(--brand)]"
/>
Terminal
</span>
<button
onClick={() => layout.hide('terminal')}
className="p-2.5 rounded-xl hover:bg-[var(--bg-subtle)] text-[var(--text-tertiary)] cursor-pointer tauri-no-drag hover:scale-110 transition-all"
title="Close"
>
<Icon icon="lucide:x" width={16} height={16} />
</button>
</div>
<div className="flex-1 min-h-0">
<TerminalPanel
visible={terminalVisible && !terminalFloating}
height={terminalHeight}
onHeightChange={(h: number) => layout.resize('terminal', h)}
floating={terminalFloating}
onToggleFloating={() => layout.setFloating('terminal', !terminalFloating)}
refreshOnOpenOrMode={true}
refreshToken={terminalRefreshToken}
startupCommand={terminalStartupCommand}
/>
</div>
</motion.div>
</>
)}
</AnimatePresence>
) : null}
{terminalVisible && terminalFloating && !modeSpec.terminalCenter && (
<FloatingPanel
panel="terminal"
title="Terminal"
icon="lucide:terminal"
onDock={() => layout.setFloating('terminal', false)}
onClose={() => {
layout.setFloating('terminal', false)
layout.hide('terminal')
}}
minW={520}
minH={280}
>
<TerminalPanel
visible={terminalVisible}
height={terminalHeight}
onHeightChange={(h: number) => layout.resize('terminal', h)}
floating={terminalFloating}
onToggleFloating={() => layout.setFloating('terminal', !terminalFloating)}
refreshOnOpenOrMode={true}
refreshToken={terminalRefreshToken}
startupCommand={terminalStartupCommand}
/>
</FloatingPanel>
)}
{showMobileBottomTabs && (
<div
className="shrink-0 border-t border-[var(--border)] bg-[color-mix(in_srgb,var(--bg-elevated)_96%,black)]"
style={{
paddingBottom: 'env(safe-area-inset-bottom, 0px)',
overscrollBehavior: 'none',
}}
>
<div
className="grid"
style={{
gridTemplateColumns: `repeat(${mobileViewTabs.length}, minmax(0, 1fr))`,
minHeight: 49,
}}
>
{mobileViewTabs.map((v) => {
const isActive = activeView === v
return (
<motion.button
key={v}
type="button"
onClick={() => {
setView(v)
}}
whileTap={{ scale: 0.92 }}
className={`relative mx-1 my-1 flex min-w-0 flex-col items-center gap-0.5 rounded-xl border py-2 text-[10px] font-medium transition-colors touch-manipulation ${
isActive
? 'border-[color-mix(in_srgb,var(--brand)_28%,var(--border))] bg-[color-mix(in_srgb,var(--brand)_10%,transparent)] text-[var(--brand)] shadow-[0_8px_20px_color-mix(in_srgb,var(--brand)_10%,transparent)]'
: 'border-transparent text-[var(--text-disabled)]'
} ${flashedTab === v ? 'animate-badge-pop' : ''}`}
title={VIEW_ICONS[v].label}
style={{ minHeight: 44, WebkitTapHighlightColor: 'transparent' }}
>
<span className="relative">
<Icon icon={VIEW_ICONS[v].icon} width={24} height={24} />
{v === 'git' && dirtyCount > 0 && (
<span className="absolute -right-2 -top-1 min-w-[14px] rounded-full bg-[var(--brand)] px-0.5 text-center text-[8px] font-bold leading-[14px] text-[var(--brand-contrast)]">
{dirtyCount > 9 ? '9+' : dirtyCount}
</span>
)}
</span>
<span className="max-w-full truncate">{VIEW_ICONS[v].label}</span>
</motion.button>
)
})}
</div>
</div>
)}
{/* Status bar */}
{!isMobile && <StatusBar agentActive={agentActive} />}
</div>
{/* Git sidebar panel — Codex-style always-visible right panel */}
{!isMobile && mode !== 'tui' && layout.isVisible('gitPanel') && <GitSidebarPanel />}
{/* Plugins */}
<SpotifyPlugin />
<YouTubePlugin />
<PipWindow />
<WidgetPipWindow />
<PluginSlotRenderer slot="floating" />
<AnimatePresence initial={false}>
{showMobileSidebarButton && mobileSidebarOpen && (
<>
<motion.button
key="mobile-sidebar-backdrop"
type="button"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[85] bg-black/60"
onClick={() => setMobileSidebarOpen(false)}
aria-label="Close workspace drawer"
/>
<motion.div
key="mobile-sidebar-drawer"
initial={{ x: '-100%' }}
animate={{ x: 0 }}
exit={{ x: '-100%' }}
transition={{ type: 'spring', stiffness: 400, damping: 34 }}
className="fixed left-0 z-[90] w-[280px]"
style={{
top: 'calc(env(safe-area-inset-top) + 0.5rem)',
bottom: 'calc(env(safe-area-inset-bottom) + 0.5rem)',
}}
>
<div
className="relative h-full"
onClickCapture={(event) => {
const target = event.target as HTMLElement
if (target.closest('button')) {
requestAnimationFrame(() => setMobileSidebarOpen(false))
}
}}
>
<WorkspaceSidebar
collapsed={false}
repoName={repo?.fullName || localRootPath?.split('/').pop()}
/>
<button
type="button"
onClick={() => setMobileSidebarOpen(false)}
className="absolute right-3 top-3 z-10 flex h-9 w-9 items-center justify-center rounded-full border border-[var(--border)] bg-[color-mix(in_srgb,var(--bg)_92%,transparent)] text-[var(--text-secondary)] shadow-[var(--shadow-xs)] transition hover:bg-[color-mix(in_srgb,var(--text-primary)_5%,transparent)] hover:text-[var(--text-primary)]"
aria-label="Close workspace drawer"
>
<Icon icon="lucide:x" width={16} height={16} />
</button>
</div>
</motion.div>
</>
)}
</AnimatePresence>
{/* Modal overlays */}
<QuickOpen
open={quickOpenVisible}
onClose={() => setQuickOpenVisible(false)}
onSelect={(path, sha) => {
emit('file-select', { path, sha })
setQuickOpenVisible(false)
}}
/>
<GlobalSearch
open={globalSearchVisible}
onClose={() => setGlobalSearchVisible(false)}
onNavigate={(path, line) => {
emit('file-select', { path })
setGlobalSearchVisible(false)
}}
/>
<CommandPalette
open={commandPaletteVisible}
onClose={() => setCommandPaletteVisible(false)}
onRun={(cmdId) => {
setCommandPaletteVisible(false)
switch (cmdId) {