An open-source, faster Devin alternative
TypeScript
fix(deferred-actions): address review — length lockstep, drop shim, harden
Igor Zalutskic0182dcf8cc6
diff --git a/.agents/work/deferred-actions.md b/.agents/work/deferred-actions.mdindex e3499199..7ed17b8e 100644--- a/.agents/work/deferred-actions.md+++ b/.agents/work/deferred-actions.md@@ -61,24 +61,40 @@ Two design consequences we adopt from the pattern:**path** only; validation at both ends, enforcement at the callback; nosigning (tampering can only pick a different page on our origin).- `agent_prefill` creates the agent (managed credential, default runtime +- model, random adjective-noun name) and lands on the agent's sessions tab- with the composer prefilled. **It does not create a session** — the first+ model, deterministic prompt-derived name) and lands on the agent's sessions+ tab with the composer prefilled. **It does not create a session** — the firstturn spends credits, so it happens on an explicit user keypress. This alsocloses the drive-by case: a malicious link can at worst create a freeagent, never spend money.- No confirm interstitial on `/do` (execution is free by construction). Aper-type `requiresConfirm` flag can be added to the registry when anaction type with real side effects arrives.-- Prompt cap at envelope validation: 4000 chars after trim, min 1.+- Prompt cap at envelope validation: **1000 chars** after trim, min 1. Kept+ in lockstep with the edge `returnTo` length cap (**4096**) — a longer+ prompt would make the `/do?action=` URL exceed what round-trips through+ the WorkOS `state` param on the anonymous signup path. WorkOS documents no+ `state` maximum, so we bound it ourselves rather than rely on a large+ round-trip.+- **Single entry — no `/?prompt=` shim.** There is exactly one way in:+ `/do?action=<envelope>`. The launch site mints that URL directly (it uses+ the same base64url algorithm as `encodeAction`). We deliberately do NOT+ add a `/?prompt=` compatibility path — one behavior, no fork.- **Attribution params are first-class passengers.** `utm_*`, ad click IDs(`gclid`, `fbclid`, …), and `ref` ride as sibling query params next to`action` — never inside the envelope — so analytics tools read them fromtheir standard positions. Everything that rewrites or strips URLs- preserves them: the shim carries them over, `/do` strips only `action`,- and `returnTo = pathname + search` round-trips them through auth- untouched. Our only reserved param names are `action` (on `/do`) and- `returnTo` (on `/auth/login`) — neither collides with any tracking- convention.+ preserves them: `/do` strips only `action`, and+ `returnTo = pathname + search` round-trips them through auth untouched.+ Our only reserved param names are `action` (on `/do`) and `returnTo` (on+ `/auth/login`) — neither collides with any tracking convention.+- **Deterministic agent name** (`agent_prefill`): derived from the prompt+ (slug + short stable hash), NOT random. So a retry — or the same link+ clicked twice — resolves to the same `(owner, name)` and `/v3/agents`+ create-or-get returns the existing agent instead of duplicating. That+ endpoint dedupes on `(owner, name)`; it has no idempotency-key path.+- **`safeReturnTo` rejects ASCII control chars** in addition to+ host/protocol/backslash tricks — a CR/LF surviving URL-decoding would+ corrupt or inject into the callback `Location` header.- `/do` sits OUTSIDE `ProtectedRoute` and owns its auth check. Reason: ananonymous arrival must fire `deferred_action_landed` while the UTM-ladenURL is live, BEFORE bouncing to login — behind ProtectedRoute the page@@ -129,14 +145,15 @@ export function decodeAction(raw: string): ActionEnvelope | null {}export const AgentPrefillParamsSchema = z.object({- prompt: z.string().trim().min(1).max(4000),+ prompt: z.string().trim().min(1).max(1000), // lockstep with edge returnTo cap})```-Also extract the name generator so `/do` and the create dialog share it:-move `NAME_ADJECTIVES`, `NAME_NOUNS`, `randomAgentName()` from-`web/src/pages/Agents.tsx:48-59` into a new `web/src/lib/agent-names.ts`-and import it back into `Agents.tsx` (no behavior change there).+The `agent_prefill` handler derives a **deterministic** name from the prompt+(a slug + short stable hash — `deriveAgentName`), so retries and repeat+clicks hit the same `(owner, name)` and dedupe server-side. (No shared+random-name module — `Agents.tsx` keeps its own `randomAgentName` for the+interactive create dialog, where fresh names are wanted.)### Step 2 — edge: `returnTo` through WorkOS `state`@@ -147,11 +164,13 @@ File: `cloudflare-workers/api-edge/src/index.ts`. Route dispatch is at```ts// Same-origin path only: no scheme, no host, no protocol-relative, no-// backslash tricks. Anything else → null (caller falls back to /dashboard).-export function safeReturnTo(raw: string | null): string | null {- if (!raw || raw.length > 2048) return null;+// backslash tricks, no control chars. Anything else → null (caller falls+// back to /dashboard). The 4096 cap is in lockstep with the prompt cap.+export function safeReturnTo(raw: string | null | undefined): string | null {+ if (!raw || raw.length > 4096) return null;if (!raw.startsWith("/") || raw.startsWith("//")) return null;if (raw.includes("\\")) return null;+ if (/[\u0000-\u001f\u007f]/.test(raw)) return null; // CR/LF header injectionreturn raw;}```@@ -276,20 +295,15 @@ Router state doesn't survive refresh — acceptable; the agent alreadyexists. Note the default tab for `/agents/:id` is overview (`:54-59`), sothe handler navigates to `/agents/:id/sessions` explicitly.-### Step 6 — SPA: legacy `/?prompt=` shim--The site already ships `/?prompt=<text>`. In `web/src/App.tsx`, wrap the-index route: a tiny inline component that checks-`window.location.search` for `prompt`; if present and non-blank, build the-envelope with `encodeAction({v: 1, type: 'agent_prefill', params: {prompt:-value.slice(0, 4000)}})`, and return `<Navigate to={...} replace />` where-the target is `/do?action=<encoded>` **plus every other query param-carried over verbatim** (delete `prompt` from a `URLSearchParams` copy, set-`action`, keep the rest — dropping `utm_*`/`gclid` here would silently-destroy attribution); otherwise render `<Dashboard />`. The site should-migrate its hero to mint `/do?action=...` URLs directly (one-line change in-`diggerhq/durableagentsessions`, separate repo — not this PR); the shim-keeps the shipped link working meanwhile.+### Step 6 — Site emits `/do?action=` directly (no shim)++**One way in, no fork.** The launch site (`diggerhq/durableagentsessions`,+separate repo) mints `/do?action=<envelope>` URLs in its hero, using the+same base64url algorithm as `encodeAction`, with any inbound `utm_*`/click+IDs appended as sibling params. No `/?prompt=` compatibility path is added+to the SPA — `App.tsx`'s index route stays `<Dashboard />`. (The site's+current `/?prompt=` hero is pre-launch and switches to `/do` as part of+shipping this; that one-line change lives in the site repo, not this PR.)### Step 7 — PostHog funnel events + attribution@@ -352,13 +366,16 @@ Automated (all must pass before push):to catch tsc -b project issues.- `cd cloudflare-workers/api-edge && npm test` — includes the new`safeReturnTo` cases.-- Envelope codec unit test (vitest is not set up under `web/` — if adding- it is disproportionate, cover the codec with a round-trip + malformed-- input test in the edge test file by copying the two pure functions'- behavior contract, or verify by hand in the browser console and say so in- the PR).-- Byte-scan the diff before push: `git diff origin/main | LC_ALL=C grep -P- '[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]'` must return nothing.+- `safeReturnTo` cases (cap, control chars, host/protocol tricks) live in+ the edge test file. The codec has no `web/`-side vitest yet — verify by+ hand in the browser console or add a runner later.+- Byte-scan the diff before push. **Do NOT use `grep -P` alone** — a NUL+ byte makes grep treat the file as binary and silently report no match+ (this bit us during the review round). Use a NUL-safe scan, e.g.+ `git diff origin/main | LC_ALL=C grep -aP '[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]'`+ (the `-a` forces text mode) and separately confirm no NUL:+ `git grep -I -l $'\x00' $(git diff --name-only origin/main)` returns+ nothing.Manual matrix (needs a deployed edge — record in the PR which rows ran;rows 1–2 need Igor's dev edge or a post-merge check, do not deploy from@@ -370,17 +387,19 @@ this branch):3. Logged-in → prompt box → immediate execution, no auth bounce.4. Logged-out, shared session URL (no action) → login → lands on thatsession, not `/dashboard` (generic returnTo works).-5. Tampered `returnTo` (`//evil.com`, `https://evil.com`, `\`) → `/dashboard`.+5. Tampered `returnTo` (`//evil.com`, `https://evil.com`, `\`, a `%0d%0a`+ CRLF) → `/dashboard`.6. Malformed / unknown-type envelope → unsupported-link screen.7. Refresh and back-button after execution → no duplicate agent (alsoverify in dev that StrictMode double-mount doesn't double-create).-8. `/?prompt=` legacy shim → identical outcome to 1–3.+8. Retry idempotency: force the create to fail once (offline), hit **Try+ again**, and re-run the same link twice — deterministic name means one+ agent, not several.9. Non-ASCII prompt (emoji, CJK) survives encode → decode → agent prompt.10. Attribution: `/do?action=...&utm_source=test&gclid=x` anonymous →signup → PostHog shows `deferred_action_landed` pre-auth with the UTM- props, and the identified person carries `$initial_utm_source=test`;- `/?prompt=...&utm_source=test` shim path preserves both params onto- `/do`.+ props, the `deferred_action_executed` event carries `agent_id`, and the+ identified person carries `$initial_utm_source=test`.## Failure modes (behavior contract)@@ -389,7 +408,7 @@ this branch):| Malformed / unknown-type / oversized action | Neutral "unsupported link" screen, dashboard link, `deferred_action_failed` || `returnTo` fails validation | Callback falls back to `/dashboard` (today's behavior) || Agent create fails (e.g. `managed_unavailable` 422) | `failed` state on `/do` with retry + dashboard link |-| Refresh / back after execution | Param already stripped; no replay. Re-visiting the same envelope later creates a second agent (random name) — visible, not silent; acceptable |+| Refresh / back after execution | Param already stripped; no replay. Re-visiting the same envelope later resolves to the same `(owner, name)` (deterministic name) → the existing agent, no duplicate || User abandons WorkOS mid-flow | Nothing created; the link works when clicked again || Email verification completed in another browser | `state` is bound to the WorkOS flow, not the browser — callback still lands on `returnTo` |@@ -401,3 +420,32 @@ this branch):- Site-side URL migration and this doc's write-backs are the coordinator's,not the implementer's. If a frozen decision looks wrong while building,stop and flag it in the PR description rather than improvising.++## Review round (2026-07-03) — changes from the first build++Reviewer findings, all addressed on the branch (code is authoritative where a+sketch above lagged):++1. **Length lockstep (the launch-path bug).** The prompt cap (was 4000) and+ the edge `returnTo` cap (was 2048) were inconsistent, so a valid long+ prompt silently dropped to `/dashboard` after signup. Fixed: prompt cap+ 1000, `returnTo` cap 4096, sized so the encoded `/do?action=` URL always+ fits the WorkOS `state` round-trip. WorkOS documents no `state` max, so we+ bound it ourselves.+2. **Dropped the `/?prompt=` shim entirely** (was behind ProtectedRoute, so+ it never got the pre-auth `/do` behavior anyway). One entry, no fork — the+ site emits `/do?action=` directly. Resolves the reviewer's finding 2 and+ the "no forking without reason" directive together.+3. **`safeReturnTo` rejects ASCII control chars** (CR/LF header injection),+ with edge tests.+4. **Retry-safe agent creation:** deterministic prompt-derived name (was+ random), so retry / repeat-click dedupes on `(owner, name)` instead of+ spawning duplicates. Reverted the now-unneeded `agent-names.ts`+ extraction — `Agents.tsx` keeps its own random name for the create dialog.+5. **Telemetry:** `deferred_action_executed` carries `agent_id` (via a+ handler `analytics` field) as the contract specified, not `navigate_to`.++Process note: the control-char regex was first written with **literal** NUL/+0x1f/0x7f bytes (compiles green, binary in git). The `grep -P` byte-scan+missed it — a NUL makes grep treat the file as binary and report no match.+Use the NUL-safe scan in Verification above.diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex 72c4a79d..3ade0855 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -329,8 +329,18 @@ describe("safeReturnTo — deferred-action deep-link validation", () => {expect(safeReturnTo("/a\\b")).toBeNull();expect(safeReturnTo("do?action=abc")).toBeNull();});- it("rejects oversized, empty, and nullish input", () => {- expect(safeReturnTo("/" + "a".repeat(3000))).toBeNull();+ it("rejects ASCII control chars (CR/LF header injection)", () => {+ expect(safeReturnTo("/do\r\nSet-Cookie: x=1")).toBeNull();+ expect(safeReturnTo("/do\n")).toBeNull();+ expect(safeReturnTo("/do\u0000")).toBeNull();+ expect(safeReturnTo("/do\u007f")).toBeNull();+ });+ it("accepts a long-but-bounded action, rejects over the cap", () => {+ const ok = "/do?action=" + "a".repeat(4000);+ expect(safeReturnTo(ok)).toBe(ok);+ expect(safeReturnTo("/" + "a".repeat(5000))).toBeNull();+ });+ it("rejects empty and nullish input", () => {expect(safeReturnTo("")).toBeNull();expect(safeReturnTo(null)).toBeNull();expect(safeReturnTo(undefined)).toBeNull();diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex d6212a8b..3f3783f5 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -1159,10 +1159,18 @@ interface WorkOSProfile {// backslash tricks. Tampering with the WorkOS `state` can then at most pick a// different page on our own origin, so the value needs no signing. Anything else// → null and the caller falls back to /dashboard.+//+// The 4096 cap is sized to comfortably fit an encoded /do?action=<envelope> for+// the 1000-char prompt limit (web/src/lib/deferred-actions.ts) through the+// WorkOS `state` round-trip — keep the two limits in sync. WorkOS documents no+// `state` maximum, so we bound it here rather than rely on a large round-trip.export function safeReturnTo(raw: string | null | undefined): string | null {- if (!raw || raw.length > 2048) return null;+ if (!raw || raw.length > 4096) return null;if (!raw.startsWith("/") || raw.startsWith("//")) return null;if (raw.includes("\\")) return null;+ // Reject ASCII control chars: a CR/LF surviving URL-decoding would corrupt or+ // inject into the callback's Location header (or throw a 500).+ if (/[\u0000-\u001f\u007f]/.test(raw)) return null;return raw;}diff --git a/web/src/App.tsx b/web/src/App.tsxindex 9769626d..f7a7c8e6 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -1,9 +1,8 @@import { lazy } from 'react'-import { Routes, Route, Navigate, useSearchParams } from 'react-router-dom'+import { Routes, Route, Navigate } from 'react-router-dom'import { AuthProvider } from './hooks/auth-provider'import ProtectedRoute from './components/ProtectedRoute'import AppShell from './components/app-shell'-import { encodeAction } from './lib/deferred-actions'// Route pages are code-split so the initial bundle stays small; the heaviest// deps (xterm, in Terminal/LogsPanel) only load on SandboxDetail when opened.@@ -24,29 +23,6 @@ const SandboxDetail = lazy(() => import('./pages/SandboxDetail'))const SandboxWebhooks = lazy(() => import('./pages/SandboxWebhooks'))const DeferredAction = lazy(() => import('./pages/DeferredAction'))-// Legacy shim: the launch site ships /?prompt=<text>. Rewrite it to the-// canonical /do?action=<envelope>, carrying every OTHER query param (utm_*,-// gclid, …) over verbatim so attribution survives. The site should mint-// /do URLs directly; this keeps the already-shipped link working.-function IndexRoute() {- const [sp] = useSearchParams()- const prompt = sp.get('prompt')?.trim()- if (prompt) {- const next = new URLSearchParams(sp)- next.delete('prompt')- next.set(- 'action',- encodeAction({- v: 1,- type: 'agent_prefill',- params: { prompt: prompt.slice(0, 4000) },- }),- )- return <Navigate to={`/do?${next.toString()}`} replace />- }- return <Dashboard />-}-export default function App() {return (<AuthProvider>@@ -56,7 +32,7 @@ export default function App() {<Route path="do" element={<DeferredAction />} /><Route element={<ProtectedRoute />}><Route element={<AppShell />}>- <Route index element={<IndexRoute />} />+ <Route index element={<Dashboard />} />{/* Agent plane */}<Route path="agents" element={<Agents />} /><Route path="agents/:agentId" element={<AgentDetail />} />diff --git a/web/src/lib/agent-names.ts b/web/src/lib/agent-names.tsdeleted file mode 100644index 75f3168f..00000000--- a/web/src/lib/agent-names.ts+++ /dev/null@@ -1,15 +0,0 @@-// Memorable adjective-noun names so creating an agent never blocks on naming.-// Shared by the create dialog (Agents.tsx) and the deferred-action executor.-const NAME_ADJECTIVES = [- 'swift', 'calm', 'bright', 'clever', 'bold', 'quiet', 'keen', 'brave',- 'nimble', 'sunny', 'lucid', 'witty', 'deft', 'mellow', 'crisp', 'vivid',-]-const NAME_NOUNS = [- 'otter', 'harbor', 'falcon', 'cedar', 'comet', 'delta', 'ember', 'fjord',- 'grove', 'heron', 'lynx', 'maple', 'nova', 'quartz', 'sparrow', 'willow',-]--export function randomAgentName(): string {- const pick = (a: readonly string[]) => a[Math.floor(Math.random() * a.length)]- return `${pick(NAME_ADJECTIVES)}-${pick(NAME_NOUNS)}`-}diff --git a/web/src/lib/deferred-actions.ts b/web/src/lib/deferred-actions.tsindex dc83412a..a36fd389 100644--- a/web/src/lib/deferred-actions.ts+++ b/web/src/lib/deferred-actions.ts@@ -10,7 +10,6 @@import { z } from 'zod'import { createAgent } from '@/api/client'import { DEFAULT_RUNTIME, defaultModelFor } from '@/lib/runtimes'-import { randomAgentName } from '@/lib/agent-names'export const ActionEnvelopeSchema = z.object({v: z.literal(1),@@ -21,6 +20,8 @@ export type ActionEnvelope = z.infer<typeof ActionEnvelopeSchema>// Unicode-safe base64url. btoa/atob operate on binary strings, so we round-trip// through UTF-8 bytes — a naive btoa(JSON.stringify(...)) throws on emoji/CJK.+// This is the reference encoder: the launch site mints /do?action= URLs with+// the identical algorithm, so keep them byte-compatible.export function encodeAction(envelope: ActionEnvelope): string {const bytes = new TextEncoder().encode(JSON.stringify(envelope))let bin = ''@@ -47,13 +48,38 @@ export function decodeAction(raw: string): ActionEnvelope | null {// Each returns where to navigate on success. Add a new action type by adding a// schema + a handler here and registering it below.-export type ActionResult = { navigateTo: string; navigateState?: unknown }+export type ActionResult = {+ navigateTo: string+ navigateState?: unknown+ // Extra props merged into the deferred_action_executed event (e.g. agent_id).+ analytics?: Record<string, unknown>+}export type ActionHandler = (params: unknown) => Promise<ActionResult>+// Cap kept in sync with the edge safeReturnTo length limit — a longer prompt+// would make the /do?action= URL exceed what round-trips through WorkOS `state`+// on the anonymous signup path (see cloudflare-workers/api-edge/src/index.ts).export const AgentPrefillParamsSchema = z.object({- prompt: z.string().trim().min(1).max(4000),+ prompt: z.string().trim().min(1).max(1000),})+// Deterministic agent name from the prompt so a retry — or the same link+// clicked twice — resolves to the SAME (owner, name) and the create-or-get+// endpoint returns the existing agent instead of spawning a duplicate.+// /v3/agents dedupes on (owner, name); it has no idempotency-key path.+function deriveAgentName(prompt: string): string {+ const slug = prompt+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 32)+ .replace(/-+$/g, '')+ let h = 0+ for (let i = 0; i < prompt.length; i++) h = (Math.imul(h, 31) + prompt.charCodeAt(i)) | 0+ const suffix = (h >>> 0).toString(36)+ return `${slug || 'agent'}-${suffix}`+}+// agent_prefill: create the agent (managed billing — free, zero-config for a// fresh org) and land on its sessions tab with the composer prefilled. It does// NOT start a session — the first turn spends credits, so it waits for an@@ -62,7 +88,7 @@ export const AgentPrefillParamsSchema = z.object({const agentPrefill: ActionHandler = async (params) => {const { prompt } = AgentPrefillParamsSchema.parse(params)const agent = await createAgent({- name: randomAgentName(),+ name: deriveAgentName(prompt),prompt,model: defaultModelFor(DEFAULT_RUNTIME),runtime: DEFAULT_RUNTIME,@@ -71,6 +97,7 @@ const agentPrefill: ActionHandler = async (params) => {return {navigateTo: `/agents/${agent.id}/sessions`,navigateState: { composerPrefill: prompt },+ analytics: { agent_id: agent.id },}}diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsxindex da414aae..419c3d1a 100644--- a/web/src/pages/Agents.tsx+++ b/web/src/pages/Agents.tsx@@ -3,7 +3,6 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { useNavigate } from 'react-router-dom'import { Bot, Plus } from 'lucide-react'import { notifyError } from '@/lib/errors'-import { randomAgentName } from '@/lib/agent-names'import {getAgents,createAgent,@@ -43,8 +42,20 @@ const NEW_CRED = '__new__'// Sent to the API as the reserved credential value "managed" (token-billing §6.6).const MANAGED = 'managed'-// Friendly starting default so "Create agent" works with a single click: a memorable-// random name (from @/lib/agent-names) + a usable general-purpose prompt.+// Friendly starting defaults so "Create agent" works with a single click: a memorable+// random name (adjective-noun) + a usable general-purpose prompt the user can keep or edit.+const NAME_ADJECTIVES = [+ 'swift', 'calm', 'bright', 'clever', 'bold', 'quiet', 'keen', 'brave',+ 'nimble', 'sunny', 'lucid', 'witty', 'deft', 'mellow', 'crisp', 'vivid',+]+const NAME_NOUNS = [+ 'otter', 'harbor', 'falcon', 'cedar', 'comet', 'delta', 'ember', 'fjord',+ 'grove', 'heron', 'lynx', 'maple', 'nova', 'quartz', 'sparrow', 'willow',+]+function randomAgentName(): string {+ const pick = (a: readonly string[]) => a[Math.floor(Math.random() * a.length)]+ return `${pick(NAME_ADJECTIVES)}-${pick(NAME_NOUNS)}`+}const DEFAULT_PROMPT ='You are a helpful AI assistant working in a sandboxed computer. Complete tasks end to end, use the tools available to you, and keep your answers clear and concise. When something is ambiguous, make a sensible assumption and say so.'diff --git a/web/src/pages/DeferredAction.tsx b/web/src/pages/DeferredAction.tsxindex 2fffe97a..e24a6e58 100644--- a/web/src/pages/DeferredAction.tsx+++ b/web/src/pages/DeferredAction.tsx@@ -51,8 +51,8 @@ export default function DeferredAction() {const result = await handler(env.params)posthog.capture('deferred_action_executed', {action_type: env.type,- navigate_to: result.navigateTo, // carries the created agent idms: Math.round(performance.now() - started),+ ...(result.analytics ?? {}), // e.g. agent_id})void navigate(result.navigateTo, {replace: true,