-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.js
More file actions
11248 lines (9488 loc) · 362 KB
/
Copy pathrenderer.js
File metadata and controls
11248 lines (9488 loc) · 362 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
const {
normalizeCanvasWorkspaceRecord,
syncCanvasWorkspaceFromLiveState,
toggleCanvasWorkspaceExpandedDirectory,
deriveCanvasWorkspaceAfterRestore,
deriveWorkspaceEntryActionState,
shouldApplyCanvasWorkspaceRestoreResult,
getCanvasWorkspaceExpandedDirectories,
getCanvasWorkspacePreviewRelativePath,
getCanvasWorkspaceRootPath
} = window.noteCanvasRendererWorkspace;
const {
createWorkspaceActionDialogState,
openWorkspaceActionDialog,
closeWorkspaceActionDialog,
getWorkspaceActionDialogSubmitValue
} = window.noteCanvasRendererActionDialog;
const {
deriveCanvasSwitcherViewModel,
deriveCanvasStripOverflowState,
deriveTerminalStripViewModel,
deriveTerminalStripDropTarget,
deriveTerminalTreeRows,
deriveTerminalTreeDropAction
} = window.noteCanvasRendererCanvasSwitcher;
const {
shouldHandleCanvasWheel,
shouldTerminalHandleWheel,
shouldClearActiveTerminalSelection,
shouldSelectTerminal,
shouldEnableTerminalInteractionOverlay,
shouldShowBoardHintsForCanvas,
deriveTerminalStripActivation,
getViewportOffsetForScaleAtPoint,
getViewportOffsetToCenterBounds,
getViewportOffsetToCenterNode,
getStripScrollTarget,
getStripOverflowTargetIndex
} = window.noteCanvasRendererCanvasNavigation;
const {
deriveWorkspacePreviewViewModel,
shouldApplyWorkspacePreviewActionError
} = window.noteCanvasRendererWorkspacePreview;
const {
closeManagedAgentSubtree,
deriveCanvasDelegationEdges,
sortCanvasAgentSnapshotsForPlacement,
findHorizontalCanvasNodePlacement
} = window.noteCanvasRendererCanvasDelegation;
const { mapWithConcurrency } = window.noteCanvasRendererAsyncPool;
const {
createFocusedTerminalLifecycle,
shouldShowNodeInFocusedMode,
pickInitialSidebarViewForFocusedMode,
pickFocusedNode,
shouldInvokeTerminalDestroy
} = window.noteCanvasRendererFocusedMode;
// The CodeMirror bundle is ~770KB, so it loads on demand the first time a
// file preview needs an editor instead of blocking startup.
let workspaceMarkdownBundlePromise = null;
let didWorkspaceMarkdownBundleFail = false;
function ensureWorkspaceMarkdownBundle() {
if (window.noteCanvasRendererWorkspaceMarkdown !== undefined || didWorkspaceMarkdownBundleFail) {
return Promise.resolve();
}
if (workspaceMarkdownBundlePromise === null) {
workspaceMarkdownBundlePromise = new Promise((resolve) => {
const script = document.createElement("script");
script.src = "./renderer_workspace_markdown.bundle.js";
script.addEventListener("load", () => {
resolve();
});
script.addEventListener("error", () => {
didWorkspaceMarkdownBundleFail = true;
console.warn("Workspace markdown editor bundle failed to load; using plain editors.");
resolve();
});
document.head.append(script);
});
}
return workspaceMarkdownBundlePromise;
}
if (window.noteCanvas?.isSmokeTest) {
window.__canvasLearningBootError = null;
window.addEventListener("error", (event) => {
const error = event.error;
window.__canvasLearningBootError = error instanceof Error
? (error.stack || error.message)
: String(event.message || "Unknown renderer boot error.");
});
}
const appShell = document.querySelector(".app-shell");
const board = document.getElementById("board");
const nodesLayer = document.getElementById("nodes-layer");
const canvasEdgeLayer = document.getElementById("canvas-edge-layer");
const emptyState = document.getElementById("empty-state");
const boardHints = document.getElementById("board-hints");
const boardNavigation = document.getElementById("board-navigation");
const boardZoomIndicator = document.getElementById("board-zoom-indicator");
const boardZoomOutButton = document.getElementById("board-zoom-out-button");
const boardZoomInButton = document.getElementById("board-zoom-in-button");
const boardCenterViewButton = document.getElementById("board-center-view-button");
const boardFullscreenExitButton = document.getElementById("board-fullscreen-exit");
const boardWelcome = document.getElementById("board-welcome");
const boardWelcomeOpenButton = document.getElementById("board-welcome-open-button");
const boardMinimap = document.getElementById("board-minimap");
const boardMinimapCanvas = document.getElementById("board-minimap-canvas");
const boardMinimapViewport = document.getElementById("board-minimap-viewport");
const canvasBreadcrumb = document.getElementById("canvas-breadcrumb");
const canvasPanelTitle = document.getElementById("canvas-panel-title");
const canvasPanelPills = document.getElementById("canvas-panel-pills");
const canvasActionsMenuRoot = document.getElementById("canvas-actions-menu-root");
const canvasActionsMenuButton = document.getElementById("canvas-actions-menu-button");
const canvasActionsMenu = document.getElementById("canvas-actions-menu");
const restartAgentSessionsButton = document.getElementById("restart-agent-sessions-button");
const closeActiveCanvasButton = document.getElementById("close-active-canvas-button");
const canvasSwitcherSection = document.getElementById("canvas-switcher-section");
const canvasStripList = document.getElementById("canvas-strip-list");
const canvasStripPrevButton = document.getElementById("canvas-strip-prev-button");
const canvasStripNextButton = document.getElementById("canvas-strip-next-button");
const terminalNavigatorSection = document.getElementById("terminal-navigator-section");
const terminalNavigator = document.getElementById("terminal-navigator");
const createTerminalButton = document.getElementById("create-terminal-button");
const sidebarViewSwitcher = document.getElementById("sidebar-view-switcher");
const sidebarViewExplorerTab = document.getElementById("sidebar-view-explorer");
const sidebarViewTerminalsTab = document.getElementById("sidebar-view-terminals");
const createCanvasButton = document.getElementById("create-canvas-button");
const exportCanvasButton = document.getElementById("export-canvas-button");
const importCanvasButton = document.getElementById("import-canvas-button");
const installAgentSkillButton = document.getElementById("install-agent-skill-button");
const selectTerminalsButton = document.getElementById("select-terminals-button");
const boardSelectModeBar = document.getElementById("board-select-mode-bar");
const boardSelectModeLabel = document.getElementById("board-select-mode-label");
const boardSelectModeCount = document.getElementById("board-select-mode-count");
const boardSelectCloseButton = document.getElementById("board-select-close-button");
const boardSelectCancelButton = document.getElementById("board-select-cancel-button");
const focusWorkspaceSearchButton = document.getElementById("focus-workspace-search-button");
const openWorkspaceButton = document.getElementById("open-workspace-button");
const refreshWorkspaceButton = document.getElementById("refresh-workspace-button");
const createWorkspaceFileButton = document.getElementById("create-workspace-file-button");
const createWorkspaceDirectoryButton = document.getElementById("create-workspace-directory-button");
const renameWorkspaceEntryButton = document.getElementById("rename-workspace-entry-button");
const deleteWorkspaceEntryButton = document.getElementById("delete-workspace-entry-button");
const workspaceBrowser = document.getElementById("workspace-browser");
const fileInspector = document.getElementById("file-inspector");
const fileInspectorResizeHandle = document.getElementById("file-inspector-resize-handle");
const workspaceActionDialog = document.getElementById("workspace-action-dialog");
const workspaceActionDialogBackdrop = document.getElementById("workspace-action-dialog-backdrop");
const workspaceActionDialogForm = document.getElementById("workspace-action-dialog-form");
const workspaceActionDialogTitle = document.getElementById("workspace-action-dialog-title");
const workspaceActionDialogMessage = document.getElementById("workspace-action-dialog-message");
const workspaceActionDialogInput = document.getElementById("workspace-action-dialog-input");
const workspaceActionDialogCancelButton = document.getElementById("workspace-action-dialog-cancel");
const workspaceActionDialogConfirmButton = document.getElementById("workspace-action-dialog-confirm");
const railToggleButton = document.getElementById("rail-toggle-button");
const sidebarToggleButton = document.getElementById("sidebar-toggle-button");
const sidebarResizeHandle = document.getElementById("sidebar-resize-handle");
const sidebarPanel = document.querySelector(".canvas-sidebar-panel");
const TerminalConstructor = window.Terminal;
const FitAddonConstructor = window.FitAddon?.FitAddon;
const Unicode11AddonConstructor = window.Unicode11Addon?.Unicode11Addon;
const WebglAddonConstructor = window.WebglAddon?.WebglAddon;
const DRAG_THRESHOLD = 3;
const CANVAS_EXPORT_VERSION = 3;
const LEGACY_CANVAS_EXPORT_VERSION = 1;
const SUPPORTED_CANVAS_EXPORT_VERSIONS = [LEGACY_CANVAS_EXPORT_VERSION, 2, CANVAS_EXPORT_VERSION];
const MAX_CANVAS_NAME_LENGTH = 80;
const MAX_TERMINAL_TITLE_LENGTH = 80;
const WHEEL_LINE_DELTA_PX = 16;
const CANVAS_SCALE_MIN = 0.25;
const CANVAS_SCALE_MAX = 1.8;
const CANVAS_SCALE_STEP = 0.0022;
const CANVAS_SCALE_STEP_FACTOR = 1.22;
const CANVAS_SCALE_PRECISION = 1000;
const CANVAS_ZOOM_WHEEL_DELTA_LIMIT = 140;
const DEFAULT_NODE_WIDTH = 636;
const DEFAULT_NODE_HEIGHT = 414;
const MIN_NODE_WIDTH = 288;
const MIN_NODE_HEIGHT = 184;
const MIN_SIDEBAR_PANEL_WIDTH = 224;
const MIN_FILE_INSPECTOR_WIDTH = 240;
const PANEL_VIEWPORT_MARGIN = 24;
const MIN_CANVAS_COLUMN_WIDTH = 360;
const ZOOM_INDICATOR_VISIBLE_MS = 1200;
const RESIZE_HANDLE_DIRECTIONS = ["n", "s", "e", "w", "nw", "ne", "sw", "se"];
const APP_SESSION_VERSION = 2;
const APP_SESSION_SAVE_DEBOUNCE_MS = 180;
const CANVAS_AGENT_SYNC_INTERVAL_MS = 6000;
const CANVAS_AGENT_LIVENESS_INTERVAL_MS = 30000;
const CANVAS_AGENT_EVENT_DEBOUNCE_MS = 250;
const MAX_WORKSPACE_PREVIEW_TABS = 5;
const TERMINAL_MIN_COLS = 20;
const TERMINAL_MIN_ROWS = 8;
const TERMINAL_FALLBACK_COLS = 80;
const TERMINAL_FALLBACK_ROWS = 24;
const TERMINAL_LAYOUT_SETTLE_DELAYS_MS = [80, 240];
const TERMINAL_RESTORE_CONCURRENCY = 4;
const MANAGED_AGENT_NODE_GAP = 72;
// Leave headroom below Chromium's per-page WebGL context limit. Terminals
// beyond this budget keep xterm's stable DOM renderer instead of causing the
// browser to evict contexts and repeatedly rebuild glyph atlases.
const MAX_TERMINAL_WEBGL_RENDERERS = 8;
const OSC52_CLIPBOARD_MAX_BYTES = 1024 * 1024;
const AGENT_SKILL_INSTALL_PROMPT_DISMISSED_KEY = "termcanvas.agentSkillInstallPromptDismissed";
const FOCUSED_TERMINAL_MODE = true;
let terminalCount = 0;
let canvasCount = 0;
const canvases = [];
const canvasMap = new Map();
const terminalNodeMap = new Map();
let activeCanvasId = null;
let activeNodeRecord = null;
let activeTitleEditorRecord = null;
let activeTerminalNodeMenuRecord = null;
let activeCanvasRenameId = null;
let isRailCollapsed = false;
let isSidebarCollapsed = true;
// Sidebar view: "explorer" (file tree) or "terminals" (agent spawn tree).
// Defaults to "terminals" when the active canvas has nodes — that's the
// view Luis reaches for most. Toggled from the sidebar header tabs.
let activeSidebarView = "explorer";
// Per-canvas set of collapsed agent names for the terminal tree. Keyed by
// canvas id so switching canvases restores each tree's own fold state.
const collapsedAgentNamesByCanvasId = new Map();
const focusedSessionKeyByCanvasId = new Map();
let hasDismissedBoardIntro = false;
let isWindowUnloading = false;
let renderedCanvasId = null;
let viewportRenderFrame = 0;
let terminalSizeSyncFrame = 0;
let terminalRefreshFrame = 0;
let shouldRefreshTerminalsAfterViewportRender = false;
// Pure pan is fully handled by the container CSS transform, so per-node
// position resnapping is deferred to zoom frames and a trailing settle render.
let shouldSyncNodePositionsOnViewportRender = false;
let viewportSettleTimer = 0;
const VIEWPORT_SETTLE_DELAY_MS = 120;
let zoomIndicatorTimeout = 0;
let canvasStripOverflowSyncFrame = 0;
let shouldEnsureActiveCanvasStripItemVisible = false;
const pendingTerminalSizeNodes = new Set();
const pendingTerminalRefreshNodes = new Set();
const pendingTailUpdateNodes = new Set();
let tailUpdateFrame = 0;
let pendingCanvasListFocus = null;
let isCanvasActionsMenuOpen = false;
let isCanvasSwitcherMenuOpen = false;
let lastExportedCanvasDebugPayload = null;
let workspacePreviewRequestId = 0;
let workspacePreviewObjectUrl = null;
let workspacePreviewTabs = [];
let workspaceStateHydrationToken = 0;
let activeCanvasWorkspaceRestoreToken = 0;
let pendingWorkspaceDirectoryRefresh = false;
let appSessionSaveTimeout = 0;
let isSessionHydrating = false;
let workspaceFilterQuery = "";
let canvasAgentSyncTimeout = 0;
let canvasAgentLivenessTimeout = 0;
let canvasAgentEventDebounceTimeout = 0;
let isCanvasAgentSyncInFlight = false;
let canvasAgentSyncGeneration = 0;
let managedAgentCloseInFlightCount = 0;
let managedAgentRestartInFlightCount = 0;
let canvasAgentUnsubscribe = null;
let canvasAgentChangeListenerRemover = null;
let lastSyncedAgentProjectTag = null;
let workspaceActionDialogResolve = null;
let isAgentSkillInstallDialogOpen = false;
let workspaceMarkdownEditor = null;
let pendingWorkspacePreviewOwnSave = null;
let pendingWorkspacePreviewSaveAfterCurrent = false;
const workspacePreviewState = {
folderId: null,
relativePath: null,
status: "empty",
data: null,
errorMessage: "",
actionErrorMessage: "",
viewMode: "auto",
isEditing: false,
draftText: "",
saveErrorMessage: "",
isDirty: false,
isSaving: false
};
const workspaceSelectionState = {
folderId: null,
relativePath: null,
kind: null
};
const workspaceDirectoryLoadState = {
folderId: null,
relativePath: null
};
let workspaceActionDialogState = createWorkspaceActionDialogState();
const workspaceState = {
importedFolders: [],
activeFolderId: null,
isRefreshing: false
};
const panState = {
pointerId: null,
startClientX: 0,
startClientY: 0,
originX: 0,
originY: 0,
hasMoved: false
};
const dragState = {
pointerId: null,
nodeRecord: null,
handleElement: null,
startClientX: 0,
startClientY: 0,
originX: 0,
originY: 0,
hasMoved: false
};
const resizeState = {
pointerId: null,
nodeRecord: null,
handleElement: null,
direction: "",
startClientX: 0,
startClientY: 0,
originX: 0,
originY: 0,
originWidth: 0,
originHeight: 0,
hasMoved: false
};
const panelResizeState = {
pointerId: null,
handleElement: null,
panelKind: "",
startClientX: 0,
originWidth: 0,
hasMoved: false
};
const listReorderState = {
kind: null,
itemId: null,
sourceIndex: -1,
targetIndex: -1,
sourceElement: null,
targetElement: null,
isAfterTarget: false,
moveItem: null
};
const focusedTerminalLifecycle = createFocusedTerminalLifecycle({
getNodes: () => canvases.flatMap((canvasRecord) => canvasRecord.nodes),
isMounted: (nodeRecord) => nodeRecord?.terminal !== null || typeof nodeRecord?.terminalId === "string",
canAttach: (nodeRecord) => (
!isWindowUnloading
&& nodeRecord?.isRemoved !== true
&& nodeRecord?.isExited !== true
&& nodeRecord?.managedAgentState !== "archived"
&& nodeRecord?.canvas?.id === activeCanvasId
&& nodeRecord === activeNodeRecord
),
detach: async (nodeRecord) => {
const hasDurableSession = nodeRecord.backend === "tmux" && nodeRecord.tmuxSessionName !== null;
await releaseTerminalSession(nodeRecord, {
shouldDestroySession: false,
retainDetachedIdentity: hasDurableSession
});
if (!hasDurableSession && !nodeRecord.isRemoved) {
setNodeExitedState(nodeRecord, null, null);
setTerminalNodeStatus(nodeRecord, "Restart required");
nodeRecord.meta.textContent = "tmux is unavailable; reopen to start a fresh shell";
}
},
attach: (nodeRecord) => bindTerminalSession(nodeRecord, { shouldFocus: false }),
focus: (nodeRecord) => {
requestAnimationFrame(() => {
if (
nodeRecord === activeNodeRecord
&& nodeRecord.terminal !== null
&& !nodeRecord.isTitleEditing
) {
nodeRecord.terminal.focus();
}
});
},
onError: (nodeRecord, error) => {
console.error(error);
if (nodeRecord == null || nodeRecord.isRemoved) {
return;
}
setNodeExitedState(nodeRecord, null, null);
const message = error instanceof Error ? error.message : String(error ?? "Could not attach terminal");
const isStoppedSession = /not running|can't find session|missing/u.test(message);
setTerminalNodeStatus(nodeRecord, isStoppedSession ? "Stopped" : "Attach failed");
nodeRecord.meta.textContent = message;
}
});
const removeTerminalDataListener = window.noteCanvas.onTerminalData(({ terminalId, data }) => {
const nodeRecord = terminalNodeMap.get(terminalId);
if (nodeRecord === undefined) {
return;
}
nodeRecord.lastDataAt = Date.now();
// Hidden tmux-backed terminals skip VT parsing entirely; tmux holds the
// real screen state and repaints the pane when the node is revealed.
if (
nodeRecord.backend === "tmux"
&& !isTerminalNodeRendererVisible(nodeRecord)
) {
nodeRecord.needsTerminalRepaint = true;
return;
}
nodeRecord.terminal?.write(data);
scheduleNodeTailUpdate(nodeRecord);
});
const removeTerminalExitListener = window.noteCanvas.onTerminalExit(({ terminalId, exitCode, signal }) => {
const nodeRecord = terminalNodeMap.get(terminalId);
if (nodeRecord === undefined) {
return;
}
terminalNodeMap.delete(terminalId);
if (nodeRecord.terminalId === terminalId) {
nodeRecord.terminalId = null;
}
nodeRecord.disposeInput();
nodeRecord.disposeInput = () => {};
nodeRecord.resizeObserver?.disconnect();
nodeRecord.resizeObserver = null;
nodeRecord.syncSize = () => {};
detachTerminalWebglRenderer(nodeRecord);
setNodeExitedState(nodeRecord, exitCode, signal);
renderCanvasSwitcher();
});
const removeTerminalCwdChangeListener = window.noteCanvas.onTerminalCwdChange(({ terminalId, cwd }) => {
const nodeRecord = terminalNodeMap.get(terminalId);
if (nodeRecord === undefined || typeof cwd !== "string" || cwd.length === 0) {
return;
}
nodeRecord.cwd = cwd;
scheduleAppSessionSave();
});
const removeWorkspaceDirectoryDataListener = window.noteCanvas.onWorkspaceDirectoryData((snapshot) => {
applyWorkspaceState(snapshot);
});
const removeToggleActiveTerminalMaximizeListener = window.noteCanvas.onToggleActiveTerminalMaximize(() => {
if (activeNodeRecord === null || activeNodeRecord.isRemoved || activeNodeRecord.canvas.id !== activeCanvasId) {
return;
}
setNodeMaximized(activeNodeRecord, !activeNodeRecord.isMaximized);
});
function isElement(value) {
return value instanceof Element;
}
function getCanvasById(canvasId) {
return canvasMap.get(canvasId) ?? null;
}
function getDefaultTerminalTitle(nodeRecord) {
const agentName = normalizeManagedAgentName(nodeRecord?.managedAgentName);
if (agentName !== null) {
return `${agentName} (${getManagedAgentRoleLabel()})`;
}
return `Terminal ${nodeRecord.id}`;
}
function normalizeTerminalTitle(value, fallbackTitle) {
if (typeof value !== "string") {
return fallbackTitle;
}
const trimmedValue = value.trim().slice(0, MAX_TERMINAL_TITLE_LENGTH);
return trimmedValue.length > 0 ? trimmedValue : fallbackTitle;
}
function normalizeCanvasName(value, fallbackName, excludedCanvasId = null) {
if (typeof value !== "string") {
return getUniqueCanvasName(fallbackName, excludedCanvasId);
}
const trimmedValue = value.trim().slice(0, MAX_CANVAS_NAME_LENGTH);
const baseName = trimmedValue.length > 0 ? trimmedValue : fallbackName;
return getUniqueCanvasName(baseName, excludedCanvasId);
}
function normalizeManagedAgentName(value) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function normalizeManagedAgentRole() {
return "agent";
}
function normalizeOptionalString(value) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function normalizeImportedSessionKey(value) {
return typeof value === "string" && /^[A-Za-z0-9_-]+$/u.test(value)
? value
: null;
}
function getManagedAgentRoleLabel() {
return "Agent";
}
function getTerminalNodeRoleLabel(nodeRecord) {
if (nodeRecord?.managedAgentName !== null && nodeRecord?.managedAgentName !== undefined) {
return getManagedAgentRoleLabel();
}
// Not an agentmux agent yet: outside the graph, cannot be asked or connected
// until adopted.
return "Solo";
}
function getManagedAgentNodeTitle(options = {}) {
const agentName = normalizeManagedAgentName(options.agentName);
const title = normalizeOptionalString(options.title);
if (agentName === null) {
return title ?? "";
}
if (options.isTitleCustomized === true && title !== null) {
return title;
}
return `${agentName} (${getManagedAgentRoleLabel()})`;
}
function isInitialTerminalTitleCustomized(options = {}) {
const title = normalizeOptionalString(options.title);
if (title === null) {
return false;
}
const agentName = normalizeManagedAgentName(options.managedAgentName);
if (agentName === null) {
return true;
}
return title !== agentName && title !== getManagedAgentNodeTitle({ agentName });
}
function getNodeSessionIdentifier(nodeRecord) {
return nodeRecord.backend === "tmux"
? (nodeRecord.tmuxSessionName ?? `termcanvas-${nodeRecord.sessionKey}`)
: nodeRecord.sessionKey;
}
async function copyTextToClipboard(text) {
if (typeof text !== "string" || text.length === 0) {
return false;
}
try {
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return true;
}
} catch {
// Fall back to a temporary selection-based copy when clipboard API is unavailable.
}
const fallbackTextArea = document.createElement("textarea");
fallbackTextArea.value = text;
fallbackTextArea.setAttribute("readonly", "readonly");
fallbackTextArea.style.position = "fixed";
fallbackTextArea.style.opacity = "0";
fallbackTextArea.style.pointerEvents = "none";
document.body.append(fallbackTextArea);
fallbackTextArea.select();
fallbackTextArea.setSelectionRange(0, fallbackTextArea.value.length);
try {
return document.execCommand("copy");
} catch {
return false;
} finally {
fallbackTextArea.remove();
}
}
function decodeOsc52ClipboardPayload(payload) {
if (typeof payload !== "string" || payload.length === 0) {
return null;
}
const estimatedBytes = Math.floor((payload.length * 3) / 4);
if (estimatedBytes > OSC52_CLIPBOARD_MAX_BYTES) {
return null;
}
try {
const binaryText = window.atob(payload);
const bytes = Uint8Array.from(binaryText, (character) => character.charCodeAt(0));
return new TextDecoder().decode(bytes);
} catch {
return null;
}
}
function handleOsc52ClipboardData(data, nodeRecord) {
if (nodeRecord?.backend !== "tmux" || typeof data !== "string") {
return false;
}
const separatorIndex = data.indexOf(";");
if (separatorIndex < 0) {
return true;
}
const payload = data.slice(separatorIndex + 1);
const text = decodeOsc52ClipboardPayload(payload);
if (text === null || text.length === 0) {
return true;
}
void copyTextToClipboard(text);
return true;
}
function registerTerminalClipboardBridge(terminal, nodeRecord) {
if (typeof terminal?.parser?.registerOscHandler !== "function") {
return;
}
terminal.parser.registerOscHandler(52, (data) => handleOsc52ClipboardData(data, nodeRecord));
}
function clampNodeDimension(value, minimum, fallback) {
if (!Number.isFinite(value)) {
return fallback;
}
return Math.max(minimum, Math.round(value));
}
function getNormalizedNodeSize(width, height) {
return {
width: clampNodeDimension(width, MIN_NODE_WIDTH, DEFAULT_NODE_WIDTH),
height: clampNodeDimension(height, MIN_NODE_HEIGHT, DEFAULT_NODE_HEIGHT)
};
}
function setBoardZoomIndicatorText(scale) {
if (!(boardZoomIndicator instanceof HTMLElement)) {
return;
}
boardZoomIndicator.textContent = `${Math.round((Number.isFinite(scale) ? scale : 1) * 100)}%`;
}
function showBoardZoomIndicator(scale) {
if (!(boardZoomIndicator instanceof HTMLElement)) {
return;
}
setBoardZoomIndicatorText(scale);
boardZoomIndicator.classList.add("is-visible");
if (zoomIndicatorTimeout !== 0) {
window.clearTimeout(zoomIndicatorTimeout);
}
zoomIndicatorTimeout = window.setTimeout(() => {
zoomIndicatorTimeout = 0;
boardZoomIndicator.classList.remove("is-visible");
}, ZOOM_INDICATOR_VISIBLE_MS);
}
function applyNodeSize(nodeRecord, width, height) {
const nextSize = getNormalizedNodeSize(width, height);
nodeRecord.width = nextSize.width;
nodeRecord.height = nextSize.height;
if (!nodeRecord.isMaximized) {
nodeRecord.element.style.width = `${nodeRecord.width}px`;
nodeRecord.element.style.height = `${nodeRecord.height}px`;
}
}
function getVisibleMaximizedNode() {
const activeCanvas = getActiveCanvas();
if (activeCanvas === null) {
return null;
}
return activeCanvas.nodes.find((nodeRecord) => nodeRecord.isMaximized) ?? null;
}
function applyCanvasFocusMode() {
const visibleMaximizedNode = FOCUSED_TERMINAL_MODE ? null : getVisibleMaximizedNode();
appShell?.classList.toggle("has-maximized-node", visibleMaximizedNode !== null);
board.classList.toggle("has-maximized-node", visibleMaximizedNode !== null);
if (boardFullscreenExitButton instanceof HTMLButtonElement) {
const exitLabel = visibleMaximizedNode === null
? "Exit terminal fullscreen"
: `Exit fullscreen for ${visibleMaximizedNode.titleText}`;
boardFullscreenExitButton.setAttribute("aria-label", exitLabel);
boardFullscreenExitButton.title = exitLabel;
}
const activeCanvas = getActiveCanvas();
if (activeCanvas === null) {
return;
}
activeCanvas.nodes.forEach((nodeRecord) => {
nodeRecord.element?.classList.toggle(
"is-muted-by-maximized-node",
visibleMaximizedNode !== null && nodeRecord !== visibleMaximizedNode
);
});
}
function updateNodeTitleInput(nodeRecord) {
if (!(nodeRecord.titleInput instanceof HTMLInputElement)) {
return;
}
nodeRecord.titleInput.value = nodeRecord.titleText;
nodeRecord.titleInput.title = nodeRecord.titleText;
nodeRecord.menuButton?.setAttribute("aria-label", `Terminal actions for ${nodeRecord.titleText}`);
nodeRecord.closeButton?.setAttribute("aria-label", `Close terminal ${nodeRecord.titleText}`);
nodeRecord.renameButton?.setAttribute("aria-label", `Rename terminal ${nodeRecord.titleText}`);
}
function setNodeTitleEditing(nodeRecord, isEditing) {
if (!(nodeRecord.titleInput instanceof HTMLInputElement)) {
return;
}
nodeRecord.isTitleEditing = isEditing;
nodeRecord.titleInput.readOnly = !isEditing;
nodeRecord.titleInput.tabIndex = isEditing ? 0 : -1;
nodeRecord.titleInput.classList.toggle("is-editing", isEditing);
nodeRecord.renameButton?.setAttribute("aria-pressed", String(isEditing));
}
function startNodeTitleEditing(nodeRecord) {
if (!(nodeRecord.titleInput instanceof HTMLInputElement)) {
return;
}
if (activeTitleEditorRecord !== null && activeTitleEditorRecord !== nodeRecord) {
activeTitleEditorRecord.titleInput?.blur();
}
setNodeTitleEditing(nodeRecord, true);
nodeRecord.titleInput.focus();
}
function commitNodeTitle(nodeRecord, rawTitle) {
const normalizedTitle = normalizeOptionalString(rawTitle);
const nextTitle = normalizeTerminalTitle(normalizedTitle, getDefaultTerminalTitle(nodeRecord));
nodeRecord.isTitleCustomized = normalizedTitle !== null;
nodeRecord.titleText = nextTitle;
updateNodeTitleInput(nodeRecord);
setNodeTitleEditing(nodeRecord, false);
syncMaximizeButton(nodeRecord);
renderTerminalStrip();
scheduleAppSessionSave();
}
function cancelNodeTitleEditing(nodeRecord) {
if (activeTitleEditorRecord === nodeRecord) {
activeTitleEditorRecord = null;
}
updateNodeTitleInput(nodeRecord);
setNodeTitleEditing(nodeRecord, false);
}
function syncMaximizeButton(nodeRecord) {
if (!(nodeRecord.maximizeButton instanceof HTMLButtonElement)) {
return;
}
const isMaximized = nodeRecord.isMaximized;
nodeRecord.maximizeButton.innerHTML = isMaximized
? '<svg class="terminal-node-control-icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M5.25 3.75h7v7"></path><path d="M10.75 12.25h-7v-7"></path><path d="M12.25 3.75 8.75 7.25"></path><path d="M3.75 12.25 7.25 8.75"></path></svg><span class="terminal-node-maximize-label">Exit fullscreen</span>'
: '<svg class="terminal-node-control-icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M3.75 6.25v-2.5h2.5"></path><path d="M12.25 9.75v2.5h-2.5"></path><path d="M3.75 3.75 7.25 7.25"></path><path d="M12.25 12.25 8.75 8.75"></path></svg>';
nodeRecord.maximizeButton.title = isMaximized ? "Exit fullscreen" : "Maximize terminal";
nodeRecord.maximizeButton.setAttribute(
"aria-label",
isMaximized ? `Exit fullscreen for ${nodeRecord.titleText}` : `Maximize ${nodeRecord.titleText}`
);
nodeRecord.maximizeButton.setAttribute("aria-pressed", String(isMaximized));
}
function setNodeMaximized(nodeRecord, shouldMaximize, options = {}) {
if (FOCUSED_TERMINAL_MODE) {
if (shouldMaximize && options.shouldSelect !== false && !nodeRecord.isRemoved) {
activateFocusedTerminalNode(nodeRecord);
}
applyCanvasFocusMode();
return;
}
const shouldSelect = options.shouldSelect !== false;
resetPointerInteractions();
if (shouldMaximize) {
nodeRecord.canvas.nodes.forEach((candidateRecord) => {
if (candidateRecord !== nodeRecord && candidateRecord.isMaximized) {
candidateRecord.isMaximized = false;
candidateRecord.element?.classList.remove("is-maximized");
positionNode(candidateRecord);
syncMaximizeButton(candidateRecord);
scheduleTerminalSizeSync([candidateRecord], { settle: true });
}
});
if (shouldSelect && shouldSelectTerminal({ reason: "maximize" })) {
setActiveNode(nodeRecord);
}
nodeRecord.isMaximized = true;
nodeRecord.element?.classList.add("is-maximized");
} else {
nodeRecord.isMaximized = false;
nodeRecord.element?.classList.remove("is-maximized");
}
positionNode(nodeRecord);
syncMaximizeButton(nodeRecord);
applyCanvasFocusMode();
scheduleTerminalSizeSync([nodeRecord], { settle: true });
requestAnimationFrame(() => {
if (!nodeRecord.isExited && nodeRecord.canvas.id === activeCanvasId) {
nodeRecord.terminal?.focus();
}
});
scheduleAppSessionSave();
}
function updateExitedOverlay(nodeRecord) {
if (!(nodeRecord.overlayTitle instanceof HTMLElement) || !(nodeRecord.overlayMeta instanceof HTMLElement)) {
return;
}
if (nodeRecord.isExited) {
const { exitCode, exitSignal } = nodeRecord;
const exitLabel = typeof exitCode === "number"
? `Exit ${exitCode}${exitSignal ? ` · ${exitSignal}` : ""}`
: exitSignal
? `Signal ${exitSignal}`
: "Shell ended";
nodeRecord.overlayTitle.textContent = "Shell exited";
nodeRecord.overlayMeta.textContent = `${exitLabel} · Reopen shell to continue here.`;
if (nodeRecord.reopenButton instanceof HTMLButtonElement) {
nodeRecord.reopenButton.textContent = nodeRecord.managedAgentName === null ? "Reopen shell" : "Resume agent";
}
nodeRecord.overlay.hidden = false;
} else {
nodeRecord.overlay.hidden = true;
}
}
function classifyNodeStatusState(text) {
const value = String(text ?? "").toLowerCase();
if (value.includes("exit") || value.includes("fail") || value.includes("ended")) {
return "exited";
}
if (value.includes("live") || value.includes("running") || value.includes("active") || value.includes("ready")) {
return "live";
}
return "pending";
}
function setTerminalNodeStatus(nodeRecord, text, explicitState) {
const label = typeof text === "string" && text.length > 0 ? text : "—";
let didChange = false;
if (nodeRecord.statusLabel) {
if (nodeRecord.statusLabel.textContent !== label) {
nodeRecord.statusLabel.textContent = label;
didChange = true;
}
} else if (nodeRecord.status) {
if (nodeRecord.status.textContent !== label) {
nodeRecord.status.textContent = label;
didChange = true;
}
}
const state = typeof explicitState === "string" && explicitState.length > 0
? explicitState
: classifyNodeStatusState(label);
if (nodeRecord.status) {
if (nodeRecord.status.dataset.state !== state) {
nodeRecord.status.dataset.state = state;
didChange = true;
}
if (nodeRecord.status.title !== label) {
nodeRecord.status.title = label;
didChange = true;
}
}
if (nodeRecord.element) {
if (nodeRecord.element.dataset.state !== state) {
nodeRecord.element.dataset.state = state;
didChange = true;
}
}
if (didChange) {
scheduleAttentionRefresh();
}
}
function getTerminalNodeStatusText(nodeRecord) {
if (nodeRecord.statusLabel) {
return nodeRecord.statusLabel.textContent;
}
return nodeRecord.status ? nodeRecord.status.textContent : "";
}
let attentionRefreshTimer = null;
let attentionCycleIndex = 0;
const notifiedAttentionKeys = new Set();
function scheduleAttentionRefresh() {
if (attentionRefreshTimer !== null) {
return;
}
attentionRefreshTimer = window.setTimeout(() => {
attentionRefreshTimer = null;
refreshAttentionState();
}, 150);
}
function getAttentionQueueNodes() {
const canvasRecord = getActiveCanvas();
if (canvasRecord === null) {
return [];
}
const activeNodes = canvasRecord.nodes.filter((nodeRecord) => !nodeRecord.isRemoved && nodeRecord.element !== null);
const queueIds = window.noteCanvasRendererNodeStatus.deriveAttentionQueue(
activeNodes.map((nodeRecord) => ({
id: nodeRecord.id,
isExited: nodeRecord.isExited,
exitCode: nodeRecord.exitCode,
attention: nodeRecord.managedAttention,
agentState: nodeRecord.managedAgentState,
runtimeState: nodeRecord.managedRuntimeState
}))
);
return queueIds
.map((queueId) => activeNodes.find((nodeRecord) => nodeRecord.id === queueId))
.filter((nodeRecord) => nodeRecord != null);
}