Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions packages/convex/convex/assistant.linkedTask.test.ts
Original file line number Diff line number Diff line change
@@ -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:<owner>), 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([]);
});
});
18 changes: 11 additions & 7 deletions packages/convex/convex/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -1037,6 +1037,15 @@ const SIDE_EFFECTS: Record<string, HandlerFn> = {
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();
Expand Down Expand Up @@ -1116,12 +1125,7 @@ const SIDE_EFFECTS: Record<string, HandlerFn> = {
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
Expand Down
13 changes: 4 additions & 9 deletions packages/convex/convex/dispatchHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

Expand Down Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions packages/web/app/inbox/QueuePageClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
14 changes: 11 additions & 3 deletions packages/web/components/ComposeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand All @@ -170,6 +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 });
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 });
Expand Down Expand Up @@ -213,7 +214,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<HTMLTextAreaElement>("textarea") : null;
if (ta) ta.scrollTop = ta.scrollHeight;
};
const t = setTimeout(() => { focusInput(); showCaret(); }, 60);
window.addEventListener("focus", focusInput);
return () => {
clearTimeout(t);
Expand Down
Loading
Loading