Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
27 changes: 26 additions & 1 deletion server/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import * as persist from './db/persist.ts'
import * as thumbs from './thumbs.ts'
import { colorFor } from '../shared/types.ts'
import { DEFAULT_ROLE_ID, mentionedRole, normalizePipeline, roleByAgentName, roleName } from '../shared/agents.ts'
import { canvasPages } from '../shared/pages.ts'
import { canvasPages, pageFrames } from '../shared/pages.ts'
import { conflicts, defaultSpot, freeSpot } from './frameLayout.ts'
import { isCanvasComment } from '../shared/comments.ts'
import { decodeEscapedHtml, looksEscapedHtml, repairEscapedHtml } from './escapedHtml.ts'
import { emitCanvasEvent } from './events.ts'
Expand Down Expand Up @@ -1371,6 +1372,27 @@ export async function duplicatePage(canvasId: string, pageId: string, actor: Act
return copy
}

/** Frames `createFrame` moved to free space because the requested spot overlapped another frame (CHE-6119). */
const relocated = new WeakSet<Frame>()
export const wasRelocated = (frame: Frame) => relocated.has(frame)

/** CHE-6119: an agent's frame whose box (explicit x/y, or the store's default for a missing one) would sit on
* another frame goes to free space instead. */
function clearOfOverlap<T extends { pageId?: string; x?: number; y?: number; width?: number; height?: number }>(
canvasId: string,
input: T,
): { input: T; moved: boolean } {
const canvas = store.getCanvas(canvasId)
const pageId = canvas && (input.pageId ?? canvasPages(canvas)[0]?.id)
if (!canvas || !pageId) return { input, moved: false }
const frames = pageFrames(canvas, pageId)
const at = defaultSpot(frames)
const box = { x: input.x ?? at.x, y: input.y ?? at.y, width: input.width ?? 640, height: input.height ?? 480 }
return conflicts(box, frames).length
? { input: { ...input, ...freeSpot(frames) }, moved: true }
: { input, moved: false }
}

