@lincyaw/dsh 0.2.0-rc.11 → 0.2.0-rc.110

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 (41) hide show
  1. package/build/client.mjs +0 -2
  2. package/build/dist/client.js +302 -299
  3. package/build/dist/client.json +76 -41
  4. package/cordis.patch.yml +20 -0
  5. package/entries/deltabox-runtime.mjs +3 -0
  6. package/package.json +12 -9
  7. package/src/client/RootLayout.tsx +18 -15
  8. package/src/client/agent-requests.ts +47 -0
  9. package/src/client/contract.ts +0 -6
  10. package/src/client/dsh.d.ts +12 -0
  11. package/src/client/fallback.tsx +6 -4
  12. package/src/client/frame.css +0 -10
  13. package/src/client/index.tsx +8 -7
  14. package/src/client/layout.ts +9 -6
  15. package/src/client/messages.ts +6 -10
  16. package/src/client/navigation-shell.tsx +2 -2
  17. package/src/client/runtime-diagnostics.tsx +1 -1
  18. package/src/client/settings-launcher.tsx +19 -0
  19. package/src/client/settings-opener.ts +6 -0
  20. package/src/client/speech-settings.tsx +2 -1
  21. package/src/client/startup.css +47 -0
  22. package/src/client/startup.ts +17 -0
  23. package/src/client/styles.css +0 -42
  24. package/src/client/workspace-events.ts +10 -8
  25. package/src/node/bindings.ts +136 -8
  26. package/src/node/context.ts +16 -26
  27. package/src/node/deltabox-runtime.ts +19 -0
  28. package/src/node/dsh-types.ts +31 -1
  29. package/src/node/launch.ts +40 -11
  30. package/src/node/policy.ts +14 -3
  31. package/src/node/routes.ts +10 -3
  32. package/src/node/service.ts +7 -1
  33. package/src/node/startup.ts +73 -0
  34. package/src/node/tools.ts +121 -8
  35. package/src/node/turns.ts +23 -8
  36. package/src/node/workbench.ts +9 -2
  37. package/src/node/workspace-events.ts +7 -4
  38. package/src/startup-messages.ts +15 -0
  39. package/src/workspace-events.ts +3 -2
  40. package/web.patch.yml +18 -6
  41. package/src/client/mascot.tsx +0 -37
@@ -1,11 +1,11 @@
1
- import { connectAuthoringClient, localeOf, Workbench, workspaceClient } from '@lincyaw/workbench'
1
+ import { openAppSettings, registerSettingsLauncher } from './settings-launcher.tsx'
2
+ import { connectAgentActivity, connectAuthoringClient, connectAuthoringWindow, localeOf, Workbench, workspaceClient } from '@lincyaw/workbench'
2
3
  import type { Locale } from '@lincyaw/workbench'
3
4
  import { workspaceSubscriptions } from './workspace-events.ts'
4
5
  import { registerAuthorSettings } from './author-settings.ts'
5
6
  import { registerSpeechSettings } from './speech-settings.tsx'
6
7
  import { openSpeechSettings } from './settings-opener.ts'
7
8
  import { registerBrand } from './brand.tsx'
8
- import { registerMascot } from './mascot.tsx'
9
9
  import { CLIENT_ID, isBootEntryLoaded, ROOT_CHILDREN, UI_LAYOUT, UI_SIDEBAR } from './contract.ts'
10
10
  import { syncDocumentContext } from './document-context.ts'
11
11
  import { FALLBACK_PANEL, registerFallbackLayout } from './fallback.tsx'
@@ -56,6 +56,8 @@ export function apply(ctx: DshClientContext): void {
56
56
  const workbench = new Workbench({ client: workspaceClient('api/presmium/', workspaceSubscriptions(ctx)), locale: workbenchLocale(ctx.locale.getLocale().active) })
57
57
  workbench.client.openSpeechSettings = openSpeechSettings
58
58
  ctx.effect(() => connectAuthoringClient(workbench), 'presmium: authoring client control')
59
+ ctx.effect(() => connectAuthoringWindow(workbench), 'presmium: authoring window control')
60
+ ctx.effect(() => connectAgentActivity(workbench), 'presmium: agent activity')
59
61
  ctx.effect(() => runtimeDiagnostics(workbench).start(), 'presmium: runtime diagnostics')
60
62
  let showEditor = (layout: DshClientContext['layout']) => layout.selectPanel(FALLBACK_PANEL)
61
63
  registerSourceLinks(ctx, workbench, layout => showEditor(layout))
@@ -75,6 +77,8 @@ export function apply(ctx: DshClientContext): void {
75
77
  }, 'presmium: light and dark')
76
78
 
