-
Notifications
You must be signed in to change notification settings - Fork 561
Expand file tree
/
Copy pathApp.vue
More file actions
2080 lines (1921 loc) · 75 KB
/
Copy pathApp.vue
File metadata and controls
2080 lines (1921 loc) · 75 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
<template>
<!-- Sidebar -->
<nav
ref="sidebarRef"
class="sidebar"
:class="{
docked: appStore.sidebarOpen,
'sidebar--drawer': isSidebarDrawer,
}"
:inert="!appStore.sidebarOpen"
:aria-hidden="appStore.sidebarOpen ? undefined : 'true'"
:aria-label="t('chrome.primaryNav')"
id="sidebar-nav"
>
<!-- Brand -->
<div class="sidebar-brand">
<div class="sidebar-brand-lockup">
<img class="sidebar-brand-mark" :src="brandMarkUrl" alt="" aria-hidden="true" />
<span class="sidebar-brand-text">OpenSquilla</span>
</div>
<button
ref="sidebarDockToggleRef"
class="sidebar-dock-toggle"
:aria-label="t('chrome.collapseSidebar')"
aria-controls="sidebar-nav"
:aria-expanded="appStore.sidebarOpen"
:aria-keyshortcuts="sidebarToggleAriaShortcut"
aria-describedby="sidebar-toggle-tip-expanded"
data-testid="sidebar-toggle-expanded"
@click="toggleDock('sidebar-button')"
>
<Icon name="sidebar-visible" :size="18" />
<span
id="sidebar-toggle-tip-expanded"
class="sidebar-toggle-tip sidebar-toggle-tip--sidebar"
role="tooltip"
>
<span>{{ t('chrome.toggleSidebar') }}</span>
<kbd v-if="sidebarToggleHint">{{ sidebarToggleHint }}</kbd>
</span>
</button>
</div>
<!-- Always-visible flat nav index. Bounded and self-scrolling under a
short viewport so it never squeezes Recents, which owns the elastic
space below; every destination stays a labelled text row. -->
<div class="sidebar-section sidebar-core" role="navigation" :aria-label="t('chrome.controlNav')">
<!-- New task leads the index: it opens a draft instantly against the
default agent (no picker to interrupt the flow) and reads as a row
rather than a boxed button so the sidebar keeps one rhythm. -->
<button
class="sidebar-new-session"
:title="newChatHint ? `${t('chrome.newTaskTitle')} (${newChatHint})` : t('chrome.newTaskTitle')"
@click="startNewChatInstant"
>
<Icon name="plus" :size="16" />
<span class="sidebar-new-session__label">{{ t('chrome.newTask') }}</span>
<!-- Badge tracks the configured binding and hides when the shortcut is
disabled (Settings → Keyboard), so it never advertises a dead key. -->
<kbd v-if="newChatHint" class="sidebar-kbd" aria-hidden="true">{{ newChatHint }}</kbd>
</button>
<!-- Overview / Skills & Channels / Cron, single-sourced from route
metadata so the rail, mobile drawer, and palette never drift. -->
<router-link
v-for="item in workNav"
:key="item.path"
:to="item.path"
class="sidebar-fn-item"
:class="{ 'is-active': isPrimaryNavActive(item.path) }"
:aria-current="isPrimaryNavActive(item.path) ? 'page' : undefined"
@click="handleNavClick"
>
<Icon :name="item.icon" :size="16" />
<span class="sidebar-fn-label">{{ item.title }}</span>
</router-link>
</div>
<SidebarSetupBanner />
<!-- Recent conversations (kept mounted while the file-tree view is
active so scroll/selection state survives the swap) -->
<SidebarConversations
v-show="sidebarView === 'tasks'"
:sections="sidebarSections"
:session-order="sidebarSessionOrder"
:error="sessionListError"
:loading="isLoading"
:loading-more="isLoadingMore"
:load-more-error="loadMoreError"
:has-more="hasMore"
:current-key="sidebarCurrentKey"
:contract-debug-enabled="contractDebugEnabled"
:search-hint="commandPaletteHint"
:can-manage-projects="rpcStore.canManageProjectWorkspaces"
:can-create-projects="rpcStore.canChooseProject"
@select="switchToSession"
@refresh="loadSidebarData"
@load-more="loadMoreSessions"
@rename="onRenameSession"
@delete="onDeleteSession"
@bulk-delete="onBulkDeleteSessions"
@reorder="onReorderSidebarSession"
@session-pin="onPinSidebarSession"
@new-chat="startNewChatInstant"
@new-project="openProjectCreator"
@new-project-task="startProjectTask"
@project-pin="onProjectPin"
@project-edit="openProjectEditor"
@view-workspace-files="viewWorkspaceFiles"
@project-delete-history="onProjectDeleteHistory"
@project-remove="onProjectRemove"
@search="openCommandPalette"
/>
<!-- Workspace file tree (swaps the conversation list in place) -->
<SidebarFileTree
v-if="fileTreeWorkspace"
:workspace="fileTreeWorkspace"
@close="closeWorkspaceFiles"
@preview="onFileTreePreview"
@attach="onFileTreeAttach"
/>
<!-- Fixed footer: settings + connection state -->
<div class="sidebar-foot">
<button
type="button"
class="sidebar-fn-item"
data-icon="settings"
@click="openSettings"
>
<Icon name="settings" :size="16" />
<span class="sidebar-fn-label">{{ t('chrome.settings') }}</span>
</button>
</div>
</nav>
<SidebarResizer
v-if="appStore.sidebarOpen && isSidebarResizable"
ref="sidebarResizerRef"
:enabled="appStore.sidebarOpen && isSidebarResizable"
:width="sidebarEffectiveWidth"
:min="SIDEBAR_MIN_WIDTH"
:max="sidebarDynamicMaximum"
:preference="appStore.sidebarWidthPreference.width"
:preference-source="appStore.sidebarWidthPreference.source"
@resize-start="handleSidebarResizeStart"
@preview="applySidebarPreview"
@commit="commitSidebarWidth"
@reset="resetSidebarWidth"
@collapse="collapseSidebarFromResize"
@cancel="applySidebarPreview"
@resize-end="handleSidebarResizeEnd"
/>
<!-- Drawer scrim is driven by the same runtime mode as JS focus/Escape logic. -->
<div
v-if="appStore.sidebarOpen && isSidebarDrawer"
class="sidebar-scrim"
role="presentation"
aria-hidden="true"
@click="closeSidebarDrawer"
/>
<CommandPalette
v-model:open="commandPaletteOpen"
:recents="sidebarSections"
@new-chat="onPaletteNewChat"
@open-settings="onPaletteOpenSettings"
@toggle-theme="onPaletteToggleTheme"
@select-session="onPaletteSelectSession"
/>
<!-- Main content -->
<div
id="app-main"
class="main"
:inert="appStore.sidebarOpen && isSidebarDrawer"
:class="{
docked: appStore.sidebarOpen,
'main--sidebar-drawer': isSidebarDrawer,
'main--sidebar-compact': sidebarLayoutMode === 'compact',
'main--chat': isChatRoute,
'main--chat-sidebar-collapsed': isChatRoute && !appStore.sidebarOpen,
'main--tabbar-hidden': mobileKeyboardOpen,
}"
>
<header ref="topbarRef" class="topbar" :class="{ 'topbar--chat': isChatRoute }">
<div class="topbar-left">
<!-- Sidebar toggle — visible when sidebar is collapsed -->
<button
v-show="!appStore.sidebarOpen"
ref="topbarSidebarToggleRef"
class="sidebar-dock-toggle topbar-toggle"
:aria-label="t('chrome.expandSidebar')"
aria-controls="sidebar-nav"
:aria-expanded="appStore.sidebarOpen"
:aria-keyshortcuts="sidebarToggleAriaShortcut"
aria-describedby="sidebar-toggle-tip-collapsed"
data-testid="sidebar-toggle-collapsed"
@click="toggleDock('topbar-button')"
>
<Icon name="sidebar-hidden" :size="18" />
<span id="sidebar-toggle-tip-collapsed" class="sidebar-toggle-tip" role="tooltip">
<span>{{ t('chrome.toggleSidebar') }}</span>
<kbd v-if="sidebarToggleHint">{{ sidebarToggleHint }}</kbd>
</span>
</button>
</div>
<!-- App owns the route header and its component tree. Chat only publishes
reactive state and commands through the typed route-header bridge. -->
<div
id="app-route-header"
class="topbar-route-header"
data-testid="route-header-host"
>
<ChatHeaderActions
v-if="isChatRoute"
v-show="chatRouteHeaderVisible"
ref="chatHeaderActionsRef"
:title="chatRouteHeaderTitle"
:copy-state="chatRouteHeaderCopyState"
:copy-icon="chatRouteHeaderCopyIcon"
:copy-live-text="chatRouteHeaderCopyLiveText"
:deliverable-count="chatRouteHeaderDeliverableCount"
:has-new-deliverable="chatRouteHeaderHasNewDeliverable"
:share-mode="chatRouteHeaderShareMode"
:shareable-message-count="chatRouteHeaderShareableMessageCount"
@open-deliverables="chatRouteHeader.invoke('openDeliverables')"
@start-share="chatRouteHeader.invoke('startShare')"
@copy-session-key="chatRouteHeader.invoke('copySessionKey')"
/>
</div>
<div
class="topbar-right"
:class="{ 'topbar-right--attention': appStore.approvalCount > 0 }"
>
<ChatSystemStatus
v-if="isChatRoute"
:layout="systemHeaderLayout"
:connection-state="effectiveConnectionState"
:connection-label="connectionStateLabel"
:approval-count="appStore.approvalCount"
:can-manage-connection="webConfigEnabled"
@open-connection="openConnectionSettings"
@open-approval="openBlockedApprovalSession"
@open-update="openDesktopRuntimeSettings"
/>
<template v-else>
<button
v-if="appStore.approvalCount > 0"
class="approval-inline"
@click="openBlockedApprovalSession"
:title="t('chrome.openBlockedSession')"
>
{{ t('chrome.approvalRequired') }}
</button>
<button
v-if="webConfigEnabled"
type="button"
class="conn-pill conn-pill--link"
:class="rpcStore.state"
:title="t('chrome.connectionTitle', { state: connectionStateLabel })"
:aria-label="t('chrome.manageConnection')"
@click="openConnectionSettings"
>{{ connectionStateLabel }}</button>
<span v-else class="conn-pill" :class="rpcStore.state">{{ connectionStateLabel }}</span>
<DesktopUpdateIndicator />
</template>
<!-- Opt-in (Settings → Appearance or the command palette); off by
default so the topbar stays music-free until asked for. -->
<BgmControl
v-if="bgmEnabled"
:presentation="isChatRoute && systemHeaderLayout !== 'wide' ? 'pause-only' : 'full'"
/>
<LanguageSwitcher />
<div class="theme-menu-wrap">
<button
ref="themeButtonRef"
class="btn btn--icon btn--ghost"
:title="t('chrome.theme')"
:aria-label="t('chrome.theme')"
aria-haspopup="menu"
:aria-expanded="themeMenuOpen"
@click.stop="themeMenuOpen = !themeMenuOpen"
>
<Icon :name="themeIconName" :size="16" />
</button>
<div
v-if="themeMenuOpen"
class="theme-menu"
role="menu"
:aria-label="t('chrome.theme')"
data-chat-topbar-popover="theme"
>
<button
v-for="opt in themeOptions"
:key="opt.mode"
type="button"
class="theme-menu__item"
role="menuitemradio"
:aria-checked="appStore.theme === opt.mode"
@click="pickTheme(opt.mode)"
>
<Icon :name="opt.icon" :size="15" />
<span>{{ opt.labelKey ? t(opt.labelKey) : opt.label }}</span>
<Icon v-if="appStore.theme === opt.mode" class="theme-menu__check" name="check" :size="14" />
</button>
<button
type="button"
class="theme-menu__item theme-menu__item--more"
role="menuitem"
:title="t('chrome.moreThemesHint')"
@click="openMoreThemes"
>
<Icon name="chevronRight" :size="15" />
<span>{{ t('chrome.moreThemes') }}</span>
<Icon v-if="isCustomThemeActive" class="theme-menu__check" name="check" :size="14" />
</button>
</div>
</div>
</div>
</header>
<div class="app-workspace">
<main
class="content"
:class="{ 'content--chat': isChatRoute }"
:data-skin="skinId || undefined"
:data-skin-variant="variants || undefined"
id="content"
>
<ErrorBoundary @error-captured="clearChatRouteHeaderAfterError">
<router-view v-slot="{ Component, route }">
<!-- out-in: one view in the DOM at a time, so pages never overlap (no
double-exposure, and never two composers/textareas mid-swap).
Console views are kept-alive, so the entering page is instant —
out-in no longer incurs the old remount/fetch "dead gap". -->
<template v-if="route.meta.routeTransition === 'none'">
<KeepAlive v-if="route.meta.keepAlive" :max="12">
<component :is="Component" :key="route.meta.viewKey || route.name" />
</KeepAlive>
<component v-else :is="Component" :key="route.meta.viewKey || route.name" />
</template>
<Transition v-else name="route-fade" mode="out-in">
<KeepAlive v-if="route.meta.keepAlive" :max="12">
<component :is="Component" :key="route.meta.viewKey || route.name" />
</KeepAlive>
<component v-else :is="Component" :key="route.meta.viewKey || route.name" />
</Transition>
</router-view>
</ErrorBoundary>
</main>
<AppWorkbench
:enabled="appStore.features.artifactWorkbench === true"
:workbench-resources-enabled="(
appStore.features.documentWorkbenchResources === true
|| appStore.features.artifactPromptAnnotations === true
)"
:prompt-annotations-enabled="appStore.features.artifactPromptAnnotations === true"
:route-active="isChatRoute"
:session-id="currentSessionKey"
:modal-blocked="workbenchModalBlocked"
/>
<ArtifactImageLightbox />
</div>
</div>
<!-- Mobile bottom tab bar (<=768px only; hides while the keyboard is up):
Chat, Sessions, Overview, then More for the flat drawer containing
Sessions / Overview / Skills & Channels / Cron and Settings. -->
<nav
class="mobile-tabbar"
:class="{ 'is-keyboard-open': mobileKeyboardOpen }"
:inert="appStore.sidebarOpen && isSidebarDrawer"
:aria-label="t('chrome.primaryMobile')"
>
<router-link
to="/chat"
class="mobile-tab"
:class="{ 'is-active': isNavActive('/chat') }"
@click="handleNavClick"
>
<Icon name="chat" :size="20" />
<span class="mobile-tab__label">{{ t('nav.chat') }}</span>
</router-link>
<router-link
to="/sessions"
class="mobile-tab"
:class="{ 'is-active': isNavActive('/sessions') }"
@click="handleNavClick"
>
<Icon name="sessions" :size="20" />
<span class="mobile-tab__label">{{ t('nav.sessions') }}</span>
<span v-if="appStore.approvalCount > 0" class="mobile-tab__badge">{{ appStore.approvalCount }}</span>
</router-link>
<router-link
to="/overview"
class="mobile-tab"
:class="{ 'is-active': isOverviewNavActive }"
@click="handleNavClick"
>
<Icon name="home" :size="20" />
<span class="mobile-tab__label">{{ t('nav.overview') }}</span>
</router-link>
<button
type="button"
class="mobile-tab"
:class="{ 'is-active': isMobileMoreActive }"
@click="openSidebarDrawer"
>
<Icon name="menu" :size="20" />
<span class="mobile-tab__label">{{ t('chrome.more') }}</span>
</button>
</nav>
<ToastHost />
<ConfirmModal />
<ProjectWorkspaceCreateDialog
v-if="rpcStore.canChooseProject"
:open="projectCreateOpen && !projectCreateConfirming && !projectSourcePickerOpen"
:name="projectCreateName"
:source-path="projectCreateSourcePath"
:busy="projectCreateBusy"
:source-picking="projectCreateSourcePicking"
@update:name="projectCreateName = $event"
@choose-source="chooseProjectSourceDirectory"
@close="closeProjectCreator"
@create="createProjectWorkspace"
/>
<ProjectWorkspacePickerDialog
v-if="rpcStore.canChooseProject"
:open="projectCreateOpen && projectSourcePickerOpen"
:enabled="rpcStore.canChooseProject"
:session-key="currentSessionKey || 'agent:main:webchat:workspace-picker'"
:initial-path="projectCreateSourcePath"
@close="projectSourcePickerOpen = false"
@choose="onProjectSourcePathChosen"
/>
<ProjectWorkspaceEditDialog
v-if="rpcStore.canManageProjectWorkspaces"
:open="Boolean(editingProject)"
:initial-name="editingProject?.name || ''"
:path="editingProject?.path || ''"
@close="editingProjectId = ''"
@save="onProjectRename"
/>
<UpdateBanner />
<!-- Single app-wide announcer for the pending-approval count. The nav badge
and topbar pill stay silent (no double-announce); this region carries the
only spoken update when the count changes. -->
<p class="app-approval-live" aria-live="polite" role="status">{{ approvalAnnouncement }}</p>
</template>
<script setup lang="ts">
import { computed, inject, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { routeTitle } from './router'
import { getPlatform } from '@/platform'
import { useAppStore, type ThemeMode, type PendingApproval } from './stores/app'
import { useRpcStore } from './stores/rpc'
import { SESSION_DIRECTORY_KEY } from './modules/sessionDirectory'
import { SESSION_DIRECTORY_CHANGES_KEY } from './modules/sessionDirectoryChanges'
import { SESSION_LIFECYCLE_KEY } from './modules/sessionLifecycle'
import { APPROVAL_CENTER_KEY, type ApprovalEvent, type ApprovalItem, type ApprovalSubscription } from './modules/approvalCenter'
import {
arrangeSidebarSections,
useSessions,
type SessionItem,
type SidebarSection,
type SidebarSectionRow,
} from './composables/useSessions'
import Icon from './components/Icon.vue'
import ErrorBoundary from './components/ErrorBoundary.vue'
import ToastHost from './components/ToastHost.vue'
import ConfirmModal from './components/ConfirmModal.vue'
import ProjectWorkspaceCreateDialog from './components/ProjectWorkspaceCreateDialog.vue'
import ProjectWorkspaceEditDialog from './components/ProjectWorkspaceEditDialog.vue'
import ProjectWorkspacePickerDialog from './components/ProjectWorkspacePickerDialog.vue'
import UpdateBanner from './components/UpdateBanner.vue'
import DesktopUpdateIndicator from './components/DesktopUpdateIndicator.vue'
import ChatSystemStatus from './components/chat/ChatSystemStatus.vue'
import ChatHeaderActions from './components/chat/ChatHeaderActions.vue'
import SidebarConversations from './components/SidebarConversations.vue'
import SidebarFileTree from './components/SidebarFileTree.vue'
import type { FileTreeWorkspace } from './stores/fileTree'
import { useWorkbenchStore } from './workbench/store'
import { createWorkspaceFileWorkbenchItem } from './workbench/workspaceFileItems'
import { requestWorkspaceFileAttach } from './workbench/workspaceFileAttachEvent'
import SidebarSetupBanner from './components/SidebarSetupBanner.vue'
import SidebarResizer from './components/SidebarResizer.vue'
import CommandPalette from './components/CommandPalette.vue'
import LanguageSwitcher from './components/LanguageSwitcher.vue'
import BgmControl from './components/BgmControl.vue'
import ArtifactImageLightbox from './components/chat/ArtifactImageLightbox.vue'
import AppWorkbench from './components/workbench/AppWorkbench.vue'
import { useBgm } from './composables/useBgm'
import { useDesktopUpdate } from './composables/useDesktopUpdate'
import { useSidebarLayout } from './composables/useSidebarLayout'
import { useSystemHeaderLayout } from './composables/useSystemHeaderLayout'
import { useDocumentEvent } from './composables/useDocumentEvent'
import { hasOpenDialogLayer, useDialogLayer } from './composables/useDialogA11y'
import {
provideChatTopbarPopoverCoordinator,
useChatTopbarPopoverCoordination,
} from './composables/useChatTopbarPopoverCoordinator'
import { provideArtifactImageLightbox } from './composables/chat/useArtifactImageLightbox'
import {
provideChatRouteHeaderBridge,
type ChatRouteHeaderHostHandle,
} from './composables/chat/useChatRouteHeaderBridge'
import { useAgentOptions } from './composables/useAgentOptions'
import { useSessionTaskAttention } from './composables/useSessionTaskAttention'
import { useToasts } from './composables/useToasts'
import { useConfirm } from './composables/useConfirm'
import { useProjectWorkspaces } from './composables/useProjectWorkspaces'
import { useFreshTaskDraft } from './composables/useFreshTaskDraft'
import { useNavigation } from './app/useNavigation'
import { useSurfaceSkin } from './themes/useSurfaceSkin'
import { themePickerOptions, getManifest } from './themes/registry'
import { normalizeAgentId } from './utils/chat/sessionKeys'
import { effectiveChatConnectionState } from './utils/chat/chatConnectionState'
import { reminderToastPreview } from './utils/cron/notifications'
import { installSessionNavigationDiagConsole, recordSessionNavigationDiag } from './utils/chat/sessionNavigationDiag'
import { isMacPlatform } from './utils/browser'
import { useShortcutsStore } from './stores/shortcuts'
import { bindingMatches, formatBinding } from './utils/keychord'
import { SIDEBAR_MIN_WIDTH, type SidebarWidthPreference } from './utils/sidebarLayout'
import { sidebarSessionOrderKeys } from './utils/sidebarDisplayProjection'
import {
dispatchLocalSessionsDeleted,
localSessionsDeletedDetail,
LOCAL_SESSIONS_DELETED_EVENT,
} from './utils/sessionSync'
import { activeTaskWasDeletedWithProjectHistory } from './utils/projectHistory'
import { createCoalescedRefresh } from './utils/coalescedRefresh'
import {
optionalSessionRpcAllowed,
optionalSessionRpcCallOptions,
} from './composables/chat/sessionBootstrapAdmission'
import { markCronFinishNotified } from './utils/cron/notifications'
import {
buildChatSessionTitles,
isSensibleChatTitle,
provideChatSessionTitles,
} from './composables/chat/useChatSessionTitles'
const appStore = useAppStore()
const rpcStore = useRpcStore()
const injectedSessionDirectory = inject(SESSION_DIRECTORY_KEY)
if (!injectedSessionDirectory) throw new Error('SessionDirectory was not provided')
const sessionDirectory = injectedSessionDirectory
const injectedSessionDirectoryChanges = inject(SESSION_DIRECTORY_CHANGES_KEY)
if (!injectedSessionDirectoryChanges) throw new Error('SessionDirectoryChanges was not provided')
const sessionDirectoryChanges = injectedSessionDirectoryChanges
const injectedSessionLifecycle = inject(SESSION_LIFECYCLE_KEY)
if (!injectedSessionLifecycle) throw new Error('SessionLifecycle was not provided')
const sessionLifecycle = injectedSessionLifecycle
const injectedApprovalCenter = inject(APPROVAL_CENTER_KEY)
if (!injectedApprovalCenter) throw new Error('ApprovalCenter was not provided')
const approvalCenter = injectedApprovalCenter
const workbenchStore = useWorkbenchStore()
const shortcutsStore = useShortcutsStore()
const artifactImageLightbox = provideArtifactImageLightbox()
const { t } = useI18n()
const $route = useRoute()
// Every transient control in the global topbar shares one active owner. The
// controls render on chat and non-chat routes, so route-scoped coordination
// would allow sibling menus such as Language and Theme to overlap.
const isChatRoute = computed(() => $route.path === '/chat' || $route.path === '/chat/new')
const topbarPopoverCoordinationEnabled = ref(true)
const topbarPopoverCoordinator = provideChatTopbarPopoverCoordinator(
topbarPopoverCoordinationEnabled,
)
const chatRouteHeader = provideChatRouteHeaderBridge()
const {
visible: chatRouteHeaderVisible,
title: chatRouteHeaderTitle,
copyState: chatRouteHeaderCopyState,
copyIcon: chatRouteHeaderCopyIcon,
copyLiveText: chatRouteHeaderCopyLiveText,
deliverableCount: chatRouteHeaderDeliverableCount,
hasNewDeliverable: chatRouteHeaderHasNewDeliverable,
shareMode: chatRouteHeaderShareMode,
shareableMessageCount: chatRouteHeaderShareableMessageCount,
} = chatRouteHeader.model
const chatHeaderActionsRef = ref<ChatRouteHeaderHostHandle | null>(null)
watch(chatHeaderActionsRef, host => chatRouteHeader.setHost(host), { flush: 'sync' })
watch(isChatRoute, active => {
if (!active) chatRouteHeader.clear()
}, { flush: 'sync' })
function clearChatRouteHeaderAfterError() {
chatRouteHeader.clear()
}
const sidebarRef = ref<HTMLElement | null>(null)
const sidebarDockToggleRef = ref<HTMLButtonElement | null>(null)
const topbarSidebarToggleRef = ref<HTMLButtonElement | null>(null)
const topbarRef = ref<HTMLElement | null>(null)
type SidebarResizerHandle = { cancel: () => boolean }
const sidebarResizerRef = ref<SidebarResizerHandle | null>(null)
const {
mode: sidebarLayoutMode,
dynamicMax: sidebarDynamicMaximum,
effectiveWidth: sidebarEffectiveWidth,
} = useSidebarLayout()
const isSidebarDrawer = computed(() => sidebarLayoutMode.value === 'drawer')
const isSidebarResizable = computed(() => sidebarLayoutMode.value === 'resizable')
const sidebarResizeActive = ref(false)
function setSidebarCssWidth(width: number) {
if (!Number.isFinite(width)) return
document.getElementById('app')?.style.setProperty('--sidebar-width', `${Math.round(width)}px`)
}
// Persisted/pre-set changes are infrequent. Pointer previews bypass App's
// reactive tree and write the same root custom property directly once per rAF.
watch(sidebarEffectiveWidth, width => {
if (!sidebarResizeActive.value) setSidebarCssWidth(width)
}, { immediate: true })
const APP_SESSION_SYNC_SOURCE = 'app-sidebar'
// Localized connection-state label for the topbar pill and its tooltip. The
// store state ('connected' | 'connecting' | 'disconnected') is a stable key, not
// display text; CSS uppercases the result (a no-op for CJK scripts).
const effectiveConnectionState = computed(() => effectiveChatConnectionState(
rpcStore.state,
appStore.chatLivePhase,
isChatRoute.value,
))
const connectionStateLabel = computed(() => t(
`chrome.connectionState.${effectiveConnectionState.value}`,
))
const router = useRouter()
// afterEach only fires on navigation, so a same-route language switch needs an
// explicit re-localize of the tab title.
watch(() => appStore.locale, () => {
document.title = `${routeTitle($route)} — OpenSquilla`
})
const {
allSessions,
sessionListError,
isLoading,
isLoadingMore,
loadMoreError,
hasMore,
loadSessions,
loadMoreSessions,
} = useSessions(sessionDirectory)
const { bottomRoutes, workNav } = useNavigation()
// Axis-B: the active expressive skin for the routed content area (meta.skin).
const { skinId, variants } = useSurfaceSkin()
const { pushToast } = useToasts()
const { confirm } = useConfirm()
const projectWorkspaces = useProjectWorkspaces()
const freshTaskDraft = useFreshTaskDraft()
const projectCreateOpen = ref(false)
const projectCreateName = ref('')
const projectCreateSourcePath = ref('')
const projectCreateBusy = ref(false)
const projectCreateSourcePicking = ref(false)
const projectCreateConfirming = ref(false)
const projectSourcePickerOpen = ref(false)
const editingProjectId = ref('')
const editingProject = computed(() =>
editingProjectId.value
? projectWorkspaces.byId.value.get(editingProjectId.value) || null
: null,
)
watch(
() => rpcStore.canManageProjectWorkspaces,
allowed => {
if (allowed) {
scheduleSessionRefresh()
return
}
projectCreateOpen.value = false
projectCreateName.value = ''
projectCreateSourcePath.value = ''
projectCreateBusy.value = false
projectCreateSourcePicking.value = false
projectCreateConfirming.value = false
projectSourcePickerOpen.value = false
editingProjectId.value = ''
},
)
// Feature-gated topbar music control; the singleton `enabled` ref is written by
// Settings → Appearance and the command palette.
const { enabled: bgmEnabled } = useBgm()
const desktopUpdate = useDesktopUpdate()
const webConfigEnabled = getPlatform().capabilities.hasWebConfig
interface AppCronRunFinishedPayload {
jobId?: string
jobName?: string
payloadKind?: string
runId?: string
sessionKey?: string
summary?: string
success?: boolean
}
let unsubscribeCronFinished: (() => void) | null = null
function handleCronRunFinished(payload: unknown) {
if (!payload || typeof payload !== 'object') return
const event = payload as AppCronRunFinishedPayload
const runId = typeof event.runId === 'string' ? event.runId : ''
const jobName = event.jobName?.trim() || t('cronSkills.jobs.unnamedTask')
markCronFinishNotified(runId)
if (event.success === false) {
pushToast(t('cronSkills.jobs.toastBackgroundFailed', { name: jobName }), {
tone: 'danger',
duration: 9_000,
})
return
}
const reminder = event.payloadKind === 'reminder'
? reminderToastPreview(event.summary)
: ''
if (reminder) {
const sessionKey = event.sessionKey?.trim() || ''
pushToast(t('cronSkills.jobs.toastBackgroundReminder', {
name: jobName,
reminder,
}), {
tone: 'ok',
duration: 10_000,
action: sessionKey
? {
label: t('cronSkills.jobs.toastViewReminder'),
onClick: () => switchToSession(sessionKey, 'cron.reminder_toast'),
}
: undefined,
})
return
}
pushToast(t('cronSkills.jobs.toastBackgroundComplete', { name: jobName }), {
tone: 'ok',
duration: 7_000,
})
}
installSessionNavigationDiagConsole()
// Shared agents.list state + fetch (singleton) for sidebar session metadata.
const { agents, loadAgents } = useAgentOptions(optionalSessionRpcCallOptions)
const mobileKeyboardOpen = ref(false)
const commandPaletteOpen = ref(false)
const localChatSessions = ref<Record<string, { effectiveAgentId: string; title: string; updatedAt: number }>>({})
// Pending optimistic renames, keyed by session key; cleared after the next list
// reload returns the backend's canonical title.
const renameOverrides = ref<Record<string, string>>({})
const chatSessionTitles = computed(() => (
buildChatSessionTitles(allSessions.value, renameOverrides.value)
))
provideChatSessionTitles(chatSessionTitles)
const brandMarkUrl = computed(() => {
if (import.meta.env.DEV) return '/opensquilla-mark.png'
const base = document.getElementById('opensquilla-data')?.dataset.basePath || '/control'
return `${base.replace(/\/$/, '')}/static/dist/opensquilla-mark.png`
})
// Display chords track the configurable bindings so the rail hint, the New chat
// badge, and the palette never drift from what the handler actually honours. A
// disabled shortcut yields an empty hint (the New chat badge then hides).
const isMac = isMacPlatform()
const commandPaletteHint = computed(() =>
formatBinding(shortcutsStore.effectiveBinding('command-palette'), isMac))
const newChatHint = computed(() =>
formatBinding(shortcutsStore.effectiveBinding('new-chat'), isMac))
const sidebarToggleBinding = computed(() => shortcutsStore.effectiveBinding('toggle-sidebar'))
const sidebarToggleHint = computed(() => formatBinding(sidebarToggleBinding.value, isMac))
const sidebarToggleAriaShortcut = computed(() => {
const binding = sidebarToggleBinding.value
if (!binding) return undefined
const parts: string[] = []
if (binding.primary) parts.push(isMac ? 'Meta' : 'Control')
if (binding.alt) parts.push('Alt')
if (binding.shift) parts.push('Shift')
parts.push(binding.key.length === 1 ? binding.key.toUpperCase() : binding.key)
return parts.join('+')
})
const themeIconName = computed(() => {
if (appStore.theme === 'system') return 'monitor'
const active = getManifest(appStore.resolvedTheme)
return active?.icon ?? (appStore.resolvedTheme === 'dark' ? 'moon' : 'sun')
})
const themeMenuOpen = ref(false)
useChatTopbarPopoverCoordination(
'theme',
themeMenuOpen,
topbarPopoverCoordinator,
)
const themeMenuIsTopmost = useDialogLayer(themeMenuOpen)
const themeButtonRef = ref<HTMLButtonElement | null>(null)
// The compact topbar menu deliberately lists only the basic modes (Light / Dark
// / System). Custom value themes live in Settings → Appearance, reached via the
// "More themes…" action below — see themePickerOptions({ scope }) in registry.ts.
const themeOptions = themePickerOptions({ scope: 'basic' })
// A custom value theme (chosen in Settings) is active but not shown in the basic
// topbar menu; mark "More themes…" instead of leaving no selection indicator.
const isCustomThemeActive = computed(
() => !themeOptions.some((o) => o.mode === appStore.theme),
)
function pickTheme(mode: ThemeMode) {
appStore.setTheme(mode)
themeMenuOpen.value = false
themeButtonRef.value?.focus()
}
// "More themes…": the full theme list lives in Settings → Appearance. Close the
// menu and deep-link straight to that section.
function openMoreThemes() {
themeMenuOpen.value = false
handleNavClick()
router.push('/settings/interface')
}
useDocumentEvent('click', (e) => {
if (!themeMenuOpen.value) return
const wrap = themeButtonRef.value?.closest('.theme-menu-wrap')
if (wrap && e.target instanceof Node && !wrap.contains(e.target)) {
themeMenuOpen.value = false
}
})
// Current session key from ChatView via URL
const currentSessionKey = computed(() => {
return ($route.query.session as string) || ''
})
const sessionTaskAttention = useSessionTaskAttention()
function currentSessionIsVisible(): boolean {
return (
$route.path === '/chat'
&& document.visibilityState === 'visible'
&& document.hasFocus()
)
}
function markCurrentSessionReadIfVisible() {
const sessionKey = currentSessionKey.value
if (sessionKey && currentSessionIsVisible()) {
sessionTaskAttention.markRead(sessionKey)
}
}
watch(currentSessionKey, markCurrentSessionReadIfVisible, {
flush: 'sync',
immediate: true,
})
// Chat layout applies to both the session view and the draft route.
const systemHeaderPressureCount = computed(() => (
Number(effectiveConnectionState.value !== 'connected')
+ Number(appStore.approvalCount > 0)
+ Number(desktopUpdate.visible.value)
+ Number(bgmEnabled.value)
))
const systemHeaderLayout = useSystemHeaderLayout({
target: topbarRef,
active: isChatRoute,
pressureCount: systemHeaderPressureCount,
})
const activeProjectDraftId = computed(() =>
$route.path === '/chat/new' ? String($route.query.project || '') : '',
)
const activeProjectDraftKey = computed(() => {
const workspaceId = activeProjectDraftId.value
if (!workspaceId) return ''
const request = freshTaskDraft.request.value
const requestId = request?.workspaceId === workspaceId ? request.id : 0
return `draft:project:${workspaceId}:${requestId}`
})
const sidebarCurrentKey = computed(() =>
currentSessionKey.value || activeProjectDraftKey.value,
)
watch(
[
currentSessionKey,
isChatRoute,
() => artifactImageLightbox.request.value?.sessionKey || '',
],
([sessionKey, chatRouteActive]) => {
const request = artifactImageLightbox.request.value
if (request && (!chatRouteActive || request.sessionKey !== sessionKey)) {
artifactImageLightbox.close()
}
},
{ flush: 'sync' },
)
// The Settings overlay (route-mounted dialog) is open on these routes. It owns
// its own Escape/focus, so App-level keyboard shortcuts defer to it. Both web
// and desktop mount the same overlay now (webConfigEnabled is true on both).
const settingsOverlayOpen = computed(() =>
webConfigEnabled && ($route.name === 'settings' || $route.name === 'settings-section'))
const workbenchModalBlocked = computed(() =>
commandPaletteOpen.value
|| themeMenuOpen.value
|| settingsOverlayOpen.value
|| (appStore.sidebarOpen && isSidebarDrawer.value))
const contractDebugEnabled = computed(() => appStore.features.contractDebug === true)
function isNavActive(path: string): boolean {
if (path === '/chat') return isChatRoute.value
return $route.path === path
}
// Overview owns the Status/Usage hub plus its diagnostic Logs route, while
// Skills fronts the Skills/Channels hub. Keep those active families disjoint so
// diagnostic routes never light an unrelated primary destination.
const OVERVIEW_NAV_PATHS = new Set(['/overview', '/usage', '/logs'])
const SKILLS_CHANNELS_HUB_PATHS = new Set(['/skills', '/channels'])
const MOBILE_MORE_PATHS = new Set(['/skills', '/channels', '/cron'])
const isOverviewNavActive = computed(() => OVERVIEW_NAV_PATHS.has($route.path))
const isSkillsChannelsHubActive = computed(() => SKILLS_CHANNELS_HUB_PATHS.has($route.path))
const isMobileMoreActive = computed(() =>
appStore.sidebarOpen || MOBILE_MORE_PATHS.has($route.path))
function isPrimaryNavActive(path: string): boolean {
if (path === '/usage') return isOverviewNavActive.value
if (path === '/skills') return isSkillsChannelsHubActive.value
return isNavActive(path)
}
function agentDisplayName(agentId: string): string {
const agent = agents.value.find(a => a.id === agentId)
return agent?.name || (agentId === 'main' ? 'Main Agent' : agentId)
}
// Raw session keys (agent:…:…) and bare UUIDs must never render in the sidebar.
function sidebarConversationTitle(item: SessionItem): string {
for (const candidate of [item.title, item.subtitle, item.groupLabel]) {
const text = String(candidate || '').trim()
if (isSensibleChatTitle(text)) return text
}
return t('shared.sidebar.untitledTask')
}
// A draft / current-session row the backend list does not yet carry. The
// sidebar arranger reads only a handful of fields off the SessionItem, so a
// synthetic chat row carries canonical defaults for the remaining fields.
function syntheticChatSession(
key: string,
effectiveAgentId: string,
title: string,
updatedAt: number,
project?: {
id: string
name: string
path: string
provisional?: boolean
},
): SessionItem {
return {
key,
title,
subtitle: '',
groupLabel: normalizeAgentId(effectiveAgentId),
workspace: project?.path,
workspaceId: project?.id,
workspaceLabel: project?.name,
workspaceDisplayPath: project?.path,
effectiveAgentId,
sessionKind: 'chat',
surface: 'webchat',
conversationKind: 'direct',
status: 'idle',
runStatus: 'idle',
runLabel: 'Idle',
messageCount: null,
updatedAt,
model: '',
parent: null,
provisional: project?.provisional,
forkedFromParent: false,
hasContractGaps: false,
}
}