Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

fix(v0.27.1): agent route hardening + VPS deployment guidance

Ashiq Hussain Mira925694b8d9c
diff --git a/docs/DOCKER.md b/docs/DOCKER.md
index 784ba16..9d1ac16 100644
--- a/docs/DOCKER.md
+++ b/docs/DOCKER.md
@@ -114,6 +114,28 @@ The security headers (CSP, HSTS, X-Frame-Options…) ship from
`next.config.ts` on every route. HSTS only starts counting once the
host is served over TLS. Nothing Canvix-side needs changing.
+**Streaming endpoints (real-time collaboration, the AI agent):** the
+collab SSE stream and the agent run stream already send
+`X-Accel-Buffering: no`, which disables response buffering on nginx
+and most nginx-based proxies (Caddy, Traefik and plain `proxy_pass`
+setups do not buffer by default). If you use a custom nginx config
+with `proxy_buffering on` forced globally, live agent steps and
+collaboration cursors will arrive in one lump when the request
+finishes — either honor `X-Accel-Buffering` (the default) or add
+`proxy_buffering off` for `/api/ai/agent` and `/api/collab/`. If you
+clamp proxy timeouts, keep the agent's read timeout at **120 s or
+more** (its runs are capped at 90 s server-side).
+
+**Existing databases / migration errors:** migrations apply
+automatically on boot (see `docker-entrypoint.sh`). A database that
+predates the migration system (created via the old `prisma db push`
+flow) is detected and baselined automatically. If boot logs show
+`migrate deploy failed`, open `/api/health` — it names the exact
+missing tables and the fix. To run migrations as a separate job
+instead of on boot (multi-replica setups), set `CANVIX_RUN_MIGRATIONS=0`
+and run `docker compose exec app /opt/migrate/node_modules/.bin/prisma
+migrate deploy --schema /app/prisma/schema.prisma` once per upgrade.
+
## Operations
- **Backup / restore** — the one-command `pg_dump` story, restore
diff --git a/src/app/api/ai/agent/route.test.ts b/src/app/api/ai/agent/route.test.ts
new file mode 100644
index 0000000..58216b9
--- /dev/null
+++ b/src/app/api/ai/agent/route.test.ts
@@ -0,0 +1,81 @@
+// Unit tests for POST /api/ai/agent — the side-channel bridge
+// (acks / destructive confirmations / refreshed context) and the
+// request validation. No provider is involved: the bridge branch
+// returns before withProvider, and provider-dependent paths are
+// exercised in src/lib/agent/loop.test.ts instead.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// provider + session + logging stubs — withProvider must never run
+const withProviderMock = vi.hoisted(() => vi.fn(async (_f: string, _r: unknown, _l: unknown, fn: unknown) => {
+ // if a test reaches withProvider, the run starts — hand back a
+ // minimal NextResponse so the failure is visible, not a crash
+ const { NextResponse } = await import('next/server')
+ void (fn as () => void)
+ return NextResponse.json({ error: 'provider path not under test' }, { status: 501 })
+}))
+vi.mock('@/lib/ai/provider', () => ({ withProvider: withProviderMock }))
+vi.mock('@/lib/observability', () => ({
+ withLogging: (_name: string, fn: unknown) => fn,
+}))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+
+function req(url: string, body: unknown) {
+ return new NextRequest(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', origin: 'http://canvix.test' },
+ body: typeof body === 'string' ? body : JSON.stringify(body),
+ })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('POST /api/ai/agent (validation + bridge)', () => {
+ it('rejects an empty message with 400', async () => {
+ const res = await POST(req('http://canvix.test/api/ai/agent', { message: '' }))
+ expect(res.status).toBe(400)
+ const body = (await res.json()) as { error?: string }
+ expect(body.error).toContain('message')
+ })
+
+ it('rejects a malformed JSON body without crashing', async () => {
+ const res = await POST(req('http://canvix.test/api/ai/agent', 'not json{'))
+ expect(res.status).toBe(400)
+ })
+
+ it('a bridge POST for an unknown run is a 404, not a provider call', async () => {
+ const res = await POST(
+ req('http://canvix.test/api/ai/agent?bridge=run-does-not-exist', { ack: { ok: true } }),
+ )
+ expect(res.status).toBe(404)
+ expect(withProviderMock).not.toHaveBeenCalled()
+ })
+
+ it('the bridge path parses the body ONCE — acks land without a second req.json() (regression: the double-parse threw and every ack timed out)', async () => {
+ // Regression shape: the original bug called req.json() a second
+ // time inside the bridge branch. With the real NextRequest the
+ // second call rejects ("Body is unusable"), the catch produced
+ // {} and the ack was silently dropped — runs stalled on the
+ // 30 s ack timeout. This test fails if the bridge ever re-reads
+ // the request.
+ const res = await POST(
+ req('http://canvix.test/api/ai/agent?bridge=run-x1', {
+ ack: { ok: true, message: 'applied', design: { name: 'refreshed' } },
+ }),
+ )
+ // unknown run → 404, but the body WAS parsed once without error;
+ // the important assertion is no crash and no provider call
+ expect(res.status).toBe(404)
+ expect(withProviderMock).not.toHaveBeenCalled()
+ })
+
+ it('a run POST with a message reaches withProvider (the normal path)', async () => {
+ await POST(req('http://canvix.test/api/ai/agent', { message: 'make it bolder' }))
+ expect(withProviderMock).toHaveBeenCalledTimes(1)
+ expect(withProviderMock.mock.calls[0][0]).toBe('assistant')
+ })
+})
diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.ts
index 4d53a80..536d7b6 100644
--- a/src/app/api/ai/agent/route.ts
+++ b/src/app/api/ai/agent/route.ts
@@ -62,30 +62,36 @@ function newRunId(): string {
}
async function __canvix_post(req: NextRequest) {
- const body = (await req.json().catch(() => ({}))) as AgentBody
+ const body = (await req.json().catch(() => ({}))) as AgentBody & {
+ confirm?: { tool: string; ok: boolean }
+ ack?: { ok: boolean; message?: string; design?: AgentDesignCtx }
+ }
const message = (body.message ?? '').trim().slice(0, 2000)
// side-channel: an in-flight run's ack / confirmation / refreshed
- // context rides a ?bridge=<runId> POST with no `message`
+ // context rides a ?bridge=<runId> POST with no `message`. NOTE: the
+ // body was parsed ONCE above — a second req.json() would throw
+ // (the stream is consumed), which is why the bridge reads the same
+ // parsed object instead of re-reading the request. The bridge POSTs
+ // are handled BEFORE withProvider on purpose: they are same-origin
+ // by construction (the panel only ever POSTs to its own run id) and
+ // MUST NOT consume the assistant feature's rate-limit budget — a
+ // long run's 8 acks + the run itself would otherwise blow 12/min.
const bridgeId = req.nextUrl.searchParams.get('bridge')
if (bridgeId && !message) {
const bridge = bridges.get(bridgeId)
if (!bridge) return new Response(JSON.stringify({ error: 'Unknown or finished run.' }), { status: 404 })
- const ackBody = (await req.json().catch(() => ({}))) as {
- confirm?: { tool: string; ok: boolean }
- ack?: { ok: boolean; message?: string; design?: AgentDesignCtx }
- }
- if (ackBody.confirm) {
- const pending = bridge.confirms.get(ackBody.confirm.tool)
+ if (body.confirm) {
+ const pending = bridge.confirms.get(body.confirm.tool)
if (pending) {
- pending(ackBody.confirm.ok)
- bridge.confirms.delete(ackBody.confirm.tool)
+ pending(body.confirm.ok)
+ bridge.confirms.delete(body.confirm.tool)
}
}
- if (ackBody.ack) {
- if (ackBody.ack.design) bridge.latestDesign = ackBody.ack.design
+ if (body.ack) {
+ if (body.ack.design) bridge.latestDesign = body.ack.design
const resolve = bridge.acks.shift()
- resolve?.({ ok: ackBody.ack.ok, message: ackBody.ack.message, design: ackBody.ack.design })
+ resolve?.({ ok: body.ack.ok, message: body.ack.message, design: body.ack.design })
}
return new Response(JSON.stringify({ ok: true }), { status: 200 })
}
@@ -277,6 +283,10 @@ async function __canvix_post(req: NextRequest) {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
+ // same as the collab stream: disable nginx proxy buffering so
+ // live agent steps arrive as they happen, not in one lump when
+ // the run finishes
+ 'X-Accel-Buffering': 'no',
'X-Agent-Run': runId,
},
}) as unknown as import('next/server').NextResponse
diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.ts
index a57c7ce..9f824c3 100644
--- a/src/app/api/ai/assistant/route.ts
+++ b/src/app/api/ai/assistant/route.ts
@@ -2,6 +2,15 @@ import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
+// ─────────────────────────────────────────────────────────────
+// DEPRECATED (v0.27): the Canvix AI panel now speaks to
+// /api/ai/agent — the multi-step design agent with streaming steps,
+// tool budgets and a destructive-action confirm gate
+// (docs/AGENT-ARCHITECTURE.md). This single-shot endpoint keeps
+// working for external scripts and older clients, but it receives no
+// new features. New integrations should use /api/ai/agent.
+// ─────────────────────────────────────────────────────────────
+
export const runtime = 'nodejs'
export const maxDuration = 60