77
79
  if (nativeLayout) {
80
+ // Its default conversation view does not mount HomePanel, so the host owns this first read.
81
+ void workbench.loadDocuments()
78
82
  registerFallbackLayout(ctx, workbench)
79
83
  } else {
80
84
  ctx.effect(() => {
@@ -102,10 +106,7 @@ export function apply(ctx: DshClientContext): void {
102
106
  subscribe: listener => instance.subscribe(listener),
103
107
  })
104
108
  showEditor = () => layout.showDocument()
105
- const openSettings = () => {
106
- const triggers = document.querySelectorAll<HTMLElement>('[data-pmw-slot="sidebar"] button[aria-haspopup="dialog"]')
107
- triggers[triggers.length - 1]?.click()
108
- }
109
+ const openSettings = openAppSettings
109
110
  const disposePanelInfo = ctx.slots.provideRoot({ hooks: { panelInfo: layout.panelInfo } })
110
111
  const disposeRoot = ctx.slots.register({ name: 'root', locale: 'common', children: {
111
112
  ...ROOT_CHILDREN,
@@ -148,8 +149,8 @@ export function apply(ctx: DshClientContext): void {
148
149
  }, 'presmium: the root layout and ctx.layout')
149
150
  }
150
151
  registerBrand(ctx, workbench)
151
- registerMascot(ctx, workbench)
152
152
  registerAuthorSettings(ctx)
153
+ registerSettingsLauncher(ctx, workbench)
153
154
  registerSpeechSettings(ctx, workbench)
154
155
  ctx.inject(['layout'], inner => inner.effect(() => connectLaunchTarget(workbench,
155
156
  () => nativeLayout ? () => {} : restoreRootReturnPoint(workbench, reload.point),
@@ -1,11 +1,11 @@
1
1
  import { defineStore } from '@deepseek-ai/dsh-client-store'
2
+ import { designLength } from '@lincyaw/design'
2
3
 
3
- export const CENTRE_MIN = 400
4
+ export const centreMinWidth = () => designLength('--pm-canvas-min-width')
4
5
  export const RIGHTBAR_MIN = 300
5
6
  export const RIGHTBAR_MAX_RATIO = 0.7
6
7
  export const RIGHTBAR_DEFAULT_RATIO = 0.45
7
8
  export const SIDE_COLLAPSE = 1024
8
- export const NARROW = 768
9
9
  export const SIDE_DEFAULT = 264
10
10
  export const SIDE_MIN = 200
11
11
  export const SIDE_MAX = 420
@@ -15,11 +15,14 @@ export const CONVERSATION_MAX = 640
15
15
  /** The width of one resize handle between two columns: a hairline, with a wider area to grab. */
16
16
  export const HANDLE = 1
17
17
 
18
+ /** A split view needs both panes and its divider; use one pane before constraints become impossible. */
19
+ export const singlePaneWidth = () => Math.max(designLength('--pm-layout-narrow-width'), centreMinWidth() + CONVERSATION_MIN + HANDLE)
20
+
18
21
  export const clamp = (px: number, min: number, max: number) => Math.min(max, Math.max(min, Math.round(px)))
19
22
 
20
23
  /** The width left for the rightbar column: the viewport less the side panel, the conversation, the centre's minimum and `handles` resize handles. */
21
24
  export function rightbarRoom(viewport: number, side: number, conversation: number, handles: number): number {
22
- return viewport - side - conversation - CENTRE_MIN - handles * HANDLE
25
+ return viewport - side - conversation - centreMinWidth() - handles * HANDLE
23
26
  }
24
27
 
25
28
  /** What the side panel shows: the chat history (DeepSeek Harness's sessions). */
@@ -61,7 +64,7 @@ function showHistory(d: LayoutState): void {
61
64
  d.layoutInfo.isSideOpen = true
62
65
  d.layoutInfo.narrowPane = 'sessions'
63
66
  if (d.layoutInfo.viewportWidth < SIDE_COLLAPSE) {
64
- d.layoutInfo.isSideExpanded = d.layoutInfo.viewportWidth >= NARROW
67
+ d.layoutInfo.isSideExpanded = d.layoutInfo.viewportWidth >= singlePaneWidth()
65
68
  d.layoutInfo.isConversationOpen = false
66
69
  } else d.layoutInfo.isConversationOpen = true
67
70
  }
@@ -121,7 +124,7 @@ export function createLayoutStore() {
121
124
  showHistory,
122
125
  toggleConversations: (d: LayoutState) => {
123
126
  const info = d.layoutInfo
124
- if (info.viewportWidth < NARROW) {
127
+ if (info.viewportWidth < singlePaneWidth()) {
125
128
  if (info.narrowPane === 'conversation') showHistory(d)
126
129
  else revealConversation(d)
127
130
  } else {
@@ -157,7 +160,7 @@ export function createLayoutStore() {
157
160
  else d.layoutInfo.isSideOpen = true
158
161
  d.layoutInfo.activity = activity
159
162
  if (d.layoutInfo.viewportWidth < SIDE_COLLAPSE) {
160
- d.layoutInfo.isSideExpanded = d.layoutInfo.viewportWidth >= NARROW
163
+ d.layoutInfo.isSideExpanded = d.layoutInfo.viewportWidth >= singlePaneWidth()
161
164
  if (d.layoutInfo.isSideExpanded) d.layoutInfo.isConversationOpen = false
162
165
  }
163
166
  d.layoutInfo.narrowPane = activity
@@ -17,11 +17,9 @@ const zh = {
17
17
  preview: '文稿',
18
18
  history: '版本历史',
19
19
  settings: '设置',
20
+ preferences: '通用设置',
21
+ mcp: 'MCP 连接',
20
22
  help: '帮助',
21
- mascot: '小猫',
22
- mascotHint: 'AI 助手工作时,对话和文稿旁的小猫会演示它在做什么:思考、阅读、修改或等你确认。',
23
- mascotShow: '显示',
24
- mascotHide: '隐藏',
25
23
  close: '关闭',
26
24
  toggleSide: '显示或隐藏对话记录',
27
25
  keys: {
@@ -41,7 +39,7 @@ const zh = {
41
39
  models: '设置模型',
42
40
  helpItems: [
43
41
  '直接在文稿中输入即可修改。修改自动保存,文稿上方显示“已保存”。',
44
- '选中文字会出现格式工具栏:段落样式、加粗、对齐、颜色、“插入链接”与“新建批注”。“新建批注”在选中的文字上留下批注,“批注”窗格列出全部批注。',
42
+ '选中文字会出现格式工具栏:段落样式、加粗、对齐、颜色、“插入链接”与“新建批注”。“新建批注”在选中的文字上留下批注,“批注”窗格列出全部批注。动画、图表的预览工具栏里有“本步批注”,可以对整个内容块或其中一步批注。',
45
43
  '鼠标移到一段内容上,旁边的“插入内容块”可插入标题、列表、表格、图片等内容,“打开内容块菜单”可删除这一段或修改它的颜色。',
46
44
  '“导航窗格”列出全部页面:“新建页面”添加一页,页面旁的“更多”可以重命名、复制、上移、下移或删除这一页。',
47
45
  '“撤消”({undo})与“恢复”({redo})逐步撤消或恢复修改。“版本历史”列出保存过的每次修改,“撤消此更改”单独撤消其中一次。',
@@ -93,11 +91,9 @@ const en: ClientMessages = {
93
91
  preview: 'Document',
94
92
  history: 'Version History',
95
93
  settings: 'Settings',
94
+ preferences: 'General Settings',
95
+ mcp: 'MCP Connection',
96
96
  help: 'Help',
97
- mascot: 'Kitten',
98
- mascotHint: 'While the AI Assistant works, a kitten beside the chat and the document acts out what it is doing: thinking, reading, changing the document, or waiting for you.',
99
- mascotShow: 'Show',
100
- mascotHide: 'Hide',
101
97
  close: 'Close',
102
98
  toggleSide: 'Show or Hide Chat History',
103
99
  keys: {
@@ -117,7 +113,7 @@ const en: ClientMessages = {
117
113
  models: 'Set Up a Model',
118
114
  helpItems: [
119
115
  'Type directly in the document to change it. Changes save automatically, and the top of the document shows Saved.',
120
- 'Select text to show the formatting toolbar: paragraph style, Bold, alignment, Colors, Insert Link, and New Comment. New Comment leaves a comment on the selected text; the Comments pane lists them all.',
116
+ 'Select text to show the formatting toolbar: paragraph style, Bold, alignment, Colors, Insert Link, and New Comment. New Comment leaves a comment on the selected text; the Comments pane lists them all. An animation or chart preview also has Comment on step, for the whole content block or one step.',
121
117
  'Point at a paragraph: Insert Block, beside it, inserts a heading, list, table, picture, and more; Open Block Menu deletes the paragraph or changes its colors.',
122
118
  'The Navigation Pane lists the pages: New Page adds one, and More beside a page renames, duplicates, moves, or deletes it.',
123
119
  'Undo ({undo}) and Redo ({redo}) step back and forth through your changes. Version History lists every saved change; Undo This Change reverses one of them.',
@@ -3,7 +3,7 @@ import type { Workbench } from '@lincyaw/workbench'
3
3
  import type { ReactNode } from 'react'
4
4
  import { isBootEntryLoaded, UI_SIDEBAR } from './contract.ts'
5
5
  import type { LayoutActions, LayoutState } from './layout.ts'
6
- import { NARROW, SIDE_COLLAPSE } from './layout.ts'
6
+ import { singlePaneWidth, SIDE_COLLAPSE } from './layout.ts'
7
7
  import { useClientMessages } from './messages.ts'
8
8
 
9
9
  interface SidebarProps {
@@ -55,7 +55,7 @@ export function registerNavigationShell(ctx: DshClientContext, workbench: Workbe
55
55
  <PmIconButton icon="plus" label={t.newConversation} small onClick={() => void startSession()} />
56
56
  <PmIconButton icon="history" label={t.conversationHistory} small onClick={() => actions.showHistory()} />
57
57
  <PmIconButton icon="close" label={t.hideConversation} small onClick={() => {
58
- if (layout.getSnapshot().layoutInfo.viewportWidth < NARROW) actions.showNarrowPane(workbench.state.document === undefined ? 'documents' : 'preview')
58
+ if (layout.getSnapshot().layoutInfo.viewportWidth < singlePaneWidth()) actions.showNarrowPane(workbench.state.document === undefined ? 'documents' : 'preview')
59
59
  else actions.setConversationOpen(false)
60
60
  }} />
61
61
  </div>
@@ -221,7 +221,7 @@ export function RuntimeDiagnosticsNotice({ workbench, fatal = false }: { workben
221
221
  export class WorkbenchRuntimeBoundary extends Component<{ workbench: Workbench, children: ReactNode }, { failed: boolean }> {
222
222
  state = { failed: false }
223
223
  static getDerivedStateFromError() { return { failed: true } }
224
- componentDidCatch(error: Error): void { runtimeDiagnostics(this.props.workbench).capture(error) }
224
+ componentDidCatch(error: Error): void { runtimeDiagnostics(this.props.workbench).capture(error); window.dispatchEvent(new Event('presmium:startup-failed')) }
225
225
  render() {
226
226
  return this.state.failed ? <main className="pmw-runtime-fallback pm-ui"><RuntimeDiagnosticsNotice workbench={this.props.workbench} fatal /></main> : this.props.children
227
227
  }
@@ -0,0 +1,19 @@
1
+ import { useStartupReady } from './startup.ts'
2
+ import { useLayoutEffect } from 'react'
3
+ import { PmIconButton } from '@lincyaw/workbench'
4
+ import type { Workbench } from '@lincyaw/workbench'
5
+ import { CLIENT_MESSAGES } from './messages.ts'
6
+
7
+ let current: (() => void) | undefined
8
+ /** Public settings.launcher contract; no hidden sidebar DOM or dependency internals. */
9
+ export function openAppSettings(): void { current?.() }
10
+ export function registerSettingsLauncher(ctx: DshClientContext, workbench: Workbench): void {
11
+ ctx.effect(() => ctx.slots.inject('settings.launcher', () => ctx.slots.register({ name: 'settings.launcher' }, function SettingsLauncher({ openSettings }: { openSettings(): void }) {
12
+ useStartupReady(workbench)
13
+ useLayoutEffect(() => {
14
+ current = openSettings
15
+ return () => { if (current === openSettings) current = undefined }
16
+ }, [openSettings])
17
+ return <PmIconButton icon="sliders" label={CLIENT_MESSAGES[workbench.state.locale].settings} onClick={openSettings} />
18
+ })), 'presmium: settings launcher')
19
+ }
@@ -24,3 +24,9 @@ export function openSpeechSettings(): boolean {
24
24
  remembered('presmium-speech')
25
25
  return true
26
26
  }
27
+
28
+ export function openMcpSettings(): boolean {
29
+ if (!remembered) return false
30
+ remembered('presmium-mcp')
31
+ return true
32
+ }
@@ -1,7 +1,8 @@
1
- import { SpeechSettingsPanel, SPEECH_SETTINGS_MESSAGES, WorkbenchProvider } from '@lincyaw/workbench'
1
+ import { McpSettingsPanel, MCP_SETTINGS_MESSAGES, SpeechSettingsPanel, SPEECH_SETTINGS_MESSAGES, WorkbenchProvider } from '@lincyaw/workbench'
2
2
  import type { Workbench } from '@lincyaw/workbench'
3
3
 
4
4
  /** The framework owns Settings navigation; Presmium owns its operator service page. */
5
5
  export function registerSpeechSettings(ctx: DshClientContext, workbench: Workbench): void {
6
+ ctx.effect(() => ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'presmium-mcp', order: 40, label: () => MCP_SETTINGS_MESSAGES[workbench.state.locale].title }, () => <WorkbenchProvider workbench={workbench}><McpSettingsPanel /></WorkbenchProvider>)), 'presmium: MCP connection settings')
6
7
  ctx.effect(() => ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'presmium-speech', order: 30, label: () => SPEECH_SETTINGS_MESSAGES[workbench.state.locale].title }, () => <WorkbenchProvider workbench={workbench}><SpeechSettingsPanel /></WorkbenchProvider>)), 'presmium: voice service settings')
7
8
  }
@@ -0,0 +1,47 @@
1
+ .pm-startup {
2
+ position: fixed;
3
+ inset: 0;
4
+ width: 100%;
5
+ height: 100%;
6
+ max-width: none;
7
+ max-height: none;
8
+ margin: 0;
9
+ border: 0;
10
+ z-index: var(--pm-z-startup);
11
+ display: grid;
12
+ place-items: center;
13
+ box-sizing: border-box;
14
+ padding: var(--pm-space-6);
15
+ background: var(--pm-color-bg);
16
+ color: var(--pm-color-ink);
17
+ font-family: var(--pm-font-sans);
18
+ font-size: var(--pm-text-sm);
19
+ }
20
+ .pm-startup__content {
21
+ display: grid;
22
+ justify-items: center;
23
+ gap: var(--pm-space-3);
24
+ max-width: var(--pm-dialog-width);
25
+ text-align: center;
26
+ }
27
+ .pm-startup__brand {
28
+ display: flex;
29
+ align-items: center;
30
+ gap: var(--pm-space-3);
31
+ margin: 0;
32
+ font-size: var(--pm-text-lg);
33
+ font-weight: var(--pm-weight-semibold);
34
+ }
35
+ .pm-startup__brand svg { width: var(--pm-size-logo); height: var(--pm-size-logo); }
36
+ .pm-startup__status, .pm-startup__actions {
37
+ display: flex;
38
+ align-items: center;
39
+ justify-content: center;
40
+ flex-wrap: wrap;
41
+ gap: var(--pm-space-2);
42
+ }
43
+ .pm-startup__status { margin: 0; color: var(--pm-color-muted); }
44
+ .pm-startup__status svg { width: var(--pm-size-icon); height: var(--pm-size-icon); }
45
+
46
+ .pm-startup__spinner { display: inline-flex; }
47
+ .pm-startup:target { display: none; }
@@ -0,0 +1,17 @@
1
+ import { useEffect, useSyncExternalStore } from 'react'
2
+ import type { Workbench } from '@lincyaw/workbench'
3
+
4
+ /** A committed shell plus its usable document list ends the product startup screen; AI history is independent. */
5
+ export function useStartupReady(workbench: Workbench): void {
6
+ const ready = useSyncExternalStore(workbench.subscribe, () => Boolean(workbench.state.documents || workbench.state.documentsFailure))
7
+ const locale = useSyncExternalStore(workbench.subscribe, () => workbench.state.locale)
8
+ const dark = useSyncExternalStore(workbench.subscribe, () => workbench.state.isDark)
9
+ useEffect(() => {
10
+ if (!ready) return
11
+ try {
12
+ localStorage.setItem('presmium.startup.locale', locale)
13
+ localStorage.setItem('presmium.startup.dark', String(dark))
14
+ } catch { /* Storage is optional. */ }
15
+ window.dispatchEvent(new Event('presmium:workspace-ready'))
16
+ }, [ready, locale, dark])
17
+ }
@@ -1,45 +1,3 @@
1
1
  @import '@lincyaw/design/design.css';
2
2
  @import '@lincyaw/workbench/styles.css';
3
3
  @import './frame.css';
4
-
5
- /* The kitten among the conversation header's actions. */
6
- .pmw-conversation-mascot {
7
- display: inline-flex;
8
- align-items: center;
9
- }
10
-
11
- /* The kitten's row in Settings → General, laid out as Harness's own rows: its name and note, then its choice. */
12
- .pmw-mascot-setting {
13
- display: flex;
14
- align-items: center;
15
- justify-content: space-between;
16
- gap: var(--pm-space-4);
17
- padding-block: var(--pm-space-4);
18
- border-top: var(--pm-size-hairline) solid var(--pm-color-line);
19
- }
20
-
21
- .pmw-mascot-setting__copy {
22
- display: grid;
23
- gap: var(--pm-space-1);
24
- min-width: 0;
25
- }
26
-
27
- .pmw-mascot-setting__title {
28
- margin: 0;
29
- color: var(--pm-color-ink);
30
- font-size: var(--pm-text-sm);
31
- }
32
-
33
- .pmw-mascot-setting__hint {
34
- margin: 0;
35
- color: var(--pm-color-muted);
36
- font-size: var(--pm-text-xs);
37
- }
38
-
39
- .pmw-mascot-setting .pm-ui-segmented {
40
- flex: none;
41
- }
42
-
43
- @media (max-width: 767px) {
44
- .pmw-mascot-setting { flex-wrap: wrap; }
45
- }
@@ -1,12 +1,12 @@
1
1
  import { WebSocket } from 'partysocket'
2
2
  import type { WorkspaceSubscription } from '@lincyaw/workbench'
3
- import type { AuthoringClientAcknowledgement, AuthoringClientEvent, AuthoringClientReport } from '@lincyaw/kernel'
3
+ import type { AuthoringClientEvent, AuthoringWindowEvent } from '@lincyaw/kernel'
4
4
  import { AUTHORING_CLIENT_REQUEST_TIMEOUT_MS } from '@lincyaw/kernel'
5
5
  import { WORKSPACE_EVENTS_PATH, workspaceEventMessage } from '../workspace-events.ts'
6
6
  import type { WorkspaceEventTopic, WorkspaceEventCommand } from '../workspace-events.ts'
7
7
 
8
8
  const TOPICS: Readonly<Record<string, WorkspaceEventTopic>> = {
9
- document: 'document', diagnostics: 'diagnostics', review: 'review', revision: 'ir', job: 'jobs', 'viewer-site': 'viewer-site', 'viewer-control': 'viewer-control', approvals: 'approvals',
9
+ document: 'document', diagnostics: 'diagnostics', review: 'review', revision: 'ir', job: 'jobs', 'viewer-site': 'viewer-site', 'viewer-control': 'viewer-control', approvals: 'approvals', 'agent-activity': 'agent-activity',
10
10
  }
11
11
 
12
12
  /** Each live reader owns one logical subscription; the library owns physical reconnect timing. */
@@ -89,7 +89,7 @@ export function workspaceSubscriptions(ctx: Pick<DshClientContext, 'effect'>): W
89
89
  const topic = TOPICS[name]
90
90
  const query = new URL(address).searchParams
91
91
  const document = query.get('document')
92
- if (!topic || topic === 'authoring-client' || document === null) throw new Error('Invalid workspace event subscription.')
92
+ if (!topic || topic === 'authoring-client' || topic === 'authoring-window' || document === null) throw new Error('Invalid workspace event subscription.')
93
93
  const request: Subscription['request'] = topic === 'viewer-site'
94
94
  ? { type: 'subscribe', id: '', topic, document, app: query.get('app') ?? '', lang: query.get('lang') ?? '', form: query.get('form') === 'slides' ? 'slides' : 'web' }
95
95
  : topic === 'viewer-control' ? { type: 'subscribe', id: '', topic, document, window: query.get('window') ?? '' }
@@ -97,18 +97,20 @@ export function workspaceSubscriptions(ctx: Pick<DshClientContext, 'effect'>): W
97
97
  const reader: Subscription = { request, received, failed, ready }
98
98
  return add(reader)
99
99
  }
100
- subscription.openAuthoringClient = (document, open, received, failed) => {
101
- const reader: Subscription = { request: { type: 'subscribe', id: '', topic: 'authoring-client', document, ...open }, pending: new Map(), failed,
102
- received(raw) { let event: AuthoringClientEvent; try { event = JSON.parse(raw) } catch { return }; if (event.type === 'connected') rejectPublications(reader); received(event) } }
100
+ const openControl = <Event extends { type: string }>(request: Subscription['request'], received: (event: Event) => void, failed: () => void) => {
101
+ const reader: Subscription = { request, pending: new Map(), failed,
102
+ received(raw) { let event: Event; try { event = JSON.parse(raw) } catch { return }; if (event.type === 'connected') rejectPublications(reader); received(event) } }
103
103
  const close = add(reader)
104
- const publish = (kind: 'state' | 'ack', connectionId: string, report: AuthoringClientReport | AuthoringClientAcknowledgement) => new Promise<void>((resolve, reject) => {
104
+ const publish = (kind: 'state' | 'ack', connectionId: string, report: { sequence: number }) => new Promise<void>((resolve, reject) => {
105
105
  if (closed || !readers.has(reader) || !reader.id || socket.readyState !== WebSocket.OPEN || reader.pending!.has(report.sequence)) { reject(new Error('client-transport-disconnected')); return }
106
106
  // A lost publication receipt must release the queue without authorizing a repeated action.
107
107
  const timer = setTimeout(() => { reader.pending!.delete(report.sequence); reject(new Error('client-publication-timeout')) }, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS / 2)
108
108
  reader.pending!.set(report.sequence, { resolve, reject, timer })
109
109
  socket.send(JSON.stringify({ type: 'authoring-client-publish', id: reader.id, connectionId, sequence: report.sequence, kind, value: report }))
110
110
  })
111
- return { close, publish: (connectionId, report) => publish('state', connectionId, report), acknowledge: (connectionId, report) => publish('ack', connectionId, report) }
111
+ return { close, publish: (connectionId: string, report: { sequence: number }) => publish('state', connectionId, report), acknowledge: (connectionId: string, report: { sequence: number }) => publish('ack', connectionId, report) }
112
112
  }
113
+ subscription.openAuthoringClient = (document, open, received, failed) => openControl<AuthoringClientEvent>({ type: 'subscribe', id: '', topic: 'authoring-client', document, ...open }, received, failed)
114
+ subscription.openAuthoringWindow = (open, received, failed) => openControl<AuthoringWindowEvent>({ type: 'subscribe', id: '', topic: 'authoring-window', ...open }, received, failed)
113
115
  return subscription
114
116
  }
@@ -1,20 +1,32 @@
1
1
  import { realpathSync } from 'node:fs'
2
2
  import { relative, resolve, sep } from 'node:path'
3
+ import { isInside } from '@lincyaw/kernel/node'
3
4
  import { connectPresmiumMcp } from '@lincyaw/mcp/client'
4
5
  import { errorMessage, isRecord } from '@lincyaw/kernel'
5
6
  import type { DiagnosticSnapshot, DocumentSummary } from '@lincyaw/kernel'
6
- import type { ListedTool, PresmiumMcpClient } from '@lincyaw/mcp/client'
7
+ import type { ListedTool, PresmiumMcpClient, PreparedMcpCall } from '@lincyaw/mcp/client'
7
8
  import type { DshAgent, DshContext, DshLogger } from './dsh-types.ts'
8
9
  import { SERVER_ROUTES } from './server-routes.ts'
9
10
  import type { WorkspaceServerClient } from './service.ts'
11
+ import { WorkspaceServerClient as CandidateServer } from './service.ts'
12
+ import { WORKSPACE_ROUTES } from './server-routes.ts'
13
+ import { deltaboxOf, runtimeAgent } from './deltabox-runtime.ts'
10
14
 
15
+ /** Fixed inputs owned by one pending invocation, including native resources that need retirement. */
16
+ export interface PreparedBindingCall { signature: string, arguments: Record<string, unknown>, native?: PreparedMcpCall }
11
17
  /** The document an agent session works on: an MCP client with a session token for it, its tools and its diagnostics. */
12
18
  export interface DocumentBinding {
13
19
  agentSessionId: string
14
20
  document: DocumentSummary
15
21
  dir: string
16
22
  client: PresmiumMcpClient
23
+ authorClient: PresmiumMcpClient
24
+ workspaceRoot: string
17
25
  readonly tools: ListedTool[]
26
+ /** Complete metadata for the currently registered model surface; replaced only at tool installation. */
27
+ registeredTools?: readonly ListedTool[]
28
+ /** Ephemeral fixed inputs between pre-execute approval and this exact invocation. */
29
+ preparedCalls?: Map<symbol, PreparedBindingCall>
18
30
  toolChanges: BindingTools
19
31
  diagnostics: BindingDiagnostics
20
32
  }
@@ -151,10 +163,14 @@ export class BindingDiagnostics {
151
163
  }
152
164
 
153
165
  async function closeBinding(binding: DocumentBinding): Promise<void> {
166
+ const prepared = [...binding.preparedCalls?.values() ?? []]
167
+ binding.preparedCalls?.clear()
154
168
  try {
155
- await Promise.all([binding.diagnostics.close(), binding.toolChanges.close()])
169
+ const results = await Promise.allSettled([...prepared.flatMap(value => value.native ? [value.native.close()] : []), binding.diagnostics.close(), binding.toolChanges.close()])
170
+ const failed = results.find(result => result.status === 'rejected')
171
+ if (failed?.status === 'rejected') throw failed.reason
156
172
  } finally {
157
- await binding.client.close()
173
+ await Promise.all([binding.client.close(), binding.authorClient.close()])
158
174
  }
159
175
  }
160
176
 
@@ -189,6 +205,87 @@ export class DocumentBindings {
189
205
  readonly #selectionListeners = new Map<string, SelectionListener>()
190
206
  readonly #selected = new Map<string, string | null>()
191
207
  #closed = false
208
+ readonly #candidates = new Map<string, Promise<WorkspaceServerClient>>()
209
+ readonly #parents = new Map<string, string>()
210
+ readonly #candidateRoots = new Map<string, string>()
211
+ readonly #candidateViews = new Map<string, string>()
212
+ readonly #candidateOwners = new Map<string, Set<string>>()
213
+ readonly #renewCandidates = new Set<string>()
214
+
215
+ rootSessionOf(agent: DshAgent): string {
216
+ const header = agent.session.header as { origin?: string, parentSession?: string } | undefined
217
+ if (header?.origin === 'subagent' && header.parentSession) this.#parents.set(agent.session.id, header.parentSession)
218
+ let id = agent.session.id
219
+ for (let depth = 0; depth < 32 && this.#parents.has(id); depth++) id = this.#parents.get(id)!
220
+ return id
221
+ }
222
+
223
+ async candidateOf(agent: DshAgent): Promise<WorkspaceServerClient> {
224
+ const id = this.rootSessionOf(agent)
225
+ let owners = this.#candidateOwners.get(id)
226
+ if (!owners) this.#candidateOwners.set(id, owners = new Set())
227
+ owners.add(agent.session.id)
228
+ let pending = this.#candidates.get(id)
229
+ if (!pending) {
230
+ pending = (async () => {
231
+ const { root } = await this.#server.requestJson<{ root: string }>(`${WORKSPACE_ROUTES}review/workspace`, { body: { session: id } })
232
+ this.#candidateRoots.set(id, root)
233
+ const runtime = deltaboxOf(this.#ctx)
234
+ const previous = runtime?.existingSession(runtimeAgent(agent))
235
+ if (previous && previous.projectRoot !== root) await previous.close()
236
+ const session = await runtime?.acquireFor(runtimeAgent(agent))
237
+ if (session?.recoveredFrom && session.reviewActive) await session.reviewCommit()
238
+ if (session) await this.#server.requestJson(`${WORKSPACE_ROUTES}review/workspace`, { body: { session: id, resumed: true } })
239
+ const view = session ? (await session.target()).mountpoint : root
240
+ this.#candidateViews.set(id, view)
241
+ const candidate = new CandidateServer({ root: view, candidate: true, presmium: this.#server.presmium }, this.#log)
242
+ await candidate.ready
243
+ return candidate
244
+ })()
245
+ this.#candidates.set(id, pending)
246
+ void pending.catch(() => { if (this.#candidates.get(id) === pending) this.#candidates.delete(id) })
247
+ }
248
+ const candidate = await pending
249
+ const directory = await candidate.ready
250
+ const workingDirectory = this.#ctx.get('workingDirectory') as { set(agent: DshAgent, path: string): Promise<string> } | undefined
251
+ if (!workingDirectory) throw new Error('Presmium needs the workingDirectory service for concurrent authoring')
252
+ if (!isInside(this.workingDirectoryOf(agent), directory.root)) await workingDirectory.set(agent, directory.root)
253
+ return candidate
254
+ }
255
+
256
+ candidateRootOf(agent: DshAgent | undefined): string | undefined {
257
+ return agent ? this.#candidateRoots.get(this.rootSessionOf(agent)) : undefined
258
+ }
259
+
260
+ candidateViewOf(agent: DshAgent | undefined): string | undefined {
261
+ return agent ? this.#candidateViews.get(this.rootSessionOf(agent)) : undefined
262
+ }
263
+
264
+ async refreshCandidate(agent: DshAgent): Promise<void> {
265
+ const { root } = await this.#server.ready
266
+ if (!this.candidateRootOf(agent) && !isInside(this.workingDirectoryOf(agent), root)) return
267
+ await this.candidateOf(agent)
268
+ const id = this.rootSessionOf(agent)
269
+ const { changed } = await this.#server.requestJson<{ changed: boolean }>(`${WORKSPACE_ROUTES}review/workspace`, { body: { session: id, refresh: true } })
270
+ if (deltaboxOf(this.#ctx) && (changed || this.#renewCandidates.has(id))) {
271
+ await this.retireCandidate(agent)
272
+ await this.candidateOf(agent)
273
+ }
274
+ }
275
+
276
+ candidateChanged(agent: DshAgent): void { this.#renewCandidates.add(this.rootSessionOf(agent)) }
277
+
278
+ /** Retire the private view only at a tool/step boundary, before its next binding is installed. */
279
+ async retireCandidate(agent: DshAgent): Promise<void> {
280
+ const id = this.rootSessionOf(agent)
281
+ await this.unbind(agent.session.id, false)
282
+ const candidate = this.#candidates.get(id)
283
+ this.#candidates.delete(id)
284
+ if (candidate) await (await candidate).close()
285
+ this.#candidateViews.delete(id)
286
+ await deltaboxOf(this.#ctx)?.existingSession(runtimeAgent(agent))?.close()
287
+ this.#renewCandidates.delete(id)
288
+ }
192
289
 
193
290
  constructor(ctx: DshContext, server: WorkspaceServerClient, log: DshLogger) {
194
291
  this.#ctx = ctx
@@ -228,18 +325,26 @@ export class DocumentBindings {
228
325
  const id = agent.session.id
229
326
  const documents = await this.#server.readDocuments()
230
327
  const selected = this.#selected.get(id)
231
- const document = selected === undefined ? documentAt(root, this.workingDirectoryOf(agent), documents) : documents.find(doc => doc.dir === selected)
328
+ const cwd = this.workingDirectoryOf(agent)
329
+ if (!this.candidateRootOf(agent) && !isInside(cwd, root)) return undefined
330
+ const document = selected === undefined ? documentAt(root, agent.session.header?.cwd ?? root, documents) ?? (documents.length === 1 ? documents[0] : undefined) : documents.find(doc => doc.dir === selected)
232
331
  if (!current()) return undefined
233
332
  if (!document) {
234
333
  this.#failures.delete(id)
235
334
  return undefined
236
335
  }
237
- const grant = await this.#server.requestJson<{ url: string, token: string }>(`${SERVER_ROUTES}tokens`, { body: { document: document.dir, session: id } })
336
+ const candidate = await this.candidateOf(agent)
337
+ const [grant, authorGrant] = await Promise.all([
338
+ candidate.requestJson<{ url: string, token: string }>(`${SERVER_ROUTES}tokens`, { body: { document: document.dir, session: id } }),
339
+ this.#server.requestJson<{ url: string, token: string }>(`${SERVER_ROUTES}tokens`, { body: { document: document.dir, session: id } }),
340
+ ])
238
341
  const client = await connectPresmiumMcp(grant.url, grant.token)
239
- const diagnostics = new BindingDiagnostics(client, document.dir)
342
+ const authorClient = await connectPresmiumMcp(authorGrant.url, authorGrant.token)
343
+ const diagnostics = new BindingDiagnostics(authorClient, document.dir)
240
344
  const toolChanges = new BindingTools(client, this.#log)
241
345
  try {
242
- const binding: DocumentBinding = { agentSessionId: id, document, dir: resolve(root, document.dir), client, get tools() { return toolChanges.snapshot }, toolChanges, diagnostics }
346
+ const workspaceRoot = (await candidate.ready).root
347
+ const binding: DocumentBinding = { agentSessionId: id, document, dir: resolve(workspaceRoot, document.dir), workspaceRoot, client, authorClient, get tools() { return toolChanges.snapshot }, toolChanges, diagnostics }
243
348
  await toolChanges.start()
244
349
  await diagnostics.start()
245
350
  if (current()) {
@@ -250,9 +355,10 @@ export class DocumentBindings {
250
355
  } catch (error) {
251
356
  await Promise.all([diagnostics.close(), toolChanges.close()]).catch(() => undefined)
252
357
  await client.close().catch(() => undefined)
358
+ await authorClient.close().catch(() => undefined)
253
359
  throw error
254
360
  }
255
- await Promise.all([diagnostics.close(), toolChanges.close()]).finally(() => client.close())
361
+ await Promise.all([diagnostics.close(), toolChanges.close()]).finally(() => Promise.all([client.close(), authorClient.close()]))
256
362
  return undefined
257
363
  }
258
364
 
@@ -315,6 +421,8 @@ export class DocumentBindings {
315
421
 
316
422
  /** Closes the session's binding and revokes its session token; `forget` drops its selection too. */
317
423
  async unbind(agentSessionId: string, forget = true): Promise<void> {
424
+ let ownerId = agentSessionId
425
+ for (let depth = 0; depth < 32 && this.#parents.has(ownerId); depth++) ownerId = this.#parents.get(ownerId)!
318
426
  if (forget) {
319
427
  this.#selectionVersions.delete(agentSessionId)
320
428
  this.#selected.delete(agentSessionId)
@@ -327,6 +435,20 @@ export class DocumentBindings {
327
435
  this.#failures.delete(agentSessionId)
328
436
  if (binding) await closeBinding(binding).catch(error => this.#log.warn(`presmium-service: closing session ${agentSessionId}: ${errorMessage(error)}`))
329
437
  else await request
438
+ if (forget) {
439
+ this.#parents.delete(agentSessionId)
440
+ const owners = this.#candidateOwners.get(ownerId)
441
+ owners?.delete(agentSessionId)
442
+ if (owners?.size === 0) {
443
+ this.#candidateOwners.delete(ownerId)
444
+ this.#candidateRoots.delete(ownerId)
445
+ this.#candidateViews.delete(ownerId)
446
+ const candidate = this.#candidates.get(ownerId)
447
+ this.#candidates.delete(ownerId)
448
+ if (candidate) await (await candidate).close()
449
+ await this.#server.requestJson(`${WORKSPACE_ROUTES}review/workspace`, { body: { session: ownerId, close: true } })
450
+ }
451
+ }
330
452
  if (!binding && !request) return
331
453
  await this.#server.request(`${SERVER_ROUTES}tokens`, { method: 'DELETE', body: { session: agentSessionId } }).then(r => r.body?.cancel(), () => undefined)
332
454
  }
@@ -341,5 +463,11 @@ export class DocumentBindings {
341
463
  this.#selected.clear()
342
464
  this.#selectionVersions.clear()
343
465
  this.#selectionListeners.clear()
466
+ await Promise.all([...this.#candidates.values()].map(async candidate => (await candidate).close()))
467
+ this.#candidates.clear()
468
+ this.#candidateRoots.clear()
469
+ this.#candidateViews.clear()
470
+ this.#candidateOwners.clear()
471
+ this.#parents.clear()
344
472
  }
345
473
  }