moi-computer 0.12.0 → 0.12.1-next.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 (140) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/app-ui-keys.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -3
  5. package/client/app/routes/WorkspaceRoute.tsx +2 -8
  6. package/client/features/applets/applet-runtime.ts +11 -13
  7. package/client/features/chat/ChatPanel.tsx +70 -49
  8. package/client/features/chat/ChatPopup.tsx +81 -8
  9. package/client/features/chat/applet-chat-intents.ts +31 -12
  10. package/client/features/chat/chat-send.ts +33 -1
  11. package/client/features/chat/chat-store.ts +10 -0
  12. package/client/features/chat/composer/ChatComposer.tsx +24 -27
  13. package/client/features/chat/composer/ModelPicker.tsx +3 -3
  14. package/client/features/chat/composer/useWorkspaceComposerState.tsx +3 -3
  15. package/client/features/chat/connection/chat-frames.ts +14 -7
  16. package/client/features/chat/messages/ChatEmptyState.tsx +33 -19
  17. package/client/features/chat/messages/MarkdownContent.tsx +3 -3
  18. package/client/features/chat/messages/fork-history.ts +14 -0
  19. package/client/features/chat/sessions/ChatSelector.tsx +138 -79
  20. package/client/features/chat/sessions/api.ts +109 -19
  21. package/client/features/chat/sessions/browser-tab-state.ts +30 -7
  22. package/client/features/chat/sessions/useSelectedSession.ts +217 -51
  23. package/client/features/chat/useChat.ts +43 -45
  24. package/client/features/collab/client.ts +10 -11
  25. package/client/features/collab/hooks.tsx +6 -11
  26. package/client/features/collab/host-state.ts +57 -128
  27. package/client/features/collab/provider.tsx +3 -3
  28. package/client/features/collab/testing/fake-engine.ts +6 -27
  29. package/client/features/collab/workspace-users-menu.tsx +3 -7
  30. package/client/features/drawings/{useViewBuilderSketch.ts → useViewSketch.ts} +7 -7
  31. package/client/features/home/HomePage.tsx +2 -2
  32. package/client/features/overview/Overview.tsx +3 -6
  33. package/client/features/overview/default/ViewsWidget.tsx +5 -12
  34. package/client/features/overview/default/registry.tsx +2 -4
  35. package/client/features/views/PendingViewScreen.tsx +279 -0
  36. package/client/features/views/ViewManager.tsx +10 -10
  37. package/client/features/views/api.ts +63 -130
  38. package/client/features/views/useViewActions.ts +151 -0
  39. package/client/features/views/useViewDrafts.ts +79 -0
  40. package/client/features/views/view-presentation.ts +4 -5
  41. package/client/features/views/view-submission.ts +88 -0
  42. package/client/features/workspace/WorkspaceMenu.tsx +63 -0
  43. package/client/features/workspace/WorkspaceScreen.tsx +180 -375
  44. package/client/features/workspace/browser-tab-state.ts +16 -9
  45. package/client/features/workspace/moi-context.ts +13 -15
  46. package/client/features/workspace/tab-resolution.ts +16 -29
  47. package/client/features/workspace/useWorkspaceNavigation.ts +146 -104
  48. package/client/index.tsx +5 -1
  49. package/client/runtime/useWorkspaceEvents.ts +7 -6
  50. package/client/store/ui.ts +25 -29
  51. package/dist/chunk-1zhnhy00.js +1 -0
  52. package/dist/chunk-27501vke.js +1 -0
  53. package/dist/{chunk-jf6czgrz.js → chunk-9xtv6djt.js} +2 -2
  54. package/dist/chunk-am1x230f.js +2 -0
  55. package/dist/{chunk-nez8sdta.js → chunk-darpsw65.js} +1 -1
  56. package/dist/{chunk-97eg9mjn.js → chunk-gps4qc38.js} +1 -1
  57. package/dist/{chunk-3a48fyf7.js → chunk-hzwr8dp8.js} +4 -4
  58. package/dist/{chunk-efdyz6xp.js → chunk-j905va8r.js} +1 -1
  59. package/dist/chunk-n33w9y38.js +10 -0
  60. package/dist/chunk-r63ks44z.js +68 -0
  61. package/dist/{chunk-vfpsc75k.js → chunk-vqpkqtdr.js} +1 -1
  62. package/dist/chunk-wd46nk26.css +1 -0
  63. package/dist/chunk-xgt7vxt9.js +1 -0
  64. package/dist/{chunk-z3byfve5.js → chunk-yvzhwtfa.js} +2 -2
  65. package/dist/index.html +1 -1
  66. package/lib/ids.ts +2 -5
  67. package/lib/moi-context.ts +100 -73
  68. package/lib/navigation.ts +48 -87
  69. package/lib/session-drafts.ts +10 -0
  70. package/lib/types.ts +64 -31
  71. package/lib/view-build-directives.ts +12 -0
  72. package/lib/workspace-layout.ts +1 -1
  73. package/lib/workspace-tabs.ts +12 -7
  74. package/package.json +3 -1
  75. package/server/agent-launcher.ts +27 -0
  76. package/server/api.ts +119 -209
  77. package/server/app-config.ts +21 -2
  78. package/server/applets/build-worker.ts +2 -1
  79. package/server/applets/view-source.ts +7 -1
  80. package/server/cli-env.ts +72 -50
  81. package/server/cli.ts +101 -64
  82. package/server/control.ts +82 -63
  83. package/server/data-dir.ts +13 -0
  84. package/server/functions.ts +2 -1
  85. package/server/harness/README.md +8 -0
  86. package/server/harness/acp/adapter.ts +2 -2
  87. package/server/harness/acp/client.ts +2 -1
  88. package/server/harness/acp/discovery.ts +3 -3
  89. package/server/harness/acp/session.ts +6 -9
  90. package/server/harness/claude-code/adapter.ts +13 -8
  91. package/server/harness/claude-code/auth.ts +3 -2
  92. package/server/harness/claude-code/cli.ts +3 -1
  93. package/server/harness/claude-code/git-worktree.ts +5 -2
  94. package/server/harness/claude-code/index.ts +5 -0
  95. package/server/harness/claude-code/mcp.ts +2 -0
  96. package/server/harness/claude-code/models.ts +2 -0
  97. package/server/harness/claude-code/session.ts +5 -34
  98. package/server/harness/claude-code/sessions.ts +8 -12
  99. package/server/harness/codex/NOTES.md +23 -4
  100. package/server/harness/codex/adapter.ts +5 -3
  101. package/server/harness/codex/client.ts +13 -21
  102. package/server/harness/codex/index.ts +18 -0
  103. package/server/harness/codex/session.ts +6 -14
  104. package/server/harness/codex/thread-list.ts +74 -0
  105. package/server/harness/fork.ts +12 -0
  106. package/server/harness/openclaw/adapter.ts +3 -3
  107. package/server/harness/openclaw/session.ts +2 -30
  108. package/server/harness/session-title.ts +12 -3
  109. package/server/harness/types.ts +8 -3
  110. package/server/moi-scaffold.ts +2 -1
  111. package/server/pending-views.ts +164 -0
  112. package/server/registry.ts +14 -4
  113. package/server/selected-session.ts +91 -44
  114. package/server/service.ts +16 -2
  115. package/server/session-archive.ts +32 -0
  116. package/server/session-config.ts +16 -111
  117. package/server/session-lifecycle.ts +17 -0
  118. package/server/session-store.ts +127 -0
  119. package/server/status.ts +3 -1
  120. package/server/tabs.ts +7 -10
  121. package/server/view-sessions.ts +267 -0
  122. package/server/views.ts +30 -41
  123. package/server/web.ts +47 -45
  124. package/server/workspace-env.ts +27 -0
  125. package/server/workspace-init.ts +6 -2
  126. package/workspace/.claude/skills/moi-workspace/SKILL.md +49 -20
  127. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +2 -5
  128. package/client/features/views/ViewBuilder.tsx +0 -239
  129. package/client/features/views/useViewBuilderActions.ts +0 -103
  130. package/client/features/views/useViewBuilderDrafts.ts +0 -68
  131. package/dist/chunk-2jncyq65.js +0 -1
  132. package/dist/chunk-e2q5ken7.js +0 -68
  133. package/dist/chunk-h2kj1ysj.js +0 -1
  134. package/dist/chunk-nzwgm8vc.css +0 -1
  135. package/dist/chunk-ph0h6h86.js +0 -1
  136. package/dist/chunk-ryg9z3kn.js +0 -10
  137. package/dist/chunk-tpn177bt.js +0 -2
  138. package/lib/view-builder-directives.ts +0 -16
  139. package/server/chat-selection.ts +0 -22
  140. package/server/view-builders.ts +0 -453
