Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
910791f
chore(release): merge main into staging [skip ci]
github-actions[bot] Nov 14, 2026
6d1f21b
fix(viewer): leave ⌘/Ctrl/Alt key combinations to the browser during …
hyamero Nov 14, 2026
18276f9
fix(cli): fall back to explorer.exe on WSL when PowerShell is blocked…
hyamero Nov 14, 2026
41e208f
docs(site): wait for the search index's failed fetch before the e2e r…
hyamero Nov 14, 2026
f965439
fix(layout): wrap a diagram on the axis the fold shortens, and only w…
hyamero Nov 14, 2026
1edb243
fix(layout): put a fan-out or fan-in label at the end of its run near…
hyamero Nov 14, 2026
a30aa6c
refactor(layout): share the large-diagram limit with validation from …
hyamero Nov 14, 2026
0e7894c
refactor(layout): have isLarge itself rule out the kinds with their o…
hyamero Nov 14, 2026
0b9f46f
feat(schema): warn when a group beside phases can lie across their bands
hyamero Nov 14, 2026
9ed8a81
fix(layout): keep later lane routes off the whole end run of an earli…
hyamero Nov 14, 2026
3e1ff1d
fix(cli): wait for macOS open to hand the file off before exiting
hyamero Nov 15, 2026
81716dc
feat(viewer): link the stackmap mark in the header to the website
hyamero Nov 15, 2026
59db314
feat(viewer): export the diagram again as one offline HTML file
hyamero Nov 15, 2026
29433a3
test(viewer): walk two more Tab stops past the header's stackmap link
hyamero Nov 15, 2026
07a32e0
refactor(viewer): hold trace and route picking as one explorer mode
hyamero Nov 19, 2026
31d9397
refactor(viewer): keep focus, presentation and the hidden toolbar in …
hyamero Nov 19, 2026
44ef3c5
fix(viewer): close the type filter when search opens from beside the …
hyamero Nov 19, 2026
1acdb24
fix(viewer): clear the last export's error when the export menu opens…
hyamero Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ The agent writes `.stackmap/<name>/diagram.json`, validates and repairs it, and
- **Find:** search titles, ids and types; the **lens** dims the node types you don't need.
- **Guided views:** tabs the agent defines, like "Checkout path", that focus one part of the diagram. **Present** steps through them full screen.
- **Flow:** **Play** sends pulses along whatever you're looking at: the whole diagram, a view, a trace or a route, hop by hop.
- **Share:** the URL keeps the view, selection, route and playback. Export PNG, JPEG, WebP, SVG, or a short video of the flow.
- **Share:** the URL keeps the view, selection, route and playback. Export PNG, JPEG, WebP, SVG, a short video of the flow, or the diagram again as one offline HTML file.
- **Keyboard:** `/` search, `R` route, `F` present, `P` play, `M` minimap, `Esc` clear; Tab and the arrow keys reach everything else.
- **Themes:** dark and light, and animations respect reduced motion.

Expand Down
24 changes: 23 additions & 1 deletion packages/cli/e2e/offline.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -28,6 +28,28 @@ test('a delivered file renders from file:// with no network', async ({ page }) =
expect(requests).toEqual([]);
});

test('Export saves the delivered page as HTML that opens offline, and the mark links to the website', async ({ page }) => {
const dir = mkdtempSync(join(tmpdir(), 'stackmap-e2e-'));
const input = join(dir, 'platform.json');
writeFileSync(input, JSON.stringify(groupedPlatform));
execFileSync('node', [fileURLToPath(new URL('../dist/cli.js', import.meta.url)), 'deliver', input, '-o', join(dir, 'delivered.html')]);
await page.goto(pathToFileURL(join(dir, 'delivered.html')).href);
await expect(page.locator('.sm-card')).toHaveCount(groupedPlatform.nodes.length);
await expect(page.getByRole('link', { name: /stackmap website/ })).toHaveAttribute('href', 'https://stackmap.omsimos.com/');

await page.getByRole('button', { name: 'Export' }).click();
const [dl] = await Promise.all([page.waitForEvent('download'), page.getByRole('menuitem', { name: /^HTML/ }).click()]);
expect(dl.suggestedFilename()).toBe('platform.html');
const saved = join(dir, 'saved.html');
await dl.saveAs(saved);
// The page as delivered, not as rendered: the viewer's own markup is left out and rebuilt on open.
expect(readFileSync(saved, 'utf8')).toMatch(/<div id="root"><\/div>/);

await page.goto(pathToFileURL(saved).href);
await expect(page.locator('.sm-card')).toHaveCount(groupedPlatform.nodes.length);
await expect(page).toHaveTitle('Platform · stackmap');
});

