@tano.page/workbench 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/package.json +50 -16
  2. package/src/App.vue +82 -752
  3. package/src/appearance/appearance.ts +14 -4
  4. package/src/appearance/components/ThemePresetPreview.vue +52 -8
  5. package/src/appearance/interface-font.ts +99 -0
  6. package/src/appearance/theme.ts +26 -10
  7. package/src/appearance/use-interface-font.ts +30 -0
  8. package/src/assets/mail-provider-icons/NOTICE.txt +27 -0
  9. package/src/assets/mail-provider-icons/aliyun-mail.svg +3 -0
  10. package/src/assets/mail-provider-icons/gmail.svg +1 -0
  11. package/src/assets/mail-provider-icons/icloud.svg +12 -0
  12. package/src/assets/mail-provider-icons/netease-126.svg +5 -0
  13. package/src/assets/mail-provider-icons/netease-163.svg +5 -0
  14. package/src/assets/mail-provider-icons/qq.svg +9 -0
  15. package/src/assets/mail-provider-icons/tencent-exmail.svg +4 -0
  16. package/src/assistant/agent-identities.ts +1 -97
  17. package/src/assistant/agent-task-context.ts +1 -54
  18. package/src/assistant/attachments.ts +1 -1
  19. package/src/assistant/completion.ts +1 -61
  20. package/src/assistant/components/AssistantChangeList.vue +98 -21
  21. package/src/assistant/components/AssistantPanel.vue +425 -8
  22. package/src/assistant/components/PluginToolProposalCard.vue +235 -0
  23. package/src/assistant/connection-actions.ts +237 -0
  24. package/src/assistant/document-mentions.ts +1 -33
  25. package/src/assistant/engine.ts +1 -532
  26. package/src/assistant/execution.ts +6 -33
  27. package/src/assistant/files.ts +5 -13
  28. package/src/assistant/hash.ts +1 -4
  29. package/src/assistant/inbox.ts +1 -148
  30. package/src/assistant/language.ts +10 -37
  31. package/src/assistant/mention-autocomplete.ts +69 -0
  32. package/src/assistant/plugin-bridge-builder.ts +146 -0
  33. package/src/assistant/prompts.ts +1 -58
  34. package/src/assistant/proposal-actions.ts +336 -0
  35. package/src/assistant/results.ts +20 -86
  36. package/src/assistant/store.ts +167 -327
  37. package/src/assistant/structures.ts +1 -155
  38. package/src/assistant/tasks.ts +8 -96
  39. package/src/assistant/tool-rules.ts +1 -7
  40. package/src/assistant/workspace-bridge.ts +1 -1
  41. package/src/composables/use-document-actions.ts +38 -20
  42. package/src/composables/use-file-tree-controller.ts +7 -12
  43. package/src/composables/use-workbench-help.ts +177 -0
  44. package/src/composables/use-workbench-history.ts +2 -4
  45. package/src/composables/use-workbench-lifecycle.ts +249 -0
  46. package/src/composables/use-workbench-modals.ts +6 -1
  47. package/src/composables/use-workbench-outline.ts +0 -5
  48. package/src/composables/use-workbench-settings.ts +185 -0
  49. package/src/composables/use-workbench-shortcuts.ts +40 -1021
  50. package/src/composables/use-workbench-views.ts +325 -0
  51. package/src/data-tables/data-tables.ts +1 -2
  52. package/src/documents/components/DocumentActionMenu.vue +279 -0
  53. package/src/documents/components/DocumentHistoryPanel.vue +3 -1
  54. package/src/documents/components/DocumentInspector.vue +168 -0
  55. package/src/documents/components/DocumentPane.vue +482 -0
  56. package/src/documents/description-merge.ts +1 -9
  57. package/src/features.ts +1 -0
  58. package/src/files/components/FileMetadataPanel.vue +49 -15
  59. package/src/fonts/Inter-Latin-Italic.woff2 +0 -0
  60. package/src/fonts/Inter-Latin.woff2 +0 -0
  61. package/src/fonts/TanoUISansSC-Bold.woff2 +0 -0
  62. package/src/fonts/TanoUISansSC-Medium.woff2 +0 -0
  63. package/src/fonts/TanoUISansSC-Regular.woff2 +0 -0
  64. package/src/help/help-milestones.ts +3 -5
  65. package/src/i18n/locale-catalogs.ts +7 -6
  66. package/src/i18n/locale-registry.ts +8 -6
  67. package/src/i18n/locales/de-DE.json +371 -3
  68. package/src/i18n/locales/en-US.json +371 -2
  69. package/src/i18n/locales/es-ES.json +371 -3
  70. package/src/i18n/locales/ja-JP.json +370 -2
  71. package/src/i18n/locales/zh-TW.json +370 -2
  72. package/src/mail/components/MailAccountDialog.vue +450 -0
  73. package/src/mail/components/MailComposerDialog.vue +326 -0
  74. package/src/mail/components/MailProviderIcon.vue +30 -0
  75. package/src/mail/components/MailWorkspaceView.vue +821 -0
  76. package/src/mail/components/SidebarMail.vue +134 -0
  77. package/src/mail/mail-avatar.ts +17 -0
  78. package/src/mail/mail-bridge.ts +68 -0
  79. package/src/mail/mail-calendar.ts +208 -0
  80. package/src/mail/mail-markdown.ts +195 -0
  81. package/src/mail/types.ts +226 -0
  82. package/src/objects/components/ObjectDetailModal.vue +1001 -0
  83. package/src/objects/content-references.ts +6 -56
  84. package/src/objects/wiki-links.ts +1 -48
  85. package/src/objects/workspace-objects.ts +3 -4
  86. package/src/plan-sync/types.ts +6 -3
  87. package/src/plans/calendar-interaction.ts +194 -0
  88. package/src/plans/calendar.ts +65 -9
  89. package/src/plans/components/CalendarAgendaView.vue +165 -0
  90. package/src/plans/components/CalendarDayPopover.vue +172 -39
  91. package/src/plans/components/CalendarFilterBar.vue +128 -0
  92. package/src/plans/components/CalendarMonthView.vue +224 -0
  93. package/src/plans/components/CalendarQuickCreateDialog.vue +269 -0
  94. package/src/plans/components/CalendarTimelineView.vue +517 -0
  95. package/src/plans/components/CalendarTopbarControls.vue +101 -0
  96. package/src/plans/components/CalendarView.vue +264 -748
  97. package/src/plans/components/CalendarYearView.vue +138 -0
  98. package/src/plans/components/PlanArchiveDialog.vue +295 -0
  99. package/src/plans/components/PlanConnectionsDialog.vue +1 -1
  100. package/src/plans/components/PlanDateField.vue +6 -4
  101. package/src/plans/components/PlanDetailPanel.vue +227 -32
  102. package/src/plans/components/PlanEventList.vue +16 -4
  103. package/src/plans/components/SidebarPlan.vue +22 -15
  104. package/src/plans/components/TaskRepeatControls.vue +169 -30
  105. package/src/plans/components/calendar-shared.css +192 -0
  106. package/src/plans/composables/use-calendar-interactions.ts +396 -0
  107. package/src/plans/composables/use-calendar-scroll.ts +420 -0
  108. package/src/plans/local-reminders.ts +149 -0
  109. package/src/plans/personal-plans.ts +10 -1
  110. package/src/plans/plan-date.ts +8 -1
  111. package/src/plans/plan-migration.ts +95 -0
  112. package/src/plans/recurrence.ts +95 -0
  113. package/src/plans/task-repeat.ts +8 -8
  114. package/src/plans/timeline-layout.ts +92 -0
  115. package/src/plugins/assistant-bridge.ts +520 -0
  116. package/src/plugins/attachment-reader.ts +3 -1
  117. package/src/plugins/cache-storage.ts +42 -2
  118. package/src/plugins/components/PluginAutomations.vue +3 -3
  119. package/src/plugins/components/PluginCatalogBrowser.vue +17 -8
  120. package/src/plugins/components/PluginChangeSummary.vue +16 -3
  121. package/src/plugins/components/PluginConnections.vue +1 -1
  122. package/src/plugins/components/PluginCustomView.vue +2 -2
  123. package/src/plugins/components/PluginDetailPage.vue +136 -57
  124. package/src/plugins/components/PluginDeveloperArea.vue +192 -0
  125. package/src/plugins/components/PluginDocumentSlot.vue +63 -0
  126. package/src/plugins/components/PluginExplorer.vue +21 -25
  127. package/src/plugins/components/PluginImportDialog.vue +410 -0
  128. package/src/plugins/components/PluginInstaller.vue +273 -288
  129. package/src/plugins/components/PluginListItem.vue +3 -0
  130. package/src/plugins/components/PluginMaintenance.vue +37 -34
  131. package/src/plugins/components/PluginRepositoryStorage.vue +4 -2
  132. package/src/plugins/components/PluginRuntimePanel.vue +3 -3
  133. package/src/plugins/components/PluginSettingsForm.vue +112 -0
  134. package/src/plugins/components/PluginStatusBar.vue +161 -0
  135. package/src/plugins/components/PluginSurface.vue +18 -6
  136. package/src/plugins/components/PluginUiDialog.vue +452 -0
  137. package/src/plugins/components/PluginsTabPage.vue +61 -0
  138. package/src/plugins/components/plugin-center.css +5 -0
  139. package/src/plugins/data.ts +9 -86
  140. package/src/plugins/editor-plugin-adapters.ts +169 -0
  141. package/src/plugins/excalidraw/bundle.tano-plugin.json +1 -1
  142. package/src/plugins/excalidraw/manifest.json +12 -1
  143. package/src/plugins/host.ts +662 -43
  144. package/src/plugins/native.ts +2 -10
  145. package/src/plugins/overlay-mapping.ts +125 -0
  146. package/src/plugins/packages.ts +73 -1
  147. package/src/plugins/plugin-data.ts +2 -3
  148. package/src/plugins/plugin-permissions.ts +57 -0
  149. package/src/plugins/plugin-rpc-router.ts +558 -0
  150. package/src/plugins/plugin-sdk.ts +1 -94
  151. package/src/plugins/plugin-ui-dialogs.ts +167 -0
  152. package/src/plugins/policy.ts +53 -3
  153. package/src/plugins/presentation-preview/bundle.tano-plugin.json +1 -1
  154. package/src/plugins/presentation-preview/manifest.json +2 -1
  155. package/src/plugins/queries.ts +1 -73
  156. package/src/plugins/sandbox.ts +15 -1
  157. package/src/plugins/use-plugin-actions.ts +67 -20
  158. package/src/plugins/user-plugins.ts +254 -0
  159. package/src/plugins/view-header.ts +2 -7
  160. package/src/plugins/word-preview/bundle.tano-plugin.json +1 -1
  161. package/src/plugins/word-preview/manifest.json +13 -1
  162. package/src/plugins/workbench.ts +175 -2
  163. package/src/plugins/worker.js +105 -8
  164. package/src/plugins/workspace-plugin-runtime.ts +23 -7
  165. package/src/plugins/workspace-plugins.ts +212 -21
  166. package/src/runtime.ts +103 -4
  167. package/src/settings/components/SettingsAppearancePage.vue +46 -0
  168. package/src/settings/components/SettingsDocumentsPage.vue +0 -1
  169. package/src/settings/components/SettingsPanel.vue +8 -3
  170. package/src/settings/components/WorkbenchSettings.vue +20 -7
  171. package/src/settings/components/settings-context.ts +1 -1
  172. package/src/settings/components/settings-search.ts +2 -3
  173. package/src/settings/settings-tab.ts +1 -0
  174. package/src/shell/command-palette.ts +3 -3
  175. package/src/shell/components/EditorToolbar.vue +8 -9
  176. package/src/shell/components/EditorTools.vue +1 -5
  177. package/src/shell/components/PaneTopbar.vue +393 -0
  178. package/src/shell/components/SelectionToolbar.vue +0 -2
  179. package/src/shell/components/SidebarNavigation.vue +22 -2
  180. package/src/shell/components/WorkbenchContextMenus.vue +58 -34
  181. package/src/shell/components/WorkbenchModals.vue +47 -62
  182. package/src/shell/components/WorkbenchPanes.vue +371 -1342
  183. package/src/shell/components/WorkbenchSidebar.vue +486 -0
  184. package/src/shell/components/WorkspaceBreadcrumb.vue +6 -14
  185. package/src/shell/components/WorkspaceViewSwitcher.vue +12 -7
  186. package/src/shell/pane-registry.ts +69 -0
  187. package/src/shell/use-surface-dismissal.ts +219 -0
  188. package/src/shell/use-workbench-commands.ts +599 -0
  189. package/src/shell/use-workbench-keybindings.ts +337 -0
  190. package/src/shell/use-workbench.ts +531 -1153
  191. package/src/shell/workbench-async-components.ts +14 -5
  192. package/src/shell/workbench-context.ts +30 -3
  193. package/src/stores/mail.ts +414 -0
  194. package/src/stores/plan-sync.ts +2 -1
  195. package/src/stores/plans.ts +2 -9
  196. package/src/stores/workspace-document-io.ts +807 -0
  197. package/src/stores/workspace-file-ops.ts +1 -1
  198. package/src/stores/workspace-knowledge.ts +2 -114
  199. package/src/stores/workspace-lifecycle.ts +459 -0
  200. package/src/stores/workspace-plugins-state.ts +254 -259
  201. package/src/stores/workspace-session.ts +287 -0
  202. package/src/stores/workspace-tabs-layout.ts +6 -44
  203. package/src/stores/workspace-types.ts +50 -0
  204. package/src/stores/workspace.ts +184 -1363
  205. package/src/styles/agent-diff-modals.css +0 -7
  206. package/src/styles/dark-theme.css +3 -3
  207. package/src/styles/inspector.css +0 -59
  208. package/src/styles/layout-themes.css +346 -0
  209. package/src/styles/mail.css +1568 -0
  210. package/src/styles/mobile.css +2 -2
  211. package/src/styles/recent-and-media.css +0 -17
  212. package/src/styles/theme-contract.css +3 -3
  213. package/src/styles/workbench-shell.css +110 -17
  214. package/src/styles/workspace-states.css +9 -33
  215. package/src/styles.css +0 -1
  216. package/src/tabs/components/DesktopTabs.vue +19 -14
  217. package/src/tabs/components/NewTabPicker.vue +10 -4
  218. package/src/tabs/tab-label.ts +0 -1
  219. package/src/windows/AuxiliaryWindows.vue +2 -2
  220. package/src/windows/use-window-event-bridge.ts +152 -0
  221. package/src/workspace/components/TemplateLibrary.vue +1 -1
  222. package/src/workspace/components/WorkspaceGeneralSettings.vue +0 -13
  223. package/src/workspace/components/WorkspaceIconPicker.vue +30 -7
  224. package/src/workspace/components/WorkspacePickerMenu.vue +317 -0
  225. package/src/workspace/workspace-comments.ts +11 -151
  226. package/src/workspace/workspace-welcome.ts +1 -1
  227. package/src/assistant/locales/de-DE.json +0 -126
  228. package/src/assistant/locales/en-US.json +0 -126
  229. package/src/assistant/locales/es-ES.json +0 -126
  230. package/src/assistant/locales/ja-JP.json +0 -126
  231. package/src/assistant/locales/zh-CN.json +0 -126
  232. package/src/assistant/locales/zh-TW.json +0 -126
  233. package/src/assistant/task-prompts.json +0 -39
  234. package/src/documents/components/FormulaMenu.vue +0 -50
  235. package/src/files/components/FileDatabasePage.vue +0 -152
  236. package/src/files/components/FolderHomeIcon.vue +0 -12
  237. package/src/objects/components/ObjectDatabasePage.vue +0 -100
  238. package/src/objects/components/ObjectPanel.vue +0 -554
  239. package/src/plans/components/PersonalPlanDialog.vue +0 -105
  240. package/src/shell/components/WorkspaceViewPage.vue +0 -127
  241. package/src/shell/components/WorkspaceViewTab.vue +0 -24
  242. package/src/styles/object-panel.css +0 -163
  243. package/src/workspace/components/GitInspectionPanel.vue +0 -35
  244. package/src/workspace/components/WorkspaceSyncPanel.vue +0 -50
  245. package/src/workspace/welcome-slogans.ts +0 -11
  246. package/src/workspace/workspace-git.ts +0 -35
  247. package/src/workspace/workspace-sync.ts +0 -46
  248. package/src/workspace/workspace-views.ts +0 -48
