Files
webstudio/packages/cli/src/project-session-api.test.ts
T
Oleg Isonen 928867a08b fix: Improve MCP CSS variable safety and state feedback (#6018)
Closes #6017
Ref #6019

## Summary

Improve agent-facing CLI/MCP feedback for CSS variables, mutation
durability, batch operations, and preview freshness.

## Implementation

- Validate structured hex colors as normalized channels and recommend
CSS strings for ordinary 0–255 hex input.
- Return exact CSS variable values while retaining `valueLength` in
compact output for compatibility.
- Preserve optional boolean inputs generically in compact MCP SDK
schemas, including `withUsage`, `verbose`, `overwrite`, and `force`.
- Add multi-variable define/delete examples and document safe batching.
- Derive `meta.session.commitStatus` from the session envelope so reads,
plans, failed/no-op mutations, and durable mutations are unambiguous.
- Retain `committed` on read results for compatibility while reporting
`commitStatus: "not-applicable"`.
- Report preview `stale` state and `renderedProjectVersion`, and avoid
marking a preview fresh when the project changes during regeneration.
- Track WSL2/9P cleanup hardening separately in #6019.

## Todo

- [x] Reject out-of-range structured hex color channels and alpha.
- [x] Add fail-before/pass-after CSS color regression coverage.
- [x] Return exact compact CSS variable values without removing
`valueLength`.
- [x] Clarify mutation durability with `commitStatus`.
- [x] Distinguish failed, unchanged, planned, committed, and read-only
results.
- [x] Distinguish server-backed reads from committed mutations at the
session boundary.
- [x] Preserve optional boolean schemas without a per-field allowlist.
- [x] Add multi-variable define and delete examples.
- [x] Report preview freshness and rendered project version.
- [x] Investigate WSL cleanup behavior and create follow-up #6019.
- [x] Review and update authoritative CLI/MCP documentation.
- [x] Verify fixture impact; no fixture inputs or outputs changed.
- [x] Run affected tests, typechecks, lint, and generated-file checks.
- [ ] Run the complete local agent evaluation suite after explicit
approval.

## Verification

- [x] Regression tests demonstrated failing before their implementation
and passing afterward.
- [x] `pnpm --filter @webstudio-is/project-build test` — 82 files, 2,085
tests passed.
- [x] `pnpm --filter webstudio test` — 57 files, 939 tests passed.
- [x] Project-build and CLI typechecks passed.
- [x] `pnpm lint` passed.
- [x] `pnpm oxfmt --check` passed.
- [x] `pnpm check:generated-api` passed.
- [x] `pnpm check:generated-docs` passed.
- [ ] `pnpm evaluations` — awaiting explicit approval per repository
policy.

## Compatibility and limitations

- `committed` remains available on every session result. For reads it is
`false` and durability does not apply; use `commitStatus:
"not-applicable"`.
- Compact CSS-variable records include both exact `value` and
`valueLength`.
- Structured hex color channels remain normalized `0..1`; CSS color
strings such as `"#2d3748"` are the recommended 0–255 representation.
- WSL2/9P process cleanup is not changed in this PR and is scoped in
#6019.
2026-08-06 02:15:51 +02:00

344 lines
9.5 KiB
TypeScript

import { describe, expect, test, vi } from "vitest";
import { executeProjectSessionApiOperation } from "./project-session-api";
type CreateProjectSession = NonNullable<
Parameters<
typeof executeProjectSessionApiOperation
>[0]["createProjectSession"]
>;
describe("project session api adapter", () => {
test("routes local-capable commands through project session runtime", async () => {
const session = {
initialize: vi.fn(async () => undefined),
read: vi.fn(async () => ({
operationId: "pages.list",
projectId: "project-1",
source: "local",
result: ["page"],
state: { committed: false, freshness: {} },
namespaces: {
read: ["pages"],
write: [],
invalidated: [],
missing: [],
},
diagnostics: [],
})),
mutate: vi.fn(),
refresh: vi.fn(),
executeServerOperation: vi.fn(),
};
const createProjectSession = vi.fn(
() => session
) as unknown as CreateProjectSession;
const result = await executeProjectSessionApiOperation({
command: "list-pages",
input: { limit: 20 },
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession,
});
expect(session.read).toHaveBeenCalledWith(
"pages.list",
{ projectId: "project-1", limit: 20 },
{ permit: "view" }
);
expect(result.result).toEqual(["page"]);
});
test("keeps configured project id for local-capable commands", async () => {
const session = {
initialize: vi.fn(async () => undefined),
read: vi.fn(async () => ({
operationId: "pages.list",
projectId: "project-1",
source: "local",
result: [],
state: { committed: false, freshness: {} },
namespaces: {
read: ["pages"],
write: [],
invalidated: [],
missing: [],
},
diagnostics: [],
})),
mutate: vi.fn(),
refresh: vi.fn(),
executeServerOperation: vi.fn(),
};
await executeProjectSessionApiOperation({
command: "list-pages",
input: { projectId: "other-project" },
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession: vi.fn(
() => session
) as unknown as CreateProjectSession,
});
expect(session.read).toHaveBeenCalledWith(
"pages.list",
{ projectId: "project-1" },
{ permit: "view" }
);
});
test("does not inject project id into strict audit input", async () => {
const session = {
initialize: vi.fn(async () => undefined),
read: vi.fn(async () => ({
operationId: "project.audit",
projectId: "project-1",
source: "local",
result: { findings: [] },
state: { committed: false, freshness: {} },
namespaces: {
read: [],
write: [],
invalidated: [],
missing: [],
},
diagnostics: [],
})),
mutate: vi.fn(),
refresh: vi.fn(),
executeServerOperation: vi.fn(),
};
await executeProjectSessionApiOperation({
command: "audit",
input: { scopes: ["seo"] },
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession: vi.fn(
() => session
) as unknown as CreateProjectSession,
});
expect(session.read).toHaveBeenCalledWith(
"project.audit",
{ scopes: ["seo"] },
{ permit: "view" }
);
});
test("routes server-only commands through project session transport", async () => {
const session = {
initialize: vi.fn(async () => undefined),
read: vi.fn(),
mutate: vi.fn(),
executeServerOperation: vi.fn(async () => ({
operationId: "auth.me",
projectId: "project-1",
source: "server",
result: { actor: "token" },
state: { committed: true, freshness: {} },
namespaces: { read: [], write: [], invalidated: [], missing: [] },
diagnostics: [],
})),
refresh: vi.fn(),
};
const createProjectSession = vi.fn(
() => session
) as unknown as CreateProjectSession;
const result = await executeProjectSessionApiOperation({
command: "whoami",
input: {},
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession,
getServerApiContract: async () => ({
clientVersion: "public-api:client",
serverVersion: "public-api:server",
supportedOperationIds: new Set(["auth.me"]),
missingServerOperationIds: [],
negotiated: true,
}),
});
expect(session.executeServerOperation).toHaveBeenCalledWith(
{
id: "auth.me",
method: "query",
invalidatesNamespaces: [],
refetchInvalidatedNamespaces: false,
},
{}
);
expect(result.result).toEqual({ actor: "token" });
});
test("rejects unsupported server-only commands before dispatch", async () => {
const session = {
initialize: vi.fn(async () => undefined),
read: vi.fn(),
mutate: vi.fn(),
executeServerOperation: vi.fn(),
refresh: vi.fn(),
};
await expect(
executeProjectSessionApiOperation({
command: "whoami",
input: {},
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession: vi.fn(
() => session
) as unknown as CreateProjectSession,
getServerApiContract: async () => ({
clientVersion: "public-api:client",
supportedOperationIds: new Set(),
missingServerOperationIds: ["auth.me"],
negotiated: false,
}),
})
).rejects.toThrow('does not advertise server operation "auth.me"');
expect(session.executeServerOperation).not.toHaveBeenCalled();
});
test("refreshes local namespaces before local-capable commands when requested", async () => {
const session = {
initialize: vi.fn(async () => undefined),
refresh: vi.fn(async () => undefined),
read: vi.fn(async () => ({
operationId: "pages.list",
projectId: "project-1",
source: "local",
result: ["page"],
state: { committed: false, freshness: {} },
namespaces: {
read: ["pages"],
write: [],
invalidated: [],
missing: [],
},
diagnostics: [],
})),
mutate: vi.fn(),
executeServerOperation: vi.fn(),
};
await executeProjectSessionApiOperation({
command: "list-pages",
input: {},
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession: vi.fn(
() => session
) as unknown as CreateProjectSession,
refresh: true,
});
expect(session.refresh).toHaveBeenCalledWith(["pages"]);
});
test("explains dry-run is only for local-capable mutations", async () => {
const createProjectSession = vi.fn() as unknown as CreateProjectSession;
await expect(
executeProjectSessionApiOperation({
command: "list-pages",
input: {},
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession,
dryRun: true,
})
).rejects.toThrow(
"list-pages does not support --dry-run. Use --dry-run only with local-capable mutation tools; omit it for read or server-only tools."
);
expect(createProjectSession).not.toHaveBeenCalled();
});
test("preserves project session diagnostic code on operation errors", async () => {
const session = {
initialize: vi.fn(async () => undefined),
read: vi.fn(async () => ({
operationId: "pages.list",
projectId: "project-1",
source: "local",
result: undefined,
state: { committed: false, freshness: {} },
namespaces: {
read: ["pages"],
write: [],
invalidated: [],
missing: [],
},
diagnostics: [
{
level: "error",
code: "INVALID_INPUT",
message: "Page input is invalid.",
issues: [
{
code: "invalid_expression",
path: ["values", "title"],
message: "Invalid Webstudio expression",
constraint: "valid_webstudio_expression",
example: 'pageTitle ?? "Pricing"',
detail: "Unexpected token",
},
],
},
],
})),
mutate: vi.fn(),
refresh: vi.fn(),
executeServerOperation: vi.fn(),
};
await expect(
executeProjectSessionApiOperation({
command: "list-pages",
input: {},
connection: {
projectId: "project-1",
origin: "https://example.com",
authToken: "token",
},
createProjectSession: vi.fn(
() => session
) as unknown as CreateProjectSession,
})
).rejects.toMatchObject({
code: "INVALID_INPUT",
message: "Page input is invalid.",
issues: [
expect.objectContaining({
path: ["values", "title"],
constraint: "valid_webstudio_expression",
}),
],
});
});
});