From 883c190cd5c119bbeaea7d97e49a5b79fd09131d Mon Sep 17 00:00:00 2001 From: Jason Benn Date: Mon, 23 Nov 2026 02:53:31 -0800 Subject: [PATCH 1/2] feat(web): /inbox?compose= link opens a pre-filled new-session composer A page outside the app (a day view) can start the right session in one click: draft, optional task binding, agent and folder. Untrusted text is cleaned and nothing sends on its own; task binding now follows workspace access. Codecast-Session: https://codecast.sh/conversation/jx7c455r6jxsf98s5zk5xt1ajs8jrkrp --- .../convex/convex/assistant.entry.test.ts | 41 +++ packages/convex/convex/dispatch.ts | 18 +- packages/convex/convex/dispatchHelpers.ts | 13 +- packages/web/app/inbox/QueuePageClient.tsx | 4 + packages/web/components/ComposeView.tsx | 23 +- .../__tests__/useComposeLink.mount.test.tsx | 279 ++++++++++++++++++ packages/web/hooks/useComposeLink.ts | 118 ++++++++ packages/web/lib/composeLink.test.ts | 247 ++++++++++++++++ packages/web/lib/composeLink.ts | 203 +++++++++++++ packages/web/lib/defaultAgent.test.ts | 7 + packages/web/lib/defaultAgent.ts | 11 +- packages/web/store/composeSlice.ts | 10 +- packages/web/store/contextSessionLink.test.ts | 20 ++ packages/web/store/inboxStore.ts | 1 + packages/web/store/viewNav.ts | 7 +- 15 files changed, 976 insertions(+), 26 deletions(-) create mode 100644 packages/web/hooks/__tests__/useComposeLink.mount.test.tsx create mode 100644 packages/web/hooks/useComposeLink.ts create mode 100644 packages/web/lib/composeLink.test.ts create mode 100644 packages/web/lib/composeLink.ts diff --git a/packages/convex/convex/assistant.entry.test.ts b/packages/convex/convex/assistant.entry.test.ts index f6b2c9b243..08cd054957 100644 --- a/packages/convex/convex/assistant.entry.test.ts +++ b/packages/convex/convex/assistant.entry.test.ts @@ -149,6 +149,47 @@ describe("startConversation", () => { expect(commands).toHaveLength(0); }); + test("a hosted stub started for a task is linked to it, as a machine session is", async () => { + // A compose link (/inbox?task=ct-N) on the hosted assistant: the create + // carries the task as linked_object and the session lands on the task. + const { t, user, authed } = await setup(); + const taskId = await t.run((ctx) => ctx.db.insert("tasks", { + user_id: user, short_id: "ct-77", title: "Link me", status: "open", task_type: "task", priority: "medium", + created_at: Date.now(), updated_at: Date.now(), workspace: `user:${user}`, + } as any)); + const args = [{ agent_type: "codecast", session_id: "stub-task", first_message: "Let's do this task ct-77", first_message_client_id: "client-t", linked_object: { type: "task", id: taskId } }]; + await authed.mutation(api.dispatch.dispatch, { action: "createSession", args }); + const { conv, task } = await t.run(async (ctx) => ({ + conv: await ctx.db.query("conversations").withIndex("by_session_id", (q) => q.eq("session_id", "stub-task")).first(), + task: await ctx.db.get(taskId), + })); + expect((task as any).conversation_ids?.map(String)).toContain(String(conv!._id)); + }); + + test("a task private to its owner inside a team is not a teammate's to link", async () => { + // Access is the task's workspace (user:), never its team: a + // teammate's create naming it starts the session and leaves the task alone. + const { t, user: owner } = await setup(); + const { mate, taskId } = await t.run(async (ctx) => { + const mate = await ctx.db.insert("users", { emailVerificationTime: 1 }); + const team = await ctx.db.insert("teams", { name: "T", created_at: Date.now() } as any); + for (const u of [owner, mate]) await ctx.db.insert("team_memberships", { user_id: u, team_id: team, role: "member", joined_at: Date.now() } as any); + const taskId = await ctx.db.insert("tasks", { + user_id: owner, team_id: team, short_id: "ct-78", title: "Mine", status: "open", task_type: "task", priority: "medium", + created_at: Date.now(), updated_at: Date.now(), workspace: `user:${owner}`, + } as any); + return { mate, taskId }; + }); + const args = [{ agent_type: "codecast", session_id: "stub-mate", linked_object: { type: "task", id: taskId } }]; + await t.withIdentity({ subject: mate }).mutation(api.dispatch.dispatch, { action: "createSession", args }); + const { conv, task } = await t.run(async (ctx) => ({ + conv: await ctx.db.query("conversations").withIndex("by_session_id", (q) => q.eq("session_id", "stub-mate")).first(), + task: await ctx.db.get(taskId), + })); + expect(conv).not.toBeNull(); + expect((task as any).conversation_ids ?? []).toEqual([]); + }); + test("refuses a session id another conversation holds", async () => { const { t, user, authed } = await setup(); await t.run((ctx) => ctx.db.insert("conversations", { diff --git a/packages/convex/convex/dispatch.ts b/packages/convex/convex/dispatch.ts index 9b71b32cb5..c72b47d6ea 100644 --- a/packages/convex/convex/dispatch.ts +++ b/packages/convex/convex/dispatch.ts @@ -91,7 +91,7 @@ import { hideConversationForViewer, unhideConversationForViewer } from "./inboxH import { patchCommentWithRevision } from "./commentViewWrites"; import { getComment } from "./commentStore"; import type { CommentId } from "./lib/conversationCommentRows"; -import { canAccessConversation, canAccessProject, requireTeamMembership } from "./lib/access"; +import { canAccessConversation, canAccessProject, canAccessTask, requireTeamMembership } from "./lib/access"; import { patchConversationVisibility } from "./lib/conversationVisibility"; import { enqueueConfigCommand } from "./users"; import { patchConversationThroughFavoriteView } from "./favoriteViewWrites"; @@ -1037,6 +1037,15 @@ const SIDE_EFFECTS: Record = { firstMessage: opts.first_message, first_message_client_id: opts.first_message_client_id, }); + // A hosted session started for a task or doc (a compose link, a context + // chat) is linked to it the same way a machine session is below. + if (opts.linked_object?.id) { + await linkConversationToObject(ctx, userId, opts.linked_object.type, opts.linked_object.id, started.conversation_id); + // Born bound to a task a lead owns: the lead's, as below (S35). + if (opts.linked_object.type === "task") { + await (ctx as any).scheduler?.runAfter(0, internal.sessionOwnership.reconcileHold, { conversation_id: started.conversation_id }); + } + } return started.conversation_id; } const sessionId = opts.session_id || crypto.randomUUID(); @@ -1116,12 +1125,7 @@ const SIDE_EFFECTS: Record = { linkedTask = await ctx.db.get(opts.linked_object.id as Id<"tasks">); } catch { linkedTask = null; } if (linkedTask) { - const hasAccess = linkedTask.user_id.toString() === userId.toString() - || (linkedTask.team_id && !!(await ctx.db - .query("team_memberships") - .withIndex("by_user_team", (q: any) => q.eq("user_id", userId).eq("team_id", linkedTask.team_id)) - .first())); - if (!hasAccess) { + if (!(await canAccessTask(ctx as any, userId, linkedTask))) { linkedTask = null; } else { // Resolve project_path/git_root/git_remote_url from the task. Shared diff --git a/packages/convex/convex/dispatchHelpers.ts b/packages/convex/convex/dispatchHelpers.ts index aa5d0988ce..ea85440bee 100644 --- a/packages/convex/convex/dispatchHelpers.ts +++ b/packages/convex/convex/dispatchHelpers.ts @@ -4,6 +4,7 @@ import type { Id } from "./_generated/dataModel"; import { claimTaskOwnership } from "./lib/taskOwner"; import { addConversationToWorkItem } from "./conversationLinks"; +import { canAccessTask } from "./lib/access"; export type HandlerCtx = { db: any; storage?: any; runMutation?: any; runQuery?: any }; @@ -78,15 +79,9 @@ export async function linkConversationToObject( if (objectType === "task") { const task = await ctx.db.get(objectId as Id<"tasks">); - if (!task) return; - if (task.user_id.toString() !== userId.toString()) { - if (!task.team_id) return; - const membership = await ctx.db - .query("team_memberships") - .withIndex("by_user_team", (q: any) => q.eq("user_id", userId).eq("team_id", task.team_id)) - .first(); - if (!membership) return; - } + // Access is the task's workspace, never its team: a task private to its + // owner inside a team is not a teammate's to link and take. + if (!task || !(await canAccessTask(ctx as any, userId, task))) return; // The list append and the association rail (best-effort; legacy fields // stay authoritative) are one helper — see conversationLinks.ts. await addConversationToWorkItem(ctx, userId, "task", task, conversationId); diff --git a/packages/web/app/inbox/QueuePageClient.tsx b/packages/web/app/inbox/QueuePageClient.tsx index aef3591d7a..eba6050a2d 100644 --- a/packages/web/app/inbox/QueuePageClient.tsx +++ b/packages/web/app/inbox/QueuePageClient.tsx @@ -8,6 +8,7 @@ import { useMissingSessionLookup } from "../../hooks/useMissingSessionRow"; import { SessionPrewarm } from "../../components/SessionPrewarm"; import { useRouter, useSearchParams } from "next/navigation"; import { useTabActive } from "../../hooks/usePagePresence"; +import { useComposeLink } from "../../hooks/useComposeLink"; import { urlSessionId } from "../../lib/pathLabel"; import { ConversationUnavailable } from "../../components/ConversationUnavailable"; import { Id } from "@codecast/convex/convex/_generated/dataModel"; @@ -380,6 +381,9 @@ export function QueuePageClient() { // and scroll position survive untouched until it's brought forward again. // Outside the tab shell (web standalone), there's no context → always active. const isActiveTab = useTabActive(); + // `/inbox?compose=…`: a link from outside opens the new-session composer + // with its draft (lib/composeLink). + useComposeLink(isActiveTab); // The session rail's route defaults (auto-open on entering the inbox) live // in DashboardLayout's navigation effects, gated so a tab switch — which diff --git a/packages/web/components/ComposeView.tsx b/packages/web/components/ComposeView.tsx index ff6c748420..cdd5f6989b 100644 --- a/packages/web/components/ComposeView.tsx +++ b/packages/web/components/ComposeView.tsx @@ -144,7 +144,7 @@ export function ComposeView({ initialQuery, context, onClose, closeGuardRef, ins // A resumed draft keeps its agent; otherwise the caller's agent, then the // conversation on screen's, carries over, and the default // (lib/defaultAgent: the hosted assistant with no machine) fills in. - const agentType = resumed?.agent_type || newConversationAgentType(store, context?.agentType ?? ctx.agentType); + const agentType = resumed?.agent_type || newConversationAgentType(store, ctx.agentType, context?.agentType); // Shared optimistic-create path — see store.beginOptimisticSession. // deferCreate: opening the popup seeds ONLY a local stub (so the null-state @@ -170,6 +170,18 @@ export function ComposeView({ initialQuery, context, onClose, closeGuardRef, ins if (instance) store.bindComposeStub(instance.id, sid); if (initialQuery) store.setDraft(sid, { draft_message: initialQuery }); + // A composer opened for a task (a compose link) is born bound to it: the + // create carries the stub's _linkedObject (createSessionFromStub), and the + // server links the session and makes it the task's owner in the same + // transaction, as the task list's start does. active_task is the new + // session's task badge (header, sidebar) from its first optimistic paint, + // as ContextChatInput sets it; the composer itself draws no task chip. + const task = context?.linkedTask; + if (task && sid !== resumeStubId) { + const activeTask = { _id: task._id, short_id: task.short_id, title: task.title, status: task.status }; + store.syncRecord("sessions", sid, { _linkedObject: { type: "task", id: task._id }, active_task: activeTask }); + store.syncRecord("conversations", sid, { active_task_id: task._id, active_task: activeTask }); + } setSessionId(sid); setRestored(sid === resumeStubId); setSkillCtx({ projectPath: (sid === resumeStubId ? resumed?.project_path : path) || undefined, agentType }); @@ -213,7 +225,14 @@ export function ComposeView({ initialQuery, context, onClose, closeGuardRef, ins // refs) expects typing to append, but focus() alone leaves the caret at 0. ta.setSelectionRange(ta.value.length, ta.value.length); }; - const t = setTimeout(focusInput, 60); + // A seeded draft taller than the box would open at its top, the lines + // under the edge out of sight of the person about to press Enter (a + // compose link's untrusted text above all): show the caret's end. + const showCaret = () => { + const ta = initialQuery ? rootRef.current?.querySelector("textarea") : null; + if (ta) ta.scrollTop = ta.scrollHeight; + }; + const t = setTimeout(() => { focusInput(); showCaret(); }, 60); window.addEventListener("focus", focusInput); return () => { clearTimeout(t); diff --git a/packages/web/hooks/__tests__/useComposeLink.mount.test.tsx b/packages/web/hooks/__tests__/useComposeLink.mount.test.tsx new file mode 100644 index 0000000000..a22a1b09b8 --- /dev/null +++ b/packages/web/hooks/__tests__/useComposeLink.mount.test.tsx @@ -0,0 +1,279 @@ +// A compose link opened on the inbox: the composer opens once with the link's +// draft, bound to its task when the viewer can see the task, and the address +// loses the link's parameters. Whatever the link names that does not resolve +// (a task the server will not hand over, an unknown folder or agent, a server +// that never answers) leaves a plain composer with the draft. +import { afterAll, beforeEach, expect, mock, test } from "bun:test"; +import { JSDOM } from "jsdom"; +import * as React from "react"; +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { MemoryRouter, Route, Routes, useLocation, useNavigate } from "react-router"; +import { closeDomWindow } from "../../test-helpers/domGlobals"; + +const dom = new JSDOM("
", { url: "https://codecast.test/inbox", pretendToBeVisual: true }); +for (const key of ["window", "document", "navigator", "HTMLElement", "Element", "Node", "MutationObserver", "Event"]) { + Object.defineProperty(globalThis, key, { value: (dom.window as any)[key], configurable: true, writable: true }); +} +(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; + +let location = { pathname: "/inbox", search: "" }; +const replaced: string[] = []; +mock.module("next/navigation", () => ({ + useRouter: () => { + const navigate = useNavigate(); + return React.useMemo(() => ({ + replace: (url: string) => { replaced.push(url); navigate(url, { replace: true }); }, + push: (url: string) => navigate(url), + }), [navigate]); + }, + useSearchParams: () => { + const loc = useLocation(); + location = { pathname: loc.pathname, search: loc.search }; + return new URLSearchParams(loc.search); + }, + usePathname: () => useLocation().pathname, +})); + +// The task the server hands back: undefined (not answered), null (not +// visible to this viewer), or the row. Asked-for ids are recorded. +let taskAnswer: any = undefined; +const asked: (string | undefined)[] = []; +const listeners = new Set<() => void>(); +const setTaskAnswer = (v: any) => { taskAnswer = v; listeners.forEach((l) => l()); }; +const realTasks = { ...(await import("../useSyncTasks")) }; +mock.module("../useSyncTasks", () => ({ + ...realTasks, + useSyncTaskDetail: (id?: string) => { + asked.push(id); + const v = React.useSyncExternalStore((cb) => { listeners.add(cb); return () => listeners.delete(cb); }, () => taskAnswer); + return id ? v : undefined; + }, +})); + +// Whether the socket has confirmed who is signed in. +let authed = true; +const authListeners = new Set<() => void>(); +const setAuthed = (v: boolean) => { authed = v; authListeners.forEach((l) => l()); }; +const realConvex = { ...(await import("convex/react")) }; +mock.module("convex/react", () => ({ + ...realConvex, + useConvexAuth: () => ({ + isLoading: false, + isAuthenticated: React.useSyncExternalStore((cb) => { authListeners.add(cb); return () => authListeners.delete(cb); }, () => authed), + }), +})); + +// What the person is told: a loading notice while a task link waits, and a +// notice when a task link opens without its task. +const toasts: string[] = []; +const realSonner = { ...(await import("sonner")) }; +mock.module("sonner", () => ({ + ...realSonner, + toast: Object.assign((m: string) => { toasts.push(m); }, { + loading: (m: string, o?: { id?: string }) => { toasts.push(`loading: ${m}`); return o?.id ?? 1; }, + dismiss: () => { toasts.push("dismiss"); }, + }), +})); + +const { useInboxStore } = await import("../../store/inboxStore"); +const { useComposeLink, composeLinkWait } = await import("../useComposeLink"); +composeLinkWait.ms = 300; + +const opened: Array<{ text?: string; context?: any }> = []; +// The page's own navigate, for a second link arriving on a mounted page (a +// desktop deep link into the app that is already open). +let go: (url: string) => void = () => {}; +function Probe({ active = true }: { active?: boolean }) { + useComposeLink(active); + const navigate = useNavigate(); + go = (url) => navigate(url); + return null; +} + +let root: Root; +let mounts = 0; +const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 10)); }); +const open = async (url: string, active = true) => { + await act(async () => root.render( + + } /> + , + )); + await flush(); +}; + +beforeEach(() => { + root?.unmount(); + document.body.innerHTML = "
"; + root = createRoot(document.getElementById("root")!); + opened.length = 0; + replaced.length = 0; + asked.length = 0; + toasts.length = 0; + taskAnswer = undefined; + authed = true; + useInboxStore.setState({ + clientStateInitialized: true, + machineRosterLive: true, + machineRoster: [{ device_id: "d1", local_project_roots: ["/Users/me/code/app"] }] as any, + recentProjects: [{ path: "/Users/me/code/app", count: 3, lastActive: 1 }], + openCompose: ((text?: string, context?: any) => { opened.push({ text, context }); }) as any, + } as any); +}); + +afterAll(() => { + root?.unmount(); + closeDomWindow(dom); +}); + +test("a plain draft opens the composer with exactly that text and leaves the address clean", async () => { + await open("/inbox?compose=About%20in-22%20Infrastructure%3A%20&s=keep"); + expect(opened).toEqual([{ text: "About in-22 Infrastructure: ", context: {} }]); + expect(toasts).toEqual([]); + expect(replaced).toEqual(["/inbox?s=keep"]); + expect(location.search).toBe("?s=keep"); +}); + +test("a task the viewer can see binds the session and starts in its folder", async () => { + await open("/inbox?task=ct-42"); + expect(opened).toEqual([]); + expect(asked).toContain("ct-42"); + await act(async () => setTaskAnswer({ _id: "k1", short_id: "ct-42", title: "Ship it", status: "open", project_path: "/Users/me/code/app" })); + await flush(); + expect(opened).toEqual([{ + text: "Let's do this task ct-42 ", + context: { projectPath: "/Users/me/code/app", gitRoot: "/Users/me/code/app", linkedTask: { _id: "k1", short_id: "ct-42", title: "Ship it", status: "open" } }, + }]); + expect(toasts).toEqual(["loading: Opening ct-42…", "dismiss", "dismiss"]); + expect(location.search).toBe(""); +}); + +test("a task the server will not hand over (unknown, or another workspace's) leaves a plain composer with the draft", async () => { + await open("/inbox?compose=Look%20at%20this&task=ct-999"); + await act(async () => setTaskAnswer(null)); + await flush(); + expect(opened).toEqual([{ text: "Look at this", context: {} }]); + expect(toasts).toEqual(["loading: Opening ct-999…", "dismiss", "ct-999 isn't a task you can open, so this session won't be linked to it", "dismiss"]); +}); + +test("an answer for a different task is never bound", async () => { + await open("/inbox?compose=x&task=ct-1"); + await act(async () => setTaskAnswer({ _id: "k2", short_id: "ct-2", title: "Other", status: "open" })); + await flush(); + expect(opened).toEqual([{ text: "x", context: {} }]); +}); + +test("an unknown folder and an unknown agent are dropped; known ones carry", async () => { + await open("/inbox?compose=x&project=%2Fetc&agent=gpt"); + expect(opened).toEqual([{ text: "x", context: {} }]); + expect(toasts).toEqual(['No folder "/etc" on your machines, so this session starts in your usual one']); + toasts.length = 0; + await open("/inbox?compose=y&project=app&agent=codex"); + expect(toasts).toEqual([]); + expect(opened[1]).toEqual({ text: "y", context: { projectPath: "/Users/me/code/app", gitRoot: "/Users/me/code/app", agentType: "codex" } }); +}); + +test("a server that never answers still opens the draft after the wait", async () => { + await open("/inbox?compose=late&task=ct-5"); + expect(opened).toEqual([]); + await act(async () => { await new Promise((r) => setTimeout(r, 400)); }); + expect(opened).toEqual([{ text: "late", context: {} }]); +}, 10_000); + +test("it waits for the person's settings before opening", async () => { + useInboxStore.setState({ clientStateInitialized: false } as any); + await open("/inbox?compose=wait"); + expect(opened).toEqual([]); + await act(async () => useInboxStore.setState({ clientStateInitialized: true } as any)); + await flush(); + expect(opened).toEqual([{ text: "wait", context: {} }]); +}); + +test("a background tab does nothing, and a link opens one composer however often it renders", async () => { + await open("/inbox?compose=bg", false); + expect(opened).toEqual([]); + expect(replaced).toEqual([]); + await open("/inbox?compose=once"); + await act(async () => useInboxStore.setState({ machineRosterLive: false } as any)); + await act(async () => useInboxStore.setState({ machineRosterLive: true } as any)); + await flush(); + expect(opened.map((o) => o.text)).toEqual(["once"]); +}); + +test("a 'not found' answered before the socket is signed in settles nothing", async () => { + setAuthed(false); + await open("/inbox?compose=go&task=ct-42"); + await act(async () => setTaskAnswer(null)); + await flush(); + expect(opened).toEqual([]); + // The task is not even asked for until the socket knows the caller. + expect(asked.filter(Boolean)).toEqual([]); + await act(async () => setTaskAnswer({ _id: "k1", short_id: "ct-42", title: "Ship it", status: "open" })); + await act(async () => setAuthed(true)); + await flush(); + expect(asked).toContain("ct-42"); + expect(opened).toEqual([{ text: "go ct-42 ", context: { linkedTask: { _id: "k1", short_id: "ct-42", title: "Ship it", status: "open" } } }]); +}); + +test("one link's timeout does not rush the next link on the same page", async () => { + await open("/inbox?compose=first&task=ct-5"); + await act(async () => { await new Promise((r) => setTimeout(r, 400)); }); + expect(opened.map((o) => o.text)).toEqual(["first"]); + await act(async () => go("/inbox?task=ct-6")); + await flush(); + expect(opened).toHaveLength(1); + await act(async () => setTaskAnswer({ _id: "k6", short_id: "ct-6", title: "Six", status: "open" })); + await flush(); + expect(opened[1]?.context?.linkedTask?.short_id).toBe("ct-6"); +}, 10_000); + +test("a folder the task pins wins over the link's, as on the server", async () => { + useInboxStore.setState({ projects: { p1: { _id: "p1", project_path: "/Users/me/code/app" } } } as any); + await open("/inbox?task=ct-8&project=%2FUsers%2Fme%2Fcode%2Fapp%2Fsub"); + await act(async () => setTaskAnswer({ _id: "k8", short_id: "ct-8", title: "Eight", status: "open", project_id: "p1" })); + await flush(); + expect(opened[0]?.context?.projectPath).toBe("/Users/me/code/app"); + await open("/inbox?task=ct-9&project=%2FUsers%2Fme%2Fcode%2Fapp%2Fsub"); + await act(async () => setTaskAnswer({ _id: "k9", short_id: "ct-9", title: "Nine", status: "open" })); + await flush(); + expect(opened[1]?.context?.projectPath).toBe("/Users/me/code/app/sub"); +}); + +test("the same link clicked again after a timeout waits again", async () => { + await open("/inbox?compose=a&task=ct-5"); + await act(async () => { await new Promise((r) => setTimeout(r, 400)); }); + expect(opened).toHaveLength(1); + await act(async () => go("/inbox?compose=a&task=ct-5")); + await flush(); + expect(opened).toHaveLength(1); + await act(async () => setTaskAnswer({ _id: "k5", short_id: "ct-5", title: "Five", status: "open" })); + await flush(); + expect(opened[1]?.context?.linkedTask?.short_id).toBe("ct-5"); +}, 10_000); + +test("a task row left in the store binds nothing the server will not hand over", async () => { + // The store keeps rows from workspaces the viewer has left: the server decides. + useInboxStore.setState({ tasks: { k3: { _id: "k3", short_id: "ct-3", title: "Three", status: "open" } } } as any); + await open("/inbox?compose=go&task=ct-3"); + expect(opened).toEqual([]); + await act(async () => setTaskAnswer(null)); + await flush(); + expect(opened).toEqual([{ text: "go", context: {} }]); + useInboxStore.setState({ tasks: {} } as any); +}); + +test("with no machine known yet, it waits for the live roster so a machine-less account gets the assistant", async () => { + useInboxStore.setState({ machineRoster: [], machineRosterLive: false } as any); + await open("/inbox?compose=hi"); + expect(opened).toEqual([]); + await act(async () => useInboxStore.setState({ machineRosterLive: true } as any)); + await flush(); + expect(opened).toEqual([{ text: "hi", context: {} }]); +}); + +test("no link, no composer", async () => { + await open("/inbox?s=abc"); + expect(opened).toEqual([]); + expect(replaced).toEqual([]); +}); diff --git a/packages/web/hooks/useComposeLink.ts b/packages/web/hooks/useComposeLink.ts new file mode 100644 index 0000000000..c56d9cab83 --- /dev/null +++ b/packages/web/hooks/useComposeLink.ts @@ -0,0 +1,118 @@ +// Opens the new-session composer a compose link asks for (lib/composeLink), +// once per link, then takes the link's parameters out of the address. Waits +// for what the composer resolves at mount (the person's settings, and the +// task or machines the link names) so it opens on the right agent and folder; +// past composeLinkWait it opens with whatever resolved, never with nothing, and +// never sends: the person presses Enter. +import { useMemo, useRef, useState } from "react"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { useConvexAuth } from "convex/react"; +import { toast } from "sonner"; +import { useInboxStore, findProjectPathByName } from "../store/inboxStore"; +import { parseComposeLink, draftForTask, resolveLinkProject, stripComposeLink } from "../lib/composeLink"; +import { useSyncTaskDetail } from "./useSyncTasks"; +import { useWatchEffect } from "./useWatchEffect"; + +// How long a link waits on the server and the machine roster on a cold load. +// A cold boot (sign-in, then the task's read) has taken over 5s on a slow +// machine; opening unbound then would quietly lose the task. +export const composeLinkWait = { ms: 15_000 }; + +const noticeId = (key: string) => `compose-link:${key}`; + +export function useComposeLink(active: boolean): void { + // The router's address, not window.location: inside a tab the page's own + // path and query live in the tab context. + const searchParams = useSearchParams(); + const pathname = usePathname(); + const router = useRouter(); + const key = searchParams.toString(); + // eslint-disable-next-line react-hooks/exhaustive-deps + const link = useMemo(() => parseComposeLink(searchParams), [key]); + const handled = useRef(null); + if (!link) handled.current = null; + + // undefined while the server has not answered; null when the viewer cannot + // see the task (unknown, or another workspace's): the draft opens unbound. + // Asked only once the socket is signed in: before that the server answers + // null for a caller it does not know yet, which would read as "not yours". + const { isAuthenticated } = useConvexAuth(); + const answer = useSyncTaskDetail(active && isAuthenticated && link?.task ? link.task : undefined); + const settingsReady = useInboxStore((s) => s.clientStateInitialized); + const rosterReady = useInboxStore((s) => s.machineRosterLive); + // No machine known yet may mean none at all, where only the hosted + // assistant can answer: the agent waits on the live roster then. + const rosterEmpty = useInboxStore((s) => s.machineRoster.length === 0); + + // Which link's wait ran out: a flag would carry one link's timeout over to + // the next link that arrives on the same page. + const [timedOutKey, setTimedOutKey] = useState(null); + const timedOut = timedOutKey === key; + // A task link waits on the server, so the click says it was heard; the + // notice goes when the composer opens or the link is left. + useWatchEffect(() => { + if (!active || !link) return; + const t = setTimeout(() => setTimedOutKey(key), composeLinkWait.ms); + // One notice per link, by id: a remount updates it instead of stacking a + // second. + const notice = link.task ? toast.loading(`Opening ${link.task}…`, { id: noticeId(key) }) : undefined; + return () => { + clearTimeout(t); + setTimedOutKey(null); + if (notice !== undefined) toast.dismiss(notice); + }; + }, [active, key]); + + useWatchEffect(() => { + if (!active || !link || handled.current === key) return; + const st = useInboxStore.getState(); + // The server decides, never the store: whether a link may bind a task is + // an access question, and the store keeps rows from workspaces the viewer + // has left (a bind the server then drops on send without a word). + const task = answer; + const waiting = !settingsReady || (link.task && task === undefined) || ((link.project || rosterEmpty) && !rosterReady); + if (waiting && !timedOut) return; + handled.current = key; + // Dismissed now and once more a beat later: sonner adds a toast on a + // timer and dismisses on an animation frame, so a dismiss in the same + // commit as the add can land first and leave a loading toast that never + // expires. + if (link.task) { + const id = noticeId(key); + toast.dismiss(id); + setTimeout(() => toast.dismiss(id), 500); + } + + const known = { + paths: [ + ...st.recentProjects.map((p) => p.path), + ...st.machineRoster.flatMap((d) => d.local_project_roots ?? []), + ], + byName: (name: string) => findProjectPathByName(name, st), + }; + const linked = task && typeof task.short_id === "string" && task.short_id.toLowerCase() === link.task ? task : null; + // A folder the task pins wins over the link's, as it does on the server + // (resolveTaskGitContext), so the composer shows where the session runs. + const taskPath: string | undefined = linked + ? linked.project_path || (linked.project_id ? st.projects[linked.project_id]?.project_path : undefined) + : undefined; + const projectPath = taskPath || resolveLinkProject(link.project, known); + const draft = linked ? draftForTask(link.draft, linked.short_id) : link.draft; + st.openCompose(draft || undefined, { + ...(projectPath ? { projectPath, gitRoot: projectPath } : {}), + ...(link.agent ? { agentType: link.agent } : {}), + ...(linked ? { linkedTask: { _id: String(linked._id), short_id: linked.short_id, title: linked.title, status: linked.status } } : {}), + }); + // What the link asked for and did not get is said, never dropped quietly: + // a task the session will not be linked to, a folder it will not start in. + if (link.task && !linked) { + toast(task === null + ? `${link.task} isn't a task you can open, so this session won't be linked to it` + : `Codecast didn't answer about ${link.task} in time, so this session won't be linked to it`); + } + if (link.project && !projectPath) { + toast(`No folder "${link.project}" on your machines, so this session starts in your usual one`); + } + router.replace(stripComposeLink(pathname, key)); + }, [active, key, settingsReady, rosterReady, rosterEmpty, answer, timedOut]); +} diff --git a/packages/web/lib/composeLink.test.ts b/packages/web/lib/composeLink.test.ts new file mode 100644 index 0000000000..5bed45aa33 --- /dev/null +++ b/packages/web/lib/composeLink.test.ts @@ -0,0 +1,247 @@ +import { describe, expect, test } from "bun:test"; +import { parseComposeLink, draftForTask, resolveLinkProject, stripComposeLink } from "./composeLink"; +import { PREFILL_MAX_LENGTH } from "./composerPrefill"; + +const parse = (qs: string) => parseComposeLink(new URLSearchParams(qs)); + +describe("parseComposeLink", () => { + test("no compose and no task is no link", () => { + expect(parse("")).toBeNull(); + expect(parse("s=abc&agent=codex&project=/x")).toBeNull(); + expect(parse("task=not-a-task")).toBeNull(); + }); + + test("the draft arrives as written, decoded once", () => { + expect(parse("compose=About%20in-22%20Infrastructure%3A%20")).toEqual({ draft: "About in-22 Infrastructure: " }); + expect(parse("compose=")).toEqual({ draft: "" }); + }); + + test("markup stays plain text", () => { + const html = `[a](javascript:alert(1))`; + expect(parse(`compose=${encodeURIComponent(html)}`)?.draft).toBe(html); + }); + + test("the draft is capped at PREFILL_MAX_LENGTH", () => { + const link = parse(`compose=${"a".repeat(PREFILL_MAX_LENGTH * 5)}`); + expect(link?.draft.length).toBe(PREFILL_MAX_LENGTH); + }); + + test("control characters go, newlines and tabs stay, CRLF becomes LF", () => { + expect(parse(`compose=${encodeURIComponent("a\u0000b\u001b[31mc\r\nd\te\u007f")}`)?.draft).toBe("ab[31mc\nd\te"); + }); + + test("characters that draw nothing go; emoji joiners stay; line separators become newlines", () => { + const hidden = "Summarize README" + "\u{E0049}\u{E0067}\u{E006E}" + "‮evil‬" + "a​b⁦c⁩"; + expect(parse(`compose=${encodeURIComponent(hidden)}`)?.draft).toBe("Summarize READMEevilabc"); + expect(parse(`compose=${encodeURIComponent("👩‍💻 x
y")}`)?.draft).toBe("👩‍💻 x\ny"); + }); + + test("standardized selectors and fillers go; an emoji's selector and ZWNJ stay", () => { + const smuggled = "Fix it \u{1F642}" + "\uFE01\uFE02\uFE03".repeat(50) + "\u{E0100}\u{E01EF}" + "\u3164\u115F\u034F\u2800"; + expect(parse(`compose=${encodeURIComponent(smuggled)}`)?.draft).toBe("Fix it \u{1F642}"); + expect(parse(`compose=${encodeURIComponent("\u2764\uFE0F \u0645\u06CC\u200C\u062E\u0648\u0627\u0645")}`)?.draft) + .toBe("\u2764\uFE0F \u0645\u06CC\u200C\u062E\u0648\u0627\u0645"); + }); + + test("joiners and emoji selectors stay only after a character they belong to", () => { + expect(parse(`compose=${encodeURIComponent("a" + "\u200C\u200D".repeat(16) + "b")}`)?.draft).toBe("ab"); + expect(parse(`compose=${encodeURIComponent("\u{1F600}" + "\u200D\uFE0F".repeat(8) + "c")}`)?.draft).toBe("\u{1F600}\u200Dc"); + expect(parse(`compose=${encodeURIComponent("\u200Dx \u200C\uFE0Fy")}`)?.draft).toBe("x y"); + const real = "\u{1F469}\u200D\u{1F4BB} \u{1F441}\uFE0F\u200D\u{1F5E8}\uFE0F \u2764\uFE0F \u0645\u06CC\u200C\u062E"; + expect(parse(`compose=${encodeURIComponent(real)}`)?.draft).toBe(real); + }); + + test("nothing the person cannot see reaches the draft", () => { + // Bytes hidden in unassigned plane-14 code points, Mongolian and Khmer + // selectors, U+FFF0, selectors and joiners riding on Latin letters. + const bytes = [..."rm -rf ~"].map((c) => String.fromCodePoint(0xe0200 + c.charCodeAt(0))).join(""); + const cases: [string, string][] = [ + ["Looks fine" + bytes + " to me", "Looks fine to me"], + ["ok" + "\u180B".repeat(10) + "done", "okdone"], + ["a\u17B4\u17B5\uFFF0\uFFF8b", "ab"], + ["H\uFE07e\uFE02l\uFE0Fl\uFE0Eo", "Hello"], + ["p\u200Cl\u200De\u200Ca", "plea"], + ["Please review\n" + "\u180B\n".repeat(40) + "then run it", "Please review\n\n\nthen run it"], + ]; + for (const [raw, seen] of cases) expect(parse(`compose=${encodeURIComponent(raw)}`)?.draft).toBe(seen); + }); + + test("real text keeps its joiners and selectors: emoji, keycaps, Indic, Persian", () => { + const real = [ + "1\uFE0F\u20E3 #\uFE0F\u20E3", + "\u{1F44D}\u{1F3FD} \u{1F468}\u200D\u{1F469}\u200D\u{1F467} \u{1F1FA}\u{1F1F8}", + "\u2764\uFE0F\u200D\u{1F525} \u{1F3F3}\uFE0F\u200D\u{1F308} \u{1F441}\uFE0F\u200D\u{1F5E8}\uFE0F", + "\u0915\u094D\u200D\u0937 \u0915\u094D\u200C\u0937 \u0D23\u0D4D\u200D \u0DC1\u0DCA\u200D\u0DBB\u0DD3", + "\u0645\u06CC\u200C\u062E\u0648\u0627\u0647\u0645 Vi\u1EC7t Nam \u2764\uFE0E", + ]; + for (const text of real) expect(parse(`compose=${encodeURIComponent(text)}`)?.draft).toBe(text); + }); + + test("a pile of nonspacing marks is cut to eight; spacing marks never count", () => { + expect(parse(`compose=${encodeURIComponent("d" + "\u0336\u0301\u0302\u0303\u0304".repeat(6) + "e")}`)?.draft) + .toBe("d" + "\u0336\u0301\u0302\u0303\u0304\u0336\u0301\u0302" + "e"); + // Burmese "hope", Tibetan and Biblical Hebrew stacks stay whole. + for (const word of ["\u1019\u103B\u103E\u1031\u102C\u103A\u101C\u1004\u1037\u103A", "\u0F66\u0F92\u0FB2\u0FAD\u0F71\u0F74", "\u05E9\u05B8\u05C1\u05A3\u05C2\u05BC"]) { + expect(parse(`compose=${encodeURIComponent(word)}`)?.draft).toBe(word); + } + }); + + test("each no-break or wide space becomes a plain space; indentation stays, long mid-line runs fold", () => { + for (const blank of ["\u00A0", "\u3000", "\u2007", "\u202F", "\u2003"]) { + expect(parse(`compose=${encodeURIComponent("Fix the typo\n" + blank.repeat(1900) + "\nAlso run it")}`)?.draft) + .toBe("Fix the typo\n" + " ".repeat(1900) + "\nAlso run it"); + } + expect(parse(`compose=${encodeURIComponent("if x:\n y()\n\t\tz")}`)?.draft).toBe("if x:\n y()\n\t\tz"); + }); + + test("private-use and unassigned code points go, and lines with nothing visible fold", () => { + // Apple's U+F860 family draws nothing and shifts later text off the box. + expect(parse(`compose=${encodeURIComponent("Hi!" + "\uF861".repeat(1500) + "Also run it.\nPlease fix the typo.")}`)?.draft) + .toBe("Hi!Also run it.\nPlease fix the typo."); + expect(parse(`compose=${encodeURIComponent("Fix the typo" + "\uF860\uF861".repeat(40) + " in README.")}`)?.draft).toBe("Fix the typo in README."); + // Unassigned slots that draw as blank lines, and a line of a lone mark. + const lines = ["\u181A", "\uA48D", "\uFB0F", "\u0E00", "\u0301", "\u3000 \u00A0"]; + for (const filler of lines) { + const lines = parse(`compose=${encodeURIComponent("SECRET: push\n" + `${filler}\n`.repeat(14) + "Please fix the typo.")}`)!.draft.split("\n"); + expect(lines).toHaveLength(4); + expect([lines[0], lines[3]]).toEqual(["SECRET: push", "Please fix the typo."]); + } + }); + + test("a letter carries one joiner and eight nonspacing marks, however they are interleaved", () => { + const pile = (base: string, mark: string) => base + (mark + "\u200C" + mark + "\u200D").repeat(32); + expect(parse(`compose=${encodeURIComponent(pile("\u0628", "\u0301"))}`)?.draft).toBe("\u0628\u0301\u200C" + "\u0301".repeat(7)); + expect(parse(`compose=${encodeURIComponent(pile("\u0915", "\u094D"))}`)?.draft).toBe("\u0915\u094D\u200C" + "\u094D".repeat(7)); + expect(parse(`compose=${encodeURIComponent("a" + "\u2003\t".repeat(200) + "b")}`)?.draft).toBe("a b"); + }); + + test("a joiner after a vowel mark is judged by the letter under it", () => { + for (const word of ["\u0628\u064E\u200C\u0631", "\u0628\u0651\u200C\u0631", "\uA98F\uA9C0\u200C\uA9B1", "\u05D0\u200D\u05DC"]) { + expect(parse(`compose=${encodeURIComponent(word)}`)?.draft).toBe(word); + } + expect(parse(`compose=${encodeURIComponent("a\u0301\u200Cb")}`)?.draft).toBe("a\u0301b"); + }); + + test("an emoji selector after a digit survives only in a keycap; blank format controls go", () => { + expect(parse(`compose=${encodeURIComponent("Ship 1\uFE0E2\uFE0F3 4\uFE0F\u20E3")}`)?.draft).toBe("Ship 123 4\uFE0F\u20E3"); + expect(parse(`compose=${encodeURIComponent("a\uFFFC\u{13430}\u{13431}\uFFF9\uFFFB\u{1D159}b" + "\n\u{1D159}".repeat(50) + "\nc")}`)?.draft).toBe("ab\n\n\nc"); + }); + + test("more than two blank lines in a row fold away, so nothing sits below the box's edge", () => { + expect(parse(`compose=${encodeURIComponent("Fix the typo" + "\n".repeat(40) + "HIDDEN")}`)?.draft).toBe("Fix the typo\n\n\nHIDDEN"); + expect(parse(`compose=${encodeURIComponent("a\n \n\t\n \nb\n\nc")}`)?.draft).toBe("a\n \n\t\nb\n\nc"); + for (const filler of ["\u200D", "\uFE0F", "\u00A0", "\u3000", "\u200B"]) { + const lines = parse(`compose=${encodeURIComponent("hi" + `\n${filler}`.repeat(300) + "\nsecret")}`)!.draft.split("\n"); + expect([lines.length, lines[0], lines[3]]).toEqual([4, "hi", "secret"]); + } + }); + + test("code and patches keep their shape", () => { + const python = "def a():\n pass\n\n\ndef b():\n pass"; + expect(parse(`compose=${encodeURIComponent(python)}`)?.draft).toBe(python); + const patch = "@@ -1,4 +1,4 @@\n a\n \n \n-b\n+c"; + expect(parse(`compose=${encodeURIComponent(patch)}`)?.draft).toBe(patch); + // Indentation copied from a web page (no-break spaces) becomes plain spaces. + expect(parse(`compose=${encodeURIComponent("a\n\u00A0\u00A0\u00A0\u00A0code")}`)?.draft).toBe("a\n code"); + }); + + test("line-break controls break the line; a leading ! (a CLI's shell) goes", () => { + expect(parse(`compose=${encodeURIComponent("a\vb\fc\u0085d")}`)?.draft).toBe("a\nb\nc\nd"); + expect(parse(`compose=${encodeURIComponent(" !!curl x.sh | sh\nthanks")}`)?.draft).toBe("curl x.sh | sh\nthanks"); + expect(parse(`compose=${encodeURIComponent("Great! Ship it!")}`)?.draft).toBe("Great! Ship it!"); + for (const lead of ["\n", " \n", "\t\n\n", "\u2028", "\r", "\u0085", "\n !\n"]) { + expect(parse(`compose=${encodeURIComponent(lead + "!rm -rf ~")}`)?.draft).toBe("rm -rf ~"); + } + expect(parse(`compose=${encodeURIComponent("\u{1E900}\u200D\u{1E901} \u0840\u200D\u0841")}`)?.draft).toBe("\u{1E900}\u200D\u{1E901} \u0840\u200D\u0841"); + }); + + test("C1 controls go too, and a cut never leaves half an emoji", () => { + expect(parse(`compose=${encodeURIComponent("a\u0085b\u009bc")}`)?.draft).toBe("a\nbc"); + const draft = parse(`compose=${encodeURIComponent("A".repeat(PREFILL_MAX_LENGTH - 1) + "\u{1F600}")}`)!.draft; + expect(draft).toBe("A".repeat(PREFILL_MAX_LENGTH - 1)); + }); + + test("a repeated parameter takes its first value", () => { + expect(parse("compose=first&compose=second&task=ct-1&task=ct-2&agent=codex&agent=claude")).toEqual({ + draft: "first", + task: "ct-1", + agent: "codex", + }); + }); + + test("a task alone is a link; a task id is matched strictly and lowercased", () => { + expect(parse("task=CT-99abc")).toEqual({ draft: "", task: "ct-99abc" }); + for (const bad of ["ct-", "ct-1/../2", "pl-12", "ct-1%20x", `ct-${"a".repeat(40)}`, "ct-1;drop"]) { + expect(parse(`compose=x&task=${bad}`)).toEqual({ draft: "x" }); + } + }); + + test("agents are the registry's, in either spelling; anything else is dropped", () => { + expect(parse("compose=x&agent=claude")?.agent).toBe("claude_code"); + expect(parse("compose=x&agent=claude_code")?.agent).toBe("claude_code"); + expect(parse("compose=x&agent=Codex")?.agent).toBe("codex"); + expect(parse("compose=x&agent=codecast")?.agent).toBe("codecast"); + for (const bad of ["cowork", "gpt", "", "claude;rm", "__proto__"]) { + expect(parse(`compose=x&agent=${bad}`)?.agent).toBeUndefined(); + } + }); + + test("a project is kept as text for later resolution, capped and single-line", () => { + expect(parse("compose=x&project=%2FUsers%2Fme%2Fcode%2Fapp")?.project).toBe("/Users/me/code/app"); + expect(parse(`compose=x&project=${encodeURIComponent(" a\nb ")}`)?.project).toBe("a b"); + expect(parse(`compose=x&project=${"p".repeat(5000)}`)?.project?.length).toBe(512); + expect(parse("compose=x&project=")?.project).toBeUndefined(); + }); +}); + +describe("draftForTask", () => { + test("a task-only link reads like the task list's start", () => { + expect(draftForTask("", "ct-7")).toBe("Let's do this task ct-7 "); + expect(draftForTask(" ", "ct-7")).toBe("Let's do this task ct-7 "); + }); + test("a draft naming the task is left exactly as written", () => { + expect(draftForTask("Continue ct-7: ", "ct-7")).toBe("Continue ct-7: "); + expect(draftForTask("continue CT-7", "ct-7")).toBe("continue CT-7"); + }); + test("a draft that does not name the task gets its id", () => { + expect(draftForTask("Pick this up ", "ct-7")).toBe("Pick this up ct-7 "); + expect(draftForTask("re ct-993591 too", "ct-99359")).toBe("re ct-993591 too ct-99359 "); + expect(draftForTask("see xct-7", "ct-7")).toBe("see xct-7 ct-7 "); + }); + test("the id fits inside the cap, at the end", () => { + const out = draftForTask("a".repeat(PREFILL_MAX_LENGTH), "ct-123456"); + expect(out.length).toBe(PREFILL_MAX_LENGTH); + expect(out.endsWith(" ct-123456 ")).toBe(true); + }); +}); + +describe("resolveLinkProject", () => { + const known = { + paths: ["/Users/me/code/app", "/Users/me/src/"], + byName: (n: string) => (n === "app" ? "/Users/me/code/app" : undefined), + }; + test("a known folder, or one inside it, resolves", () => { + expect(resolveLinkProject("/Users/me/code/app", known)).toBe("/Users/me/code/app"); + expect(resolveLinkProject("/Users/me/code/app/", known)).toBe("/Users/me/code/app"); + expect(resolveLinkProject("/Users/me/src/other", known)).toBe("/Users/me/src/other"); + }); + test("a bare name resolves by folder name", () => { + expect(resolveLinkProject("app", known)).toBe("/Users/me/code/app"); + }); + test("anything else falls back to the composer's own default", () => { + expect(resolveLinkProject(undefined, known)).toBeUndefined(); + expect(resolveLinkProject("/Users/me/code/application", known)).toBeUndefined(); + expect(resolveLinkProject("/Users/me/code/app/../../../etc", known)).toBeUndefined(); + expect(resolveLinkProject("/etc", known)).toBeUndefined(); + expect(resolveLinkProject("nope", known)).toBeUndefined(); + expect(resolveLinkProject("~/code/app", known)).toBeUndefined(); + expect(resolveLinkProject("/", { paths: ["/"], byName: () => undefined })).toBeUndefined(); + }); +}); + +describe("stripComposeLink", () => { + test("takes out only the link's parameters", () => { + expect(stripComposeLink("/inbox", "?compose=x&task=ct-1&agent=codex&project=a&s=abc")).toBe("/inbox?s=abc"); + expect(stripComposeLink("/inbox", "?compose=x&compose=y")).toBe("/inbox"); + }); +}); diff --git a/packages/web/lib/composeLink.ts b/packages/web/lib/composeLink.ts new file mode 100644 index 0000000000..4dd8040249 --- /dev/null +++ b/packages/web/lib/composeLink.ts @@ -0,0 +1,203 @@ +// A link from outside the app that opens a NEW session's composer with a +// draft already typed (`/inbox?compose=[&task=ct-N][&agent=…][&project=…]`), +// ready to edit or send. Nothing is ever sent by the link: the person presses +// Enter. A day view, a doc or a bookmark builds these; every value is untrusted +// text from whoever wrote the link, so each one either resolves to something +// the viewer could have picked by hand or is dropped, and the composer still +// opens with the draft. +// +// `?prefill=` (lib/composerPrefill) is the existing-session sibling: it quotes +// its text for a notification reply. This one types the text as written. + +import { fromConvexAgentType, toConvexAgentType, type ConvexAgentType } from "@codecast/shared/contracts"; +import { PREFILL_MAX_LENGTH } from "./composerPrefill"; + +export const COMPOSE_LINK_PARAMS = ["compose", "task", "agent", "project"] as const; + +export type ComposeLink = { + /** The text the composer opens with, as written (capped, controls stripped). */ + draft: string; + /** A task short id (`ct-…`), lowercased; resolved against the viewer's access later. */ + task?: string; + agent?: ConvexAgentType; + /** A folder path or a project name; resolved against the viewer's machines later. */ + project?: string; +}; + +const LEADING_BANG = /^[\s!]+/; +const TASK_SHORT_ID = /^ct-[a-z0-9]{1,32}$/; +const PROJECT_MAX_LENGTH = 512; +// C0 and C1 controls and DEL, except tab and newline: they only reach a +// textarea's value, but a NUL or an escape sequence is never part of a draft +// worth keeping. +// eslint-disable-next-line no-control-regex +const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g; +// Characters that draw nothing, which can carry text the person cannot see to +// the agent that reads the message they send: every default-ignorable code +// point (format characters, the tag block, variation selectors, fillers, the +// unassigned rest of plane 14), and the few blank-drawing format characters +// Unicode leaves out of that set (braille blank, Egyptian format controls, +// interlinear annotation marks, the object replacement character, the null +// notehead). Joiners and the two emoji +// selectors are judged by what they follow instead (dropStrayMarks). +const IGNORABLE = /(?![\u200c\u200d\ufe0e\ufe0f])\p{Default_Ignorable_Code_Point}|[\u2800\ufff9-\ufffc\u{13430}-\u{1343f}\u{1d159}]/gu; +// Private-use and unassigned code points: no font this text will meet draws +// them as words, and some draw as nothing at all (Apple's U+F860 family, the +// unassigned Mongolian and Thai slots) or shift the text after them. +const UNDRAWABLE = /[\p{Co}\p{Cn}]/gu; +// What a joiner may follow: a letter or mark of a script that joins with it, +// an emoji, a skin tone, or an emoji selector. After anything else, Latin +// included, a joiner only hides a bit. +const JOINER_BASE = /[\p{sc=Arabic}\p{sc=Syriac}\p{sc=Thaana}\p{sc=Nko}\p{sc=Hebrew}\p{sc=Devanagari}\p{sc=Bengali}\p{sc=Gurmukhi}\p{sc=Gujarati}\p{sc=Oriya}\p{sc=Tamil}\p{sc=Telugu}\p{sc=Kannada}\p{sc=Malayalam}\p{sc=Sinhala}\p{sc=Myanmar}\p{sc=Khmer}\p{sc=Tibetan}\p{sc=Mongolian}\p{sc=Javanese}\p{sc=Balinese}\p{sc=Adlam}\p{sc=Mandaic}\p{sc=Hanifi_Rohingya}\p{Extended_Pictographic}\p{Emoji_Modifier}\ufe0f]/u; +// What an emoji selector (FE0E, FE0F) may follow: a pictograph, or a digit, +// # or * that the keycap mark (U+20E3) completes. +const PICTOGRAPH = /\p{Extended_Pictographic}/u; +const KEYCAP_BASE = /[0-9#*]/; +const KEYCAP = "\u20e3"; +const MARK = /\p{M}/u; +// Nonspacing and enclosing marks: more than eight on one letter is a pile +// that draws over the text around it. Spacing marks (Burmese, Tibetan) +// stack in ordinary words and never count. +const PILING_MARK = /[\p{Mn}\p{Me}]/u; +const PILE_MAX = 8; +// A blank other than the plain space and tab (no-break, wide, ideographic): +// one plain space for each. A run of plain spaces hangs at the end of a line +// in the box; a run of no-break spaces wraps into lines that look empty. +const ODD_BLANK = /[^\S\n\t ]/g; +// Sixteen or more blanks after text on a line: they wrap into lines that look +// empty and push the words after them out of the box. Indentation at the start +// of a line is left alone. +const MIDLINE_BLANKS = /(?<=\S)[^\S\n]{16,}/g; +// A line holding no letter, number, punctuation or symbol looks empty +// whatever it is made of. Two in a row are kept as written (code puts two +// blank lines between definitions; a patch's blank context line is a space); +// more fold away: a short draft could otherwise push text out of the box, +// out of sight of the person about to press Enter. +const VISIBLE = /[\p{L}\p{N}\p{P}\p{S}]/u; +const BLANK_LINES_MAX = 2; + +function foldBlankLines(text: string): string { + const out: string[] = []; + let blanks = 0; + for (const line of text.split("\n")) { + blanks = VISIBLE.test(line) ? 0 : blanks + 1; + if (blanks <= BLANK_LINES_MAX) out.push(line); + } + return out.join("\n"); +} + +/** What may sit on a letter, judged per letter against what was kept: one + * joiner, only after a character it belongs to (a mark is read through to + * the letter under it); an emoji selector only right after a pictograph or + * a keycap's digit; at most PILE_MAX nonspacing marks. A run of any of them + * keeps no more than that, however it is interleaved. A loop, not a + * lookbehind: JavaScriptCore's lookbehind misreads a character outside the + * BMP (every emoji) before the mark. */ +function dropStrayMarks(text: string): string { + const chars = Array.from(text); + const out: string[] = []; + let letter: string | undefined; // the last kept character that is not a mark + let joined = false; // a joiner kept since that letter + let piled = 0; // nonspacing marks kept on that letter + chars.forEach((ch, i) => { + const prev = out[out.length - 1]; + if (ch === "\u200c" || ch === "\u200d") { + const base = prev && MARK.test(prev) && !JOINER_BASE.test(prev) ? letter : prev; + if (joined || !base || !JOINER_BASE.test(base)) return; + joined = true; + } else if (ch === "\ufe0e" || ch === "\ufe0f") { + const keycap = !!prev && KEYCAP_BASE.test(prev) && chars[i + 1] === KEYCAP; + if (!prev || !(PICTOGRAPH.test(prev) || keycap)) return; + } else if (PILING_MARK.test(ch)) { + if (++piled > PILE_MAX) return; + } else if (!MARK.test(ch)) { + letter = ch; + joined = false; + piled = 0; + } + out.push(ch); + }); + return out.join(""); +} + +/** The first `max` UTF-16 units, never ending on half of an emoji. */ +function clip(text: string, max: number): string { + const cut = text.slice(0, max); + return /[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut; +} + +function cleanText(raw: string, max: number): string { + // Marks go before the fold: a line of stray marks is a blank line once + // they are gone. + const plain = dropStrayMarks(raw + .replace(/\r\n?|[\v\f\u0085\u2028\u2029]/g, "\n") + .replace(CONTROL_CHARS, "") + .replace(IGNORABLE, "") + .replace(UNDRAWABLE, "")) + .replace(ODD_BLANK, " ") + .replace(MIDLINE_BLANKS, " "); + return clip(foldBlankLines(plain), max); +} + +/** An agent the registry knows, in either spelling (`claude` or `claude_code`). */ +function knownAgent(raw: string | null): ConvexAgentType | undefined { + if (!raw) return undefined; + const v = raw.trim().toLowerCase(); + const id = fromConvexAgentType(v); + const convex = toConvexAgentType(id); + return v === id || v === convex ? convex : undefined; +} + +/** The link's parameters, or null when the address carries no compose link. + * A repeated parameter takes its first value. A task alone is a link too. */ +export function parseComposeLink(params: Pick): ComposeLink | null { + const rawTask = params.get("task")?.trim().toLowerCase(); + const task = rawTask && TASK_SHORT_ID.test(rawTask) ? rawTask : undefined; + if (!params.has("compose") && !task) return null; + // No leading "!": an agent that takes typed keys (Gemini's CLI) reads "!" in + // an empty input as its shell, and the line would run as a command. Leading + // blanks and line breaks go with it: the composer trims them on send, which + // would put the "!" first again. + const draft = cleanText(params.get("compose") ?? "", PREFILL_MAX_LENGTH).replace(LEADING_BANG, ""); + const agent = knownAgent(params.get("agent")); + const project = cleanText(params.get("project") ?? "", PROJECT_MAX_LENGTH).replace(/\s+/g, " ").trim() || undefined; + return { draft, ...(task ? { task } : {}), ...(agent ? { agent } : {}), ...(project ? { project } : {}) }; +} + +/** The draft with the task named in it: a task-only link reads like the task + * list's own start ("Let's do this task ct-N"); a draft that does not mention + * the task gets its id appended, so the first message says which task. Only + * called once the task resolved for the viewer. */ +export function draftForTask(draft: string, shortId: string): string { + if (!draft.trim()) return `Let's do this task ${shortId} `; + // The id as a word: "ct-993591" does not name ct-99359. + if (new RegExp(`(^|[^a-z0-9-])${shortId}(?![a-z0-9])`, "i").test(draft)) return draft; + const tail = ` ${shortId} `; + return `${clip(draft.trimEnd(), PREFILL_MAX_LENGTH - tail.length)}${tail}`; +} + +/** A link's project, as a folder one of the viewer's machines can start in, + * or undefined when it names nothing they have. A path matches a known folder + * or sits inside one; a bare name matches a project by its folder name. */ +export function resolveLinkProject( + project: string | undefined, + known: { paths: string[]; byName: (name: string) => string | undefined }, +): string | undefined { + if (!project) return undefined; + if (!project.startsWith("/")) return project.includes("/") ? undefined : known.byName(project); + const path = project.replace(/\/+$/, "") || "/"; + if (path.split("/").includes("..")) return undefined; + return known.paths.some((k) => { + const root = k.replace(/\/+$/, ""); + return !!root && (path === root || path.startsWith(`${root}/`)); + }) ? path : undefined; +} + +/** The address with the link's parameters taken out, so a reload or Back + * never opens a second composer. */ +export function stripComposeLink(pathname: string, search: string): string { + const sp = new URLSearchParams(search); + for (const k of COMPOSE_LINK_PARAMS) sp.delete(k); + const rest = sp.toString(); + return rest ? `${pathname}?${rest}` : pathname; +} diff --git a/packages/web/lib/defaultAgent.test.ts b/packages/web/lib/defaultAgent.test.ts index df8863872e..5efda3fba7 100644 --- a/packages/web/lib/defaultAgent.test.ts +++ b/packages/web/lib/defaultAgent.test.ts @@ -48,5 +48,12 @@ describe("newConversationAgentType", () => { test("a machine-less account always starts the hosted assistant", () => { expect(newConversationAgentType(state({}, []), "claude_code")).toBe("codecast"); + expect(newConversationAgentType(state({}, []), undefined, "codex")).toBe("codecast"); + }); + + test("an agent the caller asked for outranks the saved default; an unknown one does not count", () => { + expect(newConversationAgentType(state({ default_agent: "codex" }), "gemini", "claude_code")).toBe("claude_code"); + expect(newConversationAgentType(state({ default_agent: "codex" }), undefined, "bogus")).toBe("codex"); + expect(newConversationAgentType(state({}), "gemini", null)).toBe("gemini"); }); }); diff --git a/packages/web/lib/defaultAgent.ts b/packages/web/lib/defaultAgent.ts index 758447741f..e5bfd6e71d 100644 --- a/packages/web/lib/defaultAgent.ts +++ b/packages/web/lib/defaultAgent.ts @@ -54,10 +54,11 @@ export function defaultAgentType(s: DefaultAgentState): ConvexAgentType { } /** The agent for a new conversation opened beside `inherit` (the agent of - * the conversation on screen, or a resumed draft's). The person's saved - * default and last hand pick come first; the conversation's own agent - * fills in when they have neither. */ -export function newConversationAgentType(s: DefaultAgentState, inherit?: string | null): ConvexAgentType { + * the conversation on screen, or a resumed draft's). An `explicit` agent the + * caller asked for (a compose link's, the first run's "Ask the assistant") + * wins; then the person's saved default and last hand pick; the + * conversation's own agent fills in when they have neither. */ +export function newConversationAgentType(s: DefaultAgentState, inherit?: string | null, explicit?: string | null): ConvexAgentType { if (onlyHostedAgent(s)) return HOSTED_AGENT_TYPE; - return intendedAgentType(s) ?? knownAgentType(inherit) ?? LOCAL_DEFAULT; + return knownAgentType(explicit) ?? intendedAgentType(s) ?? knownAgentType(inherit) ?? LOCAL_DEFAULT; } diff --git a/packages/web/store/composeSlice.ts b/packages/web/store/composeSlice.ts index 91e9daf4f4..57f7e285be 100644 --- a/packages/web/store/composeSlice.ts +++ b/packages/web/store/composeSlice.ts @@ -20,8 +20,14 @@ import { flushDraftWrite } from "../lib/pendingDraftWrites"; import { isConvexId } from "../lib/entityLinks"; /** `agentType` starts the composer on that agent rather than the default - * (the empty inbox's "Ask the assistant" start). */ -export type ComposeContext = { projectPath?: string; gitRoot?: string; agentType?: string }; + * (the empty inbox's "Ask the assistant" start). `linkedTask` binds the + * session it creates to that task (a compose link, hooks/useComposeLink). */ +export type ComposeContext = { + projectPath?: string; + gitRoot?: string; + agentType?: string; + linkedTask?: { _id: string; short_id: string; title?: string; status?: string }; +}; export type ComposeInstance = { id: number; mode: "modal" | "dock"; diff --git a/packages/web/store/contextSessionLink.test.ts b/packages/web/store/contextSessionLink.test.ts index 04cdfe5d60..193c9e7495 100644 --- a/packages/web/store/contextSessionLink.test.ts +++ b/packages/web/store/contextSessionLink.test.ts @@ -59,4 +59,24 @@ describe("ContextChat linked create intent", () => { expect(healedOpts?.linked_object).toEqual(LINKED_DOC); }); + + // A compose link's composer stamps the task on its stub (ComposeView), and + // the create carries it on every agent, the hosted assistant included. + for (const agent of ["claude_code", "codecast"]) { + test(`a task stamped on a compose stub reaches the ${agent} create`, async () => { + const task = { type: "task", id: "tasks_linked" }; + useInboxStore.getState().syncRecord("sessions", STUB_ID, { _id: STUB_ID, session_id: STUB_ID, agent_type: agent, project_path: "/repo" }); + useInboxStore.getState().syncRecord("sessions", STUB_ID, { _linkedObject: task }); + const originalCreate = useInboxStore.getState().createSession; + let sent: Record | undefined; + useInboxStore.setState({ createSession: ((opts: Record) => { sent = opts; return Promise.resolve(REAL_ID); }) as any }); + try { + await useInboxStore.getState().createSessionFromStub(STUB_ID); + } finally { + useInboxStore.setState({ createSession: originalCreate }); + } + expect(sent?.agent_type).toBe(agent); + expect(sent?.linked_object).toEqual(task); + }); + } }); diff --git a/packages/web/store/inboxStore.ts b/packages/web/store/inboxStore.ts index db50a8656d..0c02433e6a 100644 --- a/packages/web/store/inboxStore.ts +++ b/packages/web/store/inboxStore.ts @@ -12531,6 +12531,7 @@ const inboxStoreConfig = (set: any, get: any) => ({ return s.createSession({ agent_type: agentType, session_id: stubId, + ...(cur?._linkedObject?.type && cur?._linkedObject?.id ? { linked_object: cur._linkedObject } : {}), ...(fallback?.firstMessage ? { first_message: fallback.firstMessage.content, first_message_client_id: fallback.firstMessage.clientId } : {}), diff --git a/packages/web/store/viewNav.ts b/packages/web/store/viewNav.ts index a2d7cde360..bfd3b36d8a 100644 --- a/packages/web/store/viewNav.ts +++ b/packages/web/store/viewNav.ts @@ -13,6 +13,8 @@ // Every attempt — allowed or blocked — lands in a ring buffer persisted to // localStorage, so one console call after a jump names the culprit: // __navLog() // in any build, dev or prod +import { parseComposeLink } from "../lib/composeLink"; + export type ViewNavSource = | "gesture" // a click/keypress in this window — always allowed | "boot-restore" // hydration putting the client back on its own last position @@ -78,7 +80,10 @@ function readFreshHomeLaunch(): boolean { if (nav?.type !== "navigate") return false; const page = window.location.pathname.replace(/\/+$/, "") || "/"; if (page !== "/" && page !== "/inbox") return false; - return !new URLSearchParams(window.location.search).has("s"); + // A compose link opens its own composer: a landing page under it would be + // a second composer competing for the cursor. + const sp = new URLSearchParams(window.location.search); + return !sp.has("s") && !parseComposeLink(sp); } let freshHomeLaunch: boolean | null = null; export function freshHomeLaunchPending(): boolean { From 1c7c56a752a89c93c4c2f749f13091683ece355b Mon Sep 17 00:00:00 2001 From: Jason Benn Date: Mon, 23 Nov 2026 03:22:53 -0800 Subject: [PATCH 2/2] fix(web): compose link passes CI: no provider throw, lint, line pins useServerAuthenticated reads a tree with no auth provider as signed in; the task stamp moves to composeSlice and the hosted-link tests to their own file, so no pinned file grows. Codecast-Session: https://codecast.sh/conversation/jx7c455r6jxsf98s5zk5xt1ajs8jrkrp --- .../convex/convex/assistant.entry.test.ts | 41 ----------- .../convex/assistant.linkedTask.test.ts | 70 +++++++++++++++++++ packages/web/components/ComposeView.tsx | 15 +--- packages/web/hooks/useComposeLink.ts | 4 +- packages/web/lib/composeLink.ts | 3 +- packages/web/store/composeSlice.ts | 16 +++++ 6 files changed, 91 insertions(+), 58 deletions(-) create mode 100644 packages/convex/convex/assistant.linkedTask.test.ts diff --git a/packages/convex/convex/assistant.entry.test.ts b/packages/convex/convex/assistant.entry.test.ts index 08cd054957..f6b2c9b243 100644 --- a/packages/convex/convex/assistant.entry.test.ts +++ b/packages/convex/convex/assistant.entry.test.ts @@ -149,47 +149,6 @@ describe("startConversation", () => { expect(commands).toHaveLength(0); }); - test("a hosted stub started for a task is linked to it, as a machine session is", async () => { - // A compose link (/inbox?task=ct-N) on the hosted assistant: the create - // carries the task as linked_object and the session lands on the task. - const { t, user, authed } = await setup(); - const taskId = await t.run((ctx) => ctx.db.insert("tasks", { - user_id: user, short_id: "ct-77", title: "Link me", status: "open", task_type: "task", priority: "medium", - created_at: Date.now(), updated_at: Date.now(), workspace: `user:${user}`, - } as any)); - const args = [{ agent_type: "codecast", session_id: "stub-task", first_message: "Let's do this task ct-77", first_message_client_id: "client-t", linked_object: { type: "task", id: taskId } }]; - await authed.mutation(api.dispatch.dispatch, { action: "createSession", args }); - const { conv, task } = await t.run(async (ctx) => ({ - conv: await ctx.db.query("conversations").withIndex("by_session_id", (q) => q.eq("session_id", "stub-task")).first(), - task: await ctx.db.get(taskId), - })); - expect((task as any).conversation_ids?.map(String)).toContain(String(conv!._id)); - }); - - test("a task private to its owner inside a team is not a teammate's to link", async () => { - // Access is the task's workspace (user:), never its team: a - // teammate's create naming it starts the session and leaves the task alone. - const { t, user: owner } = await setup(); - const { mate, taskId } = await t.run(async (ctx) => { - const mate = await ctx.db.insert("users", { emailVerificationTime: 1 }); - const team = await ctx.db.insert("teams", { name: "T", created_at: Date.now() } as any); - for (const u of [owner, mate]) await ctx.db.insert("team_memberships", { user_id: u, team_id: team, role: "member", joined_at: Date.now() } as any); - const taskId = await ctx.db.insert("tasks", { - user_id: owner, team_id: team, short_id: "ct-78", title: "Mine", status: "open", task_type: "task", priority: "medium", - created_at: Date.now(), updated_at: Date.now(), workspace: `user:${owner}`, - } as any); - return { mate, taskId }; - }); - const args = [{ agent_type: "codecast", session_id: "stub-mate", linked_object: { type: "task", id: taskId } }]; - await t.withIdentity({ subject: mate }).mutation(api.dispatch.dispatch, { action: "createSession", args }); - const { conv, task } = await t.run(async (ctx) => ({ - conv: await ctx.db.query("conversations").withIndex("by_session_id", (q) => q.eq("session_id", "stub-mate")).first(), - task: await ctx.db.get(taskId), - })); - expect(conv).not.toBeNull(); - expect((task as any).conversation_ids ?? []).toEqual([]); - }); - test("refuses a session id another conversation holds", async () => { const { t, user, authed } = await setup(); await t.run((ctx) => ctx.db.insert("conversations", { diff --git a/packages/convex/convex/assistant.linkedTask.test.ts b/packages/convex/convex/assistant.linkedTask.test.ts new file mode 100644 index 0000000000..12078fe586 --- /dev/null +++ b/packages/convex/convex/assistant.linkedTask.test.ts @@ -0,0 +1,70 @@ +// A hosted session started for a task (a compose link, /inbox?task=ct-N, on +// the Codecast assistant) is linked to the task the way a machine session is, +// and only when the task's workspace lets the caller open it. +import { describe, expect, setDefaultTimeout, test } from "bun:test"; +import { convexTest } from "convex-test"; +import schema from "./schema"; +import { api } from "./_generated/api"; + +setDefaultTimeout(60_000); + +const modules = { + "./_generated/server.ts": () => import("./_generated/server"), + "./syncOutbox.ts": () => import("./syncOutbox"), + "./assistant/entry.ts": () => import("./assistant/entry"), + "./agentTasks.ts": () => import("./agentTasks"), + "./managedSessions.ts": () => import("./managedSessions"), + "./messages.ts": () => import("./messages"), + "./sessionDecisions.ts": () => import("./sessionDecisions"), + "./conversations.ts": () => import("./conversations"), + "./dispatch.ts": () => import("./dispatch"), + "./pendingMessages.ts": () => import("./pendingMessages"), +}; + +async function setup() { + const t = convexTest(schema, modules); + // A proven address: the Free plan serves only one (assistant/freeGate.ts). + const user = await t.run((ctx) => ctx.db.insert("users", { emailVerificationTime: 1 })); + return { t, user, authed: t.withIdentity({ subject: user }) }; +} + +describe("a hosted session started for a task", () => { + test("is linked to the task, as a machine session is", async () => { + const { t, user, authed } = await setup(); + const taskId = await t.run((ctx) => ctx.db.insert("tasks", { + user_id: user, short_id: "ct-77", title: "Link me", status: "open", task_type: "task", priority: "medium", + created_at: Date.now(), updated_at: Date.now(), workspace: `user:${user}`, + } as any)); + const args = [{ agent_type: "codecast", session_id: "stub-task", first_message: "Let's do this task ct-77", first_message_client_id: "client-t", linked_object: { type: "task", id: taskId } }]; + await authed.mutation(api.dispatch.dispatch, { action: "createSession", args }); + const { conv, task } = await t.run(async (ctx) => ({ + conv: await ctx.db.query("conversations").withIndex("by_session_id", (q) => q.eq("session_id", "stub-task")).first(), + task: await ctx.db.get(taskId), + })); + expect((task as any).conversation_ids?.map(String)).toContain(String(conv!._id)); + }); + + test("leaves a task private to its owner inside a team alone when a teammate names it", async () => { + // Access is the task's workspace (user:), never its team: the + // teammate's session starts and the task is not linked or taken. + const { t, user: owner } = await setup(); + const { mate, taskId } = await t.run(async (ctx) => { + const mate = await ctx.db.insert("users", { emailVerificationTime: 1 }); + const team = await ctx.db.insert("teams", { name: "T", created_at: Date.now() } as any); + for (const u of [owner, mate]) await ctx.db.insert("team_memberships", { user_id: u, team_id: team, role: "member", joined_at: Date.now() } as any); + const taskId = await ctx.db.insert("tasks", { + user_id: owner, team_id: team, short_id: "ct-78", title: "Mine", status: "open", task_type: "task", priority: "medium", + created_at: Date.now(), updated_at: Date.now(), workspace: `user:${owner}`, + } as any); + return { mate, taskId }; + }); + const args = [{ agent_type: "codecast", session_id: "stub-mate", linked_object: { type: "task", id: taskId } }]; + await t.withIdentity({ subject: mate }).mutation(api.dispatch.dispatch, { action: "createSession", args }); + const { conv, task } = await t.run(async (ctx) => ({ + conv: await ctx.db.query("conversations").withIndex("by_session_id", (q) => q.eq("session_id", "stub-mate")).first(), + task: await ctx.db.get(taskId), + })); + expect(conv).not.toBeNull(); + expect((task as any).conversation_ids ?? []).toEqual([]); + }); +}); diff --git a/packages/web/components/ComposeView.tsx b/packages/web/components/ComposeView.tsx index cdd5f6989b..987a453f30 100644 --- a/packages/web/components/ComposeView.tsx +++ b/packages/web/components/ComposeView.tsx @@ -16,7 +16,7 @@ import { resolveSessionSkills } from "../lib/sessionSkills"; import { broadcastComposeOptimistic } from "../lib/composeBridge"; import { agentDisplayName, isHostedAgentType } from "@codecast/shared/contracts"; import { newConversationAgentType } from "../lib/defaultAgent"; -import { composeDraftContent, findKeptComposeDraft, type ComposeContext, type ComposeInstance } from "../store/composeSlice"; +import { bindComposeTask, composeDraftContent, findKeptComposeDraft, type ComposeContext, type ComposeInstance } from "../store/composeSlice"; import { flushDraftWrite } from "../lib/pendingDraftWrites"; import { settleHostedStart } from "../lib/startHostedConversation"; import { useOnlyHostedAgent } from "../hooks/usePinnedAgents"; @@ -170,18 +170,7 @@ export function ComposeView({ initialQuery, context, onClose, closeGuardRef, ins if (instance) store.bindComposeStub(instance.id, sid); if (initialQuery) store.setDraft(sid, { draft_message: initialQuery }); - // A composer opened for a task (a compose link) is born bound to it: the - // create carries the stub's _linkedObject (createSessionFromStub), and the - // server links the session and makes it the task's owner in the same - // transaction, as the task list's start does. active_task is the new - // session's task badge (header, sidebar) from its first optimistic paint, - // as ContextChatInput sets it; the composer itself draws no task chip. - const task = context?.linkedTask; - if (task && sid !== resumeStubId) { - const activeTask = { _id: task._id, short_id: task.short_id, title: task.title, status: task.status }; - store.syncRecord("sessions", sid, { _linkedObject: { type: "task", id: task._id }, active_task: activeTask }); - store.syncRecord("conversations", sid, { active_task_id: task._id, active_task: activeTask }); - } + if (context?.linkedTask && sid !== resumeStubId) bindComposeTask(store, sid, context.linkedTask); setSessionId(sid); setRestored(sid === resumeStubId); setSkillCtx({ projectPath: (sid === resumeStubId ? resumed?.project_path : path) || undefined, agentType }); diff --git a/packages/web/hooks/useComposeLink.ts b/packages/web/hooks/useComposeLink.ts index c56d9cab83..876f5c7120 100644 --- a/packages/web/hooks/useComposeLink.ts +++ b/packages/web/hooks/useComposeLink.ts @@ -6,7 +6,7 @@ // never sends: the person presses Enter. import { useMemo, useRef, useState } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; -import { useConvexAuth } from "convex/react"; +import { useServerAuthenticated } from "./useServerAuthSettled"; import { toast } from "sonner"; import { useInboxStore, findProjectPathByName } from "../store/inboxStore"; import { parseComposeLink, draftForTask, resolveLinkProject, stripComposeLink } from "../lib/composeLink"; @@ -36,7 +36,7 @@ export function useComposeLink(active: boolean): void { // see the task (unknown, or another workspace's): the draft opens unbound. // Asked only once the socket is signed in: before that the server answers // null for a caller it does not know yet, which would read as "not yours". - const { isAuthenticated } = useConvexAuth(); + const isAuthenticated = useServerAuthenticated(); const answer = useSyncTaskDetail(active && isAuthenticated && link?.task ? link.task : undefined); const settingsReady = useInboxStore((s) => s.clientStateInitialized); const rosterReady = useInboxStore((s) => s.machineRosterLive); diff --git a/packages/web/lib/composeLink.ts b/packages/web/lib/composeLink.ts index 4dd8040249..a281fc7fec 100644 --- a/packages/web/lib/composeLink.ts +++ b/packages/web/lib/composeLink.ts @@ -30,7 +30,6 @@ const PROJECT_MAX_LENGTH = 512; // C0 and C1 controls and DEL, except tab and newline: they only reach a // textarea's value, but a NUL or an escape sequence is never part of a draft // worth keeping. -// eslint-disable-next-line no-control-regex const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g; // Characters that draw nothing, which can carry text the person cannot see to // the agent that reads the message they send: every default-ignorable code @@ -40,7 +39,7 @@ const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g; // interlinear annotation marks, the object replacement character, the null // notehead). Joiners and the two emoji // selectors are judged by what they follow instead (dropStrayMarks). -const IGNORABLE = /(?![\u200c\u200d\ufe0e\ufe0f])\p{Default_Ignorable_Code_Point}|[\u2800\ufff9-\ufffc\u{13430}-\u{1343f}\u{1d159}]/gu; +const IGNORABLE = /(?!\u200c|\u200d|\ufe0e|\ufe0f)\p{Default_Ignorable_Code_Point}|[\u2800\ufff9-\ufffc\u{13430}-\u{1343f}\u{1d159}]/gu; // Private-use and unassigned code points: no font this text will meet draws // them as words, and some draw as nothing at all (Apple's U+F860 family, the // unassigned Mongolian and Thai slots) or shift the text after them. diff --git a/packages/web/store/composeSlice.ts b/packages/web/store/composeSlice.ts index 57f7e285be..1f43f48b54 100644 --- a/packages/web/store/composeSlice.ts +++ b/packages/web/store/composeSlice.ts @@ -53,6 +53,22 @@ export type ComposeSliceState = { toggleComposeDock: () => void; }; +/** A composer opened for a task (a compose link) is born bound to it: the + * create carries the stub's _linkedObject (createSessionFromStub), and the + * server links the session and makes it the task's owner in the same + * transaction, as the task list's start does. active_task is the new + * session's task badge (header, sidebar) from its first optimistic paint, as + * ContextChatInput sets it; the composer itself draws no task chip. */ +export function bindComposeTask( + store: { syncRecord: (field: string, id: string, record: any) => void }, + stubId: string, + task: NonNullable, +): void { + const activeTask = { _id: task._id, short_id: task.short_id, title: task.title, status: task.status }; + store.syncRecord("sessions", stubId, { _linkedObject: { type: "task", id: task._id }, active_task: activeTask }); + store.syncRecord("conversations", stubId, { active_task_id: task._id, active_task: activeTask }); +} + /** The draft content held for a compose stub, or null when there is none worth * keeping. MessageInput persists text and pasted images (blob previews * included) into drafts[id] synchronously as they change. */