@@ -1,83 +1,38 @@
1
- import { computed, onScopeDispose, ref, watch, type ComputedRef } from 'vue';
1
+ import { computed, onScopeDispose, ref } from 'vue';
2
2
  import { defineStore } from 'pinia';
3
3
  import {
4
- basename,
5
- documentLayoutPath,
6
4
  FileRegistry,
7
- isDataTableFilePath,
8
- isMarkdown,
9
- isWorkspaceInternalPath,
10
- parentPath,
11
- parseDocumentLayout,
12
- validatePath,
13
5
  type DataTable,
14
6
  type FileEntry,
15
- type PluginManifest,
16
7
  type RecentWorkspace,
17
- type TableLayout,
18
8
  type Workspace,
19
- type WorkspaceLayout,
20
- type WorkspaceSession,
21
9
  } from '@tano/protocol';
22
10
  import { createWorkspaceAssistantBridge } from '../assistant/workspace-bridge';
23
11
  import { createDataTableController } from '../data-tables/data-table-controller';
24
- import { isTableTab, TABLES_TAB_ID, tableFileId, tableTabId } from '../data-tables/data-tables';
25
- import { GRAPH_TAB_ID } from '../documents/document-graph';
26
12
  import { useDocumentIndex } from '../documents/document-index';
27
13
  import { createDocumentSession, documentDirty as dirty, type OpenDocument } from '../documents/document-session';
28
- import { indexFolderHomes } from '../files/folder-home';
29
- import { recordHelpCompleted } from '../help/help-checklist';
30
- import { createHelpEditQueue } from '../help/help-edit-queue';
31
14
  import { optimisticFiles } from '../files/optimistic-files';
32
- import { layoutPanes, restoreLayout } from '../shell/pane-layout';
33
- import type { PluginWorkbenchView } from '../plugins/workbench';
34
- import { useWorkbenchRuntime, type WorkbenchViewTab } from '../runtime';
35
- import { SessionJournal } from '../shell/session-journal';
36
- import {
37
- DocumentLayoutConflict,
38
- layoutDirty,
39
- loadDocumentLayout,
40
- saveDocumentLayout,
41
- } from '../workspace/workspace-document-layout';
15
+ import { createHelpEditQueue } from '../help/help-edit-queue';
16
+ import type { InstalledObjectPlugin } from '../plugins/workspace-plugins';
17
+ import { useWorkbenchRuntime } from '../runtime';
18
+ import { layoutDirty } from '../workspace/workspace-document-layout';
42
19
  import { WorkspaceLifecycle } from '../workspace/workspace-lifecycle';
43
- import { PLUGINS_TAB_ID, type InstalledObjectPlugin } from '../plugins/workspace-plugins';
44
- import { readStartupWorkspace, rememberStartupWorkspace } from '../workspace/workspace-startup';
45
- import type { WorkspaceViewRecord } from '../workspace/workspace-views';
46
- import { addWorkspaceWelcome, workspaceWelcomePath } from '../workspace/workspace-welcome';
20
+ import { createWorkspaceDocumentIO } from './workspace-document-io';
47
21
  import { createWorkspaceFileOps } from './workspace-file-ops';
48
22
  import { createWorkspaceKnowledge } from './workspace-knowledge';
23
+ import { createWorkspaceLifecycle } from './workspace-lifecycle';
49
24
  import { createWorkspacePluginsState } from './workspace-plugins-state';
50
25
  import { createWorkspacePolicy } from './workspace-policy';
26
+ import { createWorkspaceSession } from './workspace-session';
51
27
  import { createWorkspaceTabsLayout } from './workspace-tabs-layout';
28
+ import type {
29
+ Activity,
30
+ DocumentTab,
31
+ WorkspaceLifecycleHooks,
32
+ WorkspaceLoadingState,
33
+ } from './workspace-types';
52
34
 
53
- export type { OpenDocument } from '../documents/document-session';
54
-
55
- export interface DocumentTab {
56
- id: string;
57
- path: string;
58
- blank: boolean;
59
- graph: boolean;
60
- plugins: boolean;
61
- calendar: boolean;
62
- view?: WorkbenchViewTab;
63
- workspaceView?: WorkspaceViewRecord;
64
- directory?: { path: string; name: string; missing: boolean };
65
- pluginView?: PluginWorkbenchView;
66
- pluginDetail?: PluginManifest;
67
- document?: OpenDocument;
68
- attachmentPreview: boolean;
69
- attachment?: FileEntry;
70
- dataTable?: { name: string; dirty: boolean; icon?: string };
71
- }
72
-
73
- export interface Activity {
74
- id: string;
75
- label: string;
76
- detail: string;
77
- time: number;
78
- kind: 'external' | 'save' | 'conflict' | 'file';
79
- change?: { before: string; after: string };
80
- }
35
+ export type { Activity, DocumentTab, OpenDocument };
81
36
 
