{{ message }}
Repository navigation
Expand file tree
/
Copy pathApp.tsx
More file actions
1007 lines (947 loc) · 36.1 KB
/
Copy pathApp.tsx
File metadata and controls
1007 lines (947 loc) · 36.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
import { GitHubIssuesPage } from './components/GitHubIssuesPage';
import '@xterm/xterm/css/xterm.css';
import '@fontsource/inter/400.css';
import '@fontsource/inter/500.css';
import '@fontsource/inter/600.css';
import '@fontsource/sora/400.css';
import '@fontsource/sora/500.css';
import '@fontsource/sora/600.css';
import '@fontsource/sora/700.css';
import '@fontsource/space-grotesk/500.css';
import '@fontsource/space-grotesk/700.css';
import '@fontsource/jetbrains-mono/400.css';
import '@fontsource/jetbrains-mono/500.css';
import './styles.css';
import {
onMount,
onCleanup,
createEffect,
Show,
ErrorBoundary,
createSignal,
lazy,
} from 'solid-js';
import { invoke } from './lib/ipc';
import { IPC } from '../electron/ipc/channels';
import { appWindow } from './lib/window';
import { startWindowVisibilityTracking } from './lib/windowVisibility';
import { choice } from './lib/dialog';
import { CLOSE_DIALOG_BUTTONS, resolveCloseChoice } from './lib/close-decision';
import { resolvePanelCloseTarget } from './store/close-target';
import { Sidebar } from './components/Sidebar';
import { TilingLayout } from './components/TilingLayout';
import { HelpDialog } from './components/HelpDialog';
import { SettingsDialog } from './components/SettingsDialog';
import { WorkspaceControls } from './components/WorkspaceControls';
import { WindowTitleBar } from './components/WindowTitleBar';
import { FocusModeTaskIndicators } from './components/FocusModeTaskIndicators';
import { UsageStatusBar } from './components/UsageStatusBar';
import { theme } from './lib/theme';
import * as log from './lib/log';
import {
store,
loadAgents,
loadState,
saveState,
toggleNewTaskPanel,
toggleSidebar,
toggleArena,
moveActiveTask,
jumpToTask,
adjustGlobalScale,
resetGlobalScale,
startTaskStatusPolling,
stopTaskStatusPolling,
startUsagePolling,
stopUsagePolling,
navigateRow,
navigateColumn,
navigateTask,
setPendingAction,
toggleHelpDialog,
toggleSettingsDialog,
sendActivePrompt,
spawnShellForTask,
closeShell,
clearNotification,
setWindowState,
createTerminal,
closeTerminal,
setNewTaskDropUrl,
validateProjectPaths,
setPlanContent,
setStepsContent,
setDockerAvailable,
toggleTaskFocusMode,
initMCPListeners,
markTaskMcpPending,
applyTaskMcpLaunchResult,
markTaskMcpError,
getProject,
triggerAction,
} from './store/store';
import { isGitHubUrl } from './lib/github-url';
import { getDeepActiveElement } from './lib/dom-focus';
import { HoldToQuit } from './components/HoldToQuit';
import type { PersistedWindowState } from './store/types';
import {
initShortcuts,
registerFromRegistry,
registerJumpToTaskShortcuts,
registerZoomShortcuts,
} from './lib/shortcuts';
import { resolvedBindings, loadKeybindings, dismissMigrationBanner } from './store/keybindings';
import { setupAutosave } from './store/autosave';
import { buildCustomThemeCss } from './lib/custom-theme';
import { osIsDark } from './lib/os-appearance';
import { applyAppearanceMode, markCustomThemesReady, loadCustomThemes } from './store/store';
import { isMac } from './lib/platform';
import { createCtrlWheelZoomHandler } from './lib/wheelZoom';
import { redrawAllTerminals } from './lib/terminalFitManager';
import { isDocumentAgentTaskId } from './documents/agent-task';
import { isHiddenAgentTaskId } from './documents/task-id';
import {
closeDocumentWorkspace,
documentStore,
initDocumentListeners,
setDocumentComposerDraft,
setDocumentSelection,
} from './documents/store';
import { dismissPinnedBubbles } from './documents/workspace-ui';
import { resetForNewMatch } from './arena/store';
import { startDesktopNotificationWatcher } from './store/desktopNotifications';
import { startSuperProductivitySync, startSpOpenListener } from './store/store';
import { startBackgroundTaskWatcher } from './store/background-tasks';
import { startPrChecksSubscription } from './store/pr-checks';
import { startUpdateSubscription } from './store/updates';
import { startRemoteTaskHandlers } from './store/remoteTaskHandler';
import { startRemoteStatusSync } from './store/remoteStatusSync';
import { startAgentHookStatusListener } from './store/agentHookStatus';
import { applyPlanContent, startCanvasAutoOpen } from './store/canvas';
import { startEvidenceAutoBuild } from './store/evidence-auto';
import type { PlanContentMessage } from './store/canvas';
import { SyncIcon } from './components/icons';
const ArenaOverlay = lazy(() =>
import('./arena/ArenaOverlay').then((m) => ({ default: m.ArenaOverlay })),
);
const MIN_WINDOW_DIMENSION = 100;
function DropOverlay() {
return (
<div
style={{
position: 'fixed',
inset: '0',
background: 'rgba(0, 0, 0, 0.65)',
display: 'flex',
'flex-direction': 'column',
'align-items': 'center',
'justify-content': 'center',
gap: '16px',
'z-index': '9999',
'pointer-events': 'none',
'backdrop-filter': 'blur(4px)',
}}
>
<svg
width="48"
height="48"
viewBox="0 0 16 16"
fill={theme.accent}
style={{ opacity: '0.9' }}
>
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8Z" />
</svg>
<span
style={{
color: theme.fg,
'font-size': '17px',
'font-weight': '600',
'font-family': 'var(--font-ui)',
}}
>
Drop GitHub link to create task
</span>
<span
style={{
color: theme.fgMuted,
'font-size': '13px',
'font-family': 'var(--font-ui)',
}}
>
A new task will be created with the link in the prompt
</span>
</div>
);
}
function App() {
let mainRef!: HTMLDivElement;
const [windowFocused, setWindowFocused] = createSignal(true);
const [windowMaximized, setWindowMaximized] = createSignal(false);
const [showDropOverlay, setShowDropOverlay] = createSignal(false);
const [closeHandlerReady, setCloseHandlerReady] = createSignal(false);
let dragCounter = 0;
function closeArena() {
void resetForNewMatch();
toggleArena(false);
}
function extractGitHubUrl(dt: DataTransfer): string | null {
const uriList = dt.getData('text/uri-list');
if (uriList) {
const firstUrl = uriList
.split('\n')
.find((l) => !l.startsWith('#'))
?.trim();
if (firstUrl && isGitHubUrl(firstUrl)) return firstUrl;
}
const text = dt.getData('text/plain')?.trim();
if (text && isGitHubUrl(text)) return text;
return null;
}
// Can't inspect data during dragenter/dragover — only check types exist.
// Exclude file drags (OS file manager, desktop icons) to avoid false positives.
function mayContainUrl(dt: DataTransfer): boolean {
if (dt.types.includes('Files')) return false;
return dt.types.includes('text/uri-list') || dt.types.includes('text/plain');
}
function handleDragEnter(e: DragEvent) {
if (!e.dataTransfer || !mayContainUrl(e.dataTransfer)) return;
e.preventDefault();
dragCounter++;
if (dragCounter === 1) setShowDropOverlay(true);
}
function handleDragOver(e: DragEvent) {
if (!showDropOverlay()) return;
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
}
function handleDragLeave(_e: DragEvent) {
if (!showDropOverlay()) return;
dragCounter--;
if (dragCounter <= 0) {
dragCounter = 0;
setShowDropOverlay(false);
}
}
function handleDrop(e: DragEvent) {
e.preventDefault();
dragCounter = 0;
setShowDropOverlay(false);
if (!e.dataTransfer) return;
const url = extractGitHubUrl(e.dataTransfer);
if (!url) return;
setNewTaskDropUrl(url);
toggleNewTaskPanel(true);
}
let unlistenFocusChanged: (() => void) | null = null;
let unlistenResized: (() => void) | null = null;
let unlistenMoved: (() => void) | null = null;
const syncWindowFocused = async () => {
const focused = await appWindow.isFocused().catch(() => true);
setWindowFocused(focused);
};
const syncWindowMaximized = async () => {
const maximized = await appWindow.isMaximized().catch(() => false);
setWindowMaximized(maximized);
};
const readWindowGeometry = async (): Promise<Omit<PersistedWindowState, 'maximized'> | null> => {
const [position, size] = await Promise.all([
appWindow.outerPosition().catch(() => null),
appWindow.outerSize().catch(() => null),
]);
if (!position || !size) return null;
if (size.width < MIN_WINDOW_DIMENSION || size.height < MIN_WINDOW_DIMENSION) return null;
return {
x: Math.round(position.x),
y: Math.round(position.y),
width: Math.round(size.width),
height: Math.round(size.height),
};
};
const captureWindowState = async (): Promise<void> => {
const maximized = await appWindow.isMaximized().catch(() => false);
const current = store.windowState;
if (maximized && current) {
if (!current.maximized) {
setWindowState({ ...current, maximized: true });
}
return;
}
const geometry = await readWindowGeometry();
if (!geometry) return;
setWindowState({ ...geometry, maximized });
};
const restoreWindowState = async (): Promise<void> => {
const saved = store.windowState;
if (!saved) return;
if (saved.width < MIN_WINDOW_DIMENSION || saved.height < MIN_WINDOW_DIMENSION) return;
await appWindow.unmaximize().catch(() => {});
await appWindow.setSize({ width: saved.width, height: saved.height }).catch(() => {});
await appWindow.setPosition({ x: saved.x, y: saved.y }).catch(() => {});
if (saved.maximized) {
await appWindow.maximize().catch(() => {});
}
void syncWindowMaximized();
};
// Re-derive effective theme whenever OS dark mode or appearance mode/slots change
createEffect(() => {
osIsDark(); // reactive dependency
applyAppearanceMode();
});
// Sync theme to <html> so Portal content (dialogs, tooltips) inherits CSS variables.
// data-look always holds the base preset so structural rules (islands, workbench, etc.)
// continue to apply. data-custom-theme overlays color variables when a custom theme is active.
createEffect(() => {
document.documentElement.dataset.look = store.themePreset;
const customId = store.activeCustomThemeId;
if (customId) {
document.documentElement.dataset.customTheme = customId;
} else {
delete document.documentElement.dataset.customTheme;
}
});
// Inject/update custom theme CSS into a dedicated <style> tag
createEffect(() => {
const customId = store.activeCustomThemeId;
let styleEl = document.getElementById('custom-theme-style') as HTMLStyleElement | null;
if (!customId) {
if (styleEl) styleEl.textContent = '';
return;
}
const theme = store.customThemes[customId];
if (!styleEl) {
styleEl = document.createElement('style');
styleEl.id = 'custom-theme-style';
document.head.appendChild(styleEl);
}
styleEl.textContent = theme ? buildCustomThemeCss(theme) : '';
});
// Toggle font smoothing CSS class on body
createEffect(() => {
document.body.classList.toggle('font-smoothing', store.fontSmoothing);
});
// Apply zoom via Electron's webFrame so window.devicePixelRatio scales with it.
// CSS transform: scale() does not affect devicePixelRatio, so canvas-based renderers
// (xterm.js WebGL) would render at insufficient pixel density and look blurry.
// webFrame.setZoomFactor() raises devicePixelRatio proportionally, triggering
// xterm's ScreenDprMonitor to re-render at the correct resolution.
createEffect(() => {
window.electron.setZoomFactor(store.globalScale);
});
// Sync the renderer logger's verbose state with the persisted setting.
createEffect(() => {
log.setVerbose(store.verboseLogging);
});
onMount(async () => {
// Before the first await: restored agents start firing hooks as soon as
// loadState spawns them, and IPC does not replay what nobody listened to.
const stopMCPListeners = initMCPListeners();
const stopAgentHookStatusListener = startAgentHookStatusListener();
const stopCanvasAutoOpen = startCanvasAutoOpen();
const stopEvidenceAutoBuild = startEvidenceAutoBuild();
// Listen for plan content pushed from backend plan watcher
const offPlanContent = window.electron.ipcRenderer.on(IPC.PlanContent, (data: unknown) => {
if (!data || typeof data !== 'object') return;
applyPlanContent(data as PlanContentMessage);
});
const stopDocumentListeners = initDocumentListeners();
const stopWindowVisibilityTracking = startWindowVisibilityTracking();
void syncWindowFocused();
void syncWindowMaximized();
void (async () => {
try {
unlistenFocusChanged = await appWindow.onFocusChanged((event) => {
const focused = Boolean(event.payload);
setWindowFocused(focused);
// The compositor can throttle the window's WebGL surface while it's
// backgrounded, leaving a corrupt glyph atlas (issue #121). Repaint
// every terminal on refocus so the corruption clears reliably.
// macOS-only: the corruption has never been reported on Linux, so
// Linux users don't pay the per-refocus repaint. The manual
// redrawTerminals shortcut stays cross-platform as an escape hatch.
if (focused && isMac) redrawAllTerminals();
});
} catch {
unlistenFocusChanged = null;
}
try {
let resizeTimer: ReturnType<typeof setTimeout> | undefined;
unlistenResized = await appWindow.onResized(() => {
if (resizeTimer !== undefined) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
resizeTimer = undefined;
void syncWindowMaximized();
void captureWindowState();
}, 200);
});
} catch {
unlistenResized = null;
}
let moveTimer: ReturnType<typeof setTimeout> | undefined;
try {
unlistenMoved = await appWindow.onMoved(() => {
if (moveTimer !== undefined) clearTimeout(moveTimer);
moveTimer = setTimeout(() => {
moveTimer = undefined;
void captureWindowState();
}, 200);
});
} catch {
unlistenMoved = null;
}
})();
await loadAgents();
invoke<boolean>(IPC.CheckDockerAvailable).then(
(available) => setDockerAvailable(available),
() => setDockerAvailable(false),
);
await loadState();
const themesLoaded = await loadCustomThemes();
// Only unlock slot-ID sanitization when the IPC call succeeded. On failure
// customThemes remains {} and we must not null out the user's persisted selections.
if (themesLoaded) markCustomThemesReady();
await loadKeybindings();
// Rewrite MCP config files for persisted coordinator tasks so the new
// session's port/token are in effect before any agent resumes.
// Docker coordinator tasks have no persisted mcpConfigPath (their .mcp.json
// lives in the worktree, not a temp file), but they still need StartMCPServer
// called so the remote server starts and the container name is registered.
const mcpRestorePromises: Promise<unknown>[] = [];
for (const taskId of [...store.taskOrder, ...store.collapsedTaskOrder]) {
const task = store.tasks[taskId];
if (!task?.coordinatorMode) continue;
const projectRoot = store.projects.find((p) => p.id === task.projectId)?.path;
if (!projectRoot) continue;
const agentDef = task.agentIds[0] ? store.agents[task.agentIds[0]]?.def : undefined;
// Reconstruct Docker container name from the coordinator's PTY agent id.
// The container may be dead after restart, but this wires up docker exec for sub-tasks
// when the user manually restarts the coordinator agent.
const dockerContainerName =
task.dockerMode && task.agentIds[0]
? `parallel-code-${task.agentIds[0].slice(0, 12)}`
: undefined;
markTaskMcpPending(taskId);
mcpRestorePromises.push(
invoke<{ mcpLaunchArgs?: string[] }>(IPC.StartMCPServer, {
coordinatorTaskId: task.id,
projectId: task.projectId,
projectRoot,
coordinatorBranch: task.branchName || undefined,
worktreePath: task.gitIsolation === 'worktree' ? task.worktreePath : undefined,
skipPermissions: task.skipPermissions ?? false,
propagateSkipPermissions: task.propagateSkipPermissions ?? false,
maxConcurrentTasks: task.maxConcurrentTasks,
verifyCommand: getProject(task.projectId)?.verifyCommand,
agentCommand: agentDef?.command ?? 'claude',
agentArgs: agentDef?.args ?? [],
agentEnvFile: agentDef ? store.agentEnvFiles[agentDef.id] : undefined,
dockerContainerName,
dockerImage: task.dockerMode ? task.dockerImage : undefined,
})
.then((result) => {
applyTaskMcpLaunchResult(taskId, result);
})
.catch((err) => {
console.warn(`[MCP] Failed to restore MCP server for coordinator task ${taskId}:`, err);
markTaskMcpError(taskId, String(err));
}),
);
}
// Wait for all coordinators to register before hydrating their children —
// hydrateTask() needs the coordinator entry to exist in the backend registry.
await Promise.allSettled(mcpRestorePromises);
// Hydrate backend coordinator task registry with persisted child tasks so MCP
// tools (list_tasks, send_prompt, close_task, etc.) work after app restart.
const hydratePromises: Promise<void>[] = [];
for (const taskId of [...store.taskOrder, ...store.collapsedTaskOrder]) {
const task = store.tasks[taskId];
if (!task?.coordinatedBy) continue;
if (
task.landingState === 'landed_pending_review' ||
task.landingState === 'landed_cleanup_failed' ||
task.landingState === 'reviewed'
)
continue;
// Skip if coordinator restore failed — hydrating into a broken coordinator leaves
// children with stale MCP wiring and misleading 'ready' status.
const parent = store.tasks[task.coordinatedBy];
if (!parent || (parent.coordinatorMode && parent.mcpStartupStatus !== 'ready')) continue;
const projectRoot = store.projects.find((p) => p.id === task.projectId)?.path;
if (!projectRoot) continue;
markTaskMcpPending(task.id);
hydratePromises.push(
invoke<{ mcpLaunchArgs?: string[] }>(IPC.MCP_HydrateCoordinatedTask, {
id: task.id,
name: task.name,
projectId: task.projectId,
projectRoot,
branchName: task.branchName,
baseBranch: task.baseBranch,
worktreePath: task.worktreePath,
coordinatorTaskId: task.coordinatedBy,
integrationPolicy: task.integrationPolicy,
controlledBy: task.controlledBy,
agentId: task.agentIds[0],
completion: task.completion,
reviewRevision: task.reviewRevision,
signalDoneAt: task.signalDoneAt,
signalDoneConsumed: task.signalDoneConsumed,
verification: task.verification,
landingState: task.landingState,
landingReason: task.landingReason,
landingSummary: task.landingSummary,
landedMetadata: task.landedMetadata,
mcpConfigPath: task.mcpConfigPath,
agentCommand: store.agents[task.agentIds[0]]?.def.command ?? 'claude',
preambleFileExistedBefore: task.preambleFileExistedBefore,
initialPrompt: task.initialPrompt,
})
.then((result) => {
applyTaskMcpLaunchResult(task.id, result);
})
.catch((err) => {
console.warn(`[MCP] Failed to hydrate coordinated task ${taskId}:`, err);
markTaskMcpError(task.id, String(err));
}),
);
}
await Promise.allSettled(hydratePromises);
// Restore plan content for tasks that had a plan file before restart
for (const taskId of [...store.taskOrder, ...store.collapsedTaskOrder]) {
const task = store.tasks[taskId];
if (!task?.worktreePath || !task.planFileName) continue;
invoke<{ content: string; fileName: string; relativePath: string } | null>(
IPC.ReadPlanContent,
{ worktreePath: task.worktreePath, fileName: task.planFileName },
)
.then((result) => {
if (result) setPlanContent(taskId, result.content, result.fileName, result.relativePath);
})
.catch((err) => {
console.warn(`Failed to restore plan for task ${taskId}:`, err);
});
}
// Restore steps content for tasks that had steps before restart
for (const taskId of [...store.taskOrder, ...store.collapsedTaskOrder]) {
const task = store.tasks[taskId];
if (!task?.worktreePath || !task.stepsEnabled) continue;
invoke<unknown[] | null>(IPC.ReadStepsContent, {
worktreePath: task.worktreePath,
})
.then((result) => {
if (result) setStepsContent(taskId, result);
})
.catch((err) => {
console.warn(`Failed to restore steps for task ${taskId}:`, err);
});
}
await validateProjectPaths();
await restoreWindowState();
await captureWindowState();
setupAutosave();
startTaskStatusPolling();
startUsagePolling();
const stopNotificationWatcher = startDesktopNotificationWatcher(windowFocused);
const stopSuperProductivitySync = startSuperProductivitySync(windowFocused);
const stopSpOpenListener = startSpOpenListener();
const stopBackgroundTaskWatcher = startBackgroundTaskWatcher();
const stopPrChecksSubscription = startPrChecksSubscription();
const stopUpdateSubscription = startUpdateSubscription();
const stopRemoteTaskHandlers = startRemoteTaskHandlers();
const stopRemoteStatusSync = startRemoteStatusSync();
// Listen for steps content pushed from backend steps watcher
const offStepsContent = window.electron.ipcRenderer.on(IPC.StepsContent, (data: unknown) => {
if (!data || typeof data !== 'object') return;
const msg = data as { taskId: string; steps: unknown[] | null };
log.debug('steps', 'recv', { taskId: msg.taskId, len: msg.steps?.length ?? null });
if (msg.taskId && store.tasks[msg.taskId]) {
setStepsContent(msg.taskId, msg.steps);
}
});
const handlePaste = (e: ClipboardEvent) => {
if (store.showNewTaskPanel || store.showHelpDialog || store.showSettingsDialog) return;
const el = getDeepActiveElement();
if (
el instanceof HTMLInputElement ||
el instanceof HTMLTextAreaElement ||
(el instanceof HTMLElement && el.isContentEditable) ||
el?.closest?.('.xterm')
) {
return;
}
const text = e.clipboardData?.getData('text/plain')?.trim();
if (text && isGitHubUrl(text)) {
e.preventDefault();
setNewTaskDropUrl(text);
toggleNewTaskPanel(true);
}
};
document.addEventListener('paste', handlePaste);
const handleBeforeUnload = () => {
void saveState();
};
window.addEventListener('beforeunload', handleBeforeUnload);
const handleWheel = createCtrlWheelZoomHandler((delta) => adjustGlobalScale(delta));
mainRef.addEventListener('wheel', handleWheel, { passive: false });
const cleanupShortcuts = initShortcuts();
let allowClose = false;
let handlingClose = false;
const unlistenCloseRequested = await appWindow.onCloseRequested(async (event) => {
await captureWindowState();
await saveState();
if (allowClose) return;
if (handlingClose) {
event.preventDefault();
return;
}
const runningCount = await invoke<number>(IPC.CountRunningAgents).catch(() => 0);
if (runningCount <= 0) return;
event.preventDefault();
handlingClose = true;
try {
const countLabel =
runningCount === 1
? '1 running terminal session'
: `${runningCount} running terminal sessions`;
const selected = await choice(
`You have ${countLabel}. They can be restored on app restart. Kill them and quit, keep them alive in the background, or cancel?`,
{
title: 'Running Terminals',
kind: 'warning',
buttons: [...CLOSE_DIALOG_BUTTONS],
defaultId: 2,
cancelId: 2,
},
).catch(() => 2);
const action = resolveCloseChoice(selected);
if (action === 'kill') {
await invoke(IPC.KillAllAgents).catch(console.error);
allowClose = true;
await appWindow.close().catch(console.error);
return;
}
if (action === 'background') {
await appWindow.hide().catch(console.error);
}
// 'abort': close already prevented above — leave the window open.
} finally {
handlingClose = false;
}
});
setCloseHandlerReady(true);
// A document workspace's hidden agent task can be the active one; it has
// no worktree to close, merge or push and no panel a shell could show in.
const listedTask = (id: string) =>
!store.githubIssuesProjectId && store.tasks[id] !== undefined && !isHiddenAgentTaskId(id);
const actionHandlers: Record<string, (e: KeyboardEvent) => void> = {
'navigateRow:up': () => navigateRow('up'),
'navigateRow:down': () => navigateRow('down'),
'navigateColumn:left': () => navigateColumn('left'),
'navigateColumn:right': () => navigateColumn('right'),
'navigateTask:left': () => navigateTask('left'),
'navigateTask:right': () => navigateTask('right'),
'moveActiveTask:left': () => moveActiveTask('left'),
'moveActiveTask:right': () => moveActiveTask('right'),
...Object.fromEntries(
Array.from({ length: 9 }, (_, i) => [`jumpToTask:${i + 1}`, () => jumpToTask(i)]),
),
closeShell: (e) => {
if (store.githubIssuesProjectId) return;
// Auto-repeat would walk through adjacent terminals or canvas tabs.
if (e.repeat) return;
const target = resolvePanelCloseTarget(store);
if (!target) return;
if (target.kind === 'terminal') closeTerminal(target.terminalId);
else if (target.kind === 'shell') closeShell(target.taskId, target.shellId);
else triggerAction(`${target.taskId}:close-canvas-active-tab`);
},
closeTask: () => {
if (store.githubIssuesProjectId) return;
const id = store.activeTaskId;
if (!id) return;
if (store.terminals[id]) {
closeTerminal(id);
return;
}
if (isDocumentAgentTaskId(id)) {
closeDocumentWorkspace();
return;
}
if (listedTask(id)) setPendingAction({ type: 'close', taskId: id });
},
mergeTask: () => {
const id = store.activeTaskId;
if (id && listedTask(id)) setPendingAction({ type: 'merge', taskId: id });
},
pushTask: () => {
const id = store.activeTaskId;
if (id && listedTask(id)) setPendingAction({ type: 'push', taskId: id });
},
spawnShell: () => {
const id = store.activeTaskId;
if (id && listedTask(id)) spawnShellForTask(id);
},
sendPrompt: () => {
if (!store.githubIssuesProjectId) sendActivePrompt();
},
createTerminal: (e) => {
if (!e.repeat) createTerminal();
},
newTask: () => toggleNewTaskPanel(true),
toggleSidebar: () => toggleSidebar(),
toggleFocusMode: () => toggleTaskFocusMode(),
toggleHelp: () => toggleHelpDialog(),
toggleSettings: () => toggleSettingsDialog(),
closeDialogs: () => {
if (store.showArena) {
closeArena();
return;
}
if (store.activeDocumentProjectId && isDocumentAgentTaskId(store.activeTaskId)) {
// A pinned note covers the prose and goes first. Then the composer,
// up with a passage or with a draft opened from the toolbar or a
// note; either way Escape closes it before the workspace.
if (dismissPinnedBubbles()) return;
if (documentStore.selection || documentStore.composerDraft) {
setDocumentSelection(null);
setDocumentComposerDraft(null);
} else {
closeDocumentWorkspace();
}
return;
}
if (store.showHelpDialog) {
toggleHelpDialog(false);
return;
}
if (store.showSettingsDialog) {
toggleSettingsDialog(false);
return;
}
},
resetZoom: () => resetGlobalScale(),
redrawTerminals: () => redrawAllTerminals(),
};
const cleanupZoomShortcuts = registerZoomShortcuts({
zoomIn: () => adjustGlobalScale(1),
zoomOut: () => adjustGlobalScale(-1),
resetZoom: () => resetGlobalScale(),
});
const cleanupJumpToTaskShortcuts = registerJumpToTaskShortcuts((i) => jumpToTask(i));
createEffect(() => {
const cleanup = registerFromRegistry(resolvedBindings(), actionHandlers);
onCleanup(cleanup);
});
onCleanup(() => {
document.removeEventListener('paste', handlePaste);
window.removeEventListener('beforeunload', handleBeforeUnload);
mainRef.removeEventListener('wheel', handleWheel);
unlistenCloseRequested();
cleanupShortcuts();
stopTaskStatusPolling();
stopUsagePolling();
stopMCPListeners();
stopNotificationWatcher();
stopSuperProductivitySync();
stopSpOpenListener();
stopBackgroundTaskWatcher();
stopPrChecksSubscription();
stopUpdateSubscription();
stopRemoteTaskHandlers();
stopRemoteStatusSync();
stopAgentHookStatusListener();
stopCanvasAutoOpen();
stopEvidenceAutoBuild();
stopDocumentListeners();
stopWindowVisibilityTracking();
offPlanContent();
offStepsContent();
unlistenFocusChanged?.();
unlistenResized?.();
unlistenMoved?.();
cleanupZoomShortcuts();
cleanupJumpToTaskShortcuts();
});
});
return (
<ErrorBoundary
fallback={(err, reset) => (
<div
style={{
width: '100vw',
height: '100vh',
display: 'flex',
'flex-direction': 'column',
'align-items': 'center',
'justify-content': 'center',
gap: '16px',
background: theme.bg,
color: theme.fg,
'font-family': "var(--font-ui, 'Sora', sans-serif)",
}}
>
<div style={{ 'font-size': '19px', 'font-weight': '600', color: theme.error }}>
Something went wrong
</div>
<div
style={{
'max-width': '500px',
'text-align': 'center',
color: theme.fgMuted,
'word-break': 'break-word',
}}
>
{String(err)}
</div>
<button
class="btn-with-icon"
onClick={reset}
style={{
background: theme.bgElevated,
border: `1px solid ${theme.border}`,
color: theme.fg,
padding: '8px 24px',
'border-radius': 'var(--radius-md)',
cursor: 'pointer',
'font-size': '15px',
}}
>
<SyncIcon size={14} />
Reload
</button>
</div>
)}
>
<div
ref={mainRef}
class="app-shell"
data-look={store.themePreset}
data-window-border={!isMac ? 'true' : 'false'}
data-window-focused={windowFocused() ? 'true' : 'false'}
data-window-maximized={windowMaximized() ? 'true' : 'false'}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
style={{
'--inactive-column-opacity': store.inactiveColumnOpacity,
width: '100vw',
height: '100vh',
display: 'flex',
'flex-direction': 'column',
position: 'relative',
background: theme.bg,
color: theme.fg,
'font-family': "var(--font-ui, 'Sora', sans-serif)",
'font-size': '14px',
overflow: 'hidden',
}}
>
<Show when={!isMac}>
<WindowTitleBar />
</Show>
<Show when={isMac}>
<div class="mac-titlebar-spacer" data-tauri-drag-region>
<WorkspaceControls />
<FocusModeTaskIndicators />
</div>
</Show>
<Show when={!store.keybindingMigrationDismissed}>
<div
class="keybinding-migration-notice"
role="region"
aria-label="Keyboard shortcuts update"
>
<span>
Keyboard shortcuts are now configurable.{' '}
<button
type="button"
class="keybinding-migration-notice-action"
onClick={() => {
toggleHelpDialog(true);
dismissMigrationBanner();
}}
>
Pick a preset for your coding agent
</button>{' '}
or{' '}
<button
type="button"
class="keybinding-migration-notice-action secondary"
onClick={() => dismissMigrationBanner()}
>
dismiss
</button>
.
</span>
<button
type="button"
class="keybinding-migration-notice-close"
aria-label="Dismiss keyboard shortcuts update"
onClick={() => dismissMigrationBanner()}
>
×
</button>
</div>
</Show>
<main style={{ flex: '1', display: 'flex', overflow: 'hidden' }}>
<Show when={store.sidebarVisible}>
<Sidebar />
</Show>
{/* Keep terminals mounted while the issue page occupies the workspace. */}
<div
class="task-workspace"
style={{
display: store.projects.some((p) => p.id === store.githubIssuesProjectId)
? 'none'
: undefined,
}}
>
<TilingLayout />
</div>
<GitHubIssuesPage />
</main>
<UsageStatusBar />
<HelpDialog open={store.showHelpDialog} onClose={() => toggleHelpDialog(false)} />
<SettingsDialog
open={store.showSettingsDialog}
onClose={() => toggleSettingsDialog(false)}
/>
<Show when={store.showArena}>
<ArenaOverlay onClose={closeArena} />
</Show>
<Show when={showDropOverlay()}>
<DropOverlay />
</Show>
{/* Not before the close handler is listening: Cmd+Q closes the window,
and a close nobody answers hits the backend's 5s watchdog, which
force-destroys and takes the terminals with it. */}
<Show when={isMac && closeHandlerReady()}>
<HoldToQuit />
</Show>
<Show when={store.notification}>
<div
onClick={() => clearNotification()}
style={{
position: 'fixed',
bottom: '24px',
left: '50%',
transform: 'translateX(-50%)',
background: theme.islandBg,
border: `1px solid ${theme.border}`,
'border-radius': 'var(--radius-md)',
padding: '10px 20px',
color: theme.fg,
'font-size': '14px',
'z-index': '2000',
'box-shadow': '0 4px 24px rgba(0,0,0,0.4)',
cursor: 'pointer',
}}
>
{store.notification}
</div>
You can’t perform that action at this time.
