Files
open-design/apps/daemon/tests/mcp-get-artifact.test.ts
809d45f27c feat(integrations): add the local Open Design Cloud flow for Codex (#6055)
* feat(daemon): expose Vela login through CLI and MCP

* feat(mcp): add interactive local brief card

* feat(packaged): bootstrap local MCP headlessly

* feat(daemon): secure local BYOK credential profiles

* feat(cli): manage secure BYOK profiles

* feat(web): store BYOK keys in secure profiles

* fix(runs): deduplicate cloud generation requests

* feat(daemon): add end-to-end plugin observability

* fix(pack): include native PTY runtime in desktop packages

Lazy-load node-pty in the daemon so missing native binaries only
disable Terminal and interactive Keychain operations instead of
crashing startup.

Ship and validate target prebuilds in macOS and Windows packages.
Repair the macOS spawn helper before signing, and invalidate stale
Windows packaging caches.

Cover the packaged PTY path in macOS and Windows smoke tests. Require
Vela CLI for every beta desktop build target.

* fix(mcp): localize and stabilize plugin briefs

Keep collect and confirm on one MCP Apps card, report intrinsic size changes,
and remove the fragile widget-state fallback.

Localize brief forms, summaries, status, and public errors from the current
request or Host locale while preserving stable protocol ids and selections.

Keep internal runtime identifiers out of user-facing MCP guidance.

* fix(packaged): register live Studio URLs with daemon

Register the packaged web sidecar loopback origin over namespace-scoped daemon
IPC after dynamic binding.

Invalidate install-info by the live web port and remove the second MCP URL cache
so run and project responses use the current Studio address.

Validate loopback origins and cover registration, rebind, and cache refresh.

* fix(mcp): stabilize brief confirmation lifecycle

Keep confirmed briefs locked after Host publication failures and retry only the cached follow-up message instead of confirming twice.

Replace blank initialization with a compact loading state, accept immediate and delayed tool results, and bump the MCP Apps resource to v3 so Codex does not reuse the stale card.

Add an executable JSDOM Host bridge harness covering double-submit, publication retry, delayed results, and repeated draft notifications. Validated with the full daemon suite, workspace typecheck, and guard.

* fix(mcp): prevent brief app resize feedback loops

Replace the self-observed intrinsic-height loop with deduplicated body measurements so Codex MCP app iframes do not repeatedly resize themselves and fail sandbox startup.

Bump the brief resource URI to v4 to avoid cached v3 cards and cover the regression with the focused brief-app spec. Validated with daemon tests/build, workspace guard/typecheck, a verified beta DMG, and a direct packaged MCP resource smoke.

* fix(mcp): use the final Open Design plugin identity

Make open-design the only accepted external plugin ID across MCP tools, run attribution, artifact version origins, and telemetry. Rename the Brief MCP App resource to v5 and reject the unpublished old ID instead of aliasing it.

Validated with 171 daemon tests, 5 web tests, daemon/web typechecks, and guard.

* chore(pack): bump Vela CLI to 0.0.27

* chore(nix): refresh pnpm dependency hashes

* fix(mcp): honor host and plugin request contracts

Respect independently advertised MCP Apps capabilities and prefer the Codex-native follow-up bridge so confirmed briefs render as readable user turns instead of context-only messages. Bump the brief resource to v6 to invalidate stale cards.\n\nMark Vela login and account probes as open-world interactions, and require stable request IDs for attributed generation so lost responses cannot create a second logical run.

* fix(cli): support keyless BYOK profiles

Add an explicit --no-api-key save mode for local and self-hosted providers while keeping credential-bearing profiles stdin-only. Reject missing or conflicting credential modes and cover both paths in the CLI tests.

* fix(pack): replace headless owner when desktop opens

Advertise headless packaged runtimes as having no visible window, then shut them down before a normal desktop launch continues instead of treating SHOW as a successful focus.

Validated with the focused packaged headless and launcher lifecycle tests (20 passed).

* fix(pack): clean up failed headless startup

Acquire the headless identity, sidecars, and IPC server through one failure-atomic lifecycle so later bootstrap errors close every previously acquired owner in reverse order.

Cover MCP-install and web-identity publication failures; validated with 22 focused tests and the packaged typecheck.

* fix(byok): remove raw provider request contract

Expose only daemon-owned BYOK profile references from shared run types and the web transport, while retaining the daemon's fail-closed rejection for legacy or untyped raw credential payloads.

Validated with 76 web provider tests plus web and contracts typechecks.

* fix(daemon): preserve interrupted run idempotency

Hydrate queued or running durable requests as DAEMON_RESTARTED failures before idempotency reuse, preserving the original request and workflow mappings instead of creating a second cloud operation.

Share the restart transition with boot reconciliation and expose synthetic terminal events to reattaching clients. Validated with 48 focused tests and the daemon typecheck.

* fix(byok): roll back failed credential metadata writes

Snapshot secure-store values before mutation and compensate create, update, and delete operations when profile metadata cannot be persisted, preventing orphaned or lost credentials.

Validated with nine focused credential-service tests and the daemon typecheck.

* fix(web): reconcile selected BYOK profile metadata

Treat the daemon's selected secure profile as authoritative for protocol, endpoint, model, and API version so CLI profile edits cannot leave the browser showing stale execution settings.

Validated with 66 config tests and the web typecheck.

* fix(byok): migrate legacy credentials before cleanup

Import each supported legacy browser credential into a stable daemon-owned secure profile before removing plaintext copies. Keep the original browser record on secure-store or unsupported-provider failures and surface a Settings recovery path.

Cover successful migration, duplicate projections, and injected secure-backend failure while preserving existing Bedrock downgrade behavior in memory.

* fix(byok): secure Windows profiles with DPAPI

Dispatch native Windows BYOK profiles to a CurrentUser DPAPI backend rooted under the resolved daemon data directory. Secrets enter PowerShell only through stdin, encrypted blobs stay separate from non-secret profile metadata, and API responses remain secret-free.

Add platform dispatch coverage, a Windows-only real DPAPI round-trip test, and the packaged Windows smoke path for create, resolve, response-redaction, and delete behavior.

* fix(web): preserve config writes during hydration

* fix(byok): persist secure credentials across entry flows

* test(byok): cover secure onboarding persistence

---------

Co-authored-by: Cheems <94773058+itscheems@users.noreply.github.com>
Co-authored-by: lefarcen <935902669@qq.com>
2026-07-30 02:00:56 +00:00

356 lines
11 KiB
TypeScript

import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import type { Express } from 'express';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { getArtifact, fetchProjectFile, handleMcpToolCall } from '../src/mcp.js';
// A minimal mock of the daemon's project file endpoints. Tests control
// the file list and per-file response via the opts object.
interface DaemonAppOpts {
files?: Array<{ name: string }>;
fileContent?: string;
contentType?: string;
contentLength?: number | null;
failFile?: string;
}
interface Harness {
server: http.Server;
baseUrl: string;
}
interface TextContent {
type: string;
text: string;
}
interface ArtifactBody {
truncated: boolean;
skippedFileCount?: number;
files: unknown[];
}
function firstText(content: TextContent[]): string {
const item = content[0];
if (item == null) throw new Error('expected MCP text content');
return item.text;
}
function parseArtifactBody(text: string): ArtifactBody {
return JSON.parse(text) as ArtifactBody;
}
function makeDaemonApp(opts: DaemonAppOpts = {}): Express {
const {
files = [],
fileContent = 'body {}',
contentType = 'text/css',
contentLength = null,
failFile,
} = opts;
const app = express();
app.get('/api/projects/:id', (_req, res) =>
res.json({
project: { id: _req.params.id, name: 'Test', metadata: { entryFile: 'index.html' } },
}),
);
app.get('/api/projects/:id/files', (_req, res) => res.json({ files }));
app.get('/api/projects/:id/raw/*splat', (_req, res) => {
if (_req.params.splat?.join('/') === failFile) {
res.status(500).json({ error: 'fixture read failure' });
return;
}
const headers: Record<string, string> = { 'content-type': contentType };
if (contentLength != null) headers['content-length'] = String(contentLength);
res.set(headers).send(fileContent);
});
return app;
}
function startServer(app: Express): Promise<Harness> {
return new Promise((resolve) => {
const tmp = http.createServer();
tmp.listen(0, '127.0.0.1', () => {
const { port } = tmp.address() as AddressInfo;
tmp.close(() => {
const server = app.listen(port, '127.0.0.1', () =>
resolve({ server, baseUrl: `http://127.0.0.1:${port}` }),
);
});
});
});
}
const PROJECT_ID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
describe('getArtifact file-count cap (MAX_FILES = 200)', () => {
let server: http.Server;
let baseUrl: string;
const fileList = Array.from({ length: 250 }, (_, i) => ({ name: `file${i}.css` }));
beforeAll(async () => {
const r = await startServer(makeDaemonApp({ files: fileList, fileContent: 'a {}', contentType: 'text/css' }));
server = r.server;
baseUrl = r.baseUrl;
});
afterAll(() => new Promise((resolve) => server.close(resolve)));
it('caps at 200 files and sets truncated: true when the project has 250 files', async () => {
const result = await getArtifact(baseUrl, PROJECT_ID, 'index.html', 'all', 10_000_000);
const body = parseArtifactBody(firstText(result.content));
expect(body.truncated).toBe(true);
expect(body.files.length).toBe(200);
});
});
describe('getArtifact maxBytes cap', () => {
let server: http.Server;
let baseUrl: string;
// 10 files, each 200 bytes. With maxBytes=400 the third loop iteration
// finds totalTextBytes >= maxBytes and sets truncated: true.
const fileList = Array.from({ length: 10 }, (_, i) => ({ name: `file${i}.css` }));
const fileContent = 'a'.repeat(200);
beforeAll(async () => {
const r = await startServer(makeDaemonApp({ files: fileList, fileContent, contentType: 'text/css' }));
server = r.server;
baseUrl = r.baseUrl;
});
afterAll(() => new Promise((resolve) => server.close(resolve)));
it('stops fetching and sets truncated: true when byte cap is reached', async () => {
const result = await getArtifact(baseUrl, PROJECT_ID, 'index.html', 'all', 400);
const body = parseArtifactBody(firstText(result.content));
expect(body.truncated).toBe(true);
expect(body.files.length).toBeLessThan(10);
});
});
describe('getArtifact UTF-8 byte accounting and partial reads', () => {
it('counts UTF-8 bytes rather than JavaScript string length', async () => {
const r = await startServer(makeDaemonApp({
files: [{ name: 'first.css' }, { name: 'second.css' }],
fileContent: '你好',
contentType: 'text/css',
}));
try {
const result = await getArtifact(
r.baseUrl,
PROJECT_ID,
'index.html',
'all',
6,
);
const body = parseArtifactBody(firstText(result.content));
expect(body.files).toHaveLength(1);
expect(body.truncated).toBe(true);
} finally {
await new Promise<void>((resolve) => r.server.close(() => resolve()));
}
});
it('reports skipped dependency reads as a partial bundle fact', async () => {
const r = await startServer(makeDaemonApp({
files: [{ name: 'ok.css' }, { name: 'broken.css' }],
fileContent: 'ok',
contentType: 'text/css',
failFile: 'broken.css',
}));
try {
const result = await getArtifact(
r.baseUrl,
PROJECT_ID,
'index.html',
'all',
1_000,
);
const body = parseArtifactBody(firstText(result.content));
expect(body.skippedFileCount).toBe(1);
expect(body.truncated).toBe(false);
} finally {
await new Promise<void>((resolve) => r.server.close(() => resolve()));
}
});
});
describe('fetchProjectFile per-file size pre-check', () => {
let server: http.Server;
let baseUrl: string;
beforeAll(async () => {
const r = await startServer(
makeDaemonApp({ fileContent: 'x'.repeat(10_000), contentType: 'text/css', contentLength: 10_000 }),
);
server = r.server;
baseUrl = r.baseUrl;
});
afterAll(() => new Promise((resolve) => server.close(resolve)));
it('throws when content-length exceeds remainingBytes without reading the body', async () => {
await expect(fetchProjectFile(baseUrl, PROJECT_ID, 'styles.css', 5_000)).rejects.toThrow(
/exceeds remaining budget/,
);
});
it('succeeds and returns content when remainingBytes is sufficient', async () => {
const file = await fetchProjectFile(baseUrl, PROJECT_ID, 'styles.css', 20_000);
expect(file.binary).toBe(false);
expect(file.content?.length).toBe(10_000);
});
});
describe('getArtifact truncated: true when per-file content-length pre-check fires (include=all)', () => {
let server: http.Server;
let baseUrl: string;
// 5 files, each 250 bytes with explicit content-length.
// maxBytes=400: file0 (remaining=400, size=250) fetches fine.
// file1+ (remaining=150, size=250 > 150) hit the BudgetExceededError path.
// totalTextBytes never reaches maxBytes, so only the pre-check path sets truncated.
const fileList = Array.from({ length: 5 }, (_, i) => ({ name: `file${i}.css` }));
const fileContent = 'a'.repeat(250);
beforeAll(async () => {
const r = await startServer(
makeDaemonApp({ files: fileList, fileContent, contentType: 'text/css', contentLength: 250 }),
);
server = r.server;
baseUrl = r.baseUrl;
});
afterAll(() => new Promise((resolve) => server.close(resolve)));
it('sets truncated: true even when totalTextBytes never reaches maxBytes', async () => {
const result = await getArtifact(baseUrl, PROJECT_ID, 'index.html', 'all', 400);
const body = parseArtifactBody(firstText(result.content));
expect(body.truncated).toBe(true);
expect(body.files.length).toBe(1);
});
});
describe('public MCP get_artifact active context defaults', () => {
let server: http.Server;
let baseUrl: string;
beforeAll(async () => {
const app = express();
app.get('/api/active', (_req, res) =>
res.json({
active: true,
projectId: 'active-project',
projectName: 'Active Project',
fileName: 'landing.html',
ageMs: 50,
}),
);
app.get('/api/projects/:id', (_req, res) =>
res.json({
project: {
id: 'active-project',
name: 'Active Project',
metadata: { entryFile: 'index.html' },
},
}),
);
app.get('/api/projects/:id/raw/*splat', (req, res) => {
expect(req.params.id).toBe('active-project');
expect(req.params.splat).toEqual(['landing.html']);
res.set({ 'content-type': 'text/html' }).send('<!doctype html><h1>Active artifact</h1>');
});
const r = await startServer(app);
server = r.server;
baseUrl = r.baseUrl;
});
afterAll(() => new Promise((resolve) => server.close(resolve)));
it('uses the active file ahead of metadata.entryFile when project and entry are omitted', async () => {
const result = await handleMcpToolCall(baseUrl, 'get_artifact', { include: 'shallow' });
const body = parseArtifactBody(firstText(result.content)) as ArtifactBody & {
entryFile?: string;
usedActiveContext?: { projectId?: string; fileName?: string };
};
expect(body.entryFile).toBe('landing.html');
expect(body.files).toHaveLength(1);
expect(body.usedActiveContext).toMatchObject({
projectId: 'active-project',
fileName: 'landing.html',
});
});
});
describe('public MCP get_artifact active context fallbacks', () => {
let server: http.Server;
let baseUrl: string;
beforeAll(async () => {
const app = express();
app.get('/api/active', (_req, res) =>
res.json({
active: true,
projectId: 'active-project',
projectName: 'Active Project',
ageMs: 50,
}),
);
app.get('/api/projects/:id', (req, res) =>
res.json({
project: {
id: req.params.id,
name: req.params.id === 'active-project' ? 'Active Project' : 'Explicit Project',
metadata: { entryFile: 'index.html' },
},
}),
);
app.get('/api/projects/:id/raw/*splat', (req, res) => {
res.set({ 'content-type': 'text/html' }).send(`<!doctype html><h1>${req.params.splat.join('/')}</h1>`);
});
const r = await startServer(app);
server = r.server;
baseUrl = r.baseUrl;
});
afterAll(() => new Promise((resolve) => server.close(resolve)));
it('falls back to metadata.entryFile when the active project has no active file', async () => {
const result = await handleMcpToolCall(baseUrl, 'get_artifact', { include: 'shallow' });
const body = parseArtifactBody(firstText(result.content)) as ArtifactBody & {
entryFile?: string;
usedActiveContext?: { projectId?: string; fileName?: string | null };
files?: Array<{ content?: string | null }>;
};
expect(body.entryFile).toBe('index.html');
expect(body.usedActiveContext).toMatchObject({
projectId: 'active-project',
fileName: null,
});
expect(body.files?.[0]?.content).toContain('<h1>index.html</h1>');
});
it('does not stamp active context when project and entry are explicit', async () => {
const result = await handleMcpToolCall(baseUrl, 'get_artifact', {
project: PROJECT_ID,
entry: 'explicit.html',
include: 'shallow',
});
const body = parseArtifactBody(firstText(result.content)) as ArtifactBody & {
entryFile?: string;
usedActiveContext?: unknown;
files?: Array<{ content?: string | null }>;
};
expect(body.entryFile).toBe('explicit.html');
expect(body.usedActiveContext).toBeUndefined();
expect(body.files?.[0]?.content).toContain('<h1>explicit.html</h1>');
});
});