export function createFrame(
canvasId: string,
input: {
Expand All @@ -1388,8 +1410,11 @@ export function createFrame(
actor: Actor,
): Frame | undefined {
if (input.html !== undefined) input = { ...input, html: repairEscapedHtml(input.html) }
let moved = false
if (actor.kind === 'agent') ({ input, moved } = clearOfOverlap(canvasId, input))
const frame = store.createFrame(canvasId, input, actor.name)
if (!frame) return undefined
if (moved) relocated.add(frame)
bursts.set(frame.id, { actor, lastAt: frame.createdAt })
if (actor.kind === 'agent' && frame.html.length > 0) {
/* agent one-shot creation still plays back as a reveal */
Expand Down
43 changes: 43 additions & 0 deletions server/frameLayout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* Frame layout guard (CHE-6119): agent writes may not leave two frames on a page intersecting or closer than
FRAME_GAP. Runs at the write itself (actions.createFrame relocates, the MCP update_frame refuses), so a person
never drags a frame away to read what is under it. Hidden frames take no space. */
import type { Frame } from '../shared/types.ts'

export const FRAME_GAP = 40 // minimum clear space between frames, in canvas px
export const PLACE_GAP = 80 // clear space left above a frame placed in free space

export interface Box {
x: number
y: number
width: number
height: number
}

type Placed = Pick<Frame, 'id' | 'name' | 'x' | 'y' | 'width' | 'height' | 'hidden'>

/** Other visible frames whose box is closer than `gap` to `box`. */
export function conflicts<T extends Placed>(box: Box, frames: T[], selfId?: string, gap = FRAME_GAP): T[] {
return frames.filter(
(f) =>
f.id !== selfId &&
!f.hidden &&
Math.min(box.x + box.width, f.x + f.width) - Math.max(box.x, f.x) > -gap &&
Math.min(box.y + box.height, f.y + f.height) - Math.max(box.y, f.y) > -gap,
)
}

/** Free spot for a new frame: the page's left edge, below its lowest visible frame. */
export function freeSpot(frames: Placed[]): { x: number; y: number } {
const visible = frames.filter((f) => !f.hidden)
if (!visible.length) return { x: 120, y: 120 }
return {
x: Math.min(...visible.map((f) => f.x)),
y: Math.max(...visible.map((f) => f.y + f.height)) + PLACE_GAP,
}
}

/** Where the store puts a frame with no x/y: right of the right-most frame, or the page origin when empty. */
export function defaultSpot(frames: Pick<Frame, 'x' | 'width'>[]): { x: number; y: number } {
const rightmost = frames.reduce((mx, f) => Math.max(mx, f.x + f.width), 0)
return { x: frames.length ? rightmost + 80 : 120, y: 120 }
}
51 changes: 41 additions & 10 deletions server/mcp.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { env } from './env.ts'
import { canvasPages, samePages } from '../shared/pages.ts'
import { canvasPages, framePageId, pageFrames, samePages } from '../shared/pages.ts'
import { conflicts, freeSpot, FRAME_GAP } from './frameLayout.ts'
import { MULTICA_TASK_HEADER, parseMulticaTaskId } from '../shared/pageIssue.ts'
import { prototypeReport, prototypeUrl, setPrototypeStart } from './prototypeTools.ts'
import { attestPage } from './designAttestations.ts'
Expand Down Expand Up @@ -194,6 +195,28 @@ const agentName = z
'Your display name, shown live to everyone on the canvas (e.g. "Claude", "Codex"). Reuse the SAME name on every call so your work is attributed consistently.',
)

/** CHE-6119: why an update_frame that moves or resizes a frame onto another frame is refused (undefined = fine). */
function overlapRefusal(
frame: Frame,
patch: Partial<Pick<Frame, 'x' | 'y' | 'width' | 'height' | 'pageId'>>,
): string | undefined {
if (!(['x', 'y', 'width', 'height', 'pageId'] as const).some((k) => patch[k] !== undefined)) return undefined
const canvas = store.getCanvas(frame.canvasId)
if (!canvas) return undefined
const pageId = patch.pageId ?? framePageId(canvas, frame)
const box = {
x: patch.x ?? frame.x,
y: patch.y ?? frame.y,
width: patch.width ?? frame.width,
height: patch.height ?? frame.height,
}
const others = pageFrames(canvas, pageId)
const hit = conflicts(box, others, frame.id)
if (!hit.length) return undefined
const spot = freeSpot(others.filter((f) => f.id !== frame.id))
return `frames may not overlap or sit closer than ${FRAME_GAP}px: this ${box.width}x${box.height} box at ${box.x},${box.y} hits ${hit.map((f) => `${f.id} “${f.name}”`).join(', ')}. Free space: x ${spot.x}, y ${spot.y}.`
}

function frameSummary(f: {
pageId?: string
id: string
Expand Down Expand Up @@ -995,7 +1018,7 @@ export function buildMcpServer(owner?: string, ownerId?: string, multicaTaskId?:
has no card either). The review screenshot after the stream is the
first card the person sees. */
description:
'Create a new frame on a canvas with an HTML design. A frame is a rectangular artboard that renders a full HTML document (inline <style> and <script> allowed, no external network access needed). If x/y are omitted the frame is auto-placed to the right of existing frames. Everyone viewing the canvas sees it appear live.',
'Create a new frame on a canvas with an HTML design. A frame is a rectangular artboard that renders a full HTML document (inline <style> and <script> allowed, no external network access needed). If x/y are omitted the frame is auto-placed to the right of existing frames; an requested position (explicit or defaulted x/y) that would overlap another frame is replaced by free space (see `placement` in the result). Everyone viewing the canvas sees it appear live.',
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
inputSchema: {
canvas_id: z.string(),
Expand All @@ -1017,12 +1040,17 @@ export function buildMcpServer(owner?: string, ownerId?: string, multicaTaskId?:
if (!canvasFor(canvas_id, 'edit')) return noCanvas(canvas_id)
const frame = actions.createFrame(canvas_id, { name, pageId, html, x, y, width, height }, actorFrom(agent_name))
if (!frame) return noCanvas(canvas_id)
const result = withEscapeNote(
frame.html.length > 0
? textWithNudge({ ok: true, frame: frameSummary(frame) }, REVIEW_NUDGE)
: text({ ok: true, frame: frameSummary(frame) }),
html,
)
const moved = actions.wasRelocated(frame)
const body = {
ok: true,
frame: frameSummary(frame),
...(moved
? {
placement: `the requested position would overlap another frame; placed in free space at ${frame.x},${frame.y}`,
}
: {}),
}
const result = withEscapeNote(frame.html.length > 0 ? textWithNudge(body, REVIEW_NUDGE) : text(body), html)
return withGuidelinesNudge(
withStatusNudge(withFeedback(result, canvas_id, actorFrom(agent_name)), canvas_id, actorFrom(agent_name)),
canvas_id,
Expand Down Expand Up @@ -1751,7 +1779,7 @@ export function buildMcpServer(owner?: string, ownerId?: string, multicaTaskId?:
title: 'Rename, move or resize a frame',
_meta: previewToolMeta('Updating the frame…', 'Frame updated'),
description:
'Update frame metadata: rename it, move/resize it, or move it to another page using pageId. Set locked to true to lock the frame on the canvas (humans cannot select, move, resize or delete it from the stage until it is unlocked) or false to unlock it.',
'Update frame metadata: rename it, move/resize it, or move it to another page using pageId. Set locked to true to lock the frame on the canvas (humans cannot select, move, resize or delete it from the stage until it is unlocked) or false to unlock it. A move or resize that would overlap another frame on the page (or leave less than 40px clear) is refused with the free spot to use.',
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
inputSchema: {
frame_id: z.string(),
Expand All @@ -1768,7 +1796,10 @@ export function buildMcpServer(owner?: string, ownerId?: string, multicaTaskId?:
async ({ frame_id, agent_name, ...patch }) => {
const clean = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined))
if (!Object.keys(clean).length) return err('nothing to update')
if (!frameFor(frame_id, 'edit')) return noFrame(frame_id)
const current = frameFor(frame_id, 'edit')
if (!current) return noFrame(frame_id)
const blocked = overlapRefusal(current, clean)
if (blocked) return err(blocked)
const frame = actions.updateFrame(frame_id, clean, actorFrom(agent_name))
if (!frame) return noFrame(frame_id)
return withPreview(
Expand Down
11 changes: 4 additions & 7 deletions server/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { nanoid } from 'nanoid'
import { canvasPages, copyPageName, framePageId, pageFrames, samePages } from '../shared/pages.ts'
import { defaultSpot } from './frameLayout.ts'
import * as persist from './db/persist.ts'
import type { LinkAccess } from '../shared/canvasRole.ts'
import { MAX_GUIDES } from '../shared/guides.ts'
Expand Down Expand Up @@ -662,13 +663,9 @@ class Store {
const frames = pageFrames(c, pageId)
const now = Date.now()
// auto-place: to the right of the right-most frame
let x = input.x
let y = input.y
if (x === undefined || y === undefined) {
const rightmost = frames.reduce((mx, f) => Math.max(mx, f.x + f.width), 0)
x ??= frames.length ? rightmost + 80 : 120
y ??= 120
}
const at = defaultSpot(frames)
const x = input.x ?? at.x
const y = input.y ?? at.y
const frame: Frame = {
id: nanoid(10),
canvasId,
Expand Down
2 changes: 1 addition & 1 deletion tests/frameApproval.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ it('exposes approval to agents, filters implementation candidates, and invalidat
expect(ready.frames).toHaveLength(1)
expect(ready.frames[0]).toMatchObject({ id: frame.id, approvalStatus: 'ready_for_dev', approval: approved.approval })
expect((await callTool('get_frame', { frame_id: frame.id })).approval).toEqual(approved.approval)
await callTool('update_frame', { frame_id: frame.id, width: 900, agent_name: 'Implementer' })
await callTool('update_frame', { frame_id: frame.id, height: 900, agent_name: 'Implementer' })
expect((await callTool('get_canvas', { canvas_id: canvas.id, approval_status: 'ready_for_dev' })).frames).toEqual([])
expect((await callTool('get_frame', { frame_id: frame.id })).approvalStatus).toBe('needs_review')
expect((await callTool('get_canvas', { canvas_id: canvas.id, approval_status: 'draft' })).frames).toHaveLength(1)
Expand Down
107 changes: 107 additions & 0 deletions tests/frameOverlapGuard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { Client as McpClient } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import type { Canvas, Frame } from '../shared/types'
import { conflicts, freeSpot } from '../server/frameLayout.ts'
import { Client, startServer, type Server } from './harness.ts'

/* CHE-6119: an agent's direct doop write (MCP create_frame / update_frame) never leaves frames overlapping */
let server: Server
let owner: Client
let agent: McpClient

beforeAll(async () => {
server = await startServer()
owner = await new Client(server).signUp('overlap@test.dev', 'Overlap Owner')
const { secret } = await (await owner.post('/api/agent-keys', { name: 'Design agent' })).json()
agent = new McpClient({ name: 'overlap-test', version: '1.0.0' })
await agent.connect(
new StreamableHTTPClientTransport(new URL('/mcp', server.base), {
requestInit: { headers: { Authorization: `Bearer ${secret}` } },
}),
)
}, 60_000)

afterAll(async () => {
await agent?.close()
server?.stop()
})

async function call(name: string, args: Record<string, unknown>) {
const result = await agent.callTool({ name, arguments: { agent_name: 'Designer', ...args } })
const text = (result.content as { type: string; text?: string }[]).find((c) => c.type === 'text')!.text!
return { isError: !!result.isError, text }
}

async function frames(canvasId: string): Promise<Frame[]> {
return ((await (await owner.get(`/api/canvases/${canvasId}`)).json()) as Canvas).frames
}

function overlapping(fs: Frame[]) {
return fs.flatMap((a, i) => fs.slice(i + 1).flatMap((b) => (conflicts(a, [b]).length ? [[a.id, b.id]] : [])))
}

describe('frameLayout', () => {
const f = (id: string, x: number, y: number, w = 100, h = 100) => ({ id, name: id, x, y, width: w, height: h })

it('flags intersecting and too-close boxes, ignores clear, hidden and self', () => {
const others = [f('a', 0, 0), { ...f('h', 0, 0), hidden: true }]
expect(conflicts({ x: 50, y: 50, width: 100, height: 100 }, others).map((o) => o.id)).toEqual(['a'])
expect(conflicts({ x: 120, y: 0, width: 100, height: 100 }, others)).toHaveLength(1) // 20px gap < 40
expect(conflicts({ x: 140, y: 0, width: 100, height: 100 }, others)).toHaveLength(0) // 40px gap
expect(conflicts({ x: 0, y: 0, width: 100, height: 100 }, others, 'a')).toHaveLength(0)
})

it('places a new frame below the lowest visible frame', () => {
expect(freeSpot([f('a', 10, 20), f('b', 300, 50, 100, 400)])).toEqual({ x: 10, y: 530 })
expect(freeSpot([])).toEqual({ x: 120, y: 120 })
})
})

describe('agent writes through MCP', () => {
it('create_frame at an overlapping x/y lands in free space and says so', async () => {
const canvas: Canvas = await (await owner.post('/api/canvases', { name: 'Create' })).json()
const a = JSON.parse((await call('create_frame', { canvas_id: canvas.id, name: 'A', html: '', x: 0, y: 0 })).text)
const b = JSON.parse(
(await call('create_frame', { canvas_id: canvas.id, name: 'B', html: '', x: 100, y: 100 })).text,
)
expect(a.frame.x).toBe(0)
expect(b.placement).toMatch(/placed in free space/)
expect(overlapping(await frames(canvas.id))).toEqual([])
})

it('create_frame with only x or only y is checked after the defaults are filled in', async () => {
const canvas: Canvas = await (await owner.post('/api/canvases', { name: 'Partial' })).json()
await call('create_frame', { canvas_id: canvas.id, name: 'A', html: '', x: 0, y: 0 })
const onlyX = JSON.parse((await call('create_frame', { canvas_id: canvas.id, name: 'B', html: '', x: 0 })).text)
const onlyY = JSON.parse((await call('create_frame', { canvas_id: canvas.id, name: 'C', html: '', y: 0 })).text)
expect(onlyX.placement).toMatch(/placed in free space/)
expect(onlyY.frame.id).toBeTruthy()
expect(overlapping(await frames(canvas.id))).toEqual([])
})

it('update_frame refuses a move or resize onto another frame, accepts a clear one, and a rename always passes', async () => {
const canvas: Canvas = await (await owner.post('/api/canvases', { name: 'Move' })).json()
const ids: string[] = []
for (const [name, x] of [
['A', 0],
['B', 1000],
] as const) {
const r = JSON.parse((await call('create_frame', { canvas_id: canvas.id, name, html: '', x, y: 0 })).text)
ids.push(r.frame.id)
}
const [a, b] = ids as [string, string]

const onto = await call('update_frame', { frame_id: b, x: 100, y: 100 })
expect(onto.isError).toBe(true)
expect(onto.text).toMatch(/may not overlap/)
expect(onto.text).toContain(a)
const grow = await call('update_frame', { frame_id: a, width: 1200 })
expect(grow.isError).toBe(true)

const clear = await call('update_frame', { frame_id: b, x: 2000, y: 0 })
expect(clear.isError).toBe(false)
expect((await call('update_frame', { frame_id: a, name: 'A2' })).isError).toBe(false)
expect(overlapping(await frames(canvas.id))).toEqual([])
})
})
Loading