@lincyaw/workspace 1.0.0-rc.7 → 1.0.0-rc.72

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.
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { createRequire } from 'node:module'
3
3
  import { DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, PRODUCTION_AUDIO_AUTHORING, pushStream, SPEECH, sseResponse } from '@lincyaw/kernel'
4
- import type { ChangesAnswer, CommitAnswer, CompileJob, DocumentsAnswer, JobsAnswer, Member, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
4
+ import type { CompileJob, DocumentsAnswer, JobsAnswer, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
5
5
  import { hasBearerToken } from '@lincyaw/server'
6
6
  import { saveSummary } from '../domain/commit-message.ts'
7
7
  import { documentSummaries, listDocuments } from './config.ts'
@@ -9,12 +9,11 @@ import type { WorkspaceConfig } from './config.ts'
9
9
  import { documentsDiff } from './document-operations.ts'
10
10
  import type { DocumentOperations, DocumentsChange } from './document-operations.ts'
11
11
  import { catchRequestErrors, RequestError } from './errors.ts'
12
- import { lockedError } from './locks.ts'
13
12
  import type { DocumentLocks } from './locks.ts'
14
13
  import type { Revisions } from './revisions.ts'
15
14
  import { reviewRoutes } from './review/routes.ts'
16
15
  import type { AgentSessionReviews } from './review/agent-session-reviews.ts'
17
- import { MAX_SOURCE, MAX_SOURCE_CHANGES, validateDocumentSource } from './source-editor.ts'
16
+ import { MAX_SOURCE, MAX_SOURCE_CHANGES } from './source-editor.ts'
18
17
  import type { SourceEditor } from './source-editor.ts'
19
18
  import { listTemplates } from './templates.ts'
20
19
  import type { Jobs } from './jobs.ts'
@@ -25,8 +24,8 @@ import { createDocumentAudioAuthoring } from './document-audio.ts'
25
24
  import { createDocumentImageAuthoring } from './document-images.ts'
26
25
  import { createDocumentTranscriptions, documentTranscriptionRoutes } from './document-transcription.ts'
27
26
  import type { DocumentTranscriptions, ProductionAudioAuthoring, SpeechService } from '@lincyaw/kernel'
28
- import { documentDirOf } from './writer.ts'
29
27
  import { createDocumentHistory } from './document-history.ts'
28
+ import { createWorkspaceChanges } from './workspace-changes.ts'
30
29
 
31
30
  const { version } = createRequire(import.meta.url)('../../package.json') as { version: string }
32
31
 
@@ -62,6 +61,7 @@ export interface WorkspaceRoutesOptions {
62
61
  authoringClientRoutes?: Record<string, Route>
63
62
  projectRoutes?: Record<string, Route>
64
63
  speechSettings?: Route
64
+ changesRoutes?: Record<string, Route>
65
65
  }
66
66
 
67
67
  function toRendererIds(body: unknown): string[] | undefined {
@@ -70,13 +70,6 @@ function toRendererIds(body: unknown): string[] | undefined {
70
70
  return ids.length > 0 ? ids : undefined
71
71
  }
72
72
 
73
- const NO_GIT = 'the workspace is not a git repository: run git init in it to use the document operations and the history'
74
-
75
-
76
- function toChosenPaths(body: unknown, uncommitted: string[]): string[] {
77
- const asked = isRecord(body) && Array.isArray(body.paths) ? body.paths.filter((path): path is string => typeof path === 'string') : undefined
78
- return asked ? uncommitted.filter(path => asked.includes(path)) : uncommitted
79
- }
80
73
 
81
74
  function toSaveMessage(value: unknown): string {
82
75
  return typeof value === 'string' ? [...(value.trim().split(/\r?\n/)[0] ?? '').trim()].slice(0, 200).join('') : ''
@@ -87,21 +80,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
87
80
  const { config, editor, locks, revisions, operations, reviews, workbench } = options
88
81
  const listed = () => listDocuments(config).map(doc => doc.dir)
89
82
  const scopeOf = (ctx: RequestContext) => editor.scope(ctx.document)
90
- const uncommitted = async (ctx: RequestContext) => (revisions ? await revisions.uncommittedFiles(editor.roots(scopeOf(ctx))) : [])
91
- const withChosenChanges = async (request: Request, ctx: RequestContext, holder: string, work: (revisions: Revisions, paths: string[], member: Member, body: Record<string, unknown>) => Promise<Response>) => {
92
- if (request.method !== 'POST') return problemResponse(405, 'POST')
93
- if (!revisions) return problemResponse(409, NO_GIT)
94
- const body: unknown = await request.json().catch(() => ({}))
95
- const paths = toChosenPaths(body, (await uncommitted(ctx)).map(file => file.path))
96
- if (paths.length === 0) return problemResponse(409, 'no changes to take: every file is as committed')
97
- const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path) ?? ''), holder)
98
- if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
99
- try {
100
- return await work(revisions, paths, ctx.member, isRecord(body) ? body : {})
101
- } finally {
102
- claimed.release()
103
- }
104
- }
83
+ const changes = options.changesRoutes ?? createWorkspaceChanges({ config, editor, locks, revisions, changed: options.documentsChanged }).routes
105
84
  const ownedHistory = options.historyRoutes ? undefined : createDocumentHistory({ config, editor, locks, revisions, changed: (before, after) => options.documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => reviews?.reverted(target, revision) })
106
85
  const ownedTranscriptions = options.transcriptions ? undefined : createDocumentTranscriptions({ root: config.root, editor, audio: options.audio, speech: options.speech })
107
86
  const transcriptions = options.transcriptions ?? ownedTranscriptions!
@@ -178,39 +157,11 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
178
157
  return jsonResponse(await editor.transaction(scopeOf(ctx), changes, ctx.member, history) satisfies SourceTransactionAnswer)
179
158
  }),