test('the bare template says no diagram is embedded', async ({ page }) => {
await page.goto(new URL('../dist/viewer.html', import.meta.url).href);
await expect(page.getByRole('status')).toHaveText(/No diagram embedded/);
Expand Down
14 changes: 13 additions & 1 deletion packages/cli/e2e/serve.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -51,6 +51,18 @@ test('edits reload the page; a broken edit keeps the last good version and says
await expect(toast).toHaveCount(0);
});

test('an HTML export of a served page is the offline file, without the live connection', async ({ page }) => {
await start(commerceApi);
await page.goto(url);
await expect(page.locator('.sm-card')).toHaveCount(commerceApi.nodes.length);
await page.getByRole('button', { name: 'Export' }).click();
const [dl] = await Promise.all([page.waitForEvent('download'), page.getByRole('menuitem', { name: /^HTML/ }).click()]);
const html = readFileSync((await dl.path())!, 'utf8');
expect(html).toContain('<script type="application/json" id="stackmap-data">{');
// The bundle names the block's id too; it's the element that must be gone.
expect(html).not.toContain('<script type="application/json" id="stackmap-live">');
});

test('the camera, selection and theme survive a live reload', async ({ page }) => {
await start(commerceApi);
await page.goto(url);
Expand Down
6 changes: 2 additions & 4 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { extname, resolve } from 'node:path';
import { isLaneKind } from '@stackmap/core';
import { isLarge, layoutDiagram } from '@stackmap/layout';
import { validateDiagram, type Diagnostic, type ValidationResult } from '@stackmap/schema';
import { embedDiagram } from './embed';
Expand Down Expand Up @@ -72,10 +71,9 @@ export async function buildHtml(
): Promise<ValidationResult & { html?: string }> {
const result = validateFile(path);
if (!result.ok || !result.diagram) return result;
const { kind, nodes, edges } = result.diagram;
const { nodes, edges } = result.diagram;
// The result only prints once the layout is done; without this a big diagram looks hung for minutes.
// Lane and sequence kinds have their own layouts, which take a second at their largest.
if (progress && !isLaneKind(kind) && kind !== 'sequence' && isLarge(result.diagram))
if (progress && isLarge(result.diagram))
progress(`laying out ${nodes.length} nodes and ${edges.length} connections; a diagram this size can take a while`);
return { ...result, html: embedDiagram(template, await layoutDiagram(result.diagram)) };
}
Expand Down
63 changes: 43 additions & 20 deletions packages/cli/src/open.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,54 @@
import { execFileSync, spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';

/**
* One way to open a file. `orAt` finds `cmd` when it isn't on the PATH. `startFile` is a file for PowerShell to
* start (WSL): its Windows path goes on the end of `args`, as an encoded command. `wait` is how long, in ms, the
* opener gets to exit before it counts as having handed the file off.
* start (WSL): its Windows path goes on the end of `args`, as an encoded command; `windowsFile` is one whose Windows
* path goes there as it is. `wait` is how long, in ms, the opener gets to exit before it counts as having handed the
* file off. `blind` marks an opener whose exit code says nothing, so that having started is all it can report.
*/
export type Opener = { cmd: string; args: string[]; orAt?: () => string; startFile?: string; wait?: number };
export type Opener = {
cmd: string;
args: string[];
orAt?: () => string;
startFile?: string;
windowsFile?: string;
wait?: number;
blind?: true;
};

const NOT_FOUND = 'not found';
// xdg-open can turn into the browser itself and never exit, so a short wait has to count as a hand-off.
const HANDED_OFF = 3000;
// A Windows program started through WSL interop can take longer than that to load, and its exit code is the only
// sign that nothing opened.
const WINDOWS_START = 15000;
// macOS `open` returns once the browser has the file, which can take seconds while the browser wakes. Exiting before
// then can leave it to be killed with the caller's shell (an agent's tool), so the file never opens and no warning shows.
const MAC_OPEN = 15000;

// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt.
function powershell(): string {
const inWindows = (path: string) => (): string => {
try {
return wslpath('-u', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe');
return wslpath('-u', `C:\\Windows\\${path}`);
} catch {
return '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
return `/mnt/c/Windows/${path.replaceAll('\\', '/')}`;
}
}
};

const INTEROP = ['/proc/sys/fs/binfmt_misc/WSLInterop', '/proc/sys/fs/binfmt_misc/WSLInterop-late'];

/** Whether this Linux is WSL, where a stock distro has no xdg-open but Windows has a browser. */
export function isWsl(env: NodeJS.ProcessEnv = process.env): boolean {
export function isWsl(
env: NodeJS.ProcessEnv = process.env,
read: (path: string) => string = (path) => readFileSync(path, 'utf8'),
has: (path: string) => boolean = existsSync,
): boolean {
if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
try {
return /microsoft/i.test(readFileSync('/proc/version', 'utf8'));
// A Docker Desktop container runs on the WSL kernel too, but only WSL itself registers the Windows interop.
return /microsoft/i.test(read('/proc/version')) && INTEROP.some(has);
} catch {
return false;
}
Expand All @@ -41,7 +60,7 @@ export function browserCommands(
platform: NodeJS.Platform = process.platform,
wsl = platform === 'linux' && isWsl(),
): Opener[] | { refused: string } {
if (platform === 'darwin') return [{ cmd: 'open', args: [file] }];
if (platform === 'darwin') return [{ cmd: 'open', args: [file], wait: MAC_OPEN }];
// `start` is a cmd builtin, and its first quoted argument is the window title.
// Quoted, cmd takes & | < > ^ ( ) literally; it still expands %VAR% inside quotes, and " would end the quoting.
if (platform === 'win32')
Expand All @@ -53,14 +72,16 @@ export function browserCommands(
// nothing, which would end the chain. PowerShell, unlike explorer.exe, exits non-zero when it couldn't start the file.
const start: Opener = {
cmd: 'powershell.exe',
orAt: powershell,
orAt: inWindows('System32\\WindowsPowerShell\\v1.0\\powershell.exe'),
args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'],
startFile: file,
wait: WINDOWS_START,
};
// wslview hands the path to PowerShell with quoting of its own, so it only gets paths PowerShell reads literally.
const viaWslview: Opener[] = /[$`'"‘’‚‛“”„]/.test(file) ? [] : [{ cmd: 'wslview', args: [file], wait: WINDOWS_START }];
return [...viaWslview, start, { cmd: 'xdg-open', args: [file] }];
// Where policy blocks PowerShell, explorer.exe still opens the file; it exits 1 either way.
const explorer: Opener = { cmd: 'explorer.exe', orAt: inWindows('explorer.exe'), args: [], windowsFile: file, wait: WINDOWS_START, blind: true };
return [...viaWslview, start, explorer, { cmd: 'xdg-open', args: [file] }];
}

export function startCommand(windowsPath: string): string {
Expand Down Expand Up @@ -96,23 +117,25 @@ export async function openWith(
}

async function run(
{ cmd, args, orAt, startFile, wait = HANDED_OFF }: Opener,
{ cmd, args, orAt, startFile, windowsFile, wait = HANDED_OFF, blind }: Opener,
windowsPath: (file: string) => string,
): Promise<string | null> {
if (startFile !== undefined) {
const file = startFile ?? windowsFile;
if (file !== undefined) {
try {
args = [...args, Buffer.from(startCommand(windowsPath(resolve(startFile))), 'utf16le').toString('base64')];
const path = windowsPath(resolve(file));
args = [...args, startFile === undefined ? path : Buffer.from(startCommand(path), 'utf16le').toString('base64')];
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'wslpath not found' : "wslpath couldn't convert the path";
}
}
let why = await launch(cmd, args, wait);
if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait);
let why = await launch(cmd, args, wait, blind);
if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait, blind);
return why === null ? null : `${cmd} ${why}`;
}

/** Resolves null once the command exits cleanly or is still running after `wait` ms, else what went wrong. */
function launch(cmd: string, args: string[], wait: number): Promise<string | null> {
function launch(cmd: string, args: string[], wait: number, blind = false): Promise<string | null> {
return new Promise((done) => {
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' });
const timer = setTimeout(() => done(null), wait);
Expand All @@ -121,7 +144,7 @@ function launch(cmd: string, args: string[], wait: number): Promise<string | nul
done(why);
};
child.once('error', (e) => finish((e as NodeJS.ErrnoException).code === 'ENOENT' ? NOT_FOUND : `failed (${e.message})`));
child.once('exit', (code, signal) => finish(code ? `exited with ${code}` : signal ? `was killed by ${signal}` : null));
child.once('exit', (code, signal) => finish(blind ? null : code ? `exited with ${code}` : signal ? `was killed by ${signal}` : null));
child.unref();
});
}
26 changes: 23 additions & 3 deletions packages/cli/test/open.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ const posix = it.skipIf(process.platform === 'win32');

describe('browserCommands', () => {
it('uses the native opener on darwin and linux', () => {
expect(browserCommands('/tmp/a b.html', 'darwin')).toEqual([{ cmd: 'open', args: ['/tmp/a b.html'] }]);
expect(browserCommands('/tmp/a b.html', 'darwin')).toEqual([{ cmd: 'open', args: ['/tmp/a b.html'], wait: 15000 }]);
expect(browserCommands('/tmp/a.html', 'linux', false)).toEqual([{ cmd: 'xdg-open', args: ['/tmp/a.html'] }]);
});

it('tries the Windows side first on WSL, and xdg-open last', () => {
const commands = browserCommands('/tmp/a.html', 'linux', true) as Opener[];
expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']);
expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'explorer.exe', 'xdg-open']);
expect(commands[2]).toMatchObject({ windowsFile: '/tmp/a.html', blind: true, args: [] });
// run() puts the encoded command straight after the last argument.
expect(commands[1]).toMatchObject({ startFile: '/tmp/a.html', orAt: expect.any(Function) });
expect(commands[1]!.args.at(-1)).toBe('-EncodedCommand');
Expand All @@ -24,7 +25,7 @@ describe('browserCommands', () => {
it('keeps a path PowerShell would expand or unquote away from wslview', () => {
for (const file of ['/home/u/$(x)/a.html', '/home/u/a`b.html', "/home/u/it's.html", '/home/u/a"b.html']) {
const commands = browserCommands(file, 'linux', true) as Opener[];
expect(commands.map((c) => c.cmd)).toEqual(['powershell.exe', 'xdg-open']);
expect(commands.map((c) => c.cmd)).toEqual(['powershell.exe', 'explorer.exe', 'xdg-open']);
}
});

Expand All @@ -50,6 +51,15 @@ describe('isWsl', () => {
expect(isWsl({ WSL_DISTRO_NAME: 'Ubuntu' })).toBe(true);
expect(isWsl({ WSL_INTEROP: '/run/WSL/1_interop' })).toBe(true);
});

it('takes a WSL kernel for WSL only where the Windows interop is registered', () => {
const kernel = () => 'Linux version 5.15.167.4-microsoft-standard-WSL2';
expect(isWsl({}, kernel, (path) => path.endsWith('/WSLInterop'))).toBe(true);
expect(isWsl({}, kernel, (path) => path.endsWith('/WSLInterop-late'))).toBe(true);
// A Docker Desktop container.
expect(isWsl({}, kernel, () => false)).toBe(false);
expect(isWsl({}, () => 'Linux version 6.8.0-generic', () => true)).toBe(false);
});
});

describe('startCommand', () => {
Expand Down Expand Up @@ -78,6 +88,16 @@ describe('openWith', () => {
expect(await openWith([{ cmd: MISSING, orAt: () => `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`);
});

it('takes a blind opener as having opened once it has run, whatever it exits with', async () => {
expect(await openWith([{ ...exits(1), blind: true }])).toBeNull();
expect(await openWith([{ cmd: MISSING, args: [], blind: true }])).toBe(`${MISSING} not found`);
});

posix('hands a windowsFile opener the Windows path itself', async () => {
const check = `process.exit(process.argv[1] === 'W:\\\\a.html' ? 0 : 7)`;
expect(await openWith([{ cmd: NODE, args: ['-e', check], windowsFile: '/home/u/a.html' }], () => 'W:\\a.html')).toBeNull();
});

it('waits as long as the opener asks before taking it as handed off', async () => {
const slow = { cmd: NODE, args: ['-e', 'setTimeout(() => process.exit(1), 1000)'] };
expect(await openWith([{ ...slow, wait: 100 }])).toBeNull();
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/diagram-stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export const TYPE_LABELS: Record<NodeType, string> = {
neutral: 'Neutral',
};

/** Past this many nodes validation warns to split the diagram, and the layout takes its cheaper settings. */
export const LARGE_DIAGRAM = 60;

export function countByType(nodes: DiagramNode[]): [NodeType, number][] {
const counts = new Map<NodeType, number>();
for (const n of nodes) counts.set(n.type, (counts.get(n.type) ?? 0) + 1);
Expand Down
Loading
Loading