@@ -1,2 +0,0 @@
1
- var X=["pink","orange","amber","lime","emerald","cyan","blue","violet"];function V(f){return typeof f==="string"&&X.includes(f)}function Z(f){let A=2166136261;for(let C=0;C<f.length;C++)A^=f.charCodeAt(C),A=Math.imul(A,16777619);return X[(A>>>0)%X.length]??X[0]}var o=1;var w=8192,D=320;function H(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function j(f,A=256){return typeof f==="string"&&f.length>0&&!f.includes("\x00")&&new TextEncoder().encode(f).length<=A}function $(f){return H(f)&&j(f.id,240)&&f.id.trim().length>0&&(f.name===void 0||j(f.name)&&f.name.trim().length>0)&&V(f.color)&&(f.avatar===void 0||j(f.avatar,w))&&(f.email===void 0||j(f.email,D))}var I=["Curious Kiwi","Cheerful Cherry","Sleepy Peach","Excited Banana","Cosmic Mango","Velvet Lemon","Electric Plum","Wandering Pear","Dramatic Papaya","Suspicious Pineapple","Confused Coconut","Sneaky Tangerine","Gentle Fig","Quiet Apricot","Mellow Melon","Dreamy Guava"];function y(f,A){let C=f.filter((g)=>g!==A);return C[Math.floor(Math.random()*C.length)]??f[0]}function R(f){return{name:y(I,f?.name),color:y(X,f?.color)}}function m(f,A){let C=A.name.trim();return{id:f,...C?{name:C}:{},color:A.color}}function Y(){return m(`local-${crypto.randomUUID().slice(0,8)}`,R())}var W="moi:collab:dev-profile",T,F=!1,M,J=new Set,_=new Map,E=new Set,b=Object.freeze({}),L=Object.freeze({status:"loading"}),N;function n(f){if(!f||typeof f.id!=="string"||!f.id.trim())throw Error("A user profile needs an id.");if(f.name!==void 0&&typeof f.name!=="string")throw Error("A user profile name must be a string when provided.");if(f.color!==void 0&&!V(f.color))throw Error("A user profile color must be one of the user palette names.");let A=f.id.trim(),C=f.name?.trim(),g={id:A,...C?{name:C}:{},color:f.color??Z(A),...f.avatar!==void 0?{avatar:f.avatar}:{},...f.email!==void 0?{email:f.email}:{}};if(!$(g))throw Error("Invalid user profile.");return Object.freeze(g)}function k(f){if(!Array.isArray(f))throw Error("Workspace users must be an array.");let A=new Set,C=f.map((g)=>{let B=n(g);if(A.has(B.id))throw Error("Workspace users must have unique ids.");return A.add(B.id),B});return Object.freeze(C)}function z(f){if(!f||typeof f!=="object")throw Error("Invalid host state.");let A=f.currentUser===void 0?void 0:n(f.currentUser);if(!f.workspaces||typeof f.workspaces!=="object"||Array.isArray(f.workspaces))throw Error("Host workspaces must be a record.");let C=Object.entries(f.workspaces).map(([g,B])=>{if(!g.trim()||!B||typeof B!=="object")throw Error("Invalid workspace directory.");if(B.status==="loading")return[g,L];if(B.status!=="ready")throw Error("Invalid workspace directory status.");let x=k(B.users),P=Object.freeze(x.map((Q)=>A&&Q.id===A.id?A:Q));return[g,Object.freeze({status:"ready",users:P})]});return Object.freeze({currentUser:A,workspaces:A?Object.freeze(Object.fromEntries(C)):b})}function G(){return N}function O(f){if(!N)return;return(Object.hasOwn(N.workspaces,f)?N.workspaces[f]:void 0)??L}function q(f){let A=z(f),C=new Map([..._.keys()].map((g)=>[g,O(g)]));N=A,M="external",T=A.currentUser,J.forEach((g)=>g());for(let[g,B]of _)if(O(g)!==C.get(g))B.forEach((x)=>x());E.forEach((g)=>g())}function h(f){return E.add(f),()=>{E.delete(f)}}function p(f){let A=h(()=>f(G()));return f(G()),A}function l(f,A){let C=_.get(f);if(!C)C=new Set,_.set(f,C);return C.add(A),()=>{if(C.delete(A),!C.size)_.delete(f)}}function s(){return T}function r(f){return J.add(f),()=>{J.delete(f)}}function e({provider:f,profile:A}){if(M==="external")return;if(f===void 0){if(M===void 0||M==="local")return;M=void 0,T=void 0}else{let C=A===void 0?void 0:n(A);if(M===f&&JSON.stringify(T)===JSON.stringify(C))return;M=f,T=C}J.forEach((C)=>C())}function S(){try{sessionStorage.setItem(W,JSON.stringify(T))}catch{}}function K(f){if(M!==void 0&&M!=="local")return;let A=n(f);M="local",T=A,S(),J.forEach((C)=>C())}function ff(f,A){if(!f||!A||A.provider!==void 0||M!==void 0)return;try{let C=sessionStorage.getItem(W);if(C){K(JSON.parse(C));return}}catch{}K(Y())}function Af(){if(typeof window>"u"||F)return;F=!0;let f=window,A=f.moi?.collab;if(A?.getHostState)try{q(A.getHostState()??{workspaces:{}})}catch{q({workspaces:{}})}f.moi??={};let C={getHostState:G,setHostState:q,subscribeHostState:p};if(f.moi.collab=C,typeof window.dispatchEvent==="function")window.dispatchEvent(new CustomEvent("moi:collab-ready"))}
2
- export{o as Fc,O as Gc,l as Hc,s as Ic,r as Jc,e as Kc,ff as Lc,Af as Mc};
@@ -1,16 +0,0 @@
1
- // View-builder bootstrap instructions, delivered as one-shot directives inside
2
- // the `<moi-context>` envelope (lib/moi-context.ts) via SendMessageInput's
3
- // `context` channel — see the view-builder POST route in server/api.ts.
4
- export function viewBuilderDirectives(builderId: string, availableIcons: string[]): string[] {
5
- return [
6
- 'View builder request — this chat is linked to a pending view tab.',
7
- `Builder id: ${builderId}`,
8
- `Available view icons: ${availableIcons.join(', ')}`,
9
- 'Your first action must be to infer a stable view id, sentence-case title, and relevant icon from the requirements, then run:',
10
- `moi builder set <view-id> --builder ${builderId} --kind view --title "<title>" --icon <icon-id>`,
11
- 'Do this before reading files, planning, or writing code. Choose the icon id from the available view icons above.',
12
- 'Capitalize only the first word of the title.',
13
- 'Use the same icon id in the view config.',
14
- 'After building the view, run `moi bundle --only views`.'
15
- ]
16
- }
@@ -1,22 +0,0 @@
1
- import type { SelectedSessionScope, WorkspaceEntry } from '@/lib/types'
2
-
3
- import { publishEvent } from './events'
4
- import { saveSelectedSession } from './selected-session'
5
-
6
- // A new chat updates the shared selection only when this tab uses that scope.
7
- export async function selectChatSession(
8
- workspace: Pick<WorkspaceEntry, 'id' | 'path'>,
9
- sessionId: string,
10
- selectedSessionScope: SelectedSessionScope = 'shared',
11
- previousSessionId?: string | null
12
- ): Promise<void> {
13
- if (selectedSessionScope === 'browser-tab') return
14
- const selection = await saveSelectedSession(workspace.path, sessionId, previousSessionId)
15
- if (selection.changed) {
16
- publishEvent({
17
- type: 'selected-session:updated',
18
- workspaceId: workspace.id,
19
- sessionId: selection.sessionId
20
- })
21
- }
22
- }
@@ -1,453 +0,0 @@
1
- import { mkdir, rename } from 'node:fs/promises'
2
- import { join } from 'node:path'
3
-
4
- import { APP_ICON_IDS, isAppIconId } from '@/lib/app-icons'
5
- import { newBuilderId } from '@/lib/ids'
6
- import type { AppletKind, ViewBuilder, ViewInfo } from '@/lib/types'
7
-
8
- import { DATA_DIR } from './data-dir'
9
- import { publishEvent } from './events'
10
-
11
- type ViewBuilderStore = Record<string, ViewBuilder[]>
12
-
13
- // A build running past this is treated as hung/abandoned and reconciled back to
14
- // `waiting`, even if its session still looks live. Generous so a slow but real
15
- // build is never cut off mid-flight.
16
- const STALE_BUILD_MS = 10 * 60_000
17
- const APP_ICON_NAMES: readonly string[] = APP_ICON_IDS
18
-
19
- export class ViewBuilderError extends Error {
20
- status: 400 | 404 | 409
21
-
22
- constructor(message: string, status: 400 | 404 | 409) {
23
- super(message)
24
- this.name = 'ViewBuilderError'
25
- this.status = status
26
- }
27
- }
28
-
29
- let storePath = join(DATA_DIR, 'view-builders.json')
30
- let writeChain: Promise<unknown> = Promise.resolve()
31
-
32
- export function setViewBuilderStorePath(path: string): void {
33
- storePath = path
34
- }
35
-
36
- async function readStore(): Promise<ViewBuilderStore> {
37
- try {
38
- const parsed = JSON.parse(await Bun.file(storePath).text())
39
- return parsed && typeof parsed === 'object' ? (parsed as ViewBuilderStore) : {}
40
- } catch {
41
- return {}
42
- }
43
- }
44
-
45
- async function writeStore(store: ViewBuilderStore): Promise<void> {
46
- await mkdir(join(storePath, '..'), { recursive: true })
47
- const tmp = `${storePath}.${process.pid}.tmp`
48
- await Bun.write(tmp, JSON.stringify(store, null, 2))
49
- await rename(tmp, storePath)
50
- }
51
-
52
- function locked<T>(fn: () => Promise<T>): Promise<T> {
53
- const run = writeChain.then(fn, fn)
54
- writeChain = run.catch(() => {})
55
- return run
56
- }
57
-
58
- async function mutateBuilders<T>(
59
- workspacePath: string,
60
- mutate: (builders: ViewBuilder[]) => T
61
- ): Promise<T> {
62
- return locked(async () => {
63
- const store = await readStore()
64
- const previous = store[workspacePath] ?? []
65
- const builders = [...previous]
66
- const result = mutate(builders)
67
- // Builder records are immutable inside mutations, so reference equality is
68
- // enough to detect a real add, replacement, or deletion.
69
- const changed =
70
- builders.length !== previous.length ||
71
- builders.some((builder, index) => builder !== previous[index])
72
- if (!changed) return result
73
- if (builders.length > 0) store[workspacePath] = builders
74
- else delete store[workspacePath]
75
- await writeStore(store)
76
- return result
77
- })
78
- }
79
-
80
- function updated(builder: ViewBuilder, patch: Partial<ViewBuilder>): ViewBuilder {
81
- return { ...builder, ...patch, updatedAt: Math.max(Date.now(), builder.updatedAt + 1) }
82
- }
83
-
84
- function replace(builders: ViewBuilder[], index: number, builder: ViewBuilder): ViewBuilder {
85
- builders[index] = builder
86
- return builder
87
- }
88
-
89
- function findBuilder(builders: ViewBuilder[], builderId: string): [ViewBuilder, number] {
90
- const index = builders.findIndex(builder => builder.id === builderId)
91
- if (index === -1) throw new ViewBuilderError('View builder not found', 404)
92
- return [builders[index], index]
93
- }
94
-
95
- function publishUpdated(workspaceId: string, builder: ViewBuilder): void {
96
- // Widget builders are record-only for now — no host UI consumes them, so keep
97
- // them off the client event stream (and out of the view-builder tab list).
98
- if (builder.kind === 'widget') return
99
- publishEvent({ type: 'view-builder:updated', workspaceId, builder })
100
- }
101
-
102
- export async function listViewBuilders(workspacePath: string): Promise<ViewBuilder[]> {
103
- return (await readStore())[workspacePath] ?? []
104
- }
105
-
106
- export async function createViewBuilder(
107
- workspaceId: string,
108
- workspacePath: string
109
- ): Promise<ViewBuilder> {
110
- const builder = await mutateBuilders(workspacePath, builders => {
111
- const now = Date.now()
112
- const created: ViewBuilder = {
113
- id: newBuilderId(),
114
- kind: 'view',
115
- status: 'draft',
116
- input: { requirements: '' },
117
- sessionId: crypto.randomUUID(),
118
- createdAt: now,
119
- updatedAt: now
120
- }
121
- builders.push(created)
122
- return created
123
- })
124
- publishUpdated(workspaceId, builder)
125
- return builder
126
- }
127
-
128
- export async function updateViewBuilderInput(
129
- workspaceId: string,
130
- workspacePath: string,
131
- builderId: string,
132
- requirements: string
133
- ): Promise<ViewBuilder> {
134
- const builder = await mutateBuilders(workspacePath, builders => {
135
- const [current, index] = findBuilder(builders, builderId)
136
- if (current.status !== 'draft') {
137
- throw new ViewBuilderError('Submitted view builder input cannot be changed', 409)
138
- }
139
- return replace(builders, index, updated(current, { input: { requirements } }))
140
- })
141
- publishUpdated(workspaceId, builder)
142
- return builder
143
- }
144
-
145
- export async function beginViewBuilder(
146
- workspaceId: string,
147
- workspacePath: string,
148
- builderId: string,
149
- requirements: string,
150
- hasSketch = false
151
- ): Promise<ViewBuilder> {
152
- const text = requirements.trim()
153
- if (!text && !hasSketch)
154
- throw new ViewBuilderError('View requirements or an attachment are required', 400)
155
- const builder = await mutateBuilders(workspacePath, builders => {
156
- const [current, index] = findBuilder(builders, builderId)
157
- if (current.status !== 'draft') {
158
- throw new ViewBuilderError('View builder has already been submitted', 409)
159
- }
160
- const { error: _error, ...withoutError } = current
161
- return replace(
162
- builders,
163
- index,
164
- updated(withoutError as ViewBuilder, {
165
- status: 'building',
166
- buildingSince: Date.now(),
167
- input: { requirements: text }
168
- })
169
- )
170
- })
171
- publishUpdated(workspaceId, builder)
172
- return builder
173
- }
174
-
175
- type SetBuilderInput = {
176
- // Correlation handle for a pending, UI-initiated builder (the value injected
177
- // into the agent's prompt). Omitted for a standalone/widget build, which is
178
- // then keyed and upserted by its applet id.
179
- builderId?: string
180
- kind?: AppletKind
181
- // The states the agent reports first-hand. `ready` is never accepted here —
182
- // it stays server-derived from the compiled applet (bundle + reconcile).
183
- status?: 'building' | 'waiting'
184
- title?: string
185
- icon?: string
186
- }
187
-
188
- // Bind an applet id (+ optional title/icon/status) to a builder — the single
189
- // write behind `moi builder set`. Locates the record by handle when claiming a
190
- // pending builder, otherwise by applet id (creating one for a standalone build).
191
- export async function setBuilder(
192
- workspaceId: string,
193
- workspacePath: string,
194
- appletId: string,
195
- input: SetBuilderInput
196
- ): Promise<ViewBuilder> {
197
- if (!/^[a-z0-9][a-z0-9_-]*$/.test(appletId)) {
198
- throw new ViewBuilderError('Invalid applet id', 400)
199
- }
200
- if (input.icon !== undefined && !isAppIconId(input.icon)) {
201
- throw new ViewBuilderError(
202
- `Unknown view icon id "${input.icon}". Use one of: ${APP_ICON_NAMES.join(', ')}`,
203
- 400
204
- )
205
- }
206
- // Views and widgets are separate applet namespaces, so an id is only unique
207
- // within a kind — a view and a widget may both be called "stats".
208
- const kind: AppletKind = input.kind ?? 'view'
209
- const sameApplet = (candidate: ViewBuilder) =>
210
- candidate.viewId === appletId && (candidate.kind ?? 'view') === kind
211
- const builder = await mutateBuilders(workspacePath, builders => {
212
- const index = input.builderId
213
- ? builders.findIndex(candidate => candidate.id === input.builderId)
214
- : builders.findIndex(sameApplet)
215
- if (input.builderId && index === -1) {
216
- throw new ViewBuilderError('View builder not found', 404)
217
- }
218
- const clash = builders.find((candidate, i) => i !== index && sameApplet(candidate))
219
- if (clash) throw new ViewBuilderError(`View id "${appletId}" is already claimed`, 409)
220
-
221
- if (index === -1) {
222
- // Standalone build (e.g. a widget) with no pending record — create one.
223
- const now = Date.now()
224
- const status = input.status ?? 'building'
225
- const created: ViewBuilder = {
226
- id: newBuilderId(),
227
- kind,
228
- status,
229
- input: { requirements: '' },
230
- sessionId: crypto.randomUUID(),
231
- viewId: appletId,
232
- ...(input.title ? { title: input.title } : {}),
233
- ...(input.icon ? { icon: input.icon } : {}),
234
- ...(status === 'building' ? { buildingSince: now } : {}),
235
- createdAt: now,
236
- updatedAt: now
237
- }
238
- builders.push(created)
239
- return created
240
- }
241
-
242
- const current = builders[index]
243
- if (input.builderId && current.status === 'draft') {
244
- throw new ViewBuilderError('View builder has not been submitted', 409)
245
- }
246
- if (current.viewId && current.viewId !== appletId) {
247
- throw new ViewBuilderError(`View builder already claimed "${current.viewId}"`, 409)
248
- }
249
- // `ready` is terminal and server-owned: the agent's reported status can
250
- // never move a built applet back to building/waiting.
251
- const status = current.status === 'ready' ? 'ready' : (input.status ?? current.status)
252
- const enteringBuild = status === 'building' && current.status !== 'building'
253
- const { error: _error, ...withoutError } = current
254
- return replace(
255
- builders,
256
- index,
257
- updated(withoutError as ViewBuilder, {
258
- viewId: appletId,
259
- ...(input.kind ? { kind: input.kind } : {}),
260
- ...(input.title !== undefined ? { title: input.title } : {}),
261
- ...(input.icon !== undefined ? { icon: input.icon } : {}),
262
- status,
263
- ...(enteringBuild ? { buildingSince: Date.now() } : {})
264
- })
265
- )
266
- })
267
- publishUpdated(workspaceId, builder)
268
- return builder
269
- }
270
-
271
- export async function markViewBuilderBuildingBySession(
272
- workspaceId: string,
273
- workspacePath: string,
274
- sessionId: string
275
- ): Promise<ViewBuilder | null> {
276
- const builder = await mutateBuilders(workspacePath, builders => {
277
- const index = builders.findIndex(candidate => candidate.sessionId === sessionId)
278
- if (index === -1 || builders[index].status !== 'waiting') return null
279
- const { error: _error, ...withoutError } = builders[index]
280
- return replace(
281
- builders,
282
- index,
283
- updated(withoutError as ViewBuilder, { status: 'building', buildingSince: Date.now() })
284
- )
285
- })
286
- if (builder) publishUpdated(workspaceId, builder)
287
- return builder
288
- }
289
-
290
- export async function markViewBuilderWaitingBySession(
291
- workspaceId: string,
292
- workspacePath: string,
293
- sessionId: string,
294
- error?: string
295
- ): Promise<ViewBuilder | null> {
296
- const builder = await mutateBuilders(workspacePath, builders => {
297
- const index = builders.findIndex(candidate => candidate.sessionId === sessionId)
298
- if (index === -1) return null
299
- const current = builders[index]
300
- if (current.status === 'waiting' && error && current.error !== error) {
301
- return replace(builders, index, updated(current, { error }))
302
- }
303
- if (current.status !== 'building') return null
304
- return replace(
305
- builders,
306
- index,
307
- updated(current, { status: 'waiting', ...(error ? { error } : {}) })
308
- )
309
- })
310
- if (builder) publishUpdated(workspaceId, builder)
311
- return builder
312
- }
313
-
314
- export async function markViewBuilderWaiting(
315
- workspaceId: string,
316
- workspacePath: string,
317
- builderId: string,
318
- error?: string
319
- ): Promise<ViewBuilder | null> {
320
- const builder = await mutateBuilders(workspacePath, builders => {
321
- const [current, index] = findBuilder(builders, builderId)
322
- if (current.status === 'ready' || (current.status === 'waiting' && current.error === error)) {
323
- return null
324
- }
325
- return replace(
326
- builders,
327
- index,
328
- updated(current, { status: 'waiting', ...(error ? { error } : {}) })
329
- )
330
- })
331
- if (builder) publishUpdated(workspaceId, builder)
332
- return builder
333
- }
334
-
335
- export async function renameViewBuilderSession(
336
- workspaceId: string,
337
- workspacePath: string,
338
- from: string,
339
- to: string
340
- ): Promise<ViewBuilder | null> {
341
- if (from === to) return null
342
- const builder = await mutateBuilders(workspacePath, builders => {
343
- const index = builders.findIndex(candidate => candidate.sessionId === from)
344
- if (index === -1) return null
345
- return replace(builders, index, updated(builders[index], { sessionId: to }))
346
- })
347
- if (builder) publishUpdated(workspaceId, builder)
348
- return builder
349
- }
350
-
351
- export async function markViewBuilderReady(
352
- workspaceId: string,
353
- workspacePath: string,
354
- viewId: string,
355
- title: string,
356
- icon?: string
357
- ): Promise<ViewBuilder | null> {
358
- const builder = await mutateBuilders(workspacePath, builders => {
359
- const index = builders.findIndex(candidate => candidate.viewId === viewId)
360
- if (index === -1 || builders[index].status === 'ready') return null
361
- const { error: _error, ...withoutError } = builders[index]
362
- return replace(
363
- builders,
364
- index,
365
- updated(withoutError as ViewBuilder, {
366
- status: 'ready',
367
- title,
368
- ...(icon ? { icon } : {})
369
- })
370
- )
371
- })
372
- if (builder) publishUpdated(workspaceId, builder)
373
- return builder
374
- }
375
-
376
- export async function reconcileViewBuilders(
377
- workspaceId: string,
378
- workspacePath: string,
379
- views: ViewInfo[],
380
- activeSessionIds: Set<string>
381
- ): Promise<ViewBuilder[]> {
382
- const now = Date.now()
383
- const changed = await mutateBuilders(workspacePath, builders => {
384
- const viewsById = new Map(views.map(view => [view.id, view]))
385
- const updates: ViewBuilder[] = []
386
- for (let index = 0; index < builders.length; index++) {
387
- const current = builders[index]
388
- // Only view builders reconcile against the compiled view list; widget
389
- // records track their own applet id in a separate namespace.
390
- const view =
391
- current.viewId && current.kind !== 'widget' ? viewsById.get(current.viewId) : undefined
392
- // A build with no live session (server restart, drained turn) — or one that
393
- // has been building far too long (a hung/abandoned turn that never drained)
394
- // — is stuck; hand it back so the user can resume or discard it.
395
- const stuck =
396
- current.status === 'building' &&
397
- (!activeSessionIds.has(current.sessionId) ||
398
- (current.buildingSince !== undefined && now - current.buildingSince > STALE_BUILD_MS))
399
- if (view && current.status !== 'ready') {
400
- const { error: _error, ...withoutError } = current
401
- const next = updated(withoutError as ViewBuilder, {
402
- status: 'ready',
403
- title: view.config.title,
404
- ...(view.config.icon ? { icon: view.config.icon } : {})
405
- })
406
- builders[index] = next
407
- updates.push(next)
408
- } else if (stuck) {
409
- const next = updated(current, { status: 'waiting' })
410
- builders[index] = next
411
- updates.push(next)
412
- }
413
- }
414
- return updates
415
- })
416
- for (const builder of changed) publishUpdated(workspaceId, builder)
417
- return listViewBuilders(workspacePath)
418
- }
419
-
420
- export async function deleteViewBuilder(
421
- workspaceId: string,
422
- workspacePath: string,
423
- builderId: string
424
- ): Promise<void> {
425
- await mutateBuilders(workspacePath, builders => {
426
- const [builder, index] = findBuilder(builders, builderId)
427
- if (builder.status === 'building') {
428
- throw new ViewBuilderError('A building view can only be closed', 409)
429
- }
430
- if (builder.status === 'ready') {
431
- throw new ViewBuilderError('Ready view builder history is retained', 409)
432
- }
433
- builders.splice(index, 1)
434
- })
435
- publishEvent({ type: 'view-builder:deleted', workspaceId, builderId })
436
- }
437
-
438
- export async function deleteViewBuilderForView(
439
- workspaceId: string,
440
- workspacePath: string,
441
- viewId: string
442
- ): Promise<void> {
443
- const deleted = await mutateBuilders(workspacePath, builders => {
444
- const index = builders.findIndex(
445
- builder => builder.viewId === viewId && (builder.kind ?? 'view') === 'view'
446
- )
447
- if (index === -1) return null
448
- return builders.splice(index, 1)[0]
449
- })
450
- if (deleted) {
451
- publishEvent({ type: 'view-builder:deleted', workspaceId, builderId: deleted.id })
452
- }
453
- }