180
159
  },
181
- 'changes': {
182
- role: 'editor',
183
- handle: (request, ctx) => catchRequestErrors(async () => {
184
- if (request.method !== 'GET') return problemResponse(405, 'GET')
185
- return jsonResponse({ files: await uncommitted(ctx) } satisfies ChangesAnswer)
186
- }),
187
- },
188
- 'changes/commit': {
189
- role: 'editor',
190
- handle: (request, ctx) => catchRequestErrors(() => withChosenChanges(request, ctx, 'editor:commit', async (history, paths, member, body) => {
191
- const message = typeof body.message === 'string' ? body.message.trim().slice(0, 4000) : ''
192
- if (!message) return problemResponse(400, '{ message: what the change is, paths? }')
193
- for (const path of paths) {
194
- if (!path.endsWith(`/${DOCUMENT_ENTRY}`) && path !== DOCUMENT_ENTRY) continue
195
- const source = editor.read(scopeOf(ctx), path, member)
196
- validateDocumentSource(path, source.content)
197
- }
198
- const revision = await history.commit({ files: paths, message, origin: { kind: 'editor', member } })
199
- return jsonResponse({ ...revision ? { revision } : {}, paths } satisfies CommitAnswer)
200
- })),
201
- },
160
+ ...changes,
202
161
  ...workbench ? workbenchRoutes(workbench) : {},
203
162
  ...options.jobs ? jobRoutes(options.jobs, editor) : {},
204
163
  ...reviews ? reviewRoutes(reviews) : {},
205
- 'changes/discard': {
206
- role: 'editor',
207
- handle: (request, ctx) => catchRequestErrors(() => withChosenChanges(request, ctx, 'editor:discard', async (history, paths) => {
208
- const before = listed()
209
- await history.discard(paths)
210
- await options.documentsChanged(documentsDiff(before, listed()))
211
- return jsonResponse({ paths } satisfies CommitAnswer)
212
- })),
213
- },
164
+
214
165
  }
215
166
  return { routes: authorizeWorkspaceRoutes(routes, options.launcherToken), close: async () => { await Promise.all([ownedTranscriptions?.close(), ownedAudio?.close(), ownedHistory?.close()]) } }
216
167
  }
@@ -257,7 +208,7 @@ function workbenchRoutes(workbench: WorkbenchApi): Record<string, Route> {
257
208
  const params = new URL(request.url).searchParams
258
209
  const renderer = params.get('view') ?? undefined
259
210
  if (renderer !== undefined && renderer !== 'web' && renderer !== 'slides') return problemResponse(400, 'view must be web or slides')
260
- return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1'))
211
+ return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1', request.headers.get('x-presmium-preview-origin') ?? undefined))
261
212
  }),
262
213
  },
