TypeScript
feat: share a thread with a guest who watches live and sends messages you approve (#24104)
Theo Brownefb76594d7b9f
diff --git a/apps/mobile/generated-uniwind-themes.css b/apps/mobile/generated-uniwind-themes.cssindex caf91e40348..039c7d694ed 100644--- a/apps/mobile/generated-uniwind-themes.css+++ b/apps/mobile/generated-uniwind-themes.css@@ -110,6 +110,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);--color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);--color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);+ --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);--color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);--color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);@@ -271,6 +273,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);--color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);--color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);+ --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);--color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);--color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);@@ -432,6 +436,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);--color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);--color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);+ --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);--color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);--color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);@@ -593,6 +599,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);--color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);--color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);+ --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);--color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);--color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);@@ -754,6 +762,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);--color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);--color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);+ --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);--color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);--color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);@@ -915,6 +925,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);--color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);--color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);+ --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);--color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);--color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);@@ -1076,6 +1088,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);--color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);--color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);+ --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);--color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);--color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);@@ -1237,6 +1251,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);--color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);--color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);+ --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);--color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);--color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);@@ -1398,6 +1414,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);--color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);--color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);+ --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);--color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);--color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);@@ -1559,6 +1577,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);--color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);--color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);+ --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);--color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);--color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);@@ -1720,6 +1740,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);--color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);--color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);+ --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);--color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);--color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);@@ -1881,6 +1903,8 @@--color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);--color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);--color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);+ --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);+ --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);--color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);--color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);--color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);diff --git a/apps/mobile/scripts/generate-uniwind-themes.mts b/apps/mobile/scripts/generate-uniwind-themes.mtsindex d930766e5fd..0aa52aab7ce 100644--- a/apps/mobile/scripts/generate-uniwind-themes.mts+++ b/apps/mobile/scripts/generate-uniwind-themes.mts@@ -86,6 +86,11 @@ const ADAPTIVE_COLORS: Readonly<Record<string, readonly [light: string, dark: st],"--color-adaptive-emerald-600-400": [color("emerald", 600), color("emerald", 400)],"--color-adaptive-emerald-700-300": [color("emerald", 700), color("emerald", 300)],+ "--color-adaptive-fuchsia-500-a50-300-a40": [+ color("fuchsia", 500, 0.5),+ color("fuchsia", 300, 0.4),+ ],+ "--color-adaptive-fuchsia-600-300": [color("fuchsia", 600), color("fuchsia", 300)],"--color-adaptive-indigo-500-a12-a16": [color("indigo", 500, 0.12), color("indigo", 500, 0.16)],"--color-adaptive-indigo-600-300": [color("indigo", 600), color("indigo", 300)],"--color-adaptive-indigo-700-300": [color("indigo", 700), color("indigo", 300)],diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 83fd54f2ac0..7f6fb2032c5 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -188,6 +188,7 @@ import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";import { useThreadTurnSubagents } from "./ThreadAgentsSheet";import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";import { useThreadQueuedCount } from "./ThreadQueueControl";+import { ThreadGuestShareBar } from "./ThreadGuestShareBar";import type { ThreadContentPresentation } from "./threadContentPresentation";import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";import { useOpenLinkedThread } from "./useOpenLinkedThread";@@ -1632,6 +1633,10 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaikey={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}thread={props.selectedThread}/>+ <ThreadGuestShareBar+ threadRef={props.selectedThreadDetailRef}+ canOperateThread={props.canOperateThread}+ />{props.feedbackSubmissions.map((submission) => (<ComposerFeedbackkey={submission.id}diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 6f0619ab37a..85c33fa08fb 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -16,6 +16,8 @@ import {} from "../../lib/enrichedLinkPresentation";import { ThreadContextDivider } from "./thread-context-divider";import { ThreadHandoffDivider, ThreadHandoffRow } from "./thread-handoff-row";+import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle";+import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar";import { SecretRequestCard } from "./SecretRequestCard";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import {@@ -229,9 +231,11 @@ import {WORK_GROUP_TOGGLE_HEIGHT,} from "./thread-work-log";import {+ appendGuestPendingMessages,appendPendingThreadMessages,isCompactionCommandFeedEntry,type PendingThreadFeedEntry,+ type ThreadFeedRow,} from "./pending-thread-feed";import type { QueuedThreadMessage } from "../../state/thread-outbox-model";import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";@@ -760,6 +764,38 @@ function MessageAttachmentFile(props: {);}+/** A message's files as its bubble shows them; a guest's waiting message uses it too. */+function MessageAttachmentList(props: {+ readonly attachments: ReadonlyArray<ChatAttachment>;+ readonly environmentId: EnvironmentId;+ readonly onPressPreview: (source: FilePreviewSource) => void;+ readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;+}) {+ return props.attachments.map((attachment) =>+ isImageAttachment(attachment) ? (+ <MessageAttachmentImage+ key={attachment.id}+ environmentId={props.environmentId}+ attachmentId={attachment.id}+ name={attachment.name}+ mimeType={attachment.mimeType}+ className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-subtle-strong"+ onPressPreview={props.onPressPreview}+ />+ ) : isFileAttachment(attachment) ? (+ <MessageAttachmentFile+ key={attachment.id}+ environmentId={props.environmentId}+ attachment={attachment}+ onPressPreview={props.onPressPreview}+ onPressVideo={props.onPressVideo}+ />+ ) : (+ <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />+ ),+ );+}+function MessageAttachmentUnknown(props: { readonly name: string }) {return (<View className="flex-row items-center gap-2 py-1">@@ -1203,7 +1239,7 @@ function compactionLabel(label: string, title: string | undefined) {}function renderFeedEntry(- info: { item: PendingThreadFeedEntry; index: number },+ info: { item: ThreadFeedRow; index: number },props: Pick<ThreadFeedProps,| "environmentId"@@ -1251,6 +1287,25 @@ function renderFeedEntry(const entry = info.item;const { markdownStyles, iconSubtleColor, userBubbleColor } = props;+ if (entry.type === "guest-pending") {+ return (+ <ThreadGuestPendingMessage+ threadRef={scopeThreadRef(props.environmentId, props.threadId)}+ guestName={entry.guestName}+ message={entry.message}+ bubbleMaxWidth={props.duoColumns ? "85%" : props.userBubbleMaxWidth}+ renderAttachments={(attachments) => (+ <MessageAttachmentList+ attachments={attachments}+ environmentId={props.environmentId}+ onPressPreview={props.onPressPreview}+ onPressVideo={props.onPressVideo}+ />+ )}+ />+ );+ }+if (entry.type === "run-fold") {return (<View className="mb-1 flex-row items-center border-b border-border-subtle px-2">@@ -1504,6 +1559,9 @@ function renderFeedEntry(Sent by T3 Code</Text>) : null}+ {presentation.guestName !== undefined ? (+ <GuestMessageName name={presentation.guestName} />+ ) : null}<ViewclassName="min-w-0 rounded-[20px]"style={{@@ -1518,6 +1576,7 @@ function renderFeedEntry(: null),}}>+ {presentation.attribution === "guest" ? <GuestBubbleTint /> : null}{foldRowId !== null ? (<AgentMessageFoldHeaderenvironmentId={props.environmentId}@@ -1676,7 +1735,7 @@ function renderFeedEntry(<UserMessageCopyButtontext={presentation.text}onCopy={- message.context+ message.context && presentation.attribution !== "guest"? () =>writeComposerContextClipboard(message.text, {version: 1,@@ -1722,29 +1781,12 @@ function renderFeedEntry(/></MarkdownImageAvailableWidthContext>) : null}- {attachments.map((attachment) => {- return isImageAttachment(attachment) ? (- <MessageAttachmentImage- key={attachment.id}- environmentId={props.environmentId}- attachmentId={attachment.id}- name={attachment.name}- mimeType={attachment.mimeType}- className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-subtle-strong"- onPressPreview={props.onPressPreview}- />- ) : isFileAttachment(attachment) ? (- <MessageAttachmentFile- key={attachment.id}- environmentId={props.environmentId}- attachment={attachment}- onPressPreview={props.onPressPreview}- onPressVideo={props.onPressVideo}- />- ) : (- <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />- );- })}+ <MessageAttachmentList+ attachments={attachments}+ environmentId={props.environmentId}+ onPressPreview={props.onPressPreview}+ onPressVideo={props.onPressVideo}+ />{showAssistantMeta && message.checkpointSummary ? (<TurnDiffStatcheckpoint={message.checkpointSummary}@@ -2067,6 +2109,11 @@ function useThreadFeedPresentation(export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);+ const guestThreadRef = useMemo(+ () => scopeThreadRef(props.environmentId, props.threadId),+ [props.environmentId, props.threadId],+ );+ const guestShare = useThreadGuestShare(guestThreadRef);const deviceType = useDeviceType();const duoColumns = useNativeWorkspaceColumnsSupported() && isDuoDevice(deviceType);const openPullRequest = useOpenPullRequest();@@ -2662,7 +2709,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {reportHeaderMaterialVisibility(false);}, [feedThreadKey, reportHeaderMaterialVisibility]);- const presentedFeed = useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups);+ const presentedFeed = appendGuestPendingMessages(+ useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups),+ guestShare,+ );const setupAnchorIndex = presentedFeed.findIndex((entry) => entry.type === "message" && entry.message.role === "user",);@@ -2880,7 +2930,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {}};- const shouldRestoreVisibleContentPosition = (entry: ThreadFeedEntry) => {+ const shouldRestoreVisibleContentPosition = (entry: ThreadFeedRow) => {const disclosureAnchorKey = disclosureAnchorKeyRef.current;return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;};@@ -2964,7 +3014,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {// Without this, every row above the viewport is assumed to be// estimatedItemSize tall, and scrolling up through unmeasured content// corrects each row's height as it mounts — the feed visibly jumps.- const getFixedItemSize = (entry: ThreadFeedEntry) => {+ const getFixedItemSize = (entry: ThreadFeedRow) => {+ if (entry.type === "guest-pending") return undefined;if (entry.type === "html-render") {return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth));}@@ -3010,7 +3061,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" });}, [beginReflow, contentWidth, hasHtmlRenders, listRef]);- const renderItem = (info: { item: PendingThreadFeedEntry; index: number }) => (+ const renderItem = (info: { item: ThreadFeedRow; index: number }) => (<Animated.Viewkey={info.item.id}entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}@@ -3301,7 +3352,7 @@ function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) {}function MessageImageGalleryScope(props: {- entry: PendingThreadFeedEntry;+ entry: ThreadFeedRow;environmentId: EnvironmentId;threadId: ThreadId;workspaceRoot: string | null | undefined;diff --git a/apps/mobile/src/features/threads/ThreadGuestShareBar.tsx b/apps/mobile/src/features/threads/ThreadGuestShareBar.tsxnew file mode 100644index 00000000000..51858161c82--- /dev/null+++ b/apps/mobile/src/features/threads/ThreadGuestShareBar.tsx@@ -0,0 +1,189 @@+import { useAtomValue } from "@effect/atom-react";+import {+ type AtomCommandResult,+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import {+ AuthOrchestrationOperateScope,+ type ChatAttachment,+ type ScopedThreadRef,+ type ThreadGuestMessage,+ type ThreadGuestShare,+} from "@t3tools/contracts";+import { Atom } from "effect/reactivity";+import { type ReactNode, useEffect, useMemo, useState } from "react";+import { View } from "react-native";++import { Button } from "../../components/ui/Button";+import { AppText as Text } from "../../components/ui/AppText";+import { SymbolView } from "../../components/ui/AppSymbol";+import * as Dialog from "../../components/ui/Dialog";+import { useEnvironmentScope } from "../../state/session";+import { environmentThreadDetails, threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { GUEST_PENDING_BUBBLE_CLASS_NAME, GuestMessageName } from "./guestMessageStyle";++const NO_GUEST_SHARE_ATOM = Atom.make<ThreadGuestShare | null>(null);++function guestShareAtom(ref: ScopedThreadRef) {+ let previous: ThreadGuestShare | null = null;+ return Atom.make((get) => {+ const next =+ get(environmentThreadDetails.threadAtom(ref))?.projection.thread.guestShare ?? null;+ // The thread record is replaced on unrelated updates; only share changes matter here.+ if (JSON.stringify(next) !== JSON.stringify(previous)) previous = next;+ return previous;+ });+}++export function useThreadGuestShare(threadRef: ScopedThreadRef | null): ThreadGuestShare | null {+ const shareAtom = useMemo(+ () => (threadRef === null ? NO_GUEST_SHARE_ATOM : guestShareAtom(threadRef)),+ [threadRef],+ );+ return useAtomValue(shareAtom);+}++function alertOnFailure(failureTitle: string, result: AtomCommandResult<unknown, unknown>) {+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ Dialog.alert(failureTitle, error instanceof Error ? error.message : "Try again.");+ }+}++/**+ * Owner controls for a guest link, above the composer: who the link is for and a way to stop+ * sharing. Links are created on web. Waiting messages show in the feed, see+ * `ThreadGuestPendingMessage`.+ */+export function ThreadGuestShareBar(props: {+ readonly threadRef: ScopedThreadRef | null;+ readonly canOperateThread: boolean;+}) {+ const { threadRef } = props;+ const share = useThreadGuestShare(threadRef);+ const closeGuestShare = useAtomCommand(threadEnvironment.closeGuestShare, "stop guest sharing");+ const [busy, setBusy] = useState(false);+ // The server keeps an expired link so waiting messages stay resolvable; the label flips when+ // it expires.+ // Keyed by the expiry, so a replaced link (even one already expired) gets its own timer.+ const [expiredAt, setExpiredAt] = useState<string | null>(null);+ const expiresAt = share?.expiresAt;+ useEffect(() => {+ if (expiresAt === undefined) return;+ const timer = setTimeout(+ () => setExpiredAt(expiresAt),+ Math.max(0, Date.parse(expiresAt) - Date.now()),+ );+ return () => clearTimeout(timer);+ }, [expiresAt]);+ if (threadRef === null || !share) return null;++ const disabled = busy || !props.canOperateThread;+ const stopSharing = () =>+ Dialog.confirm({+ title: "Stop sharing?",+ message: "The guest loses access and the link stops working.",+ confirmText: "Stop sharing",+ destructive: true,+ onConfirm: () => {+ if (disabled) return;+ setBusy(true);+ void closeGuestShare({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId },+ }).then((result) => {+ setBusy(false);+ alertOnFailure("Could not stop sharing", result);+ });+ },+ });++ return (+ <View className="flex-row items-center gap-2 px-4 pb-2">+ <SymbolView name="person.2" size={12} tintColorClassName="accent-foreground-muted" />+ <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>+ {expiredAt === share.expiresAt+ ? "Guest link expired"+ : share.guestName === null+ ? "Guest link active"+ : `${share.guestName} is a guest`}+ </Text>+ <Button label="Stop sharing" tone="text" disabled={disabled} onPress={stopSharing} />+ </View>+ );+}++/**+ * One guest message waiting at the end of the feed until the owner sends or dismisses it. Sent+ * ones then show in the feed as user messages with the guest's name.+ */+export function ThreadGuestPendingMessage(props: {+ readonly threadRef: ScopedThreadRef;+ readonly guestName: string;+ readonly message: ThreadGuestMessage;+ readonly bubbleMaxWidth: number | `${number}%`;+ /** The feed's own attachment rendering, so the owner sees the files before Send. */+ readonly renderAttachments: (attachments: ReadonlyArray<ChatAttachment>) => ReactNode;+}) {+ const { threadRef, guestName, message } = props;+ const canOperate = useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope);+ const resolveGuestMessage = useAtomCommand(+ threadEnvironment.resolveGuestMessage,+ "resolve guest message",+ );+ // One request at a time: a second tap while the first is in flight would double-send.+ const [busy, setBusy] = useState(false);++ const resolve = async (decision: "send" | "dismiss") => {+ if (busy) return;+ setBusy(true);+ const result = await resolveGuestMessage({+ environmentId: threadRef.environmentId,+ input: {+ threadId: threadRef.threadId,+ guestMessageId: message.id,+ decision,+ creationSource: "mobile",+ },+ });+ setBusy(false);+ alertOnFailure(+ decision === "send" ? "Could not send guest message" : "Could not dismiss guest message",+ result,+ );+ };++ return (+ <View className="items-end pb-5">+ <GuestMessageName name={guestName} />+ <View className={GUEST_PENDING_BUBBLE_CLASS_NAME} style={{ maxWidth: props.bubbleMaxWidth }}>+ {message.text ? (+ <Text selectable className="text-base text-foreground">+ {message.text}+ </Text>+ ) : null}+ {props.renderAttachments(message.attachments ?? [])}+ </View>+ {canOperate ? (+ <View className="mt-1.5 flex-row gap-2">+ <Button+ label="Dismiss"+ tone="secondary"+ accessibilityLabel={`Dismiss message from ${guestName}`}+ disabled={busy}+ onPress={() => void resolve("dismiss")}+ />+ <Button+ label="Send"+ tone="primary"+ accessibilityLabel={`Send message from ${guestName}`}+ disabled={busy}+ onPress={() => void resolve("send")}+ />+ </View>+ ) : null}+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsxindex 11ac46da06d..d84c6cd3fcf 100644--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx@@ -211,7 +211,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {No messages waiting in this queue.</Text>) : null}- {queuedRuns.map(({ run, text, attachments }, index) => {+ {queuedRuns.map(({ run, text, attachments, context }, index) => {const layout = dragRows?.find((row) => row.id === run.id);const offset =sourceLayout?.y !== undefined &&@@ -227,6 +227,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {canReorder: workflow?.canReorder ?? false,index,isEditing: editing?.runId === run.id,+ isGuestMessage: context?.guest !== undefined,queuedCount: queuedRuns.length,text,});@@ -364,7 +365,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {<PressableaccessibilityRole="button"accessibilityLabel={title}- accessibilityHint="Opens this message in the composer for editing"+ accessibilityHint={+ controls.canEdit+ ? "Opens this message in the composer for editing"+ : undefined+ }disabled={!controls.canEdit}onPress={() => void act(run.id, "edit")}className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"@@ -381,6 +386,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {}numberOfLines={1}>+ {context?.guest === undefined ? null : (+ <Text className="font-t3-medium text-adaptive-fuchsia-600-300">+ {`${context.guest.name} `}+ </Text>+ )}{title}</Text>{controls.isEditing ? (diff --git a/apps/mobile/src/features/threads/guestMessageStyle.tsx b/apps/mobile/src/features/threads/guestMessageStyle.tsxnew file mode 100644index 00000000000..2704e19fcab--- /dev/null+++ b/apps/mobile/src/features/threads/guestMessageStyle.tsx@@ -0,0 +1,30 @@+import { View } from "react-native";++import { AppText as Text } from "../../components/ui/AppText";++/** The guest's name above their message, where "Sent by T3 Code" sits for server messages. */+export function GuestMessageName(props: { readonly name: string }) {+ return (+ <Text+ accessibilityLabel={`${props.name} (guest)`}+ className="mb-1 pr-1 font-t3-medium text-2xs text-adaptive-fuchsia-600-300"+ numberOfLines={1}+ >+ {props.name}+ </Text>+ );+}++/**+ * First child of a sent guest bubble. Over the bubble color it gives the web's 14% fuchsia mix,+ * which every theme gets without a per-theme token.+ */+export function GuestBubbleTint() {+ return (+ <View pointerEvents="none" className="absolute inset-0 rounded-[20px] bg-fuchsia-500/14" />+ );+}++/** A pending guest bubble has a dashed edge and no fill. */+export const GUEST_PENDING_BUBBLE_CLASS_NAME =+ "min-w-0 rounded-[20px] border border-dashed border-adaptive-fuchsia-500-a50-300-a40 bg-transparent px-3.5 py-2.5";diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.tsindex 80ed9798b98..820afb66a75 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.ts@@ -1,12 +1,51 @@-import { isCompactionCommandMessage } from "@t3tools/contracts";+import {+ isCompactionCommandMessage,+ type ThreadGuestMessage,+ type ThreadGuestShare,+} from "@t3tools/contracts";import type { ThreadFeedEntry } from "../../lib/threadActivity";import type { QueuedThreadMessage } from "../../state/thread-outbox-model";+/**+ * A guest's message waiting for the owner's Send or Dismiss. It is a feed row, not the list+ * footer, so the feed follows it arriving and leaving the way it follows any row.+ */+export interface GuestPendingFeedEntry {+ readonly type: "guest-pending";+ readonly id: string;+ readonly createdAt: string;+ readonly guestName: string;+ readonly message: ThreadGuestMessage;+}+export type PendingThreadFeedEntry = ThreadFeedEntry & {readonly pendingMessage?: QueuedThreadMessage;readonly acknowledged?: boolean;};+/** A row of the thread feed's list. */+export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry;++/** Waiting guest messages go after the transcript, oldest first. */+export function appendGuestPendingMessages(+ presentedFeed: ReadonlyArray<PendingThreadFeedEntry>,+ share: ThreadGuestShare | null,+): ReadonlyArray<ThreadFeedRow> {+ const pending = share?.messages.filter((message) => message.status === "pending") ?? [];+ if (share === null || pending.length === 0) return presentedFeed;+ const guestName = share.guestName ?? "Guest";+ return [+ ...presentedFeed,+ ...pending.map((message): GuestPendingFeedEntry => ({+ type: "guest-pending",+ id: `guest-pending:${message.id}`,+ createdAt: message.submittedAt,+ guestName,+ message,+ })),+ ];+}+export function appendPendingThreadMessages(presentedFeed: ReadonlyArray<ThreadFeedEntry>,feed: ReadonlyArray<ThreadFeedEntry>,diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsxindex 14f9b6688c4..0112824f95f 100644--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx@@ -87,6 +87,12 @@ const STATUS_LABEL_BY_STATUS: Partial<Record<ThreadListV2Status, StatusLabel>> =className: "text-adaptive-indigo-600-300",iconTintClassName: "accent-adaptive-indigo-600-300",},+ request: {+ label: "Request",+ icon: "person.crop.circle",+ className: "text-adaptive-fuchsia-600-300",+ iconTintClassName: "accent-adaptive-fuchsia-600-300",+ },working: {label: "Working",icon: "circle.dashed",diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.tsindex a5fc77b2c6f..58d06bd5e69 100644--- a/apps/mobile/src/features/threads/threadListV2.test.ts+++ b/apps/mobile/src/features/threads/threadListV2.test.ts@@ -100,6 +100,18 @@ describe("resolveThreadListV2Status", () => {);});+ it("shows a waiting guest message as Request, after the agent's own requests", () => {+ const thread = presentThreadShell(+ environmentId,+ decodeThreadShell(makeRawThreadShell({ status: "running" })),+ );+ const guest = { ...thread, pendingGuestMessageCount: 1 };++ expect(resolveThreadListV2Status(guest)).toBe("request");+ expect(resolveThreadListV2Status({ ...guest, hasPendingUserInput: true })).toBe("input");+ expect(resolveThreadListV2Status({ ...guest, hasPendingApprovals: true })).toBe("approval");+ });+it.each([{ roster: "dev server", task: { kind: "command" }, status: "ready" },{ roster: "dev server watchdog", task: { kind: "monitor" }, status: "ready" },diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.tsindex fe0683498d3..52695825152 100644--- a/apps/mobile/src/features/threads/threadListV2.ts+++ b/apps/mobile/src/features/threads/threadListV2.ts@@ -64,6 +64,7 @@ export function resolveThreadListV2ProviderDrivers(export type ThreadListV2Status =| "approval"| "input"+ | "request"| "working"| "waiting"| "failed"@@ -175,6 +176,7 @@ export function resolveThreadListV2Status(| "hasPendingApprovals"| "hasPendingUserInput"| "pendingSubagentRequest"+ | "pendingGuestMessageCount"| "runtime"| "blockedOnThreadWait">,@@ -185,6 +187,10 @@ export function resolveThreadListV2Status(if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {return "input";}+ // A guest is waiting on the owner; the agent's own requests come first.+ if ((thread.pendingGuestMessageCount ?? 0) > 0) {+ return "request";+ }if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {return "waiting";}diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.test.tsindex 60e37f9475d..e53753d8511 100644--- a/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts+++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts@@ -74,6 +74,22 @@ describe("threadQueueControlPresentation", () => {expect(editing.canMoveUp).toBe(true);expect(editing.canDismiss).toBe(true);});++ it("lets the owner cancel a guest's queued message but not rewrite it", () => {+ const guest = resolveThreadQueueRowControls({+ busy: false,+ canPromoteToSteer: true,+ canSendNow: false,+ canReorder: true,+ index: 0,+ isGuestMessage: true,+ queuedCount: 1,+ text: "Why?",+ });++ expect(guest.canEdit).toBe(false);+ expect(guest.canDismiss).toBe(true);+ });});describe("queue drag insertion", () => {diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.tsindex 14fa9e02841..9ffffd98476 100644--- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts+++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts@@ -21,6 +21,8 @@ export function resolveThreadQueueRowControls(input: {readonly canReorder: boolean;readonly index: number;readonly isEditing?: boolean;+ /** A guest's message keeps the guest's words; the owner can cancel it, not rewrite it. */+ readonly isGuestMessage?: boolean;readonly queuedCount: number;readonly text: string;}): ThreadQueueRowControls {@@ -31,7 +33,7 @@ export function resolveThreadQueueRowControls(input: {canDismiss: !input.busy,// Re-opening the row already in the composer would reload it and throw// away whatever has been typed since.- canEdit: mutationEnabled && !isEditing,+ canEdit: mutationEnabled && !isEditing && input.isGuestMessage !== true,canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,canMoveUp: mutationEnabled && input.canReorder && input.index > 0,canSend: mutationEnabled && (input.canPromoteToSteer || input.canSendNow) && !isEditing,diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.tsnew file mode 100644index 00000000000..97cbae14e9e--- /dev/null+++ b/apps/server/src/guest/GuestShareService.test.ts@@ -0,0 +1,810 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { assert, it } from "@effect/vitest";+import {+ ChatAttachmentId,+ CommandId,+ EventId,+ GuestShareId,+ MessageId,+ type OrchestrationV2TurnItem,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ThreadId,+ TurnItemId,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";+import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";+import * as FileSystem from "effect/FileSystem";+import * as Fiber from "effect/Fiber";+import * as Layer from "effect/Layer";+import * as Ref from "effect/Ref";+import * as Option from "effect/Option";+import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";++import {+ createAttachmentId,+ resolveAttachmentPath,+ resolveAttachmentPathById,+ sweepStalePendingAttachments,+} from "../attachmentStore.ts";+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";+import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";+import * as ServerConfig from "../config.ts";+import * as SqlitePersistence from "../persistence/Sqlite.ts";+import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";+import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";+import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts";+import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";+import * as EventSink from "../orchestration-v2/EventSink.ts";+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";+import * as ResourceCleanupService from "../orchestration-v2/ResourceCleanupService.ts";+import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";+import * as ServerSettings from "../serverSettings.ts";+import * as GuestShareService from "./GuestShareService.ts";++const instanceId = ProviderInstanceId.make("codex");+const adapter = {+ instanceId,+ driver: ProviderDriverKind.make("codex"),+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),+ openSession: () => Effect.die("No provider process needed for guest shares"),+} as ProviderAdapter.ProviderAdapterV2["Service"];+const layerDatabase = SqlitePersistence.layerMemory;+const layerOrchestration = Layer.mergeAll(+ layerDatabase,+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),+ EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),+ ProviderReplayHarness.layerWithRegistry(+ { name: "guest-share-service" },+ ProviderAdapterRegistry.layerFromAdapters([adapter]),+ { databaseLayer: layerDatabase, runEffectWorker: false },+ ),+);++// The Connect hostname the fake tunnel reports. Tests set it to null to simulate an unlink.+const hostname = Ref.makeUnsafe<string | null>("env.t3.test");+const layerConnect = Layer.mock(CloudManagedEndpointRuntime)({+ inspectConnector: Effect.map(Ref.get(hostname), (value) => ({+ readyConnections: 1,+ hostname: value,+ protocol: "http2",+ })),+});+const layerProviders = Layer.mock(ProviderRegistry.ProviderRegistry)({+ getProviders: Effect.succeed([]),+});+const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-guest-share-" });+// The real cleanup also closes terminals and previews; these tests only need the files gone.+const layerCleanup = Layer.effect(+ ResourceCleanupService.ResourceCleanupService,+ Effect.gen(function* () {+ const { attachmentsDir } = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ return {+ cleanupScheduledTasks: () => Effect.void,+ cleanupTerminals: () => Effect.void,+ cleanupPreviews: () => Effect.void,+ cleanupAttachments: (attachmentIds) =>+ Effect.forEach(+ attachmentIds,+ (attachmentId) => {+ const path = resolveAttachmentPathById({ attachmentsDir, attachmentId });+ return path === null ? Effect.void : fileSystem.remove(path).pipe(Effect.orDie);+ },+ { discard: true },+ ),+ };+ }),+).pipe(Layer.provide(layerConfig), Layer.provide(NodeServices.layer));+const layerTest = GuestShareService.layer.pipe(+ Layer.provideMerge(+ CommandOutputHub.layer.pipe(+ Layer.provideMerge(layerOrchestration.pipe(Layer.provide(layerCleanup))),+ ),+ ),+ Layer.provide(layerProviders),+ Layer.provideMerge(ServerSettings.layerTest({ guestSharingEnabled: true })),+ Layer.provide(layerConnect),+ Layer.provide(ServerSecretStore.layer),+ Layer.provideMerge(layerConfig),+ Layer.provideMerge(NodeServices.layer),+);++const threadId = ThreadId.make("thread:guest-share-service");++const shareThreadFor = Effect.fn(function* (threadId: ThreadId) {+ yield* Ref.set(hostname, "env.t3.test");+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ yield* orchestrator.dispatch({+ type: "thread.create",+ commandId: CommandId.make(`create:${threadId}`),+ threadId,+ projectId: ProjectId.make("project:guest-share-service"),+ title: "Review me",+ modelSelection: { instanceId, model: "gpt-5.1-codex" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdBy: "user",+ creationSource: "web",+ });+ const guestShares = yield* GuestShareService.GuestShareService;+ const { url } = yield* guestShares.create({ threadId });+ assert.isTrue(url.startsWith("https://env.t3.test/guest#"));+ const credential = url.slice(url.indexOf("#") + 1);+ return { orchestrator, guestShares, credential };+});+const shareThread = shareThreadFor(threadId);++it.effect("spends an invite once and ends the guest stream when the owner stops sharing", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const again = yield* Effect.exit(guestShares.redeem({ credential, name: "Eve" }));+ assert.isTrue(Exit.isFailure(again));+ // The browser that joined can come back without the spent invite.+ assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.check(session))));+ // An invite token is not a session token.+ assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(credential))));++ const events = yield* guestShares.stream(session);+ yield* orchestrator.dispatch({+ type: "thread.guest-share.close",+ commandId: CommandId.make("close-guest-share"),+ threadId,+ });+ const received = Array.from(yield* Stream.runCollect(events));+ assert.deepEqual(+ received.map((event) => (event.type === "thread" ? event.item.kind : event.type)),+ ["view", "snapshot", "ended"],+ );+ assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(session))));+ assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.check(session))));+ }).pipe(Effect.provide(layerTest)),+);++it.effect("streams the owner's thread events after the share and a snapshot", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const events = yield* guestShares.stream(session);+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-message"),+ threadId,+ messageId: MessageId.make("message:owner"),+ text: "Fix the login bug",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-share.close",+ commandId: CommandId.make("close-after-message"),+ threadId,+ });+ const received = Array.from(yield* Stream.runCollect(events));+ assert.equal(received.at(-1)?.type, "ended");+ const turnItems = received.flatMap((event) =>+ event.type === "thread" &&+ event.item.kind === "event" &&+ event.item.event.type === "turn-item.updated"+ ? [event.item.event.payload]+ : [],+ );+ assert.deepEqual(+ turnItems.flatMap((item) => (item.type === "user_message" ? [item.text] : [])),+ ["Fix the login bug"],+ );+ }).pipe(Effect.provide(layerTest)),+);++it.effect("starts a stream with the runs and items already in the thread", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-message-before"),+ threadId,+ messageId: MessageId.make("message:before"),+ text: "Fix the login bug",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ const [view, snapshot] = Array.from(+ yield* Stream.runCollect(Stream.take(yield* guestShares.stream(session), 2)),+ );+ assert.equal(view?.type, "view");+ if (snapshot?.type !== "thread" || snapshot.item.kind !== "snapshot") {+ return assert.fail("Expected the thread snapshot second.");+ }+ assert.equal(snapshot.item.projection.runs.length, 1);+ assert.include(+ snapshot.item.projection.visibleTurnItems.map((row) => row.item.type),+ "user_message",+ );+ }).pipe(Effect.provide(layerTest)),+);++it.effect("redeems only a short invite whose signature and share id are both current", () =>+ Effect.gen(function* () {+ const { guestShares, credential: replaced } = yield* shareThread;+ const { url } = yield* guestShares.create({ threadId });+ const credential = url.slice(url.indexOf("#") + 1);+ assert.match(credential, /^[\w-]{22}\.[\w-]{22}$/);++ const [shareId, signature] = credential.split(".");+ const tampered = `${shareId}.${signature!.startsWith("A") ? "B" : "A"}${signature!.slice(1)}`;+ for (const rejected of [tampered, replaced]) {+ const error = yield* Effect.flip(guestShares.redeem({ credential: rejected, name: "Eve" }));+ assert.equal(error.reason, "invalid");+ }+ assert.isTrue(+ Exit.isSuccess(yield* Effect.exit(guestShares.redeem({ credential, name: "Sam" }))),+ );+ }).pipe(Effect.provide(layerTest)),+);++it.effect("refuses guest requests once T3 Connect no longer serves the link's host", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const { id: shareId } = (yield* Orchestrator.OrchestratorV2.use((orchestrator) =>+ orchestrator.getThreadRecords(threadId, []),+ )).thread.guestShare!;+ yield* Ref.set(hostname, null);+ const submitted = yield* Effect.exit(+ guestShares.submit(session, { shareId, text: "Hello" }, []),+ );+ assert.isTrue(Exit.isFailure(submitted));+ }).pipe(Effect.provide(layerTest)),+);++it.effect("closes an open guest stream when T3 Connect stops serving the link's host", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(+ Effect.forkChild,+ );+ yield* Ref.set(hostname, null);+ yield* TestClock.adjust("30 seconds");+ // No `ended`: the browser reconnects, and the host check refuses it while Connect is gone.+ const received = Array.from(yield* Fiber.join(collecting));+ assert.deepEqual(+ received.map((event) => (event.type === "thread" ? event.item.kind : event.type)),+ ["view", "snapshot"],+ );+ assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(session))));+ yield* Ref.set(hostname, "env.t3.test");+ assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.stream(session))));+ }).pipe(Effect.provide(layerTest)),+);++it.effect("refuses new links and every guest request while the beta is off", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(+ Effect.forkChild,+ );+ const settings = yield* ServerSettings.ServerSettingsService;+ yield* settings.updateSettings({ guestSharingEnabled: false });+ // An open stream closes at the next access check.+ yield* TestClock.adjust("30 seconds");+ yield* Fiber.join(collecting);+ assert.equal((yield* Effect.flip(guestShares.create({ threadId }))).reason, "disabled");+ assert.equal((yield* Effect.flip(guestShares.check(session))).reason, "inactive");+ // Turning it back on lets the same guest back in.+ yield* settings.updateSettings({ guestSharingEnabled: true });+ assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.check(session))));+ }).pipe(Effect.provide(layerTest)),+);++it.effect("ends an open guest stream when the link expires", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(+ Effect.forkChild,+ );+ yield* TestClock.adjust("25 hours");+ const received = Array.from(yield* Fiber.join(collecting));+ assert.equal(received.at(-1)?.type, "ended");+ }).pipe(Effect.provide(layerTest)),+);++it.effect("shows the guest the thread's new model", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const events = yield* guestShares.stream(session);+ yield* orchestrator.dispatch({+ type: "thread.model-selection.set",+ commandId: CommandId.make("switch-model"),+ threadId,+ modelSelection: { instanceId, model: "gpt-5.2-codex" },+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-share.close",+ commandId: CommandId.make("close-after-switch"),+ threadId,+ });+ const views = Array.from(yield* Stream.runCollect(events)).flatMap((event) =>+ event.type === "view" ? [event.view.model.name] : [],+ );+ assert.include(views, "gpt-5.2-codex");+ }).pipe(Effect.provide(layerTest)),+);++it.effect("refuses a message a page sends for a share the cookie no longer opens", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const submitted = yield* Effect.exit(+ guestShares.submit(session, { shareId: GuestShareId.make("share:older"), text: "Hello" }, []),+ );+ assert.isTrue(Exit.isFailure(submitted));+ }).pipe(Effect.provide(layerTest)),+);++it.effect("serves no render for an item outside the shared thread", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.render(session, "item:missing"))));+ // The invite itself is not a session.+ assert.isTrue(+ Exit.isFailure(yield* Effect.exit(guestShares.render(credential, "item:missing"))),+ );+ }).pipe(Effect.provide(layerTest)),+);++/** A message from the owner, which opens a run for the command below. */+const ownerRun = Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-message-for-command"),+ threadId,+ messageId: MessageId.make("message:command"),+ text: "Build it",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ const { runs } = (yield* orchestrator.getThreadSnapshotWindow(threadId, { rowLimit: 10 }))+ .projection;+ return runs[0]!.id;+});++const writeCommand = (+ id: string,+ fields: Pick<+ Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,+ "status" | "output"+ >,+) =>+ Effect.gen(function* () {+ const runId = yield* ownerRun;+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ yield* eventSink.write({+ events: [+ {+ id: EventId.make(`event:${id}`),+ type: "turn-item.updated",+ threadId,+ driver: ProviderDriverKind.make("codex"),+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: TurnItemId.make(id),+ threadId,+ runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ title: null,+ startedAt: now,+ completedAt: fields.status === "running" ? null : now,+ updatedAt: now,+ type: "command_execution",+ input: "ls /work/src",+ ...fields,+ },+ },+ ],+ });+ return TurnItemId.make(id);+ });++it.effect("gives the guest a command's detail and output, as the owner's row loads them", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const command = yield* writeCommand("item:command", {+ status: "completed",+ output: "/work/src/auth.ts\n",+ });++ const detail = (yield* guestShares.item(session, command)).item;+ assert.deepInclude(detail, { input: "ls /work/src", output: "/work/src/auth.ts\n" });+ const frames = Array.from(+ yield* Stream.runCollect(yield* guestShares.commandOutput(session, command)),+ );+ assert.deepEqual(frames, [+ { kind: "replace", text: "/work/src/auth.ts\n", truncated: false, running: false },+ ]);+ // Only with a session, and only for an item of this thread.+ const refused: ReadonlyArray<Effect.Effect<unknown, GuestShareService.GuestShareAccessError>> =+ [+ guestShares.item(credential, command),+ guestShares.commandOutput(credential, command),+ guestShares.item(session, "item:elsewhere"),+ ];+ for (const request of refused) {+ assert.isTrue(Exit.isFailure(yield* Effect.exit(request)));+ }+ }).pipe(Effect.provide(layerTest)),+);++it.effect("ends a running command's output once the owner stops sharing", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, credential } = yield* shareThread;+ const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });+ const command = yield* writeCommand("item:running", { status: "running" });+ const collecting = yield* Stream.runCollect(+ yield* guestShares.commandOutput(session, command),+ ).pipe(Effect.forkChild);+ yield* orchestrator.dispatch({+ type: "thread.guest-share.close",+ commandId: CommandId.make("close-during-command"),+ threadId,+ });+ yield* TestClock.adjust("30 seconds");+ const frames = Array.from(yield* Fiber.join(collecting));+ assert.isTrue(frames.every((frame) => frame.running));+ assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command))));+ }).pipe(Effect.provide(layerTest)),+);++const PNG = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13);+const MIB = 1024 * 1024;++/** Files as the multipart parser leaves them: on disk, with the browser's name and type. */+const uploadsOf = Effect.fn(function* (+ files: ReadonlyArray<{+ readonly name: string;+ readonly contentType: string;+ readonly bytes: Uint8Array;+ }>,+) {+ const fileSystem = yield* FileSystem.FileSystem;+ const directory = yield* fileSystem.makeTempDirectoryScoped();+ return yield* Effect.forEach(files, (file, index) => {+ const path = `${directory}/${index}`;+ return fileSystem+ .writeFile(path, file.bytes)+ .pipe(Effect.as({ name: file.name, contentType: file.contentType, path }));+ });+});+const png = (name: string, sizeBytes = PNG.length) => {+ const bytes = new Uint8Array(sizeBytes);+ bytes.set(PNG);+ return { name, contentType: "image/png", bytes };+};++/** Every stored attachment file. */+const storedFiles = Effect.gen(function* () {+ const { attachmentsDir } = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ return yield* fileSystem.readDirectory(attachmentsDir).pipe(Effect.orElseSucceed(() => []));+});++const joinedGuest = Effect.gen(function* () {+ const shared = yield* shareThread;+ const { token: session, shareId } = yield* shared.guestShares.redeem({+ credential: shared.credential,+ name: "Sam",+ });+ return { ...shared, session, shareId };+});++const waitingMessages = Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const { thread } = yield* orchestrator.getThreadRecords(threadId, []);+ return thread.guestShare?.messages ?? [];+});++it.effect("refuses too many files, too many bytes, and images that are not what they say", () =>+ Effect.gen(function* () {+ const { guestShares, session, shareId } = yield* joinedGuest;+ const before = yield* storedFiles;+ const refused = [+ ["too_many_files", [1, 2, 3, 4, 5].map((index) => png(`${index}.png`))],+ ["too_large", [png("big.png", 10 * MIB + 1)]],+ ["unsupported_file", [{ name: "logo.svg", contentType: "image/svg+xml", bytes: PNG }]],+ [+ "unsupported_file",+ [{ name: "page.png", contentType: "image/png", bytes: new TextEncoder().encode("<html>") }],+ ],+ [+ "unsupported_file",+ [{ name: "empty.txt", contentType: "text/plain", bytes: new Uint8Array() }],+ ],+ ] as const;+ for (const [reason, files] of refused) {+ const error = yield* Effect.flip(+ guestShares.submit(session, { shareId, text: "Look" }, yield* uploadsOf(files)),+ );+ assert.equal(error.reason, reason);+ }+ // Nothing is kept from a refused message, and no message waits.+ assert.deepEqual(yield* storedFiles, before);+ assert.deepEqual(yield* waitingMessages, []);++ yield* guestShares.submit(+ session,+ { shareId, text: "" },+ yield* uploadsOf([+ png("screen.png"),+ // A direction override would make this name read as a PDF.+ {+ name: "notes\u202Efdp.html",+ contentType: "text/html",+ bytes: new TextEncoder().encode("<b>"),+ },+ ]),+ );+ const [message] = yield* waitingMessages;+ assert.deepEqual(+ message?.attachments?.map(({ type, name, mimeType, sizeBytes }) => ({+ type,+ name,+ mimeType,+ sizeBytes,+ })),+ [+ { type: "image", name: "screen.png", mimeType: "image/png", sizeBytes: PNG.length },+ { type: "file", name: "notes_fdp.html", mimeType: "text/html", sizeBytes: 3 },+ ],+ );+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);++it.effect("caps the bytes of files waiting in one share", () =>+ Effect.gen(function* () {+ const { guestShares, session, shareId } = yield* joinedGuest;+ const submit = (sizeBytes: number) =>+ Effect.gen(function* () {+ return guestShares.submit(+ session,+ { shareId, text: "Look" },+ yield* uploadsOf([png("big.png", sizeBytes)]),+ );+ }).pipe(Effect.flatten);+ yield* submit(9 * MIB);+ yield* submit(9 * MIB);+ const error = yield* Effect.flip(submit(9 * MIB));+ assert.equal(error.reason, "files_busy");+ // Text alone still goes through.+ yield* guestShares.submit(session, { shareId, text: "One more thing" }, []);+ assert.equal((yield* waitingMessages).length, 3);+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);++it.effect("deletes a waiting message's files when the owner dismisses it or stops sharing", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;+ yield* guestShares.submit(+ session,+ { shareId, text: "First" },+ yield* uploadsOf([png("a.png")]),+ );+ yield* guestShares.submit(+ session,+ { shareId, text: "Second" },+ yield* uploadsOf([png("b.png")]),+ );+ const [first, second] = yield* waitingMessages;+ const fileOf = (message: typeof first) => message!.attachments![0]!.id;+ const stored = yield* storedFiles;+ assert.isTrue(stored.some((entry) => entry.startsWith(fileOf(first))));++ yield* orchestrator.dispatch({+ type: "thread.guest-message.dismiss",+ commandId: CommandId.make("dismiss-first"),+ threadId,+ guestMessageId: first!.id,+ });+ yield* worker.drain();+ const afterDismiss = yield* storedFiles;+ assert.isFalse(afterDismiss.some((entry) => entry.startsWith(fileOf(first))));+ assert.isTrue(afterDismiss.some((entry) => entry.startsWith(fileOf(second))));+ // A dismissed message's file is no longer the guest's to load.+ assert.isTrue(+ Exit.isFailure(yield* Effect.exit(guestShares.attachment(session, fileOf(first)))),+ );++ yield* orchestrator.dispatch({+ type: "thread.guest-share.close",+ commandId: CommandId.make("close-with-files"),+ threadId,+ });+ yield* worker.drain();+ assert.isFalse((yield* storedFiles).some((entry) => entry.startsWith(fileOf(second))));+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);++it.effect.each(["thread.archive", "thread.delete"] as const)(+ "deletes a waiting message's files on %s",+ (type) =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;+ const before = yield* storedFiles;+ yield* guestShares.submit(+ session,+ { shareId, text: "Look" },+ yield* uploadsOf([png("a.png")]),+ );+ assert.equal((yield* storedFiles).length, before.length + 1);+ yield* orchestrator.dispatch({+ type,+ commandId: CommandId.make(`${type}-with-files`),+ threadId,+ });+ yield* worker.drain();+ assert.deepEqual(yield* storedFiles, before);+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);++it.effect("sends a guest's files as the guest's message and keeps them the guest's to load", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;+ yield* guestShares.submit(+ session,+ { shareId, text: "See this" },+ yield* uploadsOf([png("a.png")]),+ );+ const [message] = yield* waitingMessages;+ const pending = message!.attachments!;+ // Served while it waits.+ const served = yield* guestShares.attachment(session, pending[0]!.id);+ assert.equal(served.attachment.mimeType, "image/png");++ // The day-old pending-upload sweep leaves a waiting guest's files alone.+ const { attachmentsDir } = yield* ServerConfig.ServerConfig;+ // Any pending upload counts as stale at the end of time.+ sweepStalePendingAttachments({ attachmentsDir, nowMs: Number.MAX_SAFE_INTEGER });+ const copied = pending[0]!;+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("send-guest-files"),+ threadId,+ messageId: MessageId.make("message:guest-files"),+ guestMessageId: message!.id,+ text: "",+ attachments: [copied],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ const items = (yield* orchestrator.getThreadSnapshotWindow(threadId, {+ rowLimit: 20,+ })).projection.visibleTurnItems.map((entry) => entry.item);+ const sent = items.find(+ (item) => item.type === "user_message" && item.context?.guest?.guestMessageId === message!.id,+ );+ assert.deepInclude(sent, { attachments: [copied] });+ if (sent?.type !== "user_message") return;+ assert.deepEqual(sent.context?.guest, {+ guestMessageId: message!.id,+ name: "Sam",+ text: "See this",+ shareId,+ });+ // The guest loads the thread's copy from their own row.+ const fromRow = yield* guestShares.attachment(session, copied.id);+ assert.equal(fromRow.attachment.id, copied.id);++ // Still theirs after their share's message list has trimmed it away.+ for (let index = 0; index < 21; index += 1) {+ yield* guestShares.submit(session, { shareId, text: `note ${index}` }, []);+ const [waiting] = (yield* waitingMessages).filter((next) => next.status === "pending");+ yield* orchestrator.dispatch({+ type: "thread.guest-message.dismiss",+ commandId: CommandId.make(`dismiss-note-${index}`),+ threadId,+ guestMessageId: waiting!.id,+ });+ }+ assert.isFalse((yield* waitingMessages).some((next) => next.id === message!.id));+ assert.equal((yield* guestShares.attachment(session, copied.id)).attachment.id, copied.id);+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);++it.effect("serves the shared thread's files to its guest, never another thread's", () =>+ Effect.gen(function* () {+ const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;+ // Another thread's guest attaches a file.+ const other = yield* shareThreadFor(ThreadId.make("thread:other-share"));+ const otherGuest = yield* guestShares.redeem({ credential: other.credential, name: "Eve" });+ yield* guestShares.submit(+ otherGuest.token,+ { shareId: otherGuest.shareId, text: "Mine" },+ yield* uploadsOf([png("eve.png")]),+ );+ const { thread: otherThread } = yield* orchestrator.getThreadRecords(+ ThreadId.make("thread:other-share"),+ [],+ );+ const othersFile = otherThread.guestShare!.messages[0]!.attachments![0]!.id;+ assert.isTrue(+ Exit.isSuccess(yield* Effect.exit(guestShares.attachment(otherGuest.token, othersFile))),+ );++ // The owner sends a message with an image of their own.+ const { attachmentsDir } = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const ownerImage = {+ type: "image" as const,+ id: ChatAttachmentId.make(createAttachmentId(threadId)!),+ name: "secret.png",+ mimeType: "image/png",+ sizeBytes: PNG.length,+ };+ yield* fileSystem.writeFile(+ resolveAttachmentPath({ attachmentsDir, attachment: ownerImage })!,+ PNG,+ );+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-image"),+ threadId,+ messageId: MessageId.make("message:owner-image"),+ text: "My screen",+ attachments: [ownerImage],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });++ // The guest sees the thread as the owner does, files included.+ assert.equal(+ (yield* guestShares.attachment(session, ownerImage.id)).attachment.id,+ ownerImage.id,+ );+ for (const id of [othersFile, "pending-missing"]) {+ const error = yield* Effect.flip(guestShares.attachment(session, id));+ assert.equal(error.reason, "unavailable");+ }+ // Nor with the other share's id on this page.+ assert.equal(+ (yield* Effect.flip(+ guestShares.submit(session, { shareId: otherGuest.shareId, text: "x" }, []),+ )).reason,+ "stale_page",+ );+ assert.isDefined(shareId);+ }).pipe(Effect.scoped, Effect.provide(layerTest)),+);diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.tsnew file mode 100644index 00000000000..99d1ff3b56b--- /dev/null+++ b/apps/server/src/guest/GuestShareService.ts@@ -0,0 +1,638 @@+import {+ type ChatAttachment,+ ChatAttachmentId,+ CommandId,+ GUEST_SHARE_TTL_MS,+ GuestMessageId,+ GuestShareCreateError,+ type GuestShareCreateInput,+ type GuestShareCreateResult,+ GuestShareId,+ type GuestRedeemRequest,+ type GuestStreamEvent,+ type GuestSubmitRequest,+ type OrchestrationV2AppThread,+ type OrchestrationV2CommandOutputFrame,+ type OrchestrationV2DomainEvent,+ type OrchestrationV2GetTurnItemResult,+ ThreadId,+ TurnItemId,+} from "@t3tools/contracts";+import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";+import * as Context from "effect/Context";+import * as Crypto from "effect/Crypto";+import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Schedule from "effect/Schedule";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";++import {+ base64UrlDecodeUtf8,+ base64UrlEncode,+ signPayload,+ timingSafeEqualBase64Url,+} from "../auth/utils.ts";+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";+import {+ attachmentFileExtension,+ createAttachmentId,+ resolveAttachmentPath,+ resolveAttachmentPathById,+ threadHtmlRenderAttachmentIds,+} from "../attachmentStore.ts";+import * as ServerConfig from "../config.ts";+import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";+import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";+import { GUEST_FAILURE } from "../orchestration-v2/GuestShareDecider.ts";+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";+import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoalescer.ts";+import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts";+import {+ projectDomainEventForWire,+ projectTurnItemForDetail,+} from "../orchestration-v2/WireProjection.ts";+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";+import * as ServerSettings from "../serverSettings.ts";+import { guestShareView, guestThreadModel } from "./guestView.ts";+import {+ classifyGuestUploads,+ GUEST_UPLOAD_HEADER_BYTES,+ type GuestUpload,+} from "./guestAttachments.ts";++const SIGNING_SECRET_NAME = "guest-share-signing-key";+const SHARE_ID_BYTES = 16;+const INVITE_SIGNATURE_BYTES = 16;+const SNAPSHOT_ROW_LIMIT = 600;+const SNAPSHOT_USER_TURN_LIMIT = 20;+// How soon an open read notices that its link stopped working, such as Connect no longer serving+// the host. Closing or replacing the link ends the main stream at once.+const ACCESS_RECHECK_INTERVAL = Duration.seconds(30);++const GUEST_ACCESS_MESSAGES = {+ ...GUEST_FAILURE,+ invalid: "This guest link is not valid.",+ stale_page: "This page is for an older guest link. Reload it to continue.",+ unavailable: "This item is not available.",+ rejected: "The owner's server rejected this request.",+ empty: "Write a message or attach a file.",+ too_many_files: "Attach up to 4 files to a message.",+ too_large: "Attached files can total up to 10 MB per message.",+ unsupported_file: "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP.",+ files_busy: GUEST_FAILURE.filesBusy,+} as const;++/** What a guest is told. The message comes from `reason`, never from a cause. */+export class GuestShareAccessError extends Schema.TaggedError<GuestShareAccessError>()(+ "GuestShareAccessError",+ {+ reason: Schema.Literals([+ "invalid",+ "inactive",+ "used",+ "busy",+ "stale_page",+ "unavailable",+ "rejected",+ "empty",+ "too_many_files",+ "too_large",+ "unsupported_file",+ "files_busy",+ ]),+ },+) {+ override get message(): string {+ return GUEST_ACCESS_MESSAGES[this.reason];+ }+}++const guestFailureReason = (cause: unknown): GuestShareAccessError["reason"] =>+ cause === GUEST_FAILURE.inactive+ ? "inactive"+ : cause === GUEST_FAILURE.used+ ? "used"+ : cause === GUEST_FAILURE.busy+ ? "busy"+ : cause === GUEST_FAILURE.filesBusy+ ? "files_busy"+ : "rejected";++const SessionClaims = Schema.Struct({+ kind: Schema.Literal("session"),+ threadId: ThreadId,+ shareId: GuestShareId,+});+type SessionClaims = typeof SessionClaims.Type;+const decodeSessionClaims = Schema.decodeUnknownOption(Schema.fromJsonString(SessionClaims));++/** A truncated HMAC keeps invite links short. 128 bits is still far beyond guessing range. */+const inviteSignature = (shareId: string, key: Uint8Array) =>+ base64UrlEncode(+ Buffer.from(signPayload(`guest-invite:${shareId}`, key), "base64url").subarray(+ 0,+ INVITE_SIGNATURE_BYTES,+ ),+ );++const inactive = new GuestShareAccessError({ reason: "inactive" });++export class GuestShareService extends Context.Service<+ GuestShareService,+ {+ readonly create: (+ input: GuestShareCreateInput,+ ) => Effect.Effect<GuestShareCreateResult, GuestShareCreateError>;+ /** Spends an invite and returns the session token for the guest's cookie. */+ readonly redeem: (+ request: GuestRedeemRequest,+ ) => Effect.Effect<+ { readonly token: string; readonly shareId: GuestShareId },+ GuestShareAccessError+ >;+ /** Succeeds while the session can still open its share. */+ readonly check: (session: string) => Effect.Effect<void, GuestShareAccessError>;+ /** Stores the guest's files as the thread's attachments and records the message with them. */+ readonly submit: (+ session: string,+ request: GuestSubmitRequest,+ uploads: ReadonlyArray<GuestUpload>,+ ) => Effect.Effect<void, GuestShareAccessError>;+ readonly stream: (+ session: string,+ ) => Effect.Effect<Stream.Stream<GuestStreamEvent>, GuestShareAccessError>;+ /** The file of an HTML render in the shared thread, and its title. */+ readonly render: (+ session: string,+ itemId: string,+ ) => Effect.Effect<{ readonly path: string; readonly title: string }, GuestShareAccessError>;+ /** One item of the shared thread, as the owner's expanded row loads it. */+ readonly item: (+ session: string,+ itemId: string,+ ) => Effect.Effect<OrchestrationV2GetTurnItemResult, GuestShareAccessError>;+ /** A command's output frames, as the owner's expanded row gets them, until the link ends. */+ readonly commandOutput: (+ session: string,+ itemId: string,+ ) => Effect.Effect<Stream.Stream<OrchestrationV2CommandOutputFrame>, GuestShareAccessError>;+ /** A file in the shared thread or one of the share's messages, never a dismissed one's. */+ readonly attachment: (+ session: string,+ attachmentId: string,+ ) => Effect.Effect<+ { readonly path: string; readonly attachment: ChatAttachment },+ GuestShareAccessError+ >;+ }+>()("t3/guest/GuestShareService") {}++/** The thread record an event carries, for the share and the view. */+const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => {+ switch (event.type) {+ case "thread.guest-share-updated":+ case "thread.metadata-updated":+ case "thread.model-selection-updated":+ case "thread.provider-switched":+ return event.payload;+ default:+ return null;+ }+};++const make = Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const commandOutputs = yield* CommandOutputHub.CommandOutputHub;+ const providerRegistry = yield* ProviderRegistry.ProviderRegistry;+ const serverSettings = yield* ServerSettings.ServerSettingsService;+ const managedEndpoint = yield* CloudManagedEndpointRuntime;+ const { attachmentsDir } = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const crypto = yield* Crypto.Crypto;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;+ const signingKey = yield* Effect.cached(+ secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),+ );++ // Tokens are derived from the share id, so nothing secret is stored and replacing or closing+ // the share in the thread projection revokes every token for it. An invite is+ // `<shareId>.<signature>` and the thread is looked up by share id; a session token carries+ // signed claims.+ const signInvite = (shareId: GuestShareId) =>+ Effect.map(signingKey, (key) => `${shareId}.${inviteSignature(shareId, key)}`);+ const signSession = (claims: SessionClaims) =>+ Effect.map(signingKey, (key) => {+ const payload = base64UrlEncode(JSON.stringify(claims));+ return `${payload}.${signPayload(payload, key)}`;+ });+ const splitToken = (token: string) => {+ const [payload, signature, extra] = token.split(".");+ return payload && signature && extra === undefined ? { payload, signature } : null;+ };+ const verifyInvite = Effect.fn("GuestShareService.verifyInvite")(function* (token: string) {+ const parts = splitToken(token);+ if (parts === null) return Option.none<SessionClaims>();+ const key = yield* signingKey;+ if (!timingSafeEqualBase64Url(parts.signature, inviteSignature(parts.payload, key))) {+ return Option.none<SessionClaims>();+ }+ const shareId = GuestShareId.make(parts.payload);+ const threadId = yield* orchestrator+ .findGuestShareThreadId(shareId)+ .pipe(Effect.mapError(() => inactive));+ return threadId === null+ ? Option.none<SessionClaims>()+ : Option.some<SessionClaims>({ kind: "session", threadId, shareId });+ });+ const verifySession = (token: string) =>+ Effect.map(signingKey, (key) => {+ const parts = splitToken(token);+ if (parts === null) return Option.none<SessionClaims>();+ if (!timingSafeEqualBase64Url(parts.signature, signPayload(parts.payload, key))) {+ return Option.none<SessionClaims>();+ }+ return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));+ });++ const connectHostname = managedEndpoint.inspectConnector.pipe(+ Effect.map((facts) => facts?.hostname ?? null),+ );+ // A beta: while it is off, no link opens and every guest request is refused.+ const sharingEnabled = serverSettings.getSettings.pipe(+ Effect.map((settings) => settings.guestSharingEnabled),+ Effect.orElseSucceed(() => false),+ );++ const dispatchGuestCommand = (+ command: Parameters<Orchestrator.OrchestratorV2["Service"]["dispatch"]>[0],+ ) =>+ orchestrator.dispatch(command).pipe(+ Effect.mapError(+ (error) =>+ new GuestShareAccessError({+ reason: guestFailureReason("cause" in error ? error.cause : undefined),+ }),+ ),+ );++ const commandId = (label: string) =>+ crypto.randomUUIDv4().pipe(+ Effect.map((uuid) => CommandId.make(`server:guest-share:${label}:${uuid}`)),+ Effect.orDie,+ );++ /** Checks a token against the live share: same id, not expired, and Connect still serving it. */+ const authorize = Effect.fn("GuestShareService.authorize")(function* (+ token: string,+ kind: "invite" | "session",+ ) {+ const claims = yield* kind === "invite" ? verifyInvite(token) : verifySession(token);+ if (Option.isNone(claims)) {+ return yield* new GuestShareAccessError({ reason: "invalid" });+ }+ const { thread } = yield* orchestrator+ .getThreadRecords(claims.value.threadId, [])+ .pipe(Effect.mapError(() => inactive));+ const share = thread.guestShare;+ const now = yield* DateTime.now;+ if (+ !(yield* sharingEnabled) ||+ !share ||+ share.id !== claims.value.shareId ||+ thread.archivedAt !== null ||+ thread.deletedAt !== null ||+ DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) ||+ (kind === "session" && share.guestName === null) ||+ (yield* connectHostname) !== share.host+ ) {+ return yield* inactive;+ }+ return { thread, share };+ });++ const create = Effect.fn("GuestShareService.create")(function* (input: GuestShareCreateInput) {+ if (!(yield* sharingEnabled)) {+ return yield* new GuestShareCreateError({ reason: "disabled" });+ }+ const host = yield* connectHostname;+ if (host === null) {+ return yield* new GuestShareCreateError({ reason: "connect_unavailable" });+ }+ const shareId = GuestShareId.make(+ base64UrlEncode(yield* crypto.randomBytes(SHARE_ID_BYTES).pipe(Effect.orDie)),+ );+ const now = yield* DateTime.now;+ const expiresAt = DateTime.formatIso(DateTime.add(now, { milliseconds: GUEST_SHARE_TTL_MS }));+ yield* orchestrator+ .dispatch({+ type: "thread.guest-share.open",+ commandId: yield* commandId("open"),+ threadId: input.threadId,+ shareId,+ host,+ expiresAt,+ })+ .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "thread_unavailable" })));+ const { thread } = yield* orchestrator+ .getThreadRecords(input.threadId, [])+ .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "read_failed" })));+ if (!thread.guestShare || thread.guestShare.id !== shareId) {+ return yield* new GuestShareCreateError({ reason: "changed" });+ }+ const credential = yield* signInvite(shareId);+ return { url: `https://${host}/guest#${credential}`, share: thread.guestShare };+ });++ const redeem = Effect.fn("GuestShareService.redeem")(function* (request: GuestRedeemRequest) {+ const { thread, share } = yield* authorize(request.credential, "invite");+ yield* dispatchGuestCommand({+ type: "thread.guest-share.redeem",+ commandId: yield* commandId("redeem"),+ threadId: thread.id,+ shareId: share.id,+ guestName: request.name,+ });+ const token = yield* signSession({ kind: "session", threadId: thread.id, shareId: share.id });+ return { token, shareId: share.id };+ });++ const check = Effect.fn("GuestShareService.check")(function* (session: string) {+ yield* authorize(session, "session");+ });++ const uploadFailed = new GuestShareAccessError({ reason: "rejected" });+ const removeStored = (attachments: ReadonlyArray<ChatAttachment>) =>+ Effect.forEach(+ attachments,+ (attachment) => {+ const path = resolveAttachmentPath({ attachmentsDir, attachment });+ return path === null+ ? Effect.void+ : fileSystem.remove(path, { force: true }).pipe(Effect.ignore);+ },+ { discard: true },+ );++ /**+ * Checks the files and stores them as the thread's attachments, so a message can wait longer+ * than the day the pending-upload sweep allows. Send uses them as they are; dismissing the+ * message or ending the share deletes them.+ */+ const storeUploads = Effect.fn("GuestShareService.storeUploads")(function* (+ threadId: ThreadId,+ uploads: ReadonlyArray<GuestUpload>,+ ) {+ const inspected = yield* Effect.forEach(uploads, (upload) =>+ Effect.gen(function* () {+ const info = yield* fileSystem.stat(upload.path);+ const file = yield* fileSystem.open(upload.path, { flag: "r" });+ const header = Option.getOrElse(+ yield* file.readAlloc(GUEST_UPLOAD_HEADER_BYTES),+ () => new Uint8Array(),+ );+ return { ...upload, sizeBytes: Number(info.size), header };+ }).pipe(+ Effect.scoped,+ Effect.mapError(() => uploadFailed),+ ),+ );+ const classified = classifyGuestUploads(inspected);+ if (!classified.ok) return yield* new GuestShareAccessError({ reason: classified.reason });+ const stored: Array<ChatAttachment> = [];+ yield* Effect.forEach(+ classified.attachments,+ (draft, index) =>+ Effect.gen(function* () {+ const id = createAttachmentId(+ threadId,+ draft.type === "file" ? attachmentFileExtension(draft.name) : undefined,+ );+ if (id === null) return yield* uploadFailed;+ const attachment: ChatAttachment = { ...draft, id: ChatAttachmentId.make(id) };+ const path = resolveAttachmentPath({ attachmentsDir, attachment });+ if (path === null) return yield* uploadFailed;+ yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });+ yield* fileSystem.copyFile(uploads[index]!.path, path);+ stored.push(attachment);+ }).pipe(Effect.mapError(() => uploadFailed)),+ { discard: true },+ ).pipe(Effect.onError(() => removeStored(stored)));+ return stored;+ });++ const submit = Effect.fn("GuestShareService.submit")(function* (+ session: string,+ request: GuestSubmitRequest,+ uploads: ReadonlyArray<GuestUpload>,+ ) {+ const { thread, share } = yield* authorize(session, "session");+ if (request.shareId !== share.id) {+ return yield* new GuestShareAccessError({ reason: "stale_page" });+ }+ if (request.text === "" && uploads.length === 0) {+ return yield* new GuestShareAccessError({ reason: "empty" });+ }+ const attachments = yield* storeUploads(thread.id, uploads);+ yield* dispatchGuestCommand({+ type: "thread.guest-message.submit",+ commandId: yield* commandId("submit"),+ threadId: thread.id,+ shareId: share.id,+ guestMessageId: GuestMessageId.make(yield* crypto.randomUUIDv4().pipe(Effect.orDie)),+ text: request.text,+ ...(attachments.length === 0 ? {} : { attachments }),+ }).pipe(Effect.onError(() => removeStored(attachments)));+ });++ /** Completes once the session no longer opens its share, so open reads end with it. */+ const untilRevoked = (session: string) =>+ authorize(session, "session").pipe(+ Effect.repeat(Schedule.spaced(ACCESS_RECHECK_INTERVAL)),+ Effect.ignore,+ );++ /**+ * The thread as the owner's thread subscription sends it: a bounded snapshot, then the same+ * wire events, batched the same way. Only the share's own state is added.+ */+ const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {+ const { thread, share } = yield* authorize(session, "session");+ const snapshot = yield* orchestrator+ .getThreadSnapshotWindow(thread.id, {+ rowLimit: SNAPSHOT_ROW_LIMIT,+ userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,+ })+ .pipe(Effect.mapError(() => inactive));+ // The share can end between authorize and this read; the live tail starts after it.+ if (+ snapshot.projection.thread.guestShare?.id !== share.id ||+ snapshot.projection.thread.archivedAt !== null ||+ snapshot.projection.thread.deletedAt !== null+ ) {+ return yield* inactive;+ }+ // Read once; a provider configured mid-share shows after the guest reconnects.+ const providers = yield* providerRegistry.getProviders;+ const viewOf = (current: OrchestrationV2AppThread) =>+ guestShareView(current, guestThreadModel(current.modelSelection, providers));+ const initialView = viewOf(snapshot.projection.thread);+ if (initialView === null) return yield* inactive;++ const ended: GuestStreamEvent = { type: "ended" };+ const endsShare = (event: OrchestrationV2DomainEvent) => {+ if (event.type === "thread.archived" || event.type === "thread.deleted") return true;+ const updated = threadOf(event);+ return updated !== null && updated.guestShare?.id !== share.id;+ };+ const live = orchestrator+ .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })+ .pipe(+ Stream.map((stored) => ({+ kind: "event" as const,+ sequence: stored.sequence,+ event: projectDomainEventForWire(stored.event),+ })),+ // Ending the source here flushes what the coalescer holds, so `ended` is not held back.+ Stream.takeUntil((item) => endsShare(item.event)),+ coalesceThreadLiveStream,+ Stream.map((item): ReadonlyArray<GuestStreamEvent> => {+ if (item.kind !== "event") return [];+ if (endsShare(item.event)) return [ended];+ const updated = threadOf(item.event);+ const view = updated === null ? null : viewOf(updated);+ return view === null+ ? [{ type: "thread", item }]+ : [+ { type: "thread", item },+ { type: "view", view },+ ];+ }),+ Stream.flattenIterable,+ // A failed read closes the response without `ended`: the browser reconnects, and+ // `authorize` decides whether the link still works.+ Stream.catchCause(() => Stream.empty),+ );+ const untilExpiry = Effect.sleep(+ Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),+ );+ const opening: ReadonlyArray<GuestStreamEvent> = [+ { type: "view", view: initialView },+ {+ type: "thread",+ item: buildBoundedThreadStreamSnapshot({+ snapshotSequence: snapshot.snapshotSequence,+ projection: snapshot.projection,+ }),+ },+ ];+ return Stream.fromIterable(opening).pipe(+ Stream.concat(+ Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {+ haltStrategy: "either",+ }),+ ),+ Stream.takeUntil((event) => event.type === "ended"),+ // Unlinking T3 Connect closes it quietly, so a tunnel that comes back on the same host+ // keeps the guest in. Turning the beta off closes it the same way. Closing and expiry end+ // it above, with `ended`.+ Stream.interruptWhen(+ Effect.all([connectHostname, sharingEnabled]).pipe(+ Effect.repeat({+ schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),+ until: ([host, enabled]) => host !== share.host || !enabled,+ }),+ ),+ ),+ );+ });++ const unavailable = new GuestShareAccessError({ reason: "unavailable" });++ /** An item of the shared thread, read after the session check. */+ const threadItem = Effect.fn("GuestShareService.threadItem")(function* (+ session: string,+ itemId: string,+ ) {+ const { thread } = yield* authorize(session, "session");+ const item = yield* orchestrator+ .getTurnItem({ threadId: thread.id, itemId: TurnItemId.make(itemId) })+ .pipe(Effect.mapError(() => unavailable));+ return item === null ? yield* unavailable : { thread, item };+ });++ const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {+ const { thread, item } = yield* threadItem(session, itemId);+ if (item.type !== "dynamic_tool") return yield* unavailable;+ const reference = htmlRenderFromToolItem(item);+ const [attachmentId] = threadHtmlRenderAttachmentIds(thread.id, [item]);+ const path =+ attachmentId === undefined+ ? null+ : resolveAttachmentPathById({ attachmentsDir, attachmentId });+ if (reference === undefined || path === null) return yield* unavailable;+ return { path, title: reference.title };+ });++ const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) {+ const { item } = yield* threadItem(session, itemId);+ return { item: projectTurnItemForDetail(item) };+ });++ const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (+ session: string,+ itemId: string,+ ) {+ const { thread, item } = yield* threadItem(session, itemId);+ if (item.type !== "command_execution") return yield* unavailable;+ return commandOutputs.subscribe({ threadId: thread.id, itemId: item.id }).pipe(+ // A lost hub stream ends the output; the row reloads it when reopened.+ Stream.catchCause(() => Stream.empty),+ Stream.interruptWhen(untilRevoked(session)),+ );+ });++ const attachment = Effect.fn("GuestShareService.attachment")(function* (+ session: string,+ attachmentId: string,+ ) {+ const { thread, share } = yield* authorize(session, "session");+ // A dismissed message's files are deleted with it.+ const fromShare = share.messages+ .flatMap((message) => (message.status === "dismissed" ? [] : (message.attachments ?? [])))+ .find((candidate) => candidate.id === attachmentId);+ const found =+ fromShare ??+ (yield* orchestrator.getThreadRecords(thread.id, ["messages"]).pipe(+ Effect.map(({ messages }) =>+ messages+ .flatMap((message) => message.attachments ?? [])+ .find((candidate) => candidate.id === attachmentId),+ ),+ Effect.mapError(() => unavailable),+ ));+ const path =+ found === undefined ? null : resolveAttachmentPath({ attachmentsDir, attachment: found });+ if (found === undefined || path === null) return yield* unavailable;+ const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));+ return exists ? { path, attachment: found } : yield* unavailable;+ });++ return GuestShareService.of({+ create,+ redeem,+ check,+ submit,+ stream,+ render,+ item,+ commandOutput,+ attachment,+ });+});++export const layer = Layer.effect(GuestShareService, make);diff --git a/apps/server/src/guest/guestAttachments.ts b/apps/server/src/guest/guestAttachments.tsnew file mode 100644index 00000000000..ab7bd1a78b8--- /dev/null+++ b/apps/server/src/guest/guestAttachments.ts@@ -0,0 +1,103 @@+import {+ GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,+ GUEST_MESSAGE_MAX_ATTACHMENTS,+ isProviderSendTurnSupportedImageMimeType,+} from "@t3tools/contracts";++/** A file from a guest's message request, saved by the multipart parser to a temporary path. */+export interface GuestUpload {+ readonly name: string;+ readonly contentType: string;+ readonly path: string;+}++/** What the server learned about an upload before deciding what it may become. */+export interface InspectedGuestUpload {+ readonly name: string;+ readonly contentType: string;+ readonly sizeBytes: number;+ /** The first bytes of the file. */+ readonly header: Uint8Array;+}++export type GuestUploadRejection = "too_many_files" | "too_large" | "unsupported_file";++/** An attachment before it is stored and gets its id. */+export interface GuestAttachmentDraft {+ readonly type: "image" | "file";+ readonly name: string;+ readonly mimeType: string;+ readonly sizeBytes: number;+}++/** Bytes of the file the signature check reads. */+export const GUEST_UPLOAD_HEADER_BYTES = 12;++const startsWith = (header: Uint8Array, bytes: ReadonlyArray<number>, offset = 0) =>+ bytes.every((byte, index) => header[offset + index] === byte);+const ascii = (text: string) => Array.from(text, (character) => character.charCodeAt(0));++/** An image must be what its type says, so a renamed HTML page never travels as one. */+const IMAGE_SIGNATURES: Readonly<Record<string, (header: Uint8Array) => boolean>> = {+ "image/png": (header) => startsWith(header, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ "image/jpeg": (header) => startsWith(header, [0xff, 0xd8, 0xff]),+ "image/gif": (header) => startsWith(header, ascii("GIF8")),+ "image/webp": (header) =>+ startsWith(header, ascii("RIFF")) && startsWith(header, ascii("WEBP"), 8),+};++/**+ * Control characters and separators would break the name in headers and on disk, and direction+ * overrides would let `invoice\u202Efdp.exe` show as a PDF.+ */+const safeName = (name: string, fallback: string) =>+ name+ .replace(/[\p{Cc}\\/\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu, "_")+ .trim()+ .slice(0, 255) || fallback;++/**+ * The attachments a guest's files become, as the owner's composer takes them: supported images as+ * images, anything else that is not an image as a file. Other image types (SVG, HEIC) and empty+ * files are refused, as are too many files or too many bytes in one message.+ */+export function classifyGuestUploads(+ uploads: ReadonlyArray<InspectedGuestUpload>,+):+ | { readonly ok: true; readonly attachments: ReadonlyArray<GuestAttachmentDraft> }+ | { readonly ok: false; readonly reason: GuestUploadRejection } {+ if (uploads.length > GUEST_MESSAGE_MAX_ATTACHMENTS)+ return { ok: false, reason: "too_many_files" };+ const total = uploads.reduce((sum, upload) => sum + upload.sizeBytes, 0);+ if (total > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) return { ok: false, reason: "too_large" };+ const attachments: Array<GuestAttachmentDraft> = [];+ for (const upload of uploads) {+ const mimeType =+ upload.contentType.split(";", 1)[0]!.trim().toLowerCase() || "application/octet-stream";+ if (upload.sizeBytes === 0) return { ok: false, reason: "unsupported_file" };+ if (mimeType.startsWith("image/")) {+ const signatureMatches = IMAGE_SIGNATURES[mimeType];+ if (+ !isProviderSendTurnSupportedImageMimeType(mimeType) ||+ signatureMatches === undefined ||+ !signatureMatches(upload.header)+ ) {+ return { ok: false, reason: "unsupported_file" };+ }+ attachments.push({+ type: "image",+ name: safeName(upload.name, "image"),+ mimeType,+ sizeBytes: upload.sizeBytes,+ });+ continue;+ }+ attachments.push({+ type: "file",+ name: safeName(upload.name, "file"),+ mimeType: mimeType.length <= 100 ? mimeType : "application/octet-stream",+ sizeBytes: upload.sizeBytes,+ });+ }+ return { ok: true, attachments };+}diff --git a/apps/server/src/guest/guestView.test.ts b/apps/server/src/guest/guestView.test.tsnew file mode 100644index 00000000000..17cdf8e64e7--- /dev/null+++ b/apps/server/src/guest/guestView.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "@effect/vitest";++import { guestThreadModel } from "./guestView.ts";++describe("guestThreadModel", () => {+ const providers = [+ {+ instanceId: "claude-work",+ driver: "claudeAgent",+ models: [+ {+ slug: "claude-opus",+ name: "Claude Opus",+ shortName: "Opus",+ isCustom: false,+ capabilities: null,+ },+ ],+ },+ ] as unknown as Parameters<typeof guestThreadModel>[1];++ it("names the model as the owner's picker does, or by its id when it is not listed", () => {+ const selection = (instanceId: string, model: string) =>+ ({ instanceId, model }) as Parameters<typeof guestThreadModel>[0];+ expect(guestThreadModel(selection("claude-work", "claude-opus"), providers)).toEqual({+ driver: "claudeAgent",+ name: "Claude Opus",+ shortName: "Opus",+ });+ expect(guestThreadModel(selection("removed", "gpt-5"), providers)).toEqual({+ driver: null,+ name: "gpt-5",+ });+ });+});diff --git a/apps/server/src/guest/guestView.ts b/apps/server/src/guest/guestView.tsnew file mode 100644index 00000000000..ac5af5c0402--- /dev/null+++ b/apps/server/src/guest/guestView.ts@@ -0,0 +1,38 @@+import type {+ GuestShareView,+ GuestThreadModel,+ OrchestrationV2AppThread,+ ServerProvider,+} from "@t3tools/contracts";++/** The thread's model as the owner's composer labels it, from the configured providers. */+export function guestThreadModel(+ selection: OrchestrationV2AppThread["modelSelection"],+ providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver" | "models">>,+): GuestThreadModel {+ const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);+ const model = provider?.models.find((candidate) => candidate.slug === selection.model);+ return {+ driver: provider?.driver ?? null,+ name: model?.name ?? selection.model,+ ...(model?.shortName === undefined ? {} : { shortName: model.shortName }),+ ...(model?.subProvider === undefined ? {} : { subProvider: model.subProvider }),+ };+}++/** The share as its guest sees it, or null before the guest has joined. */+export function guestShareView(+ thread: OrchestrationV2AppThread,+ model: GuestThreadModel,+): GuestShareView | null {+ const share = thread.guestShare;+ if (!share || share.guestName === null) return null;+ return {+ shareId: share.id,+ title: thread.title,+ guestName: share.guestName,+ expiresAt: share.expiresAt,+ messages: share.messages,+ model,+ };+}diff --git a/apps/server/src/guest/http.test.ts b/apps/server/src/guest/http.test.tsnew file mode 100644index 00000000000..e4c2402197b--- /dev/null+++ b/apps/server/src/guest/http.test.ts@@ -0,0 +1,28 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import { HttpServerRequest } from "effect/http";++import { readSubmission } from "./http.ts";++it.effect("keeps a JSON file a guest attaches as a file, not a form field", () =>+ Effect.gen(function* () {+ const form = new FormData();+ form.append("shareId", "share-1");+ form.append("text", "");+ form.append("file", new File(['{"a":1}'], "data.json", { type: "application/json" }));+ const request = HttpServerRequest.fromWeb(+ new Request("http://localhost/api/guest/messages?share=share-1", {+ method: "POST",+ body: form,+ }),+ );+ const submission = yield* readSubmission.pipe(+ Effect.provideService(HttpServerRequest.HttpServerRequest, request),+ );+ assert.deepEqual(+ submission?.uploads.map((upload) => [upload.name, upload.contentType]),+ [["data.json", "application/json"]],+ );+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);diff --git a/apps/server/src/guest/http.ts b/apps/server/src/guest/http.tsnew file mode 100644index 00000000000..dff485de8f8--- /dev/null+++ b/apps/server/src/guest/http.ts@@ -0,0 +1,346 @@+import {+ GUEST_ATTACHMENT_ROUTE,+ GUEST_COMMAND_OUTPUT_ROUTE,+ GUEST_ITEM_ROUTE,+ GUEST_RENDER_ROUTE,+ GUEST_ROUTE_PREFIX,+ GUEST_SHARE_PARAM,+ GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,+ GUEST_MESSAGE_MAX_ATTACHMENTS,+ GUEST_SHARE_TTL_MS,+ GuestRedeemRequest,+ GuestStreamEvent,+ GuestSubmitRequest,+ guestSessionCookieName,+ isProviderSendTurnSupportedImageMimeType,+ OrchestrationV2CommandOutputFrame,+ OrchestrationV2GetTurnItemResult,+} from "@t3tools/contracts";+import * as ByteSize from "effect/ByteSize";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";+import { HttpRouter, HttpServerRequest, HttpServerResponse, Multipart } from "effect/http";+import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";++import { htmlRenderFileName } from "@t3tools/shared/htmlRender";++import { assetFileResponse, downloadContentDisposition } from "../http.ts";+import type { GuestUpload } from "./guestAttachments.ts";+import { GuestShareAccessError, GuestShareService } from "./GuestShareService.ts";++// Cloudflare closes idle streams after about 100 seconds.+const HEARTBEAT_INTERVAL = Duration.seconds(20);+const NO_STORE = { "cache-control": "no-store" };++const decodeRedeem = Schema.decodeUnknownEffect(GuestRedeemRequest);+const decodeSubmit = Schema.decodeUnknownEffect(GuestSubmitRequest);+// The owner's thread types hold DateTime values; the JSON codec writes them as strings.+const encodeStreamEvent = Schema.encodeEffect(+ Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)),+);+const encodeOutputFrame = Schema.encodeEffect(+ Schema.fromJsonString(OrchestrationV2CommandOutputFrame),+);+const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));++const errorResponse = (error: GuestShareAccessError) =>+ HttpServerResponse.json(+ { reason: error.reason, message: error.message },+ {+ status:+ error.reason === "invalid" || error.reason === "inactive" || error.reason === "unavailable"+ ? 403+ : error.reason === "empty" ||+ error.reason === "too_many_files" ||+ error.reason === "too_large" ||+ error.reason === "unsupported_file"+ ? 400+ : 409,+ headers: NO_STORE,+ },+ );++const badRequest = HttpServerResponse.json(+ { reason: "invalid", message: "The request was not valid." },+ { status: 400, headers: NO_STORE },+);++const sessionFor = (request: HttpServerRequest.HttpServerRequest, shareId: string | null) =>+ shareId === null ? "" : (request.cookies[guestSessionCookieName(shareId)] ?? "");++const requestedShareId = (request: HttpServerRequest.HttpServerRequest) =>+ new URLSearchParams(request.url.split("?", 2)[1] ?? "").get(GUEST_SHARE_PARAM);++/** The session for the share the request names in `?share=`. */+const sessionToken = Effect.map(HttpServerRequest.HttpServerRequest, (request) =>+ sessionFor(request, requestedShareId(request)),+);++/** The `?item=` a per-item route names. */+const itemParam = Effect.map(HttpServerRequest.HttpServerRequest, (request) =>+ new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("item"),+);++/** Server-sent events with a heartbeat, never cached or buffered on the way. */+const eventStreamResponse = <A, I>(+ events: Stream.Stream<A>,+ encode: (event: A) => Effect.Effect<string, Schema.SchemaError>,+) => {+ const data = events.pipe(+ Stream.mapEffect((event) =>+ encode(event).pipe(+ Effect.map((json) => [`data: ${json}\n\n`]),+ // The guest misses one update instead of the whole stream.+ Effect.catch(() =>+ Effect.logWarning("Dropped a guest stream event that failed to encode.").pipe(+ Effect.as([]),+ ),+ ),+ ),+ ),+ Stream.flattenIterable,+ );+ const heartbeat = Stream.tick(HEARTBEAT_INTERVAL).pipe(Stream.map(() => ": ping\n\n"));+ return HttpServerResponse.stream(+ data.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }), Stream.encodeText),+ {+ contentType: "text/event-stream",+ // no-transform keeps the compression middleware from buffering the stream.+ headers: { "cache-control": "no-store, no-transform", "x-accel-buffering": "no" },+ },+ );+};++// Guest JSON bodies are a name or one message; anyone who can reach the tunnel can post them.+const JSON_MAX_BODY_BYTES = 64 * 1024;+const readJson = Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ // A declared length over the cap is refused before reading; chunked bodies hit the reader cap.+ if (Number(request.headers["content-length"] ?? "0") > JSON_MAX_BODY_BYTES) {+ return yield* new GuestShareAccessError({ reason: "too_large" });+ }+ return yield* request.json.pipe(+ Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(JSON_MAX_BODY_BYTES)),+ );+});++const redeemRoute = HttpRouter.add(+ "POST",+ `${GUEST_ROUTE_PREFIX}/redeem`,+ Effect.gen(function* () {+ const body = yield* readJson.pipe(Effect.flatMap(decodeRedeem), Effect.option);+ if (body._tag === "None") return yield* badRequest;+ const guestShares = yield* GuestShareService;+ return yield* guestShares.redeem(body.value).pipe(+ Effect.flatMap(({ token, shareId }) =>+ HttpServerResponse.empty({ status: 204, headers: NO_STORE }).pipe(+ HttpServerResponse.setCookie(guestSessionCookieName(shareId), token, {+ httpOnly: true,+ secure: true,+ sameSite: "strict",+ path: GUEST_ROUTE_PREFIX,+ maxAge: Duration.millis(GUEST_SHARE_TTL_MS),+ }),+ ),+ ),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ );+ }),+);++// The parser stops a request with too many parts or bytes before it reaches the disk; the+// service checks the exact limits and types.+const UPLOAD_LIMITS = Multipart.limitsServices({+ maxParts: GUEST_MESSAGE_MAX_ATTACHMENTS + 4,+ maxFileSize: GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,+ maxTotalSize: GUEST_MESSAGE_MAX_ATTACHMENT_BYTES + 64 * 1024,+ // By default a JSON part is read as a field, which would drop a guest's `.json` file.+ fieldMimeTypes: [],+});++/** A message as JSON (text only), or as multipart form data with `file` parts. */+export const readSubmission = Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ if (!request.headers["content-type"]?.startsWith("multipart/form-data")) {+ const body = yield* readJson.pipe(Effect.flatMap(decodeSubmit), Effect.option);+ return body._tag === "None" ? null : { fields: body.value, uploads: [] };+ }+ const parts = yield* request.multipart.pipe(+ Effect.provideContext(UPLOAD_LIMITS),+ Effect.mapError(+ (error) =>+ new GuestShareAccessError({+ reason:+ error.reason._tag === "TooManyParts"+ ? "too_many_files"+ : error.reason._tag === "Parse"+ ? "rejected"+ : "too_large",+ }),+ ),+ );+ const fields = yield* decodeSubmit({ shareId: parts.shareId, text: parts.text ?? "" }).pipe(+ Effect.option,+ );+ if (fields._tag === "None") return null;+ const files = parts.file;+ const uploads: ReadonlyArray<GuestUpload> = Array.isArray(files)+ ? files.filter(Multipart.isPersistedFile).map(({ name, contentType, path }) => ({+ name,+ contentType,+ path,+ }))+ : [];+ return { fields: fields.value, uploads };+});++const submitRoute = HttpRouter.add(+ "POST",+ `${GUEST_ROUTE_PREFIX}/messages`,+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const guestShares = yield* GuestShareService;+ // The session is checked before the body is read, so only a guest can make the server parse+ // and store up to 10 MB.+ const shareId = requestedShareId(request);+ const session = sessionFor(request, shareId);+ yield* guestShares.check(session);+ const submission = yield* readSubmission;+ if (submission === null || submission.fields.shareId !== shareId) return yield* badRequest;+ yield* guestShares.submit(session, submission.fields, submission.uploads);+ return HttpServerResponse.empty({ status: 204, headers: NO_STORE });+ }).pipe(+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ // The parser's temporary files are removed once the response is ready.+ Effect.scoped,+ ),+);++const streamRoute = HttpRouter.add(+ "GET",+ `${GUEST_ROUTE_PREFIX}/stream`,+ Effect.gen(function* () {+ const guestShares = yield* GuestShareService;+ return yield* guestShares.stream(yield* sessionToken).pipe(+ Effect.map((events) => eventStreamResponse(events, encodeStreamEvent)),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ );+ }),+);++// Lets a returning guest skip the name form when this browser already joined the share.+const sessionRoute = HttpRouter.add(+ "GET",+ `${GUEST_ROUTE_PREFIX}/session`,+ Effect.gen(function* () {+ const guestShares = yield* GuestShareService;+ return yield* guestShares+ .check(yield* sessionToken)+ .pipe(+ Effect.as(HttpServerResponse.empty({ status: 204, headers: NO_STORE })),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ );+ }),+);++// The response carries the asset route's sandbox CSP: the page gets an opaque origin, so its+// scripts cannot send the guest cookie or call these routes as the guest.+const renderRoute = HttpRouter.add(+ "GET",+ GUEST_RENDER_ROUTE,+ Effect.gen(function* () {+ const itemId = yield* itemParam;+ if (!itemId) return yield* badRequest;+ const guestShares = yield* GuestShareService;+ return yield* guestShares.render(yield* sessionToken, itemId).pipe(+ Effect.flatMap(({ path, title }) =>+ assetFileResponse({ path, mimeType: "text/html", fileName: htmlRenderFileName(title) }),+ ),+ // Each load re-checks the share, so a closed, replaced, or expired link stops it at once.+ Effect.map((response) => HttpServerResponse.setHeaders(response, NO_STORE)),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ );+ }),+);++const itemRoute = HttpRouter.add(+ "GET",+ GUEST_ITEM_ROUTE,+ Effect.gen(function* () {+ const itemId = yield* itemParam;+ if (!itemId) return yield* badRequest;+ const guestShares = yield* GuestShareService;+ return yield* guestShares.item(yield* sessionToken, itemId).pipe(+ Effect.flatMap((result) =>+ encodeItem(result).pipe(+ Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })),+ ),+ ),+ Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ );+ }),+);++// Ends when the command settles; the page closes its EventSource on that last frame, so the+// browser does not reconnect.+const commandOutputRoute = HttpRouter.add(+ "GET",+ GUEST_COMMAND_OUTPUT_ROUTE,+ Effect.gen(function* () {+ const itemId = yield* itemParam;+ if (!itemId) return yield* badRequest;+ const guestShares = yield* GuestShareService;+ return yield* guestShares.commandOutput(yield* sessionToken, itemId).pipe(+ Effect.map((frames) => eventStreamResponse(frames, encodeOutputFrame)),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ );+ }),+);++// Images of the four checked types load inline; anything else downloads as bytes, so a guest's+// HTML or SVG never renders as a page on this origin.+const attachmentRoute = HttpRouter.add(+ "GET",+ GUEST_ATTACHMENT_ROUTE,+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const attachmentId = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("id");+ if (!attachmentId) return yield* badRequest;+ const guestShares = yield* GuestShareService;+ return yield* guestShares.attachment(yield* sessionToken, attachmentId).pipe(+ Effect.flatMap(({ path, attachment }) =>+ HttpServerResponse.file(path, {+ headers: {+ ...NO_STORE,+ "x-content-type-options": "nosniff",+ "content-security-policy": "default-src 'none'; sandbox",+ ...(attachment.type === "image" &&+ isProviderSendTurnSupportedImageMimeType(attachment.mimeType)+ ? { "content-type": attachment.mimeType }+ : {+ "content-type": "application/octet-stream",+ "content-disposition": downloadContentDisposition(attachment.name),+ }),+ },+ }),+ ),+ Effect.catchTags({ GuestShareAccessError: errorResponse }),+ Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500, headers: NO_STORE })),+ );+ }),+);++export const layer = Layer.mergeAll(+ redeemRoute,+ sessionRoute,+ submitRoute,+ streamRoute,+ renderRoute,+ itemRoute,+ commandOutputRoute,+ attachmentRoute,+);diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 769fc2d1feb..41112ea8253 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -97,6 +97,7 @@ const RPC_AGGREGATES = {[WS_METHODS.scheduledTasksListWebhookDeliveries]: "scheduledTasks",[WS_METHODS.scheduledTasksGetWebhookDelivery]: "scheduledTasks",[WS_METHODS.secretsAnswerRequest]: "secrets",+ [WS_METHODS.guestShareCreate]: "guest-share",[WS_METHODS.cloudGetRelayClientStatus]: "cloud",[WS_METHODS.cloudInstallRelayClient]: "cloud",[WS_METHODS.pullRequestsList]: "pull-requests",diff --git a/apps/server/src/orchestration-v2/GuestShare.test.ts b/apps/server/src/orchestration-v2/GuestShare.test.tsnew file mode 100644index 00000000000..d789b206016--- /dev/null+++ b/apps/server/src/orchestration-v2/GuestShare.test.ts@@ -0,0 +1,343 @@+import { assert, it } from "@effect/vitest";+import {+ CommandId,+ GuestMessageId,+ GuestShareId,+ MessageId,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ThreadId,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";+import * as Layer from "effect/Layer";+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";++import * as SqlitePersistence from "../persistence/Sqlite.ts";+import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";+import * as EffectOutbox from "./EffectOutbox.ts";+import * as Orchestrator from "./Orchestrator.ts";+import * as ProjectionStore from "./ProjectionStore.ts";+import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";+import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";++const instanceId = ProviderInstanceId.make("codex");+const adapter = {+ instanceId,+ driver: ProviderDriverKind.make("codex"),+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),+ openSession: () => Effect.die("No provider process needed for guest shares"),+} as ProviderAdapter.ProviderAdapterV2["Service"];+const layerDatabase = SqlitePersistence.layerMemory;+const layerTest = Layer.mergeAll(+ layerDatabase,+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),+ EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),+ ProviderReplayHarness.layerWithRegistry(+ { name: "guest-share" },+ ProviderAdapterRegistry.layerFromAdapters([adapter]),+ { databaseLayer: layerDatabase, runEffectWorker: false },+ ),+);++const threadId = ThreadId.make("thread:guest-share");+const shareId = GuestShareId.make("share:one");+const guestMessageId = GuestMessageId.make("guest-message:one");++const setup = Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ yield* orchestrator.dispatch({+ type: "thread.create",+ commandId: CommandId.make("create-guest-share"),+ threadId,+ projectId: ProjectId.make("project:guest-share"),+ title: "Review me",+ modelSelection: { instanceId, model: "gpt-5.1-codex" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdBy: "user",+ creationSource: "web",+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-share.open",+ commandId: CommandId.make("open-guest-share"),+ threadId,+ shareId,+ host: "env.t3.test",+ expiresAt: DateTime.formatIso(DateTime.add(yield* DateTime.now, { hours: 24 })),+ });+ return orchestrator;+});++const sendGuestMessage = (orchestrator: Orchestrator.OrchestratorV2["Service"], id: string) =>+ orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make(id),+ threadId,+ messageId: MessageId.make(id),+ guestMessageId,+ text: "ignored: the server sends the guest's own text",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });++it.effect("redeems a guest link once and sends each guest message once, with its turn", () =>+ Effect.gen(function* () {+ const orchestrator = yield* setup;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const redeem = (id: string) =>+ orchestrator.dispatch({+ type: "thread.guest-share.redeem",+ commandId: CommandId.make(id),+ threadId,+ shareId,+ guestName: "Sam",+ });+ yield* redeem("redeem-1");+ assert.isTrue(Exit.isFailure(yield* Effect.exit(redeem("redeem-2"))));++ yield* orchestrator.dispatch({+ type: "thread.guest-message.submit",+ commandId: CommandId.make("submit-1"),+ threadId,+ shareId,+ guestMessageId,+ text: "Why not keep the old cache?",+ });+ assert.equal((yield* projections.getThreadShell(threadId))?.pendingGuestMessageCount, 1);++ yield* sendGuestMessage(orchestrator, "send-1");+ const projection = yield* projections.getThreadProjection(threadId);+ assert.deepEqual(+ projection.thread.guestShare?.messages.map((message) => message.status),+ ["sent"],+ );+ const sent = projection.messages.find((message) => message.id === MessageId.make("send-1"));+ assert.equal(+ sent?.text,+ "Message from guest Sam, sent by the owner:\n\nWhy not keep the old cache?",+ );+ assert.deepEqual(sent?.context?.guest, {+ guestMessageId,+ name: "Sam",+ text: "Why not keep the old cache?",+ shareId,+ });+ assert.lengthOf(projection.runs, 1);+ assert.equal((yield* projections.getThreadShell(threadId))?.pendingGuestMessageCount, 0);++ // A second owner device clicking Send must not start another turn.+ assert.isTrue(Exit.isFailure(yield* Effect.exit(sendGuestMessage(orchestrator, "send-2"))));+ assert.lengthOf((yield* projections.getThreadProjection(threadId)).runs, 1);+ }).pipe(Effect.provide(layerTest)),+);++it.effect("rejects guest messages until the link is redeemed and after archive", () =>+ Effect.gen(function* () {+ const orchestrator = yield* setup;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const submit = orchestrator.dispatch({+ type: "thread.guest-message.submit",+ commandId: CommandId.make("submit-early"),+ threadId,+ shareId,+ guestMessageId,+ text: "Hello",+ });+ assert.isTrue(Exit.isFailure(yield* Effect.exit(submit)));++ yield* orchestrator.dispatch({+ type: "thread.archive",+ commandId: CommandId.make("archive-guest-share"),+ threadId,+ });+ assert.isNull((yield* projections.getThread(threadId)).guestShare ?? null);+ }).pipe(Effect.provide(layerTest)),+);++it.effect("drops guest attribution that a client sends on its own message", () =>+ Effect.gen(function* () {+ const orchestrator = yield* setup;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-message"),+ threadId,+ messageId: MessageId.make("owner-message"),+ text: "Mine",+ context: { version: 1, records: [], guest: { guestMessageId, name: "Sam", text: "Mine" } },+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ const projection = yield* projections.getThreadProjection(threadId);+ const sent = projection.messages.find(+ (message) => message.id === MessageId.make("owner-message"),+ );+ assert.isUndefined(sent?.context?.guest);+ }).pipe(Effect.provide(layerTest)),+);++it.effect("keeps a queued guest message unchanged when the owner tries to edit it", () =>+ Effect.gen(function* () {+ const orchestrator = yield* setup;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-first"),+ threadId,+ messageId: MessageId.make("owner-first"),+ text: "Start",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-share.redeem",+ commandId: CommandId.make("redeem"),+ threadId,+ shareId,+ guestName: "Sam",+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-message.submit",+ commandId: CommandId.make("submit"),+ threadId,+ shareId,+ guestMessageId,+ text: "Why?",+ });+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("send-queued"),+ threadId,+ messageId: MessageId.make("send-queued"),+ guestMessageId,+ text: "",+ attachments: [],+ dispatchMode: { type: "queue_after_active" },+ createdBy: "user",+ creationSource: "web",+ });+ const queued = (yield* projections.getThreadProjection(threadId)).runs.find(+ (run) => run.status === "queued",+ );+ assert.isDefined(queued);++ const edit = orchestrator.dispatch({+ type: "queued-run.edit",+ commandId: CommandId.make("edit"),+ threadId,+ runId: queued.id,+ text: "My own words",+ });+ assert.isTrue(Exit.isFailure(yield* Effect.exit(edit)));+ const message = (yield* projections.getThreadProjection(threadId)).messages.find(+ (candidate) => candidate.id === MessageId.make("send-queued"),+ );+ assert.equal(message?.context?.guest?.text, "Why?");+ }).pipe(Effect.provide(layerTest)),+);++it.effect("shows a guest message as dismissed when the owner cancels its queued send", () =>+ Effect.gen(function* () {+ const orchestrator = yield* setup;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("owner-first"),+ threadId,+ messageId: MessageId.make("owner-first"),+ text: "Start",+ attachments: [],+ dispatchMode: { type: "defer_start" },+ createdBy: "user",+ creationSource: "web",+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-share.redeem",+ commandId: CommandId.make("redeem"),+ threadId,+ shareId,+ guestName: "Sam",+ });+ yield* orchestrator.dispatch({+ type: "thread.guest-message.submit",+ commandId: CommandId.make("submit"),+ threadId,+ shareId,+ guestMessageId,+ text: "Why?",+ });+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("send-queued"),+ threadId,+ messageId: MessageId.make("send-queued"),+ guestMessageId,+ text: "",+ attachments: [],+ dispatchMode: { type: "queue_after_active" },+ createdBy: "user",+ creationSource: "web",+ });+ const queued = (yield* projections.getThreadProjection(threadId)).runs.find(+ (run) => run.status === "queued",+ );+ assert.isDefined(queued);+ yield* orchestrator.dispatch({+ type: "queued-run.cancel",+ commandId: CommandId.make("cancel"),+ threadId,+ runId: queued.id,+ });+ const { thread } = yield* projections.getThreadProjection(threadId);+ assert.equal(+ thread.guestShare?.messages.find((message) => message.id === guestMessageId)?.status,+ "dismissed",+ );+ }).pipe(Effect.provide(layerTest)),+);++it.effect("brings a settled thread back when its guest sends a request", () =>+ Effect.gen(function* () {+ const orchestrator = yield* setup;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ yield* orchestrator.dispatch({+ type: "thread.guest-share.redeem",+ commandId: CommandId.make("redeem"),+ threadId,+ shareId,+ guestName: "Sam",+ });+ yield* orchestrator.dispatch({+ type: "thread.settle",+ commandId: CommandId.make("settle"),+ threadId,+ });+ assert.equal(+ (yield* projections.getThreadProjection(threadId)).thread.settledOverride,+ "settled",+ );+ yield* orchestrator.dispatch({+ type: "thread.guest-message.submit",+ commandId: CommandId.make("submit"),+ threadId,+ shareId,+ guestMessageId,+ text: "Why?",+ });+ const { thread } = yield* projections.getThreadProjection(threadId);+ assert.isNull(thread.settledOverride);+ assert.isNull(thread.settledAt);+ }).pipe(Effect.provide(layerTest)),+);diff --git a/apps/server/src/orchestration-v2/GuestShareDecider.ts b/apps/server/src/orchestration-v2/GuestShareDecider.tsnew file mode 100644index 00000000000..00f9f8ae3b9--- /dev/null+++ b/apps/server/src/orchestration-v2/GuestShareDecider.ts@@ -0,0 +1,255 @@+import {+ GUEST_PENDING_ATTACHMENT_BYTES_LIMIT,+ GUEST_PENDING_MESSAGE_LIMIT,+ GUEST_RESOLVED_MESSAGE_LIMIT,+ type GuestMessageAttribution,+ type GuestMessageId,+ type OrchestrationMessageContext,+ type OrchestrationV2AppThread,+ type OrchestrationV2ServerCommand,+ type ThreadGuestMessage,+ type ThreadGuestShare,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Result from "effect/Result";++export type GuestShareCommand = Extract<+ OrchestrationV2ServerCommand,+ {+ readonly type:+ | "thread.guest-share.open"+ | "thread.guest-share.redeem"+ | "thread.guest-share.close"+ | "thread.guest-message.submit"+ | "thread.guest-message.dismiss";+ }+>;++/** Failures a guest may be told about. Any other dispatch failure reaches them as "rejected". */+export const GUEST_FAILURE = {+ inactive: "This guest link is no longer active.",+ used: "This guest link was already used.",+ busy: "Wait for the owner to answer your earlier messages.",+ filesBusy: "Wait for the owner to answer your earlier messages before you attach more files.",+} as const;++const isExpired = (share: ThreadGuestShare, now: DateTime.Utc) =>+ DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt);++const pendingAttachments = (share: ThreadGuestShare | null) =>+ share?.messages.flatMap((message) =>+ message.status === "pending" ? (message.attachments ?? []) : [],+ ) ?? [];++/**+ * Stored files a share change leaves behind: those of waiting messages that were dismissed or+ * dropped with the share. A sent message keeps its files, which its thread message now holds.+ */+export function releasedGuestAttachmentIds(+ before: ThreadGuestShare | null,+ after: ThreadGuestShare | null,+): ReadonlyArray<string> {+ const kept = new Set(+ after !== null && after.id === before?.id+ ? after.messages.flatMap((message) =>+ message.status === "dismissed"+ ? []+ : (message.attachments ?? []).map((attachment) => attachment.id),+ )+ : [],+ );+ return pendingAttachments(before)+ .map((attachment) => attachment.id)+ .filter((id) => !kept.has(id));+}++/** Keeps every pending message and only the newest resolved ones. */+function trimResolved(messages: ReadonlyArray<ThreadGuestMessage>): Array<ThreadGuestMessage> {+ let resolvedBudget = GUEST_RESOLVED_MESSAGE_LIMIT;+ const kept: Array<ThreadGuestMessage> = [];+ for (const message of messages.toReversed()) {+ if (message.status !== "pending") {+ if (resolvedBudget === 0) continue;+ resolvedBudget -= 1;+ }+ kept.push(message);+ }+ return kept.toReversed();+}++const resolveMessage = (+ share: ThreadGuestShare,+ guestMessageId: GuestMessageId,+ status: "sent" | "dismissed",+): Result.Result<ThreadGuestShare, string> => {+ const message = share.messages.find((candidate) => candidate.id === guestMessageId);+ if (message === undefined || message.status !== "pending") {+ return Result.fail(`Guest message ${guestMessageId} is not pending.`);+ }+ return Result.succeed({+ ...share,+ messages: trimResolved(+ share.messages.map((candidate) =>+ candidate.id === guestMessageId ? { ...candidate, status } : candidate,+ ),+ ),+ });+};++/**+ * Applies a guest share command to the thread. The orchestrator runs commands one at a time, so+ * checking state here is what makes a link redeem once and a message send once.+ */+export function decideGuestShareCommand(input: {+ readonly thread: OrchestrationV2AppThread;+ readonly command: GuestShareCommand;+ readonly now: DateTime.Utc;+}): Result.Result<OrchestrationV2AppThread, string> {+ const { thread, command, now } = input;+ const share = thread.guestShare ?? null;+ const withShare = (guestShare: ThreadGuestShare | null) =>+ Result.succeed({ ...thread, guestShare, updatedAt: now });++ switch (command.type) {+ case "thread.guest-share.open": {+ if (thread.archivedAt !== null) return Result.fail("Archived threads cannot be shared.");+ return withShare({+ id: command.shareId,+ host: command.host,+ createdAt: DateTime.formatIso(now),+ expiresAt: command.expiresAt,+ guestName: null,+ messages: [],+ });+ }+ case "thread.guest-share.close":+ return share === null ? Result.succeed(thread) : withShare(null);+ case "thread.guest-share.redeem": {+ if (share === null || share.id !== command.shareId || isExpired(share, now)) {+ return Result.fail(GUEST_FAILURE.inactive);+ }+ if (share.guestName !== null) return Result.fail(GUEST_FAILURE.used);+ return withShare({ ...share, guestName: command.guestName });+ }+ case "thread.guest-message.submit": {+ if (+ share === null ||+ share.id !== command.shareId ||+ share.guestName === null ||+ isExpired(share, now)+ ) {+ return Result.fail(GUEST_FAILURE.inactive);+ }+ if (+ share.messages.filter((message) => message.status === "pending").length >=+ GUEST_PENDING_MESSAGE_LIMIT+ ) {+ return Result.fail(GUEST_FAILURE.busy);+ }+ const attachments = command.attachments ?? [];+ const pendingBytes = [...pendingAttachments(share), ...attachments].reduce(+ (total, attachment) => total + attachment.sizeBytes,+ 0,+ );+ if (attachments.length > 0 && pendingBytes > GUEST_PENDING_ATTACHMENT_BYTES_LIMIT) {+ return Result.fail(GUEST_FAILURE.filesBusy);+ }+ const guestShare: ThreadGuestShare = {+ ...share,+ messages: trimResolved([+ ...share.messages,+ {+ id: command.guestMessageId,+ text: command.text,+ status: "pending",+ submittedAt: DateTime.formatIso(now),+ ...(attachments.length === 0 ? {} : { attachments }),+ },+ ]),+ };+ // A request needs the owner, so a settled thread comes back as a new message brings it.+ return thread.settledOverride === "settled"+ ? Result.succeed({+ ...thread,+ guestShare,+ settledOverride: null,+ settledAt: null,+ unsettledAt: now,+ updatedAt: now,+ })+ : withShare(guestShare);+ }+ case "thread.guest-message.dismiss": {+ if (share === null) return Result.fail("This thread has no guest link.");+ return Result.map(resolveMessage(share, command.guestMessageId, "dismissed"), (next) => ({+ ...thread,+ guestShare: next,+ updatedAt: now,+ }));+ }+ }+}++/**+ * Marks a guest message sent. `text` is what the agent receives: it names the guest so the agent+ * does not mistake it for the owner's words, and so a guest cannot start a slash command.+ * `guest` lets clients show the guest's own text with their name beside it.+ */+export function decideGuestMessageSend(input: {+ readonly thread: OrchestrationV2AppThread;+ readonly guestMessageId: GuestMessageId;+ readonly now: DateTime.Utc;+}): Result.Result<+ {+ readonly thread: OrchestrationV2AppThread;+ readonly text: string;+ readonly guest: GuestMessageAttribution;+ },+ string+> {+ const share = input.thread.guestShare ?? null;+ if (share === null) return Result.fail("This thread has no guest link.");+ const message = share.messages.find((candidate) => candidate.id === input.guestMessageId);+ const name = share.guestName ?? "Guest";+ const guestText = message?.text ?? "";+ return Result.map(resolveMessage(share, input.guestMessageId, "sent"), (next) => ({+ thread: { ...input.thread, guestShare: next, updatedAt: input.now },+ text: `Message from guest ${name}, sent by the owner:\n\n${guestText}`,+ guest: { guestMessageId: input.guestMessageId, name, text: guestText, shareId: share.id },+ }));+}++/**+ * The owner cancelled a queued send, so the agent never got the message. It shows as dismissed,+ * which the guest can see, instead of sent with no reply ever coming. A share that changed since+ * the send is left alone.+ */+export function guestShareAfterCancelledSend(+ thread: OrchestrationV2AppThread,+ guest: Pick<GuestMessageAttribution, "guestMessageId" | "shareId">,+ now: DateTime.Utc,+): OrchestrationV2AppThread {+ const share = thread.guestShare ?? null;+ if (share === null || share.id !== guest.shareId) return thread;+ const message = share.messages.find((candidate) => candidate.id === guest.guestMessageId);+ if (message?.status !== "sent") return thread;+ return {+ ...thread,+ guestShare: {+ ...share,+ messages: share.messages.map((candidate) =>+ candidate.id === guest.guestMessageId ? { ...candidate, status: "dismissed" } : candidate,+ ),+ },+ updatedAt: now,+ };+}++/** Guest attribution comes only from `decideGuestMessageSend`; a client cannot claim it. */+export function withoutGuestAttribution<+ C extends { readonly context?: OrchestrationMessageContext | undefined },+>(command: C): C {+ if (command.context?.guest === undefined) return command;+ const { guest: _guest, ...context } = command.context;+ return { ...command, context };+}diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 8f5fad1c735..dfd8653bcab 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -1,4 +1,5 @@import type {+ GuestShareId,OrchestrationV2SearchThreadInput,OrchestrationV2SearchThreadResult,OrchestrationV2ThreadHistoryPage,@@ -20,6 +21,7 @@ import {ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,type ChatAttachment,CommandId,+ type GuestMessageId,isOrchestrationV2WorkActive,isProviderNativeSubagentThread,MessageId,@@ -78,6 +80,7 @@ import * as Path from "effect/Path";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Ref from "effect/Ref";+import * as Result from "effect/Result";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -105,6 +108,14 @@ import {isUndeliveredMailboxSteer,} from "./NotificationMailbox.ts";import { EventSinkV2 } from "./EventSink.ts";+import {+ decideGuestMessageSend,+ guestShareAfterCancelledSend,+ releasedGuestAttachmentIds,+ withoutGuestAttribution,+ decideGuestShareCommand,+ type GuestShareCommand,+} from "./GuestShareDecider.ts";import * as EffectOutbox from "./EffectOutbox.ts";import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";@@ -387,6 +398,9 @@ export interface OrchestratorV2Shape {readonly getThreadShell: (threadId: ThreadId,) => Effect.Effect<OrchestrationV2ThreadShell | null, OrchestratorV2Error>;+ readonly findGuestShareThreadId: (+ shareId: GuestShareId,+ ) => Effect.Effect<ThreadId | null, OrchestratorV2Error>;readonly getThreadEventSequence: (threadId: ThreadId,) => Effect.Effect<number, OrchestratorV2Error>;@@ -451,6 +465,11 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {case "thread.archive":case "thread.unarchive":case "thread.delete":+ case "thread.guest-share.open":+ case "thread.guest-share.redeem":+ case "thread.guest-share.close":+ case "thread.guest-message.submit":+ case "thread.guest-message.dismiss":case "thread.settle":case "thread.auto-settle":case "thread.unsettle":@@ -2658,6 +2677,100 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio},);+ // Deleted after the share change commits: the files of waiting messages it dismissed or dropped.+ const releaseGuestAttachments = (+ command: { readonly commandId: CommandId; readonly threadId: ThreadId },+ before: OrchestrationV2AppThread["guestShare"],+ after: OrchestrationV2AppThread["guestShare"],+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,+ ) => {+ const attachmentIds = releasedGuestAttachmentIds(before ?? null, after ?? null);+ return attachmentIds.length === 0+ ? Effect.void+ : Ref.update(effects, (existing) => [+ ...existing,+ {+ id: `effect:${command.commandId}:guest-attachment.cleanup`,+ commandId: command.commandId,+ threadId: command.threadId,+ request: { type: "attachment.cleanup", attachmentIds: [...attachmentIds] },+ } satisfies PendingOrchestrationEffectV2,+ ]);+ };++ const dispatchGuestShare = Effect.fn("orchestrationV2.dispatch.guestShare")(function* (+ command: GuestShareCommand,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,+ ) {+ const projection = yield* projectionStore+ .getThreadRecords(command.threadId, [])+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),+ ),+ );+ const thread = projection.thread;+ const now = yield* DateTime.now;+ const decided =+ thread.deletedAt !== null+ ? Result.fail(`Thread ${command.threadId} is deleted.`)+ : decideGuestShareCommand({+ thread,+ command,+ now,+ });+ if (Result.isFailure(decided)) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: decided.failure,+ });+ }+ if (decided.success === thread) return;+ yield* emit(+ events,+ command,+ )({+ type: "thread.guest-share-updated",+ threadId: command.threadId,+ providerInstanceId: thread.providerInstanceId,+ occurredAt: now,+ payload: decided.success,+ });+ yield* releaseGuestAttachments(command, thread.guestShare, decided.success.guestShare, effects);+ });++ // Emitted before the message so the send and the status change commit together, and so+ // `dispatchMessage`, which reads pending events, keeps the updated share.+ const emitGuestMessageSent = Effect.fn("orchestrationV2.dispatch.guestMessageSent")(function* (+ command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,+ guestMessageId: GuestMessageId,+ thread: OrchestrationV2AppThread,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ ) {+ const now = yield* DateTime.now;+ const decided = decideGuestMessageSend({ thread, guestMessageId, now });+ if (Result.isFailure(decided)) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: decided.failure,+ });+ }+ yield* emit(+ events,+ command,+ )({+ type: "thread.guest-share-updated",+ threadId: command.threadId,+ providerInstanceId: thread.providerInstanceId,+ occurredAt: now,+ payload: decided.success.thread,+ });+ return decided.success;+ });+const dispatchThreadMutation = Effect.fn("orchestrationV2.dispatch.threadMutation")(function* (command: Extract<OrchestrationV2ServerCommand,@@ -3099,6 +3212,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio...thread,archivedAt: now,titleRegeneration: null,+ guestShare: null,pullRequests: thread.pullRequests?.map((link) => withPullRequestWatch(link, undefined)),updatedAt: now,};@@ -3600,6 +3714,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiooccurredAt: now,payload: updatedThread,});+ // Archiving ends the guest share, so its waiting files go too.+ yield* releaseGuestAttachments(command, thread.guestShare, updatedThread.guestShare, effects);if (command.type === "thread.metadata.update" && command.regenerateTitle === true) {yield* Ref.update(effects, (existing) => [@@ -8423,6 +8539,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio},});}+ const guest = queuedMessage?.context?.guest;+ if (guest !== undefined) {+ const thread = guestShareAfterCancelledSend(projection.thread, guest, now);+ if (thread !== projection.thread) {+ yield* emitEvent({+ type: "thread.guest-share-updated",+ threadId: command.threadId,+ providerInstanceId: thread.providerInstanceId,+ occurredAt: now,+ payload: thread,+ });+ }+ }});const dispatchQueuedRunEdit = Effect.fn("Orchestrator.dispatchQueuedRunEdit")(function* (@@ -8470,6 +8599,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocause: "Automatic completion deliveries cannot be edited.",});}+ // The agent text and the shown text of a guest message must stay the guest's words.+ if (queuedMessage.context?.guest !== undefined) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: "A guest's message cannot be edited. Cancel it instead.",+ });+ }const queuedTurnItem = projection.turnItems.find((candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id,);@@ -8485,13 +8622,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),providerInstanceId: queuedRun.providerInstanceId,occurredAt: now,- payload: {+ payload: withoutGuestAttribution({...queuedMessage,text: command.text,...editedAttachments,...(command.context ? { context: command.context } : {}),updatedAt: now,- },+ }),});if (queuedTurnItem !== undefined && queuedTurnItem.type === "user_message") {yield* emitEvent({@@ -8501,13 +8638,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),providerInstanceId: queuedRun.providerInstanceId,occurredAt: now,- payload: {+ payload: withoutGuestAttribution({...queuedTurnItem,text: command.text,...editedAttachments,...(command.context ? { context: command.context } : {}),updatedAt: now,- },+ }),});}});@@ -11582,6 +11719,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocase "thread.pull-request-watch.sync":yield* dispatchPullRequestWatchSync(command, events, effects);break;+ case "thread.guest-share.open":+ case "thread.guest-share.redeem":+ case "thread.guest-share.close":+ case "thread.guest-message.submit":+ case "thread.guest-message.dismiss":+ yield* dispatchGuestShare(command, events, effects);+ break;case "provider-session.detach":yield* dispatchProviderSessionDetach(command, events, effects);break;@@ -11602,8 +11746,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiothreadId: command.threadId,});}- yield* dispatchMessage(command, events, effects);- yield* recordSubagentFollowup(command, events).pipe(mapDispatchError(command));+ const guestSend =+ command.guestMessageId === undefined+ ? undefined+ : yield* emitGuestMessageSent(command, command.guestMessageId, thread, events);+ const dispatched =+ guestSend === undefined+ ? withoutGuestAttribution(command)+ : {+ ...command,+ text: guestSend.text,+ context: { version: 1 as const, records: [], guest: guestSend.guest },+ };+ yield* dispatchMessage(dispatched, events, effects);+ yield* recordSubagentFollowup(dispatched, events).pipe(mapDispatchError(command));break;}case "notification.delivery.accept":@@ -11880,7 +12036,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioplanned.events.length > 0 ||command.type === "thread.background-work.settle" ||command.type === "thread.stop" ||- command.type === "subagent.stop"+ command.type === "subagent.stop" ||+ // A second Stop sharing, or one after the share already ended, is not an error.+ command.type === "thread.guest-share.close"? Effect.succeed(planned): Effect.fail(new OrchestratorDispatchError({@@ -12400,6 +12558,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioprojectionStore.getThreadShell(threadId).pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),+ findGuestShareThreadId: (shareId) =>+ projectionStore.findGuestShareThreadId(shareId).pipe(Effect.mapError(shellProjectionError)),getThreadEventSequence: (threadId) =>eventSink.latestSequence({ threadId })@@ -12555,6 +12715,13 @@ const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(cause: "Orchestration V2 live runtime is not configured.",}),),+ findGuestShareThreadId: () =>+ Effect.fail(+ new OrchestratorProjectionError({+ threadId: ThreadId.make("thread:shell"),+ cause: "Orchestration V2 live runtime is not configured.",+ }),+ ),getThreadEventSequence: (threadId) =>Effect.fail(new OrchestratorProjectionError({diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.tsindex 6c5835d8f40..48cb1d843fb 100644--- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts+++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts@@ -217,6 +217,7 @@ export const layer: Layer.Layer<"thread.interaction-mode-updated","thread.model-selection-updated","thread.provider-switched",+ "thread.guest-share-updated",];// Read-state events carry the whole thread too, but client reducers apply// them without bumping updatedAt. They supersede only each other: a newerdiff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 84ec210dc39..a7257e725f2 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -1,3 +1,4 @@+import { pendingGuestMessageCount } from "@t3tools/contracts";import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts";import { projectTurnItemForWire } from "./WireProjection.ts";import * as Stream from "effect/Stream";@@ -35,6 +36,7 @@ import type {OrchestrationV2ThreadShell,OrchestrationV2ThreadProjection,OrchestrationV2TurnItem,+ GuestShareId,ProjectId,ProviderSessionId,ProviderThreadId,@@ -212,6 +214,7 @@ export type ProjectionSettlementCandidate = Pick<| "activityRunStatus"| "pendingRuntimeRequest"| "pendingBackgroundTasks"+ | "pendingGuestMessageCount"> &Pick<OrchestrationV2AppThread, "lastSnoozeWakeAt"> & {readonly latestUserAuthoredMessageAt: DateTime.Utc | null;@@ -472,6 +475,10 @@ export interface ProjectionStoreV2Shape {readonly getThreadShell: (threadId: ThreadId,) => Effect.Effect<OrchestrationV2ThreadShell | null, ProjectionStoreV2Error>;+ /** The thread whose current guest share has this id. Scans thread rows; only redeem uses it. */+ readonly findGuestShareThreadId: (+ shareId: GuestShareId,+ ) => Effect.Effect<ThreadId | null, ProjectionStoreV2Error>;readonly getThread: (threadId: ThreadId,) => Effect.Effect<OrchestrationV2AppThread, ProjectionStoreV2Error>;@@ -826,6 +833,7 @@ export function applyToProjection(case "thread.interaction-mode-updated":case "thread.model-selection-updated":case "thread.provider-switched":+ case "thread.guest-share-updated":return {...base,thread: event.payload,@@ -1666,6 +1674,7 @@ export function threadShellFromProjection(providerSession?.lastError ?? null,),pendingRuntimeRequest,+ pendingGuestMessageCount: pendingGuestMessageCount(projection.thread.guestShare),// Thread detail owns message bodies. Keeping them out of shell rows makes// initial hydration and streaming updates independent of transcript size.latestVisibleMessage: null,@@ -1923,6 +1932,7 @@ function shellFromState(input: {lastErrorCode: input.state.lastErrorCode,usageLimitResetAt: input.state.usageLimitResetAt,pendingRuntimeRequest: input.state.pendingRuntimeRequest,+ pendingGuestMessageCount: pendingGuestMessageCount(input.state.thread.guestShare),latestVisibleMessage: null,latestUserMessageAt: input.state.latestUserMessageAt,latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt,@@ -2005,7 +2015,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =case "thread.runtime-mode-updated":case "thread.interaction-mode-updated":case "thread.model-selection-updated":- case "thread.provider-switched": {+ case "thread.provider-switched":+ case "thread.guest-share-updated": {const payloadJson = yield* encodeThreadPayload(event.payload);const payload = parseEncodedPayload(payloadJson);yield* sql`@@ -2838,7 +2849,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =event.type !== "thread.runtime-mode-updated" &&event.type !== "thread.interaction-mode-updated" &&event.type !== "thread.model-selection-updated" &&- event.type !== "thread.provider-switched"+ event.type !== "thread.provider-switched" &&+ event.type !== "thread.guest-share-updated") {const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt);yield* sql`@@ -5288,11 +5300,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =WHERE thread_id = ${threadId}AND type = 'dynamic_tool'AND (payload_json LIKE '%htmlRender%' OR payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`})+ `,+ // A guest's waiting files are pending uploads that no message row holds yet.+ sql<{ id: string }>`+ SELECT DISTINCT json_extract(attachment.value, '$.id') AS id+ FROM orchestration_v2_projection_threads AS thread,+ json_each(thread.payload_json, '$.guestShare.messages') AS message,+ json_each(message.value, '$.attachments') AS attachment+ WHERE thread.thread_id = ${threadId}+ AND json_extract(message.value, '$.status') = 'pending'`,]).pipe(- Effect.map(([messages, renders]) => [+ Effect.map(([messages, renders, guestFiles]) => [...new Set([...messages.map((row) => row.id),+ ...guestFiles.map((row) => row.id),...threadHtmlRenderAttachmentIds(threadId,renders.map((row) => {@@ -6175,6 +6197,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =activityRunStatus: null,activityRunStartedAt: null,pendingRuntimeRequest: null,+ pendingGuestMessageCount: pendingGuestMessageCount(thread.guestShare),pendingBackgroundTasks: derivePendingBackgroundWork({latestRun:latestRunId === null || status === "idle"@@ -6553,6 +6576,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =Effect.mapError(shellSnapshotReadError),);+ const findGuestShareThreadId = Effect.fn("ProjectionStore.findGuestShareThreadId")(function* (+ shareId: GuestShareId,+ ) {+ const rows = yield* sql<{ readonly thread_id: string }>`+ SELECT thread_id+ FROM orchestration_v2_projection_threads+ WHERE json_extract(payload_json, '$.guestShare.id') = ${shareId}+ LIMIT 1+ `;+ return rows[0] === undefined ? null : ThreadId.make(rows[0].thread_id);+ }, Effect.mapError(shellSnapshotReadError));+const getThreadShell: ProjectionStoreV2Shape["getThreadShell"] = (threadId) =>sql.withTransaction(@@ -6648,6 +6683,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =listActiveSubagentThreadIds: readOnReader(listActiveSubagentThreadIds),readShellSnapshot: readOnReader(readShellSnapshot),getThreadShell: readOnReader(getThreadShell),+ findGuestShareThreadId: readOnReader(findGuestShareThreadId),getThread: readOnReader(getThread),getSettlementCandidates: readOnReader(getSettlementCandidates),getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests),@@ -6795,6 +6831,15 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(.pipe(Effect.map(threadShellFromProjection));return shell.deletedAt === null ? shell : null;}),+ findGuestShareThreadId: Effect.fn("ProjectionStore.findGuestShareThreadId")(+ function* (shareId) {+ const existing = (yield* Ref.get(replayState)).projections;+ for (const { thread } of existing.values()) {+ if (thread.guestShare?.id === shareId) return thread.id;+ }+ return null;+ },+ ),getThread: Effect.fn("ProjectionStore.getThread")(function* (threadId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined) {@@ -7008,6 +7053,11 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(...projection.messages.flatMap((message) =>message.attachments.map((attachment) => attachment.id),),+ ...(projection.thread.guestShare?.messages ?? []).flatMap((message) =>+ message.status === "pending"+ ? (message.attachments ?? []).map((attachment) => attachment.id)+ : [],+ ),...threadHtmlRenderAttachmentIds(threadId,projection.turnItems.flatMap((item) =>diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.tsindex 3ae3a9974b4..42646e974ec 100644--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts@@ -214,6 +214,7 @@ it.effect(listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),readShellSnapshot: () => Effect.die("unused readShellSnapshot"),getThreadShell: () => Effect.die("unused getThreadShell"),+ findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.tsindex 5c9ccb981c9..fcf61cbc00e 100644--- a/apps/server/src/orchestration-v2/ThreadForkService.ts+++ b/apps/server/src/orchestration-v2/ThreadForkService.ts@@ -110,6 +110,8 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(settledAt: null,snoozedUntil: null,snoozedAt: null,+ // A guest link belongs to the thread it was made for.+ guestShare: null,lastVisitedAt: null,// A fork is a new thread; it does not inherit how often the source was opened.opens: null,diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.tsindex 2a884d19d3f..16707e2e357 100644--- a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts+++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts@@ -7,6 +7,8 @@ import {ChatAttachmentId,CommandId,EventId,+ GuestMessageId,+ MessageId,RuntimeRequestId,ThreadId,TurnItemId,@@ -18,7 +20,11 @@ import {import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import { createPendingAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";+import {+ createAttachmentId,+ createPendingAttachmentId,+ resolveAttachmentPath,+} from "../attachmentStore.ts";import * as ServerConfig from "../config.ts";import * as ServerSettings from "../serverSettings.ts";import {@@ -32,18 +38,21 @@ const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {prefix: "t3-question-intake-",}).pipe(Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ServerSettings.layerTest()));+const layerFailingDispatchHandler =+ (captured: OrchestrationV2ServerCommand[]) => (command: OrchestrationV2ServerCommand) => {+ captured.push(command);+ return Effect.fail(+ new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: "Stop after intake",+ }),+ );+ };+const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) =>Layer.mock(ThreadManagementService.ThreadManagementService)({- dispatch: (command) => {- captured.push(command);- return Effect.fail(- new OrchestratorDispatchError({- commandId: command.commandId,- commandType: command.type,- cause: "Stop after intake",- }),- );- },+ dispatch: layerFailingDispatchHandler(captured),});const NOW = DateTime.makeUnsafe("2026-09-13T00:00:00.000Z");@@ -359,3 +368,57 @@ it.effect("a retried response re-claims the preserved pending uploads", () =>).toHaveLength(2);}).pipe(Effect.provide(layerIntakeTest)),);++it.effect("sends a guest message with the guest's files, never ones the client names", () =>+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const guestFile = {+ type: "image" as const,+ id: ChatAttachmentId.make(createAttachmentId("thread-guest")!),+ name: "screen.png",+ mimeType: "image/png",+ sizeBytes: 3,+ };+ NodeFS.writeFileSync(+ NodePath.join(config.attachmentsDir, `${guestFile.id}.png`),+ new Uint8Array([1, 2, 3]),+ );+ const guestMessageId = GuestMessageId.make("guest-message:files");+ const captured: OrchestrationV2ServerCommand[] = [];+ const layerGuestShare = Layer.mock(ThreadManagementService.ThreadManagementService)({+ dispatch: layerFailingDispatchHandler(captured),+ // Only the share is read.+ getThreadSnapshotWindow: () =>+ Effect.succeed({+ projection: {+ thread: {+ guestShare: {+ messages: [{ id: guestMessageId, status: "pending", attachments: [guestFile] }],+ },+ },+ },+ } as unknown as Effect.Success<+ ReturnType<+ ThreadManagementService.ThreadManagementServiceShape["getThreadSnapshotWindow"]+ >+ >),+ });+ yield* dispatchCommand({+ type: "message.dispatch",+ commandId: CommandId.make("send-guest-message"),+ threadId: ThreadId.make("thread-guest"),+ messageId: MessageId.make("message-guest"),+ guestMessageId,+ text: "",+ attachments: [{ ...guestFile, id: ChatAttachmentId.make("thread-guest-owner-file") }],+ dispatchMode: { type: "queue_after_active" },+ createdBy: "user",+ creationSource: "web",+ }).pipe(Effect.provide(layerGuestShare), Effect.result);+ const command = captured[0];+ if (command?.type !== "message.dispatch") throw new Error("Expected a message dispatch.");+ expect(command.attachments).toHaveLength(1);+ // The guest's file, which is already the thread's.+ expect(command.attachments).toEqual([guestFile]);+ }).pipe(Effect.provide(layerIntakeTest)),+);diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.tsindex fa8f068849d..0c5ae6fbd85 100644--- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts+++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts@@ -53,9 +53,39 @@ const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims"));});+/**+ * A guest message goes out with the files the guest attached, never ones a client names. They+ * are already the thread's attachments. A message no longer waiting gets none; the orchestrator+ * then refuses or replays the send.+ */+const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments")(function* (+ command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,+) {+ if (command.guestMessageId === undefined) return command;+ const threads = yield* ThreadManagement.ThreadManagementService;+ // Only the thread record is needed; the window keeps the read small.+ const { projection } = yield* threads+ .getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })+ .pipe(+ Effect.mapError(+ (cause) =>+ new AttachmentClaims.AttachmentClaimError({+ message: "Failed to read the guest message.",+ cause,+ }),+ ),+ );+ const message = projection.thread.guestShare?.messages.find(+ (candidate) => candidate.id === command.guestMessageId && candidate.status === "pending",+ );+ return { ...command, attachments: message?.attachments ?? [] };+});+export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (- command: OrchestrationV2Command,+ incoming: OrchestrationV2Command,) {+ const command =+ incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming;const threads = yield* ThreadManagement.ThreadManagementService;if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {const config = yield* ServerConfig.ServerConfig;diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.tsindex f17aaad4b86..e6e7b20e1a9 100644--- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts@@ -141,6 +141,21 @@ describe("isAutoSettlementCandidate", () => {).toBe(true);});+ it("never settles, or keeps snoozed, a thread whose guest is waiting on the owner", () => {+ expect(+ ThreadSettlementService.isAutoSettlementCandidate(+ shell({ pendingGuestMessageCount: 1 }),+ NOW_MS,+ ),+ ).toBe(false);+ const snoozed = shell({+ snoozedUntil: at(60 * 60 * 1_000),+ snoozedAt: at(-60 * 60 * 1_000),+ pendingGuestMessageCount: 1,+ });+ expect(ThreadSettlementService.isSnoozed(snoozed, NOW_MS)).toBe(false);+ });+it("keeps snoozed threads parked until a fresh failure or timer wake", () => {const snoozed = shell({snoozedUntil: at(60 * 60 * 1_000),diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.tsindex d218205fbc5..beb77b8ca8e 100644--- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts@@ -152,6 +152,8 @@ export function isAutoSettlementCandidate(if (thread.archivedAt !== null || thread.settledOverride !== null) return false;if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false;if (thread.pendingRuntimeRequest !== null) return false;+ // A guest is waiting on the owner; settling would hide the Request.+ if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;if (thread.activityRunStatus != null) return false;if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false;if (threadHasQueuedTurnStart(thread, nowMs)) return false;@@ -166,13 +168,20 @@ export function isAutoSettlementCandidate(export function isSnoozed(thread: Pick<ProjectionStore.ProjectionSettlementCandidate,- "snoozedUntil" | "snoozedAt" | "latestRunCompletedAt" | "status" | "pendingRuntimeRequest"+ | "snoozedUntil"+ | "snoozedAt"+ | "latestRunCompletedAt"+ | "status"+ | "pendingRuntimeRequest"+ | "pendingGuestMessageCount">,nowMs: number,): boolean {const snoozedUntilMs = toMillis(thread.snoozedUntil);if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;if (thread.pendingRuntimeRequest !== null) return false;+ // Same as the client: a waiting guest message wakes the thread, and the snooze stays stored.+ if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;const snoozedAtMs = toMillis(thread.snoozedAt);const completedAtMs = toMillis(thread.latestRunCompletedAt);const wokeOnError =diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.tsindex ad4c7ecda87..d8337c56272 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts@@ -1,3 +1,4 @@+import * as GuestShareService from "../guest/GuestShareService.ts";import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";import * as Scheduler from "../scheduling/Scheduler.ts";import * as Layer from "effect/Layer";@@ -367,6 +368,9 @@ export const layerProduction = Layer.mergeAll(layerThreadLifecycleProvided,layerScheduledTaskProvided,layerSecretRequestsProvided,+ GuestShareService.layer.pipe(+ Layer.provide(Layer.merge(layerOrchestratorProvided, layerCommandOutputHubProvided)),+ ),UsageLimitRecoveryWorker.layer.pipe(Layer.provide(Layer.mergeAll(diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.tsindex 4e98e20949c..191aaca00df 100644--- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts@@ -135,6 +135,8 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Threadcase "thread.archive":case "thread.unarchive":case "thread.delete":+ case "thread.guest-share.close":+ case "thread.guest-message.dismiss":case "thread.settle":case "thread.auto-settle":case "thread.unsettle":diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsindex c6a61817f69..70186bb347a 100644--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.ts@@ -104,6 +104,7 @@ function shouldPublishAgentAwarenessEvent(return true;// Unsettling must not re-alert a dismissed result.case "thread.unsettled":+ case "thread.guest-share-updated":case "thread.snoozed":case "thread.unsnoozed":case "thread.auto-settle-set":diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex c88a42bd12b..a237cec73e9 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -141,6 +141,7 @@ import {} from "./cloud/config.ts";import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import * as CloudHttp from "./cloud/http.ts";+import * as GuestHttp from "./guest/http.ts";import * as CloudLink from "./cloud/CloudLink.ts";import * as ConnectReachability from "./cloud/ConnectReachability.ts";import { pendingServiceUpdateExists } from "./cloud/updateHandoff.ts";@@ -719,6 +720,7 @@ const layerMakeRoutes = Layer.mergeAll(ServerHttp.layerOtlpTracesProxyRoute,ServerHttp.layerAssetRoute,ServerHttp.layerAttachmentUploadRoute,+ GuestHttp.layer,DeviceHubProxy.layer,ServerBrowserStream.routeLayer,ServerHttp.layerStaticAndDevRoute,diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex 894f95c0d82..34b54156eb8 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -69,6 +69,7 @@ import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";import * as ReviewService from "./review/ReviewService.ts";import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";import * as SecretRequests from "./secrets/SecretRequests.ts";+import * as GuestShareService from "./guest/GuestShareService.ts";import * as ServerEnvironment from "./environment/ServerEnvironment.ts";import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";@@ -405,6 +406,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(Layer.mock(ReviewService.ReviewService)({}),Layer.mock(ScheduledTasks.ScheduledTaskService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(GuestShareService.GuestShareService)({}),Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}),Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}),Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 3316829f483..bed47be949f 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -121,6 +121,7 @@ import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";import * as SecretRequests from "./secrets/SecretRequests.ts";+import * as GuestShareService from "./guest/GuestShareService.ts";import {archivedShellStreamItemFromThreadShell,buildActiveShellSnapshot,@@ -1268,6 +1269,7 @@ export const layerWsRpc = (const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2;const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService;const secretRequests = yield* SecretRequests.SecretRequests;+ const guestShares = yield* GuestShareService.GuestShareService;const pullRequests = yield* PullRequestService.PullRequestService;const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor;@@ -2162,6 +2164,10 @@ export const layerWsRpc = (Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe(Effect.andThen(scheduledTasks.rotateWebhookToken(input)),),+ [WS_METHODS.guestShareCreate]: (input) =>+ Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(+ Effect.andThen(guestShares.create(input)),+ ),[WS_METHODS.secretsAnswerRequest]: (input) =>Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(Effect.andThen(secretRequests.answer(input)),diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 800998728cf..e9d787ca8b4 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -165,6 +165,7 @@ import {} from "../previewMiniPlayerStore";import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.logic";import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog";+import { GuestPendingMessages } from "./chat/GuestShareControls";import { useDeviceState } from "~/state/device";import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";@@ -2960,23 +2961,53 @@ export default function ChatView(props: ChatViewProps) {const sendPreviewAnnotationStable = useStableCallback(sendPreviewAnnotation);const onComposerResumeStable = useStableCallback(onResume);const onComposerCompactContextStable = useStableCallback(onCompactContext);+ // Read from the projection the footer renders, so the scroll below sees the new message.+ const pendingGuestMessageIds =+ serverProjection?.thread.guestShare?.messages.flatMap((message) =>+ message.status === "pending" ? [message.id] : [],+ ) ?? [];+ const pendingGuestMessageCount = pendingGuestMessageIds.length;+ const pendingGuestMessageKey = pendingGuestMessageIds.join(",");+ const previousPendingGuestMessagesRef = useRef({+ threadKey: routeThreadKey,+ key: pendingGuestMessageKey,+ });+ useEffect(() => {+ const previous = previousPendingGuestMessagesRef.current;+ previousPendingGuestMessagesRef.current = {+ threadKey: routeThreadKey,+ key: pendingGuestMessageKey,+ };+ // Opening another thread is not a new message; its own scroll position wins.+ if (previous.threadKey !== routeThreadKey) return;+ // Pending guest messages sit in the list footer, which the list does not follow on its own.+ // The follow flag reflects the owner's position before the footer grew; a live measure may not.+ // Any new id counts, even when another one was resolved in the same update.+ const previousIds = new Set(previous.key.split(","));+ const hasNewMessage = pendingGuestMessageKey+ .split(",")+ .some((id) => id !== "" && !previousIds.has(id));+ if (hasNewMessage && timelineLiveFollowEnabled) scrollToEnd(true);+ }, [routeThreadKey, pendingGuestMessageKey, timelineLiveFollowEnabled, scrollToEnd]);const queuedRunsControl =isServerThread && activeThread ? (- <QueuedRunsControl- ref={queuedRunsControlRef}- steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {- context: { terminalFocus: false },- })}- editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {- context: { composerFocus: true },- })}- environmentId={activeThread.environmentId}- threadId={activeThread.id}- optimisticMessages={optimisticUserMessages}- editingRunId={queuedRunEdit.editingRunId}- onEditQueuedRun={queuedRunEdit.beginEdit}- onCancelEdit={queuedRunEdit.cancelEdit}- />+ <>+ <QueuedRunsControl+ ref={queuedRunsControlRef}+ steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {+ context: { terminalFocus: false },+ })}+ editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {+ context: { composerFocus: true },+ })}+ environmentId={activeThread.environmentId}+ threadId={activeThread.id}+ optimisticMessages={optimisticUserMessages}+ editingRunId={queuedRunEdit.editingRunId}+ onEditQueuedRun={queuedRunEdit.beginEdit}+ onCancelEdit={queuedRunEdit.cancelEdit}+ />+ </>) : null;// One-shot: the resend "Work locally" queued fires once, then the marker clears.const resendAfterWorkLocally = () => {@@ -3316,18 +3347,28 @@ export default function ChatView(props: ChatViewProps) {{...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree}footer={- paintOnlyDisplayedTimeline ? null : pendingHandoff === null ? (- threadStatusLine- ) : (+ paintOnlyDisplayedTimeline ||+ (pendingHandoff === null &&+ pendingGuestMessageCount === 0 &&+ threadStatusLine === null) ? null : (<>- <div className="chat-content-lane">- <HandoffRow- environmentId={environmentId}- endpoints={pendingHandoff}- providers={providerStatuses}- pending+ {pendingHandoff === null ? null : (+ <div className="chat-content-lane">+ <HandoffRow+ environmentId={environmentId}+ endpoints={pendingHandoff}+ providers={providerStatuses}+ pending+ />+ </div>+ )}+ {pendingGuestMessageCount > 0 && isServerThread && activeThread ? (+ <GuestPendingMessages+ threadRef={scopeThreadRef(activeThread.environmentId, activeThread.id)}+ onImageExpand={onExpandTimelineImageStable}+ onFileOpen={openFileAttachmentStable}/>- </div>+ ) : null}{threadStatusLine}</>)diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex 1516a6cd992..f0ae6eddb97 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -64,6 +64,7 @@ import {SettingsIcon,SquarePenIcon,TextSearchIcon,+ UserPlusIcon,} from "lucide-react";import { requestThreadFindOpen } from "./chat/threadFindActionBus";import {@@ -217,6 +218,8 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";import { Checkbox } from "./ui/checkbox";import { ProjectFilePicker } from "./files/ProjectFilePicker";import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";+import { canShareWithGuestAtom } from "./chat/guestShareAvailability";+import { openGuestShareDialog } from "./chat/guestShareDialogState";import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";@@ -540,6 +543,9 @@ function OpenCommandPaletteDialog(props: {const activeThreadServerConfig = useServerConfigs().get(activeThread?.environmentId ?? ("" as EnvironmentId),);+ const canShareActiveThreadWithGuest = useAtomValue(+ canShareWithGuestAtom(activeThread?.environmentId ?? ("" as EnvironmentId)),+ );const activeThreadReferenceCopyTarget =referenceThreadRef === null || (pathname === "/pull-requests" && !openPanelPullRequestUrl)? null@@ -1364,6 +1370,20 @@ function OpenCommandPaletteDialog(props: {}}+ if (activeThread !== null && canShareActiveThreadWithGuest) {+ const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);+ actionItems.push({+ kind: "action",+ value: "action:share-thread-with-guest",+ searchTerms: ["share", "guest", "invite", "link", "teammate"],+ title: "Share with guest",+ icon: <UserPlusIcon className={ITEM_ICON_CLASS} />,+ run: async () => {+ openGuestShareDialog(threadRef);+ },+ });+ }+if (activeThread !== null) {const thread = activeThread;actionItems.push({diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex d9bf1474825..aa595c9186e 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -207,7 +207,10 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";import { useIsMobile } from "~/hooks/useMediaQuery";import { CommandDialogTrigger } from "./ui/command";import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";-import { primaryServerKeybindingsAtom } from "../state/server";+import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { canShareWithGuestAtom } from "./chat/guestShareAvailability";+import { openGuestShareDialog } from "./chat/guestShareDialogState";import {derivePhysicalProjectKey,deriveProjectGroupingOverrideKey,@@ -2165,6 +2168,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]: []),{ id: "rename", label: "Rename thread", disabled: !canOperateThread },+ ...(appAtomRegistry.get(canShareWithGuestAtom(thread.environmentId))+ ? [{ id: "share-guest", label: "Share with guest" }]+ : []),{ id: "mark-unread", label: "Mark unread" },{ id: "copy-path", label: "Copy Path" },{ id: "copy-thread-id", label: "Copy Thread ID" },@@ -2216,6 +2222,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjecreturn;}+ if (clicked === "share-guest") {+ openGuestShareDialog(threadRef);+ return;+ }if (clicked === "mark-unread") {markThreadUnread(threadRef);return;diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex 0b103763f1f..503a6160df7 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -272,6 +272,19 @@ describe("resolveSidebarThreadStatus", () => {).toBe("approval");});+ it("shows a waiting guest message as a Request, below the agent's own requests", () => {+ expect(resolveSidebarThreadStatus({ ...idle, pendingGuestMessageCount: 1, runtime })).toBe(+ "request",+ );+ expect(+ resolveSidebarThreadStatus({+ ...idle,+ hasPendingUserInput: true,+ pendingGuestMessageCount: 1,+ }),+ ).toBe("input");+ });+it("keeps usage-limit stops Limited and visible until the thread recovers", () => {const limited = {...runtime,diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 97046c71a11..0e6d4f5a838 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -589,6 +589,7 @@ export interface ThreadStatusPill {| "Failed"| "Pending Approval"| "Awaiting Input"+ | "Guest Request"| "Waiting"| "Plan Ready";colorClass: string;@@ -599,6 +600,7 @@ export interface ThreadStatusPill {const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {"Pending Approval": 5,"Awaiting Input": 4,+ "Guest Request": 3.75,Failed: 3.5,Working: 3,Connecting: 3,@@ -613,6 +615,7 @@ type ThreadStatusInput = Pick<| "hasPendingApprovals"| "hasPendingUserInput"| "pendingSubagentRequest"+ | "pendingGuestMessageCount"| "interactionMode"| "latestRun"| "runtime"@@ -866,6 +869,7 @@ export function isContextMenuPointerDown(input: {export type SidebarThreadStatus =| "approval"| "input"+ | "request"| "working"| "waiting"| "failed"@@ -879,7 +883,14 @@ export function shouldRecedeSidebarThread(input: {isActive: boolean;isSelected: boolean;}): boolean {- if (input.isActive || input.isSelected || input.status === "input") return false;+ if (+ input.isActive ||+ input.isSelected ||+ input.status === "input" ||+ input.status === "request"+ ) {+ return false;+ }if (input.status === "working" || input.status === "waiting") return true;if (input.status === "ready" || input.status === "approval") {return !input.isUnread && !input.isWoke;@@ -892,6 +903,7 @@ type SidebarThreadStatusInput = Pick<| "hasPendingApprovals"| "hasPendingUserInput"| "pendingSubagentRequest"+ | "pendingGuestMessageCount"| "runtime"| "blockedOnThreadWait">;@@ -903,6 +915,10 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Siif (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {return "input";}+ // A guest is waiting on the owner; the agent's own requests come first.+ if ((thread.pendingGuestMessageCount ?? 0) > 0) {+ return "request";+ }if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {return "waiting";}@@ -927,6 +943,7 @@ export type SidebarV2TopStatusKind =| "failed"| "limited"| "input"+ | "request"| "waiting"| "woke"| "working";@@ -945,8 +962,8 @@ export function resolveSidebarV2TopStatus(input: {if (input.status === "approval") {return "approval";}- if (input.status === "input") {- return "input";+ if (input.status === "input" || input.status === "request") {+ return input.status;}if (input.status === "failed" || input.status === "limited") {return input.status;@@ -1092,6 +1109,15 @@ export function resolveThreadStatusPill(input: {};}+ if ((thread.pendingGuestMessageCount ?? 0) > 0) {+ return {+ label: "Guest Request",+ colorClass: "text-guest-foreground",+ dotClass: "bg-guest",+ pulse: false,+ };+ }+if ((thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||thread.runtime?.status === "waiting"diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 827f62ee611..faee72b80f3 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -126,12 +126,15 @@ import {useQuietThreadShells,} from "../state/entities";import { environmentPresentations } from "../state/presentation";-import { primaryServerKeybindingsAtom } from "../state/server";+import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server";import { environmentProjects } from "../state/projects";import { threadEnvironment } from "../state/threads";import { useThreadSearch } from "../state/queries";import { useOrchestrationCommand } from "../state/use-orchestration-command";import { readEnvironmentScope } from "../state/session";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { canShareWithGuestAtom } from "./chat/guestShareAvailability";+import { openGuestShareDialog } from "./chat/guestShareDialogState";import { buildThreadRouteParams, resolveActiveThreadRouteRef } from "../threadRoutes";import type { SidebarThreadSummary } from "../types";import { isScratchProject } from "@t3tools/client-runtime/state/projects";@@ -2388,6 +2391,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteRevecanSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),isRegeneratingTitle,isRunning: !threadRuntimeCanArchive(thread.runtime),+ canShareWithGuest: appAtomRegistry.get(+ canShareWithGuestAtom(threadRef.environmentId),+ ),supports: {settlement: supportsSettlement,autoSettleOptOut: supportsAutoSettleOptOut,@@ -2484,6 +2490,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteRevecase "rename":startThreadRename(threadRef, thread.title);return;+ case "share-guest":+ openGuestShareDialog(threadRef);+ return;case "regenerate-title": {if (isRegeneratingTitle) return;const result = await updateThreadMetadata({diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsxindex edc1b8e2f3c..9769fbce75e 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx@@ -139,7 +139,11 @@ function EnvironmentNotifications({let status = resolveSidebarThreadStatus(thread);if (status === "ready" && thread.latestRun?.status === "failed") status = "failed";const attention =- status === "input" || status === "approval" || status === "failed" || status === "limited"+ status === "input" ||+ status === "request" ||+ status === "approval" ||+ status === "failed" ||+ status === "limited"? `${thread.latestRun?.runId ?? ""}:${status}`: null;const completedAt = Date.parse(thread.latestRun?.completedAt ?? "");@@ -170,7 +174,9 @@ function EnvironmentNotifications({? "Usage limit reached": status === "failed"? "Thread failed"- : "Input needed";+ : status === "request"+ ? "Guest request"+ : "Input needed";if (hasNotificationSound(mode)) {void playNotificationSound(kind, () =>hasNotificationSound(getClientSettings().notificationMode),diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsxindex 56861a5d9a0..c3d59135433 100644--- a/apps/web/src/components/chat/ChatHeader.tsx+++ b/apps/web/src/components/chat/ChatHeader.tsx@@ -24,6 +24,9 @@ import { toastManager } from "../ui/toast";import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";import { readLocalApi } from "~/localApi";import { threadEnvironment } from "../../state/threads";+import { serverEnvironment } from "../../state/server";+import { canShareWithGuestAtom } from "./guestShareAvailability";+import { useAtomValue } from "@effect/atom-react";import { useOrchestrationCommand } from "../../state/use-orchestration-command";import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";import { ProjectFavicon } from "../ProjectFavicon";@@ -37,6 +40,7 @@ import { observeResize } from "~/lib/observeResize";import { cn } from "~/lib/utils";import { textDirection } from "~/textDirection";import { useClientSettings } from "../../hooks/useSettings";+import { GuestShareIndicator } from "./GuestShareControls";interface ChatHeaderProps {activeThreadEnvironmentId: EnvironmentId;@@ -88,6 +92,7 @@ export const ChatHeader = memo(function ChatHeader({activeThreadEnvironmentId,AuthOrchestrationOperateScope,);+ const canShareWithGuest = useAtomValue(canShareWithGuestAtom(activeThreadEnvironmentId));const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {reportFailure: false,});@@ -191,6 +196,7 @@ export const ChatHeader = memo(function ChatHeader({threadRef: isServerThread ? activeThreadRef : null,projectCwd: activeProjectCwd,onStartRename: startRename,+ canShareWithGuest,});const titleButtonRef = useRef<HTMLButtonElement | null>(null);const titleMenuTimerRef = useRef<number | null>(null);@@ -406,6 +412,7 @@ export const ChatHeader = memo(function ChatHeader({)}</WorkspaceBreadcrumbItem></WorkspaceBreadcrumb>+ {isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}</div>);});diff --git a/apps/web/src/components/chat/CommandOutputPanel.tsx b/apps/web/src/components/chat/CommandOutputPanel.tsxindex cc631e76317..d030351cb8d 100644--- a/apps/web/src/components/chat/CommandOutputPanel.tsx+++ b/apps/web/src/components/chat/CommandOutputPanel.tsx@@ -1,3 +1,4 @@+import type { CommandOutputView } from "@t3tools/client-runtime/state/command-output";import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";import { TERMINAL_PALETTES, terminalOutputSpans } from "@t3tools/shared/terminalOutput";import { useLayoutEffect, useRef } from "react";@@ -6,6 +7,7 @@ import { useTheme } from "../../hooks/useTheme";import { useServerConfigs } from "../../state/entities";import { orchestrationEnvironment } from "../../state/orchestration";import { useEnvironmentQuery } from "../../state/query";+import type { TurnItemSource } from "./timelineRowContext";// Within this many pixels of the end still counts as following the output.const FOLLOW_SLACK_PX = 8;@@ -19,19 +21,21 @@ export function useCommandOutputStreaming(environmentId: EnvironmentId): boolean/*** Output of one expanded command row: streams while the command runs, then- * shows its final output. Mount it only when `useCommandOutputStreaming` holds.+ * shows its final output. Mount it only when `useCommandOutputStreaming` holds+ * or a `source` serves the output.* It subscribes only while mounted, so collapsed rows and other threads receive nothing.*/export function CommandOutputPanel(props: {readonly environmentId: EnvironmentId;readonly threadId: ThreadId;readonly itemId: TurnItemId;+ readonly source?: TurnItemSource["commandOutput"] | undefined;}) {- const { data, error } = useEnvironmentQuery(- orchestrationEnvironment.v2.commandOutput({- environmentId: props.environmentId,- input: { threadId: props.threadId, itemId: props.itemId },- }),+ const input = { threadId: props.threadId, itemId: props.itemId };+ const { data, error } = useEnvironmentQuery<CommandOutputView, unknown>(+ props.source+ ? props.source(input)+ : orchestrationEnvironment.v2.commandOutput({ environmentId: props.environmentId, input }),);const scrollRef = useRef<HTMLDivElement>(null);// Follow new output until the reader scrolls up; scrolling back down resumes.diff --git a/apps/web/src/components/chat/GuestMessageAttachments.tsx b/apps/web/src/components/chat/GuestMessageAttachments.tsxnew file mode 100644index 00000000000..e66fefb7d27--- /dev/null+++ b/apps/web/src/components/chat/GuestMessageAttachments.tsx@@ -0,0 +1,102 @@+import type { ChatAttachment } from "@t3tools/contracts";+import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";++import { useTheme } from "~/hooks/useTheme";+import { cn } from "~/lib/utils";+import { type ChatFileAttachment, isFileAttachment, isImageAttachment } from "../../types";+import { AttachmentImage } from "../media/AttachmentImage";+import { PierreEntryIcon } from "./PierreEntryIcon";++const IMAGE_FRAME =+ "aspect-[4/3] overflow-hidden rounded-lg border border-border/80 bg-background/70";+const FILE_ROW = "flex min-w-0 items-center gap-2 py-1 text-sm";++/**+ * A guest message's files, drawn like a sent message's: image thumbnails, then file rows. The+ * owner opens them in the app; the guest loads them from the guest route.+ */+export function GuestMessageAttachments(props: {+ readonly attachments: ReadonlyArray<ChatAttachment>;+ /** Where an image loads from; undefined while its URL is not ready. */+ readonly imageUrl: (attachment: ChatAttachment) => string | undefined;+ readonly onOpenImage: (attachment: ChatAttachment) => void;+ /** A file row as a link, or a button that calls `onOpenFile`. */+ readonly fileHref?: (attachment: ChatFileAttachment) => string;+ readonly onOpenFile?: (attachment: ChatFileAttachment) => void;+}) {+ const { resolvedTheme } = useTheme();+ const images = props.attachments.filter(isImageAttachment);+ const files = props.attachments.filter(isFileAttachment);+ if (images.length === 0 && files.length === 0) return null;+ return (+ <div className="flex flex-col items-end gap-2">+ {images.length > 0 ? (+ <div className="grid w-[210px] grid-cols-2 gap-2">+ {images.map((image) => {+ const src = props.imageUrl(image);+ return (+ <div key={image.id} className={IMAGE_FRAME}>+ {src ? (+ <button+ type="button"+ className="block size-full cursor-zoom-in"+ aria-label={`Preview ${image.name}`}+ onClick={() => props.onOpenImage(image)}+ >+ <AttachmentImage+ name={image.name}+ mimeType={image.mimeType}+ src={src}+ alt={image.name}+ decoding="async"+ className="block size-full object-cover"+ />+ </button>+ ) : (+ <div className="flex size-full items-center justify-center px-2 text-center text-2xs text-muted-foreground/70">+ {image.name}+ </div>+ )}+ </div>+ );+ })}+ </div>+ ) : null}+ {files.map((file) => {+ const identity = (+ <>+ <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />+ <span className="min-w-0 truncate">{file.name}</span>+ <span className="shrink-0 text-xs text-muted-foreground">+ {formatAttachmentSize(file.sizeBytes)}+ </span>+ </>+ );+ return props.fileHref ? (+ <a+ key={file.id}+ href={props.fileHref(file)}+ download={file.name}+ className={cn(FILE_ROW, "hover:underline")}+ >+ {identity}+ </a>+ ) : props.onOpenFile ? (+ <button+ key={file.id}+ type="button"+ aria-label={`Preview ${file.name}`}+ onClick={() => props.onOpenFile?.(file)}+ className={cn(FILE_ROW, "cursor-pointer hover:underline")}+ >+ {identity}+ </button>+ ) : (+ <div key={file.id} className={FILE_ROW}>+ {identity}+ </div>+ );+ })}+ </div>+ );+}diff --git a/apps/web/src/components/chat/GuestShareControls.tsx b/apps/web/src/components/chat/GuestShareControls.tsxnew file mode 100644index 00000000000..797cb0e5c52--- /dev/null+++ b/apps/web/src/components/chat/GuestShareControls.tsx@@ -0,0 +1,326 @@+import { useAtomValue } from "@effect/atom-react";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import {+ AuthOrchestrationOperateScope,+ type ChatAttachment,+ type GuestMessageId,+ type ScopedThreadRef,+ type ThreadGuestShare,+} from "@t3tools/contracts";+import { CheckIcon, CopyIcon, UserIcon } from "lucide-react";+import { useState } from "react";++import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";+import { useNowMinute } from "~/hooks/useNowMinute";+import { appAtomRegistry } from "~/rpc/atomRegistry";+import { useQuietThreadProjection } from "~/state/entities";+import { serverEnvironment } from "~/state/server";+import { useEnvironmentScope } from "~/state/session";+import { threadEnvironment } from "~/state/threads";+import { useAtomCommand } from "~/state/use-atom-command";+import { cn } from "~/lib/utils";+import { useOrchestrationCommand } from "~/state/use-orchestration-command";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";+import { Input } from "../ui/input";+import { useAssetUrls } from "~/assets/assetUrls";+import { type ChatFileAttachment, isImageAttachment } from "../../types";+import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";+import { GuestMessageAttachments } from "./GuestMessageAttachments";+import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle";+import { guestShareDialogThreadAtom } from "./guestShareDialogState";++function useThreadGuestShare(threadRef: ScopedThreadRef | null): ThreadGuestShare | null {+ return useQuietThreadProjection(threadRef)?.projection.thread.guestShare ?? null;+}++export function GuestShareDialogHost() {+ const threadRef = useAtomValue(guestShareDialogThreadAtom);+ if (threadRef === null) return null;+ return (+ <GuestShareDialog+ key={`${threadRef.environmentId}:${threadRef.threadId}`}+ threadRef={threadRef}+ onClose={() => appAtomRegistry.set(guestShareDialogThreadAtom, null)}+ />+ );+}++type CreateState =+ | { readonly status: "idle" }+ | { readonly status: "creating" }+ | { readonly status: "created"; readonly url: string }+ | { readonly status: "failed"; readonly message: string };++function GuestShareDialog({+ threadRef,+ onClose,+}: {+ readonly threadRef: ScopedThreadRef;+ readonly onClose: () => void;+}) {+ const activeShare = useThreadGuestShare(threadRef);+ const canCreate = useAtomValue(+ serverEnvironment.createGuestShare.permissionAtom(threadRef.environmentId),+ );+ const createGuestShare = useAtomCommand(serverEnvironment.createGuestShare, {+ reportFailure: false,+ });+ const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "guest link" });+ const [state, setState] = useState<CreateState>({ status: "idle" });++ const create = async () => {+ setState({ status: "creating" });+ const result = await createGuestShare({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId },+ });+ if (result._tag === "Success") {+ setState({ status: "created", url: result.value.url });+ return;+ }+ if (isAtomCommandInterrupted(result)) {+ setState({ status: "idle" });+ return;+ }+ const error = squashAtomCommandFailure(result);+ setState({+ status: "failed",+ message: error instanceof Error ? error.message : "Could not create a guest link.",+ });+ };++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && state.status !== "creating") onClose();+ }}+ >+ <DialogPopup className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Share with guest</DialogTitle>+ <DialogDescription>+ The guest sees the thread as you do, including command output and the agent's+ reasoning. Each message they send waits for you.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel>+ {state.status === "created" ? (+ <div className="flex items-center gap-2">+ <Input+ readOnly+ aria-label="Guest link"+ value={state.url}+ onFocus={(event) => event.currentTarget.select()}+ />+ <Button size="sm" variant="outline" onClick={() => copyToClipboard(state.url)}>+ {isCopied ? <CheckIcon /> : <CopyIcon />}+ {isCopied ? "Copied" : "Copy"}+ </Button>+ </div>+ ) : (+ <p className="text-muted-foreground text-sm">+ {activeShare !== null+ ? "A new link ends the current one."+ : "The link works once and expires in 24 hours."}+ </p>+ )}+ {state.status === "failed" ? (+ <p role="alert" className="text-destructive text-xs">+ {state.message}+ </p>+ ) : null}+ </DialogPanel>+ <DialogFooter>+ {state.status === "created" ? (+ <Button size="sm" onClick={onClose}>+ Done+ </Button>+ ) : (+ <>+ <Button+ variant="outline"+ size="sm"+ onClick={onClose}+ disabled={state.status === "creating"}+ >+ Cancel+ </Button>+ <Button+ size="sm"+ onClick={() => void create()}+ disabled={!canCreate || state.status === "creating"}+ >+ {state.status === "creating" ? "Creating..." : "Create link"}+ </Button>+ </>+ )}+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ );+}++/** Header status for a shared thread, with the way to end the share. */+export function GuestShareIndicator({ threadRef }: { readonly threadRef: ScopedThreadRef }) {+ const share = useThreadGuestShare(threadRef);+ const closeGuestShare = useOrchestrationCommand(threadEnvironment.closeGuestShare, {+ label: "stop guest share",+ });+ const [closing, setClosing] = useState(false);+ if (share === null) return null;+ return (+ <div className="flex shrink-0 items-center gap-1 text-muted-foreground text-xs">+ <UserIcon aria-hidden className="size-3.5" />+ <GuestShareStatus share={share} />+ <Button+ size="xs"+ variant="ghost-muted"+ disabled={closing}+ onClick={async () => {+ setClosing(true);+ await closeGuestShare({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId },+ });+ setClosing(false);+ }}+ >+ Stop sharing+ </Button>+ </div>+ );+}++function GuestShareStatus({ share }: { readonly share: ThreadGuestShare }) {+ const nowMinute = useNowMinute();+ // The share stays on the thread after it expires, until the owner clears it.+ if (share.expiresAt.slice(0, 16) <= nowMinute) return <span>Guest link expired</span>;+ return (+ <span>{share.guestName !== null ? `${share.guestName} is a guest` : "Guest link active"}</span>+ );+}++/**+ * A guest's messages wait at the end of the timeline until the owner sends or dismisses each one.+ * Sent ones then show in the timeline as normal user messages with the guest's name.+ */+export function GuestPendingMessages({+ threadRef,+ onImageExpand,+ onFileOpen,+}: {+ readonly threadRef: ScopedThreadRef;+ readonly onImageExpand: (preview: ExpandedImagePreview) => void;+ readonly onFileOpen: (attachment: ChatFileAttachment) => void;+}) {+ const share = useThreadGuestShare(threadRef);+ const canOperate = useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope);+ const resolveGuestMessage = useOrchestrationCommand(threadEnvironment.resolveGuestMessage, {+ label: "resolve guest message",+ });+ const [busyIds, setBusyIds] = useState<ReadonlySet<GuestMessageId>>(new Set());+ const pending = share?.messages.filter((message) => message.status === "pending") ?? [];+ // The files are the thread's attachments, which the owner's environment serves like any other.+ const images = pending.flatMap((message) => message.attachments ?? []).filter(isImageAttachment);+ const imageUrls = useAssetUrls(+ threadRef.environmentId,+ images.map((image) => ({ _tag: "attachment" as const, attachmentId: image.id })),+ );+ const imageUrlById = new Map(+ images.flatMap((image, index) => {+ const url = imageUrls[index];+ return url ? [[image.id, url] as const] : [];+ }),+ );+ if (share === null || pending.length === 0) return null;+ const guestName = share.guestName ?? "Guest";+ const openImage = (attachment: ChatAttachment) => {+ const preview = buildExpandedImagePreview(+ images.map((image) => ({ ...image, previewUrl: imageUrlById.get(image.id) ?? "" })),+ attachment.id,+ );+ if (preview) onImageExpand(preview);+ };++ const resolve = async (guestMessageId: GuestMessageId, decision: "send" | "dismiss") => {+ setBusyIds((ids) => new Set(ids).add(guestMessageId));+ await resolveGuestMessage({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId, guestMessageId, decision },+ });+ setBusyIds((ids) => {+ const next = new Set(ids);+ next.delete(guestMessageId);+ return next;+ });+ };++ return (+ <ol+ className="chat-content-lane flex flex-col gap-4 pb-4"+ aria-label={`${pending.length} guest message${pending.length === 1 ? "" : "s"} waiting`}+ aria-live="polite"+ >+ {pending.map((message) => {+ const busy = busyIds.has(message.id);+ return (+ <li key={message.id} className="flex flex-col items-end gap-1">+ <GuestMessageName name={guestName} />+ <div+ className={cn(+ "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-foreground",+ guestBubbleClassName(true),+ )}+ >+ <GuestMessageAttachments+ attachments={message.attachments ?? []}+ imageUrl={(attachment) => imageUrlById.get(attachment.id)}+ onOpenImage={openImage}+ onOpenFile={onFileOpen}+ />+ {message.text ? (+ <p className="text-sm leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]">+ {message.text}+ </p>+ ) : null}+ </div>+ {canOperate ? (+ <div className="flex items-center gap-1 pe-1">+ <Button+ size="xs"+ variant="ghost-muted"+ disabled={busy}+ aria-label={`Dismiss message from ${guestName}`}+ onClick={() => void resolve(message.id, "dismiss")}+ >+ Dismiss+ </Button>+ <Button+ size="xs"+ disabled={busy}+ aria-label={`Send message from ${guestName}`}+ onClick={() => void resolve(message.id, "send")}+ >+ Send+ </Button>+ </div>+ ) : null}+ </li>+ );+ })}+ </ol>+ );+}diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex ee61f27e20c..6da2d5c6f03 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -212,15 +212,17 @@ interface MessagesTimelineProps {paintOnly?: boolean;/** Off where another region already speaks the thread's status, like a subagent's bar. */announceTurnStatus?: boolean;- onOpenTurnDiff: (runId: RunId, filePath?: string) => void;+ onOpenTurnDiff?: (runId: RunId, filePath?: string) => void;onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;+ renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];+ turnItemSource?: TimelineRowSharedState["turnItemSource"];parentThreadLink?: {readonly threadId: ThreadId;readonly title: string;} | null;/** Set on a workflow coordinator's thread: its script message renders as this opening. */workflowOpening?: WorkflowOpening | null;- onForkFromRun: (input: {+ onForkFromRun?: (input: {readonly sourceThreadId: ThreadId;readonly runId: RunId;}) => Promise<void>;@@ -328,6 +330,8 @@ const ConversationTimeline = memo(function ConversationTimeline({announceTurnStatus = true,onOpenTurnDiff,onOpenThread,+ renderHtmlRender,+ turnItemSource,parentThreadLink = null,workflowOpening = null,onForkFromRun,@@ -931,6 +935,8 @@ const ConversationTimeline = memo(function ConversationTimeline({openPullRequest,onOpenTurnDiff,onOpenThread,+ renderHtmlRender,+ turnItemSource,workflowOpening,onForkFromRun,onRollbackCheckpoint,diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsxindex 15ea2318ba6..98c7de52f1b 100644--- a/apps/web/src/components/chat/QueuedRunsControl.tsx+++ b/apps/web/src/components/chat/QueuedRunsControl.tsx@@ -119,12 +119,15 @@ export function QueuedRunsControl({(message) => message.inputIntent === "queued_turn" && !acknowledgedMessageIds.has(message.id),);const items = [- ...queued.map(({ run, text, attachments }, serverIndex) => ({+ ...queued.map(({ run, text, attachments, context }, serverIndex) => ({key: run.id,runId: run.id,messageId: run.userMessageId,serverIndex,text,+ // A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.+ editable: context?.guest === undefined,+ guestName: context?.guest?.name,attachments,thumbnails: attachments.filter((attachment) => attachment.type === "image")@@ -141,6 +144,8 @@ export function QueuedRunsControl({messageId: null,serverIndex: null,text: message.text,+ editable: true,+ guestName: undefined,attachments: [] as ReadonlyArray<ContractChatAttachment>,thumbnails: (message.attachments ?? []).filter(isImageAttachment)@@ -202,7 +207,14 @@ export function QueuedRunsControl({// moving the caret inside that draft.editLatest(repeat) {const latest = queued.at(-1);- if (!latest || props.editingRunId !== null || busyRunId !== null) return false;+ if (+ !latest ||+ latest.context?.guest !== undefined ||+ props.editingRunId !== null ||+ busyRunId !== null+ ) {+ return false;+ }if (!repeat) {setExpanded(true);props.onEditQueuedRun({@@ -380,6 +392,9 @@ export function QueuedRunsControl({))}</span>) : null}+ {item.guestName === undefined ? null : (+ <span className="shrink-0 text-guest-foreground">{item.guestName}</span>+ )}<Tooltip><TooltipTrigger render={<span className="min-w-0 flex-1 truncate" />}>{previewText}@@ -408,7 +423,9 @@ export function QueuedRunsControl({size="icon-xs"variant="ghost-muted"aria-label="Edit queued message"- disabled={item.runId === null || busyRunId !== null}+ disabled={+ item.runId === null || !item.editable || busyRunId !== null+ }onClick={() => {if (item.runId !== null && item.messageId !== null) {props.onEditQueuedRun({diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsxindex 6f99213057f..89b52ae5c5c 100644--- a/apps/web/src/components/chat/TimelineAssistantRows.tsx+++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx@@ -53,12 +53,14 @@ export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind/></AssistantCitationSource></div>- <AssistantChangedFilesSection- turnSummary={row.assistantTurnDiffSummary}- routeThreadKey={ctx.routeThreadKey}- resolvedTheme={ctx.resolvedTheme}- onOpenTurnDiff={ctx.onOpenTurnDiff}- />+ {ctx.onOpenTurnDiff ? (+ <AssistantChangedFilesSection+ turnSummary={row.assistantTurnDiffSummary}+ routeThreadKey={ctx.routeThreadKey}+ resolvedTheme={ctx.resolvedTheme}+ onOpenTurnDiff={ctx.onOpenTurnDiff}+ />+ ) : null}{row.showAssistantMeta ? (<AssistantMessageMetaclassName="mt-1.5"@@ -90,7 +92,8 @@ function AssistantForkButton({capabilities: support.providerSession?.capabilities,});- if (!canFork || projectedItem.item.runId === null) return null;+ const onForkFromRun = ctx.onForkFromRun;+ if (!canFork || onForkFromRun === undefined || projectedItem.item.runId === null) return null;const runId = projectedItem.item.runId;return (@@ -104,9 +107,9 @@ function AssistantForkButton({disabled={busy}onClick={() => {setBusy(true);- void ctx- .onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId })- .finally(() => setBusy(false));+ void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally(+ () => setBusy(false),+ );}}aria-label="Fork from this response"/>@@ -244,6 +247,9 @@ export function HtmlRenderTimelineRow({const { onAppFullscreenChange } = ctx;const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);+ if (ctx.renderHtmlRender) {+ return <div className="min-w-0 px-1">{ctx.renderHtmlRender(row)}</div>;+ }return (<div className="min-w-0 px-1"><HtmlRenderFramediff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsxindex 0fb9ac7f66c..5a24df014ae 100644--- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx+++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx@@ -42,6 +42,7 @@ import {SNAP_SHOT_ATTACHMENT_FRAME_CLASS,SnapShotAttachmentDetails,} from "./SnapShotAttachmentDetails";+import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle";import { MessageCopyButton } from "./MessageCopyButton";import { promptLinkFor } from "../promptLinks/copyPromptLink";import { PierreEntryIcon } from "./PierreEntryIcon";@@ -303,7 +304,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"? { environmentId: ctx.activeThreadEnvironmentId, threadId: senderThreadId }: null,);- const resolvedContext = resolveUserMessageContext(row.message);+ const resolvedContext = resolveUserMessageContext(+ userMessage.attribution === "guest" ? { ...row.message, text: userMessage.text } : row.message,+ );const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));const revertTurnCount = row.revertTurnCount;const chippedAttachmentIds = new Set(@@ -427,13 +430,20 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"Sent by T3 Code</p>) : null}+ {/* The row's heading already names the guest for screen readers. */}+ {userMessage.guestName !== undefined ? (+ <div aria-hidden>+ <GuestMessageName name={userMessage.guestName} />+ </div>+ ) : null}{row.message.inputIntent === "steer" ||row.message.inputIntent === "promoted_queued_to_steer" ? (<UserMessageIntentMarker intent={row.message.inputIntent} />) : null}<divclassName={cn(- "relative min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",+ "relative min-w-0 max-w-[80%] rounded-2xl text-message-foreground",+ userMessage.attribution === "guest" ? guestBubbleClassName(false) : "bg-message",!folded && "p-3",folded && expanded && "w-full",)}@@ -457,7 +467,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"folded && !ctx.findActive && "max-h-96 overflow-auto",)}>- <MessageAuthorHeading>You</MessageAuthorHeading>+ <MessageAuthorHeading>+ {userMessage.guestName === undefined ? "You" : `${userMessage.guestName} (guest)`}+ </MessageAuthorHeading>{(regularImages.length > 0 || userVideos.length > 0) && (<div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">{regularImages.map((image) => (diff --git a/apps/web/src/components/chat/TimelineV2EventRow.tsx b/apps/web/src/components/chat/TimelineV2EventRow.tsxindex a4d2adf902f..9a64ca0f031 100644--- a/apps/web/src/components/chat/TimelineV2EventRow.tsx+++ b/apps/web/src/components/chat/TimelineV2EventRow.tsx@@ -126,6 +126,7 @@ export function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind:onOpenTurnDiff={ctx.onOpenTurnDiff}onRollbackCheckpoint={ctx.onRollbackCheckpoint}onImageExpand={ctx.onImageExpand}+ source={ctx.turnItemSource}/></div></div>@@ -201,6 +202,7 @@ export function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind:onOpenTurnDiff={ctx.onOpenTurnDiff}onRollbackCheckpoint={ctx.onRollbackCheckpoint}onImageExpand={ctx.onImageExpand}+ source={ctx.turnItemSource}/></div></div>diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsxindex 457e960e9fb..76daf03c106 100644--- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx+++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx@@ -534,6 +534,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {onOpenTurnDiff={ctx.onOpenTurnDiff}onRollbackCheckpoint={ctx.onRollbackCheckpoint}onImageExpand={ctx.onImageExpand}+ source={ctx.turnItemSource}/>) : (<>@@ -545,6 +546,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {projectedItem={workEntry.projectedItem}environmentId={ctx.activeThreadEnvironmentId}onImageExpand={onImageExpand}+ source={ctx.turnItemSource}/>) : null}</>diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsxindex a93e8a5b611..b0727a1599f 100644--- a/apps/web/src/components/chat/V2ItemInspector.tsx+++ b/apps/web/src/components/chat/V2ItemInspector.tsx@@ -31,6 +31,7 @@ import { CommandOutputPanel, useCommandOutputStreaming } from "./CommandOutputPaimport { resolveExternalWebLinkHref } from "./externalLinkContextMenu";import type { ExpandedImagePreview } from "./ExpandedImagePreview";import { ShellCommandBlock } from "./ShellCommandBlock";+import type { TurnItemSource } from "./timelineRowContext";interface V2ItemInspectorProps {readonly projectedItem: OrchestrationV2ProjectedTurnItem;@@ -38,12 +39,13 @@ interface V2ItemInspectorProps {readonly cwd?: string | undefined;readonly workspaceRoot?: string | undefined;readonly onOpenThread: (threadId: ThreadId) => void;- readonly onOpenTurnDiff: (runId: RunId, filePath?: string) => void;+ readonly onOpenTurnDiff?: ((runId: RunId, filePath?: string) => void) | undefined;readonly onRollbackCheckpoint?: (input: {readonly checkpointId: string;readonly scopeId: string;}) => void;readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;+ readonly source?: TurnItemSource | undefined;}function SyntaxTokens({@@ -112,6 +114,7 @@ function StructuredValue({function useFetchedTurnItem(projectedItem: OrchestrationV2ProjectedTurnItem,environmentId: EnvironmentId,+ source: TurnItemSource | undefined,skip = false,) {const wireItem = projectedItem.item;@@ -125,6 +128,7 @@ function useFetchedTurnItem(revision: turnItemDetailRevision(wireItem),}: null,+ source?.detail,);const fetchedItem = detail.data?.item;const item = fetchedItem?.type === wireItem.type ? fetchedItem : wireItem;@@ -188,8 +192,9 @@ export function FetchedToolOutput(props: {readonly projectedItem: OrchestrationV2ProjectedTurnItem;readonly environmentId: EnvironmentId;readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;+ readonly source?: TurnItemSource | undefined;}) {- const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId);+ const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId, props.source);return (<div className={cn("mt-1.5 space-y-1.5", monoClassName)}><ToolOutput {...output} onImageExpand={props.onImageExpand} />@@ -236,10 +241,16 @@ function ToolCallBody(export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) {// Command rows stream their output, including the final output, from the server.+ const environmentStreamsOutput = useCommandOutputStreaming(props.environmentId);const streamsOutput =- useCommandOutputStreaming(props.environmentId) &&+ (props.source !== undefined || environmentStreamsOutput) &&props.projectedItem.item.type === "command_execution";- const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId, streamsOutput);+ const fetched = useFetchedTurnItem(+ props.projectedItem,+ props.environmentId,+ props.source,+ streamsOutput,+ );const item = fetched.item;const outputState = fetched.output;const support = useV2ItemSupport({@@ -275,6 +286,7 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspecenvironmentId={props.environmentId}threadId={props.projectedItem.sourceThreadId}itemId={props.projectedItem.sourceItemId}+ source={props.source?.commandOutput}/>) : undefined}@@ -293,11 +305,11 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec<span className="text-diff-deletion">-{formatDiffCount(item.deletions ?? 0)}</span></span>) : null}- {item.runId !== null ? (+ {item.runId !== null && props.onOpenTurnDiff ? (<Buttonsize="xs"variant="outline"- onClick={() => props.onOpenTurnDiff(item.runId!, item.fileName)}+ onClick={() => props.onOpenTurnDiff?.(item.runId!, item.fileName)}>Open diff</Button>@@ -386,7 +398,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec{item.type === "approval_request" ? <StructuredValue value={item.prompt} /> : null}{item.type === "user_input_request" ? (- <StructuredValue value={item.questions.map((question) => question.question).join("\n\n")} />+ <StructuredValue+ value={item.questions+ .map((question) =>+ [question.question, ...question.options.map((option) => `• ${option.label}`)].join(+ "\n",+ ),+ )+ .join("\n\n")}+ />) : null}{item.type === "notification" ? <StructuredValue value={item.detail} /> : null}{item.type === "system_notice" ? <StructuredValue value={item.message} /> : null}diff --git a/apps/web/src/components/chat/guestMessageStyle.tsx b/apps/web/src/components/chat/guestMessageStyle.tsxnew file mode 100644index 00000000000..90e49994f8e--- /dev/null+++ b/apps/web/src/components/chat/guestMessageStyle.tsx@@ -0,0 +1,14 @@+/** Bubble classes for a guest's message. A pending one has a dashed edge and no fill. */+export function guestBubbleClassName(pending: boolean): string {+ return pending ? "border border-dashed border-guest/50 bg-transparent" : "bg-guest-surface";+}++/** The guest's name above their message, where "Sent by T3 Code" sits for server messages. */+export function GuestMessageName({ name }: { readonly name: string }) {+ return (+ <p className="me-1 text-2xs text-guest-foreground">+ {name}+ <span className="sr-only"> (guest)</span>+ </p>+ );+}diff --git a/apps/web/src/components/chat/guestShareAvailability.ts b/apps/web/src/components/chat/guestShareAvailability.tsnew file mode 100644index 00000000000..618b8f042e4--- /dev/null+++ b/apps/web/src/components/chat/guestShareAvailability.ts@@ -0,0 +1,18 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { Atom } from "effect/reactivity";++import { environmentPresentations } from "~/state/presentation";+import { serverEnvironment } from "~/state/server";++/**+ * Whether this environment offers "Share with guest": the user may create links there, and its+ * Guest links beta is on (Settings > Beta). The server refuses links while the beta is off.+ */+export const canShareWithGuestAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make(+ (get) =>+ get(serverEnvironment.createGuestShare.permissionAtom(environmentId)) &&+ get(environmentPresentations.serverConfigsAtom).get(environmentId)?.settings+ .guestSharingEnabled === true,+ ).pipe(Atom.withLabel(`guest-share:available:${environmentId}`)),+);diff --git a/apps/web/src/components/chat/guestShareDialogState.ts b/apps/web/src/components/chat/guestShareDialogState.tsnew file mode 100644index 00000000000..f8d0e5d095f--- /dev/null+++ b/apps/web/src/components/chat/guestShareDialogState.ts@@ -0,0 +1,17 @@+import type { ScopedThreadRef } from "@t3tools/contracts";+import { Atom } from "effect/reactivity";++import { appAtomRegistry } from "~/rpc/atomRegistry";++/**+ * Which thread has the guest share dialog open. The thread menu and the command palette both+ * close as their command runs, so the chat view renders the dialog once.+ */+export const guestShareDialogThreadAtom = Atom.make<ScopedThreadRef | null>(null).pipe(+ Atom.keepAlive,+ Atom.withLabel("guest-share:dialog-thread"),+);++export function openGuestShareDialog(threadRef: ScopedThreadRef): void {+ appAtomRegistry.set(guestShareDialogThreadAtom, threadRef);+}diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.tsindex fdfb833ecc6..aa0c919ab10 100644--- a/apps/web/src/components/chat/timelineRowContext.ts+++ b/apps/web/src/components/chat/timelineRowContext.ts@@ -8,9 +8,12 @@ import {type ServerProviderSkill,type RunId,ThreadId,+ type TurnItemId,} from "@t3tools/contracts";+import type { AsyncResult, Atom } from "effect/reactivity";+import type { CommandOutputView } from "@t3tools/client-runtime/state/command-output";import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";-import { createContext, type MouseEvent } from "react";+import { createContext, type MouseEvent, type ReactNode } from "react";import { type LegendListRef } from "@legendapp/list/react";import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";import { type ChatFileAttachment } from "../../types";@@ -18,8 +21,21 @@ import { ExpandedImagePreview } from "./ExpandedImagePreview";import { type AssistantCitationTarget } from "./AssistantCitationSource";import { type MessagesTimelineRow, type WorkGroupScrollAnchor } from "./MessagesTimeline.logic";import { type TimestampFormat } from "@t3tools/contracts/settings";+import type { TurnItemDetailSource } from "../../state/queries";import { type HandoffTimelineRun } from "./V2LifecycleRow";+/**+ * Where an expanded row reads an item's detail and a command's output. The owner's rows read them+ * from the environment; the guest page reads them through its own routes.+ */+export interface TurnItemSource {+ readonly detail: TurnItemDetailSource;+ readonly commandOutput: (target: {+ readonly threadId: ThreadId;+ readonly itemId: TurnItemId;+ }) => Atom.Atom<AsyncResult.AsyncResult<CommandOutputView, unknown>>;+}+export interface TimelineRowSharedState {citationRequest: AssistantCitationTarget | null;listRef: React.RefObject<LegendListRef | null>;@@ -40,13 +56,21 @@ export interface TimelineRowSharedState {findActive: boolean;onImageExpand: (preview: ExpandedImagePreview) => void;displayThreadKey?: string;- onOpenTurnDiff: (runId: RunId, filePath?: string) => void;+ /** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */+ onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined;+ /**+ * Draws a published HTML visual. Unset, the row loads it from the environment; the guest page+ * loads it through its own route.+ */+ renderHtmlRender: ((row: Extract<TimelineRow, { kind: "html-render" }>) => ReactNode) | undefined;+ /** Unset, expanded rows read detail and command output from the environment. */+ turnItemSource: TurnItemSource | undefined;onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;workflowOpening: WorkflowOpening | null;- onForkFromRun: (input: {- readonly sourceThreadId: ThreadId;- readonly runId: RunId;- }) => Promise<void>;+ /** Absent hides "Fork from this response", as in the guest view. */+ onForkFromRun:+ | ((input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => Promise<void>)+ | undefined;onRollbackCheckpoint: (input: {readonly checkpointId: string;readonly scopeId: string;diff --git a/apps/web/src/components/guest/GuestHtmlRender.tsx b/apps/web/src/components/guest/GuestHtmlRender.tsxnew file mode 100644index 00000000000..75b7445ac6e--- /dev/null+++ b/apps/web/src/components/guest/GuestHtmlRender.tsx@@ -0,0 +1,93 @@+import { GUEST_RENDER_ROUTE, GUEST_SHARE_PARAM } from "@t3tools/contracts";+import {+ type HtmlRenderReference,+ HTML_RENDER_COLUMN_WIDTH,+ htmlRenderFrameHeight,+ htmlRenderResult,+ htmlRenderThemeFragment,+ htmlRenderThemeMessage,+ readHtmlRenderContentHeight,+ readHtmlRenderLinkRequest,+} from "@t3tools/shared/htmlRender";+import { useEffect, useLayoutEffect, useRef, useState } from "react";++import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";+import { observeResize } from "~/lib/observeResize";++/**+ * A visual the agent published, as the guest sees it. The server sends it with a sandbox CSP and+ * the frame is sandboxed too, so the page runs scripts in an opaque origin. It can size itself+ * and ask to open a web link; it cannot reach the guest's session.+ */+export function GuestHtmlRender({+ itemId,+ reference,+ shareId,+}: {+ readonly itemId: string;+ readonly reference: HtmlRenderReference;+ readonly shareId: string;+}) {+ const theme = useHtmlRenderTheme();+ const boxRef = useRef<HTMLDivElement>(null);+ const frameRef = useRef<HTMLIFrameElement>(null);+ const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);+ const [contentHeight, setContentHeight] = useState<number>();+ // The theme rides in the fragment for the first paint; later changes are posted.+ const [src] = useState(+ () =>+ `${GUEST_RENDER_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}${htmlRenderThemeFragment(theme)}`,+ );+ useLayoutEffect(() => {+ const box = boxRef.current;+ if (!box) return;+ setWidth(box.clientWidth);+ return observeResize(box, ([entry]) => {+ if (entry) setWidth(entry.contentRect.width);+ });+ }, []);+ useEffect(() => {+ frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");+ }, [theme]);+ useEffect(() => {+ const onMessage = (event: MessageEvent) => {+ const frame = frameRef.current;+ if (frame === null || event.source !== frame.contentWindow) return;+ const height = readHtmlRenderContentHeight(event.data);+ if (height !== undefined) {+ setContentHeight(height);+ return;+ }+ // Only while the reader is using this frame, so a page cannot open links on its own.+ const link = readHtmlRenderLinkRequest(event.data);+ if (+ link === undefined ||+ document.activeElement !== frame ||+ navigator.userActivation?.isActive === false+ ) {+ return;+ }+ window.open(link.url, "_blank", "noopener,noreferrer");+ frame.contentWindow?.postMessage(htmlRenderResult(link.id), "*");+ };+ window.addEventListener("message", onMessage);+ return () => window.removeEventListener("message", onMessage);+ }, []);++ return (+ <div+ ref={boxRef}+ style={{+ height: htmlRenderFrameHeight(reference, width, contentHeight),+ }}+ >+ <iframe+ ref={frameRef}+ src={src}+ title={reference.title}+ sandbox="allow-scripts allow-forms allow-popups allow-downloads"+ className="block size-full rounded-lg border border-border"+ />+ </div>+ );+}diff --git a/apps/web/src/components/guest/GuestPage.browser.test.tsx b/apps/web/src/components/guest/GuestPage.browser.test.tsxnew file mode 100644index 00000000000..f3668478edb--- /dev/null+++ b/apps/web/src/components/guest/GuestPage.browser.test.tsx@@ -0,0 +1,400 @@+import {+ EventId,+ GUEST_COMMAND_OUTPUT_ROUTE,+ GUEST_RENDER_ROUTE,+ GuestMessageId,+ GuestShareId,+ GuestStreamEvent,+ MessageId,+ ProviderDriverKind,+ RunId,+ TurnItemId,+ type GuestShareView,+ type OrchestrationV2Run,+ type OrchestrationV2TurnItem,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Schema from "effect/Schema";+import { describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import "~/index.css";++import { render } from "../../../test/render";+import { makeThreadProjectionFixture } from "../../test-fixtures";+import { GuestPage } from "./GuestPage";++const SHARE_ID = "share-1";+const encodeEvent = Schema.encodeSync(Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)));++const fixture = makeThreadProjectionFixture();+const threadId = fixture.thread.id;+const started = DateTime.makeUnsafe("2026-10-23T10:00:00.000Z");+const finished = DateTime.makeUnsafe("2026-10-23T10:00:05.000Z");++const run = (id: string, ordinal: number, status: OrchestrationV2Run["status"]) =>+ ({+ id: RunId.make(id),+ threadId,+ ordinal,+ providerInstanceId: fixture.thread.providerInstanceId,+ modelSelection: fixture.thread.modelSelection,+ providerThreadId: null,+ userMessageId: MessageId.make(`user-${id}`),+ rootNodeId: null,+ activeAttemptId: null,+ status,+ requestedAt: started,+ startedAt: started,+ completedAt: status === "running" ? null : finished,+ checkpointId: null,+ contextHandoffId: null,+ }) satisfies OrchestrationV2Run;++const itemBase = (id: string, ordinal: number, runId = "run-1") => ({+ id: TurnItemId.make(id),+ threadId,+ runId: RunId.make(runId),+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ status: "completed" as const,+ title: null,+ startedAt: started,+ completedAt: finished,+ updatedAt: finished,+});++const reply = (id: string, ordinal: number, text: string, runId?: string) =>+ ({+ ...itemBase(id, ordinal, runId),+ type: "assistant_message",+ messageId: MessageId.make(id),+ text,+ streaming: false,+ }) satisfies OrchestrationV2TurnItem;++const items: ReadonlyArray<OrchestrationV2TurnItem> = [+ {+ ...itemBase("user", 0),+ type: "user_message",+ createdBy: "user",+ creationSource: "web",+ messageId: MessageId.make("user"),+ inputIntent: "turn_start",+ text: "Run the checks",+ attachments: [],+ },+ // As the owner's stream sends it: the output loads when the row expands.+ {+ ...itemBase("command", 1),+ type: "command_execution",+ input: "vp run check:changed",+ outputOmitted: true,+ exitCode: 0,+ },+ {+ ...itemBase("visual", 2),+ type: "dynamic_tool",+ toolName: "mcp__t3-code__html_render",+ input: null,+ output: { htmlRender: { attachmentId: "thread-a-1", title: "Chart", height: 200 } },+ },+ reply("reply", 3, "All checks pass."),+];++const view: GuestShareView = {+ shareId: GuestShareId.make(SHARE_ID),+ title: "Fix login",+ guestName: "Sam",+ expiresAt: "2026-10-24T10:00:00.000Z",+ messages: [],+ model: { driver: ProviderDriverKind.make("codex"), name: "GPT-5.4", shortName: "5.4" },+};++/** The stream's opening, as the server sends it: the share, then the owner's snapshot. */+const opening = (+ runs: ReadonlyArray<OrchestrationV2Run>,+ turnItems: ReadonlyArray<OrchestrationV2TurnItem>,+): ReadonlyArray<GuestStreamEvent> => [+ { type: "view", view },+ {+ type: "thread",+ item: {+ kind: "snapshot",+ snapshotSequence: 1,+ projection: {+ ...fixture,+ runs,+ turnItems,+ visibleTurnItems: turnItems.map((item, position) => ({+ position,+ visibility: "local",+ sourceThreadId: threadId,+ sourceItemId: item.id,+ item,+ })),+ },+ },+ },+];++/** One of the owner's thread events, numbered after the snapshot. */+const threadEvent = (+ sequence: number,+ event:+ | { readonly type: "turn-item.updated"; readonly payload: OrchestrationV2TurnItem }+ | { readonly type: "run.updated"; readonly payload: OrchestrationV2Run },+): GuestStreamEvent => {+ const common = {+ id: EventId.make(`event-${sequence}`),+ threadId,+ providerInstanceId: fixture.thread.providerInstanceId,+ occurredAt: finished,+ };+ return {+ type: "thread",+ item: {+ kind: "event",+ sequence,+ event:+ event.type === "run.updated"+ ? { ...common, type: "run.updated", runId: event.payload.id, payload: event.payload }+ : {+ ...common,+ type: "turn-item.updated",+ driver: ProviderDriverKind.make("codex"),+ payload: event.payload,+ },+ },+ };+};++const finalOutput = JSON.stringify({+ kind: "replace",+ text: "4 files checked\n",+ truncated: false,+ running: false,+});++/**+ * Delivers the opening as soon as the page subscribes, or a command's final output. `sources`+ * collects the streams, so a test can send more events.+ */+function fakeEventSource(+ events: ReadonlyArray<GuestStreamEvent>,+ sources: Array<EventTarget> = [],+) {+ return class extends EventTarget {+ static readonly CLOSED = 2;+ readyState = 1;+ constructor(readonly url: string) {+ super();+ sources.push(this);+ const frames = url.startsWith(GUEST_COMMAND_OUTPUT_ROUTE)+ ? [finalOutput]+ : events.map((event) => encodeEvent(event));+ queueMicrotask(() => {+ for (const data of frames) this.dispatchEvent(new MessageEvent("message", { data }));+ });+ }+ close() {+ this.readyState = 2;+ }+ };+}++function visit(path: string): Disposable {+ const previous = `${window.location.pathname}${window.location.search}`;+ window.history.replaceState(window.history.state, "", path);+ return {+ [Symbol.dispose]: () => window.history.replaceState(window.history.state, "", previous),+ };+}++describe("GuestPage", () => {+ it("shows the shared thread in the real timeline without opening an environment connection", async () => {+ using _page = visit(`/guest?share=${SHARE_ID}`);+ using _session = vi+ .spyOn(window, "fetch")+ .mockImplementation(async () => new Response(null, { status: 204 }));+ using _stream = vi+ .spyOn(window, "EventSource")+ .mockImplementation(fakeEventSource(opening([run("run-1", 1, "completed")], items)) as never);+ using socket = vi.spyOn(window, "WebSocket");+ const container = document.createElement("div");+ container.style.cssText = "height: 900px; width: 900px; display: flex; flex-direction: column;";+ await using screen = await render(<GuestPage />, { container });++ await expect.element(screen.getByText("All checks pass.")).toBeVisible();+ // A finished turn folds its work, as it does for the owner; the command is inside.+ await userEvent.click(screen.getByRole("button", { name: /Worked for/ }));+ await expect.element(screen.getByText("vp run check:changed")).toBeVisible();+ // Expanding the command shows its output, read through the guest route.+ await userEvent.click(screen.getByText("vp run check:changed"));+ await expect.element(screen.getByText("4 files checked")).toBeVisible();+ await expect+ .element(screen.getByTitle("Chart"))+ .toHaveAttribute(+ "src",+ expect.stringContaining(`${GUEST_RENDER_ROUTE}?share=${SHARE_ID}&item=visual`),+ );+ // Guests cannot act on the thread, so no control offers to.+ expect(screen.container.querySelector('[aria-label="Fork from this response"]')).toBeNull();+ expect(socket).not.toHaveBeenCalled();+ // The composer names the thread's model, as the owner's does, with nothing to pick.+ await expect.element(screen.getByLabelText("Model: 5.4")).toBeVisible();+ });++ it("sends attached files with the message, as form data", async () => {+ using _page = visit(`/guest?share=${SHARE_ID}`);+ using fetchSpy = vi+ .spyOn(window, "fetch")+ .mockImplementation(async () => new Response(null, { status: 204 }));+ using _stream = vi+ .spyOn(window, "EventSource")+ .mockImplementation(fakeEventSource(opening([run("run-1", 1, "completed")], items)) as never);+ await using screen = await render(<GuestPage />);++ await expect.element(screen.getByLabelText("Attach files")).toBeVisible();+ const notes = new File(["hello"], "notes.txt", { type: "text/plain" });+ await userEvent.upload(screen.getByLabelText("Files to attach"), notes);+ await expect.element(screen.getByText("notes.txt")).toBeVisible();+ await userEvent.click(screen.getByRole("button", { name: "Send" }));+ await vi.waitFor(() =>+ expect(fetchSpy).toHaveBeenCalledWith(+ `/api/guest/messages?share=${SHARE_ID}`,+ expect.objectContaining({ method: "POST" }),+ ),+ );+ const body = fetchSpy.mock.calls.find(+ ([url]) => url === `/api/guest/messages?share=${SHARE_ID}`,+ )?.[1]?.body;+ expect(body).toBeInstanceOf(FormData);+ const form = body as FormData;+ expect(form.get("shareId")).toBe(SHARE_ID);+ expect(form.get("text")).toBe("");+ expect((form.get("file") as File).name).toBe("notes.txt");+ // Sent files leave the composer.+ await expect.element(screen.getByText("notes.txt")).not.toBeInTheDocument();+ });++ it("follows the end as replies stream, and shows the guest's own message even after they scrolled up", async () => {+ using _page = visit(`/guest?share=${SHARE_ID}`);+ using _session = vi+ .spyOn(window, "fetch")+ .mockImplementation(async () => new Response(null, { status: 204 }));+ const sources: Array<EventTarget> = [];+ // Enough turns that the thread overflows the page.+ const longItems = Array.from({ length: 12 }, (_, index) =>+ reply(+ `reply-${index}`,+ index,+ `Reply ${index}\n\n${"A long paragraph about the change. ".repeat(20)}`,+ ),+ );+ using _stream = vi+ .spyOn(window, "EventSource")+ .mockImplementation(+ fakeEventSource(opening([run("run-1", 1, "running")], longItems), sources) as never,+ );+ const send = (event: GuestStreamEvent) =>+ sources.at(-1)!.dispatchEvent(new MessageEvent("message", { data: encodeEvent(event) }));+ const container = document.createElement("div");+ container.style.cssText = "height: 600px; width: 900px; display: flex; flex-direction: column;";+ await using screen = await render(<GuestPage />, { container });+ await expect.element(screen.getByText("Reply 11")).toBeInTheDocument();+ const scroller = () =>+ screen.container.querySelector<HTMLElement>(".messages-timeline-scroll")!;+ const expectAtEnd = () =>+ vi.waitFor(() => {+ const node = scroller();+ expect(node.scrollHeight - node.scrollTop - node.clientHeight).toBeLessThan(2);+ });+ await expectAtEnd();++ // A new reply streams in at the end.+ send(+ threadEvent(2, {+ type: "turn-item.updated",+ payload: {+ ...reply(+ "reply-new",+ 20,+ `Newest reply\n\n${"More words as the agent writes. ".repeat(30)}`,+ ),+ streaming: true,+ },+ }),+ );+ await expect.element(screen.getByText("Newest reply")).toBeInTheDocument();+ await expectAtEnd();++ // The guest reads back a little, then sends: their message comes into view anyway, as the+ // owner's own send does.+ const node = scroller();+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: -400, bubbles: true }));+ node.scrollTop = node.scrollTop - 400;+ node.dispatchEvent(new Event("scroll"));+ await expect.element(screen.getByRole("button", { name: /scroll to/i })).toBeVisible();++ // The guest's own message waits at the end for the owner.+ const waiting = {+ id: GuestMessageId.make("guest-1"),+ text: "Can you also check the logout flow?",+ status: "pending" as const,+ submittedAt: "2026-10-23T10:01:00.000Z",+ };+ send({ type: "view", view: { ...view, messages: [waiting] } });+ await expect.element(screen.getByText(waiting.text)).toBeInTheDocument();+ await expectAtEnd();++ // The owner sends it: the run ends, the message becomes a row, and a new run's reply grows.+ const sent = { ...waiting, status: "sent" as const };+ send(threadEvent(3, { type: "run.updated", payload: run("run-1", 1, "completed") }));+ send({ type: "view", view: { ...view, messages: [sent] } });+ send(threadEvent(4, { type: "run.updated", payload: run("run-2", 2, "running") }));+ send(+ threadEvent(5, {+ type: "turn-item.updated",+ payload: {+ ...itemBase("guest-row", 30, "run-2"),+ type: "user_message",+ createdBy: "user",+ creationSource: "web",+ messageId: MessageId.make("guest-row"),+ inputIntent: "turn_start",+ text: `Message from guest Sam, sent by the owner: ${sent.text}`,+ attachments: [],+ context: {+ version: 1,+ guest: { guestMessageId: sent.id, name: "Sam", text: sent.text },+ records: [],+ },+ },+ }),+ );+ await expectAtEnd();+ for (const [index, words] of [10, 40, 120].entries()) {+ send(+ threadEvent(6 + index, {+ type: "turn-item.updated",+ payload: {+ ...reply(+ "logout-reply",+ 31,+ `Logout reply\n\n${"Checking the logout flow now. ".repeat(words)}`,+ "run-2",+ ),+ streaming: true,+ },+ }),+ );+ await expectAtEnd();+ await expect.element(screen.getByText("Logout reply")).toBeInTheDocument();+ }+ });+});diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsxnew file mode 100644index 00000000000..28b28161866--- /dev/null+++ b/apps/web/src/components/guest/GuestPage.tsx@@ -0,0 +1,763 @@+import {+ EnvironmentId,+ GUEST_MESSAGE_MAX_LENGTH,+ GUEST_NAME_MAX_LENGTH,+ GUEST_ROUTE_PREFIX,+ GUEST_SHARE_PARAM,+ GuestMessageId,+ type GuestRedeemRequest,+ type GuestShareView,+ type GuestThreadModel,+ type OrchestrationV2ThreadProjection,+ type ThreadGuestMessage,+ type ThreadGuestMessageStatus,+} from "@t3tools/contracts";+import type { LegendListRef } from "@legendapp/list/react";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";+import {+ deriveRunlessWorkStartedAt,+ deriveThreadActivityRun,+ deriveThreadStructureRuntime,+} from "@t3tools/client-runtime/state/thread-execution";+import { createQuestionHistoryProjector } from "@t3tools/client-runtime/state/thread-requests";+import { ArrowUpIcon, PaperclipIcon, XIcon } from "lucide-react";+import {+ createRef,+ useEffect,+ useReducer,+ useRef,+ useState,+ type ClipboardEvent,+ type FormEvent,+ type KeyboardEvent,+} from "react";++import { useIncrementalTimelineEntries } from "~/hooks/useIncrementalTimelineEntries";+import { useNowMinute } from "~/hooks/useNowMinute";+import { useStableCallback } from "~/hooks/useStableCallback";+import { useTheme } from "~/hooks/useTheme";+import { observeResize } from "~/lib/observeResize";+import { cn } from "~/lib/utils";+import { deriveActiveWorkStartedAt, derivePhase } from "~/session-logic";+import type { ChatComposerHandle } from "../chat/ChatComposer";+import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl";+import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview";+import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";+import { PierreEntryIcon } from "../chat/PierreEntryIcon";+import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";+import { MessagesTimeline } from "../chat/MessagesTimeline";+import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";+import { getTriggerDisplayModelName } from "../chat/providerIconUtils";+import { ScrollToEndButton } from "../chat/TimelineOverlays";+import type { TimelineRow } from "../chat/timelineRowContext";+import { useTimelineFollow } from "../chat/useTimelineFollow";+import { GuestHtmlRender } from "./GuestHtmlRender";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import {+ applyGuestStreamEvent,+ formatGuestExpiry,+ guestAttachmentUrl,+ createGuestAttachmentUrls,+ guestFilesProblem,+ initialGuestStreamState,+ inviteShareId,+ type GuestStreamState,+ parseGuestStreamEvent,+ unplacedGuestMessages,+} from "./guestStream.logic";+import { guestTurnItemSource } from "./guestTurnItemSource";++interface GuestEntry {+ /** Unspent invite from the URL hash, if this load came from a link. */+ readonly credential: string | null;+ readonly shareId: string | null;+}++let capturedEntry: GuestEntry | null = null;++// A reload keeps the tab's session, so it keeps which messages still wait for a row too.+const AWAITING_ROWS_KEY = "t3:guest-awaiting-rows";+const AWAITING_ROWS_LIMIT = 50;++function readAwaitingRowIds(): ReadonlySet<GuestMessageId> {+ try {+ const stored: unknown = JSON.parse(sessionStorage.getItem(AWAITING_ROWS_KEY) ?? "[]");+ return new Set(+ Array.isArray(stored)+ ? stored.filter((id) => typeof id === "string").map((id) => GuestMessageId.make(id))+ : [],+ );+ } catch {+ return new Set();+ }+}++function writeAwaitingRowIds(ids: ReadonlySet<GuestMessageId>) {+ try {+ sessionStorage.setItem(AWAITING_ROWS_KEY, JSON.stringify([...ids].slice(-AWAITING_ROWS_LIMIT)));+ } catch {}+}++/**+ * The invite credential travels in the URL hash so it never reaches a server log. It is read+ * once and removed from history, so it lives only in memory. Opening the page never redeems it:+ * only submitting a name does, so a reload before that leaves the link usable.+ */+function takeGuestEntry(): GuestEntry {+ if (capturedEntry === null) {+ // A malformed fragment is an invalid link, not a crash.+ let credential = "";+ try {+ credential = decodeURIComponent(window.location.hash.slice(1)).trim();+ } catch {}+ const shareId =+ credential !== ""+ ? inviteShareId(credential)+ : new URLSearchParams(window.location.search).get(GUEST_SHARE_PARAM);+ // The share stays in the URL, so a reload or bookmark finds this browser's session for it.+ window.history.replaceState(+ window.history.state,+ "",+ shareId === null+ ? window.location.pathname+ : `${window.location.pathname}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,+ );+ capturedEntry = { credential: credential === "" ? null : credential, shareId };+ }+ return capturedEntry;+}++const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({ message: Schema.String }));++/** Resolves to null on success, or to a message the guest can read. */+async function postGuest(+ path: "redeem" | `messages?${string}`,+ body: typeof GuestRedeemRequest.Encoded | FormData,+): Promise<string | null> {+ try {+ const response = await fetch(+ `${GUEST_ROUTE_PREFIX}/${path}`,+ body instanceof FormData+ ? { method: "POST", body }+ : {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ },+ );+ if (response.ok) return null;+ const json: unknown = await response.json().catch(() => null);+ return Option.match(decodeErrorBody(json), {+ onNone: () => "Something went wrong. Try again.",+ onSome: ({ message }) => message,+ });+ } catch {+ return "Could not reach the server.";+ }+}++const STATUS_LABEL: Record<ThreadGuestMessageStatus, string> = {+ pending: "Waiting for approval",+ sent: "Sent",+ dismissed: "Not sent",+};++/** Same column as the owner's timeline, so both views wrap text at the same width. */+const LANE = "chat-content-lane px-4";++type GuestAccess = "checking" | "session" | "name" | "none";++export function GuestPage() {+ const [{ credential, shareId }] = useState(takeGuestEntry);+ // A browser that already joined this share goes straight back in, even from the spent link.+ // Sessions are per share, so one for another link never stands in for this one.+ const [access, setAccess] = useState<GuestAccess>(shareId === null ? "none" : "checking");+ useEffect(() => {+ if (shareId === null) return;+ let live = true;+ void fetch(`${GUEST_ROUTE_PREFIX}/session?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`)+ .then(+ (response): GuestAccess =>+ response.ok ? "session" : credential !== null ? "name" : "none",+ // Offline: an invite still needs the name form; without one, the stream reports what+ // it finds once the network is back.+ (): GuestAccess => (credential !== null ? "name" : "session"),+ )+ .then((next) => {+ if (live) setAccess(next);+ });+ return () => {+ live = false;+ };+ }, [credential, shareId]);+ // Pasting another guest link into this tab changes only the hash, which does not reload the+ // page; reload so the new invite is read instead of the one already captured.+ useEffect(() => {+ const onHashChange = () => {+ if (window.location.hash !== "") window.location.reload();+ };+ window.addEventListener("hashchange", onHashChange);+ return () => window.removeEventListener("hashchange", onHashChange);+ }, []);++ return (+ <div className="flex h-dvh flex-col bg-background text-foreground">+ {access === "checking" ? (+ <Notice title="Connecting..." />+ ) : access === "name" && credential !== null ? (+ <NameForm+ credential={credential}+ onJoined={() => {+ // The invite is spent; a remount must open the session, not the name form again.+ capturedEntry = { credential: null, shareId };+ setAccess("session");+ }}+ />+ ) : access === "session" && shareId !== null ? (+ <GuestSession shareId={shareId} />+ ) : (+ <Notice+ title="This link has ended or is not valid"+ detail="Ask the owner for a new link. Each link works in one browser."+ />+ )}+ </div>+ );+}++function GuestSession({ shareId }: { readonly shareId: string }) {+ const [stream, dispatch] = useReducer(applyGuestStreamEvent, null, () => ({+ ...initialGuestStreamState,+ awaitingRowIds: readAwaitingRowIds(),+ }));+ useEffect(() => writeAwaitingRowIds(stream.awaitingRowIds), [stream.awaitingRowIds]);+ // EventSource closes for good only on a non-200 response, which the guest routes send for a+ // missing, invalid, or ended session. Network drops reconnect on their own.+ const [rejected, setRejected] = useState(false);++ useEffect(() => {+ if (stream.view) document.title = stream.view.title;+ }, [stream.view]);++ useEffect(() => {+ const source = new EventSource(+ `${GUEST_ROUTE_PREFIX}/stream?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,+ );+ source.addEventListener("message", (message) => {+ const event = parseGuestStreamEvent(message.data);+ if (event === null) return;+ dispatch(event);+ if (event.type === "ended") source.close();+ });+ source.addEventListener("error", () => {+ if (source.readyState === EventSource.CLOSED) setRejected(true);+ });+ return () => source.close();+ }, [shareId]);++ if (stream.ended || (rejected && stream.view !== null)) {+ return <Notice title="This link has ended" detail="The owner stopped sharing this thread." />;+ }+ if (stream.view !== null) {+ if (stream.projection === null) return <Notice title="Connecting..." />;+ return (+ <GuestThread+ view={stream.view}+ projection={stream.projection}+ awaitingRowIds={stream.awaitingRowIds}+ />+ );+ }+ if (!rejected) return <Notice title="Connecting..." />;+ return (+ <Notice+ title="This link has ended or is not valid"+ detail="Ask the owner for a new link. Each link works in one browser."+ />+ );+}++function Notice({ title, detail }: { readonly title: string; readonly detail?: string }) {+ return (+ <div className="m-auto flex max-w-sm flex-col gap-1 p-6 text-center">+ <p className="text-sm font-medium">{title}</p>+ {detail ? <p className="text-xs text-muted-foreground">{detail}</p> : null}+ </div>+ );+}++function NameForm({+ credential,+ onJoined,+}: {+ readonly credential: string;+ readonly onJoined: () => void;+}) {+ const [name, setName] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const submit = async (event: FormEvent) => {+ event.preventDefault();+ const trimmed = name.trim();+ if (trimmed === "" || submitting) return;+ setSubmitting(true);+ const failure = await postGuest("redeem", { credential, name: trimmed });+ setSubmitting(false);+ if (failure === null) onJoined();+ else setError(failure);+ };+ return (+ <form className="m-auto flex w-full max-w-xs flex-col gap-3 p-6" onSubmit={submit}>+ <h1 className="text-base font-medium">Join a shared thread</h1>+ <label className="flex flex-col gap-1.5 text-sm" htmlFor="guest-name">+ Your name+ <Input+ id="guest-name"+ autoFocus+ autoComplete="name"+ maxLength={GUEST_NAME_MAX_LENGTH}+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ </label>+ {error !== null ? (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ ) : null}+ <Button type="submit" disabled={submitting || name.trim() === ""}>+ Join+ </Button>+ <p className="text-xs text-muted-foreground">+ The owner sees your name and approves each message before the agent gets it.+ </p>+ </form>+ );+}++// The timeline needs an environment id to key its rows. Nothing behind it loads on this page;+// see isGuestPage.+const GUEST_ENVIRONMENT_ID = EnvironmentId.make("guest");+const NO_COMPOSER = createRef<ChatComposerHandle>();+const NO_TURN_DIFFS: ReadonlyArray<never> = [];+const NO_OPTIMISTIC_MESSAGES: ReadonlyArray<never> = [];+const ignore = () => {};++/**+ * The owner's timeline, read-only: every action that would reach the owner's machine (fork,+ * revert, diffs, files, other threads, shell) is left out, so its control does not render.+ */+function GuestThread({+ view: { shareId, title, expiresAt, messages, model },+ projection,+ awaitingRowIds,+}: {+ readonly view: GuestShareView;+ readonly projection: OrchestrationV2ThreadProjection;+ readonly awaitingRowIds: GuestStreamState["awaitingRowIds"];+}) {+ // No ":" so the timeline finds no environment thread behind the key.+ const threadKey = `guest-${shareId}`;+ const listRef = useRef<LegendListRef | null>(null);+ const { resolvedTheme } = useTheme();+ // The rest is what ChatView derives from the same projection.+ const [projectQuestionHistory] = useState(() => createQuestionHistoryProjector());+ const items = projectQuestionHistory(projection);+ // Files load through the guest route.+ const [attachmentUrls] = useState(() => createGuestAttachmentUrls(shareId));+ // Expanded rows read detail and command output through the guest routes.+ const [turnItemSource] = useState(() => guestTurnItemSource(shareId));+ const attachmentUrlById = attachmentUrls(items);+ const entries = useIncrementalTimelineEntries(threadKey, {+ visibleTurnItems: items,+ optimisticMessages: NO_OPTIMISTIC_MESSAGES,+ attachmentUrlById,+ attempts: projection.attempts,+ nodes: projection.nodes,+ plans: projection.plans,+ });+ const openFile = useStableCallback((file: { readonly id: string }) =>+ openInNewTab(guestAttachmentUrl(shareId, file.id)),+ );+ const activityRun = deriveThreadActivityRun(projection);+ const runtime = deriveThreadStructureRuntime(projection);+ const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection);+ const isWorking = derivePhase(runtime) === "running" || runlessWorkStartedAt !== null;+ const workStartedAt =+ deriveActiveWorkStartedAt(activityRun, runtime, null) ?? runlessWorkStartedAt;+ const runningRunId = runtime?.activeRunId ?? null;+ const follow = useTimelineFollow({+ legendListRef: listRef,+ composerRef: NO_COMPOSER,+ composerOverlayElement: null,+ composerTimelineInset: 0,+ routeThreadKey: threadKey,+ activeThreadKey: threadKey,+ activeThreadId: undefined,+ // Not a server thread: new turns follow the end instead of anchoring near the top.+ isServerThread: false,+ serverProjection: null,+ threadStatus: "live",+ activeActivityRun: activityRun,+ activeRunningTurnId: runningRunId,+ timelineEntries: entries,+ timelineAnchorMessageId: null,+ setTimelineAnchor: ignore,+ });+ const renderHtmlRender = useStableCallback(+ (row: Extract<TimelineRow, { kind: "html-render" }>) => (+ <GuestHtmlRender itemId={row.id} reference={row.htmlRender} shareId={shareId} />+ ),+ );+ const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds);+ // The guest's waiting messages sit in the list footer, which the list does not follow on its+ // own (the owner's view does the same in ChatView). A new one is the guest's own send, so it+ // comes into view even if they had scrolled up, as the owner's send does. While following, the+ // footer stays in view as it grows, such as when its images load.+ const unplacedKey = unplaced.map((message) => message.id).join(",");+ const previousUnplacedKey = useRef(unplacedKey);+ const following = useRef(follow.timelineLiveFollowEnabled);+ const scrollToEnd = useStableCallback(follow.scrollToEnd);+ useEffect(() => {+ following.current = follow.timelineLiveFollowEnabled;+ const previous = new Set(previousUnplacedKey.current.split(","));+ previousUnplacedKey.current = unplacedKey;+ if (unplacedKey.split(",").some((id) => id !== "" && !previous.has(id))) scrollToEnd(true);+ }, [follow.timelineLiveFollowEnabled, unplacedKey, scrollToEnd, following, previousUnplacedKey]);+ const footerRef = useRef<HTMLOListElement>(null);+ const hasFooter = unplaced.length > 0;+ useEffect(() => {+ const footer = footerRef.current;+ if (!hasFooter || footer === null) return;+ return observeResize(footer, () => {+ if (following.current) scrollToEnd();+ });+ }, [hasFooter, scrollToEnd, following]);+ return (+ <>+ <header className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5">+ <h1 className="min-w-0 flex-1 truncate text-sm font-medium">{title}</h1>+ <ExpiryLabel expiresAt={expiresAt} />+ </header>+ <div className="relative min-h-0 flex-1">+ <MessagesTimeline+ listRef={listRef}+ timelineEntries={entries}+ isWorking={isWorking}+ activeTurnInProgress={isWorking}+ activeTurnStartedAt={workStartedAt}+ latestRun={activityRun}+ runningRunId={runningRunId}+ turnDiffSummaries={NO_TURN_DIFFS}+ runs={projection.runs}+ routeThreadKey={threadKey}+ onOpenThread={ignore}+ onRollbackCheckpoint={ignore}+ supportsConversationRollback={false}+ onRevertToTurnCount={ignore}+ isRevertingCheckpoint={false}+ onImageExpand={openExpandedImage}+ onFileOpen={openFile}+ onFileDownload={openFile}+ renderHtmlRender={renderHtmlRender}+ turnItemSource={turnItemSource}+ activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}+ markdownCwd={undefined}+ resolvedTheme={resolvedTheme}+ timestampFormat="locale"+ workspaceRoot={undefined}+ anchorMessageId={null}+ onAnchorReady={ignore}+ onAnchorSizeChanged={ignore}+ contentInsetEndAdjustment={0}+ emptyPlaceholderInset={0}+ liveFollowEnabled={follow.timelineLiveFollowEnabled}+ onIsAtEndChange={follow.onIsAtEndChangeStable}+ onManualNavigation={follow.cancelTimelineLiveFollowForUserNavigationStable}+ cancelPositionRestoreRef={follow.cancelPositionRestoreRef}+ footer={+ unplaced.length === 0 ? null : (+ <ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">+ {unplaced.map((message) => (+ <li key={message.id}>+ <UnplacedGuestMessage shareId={shareId} message={message} />+ </li>+ ))}+ </ol>+ )+ }+ />+ {follow.showScrollToBottom ? (+ <ScrollToEndButton bottom={4} onScrollToEnd={() => follow.scrollToEnd(true)} />+ ) : null}+ </div>+ <div className={cn(LANE, "shrink-0 pb-4")}>+ <GuestComposer shareId={shareId} model={model} />+ </div>+ </>+ );+}++function ExpiryLabel({ expiresAt }: { readonly expiresAt: string }) {+ const nowMinute = useNowMinute();+ return (+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">+ {formatGuestExpiry(expiresAt, Date.parse(`${nowMinute}Z`))}+ </span>+ );+}++const BUBBLE =+ "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]";++const openInNewTab = (url: string) => window.open(url, "_blank", "noopener,noreferrer");+/** Guests have no image viewer; the browser shows the picture in its own tab. */+const openExpandedImage = (preview: ExpandedImagePreview) => {+ const src = preview.images[preview.index]?.src;+ if (src) openInNewTab(src);+};++/** A guest message the owner has not sent yet, or chose not to send. */+function UnplacedGuestMessage({+ shareId,+ message,+}: {+ readonly shareId: GuestShareView["shareId"];+ readonly message: ThreadGuestMessage;+}) {+ // A dismissed message's files are deleted, so only their names remain.+ const served = message.status !== "dismissed";+ const url = (attachment: { readonly id: string }) => guestAttachmentUrl(shareId, attachment.id);+ return (+ <div className="flex flex-col items-end gap-1">+ <GuestMessageName name="You" />+ <div+ className={cn(+ BUBBLE,+ guestBubbleClassName(message.status !== "sent"),+ message.status === "dismissed" ? "text-muted-foreground" : "text-message-foreground",+ )}+ >+ <GuestMessageAttachments+ attachments={message.attachments ?? []}+ imageUrl={(attachment) => (served ? url(attachment) : undefined)}+ onOpenImage={(attachment) => openInNewTab(url(attachment))}+ {...(served ? { fileHref: url } : {})}+ />+ {message.text ? <span>{message.text}</span> : null}+ </div>+ <p className="me-1 text-2xs text-muted-foreground">{STATUS_LABEL[message.status]}</p>+ </div>+ );+}++/** The thread's model, labeled as the owner's composer labels it, with no way to change it. */+function GuestModelLabel({ model }: { readonly model: GuestThreadModel }) {+ const label = getTriggerDisplayModelName({ slug: model.name, ...model });+ return (+ <ComposerControl+ render={<span />}+ aria-label={`Model: ${label}`}+ className="pointer-events-none min-w-0 shrink"+ >+ {model.driver === null ? null : (+ <ProviderInstanceIcon+ driverKind={model.driver}+ displayName={label}+ className="size-4"+ iconClassName="size-4"+ />+ )}+ <span className="min-w-0 truncate" data-chat-provider-model-picker-label="true">+ {label}+ </span>+ </ComposerControl>+ );+}++interface StagedFile {+ readonly key: string;+ readonly file: File;+}++/** A staged image's thumbnail; its object URL lives as long as the element. */+function StagedImage({ file }: { readonly file: File }) {+ return (+ <img+ alt={file.name}+ className="size-full object-cover"+ ref={(image) => {+ if (!image) return;+ const url = URL.createObjectURL(file);+ image.src = url;+ return () => URL.revokeObjectURL(url);+ }}+ />+ );+}++function GuestComposer({+ shareId,+ model,+}: {+ readonly shareId: GuestShareView["shareId"];+ readonly model: GuestThreadModel;+}) {+ const [text, setText] = useState("");+ const [files, setFiles] = useState<ReadonlyArray<StagedFile>>([]);+ const [sending, setSending] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);+ const nextFileKey = useRef(0);+ const { resolvedTheme } = useTheme();+ const addFiles = (added: ReadonlyArray<File>) => {+ if (added.length === 0) return;+ const next = [+ ...files,+ ...added.map((file) => ({ key: `staged-${nextFileKey.current++}`, file })),+ ];+ const problem = guestFilesProblem(next.map((staged) => staged.file));+ setError(problem);+ if (problem === null) setFiles(next);+ };+ const send = async () => {+ const trimmed = text.trim();+ if ((trimmed === "" && files.length === 0) || sending) return;+ setSending(true);+ const sentFiles = files;+ const form = new FormData();+ form.append("shareId", shareId);+ form.append("text", trimmed);+ for (const staged of sentFiles) form.append("file", staged.file, staged.file.name);+ const failure = await postGuest(+ `messages?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,+ form,+ );+ setSending(false);+ setError(failure);+ // Keep anything typed or attached while the request was in flight.+ if (failure === null) {+ setText((current) => (current.trim() === trimmed ? "" : current));+ setFiles((current) => current.filter((staged) => !sentFiles.includes(staged)));+ }+ };+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ // Same as the app composer: Enter sends, Shift+Enter adds a line, IME composition is left alone.+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault();+ void send();+ }+ };+ // As in the app composer: pasted images attach, and other files attach when no text came along.+ const onPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {+ const pasted = Array.from(event.clipboardData.files);+ const hasImage = pasted.some((file) => file.type.startsWith("image/"));+ if (pasted.length === 0 || (!hasImage && event.clipboardData.getData("text/plain") !== "")) {+ return;+ }+ event.preventDefault();+ addFiles(pasted);+ };+ return (+ <form+ className="flex flex-col gap-2 rounded-3xl border border-border bg-card px-4 pt-3 pb-2.5 shadow-composer dark:shadow-composer-dark"+ onSubmit={(event) => {+ event.preventDefault();+ void send();+ }}+ onDragOver={(event) => {+ if (event.dataTransfer.types.includes("Files")) event.preventDefault();+ }}+ onDrop={(event) => {+ if (event.dataTransfer.files.length === 0) return;+ event.preventDefault();+ addFiles(Array.from(event.dataTransfer.files));+ }}+ >+ {files.length > 0 ? (+ <ul className="flex flex-wrap gap-2" aria-label="Attached files">+ {files.map((staged) => (+ <li+ key={staged.key}+ className="flex h-14 min-w-0 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background/70 pe-1"+ >+ {staged.file.type.startsWith("image/") ? (+ <span className="size-14 shrink-0">+ <StagedImage file={staged.file} />+ </span>+ ) : (+ <span className="flex min-w-0 items-center gap-2 ps-2 text-sm">+ <PierreEntryIcon pathValue={staged.file.name} kind="file" theme={resolvedTheme} />+ <span className="max-w-40 truncate">{staged.file.name}</span>+ <span className="shrink-0 text-xs text-muted-foreground">+ {formatAttachmentSize(staged.file.size)}+ </span>+ </span>+ )}+ <Button+ size="icon-xs"+ variant="ghost-muted"+ aria-label={`Remove ${staged.file.name}`}+ onClick={() => {+ setError(null);+ setFiles((current) => current.filter((candidate) => candidate !== staged));+ }}+ >+ <XIcon />+ </Button>+ </li>+ ))}+ </ul>+ ) : null}+ <textarea+ aria-label="Message"+ placeholder="Message"+ rows={2}+ maxLength={GUEST_MESSAGE_MAX_LENGTH}+ value={text}+ onChange={(event) => setText(event.target.value)}+ onKeyDown={onKeyDown}+ onPaste={onPaste}+ className="max-h-60 min-h-12 w-full resize-none bg-transparent text-sm outline-none field-sizing-content placeholder:text-placeholder"+ />+ <div className="flex items-center gap-3">+ <input+ ref={fileInputRef}+ type="file"+ multiple+ hidden+ aria-label="Files to attach"+ onChange={(event) => {+ addFiles(Array.from(event.target.files ?? []));+ // The same file can be picked again after it is removed.+ event.target.value = "";+ }}+ />+ <ComposerControl aria-label="Attach files" onClick={() => fileInputRef.current?.click()}>+ <ComposerControlIcon icon={PaperclipIcon} />+ </ComposerControl>+ <GuestModelLabel model={model} />+ {error !== null ? (+ <p role="alert" className="min-w-0 flex-1 text-xs text-destructive">+ {error}+ </p>+ ) : (+ <p className="min-w-0 flex-1 truncate text-xs text-muted-foreground">+ The owner approves each message+ </p>+ )}+ <button+ type="submit"+ aria-label="Send"+ disabled={sending || (text.trim() === "" && files.length === 0)}+ className="flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-message-action text-message-action-foreground shadow-xs hover:bg-message-action-hover focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-64"+ >+ <ArrowUpIcon aria-hidden className="size-4" />+ </button>+ </div>+ </form>+ );+}diff --git a/apps/web/src/components/guest/guestStream.logic.test.ts b/apps/web/src/components/guest/guestStream.logic.test.tsnew file mode 100644index 00000000000..fbdf9ce1927--- /dev/null+++ b/apps/web/src/components/guest/guestStream.logic.test.ts@@ -0,0 +1,222 @@+import {+ EventId,+ GuestMessageId,+ GuestShareId,+ MessageId,+ ProviderDriverKind,+ RunId,+ TurnItemId,+ type GuestShareView,+ type GuestStreamEvent,+ type OrchestrationV2TurnItem,+ type ThreadGuestMessage,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import { describe, expect, it } from "vite-plus/test";++import { makeThreadProjectionFixture } from "../../test-fixtures";+import {+ applyGuestStreamEvent,+ formatGuestExpiry,+ guestFilesProblem,+ initialGuestStreamState,+ inviteShareId,+ parseGuestStreamEvent,+ unplacedGuestMessages,+ type GuestStreamState,+} from "./guestStream.logic";++const view: GuestShareView = {+ shareId: GuestShareId.make("share-1"),+ title: "Fix login",+ guestName: "Sam",+ expiresAt: "2026-10-24T00:00:00.000Z",+ messages: [],+ model: { driver: null, name: "gpt-5.4" },+};++const projection = makeThreadProjectionFixture();+const now = DateTime.makeUnsafe("2026-10-23T10:00:00.000Z");++const base = {+ threadId: projection.thread.id,+ runId: RunId.make("run-1"),+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: "completed",+ title: null,+ startedAt: now,+ completedAt: now,+ updatedAt: now,+} as const;++const reply = (id: string, text: string): OrchestrationV2TurnItem => ({+ ...base,+ id: TurnItemId.make(id),+ type: "assistant_message",+ messageId: MessageId.make(id),+ text,+ streaming: false,+});++const guestMessageRow = (id: string, guestMessageId: GuestMessageId): OrchestrationV2TurnItem => ({+ ...base,+ id: TurnItemId.make(id),+ type: "user_message",+ createdBy: "user",+ creationSource: "web",+ messageId: MessageId.make(id),+ inputIntent: "turn_start",+ text: "Why?",+ context: { version: 1, records: [], guest: { guestMessageId, name: "Sam", text: "Why?" } },+ attachments: [],+});++const snapshot = (snapshotSequence = 1): GuestStreamEvent => ({+ type: "thread",+ item: { kind: "snapshot", snapshotSequence, projection },+});++const itemEvent = (sequence: number, item: OrchestrationV2TurnItem): GuestStreamEvent => ({+ type: "thread",+ item: {+ kind: "event",+ sequence,+ event: {+ id: EventId.make(`event-${sequence}`),+ type: "turn-item.updated",+ threadId: projection.thread.id,+ driver: ProviderDriverKind.make("codex"),+ providerInstanceId: projection.thread.providerInstanceId,+ occurredAt: now,+ payload: item,+ },+ },+});++const apply = (events: ReadonlyArray<GuestStreamEvent>, state = initialGuestStreamState) =>+ events.reduce<GuestStreamState>(applyGuestStreamEvent, state);++const itemIds = (state: GuestStreamState) =>+ state.projection?.visibleTurnItems.map((row) => row.item.id) ?? [];++describe("applyGuestStreamEvent", () => {+ it("builds the thread from the snapshot and applies each later event once", () => {+ const once = apply([{ type: "view", view }, snapshot(1), itemEvent(2, reply("a1", "Hi"))]);+ expect(itemIds(once)).toEqual(["a1"]);+ // A replayed or older event changes nothing.+ expect(apply([itemEvent(2, reply("a1", "Changed"))], once)).toBe(once);+ });++ it("replaces the thread on a new snapshot, as after a reconnect", () => {+ const before = apply([snapshot(1), itemEvent(2, reply("a1", "Hi")), { type: "ended" }]);+ const after = apply([snapshot(1)], { ...before, ended: false });+ expect(itemIds(after)).toEqual([]);+ });++ it("ends when the view names another link than the page's", () => {+ const state = apply([+ { type: "view", view },+ { type: "view", view: { ...view, shareId: GuestShareId.make("share-2") } },+ ]);+ expect(state.ended).toBe(true);+ expect(state.view?.shareId).toBe(view.shareId);+ });++ it("remembers a waiting message across a reconnect until its row arrives", () => {+ const waiting = {+ id: GuestMessageId.make("m1"),+ text: "Why?",+ status: "pending" as const,+ submittedAt: "2026-10-23T10:00:00.000Z",+ };+ const sent = { ...waiting, status: "sent" as const };+ const queued = apply([+ { type: "view", view: { ...view, messages: [waiting] } },+ snapshot(1),+ { type: "view", view: { ...view, messages: [sent] } },+ ]);+ expect([...queued.awaitingRowIds]).toEqual([waiting.id]);++ // Once placed, a later snapshot whose window no longer holds the row must not resurrect it.+ const placed = apply([itemEvent(2, guestMessageRow("u1", waiting.id)), snapshot(3)], queued);+ expect(placed.awaitingRowIds.size).toBe(0);+ });+});++describe("parseGuestStreamEvent", () => {+ it("decodes a valid frame and rejects malformed ones", () => {+ expect(parseGuestStreamEvent(JSON.stringify({ type: "ended" }))).toEqual({ type: "ended" });+ expect(parseGuestStreamEvent("{not json")).toBeNull();+ expect(parseGuestStreamEvent(JSON.stringify({ type: "unknown" }))).toBeNull();+ });+});++describe("unplacedGuestMessages", () => {+ const message = (id: string, status: ThreadGuestMessage["status"], submittedAt: string) => ({+ id: GuestMessageId.make(id),+ text: id,+ status,+ submittedAt,+ });++ it("shows pending ones, and resolved ones only if this page saw them waiting", () => {+ const messages = [+ message("late", "pending", "2026-10-23T10:05:00.000Z"),+ message("placed", "sent", "2026-10-23T10:00:00.000Z"),+ message("queued", "sent", "2026-10-23T09:59:00.000Z"),+ message("dismissed", "dismissed", "2026-10-23T10:01:00.000Z"),+ message("old-history", "sent", "2026-10-23T09:00:00.000Z"),+ ];+ const seen = new Set(+ ["placed", "queued", "dismissed", "late"].map((id) => GuestMessageId.make(id)),+ );+ const items = [+ {+ position: 0,+ visibility: "local" as const,+ sourceThreadId: projection.thread.id,+ sourceItemId: TurnItemId.make("u1"),+ item: guestMessageRow("u1", GuestMessageId.make("placed")),+ },+ ];+ expect(unplacedGuestMessages(messages, items, seen).map((m) => m.id)).toEqual([+ "queued",+ "dismissed",+ "late",+ ]);+ });+});++describe("formatGuestExpiry", () => {+ const now = Date.parse("2026-10-23T00:00:00.000Z");+ it("shows whole hours, then minutes, then expired", () => {+ expect(formatGuestExpiry("2026-10-23T23:59:00.000Z", now)).toBe("23h left");+ expect(formatGuestExpiry("2026-10-23T00:45:30.000Z", now)).toBe("45m left");+ expect(formatGuestExpiry("2026-10-23T00:00:00.000Z", now)).toBe("Expired");+ });+});++describe("inviteShareId", () => {+ it("reads the share id before the signature and rejects anything else", () => {+ expect(inviteShareId("k3J9xQ2mT8vL5nR1pW7yZa.sig")).toBe("k3J9xQ2mT8vL5nR1pW7yZa");+ expect(inviteShareId("no-signature")).toBeNull();+ expect(inviteShareId(".sig")).toBeNull();+ expect(inviteShareId("")).toBeNull();+ });+});++describe("guestFilesProblem", () => {+ const file = (type: string, size = 1) => ({ type, size });+ it("takes up to four files and 10 MB, with images in the types the owner's composer takes", () => {+ expect(guestFilesProblem([file("image/png"), file("application/pdf"), file("")])).toBeNull();+ expect(guestFilesProblem([1, 2, 3, 4, 5].map(() => file("image/png")))).toMatch(/up to 4/);+ expect(guestFilesProblem([file("image/png", 10 * 1024 * 1024 + 1)])).toMatch(/10 MB/);+ expect(guestFilesProblem([file("image/svg+xml")])).toMatch(/PNG, JPEG, GIF, or WebP/);+ expect(guestFilesProblem([file("text/plain", 0)])).toMatch(/cannot be attached/);+ });+});diff --git a/apps/web/src/components/guest/guestStream.logic.ts b/apps/web/src/components/guest/guestStream.logic.tsnew file mode 100644index 00000000000..a424cf04721--- /dev/null+++ b/apps/web/src/components/guest/guestStream.logic.ts@@ -0,0 +1,232 @@+import {+ GUEST_ATTACHMENT_ROUTE,+ GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,+ GUEST_MESSAGE_MAX_ATTACHMENTS,+ GUEST_SHARE_PARAM,+ GuestStreamEvent,+ isProviderSendTurnSupportedImageMimeType,+ type GuestMessageId,+ type GuestShareView,+ type OrchestrationV2ProjectedTurnItem,+ type OrchestrationV2ThreadProjection,+ type OrchestrationV2TurnItem,+ type ThreadGuestMessage,+} from "@t3tools/contracts";+import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";+import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";++export interface GuestStreamState {+ readonly view: GuestShareView | null;+ /** The thread as the owner's client holds it, built with the same reducer. */+ readonly projection: OrchestrationV2ThreadProjection | null;+ readonly sequence: number;+ /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */+ readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null;+ readonly ended: boolean;+ /**+ * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a+ * message leaves once its row arrives, so a later bounded snapshot cannot bring it back.+ */+ readonly awaitingRowIds: ReadonlySet<GuestMessageId>;+}++export const initialGuestStreamState: GuestStreamState = {+ view: null,+ projection: null,+ sequence: 0,+ partial: null,+ ended: false,+ awaitingRowIds: new Set(),+};++const guestMessageIdOf = (item: OrchestrationV2TurnItem) =>+ item.type === "user_message" ? item.context?.guest?.guestMessageId : undefined;++function withPendingFrom(+ awaiting: ReadonlySet<GuestMessageId>,+ view: GuestShareView,+): ReadonlySet<GuestMessageId> {+ const pending = view.messages.filter((message) => message.status === "pending");+ if (pending.every((message) => awaiting.has(message.id))) return awaiting;+ return new Set([...awaiting, ...pending.map((message) => message.id)]);+}++function withoutPlaced(+ awaiting: ReadonlySet<GuestMessageId>,+ items: ReadonlyArray<OrchestrationV2TurnItem>,+): ReadonlySet<GuestMessageId> {+ const placed = items.flatMap((item) => {+ const id = guestMessageIdOf(item);+ return id !== undefined && awaiting.has(id) ? [id] : [];+ });+ if (placed.length === 0) return awaiting;+ const next = new Set(awaiting);+ for (const id of placed) next.delete(id);+ return next;+}++const decodeGuestStreamEvent = Schema.decodeUnknownOption(+ Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)),+);++/** Returns null for anything the server would never send, so a bad frame is skipped, not fatal. */+export const parseGuestStreamEvent = (data: string): GuestStreamEvent | null =>+ Option.getOrNull(decodeGuestStreamEvent(data));++/**+ * Applies the owner's thread stream the way the owner's client does (see+ * EnvironmentThreadState in client-runtime): a snapshot replaces the thread, and later events+ * pass through the same projection reducer, once each.+ */+export function applyGuestStreamEvent(+ state: GuestStreamState,+ event: GuestStreamEvent,+): GuestStreamState {+ switch (event.type) {+ case "view":+ // The page follows the share it names; a view of another one means the link changed.+ if (state.view !== null && state.view.shareId !== event.view.shareId) {+ return { ...state, ended: true };+ }+ return {+ ...state,+ view: event.view,+ awaitingRowIds: withPendingFrom(state.awaitingRowIds, event.view),+ };+ case "thread": {+ const item = event.item;+ if (item.kind === "snapshot") {+ const projection = boundedSnapshotProjection(item);+ return {+ ...state,+ projection,+ sequence: item.snapshotSequence,+ partial:+ item.hasMoreHistory === true || (item.historyCursor ?? null) !== null+ ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null }+ : null,+ awaitingRowIds: withoutPlaced(+ state.awaitingRowIds,+ projection.visibleTurnItems.map((row) => row.item),+ ),+ };+ }+ if (item.kind === "synchronized" || item.sequence <= state.sequence) return state;+ if (item.kind === "unknown-event") return { ...state, sequence: item.sequence };+ const projection =+ applyOrchestrationV2ProjectionEvent(+ state.projection,+ item.event,+ state.partial === null ? undefined : { partialTimeline: true, ...state.partial },+ ) ?? state.projection;+ const turnItem = item.event.type === "turn-item.updated" ? item.event.payload : null;+ const watermark = state.partial?.latestLocalTurnOrdinal ?? null;+ return {+ ...state,+ projection,+ sequence: item.sequence,+ partial:+ state.partial !== null &&+ turnItem !== null &&+ (watermark === null || turnItem.ordinal > watermark)+ ? { latestLocalTurnOrdinal: turnItem.ordinal }+ : state.partial,+ awaitingRowIds:+ turnItem === null+ ? state.awaitingRowIds+ : withoutPlaced(state.awaitingRowIds, [turnItem]),+ };+ }+ case "ended":+ return { ...state, ended: true };+ }+}++/**+ * The guest's messages to show after the transcript, oldest first. Pending ones always show. A+ * sent or dismissed one shows only while it awaits a row (see `awaitingRowIds`): a queued send, or+ * a dismissal to report. The transcript is a bounded window, so any other resolved message is old+ * history, not something to place at the end.+ */+export function unplacedGuestMessages(+ messages: ReadonlyArray<ThreadGuestMessage>,+ items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,+ awaitingRowIds: ReadonlySet<GuestMessageId>,+): ReadonlyArray<ThreadGuestMessage> {+ const placed = new Set(items.flatMap((row) => guestMessageIdOf(row.item) ?? []));+ return messages+ .filter(+ (message) =>+ !placed.has(message.id) && (message.status === "pending" || awaitingRowIds.has(message.id)),+ )+ .toSorted((a, b) => a.submittedAt.localeCompare(b.submittedAt));+}++/** "23h left" or "5m left", rounded down, for the guest page header. */+export function formatGuestExpiry(expiresAt: string, nowMs: number): string {+ const minutes = Math.floor((Date.parse(expiresAt) - nowMs) / 60_000);+ if (minutes <= 0) return "Expired";+ return minutes >= 60 ? `${Math.floor(minutes / 60)}h left` : `${minutes}m left`;+}++/**+ * The share an invite (`<shareId>.<signature>`) opens. Only used to name the share in the page+ * URL and to find this browser's session for it; the server checks the signature.+ */+export function inviteShareId(credential: string): string | null {+ const [shareId, signature] = credential.split(".");+ return shareId && signature ? shareId : null;+}++/** Where the guest page loads a file of the shared thread or of a waiting message. */+export const guestAttachmentUrl = (shareId: string, attachmentId: string) =>+ `${GUEST_ATTACHMENT_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&id=${encodeURIComponent(attachmentId)}`;++/**+ * Why these files cannot go with one message, or null. The server checks the same limits; this+ * only says so before the upload.+ */+export function guestFilesProblem(+ files: ReadonlyArray<Pick<File, "type" | "size">>,+): string | null {+ if (files.length > GUEST_MESSAGE_MAX_ATTACHMENTS) {+ return `Attach up to ${GUEST_MESSAGE_MAX_ATTACHMENTS} files to a message.`;+ }+ if (files.reduce((total, file) => total + file.size, 0) > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) {+ return "Attached files can total up to 10 MB per message.";+ }+ const unsupported = files.some(+ (file) =>+ file.size === 0 ||+ (file.type.toLowerCase().startsWith("image/") &&+ !isProviderSendTurnSupportedImageMimeType(file.type)),+ );+ return unsupported+ ? "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP."+ : null;+}++/**+ * Image URLs for the thread's messages, which the timeline shows as previews. The map keeps its+ * identity while the rows do, because the timeline rebuilds its entries when it changes.+ */+export function createGuestAttachmentUrls(shareId: string) {+ let previousItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> | null = null;+ let previous: ReadonlyMap<string, string> = new Map();+ return (items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>): ReadonlyMap<string, string> => {+ if (items === previousItems) return previous;+ previousItems = items;+ previous = new Map(+ items.flatMap(({ item }) =>+ item.type === "user_message"+ ? item.attachments.map(+ (attachment) => [attachment.id, guestAttachmentUrl(shareId, attachment.id)] as const,+ )+ : [],+ ),+ );+ return previous;+ };+}diff --git a/apps/web/src/components/guest/guestTurnItemSource.ts b/apps/web/src/components/guest/guestTurnItemSource.tsnew file mode 100644index 00000000000..5ce858251d8--- /dev/null+++ b/apps/web/src/components/guest/guestTurnItemSource.ts@@ -0,0 +1,102 @@+import {+ applyCommandOutputFrame,+ EMPTY_COMMAND_OUTPUT,+} from "@t3tools/client-runtime/state/command-output";+import {+ GUEST_COMMAND_OUTPUT_ROUTE,+ GUEST_ITEM_ROUTE,+ GUEST_SHARE_PARAM,+ OrchestrationV2CommandOutputFrame,+ OrchestrationV2GetTurnItemResult,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import * as Data from "effect/Data";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as Queue from "effect/Queue";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";+import { Atom } from "effect/reactivity";++import type { TurnItemSource } from "../chat/timelineRowContext";++/** What an expanded guest row says when it cannot read the item. */+class GuestItemReadError extends Data.TaggedError("GuestItemReadError")<{+ readonly message: string;+}> {}++const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));+const decodeFrame = Schema.decodeUnknownOption(+ Schema.fromJsonString(OrchestrationV2CommandOutputFrame),+);++const itemUrl = (route: string, shareId: string, itemId: string) =>+ `${route}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}`;++/** `item` is null when the thread no longer has the item, or the share ended. */+async function fetchGuestItemDetail(+ shareId: string,+ itemId: string,+): Promise<OrchestrationV2GetTurnItemResult> {+ const response = await fetch(itemUrl(GUEST_ITEM_ROUTE, shareId, itemId));+ if (response.status === 403) return { item: null };+ if (!response.ok) throw new Error(`Guest item request failed with ${response.status}.`);+ return decodeDetail(await response.json());+}++// Keys are JSON so a share id or item id can never run into the next part.+const guestItemDetailAtom = Atom.family((key: string) => {+ const [shareId, itemId] = JSON.parse(key) as [string, string, string];+ return Atom.make(+ Effect.tryPromise({+ try: () => fetchGuestItemDetail(shareId, itemId),+ catch: () => new GuestItemReadError({ message: "Could not load this item." }),+ }),+ );+});++/** Ends after the frame of a settled command, so the browser does not reconnect to it. */+const guestCommandOutputAtom = Atom.family((key: string) => {+ const [shareId, itemId] = JSON.parse(key) as [string, string];+ const frames = Stream.callback<OrchestrationV2CommandOutputFrame, GuestItemReadError>((queue) =>+ Effect.acquireRelease(+ Effect.sync(() => {+ const source = new EventSource(itemUrl(GUEST_COMMAND_OUTPUT_ROUTE, shareId, itemId));+ source.addEventListener("message", (message) => {+ const frame = decodeFrame(message.data);+ if (Option.isNone(frame)) return;+ Queue.offerUnsafe(queue, frame.value);+ if (!frame.value.running) {+ source.close();+ Queue.endUnsafe(queue);+ }+ });+ // A non-200 response closes the source for good: the share ended or the item is gone.+ source.addEventListener("error", () => {+ if (source.readyState === EventSource.CLOSED) {+ Queue.failCauseUnsafe(+ queue,+ Cause.fail(new GuestItemReadError({ message: "Output is no longer available." })),+ );+ }+ });+ return source;+ }),+ (source) => Effect.sync(() => source.close()),+ ),+ );+ // `scan` emits its seed first; skipping it keeps the row "loading" until the first frame.+ return Atom.make(+ frames.pipe(+ Stream.scan(() => EMPTY_COMMAND_OUTPUT, applyCommandOutputFrame),+ Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),+ ),+ );+});++/** Expanded rows on the guest page read through the guest routes, with the page's share cookie. */+export const guestTurnItemSource = (shareId: string): TurnItemSource => ({+ detail: ({ itemId, revision }) =>+ guestItemDetailAtom(JSON.stringify([shareId, itemId, revision])),+ commandOutput: ({ itemId }) => guestCommandOutputAtom(JSON.stringify([shareId, itemId])),+});diff --git a/apps/web/src/components/settings/BetaSettingsPanel.tsx b/apps/web/src/components/settings/BetaSettingsPanel.tsxnew file mode 100644index 00000000000..00a9e5825d7--- /dev/null+++ b/apps/web/src/components/settings/BetaSettingsPanel.tsx@@ -0,0 +1,106 @@+import { useAuth } from "@clerk/react";+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";+import { Link } from "@tanstack/react-router";++import { hasCloudPublicConfig } from "~/cloud/publicConfig";+import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";+import { Button } from "../ui/button";+import { Switch } from "../ui/switch";+import { ScopedSwitch } from "./ScopedSwitch";+import {+ SettingResetButton,+ SettingsPageContainer,+ SettingsRow,+ SettingsSection,+} from "./settingsLayout";+import { searchableSetting } from "./settingsSearch";+import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";++/** Features that are still settling in. Each is off until turned on here. */+export function BetaSettingsPanel() {+ const settings = useScopedSettings();+ const updateSettings = useUpdateScopedSettings();+ return (+ <SettingsPageContainer>+ <SettingsSection id="beta" title="Beta">+ <SettingsRow+ {...searchableSetting("working-shelf")}+ description="Fold working and monitoring threads into a Working section. They return to the top of the inbox when they need you."+ resetAction={+ settings.sidebarWorkingShelfEnabled !==+ DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? (+ <SettingResetButton+ label="working section"+ onClick={() =>+ updateSettings({+ sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled,+ })+ }+ />+ ) : null+ }+ control={+ <Switch+ checked={settings.sidebarWorkingShelfEnabled}+ onCheckedChange={(checked) =>+ updateSettings({ sidebarWorkingShelfEnabled: Boolean(checked) })+ }+ aria-label="Working section"+ />+ }+ />+ {/* Clerk is only mounted when this build has T3 Connect. */}+ {hasCloudPublicConfig() ? <GuestLinksRowWithSignIn /> : <GuestLinksRow />}+ </SettingsSection>+ </SettingsPageContainer>+ );+}++/** Signed out of T3 Connect, the row offers to sign in instead of its switch. */+function GuestLinksRowWithSignIn() {+ const { isSignedIn } = useAuth();+ const { openAuthPrompt } = useT3ConnectAuthPrompt();+ // `isSignedIn` is undefined until Clerk loads.+ if (isSignedIn !== false) return <GuestLinksRow />;+ return (+ <SettingsRow+ {...searchableSetting("guest-links")}+ description="Share a thread with a guest who watches it live in their browser and sends messages you approve. Sign in to T3 Connect to use guest links."+ control={+ <Button size="sm" variant="outline" onClick={openAuthPrompt}>+ Sign in+ </Button>+ }+ />+ );+}++function GuestLinksRow() {+ const settings = useScopedSettings();+ const updateSettings = useUpdateScopedSettings();+ return (+ <SettingsRow+ serverScoped+ {...searchableSetting("guest-links")}+ settingKeys={["guestSharingEnabled"]}+ description={+ <>+ Share a thread with a guest who watches it live in their browser and sends messages you+ approve. Needs T3 Connect: sign in and link this machine in{" "}+ <Link to="/settings/connections" className="underline underline-offset-2">+ Connections+ </Link>+ . While it is off, every guest link stops working.+ </>+ }+ control={+ <ScopedSwitch+ settingKeys={["guestSharingEnabled"]}+ checked={settings.guestSharingEnabled}+ onCheckedChange={(checked) => updateSettings({ guestSharingEnabled: Boolean(checked) })}+ aria-label="Guest links"+ />+ }+ />+ );+}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex ec1e510ad16..2a4c88cc5ea 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -975,33 +975,6 @@ export function GeneralSettingsPanel() {}/>- <SettingsRow- {...searchableSetting("working-shelf")}- description="Fold working and monitoring threads into a Working section. They return to the top of the inbox when they need you."- resetAction={- settings.sidebarWorkingShelfEnabled !==- DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? (- <SettingResetButton- label="working section"- onClick={() =>- updateSettings({- sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled,- })- }- />- ) : null- }- control={- <Switch- checked={settings.sidebarWorkingShelfEnabled}- onCheckedChange={(checked) =>- updateSettings({ sidebarWorkingShelfEnabled: Boolean(checked) })- }- aria-label="Working section (beta)"- />- }- />-<SettingsRowserverScopedsettingKeys={["idleCompaction", "compactIdleThreads"]}diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxindex 9be69473783..f096583ed3b 100644--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx@@ -9,6 +9,7 @@ import {} from "react";import {ArchiveIcon,+ FlaskConicalIcon,BlocksIcon,BotIcon,createLucideIcon,@@ -87,6 +88,7 @@ const SETTINGS_SECTION_ICONS: Readonly<"/settings/source-control": GitBranchIcon,"/settings/storage": HardDriveIcon,"/settings/connections": Link2Icon,+ "/settings/beta": FlaskConicalIcon,"/settings/archived": ArchiveIcon,};diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex b621143836f..000ae5d4742 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -29,6 +29,7 @@ export type SettingsPath =| "/settings/source-control"| "/settings/storage"| "/settings/connections"+ | "/settings/beta"| "/settings/archived";export type SettingsSearchScope =@@ -87,6 +88,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {"/settings/source-control": "Source Control","/settings/storage": "Storage","/settings/connections": "Connections",+ "/settings/beta": "Beta","/settings/archived": "Archive",};@@ -347,9 +349,16 @@ export const SETTINGS_SEARCH_ITEMS = [},{id: "working-shelf",- title: "Working section (beta)",- to: "/settings/general",- searchTerms: ["hide fold running monitoring threads inbox sidebar shelf"],+ title: "Working section",+ to: "/settings/beta",+ searchTerms: ["beta hide fold running monitoring threads inbox sidebar shelf"],+ },+ {+ id: "guest-links",+ title: "Guest links",+ to: "/settings/beta",+ scope: "environment",+ searchTerms: ["beta share guest invite link teammate watch t3 connect tunnel"],},{id: "auto-settle-inactive-threads",@@ -1045,6 +1054,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScop"/settings/storage": "project-defaults","/settings/connections": "connections","/settings/scheduled-tasks": null,+ "/settings/beta": null,"/settings/archived": "project-defaults",};diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsxindex 4a276b0ee73..d2eb759903b 100644--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx@@ -44,6 +44,7 @@ import {SquarePenIcon,TerminalIcon,Undo2Icon,+ UserRoundIcon,XIcon,} from "lucide-react";import {@@ -673,31 +674,37 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowPicon: "input" as const,className: "text-indigo-600 dark:text-indigo-300",}- : status === "limited"+ : status === "request"? {- label: "Limited",- icon: "failed" as const,- className: "text-warning",+ label: "Request",+ icon: "request" as const,+ className: "text-guest-foreground",}- : status === "failed"+ : status === "limited"? {- label: "Failed",+ label: "Limited",icon: "failed" as const,- className: "text-error",+ className: "text-warning",}- : isWoke+ : status === "failed"? {- label: "Woke",- icon: "woke" as const,- className: "text-warning",+ label: "Failed",+ icon: "failed" as const,+ className: "text-error",}- : isUnread+ : isWoke? {- label: "Done",- icon: "done" as const,- className: "text-success",+ label: "Woke",+ icon: "woke" as const,+ className: "text-warning",}- : null;+ : isUnread+ ? {+ label: "Done",+ icon: "done" as const,+ className: "text-success",+ }+ : null;const isWokeStatus = topStatus?.icon === "woke";const branchMismatch = resolveLocalCheckoutBranchMismatch({@@ -968,7 +975,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP"truncate",shouldRecede? "text-secondary-label"- : isUnread || isWoke || status === "input"+ : isUnread || isWoke || status === "input" || status === "request"? "text-foreground": status === "failed"? "text-foreground/95"@@ -978,7 +985,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP"truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",shouldRecede? "text-secondary-label/70"- : props.isActive || isWoke || status === "input"+ : props.isActive || isWoke || status === "input" || status === "request"? "text-foreground": isUnread? "text-muted-foreground"@@ -1335,6 +1342,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP<CircleDotDashedIcon aria-hidden className="size-4 shrink-0" />) : topStatus.icon === "input" ? (<MessageCircleQuestionIcon aria-hidden className="size-4 shrink-0" />+ ) : topStatus.icon === "request" ? (+ <UserRoundIcon aria-hidden className="size-4 shrink-0" />) : topStatus.icon === "approval" ? (<ShieldQuestionIcon aria-hidden className="size-4 shrink-0" />) : topStatus.icon === "failed" ? (diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.tsindex cca7bcf20ed..c56bbb9c235 100644--- a/apps/web/src/components/threadActionMenu.logic.ts+++ b/apps/web/src/components/threadActionMenu.logic.ts@@ -18,6 +18,7 @@ export type ThreadActionMenuId =| "rename"| "regenerate-title"| "mark-unread"+ | "share-guest"| "copy"| "copy-path"| "copy-branch"@@ -86,6 +87,8 @@ export interface ThreadActionMenuState {readonly titleRegeneration: boolean;};readonly snoozePresets: ReadonlyArray<SnoozePreset>;+ /** Guest links need their own grant, so the caller checks it instead of `canOperate`. */+ readonly canShareWithGuest?: boolean;}/** Local navigation, read markers, and copying remain available to read-only clients. */@@ -94,6 +97,7 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean"new-thread-on-branch","project-settings","mark-unread",+ "share-guest","copy","copy-path","copy-branch",@@ -159,6 +163,9 @@ export function buildThreadActionMenuItems(]: []),{ id: "mark-unread", label: "Mark unread", icon: "mail-open" },+ ...(state.canShareWithGuest+ ? [{ id: "share-guest" as const, label: "Share with guest", icon: "user-plus" }]+ : []),...(state.projectFilter? [{diff --git a/apps/web/src/connection/runtime.browser.test.ts b/apps/web/src/connection/runtime.browser.test.tsnew file mode 100644index 00000000000..958f59148e7--- /dev/null+++ b/apps/web/src/connection/runtime.browser.test.ts@@ -0,0 +1,29 @@+import * as Cause from "effect/Cause";+import { AsyncResult, AtomRegistry } from "effect/reactivity";+import { describe, expect, it, vi } from "vite-plus/test";++import { connectionAtomRuntime } from "./runtime";++function visit(path: string): Disposable {+ const previous = `${window.location.pathname}${window.location.search}`;+ window.history.replaceState(window.history.state, "", path);+ return {+ [Symbol.dispose]: () => window.history.replaceState(window.history.state, "", previous),+ };+}++describe("connectionAtomRuntime", () => {+ it("connects to no environment on the guest page", async () => {+ using _page = visit("/guest?share=share-1");+ using socket = vi.spyOn(window, "WebSocket");+ const registry = AtomRegistry.make();+ using _mounted = { [Symbol.dispose]: registry.mount(connectionAtomRuntime) };+ await vi.waitFor(() => {+ const result = registry.get(connectionAtomRuntime);+ expect(AsyncResult.isFailure(result) && String(Cause.squash(result.cause))).toContain(+ "The guest page has no environment connection.",+ );+ });+ expect(socket).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.tsindex 5e3aa365510..6a3cc4acb43 100644--- a/apps/web/src/connection/runtime.ts+++ b/apps/web/src/connection/runtime.ts@@ -5,9 +5,12 @@ import {ThreadHistoryController,} from "@t3tools/client-runtime/state/threads";import { PullRequestDiffLoader } from "@t3tools/client-runtime/state/pull-requests";+import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { Atom } from "effect/reactivity";+import { isGuestPage } from "../guestPage";+import * as Runtime from "../lib/runtime";import * as BackgroundActivityReporter from "../lib/backgroundActivityReporter";import * as ConnectionPlatform from "./platform";@@ -50,7 +53,20 @@ const layerConnection = BackgroundActivityReporter.layer.pipe(Layer.provideMerge(layerProvidedClientConnection),);+/**+ * A guest has no session here. Building the connection would open the page origin's environment+ * with whatever cookie this browser holds, plus every environment saved in it, so on the guest+ * page the runtime fails to build and every atom on it keeps its empty value.+ */+const layerForPage = Layer.unwrap(+ Effect.suspend((): Effect.Effect<typeof layerConnection> =>+ isGuestPage()+ ? Effect.die(new Error("The guest page has no environment connection."))+ : Effect.succeed(layerConnection),+ ),+);+export const connectionAtomRuntime: Atom.AtomRuntime<Layer.Success<ConnectionLayerSource>,Layer.Error<ConnectionLayerSource>-> = Atom.runtime(layerConnection);+> = Atom.runtime(layerForPage);diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.tsindex c6f831efcb5..76baa1a93e3 100644--- a/apps/web/src/contextMenuFallback.ts+++ b/apps/web/src/contextMenuFallback.ts@@ -110,6 +110,12 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri},{ tag: "circle", attrs: { cx: "12", cy: "12", r: "3" } },],+ "user-plus": [+ { tag: "path", attrs: { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" } },+ { tag: "circle", attrs: { cx: "9", cy: "7", r: "4" } },+ { tag: "line", attrs: { x1: "19", x2: "19", y1: "8", y2: "14" } },+ { tag: "line", attrs: { x1: "22", x2: "16", y1: "11", y2: "11" } },+ ],"folder-tree": [{tag: "path",diff --git a/apps/web/src/guestPage.ts b/apps/web/src/guestPage.tsnew file mode 100644index 00000000000..2055c77531c--- /dev/null+++ b/apps/web/src/guestPage.ts@@ -0,0 +1,6 @@+/** The page a guest link opens. It shows one shared thread to a browser with no T3 session. */+export const GUEST_PAGE_PATH = "/guest";++export function isGuestPage(): boolean {+ return window.location.pathname === GUEST_PAGE_PATH;+}diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.tsindex b584bbd5807..899cf38ee51 100644--- a/apps/web/src/hooks/useThreadActionMenu.test.ts+++ b/apps/web/src/hooks/useThreadActionMenu.test.ts@@ -156,6 +156,7 @@ const createMenu = () =>threadRef: target,projectCwd: "/project",onStartRename: () => recordEffect("rename"),+ canShareWithGuest: false,});beforeEach(() => {diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.tsindex 08ed2b24e4c..9796806b22d 100644--- a/apps/web/src/hooks/useThreadActionMenu.ts+++ b/apps/web/src/hooks/useThreadActionMenu.ts@@ -1,5 +1,6 @@import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { requestCustomSnooze } from "../components/CustomSnoozeDialog";+import { openGuestShareDialog } from "../components/chat/guestShareDialogState";import {type AtomCommandResult,isAtomCommandInterrupted,@@ -61,8 +62,9 @@ export function useThreadActionMenu(input: {readonly threadRef: ScopedThreadRef | null;readonly projectCwd: string | null;readonly onStartRename: () => void;+ readonly canShareWithGuest: boolean;}) {- const { threadRef, projectCwd, onStartRename } = input;+ const { threadRef, projectCwd, onStartRename, canShareWithGuest } = input;const router = useRouter();const projects = useProjects();const primaryEnvironmentId = usePrimaryEnvironmentId();@@ -141,6 +143,7 @@ export function useThreadActionMenu(input: {isRunning: !threadRuntimeCanArchive(thread.runtime),supports,snoozePresets,+ canShareWithGuest,});const clicked = await settlePromise(() => api.contextMenu.show(items, position));if (clicked._tag === "Failure" || clicked.value === null) return;@@ -243,6 +246,9 @@ export function useThreadActionMenu(input: {case "mark-unread":markThreadUnread(threadRef);return;+ case "share-guest":+ openGuestShareDialog(threadRef);+ return;case "copy-path": {const workspacePath = thread.worktreePath ?? projectCwd;if (!workspacePath) {diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 814cfa484dc..eeb66215733 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -240,6 +240,9 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil--color-diff-deletion-foreground: var(--diff-deletion-foreground);--color-info-foreground: var(--info-foreground);--color-info: var(--info);+ --color-guest: var(--guest);+ --color-guest-foreground: var(--guest-foreground);+ --color-guest-surface: var(--guest-surface);--color-destructive-foreground: var(--destructive-foreground);--color-ring: var(--ring);--color-input: var(--contrast-input);@@ -1132,6 +1135,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil--destructive-foreground: var(--error-foreground);--info: var(--color-blue-500);--info-foreground: var(--color-blue-700);+ /* Messages from a guest link, and the sidebar Request status. */+ --guest: var(--color-fuchsia-500);+ --guest-foreground: var(--color-fuchsia-600);+ --guest-surface: color-mix(in srgb, var(--guest) 14%, var(--message-surface));--success: var(--color-emerald-500);--success-foreground: var(--color-emerald-700);--warning: var(--color-amber-500);@@ -1183,6 +1190,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil--border: --alpha(var(--color-white) / 6%);--input: --alpha(var(--color-white) / 8%);--info-foreground: var(--color-blue-400);+ --guest-foreground: var(--color-fuchsia-300);--success-foreground: var(--color-emerald-400);--warning-foreground: var(--color-amber-400);--warning-surface: color-mix(in srgb, var(--warning) 16%, transparent);diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 7c0b13ef767..b8322b83ba8 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -13,6 +13,7 @@ import { Route as WelcomeRouteImport } from './routes/welcome'import { Route as UsageRouteImport } from './routes/usage'import { Route as SettingsRouteImport } from './routes/settings'import { Route as PairRouteImport } from './routes/pair'+import { Route as GuestRouteImport } from './routes/guest'import { Route as ConnectAgentRouteImport } from './routes/connect-agent'import { Route as ConnectRouteImport } from './routes/connect'import { Route as ChatRouteImport } from './routes/_chat'@@ -29,6 +30,7 @@ import { Route as SettingsIntegrationsRouteImport } from './routes/settings.inteimport { Route as SettingsGeneralRouteImport } from './routes/settings.general'import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'+import { Route as SettingsBetaRouteImport } from './routes/settings.beta'import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'@@ -57,6 +59,11 @@ const PairRoute = PairRouteImport.update({path: '/pair',getParentRoute: () => rootRouteImport,} as any)+const GuestRoute = GuestRouteImport.update({+ id: '/guest',+ path: '/guest',+ getParentRoute: () => rootRouteImport,+} as any)const ConnectAgentRoute = ConnectAgentRouteImport.update({id: '/connect-agent',path: '/connect-agent',@@ -137,6 +144,11 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({path: '/connections',getParentRoute: () => SettingsRoute,} as any)+const SettingsBetaRoute = SettingsBetaRouteImport.update({+ id: '/beta',+ path: '/beta',+ getParentRoute: () => SettingsRoute,+} as any)const SettingsArchivedRoute = SettingsArchivedRouteImport.update({id: '/archived',path: '/archived',@@ -178,6 +190,7 @@ export interface FileRoutesByFullPath {'/': typeof ChatIndexRoute'/connect': typeof ConnectRoute'/connect-agent': typeof ConnectAgentRoute+ '/guest': typeof GuestRoute'/pair': typeof PairRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute@@ -187,6 +200,7 @@ export interface FileRoutesByFullPath {'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/appearance': typeof SettingsAppearanceRoute'/settings/archived': typeof SettingsArchivedRoute+ '/settings/beta': typeof SettingsBetaRoute'/settings/connections': typeof SettingsConnectionsRoute'/settings/diagnostics': typeof SettingsDiagnosticsRoute'/settings/general': typeof SettingsGeneralRoute@@ -205,6 +219,7 @@ export interface FileRoutesByFullPath {export interface FileRoutesByTo {'/connect': typeof ConnectRoute'/connect-agent': typeof ConnectAgentRoute+ '/guest': typeof GuestRoute'/pair': typeof PairRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute@@ -214,6 +229,7 @@ export interface FileRoutesByTo {'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/appearance': typeof SettingsAppearanceRoute'/settings/archived': typeof SettingsArchivedRoute+ '/settings/beta': typeof SettingsBetaRoute'/settings/connections': typeof SettingsConnectionsRoute'/settings/diagnostics': typeof SettingsDiagnosticsRoute'/settings/general': typeof SettingsGeneralRoute@@ -235,6 +251,7 @@ export interface FileRoutesById {'/_chat': typeof ChatRouteWithChildren'/connect': typeof ConnectRoute'/connect-agent': typeof ConnectAgentRoute+ '/guest': typeof GuestRoute'/pair': typeof PairRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute@@ -244,6 +261,7 @@ export interface FileRoutesById {'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/appearance': typeof SettingsAppearanceRoute'/settings/archived': typeof SettingsArchivedRoute+ '/settings/beta': typeof SettingsBetaRoute'/settings/connections': typeof SettingsConnectionsRoute'/settings/diagnostics': typeof SettingsDiagnosticsRoute'/settings/general': typeof SettingsGeneralRoute@@ -266,6 +284,7 @@ export interface FileRouteTypes {| '/'| '/connect'| '/connect-agent'+ | '/guest'| '/pair'| '/settings'| '/usage'@@ -275,6 +294,7 @@ export interface FileRouteTypes {| '/projects/$projectKey'| '/settings/appearance'| '/settings/archived'+ | '/settings/beta'| '/settings/connections'| '/settings/diagnostics'| '/settings/general'@@ -293,6 +313,7 @@ export interface FileRouteTypes {to:| '/connect'| '/connect-agent'+ | '/guest'| '/pair'| '/settings'| '/usage'@@ -302,6 +323,7 @@ export interface FileRouteTypes {| '/projects/$projectKey'| '/settings/appearance'| '/settings/archived'+ | '/settings/beta'| '/settings/connections'| '/settings/diagnostics'| '/settings/general'@@ -322,6 +344,7 @@ export interface FileRouteTypes {| '/_chat'| '/connect'| '/connect-agent'+ | '/guest'| '/pair'| '/settings'| '/usage'@@ -331,6 +354,7 @@ export interface FileRouteTypes {| '/projects/$projectKey'| '/settings/appearance'| '/settings/archived'+ | '/settings/beta'| '/settings/connections'| '/settings/diagnostics'| '/settings/general'@@ -352,6 +376,7 @@ export interface RootRouteChildren {ChatRoute: typeof ChatRouteWithChildrenConnectRoute: typeof ConnectRouteConnectAgentRoute: typeof ConnectAgentRoute+ GuestRoute: typeof GuestRoutePairRoute: typeof PairRouteSettingsRoute: typeof SettingsRouteWithChildrenUsageRoute: typeof UsageRoute@@ -389,6 +414,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof PairRouteImportparentRoute: typeof rootRouteImport}+ '/guest': {+ id: '/guest'+ path: '/guest'+ fullPath: '/guest'+ preLoaderRoute: typeof GuestRouteImport+ parentRoute: typeof rootRouteImport+ }'/connect-agent': {id: '/connect-agent'path: '/connect-agent'@@ -501,6 +533,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsConnectionsRouteImportparentRoute: typeof SettingsRoute}+ '/settings/beta': {+ id: '/settings/beta'+ path: '/beta'+ fullPath: '/settings/beta'+ preLoaderRoute: typeof SettingsBetaRouteImport+ parentRoute: typeof SettingsRoute+ }'/settings/archived': {id: '/settings/archived'path: '/archived'@@ -574,6 +613,7 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)interface SettingsRouteChildren {SettingsAppearanceRoute: typeof SettingsAppearanceRouteSettingsArchivedRoute: typeof SettingsArchivedRoute+ SettingsBetaRoute: typeof SettingsBetaRouteSettingsConnectionsRoute: typeof SettingsConnectionsRouteSettingsDiagnosticsRoute: typeof SettingsDiagnosticsRouteSettingsGeneralRoute: typeof SettingsGeneralRoute@@ -591,6 +631,7 @@ interface SettingsRouteChildren {const SettingsRouteChildren: SettingsRouteChildren = {SettingsAppearanceRoute: SettingsAppearanceRoute,SettingsArchivedRoute: SettingsArchivedRoute,+ SettingsBetaRoute: SettingsBetaRoute,SettingsConnectionsRoute: SettingsConnectionsRoute,SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,SettingsGeneralRoute: SettingsGeneralRoute,@@ -613,6 +654,7 @@ const rootRouteChildren: RootRouteChildren = {ChatRoute: ChatRouteWithChildren,ConnectRoute: ConnectRoute,ConnectAgentRoute: ConnectAgentRoute,+ GuestRoute: GuestRoute,PairRoute: PairRoute,SettingsRoute: SettingsRouteWithChildren,UsageRoute: UsageRoute,diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 3d73c01104a..5a2a2ebc74a 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -19,6 +19,7 @@ import { resolveServerBackedAppDisplayName } from "../branding.logic";import { AppSidebarLayout } from "../components/AppSidebarLayout";import { CommandPalette } from "../components/CommandPalette";import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";+import { GuestShareDialogHost } from "../components/chat/GuestShareControls";import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";import { ConfirmDialogHost } from "../components/ConfirmDialogHost";import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";@@ -67,6 +68,7 @@ import { useUiStateStore } from "../uiStateStore";import { syncBrowserChromeTheme } from "../hooks/useTheme";import { configureClientTracing } from "../observability/clientTracing";import { resolveInitialServerAuthGateState } from "../environments/primary";+import { GUEST_PAGE_PATH } from "../guestPage";import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";import { isLocalEnvironmentDisabled } from "../localEnvironment";@@ -89,6 +91,16 @@ import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";export const Route = createRootRoute({beforeLoad: async ({ location }) => {+ // Guest links open on the owner's tunnel host in a browser with no T3 session, and must+ // not trigger pairing or an environment connection.+ if (location.pathname === GUEST_PAGE_PATH) {+ return {+ authGateState: {+ status: "guest",+ } as const,+ };+ }+if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {return {authGateState: {@@ -153,6 +165,8 @@ function RootRouteView() {authGateState.status === "hosted-static",);+ if (pathname === GUEST_PAGE_PATH) return <Outlet />;+if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {return (<>@@ -187,6 +201,7 @@ function RootRouteView() {<FontAppearanceSync /><ProviderAuthCallbackCoordinator /><CustomSnoozeDialogHost />+ <GuestShareDialogHost /><CommandPalette><AppSidebarLayout><Outlet />@@ -242,6 +257,7 @@ function RootRouteView() {<ReopenClosedViewShortcut /><ConfirmDialogHost /><CustomSnoozeDialogHost />+ <GuestShareDialogHost /><SlowRpcRequestToastCoordinator /><HostFreezeToastCoordinator /><PermissionUpdateNotice />diff --git a/apps/web/src/routes/guest.tsx b/apps/web/src/routes/guest.tsxnew file mode 100644index 00000000000..a07b98b79e1--- /dev/null+++ b/apps/web/src/routes/guest.tsx@@ -0,0 +1,7 @@+import { createFileRoute } from "@tanstack/react-router";++import { GuestPage } from "../components/guest/GuestPage";++export const Route = createFileRoute("/guest")({+ component: GuestPage,+});diff --git a/apps/web/src/routes/pair.tsx b/apps/web/src/routes/pair.tsxindex 769ad48abda..f91d39d7999 100644--- a/apps/web/src/routes/pair.tsx+++ b/apps/web/src/routes/pair.tsx@@ -15,7 +15,11 @@ export const Route = createFileRoute("/pair")({};}- if (authGateState.status === "authenticated" || authGateState.status === "hosted-static") {+ if (+ authGateState.status === "authenticated" ||+ authGateState.status === "hosted-static" ||+ authGateState.status === "guest"+ ) {throw redirect({ to: "/", replace: true });}return {diff --git a/apps/web/src/routes/settings.beta.tsx b/apps/web/src/routes/settings.beta.tsxnew file mode 100644index 00000000000..e0c17534096--- /dev/null+++ b/apps/web/src/routes/settings.beta.tsx@@ -0,0 +1,5 @@+import { createFileRoute } from "@tanstack/react-router";++import { BetaSettingsPanel } from "../components/settings/BetaSettingsPanel";++export const Route = createFileRoute("/settings/beta")({ component: BetaSettingsPanel });diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.tsindex fcf12d209a0..28a27bf1a92 100644--- a/apps/web/src/state/queries.ts+++ b/apps/web/src/state/queries.ts@@ -15,6 +15,7 @@ import { messageSearchTokens } from "@t3tools/shared/paletteSearch";import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";import type {EnvironmentId,+ OrchestrationV2GetTurnItemResult,ProjectContentMatch,ProjectEntry,ProjectEntryKind,@@ -402,6 +403,13 @@ export function useCheckpointDiff(return fullThreadTarget === null ? turn : fullThread;}+/** Reads one item's detail from somewhere other than the environment, as the guest page does. */+export type TurnItemDetailSource = (input: {+ readonly threadId: ThreadId;+ readonly itemId: TurnItemId;+ readonly revision: string;+}) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>;+export function useTurnItemDetail(target: {readonly environmentId: EnvironmentId;@@ -409,13 +417,17 @@ export function useTurnItemDetail(readonly itemId: TurnItemId;readonly revision: string;} | null,+ source?: TurnItemDetailSource,) {- return useEnvironmentQuery(+ const input =target === null? null- : orchestrationEnvironment.turnItem({- environmentId: target.environmentId,- input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },- }),+ : { threadId: target.threadId, itemId: target.itemId, revision: target.revision };+ return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>(+ target === null || input === null+ ? null+ : source+ ? source(input)+ : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }),);}diff --git a/docs/README.md b/docs/README.mdindex dc3c08bfc6c..d2ee571ee3e 100644--- a/docs/README.md+++ b/docs/README.md@@ -19,6 +19,7 @@- [Usage and limits](./user/usage.md)- [Product usage data](./user/telemetry.md)- [Remote access](./user/remote-access.md)+- [Guest links](./user/guest-links.md)- [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md)- [Outside agents (MCP)](./user/outside-agents.md)- [Running in the background](./user/background-service.md)diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.mdindex 005276764d2..ad7a96c5eb4 100644--- a/docs/internals/environment-auth.md+++ b/docs/internals/environment-auth.md@@ -27,6 +27,18 @@ model. DPoP binds a token to a client's proof key; an invalid proof must failrather than fall back to bearer authentication. The OAuth token-exchangevocabulary gives these grants a familiar meaning.+### Guest links are not sessions++A [guest link](../user/guest-links.md) gives one browser read access to one+thread and a way to propose messages. Its tokens are HMACs of the thread and+share id under a server key ([GuestShareService](../../apps/server/src/guest/GuestShareService.ts)),+so nothing secret is stored. The share in the thread projection is the only+state: replacing, closing, or archiving it revokes every token, and the+orchestrator's serial commands make redeeming and sending happen once. Guest+tokens never enter `SessionStore`, so no RPC, WebSocket, or MCP path can accept+one. Guest routes also require T3 Connect to still serve the link's hostname;+the request's Host header is not checked, because a LAN client can forge it.+### MCP clients are a separate audienceAgents T3 Code did not launch sign in to `/mcp` through a narrow OAuthdiff --git a/docs/user/guest-links.md b/docs/user/guest-links.mdnew file mode 100644index 00000000000..de10d16b0ef--- /dev/null+++ b/docs/user/guest-links.md@@ -0,0 +1,48 @@+# Guest links++A guest link lets a teammate follow one thread in their browser and ask the agent questions, with no+account. They see your messages and the agent's replies as they stream. Each message they send waits+until you send or dismiss it.++## Share a thread++Guest links are a beta. Turn on **Settings → Beta → Guest links** for the machine that runs the+thread. They also need [T3 Connect](./remote-access.md): sign in and link that machine, because the+link points at its T3 Connect address. The machine must stay online while the guest uses it.+While the setting is off, every guest link on that machine stops working; links that have not+expired work again when you turn it back on.++1. Right-click the thread in the sidebar and choose **Share with guest**. It is also in the thread+ menu and the command palette.+2. Copy the link and send it to one person. It works in one browser and expires after 24 hours.+ Opening it again in that browser takes them back to the thread.+3. When they send a message, it appears at the end of the thread and the sidebar shows **Request**.+ Choose **Send** to run it as a normal turn, or **Dismiss**. Files they attached show with the+ message, and **Send** includes them.++Choose **Stop sharing** to end the link at once. Archiving the thread, creating a new link, or+unlinking the machine from T3 Connect also ends it. You can send or dismiss guest messages from the mobile app.++## What the guest sees++The guest sees the thread's recent history and everything after, in the same timeline you see, as+it streams: messages and their files, the agent's replies and reasoning, plans, questions, and its+work, with command output when they expand a command. Their composer shows the thread's model, but+they cannot change it. They do not see diffs, and they cannot act on the thread: no forking,+reverting, opening files on your machine, or answering the agent for you.++Anything the agent read or printed can show, such as a value from a file. Share only threads you+are comfortable showing.++## Guest attachments++Guests can attach images and other files to a message: use the paperclip, paste, or drop them on+the message box. A message holds up to 4 files and 10 MB in total. Images must be PNG, JPEG, GIF, or+WebP. While messages wait for you, their files can total 20 MB; the guest can attach more once you+send or dismiss some.++Dismissing a message, ending the link, or archiving the thread deletes the files of messages that+still wait. A sent message keeps its files, like any message in the thread.++The guest's text and files run with the thread's current permission mode once you send them. Check+them before you choose **Send**, as you would anything pasted from a chat.diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex 86d8edde64b..560f7dd7584 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -118,7 +118,7 @@ open.### Fold working threads (beta)-Turn on **Settings → General → Working section (beta)** on web and desktop, or **Settings →+Turn on **Settings → Beta → Working section** on web and desktop, or **Settings →Thread behavior → Working section** on iOS and Android, to move threads that are working orwaiting on work they will resume from into a collapsed **Working** section below the active list.That includes subagents, watched pull requests, and background commands or monitors the agentdiff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex 8a626ac28e7..77bf26182a4 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -8,7 +8,7 @@ import {OrchestrationV2CheckpointUnavailableError,WS_METHODS,type ChatAttachment,- type MessageId,+ MessageId,type ModelSelection,type NodeId,type OrchestrationV2Command,@@ -26,6 +26,7 @@ import {type ThreadId,type ThreadEnvMode,type UploadChatAttachment,+ type GuestMessageId,} from "@t3tools/contracts";import { modelSelectionCommandType } from "@t3tools/shared/model";import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";@@ -418,7 +419,8 @@ function simpleThreadCommand(| "thread.unarchive"| "thread.settle"| "thread.pin"- | "thread.unpin",+ | "thread.unpin"+ | "thread.guest-share.close",input: ThreadCommandInput,) {return allocateCommandId(input).pipe(@@ -432,6 +434,45 @@ export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(functireturn yield* simpleThreadCommand("thread.delete", input);});+export type CloseGuestShareInput = ThreadCommandInput;+export const closeGuestShare = Effect.fn("EnvironmentCommands.closeGuestShare")(function* (+ input: CloseGuestShareInput,+) {+ return yield* simpleThreadCommand("thread.guest-share.close", input);+});++export interface ResolveGuestMessageInput extends ThreadCommandInput {+ readonly guestMessageId: GuestMessageId;+ readonly decision: "send" | "dismiss";+ readonly creationSource?: "web" | "mobile";+}+/** Send runs the guest's text as a normal turn; the server supplies the text, not the client. */+export const resolveGuestMessage = Effect.fn("EnvironmentCommands.resolveGuestMessage")(function* (+ input: ResolveGuestMessageInput,+) {+ const commandId = yield* allocateCommandId(input);+ if (input.decision === "dismiss") {+ return yield* dispatch({+ type: "thread.guest-message.dismiss",+ commandId,+ threadId: input.threadId,+ guestMessageId: input.guestMessageId,+ });+ }+ return yield* dispatch({+ type: "message.dispatch",+ commandId,+ threadId: input.threadId,+ messageId: MessageId.make(commandId),+ guestMessageId: input.guestMessageId,+ text: "",+ attachments: [],+ dispatchMode: { type: "queue_after_active" },+ createdBy: "user",+ creationSource: input.creationSource ?? "web",+ });+});+export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (input: ArchiveThreadInput,) {diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex d5a1bbaccd9..fe3e0d098b7 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -156,6 +156,8 @@ export interface EnvironmentThreadShell {readonly hasPendingApprovals: boolean;readonly hasPendingUserInput: boolean;readonly pendingSubagentRequest?: PendingSubagentRequest | null;+ /** Guest messages waiting for the owner to send or dismiss. */+ readonly pendingGuestMessageCount?: number;readonly hasActionableProposedPlan: boolean;readonly pendingBackgroundTasks: ReadonlyArray<NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]@@ -312,6 +314,7 @@ export function presentThreadShell(thread.pendingRuntimeRequest?.kind === "user_input" &&(thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),pendingSubagentRequest,+ pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,hasActionableProposedPlan: thread.hasActionableProposedPlan,pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],providerInstanceHistory: thread.providerInstanceHistory ?? [],diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.tsindex 506afe1394d..5107d9192b3 100644--- a/packages/client-runtime/src/state/orchestrationV2Projection.ts+++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts@@ -276,6 +276,7 @@ export function applyOrchestrationV2ProjectionEvent(case "thread.interaction-mode-updated":case "thread.model-selection-updated":case "thread.provider-switched":+ case "thread.guest-share-updated":return { ...base, thread: event.payload };// Visited tracking is read state, not activity: skip the updatedAt bump.case "thread.visited":diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 4361592601f..77c5beb61a4 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -1336,6 +1336,10 @@ export function createServerEnvironmentAtoms<R, E>(scheduler: configScheduler,concurrency: configConcurrency,}),+ createGuestShare: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:guest-share:create",+ tag: WS_METHODS.guestShareCreate,+ }),// Off the config lane: answering a card must not queue behind settings// edits. One answer per card at a time.answerSecretRequest: createEnvironmentRpcCommand(runtime, {diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.tsindex c9e33373495..84a290057f5 100644--- a/packages/client-runtime/src/state/threadCommands.ts+++ b/packages/client-runtime/src/state/threadCommands.ts@@ -47,6 +47,8 @@ import {type StartThreadTurnInput,type StopThreadSessionInput,type UnarchiveThreadInput,+ type CloseGuestShareInput,+ type ResolveGuestMessageInput,type UnlinkThreadPullRequestInput,type UnpinThreadInput,type WatchThreadPullRequestInput,@@ -55,6 +57,8 @@ import {type UpdateThreadMetadataInput,type VisitThreadInput,archiveThread,+ closeGuestShare,+ resolveGuestMessage,cancelQueuedRun,createThread,deleteThread,@@ -201,6 +205,18 @@ export function createThreadEnvironmentAtoms<R, E>(scheduler,concurrency,}),+ closeGuestShare: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:thread:close-guest-share",+ execute: (input: CloseGuestShareInput) => closeGuestShare(input),+ scheduler,+ concurrency,+ }),+ resolveGuestMessage: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:thread:resolve-guest-message",+ execute: (input: ResolveGuestMessageInput) => resolveGuestMessage(input),+ scheduler,+ concurrency,+ }),archive: createEnvironmentCommand(runtime, {label: "environment-data:commands:thread:archive",execute: (input: ArchiveThreadInput) => archiveThread(input),diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.tsindex cd156ccdc2e..36ddc1dfd15 100644--- a/packages/client-runtime/src/state/threadSettled.ts+++ b/packages/client-runtime/src/state/threadSettled.ts@@ -77,6 +77,7 @@ export interface ThreadSnoozeShell extends QueuedThreadShell {readonly hasPendingApprovals: boolean;readonly hasPendingUserInput: boolean;readonly pendingSubagentRequest?: PendingSubagentRequest | null;+ readonly pendingGuestMessageCount?: number;}/**@@ -88,6 +89,7 @@ export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): booleanif (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;if (shell.source?.pendingRuntimeRequest != null) return true;if (shell.pendingSubagentRequest != null) return true;+ if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;const failedAt = failureEdgeAt(shell);return (failedAt !== undefined &&@@ -114,6 +116,7 @@ export function canSnooze(| "hasPendingApprovals"| "hasPendingUserInput"| "pendingSubagentRequest"+ | "pendingGuestMessageCount"| "latestUserMessageAt"| "latestTurn"| "latestRun"@@ -127,6 +130,8 @@ export function canSnooze(// The server rejects snoozing even for nonblocking questions.if (shell.source?.pendingRuntimeRequest != null) return false;if (shell.pendingSubagentRequest != null) return false;+ // A waiting guest message would wake it at once.+ if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;if (hasQueuedTurnStart(shell, options)) return false;return true;}diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.tsindex 21139a2c454..701bd4566ea 100644--- a/packages/client-runtime/src/state/threadWorkflows.ts+++ b/packages/client-runtime/src/state/threadWorkflows.ts@@ -143,7 +143,8 @@ export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQuconst message = projection.messages.find((candidate) => candidate.id === run.userMessageId);return {run,- text: message?.text ?? "Queued message",+ // A queued guest message shows the guest's words; the agent still gets the attributed text.+ text: message?.context?.guest?.text ?? message?.text ?? "Queued message",attachments: message?.attachments ?? [],messageId: run.userMessageId,...(message?.context ? { context: message.context } : {}),diff --git a/packages/client-runtime/src/userMessage.test.ts b/packages/client-runtime/src/userMessage.test.tsindex 0f4db1cf26b..0447dc54d1b 100644--- a/packages/client-runtime/src/userMessage.test.ts+++ b/packages/client-runtime/src/userMessage.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vite-plus/test";+import { GuestMessageId } from "@t3tools/contracts";+import { resolveUserMessagePresentation } from "./userMessage.ts";describe("resolveUserMessagePresentation", () => {@@ -19,6 +21,23 @@ describe("resolveUserMessagePresentation", () => {}});+ it("shows a guest's own words and name, not the attributed text the agent reads", () => {+ expect(+ resolveUserMessagePresentation({+ role: "user",+ createdBy: "user",+ text: "Message from guest Sam, sent by the owner:\n\nWhy?",+ context: {+ guest: {+ guestMessageId: GuestMessageId.make("guest-message:one"),+ name: "Sam",+ text: "Why?",+ },+ },+ }),+ ).toEqual({ text: "Why?", attribution: "guest", scheduledTaskId: undefined, guestName: "Sam" });+ });+it("attributes older server-sent restart continuations to T3 Code, not another agent", () => {const text = "Note: the T3 server restarted.";expect(diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.tsindex 93ed98f35fe..8f5eb2e2ffe 100644--- a/packages/client-runtime/src/userMessage.ts+++ b/packages/client-runtime/src/userMessage.ts@@ -1,4 +1,5 @@import {+ type GuestMessageAttribution,type OrchestrationV2Actor,type OrchestrationV2CreationSource,type OrchestrationV2IdleCompaction,@@ -27,14 +28,27 @@ export function resolveUserMessagePresentation(message: {readonly createdBy?: OrchestrationV2Actor;readonly creationSource?: OrchestrationV2CreationSource;readonly scheduledTaskId?: ScheduledTaskId;+ readonly context?: { readonly guest?: GuestMessageAttribution | undefined } | undefined;}): {readonly text: string;- readonly attribution: "automation" | "agent" | "t3code" | null;+ readonly attribution: "automation" | "agent" | "t3code" | "guest" | null;readonly scheduledTaskId: ScheduledTaskId | undefined;+ /** Set when `attribution` is "guest". */+ readonly guestName?: string;} {if (message.role !== "user") {return { text: message.text, attribution: null, scheduledTaskId: undefined };}+ // The stored text names the guest for the agent; people see the guest's own words.+ const guest = message.context?.guest;+ if (guest !== undefined) {+ return {+ text: guest.text,+ attribution: "guest",+ scheduledTaskId: undefined,+ guestName: guest.name,+ };+ }if (message.scheduledTaskId !== undefined) {return {text: message.text,diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.tsindex 60cf9df62c3..e7492c129a4 100644--- a/packages/contracts/src/baseSchemas.ts+++ b/packages/contracts/src/baseSchemas.ts@@ -279,6 +279,10 @@ export const RunAttemptId = makeEntityId("RunAttemptId");export type RunAttemptId = typeof RunAttemptId.Type;export const NodeId = makeEntityId("NodeId");export type NodeId = typeof NodeId.Type;+export const GuestShareId = makeEntityId("GuestShareId");+export type GuestShareId = typeof GuestShareId.Type;+export const GuestMessageId = makeEntityId("GuestMessageId");+export type GuestMessageId = typeof GuestMessageId.Type;export const AuthSessionId = makeEntityId("AuthSessionId");export type AuthSessionId = typeof AuthSessionId.Type;export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.tsindex f9eaedb48bd..3fda40a04a0 100644--- a/packages/contracts/src/clientRpcPermissions.ts+++ b/packages/contracts/src/clientRpcPermissions.ts@@ -1,6 +1,7 @@import * as Schema from "effect/Schema";import { GitPreparePullRequestThreadInput, GitRunStackedActionInput } from "./git.ts";import {+ AuthAccessWriteScope,AuthOrchestrationOperateScope,AuthOrchestrationReadScope,AuthPreviewOperateScope,@@ -49,6 +50,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {[WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope,[WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,+ // A guest link hands thread access to someone outside, like a pairing link.+ [WS_METHODS.guestShareCreate]: AuthAccessWriteScope,} as const;export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;diff --git a/packages/contracts/src/composerContext.ts b/packages/contracts/src/composerContext.tsindex 0f6e9cce329..3d00d3b8f7e 100644--- a/packages/contracts/src/composerContext.ts+++ b/packages/contracts/src/composerContext.ts@@ -3,11 +3,14 @@ import * as Schema from "effect/Schema";import {EnvironmentId,ForwardCompatibleArray,+ GuestMessageId,+ GuestShareId,NonNegativeInt,PositiveInt,ThreadId,TrimmedNonEmptyString,} from "./baseSchemas.ts";+import { GUEST_MESSAGE_MAX_LENGTH, GUEST_NAME_MAX_LENGTH } from "./guestShare.ts";/*** Bytes never live here: image and file records bind to a `ChatAttachment` by id.@@ -258,9 +261,23 @@ export type ComposerContextRecord = typeof ComposerContextRecord.Type;export const COMPOSER_CONTEXT_MAX_RECORDS = 200;const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000;+/**+ * Marks a user message as a guest's, sent by the owner. The message `text` keeps the attributed+ * form the agent reads; clients show `text` here with `name` beside it. Only the server sets it.+ */+export const GuestMessageAttribution = Schema.Struct({+ guestMessageId: GuestMessageId,+ name: TrimmedNonEmptyString.check(Schema.isMaxLength(GUEST_NAME_MAX_LENGTH)),+ text: Schema.String.check(Schema.isMaxLength(GUEST_MESSAGE_MAX_LENGTH)),+ /** The link the guest used. Only that link's guest may load the message's files. */+ shareId: Schema.optional(GuestShareId),+});+export type GuestMessageAttribution = typeof GuestMessageAttribution.Type;+/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */export const OrchestrationMessageContext = Schema.Struct({version: Schema.Literal(1),+ guest: Schema.optional(GuestMessageAttribution),records: Schema.Array(Schema.Unknown).check(Schema.isMaxLength(COMPOSER_CONTEXT_MAX_RECORDS),diff --git a/packages/contracts/src/guestShare.test.ts b/packages/contracts/src/guestShare.test.tsnew file mode 100644index 00000000000..49acfe7ff57--- /dev/null+++ b/packages/contracts/src/guestShare.test.ts@@ -0,0 +1,22 @@+import * as Schema from "effect/Schema";+import { describe, expect, it } from "vite-plus/test";++import { GuestRedeemRequest } from "./guestShare.ts";++const isRedeem = Schema.is(GuestRedeemRequest);++describe("GuestRedeemRequest", () => {+ it("accepts a one-line name and rejects names that break the attribution line", () => {+ expect(isRedeem({ credential: "invite", name: "Maya Chen" })).toBe(true);+ for (const name of [+ "Maya\nowner",+ "Maya owner",+ "Maya owner",+ "Maya\u0007",+ "Theo\u202E (owner)",+ "Theo\u2066x",+ ]) {+ expect(isRedeem({ credential: "invite", name })).toBe(false);+ }+ });+});diff --git a/packages/contracts/src/guestShare.ts b/packages/contracts/src/guestShare.tsnew file mode 100644index 00000000000..e78c26dc592--- /dev/null+++ b/packages/contracts/src/guestShare.ts@@ -0,0 +1,138 @@+import * as Schema from "effect/Schema";++import { ChatAttachment } from "./chatAttachment.ts";+import {+ GuestMessageId,+ GuestShareId,+ IsoDateTime,+ ThreadId,+ TrimmedNonEmptyString,+ TrimmedString,+} from "./baseSchemas.ts";++/**+ * A guest share lets one unauthenticated browser watch a thread over T3 Connect and propose+ * messages the owner must send or dismiss. The thread projection holds this public state; the+ * credentials are derived from the share id with a server key and never stored.+ */+export const GUEST_SHARE_TTL_MS = 24 * 60 * 60 * 1000;+export const GUEST_MESSAGE_MAX_LENGTH = 4_000;+export const GUEST_NAME_MAX_LENGTH = 40;+export const GUEST_PENDING_MESSAGE_LIMIT = 3;+/** Resolved messages kept so the guest can see what happened to what they sent. */+export const GUEST_RESOLVED_MESSAGE_LIMIT = 20;+/** Files a guest can attach to one message, and their total size. */+export const GUEST_MESSAGE_MAX_ATTACHMENTS = 4;+export const GUEST_MESSAGE_MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;+/** Total size of the files in a share's waiting messages, so a guest cannot fill the disk. */+export const GUEST_PENDING_ATTACHMENT_BYTES_LIMIT = 20 * 1024 * 1024;++export const ThreadGuestMessageStatus = Schema.Literals(["pending", "sent", "dismissed"]);+export type ThreadGuestMessageStatus = typeof ThreadGuestMessageStatus.Type;++export const ThreadGuestMessage = Schema.Struct({+ id: GuestMessageId,+ text: Schema.String,+ status: ThreadGuestMessageStatus,+ submittedAt: IsoDateTime,+ /** The thread's attachments, deleted if the message is dismissed. Absent on older messages. */+ attachments: Schema.optional(Schema.Array(ChatAttachment)),+});+export type ThreadGuestMessage = typeof ThreadGuestMessage.Type;++export const ThreadGuestShare = Schema.Struct({+ id: GuestShareId,+ /** The T3 Connect tunnel hostname the link points at. Guest routes require it to still serve. */+ host: TrimmedNonEmptyString,+ createdAt: IsoDateTime,+ expiresAt: IsoDateTime,+ /** Set once, when the guest redeems the link. */+ guestName: Schema.NullOr(TrimmedNonEmptyString),+ messages: Schema.Array(ThreadGuestMessage),+});+export type ThreadGuestShare = typeof ThreadGuestShare.Type;++export const pendingGuestMessageCount = (share: ThreadGuestShare | null | undefined): number =>+ share?.messages.filter((message) => message.status === "pending").length ?? 0;++export const GuestShareCreateInput = Schema.Struct({ threadId: ThreadId });+export type GuestShareCreateInput = typeof GuestShareCreateInput.Type;++export const GuestShareCreateResult = Schema.Struct({+ url: TrimmedNonEmptyString,+ share: ThreadGuestShare,+});+export type GuestShareCreateResult = typeof GuestShareCreateResult.Type;++const GUEST_SHARE_CREATE_MESSAGES = {+ disabled: "Guest links are off. Turn them on in Settings > Beta.",+ connect_unavailable: "Guest links need a running T3 Connect tunnel.",+ thread_unavailable: "This thread cannot be shared.",+ read_failed: "Failed to read the shared thread.",+ changed: "The guest link changed while it was being created.",+} as const;++export class GuestShareCreateError extends Schema.TaggedError<GuestShareCreateError>()(+ "GuestShareCreateError",+ {+ reason: Schema.Literals([+ "disabled",+ "connect_unavailable",+ "thread_unavailable",+ "read_failed",+ "changed",+ ]),+ },+) {+ override get message(): string {+ return GUEST_SHARE_CREATE_MESSAGES[this.reason];+ }+}++// The name lands in the agent's attribution line, so it must stay one plain line, and the owner+// reads it, so direction overrides cannot make it look like another name.+const NAME_BREAKING_CHARACTER = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/u;++export const GuestRedeemRequest = Schema.Struct({+ credential: TrimmedNonEmptyString,+ name: TrimmedNonEmptyString.check(+ Schema.isMaxLength(GUEST_NAME_MAX_LENGTH),+ Schema.makeFilter((name) => !NAME_BREAKING_CHARACTER.test(name), {+ description: "a single line of text",+ }),+ ),+});+export type GuestRedeemRequest = typeof GuestRedeemRequest.Type;++/**+ * The fields of a guest message. The page posts them as multipart form data, with each file as a+ * `file` part; text can be empty when files are attached.+ */+export const GuestSubmitRequest = Schema.Struct({+ /** The share the page shows, so a message from a page for a replaced link is refused instead+ of reaching the new one. */+ shareId: GuestShareId,+ text: TrimmedString.check(Schema.isMaxLength(GUEST_MESSAGE_MAX_LENGTH)),+});+export type GuestSubmitRequest = typeof GuestSubmitRequest.Type;++export const GUEST_ROUTE_PREFIX = "/api/guest";+/** The guest page and guest routes name the share they mean with this query parameter. */+export const GUEST_SHARE_PARAM = "share";++/**+ * One session cookie per share, so a guest keeps every link they joined on a host, and a page+ * for one share never acts with another share's session.+ */+export const guestSessionCookieName = (shareId: string) => `t3_guest_${shareId}`;+/** Serves one HTML render in the shared thread: `?share=<share id>&item=<turn item id>`. */+export const GUEST_RENDER_ROUTE = `${GUEST_ROUTE_PREFIX}/render`;+/** One item of the shared thread, as an expanded row loads it: `?share=<share id>&item=<id>`. */+export const GUEST_ITEM_ROUTE = `${GUEST_ROUTE_PREFIX}/item`;+/** Server-sent output frames of one command in the shared thread: `?share=<share id>&item=<id>`. */+export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output`;+/**+ * A file in the shared thread or a guest's waiting message: `?share=<share id>&id=<attachment id>`.+ * Images load inline; other files download.+ */+export const GUEST_ATTACHMENT_ROUTE = `${GUEST_ROUTE_PREFIX}/attachment`;diff --git a/packages/contracts/src/guestStream.ts b/packages/contracts/src/guestStream.tsnew file mode 100644index 00000000000..575cac74dd0--- /dev/null+++ b/packages/contracts/src/guestStream.ts@@ -0,0 +1,42 @@+import * as Schema from "effect/Schema";++import { GuestShareId, IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas.ts";+import { ThreadGuestMessage } from "./guestShare.ts";+import { OrchestrationV2ThreadStreamItem } from "./orchestrationV2.ts";+import { ProviderDriverKind } from "./providerInstance.ts";++// This lives apart from guestShare.ts because orchestrationV2.ts imports that file.++/**+ * What the composer's model label shows; nothing else from the owner's provider settings. The+ * driver is null when the thread's provider is no longer configured.+ */+export const GuestThreadModel = Schema.Struct({+ driver: Schema.NullOr(ProviderDriverKind),+ name: TrimmedNonEmptyString,+ shortName: Schema.optional(TrimmedNonEmptyString),+ subProvider: Schema.optional(TrimmedNonEmptyString),+});+export type GuestThreadModel = typeof GuestThreadModel.Type;++export const GuestShareView = Schema.Struct({+ shareId: GuestShareId,+ title: Schema.String,+ guestName: TrimmedNonEmptyString,+ expiresAt: IsoDateTime,+ messages: Schema.Array(ThreadGuestMessage),+ model: GuestThreadModel,+});+export type GuestShareView = typeof GuestShareView.Type;++/**+ * The shared thread as the owner's client gets it: `thread` carries the same stream items the+ * owner's thread subscription sends, starting with a snapshot on every (re)connect. `view` is the+ * share itself, sent first and again when it changes.+ */+export const GuestStreamEvent = Schema.Union([+ Schema.Struct({ type: Schema.Literal("view"), view: GuestShareView }),+ Schema.Struct({ type: Schema.Literal("thread"), item: OrchestrationV2ThreadStreamItem }),+ Schema.Struct({ type: Schema.Literal("ended") }),+]);+export type GuestStreamEvent = typeof GuestStreamEvent.Type;diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.tsindex 7f38a38dbba..38c28ab65a2 100644--- a/packages/contracts/src/index.ts+++ b/packages/contracts/src/index.ts@@ -37,6 +37,8 @@ export * from "./pullRequestReviewGuide.ts";export * from "./orchestrationDispatch.ts";export * from "./orchestrationProject.ts";export * from "./orchestrationV2.ts";+export * from "./guestShare.ts";+export * from "./guestStream.ts";export * from "./applicationEvent.ts";export * from "./orchestratorMcp.ts";export * from "./threadMetadataMcp.ts";diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 8897ead60f9..258f29cba11 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -13,6 +13,8 @@ import {ContextHandoffId,ContextTransferId,EventId,+ GuestMessageId,+ GuestShareId,IsoDateTime,MessageId,NodeId,@@ -37,6 +39,7 @@ import {TurnItemId,} from "./baseSchemas.ts";import { ChatAttachment } from "./chatAttachment.ts";+import { ThreadGuestShare } from "./guestShare.ts";import {OrchestrationGetFullThreadDiffInput,OrchestrationGetFullThreadDiffResult,@@ -434,6 +437,7 @@ export const OrchestrationV2AppThread = Schema.Struct({snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)),+ guestShare: Schema.optional(Schema.NullOr(ThreadGuestShare)),pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),@@ -1704,6 +1708,7 @@ export const OrchestrationV2DomainEvent = Schema.Union(["thread.interaction-mode-updated","thread.model-selection-updated","thread.provider-switched",+ "thread.guest-share-updated",]),payload: OrchestrationV2AppThread,}),@@ -1918,6 +1923,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({lastErrorCode: Schema.optional(Schema.NullOr(Schema.String)),usageLimitResetAt: Schema.optional(Schema.NullOr(IsoDateTime)),pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary),+ /** Guest messages waiting for the owner to send or dismiss. Absent from older servers. */+ pendingGuestMessageCount: Schema.optional(NonNegativeInt),latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary),latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc),/**@@ -2551,6 +2558,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union(["thread.interaction-mode-updated","thread.model-selection-updated","thread.provider-switched",+ "thread.guest-share-updated",]),payload: OrchestrationV2AppThreadJson,}),@@ -2714,6 +2722,17 @@ export const OrchestrationV2Command = Schema.Union([commandId: CommandId,threadId: ThreadId,}),+ Schema.Struct({+ type: Schema.Literal("thread.guest-share.close"),+ commandId: CommandId,+ threadId: ThreadId,+ }),+ Schema.Struct({+ type: Schema.Literal("thread.guest-message.dismiss"),+ commandId: CommandId,+ threadId: ThreadId,+ guestMessageId: GuestMessageId,+ }),Schema.Struct({type: Schema.Literal("thread.unarchive"),commandId: CommandId,@@ -2908,6 +2927,8 @@ export const OrchestrationV2Command = Schema.Union([Schema.Struct({type: Schema.Literal("message.dispatch"),notification: Schema.optional(OrchestrationV2Notification),+ /** Sends this pending guest message; the server uses the guest's text, not `text`. */+ guestMessageId: Schema.optional(GuestMessageId),...OrchestrationV2CreationFields,scheduledTaskId: Schema.optional(ScheduledTaskId),senderThreadId: Schema.optional(ThreadId),@@ -3139,6 +3160,31 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type;* send them.*/const OrchestrationV2InternalCommand = Schema.Union([+ // Guest share commands the server issues after checking T3 Connect and the guest token.+ Schema.Struct({+ type: Schema.Literal("thread.guest-share.open"),+ commandId: CommandId,+ threadId: ThreadId,+ shareId: GuestShareId,+ host: TrimmedNonEmptyString,+ expiresAt: IsoDateTime,+ }),+ Schema.Struct({+ type: Schema.Literal("thread.guest-share.redeem"),+ commandId: CommandId,+ threadId: ThreadId,+ shareId: GuestShareId,+ guestName: TrimmedNonEmptyString,+ }),+ Schema.Struct({+ type: Schema.Literal("thread.guest-message.submit"),+ commandId: CommandId,+ threadId: ThreadId,+ shareId: GuestShareId,+ guestMessageId: GuestMessageId,+ text: Schema.String,+ attachments: Schema.optional(Schema.Array(ChatAttachment)),+ }),Schema.Struct({type: Schema.Literal("thread.pull-request-watch.sync"),commandId: CommandId,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 9257872ffab..9b53b5c14d6 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -161,6 +161,11 @@ import {ProviderUploadFeedbackResult,} from "./provider.ts";import { ProviderInstanceId, ProviderInstanceMutation } from "./providerInstance.ts";+import {+ GuestShareCreateError,+ GuestShareCreateInput,+ GuestShareCreateResult,+} from "./guestShare.ts";import { PullRequestReviewGuideResult } from "./pullRequestReviewGuide.ts";import {PullRequestActionInput,@@ -520,6 +525,7 @@ export const WS_METHODS = {scheduledTasksRunNow: "scheduledTasks.runNow",scheduledTasksRotateWebhookToken: "scheduledTasks.rotateWebhookToken",secretsAnswerRequest: "secrets.answerRequest",+ guestShareCreate: "guestShare.create",scheduledTasksListWebhookDeliveries: "scheduledTasks.listWebhookDeliveries",scheduledTasksGetWebhookDelivery: "scheduledTasks.getWebhookDelivery",@@ -1854,6 +1860,12 @@ const WsScheduledTasksRotateWebhookTokenRpc = Rpc.make(},);+const WsGuestShareCreateRpc = Rpc.make(WS_METHODS.guestShareCreate, {+ payload: GuestShareCreateInput,+ success: GuestShareCreateResult,+ error: Schema.Union([GuestShareCreateError, EnvironmentAuthorizationError]),+});+const WsSecretsAnswerRequestRpc = Rpc.make(WS_METHODS.secretsAnswerRequest, {payload: SecretRequestAnswerInput,error: Schema.Union([SecretRequestError, EnvironmentAuthorizationError]),@@ -1904,6 +1916,7 @@ export class RpcScopeAuthorization extends RpcMiddleware.Service<RpcScopeAuthori) {}export const WsRpcGroup = RpcGroup.make(+ WsGuestShareCreateRpc,WsServerProbeRpc,WsServerGetConfigRpc,WsServerRefreshProvidersRpc,diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 9f84636d12b..b6187f33f17 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1204,6 +1204,8 @@ export const ServerSettings = Schema.Struct({idleCompaction: Schema.optionalKey(IdleCompactionMode),snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),+ /** Beta: guest links for this machine's threads. Off refuses new links and pauses existing ones. */+ guestSharingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false)),),@@ -1572,6 +1574,7 @@ export const ServerSettingsPatch = Schema.Struct({sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean),+ guestSharingEnabled: Schema.optionalKey(Schema.Boolean),backgroundActivity: Schema.optionalKey(Schema.Struct({schemaVersion: Schema.optionalKey(Schema.Literal(1)),diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.tsindex d5e87153ea1..f97b89c097f 100644--- a/packages/provider-core/src/server/subagentProjection.ts+++ b/packages/provider-core/src/server/subagentProjection.ts@@ -82,6 +82,8 @@ export function makeSubagentChildThread(input: {settledAt: null,snoozedUntil: null,snoozedAt: null,+ // A guest link belongs to the thread it was made for.+ guestShare: null,lastVisitedAt: null,deletedAt: null,};