From 5a3ff585b707fa032fc64f1f0302e395386e8e1a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 22:15:10 +0000 Subject: [PATCH] fix(evolution): reliable project evolution movie (#82) - Frames load from their own immutable dataN.json (EVO-5): the shared data.json bridge is gone, apply-frame only validates (resolveFrame) and its errors go to the requester alone. - A half-built frame pipeline is torn down and rebuilt; component waits 4 s instead of 1.2 s (LIFECYCLE-4). - Progress reports revisions completed, monotonic to 100% (EVO-14). - Revision analyses run silently, snapshots are deleted after analysis, the payload cache is bounded (EVO-8, partial). - One movie on disk; Clear removes evolution/; revision numbers never reuse a folder, so an export ships the current movie (EVO-11). - Play at the end restarts; a same-movie replay keeps the frame; a speed change never re-arms under a seek (EVO-15). - Manual picks play oldest first; more than the limit is refused with a message (EVO-13). Remote HEAD alias no longer listed (EVO-18). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- .claude/docs/V1.2.1_STATUS.md | 7 ++ apps/vscode-extension/CHANGELOG.md | 9 ++ .../docs/features/PROJECT_EVOLUTION_XR.md | 23 +++- .../core/history/gitAnalysisSessionContext.ts | 44 ++++++- .../src/core/history/gitRepositoryService.ts | 35 +++++- .../history/historicalComparisonModels.ts | 12 +- .../core/history/projectEvolutionArtifacts.ts | 79 ++++++++++-- .../core/history/projectEvolutionService.ts | 84 ++++++------- .../server/analysis/projectEvolutionBridge.ts | 10 +- .../declarativePipeline.js | 30 +++-- .../frameApplication.js | 13 +- .../framePlaybackEngine.js | 17 ++- .../playbackControlsAndMessages.js | 6 + .../stateAndUiAtoms.js | 4 + .../timelineAndSources.js | 19 ++- .../transportAndRegistration.js | 17 ++- .../test/analysis/gitHistoryServices.test.cjs | 112 ++++++++++++++---- .../analysis/historicalComparison.test.cjs | 17 ++- .../analysis/projectEvolutionRuntime.test.cjs | 49 ++++++-- .../runners/run-project-evolution-harness.cjs | 44 +++---- 20 files changed, 480 insertions(+), 151 deletions(-) diff --git a/.claude/docs/V1.2.1_STATUS.md b/.claude/docs/V1.2.1_STATUS.md index fbcafcfa..356ce0dc 100644 --- a/.claude/docs/V1.2.1_STATUS.md +++ b/.claude/docs/V1.2.1_STATUS.md @@ -290,3 +290,10 @@ Then pushed `v1.2.1` to `origin` at the maintainer's request. **No merge and no **What changed**: `core/analysis/launch/` (new): `targetKey.ts`, `launchControl.ts` (AbortController + 10 min deadline + teardown stack per session, signal carried to the Python spawn via AsyncLocalStorage), `analysisTypes.ts` / `launchKinds.ts` / `storageFolders.ts` (descriptors; server capabilities, default controller views and router snapshot probes are derived). `launchPipeline.ts` is a transaction: server before watcher for every kind, rollback newest first, one error toast, silent on Close. Registry reserves the target before its first await. SSE + file map keyed by session id; `sessionServerManager.ts` and `sseNotificationManager.ts` deleted; close path matches servers by `metadata.sessionId` only. Startup cleanup sweeps the folders the launchers write. **Measured**: ESLint warnings 158 → 155 (budget `--max-warnings` lowered to 155); guardrails any.total 84 → 83, complexity.over10 53 → 52 (baseline regenerated). New suite `test/analysis/launchTransaction.test.cjs` (15 tests). Not done here: progress notifications are not cancellable (Close Analysis is the cancel path); LAUNCHER-11 belongs to another story. + +### XR bug-fix epic #72 — S10 reliable project evolution (#82) [confirmed by unit tests + harnesses] (2026-11-25, branch `claude/project-thread-kvvyg6-evolution`) + +**What changed**: EVO-5, frames load by their own immutable `dataN.json` URL. The `data.json` bridge is gone, `applyFrameToBridge` became `resolveFrame` (validation only), and apply-frame errors go to the requester only. LIFECYCLE-4, a half-built pipeline is torn down (`failEvolutionPipeline`) and component waits went from 1200 to 4000 ms. EVO-14, progress carries `completed` and the bar is monotonic. EVO-8 (partial), revision analyses run `silent`, snapshots are released after each analysis, and the payload cache is an LRU of 128. EVO-11, one `revision-N` on disk, Clear removes `evolution/`, and revision numbers never reuse a folder. EVO-15, Play at the end restarts, a same-revision replay keeps `frameIndex`, and `setSpeed` does not re-arm under a seek. EVO-13, manual picks are sorted chronologically online and more than `maxFrames` is refused on both ends. EVO-18, the remote HEAD alias is filtered by full ref. EVO-1 was already covered by S6 (plus `applySharedState` now ends `generating`). + +**Measured**: `npm test` 1,139/1,139; ESLint 154 (unchanged); filesOver500 unchanged (`resolveEvolutionFrame`/`evolutionDirectoryOf` moved to `projectEvolutionArtifacts.ts`). Harnesses xr-mode, project-evolution (now asserts each frame loads `data.json` and that no bridge file exists) and xr pass. **Not done**: live evolution still materializes snapshots with one `git show` per file and runs the directory analysis per revision; reusing the export's blob pipeline (`GitTimelineBlobAnalyzer` + worker pool) needs a payload-parity check first and is left as follow-up. + diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 10dcc609..1420beb4 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -87,6 +87,15 @@ - A double click on Generate or Compare, or two participants starting at once, no longer shows an error to everyone while the first job runs: "already running" goes only to the person who asked. A participant who joins mid-job sees it running. - A cancelled analysis is no longer recorded as "this revision has no data", which hid that commit from both Git pickers until the session ended. - Git-history exports no longer wait forever on one file: a file analysis is stopped after 2 minutes and retried once, and a Python worker that is slow to start (antivirus on Windows) reduces the number of workers instead of failing the export. +- **Project evolution is more reliable.** + - Two people moving through the movie at the same time no longer get errors that stop playback for the whole room, or a frame shown under another frame's title. Each frame is now loaded from its own file instead of being copied over a shared one, and a frame that cannot be shown is reported only to the person who asked for it. + - A movie whose first frame could not be built (a component slow to load on a headset, for example) no longer makes the mode impossible to open again until a new movie is generated. The half-built frame is removed and rebuilt, and slow components get 4 s instead of 1.2 s. + - The progress bar now counts finished revisions, so it only moves forward and reaches the end. Before, it jumped back and forth between parallel analyses. + - Generating a movie no longer opens one VS Code notification per revision, and each revision's temporary copy of the project is deleted as soon as it is analyzed instead of staying on disk (up to about 100 MB each) until VS Code closed. + - Only the current movie is kept on disk. Before, every movie generated stayed, **Clear movie** removed only the newest one, and a later export could ship an older movie that had been replaced and cleared. + - **Play** on the last frame starts the movie over instead of stopping at once, and reconnecting to the room keeps the frame you were on instead of jumping back to frame 1. + - Manual movies always play from oldest to newest, as exported movies already did, whatever order the commits were picked in. A 25th pick is refused with a message instead of being dropped without notice. + - The commit picker no longer lists the remote's default-branch alias as a branch named "origin". - A source file of the XR chart-mapping runtime contained a raw control character typed into a string. Behaviour was correct, but the file was invisible to code search and review tools. It now uses the equivalent escape sequence; the runtime value is identical. ## [1.2.0] - 2026-07-30 diff --git a/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md b/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md index fbfe211f..524b2302 100644 --- a/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md +++ b/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md @@ -31,24 +31,32 @@ The XR panel exposes a compact player: between modes; - page through available Git sources with previous/next arrows; - mark range starts in green and range ends in red; -- show manual picks with their selection order; +- show manual picks with their selection order (the movie itself always plays + oldest first, and a manual movie holds at most 24 frames: a 25th pick is + refused with a message); - play and pause; - previous and next frame; - speed presets; - clear the generated movie for everyone in the shared XR room; - current frame label, frame count and progress status. -Each frame replaces the active chart datasource and asks the analysis table to -renormalize. Playback waits for the chart/table to settle, then holds briefly +Each frame points the chart datasource at that frame's own file, +`/evolution/revision-N/data.json`, and asks the analysis table to +renormalize. The files are written once and never changed, so participants +seeking at the same time cannot overwrite each other's frame (until 1.2.1 every +frame was copied over a shared `data.json`, which raced). Playback waits for the chart/table to settle, then holds briefly before advancing, so the movie reads as a sequence of stable scenes instead of a rapid data swap. While playback is active, a small overlay above the table shows the current revision, date and frame number. When playback reaches the last frame, the final chart remains visible and the panel reports completion until -the user generates another movie or presses `Clear movie`. The Field Mapping panel remains +the user generates another movie or presses `Clear movie`; Play on the last +frame starts the movie over. The Field Mapping panel remains available, so users can change the chart and dimensions while reviewing the evolution. -`Clear movie` removes the generated `/evolution/` JSON files, clears the shared +Only the current movie is kept on disk: a new movie removes the older +`revision-N` folders, so an export always ships the movie the room was looking +at. `Clear movie` removes the whole `/evolution/` folder, clears the shared Project Evolution entity, hides the movie chart, and resets every connected client to the empty Project Evolution panel. It does not delete the normal analysis `data.json`. @@ -69,6 +77,11 @@ button reads `Cancel`: - **Leaving the mode** changes nothing on the server: the generation goes on for the room and its movie appears when it is ready. +The progress bar counts revisions finished (analyzed or discarded) out of the +total, so it only moves forward and reaches the end. Revisions are analyzed +without a VS Code notification each, and each revision's snapshot is deleted as +soon as it is analyzed. + A second Generate while one runs is answered `busy` to that participant only. A participant who opens the panel mid-generation sees the room's job (the references reply carries its state). A revision whose analysis times out is diff --git a/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts b/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts index f38a3fc1..facbeccb 100644 --- a/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts +++ b/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts @@ -22,6 +22,13 @@ import { ComparisonSource, GitAnalysisExclusionCode } from './historicalComparis */ export const REVISION_ANALYSIS_TIMEOUT_MS = 5 * 60 * 1000; +/** + * Analyzed revisions kept per session (least recently used dropped first). + * Enough for a 96-frame movie; before, every regeneration over a different + * range added to a cache nothing ever trimmed (EVO-8). + */ +export const MAX_CACHED_REVISIONS = 128; + /** One analyzed revision as both Git services cache it. */ export interface CachedPayload { payload: Record[]; @@ -107,9 +114,37 @@ export class GitAnalysisSessionContext { const cacheKey = buildAnalyzerCacheKey(this.policy.cacheVersion, source.commitSha, session); const cached = this.cache.get(cacheKey); if (cached) { + this.remember(cacheKey, cached); return cached; } + try { + return await this.analyzeRevision(source, session, cacheKey); + } finally { + // The snapshot is only the analyzer's input: once its payload is + // cached it is dead weight (up to 100 MB per revision, EVO-8). + await this.gitService.releaseSnapshot(source).catch(() => undefined); + } + } + + /** Keeps `key` as the most recently used entry and trims the oldest ones. */ + private remember(key: string, value: CachedPayload): void { + this.cache.delete(key); + this.cache.set(key, value); + while (this.cache.size > MAX_CACHED_REVISIONS) { + const oldest = this.cache.keys().next().value; + if (oldest === undefined) { + break; + } + this.cache.delete(oldest); + } + } + + private async analyzeRevision( + source: Extract, + session: UnifiedAnalysisSession, + cacheKey: string, + ): Promise { const materialized = await this.gitService.materialize(source); if (!materialized.targetPath) { if (this.policy.missingTarget === 'throw') { @@ -124,7 +159,7 @@ export class GitAnalysisSessionContext { missingTarget: true, warnings: materialized.warnings, }; - this.cache.set(cacheKey, missing); + this.remember(cacheKey, missing); return missing; } @@ -149,7 +184,7 @@ export class GitAnalysisSessionContext { missingTarget: false, warnings: materialized.warnings, }; - this.cache.set(cacheKey, result); + this.remember(cacheKey, result); return result; } @@ -168,7 +203,10 @@ export class GitAnalysisSessionContext { try { analysisResult = await runWithLaunchSignal( watchdog.signal, - () => new ExecutePython(this.extensionContext).executeAnalysis(revisionSession), + // Silent: one VS Code notification per revision (up to 24, + // four at a time) was noise; the room's progress bar is the + // report (EVO-8). + () => new ExecutePython(this.extensionContext).executeAnalysis(revisionSession, { silent: true }), ); } catch (error) { if (jobSignal?.aborted) { diff --git a/apps/vscode-extension/src/core/history/gitRepositoryService.ts b/apps/vscode-extension/src/core/history/gitRepositoryService.ts index d5fb3145..907b8917 100644 --- a/apps/vscode-extension/src/core/history/gitRepositoryService.ts +++ b/apps/vscode-extension/src/core/history/gitRepositoryService.ts @@ -207,7 +207,26 @@ export class GitRepositoryService { if (!Array.isArray(sourceIds) || sourceIds.length === 0) { return []; } - return Promise.all(sourceIds.map((sourceId) => this.resolveSource(sourceId))); + const resolved = await Promise.all(sourceIds.map((sourceId) => this.resolveSource(sourceId))); + // Oldest first, like the offline export (EVO-13): a movie plays in + // history order whatever order the commits were picked in. Dated refs + // by committer time, then undated ones in pick order, and the working + // copy (the present) last. + const group = (source: ComparisonSource): number => { + if (source.kind === 'workingCopy') { + return 2; + } + return typeof source.timestamp === 'number' ? 0 : 1; + }; + const time = (source: ComparisonSource): number => ( + source.kind === 'gitRef' && typeof source.timestamp === 'number' ? source.timestamp : 0 + ); + return resolved + .map((source, index) => ({ source, index })) + .sort((a, b) => group(a.source) - group(b.source) + || time(a.source) - time(b.source) + || a.index - b.index) + .map((entry) => entry.source); } public async materialize(source: ComparisonSource): Promise { @@ -233,6 +252,16 @@ export class GitRepositoryService { : this.materializeFile(repositoryRoot, source.commitSha, targetRelativePath, destinationPath); } + /** Deletes one revision's snapshot once its analysis is done (EVO-8). */ + public async releaseSnapshot(source: ComparisonSource): Promise { + if (source.kind !== 'gitRef' || !this.isCommitSha(source.commitSha)) { + return; + } + const sourceDirectory = path.join(this.snapshotRoot, this.safeSnapshotName(source.commitSha)); + this.assertInside(this.snapshotRoot, sourceDirectory); + await fs.promises.rm(sourceDirectory, { recursive: true, force: true }); + } + public async dispose(): Promise { await fs.promises.rm(this.snapshotRoot, { recursive: true, force: true }); } @@ -430,7 +459,9 @@ export class GitRepositoryService { const sources: ComparisonSource[] = []; for (const line of splitGitLines(stdout)) { const [fullRef, commitSha, shortName, committerDate, committerUnix] = line.split('\0'); - if (!fullRef || !this.isCommitSha(commitSha) || !shortName || shortName.endsWith('/HEAD')) { + // `%(refname:short)` of refs/remotes/origin/HEAD is just "origin", + // so the alias is recognised by its full ref (EVO-18). + if (!fullRef || !this.isCommitSha(commitSha) || !shortName || fullRef.endsWith('/HEAD')) { continue; } if (headName && fullRef === `refs/heads/${headName}`) { diff --git a/apps/vscode-extension/src/core/history/historicalComparisonModels.ts b/apps/vscode-extension/src/core/history/historicalComparisonModels.ts index 071d1869..df252e1d 100644 --- a/apps/vscode-extension/src/core/history/historicalComparisonModels.ts +++ b/apps/vscode-extension/src/core/history/historicalComparisonModels.ts @@ -156,7 +156,11 @@ export interface ProjectEvolutionResult { frames: ProjectEvolutionFrame[]; generatedAt: string; manifestUrl: string; - bridgeUrl: string; + /** + * Gone since 1.2.1: frames are loaded by their own immutable `url` + * (EVO-5). Kept optional so a movie exported by 1.2.0 still parses. + */ + bridgeUrl?: string; excludedSources: GitAnalysisExclusion[]; } @@ -172,6 +176,12 @@ export interface ProjectEvolutionProgress { revision?: number; frameIndex?: number; frameCount?: number; + /** + * Revisions finished so far (analyzed or discarded) out of `frameCount`. + * Only ever grows and reaches `frameCount`, unlike `frameIndex`, which + * names whichever of the parallel workers spoke last (EVO-14). + */ + completed?: number; /** The job this progress belongs to. */ jobId?: string; } diff --git a/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts b/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts index 7ed550af..618aa705 100644 --- a/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts +++ b/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts @@ -1,6 +1,8 @@ /** - * The files of one generated project-evolution movie: `dataN.json` per frame, - * the `data.json` bridge the scene reads, and the manifest. + * The files of one generated project-evolution movie: `dataN.json` per frame + * and the manifest. Every file is written once and never changed: the scene + * loads each frame by its own URL (EVO-5), so there is no shared bridge file + * for concurrent players to race on. * * Pure helpers split out of ProjectEvolutionService: the service owns WHEN a * revision becomes current (only once these files are written and the job is @@ -21,7 +23,7 @@ export interface EvolutionFrameInput { source: ComparisonSource; } -/** Phase 4: a fresh revision folder with dataN.json per frame, the data.json bridge and the manifest. */ +/** Phase 4: a fresh revision folder with dataN.json per frame and the manifest. */ export async function writeEvolutionRevision( revision: number, revisionDirectory: string, @@ -57,13 +59,8 @@ export async function writeEvolutionRevision( frames, generatedAt: new Date().toISOString(), manifestUrl: `/evolution/revision-${revision}/manifest.json`, - bridgeUrl: `/evolution/revision-${revision}/data.json`, excludedSources, }; - await copyFileAtomically( - path.join(revisionDirectory, 'data1.json'), - path.join(revisionDirectory, 'data.json'), - ); await fs.promises.writeFile( path.join(revisionDirectory, 'manifest.json'), JSON.stringify(result, null, 2), @@ -79,11 +76,67 @@ export function extractSourceDate(source: ComparisonSource): string | undefined return match ? match[1] : undefined; } -/** Copy through a temp file + rename, so a reader never sees half a file. */ -export async function copyFileAtomically(sourcePath: string, destinationPath: string): Promise { - const tempPath = `${destinationPath}.${process.pid}.${Date.now()}.tmp`; - await fs.promises.copyFile(sourcePath, tempPath); - await fs.promises.rename(tempPath, destinationPath); +/** `/evolution`, refusing anything that would escape the static root. */ +export function evolutionDirectoryOf(staticRootPath: string): string { + const staticRoot = path.resolve(staticRootPath); + const evolutionDirectory = path.resolve(staticRoot, 'evolution'); + if (!evolutionDirectory.startsWith(staticRoot + path.sep)) { + throw new Error('project-evolution-outside-static-root'); + } + return evolutionDirectory; +} + +/** + * Validates a frame of the current movie and returns its own URL. No file is + * copied (EVO-5): each frame is an immutable `dataN.json`, so players seeking + * at once can no longer race on a shared bridge file. + */ +export function resolveEvolutionFrame( + revision: number, + frameIndex: number, + currentRevision: number, + frameCount: number, +): { revision: number; frameIndex: number; frameUrl: string } { + const safeRevision = Math.floor(Number(revision)); + const safeFrameIndex = Math.floor(Number(frameIndex)); + if (!Number.isFinite(safeRevision) || safeRevision < 1 || safeRevision !== currentRevision) { + throw new Error('project-evolution-invalid-revision'); + } + if (!Number.isFinite(safeFrameIndex) || safeFrameIndex < 0 || safeFrameIndex >= frameCount) { + throw new Error('project-evolution-invalid-frame'); + } + return { + revision: safeRevision, + frameIndex: safeFrameIndex, + frameUrl: `/evolution/revision-${safeRevision}/data${safeFrameIndex + 1}.json`, + }; +} + +/** The revision numbers of the `revision-N` folders under `evolutionDirectory`. */ +export async function listEvolutionRevisions(evolutionDirectory: string): Promise { + let names: string[]; + try { + names = await fs.promises.readdir(evolutionDirectory); + } catch { + return []; + } + return names + .map((name) => /^revision-(\d+)$/.exec(name)) + .filter((match): match is RegExpExecArray => !!match) + .map((match) => Number(match[1])) + .filter((value) => Number.isSafeInteger(value) && value > 0); +} + +/** + * Removes every `revision-N` folder but `keep` (EVO-11): one movie on disk, + * so an export can only ship the movie the room is looking at. + */ +export async function removeOtherEvolutionRevisions(evolutionDirectory: string, keep: number): Promise { + for (const revision of await listEvolutionRevisions(evolutionDirectory)) { + if (revision !== keep) { + await fs.promises.rm(path.join(evolutionDirectory, `revision-${revision}`), { recursive: true, force: true }); + } + } } /** How a frame's revision is named in progress messages. */ diff --git a/apps/vscode-extension/src/core/history/projectEvolutionService.ts b/apps/vscode-extension/src/core/history/projectEvolutionService.ts index cf781cd4..3d7fd9a2 100644 --- a/apps/vscode-extension/src/core/history/projectEvolutionService.ts +++ b/apps/vscode-extension/src/core/history/projectEvolutionService.ts @@ -14,9 +14,12 @@ import { } from './gitAnalysisEligibility'; import { sampleTimeline } from './gitTimelineSampler'; import { - copyFileAtomically, describeRevisionType, + evolutionDirectoryOf, + listEvolutionRevisions, mergeEvolutionSources, + removeOtherEvolutionRevisions, + resolveEvolutionFrame, writeEvolutionRevision, } from './projectEvolutionArtifacts'; import { @@ -50,6 +53,8 @@ export class ProjectEvolutionService { timeoutMs: PROJECT_EVOLUTION_JOB_TIMEOUT_MS, }); private revision = 0; + /** Frames of the current movie (`revision`), for resolveFrame. */ + private frameCount = 0; public constructor( private readonly context: vscode.ExtensionContext, @@ -162,40 +167,22 @@ export class ProjectEvolutionService { await this.jobs.cancelAndWait('cancelled'); this.jobs.forgetLastRequest(); this.analysis.cache.clear(); - if (this.revision < 1) { - return; - } - const evolutionDirectory = path.resolve(this.staticRoot, 'evolution'); - const revisionDirectory = path.resolve(evolutionDirectory, `revision-${this.revision}`); - const staticRoot = path.resolve(this.staticRoot); - if (!revisionDirectory.startsWith(staticRoot + path.sep) && revisionDirectory !== staticRoot) { - throw new Error('project-evolution-clear-outside-static-root'); - } - await fs.promises.rm(revisionDirectory, { recursive: true, force: true }); + // The whole folder, not only the newest revision (EVO-11): an older + // movie left behind was what a later export shipped. + await fs.promises.rm(this.resolveEvolutionDirectory(), { recursive: true, force: true }); + this.frameCount = 0; } - public async applyFrameToBridge( + /** + * Validates a frame of the current movie and returns its own URL. No file + * is copied (EVO-5): each frame is an immutable `dataN.json`, so players + * seeking at once can no longer race on a shared bridge file. + */ + public resolveFrame( revision: number, frameIndex: number, - ): Promise<{ revision: number; frameIndex: number; bridgeUrl: string }> { - const safeRevision = Math.floor(Number(revision)); - const safeFrameIndex = Math.floor(Number(frameIndex)); - if (!Number.isFinite(safeRevision) || safeRevision < 1 || safeRevision !== this.revision) { - throw new Error('project-evolution-invalid-revision'); - } - if (!Number.isFinite(safeFrameIndex) || safeFrameIndex < 0) { - throw new Error('project-evolution-invalid-frame'); - } - const revisionDirectory = this.resolveRevisionDirectory(safeRevision); - const sourcePath = path.join(revisionDirectory, `data${safeFrameIndex + 1}.json`); - const bridgePath = path.join(revisionDirectory, 'data.json'); - await fs.promises.access(sourcePath, fs.constants.R_OK); - await copyFileAtomically(sourcePath, bridgePath); - return { - revision: safeRevision, - frameIndex: safeFrameIndex, - bridgeUrl: `/evolution/revision-${safeRevision}/data.json`, - }; + ): { revision: number; frameIndex: number; frameUrl: string } { + return resolveEvolutionFrame(revision, frameIndex, this.revision, this.frameCount); } private async executeEvolution( @@ -261,6 +248,7 @@ export class ProjectEvolutionService { message: `Analyzing ${sources.length} project revisions with ${concurrency} workers...`, frameIndex: 0, frameCount: sources.length, + completed: 0, }); const workers = Array.from({ length: concurrency }, async () => { @@ -273,6 +261,7 @@ export class ProjectEvolutionService { message: `Analyzing frame ${index + 1} / ${sources.length} (${describeRevisionType(source)}): ${source.label}`, frameIndex: index, frameCount: sources.length, + completed, }); try { const payload = await this.analysis.analyzeSource(source, this.getSession()); @@ -309,6 +298,7 @@ export class ProjectEvolutionService { : `Analyzed ${completed} / ${sources.length} project revisions. Last completed: ${describeRevisionType(source)} ${source.label}`, frameIndex: index, frameCount: sources.length, + completed, }); } }); @@ -322,7 +312,7 @@ export class ProjectEvolutionService { return { analyzed, exclusionsByIndex }; } - /** Phase 4: a new revision folder with dataN.json per frame, the data.json bridge and the manifest. */ + /** Phase 4: a new revision folder with dataN.json per frame and the manifest; older ones are removed. */ private async writeEvolutionArtifacts( valid: Array<{ payload: CachedPayload; source: ComparisonSource }>, excludedSources: GitAnalysisExclusion[], @@ -334,8 +324,11 @@ export class ProjectEvolutionService { if (signal.aborted) { throw new Error('project-evolution-cancelled'); } - const revision = this.revision + 1; - const evolutionDirectory = path.join(this.staticRoot, 'evolution'); + const evolutionDirectory = this.resolveEvolutionDirectory(); + // Never reuse a number a folder on disk already has: a new service + // starts at 0, and revision-1 of a previous one would be overwritten + // under a URL the scene may have cached (EVO-11). + const revision = Math.max(this.revision, ...await listEvolutionRevisions(evolutionDirectory)) + 1; const revisionDirectory = path.join(evolutionDirectory, `revision-${revision}`); try { const result = await writeEvolutionRevision(revision, revisionDirectory, valid, excludedSources); @@ -343,6 +336,8 @@ export class ProjectEvolutionService { throw new Error('project-evolution-cancelled'); } this.revision = revision; + this.frameCount = result.frames.length; + await removeOtherEvolutionRevisions(evolutionDirectory, revision).catch(() => undefined); return result; } catch (error) { await fs.promises.rm(revisionDirectory, { recursive: true, force: true }).catch(() => undefined); @@ -355,9 +350,14 @@ export class ProjectEvolutionService { const maxFrames = Math.max(1, Math.min(96, Math.floor(Number(request.maxFrames || DEFAULT_MAX_FRAMES)))); let candidates: ComparisonSource[]; if (mode === 'manual' && Array.isArray(request.sourceIds) && request.sourceIds.length) { - candidates = await this.gitService.resolveSourcesInChronologicalOrder( - request.sourceIds.slice(0, maxFrames), - ); + // Picks past the limit used to be dropped without a word (EVO-13). + if (request.sourceIds.length > maxFrames) { + throw new Error( + `A manual movie has at most ${maxFrames} frames and ${request.sourceIds.length} were picked. ` + + `Remove ${request.sourceIds.length - maxFrames} and generate again.`, + ); + } + candidates = await this.gitService.resolveSourcesInChronologicalOrder(request.sourceIds); } else { candidates = await this.resolveAutomaticOrRangeSources(request); } @@ -476,14 +476,8 @@ export class ProjectEvolutionService { })); } - private resolveRevisionDirectory(revision: number): string { - const evolutionDirectory = path.resolve(this.staticRoot, 'evolution'); - const revisionDirectory = path.resolve(evolutionDirectory, `revision-${revision}`); - const staticRoot = path.resolve(this.staticRoot); - if (!revisionDirectory.startsWith(staticRoot + path.sep) && revisionDirectory !== staticRoot) { - throw new Error('project-evolution-revision-outside-static-root'); - } - return revisionDirectory; + private resolveEvolutionDirectory(): string { + return evolutionDirectoryOf(this.staticRoot); } private getSession(): UnifiedAnalysisSession { diff --git a/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts b/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts index 012d61df..dc3d10b3 100644 --- a/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts +++ b/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts @@ -128,7 +128,9 @@ export class ProjectEvolutionBridge { const requestId = typeof payload.requestId === 'string' ? payload.requestId : undefined; - const result = await this.projectEvolutionService.applyFrameToBridge(revision, frameIndex); + // No file I/O any more (EVO-5): the frame is validated and its + // own URL goes to the room, which follows the seek. + const result = this.projectEvolutionService.resolveFrame(revision, frameIndex); const currentView = this.host.getAnalysisViewState(); if ( currentView?.mode !== 'project-evolution' @@ -140,11 +142,15 @@ export class ProjectEvolutionBridge { type: 'project-evolution-frame-applied', payload: { ...result, + // Scenes from 1.2.0 read the frame from `bridgeUrl`. + bridgeUrl: result.frameUrl, requestId, }, }); } catch (error) { - messageContext.broadcast({ + // A bad seek is the requester's alone: broadcasting it stopped + // playback for the whole room (EVO-5). + messageContext.send({ type: 'project-evolution-error', payload: { code: error instanceof Error ? error.message : 'project-evolution-apply-frame-failed', diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/declarativePipeline.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/declarativePipeline.js index 43f32cd7..5240a6d8 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/declarativePipeline.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/declarativePipeline.js @@ -304,6 +304,21 @@ }); } + // A Quest under load can take well over a second to attach a component; + // 1200 ms failed the pipeline there (LIFECYCLE-4). + var PIPELINE_COMPONENT_TIMEOUT_MS = 4000; + + // A pipeline that fails half-way is torn down whole: a root left without + // its chart was taken for a preserved frame and broke every later entry + // into the mode (LIFECYCLE-4). The next seek rebuilds it from scratch. + function failEvolutionPipeline(message, viewGeneration) { + if (isEvolutionViewCurrent(viewGeneration)) { + setStatus(message, 'error'); + releaseEvolutionVisualization(); + } + return null; + } + async function ensureDeclarativeEvolutionPipeline(frame, frameUrl, viewGeneration) { if (!isEvolutionViewCurrent(viewGeneration)) { return null; @@ -316,17 +331,15 @@ var rootEl = ensureEvolutionRoot(frame); var dataResult = ensureEvolutionDataSource(frameUrl); var dataSource = dataResult.entity; - if (!dataSource || !await waitForComponent(dataSource, 'babia-queryjson', 1200)) { - setStatus('Project evolution datasource is not available.', 'error'); - return null; + if (!dataSource || !await waitForComponent(dataSource, 'babia-queryjson', PIPELINE_COMPONENT_TIMEOUT_MS)) { + return failEvolutionPipeline('Project evolution datasource is not available.', viewGeneration); } if (!isEvolutionViewCurrent(viewGeneration)) { return null; } var treeBuilder = ensureEvolutionTreeBuilder(rootEl); - if (!treeBuilder || !await waitForComponent(treeBuilder, EVOLUTION_TREE_COMPONENT, 1200)) { - setStatus('Project evolution tree is not available.', 'error'); - return null; + if (!treeBuilder || !await waitForComponent(treeBuilder, EVOLUTION_TREE_COMPONENT, PIPELINE_COMPONENT_TIMEOUT_MS)) { + return failEvolutionPipeline('Project evolution tree is not available.', viewGeneration); } scopeEvolutionTreeOutput(treeBuilder); if (!isEvolutionViewCurrent(viewGeneration)) { @@ -347,9 +360,8 @@ } } var chart = ensureEvolutionChart(chartId, rootEl); - if (!chart || !await waitForComponent(chart, componentName, 1200)) { - setStatus('Project evolution chart is not available.', 'error'); - return null; + if (!chart || !await waitForComponent(chart, componentName, PIPELINE_COMPONENT_TIMEOUT_MS)) { + return failEvolutionPipeline('Project evolution chart is not available.', viewGeneration); } await waitForComponent(chart, 'codexr-chart-containment', 1200); if (!isEvolutionViewCurrent(viewGeneration)) { diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js index 4ac4b868..d4d5c57c 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js @@ -37,7 +37,7 @@ if (!isEvolutionViewCurrent(viewGeneration)) { return; } - void applyBridgeFrameToChart(frames[state.frameIndex], payload.bridgeUrl, viewGeneration).then(function (applied) { + void applyBridgeFrameToChart(frames[state.frameIndex], payload.frameUrl || payload.bridgeUrl, viewGeneration).then(function (applied) { if (!applied || !isEvolutionViewCurrent(viewGeneration)) { return; } @@ -67,9 +67,16 @@ return; } var previousRevision = Number(state.result?.revision || 0); + var sameMovie = previousRevision > 0 && previousRevision === Number(shared.result.revision || 0); state.result = shared.result; state.jobRunning = false; - state.frameIndex = 0; + state.generating = false; + renderGenerationProgress({ state: 'idle' }); + // A replay of the same movie (a reconnect, a room snapshot) keeps the + // frame on screen instead of jumping back to frame 1 (EVO-15). + if (!sameMovie) { + state.frameIndex = 0; + } if (previousRevision && previousRevision !== Number(shared.result.revision || 0)) { releaseEvolutionVisualization(); } @@ -82,7 +89,7 @@ // the view, so the local transition and the server echo cannot disagree. var transition = changeToEvolutionAnalysis({ reason: 'project-evolution-ready' }); void Promise.resolve(transition).then(function () { - return seek(0); + return seek(state.frameIndex); }); } diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/framePlaybackEngine.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/framePlaybackEngine.js index 5c590d37..c2268202 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/framePlaybackEngine.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/framePlaybackEngine.js @@ -5,10 +5,14 @@ : '')); } + // Every frame is loaded by its own immutable URL, online as offline + // (EVO-5). The shared data.json "bridge" the server used to copy each frame + // into raced between players; it stays only as the fallback for a movie + // whose frames carry no url (1.2.0 exports, harness fixtures). function frameUrlWithCache(frame, rawUrl) { var raw = client()?.isOfflineExport?.() ? String(frame.url || '') - : String(rawUrl || bridgeUrl() || frame.url || ''); + : String(frame.url || rawUrl || bridgeUrl() || ''); if (!raw) { return ''; } var separator = raw.indexOf('?') === -1 ? '?' : '&'; return raw + separator @@ -266,6 +270,15 @@ } state.frameIndex = Math.max(0, Math.min(frames.length - 1, Number(index) || 0)); var requestedFrameIndex = state.frameIndex; + state.seekInFlight += 1; + try { + return await seekFrame(requestedFrameIndex, viewGeneration, frames); + } finally { + state.seekInFlight = Math.max(0, state.seekInFlight - 1); + } + } + + async function seekFrame(requestedFrameIndex, viewGeneration, frames) { var applied = null; try { applied = await requestBridgeFrame(requestedFrameIndex); @@ -294,7 +307,7 @@ } var appliedToChart = await applyBridgeFrameToChart( frames[requestedFrameIndex], - applied.bridgeUrl, + applied.frameUrl || applied.bridgeUrl, viewGeneration ); if (!appliedToChart || !isEvolutionViewCurrent(viewGeneration)) { diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js index a55ca26d..8c14bba5 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js @@ -153,6 +153,12 @@ if (state.manualSourceIds.includes(source.id)) { state.manualSourceIds = state.manualSourceIds.filter(function (id) { return id !== source.id; }); } else { + // The limit is said, not applied silently (EVO-13). + var limit = Number(state.references?.maxFrames) || 24; + if (state.manualSourceIds.length >= limit) { + setStatus('A manual movie has at most ' + limit + ' frames. Remove one to add another.', 'error'); + return; + } state.manualSourceIds.push(source.id); } render(); diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js index 2e6272ee..1a7e3fab 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js @@ -41,6 +41,10 @@ // True while the server is building the movie: shows the progress bar and // makes the panel reserve room for it. generating: false, + // Seeks still running (setSpeed must not restart playback under one). + seekInFlight: 0, + // Revisions the progress bar has shown as finished (it never goes back). + generationCompleted: 0, // A generation job (any phase) is running for the room: the Clear button // then reads "Cancel" and stops the job instead of deleting the movie. jobRunning: false, diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/timelineAndSources.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/timelineAndSources.js index 32928661..e27ab20d 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/timelineAndSources.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/timelineAndSources.js @@ -195,16 +195,27 @@ function renderGenerationProgress(payload) { if (!refs.progressRoot) { return; } var count = Number(payload?.frameCount) || 0; - var index = Number(payload?.frameIndex) || 0; var analyzing = payload?.state === 'analyzing' && count > 0; setNodeVisible(refs.progressRoot, analyzing); - if (!analyzing) { return; } - var ratio = Math.min(1, Math.max(0, index / count)); + if (!analyzing) { + state.generationCompleted = 0; + return; + } + // Revisions FINISHED, never lower than what was already shown: with + // parallel workers frameIndex names whichever one spoke last, so the bar + // jumped back and never reached the end (EVO-14). Servers from 1.2.0 + // send no `completed`; frameIndex + 1 is the closest they offer. + var reported = payload.completed != null + ? Number(payload.completed) || 0 + : (Number(payload?.frameIndex) || 0) + 1; + state.generationCompleted = Math.min(count, Math.max(state.generationCompleted || 0, reported)); + var done = state.generationCompleted; + var ratio = Math.min(1, Math.max(0, done / count)); var width = Math.max(0.01, ratio * TIMELINE_WIDTH); refs.progressFill.setAttribute('width', width); // Grows from the left edge. refs.progressFill.setAttribute('position', ((width / 2) - (TIMELINE_WIDTH / 2)) + ' 0 0'); - refs.progressLabel.setAttribute('value', 'Generating frame ' + Math.min(index + 1, count) + ' / ' + count); + refs.progressLabel.setAttribute('value', 'Analyzed ' + done + ' / ' + count + ' revisions'); } function buildSparkline() { diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js index d52573b6..1295eb22 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js @@ -16,6 +16,18 @@ state.playing = true; state.playbackGeneration += 1; render(); + // Play on the last frame starts the movie over; it used to end at once + // with "finished" (EVO-15). + if (state.frameIndex >= state.result.frames.length - 1) { + var generation = state.playbackGeneration; + void seek(0).then(function () { + if (state.playing && generation === state.playbackGeneration) { + updatePlaybackOverlay(state.result.frames[state.frameIndex], state.result.frames.length, true); + void scheduleNext(generation); + } + }); + return true; + } updatePlaybackOverlay(state.result.frames[state.frameIndex], state.result.frames.length, true); void scheduleNext(state.playbackGeneration); return true; @@ -73,7 +85,10 @@ // Repaints both speed rows (panel + companion) so they show which speed // the movie is actually running at. render(); - if (state.playing) { + // Only a countdown is restarted at the new speed. During a seek the + // chain re-arms itself once the frame lands, and restarting it here + // raced the seek and could skip a frame (EVO-15). + if (state.playing && !state.seekInFlight) { state.playbackGeneration += 1; void scheduleNext(state.playbackGeneration); } diff --git a/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs b/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs index 4af39cb5..c4eefe3c 100644 --- a/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs +++ b/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs @@ -102,8 +102,9 @@ function createAnalyzer() { calls: [], killed: [], respond: null, - async run(session) { + async run(session, options) { analyzer.calls.push({ + silent: options?.silent === true, id: session.id, targetPath: session.targetPath, targetName: session.targetName, @@ -206,8 +207,8 @@ async function withServices(options, body) { const { ExecutePython } = requireOut('core/analysis/python/executePython.js'); // Like the real spawner, the stub "kills" its analysis when the // job (or revision watchdog) signal it runs under aborts. - ExecutePython.prototype.executeAnalysis = function stubbedAnalysis(session) { - const work = analyzer.run(session); + ExecutePython.prototype.executeAnalysis = function stubbedAnalysis(session, options) { + const work = analyzer.run(session, options); const signal = launch.currentLaunchSignal(); if (!signal) { return work; @@ -665,7 +666,7 @@ test('S6: cancelling a movie kills its analyses, discards it, frees the job and // No second revision was written; the first movie is still current. assert.deepEqual(fs.readdirSync(path.join(session.staticRoot, 'evolution')), ['revision-1']); - const applied = await evolution.applyFrameToBridge(1, 0); + const applied = evolution.resolveFrame(1, 0); assert.equal(applied.revision, 1); // A killed analysis is never recorded as a fact about the revision. assert.deepEqual((await evolution.getReferences()).eligibility?.excludedSources || [], []); @@ -687,9 +688,10 @@ test('S6: Clear during a generation cancels it and waits, so no late movie lands analyzer.respond = () => new Promise(() => {}); const movie = evolution.generate({ mode: 'manual', sourceIds: [c2, 'working-copy'] }, () => {}); await waitFor(() => analyzer.calls.length > 0); + const outcome = assert.rejects(movie, JobCancelledError); await evolution.clearGeneratedMovie(); assert.equal(evolution.isBusy(), false, 'Clear returned only once the job had ended'); - await assert.rejects(movie, JobCancelledError); + await outcome; const evolutionDirectory = path.join(session.staticRoot, 'evolution'); assert.deepEqual(fs.existsSync(evolutionDirectory) ? fs.readdirSync(evolutionDirectory) : [], []); await evolution.dispose(); @@ -789,7 +791,8 @@ test('evolution generate (file): missing target cached and excluded per frame, p [2, result.frames[2].source.label, '/evolution/revision-1/data3.json', 1, false, ''], ]); assert.equal(result.manifestUrl, '/evolution/revision-1/manifest.json'); - assert.equal(result.bridgeUrl, '/evolution/revision-1/data.json'); + // EVO-5: no shared bridge file; every frame is loaded by its own url. + assert.equal(result.bridgeUrl, undefined); assert.deepEqual(result.excludedSources, [{ id: commit(fixture.shas.c1).id, label: commit(fixture.shas.c1).label, @@ -800,7 +803,7 @@ test('evolution generate (file): missing target cached and excluded per frame, p }]); const directory = path.join(session.staticRoot, 'evolution', 'revision-1'); - assert.deepEqual(fs.readdirSync(directory).sort(), ['data.json', 'data1.json', 'data2.json', 'data3.json', 'manifest.json']); + assert.deepEqual(fs.readdirSync(directory).sort(), ['data1.json', 'data2.json', 'data3.json', 'manifest.json']); assert.deepEqual(readJson(path.join(directory, 'data1.json')), [ { functionName: 'run', parameters: 1, ccn: 2, evolutionKey: 'function:run' }, { functionName: 'run', parameters: 1, ccn: 1, evolutionKey: 'function:run' }, @@ -808,10 +811,13 @@ test('evolution generate (file): missing target cached and excluded per frame, p { name: 'NamedOnly', ccn: 1, evolutionKey: 'function:namedonly' }, ]); assert.deepEqual(readJson(path.join(directory, 'data3.json')), [{ functionName: 'Live', parameters: 0, evolutionKey: 'function:live' }]); - assert.deepEqual(readJson(path.join(directory, 'data.json')), readJson(path.join(directory, 'data1.json'))); assert.deepEqual(readJson(path.join(directory, 'manifest.json')), JSON.parse(JSON.stringify(result))); assert.equal(progress[0].message, 'Resolving project timeline...'); + // EVO-14: `completed` only grows and reaches the revision count. + const completedSeen = progress.filter((entry) => entry.completed !== undefined).map((entry) => entry.completed); + assert.deepEqual(completedSeen, [...completedSeen].sort((a, b) => a - b)); + assert.equal(Math.max(...completedSeen), 4); assert.equal(progress[1].message, 'Analyzing 4 project revisions with 4 workers...'); assert.ok(progress.some((entry) => entry.message === `Discarded ${commit(fixture.shas.c1).label}: The analyzed target does not exist in this revision.`)); assert.match(progress.at(-1).jobId, /^job-/); @@ -831,12 +837,17 @@ test('evolution generate (file): missing target cached and excluded per frame, p assert.ok(analyzer.calls.every((call) => 'projectEvolutionSource' in call.metadata)); assert.ok(analyzer.calls.every((call) => posix(call.targetPath).startsWith(posix(path.join(context.storageUri.fsPath, 'project-evolution', 'sess-file', 'snapshots'))))); assert.deepEqual([...materialized].sort(), [fixture.shas.c1, fixture.shas.c2, fixture.shas.c3].sort()); - - // The frame bridge copies dataN.json over data.json for the current revision only. - assert.deepEqual(await service.applyFrameToBridge(1, 1), { revision: 1, frameIndex: 1, bridgeUrl: '/evolution/revision-1/data.json' }); - assert.deepEqual(readJson(path.join(directory, 'data.json')), readJson(path.join(directory, 'data2.json'))); - await assert.rejects(service.applyFrameToBridge(2, 0), /^Error: project-evolution-invalid-revision$/); - await assert.rejects(service.applyFrameToBridge(1, -1), /^Error: project-evolution-invalid-frame$/); + // EVO-8: no VS Code notification per revision, and no snapshot is + // left on disk once its revision is analyzed. + assert.ok(analyzer.calls.every((call) => call.silent), 'revision analyses run silently'); + const snapshotRoot = path.join(context.storageUri.fsPath, 'project-evolution', 'sess-file', 'snapshots'); + assert.deepEqual(fs.existsSync(snapshotRoot) ? fs.readdirSync(snapshotRoot) : [], []); + + // EVO-5: a frame resolves to its own file; nothing is copied. + assert.deepEqual(service.resolveFrame(1, 1), { revision: 1, frameIndex: 1, frameUrl: '/evolution/revision-1/data2.json' }); + assert.throws(() => service.resolveFrame(2, 0), /^Error: project-evolution-invalid-revision$/); + assert.throws(() => service.resolveFrame(1, -1), /^Error: project-evolution-invalid-frame$/); + assert.throws(() => service.resolveFrame(1, 3), /^Error: project-evolution-invalid-frame$/); // Second run: every commit (including the missing one) is cached. const second = await service.generate({ mode: 'manual', sourceIds: ids }, () => {}); @@ -846,10 +857,12 @@ test('evolution generate (file): missing target cached and excluded per frame, p assert.equal(second.excludedSources.length, 1); assert.deepEqual((await service.getReferences()).activeRequest, { mode: 'manual', sourceIds: ids }); - // Clearing removes the current revision folder and the cache. + // EVO-11: one movie on disk, so an export ships the current one. + assert.deepEqual(fs.readdirSync(path.join(session.staticRoot, 'evolution')), ['revision-2']); + + // Clearing removes every movie and the cache. await service.clearGeneratedMovie(); - assert.equal(fs.existsSync(path.join(session.staticRoot, 'evolution', 'revision-2')), false); - assert.equal(fs.existsSync(path.join(session.staticRoot, 'evolution', 'revision-1')), true); + assert.equal(fs.existsSync(path.join(session.staticRoot, 'evolution')), false); assert.equal((await service.getReferences()).activeRequest, null); await service.generate({ mode: 'manual', sourceIds: ids }, () => {}); assert.equal(analyzer.calls.length, 4, 'the cache was cleared'); @@ -1296,11 +1309,11 @@ test('evolution bridge: a cancelled movie is silent; clear and apply-frame repor throw new JobCancelledError('cancelled', 'project-evolution-cancelled'); }, async clearGeneratedMovie() {}, - async applyFrameToBridge(revision, frameIndex) { + resolveFrame(revision, frameIndex) { if (frameIndex < 0) { throw new Error('project-evolution-invalid-frame'); } - return { revision, frameIndex, bridgeUrl: 'u' }; + return { revision, frameIndex, frameUrl: 'u' }; }, }), }); @@ -1320,8 +1333,10 @@ test('evolution bridge: a cancelled movie is silent; clear and apply-frame repor await bridge.handleProjectEvolutionApplyFrameMessage(applied, { payload: { revision: '2', frameIndex: 1, requestId: 'r1' } }); await bridge.handleProjectEvolutionApplyFrameMessage(applied, { payload: { revision: 2, frameIndex: -1, requestId: 7 } }); assert.deepEqual(applied.log, [ - ['broadcast', { type: 'project-evolution-frame-applied', payload: { revision: 2, frameIndex: 1, bridgeUrl: 'u', requestId: 'r1' } }], - ['broadcast', { type: 'project-evolution-error', payload: { code: 'project-evolution-invalid-frame', message: 'project-evolution-invalid-frame' } }], + // The room follows the seek; 1.2.0 scenes read bridgeUrl. + ['broadcast', { type: 'project-evolution-frame-applied', payload: { revision: 2, frameIndex: 1, frameUrl: 'u', bridgeUrl: 'u', requestId: 'r1' } }], + // A bad seek is the requester's alone (EVO-5): it no longer stops the room. + ['send', { type: 'project-evolution-error', payload: { code: 'project-evolution-invalid-frame', message: 'project-evolution-invalid-frame' } }], ]); coordinatorCalls.length = 0; @@ -1361,3 +1376,58 @@ test('S6 bridges: Cancel stops the job for the whole room, or tells only the req assert.equal(new ProjectEvolutionBridge(createHost({})).handleProjectEvolutionCancelMessage(room), false); }); }); + +test('S10: manual picks play oldest first, and more than the frame limit is refused out loud (EVO-13)', async () => { + const session = makeSession(); + writeWorkingCopy(session, [{ filePath: 'main.js', totalLines: 1 }]); + await withServices({ sessions: [session] }, async ({ ProjectEvolutionService, context, analyzer }) => { + analyzer.respond = () => [{ filePath: 'main.js', totalLines: 1 }]; + const evolution = new ProjectEvolutionService(context, session.id, session.staticRoot, createCatalog()); + const refs = await evolution.getReferences(); + const commitId = (sha) => refs.sources.find((s) => s.kind === 'gitRef' && s.commitSha === sha && s.refType === 'commit').id; + // Picked newest first, with the working copy in the middle. + const movie = await evolution.generate({ + mode: 'manual', + sourceIds: [commitId(fixture.shas.c3), 'working-copy', commitId(fixture.shas.c2)], + }, () => {}); + assert.deepEqual( + movie.frames.map((frame) => (frame.source.kind === 'workingCopy' ? 'working-copy' : frame.source.commitSha)), + [fixture.shas.c2, fixture.shas.c3, 'working-copy'], + ); + const tooMany = Array.from({ length: 25 }, () => commitId(fixture.shas.c2)); + await assert.rejects( + evolution.generate({ mode: 'manual', sourceIds: tooMany, maxFrames: 24 }, () => {}), + /A manual movie has at most 24 frames and 25 were picked\. Remove 1 and generate again\./, + ); + await evolution.dispose(); + }); +}); + +test('S10: the remote HEAD alias is not offered as a branch named after the remote (EVO-18)', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-remote-head-')); + try { + const repo = path.join(root, 'repo'); + fs.mkdirSync(repo, { recursive: true }); + runGit(repo, ['init', '--quiet']); + runGit(repo, ['config', 'user.name', 'CodeXR Tests']); + runGit(repo, ['config', 'user.email', 'codexr-tests@example.invalid']); + runGit(repo, ['config', 'commit.gpgsign', 'false']); + fs.writeFileSync(path.join(repo, 'main.js'), 'export const main = 1;\n'); + runGit(repo, ['add', '.']); + runGit(repo, ['commit', '--quiet', '-m', 'first']); + const head = runGit(repo, ['rev-parse', 'HEAD']); + runGit(repo, ['update-ref', 'refs/remotes/origin/main', head]); + runGit(repo, ['symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main']); + const { GitRepositoryService } = require(path.join(projectRoot, 'out', 'core', 'history', 'gitRepositoryService.js')); + const service = new GitRepositoryService(path.join(repo, 'main.js'), path.join(root, 'snapshots')); + const branches = (await service.listReferences()).sources + .filter((source) => source.kind === 'gitRef' && source.refType === 'branch') + .map((source) => source.refName); + assert.ok(branches.includes('refs/remotes/origin/main'), JSON.stringify(branches)); + // Its short name is just "origin", which the old filter let through. + assert.ok(!branches.some((refName) => refName.endsWith('/HEAD')), JSON.stringify(branches)); + await service.dispose(); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/vscode-extension/test/analysis/historicalComparison.test.cjs b/apps/vscode-extension/test/analysis/historicalComparison.test.cjs index 3f90add9..ffac6fc7 100644 --- a/apps/vscode-extension/test/analysis/historicalComparison.test.cjs +++ b/apps/vscode-extension/test/analysis/historicalComparison.test.cjs @@ -446,17 +446,22 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(service, /Analyzing \$\{sources\.length\} project revisions with \$\{concurrency\} workers/); assert.match(service, /references\.sources\.filter\(\(source\) => source\.kind === 'gitRef'\)/); assert.match(service, /'project-evolution'/); - assert.match(service, /path\.join\(this\.staticRoot, 'evolution'\)/); + assert.match(service, /path\.resolve\(staticRoot, 'evolution'\)/); assert.match(service, /path\.join\(evolutionDirectory, `revision-\$\{revision\}`\)/); assert.match(service, /const fileName = `data\$\{index \+ 1\}\.json`/); - assert.match(service, /bridgeUrl: `\/evolution\/revision-\$\{revision\}\/data\.json`/); - assert.match(service, /path\.join\(revisionDirectory, 'data\.json'\)/); - assert.match(service, /applyFrameToBridge/); - assert.match(service, /copyFileAtomically/); + // EVO-5: no shared data.json bridge; a frame is resolved to its own file. + assert.doesNotMatch(service, /bridgeUrl: `/); + assert.doesNotMatch(service, /'data\.json'/); + assert.doesNotMatch(service, /copyFileAtomically|applyFrameToBridge/); + assert.match(service, /public resolveFrame\(/); + assert.match(service, /frameUrl: `\/evolution\/revision-\$\{safeRevision\}\/data\$\{safeFrameIndex \+ 1\}\.json`/); + // EVO-11: one movie on disk. + assert.match(service, /removeOtherEvolutionRevisions\(evolutionDirectory, revision\)/); assert.match(service, /manifest\.json/); assert.match(service, /Project evolution ready\./); assert.match(service, /clearGeneratedMovie/); assert.match(service, /fs\.promises\.rm\(revisionDirectory, \{ recursive: true, force: true \}\)/); + assert.match(service, /fs\.promises\.rm\(this\.resolveEvolutionDirectory\(\), \{ recursive: true, force: true \}\)/); assert.match(service, /cancelAndWait/); // Frame selection is the shared sampler (even spacing in time, milestones // preferred), and the movie always ends on the current state of the branch — @@ -489,7 +494,7 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(server, /removeSharedEntity\('project-evolution', 'main'\)/); assert.match(server, /type: 'project-evolution-cleared'/); assert.match(server, /message\.type === 'project-evolution-apply-frame'/); - assert.match(server, /projectEvolutionService\.applyFrameToBridge/); + assert.match(server, /projectEvolutionService\.resolveFrame\(revision, frameIndex\)/); assert.match(server, /type: 'project-evolution-frame-applied'/); assert.match(server, /message\.type === 'project-evolution-start'/); assert.match(server, /changeAnalysisViewMode\('project-evolution', 'project-evolution'\);/); diff --git a/apps/vscode-extension/test/analysis/projectEvolutionRuntime.test.cjs b/apps/vscode-extension/test/analysis/projectEvolutionRuntime.test.cjs index f43105dc..d21390fc 100644 --- a/apps/vscode-extension/test/analysis/projectEvolutionRuntime.test.cjs +++ b/apps/vscode-extension/test/analysis/projectEvolutionRuntime.test.cjs @@ -63,9 +63,14 @@ test('project evolution owns one declarative datasource and a direct tree-chart assert.doesNotMatch(runtimeSource, /setAttribute\(pipeline\.componentName, data\)/); assert.doesNotMatch(runtimeSource, /emit\('data-loaded'/); assert.match(runtimeSource, /function waitForComponent\(element, componentName, timeoutMs\)/); - assert.match(runtimeSource, /await waitForComponent\(dataSource, 'babia-queryjson', 1200\)/); - assert.match(runtimeSource, /await waitForComponent\(treeBuilder, EVOLUTION_TREE_COMPONENT, 1200\)/); - assert.match(runtimeSource, /await waitForComponent\(chart, componentName, 1200\)/); + assert.match(runtimeSource, /await waitForComponent\(dataSource, 'babia-queryjson', PIPELINE_COMPONENT_TIMEOUT_MS\)/); + assert.match(runtimeSource, /await waitForComponent\(treeBuilder, EVOLUTION_TREE_COMPONENT, PIPELINE_COMPONENT_TIMEOUT_MS\)/); + assert.match(runtimeSource, /await waitForComponent\(chart, componentName, PIPELINE_COMPONENT_TIMEOUT_MS\)/); + assert.match(runtimeSource, /var PIPELINE_COMPONENT_TIMEOUT_MS = 4000/); + // LIFECYCLE-4: a half-built pipeline is torn down whole, never left as a + // root without a chart. + assert.equal((runtimeSource.match(/return failEvolutionPipeline\(/g) || []).length, 3); + assert.match(runtimeSource, /function failEvolutionPipeline\(message, viewGeneration\) \{[\s\S]{0,200}releaseEvolutionVisualization\(\);/); assert.match(runtimeSource, /configureDeclarativeChartEntity\?\.\(/); // The git-ref-picker runtime is presentation chrome: every describeSource // use goes through the guarded helper, so a missing picker can no longer @@ -125,7 +130,7 @@ test('project evolution namespaces stable boats identities away from other analy assert.match(runtimeSource, /buffer\.__codexrEvolutionNamespace = MODE/); }); -test('project evolution bridge URL is cache-busted without changing its path', () => { +test('project evolution frame URL is the frame\'s own file, cache-busted (EVO-5)', () => { const runtime = loadRuntime(); const url = runtime.__testing.frameUrlWithCache({ @@ -133,7 +138,7 @@ test('project evolution bridge URL is cache-busted without changing its path', ( url: '/evolution/revision-3/data4.json', }, '/evolution/revision-3/data.json'); - assert.match(url, /^\/evolution\/revision-3\/data\.json\?/); + assert.match(url, /^\/evolution\/revision-3\/data4\.json\?/); assert.match(url, /revision=/); assert.match(url, /frame=4/); assert.match(url, /t=123456789/); @@ -334,14 +339,18 @@ function loadRuntimeWithClient(clientStub) { return sandbox.CodeXRProjectEvolutionRuntime; } -test('offline export plays each frame from its own file; online keeps the bridge preference', () => { +test('every frame plays from its own file, online and offline (EVO-5)', () => { const frame = { index: 3, url: '/evolution/revision-3/data4.json' }; const appliedBridgeUrl = '/evolution/revision-3/data.json'; - // Online (no offline flag): the bridge URL wins, exactly as before. + // Online: the frame's own immutable file wins over the old shared bridge, + // which raced between players seeking at once. const online = loadRuntimeWithClient({ isOfflineExport: () => false, sendMessage: () => true }); const onlineUrl = online.__testing.frameUrlWithCache(frame, appliedBridgeUrl); - assert.match(onlineUrl, /^\/evolution\/revision-3\/data\.json\?/); + assert.match(onlineUrl, /^\/evolution\/revision-3\/data4\.json\?/); + // A 1.2.0 movie whose frames carry no url still falls back to the bridge. + const legacyUrl = online.__testing.frameUrlWithCache({ index: 3 }, appliedBridgeUrl); + assert.match(legacyUrl, /^\/evolution\/revision-3\/data\.json\?/); // Offline: the same call must point at the frame's own pre-generated file, // because no server exists to swap the bridge content. @@ -579,3 +588,27 @@ test('offline generation is wired through the panel, and the no-git replay path assert.match(runtimeSource, /replays the movie generated before export/); assert.match(runtimeSource, /replay-only: it cannot be cleared or regenerated here/); }); + +test('S10: progress only grows, Play at the end restarts, replays keep the frame, picks past the limit are refused', () => { + // EVO-14: the bar shows revisions FINISHED and never goes back. + assert.match(runtimeSource, /state\.generationCompleted = Math\.min\(count, Math\.max\(state\.generationCompleted \|\| 0, reported\)\)/); + assert.match(runtimeSource, /'Analyzed ' \+ done \+ ' \/ ' \+ count \+ ' revisions'/); + assert.doesNotMatch(runtimeSource, /'Generating frame ' \+/); + // EVO-15: Play on the last frame starts over; a speed change never + // restarts the chain under a seek; a replay of the same movie keeps the + // frame instead of jumping to frame 1. + assert.match(runtimeSource, /if \(state\.frameIndex >= state\.result\.frames\.length - 1\) \{\s*var generation = state\.playbackGeneration;\s*void seek\(0\)/); + assert.match(runtimeSource, /if \(state\.playing && !state\.seekInFlight\) \{/); + assert.match(runtimeSource, /state\.seekInFlight \+= 1;[\s\S]{0,120}finally \{\s*state\.seekInFlight = Math\.max\(0, state\.seekInFlight - 1\);/); + assert.match(runtimeSource, /if \(!sameMovie\) \{\s*state\.frameIndex = 0;/); + assert.match(runtimeSource, /return seek\(state\.frameIndex\);/); + // EVO-1: a shared movie arriving ends the "generating" state too. + assert.match(runtimeSource, /state\.jobRunning = false;\s*state\.generating = false;\s*renderGenerationProgress\(\{ state: 'idle' \}\);\s*\/\/ A replay/); + // EVO-13: the limit is said when the user picks past it. + assert.match(runtimeSource, /'A manual movie has at most ' \+ limit \+ ' frames\. Remove one to add another\.'/); +}); + +test('S10: a frame applied by another participant loads that frame\'s own file', () => { + assert.match(runtimeSource, /applyBridgeFrameToChart\(frames\[state\.frameIndex\], payload\.frameUrl \|\| payload\.bridgeUrl, viewGeneration\)/); + assert.match(runtimeSource, /applied\.frameUrl \|\| applied\.bridgeUrl,/); +}); diff --git a/apps/vscode-extension/test/runners/run-project-evolution-harness.cjs b/apps/vscode-extension/test/runners/run-project-evolution-harness.cjs index 003d5cd5..314ec67a 100644 --- a/apps/vscode-extension/test/runners/run-project-evolution-harness.cjs +++ b/apps/vscode-extension/test/runners/run-project-evolution-harness.cjs @@ -69,12 +69,10 @@ function writeFixtureFiles() { 'utf8', ); }); - fs.copyFileSync(path.join(revisionRoot, 'data1.json'), path.join(revisionRoot, 'data.json')); fs.writeFileSync( path.join(revisionRoot, 'manifest.json'), `${JSON.stringify({ revision: 1, - bridgeUrl: '/output/project-evolution-harness/evolution/revision-1/data.json', frames: framePayloads.map((payload, index) => ({ index, url: `/output/project-evolution-harness/evolution/revision-1/data${index + 1}.json`, @@ -85,8 +83,11 @@ function writeFixtureFiles() { ); } -function readBridgePayload() { - return JSON.parse(fs.readFileSync(path.join(revisionRoot, 'data.json'), 'utf8')); +// EVO-5: each frame is loaded from its own immutable dataN.json; there is no +// shared data.json bridge left to read back. +function assertFrameLoaded(metrics, frameNumber, message) { + assert.match(JSON.stringify(metrics.dataUrl), new RegExp(`/data${frameNumber}\\.json\\?`), message); + assert.equal(fs.existsSync(path.join(revisionRoot, 'data.json')), false, 'no bridge file is ever written'); } function contentType(filePath) { @@ -104,21 +105,15 @@ function createServer() { if (requestUrl.pathname === '/__project_evolution_apply_frame') { const frameIndex = Number(requestUrl.searchParams.get('frameIndex') || 0); const sourcePath = path.join(revisionRoot, `data${frameIndex + 1}.json`); - const bridgePath = path.join(revisionRoot, 'data.json'); if (!Number.isInteger(frameIndex) || frameIndex < 0 || !fs.existsSync(sourcePath)) { response.writeHead(400, { 'content-type': 'application/json' }); response.end(JSON.stringify({ error: 'invalid-frame' })); return; } - const tmpPath = `${bridgePath}.${process.pid}.tmp`; - fs.copyFileSync(sourcePath, tmpPath); - fs.renameSync(tmpPath, bridgePath); + // Like ProjectEvolutionService.resolveFrame: validate, copy nothing. + const frameUrl = `/output/project-evolution-harness/evolution/revision-1/data${frameIndex + 1}.json`; response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }); - response.end(JSON.stringify({ - revision: 1, - frameIndex, - bridgeUrl: '/output/project-evolution-harness/evolution/revision-1/data.json', - })); + response.end(JSON.stringify({ revision: 1, frameIndex, frameUrl, bridgeUrl: frameUrl })); return; } @@ -151,9 +146,9 @@ async function validateBridge(port) { const applyUrl = `http://127.0.0.1:${port}/__project_evolution_apply_frame?revision=1&frameIndex=2`; const response = await fetch(applyUrl); assert.equal(response.status, 200); - const payload = JSON.parse(fs.readFileSync(path.join(revisionRoot, 'data.json'), 'utf8')); - assert.equal(payload.length, framePayloads[2].length); - fs.copyFileSync(path.join(revisionRoot, 'data1.json'), path.join(revisionRoot, 'data.json')); + const payload = await response.json(); + assert.equal(payload.frameUrl, '/output/project-evolution-harness/evolution/revision-1/data3.json'); + assert.equal(fs.existsSync(path.join(revisionRoot, 'data.json')), false); } async function runPlaywrightIfAvailable(port) { @@ -200,7 +195,7 @@ async function runScenario(browser, port) { assert.equal(metrics.treeParentId, 'codexrProjectEvolutionRoot'); assert.equal(metrics.chartParentId, 'codexrProjectEvolutionRoot'); assert.equal(metrics.hasLegacySurface, false); - assert.match(metrics.dataHtml, /babia-queryjson="url: .*data\.json/); + assert.match(metrics.dataHtml, /babia-queryjson="url: .*data1\.json/); assert.match(metrics.treeHtml, /babia-treebuilder="field: filePath/); assert.match(metrics.treeHtml, /from: codexrProjectEvolutionData/); assert.match(metrics.chartHtml, /babia-boats="[^"]*from: codexrProjectEvolutionTree/); @@ -208,8 +203,7 @@ async function runScenario(browser, port) { assert.match(metrics.chartHtml, /codexr-boats-layout-stability="enabled: true"/); assert.match(metrics.chartHtml, /codexr-chart-containment="enabled: true/); assert.ok(metrics.chartChildren > 0, 'expected chart geometry after frame 1'); - assert.match(JSON.stringify(metrics.dataUrl), /data\.json/); - assert.deepEqual(readBridgePayload(), framePayloads[0], 'data.json must contain frame 1'); + assertFrameLoaded(metrics, 1, 'frame 1 is loaded from data1.json'); const frameOneMeshes = metrics.chartMeshes; const frameOneNodeToken = metrics.chartNodeToken; @@ -263,7 +257,7 @@ async function runScenario(browser, port) { ); assert.ok(metrics.figuresOldCount > 0, 'Babia must retain figures_old for the frame transition'); assert.equal(metrics.chartAnimating, false, 'the frame transition must finish before containment settles'); - assert.deepEqual(readBridgePayload(), framePayloads[1], 'data.json must contain frame 2'); + assertFrameLoaded(metrics, 2, 'frame 2 is loaded from data2.json'); assert.ok( metrics.chartScale.y >= frameOneYScale * 0.25 && metrics.chartScale.y <= frameOneYScale * 4, @@ -319,7 +313,7 @@ async function runScenario(browser, port) { `frame 3 Boats bases must retain local height 0.2: ${metrics.greenLayerLocalHeights.join(', ')}`, ); assert.equal(metrics.boatsStyle.zoneElevation, 0.01); - assert.deepEqual(readBridgePayload(), framePayloads[2], 'data.json must contain frame 3'); + assertFrameLoaded(metrics, 3, 'frame 3 is loaded from data3.json'); await page.click('[data-testid="frame-1"]'); await page.waitForTimeout(4500); metrics = await page.evaluate(() => window.CodeXRProjectEvolutionHarness.updateStatus()); @@ -331,7 +325,7 @@ async function runScenario(browser, port) { ); assert.equal(metrics.chartNodeToken, frameOneNodeToken, 'seeking back must keep the chart identity'); assert.equal(metrics.chartComponentToken, frameOneComponentToken, 'seeking back must keep Babia'); - assert.deepEqual(readBridgePayload(), framePayloads[0], 'data.json must return to frame 1'); + assertFrameLoaded(metrics, 1, 'seeking back loads data1.json again'); await page.click('[data-testid="frame-2"]'); await page.waitForTimeout(4500); @@ -364,9 +358,8 @@ async function runScenario(browser, port) { assert.equal(metrics.runtime.frameIndex, 0); // Paused chart selection replaces only the chart. It must not seek, - // refresh the datasource, or overwrite the bridge payload. + // refresh the datasource, or load another frame file. const pausedDataUrl = JSON.stringify(metrics.dataUrl); - const pausedBridgePayload = readBridgePayload(); const pausedDataToken = metrics.dataNodeToken; const pausedTreeToken = metrics.treeNodeToken; const pausedChartToken = metrics.chartNodeToken; @@ -383,7 +376,6 @@ async function runScenario(browser, port) { assert.match(metrics.chartHtml, /babia-bars="[^"]*from: codexrChartDataSlice__codexrProjectEvolutionData/); assert.match(metrics.chartHtml, /x_axis: fileName/); assert.equal(JSON.stringify(metrics.dataUrl), pausedDataUrl, 'the datasource URL must not refresh'); - assert.deepEqual(readBridgePayload(), pausedBridgePayload, 'data.json must not change'); assert.deepEqual(metrics.normalChartTransform, normalChartTransform); assert.deepEqual(metrics.duplicateIds, []); await page.waitForFunction( @@ -409,7 +401,7 @@ async function runScenario(browser, port) { assert.equal(metrics.chartNodeToken, barsChartToken, 'the selected chart persists into later frames'); assert.equal(metrics.chartComponentToken, barsComponentToken, 'the selected Babia instance persists'); assert.deepEqual(metrics.rootChildren, ['codexrProjectEvolutionTree', 'codexrProjectEvolutionChart']); - assert.deepEqual(readBridgePayload(), framePayloads[1]); + assertFrameLoaded(metrics, 2, 'later frames load their own file with the new chart'); // Leaving parks the complete pipeline. Re-entry restores the exact entities // and frame without asking the server to apply it again.