263
214
  'build': {
package/src/node/serve.ts CHANGED
@@ -1,16 +1,20 @@
1
+ import { createMediaUploads } from './media-uploads.ts'
1
2
  import { createProjectAuthoring } from './projects.ts'
2
3
  import { createDocumentHistory } from './document-history.ts'
3
4
  import { createAuthoringClients } from './authoring-clients.ts'
4
- import { createHash } from 'node:crypto'
5
- import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
6
- import { homedir, tmpdir } from 'node:os'
5
+ import { createAuthoringWindows } from './authoring-windows.ts'
6
+ import { readAuthoringDocument } from './document-editor.ts'
7
+ import { createDocumentCapture } from './capture.ts'
8
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
9
+ import { stripVTControlCharacters } from 'node:util'
10
+ import { tmpdir } from 'node:os'
7
11
  import { join, relative } from 'node:path'
8
12
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
9
13
  import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
10
- import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
11
- import { irRevision, operatorSpeechSecrets } from '@lincyaw/kernel/node'
14
+ import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
15
+ import { irRevision, OperatorSpeechSettings, serveStateDir } from '@lincyaw/kernel/node'
12
16
  import { speechSettingsRoute } from './speech-settings.ts'
13
- import type { CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
17
+ import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
14
18
  import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
15
19
  import type { DiagnosticStore, PresmiumServer, ServedDocument, ServedPlugin, ServerHost } from '@lincyaw/server'
16
20
  import { CompileSession } from './compile-session.ts'
@@ -22,11 +26,14 @@ import { Git } from './git.ts'
22
26
  import { createJobs, OUTPUTS_PATH } from './jobs.ts'
23
27
  import { DocumentLocks } from './locks.ts'
24
28
  import { AgentSessionReviews } from './review/agent-session-reviews.ts'
29
+ import { createWorkspaceReview } from './review/workspace-review.ts'
30
+ import { createWorkspaceSource } from './workspace-source.ts'
31
+ import { createWorkspaceChanges } from './workspace-changes.ts'
25
32
  import { createTaskReviewService } from './review/task-reviews.ts'
26
33
  import { Revisions } from './revisions.ts'
27
34
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
28
35
  import { refreshDocumentVitePlugins, siteContext, siteDocument, siteDocumentIR, siteSpec, untranslatedFindings, webRenderer } from './site.ts'
29
- import { SourceEditor } from './source-editor.ts'
36
+ import { SourceEditor, versionOf } from './source-editor.ts'
30
37
  import { createDocumentEditor } from './document-editor.ts'
31
38
  import type { DocumentEditor } from './document-editor.ts'
32
39
  import { createDocumentTranscriptions } from './document-transcription.ts'
@@ -50,6 +57,8 @@ export interface ServeOptions {
50
57
  /** The address browsers use when a reverse proxy fronts the service (see `ServerOptions.publicUrl`). */
51
58
  publicUrl?: string
52
59
  env?: NodeJS.ProcessEnv
60
+ /** Approvals given without asking, over the workspace's `approvals` (`presmium serve --allow`). */
61
+ allow?: ApprovalKind[]
53
62
  approvalTimeoutMs?: number
54
63
  log?: Logger
55
64
  }
@@ -76,8 +85,7 @@ interface NodeServiceLoad { key: string, promise: Promise<AuthoringServices>, co
76
85
  const DISK_LOOK_MS = 1000
77
86
 
78
87
  function makeStateDir(root: string, env: NodeJS.ProcessEnv): string {
79
- const base = env.XDG_CACHE_HOME || join(homedir(), '.cache')
80
- const dir = join(base, 'presmium', 'serve', createHash('sha256').update(root).digest('hex').slice(0, 16))
88
+ const dir = serveStateDir(root, env)
81
89
  mkdirSync(dir, { recursive: true })
82
90
  return dir
83
91
  }
@@ -86,8 +94,10 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
86
94
  const env = options.env ?? process.env
87
95
  const log = options.log ?? pluginLogger('presmium serve')
88
96
  const config = readWorkspaceConfig(options.dir)
97
+ if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
89
98
  const { root } = config
90
99
  const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
100
+ const speechSettings = new OperatorSpeechSettings(operatorDirectory, name => env[name])
91
101
  const stateDir = makeStateDir(root, env)
92
102
  const docs = () => listDocuments(config)
93
103
  const compileSessions = new Map<string, CompileSession>()
@@ -112,12 +122,18 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
112
122
  let history: WorkspaceHistory | undefined
113
123
  let documentEditor: DocumentEditor | undefined
114
124
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
125
+ let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
126
+ let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
127
+ let workspaceChanges: ReturnType<typeof createWorkspaceChanges> | undefined
115
128
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
116
129
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
130
+ let authoringWindows: ReturnType<typeof createAuthoringWindows> | undefined
117
131
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
118
132
  let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
133
+ let mediaUploads: ReturnType<typeof createMediaUploads> | undefined
119
134
  let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
120
135
  let imageAuthoring: ReturnType<typeof createDocumentImageAuthoring> | undefined
136
+ let capture: ReturnType<typeof createDocumentCapture> | undefined
121
137
  let voiceAuthoring: ReturnType<typeof createDocumentVoiceAuthoring> | undefined
122
138
  let workspaceRoutesOwner: ReturnType<typeof workspaceRoutes> | undefined
123
139
  let routesPlugin: ServedPlugin | undefined
@@ -166,7 +182,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
166
182
  services: [...serverServices, ...workspaceServices],
167
183
  bundled: options.bundled,
168
184
  operatorDir: operatorDirectory,
169
- secret: operatorSpeechSecrets(operatorDirectory, name => env[name]),
185
+ secret: speechSettings.secret,
170
186
  })
171
187
 
172
188
  // Coalesce only in-flight discovery. A later read reassembles actual services and problems;
@@ -194,7 +210,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
194
210
  authoringServicesClosed = true
195
211
  transcriptionAdoption?.close()
196
212
  for (const load of nodeServicePending) load.controller.abort()
197
- await Promise.all([projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), workspaceRoutesOwner?.close?.()])
213
+ await Promise.all([mediaUploads?.close(), projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
198
214
  await Promise.allSettled([...nodeServicePending].map(load => load.promise))
199
215
  nodeServiceLoads.clear()
200
216
  }
@@ -249,7 +265,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
249
265
  revisions,
250
266
  operations: new DocumentOperations({ config, git, revisions, writer, changed: documentsChanged, locks }),
251
267
  git,
252
- agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log }),
268
+ agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log, flush: (documents, member) => authoringClients?.flush(documents, member) ?? Promise.resolve() }),
253
269
  taskReviews: createTaskReviewService({ config, locks, files: writer, log }),