82
37
  export const useWorkspaceStore = defineStore('workspace', () => {
83
38
  const helpEdits = createHelpEditQueue();
@@ -94,27 +49,20 @@ export const useWorkspaceStore = defineStore('workspace', () => {
94
49
  const documents = ref<OpenDocument[]>([]);
95
50
  const documentIndex = useDocumentIndex(documents);
96
51
  const tabIds = ref<string[]>([]);
97
- // Most tabs use the file/page id directly. A context-menu "open in new tab"
98
- // request can target an already open file, though, so those additional tab
99
- // instances need an id of their own while continuing to share the open
100
- // document and its draft.
101
52
  const tabAliases = ref(new Map<string, string>());
102
53
  const activeId = ref('');
103
54
  const installedPlugins = ref<InstalledObjectPlugin[]>([]);
104
55
  const activePluginSidebar = ref('');
105
56
 
106
57
  const busy = ref(false);
107
- // Folder selection keeps the current page visible. Presentation switches only
108
- // once a target is confirmed, retaining the old session for flush/recovery.
109
58
  const openingWorkspace = ref(false);
110
- const workspaceLoading = ref({
59
+ const workspaceLoading = ref<WorkspaceLoadingState>({
111
60
  files: false,
112
61
  session: false,
113
62
  settings: false,
114
63
  tables: false,
115
64
  plugins: false,
116
65
  objects: false,
117
- views: false,
118
66
  relations: false,
119
67
  capabilities: false,
120
68
  });
@@ -126,16 +74,9 @@ export const useWorkspaceStore = defineStore('workspace', () => {
126
74
  const recent = ref<RecentWorkspace[]>([]);
127
75
  const sessionError = ref('');
128
76
 
129
- let saveTimer: ReturnType<typeof setTimeout> | undefined;
130
77
  let chain: Promise<unknown> = Promise.resolve();
131
78
  let disposed = false;
132
- let sessionReady = false;
133
- let sessionBlocked = false;
134
- let beforeSwitch: (() => Promise<void>) | undefined;
135
- let beforeWorkspaceChange: (() => Promise<void>) | undefined;
136
- let afterSwitch: (() => Promise<void>) | undefined;
137
- let beforeCloseDocument: ((id: string) => Promise<void>) | undefined;
138
- let fileOpenRevision = 0;
79
+ const hooks: WorkspaceLifecycleHooks = {};
139
80
 
140
81
  function serial<T>(task: () => Promise<T>): Promise<T> {
141
82
  const next = chain.then(task, task);
@@ -149,7 +90,6 @@ export const useWorkspaceStore = defineStore('workspace', () => {
149
90
  kind: Activity['kind'],
150
91
  change?: Activity['change'],
151
92
  ) {
152
- // Session history is bounded; larger versions remain in files/server history.
153
93
  const preview =
154
94
  change && change.before.length + change.after.length <= 256 * 1024 ? change : undefined;
155
95
  activities.value.unshift({
@@ -172,7 +112,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
172
112
  }
173
113
 
174
114
  async function loadWorkspacePart(
175
- part: keyof typeof workspaceLoading.value,
115
+ part: keyof WorkspaceLoadingState,
176
116
  load: () => Promise<unknown>,
177
117
  ) {
178
118
  try {
@@ -207,7 +147,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
207
147
  const workspaceLifecycle = new WorkspaceLifecycle(
208
148
  {
209
149
  watch: (changed) => adapter.watch(changed),
210
- refresh,
150
+ refresh: () => lifecycle.refresh(),
211
151
  report,
212
152
  available: () => !!workspace.value && !disposed,
213
153
  },
@@ -225,7 +165,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
225
165
  }
226
166
  if (!isDemo && !isWeb && !mobile && typeof window !== 'undefined') {
227
167
  const refreshRecentOnFocus = () => {
228
- void refreshWorkspaces();
168
+ void lifecycle.refreshWorkspaces();
229
169
  };
230
170
  window.addEventListener('focus', refreshRecentOnFocus);
231
171
  onScopeDispose(() => window.removeEventListener('focus', refreshRecentOnFocus));
@@ -236,8 +176,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
236
176
  layoutDirty(doc.tableLayout) &&
237
177
  doc.tableLayout.conflict?.draft !== JSON.stringify(doc.tableLayout.file);
238
178
 
239
- // Domain modules composed cleanly in acyclic setup order:
240
- // 1. Policy (workspace settings & capability rules)
179
+ // Domain modules composed in acyclic order:
241
180
  const policy = createWorkspacePolicy({
242
181
  adapter,
243
182
  workspace,
@@ -247,7 +186,6 @@ export const useWorkspaceStore = defineStore('workspace', () => {
247
186
  report,
248
187
  });
249
188
 
250
- // 2. Knowledge (objects, relations, workspace views/databases, metadata, templates, repeats, references)
251
189
  const knowledge = createWorkspaceKnowledge({
252
190
  adapter,
253
191
  workspace,
@@ -262,10 +200,8 @@ export const useWorkspaceStore = defineStore('workspace', () => {
262
200
  loadWorkspacePart,
263
201
  refreshPlugins: (current) => plugins.refreshPlugins(current),
264
202
  disposePluginExecutor: () => plugins.pluginExecutor.dispose(),
265
- openWorkspaceView: (id, options) => openWorkspaceView(id, options),
266
203
  });
267
204
 
268
- // 3. Plugins state (plugin runtime, host/executor/developer, pluginCall, OAuth/connections/packages)
269
205
  const plugins = createWorkspacePluginsState({
270
206
  adapter,
271
207
  runtime,
@@ -288,20 +224,18 @@ export const useWorkspaceStore = defineStore('workspace', () => {
288
224
  writable,
289
225
  scheduleRefresh,
290
226
  refreshObjects: knowledge.refreshObjects,
291
- openInternal: (file, replaceId, current) => openInternal(file, replaceId, current),
227
+ openInternal: (file, replaceId, current) => docIO.openInternal(file, replaceId, current),
292
228
  saveInternal: (doc) => saveInternal(doc),
293
229
  ensureTabNavigation: (tabId, targetId) => tabsLayout.ensureTabNavigation(tabId, targetId),
294
230
  touchNavigation: () => tabsLayout.touchNavigation(),
295
231
  });
296
232
 
297
- // 4. Tabs, split/multi-window layouts & tab navigation history
298
233
  const tabsLayout = createWorkspaceTabsLayout({
299
234
  workspace,
300
235
  fileRegistry,
301
236
  documents,
302
237
  documentIndex,
303
238
  dataTables,
304
- workspaceViews: knowledge.workspaceViews,
305
239
  installedPlugins,
306
240
  pluginViews: plugins.pluginViews,
307
241
  activePluginSidebar,
@@ -313,14 +247,13 @@ export const useWorkspaceStore = defineStore('workspace', () => {
313
247
  busy,
314
248
  displayPath,
315
249
  layoutPending,
316
- flush,
317
- close,
318
- openAttachment,
319
- openPageTab,
320
- openFile,
250
+ flush: () => docIO.flush(),
251
+ close: (id) => docIO.close(id),
252
+ openAttachment: (file, options) => docIO.openAttachment(file, options),
253
+ openPageTab: (id, options) => docIO.openPageTab(id, options),
254
+ openFile: (file, options) => docIO.openFile(file, options),
321
255
  });
322
256
 
323
- // 5. Assistant bridge & document suggestions
324
257
  const assistantBridge = createWorkspaceAssistantBridge({
325
258
  adapter,
326
259
  workspace,
@@ -350,7 +283,6 @@ export const useWorkspaceStore = defineStore('workspace', () => {
350
283
  activity,
351
284
  });
352
285
 
353
- // 6. Document session reconciliation/save
354
286
  const { reconcile, save: saveInternal } = createDocumentSession({
355
287
  adapter,
356
288
  confirmCreation: (doc) => fileOps.confirmCreation(doc),
@@ -364,7 +296,6 @@ export const useWorkspaceStore = defineStore('workspace', () => {
364
296
  },
365
297
  });
366
298
 
367
- // 7. File & folder mutation operations
368
299
  const fileOps = createWorkspaceFileOps({
369
300
  adapter,
370
301
  mobile,
@@ -396,49 +327,108 @@ export const useWorkspaceStore = defineStore('workspace', () => {
396
327
  writable,
397
328
  report,
398
329
  activity,
399
- flush,
400
- flushDocuments,
401
- openInternal,
330
+ flush: () => docIO.flush(),
331
+ flushDocuments: () => docIO.flushDocuments(),
332
+ openInternal: (file, replaceId, current) => docIO.openInternal(file, replaceId, current),
402
333
  reconcile,
403
- hydrateDocumentLayout,
334
+ hydrateDocumentLayout: (doc) => docIO.hydrateDocumentLayout(doc),
404
335
  });
405
336
 
406
- // Data table tab helpers
407
- function dataTableFileId(id: string) {
408
- if (workspace.value?.files.some((file) => file.id === id && isDataTableFilePath(file.path)))
409
- return id;
410
- // Resolve previously shared links, whose suffix was the table's embedded identity.
411
- return dataTables.records.value.find((record) => record.table.id === id)?.fileId ?? id;
412
- }
413
- async function openDataTable(
414
- id?: string,
415
- options?: { newTab?: boolean; historyIndex?: number },
416
- ) {
417
- if (!id) {
418
- tabsLayout.createBlankTab();
419
- return;
420
- }
421
- await openPageTab(tableTabId(dataTableFileId(id)), options);
422
- }
423
- async function createDataTable(template: 'blank' | 'parts' = 'blank', parent = '') {
424
- const id = await dataTables.create(template, undefined, parent);
425
- recordHelpCompleted('data-table');
426
- await openDataTable(id);
427
- return id;
428
- }
429
- async function renameDataTable(id: string, name: string) {
430
- const file = workspace.value?.files.find(
431
- (file) => file.id === id && isDataTableFilePath(file.path),
432
- );
433
- if (!file) throw new Error('数据表文件已不存在');
434
- const path = `${parentPath(file.path) ? `${parentPath(file.path)}/` : ''}${name.trim().normalize('NFC')}.table.json`;
435
- if (!name.trim() || /[\\/]/.test(name)) throw new Error('请输入有效的文件名称');
436
- const error = validatePath(path);
437
- if (error) throw new Error(error);
438
- if (path !== file.path) await fileOps.renameEntry(file, path);
439
- }
337
+ const session = createWorkspaceSession({
338
+ adapter,
339
+ workspace,
340
+ fileRegistry,
341
+ documents,
342
+ documentIndex,
343
+ dataTables,
344
+ tabsLayout,
345
+ tabIds,
346
+ tabAliases,
347
+ activeId,
348
+ workspaceLoading,
349
+ restoringDocuments,
350
+ sessionError,
351
+ dataTableFileId: (id) => docIO.dataTableFileId(id),
352
+ loadWorkspacePart,
353
+ readOpenDocument: (file) => docIO.readOpenDocument(file),
354
+ openInternal: (file, replaceId, current) => docIO.openInternal(file, replaceId, current),
355
+ hydrateDocumentLayout: (doc) => docIO.hydrateDocumentLayout(doc),
356
+ reconcile,
357
+ saveInternal,
358
+ activity,
359
+ report,
360
+ });
361
+
362
+ const docIO = createWorkspaceDocumentIO({
363
+ adapter,
364
+ workspace,
365
+ fileRegistry,
366
+ fileMutations,
367
+ documents,
368
+ documentIndex,
369
+ dataTables,
370
+ workspaceSettings: policy.workspaceSettings,
371
+ referenceTargets: knowledge.referenceTargets,
372
+ tabIds,
373
+ activeId,
374
+ busy,
375
+ openingDocuments,
376
+ plugins,
377
+ tabsLayout,
378
+ assistantBridge,
379
+ fileOps,
380
+ helpEdits,
381
+ journal: session.journal,
382
+ hooks,
383
+ isDisposed: () => disposed,
384
+ layoutPending,
385
+ serial,
386
+ saveInternal,
387
+ report,
388
+ });
389
+
390
+ const lifecycle = createWorkspaceLifecycle({
391
+ adapter,
392
+ isDemo,
393
+ isWeb,
394
+ remembersStartupWorkspace,
395
+ workspace,
396
+ fileRegistry,
397
+ documents,
398
+ tabIds,
399
+ tabAliases,
400
+ activeId,
401
+ installedPlugins,
402
+ busy,
403
+ openingWorkspace,
404
+ workspaceLoading,
405
+ restoringDocuments,
406
+ openingDocuments,
407
+ activities,
408
+ fatal,
409
+ recent,
410
+ sessionError,
411
+ workspaceLifecycle,
412
+ stopWatching,
413
+ dataTables,
414
+ policy,
415
+ knowledge,
416
+ plugins,
417
+ tabsLayout,
418
+ assistantBridge,
419
+ session,
420
+ hooks,
421
+ serial,
422
+ activity,
423
+ report,
424
+ loadWorkspacePart,
425
+ flush: docIO.flush,
426
+ reconcile,
427
+ saveInternal,
428
+ hydrateDocumentLayout: docIO.hydrateDocumentLayout,
429
+ saveTableLayout: docIO.saveTableLayout,
430
+ });
440
431
 
441
- // Session journal & pending state
442
432
  const pending = computed(
443
433
  () =>
444
434
  fileMutations.pending.value ||
@@ -446,1197 +436,14 @@ export const useWorkspaceStore = defineStore('workspace', () => {
446
436
  !!assistantBridge.suggestionPersistence.value?.pending() ||
447
437
  documents.value.some((d) => (dirty(d) || layoutPending(d)) && !d.conflict),
448
438
  );
449
- const journal = new SessionJournal(
450
- (id, session) => adapter.saveSession!(id, session),
451
- (error) => {
452
- sessionError.value =
453
- error === undefined
454
- ? ''
455
- : `恢复草稿未写入:${String(error)}。文档仍会尝试正常保存。`;
456
- },
457
- );
458
- // Track only recoverable fields. Saving/error flags, undo stacks and plugin
459
- // state must not traverse/rewrite every open document on the input path.
460
- const recoveryDocuments = new WeakMap<
461
- OpenDocument,
462
- ComputedRef<WorkspaceSession['documents'][number]>
463
- >();
464
- const mainTabIds = computed(() => layoutPanes(tabsLayout.layout.value).flatMap((pane) => pane.tabs));
465
- const sessionDocuments = computed(() =>
466
- documents.value
467
- .filter((doc) => mainTabIds.value.some((id) => tabsLayout.tabTarget(id) === doc.id))
468
- .map((doc) => {
469
- let snapshot = recoveryDocuments.get(doc);
470
- if (!snapshot) {
471
- snapshot = computed(() => ({
472
- id: doc.id,
473
- path: doc.path,
474
- ...(dirty(doc) ? { draft: { content: doc.content, base: { ...doc.base } } } : {}),
475
- }));
476
- recoveryDocuments.set(doc, snapshot);
477
- }
478
- return snapshot.value;
479
- }),
480
- );
481
- const sessionTables = computed(() =>
482
- dataTables
483
- .drafts()
484
- .filter((draft) =>
485
- mainTabIds.value.some(
486
- (id) => tableFileId(tabsLayout.tabTarget(id)) === (draft.fileId ?? draft.id),
487
- ),
488
- ),
489
- );
490
- const sessionLayout = computed(
491
- () => JSON.parse(JSON.stringify(tabsLayout.layout.value)) as WorkspaceLayout,
492
- );
493
- const sessionPayload = computed<WorkspaceSession>(() => ({
494
- version: 1,
495
- activeId:
496
- layoutPanes(tabsLayout.layout.value).find(
497
- (pane) => pane.id === tabsLayout.windowLayouts.value.main.activePaneId,
498
- )?.activeId ?? '',
499
- tabs: [...new Set(mainTabIds.value.map(tabsLayout.tabTarget))],
500
- layout: sessionLayout.value,
501
- dataTables: sessionTables.value,
502
- documents: sessionDocuments.value,
503
- }));
504
- function queueSession() {
505
- if (!sessionReady || sessionBlocked || !workspace.value || !adapter.saveSession) return;
506
- journal.enqueue(workspace.value.id, sessionPayload.value);
507
- }
508
- const stopSessionWatch = watch(sessionPayload, queueSession, {
509
- flush: 'sync',
510
- });
511
-
512
- // Workspace initialization, open, exit & session restoration
513
- async function initialize(requestedWorkspace?: string) {
514
- if (isDemo || isWeb) {
515
- await openWorkspace(requestedWorkspace);
516
- if (!workspace.value && requestedWorkspace) await openWorkspace();
517
- if (isWeb) await refreshWorkspaces();
518
- } else if (requestedWorkspace) {
519
- await openWorkspace(requestedWorkspace);
520
- } else if (adapter.recent && (await refreshWorkspaces())) {
521
- const savedId = readStartupWorkspace();
522
- const previous =
523
- savedId === undefined
524
- ? recent.value.reduce<RecentWorkspace | undefined>(
525
- (latest, item) => (!latest || item.openedAt > latest.openedAt ? item : latest),
526
- undefined,
527
- )
528
- : recent.value.find((item) => item.id === savedId);
529
- if (previous) await openWorkspace(previous.path);
530
- else if (savedId) rememberStartupWorkspace(null);
531
- }
532
- }
533
-
534
- async function refreshWorkspaces() {
535
- if (!adapter.recent) return false;
536
- try {
537
- recent.value = policy.decorateRecent(await adapter.recent());
538
- return true;
539
- } catch (error) {
540
- report(error);
541
- return false;
542
- }
543
- }
544
-
545
- async function openWorkspace(path?: string, newName?: string) {
546
- if (busy.value) return;
547
- busy.value = true;
548
- let switching = false;
549
- let pendingWorkspaceLoads: Promise<unknown>[] = [];
550
- try {
551
- if (path === undefined && newName === undefined && adapter.selectWorkspacePath) {
552
- const selected = await adapter.selectWorkspacePath();
553
- if (selected === null) return;
554
- path = selected;
555
- }
556
- openingWorkspace.value = true;
557
- for (const part of Object.keys(
558
- workspaceLoading.value,
559
- ) as (keyof typeof workspaceLoading.value)[])
560
- workspaceLoading.value[part] = true;
561
- switching = true;
562
- // Cancel queued old-workspace refreshes before flushing. Keep the watcher
563
- // so failure can replay changes without losing external edits.
564
- workspaceLifecycle.pause();
565
- if (!(await flush())) {
566
- report('还有未保存的修改。请先处理保存错误,再切换工作空间。');
567
- return;
568
- }
569
- await beforeSwitch?.();
570
- await beforeWorkspaceChange?.();
571
- await serial(async () => {
572
- const previousReady = sessionReady;
573
- sessionReady = false;
574
- let next: Workspace | null;
575
- try {
576
- if (newName !== undefined && !adapter.createWorkspace)
577
- throw new Error('此平台不能直接创建工作空间');
578
- next =
579
- newName === undefined
580
- ? await adapter.open(path)
581
- : await adapter.createWorkspace!(newName);
582
- } catch (error) {
583
- sessionReady = previousReady;
584
- throw error;
585
- }
586
- if (!next) {
587
- sessionReady = previousReady;
588
- return;
589
- }
590
- const accountTabs = tabIds.value.filter(
591
- (id) => tabsLayout.views.value.get(id)?.scope === 'account',
592
- );
593
- const accountActive = accountTabs.includes(activeId.value) ? activeId.value : undefined;
594
- stopWatching();
595
- plugins.pluginExecutor.dispose();
596
- fatal.value = '';
597
- if (next.reinitialized) {
598
- report('.tano 已删除,工作区已重新初始化。旧对象已丢失,文档和附件保留。');
599
- }
600
- if (newName !== undefined || next.newlyCreated) {
601
- try {
602
- next = await addWorkspaceWelcome(adapter, next);
603
- } catch (error) {
604
- report(`工作区已创建,但入门文档未能添加:${String(error)}。可以继续新建文档。`);
605
- }
606
- }
607
- policy.resetPolicy(false);
608
- workspace.value = next;
609
- // The new file tree can render immediately; old documents must not
610
- // appear under it while this workspace's metadata/session is loading.
611
- documents.value = [];
612
- tabIds.value = [];
613
- activeId.value = '';
614
- openingDocuments.value = {};
615
- restoringDocuments.value = {};
616
- tabsLayout.resetTabNavigation();
617
- if (remembersStartupWorkspace) rememberStartupWorkspace(next.id);
618
- knowledge.resetKnowledge(false);
619
- dataTables.reset();
620
- installedPlugins.value = [];
621
- workspaceLoading.value.files = false;
622
- // Publish the tree now. Session and document reads do not depend on
623
- // plugin installation, object indexes, rules, or unrelated tables.
624
- const settingsReady = loadWorkspacePart('settings', policy.refreshWorkspaceSettings);
625
- const tablesReady = loadWorkspacePart('tables', () => dataTables.reload());
626
- const objectsReady = knowledge.refreshObjects().catch(report);
627
- const capabilitiesReady = loadWorkspacePart('capabilities', policy.refreshCapabilities);
628
- pendingWorkspaceLoads = [settingsReady, tablesReady, objectsReady, capabilitiesReady];
629
- assistantBridge.resetForWorkspaceChange();
630
- activities.value = [];
631
- sessionError.value = '';
632
- sessionBlocked = false;
633
- const watcherReady = workspaceLifecycle.start().catch(report);
634
- pendingWorkspaceLoads.push(watcherReady);
635
- let saved: WorkspaceSession | null = null;
636
- if (adapter.loadSession) {
637
- try {
638
- saved = await adapter.loadSession(next.id);
639
- } catch (error) {
640
- sessionBlocked = true;
641
- sessionError.value = `${String(error)}。本次不覆盖恢复记录。`;
642
- }
643
- }
644
- if (saved) await restoreSession(saved, tablesReady, objectsReady);
645
- else await settingsReady; // Only the default page depends on settings.
646
- const first =
647
- next.files.find(
648
- (f) =>
649
- f.id === policy.workspaceSettings.value.homePageId &&
650
- f.kind === 'file' &&
651
- isMarkdown(f.path),
652
- ) ??
653
- next.files.find((f) => f.path === workspaceWelcomePath) ??
654
- next.files.find((f) => /^readme\.md$/i.test(f.path)) ??
655
- next.files.find(
656
- (f) => f.kind === 'file' && isMarkdown(f.path) && !isWorkspaceInternalPath(f.path),
657
- );
658
- if (!saved && first) {
659
- try {
660
- await openInitialDocument(first);
661
- tabsLayout.ensureTabNavigation(activeId.value, activeId.value);
662
- tabsLayout.touchNavigation();
663
- } catch (error) {
664
- report(error);
665
- }
666
- }
667
- workspaceLoading.value.session = false;
668
- {
669
- for (const id of accountTabs) {
670
- if (!tabIds.value.includes(id)) tabIds.value.push(id);
671
- tabsLayout.ensureTabNavigation(id);
672
- }
673
- if (accountActive) activeId.value = accountActive;
674
- tabsLayout.touchNavigation();
675
- }
676
- // These completions protect persistence and adapter ownership, but each
677
- // component has already revealed its own ready data independently.
678
- await Promise.all([
679
- settingsReady,
680
- tablesReady,
681
- objectsReady,
682
- capabilitiesReady,
683
- watcherReady,
684
- ]);
685
- sessionReady = true;
686
- queueSession();
687
- if (adapter.recent) recent.value = policy.decorateRecentNames(await adapter.recent());
688
- activity(isDemo ? '演示工作空间已就绪' : '工作空间已打开', next.name, 'file');
689
- });
690
- } catch (error) {
691
- if (path && recent.value.some((item) => item.path === path)) {
692
- await refreshWorkspaces();
693
- if (!recent.value.some((item) => item.path === path)) {
694
- fatal.value = '';
695
- return;
696
- }
697
- }
698
- report(error);
699
- } finally {
700
- await Promise.allSettled(pendingWorkspaceLoads);
701
- openingWorkspace.value = false;
702
- for (const part of Object.keys(
703
- workspaceLoading.value,
704
- ) as (keyof typeof workspaceLoading.value)[])
705
- workspaceLoading.value[part] = false;
706
- busy.value = false;
707
- if (switching) {
708
- workspaceLifecycle.resume();
709
- try {
710
- await afterSwitch?.();
711
- } catch (error) {
712
- report(error);
713
- }
714
- }
715
- }
716
- }
717
-
718
- function createWorkspace(name?: string) {
719
- if (name === undefined) {
720
- const spaces = [...recent.value, ...(workspace.value ? [workspace.value] : [])];
721
- // Local display names can change independently of their backing folder names.
722
- const occupied = new Set(
723
- spaces.flatMap((space) => [space.name, basename(space.path.replace(/\\/g, '/'))]),
724
- );
725
- name = '新工作区';
726
- for (let suffix = 2; occupied.has(name); suffix++) name = `新工作区 ${suffix}`;
727
- }
728
- return openWorkspace(undefined, name);
729
- }
730
-
731
- function leaveWorkspace(): Promise<boolean> {
732
- return exitWorkspace();
733
- }
734
-
735
- function deleteWorkspace(workspaceId: string): Promise<boolean> {
736
- return exitWorkspace(workspaceId);
737
- }
738
-
739
- async function exitWorkspace(deleteId?: string): Promise<boolean> {
740
- if (busy.value || !workspace.value) return false;
741
- busy.value = true;
742
- try {
743
- const assertDeletion = () => {
744
- if (deleteId === undefined) return;
745
- if (workspace.value?.id !== deleteId) throw new Error('工作区已切换,请重新确认删除');
746
- if (!adapter.deleteWorkspace || !workspace.value.canDelete)
747
- throw new Error(
748
- isWeb ? '仅工作区所有者可以删除工作区' : '此平台暂不支持删除本地工作区注册',
749
- );
750
- };
751
- assertDeletion();
752
- if (!(await flush())) {
753
- report(
754
- `还有未保存的修改。请先处理保存错误,再${deleteId === undefined ? '退出' : '删除'}工作区。`,
755
- );
756
- return false;
757
- }
758
- await beforeSwitch?.();
759
- await beforeWorkspaceChange?.();
760
- await serial(async () => {
761
- assertDeletion();
762
- const current = workspace.value;
763
- if (!current) return;
764
- queueSession();
765
- await journal.flush();
766
- if (deleteId !== undefined) await adapter.deleteWorkspace!(deleteId);
767
- else await adapter.close?.(current.id);
768
- if (remembersStartupWorkspace) rememberStartupWorkspace(null);
769
- sessionReady = false;
770
- stopWatching();
771
- plugins.pluginHost.dispose();
772
- plugins.pluginExecutor.dispose();
773
- workspace.value = null;
774
- dataTables.reset();
775
- policy.resetPolicy(true);
776
- assistantBridge.resetForWorkspaceChange();
777
- documents.value = [];
778
- tabIds.value = [];
779
- tabAliases.value = new Map();
780
- activeId.value = '';
781
- tabsLayout.resetTabNavigation();
782
- knowledge.resetKnowledge(true);
783
- installedPlugins.value = [];
784
- plugins.pluginError.value = '';
785
- activities.value = [];
786
- sessionError.value = '';
787
- sessionBlocked = false;
788
- fatal.value = '';
789
- if (deleteId !== undefined) {
790
- policy.forgetWorkspaceName(deleteId);
791
- recent.value = recent.value.filter((item) => item.id !== deleteId);
792
- knowledge.referenceDocumentCache.clear();
793
- }
794
- });
795
- await refreshWorkspaces();
796
- return true;
797
- } catch (error) {
798
- report(error);
799
- return false;
800
- } finally {
801
- busy.value = false;
802
- try {
803
- await afterSwitch?.();
804
- } catch (error) {
805
- report(error);
806
- }
807
- }
808
- }
809
-
810
- async function openInitialDocument(file: FileEntry) {
811
- restoringDocuments.value = { ...restoringDocuments.value, [file.id]: file.path };
812
- tabIds.value = [file.id];
813
- activeId.value = file.id;
814
- workspaceLoading.value.session = false;
815
- try {
816
- await openInternal(file);
817
- } finally {
818
- delete restoringDocuments.value[file.id];
819
- }
820
- }
821
-
822
- async function restoreSession(
823
- saved: WorkspaceSession,
824
- tablesReady: Promise<void>,
825
- objectsReady: Promise<void>,
826
- ) {
827
- tabAliases.value = new Map();
828
- const remapped = new Map<string, string>();
829
- const pendingDocs = saved.documents.flatMap((tab) => {
830
- const file = fileRegistry.value?.get(tab.id) ?? fileRegistry.value?.at(tab.path);
831
- if (!file && !tab.draft) return [];
832
- const id = file?.id ?? tab.id;
833
- remapped.set(tab.id, id);
834
- return [{ tab, file, id }];
835
- });
836
- restoringDocuments.value = Object.fromEntries(
837
- pendingDocs.map(({ tab, file, id }) => [id, file?.path ?? tab.path]),
838
- );
839
- const planned = new Set(pendingDocs.map(({ id }) => id));
840
- const requested = (saved.tabs ?? []).map((id) => remapped.get(id) ?? id);
841
- tabIds.value = [
842
- ...new Set([
843
- ...requested.filter(
844
- (id) =>
845
- id !== TABLES_TAB_ID &&
846
- (planned.has(id) ||
847
- tabsLayout.isUtilityTab(id) ||
848
- tabsLayout.isWorkspaceViewTab(id) ||
849
- id.startsWith('plugin:')),
850
- ),
851
- ...planned,
852
- ]),
853
- ];
854
- const restoredActive = remapped.get(saved.activeId) ?? saved.activeId;
855
- tabsLayout.layout.value = restoreLayout(saved.layout, tabIds.value, remapped);
856
- tabsLayout.activePaneId.value =
857
- tabsLayout.panes.value.find((pane) => pane.tabs.includes(restoredActive))?.id ??
858
- tabsLayout.panes.value[0].id;
859
- activeId.value = tabIds.value.includes(restoredActive)
860
- ? restoredActive
861
- : (tabIds.value[0] ?? '');
862
- workspaceLoading.value.session = false;
863
- // Visible documents get the first read slots. Background tabs cannot hold
864
- // up either their labels or another pane whose document has already arrived.
865
- const visible = new Set(tabsLayout.panes.value.map((pane) => pane.activeId));
866
- const tableRecovery = (async () => {
867
- await tablesReady;
868
- if (saved.dataTables?.length) {
869
- workspaceLoading.value.tables = true;
870
- await loadWorkspacePart('tables', () => dataTables.restore(saved.dataTables!));
871
- }
872
- })();
873
- const restoreDocument = async ({ tab, file, id }: (typeof pendingDocs)[number]) => {
874
- try {
875
- if (!tab.draft) {
876
- if (file) {
877
- const doc = await readOpenDocument(file);
878
- if (!documentIndex.byId.value.has(id)) documents.value.push(doc);
879
- }
880
- return;
881
- }
882
- const doc: OpenDocument = {
883
- id: file?.id ?? tab.id,
884
- path: file?.path ?? tab.path,
885
- content: tab.draft.content,
886
- base: tab.draft.base,
887
- saving: false,
888
- creating: file?.pendingCreation,
889
- missing: !file,
890
- };
891
- if (!doc.creating) await hydrateDocumentLayout(doc);
892
- documents.value.push(doc);
893
- activity('已恢复未保存草稿', doc.path, 'file');
894
- if (file) {
895
- try {
896
- if (!doc.creating) await reconcile(doc, await adapter.read(file.path));
897
- await saveInternal(documentIndex.byId.value.get(doc.id)!);
898
- } catch (error) {
899
- doc.error = String(error);
900
- report(error);
901
- }
902
- } else doc.error = '原文件已不存在,恢复草稿已保留,请另存副本';
903
- } catch (error) {
904
- report(error);
905
- } finally {
906
- delete restoringDocuments.value[id];
907
- }
908
- };
909
- const priority = (id: string) => (id === restoredActive ? 2 : Number(visible.has(id)));
910
- const queue = [...pendingDocs].sort((a, b) => priority(b.id) - priority(a.id));
911
- const worker = async () => {
912
- for (let next = queue.shift(); next; next = queue.shift()) await restoreDocument(next);
913
- };
914
- await Promise.all([
915
- tableRecovery,
916
- objectsReady,
917
- ...Array.from({ length: Math.min(4, queue.length) }, worker),
918
- ]);
919
- // Resolve legacy table identities only after table records are available.
920
- for (const id of saved.tabs ?? [])
921
- if (isTableTab(id) && id !== TABLES_TAB_ID)
922
- remapped.set(id, tableTabId(dataTableFileId(tableFileId(id))));
923
- const byId = new Map(documents.value.map((doc) => [doc.id, doc]));
924
- documents.value = pendingDocs
925
- .map(({ id }) => byId.get(id))
926
- .filter((doc): doc is OpenDocument => !!doc);
927
- const restored = saved.tabs
928
- ?.map((id) => remapped.get(id) ?? id)
929
- .filter(
930
- (id) =>
931
- id !== TABLES_TAB_ID &&
932
- (tabsLayout.isUtilityTab(id) || documents.value.some((doc) => doc.id === id)),
933
- );
934
- tabIds.value = [...new Set([...(restored ?? []), ...documents.value.map((doc) => doc.id)])];
935
- const currentActive = remapped.get(activeId.value) ?? activeId.value;
936
- tabsLayout.layout.value = restoreLayout(tabsLayout.layout.value, tabIds.value, remapped);
937
- tabsLayout.activePaneId.value =
938
- tabsLayout.panes.value.find((pane) => pane.tabs.includes(currentActive))?.id ??
939
- tabsLayout.panes.value[0].id;
940
- activeId.value = tabIds.value.includes(currentActive)
941
- ? currentActive
942
- : (tabIds.value[0] ?? '');
943
- for (const tabId of tabIds.value) tabsLayout.ensureTabNavigation(tabId, tabId);
944
- tabsLayout.touchNavigation();
945
- }
946
-
947
- // Document opening, editing, saving, closing & conflict resolution
948
- async function readOpenDocument(file: FileEntry): Promise<OpenDocument> {
949
- const snapshot = await adapter.read(file.path);
950
- const doc: OpenDocument = {
951
- id: file.id,
952
- path: file.path,
953
- content: snapshot.content,
954
- base: snapshot,
955
- saving: false,
956
- creating: file.pendingCreation,
957
- missing: false,
958
- };
959
- if (!doc.creating) await hydrateDocumentLayout(doc);
960
- return doc;
961
- }
962
-
963
- async function openInternal(file: FileEntry, replaceId?: string, current = () => true) {
964
- // The tree may already show a pending rename; storage still uses its
965
- // confirmed path until the background mutation completes.
966
- file = workspace.value?.files.find((entry) => entry.id === file.id) ?? file;
967
- if (file.kind === 'file' && isDataTableFilePath(file.path)) {
968
- tabsLayout.activateTab(tableTabId(file.id), replaceId);
969
- return;
970
- }
971
- if (!isMarkdown(file.path) || file.kind !== 'file') return;
972
- let doc = documentIndex.byId.value.get(file.id);
973
- if (!doc) doc = await readOpenDocument(file);
974
- if (!current()) return;
975
- if (tabIds.value.includes(doc.id) && !documentIndex.byId.value.has(doc.id))
976
- documents.value.push(doc);
977
- tabsLayout.activateTab(doc.id, replaceId, doc);
978
- const opened = documentIndex.byId.value.get(doc!.id)!;
979
- if (opened.creating)
980
- void fileOps.confirmCreation(opened).then((confirmed) => {
981
- if (confirmed && !disposed && dirty(opened)) void flush();
982
- });
983
- }
984
-
985
- async function prepareTabReplacement(id?: string) {
986
- if (id && isTableTab(id) && !(await flush())) {
987
- report('此数据表尚未保存,请先处理保存错误。');
988
- return false;
989
- }
990
- if (assistantBridge.suggestionPersistence.value?.pending() && !(await flush())) return false;
991
- const current = documentIndex.byId.value.get(tabsLayout.tabTarget(id ?? ''));
992
- if (!current) return true;
993
- if ((dirty(current) || layoutPending(current)) && !(await flush())) {
994
- report('此文档尚未保存,请先处理保存错误。');
995
- return false;
996
- }
997
- if (current.conflict || current.missing) {
998
- report('请先处理当前文档的冲突或缺失,再替换标签页。');
999
- return false;
1000
- }
1001
- await beforeCloseDocument?.(current.id);
1002
- if ((dirty(current) || layoutPending(current)) && !(await flush())) {
1003
- report('此文档尚未保存,请先处理保存错误。');
1004
- return false;
1005
- }
1006
- if (current.conflict || current.missing) {
1007
- report('请先处理当前文档的冲突或缺失,再替换标签页。');
1008
- return false;
1009
- }
1010
- return true;
1011
- }
1012
-
1013
- function prefetchFile(file: FileEntry) {
1014
- if (!adapter.prefetch || busy.value || disposed || file.kind !== 'file' || !isMarkdown(file.path))
1015
- return;
1016
- const entry = fileRegistry.value?.get(file.id);
1017
- if (!entry || entry.pendingCreation) return;
1018
- // This is only a hint. Opening still reports real read errors and validates
1019
- // the current version; hovering must never surface an error banner.
1020
- void adapter.prefetch(entry.path).catch(() => {});
1021
- if (/^[0-9a-f]{6}$/.test(entry.id)) {
1022
- const path = documentLayoutPath(entry.id);
1023
- if (fileRegistry.value?.at(path)) void adapter.prefetch(path).catch(() => {});
1024
- }
1025
- }
1026
-
1027
- function openCached(file: FileEntry, replaceId?: string) {
1028
- if (fileMutations.pending.value) return false;
1029
- const existing = documentIndex.byId.value.get(file.id);
1030
- if (existing) {
1031
- tabsLayout.activateTab(existing.id, replaceId, existing);
1032
- return true;
1033
- }
1034
- const entry = fileRegistry.value?.get(file.id);
1035
- if (!entry || entry.pendingCreation) return false;
1036
- const snapshot = adapter.readCached?.(entry.path);
1037
- if (!snapshot) return false;
1038
- const doc: OpenDocument = {
1039
- id: entry.id,
1040
- path: entry.path,
1041
- content: snapshot.content,
1042
- base: snapshot,
1043
- saving: false,
1044
- missing: false,
1045
- };
1046
- if (/^[0-9a-f]{6}$/.test(entry.id)) {
1047
- const path = documentLayoutPath(entry.id);
1048
- const exists = !!fileRegistry.value?.at(path);
1049
- const base = exists ? adapter.readCached?.(path) : null;
1050
- if (exists && !base) return false;
1051
- try {
1052
- doc.tableLayout = {
1053
- base: base ?? null,
1054
- file: base
1055
- ? parseDocumentLayout(base.content, entry.id)
1056
- : { version: 1, fileId: entry.id, tables: [] },
1057
- };
1058
- } catch {
1059
- return false;
1060
- } // The ordinary loader reports malformed layouts.
1061
- }
1062
- // Cache lookup and activation are synchronous. A background workspace scan
1063
- // can reconcile later; it must not make displaying known bytes wait on I/O.
1064
- tabsLayout.activateTab(doc.id, replaceId, doc);
1065
- return true;
1066
- }
1067
-
1068
- function recordOpenedDocument(file: FileEntry) {
1069
- recordHelpCompleted('welcome');
1070
- if (
1071
- workspace.value &&
1072
- indexFolderHomes(
1073
- workspace.value.files,
1074
- policy.workspaceSettings.value.folderHomeFileName,
1075
- ).get(parentPath(file.path))?.id === file.id
1076
- )
1077
- recordHelpCompleted('folder-home');
1078
- }
1079
-
1080
- /** The bundled drawing plugin handles its own Markdown; disabled plugins keep source access. */
1081
- function drawingPluginHandles(file: FileEntry) {
1082
- return (
1083
- file.kind === 'file' &&
1084
- /\.excalidraw\.md$/i.test(file.path) &&
1085
- !!workspace.value &&
1086
- plugins.pluginRuntime.value.some(
1087
- (plugin) => plugin.id === 'excalidraw' && plugin.status === 'running',
1088
- )
1089
- );
1090
- }
1091
- async function openDrawingPlugin(file: FileEntry) {
1092
- const currentWorkspace = workspace.value;
1093
- if (!currentWorkspace) return false;
1094
- try {
1095
- await plugins.pluginExecutor.invoke('excalidraw', 'command', 'open', {
1096
- workspaceId: currentWorkspace.id,
1097
- fileId: file.id,
1098
- });
1099
- return true;
1100
- } catch (error) {
1101
- report(error);
1102
- return false;
1103
- }
1104
- }
1105
- function officePluginId(file: FileEntry) {
1106
- return /\.pptx?$/i.test(file.path)
1107
- ? 'presentation-preview'
1108
- : /\.docx?$/i.test(file.path)
1109
- ? 'word-preview'
1110
- : undefined;
1111
- }
1112
-
1113
- async function openFile(file: FileEntry, options?: { historyIndex?: number }) {
1114
- if (file.kind === 'file' && officePluginId(file)) return openAttachment(file, options);
1115
- if (drawingPluginHandles(file) && (await openDrawingPlugin(file))) return;
1116
- const creationAtRequest = fileOps.getCreationRevision();
1117
- const request = ++fileOpenRevision;
1118
- const paneId = tabsLayout.activePaneId.value;
1119
- const epoch = assistantBridge.assistantEpoch.value;
1120
- const activation = tabsLayout.getActivationRevision();
1121
- const workspaceId = workspace.value?.id;
1122
- const current = () =>
1123
- !disposed &&
1124
- !busy.value &&
1125
- request === fileOpenRevision &&
1126
- creationAtRequest === fileOps.getCreationRevision() &&
1127
- epoch === assistantBridge.assistantEpoch.value &&
1128
- workspaceId === workspace.value?.id &&
1129
- activation === tabsLayout.getActivationRevision();
1130
- try {
1131
- if (file.kind === 'file' && isDataTableFilePath(file.path))
1132
- return openDataTable(file.id, options);
1133
- if (!isMarkdown(file.path) || file.kind !== 'file') return;
1134
- const replaceId =
1135
- tabsLayout.isUtilityTab(activeId.value) &&
1136
- !activeId.value.startsWith('blank:') &&
1137
- !tabsLayout.isNavigationPage(activeId.value)
1138
- ? undefined
1139
- : activeId.value;
1140
- const wasOpen = documents.value.some((doc) => doc.id === file.id);
1141
- prefetchFile(file);
1142
- if (!wasOpen && !(await prepareTabReplacement(replaceId))) return;
1143
- if (!current()) return;
1144
- if (!wasOpen) openingDocuments.value[paneId] = { request, tabId: activeId.value };
1145
- if (!openCached(file, replaceId))
1146
- await serial(async () => {
1147
- if (!current()) return;
1148
- await openInternal(file, replaceId, current);
1149
- });
1150
- if (!wasOpen && replaceId && activeId.value === file.id)
1151
- tabsLayout.recordTabNavigation(replaceId, file.id, options?.historyIndex);
1152
- else if (!replaceId && activeId.value === file.id)
1153
- tabsLayout.ensureTabNavigation(file.id, file.id);
1154
- if (tabsLayout.active.value?.id === file.id) recordOpenedDocument(file);
1155
- } catch (e) {
1156
- if (current()) report(e);
1157
- } finally {
1158
- if (openingDocuments.value[paneId]?.request === request) delete openingDocuments.value[paneId];
1159
- }
1160
- }
1161
-
1162
- async function openFileInNewTab(file: FileEntry) {
1163
- try {
1164
- if (file.kind === 'file' && officePluginId(file)) return openAttachmentInNewTab(file);
1165
- if (drawingPluginHandles(file) && (await openDrawingPlugin(file))) return;
1166
- await serial(async () => {
1167
- if (file.kind === 'file' && isDataTableFilePath(file.path)) {
1168
- const target = tableTabId(dataTableFileId(file.id));
1169
- if (tabIds.value.includes(target)) {
1170
- const alias = tabsLayout.newTabAlias(target);
1171
- tabIds.value.push(alias);
1172
- activeId.value = alias;
1173
- tabsLayout.ensureTabNavigation(alias, target);
1174
- tabsLayout.touchNavigation();
1175
- } else await openDataTable(file.id, { newTab: true });
1176
- return;
1177
- }
1178
- const target = file.id;
1179
- if (tabIds.value.includes(target)) {
1180
- const alias = tabsLayout.newTabAlias(target);
1181
- tabIds.value.push(alias);
1182
- activeId.value = alias;
1183
- tabsLayout.ensureTabNavigation(alias, target);
1184
- tabsLayout.touchNavigation();
1185
- return;
1186
- }
1187
- await openInternal(file);
1188
- if (activeId.value === file.id) tabsLayout.ensureTabNavigation(file.id, file.id);
1189
- });
1190
- if (tabsLayout.active.value?.id === file.id) recordOpenedDocument(file);
1191
- } catch (error) {
1192
- report(error);
1193
- }
1194
- }
1195
-
1196
- async function openAttachment(
1197
- file: FileEntry,
1198
- options?: { newTab?: boolean; historyIndex?: number },
1199
- ) {
1200
- const currentWorkspace = workspace.value;
1201
- if (
1202
- !currentWorkspace ||
1203
- file.kind !== 'file' ||
1204
- isMarkdown(file.path) ||
1205
- isDataTableFilePath(file.path) ||
1206
- !currentWorkspace.files.some((entry) => entry.id === file.id && entry.path === file.path)
1207
- )
1208
- return;
1209
- const workspaceId = currentWorkspace.id;
1210
- const request = ++fileOpenRevision;
1211
- const activation = tabsLayout.getActivationRevision();
1212
- const current = () => request === fileOpenRevision && !busy.value && !disposed;
1213
- const target = `attachment:${file.id}`;
1214
- const pluginId = officePluginId(file);
1215
- const viewTab =
1216
- pluginId === 'word-preview' ? tabsLayout.wordPreviewTab : tabsLayout.presentationPreviewTab;
1217
- const usePlugin =
1218
- !!pluginId &&
1219
- plugins.pluginRuntime.value.some(
1220
- (plugin) => plugin.id === pluginId && plugin.status === 'running',
1221
- ) &&
1222
- plugins.pluginViews.value.some((view) => view.key === viewTab);
1223
- const id = usePlugin ? viewTab : target;
1224
- // The bundled viewers share a tab per plugin, while history follows individual files.
1225
- const opened = await openPageTab(id, {
1226
- ...options,
1227
- target,
1228
- current: () => current() && tabsLayout.getActivationRevision() === activation,
1229
- });
1230
- if (
1231
- !opened ||
1232
- !usePlugin ||
1233
- !current() ||
1234
- activeId.value !== id ||
1235
- workspace.value?.id !== workspaceId
1236
- )
1237
- return;
1238
- const previewActivation = tabsLayout.getActivationRevision();
1239
- try {
1240
- await plugins.pluginExecutor.invoke(pluginId, 'command', 'open', {
1241
- workspaceId,
1242
- fileId: file.id,
1243
- viewAlreadyOpen: true,
1244
- });
1245
- } catch (error) {
1246
- if (
1247
- !current() ||
1248
- tabsLayout.getActivationRevision() !== previewActivation ||
1249
- workspace.value?.id !== workspaceId
1250
- )
1251
- return;
1252
- report(error);
1253
- await openPageTab(target, {
1254
- target,
1255
- current: () => current() && tabsLayout.getActivationRevision() === previewActivation,
1256
- });
1257
- }
1258
- }
1259
-
1260
- function openAttachmentInNewTab(file: FileEntry) {
1261
- return openAttachment(file, { newTab: true });
1262
- }
1263
-
1264
- async function openFilesInNewTabsAt(
1265
- ids: readonly string[],
1266
- index: number,
1267
- workspaceId: string,
1268
- ) {
1269
- try {
1270
- await serial(async () => {
1271
- if (workspace.value?.id !== workspaceId) return;
1272
- const files = [...new Set(ids)].map((id) =>
1273
- workspace.value!.files.find((file) => file.id === id),
1274
- );
1275
- if (
1276
- !files.length ||
1277
- files.some(
1278
- (file) =>
1279
- !file ||
1280
- file.kind !== 'file' ||
1281
- !(isMarkdown(file.path) || isDataTableFilePath(file.path)),
1282
- )
1283
- )
1284
- return;
1285
- // Keep a stable neighbor while reads are pending and already-open tabs move.
1286
- const moving = new Set(
1287
- files.map((file) => (isDataTableFilePath(file!.path) ? tableTabId(file!.id) : file!.id)),
1288
- );
1289
- const following = tabIds.value.slice(Math.max(0, index)).filter((id) => !moving.has(id));
1290
- for (const file of files) {
1291
- await openInternal(file!);
1292
- if (tabsLayout.active.value?.id === file!.id) recordHelpCompleted('welcome');
1293
- const id = isDataTableFilePath(file!.path) ? tableTabId(file!.id) : file!.id;
1294
- tabsLayout.ensureTabNavigation(id, id);
1295
- const target = following.find((tabId) => tabIds.value.includes(tabId));
1296
- if (target) tabsLayout.moveDocument(id, target, 'before');
1297
- else tabsLayout.placeTab(id, tabIds.value.length);
1298
- }
1299
- });
1300
- } catch (error) {
1301
- report(error);
1302
- }
1303
- }
1304
-
1305
- async function openPageTab(
1306
- id: string,
1307
- options?: { newTab?: boolean; historyIndex?: number; target?: string; current?: () => boolean },
1308
- ) {
1309
- if (!workspace.value) return false;
1310
- if (options?.newTab) {
1311
- tabsLayout.activateTab(id);
1312
- tabsLayout.ensureTabNavigation(id, options.target);
1313
- if (options.target) tabsLayout.recordTabNavigation(id, id, undefined, options.target);
1314
- else tabsLayout.touchNavigation();
1315
- return true;
1316
- }
1317
- const workspaceId = workspace.value.id;
1318
- const epoch = assistantBridge.assistantEpoch.value;
1319
- const replaceId = activeId.value;
1320
- const wasOpen = tabIds.value.includes(id);
1321
- try {
1322
- if (!wasOpen && !(await prepareTabReplacement(replaceId))) return false;
1323
- return await serial(async () => {
1324
- if (
1325
- workspace.value?.id !== workspaceId ||
1326
- assistantBridge.assistantEpoch.value !== epoch ||
1327
- (options?.current && (!options.current() || activeId.value !== replaceId))
1328
- )
1329
- return false;
1330
- const targetId = activeId.value === replaceId ? replaceId : undefined;
1331
- tabsLayout.activateTab(id, targetId);
1332
- if (!wasOpen && targetId)
1333
- tabsLayout.recordTabNavigation(targetId, id, options?.historyIndex, options?.target);
1334
- else if (options?.target) {
1335
- tabsLayout.ensureTabNavigation(id, options.target);
1336
- tabsLayout.recordTabNavigation(
1337
- id,
1338
- id,
1339
- targetId === id ? options.historyIndex : undefined,
1340
- options.target,
1341
- );
1342
- } else {
1343
- tabsLayout.ensureTabNavigation(id);
1344
- tabsLayout.touchNavigation();
1345
- }
1346
- return true;
1347
- });
1348
- } catch (error) {
1349
- report(error);
1350
- return false;
1351
- }
1352
- }
1353
-
1354
- async function openGraphTab(options?: { newTab?: boolean; historyIndex?: number }) {
1355
- await openPageTab(GRAPH_TAB_ID, options);
1356
- if (workspace.value && activeId.value === GRAPH_TAB_ID) recordHelpCompleted('graph');
1357
- }
1358
- async function openDirectory(
1359
- path: string,
1360
- options?: { newTab?: boolean; historyIndex?: number },
1361
- ) {
1362
- if (!workspace.value) return;
1363
- const entry = workspace.value.files.find(
1364
- (file) => file.kind === 'directory' && file.path === path,
1365
- );
1366
- if (path && !entry) return;
1367
- await openPageTab(path ? `directory:${entry!.id}` : 'directory:/', options);
1368
- }
1369
- async function openWorkspaceView(
1370
- id: string,
1371
- options?: { newTab?: boolean; historyIndex?: number },
1372
- ) {
1373
- if (!knowledge.workspaceViews.value.some((record) => record.view.id === id))
1374
- throw new Error('工作区视图已不存在,请刷新后重试');
1375
- await openPageTab(tabsLayout.workspaceViewTabId(id), options);
1376
- }
1377
- async function openPluginDetail(
1378
- pluginId: string,
1379
- options?: { newTab?: boolean; historyIndex?: number },
1380
- ) {
1381
- if (tabsLayout.pluginDetailManifest(`plugin:${pluginId}`))
1382
- await openPageTab(`plugin:${pluginId}`, options);
1383
- }
1384
- async function openPluginsTab(options?: { newTab?: boolean; historyIndex?: number }) {
1385
- await openPageTab(PLUGINS_TAB_ID, options);
1386
- if (workspace.value && activeId.value === PLUGINS_TAB_ID) recordHelpCompleted('plugins');
1387
- }
1388
-
1389
- // Serialize adapter reads with workspace switches. The graph never writes
1390
- // content, and open drafts take precedence over the filesystem snapshot.
1391
- function readGraphDocument(
1392
- expectedWorkspace: Pick<Workspace, 'id' | 'path'>,
1393
- file: Pick<FileEntry, 'id'> & Partial<Pick<FileEntry, 'path'>>,
1394
- ) {
1395
- return serial(async () => {
1396
- if (
1397
- workspace.value?.id !== expectedWorkspace.id ||
1398
- workspace.value.path !== expectedWorkspace.path
1399
- )
1400
- throw new Error('工作区已切换');
1401
- const entry = fileRegistry.value?.get(file.id);
1402
- if (
1403
- !entry ||
1404
- (file.path !== undefined && entry.path !== file.path) ||
1405
- entry.kind !== 'file' ||
1406
- !isMarkdown(entry.path)
1407
- )
1408
- throw new Error('文档已移动或删除');
1409
- const draft = documentIndex.byId.value.get(file.id);
1410
- if (draft) return draft.content;
1411
- const snapshot = await adapter.read(entry.path);
1412
- return documentIndex.byId.value.get(file.id)?.content ?? snapshot.content;
1413
- });
1414
- }
1415
-
1416
- function edit(content: string) {
1417
- if (tabsLayout.active.value) editDocument(tabsLayout.active.value.id, content);
1418
- }
1419
-
1420
- function editDocument(id: string, content: string, options: { origin?: 'local' | 'remote' } = {}) {
1421
- const doc = documentIndex.byId.value.get(id);
1422
- if (!doc || doc.conflict || workspace.value?.readOnly || fileRegistry.value?.get(id)?.readOnly)
1423
- return;
1424
- const before = doc.content;
1425
- doc.content = content;
1426
- if (!doc.creating) doc.error = undefined;
1427
- clearTimeout(saveTimer);
1428
- saveTimer = setTimeout(() => {
1429
- void flush();
1430
- }, 600);
1431
- if (options.origin !== 'remote')
1432
- helpEdits.record(id, before, content, knowledge.referenceTargets.value);
1433
- }
1434
-
1435
- function receiveDocument(
1436
- id: string,
1437
- content: string,
1438
- options: { origin?: 'local' | 'remote' } = {},
1439
- ) {
1440
- const doc = documentIndex.byId.value.get(id);
1441
- if (!doc || doc.conflict || doc.missing) return;
1442
- const before = doc.content;
1443
- doc.content = content;
1444
- clearTimeout(saveTimer);
1445
- saveTimer = setTimeout(() => {
1446
- void flush();
1447
- }, 600);
1448
- if (options.origin === 'local')
1449
- helpEdits.record(id, before, content, knowledge.referenceTargets.value);
1450
- }
1451
-
1452
- async function hydrateDocumentLayout(doc: OpenDocument) {
1453
- if (!workspace.value || !/^[0-9a-f]{6}$/.test(doc.id)) return;
1454
- try {
1455
- doc.tableLayout = await loadDocumentLayout(adapter, workspace.value, doc.id);
1456
- } catch (error) {
1457
- report(`无法读取表格布局,原文件已保留:${String(error)}`);
1458
- }
1459
- }
1460
-
1461
- function editTableLayout(id: string, tables: TableLayout[]) {
1462
- const doc = documentIndex.byId.value.get(id);
1463
- if (!doc?.tableLayout || doc.conflict || doc.missing || workspace.value?.readOnly) return;
1464
- doc.tableLayout.file = {
1465
- ...doc.tableLayout.file,
1466
- tables: JSON.parse(JSON.stringify(tables)),
1467
- };
1468
- doc.tableLayout.error = undefined;
1469
- clearTimeout(saveTimer);
1470
- saveTimer = setTimeout(() => {
1471
- void flush();
1472
- }, 300);
1473
- }
1474
-
1475
- async function saveTableLayout(doc: OpenDocument) {
1476
- const state = doc.tableLayout;
1477
- if (!state || !layoutDirty(state) || doc.missing || doc.conflict) return;
1478
- const draft = JSON.stringify(state.file);
1479
- if (state.conflict?.draft === draft) return;
1480
- try {
1481
- const saved = await saveDocumentLayout(adapter, state);
1482
- state.base = saved.base;
1483
- if (JSON.stringify(state.file) === draft) state.file = saved.file;
1484
- state.error = undefined;
1485
- state.conflict = undefined;
1486
- } catch (error) {
1487
- if (error instanceof DocumentLayoutConflict) state.conflict = { path: error.path, draft };
1488
- state.error = String(error);
1489
- report(error);
1490
- }
1491
- }
1492
-
1493
- async function flush(): Promise<boolean> {
1494
- await fileMutations.flush();
1495
- return flushDocuments();
1496
- }
1497
-
1498
- async function flushDocuments(): Promise<boolean> {
1499
- await fileOps.awaitCreationChain();
1500
- try {
1501
- await assistantBridge.suggestionPersistence.value?.flush();
1502
- } catch (error) {
1503
- report(error);
1504
- return false;
1505
- }
1506
- clearTimeout(saveTimer);
1507
- const saved = await serial(async () => {
1508
- const tablesSaved = await dataTables.persistAll();
1509
- for (const doc of documents.value) {
1510
- await saveInternal(doc);
1511
- await saveTableLayout(doc);
1512
- }
1513
- return (
1514
- tablesSaved &&
1515
- documents.value.every((doc) => (!dirty(doc) || !!doc.conflict) && !layoutPending(doc))
1516
- );
1517
- });
1518
- await journal.flush();
1519
- return saved;
1520
- }
1521
-
1522
- async function refresh() {
1523
- if (!workspace.value) return;
1524
- const expectedId = workspace.value.id;
1525
- const expectedPath = workspace.value.path;
1526
- try {
1527
- await serial(async () => {
1528
- if (workspace.value?.id !== expectedId || workspace.value.path !== expectedPath) return;
1529
- workspace.value = await adapter.refresh();
1530
- await policy.refreshCapabilities();
1531
- await policy.refreshWorkspaceSettings();
1532
- await knowledge.refreshObjects();
1533
- await dataTables.reload();
1534
- for (const doc of documents.value) {
1535
- if (doc.creating) continue;
1536
- const entry = fileRegistry.value?.get(doc.id);
1537
- if (!entry) {
1538
- if (!doc.missing) activity('文件已在外部移除', doc.path, 'external');
1539
- doc.missing = true;
1540
- continue;
1541
- }
1542
- if (doc.path !== entry.path) {
1543
- activity('文件已在外部重命名', `${doc.path} → ${entry.path}`, 'external');
1544
- doc.path = entry.path;
1545
- }
1546
- doc.missing = false;
1547
- await reconcile(doc, await adapter.read(doc.path));
1548
- await saveInternal(doc);
1549
- if (doc.tableLayout && !layoutDirty(doc.tableLayout)) await hydrateDocumentLayout(doc);
1550
- await saveTableLayout(doc);
1551
- }
1552
- });
1553
- } catch (error) {
1554
- knowledge.clearRevokedReferences(error);
1555
- report(error);
1556
- }
1557
- }
1558
-
1559
- async function close(id: string) {
1560
- if (isTableTab(id) && !(await flush())) {
1561
- report('数据表尚有未保存的修改,请先处理保存错误。');
1562
- return;
1563
- }
1564
- const pane = tabsLayout.panes.value.find((pane) => pane.tabs.includes(id));
1565
- const nextTab = () => {
1566
- const candidate = tabsLayout.panes.value
1567
- .find((item) => item.id === pane?.id)
1568
- ?.tabs.find((tabId) => tabId !== id && tabIds.value.includes(tabId));
1569
- return candidate ?? tabIds.value.find((tabId) => tabId !== id) ?? '';
1570
- };
1571
- if (tabsLayout.isUtilityTab(id)) {
1572
- tabIds.value = tabIds.value.filter((tabId) => tabId !== id);
1573
- tabsLayout.removeTabAlias(id);
1574
- tabsLayout.removeTabNavigation(id);
1575
- if (activeId.value === id) activeId.value = nextTab();
1576
- return;
1577
- }
1578
- if (!(await flush())) {
1579
- report('此文档尚有未保存的修改或建议,请先处理保存错误。');
1580
- return;
1581
- }
1582
- try {
1583
- await beforeCloseDocument?.(tabsLayout.tabTarget(id));
1584
- } catch (error) {
1585
- report(error);
1586
- return;
1587
- }
1588
- const target = tabsLayout.tabTarget(id);
1589
- const doc = documentIndex.byId.value.get(target);
1590
- if (doc && ((dirty(doc) && !doc.conflict) || layoutPending(doc))) {
1591
- report('此文档尚未保存,请先另存副本或解决保存错误。');
1592
- return;
1593
- }
1594
- tabIds.value = tabIds.value.filter((tabId) => tabId !== id);
1595
- tabsLayout.removeTabAlias(id);
1596
- tabsLayout.removeTabNavigation(id);
1597
- if (!tabIds.value.some((tabId) => tabsLayout.tabTarget(tabId) === target))
1598
- documents.value = documents.value.filter((d) => d.id !== target);
1599
- if (activeId.value === id) activeId.value = nextTab();
1600
- }
1601
-
1602
- async function resolveConflict(doc: OpenDocument, openCopy: boolean) {
1603
- await serial(async () => {
1604
- if (!doc.conflict) return;
1605
- const copy = doc.conflict.copyPath;
1606
- // Read again: the external writer may have changed the original since the conflict.
1607
- const latest = await adapter.read(doc.path);
1608
- doc.base = latest;
1609
- doc.content = latest.content;
1610
- doc.conflict = undefined;
1611
- doc.missing = false;
1612
- doc.error = undefined;
1613
- if (openCopy) {
1614
- workspace.value = await adapter.refresh();
1615
- const file = fileRegistry.value?.at(copy);
1616
- if (file) {
1617
- await openInternal(file);
1618
- tabsLayout.ensureTabNavigation(file.id, file.id);
1619
- tabsLayout.touchNavigation();
1620
- }
1621
- }
1622
- }).catch(report);
1623
- }
1624
-
1625
- async function reveal() {
1626
- try {
1627
- await adapter.reveal();
1628
- } catch (e) {
1629
- report(e);
1630
- }
1631
- }
1632
439
 
1633
440
  function dispose() {
1634
441
  disposed = true;
1635
442
  helpEdits.dispose();
1636
443
  plugins.disposePlugins();
1637
- stopSessionWatch();
444
+ session.stopSessionWatch();
1638
445
  stopWatching();
1639
- clearTimeout(saveTimer);
446
+ docIO.clearSaveTimer();
1640
447
  }
1641
448
 
1642
449
  return {
@@ -1648,11 +455,11 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1648
455
  discardDataTable: dataTables.discard,
1649
456
  copyDataTable: async (source: DataTable, parent = '') => {
1650
457
  const id = await dataTables.create('blank', source, parent);
1651
- await openDataTable(id);
458
+ await docIO.openDataTable(id);
1652
459
  },
1653
- createDataTable,
1654
- renameDataTable,
1655
- openDataTable,
460
+ createDataTable: docIO.createDataTable,
461
+ renameDataTable: docIO.renameDataTable,
462
+ openDataTable: docIO.openDataTable,
1656
463
  layout: tabsLayout.layout,
1657
464
  windowLayouts: tabsLayout.windowLayouts,
1658
465
  moveTabToWindow: tabsLayout.moveTabToWindow,
@@ -1667,7 +474,10 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1667
474
  resizeSplit: tabsLayout.resizeSplit,
1668
475
  installedPlugins,
1669
476
  installedPluginWorkspace: plugins.installedPluginWorkspace,
477
+ personalCodePluginPolicy: plugins.personalCodePluginPolicy,
1670
478
  pluginRuntime: plugins.pluginRuntime,
479
+ pluginHostEnvironment: plugins.pluginHostEnvironment,
480
+ userPluginIntegrities: plugins.userPluginIntegrities,
1671
481
  canManagePlugins: plugins.canManagePlugins,
1672
482
  canManageSettings: policy.canManageSettings,
1673
483
  authorizePlugin: plugins.pluginServices.authorizePlugin,
@@ -1698,7 +508,6 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1698
508
  relations: knowledge.relations,
1699
509
  relationError: knowledge.relationError,
1700
510
  relationDefinitions: knowledge.relationDefinitions,
1701
- relationIndex: knowledge.relationIndex,
1702
511
  createRelation: knowledge.createRelation,
1703
512
  removeRelation: knowledge.removeRelation,
1704
513
  setRelationSource: knowledge.setRelationSource,
@@ -1728,12 +537,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1728
537
  fileRegistry,
1729
538
  readFileMetadata: knowledge.readFileMetadata,
1730
539
  updateFileMetadata: knowledge.updateFileMetadata,
1731
- createFileDatabase: knowledge.createFileDatabase,
1732
- saveFileDatabase: knowledge.saveFileDatabase,
1733
- createObjectDatabase: knowledge.createObjectDatabase,
1734
540
  deleteObject: knowledge.deleteObject,
1735
- workspaceViews: knowledge.workspaceViews,
1736
- workspaceViewErrors: knowledge.workspaceViewErrors,
1737
541
  displayPath,
1738
542
  fileMutationPending: fileMutations.pending,
1739
543
  documents,
@@ -1759,35 +563,53 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1759
563
  isWeb,
1760
564
  pending,
1761
565
  dirty,
1762
- initialize,
1763
- refreshWorkspaces,
1764
- openWorkspace,
1765
- leaveWorkspace,
1766
- deleteWorkspace,
1767
- createWorkspace,
1768
- openFile,
1769
- prefetchFile,
1770
- openFileInNewTab,
1771
- openAttachment,
1772
- openAttachmentInNewTab,
1773
- openDirectory,
1774
- openFilesInNewTabsAt,
566
+ initialize: lifecycle.initialize,
567
+ refreshWorkspaces: lifecycle.refreshWorkspaces,
568
+ openWorkspace: lifecycle.openWorkspace,
569
+ leaveWorkspace: lifecycle.leaveWorkspace,
570
+ deleteWorkspace: lifecycle.deleteWorkspace,
571
+ createWorkspace: lifecycle.createWorkspace,
572
+ openFile: docIO.openFile,
573
+ prefetchFile: docIO.prefetchFile,
574
+ openFileInNewTab: docIO.openFileInNewTab,
575
+ openAttachment: docIO.openAttachment,
576
+ openAttachmentInNewTab: docIO.openAttachmentInNewTab,
577
+ openDirectory: docIO.openDirectory,
578
+ openFilesInNewTabsAt: docIO.openFilesInNewTabsAt,
1775
579
  createBlankTab: tabsLayout.createBlankTab,
1776
- openGraphTab,
1777
- openWorkspaceView,
1778
- openPluginsTab,
1779
- openPluginDetail,
580
+ openGraphTab: docIO.openGraphTab,
581
+ openPluginsTab: docIO.openPluginsTab,
582
+ openPluginDetail: docIO.openPluginDetail,
1780
583
  openCalendarTab: tabsLayout.openCalendarTab,
1781
584
  registerViews: tabsLayout.registerViews,
1782
585
  pluginViews: plugins.pluginViews,
1783
586
  pluginCommands: plugins.pluginCommands,
587
+ pluginFileHandlers: plugins.pluginFileHandlers,
588
+ pluginSlashCommands: plugins.pluginSlashCommands,
589
+ pluginCodeBlockRenderers: plugins.pluginCodeBlockRenderers,
590
+ pluginDecorationsFor: plugins.pluginDecorationsFor,
591
+ pluginStatusBarItems: plugins.pluginStatusBarItems,
592
+ hasMarkdownFileHandler: docIO.hasMarkdownFileHandler,
1784
593
  activePluginSidebar,
594
+ activeDocumentPluginSidebar: plugins.activeDocumentPluginSidebar,
595
+ activePluginDialog: plugins.activePluginDialog,
596
+ resolvePluginDialog: plugins.resolvePluginDialog,
597
+ pluginToasts: plugins.pluginToasts,
598
+ dismissPluginToast: plugins.dismissPluginToast,
1785
599
  pluginSettingsRequest: plugins.pluginSettingsRequest,
1786
600
  pluginSettingsPages: plugins.pluginSettingsPages,
1787
601
  openPluginView: plugins.openPluginView,
1788
602
  interactWithPlugin: plugins.interactWithPlugin,
603
+ pluginContextProviders: plugins.pluginContextProviders,
604
+ invokePluginAssistantTool: plugins.invokePluginAssistantTool,
605
+ queryPluginAssistantContext: plugins.queryPluginAssistantContext,
606
+ setPluginAiRunner: plugins.setPluginAiRunner,
607
+ overlaySnapshot: plugins.overlaySnapshot,
608
+ setSafeMode: plugins.setSafeMode,
609
+ pluginHomeTabView: plugins.pluginHomeTabView,
610
+ pluginNewTabView: plugins.pluginNewTabView,
1789
611
  openViewTab: tabsLayout.openViewTab,
1790
- readGraphDocument,
612
+ readGraphDocument: docIO.readGraphDocument,
1791
613
  assistantSnapshot: assistantBridge.assistantSnapshot,
1792
614
  assistantSearch: assistantBridge.assistantSearch,
1793
615
  assistantRules: assistantBridge.assistantRules,
@@ -1800,30 +622,29 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1800
622
  writeDocumentSuggestions: assistantBridge.writeDocumentSuggestions,
1801
623
  acceptDocumentSuggestion: assistantBridge.acceptDocumentSuggestion,
1802
624
  setSuggestionPersistence: assistantBridge.setSuggestionPersistence,
1803
- edit,
1804
- editDocument,
1805
- editTableLayout,
625
+ edit: docIO.edit,
626
+ editDocument: docIO.editDocument,
627
+ editTableLayout: docIO.editTableLayout,
1806
628
  preserveDraft: fileOps.preserveDraft,
1807
- receiveDocument,
629
+ receiveDocument: docIO.receiveDocument,
1808
630
  setBeforeWorkspaceChange: (hook?: () => Promise<void>) => {
1809
- beforeWorkspaceChange = hook;
631
+ hooks.beforeWorkspaceChange = hook;
1810
632
  },
1811
- setDocumentLifecycle: (hooks: {
633
+ setDocumentLifecycle: (nextHooks: {
1812
634
  beforeSwitch: () => Promise<void>;
1813
635
  afterSwitch?: () => Promise<void>;
1814
636
  beforeCloseDocument: (id: string) => Promise<void>;
1815
637
  }) => {
1816
- beforeSwitch = hooks.beforeSwitch;
1817
- afterSwitch = hooks.afterSwitch;
1818
- beforeCloseDocument = hooks.beforeCloseDocument;
638
+ hooks.beforeSwitch = nextHooks.beforeSwitch;
639
+ hooks.afterSwitch = nextHooks.afterSwitch;
640
+ hooks.beforeCloseDocument = nextHooks.beforeCloseDocument;
1819
641
  },
1820
- flush,
1821
- refresh,
642
+ flush: docIO.flush,
643
+ refresh: lifecycle.refresh,
1822
644
  enableWorkspacePolling,
1823
645
  search: async (query: string, signal?: AbortSignal) => {
1824
646
  const scope = workspace.value?.id;
1825
647
  if (!scope || !adapter.search || signal?.aborted) return [];
1826
- // Read-only search must not hold the mutation queue while remote files load.
1827
648
  const results = await adapter.search(scope, query, signal);
1828
649
  return workspace.value?.id === scope && !signal?.aborted ? results : [];
1829
650
  },
@@ -1844,9 +665,9 @@ export const useWorkspaceStore = defineStore('workspace', () => {
1844
665
  removeEntries: fileOps.removeEntries,
1845
666
  moveDocument: tabsLayout.moveDocument,
1846
667
  placeTab: tabsLayout.placeTab,
1847
- close,
1848
- resolveConflict,
1849
- reveal,
668
+ close: docIO.close,
669
+ resolveConflict: docIO.resolveConflict,
670
+ reveal: lifecycle.reveal,
1850
671
  dispose,
1851
672
  report,
1852
673
  };