feat: share a thread with a guest who watches live and sends messages you approve #24104
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 11 commits into
main fromrefs/pull/24104/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/guest/GuestShareService.ts line 298OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +278,21 @@278+ return [item];279+ });280+ const working = () =>281+ [...runStatuses.values()].some((status) => WORKING_RUN_STATUSES.has(status));282+ let thread: OrchestrationV2AppThread = projection.thread;283+ const view = () => guestShareView(thread, working());284+ const initialView = view();285+ if (initialView === null) return yield* inactive;286+287+ const ended: GuestStreamEvent = { type: "ended" };288+ const live = orchestrator289+ .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })290+ .pipe(291+ Stream.map((stored): ReadonlyArray<GuestStreamEvent> => {292+ const event = stored.event;293+ switch (event.type) {294+ case "run.created":295+ case "run.updated": {296+ if (!isGuestVisibleRun(event.payload, share.historyStartRunOrdinal)) return [];297+ const wasWorking = working();298+ runStatuses.set(event.payload.id, event.payload.status);apps/web/src/components/guest/GuestPage.tsx line 133OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +113,21 @@113+ if (stream.view) document.title = stream.view.title;114+ }, [stream.view]);115+116+ useEffect(() => {117+ const source = new EventSource(`${GUEST_ROUTE_PREFIX}/stream`);118+ source.addEventListener("message", (message) => {119+ const event = parseGuestStreamEvent(message.data);120+ if (event === null) return;121+ dispatch(event);122+ if (event.type === "ended") source.close();123+ });124+ source.addEventListener("error", () => {125+ if (source.readyState === EventSource.CLOSED) setRejected(true);126+ });127+ return () => source.close();128+ }, []);129+130+ if (stream.ended || (rejected && stream.view !== null)) {131+ return <Notice text="This link has ended." />;132+ }133+ if (stream.view !== null) return <GuestThread view={stream.view} items={stream.items} />;apps/server/src/guest/GuestShareService.ts line 264OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +244,21 @@244+ const { thread, share } = yield* authorize(session, "session");245+ yield* dispatchGuestCommand({246+ type: "thread.guest-message.submit",247+ commandId: yield* commandId("submit"),248+ threadId: thread.id,249+ shareId: share.id,250+ guestMessageId: GuestMessageId.make(yield* crypto.randomUUIDv4().pipe(Effect.orDie)),251+ text: request.text,252+ });253+ });254+255+ const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {256+ const { thread: authorizedThread, share } = yield* authorize(session, "session");257+ const snapshot = yield* orchestrator258+ .getThreadSnapshotWindow(authorizedThread.id, {259+ rowLimit: SNAPSHOT_ROW_LIMIT,260+ userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,261+ })262+ .pipe(Effect.mapError(() => inactive));263+ const { projection } = snapshot;264+ if (projection.thread.guestShare?.id !== share.id) return yield* inactive;apps/web/src/components/guest/GuestPage.tsx line 294OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +274,21 @@274+ return (275+ <div className="chat-markdown min-w-0 text-sm leading-relaxed [overflow-wrap:anywhere]">276+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={MARKDOWN_COMPONENTS}>277+ {text}278+ </ReactMarkdown>279+ </div>280+ );281+}282+283+function GuestComposer() {284+ const [text, setText] = useState("");285+ const [sending, setSending] = useState(false);286+ const [error, setError] = useState<string | null>(null);287+ const send = async () => {288+ const trimmed = text.trim();289+ if (trimmed === "" || sending) return;290+ setSending(true);291+ const failure = await postGuest("messages", { text: trimmed });292+ setSending(false);293+ setError(failure);294+ if (failure === null) setText("");
- apps/mobile/src/features/threads/ThreadGuestShareBar.tsx lines 58 to 59OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+ * sharing, and the guest messages that wait for Send or Dismiss. Links are created on web.40+ */41+export function ThreadGuestShareBar(props: {42+ readonly threadRef: ScopedThreadRef | null;43+ readonly canOperateThread: boolean;44+}) {45+ const { threadRef } = props;46+ const shareAtom = useMemo(47+ () => (threadRef === null ? NO_GUEST_SHARE_ATOM : guestShareAtom(threadRef)),48+ [threadRef],49+ );50+ const share = useAtomValue(shareAtom);51+ const closeGuestShare = useAtomCommand(threadEnvironment.closeGuestShare, "stop guest sharing");52+ const resolveGuestMessage = useAtomCommand(53+ threadEnvironment.resolveGuestMessage,54+ "resolve guest message",55+ );56+ // One request at a time: a second tap while the first is in flight would double-send.57+ const [busy, setBusy] = useState(false);58+ // Checked when the thread opens; an expired link stays listed until the owner stops sharing.59+ const [openedAt] = useState(Date.now);apps/server/src/guest/GuestShareService.ts lines 135 to 138OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +118,21 @@118+ return decodeClaims(base64UrlDecodeUtf8(payload)).pipe(119+ Option.filter((claims) => claims.kind === kind),120+ );121+ });122+123+ const connectHostname = managedEndpoint.inspectConnector.pipe(124+ Effect.map((facts) => facts?.hostname ?? null),125+ );126+127+ const dispatchGuestCommand = (128+ command: Parameters<Orchestrator.OrchestratorV2["Service"]["dispatch"]>[0],129+ ) =>130+ orchestrator.dispatch(command).pipe(131+ Effect.mapError(132+ (cause) =>133+ new GuestShareAccessError({134+ reason: "rejected",135+ message:136+ "cause" in cause && typeof cause.cause === "string"137+ ? cause.cause138+ : "The owner's server rejected this request.",apps/server/src/orchestration-v2/GuestShareDecider.ts lines 134 to 160Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +100,21 @@100+ return withShare({ ...share, guestName: command.guestName });101+ }102+ case "thread.guest-message.submit": {103+ if (104+ share === null ||105+ share.id !== command.shareId ||106+ share.guestName === null ||107+ isExpired(share, now)108+ ) {109+ return Result.fail("This guest link is no longer active.");110+ }111+ if (112+ share.messages.filter((message) => message.status === "pending").length >=113+ GUEST_PENDING_MESSAGE_LIMIT114+ ) {115+ return Result.fail("Wait for the owner to answer your earlier messages.");116+ }117+ return withShare({118+ ...share,119+ messages: trimResolved([120+ ...share.messages,apps/web/src/components/guest/GuestPage.tsx line 35OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+import remarkGfm from "remark-gfm";16+17+import { Button } from "../ui/button";18+import { Input } from "../ui/input";19+import { Textarea } from "../ui/textarea";20+import {21+ applyGuestStreamEvent,22+ initialGuestStreamState,23+ parseGuestStreamEvent,24+} from "./guestStream.logic";25+26+let capturedInvite: { readonly credential: string | null } | null = null;27+28+/**29+ * The invite credential travels in the URL hash so it never reaches a server log. It is read30+ * once and removed from history, so it lives only in memory. Opening the page never redeems it:31+ * only submitting a name does, so a reload before that leaves the link usable.32+ */33+function takeInviteCredential(): string | null {34+ if (capturedInvite === null) {35+ const credential = decodeURIComponent(window.location.hash.slice(1)).trim();packages/client-runtime/src/state/threadSettled.ts line 92Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -88,3 +89,4 @@8889 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;8990 if (shell.source?.pendingRuntimeRequest != null) return true;9091 if (shell.pendingSubagentRequest != null) return true;92+ if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;packages/contracts/src/guestShare.ts lines 67 to 73OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +53,21 @@53+ nowMs >= Date.parse(share.expiresAt);54+55+export const pendingGuestMessageCount = (share: ThreadGuestShare | null | undefined): number =>56+ share?.messages.filter((message) => message.status === "pending").length ?? 0;57+58+export const GuestShareCreateInput = Schema.Struct({ threadId: ThreadId });59+export type GuestShareCreateInput = typeof GuestShareCreateInput.Type;60+61+export const GuestShareCreateResult = Schema.Struct({62+ url: TrimmedNonEmptyString,63+ share: ThreadGuestShare,64+});65+export type GuestShareCreateResult = typeof GuestShareCreateResult.Type;66+67+export class GuestShareCreateError extends Schema.TaggedError<GuestShareCreateError>()(68+ "GuestShareCreateError",69+ {70+ reason: Schema.Literals(["connect_unavailable", "thread_unavailable", "internal"]),71+ message: Schema.String,72+ },73+) {}packages/contracts/src/guestShare.ts line 77OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+58+export const GuestShareCreateInput = Schema.Struct({ threadId: ThreadId });59+export type GuestShareCreateInput = typeof GuestShareCreateInput.Type;60+61+export const GuestShareCreateResult = Schema.Struct({62+ url: TrimmedNonEmptyString,63+ share: ThreadGuestShare,64+});65+export type GuestShareCreateResult = typeof GuestShareCreateResult.Type;66+67+export class GuestShareCreateError extends Schema.TaggedError<GuestShareCreateError>()(68+ "GuestShareCreateError",69+ {70+ reason: Schema.Literals(["connect_unavailable", "thread_unavailable", "internal"]),71+ message: Schema.String,72+ },73+) {}74+75+export const GuestRedeemRequest = Schema.Struct({76+ credential: TrimmedNonEmptyString,77+ name: TrimmedNonEmptyString.check(Schema.isMaxLength(GUEST_NAME_MAX_LENGTH)),packages/contracts/src/orchestrationV2.ts line 440Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -412,3 +415,4 @@412415 snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),413416 lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),414417 limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)),418+ guestShare: Schema.optional(Schema.NullOr(ThreadGuestShare)),
- apps/web/src/components/guest/GuestPage.tsx line 93OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +73,21 @@73+ pending: "Waiting for approval",74+ sent: "Sent",75+ dismissed: "Dismissed",76+};77+78+export function GuestPage() {79+ const [credential] = useState(takeInviteCredential);80+ // An invite always starts at the name form: a cookie from an earlier share on this host must81+ // not stand in for the thread this link points at.82+ const [joined, setJoined] = useState(false);83+84+ useEffect(() => {85+ const root = document.documentElement;86+ root.classList.add("dark");87+ delete root.dataset.themeId;88+ }, []);89+90+ return (91+ <div className="flex h-dvh flex-col bg-black text-white">92+ {credential !== null && !joined ? (93+ <NameForm credential={credential} onJoined={() => setJoined(true)} />
- apps/web/src/components/guest/GuestPage.tsx lines 42 to 42OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +22,21 @@22+import { Button } from "../ui/button";23+import { Input } from "../ui/input";24+import {25+ applyGuestStreamEvent,26+ formatGuestExpiry,27+ initialGuestStreamState,28+ type GuestStreamState,29+ parseGuestStreamEvent,30+ unplacedGuestMessages,31+} from "./guestStream.logic";32+33+let capturedInvite: { readonly credential: string | null } | null = null;34+35+/**36+ * The invite credential travels in the URL hash so it never reaches a server log. It is read37+ * once and removed from history, so it lives only in memory. Opening the page never redeems it:38+ * only submitting a name does, so a reload before that leaves the link usable.39+ */40+function takeInviteCredential(): string | null {41+ if (capturedInvite === null) {42+ const credential = decodeURIComponent(window.location.hash.slice(1)).trim();
- apps/web/src/components/guest/GuestPage.tsx line 362OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +342,21 @@342+};343+344+function GuestMarkdown({ text }: { readonly text: string }) {345+ return (346+ <div className="chat-markdown min-w-0 text-sm leading-relaxed text-foreground/80 [overflow-wrap:anywhere]">347+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={MARKDOWN_COMPONENTS}>348+ {text}349+ </ReactMarkdown>350+ </div>351+ );352+}353+354+function GuestComposer() {355+ const [text, setText] = useState("");356+ const [sending, setSending] = useState(false);357+ const [error, setError] = useState<string | null>(null);358+ const send = async () => {359+ const trimmed = text.trim();360+ if (trimmed === "" || sending) return;361+ setSending(true);362+ const failure = await postGuest("messages", { text: trimmed });
- apps/server/src/orchestration-v2/Orchestrator.ts line 2730Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2638,0 +2663,21 @@2663+ const thread = projection.thread;2664+ const now = yield* DateTime.now;2665+ const decided =2666+ thread.deletedAt !== null2667+ ? Result.fail(`Thread ${command.threadId} is deleted.`)2668+ : decideGuestShareCommand({2669+ thread,2670+ command,2671+ now,2672+ // Queued runs have not happened yet; counting them would hide the active one.2673+ latestRunOrdinal:2674+ projection.runs.filter((run) => run.status !== "queued").at(-1)?.ordinal ?? null,2675+ });2676+ if (Result.isFailure(decided)) {2677+ return yield* new OrchestratorDispatchError({2678+ commandId: command.commandId,2679+ commandType: command.type,2680+ cause: decided.failure,2681+ });2682+ }2683+ if (decided.success === thread) return;
t3dotgg(GitHub profile, opens in a new tab) changed the title
- apps/web/src/components/guest/guestStream.logic.ts line 162Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+108+/**109+ * The guest's messages to show after the transcript, oldest first. Pending ones always show. A110+ * sent or dismissed one shows only while it awaits a row (see `awaitingRowIds`): a queued send, or111+ * a dismissal to report. The transcript is a bounded window, so any other resolved message is old112+ * history, not something to place at the end.113+ */114+export function unplacedGuestMessages(115+ messages: ReadonlyArray<ThreadGuestMessage>,116+ items: ReadonlyArray<GuestTranscriptItem>,117+ awaitingRowIds: ReadonlySet<GuestMessageId>,118+): ReadonlyArray<ThreadGuestMessage> {119+ const placed = new Set(120+ items.flatMap((item) =>121+ item.kind === "user" && item.guestMessageId ? [item.guestMessageId] : [],122+ ),123+ );124+ return messages125+ .filter(126+ (message) =>127+ !placed.has(message.id) && (message.status === "pending" || awaitingRowIds.has(message.id)),
- apps/web/src/components/guest/GuestPage.tsx line 144OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +124,21 @@124+};125+126+/** Same column as the owner's timeline, so both views wrap text at the same width. */127+const LANE = "chat-content-lane px-4";128+129+type GuestAccess = "checking" | "session" | "name" | "none";130+131+export function GuestPage() {132+ const [{ credential, shareId }] = useState(takeGuestEntry);133+ // A browser that already joined this share goes straight back in, even from the spent link.134+ // Sessions are per share, so one for another link never stands in for this one.135+ const [access, setAccess] = useState<GuestAccess>(shareId === null ? "none" : "checking");136+ useEffect(() => {137+ if (shareId === null) return;138+ let live = true;139+ void fetch(`${GUEST_ROUTE_PREFIX}/session?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`)140+ .then(141+ (response): GuestAccess =>142+ response.ok ? "session" : credential !== null ? "name" : "none",143+ // Offline: try the stream, which reports what it finds.144+ (): GuestAccess => "session",
t3dotgg(GitHub profile, opens in a new tab) changed the title
- apps/mobile/src/features/threads/ThreadGuestShareBar.tsx lines 73 to 80Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+ * sharing. Links are created on web. Waiting messages show in the feed, see65+ * `ThreadGuestPendingMessages`.66+ */67+export function ThreadGuestShareBar(props: {68+ readonly threadRef: ScopedThreadRef | null;69+ readonly canOperateThread: boolean;70+}) {71+ const { threadRef } = props;72+ const share = useThreadGuestShare(threadRef);73+ const closeGuestShare = useAtomCommand(threadEnvironment.closeGuestShare, "stop guest sharing");74+ const [busy, setBusy] = useState(false);75+ // An expired link stays listed until the owner stops sharing; the label flips when it expires.76+ const [now, setNow] = useState(Date.now);77+ const expiresAt = share?.expiresAt;78+ useEffect(() => {79+ if (expiresAt === undefined) return;80+ const remaining = Date.parse(expiresAt) - Date.now();81+ if (remaining <= 0) return;82+ const timer = setTimeout(() => setNow(Date.now()), remaining);83+ return () => clearTimeout(timer);84+ }, [expiresAt]);apps/server/src/guest/guestProjection.ts line 222OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +202,21 @@202+ }),203+ file_change: (item, base, roots) => ({204+ ...base,205+ type: "file_change",206+ fileName: guestPath(item.fileName, roots),207+ ...(item.additions === undefined ? {} : { additions: item.additions }),208+ ...(item.deletions === undefined ? {} : { deletions: item.deletions }),209+ ...(item.changes === undefined210+ ? {}211+ : {212+ changes: item.changes.map((change) => ({213+ operation: change.operation,214+ path: guestPath(change.path, roots),215+ ...(change.oldPath === undefined ? {} : { oldPath: guestPath(change.oldPath, roots) }),216+ })),217+ }),218+ }),219+ command_execution: (item, base, roots) => ({220+ ...base,221+ type: "command_execution",222+ input: guestText(item.input, roots),
- apps/server/src/guest/guestProjection.ts lines 56 to 61OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +41,21 @@41+ return [42+ ...workspaces.flatMap((root) => {43+ const trimmed = dir(root);44+ return trimmed === null ? [] : [{ dir: trimmed, as: "." as const }];45+ }),46+ ...[dir(home)].flatMap((trimmed) =>47+ trimmed === null ? [] : [{ dir: trimmed, as: "~" as const }],48+ ),49+ ].toSorted((left, right) => right.dir.length - left.dir.length);50+}51+52+const isAbsolutePath = (path: string) => /^(?:[\\/]|[A-Za-z]:[\\/])/u.test(path);53+54+/** A path inside a root loses it; any other absolute path keeps only its base name. */55+function guestPath(path: string, roots: GuestPathRoots): string {56+ for (const { dir, as } of roots) {57+ if (path === dir) return as;58+ if (path.startsWith(`${dir}/`) || path.startsWith(`${dir}\\`)) {59+ const rest = path.slice(dir.length + 1);60+ return as === "." ? rest || "." : `~/${rest}`;61+ }
- packages/contracts/src/guestStream.ts line 152OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +132,21 @@132+ Schema.Struct({133+ ...GuestTurnItemBaseFields,134+ type: Schema.Literal("file_change"),135+ fileName: TrimmedNonEmptyString,136+ additions: Schema.optional(NonNegativeInt),137+ deletions: Schema.optional(NonNegativeInt),138+ changes: Schema.optional(139+ Schema.Array(140+ Schema.Struct({141+ operation: TrimmedNonEmptyString,142+ path: TrimmedNonEmptyString,143+ oldPath: Schema.optional(TrimmedNonEmptyString),144+ }),145+ ),146+ ),147+ }),148+ /** The command and how it ended. Output is where secrets live, so it never reaches a guest. */149+ Schema.Struct({150+ ...GuestTurnItemBaseFields,151+ type: Schema.Literal("command_execution"),152+ input: Schema.String,
t3dotgg(GitHub profile, opens in a new tab) changed the title
- apps/server/src/orchestration-v2/Orchestrator.ts lines 11749 to 11760Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -11540,5 +11684,15 @@1154011684 threadId: command.threadId,1154111685 });1154211686 }11543- yield* dispatchMessage(command, events, effects);11544- yield* recordSubagentFollowup(command, events).pipe(mapDispatchError(command));11687+ const guestSend =11688+ command.guestMessageId === undefined11689+ ? undefined11690+ : yield* emitGuestMessageSent(command, command.guestMessageId, thread, events);11691+ const dispatched =11692+ guestSend === undefined11693+ ? withoutGuestAttribution(command)11694+ : {11695+ ...command,11696+ text: guestSend.text,11697+ context: { version: 1 as const, records: [], guest: guestSend.guest },11698+ };
t3dotgg(GitHub profile, opens in a new tab) changed the title
t3dotgg(GitHub profile, opens in a new tab) changed the title
- apps/server/src/guest/GuestShareService.ts line 304Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +284,21 @@284+ crypto.randomUUIDv4().pipe(285+ Effect.map((uuid) => CommandId.make(`server:guest-share:${label}:${uuid}`)),286+ Effect.orDie,287+ );288+289+ /** Checks a token against the live share: same id, not expired, and Connect still serving it. */290+ const authorize = Effect.fn("GuestShareService.authorize")(function* (291+ token: string,292+ kind: "invite" | "session",293+ ) {294+ const claims = yield* kind === "invite" ? verifyInvite(token) : verifySession(token);295+ if (Option.isNone(claims)) {296+ return yield* new GuestShareAccessError({ reason: "invalid" });297+ }298+ const { thread } = yield* orchestrator299+ .getThreadRecords(claims.value.threadId, [])300+ .pipe(Effect.mapError(() => inactive));301+ const share = thread.guestShare;302+ const now = yield* DateTime.now;303+ if (304+ !(yield* sharingEnabled) ||
t3dotgg(GitHub profile, opens in a new tab) changed the title
Sign in to join this conversation.









Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
67c3afb· PR result:f03c1e8· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.