254
270
  }
255
271
  }
@@ -263,11 +279,18 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
263
279
  get documentHistory() { return documentHistory?.service },
264
280
  get projectAuthoring() { return projectAuthoring?.service },
265
281
  get authoringClients() { return authoringClients?.service },
282
+ get authoringWindows() { return authoringWindows?.service },
283
+ get mediaUploads() { return mediaUploads },
266
284
  get audioAuthoring() { return audioAuthoring?.service },
267
285
  get imageAuthoring() { return imageAuthoring?.service },
268
286
  get voiceAuthoring() { return voiceAuthoring?.service },
287
+ speechSettings,
288
+ get workspaceReview() { return workspaceReview },
289
+ get workspaceSource() { return workspaceSource },
290
+ get workspaceChanges() { return workspaceChanges?.service },
269
291
  get transcriptions() { return transcriptions },
270
292
  get transcriptionAdoption() { return transcriptionAdoption?.service },
293
+ get capture() { return capture?.service },
271
294
  get routes() { return workspaceRoutesOwner?.routes ? { [WORKSPACE_ID]: workspaceRoutesOwner.routes, ...voiceAuthoring ? { 'presmium.lecture': authorizeWorkspaceRoutes(voiceAuthoring.routes, launcherToken) } : {} } : undefined },
272
295
  agentTools(document) {
273
296
  const compiled = (document === undefined ? [...compileSessions.values()] : [compileSessions.get(document)]).flatMap(session => session?.latest ? [session.latest] : [])
@@ -355,7 +378,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
355
378
  }
356
379
  },
357
380
  settings: config.settings,
358
- approvals: config.approvals,
381
+ approvals: { ...config.approvals, ...Object.fromEntries((options.allow ?? []).map(kind => [kind, 'allow' as const])) },
359
382
  operatorDir: operatorDirectory,
360
383
  serverHost,
361
384
  env,
@@ -374,19 +397,28 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
374
397
  })
375
398
  const running = server
376
399
  serverServices = running.services
