Skip to content

An open-source, faster Devin alternative

TypeScript

feat: deferred actions — deeplink intents that survive signup

Igor Zalutskia9b29d9e2ea2
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index 1647d865..72c4a79d 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import worker, { type Env } from "./index";
+import worker, { type Env, safeReturnTo } from "./index";
const orgID = "org-1";
const userID = "user-1";
@@ -313,3 +313,26 @@ describe("/internal/model-billing/enable — scoped-secret auth boundary", () =>
expect((await post("/internal/model-billing/enable", MANAGED, { ts: stale })).status).toBe(401);
});
});
+
+describe("safeReturnTo — deferred-action deep-link validation", () => {
+ it("accepts same-origin paths (incl. query strings)", () => {
+ expect(safeReturnTo("/do?action=abc")).toBe("/do?action=abc");
+ expect(safeReturnTo("/sessions/xyz")).toBe("/sessions/xyz");
+ expect(safeReturnTo("/")).toBe("/");
+ });
+ it("rejects absolute and protocol-relative URLs", () => {
+ expect(safeReturnTo("https://evil.com")).toBeNull();
+ expect(safeReturnTo("//evil.com")).toBeNull();
+ expect(safeReturnTo("javascript:alert(1)")).toBeNull();
+ });
+ it("rejects backslash tricks and non-path input", () => {
+ expect(safeReturnTo("/a\\b")).toBeNull();
+ expect(safeReturnTo("do?action=abc")).toBeNull();
+ });
+ it("rejects oversized, empty, and nullish input", () => {
+ expect(safeReturnTo("/" + "a".repeat(3000))).toBeNull();
+ 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.ts
index 98b383d4..d6212a8b 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1154,6 +1154,18 @@ interface WorkOSProfile {
organization_id?: string;
}
+// A post-login destination is only honored if it is a same-origin PATH: it must
+// start with a single "/", carry no host (no "//" protocol-relative form) and no
+// 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.
+export function safeReturnTo(raw: string | null | undefined): string | null {
+ if (!raw || raw.length > 2048) return null;
+ if (!raw.startsWith("/") || raw.startsWith("//")) return null;
+ if (raw.includes("\\")) return null;
+ return raw;
+}
+
async function authLogin(req: Request, env: Env): Promise<Response> {
const reqURL = new URL(req.url);
const redirectURI = `${reqURL.origin}/auth/callback`;
@@ -1164,6 +1176,11 @@ async function authLogin(req: Request, env: Env): Promise<Response> {
authURL.searchParams.set("provider", "authkit");
authURL.searchParams.set("redirect_uri", redirectURI);
authURL.searchParams.set("response_type", "code");
+ // Deferred deep link: carry the originally-requested path through WorkOS via
+ // the OAuth `state` param so the callback can land the user back on it (incl.
+ // a /do?action=… deferred action). Only same-origin paths survive validation.
+ const returnTo = safeReturnTo(reqURL.searchParams.get("returnTo"));
+ if (returnTo) authURL.searchParams.set("state", JSON.stringify({ returnTo }));
return Response.redirect(authURL.toString(), 302);
}
@@ -1271,12 +1288,23 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
// Issuer so cell middleware can distinguish.
const sessionJWT = await mintSessionJWT(env.SESSION_JWT_SECRET, orgID, userID, orgPlan, workosSessionID);
- // Redirect to dashboard with the cookie set.
- const dashURL = `${reqURL.origin}/dashboard`;
+ // Land on the deferred deep link if `state` carried a valid one, else the
+ // dashboard. Re-validate here: `state` is attacker-influenceable, so the path
+ // is only trusted after safeReturnTo passes a second time.
+ let returnTo: string | null = null;
+ const stateRaw = reqURL.searchParams.get("state");
+ if (stateRaw) {
+ try {
+ returnTo = safeReturnTo((JSON.parse(stateRaw) as { returnTo?: string }).returnTo);
+ } catch {
+ returnTo = null;
+ }
+ }
+ const landingURL = `${reqURL.origin}${returnTo ?? "/dashboard"}`;
return new Response(null, {
status: 302,
headers: {
- location: dashURL,
+ location: landingURL,
"set-cookie": `${SESSION_COOKIE}=${sessionJWT}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${SESSION_TTL_SEC}`,
},
});
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4a1570a9..9769626d 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -1,8 +1,9 @@
import { lazy } from 'react'
-import { Routes, Route, Navigate } from 'react-router-dom'
+import { Routes, Route, Navigate, useSearchParams } 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.
@@ -21,14 +22,41 @@ const Settings = lazy(() => import('./pages/Settings'))
const Billing = lazy(() => import('./pages/Billing'))
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>
<Routes>
+ {/* Deferred-action executor — outside ProtectedRoute so the anonymous
+ branch can fire analytics + capture returnTo before login. */}
+ <Route path="do" element={<DeferredAction />} />
<Route element={<ProtectedRoute />}>
<Route element={<AppShell />}>
- <Route index element={<Dashboard />} />
+ <Route index element={<IndexRoute />} />
{/* Agent plane */}
<Route path="agents" element={<Agents />} />
<Route path="agents/:agentId" element={<AgentDetail />} />
diff --git a/web/src/components/ProtectedRoute.tsx b/web/src/components/ProtectedRoute.tsx
index 31e54278..6fe0eb1b 100644
--- a/web/src/components/ProtectedRoute.tsx
+++ b/web/src/components/ProtectedRoute.tsx
@@ -10,9 +10,17 @@ export default function ProtectedRoute() {
// (proxied by Vite) that 302s to the WorkOS hosted login, so we do a
// full-page navigation rather than an in-app route. No intermediate
// "Sign in" screen — the spinner below shows until the browser leaves.
+ // Carry the requested URL as `returnTo` so the login round-trip lands the
+ // user back where they aimed (a shared session link, a /do deferred action)
+ // instead of the dashboard. The edge threads it through the WorkOS `state`.
useEffect(() => {
if (!loading && !user) {
- window.location.replace('/auth/login')
+ const returnTo = window.location.pathname + window.location.search
+ window.location.replace(
+ returnTo === '/'
+ ? '/auth/login'
+ : `/auth/login?returnTo=${encodeURIComponent(returnTo)}`,
+ )
}
}, [loading, user])
diff --git a/web/src/lib/agent-names.ts b/web/src/lib/agent-names.ts
new file mode 100644
index 00000000..75f3168f
--- /dev/null
+++ b/web/src/lib/agent-names.ts
@@ -0,0 +1,15 @@
+// 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.ts
new file mode 100644
index 00000000..dc83412a
--- /dev/null
+++ b/web/src/lib/deferred-actions.ts
@@ -0,0 +1,79 @@
+// Deferred actions — deeplink intents that survive signup.
+//
+// An action is a versioned, typed envelope base64url-encoded into the `action`
+// query param on the /do route. The URL is the store: no server-side intent
+// table, no TTL. Attribution params (utm_*, gclid, …) ride as SIBLING query
+// params next to `action`, never inside the envelope, so tracking tools read
+// them from their standard positions.
+//
+// Design + rationale: opencomputer .agents/work/deferred-actions.md
+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),
+ type: z.string().min(1),
+ params: z.record(z.string(), z.unknown()),
+})
+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.
+export function encodeAction(envelope: ActionEnvelope): string {
+ const bytes = new TextEncoder().encode(JSON.stringify(envelope))
+ let bin = ''
+ for (const b of bytes) bin += String.fromCharCode(b)
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+
+// Returns null on ANY malformed input (bad base64, bad JSON, schema miss) so
+// callers render one neutral "unsupported link" state.
+export function decodeAction(raw: string): ActionEnvelope | null {
+ try {
+ const b64 = raw.replace(/-/g, '+').replace(/_/g, '/')
+ const bin = atob(b64)
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0))
+ const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes))
+ const res = ActionEnvelopeSchema.safeParse(parsed)
+ return res.success ? res.data : null
+ } catch {
+ return null
+ }
+}
+
+// ── Handlers ─────────────────────────────────────────────────────────────────
+// 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 ActionHandler = (params: unknown) => Promise<ActionResult>
+
+export const AgentPrefillParamsSchema = z.object({
+ prompt: z.string().trim().min(1).max(4000),
+})
+
+// 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
+// explicit keypress. This also makes drive-by links harmless (a hostile link
+// can create a free agent at worst, never spend money).
+const agentPrefill: ActionHandler = async (params) => {
+ const { prompt } = AgentPrefillParamsSchema.parse(params)
+ const agent = await createAgent({
+ name: randomAgentName(),
+ prompt,
+ model: defaultModelFor(DEFAULT_RUNTIME),
+ runtime: DEFAULT_RUNTIME,
+ credential: 'managed',
+ })
+ return {
+ navigateTo: `/agents/${agent.id}/sessions`,
+ navigateState: { composerPrefill: prompt },
+ }
+}
+
+export const actionHandlers: Record<string, ActionHandler> = {
+ agent_prefill: agentPrefill,
+}
diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsx
index be186f7e..18394faa 100644
--- a/web/src/pages/AgentDetail.tsx
+++ b/web/src/pages/AgentDetail.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useNavigate, useParams } from 'react-router-dom'
+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import { ArrowLeft, MessagesSquare, Send, GitBranch } from 'lucide-react'
import { notifyError } from '@/lib/errors'
import {
@@ -120,7 +120,14 @@ export default function AgentDetail() {
}
// ── Start a session (used by the Sessions tab composer) ────────────────────
- const [task, setTask] = useState('')
+ // Seed from a deferred action's prefill (agent_prefill lands here via router
+ // state). Doesn't survive refresh — fine; the agent already exists.
+ const location = useLocation()
+ const [task, setTask] = useState(
+ () =>
+ (location.state as { composerPrefill?: string } | null)?.composerPrefill ??
+ '',
+ )
// Optional working repo — the repo the agent checks out + opens PRs from. Explicitly chosen,
// never derived from the connected/config repo (design 010 §2).
const [workingRepo, setWorkingRepo] = useState<WorkingRepo | null>(null)
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
index 419c3d1a..da414aae 100644
--- a/web/src/pages/Agents.tsx
+++ b/web/src/pages/Agents.tsx
@@ -3,6 +3,7 @@ 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,
@@ -42,20 +43,8 @@ const NEW_CRED = '__new__'
// Sent to the API as the reserved credential value "managed" (token-billing §6.6).
const MANAGED = 'managed'
-// 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)}`
-}
+// Friendly starting default so "Create agent" works with a single click: a memorable
+// random name (from @/lib/agent-names) + a usable general-purpose prompt.
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.tsx
new file mode 100644
index 00000000..2fffe97a
--- /dev/null
+++ b/web/src/pages/DeferredAction.tsx
@@ -0,0 +1,167 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Link, useNavigate } from 'react-router-dom'
+import { Loader2 } from 'lucide-react'
+import posthog from 'posthog-js'
+import { useAuth } from '@/hooks/useAuth'
+import { Button } from '@/components/ui/button'
+import {
+ actionHandlers,
+ decodeAction,
+ type ActionEnvelope,
+} from '@/lib/deferred-actions'
+
+// /do — the deferred-action executor. Reads ?action=<envelope>, and:
+// - anonymous → captures the pre-auth `landed` event, then bounces to WorkOS
+// login carrying the full URL as returnTo (so we come back here and run).
+// - authenticated → executes the action once, strips the param, navigates.
+// It lives OUTSIDE ProtectedRoute so the anonymous branch can fire analytics
+// while the attribution-laden URL is still live.
+
+// Decode the action from the live URL. Captured ONCE in state at mount, before
+// runAction strips the param — computing it during render would flip to null
+// after the strip.
+function readEnvelope(): ActionEnvelope | null {
+ const raw = new URLSearchParams(window.location.search).get('action')
+ return raw ? decodeAction(raw) : null
+}
+
+export default function DeferredAction() {
+ const { user, loading } = useAuth()
+ const navigate = useNavigate()
+ const [envelope] = useState(readEnvelope)
+ const supported = !!envelope && !!actionHandlers[envelope.type]
+ // Non-null while showing the failure screen; holds the error message.
+ const [failure, setFailure] = useState<string | null>(null)
+ // One-shot guard: StrictMode double-invokes effects on the same fiber, so a
+ // ref set before the first async hop keeps createAgent from running twice.
+ const executedRef = useRef(false)
+
+ const runAction = useCallback(
+ async (env: ActionEnvelope) => {
+ const handler = actionHandlers[env.type]
+ if (!handler) return
+ // Strip ONLY `action` before executing — keep utm_*/gclid siblings live
+ // for the analytics session — so refresh/back can't replay the create.
+ const url = new URL(window.location.href)
+ url.searchParams.delete('action')
+ window.history.replaceState(null, '', url.pathname + url.search)
+
+ const started = performance.now()
+ try {
+ const result = await handler(env.params)
+ posthog.capture('deferred_action_executed', {
+ action_type: env.type,
+ navigate_to: result.navigateTo, // carries the created agent id
+ ms: Math.round(performance.now() - started),
+ })
+ void navigate(result.navigateTo, {
+ replace: true,
+ state: result.navigateState,
+ })
+ } catch (e) {
+ posthog.capture('deferred_action_failed', {
+ action_type: env.type,
+ reason: 'api_error',
+ })
+ setFailure(e instanceof Error ? e.message : 'Something went wrong.')
+ }
+ },
+ [navigate],
+ )
+
+ useEffect(() => {
+ if (executedRef.current) return
+
+ // Structurally invalid → record why and stop; no auth needed to show this.
+ if (!supported) {
+ executedRef.current = true
+ posthog.capture('deferred_action_failed', {
+ action_type: envelope?.type ?? null,
+ reason: envelope ? 'unknown_type' : 'malformed',
+ })
+ return
+ }
+ if (loading) return // wait for auth to resolve before choosing the branch
+
+ if (!user) {
+ // Anonymous: record the top of the funnel while the URL is intact, then
+ // hand off to login. sendBeacon so the batched event survives the nav.
+ executedRef.current = true
+ posthog.capture(
+ 'deferred_action_landed',
+ { action_type: envelope.type, authenticated: false },
+ { transport: 'sendBeacon' },
+ )
+ const returnTo = window.location.pathname + window.location.search
+ window.location.replace(
+ `/auth/login?returnTo=${encodeURIComponent(returnTo)}`,
+ )
+ return
+ }
+
+ executedRef.current = true
+ posthog.capture('deferred_action_landed', {
+ action_type: envelope.type,
+ authenticated: true,
+ })
+ // runAction only setStates after an await (network I/O); the rule can't see
+ // through the callback and reads it as a synchronous effect setState.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ void runAction(envelope)
+ }, [loading, user, supported, envelope, runAction])
+
+ const retry = () => {
+ if (!envelope) return
+ setFailure(null)
+ void runAction(envelope)
+ }
+
+ return (
+ <div className="bg-background flex min-h-screen flex-col items-center justify-center gap-4 px-6 text-center">
+ {!supported ? (
+ <>
+ <p className="text-foreground text-sm font-medium">
+ This link isn&rsquo;t supported.
+ </p>
+ <p className="text-muted-foreground max-w-sm text-sm">
+ It may be from a newer version of the site. Head to your dashboard to
+ keep going.
+ </p>
+ <Link
+ to="/"
+ className="text-foreground text-sm underline underline-offset-4"
+ >
+ Go to dashboard
+ </Link>
+ </>
+ ) : failure !== null ? (
+ <>
+ <p className="text-foreground text-sm font-medium">
+ Couldn&rsquo;t set up your agent.
+ </p>
+ {failure && (
+ <p className="text-muted-foreground max-w-sm text-sm">{failure}</p>
+ )}
+ <div className="flex items-center gap-3">
+ <Button size="sm" onClick={retry}>
+ Try again
+ </Button>
+ <Link
+ to="/"
+ className="text-muted-foreground text-sm underline underline-offset-4"
+ >
+ Go to dashboard
+ </Link>
+ </div>
+ </>
+ ) : (
+ <>
+ <Loader2 className="text-muted-foreground size-5 animate-spin" />
+ <span className="text-muted-foreground font-mono text-xs tracking-wide">
+ Setting up your agent&hellip;
+ </span>
+ </>
+ )}
+ </div>
+ )
+}