Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let core decide which web chats a viewer can continue (#2267)

Regan Bell63e9c3249eba
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 230e68cf2..89f18fee5 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -327,12 +327,11 @@ type WebConversation = {
};
function conversationForScope(
- user: string,
threadRef: string,
scope: string | undefined,
channelName: string | undefined,
): WebConversation | null {
- if (!scope || scope === `personal:${user}`) return { kind: "dm", threadRef };
+ if (!scope || scope.startsWith("personal:")) return { kind: "dm", threadRef };
const sep = scope.indexOf(":");
const kind = scope.slice(0, sep);
const ref = scope.slice(sep + 1);
@@ -346,17 +345,12 @@ async function resolveWebConversation(
scope: string | undefined,
channelName: string | undefined,
): Promise<{ conversation: WebConversation } | { error: string; message: string }> {
- if (
- (/^web:.+:inbox$/.test(threadRef) && threadRef !== `web:${user}:inbox`) ||
- (!threadRef.startsWith(`web:${user}:`) &&
- !threadRef.startsWith(SUBAGENT_THREAD_PREFIX) &&
- !(scope?.startsWith("channel:") || scope?.startsWith("group:")))
- ) {
+ if (/^web:.+:inbox$/.test(threadRef) && threadRef !== `web:${user}:inbox`) {
return { error: "forbidden_thread", message: "this conversation can only be continued from its own context" };
}
if (threadRef === `web:${user}:inbox` && !isInboxUser(user))
return { error: "forbidden", message: "inbox access is not enabled for this user" };
- const conversation = conversationForScope(user, threadRef, scope, channelName);
+ const conversation = conversationForScope(threadRef, scope, channelName);
if (!conversation || (threadRef === `web:${user}:inbox` && conversation.kind !== "dm")) {
return {
error: "forbidden_scope",
diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.ts
index 122b8bdac..88e37a89f 100644
--- a/plugins/web-ui/src/contexts.ts
+++ b/plugins/web-ui/src/contexts.ts
@@ -18,7 +18,6 @@ import {
} from "lucide";
import {
api,
- isContinuable,
sharedContextLabel,
type CoreContext,
type CoreProject,
@@ -1381,7 +1380,7 @@ async function loadScopeResources(scopeId: string): Promise<void> {
function contextSessionRow(s: CoreSession): TemplateResult {
const surface = surfaceOf(s);
- const readOnly = !isContinuable(s, appState.me?.user ?? "");
+ const readOnly = !s.canContinue;
return html`
<button class="context-session-row" type="button" @click=${() => void openFromContext(s)}>
<span class="context-session-title" dir="auto">${groupDmTitle(s)}</span>
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index b9120d3c1..69c40c42f 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -140,6 +140,7 @@ export interface CoreSession {
working?: boolean;
awaitingInput?: boolean;
lastTurnFailed?: boolean;
+ canContinue?: boolean;
backgroundJobs?: number;
watches?: number;
crons?: number;
@@ -593,15 +594,6 @@ export function continuableMessages(
return { messages: kept.length ? kept : [resumeAnchor()], popped };
}
-const SUBAGENT_THREAD_PREFIX = "agent:main:subagent:";
-
-export function isContinuable(s: Pick<CoreSession, "threadRef" | "scopeId">, user: string): boolean {
- if (s.threadRef.startsWith(SUBAGENT_THREAD_PREFIX))
- return s.scopeId === `personal:${user}` || s.scopeId.startsWith("channel:") || s.scopeId.startsWith("group:");
- if (!s.threadRef.startsWith("web:")) return false;
- return s.threadRef.startsWith(`web:${user}:`) || s.scopeId.startsWith("channel:") || s.scopeId.startsWith("group:");
-}
-
function zeroUsage(): Usage {
return {
input: 0,
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index 1ac60d380..3d5eec842 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -41,7 +41,6 @@ import {
currentEarlierCount,
detachSession,
inheritedTranscript,
- isContinuable,
entriesToMessages,
regenerateTitle,
sharedContextLabel,
@@ -804,7 +803,7 @@ function isActiveRow(s: CoreSession): boolean {
}
function chatPageRow(s: CoreSession): TemplateResult {
- const readOnly = !isContinuable(s, appState.me?.user ?? "");
+ const readOnly = !s.canContinue;
const color = displaySessionColor(s.color);
return html`
<div class="list-row chat-row ${color ? "colored" : ""}" style=${color ? `--session-color:${color}` : nothing}>
@@ -890,6 +889,7 @@ export function addPendingSession(
title: pendingFork ? "Forking…" : null,
channelName,
archived: false,
+ canContinue: true,
};
if (pendingFork) pendingForkThreads.add(threadRef);
sessionsState.list = withPendingSession(sessionsState.list, pending);
@@ -980,7 +980,7 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
const untitledProjectChild = projectChild && !s.title?.trim();
let title = sessionTitle(s);
if (untitledProjectChild) title = surfaceOf(s) === "web" ? "Web chat" : "New chat";
- const readOnly = !isContinuable(s, appState.me?.user ?? "");
+ const readOnly = !s.canContinue;
const surface = surfaceOf(s);
const context = projectChild ? null : rowContext(s);
const working = sessionWorking(s);
@@ -1828,7 +1828,7 @@ export async function openSessionInto(
const fetchEntries = (): Promise<TranscriptPage | null> =>
fetchTranscript(s.id, { tailTurns: TAIL_TURNS }).catch(() => null);
- const continuable = isContinuable(s, appState.me?.user ?? "");
+ const continuable = s.canContinue === true;
const [entriesRes, approvalsRes] = await Promise.all([
entriesPrefetch ? entriesPrefetch.then((r) => r ?? fetchEntries()) : fetchEntries(),
continuable ? (approvalsPrefetch ?? fetchSessionApprovals(s.id)) : Promise.resolve(null),
diff --git a/plugins/web-ui/test/api-body-parsing.test.ts b/plugins/web-ui/test/api-body-parsing.test.ts
index a15a055d6..1f0c16b33 100644
--- a/plugins/web-ui/test/api-body-parsing.test.ts
+++ b/plugins/web-ui/test/api-body-parsing.test.ts
@@ -113,17 +113,6 @@ test("a steer forwards a server-built TurnRequest; client-supplied identity fiel
assert.deepEqual(body.request?.conversation, { kind: "dm", threadRef });
});
-test("a steer claiming a thread the user does not own is refused before reaching core", async () => {
- const before = calls.length;
- const r = await fetch(`${base}/api/runs/r1/signal`, {
- method: "POST",
- headers,
- body: JSON.stringify({ kind: "steer", text: "louder", threadRef: "web:bob:stolen" }),
- });
- assert.equal(r.status, 403);
- assert.equal(calls.length, before, "nothing is forwarded to core");
-});
-
test("ordinary steering without conversation context and abort preserve bare signal forwarding", async () => {
for (const body of [
{ kind: "steer", text: "louder" },
diff --git a/plugins/web-ui/test/continuable.test.ts b/plugins/web-ui/test/continuable.test.ts
deleted file mode 100644
index 2a6982083..000000000
--- a/plugins/web-ui/test/continuable.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { isContinuable, slackThreadUrl } from "../src/core-bridge.ts";
-
-test("own web sessions are continuable in any scope", () => {
- assert.equal(isContinuable({ threadRef: "web:alice:t1", scopeId: "personal:alice" }, "alice"), true);
- assert.equal(isContinuable({ threadRef: "web:alice:t1", scopeId: "channel:C1" }, "alice"), true);
-});
-
-test("a teammate's web session is continuable only when it lives in a shared scope", () => {
- assert.equal(isContinuable({ threadRef: "web:alice:t1", scopeId: "channel:C1" }, "bob"), true);
- assert.equal(isContinuable({ threadRef: "web:alice:t1", scopeId: "group:G1" }, "bob"), true);
- assert.equal(isContinuable({ threadRef: "web:alice:t1", scopeId: "personal:alice" }, "bob"), false);
-});
-
-test("Slack-anchored sessions are never continuable here", () => {
- assert.equal(isContinuable({ threadRef: "dm:D1", scopeId: "personal:alice" }, "alice"), false);
- assert.equal(isContinuable({ threadRef: "ch:C1:1699999999.000100", scopeId: "channel:C1" }, "alice"), false);
-});
-
-test("slackThreadUrl builds archive permalinks from threadRefs", () => {
- const base = "https://acme.slack.com";
- assert.equal(slackThreadUrl(base, "ch:C0AB12CD3:1699999999.000100"), `${base}/archives/C0AB12CD3/p1699999999000100`);
- assert.equal(slackThreadUrl(base, "dm:D0AB12CD3"), `${base}/archives/D0AB12CD3`);
- assert.equal(slackThreadUrl(null, "dm:D0AB12CD3"), null, "no workspace URL → no link");
- assert.equal(slackThreadUrl(base, "web:alice:t1"), null, "web threadRefs are not Slack-linkable");
-});
diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.ts
index 9687577d2..45fee7f37 100644
--- a/plugins/web-ui/test/deep-link-boot-fixture.ts
+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts
@@ -52,6 +52,7 @@ export const SESSION = {
threadRef: "web:tester:deep",
scopeId: "personal:tester",
title: "Deep linked chat",
+ canContinue: true,
};
export async function harness(opts: HarnessOptions): Promise<Harness> {
diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.ts
index 355058f26..a0d96b170 100644
--- a/plugins/web-ui/test/deep-link-boot.test.ts
+++ b/plugins/web-ui/test/deep-link-boot.test.ts
@@ -77,7 +77,13 @@ test("a share link whose transcript fetch flakes still opens from the session li
test("a session list that wins the race keeps its own decorated rows", async () => {
const listed = { ...SESSION, working: true };
- const other = { id: "sess-other", threadRef: "web:tester:other", scopeId: "personal:tester", title: "Other" };
+ const other = {
+ id: "sess-other",
+ threadRef: "web:tester:other",
+ scopeId: "personal:tester",
+ title: "Other",
+ canContinue: true,
+ };
const h = await harness({ path: "/s/sess-deep", holdTranscript: true, listSessions: [other, listed] });
try {
const booted = h.boot();
@@ -102,7 +108,13 @@ test("a session list that wins the race keeps its own decorated rows", async ()
});
test("a list that omits the open conversation does not drop its row", async () => {
- const other = { id: "sess-other", threadRef: "web:tester:other", scopeId: "personal:tester", title: "Other" };
+ const other = {
+ id: "sess-other",
+ threadRef: "web:tester:other",
+ scopeId: "personal:tester",
+ title: "Other",
+ canContinue: true,
+ };
const h = await harness({ path: "/s/sess-deep", listSessions: [other] });
try {
await h.boot();
@@ -119,7 +131,13 @@ test("a list that omits the open conversation does not drop its row", async () =
});
test("a list landing mid-open still keeps the row of the conversation being opened", async () => {
- const other = { id: "sess-other", threadRef: "web:tester:other", scopeId: "personal:tester", title: "Other" };
+ const other = {
+ id: "sess-other",
+ threadRef: "web:tester:other",
+ scopeId: "personal:tester",
+ title: "Other",
+ canContinue: true,
+ };
const h = await harness({ path: "/s/sess-deep", holdApprovals: true, listSessions: [other] });
try {
const booted = h.boot();
diff --git a/plugins/web-ui/test/fork-feedback.test.ts b/plugins/web-ui/test/fork-feedback.test.ts
index 062158dcc..97fd24233 100644
--- a/plugins/web-ui/test/fork-feedback.test.ts
+++ b/plugins/web-ui/test/fork-feedback.test.ts
@@ -16,6 +16,7 @@ test("fork feedback survives delayed success, failure, and navigation", async ()
id: "source",
threadRef: "web:tester:source",
scopeId: "personal:tester",
+ canContinue: true,
type: "dm",
createdAt: Date.now(),
title: "Source conversation",
diff --git a/plugins/web-ui/test/inbox-index-chat.test.ts b/plugins/web-ui/test/inbox-index-chat.test.ts
index 85760e66a..be328f460 100644
--- a/plugins/web-ui/test/inbox-index-chat.test.ts
+++ b/plugins/web-ui/test/inbox-index-chat.test.ts
@@ -16,6 +16,7 @@ test("inbox sidebar restores its conversation and releases it on native navigati
id: "inbox-session",
threadRef: "web:[email protected]:inbox",
scopeId: "personal:[email protected]",
+ canContinue: true,
surface: "web",
title: "Inbox",
updatedAt: 100,
diff --git a/plugins/web-ui/test/restored-pane-load.test.ts b/plugins/web-ui/test/restored-pane-load.test.ts
index 639da8d5c..dde221253 100644
--- a/plugins/web-ui/test/restored-pane-load.test.ts
+++ b/plugins/web-ui/test/restored-pane-load.test.ts
@@ -3,7 +3,7 @@ import test from "node:test";
import { harness, SESSION } from "./deep-link-boot-fixture.ts";
import type { CoreSession, TranscriptPage } from "../src/core-bridge.ts";
-const session: CoreSession = { ...SESSION, threadRef: "dm:sample", type: "dm", createdAt: 1 };
+const session: CoreSession = { ...SESSION, threadRef: "dm:sample", type: "dm", createdAt: 1, canContinue: false };
const entries = [{ seq: 1, type: "assistant", createdAt: 1, payload: { text: "Stored response" } }];
async function waitFor(predicate: () => boolean): Promise<void> {
for (let i = 0; i < 200 && !predicate(); i++) await new Promise((resolve) => setTimeout(resolve, 10));
diff --git a/plugins/web-ui/test/slack-thread-url.test.ts b/plugins/web-ui/test/slack-thread-url.test.ts
new file mode 100644
index 000000000..4c3f590b3
--- /dev/null
+++ b/plugins/web-ui/test/slack-thread-url.test.ts
@@ -0,0 +1,11 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { slackThreadUrl } from "../src/core-bridge.ts";
+
+test("slackThreadUrl builds archive permalinks from threadRefs", () => {
+ const base = "https://acme.slack.com";
+ assert.equal(slackThreadUrl(base, "ch:C0AB12CD3:1699999999.000100"), `${base}/archives/C0AB12CD3/p1699999999000100`);
+ assert.equal(slackThreadUrl(base, "dm:D0AB12CD3"), `${base}/archives/D0AB12CD3`);
+ assert.equal(slackThreadUrl(null, "dm:D0AB12CD3"), null, "no workspace URL → no link");
+ assert.equal(slackThreadUrl(base, "web:alice:t1"), null, "web threadRefs are not Slack-linkable");
+});
diff --git a/plugins/web-ui/test/turn-idempotency-route.test.ts b/plugins/web-ui/test/turn-idempotency-route.test.ts
index 4f9657082..d2ec73724 100644
--- a/plugins/web-ui/test/turn-idempotency-route.test.ts
+++ b/plugins/web-ui/test/turn-idempotency-route.test.ts
@@ -123,14 +123,13 @@ test("ordinary chats and invalid app references cannot inject app context", asyn
assert.equal(response.status, 202);
assert.equal(turns.at(-1)?.conversationHeader, undefined);
}
- const count = turns.length;
const response = await fetch(`${base}/api/turn`, {
method: "POST",
headers,
body: JSON.stringify({ text: "hello", threadRef: "web:bob:app-edit:sample-app" }),
});
- assert.equal(response.status, 403);
- assert.equal(turns.length, count);
+ assert.equal(response.status, 202);
+ assert.equal(turns.at(-1)?.conversationHeader, undefined, "someone else's app thread carries no app context");
});
test("inbox chat loads fresh caller-scoped previews separately from the user message", async () => {
diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.ts
index 1a8fdf1f7..bbf38bf96 100644
--- a/src/api/app-helpers.ts
+++ b/src/api/app-helpers.ts
@@ -422,6 +422,30 @@ export function createAppHelpers(deps: AppDeps, app: App) {
const principalCanWriteScope = createCanWriteScope(scopeMembershipDeps);
+ async function mayWriteSession(
+ principalId: string,
+ session: Pick<Session, "threadRef" | "scopeId">,
+ sharedAccess = new Map<ScopeId, Promise<boolean>>(),
+ ): Promise<boolean> {
+ const actor = deps.identity.classify(principalId);
+ if (!deps.identity.isInternal(actor)) return false;
+ const { kind, ref } = parseScopeId(session.scopeId);
+ if (kind === "personal") return session.scopeId === scopeId("personal", actor.id);
+ if (kind !== "channel" && kind !== "group") return false;
+ if (isSubagentThreadRef(session.threadRef)) return principalCanWriteScope(actor.id, session.scopeId);
+ if (!sharedAccess.has(session.scopeId)) sharedAccess.set(session.scopeId, mayUseSharedScope(kind, ref, actor));
+ return sharedAccess.get(session.scopeId)!;
+ }
+
+ async function canContinueOnWeb(
+ principalId: string,
+ session: Pick<Session, "threadRef" | "scopeId">,
+ sharedAccess?: Map<ScopeId, Promise<boolean>>,
+ ): Promise<boolean> {
+ if (!session.threadRef.startsWith("web:") && !isSubagentThreadRef(session.threadRef)) return false;
+ return mayWriteSession(principalId, session, sharedAccess);
+ }
+
async function principalCanAccessCurrentScope(principalId: string, targetScope: ScopeId): Promise<boolean> {
if (await principalCanWriteScope(principalId, targetScope)) return true;
const { kind, ref } = parseScopeId(targetScope);
@@ -752,6 +776,8 @@ export function createAppHelpers(deps: AppDeps, app: App) {
canUseContext,
principalCanAccessCurrentScope,
principalCanWriteScope,
+ canContinueOnWeb,
+ mayWriteSession,
principalCanManageScope,
membershipControlsScope,
authorizesCapabilityScope,
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index c3b46981e..42a7ed91e 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -6,7 +6,7 @@ import { deploymentShareScope } from "../deploy/email-access.ts";
import { workingSessionThreadRefs } from "../sessions/session-syscalls.ts";
import type { PendingApprovalRecord } from "../types.ts";
import { orgId as orgIdOf } from "../config.ts";
-import { parseScopeId, scopeId } from "../types.ts";
+import { parseScopeId, scopeId, type ScopeId } from "../types.ts";
import { fileArtifactId, artifactPath } from "../files/file-artifact-store.ts";
import { entryWithinTenure, transcriptEntries, windowedTranscript } from "../sessions/session-store.ts";
import { createTranscriptSource } from "../harness/tape-projection.ts";
@@ -117,6 +117,7 @@ export function createSessionMethods(
approvalRecordIsCurrent,
principalCanAccessCurrentScope,
principalCanWriteScope,
+ canContinueOnWeb,
principalGitPermission,
principalCanManageScope,
membershipControlsScope,
@@ -259,8 +260,9 @@ export function createSessionMethods(
},
async getSessionForViewer(sessionId, principalId, window) {
- const session = await sessionForViewer(sessionId, principalId);
- if (!session) return null;
+ const found = await sessionForViewer(sessionId, principalId);
+ if (!found) return null;
+ const session = { ...found, canContinue: await canContinueOnWeb(principalId, found) };
let limit = tailWindowLimit(window);
const [initialRead, pinRecords] = await Promise.all([
transcripts.forViewer(sessionId, principalId, {
@@ -411,9 +413,24 @@ export function createSessionMethods(
}
const waiting = new Set(approvalRows.filter((r) => r.blocksInput !== false).map((r) => r.sessionId));
const workingThreadRefs = await workingSessionThreadRefs(deps.sessions, deps.runs, waiting);
- const sessions = all.filter(
- (s) =>
- s.hasEntries !== false || Boolean(s.title?.trim()) || workingThreadRefs.has(s.threadRef) || waiting.has(s.id),
+ const sharedAccess = new Map<ScopeId, Promise<boolean>>(
+ all
+ .filter((s) => {
+ const { kind, ref } = parseScopeId(s.scopeId);
+ return kind === "group" && projectIdFromGroupRef(ref);
+ })
+ .map((s) => [s.scopeId, Promise.resolve(true)]),
+ );
+ const sessions = await Promise.all(
+ all
+ .filter(
+ (s) =>
+ s.hasEntries !== false ||
+ Boolean(s.title?.trim()) ||
+ workingThreadRefs.has(s.threadRef) ||
+ waiting.has(s.id),
+ )
+ .map(async (s) => ({ ...s, canContinue: await canContinueOnWeb(principalId, s, sharedAccess) })),
);
const now = Date.now();
const jobCounts = new Map<string, number>();
@@ -837,7 +854,8 @@ export function createSessionMethods(
const session = await sessionForViewer(sessionId, principalId);
if (!session) return null;
await deps.sessions.updateParticipantView(sessionId, principalId, patch);
- return sessionForViewer(sessionId, principalId);
+ const updated = await sessionForViewer(sessionId, principalId);
+ return updated && { ...updated, canContinue: await canContinueOnWeb(principalId, updated) };
},
async detachSession(sessionId, principalId) {
@@ -926,7 +944,8 @@ export function createSessionMethods(
resource: sessionId,
scopeLabel: source.scopeId,
});
- const session = (await deps.sessions.get(forked.id)) ?? forked;
+ const stored = (await deps.sessions.get(forked.id)) ?? forked;
+ const session = { ...stored, canContinue: await canContinueOnWeb(principalId, stored) };
return { session, entries: transcriptEntries((await transcripts.forRender(forked.id)).entries) };
};
const projectId = parsed.kind === "group" ? projectIdFromGroupRef(parsed.ref) : null;
@@ -961,7 +980,8 @@ export function createSessionMethods(
resource: session.id,
scopeLabel: scope,
});
- return { session: (await deps.sessions.get(session.id)) ?? session };
+ const stored = (await deps.sessions.get(session.id)) ?? session;
+ return { session: { ...stored, canContinue: await canContinueOnWeb(principalId, stored) } };
};
if (parsed.kind === "personal") {
return parsed.ref === principalId ? create() : null;
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index 5a0ec7589..82fc7a5c9 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -244,6 +244,8 @@ export function createTurnMethods(
if (existing.scopeId !== claimed) {
return { status: "refused", reason: "that conversation lives in a different context" };
}
+ if (!(await h.mayWriteSession(actor.id, existing)))
+ return { status: "refused", reason: "you can't continue that conversation from the web" };
} else if (threadRef.startsWith("web:") && !threadRef.startsWith(`web:${actor.id}:`)) {
return { status: "refused", reason: "you can only start a new conversation on your own thread" };
}
diff --git a/src/types.ts b/src/types.ts
index 1c8f9d19d..49d6babbf 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -112,6 +112,7 @@ export interface Session {
working?: boolean;
awaitingInput?: boolean;
lastTurnFailed?: boolean;
+ canContinue?: boolean;
backgroundJobs?: number;
watches?: number;
crons?: number;
diff --git a/test/run-signal-route.test.ts b/test/run-signal-route.test.ts
index 9c39796b5..1c47db6ce 100644
--- a/test/run-signal-route.test.ts
+++ b/test/run-signal-route.test.ts
@@ -470,7 +470,8 @@ test("web proxy: a steer claiming another user's thread is refused", async () =>
body: JSON.stringify({ kind: "steer", text: "louder", threadRef: "web:bob:stolen" }),
}),
);
- assert.equal(steer.status, 403);
+ assert.equal(steer.status, 400);
+ assert.equal(((await steer.json()) as { reason?: string }).reason, "conversation_mismatch");
assert.deepEqual(await built.signals.takePending(submit.runId!), []);
});
diff --git a/test/web-ui-shared-threads.test.ts b/test/web-ui-shared-threads.test.ts
index 0a4d18c74..59d034451 100644
--- a/test/web-ui-shared-threads.test.ts
+++ b/test/web-ui-shared-threads.test.ts
@@ -50,6 +50,7 @@ interface SessionRow {
id: string;
threadRef: string;
scopeId: string;
+ canContinue?: boolean;
}
async function sessionsOf(user: string): Promise<SessionRow[]> {
@@ -111,7 +112,7 @@ test("a channel member can continue a teammate's shared web thread; outsiders an
}),
);
assert.ok(bobTurn.status < 300, `bob's continuation should be accepted (got ${bobTurn.status})`);
- await waitForSession("bob", "web:alice:s1");
+ assert.equal((await waitForSession("bob", "web:alice:s1")).canContinue, true);
assert.equal(
(await fetch(`${webBase}/api/runs/active?threadRef=${encodeURIComponent("web:alice:s1")}`, asUser("bob"))).status,
@@ -127,7 +128,10 @@ test("a channel member can continue a teammate's shared web thread; outsiders an
asUser("bob", { method: "POST", body: JSON.stringify({ text: "sneak", threadRef: "web:alice:s1" }) }),
);
assert.equal(personalClaim.status, 403);
- assert.equal(((await personalClaim.json()) as { error: string }).error, "forbidden_thread");
+ assert.equal(
+ ((await personalClaim.json()) as { reason: string }).reason,
+ "that conversation lives in a different context",
+ );
const outsider = await fetch(
`${webBase}/api/turn`,
@@ -138,3 +142,61 @@ test("a channel member can continue a teammate's shared web thread; outsiders an
);
assert.equal(outsider.status, 403);
});
+
+test("a person's own chats stay writable whichever login started them; Slack threads and other people stay out", async () => {
+ const old = await built.sessions.getOrCreateByThread("web:oidc:test:42:p1", "dm", "personal:[email protected]");
+ await built.sessions.addParticipant(old.id, "[email protected]", "Started on my other login");
+ const slack = await built.sessions.getOrCreateByThread("dm:D9", "dm", "personal:[email protected]");
+ await built.sessions.addParticipant(slack.id, "[email protected]", "Slack DM");
+
+ const mine = await waitForSession("[email protected]", "web:oidc:test:42:p1");
+ assert.equal(mine.canContinue, true);
+ const continued = await fetch(
+ `${webBase}/api/turn`,
+ asUser("[email protected]", {
+ method: "POST",
+ body: JSON.stringify({ text: "again", threadRef: mine.threadRef, scopeId: mine.scopeId }),
+ }),
+ );
+ assert.ok(continued.status < 300, `carol should continue her own chat (got ${continued.status})`);
+
+ assert.equal(
+ (await waitForSession("[email protected]", "dm:D9")).canContinue,
+ false,
+ "Slack threads are read-only here",
+ );
+
+ const other = await fetch(
+ `${webBase}/api/turn`,
+ asUser("dave", {
+ method: "POST",
+ body: JSON.stringify({ text: "sneak", threadRef: mine.threadRef, scopeId: mine.scopeId }),
+ }),
+ );
+ assert.equal(other.status, 403);
+});
+
+test("someone who can start a chat in a public channel can keep going in it", async () => {
+ await built.app.upsertChannels(
+ [{ channelId: "C4", name: "town-square", isPrivate: false }],
+ [{ channelId: "C4", principalId: "alice" }],
+ );
+ const first = await fetch(
+ `${webBase}/api/turn`,
+ asUser("erin", {
+ method: "POST",
+ body: JSON.stringify({ text: "hi", threadRef: "web:erin:t1", scopeId: "channel:C4", channelName: "town-square" }),
+ }),
+ );
+ assert.ok(first.status < 300, `erin's first turn should be accepted (got ${first.status})`);
+ const session = await waitForSession("erin", "web:erin:t1");
+ assert.equal(session.canContinue, true);
+ const second = await fetch(
+ `${webBase}/api/turn`,
+ asUser("erin", {
+ method: "POST",
+ body: JSON.stringify({ text: "more", threadRef: session.threadRef, scopeId: session.scopeId }),
+ }),
+ );
+ assert.ok(second.status < 300, `erin's second turn should be accepted (got ${second.status})`);
+});