377
- voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
400
+ mediaUploads = createMediaUploads({ editor, url: () => `${publicOrigin()}${basePath.replace(/\/$/, '')}` })
401
+ voiceAuthoring = createDocumentVoiceAuthoring({ editor, uploads: mediaUploads, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
378
402
  workbench = createWorkbenchBackend({ root, compileSessionOf, serverHost, voices: voiceAuthoring.service, diagnostics: running.diagnostics, url: () => options.publicUrl ? new URL(options.publicUrl).origin : running.url, basePath, preview, log, warmSite: dir => site?.warm(dir) ?? Promise.resolve(), viewerPage: (dir, wait) => site?.app(dir, wait) ?? Promise.resolve(undefined) })
379
403
  history = openHistory()
404
+ workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.revisions, changed: documentsChanged })
405
+ workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
406
+ workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
380
407
  documentEditor = createDocumentEditor({ productionPlan: async (document, source) => { const audio = (await authoringServices(document, source)).audio; if (!audio) throw new RequestError(503, 'caption-production-unavailable'); return audio.readPlan({ source }) }, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
381
408
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
382
- authoringClients = createAuthoringClients(editor)
409
+ authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
410
+ authoringWindows = createAuthoringWindows((document, member) => {
411
+ if (!docs().some(value => value.dir === document)) throw new RequestError(404, 'window-target-unavailable')
412
+ return readAuthoringDocument(editor, { document, member }).content.id
413
+ })
383
414
  documentHistory = createDocumentHistory({ config, editor, locks, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required', changed: (before, after) => documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => history?.agentSessionReviews.reverted(target, revision) })
384
415
  transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
385
416
  transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
386
- audioAuthoring = createDocumentAudioAuthoring({ root, editor, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
387
- imageAuthoring = createDocumentImageAuthoring({ root, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
417
+ audioAuthoring = createDocumentAudioAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
418
+ imageAuthoring = createDocumentImageAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
388
419
  const routeOptions = {
389
- speechSettings: speechSettingsRoute(operatorDirectory, name => env[name]),
420
+ speechSettings: speechSettingsRoute(speechSettings),
421
+ changesRoutes: workspaceChanges.routes,
390
422
  config,
391
423
  editor,
392
424
  documentEditor,
@@ -395,7 +427,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
395
427
  audioAuthoringRoutes: audioAuthoring.routes,
396
428
  imageAuthoringRoutes: imageAuthoring.routes,
397
429
  historyRoutes: documentHistory.routes,
398
- authoringClientRoutes: authoringClients.routes,
430
+ authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes },
399
431
  projectRoutes: projectAuthoring.routes,
400
432
  locks,
401
433
  ...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
@@ -422,6 +454,15 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
422
454
  throw error
423
455
  }
424
456
 
457
+ // A picture right after a save shows what was saved: the document is compiled first when its file is newer.
458
+ const savedCompilation = async (dir: string): Promise<Compilation> => {
459
+ const session = compileSessionOf(dir)
460
+ const compilation = await session.ready()
461
+ const entry = docs().find(doc => doc.dir === dir)?.entry
462
+ const saved = entry ? versionOf(readFileSync(join(root, entry))) : undefined
463
+ return saved && compilation.doc.source?.version !== saved ? await session.recompile() : compilation
464
+ }
465
+ capture = createDocumentCapture({ root, url: () => running.url, viewerPage: dir => site?.app(dir, true) ?? Promise.resolve(undefined), compiled: async dir => (await savedCompilation(dir)).doc, dir: join(stateDir, 'captures') })
425
466
  started()
426
467
 
427
468
  const compileForSite = async (dir: string): Promise<IRDocument> => {
@@ -433,6 +474,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
433
474
  site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
434
475
  } catch (error) {
435
476
  await closeAuthoring()
477
+ await capture.close()
436
478
  await workbench.close()
437
479
  await running.close()
438
480
  if (home) rmSync(home, { recursive: true, force: true })
@@ -448,6 +490,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
448
490
  await closeAuthoring()
449
491
  for (const session of compileSessions.values()) session.close()
450
492
  await jobs.close()
493
+ await capture?.close()
451
494
  await workbench?.close()
452
495
  await site?.close()
453
496
  await running.close()
@@ -471,6 +514,23 @@ interface WorkspaceSiteOptions {
471
514
 
472
515
  type WorkspaceSite = Awaited<ReturnType<typeof startWorkspaceSite>>
473
516
 
517
+ /** The bundler's failure as a diagnostic: the file and the module it could not find, when that is the failure. */
518
+ function codeFailure(error: unknown): Finding {
519
+ const text = stripVTControlCharacters(errorMessage(error))
520
+ const unresolved = /failed to resolve import "([^"]+)" from "([^"]+)"/.exec(text)
521
+ if (unresolved) {
522
+ return {
523
+ checkId: 'presmium.preview.code',
524
+ severity: 'error',
525
+ message: `the document's code could not be bundled: ${unresolved[1]} cannot be found from this file`,
526
+ hint: 'Name the plugin that provides it in metadata.plugins, or add its package to the project’s dependencies.',
527
+ source: { file: unresolved[2]! },
528
+ }
529
+ }
530
+ const reason = text.split('\n').map(line => line.replace(/^Error:\s*/, '').trim()).find(line => line && !/^Build failed/.test(line)) ?? text
531
+ return { checkId: 'presmium.preview.code', severity: 'error', message: `the document's code could not be bundled: ${reason}` }
532
+ }
533
+
474
534
  /** The workspace site's dev router in this process, which serve forwards the site's paths to. */
475
535
  async function startWorkspaceSite(options: WorkspaceSiteOptions) {
476
536
  const { root, spec, log } = options
@@ -497,7 +557,20 @@ async function startWorkspaceSite(options: WorkspaceSiteOptions) {
497
557
  })
498
558
  },
499
559
  warm: (dir: string): Promise<void> => dev.warm?.(dir) ?? Promise.resolve(),
500
- app: (dir: string, wait: boolean): Promise<string | undefined> => dev.app?.(dir, wait) ?? Promise.resolve(undefined),
560
+ app: async (dir: string, wait: boolean): Promise<string | undefined> => {
561
+ // A file of the document's own code (a scene, a component) that does not bundle fails alone: what imports it
562
+ // shows its failure. Each such file is a diagnostic, where the author, the workbench's AI and MCP clients find
563
+ // it, until a preview bundles it; when none of the code bundles, the preview fails, and the reason is one.
564
+ const source = { document: dir, origin: 'preview', renderer: 'web', instance: 'code' } as const
565
+ try {
566
+ const page = await (dev.app?.(dir, wait) ?? Promise.resolve(undefined))
567
+ if (wait && page) options.diagnostics.replace(source, dev.codeFindings?.(dir) ?? [], { root, irRevision: options.diagnostics.irRevision(dir) })
568
+ return page
569
+ } catch (error) {
570
+ if (wait && !(error instanceof PreviewPreparing)) options.diagnostics.replace(source, [codeFailure(error)], { root, irRevision: options.diagnostics.irRevision(dir) })
571
+ throw error
572
+ }
573
+ },
501
574
  close: (): Promise<void> => dev.close(),
502
575
  }
503
576
  }
package/src/node/site.ts CHANGED
@@ -35,7 +35,7 @@ export async function siteTranslations(compilation: Compilation): Promise<{ tran
35
35
  }
36
36
 
37
37
  export function siteDocument(document: DocumentSummary, doc?: IRDocument, translations?: SiteDocument['translations'], compilation?: Compilation): SiteDocument {
38
- return { dir: document.dir, title: document.title, description: document.description, ...document.lang ? { lang: document.lang } : {}, ...document.tags ? { tags: document.tags } : {}, ...doc ? { doc } : {}, ...translations?.length ? { translations } : {}, ...compilation ? { nodeVitePlugins: nodeVitePlugins(compilation) } : {} }
38
+ return { dir: document.dir, title: document.title, description: document.description, ...document.lang ? { lang: document.lang } : {}, ...document.tags ? { tags: document.tags } : {}, ...document.slides ? { slides: true } : {}, ...doc ? { doc } : {}, ...translations?.length ? { translations } : {}, ...compilation ? { nodeVitePlugins: nodeVitePlugins(compilation) } : {} }
39
39
  }
40
40
 
41
41
  export function refreshDocumentVitePlugins(site: SiteSpec, dir: string, compilation: Compilation): void {
@@ -1,20 +1,19 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
5
- import { DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
5
+ import { DOCUMENT_ENTRY, SOURCE_MAX_BYTES, SOURCE_MAX_FILES, validateDocument } from '@lincyaw/kernel'
6
6
  import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
7
7
  import { isWithin } from '../domain/paths.ts'
8
8
  import { listDocumentEntries, readDocumentSummary } from './config.ts'
9
9
  import type { DocumentEntry, WorkspaceConfig } from './config.ts'
10
10
  import { RequestError } from './errors.ts'
11
- import { lockedError } from './locks.ts'
12
11
  import type { DocumentLocks } from './locks.ts'
13
12
  import { documentDirOf, FilesError, writeChanges } from './writer.ts'
14
13
  import type { DocumentWriter } from './writer.ts'
15
14
 
16
- export const MAX_SOURCE = 2 << 20
17
- export const MAX_SOURCE_CHANGES = 16
15
+ export const MAX_SOURCE = SOURCE_MAX_BYTES
16
+ export const MAX_SOURCE_CHANGES = SOURCE_MAX_FILES
18
17
  const MAX_FILES = 2000
19
18
  const HIDDEN_FROM_EDITOR = new Set(['node_modules', 'dist', '.git', '.presmium'])
20
19
  const BINARY = /\.(?:png|jpe?g|gif|webp|avif|ico|bmp|pdf|wasm|zip|gz|tgz|bz2|xz|7z|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|oga|webm|mov|avi|mkv|bin|so|dylib|dll|exe|pyc|xlsx?|docx?|pptx?|parquet|npy|npz|pkl|db|sqlite)$/i
@@ -49,6 +48,8 @@ interface Scope {
49
48
  }
50
49
 
51
50
  export interface SourceTransactionHistory {
51
+ /** Runs on final locked preimages, before any file is created or changed. */
52
+ check?(files: readonly { path: string, before?: Uint8Array }[]): void
52
53
  run<T>(work: () => Promise<T>): Promise<T>
53
54
  commit(paths: string[], lang: string | undefined): Promise<Revision | undefined>
54
55
  }
@@ -154,9 +155,20 @@ export class SourceEditor {
154
155
 
155
156
  #readBytes(scope: Scope, path: string, member: Member, documents?: readonly DocumentEntry[]): Buffer {
156
157
  const file = this.#readableFile(scope, path, member, documents)
157
- const bytes = readFileSync(file)
158
- if (bytes.byteLength > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
159
- return bytes
158
+ const before = lstatSync(file)
159
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
160
+ try {
161
+ const opened = fstatSync(fd)
162
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) throw new RequestError(409, 'source-file-changed')
163
+ if (opened.size > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
164
+ const bytes = Buffer.alloc(opened.size + 1)
165
+ let length = 0, count = 0
166
+ while (length < bytes.length && (count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += count
167
+ const after = fstatSync(fd), current = lstatSync(file)
168
+ if (length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
169
+ || current.dev !== opened.dev || current.ino !== opened.ino || realpathSync(file) !== file) throw new RequestError(409, 'source-file-changed')
170
+ return bytes.subarray(0, length)
171
+ } finally { closeSync(fd) }
160
172
  }
161
173
 
162
174
  read(scope: Scope, path: string, member: Member): SourceAnswer {
@@ -178,8 +190,7 @@ export class SourceEditor {
178
190
  if (BINARY.test(path)) throw new RequestError(415, `${path} is not a text file`)
179
191
  const document = this.#documentHolding(path, documents)?.dir
180
192
  const scopeDir = document ?? ''
181
- const release = this.#locks ? this.#locks.claim(scopeDir, 'editor:create') : () => {}
182
- if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
193
+ const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:create') : () => {}
183
194
  try {
184
195
  await this.#writer.create(path, Buffer.alloc(0), document === undefined)
185
196
  return { path, content: '', version: versionOf('') }
@@ -227,11 +238,16 @@ export class SourceEditor {
227
238
  if (bytes > MAX_SOURCE) throw new RequestError(413, `the transaction is larger than the editor saves (${MAX_SOURCE} bytes)`)
228
239
  for (const path of paths) if ([...paths].some(other => path !== other && path.startsWith(`${other}/`))) throw new RequestError(400, `a source file cannot also be a parent directory: ${path}`)
229
240
  const document = documents[0]
230
- if (!document || documents.some(found => found?.dir !== document.dir)) throw new RequestError(400, 'a source transaction must stay in one document')
231
- const scopeDir = document.dir
232
- const release = this.#locks ? this.#locks.claim(scopeDir, 'editor:transaction') : () => {}
233
- if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
241
+ if ((!document && !(scope.home && member.roles.includes('owner'))) || documents.some(found => found?.dir !== document?.dir)) throw new RequestError(400, 'a source transaction must stay in one document or the owner workspace scope')
242
+ if (!document && changes.some(change => change.path === DOCUMENT_ENTRY || change.path.endsWith(`/${DOCUMENT_ENTRY}`))) throw new RequestError(422, 'create-a-document-with-valid-content')
243
+ const scopeDir = document?.dir ?? ''
244
+ const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:transaction') : () => {}
234
245
  const work = async (): Promise<SourceTransactionAnswer> => {
246
+ const current = listDocumentEntries(this.#config)
247
+ for (const [index, change] of changes.entries()) {
248
+ this.#assertEditable(scope, change.path, member, current)
249
+ if (this.#documentHolding(change.path, current)?.dir !== documents[index]?.dir) throw new RequestError(409, 'source-scope-changed')
250
+ }
235
251
  // Read every preimage before creating directories or writing any file.
236
252
  const snapshots = changes.map(change => {
237
253
  const written = typeof change.content === 'string' ? Buffer.from(change.content, 'utf8') : Buffer.from(change.content)
@@ -256,16 +272,17 @@ export class SourceEditor {
256
272
  return { path: change.path, before: undefined, written, executable: false }
257
273
  })
258
274
  for (const snapshot of snapshots) if (snapshot.path !== binaryPath) validateDocumentSource(snapshot.path, snapshot.written.toString('utf8'), snapshot.before)
275
+ history?.check?.(snapshots)
259
276
  if (dryRun) return { versions: snapshots.map(snapshot => ({ path: snapshot.path, version: versionOf(snapshot.written) })) }
260
277
  const created: string[] = []
261
278
  const edited = snapshots.filter(snapshot => snapshot.before && !snapshot.written.equals(snapshot.before))
262
279
  const touched = snapshots.filter(snapshot => !snapshot.before || !snapshot.written.equals(snapshot.before)).map(snapshot => snapshot.path)
263
- const lang = history && touched.length ? readDocumentSummary(this.#config, document).lang : undefined
264
- const write = (next: DocumentFileChange[]) => this.#writer.write(next)
280
+ const lang = history && touched.length && document ? readDocumentSummary(this.#config, document).lang : undefined
281
+ const write = async (next: DocumentFileChange[]) => document ? await this.#writer.write(next) : writeChanges(this.#config, next, true)
265
282
  try {
266
283
  // Exclusive creation prevents replacing a file created outside serve after validation.
267
284
  for (const snapshot of snapshots) if (!snapshot.before) {
268
- await this.#writer.create(snapshot.path, snapshot.written)
285
+ await this.#writer.create(snapshot.path, snapshot.written, document === undefined)
269
286
  created.push(snapshot.path)
270
287
  }
271
288
  if (edited.length) await write(edited.map(snapshot => ({ path: snapshot.path, content: snapshot.written, ...snapshot.executable ? { executable: true } : {} })))
@@ -299,8 +316,7 @@ export class SourceEditor {
299
316
  const document = this.#documentHolding(path, documents)
300
317
  const outside = document === undefined
301
318
  const scopeDir = document?.dir ?? ''
302
- const release = this.#locks ? this.#locks.claim(scopeDir, 'editor:save') : () => {}
303
- if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
319
+ const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:save') : () => {}
304
320
  try {
305
321
  const bytes = this.#readBytes(scope, path, member, documents)
306
322
  const now = versionOf(bytes)
@@ -1,18 +1,16 @@
1
- import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
2
- import type { Route, SpeechSettingsChange } from '@lincyaw/kernel'
3
- import { OperatorSpeechSettings, SpeechSettingsError } from '@lincyaw/kernel/node'
1
+ import { jsonResponse, problemResponse } from '@lincyaw/kernel'
2
+ import type { Route, SpeechSettings } from '@lincyaw/kernel'
3
+ import { SpeechSettingsError, validateSpeechSettingsChange } from '@lincyaw/kernel/node'
4
4
 
5
5
  /** Global operator route: works before opening a document and never returns credential values. */
6
- export function speechSettingsRoute(directory: string, fallback: (name: string) => string | undefined): Route {
7
- const settings = new OperatorSpeechSettings(directory, fallback)
6
+ export function speechSettingsRoute(settings: SpeechSettings): Route {
8
7
  return { role: 'owner', maxBody: 16384, handle: async request => {
9
8
  try {
10
9
  if (request.method === 'GET') return jsonResponse(settings.read(), 200, { 'cache-control': 'no-store' })
11
10
  if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
12
11
  const body: unknown = await request.json().catch(() => undefined)
13
- if (!isRecord(body) || typeof body.revision !== 'string' || !['save', 'clear'].includes(String(body.action)) || Object.keys(body).some(key => !['action', 'revision', 'apiKey', 'appId'].includes(key))
14
- || body.action === 'save' && (body.apiKey !== undefined && typeof body.apiKey !== 'string' || body.appId !== undefined && typeof body.appId !== 'string')) return problemResponse(400, 'speech-settings-invalid')
15
- return jsonResponse(await settings.change(body as unknown as SpeechSettingsChange), 200, { 'cache-control': 'no-store' })
12
+ if (!validateSpeechSettingsChange(body)) return problemResponse(400, 'speech-settings-invalid')
13
+ return jsonResponse(await settings.change(body), 200, { 'cache-control': 'no-store' })
16
14
  } catch (error) {
17
15
  const code = error instanceof SpeechSettingsError ? error.code : 'speech-settings-unavailable'
18
16
  return problemResponse(code === 'speech-settings-invalid' ? 400 : code === 'speech-settings-conflict' || code === 'speech-settings-busy' ? 409 : 503, code)
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs'
1
+ import { existsSync, lstatSync, readdirSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import type { WorkspaceConfig } from './config.ts'
@@ -14,7 +14,7 @@ function templatesDir(config: WorkspaceConfig): string {
14
14
  export function listTemplates(config: WorkspaceConfig): string[] {
15
15
  const dir = templatesDir(config)
16
16
  try {
17
- return readdirSync(dir).filter(name => statSync(join(dir, name)).isDirectory()).sort()
17
+ return readdirSync(dir).filter(name => findTemplate(config, name) !== undefined).sort()
18
18
  } catch {
19
19
  return []
20
20
  }
@@ -33,7 +33,7 @@ export interface WorkbenchApi {
33
33
  * `prefetch`: the workbench prepares the document ahead of the author's click, answered at once. A build still running
34
34
  * after the wait is answered with 503 `preview-preparing` and `Retry-After`.
35
35
  */
36
- preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean): Promise<PreviewAnswer>
36
+ preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean, browserOrigin?: string): Promise<PreviewAnswer>
37
37
  build(document: string, to?: string[]): Promise<BuildAnswer>
38
38
  check(document: string): Promise<CheckAnswer>
39
39
  }
@@ -80,6 +80,17 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
80
80
  const { root, log } = options
81
81
  const irRevisions = new WeakMap<Compilation, string>()
82
82
  const relativeDocs = new WeakMap<Compilation, IRDocument>()
83
+ const previewBase = (base: string, browserOrigin: string | undefined): string => {
84
+ if (!browserOrigin) return base
85
+ try {
86
+ const preview = new URL(base), browser = new URL(browserOrigin)
87
+ if (preview.protocol !== browser.protocol || !['localhost', '127.0.0.1', '[::1]'].includes(preview.hostname)) return base
88
+ preview.hostname = browser.hostname
89
+ return base.endsWith('/') ? preview.href : preview.href.replace(/\/$/, '')
90
+ } catch {
91
+ return base
92
+ }
93
+ }
83
94
  const irRevisionOf = (compilation: Compilation) => {
84
95
  let known = irRevisions.get(compilation)
85
96
  if (!known) irRevisions.set(compilation, known = irRevision(compilation.doc))
@@ -119,7 +130,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
119
130
  return () => own.delete(listener)
120
131
  }, { signal })
121
132
  },
122
- async preview(document, renderer, prefetch = false) {
133
+ async preview(document, renderer, prefetch = false, browserOrigin) {
123
134
  const request = ++previewRequest
124
135
  const started = Date.now()
125
136
  const label = `[preview ${request}] document=${JSON.stringify(document || '.')} renderer=${renderer ?? 'all'} prefetch=${prefetch}`
@@ -127,7 +138,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
127
138
  let outcome = 'failed'
128
139
  log.info(`${label} state=started`)
129
140
  try {
130
- const base = options.url()
141
+ const base = previewBase(options.url(), browserOrigin)
131
142
  // The viewer app's page once it has what the document needs (an opened document waits for it a while), else the
132
143
  // document's page on the site.
133
144
  const page = await options.viewerPage?.(document, !prefetch).catch((error: unknown) => {