From b5330ddf708464901a9f4784835dc9a5879c22dc Mon Sep 17 00:00:00 2001 From: Archi Date: Mon, 26 Oct 2026 19:19:56 +0100 Subject: [PATCH 1/8] feat(core): chapters on renders and the share.allowMcp project config A render carries its scene cards as chapters in output ms (at most 100), and a project opts the MCP server into publishing share links with share.allowMcp, off by default (spec 349). --- .../core/schemas/project-config.schema.json | 11 ++++++ packages/core/src/project-config.ts | 13 +++++++ packages/core/src/run-result.ts | 12 +++++++ packages/core/test/project-config.spec.ts | 17 +++++++++ packages/core/test/run-result.spec.ts | 35 +++++++++++++++++++ 5 files changed, 88 insertions(+) diff --git a/packages/core/schemas/project-config.schema.json b/packages/core/schemas/project-config.schema.json index ba2ef8eb..3c2b75f1 100644 --- a/packages/core/schemas/project-config.schema.json +++ b/packages/core/schemas/project-config.schema.json @@ -375,6 +375,17 @@ } }, "additionalProperties": false + }, + "share": { + "type": "object", + "properties": { + "allowMcp": { + "default": false, + "description": "Let the MCP server (share_demo) publish the video of a run as a public link without asking anyone. Off by default; anyone with the link can watch until it expires or is revoked.", + "type": "boolean" + } + }, + "additionalProperties": false } }, "required": ["baseUrl"], diff --git a/packages/core/src/project-config.ts b/packages/core/src/project-config.ts index 1f6f4b8a..d7da5aa0 100644 --- a/packages/core/src/project-config.ts +++ b/packages/core/src/project-config.ts @@ -269,6 +269,18 @@ export const RenderConfigSchema = z .prefault({}); export type RenderConfig = z.infer; +/** + * Share links (spec 349, ADR-0019 §6). Off unless committed: an agent may + * then publish a video outside the machine without asking. + */ +export const ShareConfigSchema = z.strictObject({ + allowMcp: z.boolean().default(false).meta({ + description: + 'Let the MCP server (share_demo) publish the video of a run as a public link without asking anyone. Off by default; anyone with the link can watch until it expires or is revoked.', + }), +}); +export type ShareConfig = z.infer; + const PORT_TEMPLATE = // biome-ignore lint/suspicious/noTemplateCurlyInString: `${PORT}` is the config's own syntax. '${PORT} is the port of the run: --port, else PORT from the environment, else the default in ${PORT:-3000}. $${ is a literal ${.'; @@ -306,6 +318,7 @@ export const ProjectConfigSchema = z 'Where the fragments scenarios include live, relative to the project root. Default demoflow/fragments.', }), render: RenderConfigSchema, + share: ShareConfigSchema.optional(), }) .transform(({ allowedOrigins, ...config }) => { const origin = new URL(config.baseUrl).origin; diff --git a/packages/core/src/run-result.ts b/packages/core/src/run-result.ts index 966f706c..7c5a9d7e 100644 --- a/packages/core/src/run-result.ts +++ b/packages/core/src/run-result.ts @@ -94,6 +94,16 @@ export const RENDER_FORMATS = [ ] as const; export type RenderFormat = (typeof RENDER_FORMATS)[number]; +/** A scene card of a render: its title and where it starts, in output ms (spec 349). */ +export const ChapterSchema = z.strictObject({ + title: NonEmptyStringSchema.max(200), + atMs: z.number().int().nonnegative(), +}); +export type Chapter = z.infer; + +/** A render carries at most this many chapters (spec 349, Decision 1). */ +export const MAX_CHAPTERS = 100; + export const RenderOutputSchema = z.strictObject({ renderer: NonEmptyStringSchema, // Runs before spec 133 rendered only MP4 and wrote no `format`. @@ -105,6 +115,8 @@ export const RenderOutputSchema = z.strictObject({ width: z.number().int().positive(), height: z.number().int().positive(), fps: z.number().positive(), + // One per scene card, in output ms; renders before spec 349 have none. + chapters: z.array(ChapterSchema).max(MAX_CHAPTERS).optional(), }); /** One rendered file; for a GIF, its own size and frame rate. */ export type RenderOutput = z.infer; diff --git a/packages/core/test/project-config.spec.ts b/packages/core/test/project-config.spec.ts index b1517484..c6775fff 100644 --- a/packages/core/test/project-config.spec.ts +++ b/packages/core/test/project-config.spec.ts @@ -34,6 +34,23 @@ describe('parseProjectConfig', () => { }); }); + it('keeps share.allowMcp, off unless set, and rejects unknown keys (spec 349)', () => { + const baseUrl = 'https://a.example'; + expect(parseProjectConfig({ baseUrl, share: {} })).toMatchObject({ + ok: true, + value: { share: { allowMcp: false } }, + }); + expect( + parseProjectConfig({ baseUrl, share: { allowMcp: true } }), + ).toMatchObject({ ok: true, value: { share: { allowMcp: true } } }); + expect(parseProjectConfig({ baseUrl, share: { allowMcp: 'yes' } }).ok).toBe( + false, + ); + expect(parseProjectConfig({ baseUrl, share: { public: true } }).ok).toBe( + false, + ); + }); + it('keeps the square formats and their own settings (spec 304)', () => { const result = parseProjectConfig({ baseUrl: 'https://a.example', diff --git a/packages/core/test/run-result.spec.ts b/packages/core/test/run-result.spec.ts index 049f2e0b..a268cc26 100644 --- a/packages/core/test/run-result.spec.ts +++ b/packages/core/test/run-result.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { deriveRunStatus, + MAX_CHAPTERS, RunResultSchema, type RunStatus, STAGE_NAMES, @@ -139,6 +140,40 @@ describe('RunResultSchema', () => { expect(parsed.renders[0]?.format).toBe('mp4'); }); + it('reads a render without chapters, and keeps the chapters of one (spec 349)', () => { + const [render] = result.renders; + expect(RunResultSchema.parse(result).renders[0]?.chapters).toBeUndefined(); + const chapters = [ + { title: 'Sign in', atMs: 2000 }, + { title: 'Create a project', atMs: 9500 }, + ]; + expect( + RunResultSchema.parse({ ...result, renders: [{ ...render, chapters }] }) + .renders[0]?.chapters, + ).toEqual(chapters); + }); + + it('rejects a chapter that is empty, too long, negative or one too many', () => { + const [render] = result.renders; + const parses = (chapters: unknown) => + RunResultSchema.safeParse({ + ...result, + renders: [{ ...render, chapters }], + }).success; + expect(parses([{ title: '', atMs: 0 }])).toBe(false); + expect(parses([{ title: 'x'.repeat(201), atMs: 0 }])).toBe(false); + expect(parses([{ title: 'x'.repeat(200), atMs: 0 }])).toBe(true); + expect(parses([{ title: 'Intro', atMs: -1 }])).toBe(false); + expect(parses([{ title: 'Intro', atMs: 1.5 }])).toBe(false); + const many = (count: number) => + Array.from({ length: count }, (_, index) => ({ + title: `Scene ${index}`, + atMs: index * 1000, + })); + expect(parses(many(MAX_CHAPTERS))).toBe(true); + expect(parses(many(MAX_CHAPTERS + 1))).toBe(false); + }); + it('keeps each render format, in order, and rejects an unknown one', () => { const [render] = result.renders; const formats = [ From a1fd702d943791b65c10b4ba466b25a641ca2a58 Mon Sep 17 00:00:00 2001 From: Archi Date: Mon, 26 Oct 2026 19:24:27 +0100 Subject: [PATCH 2/8] feat(renderer): write a render's scene cards to result.json as chapters planChapters takes the plan's scene cards at their output start, after the idle map and every earlier card, so a chapter lands where the card is drawn. The FFmpeg renderer records them on every format it writes (spec 349, Decision 1). --- packages/renderer/src/ffmpeg/index.ts | 24 +++- packages/renderer/src/renderer.ts | 20 +++ packages/renderer/test/plan/build.spec.ts | 2 + packages/renderer/test/plan/chapters.spec.ts | 136 +++++++++++++++++++ 4 files changed, 175 insertions(+), 7 deletions(-) create mode 100644 packages/renderer/test/plan/chapters.spec.ts diff --git a/packages/renderer/src/ffmpeg/index.ts b/packages/renderer/src/ffmpeg/index.ts index 0676636a..4ffb192c 100644 --- a/packages/renderer/src/ffmpeg/index.ts +++ b/packages/renderer/src/ffmpeg/index.ts @@ -1,5 +1,10 @@ import path from 'node:path'; -import { type Renderer, recordRender, renderPath } from '../renderer.ts'; +import { + planChapters, + type Renderer, + recordRender, + renderPath, +} from '../renderer.ts'; import { drawPlan } from './pipeline.ts'; /** @@ -15,12 +20,17 @@ export const ffmpegRenderer: Renderer = { format, file: renderPath(runDir, 'ffmpeg', format), })); - return recordRender(runDir, 'ffmpeg', files, () => - drawPlan( - path.resolve(runDir, plan.source.file), - plan, - files.map(({ file }) => file), - ), + return recordRender( + runDir, + 'ffmpeg', + files, + () => + drawPlan( + path.resolve(runDir, plan.source.file), + plan, + files.map(({ file }) => file), + ), + planChapters(plan), ); }, }; diff --git a/packages/renderer/src/renderer.ts b/packages/renderer/src/renderer.ts index f65deb5f..dcf6c2e0 100644 --- a/packages/renderer/src/renderer.ts +++ b/packages/renderer/src/renderer.ts @@ -1,7 +1,9 @@ import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { + type Chapter, deriveRunStatus, + MAX_CHAPTERS, type RenderFormat, type RenderOutput, type RunResult, @@ -51,6 +53,21 @@ export function renderPath( return path.join(runDir, 'render', `${renderer}.${EXTENSIONS[format]}`); } +/** + * The chapters of a plan (spec 349): one per scene card, at its start in + * output ms — after the idle map and every card before it, as drawn. The + * intro and the outro are not chapters. + */ +export function planChapters(plan: Pick): Chapter[] { + return plan.cards + .filter((card) => card.kind === 'scene' && card.title.trim() !== '') + .slice(0, MAX_CHAPTERS) + .map((card) => ({ + title: card.title.slice(0, 200), + atMs: Math.max(0, Math.round(card.startMs)), + })); +} + /** * Runs `draw`, which writes every one of `files`, and records them in the * run's `result.json`: the `rendering` stage goes `running` → `passed` (or @@ -58,12 +75,14 @@ export function renderPath( * `renders[]` entry per file, in order, replaces every earlier one of the * same renderer, and the run status is derived again (ADR-0004 §3). A file * that fails fails them all: a partial set is never a success (spec 133). + * `chapters`, when given, go on every entry: the formats share one timeline. */ export async function recordRender( runDir: string, renderer: string, files: readonly { format: RenderFormat; file: string }[], draw: () => Promise, + chapters?: readonly Chapter[], ): Promise { await updateResult(runDir, (result) => { result.stages.rendering = { status: 'running', startedAt: timestamp() }; @@ -89,6 +108,7 @@ export async function recordRender( width: probe.width, height: probe.height, fps: probe.fps, + ...(chapters === undefined ? {} : { chapters: [...chapters] }), }); } await updateResult(runDir, (result) => { diff --git a/packages/renderer/test/plan/build.spec.ts b/packages/renderer/test/plan/build.spec.ts index fd747333..1fda79fb 100644 --- a/packages/renderer/test/plan/build.spec.ts +++ b/packages/renderer/test/plan/build.spec.ts @@ -363,6 +363,7 @@ describe.skipIf(!hasFfmpeg)('buildRenderPlan on real runs', () => { file, ]); }, + [{ title: 'Customers', atMs: 0 }], ); expect(output).toMatchObject({ renderer: 'probe', @@ -371,6 +372,7 @@ describe.skipIf(!hasFfmpeg)('buildRenderPlan on real runs', () => { width: 1920, height: 1080, fps: 30, + chapters: [{ title: 'Customers', atMs: 0 }], }); expect(output.sizeBytes).toBeGreaterThan(0); const mp4 = await probeVideo(file); diff --git a/packages/renderer/test/plan/chapters.spec.ts b/packages/renderer/test/plan/chapters.spec.ts new file mode 100644 index 00000000..601f0ec6 --- /dev/null +++ b/packages/renderer/test/plan/chapters.spec.ts @@ -0,0 +1,136 @@ +import { + type CardsConfig, + deriveRunStatus, + MAX_CHAPTERS, + type RunResult, + type Stages, + type TimelineEvent, +} from '@demoflow/core'; +import { describe, expect, it } from 'vitest'; +import { planChapters, planRender, type VideoProbe } from '../../src/index.ts'; + +function result(): RunResult { + const passed = { status: 'passed' as const }; + const stages: Stages = { + readiness: passed, + execution: passed, + verification: passed, + recording: passed, + rendering: { status: 'pending' }, + storage: { status: 'pending' }, + }; + return { + schemaVersion: 1, + runId: 'run', + scenarioId: 'inline', + scenarioName: 'Create a customer', + startedAt: '2026-10-18T10:00:00.000Z', + finishedAt: '2026-10-18T10:00:10.000Z', + status: deriveRunStatus(stages), + stages, + renders: [], + warnings: [], + }; +} + +const CARDS: CardsConfig = { + intro: { enabled: true, durationMs: 2000 }, + scenes: { enabled: true, durationMs: 1500 }, + outro: { title: 'Thanks', durationMs: 2500 }, +}; + +const scene = (atMs: number, title: string) => ({ + action: 'marker' as const, + startMs: atMs, + endMs: atMs, + marker: { title, kind: 'scene' as const }, +}); + +const wait = (startMs: number, endMs: number) => ({ + action: 'wait' as const, + startMs, + endMs, +}); + +function plan( + events: Omit[], + freezes: VideoProbe['freezes'] = [], + cards: CardsConfig = CARDS, +) { + return planRender( + { + timeline: { + schemaVersion: 1, + viewport: { width: 1280, height: 720 }, + deviceScaleFactor: 2, + videoFile: 'source.webm', + events: events.map((event, stepIndex) => ({ ...event, stepIndex })), + }, + result: result(), + source: { + width: 2560, + height: 1440, + fps: 25, + durationMs: 20_000, + codec: 'vp9', + freezes, + }, + }, + { offsetMs: 0, cards }, + ); +} + +describe('planChapters (spec 349)', () => { + it('gives one chapter per scene card, at its output start, without the intro and outro', () => { + const rendered = plan([scene(1000, 'Sign in'), scene(4000, 'Invoices')]); + expect(rendered.cards.map((card) => card.kind)).toEqual([ + 'intro', + 'scene', + 'scene', + 'outro', + ]); + // After the 2 s intro; the second also after the first 1.5 s scene card. + expect(planChapters(rendered)).toEqual([ + { title: 'Sign in', atMs: 3000 }, + { title: 'Invoices', atMs: 7500 }, + ]); + }); + + it('places a scene after a trimmed idle stretch where the card is drawn', () => { + // The 4 s wait is frozen and plays in 400 ms: 3.6 s saved before the scene. + const rendered = plan( + [wait(1000, 5000), scene(6000, 'Invoices')], + [{ startMs: 1000, endMs: 5000 }], + ); + const [chapter] = planChapters(rendered); + const card = rendered.cards.find((entry) => entry.kind === 'scene'); + expect(chapter).toEqual({ title: 'Invoices', atMs: card?.startMs }); + expect(chapter.atMs).toBe(2000 + 6000 - 3600); + }); + + it('is empty without scenes, or with scene cards off', () => { + expect(planChapters(plan([wait(0, 1000)]))).toEqual([]); + expect( + planChapters( + plan([scene(1000, 'Sign in')], [], { + ...CARDS, + scenes: { enabled: false, durationMs: 1500 }, + }), + ), + ).toEqual([]); + }); + + it('keeps at most MAX_CHAPTERS, each title at most 200 characters', () => { + const chapters = planChapters({ + cards: Array.from({ length: MAX_CHAPTERS + 5 }, (_, index) => ({ + kind: 'scene' as const, + startMs: index * 1000 + 0.4, + durationMs: 1500, + title: index === 0 ? 'x'.repeat(250) : `Scene ${index}`, + })), + }); + expect(chapters).toHaveLength(MAX_CHAPTERS); + expect(chapters[0]).toEqual({ title: 'x'.repeat(200), atMs: 0 }); + expect(chapters[1]).toEqual({ title: 'Scene 1', atMs: 1000 }); + }); +}); From ea867c88fb8d2d797ca5bfecbcf8ffedfeb5fede Mon Sep 17 00:00:00 2001 From: Archi Date: Mon, 26 Oct 2026 19:39:51 +0100 Subject: [PATCH 3/8] feat(cli): the runner prepares shares and serves their posters The daemon announces features: ['share'] and answers share.prepare with the scenario's description, the render's chapters and the size of a poster it makes with FFmpeg (one JPEG frame, at most 1280 px wide, reused while newer than the render). The relay serves that poster for video.open with asset: 'poster'; an unknown asset is not-found. scenarioDescription moves to scenario-file.ts so the daemon reads descriptions the way demoflow render does. --- apps/cli/src/commands/render.ts | 20 +- apps/cli/src/commands/scenario-file.ts | 22 +- apps/cli/src/runner/connection.ts | 19 +- apps/cli/src/runner/daemon.ts | 6 + apps/cli/src/runner/relay/index.ts | 40 +- apps/cli/src/runner/share/files.ts | 14 + apps/cli/src/runner/share/poster.ts | 87 +++++ apps/cli/src/runner/share/prepare.ts | 181 +++++++++ apps/cli/test/runner/connection.spec.ts | 48 +++ apps/cli/test/runner/daemon-launch.spec.ts | 6 +- apps/cli/test/runner/relay.spec.ts | 78 ++++ apps/cli/test/runner/share.spec.ts | 427 +++++++++++++++++++++ 12 files changed, 917 insertions(+), 31 deletions(-) create mode 100644 apps/cli/src/runner/share/files.ts create mode 100644 apps/cli/src/runner/share/poster.ts create mode 100644 apps/cli/src/runner/share/prepare.ts create mode 100644 apps/cli/test/runner/share.spec.ts diff --git a/apps/cli/src/commands/render.ts b/apps/cli/src/commands/render.ts index 4263cf53..9856f107 100644 --- a/apps/cli/src/commands/render.ts +++ b/apps/cli/src/commands/render.ts @@ -28,7 +28,7 @@ import { exitCodeFor } from './exit.ts'; import type { Io } from './io.ts'; import { formatJson, formatSummary } from './output.ts'; import { assertSafeRunId } from './run-id.ts'; -import { loadScenario } from './scenario-file.ts'; +import { scenarioDescription } from './scenario-file.ts'; import { readResult, settleRun } from './settle.ts'; export interface RenderFlags { @@ -174,24 +174,6 @@ async function readRenderable(runDir: string): Promise { return result; } -/** - * The intro card's subtitle: the scenario's `description`, read from the - * project when its file is still there and loads. An inline scenario of - * `demoflow mcp` is gone after its run, so its card has no subtitle. - */ -function scenarioDescription( - root: string, - scenarioId: string, -): string | undefined { - const file = path.join(root, scenarioId); - if (!existsSync(file)) return undefined; - try { - return loadScenario(file).scenario.description; - } catch { - return undefined; - } -} - /** * What `buildRenderPlan` gets from the project's `render.*`, for `run` and * `render` alike: a re-render is styled exactly like a first render would be diff --git a/apps/cli/src/commands/scenario-file.ts b/apps/cli/src/commands/scenario-file.ts index 4a9b4ccc..5aaab559 100644 --- a/apps/cli/src/commands/scenario-file.ts +++ b/apps/cli/src/commands/scenario-file.ts @@ -1,4 +1,5 @@ -import { readFileSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; +import path from 'node:path'; import { type FragmentSource, type Issue, @@ -40,3 +41,22 @@ export function loadScenario( } return { scenario: parsed.value, warnings: parsed.warnings }; } + +/** + * The scenario's `description`, read from the project when its file is still + * there and loads (spec 255, Decision 3): the intro card's subtitle and a + * share's description (spec 349). An inline scenario of `demoflow mcp` is + * gone after its run, so it has none. + */ +export function scenarioDescription( + root: string, + scenarioId: string, +): string | undefined { + const file = path.join(root, scenarioId); + if (!existsSync(file)) return undefined; + try { + return loadScenario(file).scenario.description; + } catch { + return undefined; + } +} diff --git a/apps/cli/src/runner/connection.ts b/apps/cli/src/runner/connection.ts index bc96d4d5..396b5557 100644 --- a/apps/cli/src/runner/connection.ts +++ b/apps/cli/src/runner/connection.ts @@ -8,6 +8,7 @@ import { import type { Logger } from './log.ts'; import type { RelaySender, VideoRelayPort } from './relay/index.ts'; import type { ProjectsPort } from './roots/index.ts'; +import type { SharePort } from './share/prepare.ts'; import type { ConnectionState } from './state.ts'; /** Decision 6: each side pings every 25 s and gives up after 60 s of silence. */ @@ -80,6 +81,11 @@ export interface ConnectionDeps { launches?: LaunchPort; /** Answers `project.*` (spec 377); without it, logged as unknown. */ projects?: ProjectsPort; + /** + * Answers `share.prepare` (spec 349); without it, logged as unknown. Its + * poster goes out through `relay`, so it is announced only with one. + */ + share?: SharePort; } export type ConnectionOutcome = 'stopped' | 'revoked'; @@ -187,7 +193,12 @@ export class RunnerConnection { // so it claims no options. const runOptions = this.deps.launches !== undefined ? [...RUN_OPTIONS] : []; // Spec 377, Decision 9: what else this daemon answers. - const features = this.deps.projects !== undefined ? ['projects'] : []; + const features: string[] = []; + if (this.deps.projects !== undefined) features.push('projects'); + // Spec 349, Decision 5: a share needs `share.prepare` and the poster's stream. + if (this.deps.share !== undefined && this.deps.relay !== undefined) { + features.push('share'); + } this.send({ type: 'launches.sync', running, @@ -274,6 +285,12 @@ export class RunnerConnection { return; } break; + case 'share.prepare': + if (this.deps.share !== undefined) { + this.deps.share.handle(fields, this.relaySender()); + return; + } + break; } this.deps.logger.log( 'warn', diff --git a/apps/cli/src/runner/daemon.ts b/apps/cli/src/runner/daemon.ts index 8c92a6ed..2eaf9eb7 100644 --- a/apps/cli/src/runner/daemon.ts +++ b/apps/cli/src/runner/daemon.ts @@ -23,6 +23,7 @@ import { isWebsiteRegistered, ProjectRequests, } from './roots/index.ts'; +import { sharePreparer } from './share/prepare.ts'; import { type ConnectionState, writeState } from './state.ts'; /** How often the daemon looks for `runner.stop`. */ @@ -161,6 +162,11 @@ export async function runForeground(io: Io, deps: DaemonDeps): Promise { loadProject: launcherDeps.loadProject, writeTemplate: defaultWriteTemplate, }), + share: sharePreparer({ + indexFile: paths.reportedRuns, + logger, + platform: deps.host.platform, + }), }); const stop = (why: string) => { diff --git a/apps/cli/src/runner/relay/index.ts b/apps/cli/src/runner/relay/index.ts index 9599f8eb..35145ed3 100644 --- a/apps/cli/src/runner/relay/index.ts +++ b/apps/cli/src/runner/relay/index.ts @@ -7,6 +7,7 @@ import { import { pathFor } from '../../config/platform.ts'; import { findReportedRun } from '../../runs-report/reported-runs.ts'; import type { Logger } from '../log.ts'; +import { posterPath } from '../share/files.ts'; import { parseRange } from './range.ts'; import { type RelayFile, @@ -82,19 +83,36 @@ export function isInside( } /** - * The real path of a reported run's rendered file in `format`, or `null`. - * The run directory comes from the index, never from the message, and only a - * file `result.json` lists, inside that directory, can come out. + * Spec 349, Decision 4: what `video.open` may ask for besides the render. + * Anything else is `not-found`. + */ +export const VIDEO_ASSETS = ['poster'] as const; +export type VideoAsset = (typeof VIDEO_ASSETS)[number]; + +/** + * The real path of a reported run's rendered file in `format` — or, with + * `asset: 'poster'`, of the poster a share made for it — or `null`. The run + * directory comes from the index, never from the message, and only a file + * `result.json` lists, or the poster's fixed name, inside that directory, + * can come out. */ export async function locateVideo( runId: string, format: RenderFormat, deps: RelayDeps, + asset?: VideoAsset, ): Promise { const entry = await findReportedRun(deps.indexFile, runId); if (entry === null) return null; const p = pathFor(deps.platform); try { + if (asset === 'poster') { + const root = await deps.fs.realpath(entry.runDir); + const real = await deps.fs.realpath( + posterPath(entry.runDir, format, deps.platform), + ); + return isInside(root, real, deps.platform) ? real : null; + } const parsed = RunResultSchema.safeParse( JSON.parse(await deps.fs.readFile(p.join(entry.runDir, RESULT_FILE))), ); @@ -196,6 +214,11 @@ export class VideoRelay implements VideoRelayPort { return; } const videoFormat = format as RenderFormat; + const { asset } = message; + // An asset this daemon does not know opens, and fails `not-found`. + const known = + asset === undefined || VIDEO_ASSETS.includes(asset as VideoAsset); + const videoAsset = asset === undefined ? undefined : (asset as VideoAsset); if (this.streams.has(streamId)) { this.deps.logger.log( 'warn', @@ -203,9 +226,10 @@ export class VideoRelay implements VideoRelayPort { ); return; } + const what = known && videoAsset !== undefined ? ` ${videoAsset}` : ''; if (this.streams.size >= MAX_STREAMS) { sender.send({ type: 'video.error', streamId, code: 'busy' }); - this.logStream(runId, videoFormat, 0, 'busy'); + this.logStream(runId, videoFormat, what, 0, 'busy'); return; } const stream = new VideoStream(streamId, sender, (outcome, sent) => { @@ -213,12 +237,13 @@ export class VideoRelay implements VideoRelayPort { this.streams.delete(streamId); this.runIds.delete(streamId); } - this.logStream(runId, videoFormat, sent, outcome); + this.logStream(runId, videoFormat, what, sent, outcome); }); this.streams.set(streamId, stream); this.runIds.set(streamId, runId); void stream.begin(async () => { - const file = await locateVideo(runId, videoFormat, this.deps); + if (!known) return null; + const file = await locateVideo(runId, videoFormat, this.deps, videoAsset); return file === null ? null : this.deps.fs.open(file); }, range); } @@ -227,12 +252,13 @@ export class VideoRelay implements VideoRelayPort { private logStream( runId: string, format: RenderFormat, + asset: string, sent: number, outcome: StreamOutcome | 'busy', ): void { this.deps.logger.log( 'info', - `video ${runId} ${format}: ${sent} bytes sent, ${outcome}`, + `video ${runId} ${format}${asset}: ${sent} bytes sent, ${outcome}`, ); } } diff --git a/apps/cli/src/runner/share/files.ts b/apps/cli/src/runner/share/files.ts new file mode 100644 index 00000000..bc1cede6 --- /dev/null +++ b/apps/cli/src/runner/share/files.ts @@ -0,0 +1,14 @@ +import type { RenderFormat } from '@demoflow/core'; +import { pathFor } from '../../config/platform.ts'; + +/** Spec 349, Decision 3: what a share makes lives in `/share/`. */ +export const SHARE_DIR = 'share'; + +/** `/share/poster-.jpg`: one poster per rendered format. */ +export function posterPath( + runDir: string, + format: RenderFormat, + platform: NodeJS.Platform, +): string { + return pathFor(platform).join(runDir, SHARE_DIR, `poster-${format}.jpg`); +} diff --git a/apps/cli/src/runner/share/poster.ts b/apps/cli/src/runner/share/poster.ts new file mode 100644 index 00000000..353f9367 --- /dev/null +++ b/apps/cli/src/runner/share/poster.ts @@ -0,0 +1,87 @@ +import { mkdir, rename, rm, stat } from 'node:fs/promises'; +import { runFfmpeg } from '@demoflow/renderer'; +import { pathFor } from '../../config/platform.ts'; + +/** #347: the API refuses a poster over 1 MiB, so the daemon does too. */ +export const POSTER_MAX_BYTES = 1024 * 1024; +/** Decision 3: the frame is taken at most this far in. */ +export const POSTER_AT_MAX_MS = 1500; +/** Decision 3: the poster is at most this wide, keeping the aspect. */ +export const POSTER_MAX_WIDTH = 1280; + +/** FFmpeg, as the poster maker runs it; tests stub it. */ +export type RunFfmpeg = (args: readonly string[]) => Promise; + +export interface PosterRequest { + /** The render's file, already checked to be inside the run directory. */ + render: string; + /** Where the poster lives: `posterPath(runDir, format)`. */ + poster: string; + /** The render's `durationMs`. */ + durationMs: number; + platform: NodeJS.Platform; +} + +/** The FFmpeg arguments for one JPEG frame of `render` at `atMs`. */ +export function posterArgs( + render: string, + output: string, + atMs: number, +): string[] { + return [ + '-y', + '-i', + render, + // After `-i`: a GIF cannot be seeked on input, and the decode is short. + '-ss', + (atMs / 1000).toFixed(3), + '-frames:v', + '1', + '-an', + '-vf', + `scale='min(${POSTER_MAX_WIDTH},iw)':-2`, + '-q:v', + '4', + output, + ]; +} + +/** Decision 3: `min(1500, ⌊durationMs / 2⌋)`. */ +export function posterAtMs(durationMs: number): number { + return Math.min(POSTER_AT_MAX_MS, Math.floor(Math.max(0, durationMs) / 2)); +} + +/** + * Decision 3: the poster of a render, made with FFmpeg unless the one on + * disk is newer than the render, and its size in bytes. It is written to a + * temporary file and renamed, so a crash never leaves half a JPEG to reuse. + * Rejects when FFmpeg fails or the poster is over `POSTER_MAX_BYTES`. + */ +export async function makePoster( + request: PosterRequest, + ffmpeg: RunFfmpeg = runFfmpeg, +): Promise { + const { render, poster } = request; + const rendered = await stat(render); + const existing = await stat(poster).catch(() => null); + let size: number; + if (existing !== null && existing.mtimeMs > rendered.mtimeMs) { + size = existing.size; + } else { + const p = pathFor(request.platform); + await mkdir(p.dirname(poster), { recursive: true }); + const temp = `${poster.slice(0, -'.jpg'.length)}.tmp.jpg`; + try { + await ffmpeg(posterArgs(render, temp, posterAtMs(request.durationMs))); + await rename(temp, poster); + } catch (error) { + await rm(temp, { force: true }); + throw error; + } + size = (await stat(poster)).size; + } + if (size === 0 || size > POSTER_MAX_BYTES) { + throw new Error(`the poster is ${size} bytes`); + } + return size; +} diff --git a/apps/cli/src/runner/share/prepare.ts b/apps/cli/src/runner/share/prepare.ts new file mode 100644 index 00000000..dc2e131b --- /dev/null +++ b/apps/cli/src/runner/share/prepare.ts @@ -0,0 +1,181 @@ +import { readFile, realpath } from 'node:fs/promises'; +import { + type Chapter, + RENDER_FORMATS, + type RenderFormat, + RunResultSchema, +} from '@demoflow/core'; +import { scenarioDescription } from '../../commands/scenario-file.ts'; +import { pathFor } from '../../config/platform.ts'; +import { findReportedRun } from '../../runs-report/reported-runs.ts'; +import type { Logger } from '../log.ts'; +import { isInside, RUN_ID } from '../relay/index.ts'; +import { posterPath } from './files.ts'; +import { makePoster, type PosterRequest } from './poster.ts'; + +/** `RUN_FILES.result` of the engine, which the daemon does not load. */ +const RESULT_FILE = 'result.json'; +/** #347: the API keeps at most this much of a share's description. */ +export const DESCRIPTION_MAX_LENGTH = 2000; + +export interface ShareDeps { + /** `reported-runs.jsonl`. */ + indexFile: string; + logger: Logger; + platform: NodeJS.Platform; + /** Decision 3; tests stub FFmpeg through it. */ + makePoster(request: PosterRequest): Promise; +} + +/** The socket, as the preparer sees it: JSON text frames only. */ +export interface ShareSender { + send(message: Record): void; +} + +/** What the connection needs from the preparer. */ +export interface SharePort { + handle(message: Record, sender: ShareSender): void; +} + +/** What `share.prepare` answers, before the request id is added. */ +export type Prepared = + | { + ok: true; + description?: string; + chapters: Chapter[]; + posterSize: number; + } + | { ok: false; code: 'not-found' | 'no-render' | 'io' }; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** + * Spec 349, Decision 2: the daemon's side of `share.prepare`. It answers with + * the scenario's description, the render's chapters and the size of a poster + * it makes, which the relay then serves as `asset: 'poster'`. The server names + * a run by its id; no path is ever sent or logged. + */ +export class SharePreparer implements SharePort { + private readonly deps: ShareDeps; + /** One poster at a time per file: two shares of a render share it. */ + private readonly posters = new Map>(); + + constructor(deps: ShareDeps) { + this.deps = deps; + } + + handle(message: Record, sender: ShareSender): void { + const { requestId, runId, format } = message; + if ( + typeof requestId !== 'string' || + !UUID.test(requestId) || + typeof runId !== 'string' || + !RUN_ID.test(runId) || + !RENDER_FORMATS.includes(format as RenderFormat) + ) { + this.deps.logger.log('warn', 'ignored a malformed share.prepare'); + return; + } + void this.prepare(runId, format as RenderFormat) + .catch((): Prepared => ({ ok: false, code: 'io' })) + .then((prepared) => { + this.deps.logger.log( + 'info', + `share ${runId} ${format}: ${prepared.ok ? 'prepared' : prepared.code}`, + ); + if (!prepared.ok) { + sender.send({ type: 'share.error', requestId, code: prepared.code }); + return; + } + const { description, chapters, posterSize } = prepared; + sender.send({ + type: 'share.prepared', + requestId, + ...(description === undefined ? {} : { description }), + chapters, + posterSize, + }); + }); + } + + async prepare(runId: string, format: RenderFormat): Promise { + const { platform } = this.deps; + const p = pathFor(platform); + const entry = await findReportedRun(this.deps.indexFile, runId); + if (entry === null) return { ok: false, code: 'not-found' }; + let raw: unknown; + try { + raw = JSON.parse( + await readFile(p.join(entry.runDir, RESULT_FILE), 'utf8'), + ); + } catch { + return { ok: false, code: 'not-found' }; + } + const parsed = RunResultSchema.safeParse(raw); + if (!parsed.success) return { ok: false, code: 'not-found' }; + const render = parsed.data.renders.find((item) => item.format === format); + if (render === undefined) return { ok: false, code: 'no-render' }; + + // The same boundary as the relay: only a file inside the run directory. + let file: string; + try { + const root = await realpath(entry.runDir); + file = await realpath(p.resolve(entry.runDir, render.file)); + if (!isInside(root, file, platform)) { + return { ok: false, code: 'no-render' }; + } + } catch { + return { ok: false, code: 'no-render' }; + } + + const posterSize = await this.poster({ + render: file, + poster: posterPath(entry.runDir, format, platform), + durationMs: render.durationMs, + platform, + }); + const description = this.description(entry.root, parsed.data.scenarioId); + return { + ok: true, + ...(description === undefined ? {} : { description }), + chapters: render.chapters ?? [], + posterSize, + }; + } + + private poster(request: PosterRequest): Promise { + const pending = this.posters.get(request.poster); + if (pending !== undefined) return pending; + const making = this.deps.makePoster(request).finally(() => { + this.posters.delete(request.poster); + }); + this.posters.set(request.poster, making); + return making; + } + + /** + * The scenario's description, from its file in the project the run was + * reported from — and only from inside that project. + */ + private description( + root: string | undefined, + scenarioId: string, + ): string | undefined { + if (root === undefined) return undefined; + const p = pathFor(this.deps.platform); + if (!isInside(root, p.resolve(root, scenarioId), this.deps.platform)) { + return undefined; + } + const description = scenarioDescription(root, scenarioId)?.trim(); + return description === undefined || description === '' + ? undefined + : description.slice(0, DESCRIPTION_MAX_LENGTH); + } +} + +/** The daemon's preparer, with the real FFmpeg. */ +export function sharePreparer( + deps: Omit, +): SharePreparer { + return new SharePreparer({ ...deps, makePoster: (r) => makePoster(r) }); +} diff --git a/apps/cli/test/runner/connection.spec.ts b/apps/cli/test/runner/connection.spec.ts index 47ceb5df..ad868068 100644 --- a/apps/cli/test/runner/connection.spec.ts +++ b/apps/cli/test/runner/connection.spec.ts @@ -18,6 +18,7 @@ import type { VideoRelayPort, } from '../../src/runner/relay/index.ts'; import type { ProjectsPort } from '../../src/runner/roots/index.ts'; +import type { SharePort } from '../../src/runner/share/prepare.ts'; import type { ConnectionState } from '../../src/runner/state.ts'; import { FakeClock, @@ -52,6 +53,7 @@ function start( artifacts?: ArtifactsPort, launches?: LaunchPort, projects?: ProjectsPort, + share?: SharePort, ) { const fake = fakeSockets(); sockets = fake.sockets; @@ -78,6 +80,7 @@ function start( ...(artifacts === undefined ? {} : { artifacts }), ...(launches === undefined ? {} : { launches }), ...(projects === undefined ? {} : { projects }), + ...(share === undefined ? {} : { share }), }); void connection.run().then((value) => { outcome = value; @@ -564,6 +567,51 @@ describe('RunnerConnection and the video relay', () => { ); }); + it('announces the share feature and routes share.prepare to it (spec 349)', () => { + const relay = recordingRelay(); + const handled: Array> = []; + const share: SharePort = { + handle(message, sender) { + handled.push(message); + sender.send({ type: 'share.error', requestId: 'q', code: 'io' }); + }, + }; + start(0.5, relay, undefined, undefined, undefined, share); + last().open(); + expect(last().sent[0]).toEqual({ ...EMPTY_SYNC, features: ['share'] }); + last().receive({ + type: 'share.prepare', + requestId: 'q', + runId: 'r', + format: 'mp4', + }); + expect(handled).toEqual([ + { type: 'share.prepare', requestId: 'q', runId: 'r', format: 'mp4' }, + ]); + expect(last().sent).toContainEqual({ + type: 'share.error', + requestId: 'q', + code: 'io', + }); + expect(logger.text()).not.toMatch(/ignored/); + }); + + it('does not announce share without the relay that streams its poster', () => { + start(0.5, undefined, undefined, undefined, undefined, { + handle: () => {}, + }); + last().open(); + expect(last().sent[0]).toEqual(EMPTY_SYNC); + }); + + it('logs share.prepare as unknown without the share port, as a daemon before #349 did', () => { + start(0.5, recordingRelay()); + last().open(); + last().receive({ type: 'share.prepare', requestId: 'q' }); + expect(logger.text()).toMatch(/ignored a message of type "share.prepare"/); + expect(last().sent).toEqual([EMPTY_SYNC]); + }); + it('logs run.start as unknown without a launcher, as a daemon before #248 did', () => { start(); last().open(); diff --git a/apps/cli/test/runner/daemon-launch.spec.ts b/apps/cli/test/runner/daemon-launch.spec.ts index 589ccedb..bc88c2e9 100644 --- a/apps/cli/test/runner/daemon-launch.spec.ts +++ b/apps/cli/test/runner/daemon-launch.spec.ts @@ -191,7 +191,7 @@ describe('the daemon with a website-started run', () => { type: 'launches.sync', running: [], runOptions: ['formats'], - features: ['projects'], + features: ['projects', 'share'], checks: true, }); first.receive({ @@ -232,7 +232,7 @@ describe('the daemon with a website-started run', () => { type: 'launches.sync', running: [REQUEST], runOptions: ['formats'], - features: ['projects'], + features: ['projects', 'share'], checks: true, }); await stop(next); @@ -249,7 +249,7 @@ describe('the daemon with a website-started run', () => { type: 'launches.sync', running: [], runOptions: ['formats'], - features: ['projects'], + features: ['projects', 'share'], checks: true, }, ]); diff --git a/apps/cli/test/runner/relay.spec.ts b/apps/cli/test/runner/relay.spec.ts index 3a292913..20227d53 100644 --- a/apps/cli/test/runner/relay.spec.ts +++ b/apps/cli/test/runner/relay.spec.ts @@ -133,6 +133,7 @@ function open( format?: RenderFormat; range?: VideoRange | null; streamId?: string; + asset?: unknown; } = {}, ): string { const streamId = options.streamId ?? randomUUID(); @@ -143,6 +144,7 @@ function open( runId: options.runId ?? RUN_ID, format: options.format ?? 'mp4', range: options.range ?? null, + ...('asset' in options ? { asset: options.asset } : {}), }, sender, ); @@ -451,6 +453,82 @@ describe('VideoRelay: the ADR-0008 boundary', () => { }); }); +describe('VideoRelay: the poster asset (spec 349)', () => { + let poster: Buffer; + beforeEach(() => { + poster = randomBytes(CHUNK_BYTES + 77); + mkdirSync(path.join(runDir, 'share')); + writeFileSync(path.join(runDir, 'share', 'poster-mp4.jpg'), poster); + }); + + it('streams exactly the poster of the format, and logs it as one', async () => { + const sender = recordingSender(); + const streamId = open(sender, { asset: 'poster' }); + expect((await drain(sender, streamId)).equals(poster)).toBe(true); + expect(sender.messagesOf(streamId)[0]).toMatchObject({ + type: 'video.head', + size: poster.length, + }); + await until(() => logger.lines.length > 0, 'log line'); + expect(logger.lines[0]?.message).toBe( + `video ${RUN_ID} mp4 poster: ${poster.length} bytes sent, sent`, + ); + expect(logger.text()).not.toContain(home); + }); + + it('still serves the render without an asset', async () => { + const sender = recordingSender(); + const streamId = open(sender); + expect((await drain(sender, streamId)).equals(video)).toBe(true); + }); + + it('answers not-found for a format with no poster', async () => { + const sender = recordingSender(); + await expectNotFound( + sender, + open(sender, { asset: 'poster', format: 'gif' }), + ); + }); + + it('answers not-found for a run this machine never reported', async () => { + const sender = recordingSender(); + await expectNotFound( + sender, + open(sender, { asset: 'poster', runId: 'someone-else' }), + ); + }); + + it.each([ + 'thumbnail', + '../result.json', + 42, + null, + ])('answers not-found for the unknown asset %j', async (asset) => { + const sender = recordingSender(); + await expectNotFound(sender, open(sender, { asset })); + expect(counts.open).toBe(0); + }); + + it('answers not-found for a poster that links out of the run directory', async (ctx) => { + const secret = path.join(home, 'secret.jpg'); + writeFileSync(secret, 'secret'); + const link = path.join(runDir, 'share', 'poster-gif.jpg'); + try { + symlinkSync(secret, link, 'file'); + } catch (error) { + if (process.platform === 'win32') { + ctx.skip(`file symlinks need a privilege here: ${String(error)}`); + } + throw error; + } + const sender = recordingSender(); + await expectNotFound( + sender, + open(sender, { asset: 'poster', format: 'gif' }), + ); + }); +}); + describe('VideoRelay: flow and ends', () => { beforeEach(() => { // 2 MiB and a bit: four windows' worth. diff --git a/apps/cli/test/runner/share.spec.ts b/apps/cli/test/runner/share.spec.ts new file mode 100644 index 00000000..78ab3c19 --- /dev/null +++ b/apps/cli/test/runner/share.spec.ts @@ -0,0 +1,427 @@ +import { randomUUID } from 'node:crypto'; +import { + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + statSync, + symlinkSync, + utimesSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import type { Chapter, RenderFormat, RunResult } from '@demoflow/core'; +import { runFfmpeg } from '@demoflow/renderer'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { posterPath } from '../../src/runner/share/files.ts'; +import { + makePoster, + POSTER_MAX_BYTES, + type PosterRequest, + posterArgs, + posterAtMs, +} from '../../src/runner/share/poster.ts'; +import { + DESCRIPTION_MAX_LENGTH, + SharePreparer, +} from '../../src/runner/share/prepare.ts'; +import { appendReportedRun } from '../../src/runs-report/reported-runs.ts'; +import { memoryLogger } from './fakes.ts'; + +const RUN_ID = 'srv-run-1'; +const SCENARIO = 'demoflow/a.demo.json'; + +let base: string; +let root: string; +let runDir: string; +let indexFile: string; +let logger: ReturnType; +let posters: PosterRequest[]; +let posterSize: number | Error; + +function writeResult( + renders: Array<{ + format: RenderFormat; + file: string; + chapters?: Chapter[]; + durationMs?: number; + }>, + scenarioId = SCENARIO, +): void { + const done = { status: 'passed' } as const; + const result: RunResult = { + schemaVersion: 1, + runId: 'local-run', + scenarioId, + scenarioName: 'A', + startedAt: '2026-10-22T10:00:00.000Z', + finishedAt: '2026-10-22T10:00:01.000Z', + status: 'completed', + stages: { + readiness: done, + execution: done, + verification: done, + recording: done, + rendering: done, + storage: { status: 'skipped' }, + }, + renders: renders.map((render) => ({ + renderer: 'ffmpeg', + durationMs: 4000, + sizeBytes: 1, + width: 1280, + height: 720, + fps: 30, + ...render, + })), + warnings: [], + }; + writeFileSync(path.join(runDir, 'result.json'), JSON.stringify(result)); +} + +function writeScenario(description?: string, file = SCENARIO): void { + const target = path.join(root, file); + mkdirSync(path.dirname(target), { recursive: true }); + writeFileSync( + target, + JSON.stringify({ + schemaVersion: 1, + name: 'A', + ...(description === undefined ? {} : { description }), + steps: [{ action: 'navigate', path: '/' }], + }), + ); +} + +function preparer(): SharePreparer { + return new SharePreparer({ + indexFile, + logger, + platform: process.platform, + makePoster: async (request) => { + posters.push(request); + if (posterSize instanceof Error) throw posterSize; + return posterSize; + }, + }); +} + +/** Sends one `share.prepare` and waits for its answer. */ +async function prepare( + message: Record = {}, + share = preparer(), +): Promise> { + return new Promise((resolve) => { + share.handle( + { + type: 'share.prepare', + requestId: '2f1f6d0e-7a53-4c1b-9d57-0c1f6f1d2a11', + runId: RUN_ID, + format: 'mp4', + ...message, + }, + { send: resolve }, + ); + }); +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(tmpdir(), 'demoflow-share-'))); + root = path.join(base, 'project'); + runDir = path.join(base, 'home', 'runs', 'local-run'); + mkdirSync(root, { recursive: true }); + mkdirSync(path.join(runDir, 'renders'), { recursive: true }); + indexFile = path.join(base, 'runner', 'reported-runs.jsonl'); + appendReportedRun(indexFile, { + id: RUN_ID, + runDir, + at: '2026-10-22T10:00:01.000Z', + root, + }); + writeFileSync(path.join(runDir, 'renders', 'demo.mp4'), 'mp4 bytes'); + logger = memoryLogger(); + posters = []; + posterSize = 1234; +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe('SharePreparer (spec 349, Decision 2)', () => { + it('answers with the description, the chapters and the poster size, and no path', async () => { + const chapters = [ + { title: 'Customers', atMs: 0 }, + { title: 'Invoices', atMs: 4200 }, + ]; + writeResult([{ format: 'mp4', file: 'renders/demo.mp4', chapters }]); + writeScenario('Create a customer, then bill them.'); + const answer = await prepare(); + expect(answer).toEqual({ + type: 'share.prepared', + requestId: '2f1f6d0e-7a53-4c1b-9d57-0c1f6f1d2a11', + description: 'Create a customer, then bill them.', + chapters, + posterSize: 1234, + }); + expect(posters).toEqual([ + { + render: path.join(runDir, 'renders', 'demo.mp4'), + poster: posterPath(runDir, 'mp4', process.platform), + durationMs: 4000, + platform: process.platform, + }, + ]); + expect(logger.text()).toContain(`share ${RUN_ID} mp4: prepared`); + expect(logger.text()).not.toContain(base); + }); + + it('answers chapters [] and no description for an old render and a gone scenario', async () => { + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + const answer = await prepare(); + expect(answer).toEqual({ + type: 'share.prepared', + requestId: '2f1f6d0e-7a53-4c1b-9d57-0c1f6f1d2a11', + chapters: [], + posterSize: 1234, + }); + }); + + it('cuts a long description to the API limit', async () => { + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + writeScenario('x'.repeat(DESCRIPTION_MAX_LENGTH + 50)); + const answer = await prepare(); + expect(answer.description).toBe('x'.repeat(DESCRIPTION_MAX_LENGTH)); + }); + + it('reads no description for a run without a project root', async () => { + rmSync(indexFile); + appendReportedRun(indexFile, { id: RUN_ID, runDir, at: '' }); + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + writeScenario('Hidden.'); + expect((await prepare()).description).toBeUndefined(); + }); + + it('reads no description from outside the project', async () => { + writeFileSync( + path.join(base, 'outside.json'), + JSON.stringify({ + schemaVersion: 1, + name: 'O', + description: 'Outside.', + steps: [{ action: 'navigate', path: '/' }], + }), + ); + writeResult( + [{ format: 'mp4', file: 'renders/demo.mp4' }], + '../outside.json', + ); + expect((await prepare()).description).toBeUndefined(); + }); + + it('answers not-found for an unreported run or an unreadable result', async () => { + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + expect(await prepare({ runId: 'srv-other' })).toEqual({ + type: 'share.error', + requestId: '2f1f6d0e-7a53-4c1b-9d57-0c1f6f1d2a11', + code: 'not-found', + }); + writeFileSync(path.join(runDir, 'result.json'), '{ not json'); + expect((await prepare()).code).toBe('not-found'); + writeFileSync(path.join(runDir, 'result.json'), '{}'); + expect((await prepare()).code).toBe('not-found'); + expect(posters).toEqual([]); + }); + + it('answers no-render for an unrendered format, a missing file or one outside the run', async () => { + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + expect((await prepare({ format: 'gif' })).code).toBe('no-render'); + + writeResult([{ format: 'mp4', file: 'renders/gone.mp4' }]); + expect((await prepare()).code).toBe('no-render'); + + writeFileSync(path.join(base, 'secret.mp4'), 'secret'); + writeResult([{ format: 'mp4', file: '../../../secret.mp4' }]); + expect((await prepare()).code).toBe('no-render'); + + if (process.platform !== 'win32') { + symlinkSync( + path.join(base, 'secret.mp4'), + path.join(runDir, 'renders', 'link.mp4'), + ); + writeResult([{ format: 'mp4', file: 'renders/link.mp4' }]); + expect((await prepare()).code).toBe('no-render'); + } + expect(posters).toEqual([]); + expect(logger.text()).toContain(`share ${RUN_ID} gif: no-render`); + }); + + it('answers io when the poster cannot be made', async () => { + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + posterSize = new Error('ffmpeg exited with 1'); + expect((await prepare()).code).toBe('io'); + expect(logger.text()).toContain(`share ${RUN_ID} mp4: io`); + expect(logger.text()).not.toContain('ffmpeg exited'); + }); + + it('ignores a malformed share.prepare', () => { + const share = preparer(); + const sent: unknown[] = []; + for (const message of [ + { requestId: 'not-a-uuid', runId: RUN_ID, format: 'mp4' }, + { requestId: randomUUID(), runId: '../x', format: 'mp4' }, + { requestId: randomUUID(), runId: RUN_ID, format: 'avi' }, + { requestId: randomUUID(), format: 'mp4' }, + ]) { + share.handle( + { type: 'share.prepare', ...message }, + { send: (m) => sent.push(m) }, + ); + } + expect(sent).toEqual([]); + expect(logger.text()).toMatch(/ignored a malformed share.prepare/); + }); + + it('makes one poster for two shares of the same render at once', async () => { + writeResult([{ format: 'mp4', file: 'renders/demo.mp4' }]); + let release = () => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + const share = new SharePreparer({ + indexFile, + logger, + platform: process.platform, + makePoster: async (request) => { + posters.push(request); + await gate; + return 1234; + }, + }); + setTimeout(release, 200); + const answers = await Promise.all([ + prepare({}, share), + prepare({ requestId: randomUUID() }, share), + ]); + expect(answers.map((answer) => answer.type)).toEqual([ + 'share.prepared', + 'share.prepared', + ]); + expect(posters).toHaveLength(1); + }); +}); + +/** The width of a baseline or progressive JPEG, from its SOF marker. */ +function jpegWidth(bytes: Buffer): number { + expect(bytes.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8])); + let at = 2; + while (at < bytes.length) { + const marker = bytes[at + 1] ?? 0; + const length = bytes.readUInt16BE(at + 2); + if (marker === 0xc0 || marker === 0xc2) return bytes.readUInt16BE(at + 7); + at += 2 + length; + } + throw new Error('no SOF marker'); +} + +describe('the poster (spec 349, Decision 3)', () => { + it('is taken at min(1500, durationMs / 2), after -i, at most 1280 wide', () => { + expect(posterAtMs(10_000)).toBe(1500); + expect(posterAtMs(1001)).toBe(500); + expect(posterAtMs(0)).toBe(0); + const args = posterArgs('in.gif', 'out.jpg', 500); + expect(args.indexOf('-ss')).toBeGreaterThan(args.indexOf('-i')); + expect(args).toContain('0.500'); + expect(args).toContain("scale='min(1280,iw)':-2"); + expect(args.slice(-3)).toEqual(['-q:v', '4', 'out.jpg']); + }); + + it.each([ + ['mp4', ['-c:v', 'libx264', '-pix_fmt', 'yuv420p']], + ['gif', []], + ] as const)( + 'makes a JPEG at most 1280 px wide from a %s render', + async (format, codec) => { + const render = path.join(runDir, 'renders', `demo.${format}`); + await runFfmpeg([ + '-y', + '-f', + 'lavfi', + '-i', + 'testsrc=size=1920x1080:rate=10:duration=1', + ...codec, + render, + ]); + const poster = posterPath(runDir, format, process.platform); + const size = await makePoster({ + render, + poster, + durationMs: 1000, + platform: process.platform, + }); + const bytes = readFileSync(poster); + expect(size).toBe(bytes.length); + expect(size).toBeLessThanOrEqual(POSTER_MAX_BYTES); + expect(jpegWidth(bytes)).toBe(1280); + }, + 60_000, + ); + + it('reuses a poster newer than its render, and remakes an older one', async () => { + const render = path.join(runDir, 'renders', 'demo.mp4'); + const poster = posterPath(runDir, 'mp4', process.platform); + const request = { + render, + poster, + durationMs: 4000, + platform: process.platform, + }; + const runs: string[][] = []; + const ffmpeg = async (args: readonly string[]) => { + runs.push([...args]); + writeFileSync(args.at(-1) ?? '', 'jpeg'); + }; + expect(await makePoster(request, ffmpeg)).toBe(4); + expect(runs).toHaveLength(1); + // Written to a temporary file, then renamed. + expect(runs[0]?.at(-1)).toBe(poster.replace(/\.jpg$/, '.tmp.jpg')); + + const later = new Date(statSync(render).mtimeMs + 10_000); + utimesSync(poster, later, later); + expect(await makePoster(request, ffmpeg)).toBe(4); + expect(runs).toHaveLength(1); + + const newer = new Date(later.getTime() + 10_000); + utimesSync(render, newer, newer); + await makePoster(request, ffmpeg); + expect(runs).toHaveLength(2); + }); + + it('rejects a poster over 1 MiB and leaves no temporary file when FFmpeg fails', async () => { + const render = path.join(runDir, 'renders', 'demo.mp4'); + const poster = posterPath(runDir, 'mp4', process.platform); + const request = { + render, + poster, + durationMs: 4000, + platform: process.platform, + }; + await expect( + makePoster(request, async (args) => { + writeFileSync(args.at(-1) ?? '', Buffer.alloc(POSTER_MAX_BYTES + 1)); + }), + ).rejects.toThrow(/bytes/); + + rmSync(poster); + await expect( + makePoster(request, async (args) => { + writeFileSync(args.at(-1) ?? '', 'half'); + throw new Error('ffmpeg exited with 1'); + }), + ).rejects.toThrow(/exited/); + expect(() => statSync(poster.replace(/\.jpg$/, '.tmp.jpg'))).toThrow(); + expect(() => statSync(poster)).toThrow(); + }); +}); From 3d1b6b50ba4bc58474c6ac78b6efbc42d137739b Mon Sep 17 00:00:00 2001 From: Archi Date: Mon, 26 Oct 2026 19:51:05 +0100 Subject: [PATCH 4/8] feat(cli): demoflow share creates a share link for a reported run The command resolves the run like demoflow render, finds its server id in the reported-runs index, posts /runner/shares with the device token and polls the share every second for up to ten minutes. Server refusals become exit-2 CommandErrors with their codes; an existing share is kept and printed; a failed upload exits 1. --password is asked for without echo on a terminal, else read from DEMOFLOW_SHARE_PASSWORD, and never taken as a flag value. --- apps/cli/src/auth/client.ts | 10 +- apps/cli/src/commands/errors.ts | 13 +- apps/cli/src/commands/render.ts | 45 ++- apps/cli/src/commands/share.ts | 238 ++++++++++++ apps/cli/src/main.ts | 36 ++ apps/cli/src/share/publish.ts | 321 ++++++++++++++++ apps/cli/test/commands/share.spec.ts | 526 +++++++++++++++++++++++++++ 7 files changed, 1169 insertions(+), 20 deletions(-) create mode 100644 apps/cli/src/commands/share.ts create mode 100644 apps/cli/src/share/publish.ts create mode 100644 apps/cli/test/commands/share.spec.ts diff --git a/apps/cli/src/auth/client.ts b/apps/cli/src/auth/client.ts index b1908e0d..53c71982 100644 --- a/apps/cli/src/auth/client.ts +++ b/apps/cli/src/auth/client.ts @@ -133,7 +133,8 @@ export async function revokeSelf( throw unexpected(response.status); } -async function send( +/** One request to the API, with the device token when given. */ +export async function send( fetchFn: Fetch, server: string, path: string, @@ -158,7 +159,10 @@ async function send( } } -async function readJson(response: Response): Promise> { +/** The JSON object a response carries, or a `ServerError`. */ +export async function readJson( + response: Response, +): Promise> { try { const body: unknown = await response.json(); if (typeof body === 'object' && body !== null && !Array.isArray(body)) { @@ -186,6 +190,6 @@ function numberField(body: Record, name: string): number { return value; } -function unexpected(status: number): ServerError { +export function unexpected(status: number): ServerError { return new ServerError(`the server answered ${status}`, false); } diff --git a/apps/cli/src/commands/errors.ts b/apps/cli/src/commands/errors.ts index af16e249..ab5fd021 100644 --- a/apps/cli/src/commands/errors.ts +++ b/apps/cli/src/commands/errors.ts @@ -16,7 +16,18 @@ export type CommandErrorCode = | 'app-already-running' | 'fresh-app-needs-dev-command' | 'missing-scenario' - | 'check-flag'; + | 'check-flag' + | 'invalid-expires' + | 'invalid-password' + // `demoflow share` (spec 349, Decision 6): the server's refusals. + | 'not-logged-in' + | 'run-not-reported' + | 'format-not-rendered' + | 'artifacts-deleted' + | 'runner-offline' + | 'runner-outdated' + | 'file-too-large' + | 'quota-exceeded'; /** Bad input to a command (spec 5: exit 2) that is not a config problem. */ export class CommandError extends Error { diff --git a/apps/cli/src/commands/render.ts b/apps/cli/src/commands/render.ts index 9856f107..81a931a3 100644 --- a/apps/cli/src/commands/render.ts +++ b/apps/cli/src/commands/render.ts @@ -78,22 +78,7 @@ export async function renderCommand( io: Io, deps: RenderDeps = defaultRenderDeps(), ): Promise { - const { host } = deps; - assertSafeRunId(runId); - const root = - flags.project === undefined - ? projectRootAbove(deps.cwd) - : projectRootAt(path.resolve(deps.cwd, flags.project)); - const config = loadProjectConfig(root); - const { home } = resolveHome({ - ...host, - out: flags.out, - cwd: deps.cwd, - projectRoot: root, - projectConfig: config, - globalConfig: loadGlobalConfig(host), - }); - const runDir = runDirFor(home, runId, host.platform); + const { root, config, runDir } = locateRun(runId, flags, deps); const result = await readRenderable(runDir); io.stderr('Rendering\n'); @@ -128,6 +113,34 @@ export async function renderCommand( return code === 0 && renderError !== undefined ? EXIT_STAGE_FAILED : code; } +/** + * Where `` lives (spec 255, Decisions 1–2): under the home of the + * project above the cwd, or of `--project`. Throws for an unsafe id or a + * missing project; the run directory itself may not exist. + */ +export function locateRun( + runId: string, + flags: { out?: string; project?: string }, + deps: { host: HostEnvironment; cwd: string }, +): { root: string; config: ProjectConfig; runDir: string } { + const { host } = deps; + assertSafeRunId(runId); + const root = + flags.project === undefined + ? projectRootAbove(deps.cwd) + : projectRootAt(path.resolve(deps.cwd, flags.project)); + const config = loadProjectConfig(root); + const { home } = resolveHome({ + ...host, + out: flags.out, + cwd: deps.cwd, + projectRoot: root, + projectConfig: config, + globalConfig: loadGlobalConfig(host), + }); + return { root, config, runDir: runDirFor(home, runId, host.platform) }; +} + /** * The run's `result.json`, if the run can be rendered: the directory exists, * the result is valid, the capture stages are finished and the source video diff --git a/apps/cli/src/commands/share.ts b/apps/cli/src/commands/share.ts new file mode 100644 index 00000000..65878d5e --- /dev/null +++ b/apps/cli/src/commands/share.ts @@ -0,0 +1,238 @@ +import { existsSync } from 'node:fs'; +import { createInterface } from 'node:readline/promises'; +import { Writable } from 'node:stream'; +import { setTimeout as delay } from 'node:timers/promises'; +import type { RenderFormat } from '@demoflow/core'; +import { ServerError } from '../auth/client.ts'; +import { readCredentials } from '../auth/credentials.ts'; +import { currentHost, type HostEnvironment } from '../config/index.ts'; +import { runnerPaths } from '../runner/paths.ts'; +import { + createShare, + DEFAULT_SHARE_LIFETIME, + PASSWORD_MAX_LENGTH, + PASSWORD_MIN_LENGTH, + reportedRunOf, + SHARE_LIFETIMES, + type Share, + type ShareLifetime, + ShareRefused, + shareableFormat, + type WaitDeps, + waitForShare, +} from '../share/publish.ts'; +import { CommandError, EXIT_STAGE_FAILED } from './errors.ts'; +import type { Io } from './io.ts'; +import { locateRun } from './render.ts'; + +/** Decision 6: the upload is polled for up to 10 minutes. */ +export const SHARE_WAIT_MS = 10 * 60_000; +/** How often a long upload says it is still going. */ +const PROGRESS_EVERY_MS = 15_000; +/** Decision 6: where `--password` reads the password without a terminal. */ +export const PASSWORD_ENV = 'DEMOFLOW_SHARE_PASSWORD'; + +export interface ShareFlags { + format?: RenderFormat; + /** `--expires`: 7, 30 or 90 days. */ + expires?: string; + /** `--password`: asked for, never a flag value (shell history). */ + password?: boolean; + json?: boolean; + out?: string; + /** Hidden: the project root, instead of searching up from the cwd. */ + project?: string; +} + +export interface ShareCommandDeps extends WaitDeps { + host: HostEnvironment; + cwd: string; + /** The password typed without echo, or `null` without a terminal. */ + askPassword(): Promise; +} + +export const defaultShareDeps = (): ShareCommandDeps => ({ + host: currentHost(), + cwd: process.cwd(), + fetch: (input, init) => fetch(input, init), + sleep: (ms) => delay(ms), + now: () => Date.now(), + askPassword: askPasswordOnTerminal, +}); + +/** + * `demoflow share ` (spec 349, Decision 6): a share link for a render + * of a run this machine reported. The runner uploads the file; this command + * asks the server for the share and waits until it is ready. Refusals are + * `CommandError`s (exit 2); an upload that fails exits 1. + */ +export async function shareCommand( + runId: string, + flags: ShareFlags, + io: Io, + deps: ShareCommandDeps = defaultShareDeps(), +): Promise { + const expiresInDays = parseLifetime(flags.expires); + const credentials = readCredentials(deps.host); + if (credentials === null) { + throw new CommandError( + 'not-logged-in', + 'this machine is not logged in: run demoflow login', + ); + } + const { runDir } = locateRun(runId, flags, deps); + if (!existsSync(runDir)) { + throw new CommandError('run-not-found', `no run directory at ${runDir}`); + } + + try { + const format = await shareableFormat(runDir, flags.format); + const reported = await reportedRunOf( + runnerPaths(deps.host).reportedRuns, + runDir, + credentials.server, + ); + const password = + flags.password === true ? await readPassword(deps) : undefined; + + io.stderr(`Sharing the ${format} render of ${runId}\n`); + const { share, existing } = await createShare( + credentials, + { + runId: reported.id, + format, + expiresInDays, + ...(password === undefined ? {} : { password }), + }, + deps.fetch, + ); + if (existing) { + io.stderr( + `This render is already shared ${share.view.hasPassword === true ? 'with' : 'without'} a password; that link is kept (revoke it on the website to share it again)\n`, + ); + } else if (share.status === 'uploading') { + io.stderr('The runner is uploading the render\n'); + } + + let reportedAt = 0; + const settled = await waitForShare(credentials, share, deps, { + timeoutMs: SHARE_WAIT_MS, + onPoll: (current, elapsedMs) => { + if (current.status !== 'uploading') return; + if (elapsedMs - reportedAt < PROGRESS_EVERY_MS) return; + reportedAt = elapsedMs; + io.stderr(`Still uploading (${Math.round(elapsedMs / 1000)} s)\n`); + }, + }); + return printShare(settled, flags, io); + } catch (error) { + if (error instanceof ShareRefused) { + throw new CommandError(error.code, error.message); + } + if (error instanceof ServerError) { + io.stderr(`${error.message}\n`); + return EXIT_STAGE_FAILED; + } + throw error; + } +} + +/** The link on stdout, and the file link when there is no password. */ +function printShare(share: Share, flags: ShareFlags, io: Io): number { + if (flags.json === true) { + io.stdout(`${JSON.stringify(share.view, null, 2)}\n`); + } + switch (share.status) { + case 'ready': + if (flags.json !== true) { + io.stdout(`${share.url}\n`); + if (share.fileUrl !== null) io.stdout(`${share.fileUrl}\n`); + } + io.stderr( + `Ready; the link works until ${share.expiresAt.slice(0, 10)}\n`, + ); + return 0; + case 'uploading': + io.stderr( + `The upload is still going after ${SHARE_WAIT_MS / 60_000} minutes; the link works once it is done: ${share.url}\n`, + ); + return 1; + case 'failed': + case 'lost': + io.stderr(`The upload failed: ${share.failure ?? share.status}\n`); + return 1; + } +} + +function parseLifetime(value: string | undefined): ShareLifetime { + if (value === undefined) return DEFAULT_SHARE_LIFETIME; + const days = SHARE_LIFETIMES.find((known) => String(known) === value); + if (days === undefined) { + throw new CommandError( + 'invalid-expires', + `--expires must be ${SHARE_LIFETIMES.join(', ')} days, not ${JSON.stringify(value)}`, + ); + } + return days; +} + +/** Decision 6: typed on a terminal, else `DEMOFLOW_SHARE_PASSWORD`. */ +async function readPassword(deps: ShareCommandDeps): Promise { + const typed = await deps.askPassword(); + const password = typed ?? deps.host.env[PASSWORD_ENV]; + if (password === undefined || password === '') { + throw new CommandError( + 'invalid-password', + typed === null + ? `--password without a terminal reads ${PASSWORD_ENV}, which is not set` + : 'the password is empty', + ); + } + if ( + password.length < PASSWORD_MIN_LENGTH || + password.length > PASSWORD_MAX_LENGTH + ) { + throw new CommandError( + 'invalid-password', + `the password must be ${PASSWORD_MIN_LENGTH}–${PASSWORD_MAX_LENGTH} characters`, + ); + } + return password; +} + +/** Typed twice without echo; no terminal, no question. */ +async function askPasswordOnTerminal(): Promise { + if (process.stdin.isTTY !== true || process.stderr.isTTY !== true) { + return null; + } + let muted = false; + // The prompt itself is shown; what is typed after it is not. + const output = new Writable({ + write(chunk, _encoding, done) { + if (!muted) process.stderr.write(chunk); + done(); + }, + }); + const prompt = createInterface({ + input: process.stdin, + output, + terminal: true, + }); + const ask = async (question: string): Promise => { + muted = false; + const answer = prompt.question(question); + muted = true; + const typed = await answer; + process.stderr.write('\n'); + return typed; + }; + try { + const password = await ask('Password for the share: '); + if ((await ask('Again: ')) !== password) { + throw new CommandError('invalid-password', 'the passwords differ'); + } + return password; + } finally { + prompt.close(); + } +} diff --git a/apps/cli/src/main.ts b/apps/cli/src/main.ts index af8d845a..73d57583 100644 --- a/apps/cli/src/main.ts +++ b/apps/cli/src/main.ts @@ -27,6 +27,11 @@ import { type RenderFlags, renderCommand } from './commands/render.ts'; import { runCommand } from './commands/run.ts'; import { registerRunsCommands } from './commands/runs.ts'; import { setupCommand } from './commands/setup.ts'; +import { + PASSWORD_ENV, + type ShareFlags, + shareCommand, +} from './commands/share.ts'; import { validateCommand } from './commands/validate.ts'; import { mcpCommand } from './mcp/command.ts'; import { @@ -156,6 +161,32 @@ export async function main( exitCode = await renderCommand(runId, flags, io); }); + program + .command('share') + .description('Share a render of a reported run as a link on the website') + .argument('', 'the run directory under /runs/') + .addOption( + new Option( + '--format ', + `the render to share (default: the run's first; ${RENDER_FORMATS.join(', ')})`, + ).argParser(parseFormat), + ) + .option( + '--expires ', + 'how long the link works: 7, 30 or 90 days', + '30', + ) + .option( + '--password', + `protect the link with a password, asked for on the terminal (else ${PASSWORD_ENV})`, + ) + .option('--json', 'print the share as one JSON object on stdout') + .option('--out ', 'artifacts directory (the home of runs/)') + .addOption(new Option('--project ', 'the project root').hideHelp()) + .action(async (runId: string, flags: ShareFlags) => { + exitCode = await shareCommand(runId, flags, io); + }); + program .command('list') .description('List recent runs of the current project, newest first') @@ -288,6 +319,11 @@ function collectFormat( return [...previous, format]; } +/** `--format` of `share`: one known format. */ +function parseFormat(value: string): RenderFormat { + return collectFormat(value)[0] as RenderFormat; +} + function collectExclude(value: string, previous: string[] = []): string[] { return [...previous, value]; } diff --git a/apps/cli/src/share/publish.ts b/apps/cli/src/share/publish.ts new file mode 100644 index 00000000..9a2355c0 --- /dev/null +++ b/apps/cli/src/share/publish.ts @@ -0,0 +1,321 @@ +import path from 'node:path'; +import type { RenderFormat } from '@demoflow/core'; +import { + type Fetch, + readJson, + ServerError, + send, + unexpected, +} from '../auth/client.ts'; +import type { Credentials } from '../auth/credentials.ts'; +import { readResult } from '../commands/settle.ts'; +import { + type ReportedRun, + readReportedRunsByDir, +} from '../runs-report/reported-runs.ts'; + +/** #348: the lifetimes a share can be created with, in days. */ +export const SHARE_LIFETIMES = [7, 30, 90] as const; +export type ShareLifetime = (typeof SHARE_LIFETIMES)[number]; +export const DEFAULT_SHARE_LIFETIME: ShareLifetime = 30; +/** #348: the API's bounds on a share password. */ +export const PASSWORD_MIN_LENGTH = 8; +export const PASSWORD_MAX_LENGTH = 128; +/** Decision 6: `GET /runner/shares/:id` once a second while it uploads. */ +export const SHARE_POLL_MS = 1_000; + +export type ShareStatus = 'uploading' | 'ready' | 'failed' | 'lost'; +const SHARE_STATUSES: readonly string[] = [ + 'uploading', + 'ready', + 'failed', + 'lost', +]; + +/** What the CLI reads of a `ShareView`. */ +export interface Share { + id: string; + url: string; + /** `null` when the share has a password. */ + fileUrl: string | null; + status: ShareStatus; + failure: string | null; + expiresAt: string; + /** The whole `ShareView`, as the server sent it (`--json`). */ + view: Record; +} + +/** Why a share cannot be made; the command and the MCP tool name it so. */ +export type ShareRefusalCode = + | 'not-logged-in' + | 'invalid-result' + | 'run-not-reported' + | 'format-not-rendered' + | 'artifacts-deleted' + | 'runner-offline' + | 'runner-outdated' + | 'file-too-large' + | 'quota-exceeded'; + +export class ShareRefused extends Error { + readonly code: ShareRefusalCode; + + constructor(code: ShareRefusalCode, message: string) { + super(message); + this.name = 'ShareRefused'; + this.code = code; + } +} + +export interface ShareRequest { + /** The server's run id, from the reported-runs index. */ + runId: string; + format: RenderFormat; + expiresInDays: ShareLifetime; + password?: string; +} + +/** + * The format to share: the one asked for, which the run must have rendered, + * or the run's first render. The daemon reads the same `result.json`. + */ +export async function shareableFormat( + runDir: string, + format: RenderFormat | undefined, +): Promise { + let formats: RenderFormat[]; + try { + formats = (await readResult(runDir)).renders.map((render) => render.format); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new ShareRefused( + 'invalid-result', + `cannot read the run's result.json: ${reason}`, + ); + } + const chosen = format ?? formats[0]; + if (chosen === undefined) { + throw new ShareRefused( + 'format-not-rendered', + 'the run has no render: make one with demoflow render ', + ); + } + if (!formats.includes(chosen)) { + throw new ShareRefused( + 'format-not-rendered', + `the run has no ${chosen} render (it has ${formats.join(', ')})`, + ); + } + return chosen; +} + +/** The run's line in the reported-runs index, if it went to `server`. */ +export async function reportedRunOf( + indexFile: string, + runDir: string, + server: string, +): Promise { + const entry = (await readReportedRunsByDir(indexFile)).get( + path.resolve(runDir), + ); + if (entry === undefined) { + throw new ShareRefused( + 'run-not-reported', + 'the run was never reported to the server: it was made signed out or with reporting off', + ); + } + if (entry.server !== undefined && entry.server !== server) { + throw new ShareRefused( + 'run-not-reported', + `the run was reported to ${entry.server}, not to ${server}`, + ); + } + return entry; +} + +/** + * `POST /runner/shares`. A live share of the same run and format is not an + * error: it is fetched and returned with `existing: true` (Decision 6). + */ +export async function createShare( + credentials: Credentials, + request: ShareRequest, + fetchFn: Fetch, +): Promise<{ share: Share; existing: boolean }> { + // A second try only for a `share-exists` that raced its own insert. + for (let attempt = 0; attempt < 2; attempt++) { + const response = await send(fetchFn, credentials.server, '/runner/shares', { + method: 'POST', + token: credentials.token, + body: { + runId: request.runId, + format: request.format, + expiresInDays: request.expiresInDays, + ...(request.password === undefined + ? {} + : { password: request.password }), + }, + }); + if (response.status === 202) { + return { share: toShare(await readJson(response)), existing: false }; + } + const body = await errorBody(response); + if (response.status === 409 && body.error === 'share-exists') { + if (typeof body.shareId !== 'string') continue; + return { + share: await fetchShare(credentials, body.shareId, fetchFn), + existing: true, + }; + } + throw refusal(response.status, body, request.format); + } + throw new ServerError('the server keeps answering share-exists', false); +} + +/** `GET /runner/shares/:id`. */ +export async function fetchShare( + credentials: Credentials, + id: string, + fetchFn: Fetch, +): Promise { + const response = await send( + fetchFn, + credentials.server, + `/runner/shares/${encodeURIComponent(id)}`, + { method: 'GET', token: credentials.token }, + ); + if (response.status === 200) return toShare(await readJson(response)); + if (response.status === 401) { + throw refusal(401, await errorBody(response), undefined); + } + throw unexpected(response.status); +} + +export interface WaitDeps { + fetch: Fetch; + sleep(ms: number): Promise; + now(): number; +} + +/** + * Polls a share until it leaves `uploading` or `timeoutMs` passes, and + * returns what it last read: still `uploading` on a timeout. + */ +export async function waitForShare( + credentials: Credentials, + share: Share, + deps: WaitDeps, + options: { + timeoutMs: number; + onPoll?(share: Share, elapsedMs: number): void; + }, +): Promise { + const started = deps.now(); + let current = share; + while (current.status === 'uploading') { + const elapsed = deps.now() - started; + if (elapsed + SHARE_POLL_MS > options.timeoutMs) break; + await deps.sleep(SHARE_POLL_MS); + current = await fetchShare(credentials, current.id, deps.fetch); + options.onPoll?.(current, deps.now() - started); + } + return current; +} + +/** `1.5 MB`: what a refusal names a size with. */ +export function formatSize(bytes: number): string { + if (bytes < 1000 * 1000) return `${Math.round(bytes / 1000)} kB`; + if (bytes < 1000 * 1000 * 1000) { + return `${(bytes / (1000 * 1000)).toFixed(1)} MB`; + } + return `${(bytes / (1000 * 1000 * 1000)).toFixed(2)} GB`; +} + +function refusal( + status: number, + body: Record, + format: RenderFormat | undefined, +): Error { + if (status === 401) { + return new ShareRefused( + 'not-logged-in', + 'the stored token was revoked: run demoflow login', + ); + } + if (status === 404) { + return new ShareRefused( + 'run-not-reported', + 'the server does not know this run on this machine: it was made signed out, with reporting off, or before the last login', + ); + } + switch (body.error) { + case 'format-not-rendered': + return new ShareRefused( + 'format-not-rendered', + `the server has no ${format ?? 'such'} render of this run: render it again with demoflow render while logged in`, + ); + case 'artifacts-deleted': + return new ShareRefused( + 'artifacts-deleted', + "the run's files were deleted on the website", + ); + case 'runner-offline': + return new ShareRefused( + 'runner-offline', + 'the runner is offline: start the runner: demoflow runner start', + ); + case 'runner-outdated': + return new ShareRefused( + 'runner-outdated', + 'the running runner cannot upload shares: restart the runner (demoflow runner stop, then demoflow runner start)', + ); + case 'file-too-large': + return new ShareRefused( + 'file-too-large', + typeof body.maxFileBytes === 'number' + ? `the render is over the ${formatSize(body.maxFileBytes)} a share can hold` + : 'the render is over the size a share can hold', + ); + case 'quota-exceeded': + return new ShareRefused( + 'quota-exceeded', + typeof body.usedBytes === 'number' && + typeof body.limitBytes === 'number' + ? `the share quota is full: ${formatSize(body.usedBytes)} of ${formatSize(body.limitBytes)} used; revoke a share on the website` + : 'the share quota is full; revoke a share on the website', + ); + } + return unexpected(status); +} + +/** An error body, or `{}` when it is not JSON: the status then decides. */ +async function errorBody(response: Response): Promise> { + try { + return await readJson(response); + } catch { + return {}; + } +} + +function toShare(body: Record): Share { + const { id, url, fileUrl, status, failure, expiresAt } = body; + if ( + typeof id !== 'string' || + typeof url !== 'string' || + !(typeof fileUrl === 'string' || fileUrl === null) || + typeof status !== 'string' || + !SHARE_STATUSES.includes(status) || + typeof expiresAt !== 'string' + ) { + throw new ServerError('the server sent a share it cannot read', false); + } + return { + id, + url, + fileUrl, + status: status as ShareStatus, + failure: typeof failure === 'string' ? failure : null, + expiresAt, + view: body, + }; +} diff --git a/apps/cli/test/commands/share.spec.ts b/apps/cli/test/commands/share.spec.ts new file mode 100644 index 00000000..aa1bc264 --- /dev/null +++ b/apps/cli/test/commands/share.spec.ts @@ -0,0 +1,526 @@ +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import type { RunResult } from '@demoflow/core'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { Fetch } from '../../src/auth/client.ts'; +import { + credentialsPath, + writeCredentials, +} from '../../src/auth/credentials.ts'; +import { CommandError } from '../../src/commands/errors.ts'; +import type { Io } from '../../src/commands/io.ts'; +import { + type ShareCommandDeps, + type ShareFlags, + shareCommand, +} from '../../src/commands/share.ts'; +import { + type HostEnvironment, + PROJECT_CONFIG_FILE, +} from '../../src/config/index.ts'; +import { main } from '../../src/main.ts'; +import { runnerPaths } from '../../src/runner/paths.ts'; +import { appendReportedRun } from '../../src/runs-report/reported-runs.ts'; + +const RUN_ID = '20261026-101500-abcdef'; +const SERVER = 'https://demoflow.example'; +const TOKEN = 'device-token-123'; +const SERVER_RUN_ID = '0d6f4a52-5d0e-4c55-9a7f-3f6f3d5c1a01'; +const SHARE_ID = 'share-1'; + +let dir: string; +let project: string; +let runDir: string; +let host: HostEnvironment; + +beforeEach(async () => { + dir = await realpath(await mkdtemp(path.join(tmpdir(), 'demoflow-share-'))); + project = path.join(dir, 'project'); + runDir = path.join(project, 'artifacts', 'runs', RUN_ID); + host = { + platform: process.platform, + env: { XDG_CONFIG_HOME: dir, APPDATA: dir }, + homedir: dir, + }; + await mkdir(runDir, { recursive: true }); + await writeFile( + path.join(project, PROJECT_CONFIG_FILE), + JSON.stringify({ + baseUrl: 'http://localhost:3680', + artifactsDir: 'artifacts', + }), + ); + await writeResult(['mp4', 'gif']); + writeCredentials(host, { server: SERVER, token: TOKEN, runnerId: 'r-1' }); + appendReportedRun(runnerPaths(host).reportedRuns, { + id: SERVER_RUN_ID, + runDir, + at: '2026-10-26T10:15:05.000Z', + projectId: 'p-1', + server: SERVER, + root: project, + }); +}); + +afterEach(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +async function writeResult(formats: ('mp4' | 'gif' | 'webm')[]) { + const stage = { status: 'passed' }; + const result = { + schemaVersion: 1, + runId: RUN_ID, + scenarioId: 'demoflow/login.demo.json', + scenarioName: 'Sign in', + startedAt: '2026-10-26T10:15:00.000Z', + finishedAt: '2026-10-26T10:15:05.000Z', + status: 'completed', + stages: { + readiness: stage, + execution: stage, + verification: stage, + recording: stage, + rendering: stage, + storage: { status: 'skipped' }, + }, + renders: formats.map((format) => ({ + renderer: 'ffmpeg', + format, + file: `render/ffmpeg.${format}`, + durationMs: 4000, + sizeBytes: 1000, + width: 1280, + height: 720, + fps: 30, + })), + warnings: [], + } as unknown as RunResult; + await writeFile(path.join(runDir, 'result.json'), JSON.stringify(result)); +} + +function view(overrides: Record = {}) { + return { + id: SHARE_ID, + url: `${SERVER}/s/abc`, + fileUrl: `${SERVER}/s/abc/file.mp4`, + runId: SERVER_RUN_ID, + projectId: 'p-1', + title: 'Sign in', + format: 'mp4', + status: 'uploading', + failure: null, + sizeBytes: 1000, + width: 1280, + height: 720, + durationMs: 4000, + hasPassword: false, + views: 0, + expiresAt: '2026-11-25T10:00:00.000Z', + createdAt: '2026-10-26T10:00:00.000Z', + ...overrides, + }; +} + +interface Call { + method: string; + url: string; + authorization: string | undefined; + body: Record | undefined; +} + +type Answer = { status: number; body: unknown }; + +/** The API: the POST answers `post`, each GET the next of `gets` (the last repeats). */ +function fakeApi(post: Answer | Answer[], gets: Answer[] = []) { + const calls: Call[] = []; + const posts = Array.isArray(post) ? [...post] : [post]; + const fetchFn: Fetch = async (input, init) => { + const headers = (init?.headers ?? {}) as Record; + const body = + typeof init?.body === 'string' + ? (JSON.parse(init.body) as Record) + : undefined; + calls.push({ + method: init?.method ?? 'GET', + url: String(input), + authorization: headers.authorization, + body, + }); + const answer = + init?.method === 'POST' + ? posts.length > 1 + ? posts.shift() + : posts[0] + : gets.length > 1 + ? gets.shift() + : gets[0]; + if (answer === undefined) throw new Error('no answer'); + return new Response(JSON.stringify(answer.body), { + status: answer.status, + headers: { 'content-type': 'application/json' }, + }); + }; + return { calls, fetchFn }; +} + +function capture(): Io & { out: string; err: string } { + const io = { + out: '', + err: '', + stdout: (text: string) => { + io.out += text; + }, + stderr: (text: string) => { + io.err += text; + }, + }; + return io; +} + +function deps( + fetchFn: Fetch, + overrides: Partial = {}, +): ShareCommandDeps { + let now = 0; + return { + host, + cwd: project, + fetch: fetchFn, + sleep: async (ms) => { + now += ms; + }, + now: () => now, + askPassword: async () => null, + ...overrides, + }; +} + +async function share( + fetchFn: Fetch, + flags: ShareFlags = {}, + overrides: Partial = {}, +) { + const io = capture(); + const code = await shareCommand(RUN_ID, flags, io, deps(fetchFn, overrides)); + return { code, ...io }; +} + +async function refusal(promise: Promise): Promise { + try { + await promise; + } catch (error) { + if (error instanceof CommandError) return error; + throw error; + } + throw new Error('expected a CommandError'); +} + +describe('demoflow share', () => { + it('creates the share, waits for it and prints both links', async () => { + const api = fakeApi({ status: 202, body: view() }, [ + { status: 200, body: view() }, + { status: 200, body: view({ status: 'ready' }) }, + ]); + const { code, out, err } = await share(api.fetchFn); + expect(code).toBe(0); + expect(out).toBe(`${SERVER}/s/abc\n${SERVER}/s/abc/file.mp4\n`); + expect(err).toContain('Ready; the link works until 2026-11-25'); + expect(api.calls[0]).toEqual({ + method: 'POST', + url: `${SERVER}/api/runner/shares`, + authorization: `Bearer ${TOKEN}`, + body: { runId: SERVER_RUN_ID, format: 'mp4', expiresInDays: 30 }, + }); + expect(api.calls.slice(1).map((call) => call.url)).toEqual([ + `${SERVER}/api/runner/shares/${SHARE_ID}`, + `${SERVER}/api/runner/shares/${SHARE_ID}`, + ]); + }); + + it('shares the format and lifetime asked for', async () => { + const api = fakeApi({ status: 202, body: view({ status: 'ready' }) }); + const { code } = await share(api.fetchFn, { + format: 'gif', + expires: '90', + }); + expect(code).toBe(0); + expect(api.calls[0]?.body).toEqual({ + runId: SERVER_RUN_ID, + format: 'gif', + expiresInDays: 90, + }); + }); + + it('prints the ShareView with --json', async () => { + const api = fakeApi({ status: 202, body: view({ status: 'ready' }) }); + const { code, out } = await share(api.fetchFn, { json: true }); + expect(code).toBe(0); + expect(JSON.parse(out)).toEqual(view({ status: 'ready' })); + }); + + it('prints no file link for a share with a password', async () => { + const api = fakeApi({ + status: 202, + body: view({ status: 'ready', fileUrl: null, hasPassword: true }), + }); + const { out } = await share( + api.fetchFn, + { password: true }, + { askPassword: async () => 'correct horse' }, + ); + expect(out).toBe(`${SERVER}/s/abc\n`); + }); + + it('keeps an existing share and says so', async () => { + const api = fakeApi( + { status: 409, body: { error: 'share-exists', shareId: 'share-0' } }, + [{ status: 200, body: view({ id: 'share-0', status: 'ready' }) }], + ); + const { code, out, err } = await share(api.fetchFn); + expect(code).toBe(0); + expect(out).toContain(`${SERVER}/s/abc\n`); + expect(err).toContain('already shared without a password'); + expect(api.calls[1]?.url).toBe(`${SERVER}/api/runner/shares/share-0`); + }); + + it('asks again when share-exists comes without a share id', async () => { + const api = fakeApi( + [ + { status: 409, body: { error: 'share-exists' } }, + { status: 409, body: { error: 'share-exists', shareId: 'share-0' } }, + ], + [{ status: 200, body: view({ id: 'share-0', status: 'ready' }) }], + ); + const { code } = await share(api.fetchFn); + expect(code).toBe(0); + expect(api.calls.map((call) => call.method)).toEqual([ + 'POST', + 'POST', + 'GET', + ]); + }); + + it('exits 1 with the failure when the upload fails', async () => { + const api = fakeApi({ status: 202, body: view() }, [ + { status: 200, body: view({ status: 'failed', failure: 'runner-gone' }) }, + ]); + const { code, out, err } = await share(api.fetchFn); + expect(code).toBe(1); + expect(out).toBe(''); + expect(err).toContain('The upload failed: runner-gone'); + }); + + it('gives up after 10 minutes of uploading', async () => { + const api = fakeApi({ status: 202, body: view() }, [ + { status: 200, body: view() }, + ]); + const { code, err } = await share(api.fetchFn); + expect(code).toBe(1); + expect(err).toContain('still going after 10 minutes'); + expect(err).toContain('Still uploading (15 s)'); + // One GET a second, for 10 minutes. + expect(api.calls.length).toBe(1 + 600); + }); + + it('exits 3 when the server is unreachable', async () => { + const { code, err } = await share(async () => { + throw new TypeError('fetch failed'); + }); + expect(code).toBe(3); + expect(err).toContain(`cannot reach ${SERVER}`); + }); + + describe('refusals exit 2 with their code', () => { + it.each([ + [401, {}, 'not-logged-in'], + [404, { error: 'not-found' }, 'run-not-reported'], + [409, { error: 'format-not-rendered' }, 'format-not-rendered'], + [409, { error: 'artifacts-deleted' }, 'artifacts-deleted'], + [409, { error: 'runner-offline' }, 'runner-offline'], + [409, { error: 'runner-outdated' }, 'runner-outdated'], + [ + 413, + { error: 'file-too-large', maxFileBytes: 200_000_000 }, + 'file-too-large', + ], + [ + 409, + { + error: 'quota-exceeded', + usedBytes: 900_000_000, + limitBytes: 1_000_000_000, + }, + 'quota-exceeded', + ], + ])('%i %j → %s', async (status, body, code) => { + const api = fakeApi({ status, body }); + const error = await refusal(share(api.fetchFn)); + expect(error.code).toBe(code); + expect(error.exitCode).toBe(2); + }); + + it('names the hint of an offline runner, the size and the quota', async () => { + const offline = await refusal( + share( + fakeApi({ status: 409, body: { error: 'runner-offline' } }).fetchFn, + ), + ); + expect(offline.message).toContain('demoflow runner start'); + const outdated = await refusal( + share( + fakeApi({ status: 409, body: { error: 'runner-outdated' } }).fetchFn, + ), + ); + expect(outdated.message).toContain('restart the runner'); + const large = await refusal( + share( + fakeApi({ + status: 413, + body: { error: 'file-too-large', maxFileBytes: 200_000_000 }, + }).fetchFn, + ), + ); + expect(large.message).toContain('200.0 MB'); + const quota = await refusal( + share( + fakeApi({ + status: 409, + body: { + error: 'quota-exceeded', + usedBytes: 900_000_000, + limitBytes: 1_000_000_000, + }, + }).fetchFn, + ), + ); + expect(quota.message).toContain('900.0 MB of 1.00 GB used'); + }); + + it('not-logged-in without credentials, before any request', async () => { + await rm(credentialsPath(host)); + const api = fakeApi({ status: 500, body: {} }); + const error = await refusal(share(api.fetchFn)); + expect(error.code).toBe('not-logged-in'); + expect(error.message).toContain('demoflow login'); + expect(api.calls).toEqual([]); + }); + + it('run-not-found for a missing run directory', async () => { + const api = fakeApi({ status: 500, body: {} }); + const io = capture(); + const error = await refusal( + shareCommand('20261026-000000-ffffff', {}, io, deps(api.fetchFn)), + ); + expect(error.code).toBe('run-not-found'); + expect(api.calls).toEqual([]); + }); + + it('run-not-reported for a run missing from the index', async () => { + await writeFile(runnerPaths(host).reportedRuns, ''); + const api = fakeApi({ status: 500, body: {} }); + const error = await refusal(share(api.fetchFn)); + expect(error.code).toBe('run-not-reported'); + expect(api.calls).toEqual([]); + }); + + it('run-not-reported for a run reported to another server', async () => { + writeCredentials(host, { + server: 'https://staging.example', + token: TOKEN, + runnerId: 'r-1', + }); + const error = await refusal( + share(fakeApi({ status: 500, body: {} }).fetchFn), + ); + expect(error.code).toBe('run-not-reported'); + expect(error.message).toContain(SERVER); + }); + + it('format-not-rendered for a format the run lacks, or no render', async () => { + const api = fakeApi({ status: 500, body: {} }); + const missing = await refusal(share(api.fetchFn, { format: 'webm' })); + expect(missing.code).toBe('format-not-rendered'); + expect(missing.message).toContain('mp4, gif'); + await writeResult([]); + const none = await refusal(share(api.fetchFn)); + expect(none.code).toBe('format-not-rendered'); + expect(api.calls).toEqual([]); + }); + + it('invalid-expires for a lifetime the server does not offer', async () => { + const error = await refusal( + share(fakeApi({ status: 500, body: {} }).fetchFn, { expires: '14' }), + ); + expect(error.code).toBe('invalid-expires'); + }); + }); + + describe('--password', () => { + it('sends the typed password in the body only', async () => { + const api = fakeApi({ + status: 202, + body: view({ status: 'ready', fileUrl: null, hasPassword: true }), + }); + await share( + api.fetchFn, + { password: true }, + { askPassword: async () => 'typed secret' }, + ); + expect(api.calls[0]?.body?.password).toBe('typed secret'); + expect(api.calls[0]?.url).not.toContain('secret'); + }); + + it('reads DEMOFLOW_SHARE_PASSWORD without a terminal', async () => { + host = { + ...host, + env: { ...host.env, DEMOFLOW_SHARE_PASSWORD: 'from the env' }, + }; + const api = fakeApi({ + status: 202, + body: view({ status: 'ready', fileUrl: null, hasPassword: true }), + }); + await share(api.fetchFn, { password: true }); + expect(api.calls[0]?.body?.password).toBe('from the env'); + }); + + it('is refused without a terminal and without the variable', async () => { + const api = fakeApi({ status: 500, body: {} }); + const error = await refusal(share(api.fetchFn, { password: true })); + expect(error.code).toBe('invalid-password'); + expect(error.message).toContain('DEMOFLOW_SHARE_PASSWORD'); + expect(api.calls).toEqual([]); + }); + + it('is refused outside 8–128 characters', async () => { + const api = fakeApi({ status: 500, body: {} }); + const short = await refusal( + share( + api.fetchFn, + { password: true }, + { askPassword: async () => 'short' }, + ), + ); + expect(short.code).toBe('invalid-password'); + const long = await refusal( + share( + api.fetchFn, + { password: true }, + { askPassword: async () => 'x'.repeat(129) }, + ), + ); + expect(long.code).toBe('invalid-password'); + }); + + it('takes no value on the command line', async () => { + const io = capture(); + const code = await main( + ['share', RUN_ID, '--password', 'hunter2hunter2'], + io, + ); + expect(code).toBe(2); + expect(io.err).toContain('too many arguments'); + }); + }); +}); From c8ffd1cc464163e361951f9b179db56e12fd6f00 Mon Sep 17 00:00:00 2001 From: Archi Date: Mon, 26 Oct 2026 20:01:54 +0100 Subject: [PATCH 5/8] feat(cli): the MCP share_demo tool, gated by share.allowMcp share_demo creates a share link for a reported run without a password, only when the run's project sets share.allowMcp: true. It waits up to 50 s for the upload and answers uploading when the runner is still at it. --- apps/cli/src/mcp/errors.ts | 8 +- apps/cli/src/mcp/server.ts | 187 ++++++++++++++++++++ apps/cli/test/mcp/server.spec.ts | 9 +- apps/cli/test/mcp/share.spec.ts | 295 +++++++++++++++++++++++++++++++ 4 files changed, 497 insertions(+), 2 deletions(-) create mode 100644 apps/cli/test/mcp/share.spec.ts diff --git a/apps/cli/src/mcp/errors.ts b/apps/cli/src/mcp/errors.ts index 05665b58..0a8529f3 100644 --- a/apps/cli/src/mcp/errors.ts +++ b/apps/cli/src/mcp/errors.ts @@ -1,4 +1,5 @@ import type { Issue } from '@demoflow/core'; +import type { ShareRefusalCode } from '../share/publish.ts'; export type ToolErrorCode = | 'invalid-input' @@ -8,7 +9,12 @@ export type ToolErrorCode = | 'invalid-scenario' | 'scenario-unreadable' | 'file-not-in-project' - | 'task-not-found'; + | 'task-not-found' + // `share_demo` (spec 349, Decision 7). + | 'share-not-allowed' + | 'share-failed' + | 'server-error' + | ShareRefusalCode; /** What an agent gets back from a failed tool call (spec #68, Decision 9). */ export interface ToolErrorPayload { diff --git a/apps/cli/src/mcp/server.ts b/apps/cli/src/mcp/server.ts index 1ab8d83c..9e3fb975 100644 --- a/apps/cli/src/mcp/server.ts +++ b/apps/cli/src/mcp/server.ts @@ -1,6 +1,7 @@ import { existsSync } from 'node:fs'; import { mkdir, writeFile } from 'node:fs/promises'; import path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; import { formatPath, type Issue, @@ -15,6 +16,8 @@ import { type Tool, } from '@modelcontextprotocol/sdk/types.js'; import { z } from 'zod'; +import { ServerError } from '../auth/client.ts'; +import { readCredentials } from '../auth/credentials.ts'; import { CommandError } from '../commands/errors.ts'; import { assertSafeRunId, generateRunId } from '../commands/run-id.ts'; import { readResult } from '../commands/settle.ts'; @@ -22,6 +25,7 @@ import { CliError, type HostEnvironment, loadGlobalConfig, + loadProjectConfig, osDataDir, projectFragments, runDir as runDirFor, @@ -31,6 +35,17 @@ import { pageUrlFor, readReportedRunsByDir, } from '../runs-report/reported-runs.ts'; +import { + createShare, + DEFAULT_SHARE_LIFETIME, + reportedRunOf, + type ShareRefusalCode, + ShareRefused, + type ShareStatus, + shareableFormat, + type WaitDeps, + waitForShare, +} from '../share/publish.ts'; import { packageVersion } from '../version.ts'; import { ToolError } from './errors.ts'; import { @@ -155,6 +170,40 @@ const CheckProjectInput = z.strictObject({ project: z.string().optional().describe(PROJECT_DESCRIPTION), }); +const ShareDemoInput = z.strictObject({ + runId: z + .string() + .describe('The task ID of a finished run (generate_demo, list_demos).'), + format: z + .enum(RENDER_FORMATS) + .optional() + .describe("The render to share; default: the run's first render."), + expiresInDays: z + .union([z.literal(7), z.literal(30), z.literal(90)]) + .optional() + .describe( + `How long the link works, in days; default ${DEFAULT_SHARE_LIFETIME}.`, + ), +}); + +/** What an agent can do about each refusal of the share API. */ +const SHARE_HINTS: Record = { + 'not-logged-in': 'Ask a person to run `demoflow login` on this machine.', + 'invalid-result': 'The run directory is damaged; generate the demo again.', + 'run-not-reported': + 'Only a run made while logged in, with reporting on, can be shared: generate the demo again after `demoflow login`.', + 'format-not-rendered': + 'Pass a format the run rendered (get_task lists the files), or generate the demo again with that format.', + 'artifacts-deleted': + "The run's files were deleted on the website; generate the demo again.", + 'runner-offline': + 'Ask a person to start the runner: `demoflow runner start`.', + 'runner-outdated': + 'Ask a person to restart the runner: `demoflow runner stop`, then `demoflow runner start`.', + 'file-too-large': 'Share a smaller render, or make a shorter demo.', + 'quota-exceeded': 'Ask a person to revoke old shares on the website.', +}; + const TOOLS: Tool[] = [ { name: 'generate_demo', @@ -191,6 +240,11 @@ const TOOLS: Tool[] = [ 'Whether a project is ready to run demos: its scenario files, a valid config, and FFmpeg and browser availability.', inputSchema: inputSchema(CheckProjectInput), }, + { + name: 'share_demo', + description: `Publish a finished run's render as a link on the DemoFlow website: anyone with the link can watch it, until it expires. Refused with share-not-allowed unless the project's committed demoflow.config.json sets "share": { "allowMcp": true }. Needs a logged-in machine with its runner running. Waits up to ${MAX_WAIT_SECONDS} s for the upload; on status "uploading", call again with the same arguments to wait more — it returns the same share.`, + inputSchema: inputSchema(ShareDemoInput), + }, ]; export interface McpServerDeps { @@ -199,12 +253,21 @@ export interface McpServerDeps { /** The default project, and where `DEMOFLOW_HOME` is resolved. */ cwd: string; newTaskId?: () => string; + /** `share_demo`'s requests and clock; tests replace them. */ + share?: WaitDeps; } +const processShareDeps: WaitDeps = { + fetch: (input, init) => fetch(input, init), + sleep: (ms) => delay(ms), + now: () => Date.now(), +}; + /** The `demoflow mcp` server, before it is connected to a transport. */ export function createMcpServer(deps: McpServerDeps): Server { const { queue, host, cwd } = deps; const newTaskId = deps.newTaskId ?? (() => generateRunId()); + const shareDeps = deps.share ?? processShareDeps; /** Homes of the projects used by this server: where a finished task is found. */ const homes = new Set(); @@ -235,6 +298,8 @@ export function createMcpServer(deps: McpServerDeps): Server { return ok( await checkProject(parse(CheckProjectInput, args), cwd, host), ); + case 'share_demo': + return ok(await shareDemo(parse(ShareDemoInput, args))); default: throw new ToolError( 'invalid-input', @@ -386,6 +451,100 @@ export function createMcpServer(deps: McpServerDeps): Server { ); } + /** + * Spec 349, Decision 7: what `demoflow share` does, without a password, + * and only for a project whose committed config allows it. + */ + async function shareDemo(input: z.infer): Promise<{ + shareId: string; + url: string; + fileUrl: string | null; + expiresAt: string; + status: ShareStatus; + existing: boolean; + }> { + checkTaskId(input.runId); + const runDir = locateRunDir(input.runId); + const indexFile = runnerPaths(host).reportedRuns; + const entry = (await readReportedRunsByDir(indexFile)).get( + path.resolve(runDir), + ); + if (entry === undefined) { + throw shareRefusal( + new ShareRefused( + 'run-not-reported', + 'the run was never reported to the server: it was made signed out or with reporting off', + ), + ); + } + checkShareAllowed(entry.root); + try { + const credentials = readCredentials(host); + if (credentials === null) { + throw new ShareRefused( + 'not-logged-in', + 'this machine is not logged in', + ); + } + await reportedRunOf(indexFile, runDir, credentials.server); + const format = await shareableFormat(runDir, input.format); + const created = await createShare( + credentials, + { + runId: entry.id, + format, + expiresInDays: input.expiresInDays ?? DEFAULT_SHARE_LIFETIME, + }, + shareDeps.fetch, + ); + const share = await waitForShare(credentials, created.share, shareDeps, { + timeoutMs: MAX_WAIT_SECONDS * 1000, + }); + if (share.status === 'failed' || share.status === 'lost') { + throw new ToolError( + 'share-failed', + `the upload failed: ${share.failure ?? share.status}`, + 'Call share_demo again to retry: a failed share is replaced.', + ); + } + return { + shareId: share.id, + url: share.url, + fileUrl: share.fileUrl, + expiresAt: share.expiresAt, + status: share.status, + existing: created.existing, + }; + } catch (error) { + if (error instanceof ShareRefused) throw shareRefusal(error); + if (error instanceof ServerError || error instanceof CliError) { + throw new ToolError( + 'server-error', + error.message, + error instanceof ServerError && error.unreachable + ? 'Check the network and the DemoFlow server, then call again.' + : 'Ask a person to check `demoflow login` on this machine.', + ); + } + throw error; + } + } + + /** The run directory of a task of this server, or of an earlier one. */ + function locateRunDir(taskId: string): string { + const task = queue.get(taskId); + if (task !== undefined) return task.spec.runDir; + for (const home of candidateHomes()) { + const runDir = runDirFor(home, taskId, host.platform); + if (existsSync(runDir)) return runDir; + } + throw new ToolError( + 'task-not-found', + `no run ${taskId}`, + 'Use a task ID returned by generate_demo or list_demos.', + ); + } + /** Every home this server wrote to, then where an earlier one would have. */ function candidateHomes(): Set { const env = host.env.DEMOFLOW_HOME; @@ -404,6 +563,34 @@ export function createMcpServer(deps: McpServerDeps): Server { return server; } +/** + * ADR-0019 §6: an agent may publish a project's videos only when the + * project's own, reviewed config says so. A run without a root, or a config + * that cannot be read, is refused the same way. + */ +function checkShareAllowed(root: string | undefined): void { + let allowed = false; + if (root !== undefined) { + try { + allowed = loadProjectConfig(root).share?.allowMcp === true; + } catch (error) { + if (!(error instanceof CliError)) throw error; + } + } + if (allowed) return; + throw new ToolError( + 'share-not-allowed', + root === undefined + ? 'the run was reported without its project root, so no project allows sharing it' + : `the project at ${root} does not let the MCP server share its demos`, + 'A person can share it with `demoflow share `. To let agents share this project\'s demos, a person sets "share": { "allowMcp": true } in its demoflow.config.json and commits it.', + ); +} + +function shareRefusal(error: ShareRefused): ToolError { + return new ToolError(error.code, error.message, SHARE_HINTS[error.code]); +} + /** Task IDs become directory names: no separators, no `..`. */ function checkTaskId(taskId: string): void { try { diff --git a/apps/cli/test/mcp/server.spec.ts b/apps/cli/test/mcp/server.spec.ts index cb3342a4..ffa6f1ce 100644 --- a/apps/cli/test/mcp/server.spec.ts +++ b/apps/cli/test/mcp/server.spec.ts @@ -216,7 +216,7 @@ afterAll(async () => { }); describe('demoflow mcp', () => { - it('lists its six tools with input schemas', async () => { + it('lists its seven tools with input schemas', async () => { const { tools } = await server.client.listTools(); expect(tools.map((tool) => tool.name).sort()).toEqual([ 'cancel_task', @@ -224,6 +224,7 @@ describe('demoflow mcp', () => { 'generate_demo', 'get_task', 'list_demos', + 'share_demo', 'validate_scenario', ]); for (const tool of tools) expect(tool.inputSchema.type).toBe('object'); @@ -243,6 +244,12 @@ describe('demoflow mcp', () => { expect(properties.scenario?.properties).toHaveProperty('steps'); const getTask = tools.find((tool) => tool.name === 'get_task'); expect(getTask?.inputSchema.required).toEqual(['taskId']); + const share = tools.find((tool) => tool.name === 'share_demo'); + expect(Object.keys(share?.inputSchema.properties ?? {}).sort()).toEqual([ + 'expiresInDays', + 'format', + 'runId', + ]); }); let finished: Record; diff --git a/apps/cli/test/mcp/share.spec.ts b/apps/cli/test/mcp/share.spec.ts new file mode 100644 index 00000000..a3259200 --- /dev/null +++ b/apps/cli/test/mcp/share.spec.ts @@ -0,0 +1,295 @@ +import { + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { Fetch } from '../../src/auth/client.ts'; +import { writeCredentials } from '../../src/auth/credentials.ts'; +import { + type HostEnvironment, + runDir as runDirFor, +} from '../../src/config/index.ts'; +import { createMcpServer } from '../../src/mcp/server.ts'; +import { TaskQueue } from '../../src/mcp/tasks.ts'; +import { runnerPaths } from '../../src/runner/paths.ts'; +import { appendReportedRun } from '../../src/runs-report/reported-runs.ts'; + +const SERVER = 'https://demoflow.example'; +const TOKEN = 'device-token-123'; +const TASK_ID = 't1'; +const SERVER_RUN_ID = '0d6f4a52-5d0e-4c55-9a7f-3f6f3d5c1a01'; + +let dir: string; +let home: string; +let project: string; +let runDir: string; +let host: HostEnvironment; +let client: Client; +let queue: TaskQueue; +let calls: { method: string; url: string; body: unknown }[]; +let gets: { status: number; body: unknown }[]; +let post: { status: number; body: unknown }; + +beforeEach(async () => { + dir = realpathSync(mkdtempSync(path.join(tmpdir(), 'demoflow-mcp-share-'))); + home = path.join(dir, 'home'); + project = path.join(dir, 'project'); + host = { + platform: process.platform, + env: { DEMOFLOW_HOME: home, XDG_CONFIG_HOME: dir, APPDATA: dir }, + homedir: path.join(dir, 'user'), + }; + config({ share: { allowMcp: true } }); + runDir = runDirFor(home, TASK_ID, host.platform); + write(path.join(runDir, 'result.json'), JSON.stringify(result())); + writeCredentials(host, { server: SERVER, token: TOKEN, runnerId: 'r-1' }); + report({ root: project }); + + calls = []; + post = { status: 202, body: view({ status: 'ready' }) }; + gets = []; + const fetchFn: Fetch = async (input, init) => { + calls.push({ + method: init?.method ?? 'GET', + url: String(input), + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + }); + const answer = + init?.method === 'POST' ? post : gets.length > 1 ? gets.shift() : gets[0]; + return new Response(JSON.stringify(answer?.body ?? {}), { + status: answer?.status ?? 500, + }); + }; + let now = 0; + queue = new TaskQueue({ + spawn: () => { + throw new Error('no runs here'); + }, + readResult: async () => { + throw new Error('no runs here'); + }, + removeFile: async () => undefined, + log: () => undefined, + }); + const server = createMcpServer({ + queue, + host, + cwd: project, + share: { + fetch: fetchFn, + sleep: async (ms) => { + now += ms; + }, + now: () => now, + }, + }); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + client = new Client({ name: 'test', version: '0' }); + await Promise.all([server.connect(serverSide), client.connect(clientSide)]); +}); + +afterEach(async () => { + await queue.close(); + await client.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +function write(file: string, content: string): void { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, content); +} + +function config(extra: Record): void { + write( + path.join(project, 'demoflow.config.json'), + JSON.stringify({ baseUrl: 'http://x', ...extra }), + ); +} + +function report(extra: { root?: string }): void { + appendReportedRun(runnerPaths(host).reportedRuns, { + id: SERVER_RUN_ID, + runDir, + at: '2026-10-26T10:15:05.000Z', + projectId: 'p-1', + server: SERVER, + ...extra, + }); +} + +function result() { + const stage = { status: 'passed' }; + return { + schemaVersion: 1, + runId: TASK_ID, + scenarioId: 'demoflow/tour.demo.json', + scenarioName: 'Tour', + startedAt: '2026-10-26T10:15:00.000Z', + finishedAt: '2026-10-26T10:15:05.000Z', + status: 'completed', + stages: { + readiness: stage, + execution: stage, + verification: stage, + recording: stage, + rendering: stage, + storage: { status: 'skipped' }, + }, + renders: ['mp4', 'gif'].map((format) => ({ + renderer: 'ffmpeg', + format, + file: `render/ffmpeg.${format}`, + durationMs: 4000, + sizeBytes: 1000, + width: 1280, + height: 720, + fps: 30, + })), + warnings: [], + }; +} + +function view(overrides: Record = {}) { + return { + id: 'share-1', + url: `${SERVER}/s/abc`, + fileUrl: `${SERVER}/s/abc/file.mp4`, + status: 'uploading', + failure: null, + hasPassword: false, + expiresAt: '2026-11-25T10:00:00.000Z', + ...overrides, + }; +} + +async function shareDemo(args: Record = {}) { + const answer = await client.callTool({ + name: 'share_demo', + arguments: { runId: TASK_ID, ...args }, + }); + return { + isError: answer.isError === true, + content: answer.structuredContent as Record, + }; +} + +describe('share_demo', () => { + it('creates the share when the project allows it', async () => { + const { isError, content } = await shareDemo(); + expect(isError).toBe(false); + expect(content).toEqual({ + shareId: 'share-1', + url: `${SERVER}/s/abc`, + fileUrl: `${SERVER}/s/abc/file.mp4`, + expiresAt: '2026-11-25T10:00:00.000Z', + status: 'ready', + existing: false, + }); + expect(calls).toEqual([ + { + method: 'POST', + url: `${SERVER}/api/runner/shares`, + body: { runId: SERVER_RUN_ID, format: 'mp4', expiresInDays: 30 }, + }, + ]); + }); + + it('passes the format and lifetime, and never a password', async () => { + await shareDemo({ format: 'gif', expiresInDays: 7 }); + expect(calls[0]?.body).toEqual({ + runId: SERVER_RUN_ID, + format: 'gif', + expiresInDays: 7, + }); + }); + + it.each([ + ['without a share block', {}], + ['with allowMcp false', { share: { allowMcp: false } }], + ])('is share-not-allowed %s', async (_name, extra) => { + config(extra); + const { isError, content } = await shareDemo(); + expect(isError).toBe(true); + expect(content.code).toBe('share-not-allowed'); + expect(content.hint).toContain('"allowMcp": true'); + expect(calls).toEqual([]); + }); + + it('is share-not-allowed for a run reported without a root', async () => { + rmSync(runnerPaths(host).reportedRuns); + report({}); + const { content } = await shareDemo(); + expect(content.code).toBe('share-not-allowed'); + expect(calls).toEqual([]); + }); + + it('is share-not-allowed when the config cannot be read', async () => { + write(path.join(project, 'demoflow.config.json'), '{not json'); + const { content } = await shareDemo(); + expect(content.code).toBe('share-not-allowed'); + }); + + it('waits for the upload, then answers uploading', async () => { + post = { status: 202, body: view() }; + gets = [{ status: 200, body: view() }]; + const { isError, content } = await shareDemo(); + expect(isError).toBe(false); + expect(content.status).toBe('uploading'); + // One GET a second, under the 60 s request timeout of MCP clients. + expect(calls.filter((call) => call.method === 'GET').length).toBe(50); + }); + + it('returns an existing share', async () => { + post = { status: 409, body: { error: 'share-exists', shareId: 'share-0' } }; + gets = [{ status: 200, body: view({ id: 'share-0', status: 'ready' }) }]; + const { content } = await shareDemo(); + expect(content.shareId).toBe('share-0'); + expect(content.existing).toBe(true); + }); + + it('is share-failed when the upload fails', async () => { + post = { status: 202, body: view() }; + gets = [{ status: 200, body: view({ status: 'failed', failure: 'io' }) }]; + const { isError, content } = await shareDemo(); + expect(isError).toBe(true); + expect(content.code).toBe('share-failed'); + expect(content.message).toContain('io'); + }); + + it('names the server refusal with a hint', async () => { + post = { status: 409, body: { error: 'runner-offline' } }; + const { content } = await shareDemo(); + expect(content.code).toBe('runner-offline'); + expect(content.hint).toContain('demoflow runner start'); + }); + + it('is not-logged-in without credentials', async () => { + rmSync(path.join(runnerPaths(host).dir, 'credentials.json')); + const { content } = await shareDemo(); + expect(content.code).toBe('not-logged-in'); + expect(calls).toEqual([]); + }); + + it('is run-not-reported for a run missing from the index', async () => { + rmSync(runnerPaths(host).reportedRuns); + const { content } = await shareDemo(); + expect(content.code).toBe('run-not-reported'); + }); + + it('is task-not-found for an unknown run', async () => { + const { content } = await shareDemo({ runId: 'nope' }); + expect(content.code).toBe('task-not-found'); + }); + + it('is invalid-input for a lifetime the server does not offer', async () => { + const { content } = await shareDemo({ expiresInDays: 14 }); + expect(content.code).toBe('invalid-input'); + }); +}); From 82c21a94c8104da79d7635276fc3b2a1e40ad428 Mon Sep 17 00:00:00 2001 From: Archi Date: Mon, 26 Oct 2026 20:02:32 +0100 Subject: [PATCH 6/8] docs(cli): demoflow share, share_demo and share.allowMcp in the README --- apps/cli/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/apps/cli/README.md b/apps/cli/README.md index febb8d5a..e9480c0e 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -202,6 +202,7 @@ typed value. Secret fills are left as recorded. | `demoflow run ` | run it in a browser and render the video | | `demoflow run --check [scenario]` | run and verify one scenario, or all of them, without a video | | `demoflow render ` | render an existing run again with the current config | +| `demoflow share ` | share a render of a reported run as a link on the website | | `demoflow list` | list recent runs of the current project, newest first | | `demoflow runs list` | list every run on this machine, with its size | | `demoflow runs delete ` / `prune` | delete runs by id, or by age and state | @@ -336,12 +337,41 @@ fragments of URLs are removed, the project path becomes ``, the home directory becomes `~`, and the text is cut to 1,000 characters. It can still contain text from the page under test or other paths. -Videos, frames and step values never leave the machine. +Videos, frames and step values never leave the machine, unless you share a +render (below). The report waits at most two seconds and fails silently; the run's output and exit code are never affected. It is off without `demoflow login`, under `CI`, and with `DEMOFLOW_NO_REPORT=1`. +## Share a render + +```sh +npx demoflow share +``` + +Makes a link to one render of a run that this machine reported, so anyone with +the link can watch it without an account. The runner uploads the file, so it +must be running (`demoflow runner start`). The command prints the share page's +link and, without a password, the file's own link, then exits 0 once the +upload is done. + +- `--format ` picks the render (default: the run's first one). +- `--expires `: 7, 30 (default) or 90 days. +- `--password` asks for a password twice on the terminal, without echo; + without a terminal it reads `DEMOFLOW_SHARE_PASSWORD`. It is never a flag + value, so it never lands in your shell history. A protected share has no file + link (it would skip the password), so only the page link is printed. +- `--json` prints the share as one object on stdout. +- A render already shared keeps its link; the command prints it. Revoke it on + the website to share the render again. +- Only that render leaves the machine, with its poster frame, the chapters + (the scene cards) and the scenario's `description`. +- It exits 2 when the share cannot be made (not logged in, a run this + machine did not report, no such render, the runner offline or too old, the + file over the size limit, the quota full), 1 when the upload fails or is + still going after 10 minutes, and 3 when the server cannot be reached. + ## With Claude Code ```sh @@ -349,7 +379,18 @@ claude mcp add demoflow -- npx demoflow mcp ``` The server offers `generate_demo`, `get_task`, `cancel_task`, -`validate_scenario`, `list_demos` and `check_project`. +`validate_scenario`, `list_demos`, `check_project` and `share_demo`. + +`share_demo` shares a render of a reported run, like `demoflow share` without +a password. It is refused (`share-not-allowed`) unless the run's project allows +it in `demoflow.config.json`, which you commit: + +```json +{ "share": { "allowMcp": true } } +``` + +It waits up to 50 seconds for the upload; when the answer is still +`uploading`, call it again later for the same link. ## Updates From 42fc75fd4178ae474d15754130708992fab54a5a Mon Sep 17 00:00:00 2001 From: Archi Date: Tue, 27 Oct 2026 10:38:29 +0100 Subject: [PATCH 7/8] fix(cli): list share_demo in the package smoke's expected MCP tools --- apps/cli/scripts/smoke.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/cli/scripts/smoke.mjs b/apps/cli/scripts/smoke.mjs index 0084710a..13438069 100644 --- a/apps/cli/scripts/smoke.mjs +++ b/apps/cli/scripts/smoke.mjs @@ -46,6 +46,7 @@ const TOOLS = [ 'generate_demo', 'get_task', 'list_demos', + 'share_demo', 'validate_scenario', ]; const browsers = process.argv.includes('--browsers'); From 56a230413e1d56e644668cf64e7f5d6509a52591 Mon Sep 17 00:00:00 2001 From: Archi Date: Tue, 27 Oct 2026 11:00:24 +0100 Subject: [PATCH 8/8] test(cli): resolve the share spec's temp dir with the native realpath --- apps/cli/test/runner/share.spec.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/cli/test/runner/share.spec.ts b/apps/cli/test/runner/share.spec.ts index 78ab3c19..14b664c9 100644 --- a/apps/cli/test/runner/share.spec.ts +++ b/apps/cli/test/runner/share.spec.ts @@ -128,7 +128,11 @@ async function prepare( } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(tmpdir(), 'demoflow-share-'))); + // The preparer resolves with the native realpath, which expands the 8.3 + // short names of a Windows temp dir (RUNNER~1); the JS one does not. + base = realpathSync.native( + mkdtempSync(path.join(tmpdir(), 'demoflow-share-')), + ); root = path.join(base, 'project'); runDir = path.join(base, 'home', 'runs', 'local-run'); mkdirSync(root, { recursive: true });