@devries-cameron20 / t3code-1 / commits / fb76594d7b
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat: share a thread with a guest who watches live and sends messages you approve (#24104)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 24, 2026 at 18:48 UTC fb76594d7b9f38d27d8d093733a791d0005c921c
109 files changed +6770 -187
apps/mobile/generated-uniwind-themes.css
+24
@@ -110,6 +110,8 @@
110 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);
111 --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);
112 --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);
113 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);
114 + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);
115 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);
116 --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);
117 --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);
@@ -271,6 +273,8 @@
273 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);
274 --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);
275 --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);
276 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);
277 + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);
278 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);
279 --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);
280 --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);
@@ -432,6 +436,8 @@
436 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);
437 --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);
438 --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);
439 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);
440 + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);
441 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);
442 --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);
443 --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);
@@ -593,6 +599,8 @@
599 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);
600 --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);
601 --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);
602 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);
603 + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);
604 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);
605 --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);
606 --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);
@@ -754,6 +762,8 @@
762 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);
763 --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);
764 --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);
765 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);
766 + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);
767 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);
768 --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);
769 --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);
@@ -915,6 +925,8 @@
925 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);
926 --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);
927 --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);
928 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);
929 + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);
930 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);
931 --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);
932 --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);
@@ -1076,6 +1088,8 @@
1088 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);
1089 --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);
1090 --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);
1091 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);
1092 + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);
1093 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);
1094 --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);
1095 --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);
@@ -1237,6 +1251,8 @@
1251 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);
1252 --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);
1253 --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);
1254 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);
1255 + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);
1256 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);
1257 --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);
1258 --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);
@@ -1398,6 +1414,8 @@
1414 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);
1415 --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);
1416 --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);
1417 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);
1418 + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);
1419 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);
1420 --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);
1421 --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);
@@ -1559,6 +1577,8 @@
1577 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);
1578 --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);
1579 --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);
1580 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);
1581 + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);
1582 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);
1583 --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);
1584 --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);
@@ -1720,6 +1740,8 @@
1740 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%);
1741 --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225);
1742 --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612);
1743 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%);
1744 + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896);
1745 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%);
1746 --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966);
1747 --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023);
@@ -1881,6 +1903,8 @@
1903 --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%);
1904 --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223);
1905 --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978);
1906 + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%);
1907 + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434);
1908 --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%);
1909 --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713);
1910 --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713);
apps/mobile/scripts/generate-uniwind-themes.mts
+5
@@ -86,6 +86,11 @@ const ADAPTIVE_COLORS: Readonly<Record<string, readonly [light: string, dark: st
86 ],
87 "--color-adaptive-emerald-600-400": [color("emerald", 600), color("emerald", 400)],
88 "--color-adaptive-emerald-700-300": [color("emerald", 700), color("emerald", 300)],
89 + "--color-adaptive-fuchsia-500-a50-300-a40": [
90 + color("fuchsia", 500, 0.5),
91 + color("fuchsia", 300, 0.4),
92 + ],
93 + "--color-adaptive-fuchsia-600-300": [color("fuchsia", 600), color("fuchsia", 300)],
94 "--color-adaptive-indigo-500-a12-a16": [color("indigo", 500, 0.12), color("indigo", 500, 0.16)],
95 "--color-adaptive-indigo-600-300": [color("indigo", 600), color("indigo", 300)],
96 "--color-adaptive-indigo-700-300": [color("indigo", 700), color("indigo", 300)],
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+5
@@ -188,6 +188,7 @@ import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
188 import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
189 import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
190 import { useThreadQueuedCount } from "./ThreadQueueControl";
191 +import { ThreadGuestShareBar } from "./ThreadGuestShareBar";
192 import type { ThreadContentPresentation } from "./threadContentPresentation";
193 import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
194 import { useOpenLinkedThread } from "./useOpenLinkedThread";
@@ -1632,6 +1633,10 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1633 key={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}
1634 thread={props.selectedThread}
1635 />
1636 + <ThreadGuestShareBar
1637 + threadRef={props.selectedThreadDetailRef}
1638 + canOperateThread={props.canOperateThread}
1639 + />
1640 {props.feedbackSubmissions.map((submission) => (
1641 <ComposerFeedback
1642 key={submission.id}
apps/mobile/src/features/threads/ThreadFeed.tsx
+81 -30
@@ -16,6 +16,8 @@ import {
16 } from "../../lib/enrichedLinkPresentation";
17 import { ThreadContextDivider } from "./thread-context-divider";
18 import { ThreadHandoffDivider, ThreadHandoffRow } from "./thread-handoff-row";
19 +import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle";
20 +import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar";
21 import { SecretRequestCard } from "./SecretRequestCard";
22 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
23 import {
@@ -229,9 +231,11 @@ import {
231 WORK_GROUP_TOGGLE_HEIGHT,
232 } from "./thread-work-log";
233 import {
234 + appendGuestPendingMessages,
235 appendPendingThreadMessages,
236 isCompactionCommandFeedEntry,
237 type PendingThreadFeedEntry,
238 + type ThreadFeedRow,
239 } from "./pending-thread-feed";
240 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
241 import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";
@@ -760,6 +764,38 @@ function MessageAttachmentFile(props: {
764 );
765 }
766
767 +/** A message's files as its bubble shows them; a guest's waiting message uses it too. */
768 +function MessageAttachmentList(props: {
769 + readonly attachments: ReadonlyArray<ChatAttachment>;
770 + readonly environmentId: EnvironmentId;
771 + readonly onPressPreview: (source: FilePreviewSource) => void;
772 + readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;
773 +}) {
774 + return props.attachments.map((attachment) =>
775 + isImageAttachment(attachment) ? (
776 + <MessageAttachmentImage
777 + key={attachment.id}
778 + environmentId={props.environmentId}
779 + attachmentId={attachment.id}
780 + name={attachment.name}
781 + mimeType={attachment.mimeType}
782 + className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-subtle-strong"
783 + onPressPreview={props.onPressPreview}
784 + />
785 + ) : isFileAttachment(attachment) ? (
786 + <MessageAttachmentFile
787 + key={attachment.id}
788 + environmentId={props.environmentId}
789 + attachment={attachment}
790 + onPressPreview={props.onPressPreview}
791 + onPressVideo={props.onPressVideo}
792 + />
793 + ) : (
794 + <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
795 + ),
796 + );
797 +}
798 +
799 function MessageAttachmentUnknown(props: { readonly name: string }) {
800 return (
801 <View className="flex-row items-center gap-2 py-1">
@@ -1203,7 +1239,7 @@ function compactionLabel(label: string, title: string | undefined) {
1239 }
1240
1241 function renderFeedEntry(
1206 - info: { item: PendingThreadFeedEntry; index: number },
1242 + info: { item: ThreadFeedRow; index: number },
1243 props: Pick<
1244 ThreadFeedProps,
1245 | "environmentId"
@@ -1251,6 +1287,25 @@ function renderFeedEntry(
1287 const entry = info.item;
1288 const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
1289
1290 + if (entry.type === "guest-pending") {
1291 + return (
1292 + <ThreadGuestPendingMessage
1293 + threadRef={scopeThreadRef(props.environmentId, props.threadId)}
1294 + guestName={entry.guestName}
1295 + message={entry.message}
1296 + bubbleMaxWidth={props.duoColumns ? "85%" : props.userBubbleMaxWidth}
1297 + renderAttachments={(attachments) => (
1298 + <MessageAttachmentList
1299 + attachments={attachments}
1300 + environmentId={props.environmentId}
1301 + onPressPreview={props.onPressPreview}
1302 + onPressVideo={props.onPressVideo}
1303 + />
1304 + )}
1305 + />
1306 + );
1307 + }
1308 +
1309 if (entry.type === "run-fold") {
1310 return (
1311 <View className="mb-1 flex-row items-center border-b border-border-subtle px-2">
@@ -1504,6 +1559,9 @@ function renderFeedEntry(
1559 Sent by T3 Code
1560 </Text>
1561 ) : null}
1562 + {presentation.guestName !== undefined ? (
1563 + <GuestMessageName name={presentation.guestName} />
1564 + ) : null}
1565 <View
1566 className="min-w-0 rounded-[20px]"
1567 style={{
@@ -1518,6 +1576,7 @@ function renderFeedEntry(
1576 : null),
1577 }}
1578 >
1579 + {presentation.attribution === "guest" ? <GuestBubbleTint /> : null}
1580 {foldRowId !== null ? (
1581 <AgentMessageFoldHeader
1582 environmentId={props.environmentId}
@@ -1676,7 +1735,7 @@ function renderFeedEntry(
1735 <UserMessageCopyButton
1736 text={presentation.text}
1737 onCopy={
1679 - message.context
1738 + message.context && presentation.attribution !== "guest"
1739 ? () =>
1740 writeComposerContextClipboard(message.text, {
1741 version: 1,
@@ -1722,29 +1781,12 @@ function renderFeedEntry(
1781 />
1782 </MarkdownImageAvailableWidthContext>
1783 ) : null}
1725 - {attachments.map((attachment) => {
1726 - return isImageAttachment(attachment) ? (
1727 - <MessageAttachmentImage
1728 - key={attachment.id}
1729 - environmentId={props.environmentId}
1730 - attachmentId={attachment.id}
1731 - name={attachment.name}
1732 - mimeType={attachment.mimeType}
1733 - className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-subtle-strong"
1734 - onPressPreview={props.onPressPreview}
1735 - />
1736 - ) : isFileAttachment(attachment) ? (
1737 - <MessageAttachmentFile
1738 - key={attachment.id}
1739 - environmentId={props.environmentId}
1740 - attachment={attachment}
1741 - onPressPreview={props.onPressPreview}
1742 - onPressVideo={props.onPressVideo}
1743 - />
1744 - ) : (
1745 - <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
1746 - );
1747 - })}
1784 + <MessageAttachmentList
1785 + attachments={attachments}
1786 + environmentId={props.environmentId}
1787 + onPressPreview={props.onPressPreview}
1788 + onPressVideo={props.onPressVideo}
1789 + />
1790 {showAssistantMeta && message.checkpointSummary ? (
1791 <TurnDiffStat
1792 checkpoint={message.checkpointSummary}
@@ -2067,6 +2109,11 @@ function useThreadFeedPresentation(
2109 export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2110 const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;
2111 const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);
2112 + const guestThreadRef = useMemo(
2113 + () => scopeThreadRef(props.environmentId, props.threadId),
2114 + [props.environmentId, props.threadId],
2115 + );
2116 + const guestShare = useThreadGuestShare(guestThreadRef);
2117 const deviceType = useDeviceType();
2118 const duoColumns = useNativeWorkspaceColumnsSupported() && isDuoDevice(deviceType);
2119 const openPullRequest = useOpenPullRequest();
@@ -2662,7 +2709,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2709 reportHeaderMaterialVisibility(false);
2710 }, [feedThreadKey, reportHeaderMaterialVisibility]);
2711
2665 - const presentedFeed = useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups);
2712 + const presentedFeed = appendGuestPendingMessages(
2713 + useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups),
2714 + guestShare,
2715 + );
2716 const setupAnchorIndex = presentedFeed.findIndex(
2717 (entry) => entry.type === "message" && entry.message.role === "user",
2718 );
@@ -2880,7 +2930,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2930 }
2931 };
2932
2883 - const shouldRestoreVisibleContentPosition = (entry: ThreadFeedEntry) => {
2933 + const shouldRestoreVisibleContentPosition = (entry: ThreadFeedRow) => {
2934 const disclosureAnchorKey = disclosureAnchorKeyRef.current;
2935 return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
2936 };
@@ -2964,7 +3014,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3014 // Without this, every row above the viewport is assumed to be
3015 // estimatedItemSize tall, and scrolling up through unmeasured content
3016 // corrects each row's height as it mounts — the feed visibly jumps.
2967 - const getFixedItemSize = (entry: ThreadFeedEntry) => {
3017 + const getFixedItemSize = (entry: ThreadFeedRow) => {
3018 + if (entry.type === "guest-pending") return undefined;
3019 if (entry.type === "html-render") {
3020 return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth));
3021 }
@@ -3010,7 +3061,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3061 if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" });
3062 }, [beginReflow, contentWidth, hasHtmlRenders, listRef]);
3063
3013 - const renderItem = (info: { item: PendingThreadFeedEntry; index: number }) => (
3064 + const renderItem = (info: { item: ThreadFeedRow; index: number }) => (
3065 <Animated.View
3066 key={info.item.id}
3067 entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}
@@ -3301,7 +3352,7 @@ function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) {
3352 }
3353
3354 function MessageImageGalleryScope(props: {
3304 - entry: PendingThreadFeedEntry;
3355 + entry: ThreadFeedRow;
3356 environmentId: EnvironmentId;
3357 threadId: ThreadId;
3358 workspaceRoot: string | null | undefined;
apps/mobile/src/features/threads/ThreadGuestShareBar.tsx new
+189
@@ -0,0 +1,189 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + type AtomCommandResult,
4 + isAtomCommandInterrupted,
5 + squashAtomCommandFailure,
6 +} from "@t3tools/client-runtime/state/runtime";
7 +import {
8 + AuthOrchestrationOperateScope,
9 + type ChatAttachment,
10 + type ScopedThreadRef,
11 + type ThreadGuestMessage,
12 + type ThreadGuestShare,
13 +} from "@t3tools/contracts";
14 +import { Atom } from "effect/reactivity";
15 +import { type ReactNode, useEffect, useMemo, useState } from "react";
16 +import { View } from "react-native";
17 +
18 +import { Button } from "../../components/ui/Button";
19 +import { AppText as Text } from "../../components/ui/AppText";
20 +import { SymbolView } from "../../components/ui/AppSymbol";
21 +import * as Dialog from "../../components/ui/Dialog";
22 +import { useEnvironmentScope } from "../../state/session";
23 +import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
24 +import { useAtomCommand } from "../../state/use-atom-command";
25 +import { GUEST_PENDING_BUBBLE_CLASS_NAME, GuestMessageName } from "./guestMessageStyle";
26 +
27 +const NO_GUEST_SHARE_ATOM = Atom.make<ThreadGuestShare | null>(null);
28 +
29 +function guestShareAtom(ref: ScopedThreadRef) {
30 + let previous: ThreadGuestShare | null = null;
31 + return Atom.make((get) => {
32 + const next =
33 + get(environmentThreadDetails.threadAtom(ref))?.projection.thread.guestShare ?? null;
34 + // The thread record is replaced on unrelated updates; only share changes matter here.
35 + if (JSON.stringify(next) !== JSON.stringify(previous)) previous = next;
36 + return previous;
37 + });
38 +}
39 +
40 +export function useThreadGuestShare(threadRef: ScopedThreadRef | null): ThreadGuestShare | null {
41 + const shareAtom = useMemo(
42 + () => (threadRef === null ? NO_GUEST_SHARE_ATOM : guestShareAtom(threadRef)),
43 + [threadRef],
44 + );
45 + return useAtomValue(shareAtom);
46 +}
47 +
48 +function alertOnFailure(failureTitle: string, result: AtomCommandResult<unknown, unknown>) {
49 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
50 + const error = squashAtomCommandFailure(result);
51 + Dialog.alert(failureTitle, error instanceof Error ? error.message : "Try again.");
52 + }
53 +}
54 +
55 +/**
56 + * Owner controls for a guest link, above the composer: who the link is for and a way to stop
57 + * sharing. Links are created on web. Waiting messages show in the feed, see
58 + * `ThreadGuestPendingMessage`.
59 + */
60 +export function ThreadGuestShareBar(props: {
61 + readonly threadRef: ScopedThreadRef | null;
62 + readonly canOperateThread: boolean;
63 +}) {
64 + const { threadRef } = props;
65 + const share = useThreadGuestShare(threadRef);
66 + const closeGuestShare = useAtomCommand(threadEnvironment.closeGuestShare, "stop guest sharing");
67 + const [busy, setBusy] = useState(false);
68 + // The server keeps an expired link so waiting messages stay resolvable; the label flips when
69 + // it expires.
70 + // Keyed by the expiry, so a replaced link (even one already expired) gets its own timer.
71 + const [expiredAt, setExpiredAt] = useState<string | null>(null);
72 + const expiresAt = share?.expiresAt;
73 + useEffect(() => {
74 + if (expiresAt === undefined) return;
75 + const timer = setTimeout(
76 + () => setExpiredAt(expiresAt),
77 + Math.max(0, Date.parse(expiresAt) - Date.now()),
78 + );
79 + return () => clearTimeout(timer);
80 + }, [expiresAt]);
81 + if (threadRef === null || !share) return null;
82 +
83 + const disabled = busy || !props.canOperateThread;
84 + const stopSharing = () =>
85 + Dialog.confirm({
86 + title: "Stop sharing?",
87 + message: "The guest loses access and the link stops working.",
88 + confirmText: "Stop sharing",
89 + destructive: true,
90 + onConfirm: () => {
91 + if (disabled) return;
92 + setBusy(true);
93 + void closeGuestShare({
94 + environmentId: threadRef.environmentId,
95 + input: { threadId: threadRef.threadId },
96 + }).then((result) => {
97 + setBusy(false);
98 + alertOnFailure("Could not stop sharing", result);
99 + });
100 + },
101 + });
102 +
103 + return (
104 + <View className="flex-row items-center gap-2 px-4 pb-2">
105 + <SymbolView name="person.2" size={12} tintColorClassName="accent-foreground-muted" />
106 + <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>
107 + {expiredAt === share.expiresAt
108 + ? "Guest link expired"
109 + : share.guestName === null
110 + ? "Guest link active"
111 + : `${share.guestName} is a guest`}
112 + </Text>
113 + <Button label="Stop sharing" tone="text" disabled={disabled} onPress={stopSharing} />
114 + </View>
115 + );
116 +}
117 +
118 +/**
119 + * One guest message waiting at the end of the feed until the owner sends or dismisses it. Sent
120 + * ones then show in the feed as user messages with the guest's name.
121 + */
122 +export function ThreadGuestPendingMessage(props: {
123 + readonly threadRef: ScopedThreadRef;
124 + readonly guestName: string;
125 + readonly message: ThreadGuestMessage;
126 + readonly bubbleMaxWidth: number | `${number}%`;
127 + /** The feed's own attachment rendering, so the owner sees the files before Send. */
128 + readonly renderAttachments: (attachments: ReadonlyArray<ChatAttachment>) => ReactNode;
129 +}) {
130 + const { threadRef, guestName, message } = props;
131 + const canOperate = useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope);
132 + const resolveGuestMessage = useAtomCommand(
133 + threadEnvironment.resolveGuestMessage,
134 + "resolve guest message",
135 + );
136 + // One request at a time: a second tap while the first is in flight would double-send.
137 + const [busy, setBusy] = useState(false);
138 +
139 + const resolve = async (decision: "send" | "dismiss") => {
140 + if (busy) return;
141 + setBusy(true);
142 + const result = await resolveGuestMessage({
143 + environmentId: threadRef.environmentId,
144 + input: {
145 + threadId: threadRef.threadId,
146 + guestMessageId: message.id,
147 + decision,
148 + creationSource: "mobile",
149 + },
150 + });
151 + setBusy(false);
152 + alertOnFailure(
153 + decision === "send" ? "Could not send guest message" : "Could not dismiss guest message",
154 + result,
155 + );
156 + };
157 +
158 + return (
159 + <View className="items-end pb-5">
160 + <GuestMessageName name={guestName} />
161 + <View className={GUEST_PENDING_BUBBLE_CLASS_NAME} style={{ maxWidth: props.bubbleMaxWidth }}>
162 + {message.text ? (
163 + <Text selectable className="text-base text-foreground">
164 + {message.text}
165 + </Text>
166 + ) : null}
167 + {props.renderAttachments(message.attachments ?? [])}
168 + </View>
169 + {canOperate ? (
170 + <View className="mt-1.5 flex-row gap-2">
171 + <Button
172 + label="Dismiss"
173 + tone="secondary"
174 + accessibilityLabel={`Dismiss message from ${guestName}`}
175 + disabled={busy}
176 + onPress={() => void resolve("dismiss")}
177 + />
178 + <Button
179 + label="Send"
180 + tone="primary"
181 + accessibilityLabel={`Send message from ${guestName}`}
182 + disabled={busy}
183 + onPress={() => void resolve("send")}
184 + />
185 + </View>
186 + ) : null}
187 + </View>
188 + );
189 +}
apps/mobile/src/features/threads/ThreadQueueControl.tsx
+12 -2
@@ -211,7 +211,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
211 No messages waiting in this queue.
212 </Text>
213 ) : null}
214 - {queuedRuns.map(({ run, text, attachments }, index) => {
214 + {queuedRuns.map(({ run, text, attachments, context }, index) => {
215 const layout = dragRows?.find((row) => row.id === run.id);
216 const offset =
217 sourceLayout?.y !== undefined &&
@@ -227,6 +227,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
227 canReorder: workflow?.canReorder ?? false,
228 index,
229 isEditing: editing?.runId === run.id,
230 + isGuestMessage: context?.guest !== undefined,
231 queuedCount: queuedRuns.length,
232 text,
233 });
@@ -364,7 +365,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
365 <Pressable
366 accessibilityRole="button"
367 accessibilityLabel={title}
367 - accessibilityHint="Opens this message in the composer for editing"
368 + accessibilityHint={
369 + controls.canEdit
370 + ? "Opens this message in the composer for editing"
371 + : undefined
372 + }
373 disabled={!controls.canEdit}
374 onPress={() => void act(run.id, "edit")}
375 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>) {
386 }
387 numberOfLines={1}
388 >
389 + {context?.guest === undefined ? null : (
390 + <Text className="font-t3-medium text-adaptive-fuchsia-600-300">
391 + {`${context.guest.name} `}
392 + </Text>
393 + )}
394 {title}
395 </Text>
396 {controls.isEditing ? (
apps/mobile/src/features/threads/guestMessageStyle.tsx new
+30
@@ -0,0 +1,30 @@
1 +import { View } from "react-native";
2 +
3 +import { AppText as Text } from "../../components/ui/AppText";
4 +
5 +/** The guest's name above their message, where "Sent by T3 Code" sits for server messages. */
6 +export function GuestMessageName(props: { readonly name: string }) {
7 + return (
8 + <Text
9 + accessibilityLabel={`${props.name} (guest)`}
10 + className="mb-1 pr-1 font-t3-medium text-2xs text-adaptive-fuchsia-600-300"
11 + numberOfLines={1}
12 + >
13 + {props.name}
14 + </Text>
15 + );
16 +}
17 +
18 +/**
19 + * First child of a sent guest bubble. Over the bubble color it gives the web's 14% fuchsia mix,
20 + * which every theme gets without a per-theme token.
21 + */
22 +export function GuestBubbleTint() {
23 + return (
24 + <View pointerEvents="none" className="absolute inset-0 rounded-[20px] bg-fuchsia-500/14" />
25 + );
26 +}
27 +
28 +/** A pending guest bubble has a dashed edge and no fill. */
29 +export const GUEST_PENDING_BUBBLE_CLASS_NAME =
30 + "min-w-0 rounded-[20px] border border-dashed border-adaptive-fuchsia-500-a50-300-a40 bg-transparent px-3.5 py-2.5";
apps/mobile/src/features/threads/pending-thread-feed.ts
+40 -1
@@ -1,12 +1,51 @@
1 -import { isCompactionCommandMessage } from "@t3tools/contracts";
1 +import {
2 + isCompactionCommandMessage,
3 + type ThreadGuestMessage,
4 + type ThreadGuestShare,
5 +} from "@t3tools/contracts";
6 import type { ThreadFeedEntry } from "../../lib/threadActivity";
7 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
8
9 +/**
10 + * A guest's message waiting for the owner's Send or Dismiss. It is a feed row, not the list
11 + * footer, so the feed follows it arriving and leaving the way it follows any row.
12 + */
13 +export interface GuestPendingFeedEntry {
14 + readonly type: "guest-pending";
15 + readonly id: string;
16 + readonly createdAt: string;
17 + readonly guestName: string;
18 + readonly message: ThreadGuestMessage;
19 +}
20 +
21 export type PendingThreadFeedEntry = ThreadFeedEntry & {
22 readonly pendingMessage?: QueuedThreadMessage;
23 readonly acknowledged?: boolean;
24 };
25
26 +/** A row of the thread feed's list. */
27 +export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry;
28 +
29 +/** Waiting guest messages go after the transcript, oldest first. */
30 +export function appendGuestPendingMessages(
31 + presentedFeed: ReadonlyArray<PendingThreadFeedEntry>,
32 + share: ThreadGuestShare | null,
33 +): ReadonlyArray<ThreadFeedRow> {
34 + const pending = share?.messages.filter((message) => message.status === "pending") ?? [];
35 + if (share === null || pending.length === 0) return presentedFeed;
36 + const guestName = share.guestName ?? "Guest";
37 + return [
38 + ...presentedFeed,
39 + ...pending.map((message): GuestPendingFeedEntry => ({
40 + type: "guest-pending",
41 + id: `guest-pending:${message.id}`,
42 + createdAt: message.submittedAt,
43 + guestName,
44 + message,
45 + })),
46 + ];
47 +}
48 +
49 export function appendPendingThreadMessages(
50 presentedFeed: ReadonlyArray<ThreadFeedEntry>,
51 feed: ReadonlyArray<ThreadFeedEntry>,
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+6
@@ -87,6 +87,12 @@ const STATUS_LABEL_BY_STATUS: Partial<Record<ThreadListV2Status, StatusLabel>> =
87 className: "text-adaptive-indigo-600-300",
88 iconTintClassName: "accent-adaptive-indigo-600-300",
89 },
90 + request: {
91 + label: "Request",
92 + icon: "person.crop.circle",
93 + className: "text-adaptive-fuchsia-600-300",
94 + iconTintClassName: "accent-adaptive-fuchsia-600-300",
95 + },
96 working: {
97 label: "Working",
98 icon: "circle.dashed",
apps/mobile/src/features/threads/threadListV2.test.ts
+12
@@ -100,6 +100,18 @@ describe("resolveThreadListV2Status", () => {
100 );
101 });
102
103 + it("shows a waiting guest message as Request, after the agent's own requests", () => {
104 + const thread = presentThreadShell(
105 + environmentId,
106 + decodeThreadShell(makeRawThreadShell({ status: "running" })),
107 + );
108 + const guest = { ...thread, pendingGuestMessageCount: 1 };
109 +
110 + expect(resolveThreadListV2Status(guest)).toBe("request");
111 + expect(resolveThreadListV2Status({ ...guest, hasPendingUserInput: true })).toBe("input");
112 + expect(resolveThreadListV2Status({ ...guest, hasPendingApprovals: true })).toBe("approval");
113 + });
114 +
115 it.each([
116 { roster: "dev server", task: { kind: "command" }, status: "ready" },
117 { roster: "dev server watchdog", task: { kind: "monitor" }, status: "ready" },
apps/mobile/src/features/threads/threadListV2.ts
+6
@@ -64,6 +64,7 @@ export function resolveThreadListV2ProviderDrivers(
64 export type ThreadListV2Status =
65 | "approval"
66 | "input"
67 + | "request"
68 | "working"
69 | "waiting"
70 | "failed"
@@ -175,6 +176,7 @@ export function resolveThreadListV2Status(
176 | "hasPendingApprovals"
177 | "hasPendingUserInput"
178 | "pendingSubagentRequest"
179 + | "pendingGuestMessageCount"
180 | "runtime"
181 | "blockedOnThreadWait"
182 >,
@@ -185,6 +187,10 @@ export function resolveThreadListV2Status(
187 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
188 return "input";
189 }
190 + // A guest is waiting on the owner; the agent's own requests come first.
191 + if ((thread.pendingGuestMessageCount ?? 0) > 0) {
192 + return "request";
193 + }
194 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
195 return "waiting";
196 }
apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts
+16
@@ -74,6 +74,22 @@ describe("threadQueueControlPresentation", () => {
74 expect(editing.canMoveUp).toBe(true);
75 expect(editing.canDismiss).toBe(true);
76 });
77 +
78 + it("lets the owner cancel a guest's queued message but not rewrite it", () => {
79 + const guest = resolveThreadQueueRowControls({
80 + busy: false,
81 + canPromoteToSteer: true,
82 + canSendNow: false,
83 + canReorder: true,
84 + index: 0,
85 + isGuestMessage: true,
86 + queuedCount: 1,
87 + text: "Why?",
88 + });
89 +
90 + expect(guest.canEdit).toBe(false);
91 + expect(guest.canDismiss).toBe(true);
92 + });
93 });
94
95 describe("queue drag insertion", () => {
apps/mobile/src/features/threads/threadQueueControlPresentation.ts
+3 -1
@@ -21,6 +21,8 @@ export function resolveThreadQueueRowControls(input: {
21 readonly canReorder: boolean;
22 readonly index: number;
23 readonly isEditing?: boolean;
24 + /** A guest's message keeps the guest's words; the owner can cancel it, not rewrite it. */
25 + readonly isGuestMessage?: boolean;
26 readonly queuedCount: number;
27 readonly text: string;
28 }): ThreadQueueRowControls {
@@ -31,7 +33,7 @@ export function resolveThreadQueueRowControls(input: {
33 canDismiss: !input.busy,
34 // Re-opening the row already in the composer would reload it and throw
35 // away whatever has been typed since.
34 - canEdit: mutationEnabled && !isEditing,
36 + canEdit: mutationEnabled && !isEditing && input.isGuestMessage !== true,
37 canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,
38 canMoveUp: mutationEnabled && input.canReorder && input.index > 0,
39 canSend: mutationEnabled && (input.canPromoteToSteer || input.canSendNow) && !isEditing,
apps/server/src/guest/GuestShareService.test.ts new
+810
@@ -0,0 +1,810 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import {
4 + ChatAttachmentId,
5 + CommandId,
6 + EventId,
7 + GuestShareId,
8 + MessageId,
9 + type OrchestrationV2TurnItem,
10 + ProjectId,
11 + ProviderDriverKind,
12 + ProviderInstanceId,
13 + ThreadId,
14 + TurnItemId,
15 +} from "@t3tools/contracts";
16 +import * as DateTime from "effect/DateTime";
17 +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
18 +import * as Effect from "effect/Effect";
19 +import * as Exit from "effect/Exit";
20 +import * as FileSystem from "effect/FileSystem";
21 +import * as Fiber from "effect/Fiber";
22 +import * as Layer from "effect/Layer";
23 +import * as Ref from "effect/Ref";
24 +import * as Option from "effect/Option";
25 +import * as Stream from "effect/Stream";
26 +import * as TestClock from "effect/testing/TestClock";
27 +
28 +import {
29 + createAttachmentId,
30 + resolveAttachmentPath,
31 + resolveAttachmentPathById,
32 + sweepStalePendingAttachments,
33 +} from "../attachmentStore.ts";
34 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
35 +import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";
36 +import * as ServerConfig from "../config.ts";
37 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
38 +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
39 +import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";
40 +import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts";
41 +import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
42 +import * as EventSink from "../orchestration-v2/EventSink.ts";
43 +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
44 +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
45 +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
46 +import * as ResourceCleanupService from "../orchestration-v2/ResourceCleanupService.ts";
47 +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
48 +import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
49 +import * as ServerSettings from "../serverSettings.ts";
50 +import * as GuestShareService from "./GuestShareService.ts";
51 +
52 +const instanceId = ProviderInstanceId.make("codex");
53 +const adapter = {
54 + instanceId,
55 + driver: ProviderDriverKind.make("codex"),
56 + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
57 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
58 + openSession: () => Effect.die("No provider process needed for guest shares"),
59 +} as ProviderAdapter.ProviderAdapterV2["Service"];
60 +const layerDatabase = SqlitePersistence.layerMemory;
61 +const layerOrchestration = Layer.mergeAll(
62 + layerDatabase,
63 + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
64 + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
65 + ProviderReplayHarness.layerWithRegistry(
66 + { name: "guest-share-service" },
67 + ProviderAdapterRegistry.layerFromAdapters([adapter]),
68 + { databaseLayer: layerDatabase, runEffectWorker: false },
69 + ),
70 +);
71 +
72 +// The Connect hostname the fake tunnel reports. Tests set it to null to simulate an unlink.
73 +const hostname = Ref.makeUnsafe<string | null>("env.t3.test");
74 +const layerConnect = Layer.mock(CloudManagedEndpointRuntime)({
75 + inspectConnector: Effect.map(Ref.get(hostname), (value) => ({
76 + readyConnections: 1,
77 + hostname: value,
78 + protocol: "http2",
79 + })),
80 +});
81 +const layerProviders = Layer.mock(ProviderRegistry.ProviderRegistry)({
82 + getProviders: Effect.succeed([]),
83 +});
84 +const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-guest-share-" });
85 +// The real cleanup also closes terminals and previews; these tests only need the files gone.
86 +const layerCleanup = Layer.effect(
87 + ResourceCleanupService.ResourceCleanupService,
88 + Effect.gen(function* () {
89 + const { attachmentsDir } = yield* ServerConfig.ServerConfig;
90 + const fileSystem = yield* FileSystem.FileSystem;
91 + return {
92 + cleanupScheduledTasks: () => Effect.void,
93 + cleanupTerminals: () => Effect.void,
94 + cleanupPreviews: () => Effect.void,
95 + cleanupAttachments: (attachmentIds) =>
96 + Effect.forEach(
97 + attachmentIds,
98 + (attachmentId) => {
99 + const path = resolveAttachmentPathById({ attachmentsDir, attachmentId });
100 + return path === null ? Effect.void : fileSystem.remove(path).pipe(Effect.orDie);
101 + },
102 + { discard: true },
103 + ),
104 + };
105 + }),
106 +).pipe(Layer.provide(layerConfig), Layer.provide(NodeServices.layer));
107 +const layerTest = GuestShareService.layer.pipe(
108 + Layer.provideMerge(
109 + CommandOutputHub.layer.pipe(
110 + Layer.provideMerge(layerOrchestration.pipe(Layer.provide(layerCleanup))),
111 + ),
112 + ),
113 + Layer.provide(layerProviders),
114 + Layer.provideMerge(ServerSettings.layerTest({ guestSharingEnabled: true })),
115 + Layer.provide(layerConnect),
116 + Layer.provide(ServerSecretStore.layer),
117 + Layer.provideMerge(layerConfig),
118 + Layer.provideMerge(NodeServices.layer),
119 +);
120 +
121 +const threadId = ThreadId.make("thread:guest-share-service");
122 +
123 +const shareThreadFor = Effect.fn(function* (threadId: ThreadId) {
124 + yield* Ref.set(hostname, "env.t3.test");
125 + const orchestrator = yield* Orchestrator.OrchestratorV2;
126 + yield* orchestrator.dispatch({
127 + type: "thread.create",
128 + commandId: CommandId.make(`create:${threadId}`),
129 + threadId,
130 + projectId: ProjectId.make("project:guest-share-service"),
131 + title: "Review me",
132 + modelSelection: { instanceId, model: "gpt-5.1-codex" },
133 + runtimeMode: "full-access",
134 + interactionMode: "default",
135 + branch: null,
136 + worktreePath: null,
137 + createdBy: "user",
138 + creationSource: "web",
139 + });
140 + const guestShares = yield* GuestShareService.GuestShareService;
141 + const { url } = yield* guestShares.create({ threadId });
142 + assert.isTrue(url.startsWith("https://env.t3.test/guest#"));
143 + const credential = url.slice(url.indexOf("#") + 1);
144 + return { orchestrator, guestShares, credential };
145 +});
146 +const shareThread = shareThreadFor(threadId);
147 +
148 +it.effect("spends an invite once and ends the guest stream when the owner stops sharing", () =>
149 + Effect.gen(function* () {
150 + const { orchestrator, guestShares, credential } = yield* shareThread;
151 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
152 + const again = yield* Effect.exit(guestShares.redeem({ credential, name: "Eve" }));
153 + assert.isTrue(Exit.isFailure(again));
154 + // The browser that joined can come back without the spent invite.
155 + assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.check(session))));
156 + // An invite token is not a session token.
157 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(credential))));
158 +
159 + const events = yield* guestShares.stream(session);
160 + yield* orchestrator.dispatch({
161 + type: "thread.guest-share.close",
162 + commandId: CommandId.make("close-guest-share"),
163 + threadId,
164 + });
165 + const received = Array.from(yield* Stream.runCollect(events));
166 + assert.deepEqual(
167 + received.map((event) => (event.type === "thread" ? event.item.kind : event.type)),
168 + ["view", "snapshot", "ended"],
169 + );
170 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(session))));
171 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.check(session))));
172 + }).pipe(Effect.provide(layerTest)),
173 +);
174 +
175 +it.effect("streams the owner's thread events after the share and a snapshot", () =>
176 + Effect.gen(function* () {
177 + const { orchestrator, guestShares, credential } = yield* shareThread;
178 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
179 + const events = yield* guestShares.stream(session);
180 + yield* orchestrator.dispatch({
181 + type: "message.dispatch",
182 + commandId: CommandId.make("owner-message"),
183 + threadId,
184 + messageId: MessageId.make("message:owner"),
185 + text: "Fix the login bug",
186 + attachments: [],
187 + dispatchMode: { type: "defer_start" },
188 + createdBy: "user",
189 + creationSource: "web",
190 + });
191 + yield* orchestrator.dispatch({
192 + type: "thread.guest-share.close",
193 + commandId: CommandId.make("close-after-message"),
194 + threadId,
195 + });
196 + const received = Array.from(yield* Stream.runCollect(events));
197 + assert.equal(received.at(-1)?.type, "ended");
198 + const turnItems = received.flatMap((event) =>
199 + event.type === "thread" &&
200 + event.item.kind === "event" &&
201 + event.item.event.type === "turn-item.updated"
202 + ? [event.item.event.payload]
203 + : [],
204 + );
205 + assert.deepEqual(
206 + turnItems.flatMap((item) => (item.type === "user_message" ? [item.text] : [])),
207 + ["Fix the login bug"],
208 + );
209 + }).pipe(Effect.provide(layerTest)),
210 +);
211 +
212 +it.effect("starts a stream with the runs and items already in the thread", () =>
213 + Effect.gen(function* () {
214 + const { orchestrator, guestShares, credential } = yield* shareThread;
215 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
216 + yield* orchestrator.dispatch({
217 + type: "message.dispatch",
218 + commandId: CommandId.make("owner-message-before"),
219 + threadId,
220 + messageId: MessageId.make("message:before"),
221 + text: "Fix the login bug",
222 + attachments: [],
223 + dispatchMode: { type: "defer_start" },
224 + createdBy: "user",
225 + creationSource: "web",
226 + });
227 + const [view, snapshot] = Array.from(
228 + yield* Stream.runCollect(Stream.take(yield* guestShares.stream(session), 2)),
229 + );
230 + assert.equal(view?.type, "view");
231 + if (snapshot?.type !== "thread" || snapshot.item.kind !== "snapshot") {
232 + return assert.fail("Expected the thread snapshot second.");
233 + }
234 + assert.equal(snapshot.item.projection.runs.length, 1);
235 + assert.include(
236 + snapshot.item.projection.visibleTurnItems.map((row) => row.item.type),
237 + "user_message",
238 + );
239 + }).pipe(Effect.provide(layerTest)),
240 +);
241 +
242 +it.effect("redeems only a short invite whose signature and share id are both current", () =>
243 + Effect.gen(function* () {
244 + const { guestShares, credential: replaced } = yield* shareThread;
245 + const { url } = yield* guestShares.create({ threadId });
246 + const credential = url.slice(url.indexOf("#") + 1);
247 + assert.match(credential, /^[\w-]{22}\.[\w-]{22}$/);
248 +
249 + const [shareId, signature] = credential.split(".");
250 + const tampered = `${shareId}.${signature!.startsWith("A") ? "B" : "A"}${signature!.slice(1)}`;
251 + for (const rejected of [tampered, replaced]) {
252 + const error = yield* Effect.flip(guestShares.redeem({ credential: rejected, name: "Eve" }));
253 + assert.equal(error.reason, "invalid");
254 + }
255 + assert.isTrue(
256 + Exit.isSuccess(yield* Effect.exit(guestShares.redeem({ credential, name: "Sam" }))),
257 + );
258 + }).pipe(Effect.provide(layerTest)),
259 +);
260 +
261 +it.effect("refuses guest requests once T3 Connect no longer serves the link's host", () =>
262 + Effect.gen(function* () {
263 + const { guestShares, credential } = yield* shareThread;
264 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
265 + const { id: shareId } = (yield* Orchestrator.OrchestratorV2.use((orchestrator) =>
266 + orchestrator.getThreadRecords(threadId, []),
267 + )).thread.guestShare!;
268 + yield* Ref.set(hostname, null);
269 + const submitted = yield* Effect.exit(
270 + guestShares.submit(session, { shareId, text: "Hello" }, []),
271 + );
272 + assert.isTrue(Exit.isFailure(submitted));
273 + }).pipe(Effect.provide(layerTest)),
274 +);
275 +
276 +it.effect("closes an open guest stream when T3 Connect stops serving the link's host", () =>
277 + Effect.gen(function* () {
278 + const { guestShares, credential } = yield* shareThread;
279 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
280 + const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(
281 + Effect.forkChild,
282 + );
283 + yield* Ref.set(hostname, null);
284 + yield* TestClock.adjust("30 seconds");
285 + // No `ended`: the browser reconnects, and the host check refuses it while Connect is gone.
286 + const received = Array.from(yield* Fiber.join(collecting));
287 + assert.deepEqual(
288 + received.map((event) => (event.type === "thread" ? event.item.kind : event.type)),
289 + ["view", "snapshot"],
290 + );
291 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(session))));
292 + yield* Ref.set(hostname, "env.t3.test");
293 + assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.stream(session))));
294 + }).pipe(Effect.provide(layerTest)),
295 +);
296 +
297 +it.effect("refuses new links and every guest request while the beta is off", () =>
298 + Effect.gen(function* () {
299 + const { guestShares, credential } = yield* shareThread;
300 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
301 + const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(
302 + Effect.forkChild,
303 + );
304 + const settings = yield* ServerSettings.ServerSettingsService;
305 + yield* settings.updateSettings({ guestSharingEnabled: false });
306 + // An open stream closes at the next access check.
307 + yield* TestClock.adjust("30 seconds");
308 + yield* Fiber.join(collecting);
309 + assert.equal((yield* Effect.flip(guestShares.create({ threadId }))).reason, "disabled");
310 + assert.equal((yield* Effect.flip(guestShares.check(session))).reason, "inactive");
311 + // Turning it back on lets the same guest back in.
312 + yield* settings.updateSettings({ guestSharingEnabled: true });
313 + assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.check(session))));
314 + }).pipe(Effect.provide(layerTest)),
315 +);
316 +
317 +it.effect("ends an open guest stream when the link expires", () =>
318 + Effect.gen(function* () {
319 + const { guestShares, credential } = yield* shareThread;
320 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
321 + const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(
322 + Effect.forkChild,
323 + );
324 + yield* TestClock.adjust("25 hours");
325 + const received = Array.from(yield* Fiber.join(collecting));
326 + assert.equal(received.at(-1)?.type, "ended");
327 + }).pipe(Effect.provide(layerTest)),
328 +);
329 +
330 +it.effect("shows the guest the thread's new model", () =>
331 + Effect.gen(function* () {
332 + const { orchestrator, guestShares, credential } = yield* shareThread;
333 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
334 + const events = yield* guestShares.stream(session);
335 + yield* orchestrator.dispatch({
336 + type: "thread.model-selection.set",
337 + commandId: CommandId.make("switch-model"),
338 + threadId,
339 + modelSelection: { instanceId, model: "gpt-5.2-codex" },
340 + });
341 + yield* orchestrator.dispatch({
342 + type: "thread.guest-share.close",
343 + commandId: CommandId.make("close-after-switch"),
344 + threadId,
345 + });
346 + const views = Array.from(yield* Stream.runCollect(events)).flatMap((event) =>
347 + event.type === "view" ? [event.view.model.name] : [],
348 + );
349 + assert.include(views, "gpt-5.2-codex");
350 + }).pipe(Effect.provide(layerTest)),
351 +);
352 +
353 +it.effect("refuses a message a page sends for a share the cookie no longer opens", () =>
354 + Effect.gen(function* () {
355 + const { guestShares, credential } = yield* shareThread;
356 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
357 + const submitted = yield* Effect.exit(
358 + guestShares.submit(session, { shareId: GuestShareId.make("share:older"), text: "Hello" }, []),
359 + );
360 + assert.isTrue(Exit.isFailure(submitted));
361 + }).pipe(Effect.provide(layerTest)),
362 +);
363 +
364 +it.effect("serves no render for an item outside the shared thread", () =>
365 + Effect.gen(function* () {
366 + const { guestShares, credential } = yield* shareThread;
367 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
368 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.render(session, "item:missing"))));
369 + // The invite itself is not a session.
370 + assert.isTrue(
371 + Exit.isFailure(yield* Effect.exit(guestShares.render(credential, "item:missing"))),
372 + );
373 + }).pipe(Effect.provide(layerTest)),
374 +);
375 +
376 +/** A message from the owner, which opens a run for the command below. */
377 +const ownerRun = Effect.gen(function* () {
378 + const orchestrator = yield* Orchestrator.OrchestratorV2;
379 + yield* orchestrator.dispatch({
380 + type: "message.dispatch",
381 + commandId: CommandId.make("owner-message-for-command"),
382 + threadId,
383 + messageId: MessageId.make("message:command"),
384 + text: "Build it",
385 + attachments: [],
386 + dispatchMode: { type: "defer_start" },
387 + createdBy: "user",
388 + creationSource: "web",
389 + });
390 + const { runs } = (yield* orchestrator.getThreadSnapshotWindow(threadId, { rowLimit: 10 }))
391 + .projection;
392 + return runs[0]!.id;
393 +});
394 +
395 +const writeCommand = (
396 + id: string,
397 + fields: Pick<
398 + Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
399 + "status" | "output"
400 + >,
401 +) =>
402 + Effect.gen(function* () {
403 + const runId = yield* ownerRun;
404 + const eventSink = yield* EventSink.EventSinkV2;
405 + const now = yield* DateTime.now;
406 + yield* eventSink.write({
407 + events: [
408 + {
409 + id: EventId.make(`event:${id}`),
410 + type: "turn-item.updated",
411 + threadId,
412 + driver: ProviderDriverKind.make("codex"),
413 + providerInstanceId: instanceId,
414 + occurredAt: now,
415 + payload: {
416 + id: TurnItemId.make(id),
417 + threadId,
418 + runId,
419 + nodeId: null,
420 + providerThreadId: null,
421 + providerTurnId: null,
422 + nativeItemRef: null,
423 + parentItemId: null,
424 + ordinal: 1,
425 + title: null,
426 + startedAt: now,
427 + completedAt: fields.status === "running" ? null : now,
428 + updatedAt: now,
429 + type: "command_execution",
430 + input: "ls /work/src",
431 + ...fields,
432 + },
433 + },
434 + ],
435 + });
436 + return TurnItemId.make(id);
437 + });
438 +
439 +it.effect("gives the guest a command's detail and output, as the owner's row loads them", () =>
440 + Effect.gen(function* () {
441 + const { guestShares, credential } = yield* shareThread;
442 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
443 + const command = yield* writeCommand("item:command", {
444 + status: "completed",
445 + output: "/work/src/auth.ts\n",
446 + });
447 +
448 + const detail = (yield* guestShares.item(session, command)).item;
449 + assert.deepInclude(detail, { input: "ls /work/src", output: "/work/src/auth.ts\n" });
450 + const frames = Array.from(
451 + yield* Stream.runCollect(yield* guestShares.commandOutput(session, command)),
452 + );
453 + assert.deepEqual(frames, [
454 + { kind: "replace", text: "/work/src/auth.ts\n", truncated: false, running: false },
455 + ]);
456 + // Only with a session, and only for an item of this thread.
457 + const refused: ReadonlyArray<Effect.Effect<unknown, GuestShareService.GuestShareAccessError>> =
458 + [
459 + guestShares.item(credential, command),
460 + guestShares.commandOutput(credential, command),
461 + guestShares.item(session, "item:elsewhere"),
462 + ];
463 + for (const request of refused) {
464 + assert.isTrue(Exit.isFailure(yield* Effect.exit(request)));
465 + }
466 + }).pipe(Effect.provide(layerTest)),
467 +);
468 +
469 +it.effect("ends a running command's output once the owner stops sharing", () =>
470 + Effect.gen(function* () {
471 + const { orchestrator, guestShares, credential } = yield* shareThread;
472 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
473 + const command = yield* writeCommand("item:running", { status: "running" });
474 + const collecting = yield* Stream.runCollect(
475 + yield* guestShares.commandOutput(session, command),
476 + ).pipe(Effect.forkChild);
477 + yield* orchestrator.dispatch({
478 + type: "thread.guest-share.close",
479 + commandId: CommandId.make("close-during-command"),
480 + threadId,
481 + });
482 + yield* TestClock.adjust("30 seconds");
483 + const frames = Array.from(yield* Fiber.join(collecting));
484 + assert.isTrue(frames.every((frame) => frame.running));
485 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command))));
486 + }).pipe(Effect.provide(layerTest)),
487 +);
488 +
489 +const PNG = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13);
490 +const MIB = 1024 * 1024;
491 +
492 +/** Files as the multipart parser leaves them: on disk, with the browser's name and type. */
493 +const uploadsOf = Effect.fn(function* (
494 + files: ReadonlyArray<{
495 + readonly name: string;
496 + readonly contentType: string;
497 + readonly bytes: Uint8Array;
498 + }>,
499 +) {
500 + const fileSystem = yield* FileSystem.FileSystem;
501 + const directory = yield* fileSystem.makeTempDirectoryScoped();
502 + return yield* Effect.forEach(files, (file, index) => {
503 + const path = `${directory}/${index}`;
504 + return fileSystem
505 + .writeFile(path, file.bytes)
506 + .pipe(Effect.as({ name: file.name, contentType: file.contentType, path }));
507 + });
508 +});
509 +const png = (name: string, sizeBytes = PNG.length) => {
510 + const bytes = new Uint8Array(sizeBytes);
511 + bytes.set(PNG);
512 + return { name, contentType: "image/png", bytes };
513 +};
514 +
515 +/** Every stored attachment file. */
516 +const storedFiles = Effect.gen(function* () {
517 + const { attachmentsDir } = yield* ServerConfig.ServerConfig;
518 + const fileSystem = yield* FileSystem.FileSystem;
519 + return yield* fileSystem.readDirectory(attachmentsDir).pipe(Effect.orElseSucceed(() => []));
520 +});
521 +
522 +const joinedGuest = Effect.gen(function* () {
523 + const shared = yield* shareThread;
524 + const { token: session, shareId } = yield* shared.guestShares.redeem({
525 + credential: shared.credential,
526 + name: "Sam",
527 + });
528 + return { ...shared, session, shareId };
529 +});
530 +
531 +const waitingMessages = Effect.gen(function* () {
532 + const orchestrator = yield* Orchestrator.OrchestratorV2;
533 + const { thread } = yield* orchestrator.getThreadRecords(threadId, []);
534 + return thread.guestShare?.messages ?? [];
535 +});
536 +
537 +it.effect("refuses too many files, too many bytes, and images that are not what they say", () =>
538 + Effect.gen(function* () {
539 + const { guestShares, session, shareId } = yield* joinedGuest;
540 + const before = yield* storedFiles;
541 + const refused = [
542 + ["too_many_files", [1, 2, 3, 4, 5].map((index) => png(`${index}.png`))],
543 + ["too_large", [png("big.png", 10 * MIB + 1)]],
544 + ["unsupported_file", [{ name: "logo.svg", contentType: "image/svg+xml", bytes: PNG }]],
545 + [
546 + "unsupported_file",
547 + [{ name: "page.png", contentType: "image/png", bytes: new TextEncoder().encode("<html>") }],
548 + ],
549 + [
550 + "unsupported_file",
551 + [{ name: "empty.txt", contentType: "text/plain", bytes: new Uint8Array() }],
552 + ],
553 + ] as const;
554 + for (const [reason, files] of refused) {
555 + const error = yield* Effect.flip(
556 + guestShares.submit(session, { shareId, text: "Look" }, yield* uploadsOf(files)),
557 + );
558 + assert.equal(error.reason, reason);
559 + }
560 + // Nothing is kept from a refused message, and no message waits.
561 + assert.deepEqual(yield* storedFiles, before);
562 + assert.deepEqual(yield* waitingMessages, []);
563 +
564 + yield* guestShares.submit(
565 + session,
566 + { shareId, text: "" },
567 + yield* uploadsOf([
568 + png("screen.png"),
569 + // A direction override would make this name read as a PDF.
570 + {
571 + name: "notes\u202Efdp.html",
572 + contentType: "text/html",
573 + bytes: new TextEncoder().encode("<b>"),
574 + },
575 + ]),
576 + );
577 + const [message] = yield* waitingMessages;
578 + assert.deepEqual(
579 + message?.attachments?.map(({ type, name, mimeType, sizeBytes }) => ({
580 + type,
581 + name,
582 + mimeType,
583 + sizeBytes,
584 + })),
585 + [
586 + { type: "image", name: "screen.png", mimeType: "image/png", sizeBytes: PNG.length },
587 + { type: "file", name: "notes_fdp.html", mimeType: "text/html", sizeBytes: 3 },
588 + ],
589 + );
590 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
591 +);
592 +
593 +it.effect("caps the bytes of files waiting in one share", () =>
594 + Effect.gen(function* () {
595 + const { guestShares, session, shareId } = yield* joinedGuest;
596 + const submit = (sizeBytes: number) =>
597 + Effect.gen(function* () {
598 + return guestShares.submit(
599 + session,
600 + { shareId, text: "Look" },
601 + yield* uploadsOf([png("big.png", sizeBytes)]),
602 + );
603 + }).pipe(Effect.flatten);
604 + yield* submit(9 * MIB);
605 + yield* submit(9 * MIB);
606 + const error = yield* Effect.flip(submit(9 * MIB));
607 + assert.equal(error.reason, "files_busy");
608 + // Text alone still goes through.
609 + yield* guestShares.submit(session, { shareId, text: "One more thing" }, []);
610 + assert.equal((yield* waitingMessages).length, 3);
611 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
612 +);
613 +
614 +it.effect("deletes a waiting message's files when the owner dismisses it or stops sharing", () =>
615 + Effect.gen(function* () {
616 + const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
617 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
618 + yield* guestShares.submit(
619 + session,
620 + { shareId, text: "First" },
621 + yield* uploadsOf([png("a.png")]),
622 + );
623 + yield* guestShares.submit(
624 + session,
625 + { shareId, text: "Second" },
626 + yield* uploadsOf([png("b.png")]),
627 + );
628 + const [first, second] = yield* waitingMessages;
629 + const fileOf = (message: typeof first) => message!.attachments![0]!.id;
630 + const stored = yield* storedFiles;
631 + assert.isTrue(stored.some((entry) => entry.startsWith(fileOf(first))));
632 +
633 + yield* orchestrator.dispatch({
634 + type: "thread.guest-message.dismiss",
635 + commandId: CommandId.make("dismiss-first"),
636 + threadId,
637 + guestMessageId: first!.id,
638 + });
639 + yield* worker.drain();
640 + const afterDismiss = yield* storedFiles;
641 + assert.isFalse(afterDismiss.some((entry) => entry.startsWith(fileOf(first))));
642 + assert.isTrue(afterDismiss.some((entry) => entry.startsWith(fileOf(second))));
643 + // A dismissed message's file is no longer the guest's to load.
644 + assert.isTrue(
645 + Exit.isFailure(yield* Effect.exit(guestShares.attachment(session, fileOf(first)))),
646 + );
647 +
648 + yield* orchestrator.dispatch({
649 + type: "thread.guest-share.close",
650 + commandId: CommandId.make("close-with-files"),
651 + threadId,
652 + });
653 + yield* worker.drain();
654 + assert.isFalse((yield* storedFiles).some((entry) => entry.startsWith(fileOf(second))));
655 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
656 +);
657 +
658 +it.effect.each(["thread.archive", "thread.delete"] as const)(
659 + "deletes a waiting message's files on %s",
660 + (type) =>
661 + Effect.gen(function* () {
662 + const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
663 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
664 + const before = yield* storedFiles;
665 + yield* guestShares.submit(
666 + session,
667 + { shareId, text: "Look" },
668 + yield* uploadsOf([png("a.png")]),
669 + );
670 + assert.equal((yield* storedFiles).length, before.length + 1);
671 + yield* orchestrator.dispatch({
672 + type,
673 + commandId: CommandId.make(`${type}-with-files`),
674 + threadId,
675 + });
676 + yield* worker.drain();
677 + assert.deepEqual(yield* storedFiles, before);
678 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
679 +);
680 +
681 +it.effect("sends a guest's files as the guest's message and keeps them the guest's to load", () =>
682 + Effect.gen(function* () {
683 + const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
684 + yield* guestShares.submit(
685 + session,
686 + { shareId, text: "See this" },
687 + yield* uploadsOf([png("a.png")]),
688 + );
689 + const [message] = yield* waitingMessages;
690 + const pending = message!.attachments!;
691 + // Served while it waits.
692 + const served = yield* guestShares.attachment(session, pending[0]!.id);
693 + assert.equal(served.attachment.mimeType, "image/png");
694 +
695 + // The day-old pending-upload sweep leaves a waiting guest's files alone.
696 + const { attachmentsDir } = yield* ServerConfig.ServerConfig;
697 + // Any pending upload counts as stale at the end of time.
698 + sweepStalePendingAttachments({ attachmentsDir, nowMs: Number.MAX_SAFE_INTEGER });
699 + const copied = pending[0]!;
700 + yield* orchestrator.dispatch({
701 + type: "message.dispatch",
702 + commandId: CommandId.make("send-guest-files"),
703 + threadId,
704 + messageId: MessageId.make("message:guest-files"),
705 + guestMessageId: message!.id,
706 + text: "",
707 + attachments: [copied],
708 + dispatchMode: { type: "defer_start" },
709 + createdBy: "user",
710 + creationSource: "web",
711 + });
712 + const items = (yield* orchestrator.getThreadSnapshotWindow(threadId, {
713 + rowLimit: 20,
714 + })).projection.visibleTurnItems.map((entry) => entry.item);
715 + const sent = items.find(
716 + (item) => item.type === "user_message" && item.context?.guest?.guestMessageId === message!.id,
717 + );
718 + assert.deepInclude(sent, { attachments: [copied] });
719 + if (sent?.type !== "user_message") return;
720 + assert.deepEqual(sent.context?.guest, {
721 + guestMessageId: message!.id,
722 + name: "Sam",
723 + text: "See this",
724 + shareId,
725 + });
726 + // The guest loads the thread's copy from their own row.
727 + const fromRow = yield* guestShares.attachment(session, copied.id);
728 + assert.equal(fromRow.attachment.id, copied.id);
729 +
730 + // Still theirs after their share's message list has trimmed it away.
731 + for (let index = 0; index < 21; index += 1) {
732 + yield* guestShares.submit(session, { shareId, text: `note ${index}` }, []);
733 + const [waiting] = (yield* waitingMessages).filter((next) => next.status === "pending");
734 + yield* orchestrator.dispatch({
735 + type: "thread.guest-message.dismiss",
736 + commandId: CommandId.make(`dismiss-note-${index}`),
737 + threadId,
738 + guestMessageId: waiting!.id,
739 + });
740 + }
741 + assert.isFalse((yield* waitingMessages).some((next) => next.id === message!.id));
742 + assert.equal((yield* guestShares.attachment(session, copied.id)).attachment.id, copied.id);
743 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
744 +);
745 +
746 +it.effect("serves the shared thread's files to its guest, never another thread's", () =>
747 + Effect.gen(function* () {
748 + const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
749 + // Another thread's guest attaches a file.
750 + const other = yield* shareThreadFor(ThreadId.make("thread:other-share"));
751 + const otherGuest = yield* guestShares.redeem({ credential: other.credential, name: "Eve" });
752 + yield* guestShares.submit(
753 + otherGuest.token,
754 + { shareId: otherGuest.shareId, text: "Mine" },
755 + yield* uploadsOf([png("eve.png")]),
756 + );
757 + const { thread: otherThread } = yield* orchestrator.getThreadRecords(
758 + ThreadId.make("thread:other-share"),
759 + [],
760 + );
761 + const othersFile = otherThread.guestShare!.messages[0]!.attachments![0]!.id;
762 + assert.isTrue(
763 + Exit.isSuccess(yield* Effect.exit(guestShares.attachment(otherGuest.token, othersFile))),
764 + );
765 +
766 + // The owner sends a message with an image of their own.
767 + const { attachmentsDir } = yield* ServerConfig.ServerConfig;
768 + const fileSystem = yield* FileSystem.FileSystem;
769 + const ownerImage = {
770 + type: "image" as const,
771 + id: ChatAttachmentId.make(createAttachmentId(threadId)!),
772 + name: "secret.png",
773 + mimeType: "image/png",
774 + sizeBytes: PNG.length,
775 + };
776 + yield* fileSystem.writeFile(
777 + resolveAttachmentPath({ attachmentsDir, attachment: ownerImage })!,
778 + PNG,
779 + );
780 + yield* orchestrator.dispatch({
781 + type: "message.dispatch",
782 + commandId: CommandId.make("owner-image"),
783 + threadId,
784 + messageId: MessageId.make("message:owner-image"),
785 + text: "My screen",
786 + attachments: [ownerImage],
787 + dispatchMode: { type: "defer_start" },
788 + createdBy: "user",
789 + creationSource: "web",
790 + });
791 +
792 + // The guest sees the thread as the owner does, files included.
793 + assert.equal(
794 + (yield* guestShares.attachment(session, ownerImage.id)).attachment.id,
795 + ownerImage.id,
796 + );
797 + for (const id of [othersFile, "pending-missing"]) {
798 + const error = yield* Effect.flip(guestShares.attachment(session, id));
799 + assert.equal(error.reason, "unavailable");
800 + }
801 + // Nor with the other share's id on this page.
802 + assert.equal(
803 + (yield* Effect.flip(
804 + guestShares.submit(session, { shareId: otherGuest.shareId, text: "x" }, []),
805 + )).reason,
806 + "stale_page",
807 + );
808 + assert.isDefined(shareId);
809 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
810 +);
apps/server/src/guest/GuestShareService.ts new
+638
@@ -0,0 +1,638 @@
1 +import {
2 + type ChatAttachment,
3 + ChatAttachmentId,
4 + CommandId,
5 + GUEST_SHARE_TTL_MS,
6 + GuestMessageId,
7 + GuestShareCreateError,
8 + type GuestShareCreateInput,
9 + type GuestShareCreateResult,
10 + GuestShareId,
11 + type GuestRedeemRequest,
12 + type GuestStreamEvent,
13 + type GuestSubmitRequest,
14 + type OrchestrationV2AppThread,
15 + type OrchestrationV2CommandOutputFrame,
16 + type OrchestrationV2DomainEvent,
17 + type OrchestrationV2GetTurnItemResult,
18 + ThreadId,
19 + TurnItemId,
20 +} from "@t3tools/contracts";
21 +import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
22 +import * as Context from "effect/Context";
23 +import * as Crypto from "effect/Crypto";
24 +import * as DateTime from "effect/DateTime";
25 +import * as Duration from "effect/Duration";
26 +import * as Effect from "effect/Effect";
27 +import * as FileSystem from "effect/FileSystem";
28 +import * as Layer from "effect/Layer";
29 +import * as Option from "effect/Option";
30 +import * as Schedule from "effect/Schedule";
31 +import * as Schema from "effect/Schema";
32 +import * as Stream from "effect/Stream";
33 +
34 +import {
35 + base64UrlDecodeUtf8,
36 + base64UrlEncode,
37 + signPayload,
38 + timingSafeEqualBase64Url,
39 +} from "../auth/utils.ts";
40 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
41 +import {
42 + attachmentFileExtension,
43 + createAttachmentId,
44 + resolveAttachmentPath,
45 + resolveAttachmentPathById,
46 + threadHtmlRenderAttachmentIds,
47 +} from "../attachmentStore.ts";
48 +import * as ServerConfig from "../config.ts";
49 +import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";
50 +import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";
51 +import { GUEST_FAILURE } from "../orchestration-v2/GuestShareDecider.ts";
52 +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
53 +import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoalescer.ts";
54 +import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts";
55 +import {
56 + projectDomainEventForWire,
57 + projectTurnItemForDetail,
58 +} from "../orchestration-v2/WireProjection.ts";
59 +import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
60 +import * as ServerSettings from "../serverSettings.ts";
61 +import { guestShareView, guestThreadModel } from "./guestView.ts";
62 +import {
63 + classifyGuestUploads,
64 + GUEST_UPLOAD_HEADER_BYTES,
65 + type GuestUpload,
66 +} from "./guestAttachments.ts";
67 +
68 +const SIGNING_SECRET_NAME = "guest-share-signing-key";
69 +const SHARE_ID_BYTES = 16;
70 +const INVITE_SIGNATURE_BYTES = 16;
71 +const SNAPSHOT_ROW_LIMIT = 600;
72 +const SNAPSHOT_USER_TURN_LIMIT = 20;
73 +// How soon an open read notices that its link stopped working, such as Connect no longer serving
74 +// the host. Closing or replacing the link ends the main stream at once.
75 +const ACCESS_RECHECK_INTERVAL = Duration.seconds(30);
76 +
77 +const GUEST_ACCESS_MESSAGES = {
78 + ...GUEST_FAILURE,
79 + invalid: "This guest link is not valid.",
80 + stale_page: "This page is for an older guest link. Reload it to continue.",
81 + unavailable: "This item is not available.",
82 + rejected: "The owner's server rejected this request.",
83 + empty: "Write a message or attach a file.",
84 + too_many_files: "Attach up to 4 files to a message.",
85 + too_large: "Attached files can total up to 10 MB per message.",
86 + unsupported_file: "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP.",
87 + files_busy: GUEST_FAILURE.filesBusy,
88 +} as const;
89 +
90 +/** What a guest is told. The message comes from `reason`, never from a cause. */
91 +export class GuestShareAccessError extends Schema.TaggedError<GuestShareAccessError>()(
92 + "GuestShareAccessError",
93 + {
94 + reason: Schema.Literals([
95 + "invalid",
96 + "inactive",
97 + "used",
98 + "busy",
99 + "stale_page",
100 + "unavailable",
101 + "rejected",
102 + "empty",
103 + "too_many_files",
104 + "too_large",
105 + "unsupported_file",
106 + "files_busy",
107 + ]),
108 + },
109 +) {
110 + override get message(): string {
111 + return GUEST_ACCESS_MESSAGES[this.reason];
112 + }
113 +}
114 +
115 +const guestFailureReason = (cause: unknown): GuestShareAccessError["reason"] =>
116 + cause === GUEST_FAILURE.inactive
117 + ? "inactive"
118 + : cause === GUEST_FAILURE.used
119 + ? "used"
120 + : cause === GUEST_FAILURE.busy
121 + ? "busy"
122 + : cause === GUEST_FAILURE.filesBusy
123 + ? "files_busy"
124 + : "rejected";
125 +
126 +const SessionClaims = Schema.Struct({
127 + kind: Schema.Literal("session"),
128 + threadId: ThreadId,
129 + shareId: GuestShareId,
130 +});
131 +type SessionClaims = typeof SessionClaims.Type;
132 +const decodeSessionClaims = Schema.decodeUnknownOption(Schema.fromJsonString(SessionClaims));
133 +
134 +/** A truncated HMAC keeps invite links short. 128 bits is still far beyond guessing range. */
135 +const inviteSignature = (shareId: string, key: Uint8Array) =>
136 + base64UrlEncode(
137 + Buffer.from(signPayload(`guest-invite:${shareId}`, key), "base64url").subarray(
138 + 0,
139 + INVITE_SIGNATURE_BYTES,
140 + ),
141 + );
142 +
143 +const inactive = new GuestShareAccessError({ reason: "inactive" });
144 +
145 +export class GuestShareService extends Context.Service<
146 + GuestShareService,
147 + {
148 + readonly create: (
149 + input: GuestShareCreateInput,
150 + ) => Effect.Effect<GuestShareCreateResult, GuestShareCreateError>;
151 + /** Spends an invite and returns the session token for the guest's cookie. */
152 + readonly redeem: (
153 + request: GuestRedeemRequest,
154 + ) => Effect.Effect<
155 + { readonly token: string; readonly shareId: GuestShareId },
156 + GuestShareAccessError
157 + >;
158 + /** Succeeds while the session can still open its share. */
159 + readonly check: (session: string) => Effect.Effect<void, GuestShareAccessError>;
160 + /** Stores the guest's files as the thread's attachments and records the message with them. */
161 + readonly submit: (
162 + session: string,
163 + request: GuestSubmitRequest,
164 + uploads: ReadonlyArray<GuestUpload>,
165 + ) => Effect.Effect<void, GuestShareAccessError>;
166 + readonly stream: (
167 + session: string,
168 + ) => Effect.Effect<Stream.Stream<GuestStreamEvent>, GuestShareAccessError>;
169 + /** The file of an HTML render in the shared thread, and its title. */
170 + readonly render: (
171 + session: string,
172 + itemId: string,
173 + ) => Effect.Effect<{ readonly path: string; readonly title: string }, GuestShareAccessError>;
174 + /** One item of the shared thread, as the owner's expanded row loads it. */
175 + readonly item: (
176 + session: string,
177 + itemId: string,
178 + ) => Effect.Effect<OrchestrationV2GetTurnItemResult, GuestShareAccessError>;
179 + /** A command's output frames, as the owner's expanded row gets them, until the link ends. */
180 + readonly commandOutput: (
181 + session: string,
182 + itemId: string,
183 + ) => Effect.Effect<Stream.Stream<OrchestrationV2CommandOutputFrame>, GuestShareAccessError>;
184 + /** A file in the shared thread or one of the share's messages, never a dismissed one's. */
185 + readonly attachment: (
186 + session: string,
187 + attachmentId: string,
188 + ) => Effect.Effect<
189 + { readonly path: string; readonly attachment: ChatAttachment },
190 + GuestShareAccessError
191 + >;
192 + }
193 +>()("t3/guest/GuestShareService") {}
194 +
195 +/** The thread record an event carries, for the share and the view. */
196 +const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => {
197 + switch (event.type) {
198 + case "thread.guest-share-updated":
199 + case "thread.metadata-updated":
200 + case "thread.model-selection-updated":
201 + case "thread.provider-switched":
202 + return event.payload;
203 + default:
204 + return null;
205 + }
206 +};
207 +
208 +const make = Effect.gen(function* () {
209 + const orchestrator = yield* Orchestrator.OrchestratorV2;
210 + const commandOutputs = yield* CommandOutputHub.CommandOutputHub;
211 + const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
212 + const serverSettings = yield* ServerSettings.ServerSettingsService;
213 + const managedEndpoint = yield* CloudManagedEndpointRuntime;
214 + const { attachmentsDir } = yield* ServerConfig.ServerConfig;
215 + const fileSystem = yield* FileSystem.FileSystem;
216 + const crypto = yield* Crypto.Crypto;
217 + const secretStore = yield* ServerSecretStore.ServerSecretStore;
218 + const signingKey = yield* Effect.cached(
219 + secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),
220 + );
221 +
222 + // Tokens are derived from the share id, so nothing secret is stored and replacing or closing
223 + // the share in the thread projection revokes every token for it. An invite is
224 + // `<shareId>.<signature>` and the thread is looked up by share id; a session token carries
225 + // signed claims.
226 + const signInvite = (shareId: GuestShareId) =>
227 + Effect.map(signingKey, (key) => `${shareId}.${inviteSignature(shareId, key)}`);
228 + const signSession = (claims: SessionClaims) =>
229 + Effect.map(signingKey, (key) => {
230 + const payload = base64UrlEncode(JSON.stringify(claims));
231 + return `${payload}.${signPayload(payload, key)}`;
232 + });
233 + const splitToken = (token: string) => {
234 + const [payload, signature, extra] = token.split(".");
235 + return payload && signature && extra === undefined ? { payload, signature } : null;
236 + };
237 + const verifyInvite = Effect.fn("GuestShareService.verifyInvite")(function* (token: string) {
238 + const parts = splitToken(token);
239 + if (parts === null) return Option.none<SessionClaims>();
240 + const key = yield* signingKey;
241 + if (!timingSafeEqualBase64Url(parts.signature, inviteSignature(parts.payload, key))) {
242 + return Option.none<SessionClaims>();
243 + }
244 + const shareId = GuestShareId.make(parts.payload);
245 + const threadId = yield* orchestrator
246 + .findGuestShareThreadId(shareId)
247 + .pipe(Effect.mapError(() => inactive));
248 + return threadId === null
249 + ? Option.none<SessionClaims>()
250 + : Option.some<SessionClaims>({ kind: "session", threadId, shareId });
251 + });
252 + const verifySession = (token: string) =>
253 + Effect.map(signingKey, (key) => {
254 + const parts = splitToken(token);
255 + if (parts === null) return Option.none<SessionClaims>();
256 + if (!timingSafeEqualBase64Url(parts.signature, signPayload(parts.payload, key))) {
257 + return Option.none<SessionClaims>();
258 + }
259 + return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));
260 + });
261 +
262 + const connectHostname = managedEndpoint.inspectConnector.pipe(
263 + Effect.map((facts) => facts?.hostname ?? null),
264 + );
265 + // A beta: while it is off, no link opens and every guest request is refused.
266 + const sharingEnabled = serverSettings.getSettings.pipe(
267 + Effect.map((settings) => settings.guestSharingEnabled),
268 + Effect.orElseSucceed(() => false),
269 + );
270 +
271 + const dispatchGuestCommand = (
272 + command: Parameters<Orchestrator.OrchestratorV2["Service"]["dispatch"]>[0],
273 + ) =>
274 + orchestrator.dispatch(command).pipe(
275 + Effect.mapError(
276 + (error) =>
277 + new GuestShareAccessError({
278 + reason: guestFailureReason("cause" in error ? error.cause : undefined),
279 + }),
280 + ),
281 + );
282 +
283 + const commandId = (label: string) =>
284 + crypto.randomUUIDv4().pipe(
285 + Effect.map((uuid) => CommandId.make(`server:guest-share:${label}:${uuid}`)),
286 + Effect.orDie,
287 + );
288 +
289 + /** Checks a token against the live share: same id, not expired, and Connect still serving it. */
290 + const authorize = Effect.fn("GuestShareService.authorize")(function* (
291 + token: string,
292 + kind: "invite" | "session",
293 + ) {
294 + const claims = yield* kind === "invite" ? verifyInvite(token) : verifySession(token);
295 + if (Option.isNone(claims)) {
296 + return yield* new GuestShareAccessError({ reason: "invalid" });
297 + }
298 + const { thread } = yield* orchestrator
299 + .getThreadRecords(claims.value.threadId, [])
300 + .pipe(Effect.mapError(() => inactive));
301 + const share = thread.guestShare;
302 + const now = yield* DateTime.now;
303 + if (
304 + !(yield* sharingEnabled) ||
305 + !share ||
306 + share.id !== claims.value.shareId ||
307 + thread.archivedAt !== null ||
308 + thread.deletedAt !== null ||
309 + DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) ||
310 + (kind === "session" && share.guestName === null) ||
311 + (yield* connectHostname) !== share.host
312 + ) {
313 + return yield* inactive;
314 + }
315 + return { thread, share };
316 + });
317 +
318 + const create = Effect.fn("GuestShareService.create")(function* (input: GuestShareCreateInput) {
319 + if (!(yield* sharingEnabled)) {
320 + return yield* new GuestShareCreateError({ reason: "disabled" });
321 + }
322 + const host = yield* connectHostname;
323 + if (host === null) {
324 + return yield* new GuestShareCreateError({ reason: "connect_unavailable" });
325 + }
326 + const shareId = GuestShareId.make(
327 + base64UrlEncode(yield* crypto.randomBytes(SHARE_ID_BYTES).pipe(Effect.orDie)),
328 + );
329 + const now = yield* DateTime.now;
330 + const expiresAt = DateTime.formatIso(DateTime.add(now, { milliseconds: GUEST_SHARE_TTL_MS }));
331 + yield* orchestrator
332 + .dispatch({
333 + type: "thread.guest-share.open",
334 + commandId: yield* commandId("open"),
335 + threadId: input.threadId,
336 + shareId,
337 + host,
338 + expiresAt,
339 + })
340 + .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "thread_unavailable" })));
341 + const { thread } = yield* orchestrator
342 + .getThreadRecords(input.threadId, [])
343 + .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "read_failed" })));
344 + if (!thread.guestShare || thread.guestShare.id !== shareId) {
345 + return yield* new GuestShareCreateError({ reason: "changed" });
346 + }
347 + const credential = yield* signInvite(shareId);
348 + return { url: `https://${host}/guest#${credential}`, share: thread.guestShare };
349 + });
350 +
351 + const redeem = Effect.fn("GuestShareService.redeem")(function* (request: GuestRedeemRequest) {
352 + const { thread, share } = yield* authorize(request.credential, "invite");
353 + yield* dispatchGuestCommand({
354 + type: "thread.guest-share.redeem",
355 + commandId: yield* commandId("redeem"),
356 + threadId: thread.id,
357 + shareId: share.id,
358 + guestName: request.name,
359 + });
360 + const token = yield* signSession({ kind: "session", threadId: thread.id, shareId: share.id });
361 + return { token, shareId: share.id };
362 + });
363 +
364 + const check = Effect.fn("GuestShareService.check")(function* (session: string) {
365 + yield* authorize(session, "session");
366 + });
367 +
368 + const uploadFailed = new GuestShareAccessError({ reason: "rejected" });
369 + const removeStored = (attachments: ReadonlyArray<ChatAttachment>) =>
370 + Effect.forEach(
371 + attachments,
372 + (attachment) => {
373 + const path = resolveAttachmentPath({ attachmentsDir, attachment });
374 + return path === null
375 + ? Effect.void
376 + : fileSystem.remove(path, { force: true }).pipe(Effect.ignore);
377 + },
378 + { discard: true },
379 + );
380 +
381 + /**
382 + * Checks the files and stores them as the thread's attachments, so a message can wait longer
383 + * than the day the pending-upload sweep allows. Send uses them as they are; dismissing the
384 + * message or ending the share deletes them.
385 + */
386 + const storeUploads = Effect.fn("GuestShareService.storeUploads")(function* (
387 + threadId: ThreadId,
388 + uploads: ReadonlyArray<GuestUpload>,
389 + ) {
390 + const inspected = yield* Effect.forEach(uploads, (upload) =>
391 + Effect.gen(function* () {
392 + const info = yield* fileSystem.stat(upload.path);
393 + const file = yield* fileSystem.open(upload.path, { flag: "r" });
394 + const header = Option.getOrElse(
395 + yield* file.readAlloc(GUEST_UPLOAD_HEADER_BYTES),
396 + () => new Uint8Array(),
397 + );
398 + return { ...upload, sizeBytes: Number(info.size), header };
399 + }).pipe(
400 + Effect.scoped,
401 + Effect.mapError(() => uploadFailed),
402 + ),
403 + );
404 + const classified = classifyGuestUploads(inspected);
405 + if (!classified.ok) return yield* new GuestShareAccessError({ reason: classified.reason });
406 + const stored: Array<ChatAttachment> = [];
407 + yield* Effect.forEach(
408 + classified.attachments,
409 + (draft, index) =>
410 + Effect.gen(function* () {
411 + const id = createAttachmentId(
412 + threadId,
413 + draft.type === "file" ? attachmentFileExtension(draft.name) : undefined,
414 + );
415 + if (id === null) return yield* uploadFailed;
416 + const attachment: ChatAttachment = { ...draft, id: ChatAttachmentId.make(id) };
417 + const path = resolveAttachmentPath({ attachmentsDir, attachment });
418 + if (path === null) return yield* uploadFailed;
419 + yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
420 + yield* fileSystem.copyFile(uploads[index]!.path, path);
421 + stored.push(attachment);
422 + }).pipe(Effect.mapError(() => uploadFailed)),
423 + { discard: true },
424 + ).pipe(Effect.onError(() => removeStored(stored)));
425 + return stored;
426 + });
427 +
428 + const submit = Effect.fn("GuestShareService.submit")(function* (
429 + session: string,
430 + request: GuestSubmitRequest,
431 + uploads: ReadonlyArray<GuestUpload>,
432 + ) {
433 + const { thread, share } = yield* authorize(session, "session");
434 + if (request.shareId !== share.id) {
435 + return yield* new GuestShareAccessError({ reason: "stale_page" });
436 + }
437 + if (request.text === "" && uploads.length === 0) {
438 + return yield* new GuestShareAccessError({ reason: "empty" });
439 + }
440 + const attachments = yield* storeUploads(thread.id, uploads);
441 + yield* dispatchGuestCommand({
442 + type: "thread.guest-message.submit",
443 + commandId: yield* commandId("submit"),
444 + threadId: thread.id,
445 + shareId: share.id,
446 + guestMessageId: GuestMessageId.make(yield* crypto.randomUUIDv4().pipe(Effect.orDie)),
447 + text: request.text,
448 + ...(attachments.length === 0 ? {} : { attachments }),
449 + }).pipe(Effect.onError(() => removeStored(attachments)));
450 + });
451 +
452 + /** Completes once the session no longer opens its share, so open reads end with it. */
453 + const untilRevoked = (session: string) =>
454 + authorize(session, "session").pipe(
455 + Effect.repeat(Schedule.spaced(ACCESS_RECHECK_INTERVAL)),
456 + Effect.ignore,
457 + );
458 +
459 + /**
460 + * The thread as the owner's thread subscription sends it: a bounded snapshot, then the same
461 + * wire events, batched the same way. Only the share's own state is added.
462 + */
463 + const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {
464 + const { thread, share } = yield* authorize(session, "session");
465 + const snapshot = yield* orchestrator
466 + .getThreadSnapshotWindow(thread.id, {
467 + rowLimit: SNAPSHOT_ROW_LIMIT,
468 + userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,
469 + })
470 + .pipe(Effect.mapError(() => inactive));
471 + // The share can end between authorize and this read; the live tail starts after it.
472 + if (
473 + snapshot.projection.thread.guestShare?.id !== share.id ||
474 + snapshot.projection.thread.archivedAt !== null ||
475 + snapshot.projection.thread.deletedAt !== null
476 + ) {
477 + return yield* inactive;
478 + }
479 + // Read once; a provider configured mid-share shows after the guest reconnects.
480 + const providers = yield* providerRegistry.getProviders;
481 + const viewOf = (current: OrchestrationV2AppThread) =>
482 + guestShareView(current, guestThreadModel(current.modelSelection, providers));
483 + const initialView = viewOf(snapshot.projection.thread);
484 + if (initialView === null) return yield* inactive;
485 +
486 + const ended: GuestStreamEvent = { type: "ended" };
487 + const endsShare = (event: OrchestrationV2DomainEvent) => {
488 + if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
489 + const updated = threadOf(event);
490 + return updated !== null && updated.guestShare?.id !== share.id;
491 + };
492 + const live = orchestrator
493 + .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })
494 + .pipe(
495 + Stream.map((stored) => ({
496 + kind: "event" as const,
497 + sequence: stored.sequence,
498 + event: projectDomainEventForWire(stored.event),
499 + })),
500 + // Ending the source here flushes what the coalescer holds, so `ended` is not held back.
501 + Stream.takeUntil((item) => endsShare(item.event)),
502 + coalesceThreadLiveStream,
503 + Stream.map((item): ReadonlyArray<GuestStreamEvent> => {
504 + if (item.kind !== "event") return [];
505 + if (endsShare(item.event)) return [ended];
506 + const updated = threadOf(item.event);
507 + const view = updated === null ? null : viewOf(updated);
508 + return view === null
509 + ? [{ type: "thread", item }]
510 + : [
511 + { type: "thread", item },
512 + { type: "view", view },
513 + ];
514 + }),
515 + Stream.flattenIterable,
516 + // A failed read closes the response without `ended`: the browser reconnects, and
517 + // `authorize` decides whether the link still works.
518 + Stream.catchCause(() => Stream.empty),
519 + );
520 + const untilExpiry = Effect.sleep(
521 + Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
522 + );
523 + const opening: ReadonlyArray<GuestStreamEvent> = [
524 + { type: "view", view: initialView },
525 + {
526 + type: "thread",
527 + item: buildBoundedThreadStreamSnapshot({
528 + snapshotSequence: snapshot.snapshotSequence,
529 + projection: snapshot.projection,
530 + }),
531 + },
532 + ];
533 + return Stream.fromIterable(opening).pipe(
534 + Stream.concat(
535 + Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {
536 + haltStrategy: "either",
537 + }),
538 + ),
539 + Stream.takeUntil((event) => event.type === "ended"),
540 + // Unlinking T3 Connect closes it quietly, so a tunnel that comes back on the same host
541 + // keeps the guest in. Turning the beta off closes it the same way. Closing and expiry end
542 + // it above, with `ended`.
543 + Stream.interruptWhen(
544 + Effect.all([connectHostname, sharingEnabled]).pipe(
545 + Effect.repeat({
546 + schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),
547 + until: ([host, enabled]) => host !== share.host || !enabled,
548 + }),
549 + ),
550 + ),
551 + );
552 + });
553 +
554 + const unavailable = new GuestShareAccessError({ reason: "unavailable" });
555 +
556 + /** An item of the shared thread, read after the session check. */
557 + const threadItem = Effect.fn("GuestShareService.threadItem")(function* (
558 + session: string,
559 + itemId: string,
560 + ) {
561 + const { thread } = yield* authorize(session, "session");
562 + const item = yield* orchestrator
563 + .getTurnItem({ threadId: thread.id, itemId: TurnItemId.make(itemId) })
564 + .pipe(Effect.mapError(() => unavailable));
565 + return item === null ? yield* unavailable : { thread, item };
566 + });
567 +
568 + const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {
569 + const { thread, item } = yield* threadItem(session, itemId);
570 + if (item.type !== "dynamic_tool") return yield* unavailable;
571 + const reference = htmlRenderFromToolItem(item);
572 + const [attachmentId] = threadHtmlRenderAttachmentIds(thread.id, [item]);
573 + const path =
574 + attachmentId === undefined
575 + ? null
576 + : resolveAttachmentPathById({ attachmentsDir, attachmentId });
577 + if (reference === undefined || path === null) return yield* unavailable;
578 + return { path, title: reference.title };
579 + });
580 +
581 + const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) {
582 + const { item } = yield* threadItem(session, itemId);
583 + return { item: projectTurnItemForDetail(item) };
584 + });
585 +
586 + const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
587 + session: string,
588 + itemId: string,
589 + ) {
590 + const { thread, item } = yield* threadItem(session, itemId);
591 + if (item.type !== "command_execution") return yield* unavailable;
592 + return commandOutputs.subscribe({ threadId: thread.id, itemId: item.id }).pipe(
593 + // A lost hub stream ends the output; the row reloads it when reopened.
594 + Stream.catchCause(() => Stream.empty),
595 + Stream.interruptWhen(untilRevoked(session)),
596 + );
597 + });
598 +
599 + const attachment = Effect.fn("GuestShareService.attachment")(function* (
600 + session: string,
601 + attachmentId: string,
602 + ) {
603 + const { thread, share } = yield* authorize(session, "session");
604 + // A dismissed message's files are deleted with it.
605 + const fromShare = share.messages
606 + .flatMap((message) => (message.status === "dismissed" ? [] : (message.attachments ?? [])))
607 + .find((candidate) => candidate.id === attachmentId);
608 + const found =
609 + fromShare ??
610 + (yield* orchestrator.getThreadRecords(thread.id, ["messages"]).pipe(
611 + Effect.map(({ messages }) =>
612 + messages
613 + .flatMap((message) => message.attachments ?? [])
614 + .find((candidate) => candidate.id === attachmentId),
615 + ),
616 + Effect.mapError(() => unavailable),
617 + ));
618 + const path =
619 + found === undefined ? null : resolveAttachmentPath({ attachmentsDir, attachment: found });
620 + if (found === undefined || path === null) return yield* unavailable;
621 + const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));
622 + return exists ? { path, attachment: found } : yield* unavailable;
623 + });
624 +
625 + return GuestShareService.of({
626 + create,
627 + redeem,
628 + check,
629 + submit,
630 + stream,
631 + render,
632 + item,
633 + commandOutput,
634 + attachment,
635 + });
636 +});
637 +
638 +export const layer = Layer.effect(GuestShareService, make);
apps/server/src/guest/guestAttachments.ts new
+103
@@ -0,0 +1,103 @@
1 +import {
2 + GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
3 + GUEST_MESSAGE_MAX_ATTACHMENTS,
4 + isProviderSendTurnSupportedImageMimeType,
5 +} from "@t3tools/contracts";
6 +
7 +/** A file from a guest's message request, saved by the multipart parser to a temporary path. */
8 +export interface GuestUpload {
9 + readonly name: string;
10 + readonly contentType: string;
11 + readonly path: string;
12 +}
13 +
14 +/** What the server learned about an upload before deciding what it may become. */
15 +export interface InspectedGuestUpload {
16 + readonly name: string;
17 + readonly contentType: string;
18 + readonly sizeBytes: number;
19 + /** The first bytes of the file. */
20 + readonly header: Uint8Array;
21 +}
22 +
23 +export type GuestUploadRejection = "too_many_files" | "too_large" | "unsupported_file";
24 +
25 +/** An attachment before it is stored and gets its id. */
26 +export interface GuestAttachmentDraft {
27 + readonly type: "image" | "file";
28 + readonly name: string;
29 + readonly mimeType: string;
30 + readonly sizeBytes: number;
31 +}
32 +
33 +/** Bytes of the file the signature check reads. */
34 +export const GUEST_UPLOAD_HEADER_BYTES = 12;
35 +
36 +const startsWith = (header: Uint8Array, bytes: ReadonlyArray<number>, offset = 0) =>
37 + bytes.every((byte, index) => header[offset + index] === byte);
38 +const ascii = (text: string) => Array.from(text, (character) => character.charCodeAt(0));
39 +
40 +/** An image must be what its type says, so a renamed HTML page never travels as one. */
41 +const IMAGE_SIGNATURES: Readonly<Record<string, (header: Uint8Array) => boolean>> = {
42 + "image/png": (header) => startsWith(header, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
43 + "image/jpeg": (header) => startsWith(header, [0xff, 0xd8, 0xff]),
44 + "image/gif": (header) => startsWith(header, ascii("GIF8")),
45 + "image/webp": (header) =>
46 + startsWith(header, ascii("RIFF")) && startsWith(header, ascii("WEBP"), 8),
47 +};
48 +
49 +/**
50 + * Control characters and separators would break the name in headers and on disk, and direction
51 + * overrides would let `invoice\u202Efdp.exe` show as a PDF.
52 + */
53 +const safeName = (name: string, fallback: string) =>
54 + name
55 + .replace(/[\p{Cc}\\/\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu, "_")
56 + .trim()
57 + .slice(0, 255) || fallback;
58 +
59 +/**
60 + * The attachments a guest's files become, as the owner's composer takes them: supported images as
61 + * images, anything else that is not an image as a file. Other image types (SVG, HEIC) and empty
62 + * files are refused, as are too many files or too many bytes in one message.
63 + */
64 +export function classifyGuestUploads(
65 + uploads: ReadonlyArray<InspectedGuestUpload>,
66 +):
67 + | { readonly ok: true; readonly attachments: ReadonlyArray<GuestAttachmentDraft> }
68 + | { readonly ok: false; readonly reason: GuestUploadRejection } {
69 + if (uploads.length > GUEST_MESSAGE_MAX_ATTACHMENTS)
70 + return { ok: false, reason: "too_many_files" };
71 + const total = uploads.reduce((sum, upload) => sum + upload.sizeBytes, 0);
72 + if (total > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) return { ok: false, reason: "too_large" };
73 + const attachments: Array<GuestAttachmentDraft> = [];
74 + for (const upload of uploads) {
75 + const mimeType =
76 + upload.contentType.split(";", 1)[0]!.trim().toLowerCase() || "application/octet-stream";
77 + if (upload.sizeBytes === 0) return { ok: false, reason: "unsupported_file" };
78 + if (mimeType.startsWith("image/")) {
79 + const signatureMatches = IMAGE_SIGNATURES[mimeType];
80 + if (
81 + !isProviderSendTurnSupportedImageMimeType(mimeType) ||
82 + signatureMatches === undefined ||
83 + !signatureMatches(upload.header)
84 + ) {
85 + return { ok: false, reason: "unsupported_file" };
86 + }
87 + attachments.push({
88 + type: "image",
89 + name: safeName(upload.name, "image"),
90 + mimeType,
91 + sizeBytes: upload.sizeBytes,
92 + });
93 + continue;
94 + }
95 + attachments.push({
96 + type: "file",
97 + name: safeName(upload.name, "file"),
98 + mimeType: mimeType.length <= 100 ? mimeType : "application/octet-stream",
99 + sizeBytes: upload.sizeBytes,
100 + });
101 + }
102 + return { ok: true, attachments };
103 +}
apps/server/src/guest/guestView.test.ts new
+35
@@ -0,0 +1,35 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +
3 +import { guestThreadModel } from "./guestView.ts";
4 +
5 +describe("guestThreadModel", () => {
6 + const providers = [
7 + {
8 + instanceId: "claude-work",
9 + driver: "claudeAgent",
10 + models: [
11 + {
12 + slug: "claude-opus",
13 + name: "Claude Opus",
14 + shortName: "Opus",
15 + isCustom: false,
16 + capabilities: null,
17 + },
18 + ],
19 + },
20 + ] as unknown as Parameters<typeof guestThreadModel>[1];
21 +
22 + it("names the model as the owner's picker does, or by its id when it is not listed", () => {
23 + const selection = (instanceId: string, model: string) =>
24 + ({ instanceId, model }) as Parameters<typeof guestThreadModel>[0];
25 + expect(guestThreadModel(selection("claude-work", "claude-opus"), providers)).toEqual({
26 + driver: "claudeAgent",
27 + name: "Claude Opus",
28 + shortName: "Opus",
29 + });
30 + expect(guestThreadModel(selection("removed", "gpt-5"), providers)).toEqual({
31 + driver: null,
32 + name: "gpt-5",
33 + });
34 + });
35 +});
apps/server/src/guest/guestView.ts new
+38
@@ -0,0 +1,38 @@
1 +import type {
2 + GuestShareView,
3 + GuestThreadModel,
4 + OrchestrationV2AppThread,
5 + ServerProvider,
6 +} from "@t3tools/contracts";
7 +
8 +/** The thread's model as the owner's composer labels it, from the configured providers. */
9 +export function guestThreadModel(
10 + selection: OrchestrationV2AppThread["modelSelection"],
11 + providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver" | "models">>,
12 +): GuestThreadModel {
13 + const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
14 + const model = provider?.models.find((candidate) => candidate.slug === selection.model);
15 + return {
16 + driver: provider?.driver ?? null,
17 + name: model?.name ?? selection.model,
18 + ...(model?.shortName === undefined ? {} : { shortName: model.shortName }),
19 + ...(model?.subProvider === undefined ? {} : { subProvider: model.subProvider }),
20 + };
21 +}
22 +
23 +/** The share as its guest sees it, or null before the guest has joined. */
24 +export function guestShareView(
25 + thread: OrchestrationV2AppThread,
26 + model: GuestThreadModel,
27 +): GuestShareView | null {
28 + const share = thread.guestShare;
29 + if (!share || share.guestName === null) return null;
30 + return {
31 + shareId: share.id,
32 + title: thread.title,
33 + guestName: share.guestName,
34 + expiresAt: share.expiresAt,
35 + messages: share.messages,
36 + model,
37 + };
38 +}
apps/server/src/guest/http.test.ts new
+28
@@ -0,0 +1,28 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import { HttpServerRequest } from "effect/http";
5 +
6 +import { readSubmission } from "./http.ts";
7 +
8 +it.effect("keeps a JSON file a guest attaches as a file, not a form field", () =>
9 + Effect.gen(function* () {
10 + const form = new FormData();
11 + form.append("shareId", "share-1");
12 + form.append("text", "");
13 + form.append("file", new File(['{"a":1}'], "data.json", { type: "application/json" }));
14 + const request = HttpServerRequest.fromWeb(
15 + new Request("http://localhost/api/guest/messages?share=share-1", {
16 + method: "POST",
17 + body: form,
18 + }),
19 + );
20 + const submission = yield* readSubmission.pipe(
21 + Effect.provideService(HttpServerRequest.HttpServerRequest, request),
22 + );
23 + assert.deepEqual(
24 + submission?.uploads.map((upload) => [upload.name, upload.contentType]),
25 + [["data.json", "application/json"]],
26 + );
27 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
28 +);
apps/server/src/guest/http.ts new
+346
@@ -0,0 +1,346 @@
1 +import {
2 + GUEST_ATTACHMENT_ROUTE,
3 + GUEST_COMMAND_OUTPUT_ROUTE,
4 + GUEST_ITEM_ROUTE,
5 + GUEST_RENDER_ROUTE,
6 + GUEST_ROUTE_PREFIX,
7 + GUEST_SHARE_PARAM,
8 + GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
9 + GUEST_MESSAGE_MAX_ATTACHMENTS,
10 + GUEST_SHARE_TTL_MS,
11 + GuestRedeemRequest,
12 + GuestStreamEvent,
13 + GuestSubmitRequest,
14 + guestSessionCookieName,
15 + isProviderSendTurnSupportedImageMimeType,
16 + OrchestrationV2CommandOutputFrame,
17 + OrchestrationV2GetTurnItemResult,
18 +} from "@t3tools/contracts";
19 +import * as ByteSize from "effect/ByteSize";
20 +import * as Duration from "effect/Duration";
21 +import * as Effect from "effect/Effect";
22 +import * as Layer from "effect/Layer";
23 +import * as Schema from "effect/Schema";
24 +import * as Stream from "effect/Stream";
25 +import { HttpRouter, HttpServerRequest, HttpServerResponse, Multipart } from "effect/http";
26 +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
27 +
28 +import { htmlRenderFileName } from "@t3tools/shared/htmlRender";
29 +
30 +import { assetFileResponse, downloadContentDisposition } from "../http.ts";
31 +import type { GuestUpload } from "./guestAttachments.ts";
32 +import { GuestShareAccessError, GuestShareService } from "./GuestShareService.ts";
33 +
34 +// Cloudflare closes idle streams after about 100 seconds.
35 +const HEARTBEAT_INTERVAL = Duration.seconds(20);
36 +const NO_STORE = { "cache-control": "no-store" };
37 +
38 +const decodeRedeem = Schema.decodeUnknownEffect(GuestRedeemRequest);
39 +const decodeSubmit = Schema.decodeUnknownEffect(GuestSubmitRequest);
40 +// The owner's thread types hold DateTime values; the JSON codec writes them as strings.
41 +const encodeStreamEvent = Schema.encodeEffect(
42 + Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)),
43 +);
44 +const encodeOutputFrame = Schema.encodeEffect(
45 + Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
46 +);
47 +const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
48 +
49 +const errorResponse = (error: GuestShareAccessError) =>
50 + HttpServerResponse.json(
51 + { reason: error.reason, message: error.message },
52 + {
53 + status:
54 + error.reason === "invalid" || error.reason === "inactive" || error.reason === "unavailable"
55 + ? 403
56 + : error.reason === "empty" ||
57 + error.reason === "too_many_files" ||
58 + error.reason === "too_large" ||
59 + error.reason === "unsupported_file"
60 + ? 400
61 + : 409,
62 + headers: NO_STORE,
63 + },
64 + );
65 +
66 +const badRequest = HttpServerResponse.json(
67 + { reason: "invalid", message: "The request was not valid." },
68 + { status: 400, headers: NO_STORE },
69 +);
70 +
71 +const sessionFor = (request: HttpServerRequest.HttpServerRequest, shareId: string | null) =>
72 + shareId === null ? "" : (request.cookies[guestSessionCookieName(shareId)] ?? "");
73 +
74 +const requestedShareId = (request: HttpServerRequest.HttpServerRequest) =>
75 + new URLSearchParams(request.url.split("?", 2)[1] ?? "").get(GUEST_SHARE_PARAM);
76 +
77 +/** The session for the share the request names in `?share=`. */
78 +const sessionToken = Effect.map(HttpServerRequest.HttpServerRequest, (request) =>
79 + sessionFor(request, requestedShareId(request)),
80 +);
81 +
82 +/** The `?item=` a per-item route names. */
83 +const itemParam = Effect.map(HttpServerRequest.HttpServerRequest, (request) =>
84 + new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("item"),
85 +);
86 +
87 +/** Server-sent events with a heartbeat, never cached or buffered on the way. */
88 +const eventStreamResponse = <A, I>(
89 + events: Stream.Stream<A>,
90 + encode: (event: A) => Effect.Effect<string, Schema.SchemaError>,
91 +) => {
92 + const data = events.pipe(
93 + Stream.mapEffect((event) =>
94 + encode(event).pipe(
95 + Effect.map((json) => [`data: ${json}\n\n`]),
96 + // The guest misses one update instead of the whole stream.
97 + Effect.catch(() =>
98 + Effect.logWarning("Dropped a guest stream event that failed to encode.").pipe(
99 + Effect.as([]),
100 + ),
101 + ),
102 + ),
103 + ),
104 + Stream.flattenIterable,
105 + );
106 + const heartbeat = Stream.tick(HEARTBEAT_INTERVAL).pipe(Stream.map(() => ": ping\n\n"));
107 + return HttpServerResponse.stream(
108 + data.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }), Stream.encodeText),
109 + {
110 + contentType: "text/event-stream",
111 + // no-transform keeps the compression middleware from buffering the stream.
112 + headers: { "cache-control": "no-store, no-transform", "x-accel-buffering": "no" },
113 + },
114 + );
115 +};
116 +
117 +// Guest JSON bodies are a name or one message; anyone who can reach the tunnel can post them.
118 +const JSON_MAX_BODY_BYTES = 64 * 1024;
119 +const readJson = Effect.gen(function* () {
120 + const request = yield* HttpServerRequest.HttpServerRequest;
121 + // A declared length over the cap is refused before reading; chunked bodies hit the reader cap.
122 + if (Number(request.headers["content-length"] ?? "0") > JSON_MAX_BODY_BYTES) {
123 + return yield* new GuestShareAccessError({ reason: "too_large" });
124 + }
125 + return yield* request.json.pipe(
126 + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(JSON_MAX_BODY_BYTES)),
127 + );
128 +});
129 +
130 +const redeemRoute = HttpRouter.add(
131 + "POST",
132 + `${GUEST_ROUTE_PREFIX}/redeem`,
133 + Effect.gen(function* () {
134 + const body = yield* readJson.pipe(Effect.flatMap(decodeRedeem), Effect.option);
135 + if (body._tag === "None") return yield* badRequest;
136 + const guestShares = yield* GuestShareService;
137 + return yield* guestShares.redeem(body.value).pipe(
138 + Effect.flatMap(({ token, shareId }) =>
139 + HttpServerResponse.empty({ status: 204, headers: NO_STORE }).pipe(
140 + HttpServerResponse.setCookie(guestSessionCookieName(shareId), token, {
141 + httpOnly: true,
142 + secure: true,
143 + sameSite: "strict",
144 + path: GUEST_ROUTE_PREFIX,
145 + maxAge: Duration.millis(GUEST_SHARE_TTL_MS),
146 + }),
147 + ),
148 + ),
149 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
150 + );
151 + }),
152 +);
153 +
154 +// The parser stops a request with too many parts or bytes before it reaches the disk; the
155 +// service checks the exact limits and types.
156 +const UPLOAD_LIMITS = Multipart.limitsServices({
157 + maxParts: GUEST_MESSAGE_MAX_ATTACHMENTS + 4,
158 + maxFileSize: GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
159 + maxTotalSize: GUEST_MESSAGE_MAX_ATTACHMENT_BYTES + 64 * 1024,
160 + // By default a JSON part is read as a field, which would drop a guest's `.json` file.
161 + fieldMimeTypes: [],
162 +});
163 +
164 +/** A message as JSON (text only), or as multipart form data with `file` parts. */
165 +export const readSubmission = Effect.gen(function* () {
166 + const request = yield* HttpServerRequest.HttpServerRequest;
167 + if (!request.headers["content-type"]?.startsWith("multipart/form-data")) {
168 + const body = yield* readJson.pipe(Effect.flatMap(decodeSubmit), Effect.option);
169 + return body._tag === "None" ? null : { fields: body.value, uploads: [] };
170 + }
171 + const parts = yield* request.multipart.pipe(
172 + Effect.provideContext(UPLOAD_LIMITS),
173 + Effect.mapError(
174 + (error) =>
175 + new GuestShareAccessError({
176 + reason:
177 + error.reason._tag === "TooManyParts"
178 + ? "too_many_files"
179 + : error.reason._tag === "Parse"
180 + ? "rejected"
181 + : "too_large",
182 + }),
183 + ),
184 + );
185 + const fields = yield* decodeSubmit({ shareId: parts.shareId, text: parts.text ?? "" }).pipe(
186 + Effect.option,
187 + );
188 + if (fields._tag === "None") return null;
189 + const files = parts.file;
190 + const uploads: ReadonlyArray<GuestUpload> = Array.isArray(files)
191 + ? files.filter(Multipart.isPersistedFile).map(({ name, contentType, path }) => ({
192 + name,
193 + contentType,
194 + path,
195 + }))
196 + : [];
197 + return { fields: fields.value, uploads };
198 +});
199 +
200 +const submitRoute = HttpRouter.add(
201 + "POST",
202 + `${GUEST_ROUTE_PREFIX}/messages`,
203 + Effect.gen(function* () {
204 + const request = yield* HttpServerRequest.HttpServerRequest;
205 + const guestShares = yield* GuestShareService;
206 + // The session is checked before the body is read, so only a guest can make the server parse
207 + // and store up to 10 MB.
208 + const shareId = requestedShareId(request);
209 + const session = sessionFor(request, shareId);
210 + yield* guestShares.check(session);
211 + const submission = yield* readSubmission;
212 + if (submission === null || submission.fields.shareId !== shareId) return yield* badRequest;
213 + yield* guestShares.submit(session, submission.fields, submission.uploads);
214 + return HttpServerResponse.empty({ status: 204, headers: NO_STORE });
215 + }).pipe(
216 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
217 + // The parser's temporary files are removed once the response is ready.
218 + Effect.scoped,
219 + ),
220 +);
221 +
222 +const streamRoute = HttpRouter.add(
223 + "GET",
224 + `${GUEST_ROUTE_PREFIX}/stream`,
225 + Effect.gen(function* () {
226 + const guestShares = yield* GuestShareService;
227 + return yield* guestShares.stream(yield* sessionToken).pipe(
228 + Effect.map((events) => eventStreamResponse(events, encodeStreamEvent)),
229 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
230 + );
231 + }),
232 +);
233 +
234 +// Lets a returning guest skip the name form when this browser already joined the share.
235 +const sessionRoute = HttpRouter.add(
236 + "GET",
237 + `${GUEST_ROUTE_PREFIX}/session`,
238 + Effect.gen(function* () {
239 + const guestShares = yield* GuestShareService;
240 + return yield* guestShares
241 + .check(yield* sessionToken)
242 + .pipe(
243 + Effect.as(HttpServerResponse.empty({ status: 204, headers: NO_STORE })),
244 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
245 + );
246 + }),
247 +);
248 +
249 +// The response carries the asset route's sandbox CSP: the page gets an opaque origin, so its
250 +// scripts cannot send the guest cookie or call these routes as the guest.
251 +const renderRoute = HttpRouter.add(
252 + "GET",
253 + GUEST_RENDER_ROUTE,
254 + Effect.gen(function* () {
255 + const itemId = yield* itemParam;
256 + if (!itemId) return yield* badRequest;
257 + const guestShares = yield* GuestShareService;
258 + return yield* guestShares.render(yield* sessionToken, itemId).pipe(
259 + Effect.flatMap(({ path, title }) =>
260 + assetFileResponse({ path, mimeType: "text/html", fileName: htmlRenderFileName(title) }),
261 + ),
262 + // Each load re-checks the share, so a closed, replaced, or expired link stops it at once.
263 + Effect.map((response) => HttpServerResponse.setHeaders(response, NO_STORE)),
264 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
265 + );
266 + }),
267 +);
268 +
269 +const itemRoute = HttpRouter.add(
270 + "GET",
271 + GUEST_ITEM_ROUTE,
272 + Effect.gen(function* () {
273 + const itemId = yield* itemParam;
274 + if (!itemId) return yield* badRequest;
275 + const guestShares = yield* GuestShareService;
276 + return yield* guestShares.item(yield* sessionToken, itemId).pipe(
277 + Effect.flatMap((result) =>
278 + encodeItem(result).pipe(
279 + Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })),
280 + ),
281 + ),
282 + Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })),
283 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
284 + );
285 + }),
286 +);
287 +
288 +// Ends when the command settles; the page closes its EventSource on that last frame, so the
289 +// browser does not reconnect.
290 +const commandOutputRoute = HttpRouter.add(
291 + "GET",
292 + GUEST_COMMAND_OUTPUT_ROUTE,
293 + Effect.gen(function* () {
294 + const itemId = yield* itemParam;
295 + if (!itemId) return yield* badRequest;
296 + const guestShares = yield* GuestShareService;
297 + return yield* guestShares.commandOutput(yield* sessionToken, itemId).pipe(
298 + Effect.map((frames) => eventStreamResponse(frames, encodeOutputFrame)),
299 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
300 + );
301 + }),
302 +);
303 +
304 +// Images of the four checked types load inline; anything else downloads as bytes, so a guest's
305 +// HTML or SVG never renders as a page on this origin.
306 +const attachmentRoute = HttpRouter.add(
307 + "GET",
308 + GUEST_ATTACHMENT_ROUTE,
309 + Effect.gen(function* () {
310 + const request = yield* HttpServerRequest.HttpServerRequest;
311 + const attachmentId = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("id");
312 + if (!attachmentId) return yield* badRequest;
313 + const guestShares = yield* GuestShareService;
314 + return yield* guestShares.attachment(yield* sessionToken, attachmentId).pipe(
315 + Effect.flatMap(({ path, attachment }) =>
316 + HttpServerResponse.file(path, {
317 + headers: {
318 + ...NO_STORE,
319 + "x-content-type-options": "nosniff",
320 + "content-security-policy": "default-src 'none'; sandbox",
321 + ...(attachment.type === "image" &&
322 + isProviderSendTurnSupportedImageMimeType(attachment.mimeType)
323 + ? { "content-type": attachment.mimeType }
324 + : {
325 + "content-type": "application/octet-stream",
326 + "content-disposition": downloadContentDisposition(attachment.name),
327 + }),
328 + },
329 + }),
330 + ),
331 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
332 + Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500, headers: NO_STORE })),
333 + );
334 + }),
335 +);
336 +
337 +export const layer = Layer.mergeAll(
338 + redeemRoute,
339 + sessionRoute,
340 + submitRoute,
341 + streamRoute,
342 + renderRoute,
343 + itemRoute,
344 + commandOutputRoute,
345 + attachmentRoute,
346 +);
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -97,6 +97,7 @@ const RPC_AGGREGATES = {
97 [WS_METHODS.scheduledTasksListWebhookDeliveries]: "scheduledTasks",
98 [WS_METHODS.scheduledTasksGetWebhookDelivery]: "scheduledTasks",
99 [WS_METHODS.secretsAnswerRequest]: "secrets",
100 + [WS_METHODS.guestShareCreate]: "guest-share",
101 [WS_METHODS.cloudGetRelayClientStatus]: "cloud",
102 [WS_METHODS.cloudInstallRelayClient]: "cloud",
103 [WS_METHODS.pullRequestsList]: "pull-requests",
apps/server/src/orchestration-v2/GuestShare.test.ts new
+343
@@ -0,0 +1,343 @@
1 +import { assert, it } from "@effect/vitest";
2 +import {
3 + CommandId,
4 + GuestMessageId,
5 + GuestShareId,
6 + MessageId,
7 + ProjectId,
8 + ProviderDriverKind,
9 + ProviderInstanceId,
10 + ThreadId,
11 +} from "@t3tools/contracts";
12 +import * as DateTime from "effect/DateTime";
13 +import * as Effect from "effect/Effect";
14 +import * as Exit from "effect/Exit";
15 +import * as Layer from "effect/Layer";
16 +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
17 +
18 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
19 +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
20 +import * as EffectOutbox from "./EffectOutbox.ts";
21 +import * as Orchestrator from "./Orchestrator.ts";
22 +import * as ProjectionStore from "./ProjectionStore.ts";
23 +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
24 +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
25 +
26 +const instanceId = ProviderInstanceId.make("codex");
27 +const adapter = {
28 + instanceId,
29 + driver: ProviderDriverKind.make("codex"),
30 + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
31 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
32 + openSession: () => Effect.die("No provider process needed for guest shares"),
33 +} as ProviderAdapter.ProviderAdapterV2["Service"];
34 +const layerDatabase = SqlitePersistence.layerMemory;
35 +const layerTest = Layer.mergeAll(
36 + layerDatabase,
37 + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
38 + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
39 + ProviderReplayHarness.layerWithRegistry(
40 + { name: "guest-share" },
41 + ProviderAdapterRegistry.layerFromAdapters([adapter]),
42 + { databaseLayer: layerDatabase, runEffectWorker: false },
43 + ),
44 +);
45 +
46 +const threadId = ThreadId.make("thread:guest-share");
47 +const shareId = GuestShareId.make("share:one");
48 +const guestMessageId = GuestMessageId.make("guest-message:one");
49 +
50 +const setup = Effect.gen(function* () {
51 + const orchestrator = yield* Orchestrator.OrchestratorV2;
52 + yield* orchestrator.dispatch({
53 + type: "thread.create",
54 + commandId: CommandId.make("create-guest-share"),
55 + threadId,
56 + projectId: ProjectId.make("project:guest-share"),
57 + title: "Review me",
58 + modelSelection: { instanceId, model: "gpt-5.1-codex" },
59 + runtimeMode: "full-access",
60 + interactionMode: "default",
61 + branch: null,
62 + worktreePath: null,
63 + createdBy: "user",
64 + creationSource: "web",
65 + });
66 + yield* orchestrator.dispatch({
67 + type: "thread.guest-share.open",
68 + commandId: CommandId.make("open-guest-share"),
69 + threadId,
70 + shareId,
71 + host: "env.t3.test",
72 + expiresAt: DateTime.formatIso(DateTime.add(yield* DateTime.now, { hours: 24 })),
73 + });
74 + return orchestrator;
75 +});
76 +
77 +const sendGuestMessage = (orchestrator: Orchestrator.OrchestratorV2["Service"], id: string) =>
78 + orchestrator.dispatch({
79 + type: "message.dispatch",
80 + commandId: CommandId.make(id),
81 + threadId,
82 + messageId: MessageId.make(id),
83 + guestMessageId,
84 + text: "ignored: the server sends the guest's own text",
85 + attachments: [],
86 + dispatchMode: { type: "defer_start" },
87 + createdBy: "user",
88 + creationSource: "web",
89 + });
90 +
91 +it.effect("redeems a guest link once and sends each guest message once, with its turn", () =>
92 + Effect.gen(function* () {
93 + const orchestrator = yield* setup;
94 + const projections = yield* ProjectionStore.ProjectionStoreV2;
95 + const redeem = (id: string) =>
96 + orchestrator.dispatch({
97 + type: "thread.guest-share.redeem",
98 + commandId: CommandId.make(id),
99 + threadId,
100 + shareId,
101 + guestName: "Sam",
102 + });
103 + yield* redeem("redeem-1");
104 + assert.isTrue(Exit.isFailure(yield* Effect.exit(redeem("redeem-2"))));
105 +
106 + yield* orchestrator.dispatch({
107 + type: "thread.guest-message.submit",
108 + commandId: CommandId.make("submit-1"),
109 + threadId,
110 + shareId,
111 + guestMessageId,
112 + text: "Why not keep the old cache?",
113 + });
114 + assert.equal((yield* projections.getThreadShell(threadId))?.pendingGuestMessageCount, 1);
115 +
116 + yield* sendGuestMessage(orchestrator, "send-1");
117 + const projection = yield* projections.getThreadProjection(threadId);
118 + assert.deepEqual(
119 + projection.thread.guestShare?.messages.map((message) => message.status),
120 + ["sent"],
121 + );
122 + const sent = projection.messages.find((message) => message.id === MessageId.make("send-1"));
123 + assert.equal(
124 + sent?.text,
125 + "Message from guest Sam, sent by the owner:\n\nWhy not keep the old cache?",
126 + );
127 + assert.deepEqual(sent?.context?.guest, {
128 + guestMessageId,
129 + name: "Sam",
130 + text: "Why not keep the old cache?",
131 + shareId,
132 + });
133 + assert.lengthOf(projection.runs, 1);
134 + assert.equal((yield* projections.getThreadShell(threadId))?.pendingGuestMessageCount, 0);
135 +
136 + // A second owner device clicking Send must not start another turn.
137 + assert.isTrue(Exit.isFailure(yield* Effect.exit(sendGuestMessage(orchestrator, "send-2"))));
138 + assert.lengthOf((yield* projections.getThreadProjection(threadId)).runs, 1);
139 + }).pipe(Effect.provide(layerTest)),
140 +);
141 +
142 +it.effect("rejects guest messages until the link is redeemed and after archive", () =>
143 + Effect.gen(function* () {
144 + const orchestrator = yield* setup;
145 + const projections = yield* ProjectionStore.ProjectionStoreV2;
146 + const submit = orchestrator.dispatch({
147 + type: "thread.guest-message.submit",
148 + commandId: CommandId.make("submit-early"),
149 + threadId,
150 + shareId,
151 + guestMessageId,
152 + text: "Hello",
153 + });
154 + assert.isTrue(Exit.isFailure(yield* Effect.exit(submit)));
155 +
156 + yield* orchestrator.dispatch({
157 + type: "thread.archive",
158 + commandId: CommandId.make("archive-guest-share"),
159 + threadId,
160 + });
161 + assert.isNull((yield* projections.getThread(threadId)).guestShare ?? null);
162 + }).pipe(Effect.provide(layerTest)),
163 +);
164 +
165 +it.effect("drops guest attribution that a client sends on its own message", () =>
166 + Effect.gen(function* () {
167 + const orchestrator = yield* setup;
168 + const projections = yield* ProjectionStore.ProjectionStoreV2;
169 + yield* orchestrator.dispatch({
170 + type: "message.dispatch",
171 + commandId: CommandId.make("owner-message"),
172 + threadId,
173 + messageId: MessageId.make("owner-message"),
174 + text: "Mine",
175 + context: { version: 1, records: [], guest: { guestMessageId, name: "Sam", text: "Mine" } },
176 + attachments: [],
177 + dispatchMode: { type: "defer_start" },
178 + createdBy: "user",
179 + creationSource: "web",
180 + });
181 + const projection = yield* projections.getThreadProjection(threadId);
182 + const sent = projection.messages.find(
183 + (message) => message.id === MessageId.make("owner-message"),
184 + );
185 + assert.isUndefined(sent?.context?.guest);
186 + }).pipe(Effect.provide(layerTest)),
187 +);
188 +
189 +it.effect("keeps a queued guest message unchanged when the owner tries to edit it", () =>
190 + Effect.gen(function* () {
191 + const orchestrator = yield* setup;
192 + const projections = yield* ProjectionStore.ProjectionStoreV2;
193 + yield* orchestrator.dispatch({
194 + type: "message.dispatch",
195 + commandId: CommandId.make("owner-first"),
196 + threadId,
197 + messageId: MessageId.make("owner-first"),
198 + text: "Start",
199 + attachments: [],
200 + dispatchMode: { type: "defer_start" },
201 + createdBy: "user",
202 + creationSource: "web",
203 + });
204 + yield* orchestrator.dispatch({
205 + type: "thread.guest-share.redeem",
206 + commandId: CommandId.make("redeem"),
207 + threadId,
208 + shareId,
209 + guestName: "Sam",
210 + });
211 + yield* orchestrator.dispatch({
212 + type: "thread.guest-message.submit",
213 + commandId: CommandId.make("submit"),
214 + threadId,
215 + shareId,
216 + guestMessageId,
217 + text: "Why?",
218 + });
219 + yield* orchestrator.dispatch({
220 + type: "message.dispatch",
221 + commandId: CommandId.make("send-queued"),
222 + threadId,
223 + messageId: MessageId.make("send-queued"),
224 + guestMessageId,
225 + text: "",
226 + attachments: [],
227 + dispatchMode: { type: "queue_after_active" },
228 + createdBy: "user",
229 + creationSource: "web",
230 + });
231 + const queued = (yield* projections.getThreadProjection(threadId)).runs.find(
232 + (run) => run.status === "queued",
233 + );
234 + assert.isDefined(queued);
235 +
236 + const edit = orchestrator.dispatch({
237 + type: "queued-run.edit",
238 + commandId: CommandId.make("edit"),
239 + threadId,
240 + runId: queued.id,
241 + text: "My own words",
242 + });
243 + assert.isTrue(Exit.isFailure(yield* Effect.exit(edit)));
244 + const message = (yield* projections.getThreadProjection(threadId)).messages.find(
245 + (candidate) => candidate.id === MessageId.make("send-queued"),
246 + );
247 + assert.equal(message?.context?.guest?.text, "Why?");
248 + }).pipe(Effect.provide(layerTest)),
249 +);
250 +
251 +it.effect("shows a guest message as dismissed when the owner cancels its queued send", () =>
252 + Effect.gen(function* () {
253 + const orchestrator = yield* setup;
254 + const projections = yield* ProjectionStore.ProjectionStoreV2;
255 + yield* orchestrator.dispatch({
256 + type: "message.dispatch",
257 + commandId: CommandId.make("owner-first"),
258 + threadId,
259 + messageId: MessageId.make("owner-first"),
260 + text: "Start",
261 + attachments: [],
262 + dispatchMode: { type: "defer_start" },
263 + createdBy: "user",
264 + creationSource: "web",
265 + });
266 + yield* orchestrator.dispatch({
267 + type: "thread.guest-share.redeem",
268 + commandId: CommandId.make("redeem"),
269 + threadId,
270 + shareId,
271 + guestName: "Sam",
272 + });
273 + yield* orchestrator.dispatch({
274 + type: "thread.guest-message.submit",
275 + commandId: CommandId.make("submit"),
276 + threadId,
277 + shareId,
278 + guestMessageId,
279 + text: "Why?",
280 + });
281 + yield* orchestrator.dispatch({
282 + type: "message.dispatch",
283 + commandId: CommandId.make("send-queued"),
284 + threadId,
285 + messageId: MessageId.make("send-queued"),
286 + guestMessageId,
287 + text: "",
288 + attachments: [],
289 + dispatchMode: { type: "queue_after_active" },
290 + createdBy: "user",
291 + creationSource: "web",
292 + });
293 + const queued = (yield* projections.getThreadProjection(threadId)).runs.find(
294 + (run) => run.status === "queued",
295 + );
296 + assert.isDefined(queued);
297 + yield* orchestrator.dispatch({
298 + type: "queued-run.cancel",
299 + commandId: CommandId.make("cancel"),
300 + threadId,
301 + runId: queued.id,
302 + });
303 + const { thread } = yield* projections.getThreadProjection(threadId);
304 + assert.equal(
305 + thread.guestShare?.messages.find((message) => message.id === guestMessageId)?.status,
306 + "dismissed",
307 + );
308 + }).pipe(Effect.provide(layerTest)),
309 +);
310 +
311 +it.effect("brings a settled thread back when its guest sends a request", () =>
312 + Effect.gen(function* () {
313 + const orchestrator = yield* setup;
314 + const projections = yield* ProjectionStore.ProjectionStoreV2;
315 + yield* orchestrator.dispatch({
316 + type: "thread.guest-share.redeem",
317 + commandId: CommandId.make("redeem"),
318 + threadId,
319 + shareId,
320 + guestName: "Sam",
321 + });
322 + yield* orchestrator.dispatch({
323 + type: "thread.settle",
324 + commandId: CommandId.make("settle"),
325 + threadId,
326 + });
327 + assert.equal(
328 + (yield* projections.getThreadProjection(threadId)).thread.settledOverride,
329 + "settled",
330 + );
331 + yield* orchestrator.dispatch({
332 + type: "thread.guest-message.submit",
333 + commandId: CommandId.make("submit"),
334 + threadId,
335 + shareId,
336 + guestMessageId,
337 + text: "Why?",
338 + });
339 + const { thread } = yield* projections.getThreadProjection(threadId);
340 + assert.isNull(thread.settledOverride);
341 + assert.isNull(thread.settledAt);
342 + }).pipe(Effect.provide(layerTest)),
343 +);
apps/server/src/orchestration-v2/GuestShareDecider.ts new
+255
@@ -0,0 +1,255 @@
1 +import {
2 + GUEST_PENDING_ATTACHMENT_BYTES_LIMIT,
3 + GUEST_PENDING_MESSAGE_LIMIT,
4 + GUEST_RESOLVED_MESSAGE_LIMIT,
5 + type GuestMessageAttribution,
6 + type GuestMessageId,
7 + type OrchestrationMessageContext,
8 + type OrchestrationV2AppThread,
9 + type OrchestrationV2ServerCommand,
10 + type ThreadGuestMessage,
11 + type ThreadGuestShare,
12 +} from "@t3tools/contracts";
13 +import * as DateTime from "effect/DateTime";
14 +import * as Result from "effect/Result";
15 +
16 +export type GuestShareCommand = Extract<
17 + OrchestrationV2ServerCommand,
18 + {
19 + readonly type:
20 + | "thread.guest-share.open"
21 + | "thread.guest-share.redeem"
22 + | "thread.guest-share.close"
23 + | "thread.guest-message.submit"
24 + | "thread.guest-message.dismiss";
25 + }
26 +>;
27 +
28 +/** Failures a guest may be told about. Any other dispatch failure reaches them as "rejected". */
29 +export const GUEST_FAILURE = {
30 + inactive: "This guest link is no longer active.",
31 + used: "This guest link was already used.",
32 + busy: "Wait for the owner to answer your earlier messages.",
33 + filesBusy: "Wait for the owner to answer your earlier messages before you attach more files.",
34 +} as const;
35 +
36 +const isExpired = (share: ThreadGuestShare, now: DateTime.Utc) =>
37 + DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt);
38 +
39 +const pendingAttachments = (share: ThreadGuestShare | null) =>
40 + share?.messages.flatMap((message) =>
41 + message.status === "pending" ? (message.attachments ?? []) : [],
42 + ) ?? [];
43 +
44 +/**
45 + * Stored files a share change leaves behind: those of waiting messages that were dismissed or
46 + * dropped with the share. A sent message keeps its files, which its thread message now holds.
47 + */
48 +export function releasedGuestAttachmentIds(
49 + before: ThreadGuestShare | null,
50 + after: ThreadGuestShare | null,
51 +): ReadonlyArray<string> {
52 + const kept = new Set(
53 + after !== null && after.id === before?.id
54 + ? after.messages.flatMap((message) =>
55 + message.status === "dismissed"
56 + ? []
57 + : (message.attachments ?? []).map((attachment) => attachment.id),
58 + )
59 + : [],
60 + );
61 + return pendingAttachments(before)
62 + .map((attachment) => attachment.id)
63 + .filter((id) => !kept.has(id));
64 +}
65 +
66 +/** Keeps every pending message and only the newest resolved ones. */
67 +function trimResolved(messages: ReadonlyArray<ThreadGuestMessage>): Array<ThreadGuestMessage> {
68 + let resolvedBudget = GUEST_RESOLVED_MESSAGE_LIMIT;
69 + const kept: Array<ThreadGuestMessage> = [];
70 + for (const message of messages.toReversed()) {
71 + if (message.status !== "pending") {
72 + if (resolvedBudget === 0) continue;
73 + resolvedBudget -= 1;
74 + }
75 + kept.push(message);
76 + }
77 + return kept.toReversed();
78 +}
79 +
80 +const resolveMessage = (
81 + share: ThreadGuestShare,
82 + guestMessageId: GuestMessageId,
83 + status: "sent" | "dismissed",
84 +): Result.Result<ThreadGuestShare, string> => {
85 + const message = share.messages.find((candidate) => candidate.id === guestMessageId);
86 + if (message === undefined || message.status !== "pending") {
87 + return Result.fail(`Guest message ${guestMessageId} is not pending.`);
88 + }
89 + return Result.succeed({
90 + ...share,
91 + messages: trimResolved(
92 + share.messages.map((candidate) =>
93 + candidate.id === guestMessageId ? { ...candidate, status } : candidate,
94 + ),
95 + ),
96 + });
97 +};
98 +
99 +/**
100 + * Applies a guest share command to the thread. The orchestrator runs commands one at a time, so
101 + * checking state here is what makes a link redeem once and a message send once.
102 + */
103 +export function decideGuestShareCommand(input: {
104 + readonly thread: OrchestrationV2AppThread;
105 + readonly command: GuestShareCommand;
106 + readonly now: DateTime.Utc;
107 +}): Result.Result<OrchestrationV2AppThread, string> {
108 + const { thread, command, now } = input;
109 + const share = thread.guestShare ?? null;
110 + const withShare = (guestShare: ThreadGuestShare | null) =>
111 + Result.succeed({ ...thread, guestShare, updatedAt: now });
112 +
113 + switch (command.type) {
114 + case "thread.guest-share.open": {
115 + if (thread.archivedAt !== null) return Result.fail("Archived threads cannot be shared.");
116 + return withShare({
117 + id: command.shareId,
118 + host: command.host,
119 + createdAt: DateTime.formatIso(now),
120 + expiresAt: command.expiresAt,
121 + guestName: null,
122 + messages: [],
123 + });
124 + }
125 + case "thread.guest-share.close":
126 + return share === null ? Result.succeed(thread) : withShare(null);
127 + case "thread.guest-share.redeem": {
128 + if (share === null || share.id !== command.shareId || isExpired(share, now)) {
129 + return Result.fail(GUEST_FAILURE.inactive);
130 + }
131 + if (share.guestName !== null) return Result.fail(GUEST_FAILURE.used);
132 + return withShare({ ...share, guestName: command.guestName });
133 + }
134 + case "thread.guest-message.submit": {
135 + if (
136 + share === null ||
137 + share.id !== command.shareId ||
138 + share.guestName === null ||
139 + isExpired(share, now)
140 + ) {
141 + return Result.fail(GUEST_FAILURE.inactive);
142 + }
143 + if (
144 + share.messages.filter((message) => message.status === "pending").length >=
145 + GUEST_PENDING_MESSAGE_LIMIT
146 + ) {
147 + return Result.fail(GUEST_FAILURE.busy);
148 + }
149 + const attachments = command.attachments ?? [];
150 + const pendingBytes = [...pendingAttachments(share), ...attachments].reduce(
151 + (total, attachment) => total + attachment.sizeBytes,
152 + 0,
153 + );
154 + if (attachments.length > 0 && pendingBytes > GUEST_PENDING_ATTACHMENT_BYTES_LIMIT) {
155 + return Result.fail(GUEST_FAILURE.filesBusy);
156 + }
157 + const guestShare: ThreadGuestShare = {
158 + ...share,
159 + messages: trimResolved([
160 + ...share.messages,
161 + {
162 + id: command.guestMessageId,
163 + text: command.text,
164 + status: "pending",
165 + submittedAt: DateTime.formatIso(now),
166 + ...(attachments.length === 0 ? {} : { attachments }),
167 + },
168 + ]),
169 + };
170 + // A request needs the owner, so a settled thread comes back as a new message brings it.
171 + return thread.settledOverride === "settled"
172 + ? Result.succeed({
173 + ...thread,
174 + guestShare,
175 + settledOverride: null,
176 + settledAt: null,
177 + unsettledAt: now,
178 + updatedAt: now,
179 + })
180 + : withShare(guestShare);
181 + }
182 + case "thread.guest-message.dismiss": {
183 + if (share === null) return Result.fail("This thread has no guest link.");
184 + return Result.map(resolveMessage(share, command.guestMessageId, "dismissed"), (next) => ({
185 + ...thread,
186 + guestShare: next,
187 + updatedAt: now,
188 + }));
189 + }
190 + }
191 +}
192 +
193 +/**
194 + * Marks a guest message sent. `text` is what the agent receives: it names the guest so the agent
195 + * does not mistake it for the owner's words, and so a guest cannot start a slash command.
196 + * `guest` lets clients show the guest's own text with their name beside it.
197 + */
198 +export function decideGuestMessageSend(input: {
199 + readonly thread: OrchestrationV2AppThread;
200 + readonly guestMessageId: GuestMessageId;
201 + readonly now: DateTime.Utc;
202 +}): Result.Result<
203 + {
204 + readonly thread: OrchestrationV2AppThread;
205 + readonly text: string;
206 + readonly guest: GuestMessageAttribution;
207 + },
208 + string
209 +> {
210 + const share = input.thread.guestShare ?? null;
211 + if (share === null) return Result.fail("This thread has no guest link.");
212 + const message = share.messages.find((candidate) => candidate.id === input.guestMessageId);
213 + const name = share.guestName ?? "Guest";
214 + const guestText = message?.text ?? "";
215 + return Result.map(resolveMessage(share, input.guestMessageId, "sent"), (next) => ({
216 + thread: { ...input.thread, guestShare: next, updatedAt: input.now },
217 + text: `Message from guest ${name}, sent by the owner:\n\n${guestText}`,
218 + guest: { guestMessageId: input.guestMessageId, name, text: guestText, shareId: share.id },
219 + }));
220 +}
221 +
222 +/**
223 + * The owner cancelled a queued send, so the agent never got the message. It shows as dismissed,
224 + * which the guest can see, instead of sent with no reply ever coming. A share that changed since
225 + * the send is left alone.
226 + */
227 +export function guestShareAfterCancelledSend(
228 + thread: OrchestrationV2AppThread,
229 + guest: Pick<GuestMessageAttribution, "guestMessageId" | "shareId">,
230 + now: DateTime.Utc,
231 +): OrchestrationV2AppThread {
232 + const share = thread.guestShare ?? null;
233 + if (share === null || share.id !== guest.shareId) return thread;
234 + const message = share.messages.find((candidate) => candidate.id === guest.guestMessageId);
235 + if (message?.status !== "sent") return thread;
236 + return {
237 + ...thread,
238 + guestShare: {
239 + ...share,
240 + messages: share.messages.map((candidate) =>
241 + candidate.id === guest.guestMessageId ? { ...candidate, status: "dismissed" } : candidate,
242 + ),
243 + },
244 + updatedAt: now,
245 + };
246 +}
247 +
248 +/** Guest attribution comes only from `decideGuestMessageSend`; a client cannot claim it. */
249 +export function withoutGuestAttribution<
250 + C extends { readonly context?: OrchestrationMessageContext | undefined },
251 +>(command: C): C {
252 + if (command.context?.guest === undefined) return command;
253 + const { guest: _guest, ...context } = command.context;
254 + return { ...command, context };
255 +}
apps/server/src/orchestration-v2/Orchestrator.ts
+174 -7
@@ -1,4 +1,5 @@
1 import type {
2 + GuestShareId,
3 OrchestrationV2SearchThreadInput,
4 OrchestrationV2SearchThreadResult,
5 OrchestrationV2ThreadHistoryPage,
@@ -20,6 +21,7 @@ import {
21 ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
22 type ChatAttachment,
23 CommandId,
24 + type GuestMessageId,
25 isOrchestrationV2WorkActive,
26 isProviderNativeSubagentThread,
27 MessageId,
@@ -78,6 +80,7 @@ import * as Path from "effect/Path";
80 import * as Layer from "effect/Layer";
81 import * as Option from "effect/Option";
82 import * as Ref from "effect/Ref";
83 +import * as Result from "effect/Result";
84 import * as Schema from "effect/Schema";
85 import * as Stream from "effect/Stream";
86
@@ -105,6 +108,14 @@ import {
108 isUndeliveredMailboxSteer,
109 } from "./NotificationMailbox.ts";
110 import { EventSinkV2 } from "./EventSink.ts";
111 +import {
112 + decideGuestMessageSend,
113 + guestShareAfterCancelledSend,
114 + releasedGuestAttachmentIds,
115 + withoutGuestAttribution,
116 + decideGuestShareCommand,
117 + type GuestShareCommand,
118 +} from "./GuestShareDecider.ts";
119 import * as EffectOutbox from "./EffectOutbox.ts";
120 import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
121 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -387,6 +398,9 @@ export interface OrchestratorV2Shape {
398 readonly getThreadShell: (
399 threadId: ThreadId,
400 ) => Effect.Effect<OrchestrationV2ThreadShell | null, OrchestratorV2Error>;
401 + readonly findGuestShareThreadId: (
402 + shareId: GuestShareId,
403 + ) => Effect.Effect<ThreadId | null, OrchestratorV2Error>;
404 readonly getThreadEventSequence: (
405 threadId: ThreadId,
406 ) => Effect.Effect<number, OrchestratorV2Error>;
@@ -451,6 +465,11 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
465 case "thread.archive":
466 case "thread.unarchive":
467 case "thread.delete":
468 + case "thread.guest-share.open":
469 + case "thread.guest-share.redeem":
470 + case "thread.guest-share.close":
471 + case "thread.guest-message.submit":
472 + case "thread.guest-message.dismiss":
473 case "thread.settle":
474 case "thread.auto-settle":
475 case "thread.unsettle":
@@ -2658,6 +2677,100 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2677 },
2678 );
2679
2680 + // Deleted after the share change commits: the files of waiting messages it dismissed or dropped.
2681 + const releaseGuestAttachments = (
2682 + command: { readonly commandId: CommandId; readonly threadId: ThreadId },
2683 + before: OrchestrationV2AppThread["guestShare"],
2684 + after: OrchestrationV2AppThread["guestShare"],
2685 + effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
2686 + ) => {
2687 + const attachmentIds = releasedGuestAttachmentIds(before ?? null, after ?? null);
2688 + return attachmentIds.length === 0
2689 + ? Effect.void
2690 + : Ref.update(effects, (existing) => [
2691 + ...existing,
2692 + {
2693 + id: `effect:${command.commandId}:guest-attachment.cleanup`,
2694 + commandId: command.commandId,
2695 + threadId: command.threadId,
2696 + request: { type: "attachment.cleanup", attachmentIds: [...attachmentIds] },
2697 + } satisfies PendingOrchestrationEffectV2,
2698 + ]);
2699 + };
2700 +
2701 + const dispatchGuestShare = Effect.fn("orchestrationV2.dispatch.guestShare")(function* (
2702 + command: GuestShareCommand,
2703 + events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
2704 + effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
2705 + ) {
2706 + const projection = yield* projectionStore
2707 + .getThreadRecords(command.threadId, [])
2708 + .pipe(
2709 + Effect.mapError(
2710 + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
2711 + ),
2712 + );
2713 + const thread = projection.thread;
2714 + const now = yield* DateTime.now;
2715 + const decided =
2716 + thread.deletedAt !== null
2717 + ? Result.fail(`Thread ${command.threadId} is deleted.`)
2718 + : decideGuestShareCommand({
2719 + thread,
2720 + command,
2721 + now,
2722 + });
2723 + if (Result.isFailure(decided)) {
2724 + return yield* new OrchestratorDispatchError({
2725 + commandId: command.commandId,
2726 + commandType: command.type,
2727 + cause: decided.failure,
2728 + });
2729 + }
2730 + if (decided.success === thread) return;
2731 + yield* emit(
2732 + events,
2733 + command,
2734 + )({
2735 + type: "thread.guest-share-updated",
2736 + threadId: command.threadId,
2737 + providerInstanceId: thread.providerInstanceId,
2738 + occurredAt: now,
2739 + payload: decided.success,
2740 + });
2741 + yield* releaseGuestAttachments(command, thread.guestShare, decided.success.guestShare, effects);
2742 + });
2743 +
2744 + // Emitted before the message so the send and the status change commit together, and so
2745 + // `dispatchMessage`, which reads pending events, keeps the updated share.
2746 + const emitGuestMessageSent = Effect.fn("orchestrationV2.dispatch.guestMessageSent")(function* (
2747 + command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
2748 + guestMessageId: GuestMessageId,
2749 + thread: OrchestrationV2AppThread,
2750 + events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
2751 + ) {
2752 + const now = yield* DateTime.now;
2753 + const decided = decideGuestMessageSend({ thread, guestMessageId, now });
2754 + if (Result.isFailure(decided)) {
2755 + return yield* new OrchestratorDispatchError({
2756 + commandId: command.commandId,
2757 + commandType: command.type,
2758 + cause: decided.failure,
2759 + });
2760 + }
2761 + yield* emit(
2762 + events,
2763 + command,
2764 + )({
2765 + type: "thread.guest-share-updated",
2766 + threadId: command.threadId,
2767 + providerInstanceId: thread.providerInstanceId,
2768 + occurredAt: now,
2769 + payload: decided.success.thread,
2770 + });
2771 + return decided.success;
2772 + });
2773 +
2774 const dispatchThreadMutation = Effect.fn("orchestrationV2.dispatch.threadMutation")(function* (
2775 command: Extract<
2776 OrchestrationV2ServerCommand,
@@ -3099,6 +3212,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3212 ...thread,
3213 archivedAt: now,
3214 titleRegeneration: null,
3215 + guestShare: null,
3216 pullRequests: thread.pullRequests?.map((link) => withPullRequestWatch(link, undefined)),
3217 updatedAt: now,
3218 };
@@ -3600,6 +3714,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3714 occurredAt: now,
3715 payload: updatedThread,
3716 });
3717 + // Archiving ends the guest share, so its waiting files go too.
3718 + yield* releaseGuestAttachments(command, thread.guestShare, updatedThread.guestShare, effects);
3719
3720 if (command.type === "thread.metadata.update" && command.regenerateTitle === true) {
3721 yield* Ref.update(effects, (existing) => [
@@ -8423,6 +8539,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8539 },
8540 });
8541 }
8542 + const guest = queuedMessage?.context?.guest;
8543 + if (guest !== undefined) {
8544 + const thread = guestShareAfterCancelledSend(projection.thread, guest, now);
8545 + if (thread !== projection.thread) {
8546 + yield* emitEvent({
8547 + type: "thread.guest-share-updated",
8548 + threadId: command.threadId,
8549 + providerInstanceId: thread.providerInstanceId,
8550 + occurredAt: now,
8551 + payload: thread,
8552 + });
8553 + }
8554 + }
8555 });
8556
8557 const dispatchQueuedRunEdit = Effect.fn("Orchestrator.dispatchQueuedRunEdit")(function* (
@@ -8470,6 +8599,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8599 cause: "Automatic completion deliveries cannot be edited.",
8600 });
8601 }
8602 + // The agent text and the shown text of a guest message must stay the guest's words.
8603 + if (queuedMessage.context?.guest !== undefined) {
8604 + return yield* new OrchestratorDispatchError({
8605 + commandId: command.commandId,
8606 + commandType: command.type,
8607 + cause: "A guest's message cannot be edited. Cancel it instead.",
8608 + });
8609 + }
8610 const queuedTurnItem = projection.turnItems.find(
8611 (candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id,
8612 );
@@ -8485,13 +8622,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8622 ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
8623 providerInstanceId: queuedRun.providerInstanceId,
8624 occurredAt: now,
8488 - payload: {
8625 + payload: withoutGuestAttribution({
8626 ...queuedMessage,
8627 text: command.text,
8628 ...editedAttachments,
8629 ...(command.context ? { context: command.context } : {}),
8630 updatedAt: now,
8494 - },
8631 + }),
8632 });
8633 if (queuedTurnItem !== undefined && queuedTurnItem.type === "user_message") {
8634 yield* emitEvent({
@@ -8501,13 +8638,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8638 ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
8639 providerInstanceId: queuedRun.providerInstanceId,
8640 occurredAt: now,
8504 - payload: {
8641 + payload: withoutGuestAttribution({
8642 ...queuedTurnItem,
8643 text: command.text,
8644 ...editedAttachments,
8645 ...(command.context ? { context: command.context } : {}),
8646 updatedAt: now,
8510 - },
8647 + }),
8648 });
8649 }
8650 });
@@ -11582,6 +11719,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11719 case "thread.pull-request-watch.sync":
11720 yield* dispatchPullRequestWatchSync(command, events, effects);
11721 break;
11722 + case "thread.guest-share.open":
11723 + case "thread.guest-share.redeem":
11724 + case "thread.guest-share.close":
11725 + case "thread.guest-message.submit":
11726 + case "thread.guest-message.dismiss":
11727 + yield* dispatchGuestShare(command, events, effects);
11728 + break;
11729 case "provider-session.detach":
11730 yield* dispatchProviderSessionDetach(command, events, effects);
11731 break;
@@ -11602,8 +11746,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11746 threadId: command.threadId,
11747 });
11748 }
11605 - yield* dispatchMessage(command, events, effects);
11606 - yield* recordSubagentFollowup(command, events).pipe(mapDispatchError(command));
11749 + const guestSend =
11750 + command.guestMessageId === undefined
11751 + ? undefined
11752 + : yield* emitGuestMessageSent(command, command.guestMessageId, thread, events);
11753 + const dispatched =
11754 + guestSend === undefined
11755 + ? withoutGuestAttribution(command)
11756 + : {
11757 + ...command,
11758 + text: guestSend.text,
11759 + context: { version: 1 as const, records: [], guest: guestSend.guest },
11760 + };
11761 + yield* dispatchMessage(dispatched, events, effects);
11762 + yield* recordSubagentFollowup(dispatched, events).pipe(mapDispatchError(command));
11763 break;
11764 }
11765 case "notification.delivery.accept":
@@ -11880,7 +12036,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12036 planned.events.length > 0 ||
12037 command.type === "thread.background-work.settle" ||
12038 command.type === "thread.stop" ||
11883 - command.type === "subagent.stop"
12039 + command.type === "subagent.stop" ||
12040 + // A second Stop sharing, or one after the share already ended, is not an error.
12041 + command.type === "thread.guest-share.close"
12042 ? Effect.succeed(planned)
12043 : Effect.fail(
12044 new OrchestratorDispatchError({
@@ -12400,6 +12558,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12558 projectionStore
12559 .getThreadShell(threadId)
12560 .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12561 + findGuestShareThreadId: (shareId) =>
12562 + projectionStore.findGuestShareThreadId(shareId).pipe(Effect.mapError(shellProjectionError)),
12563 getThreadEventSequence: (threadId) =>
12564 eventSink
12565 .latestSequence({ threadId })
@@ -12555,6 +12715,13 @@ const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
12715 cause: "Orchestration V2 live runtime is not configured.",
12716 }),
12717 ),
12718 + findGuestShareThreadId: () =>
12719 + Effect.fail(
12720 + new OrchestratorProjectionError({
12721 + threadId: ThreadId.make("thread:shell"),
12722 + cause: "Orchestration V2 live runtime is not configured.",
12723 + }),
12724 + ),
12725 getThreadEventSequence: (threadId) =>
12726 Effect.fail(
12727 new OrchestratorProjectionError({
apps/server/src/orchestration-v2/ProjectionMaintenance.ts
+1
@@ -217,6 +217,7 @@ export const layer: Layer.Layer<
217 "thread.interaction-mode-updated",
218 "thread.model-selection-updated",
219 "thread.provider-switched",
220 + "thread.guest-share-updated",
221 ];
222 // Read-state events carry the whole thread too, but client reducers apply
223 // them without bumping updatedAt. They supersede only each other: a newer
apps/server/src/orchestration-v2/ProjectionStore.ts
+53 -3
@@ -1,3 +1,4 @@
1 +import { pendingGuestMessageCount } from "@t3tools/contracts";
2 import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts";
3 import { projectTurnItemForWire } from "./WireProjection.ts";
4 import * as Stream from "effect/Stream";
@@ -35,6 +36,7 @@ import type {
36 OrchestrationV2ThreadShell,
37 OrchestrationV2ThreadProjection,
38 OrchestrationV2TurnItem,
39 + GuestShareId,
40 ProjectId,
41 ProviderSessionId,
42 ProviderThreadId,
@@ -212,6 +214,7 @@ export type ProjectionSettlementCandidate = Pick<
214 | "activityRunStatus"
215 | "pendingRuntimeRequest"
216 | "pendingBackgroundTasks"
217 + | "pendingGuestMessageCount"
218 > &
219 Pick<OrchestrationV2AppThread, "lastSnoozeWakeAt"> & {
220 readonly latestUserAuthoredMessageAt: DateTime.Utc | null;
@@ -472,6 +475,10 @@ export interface ProjectionStoreV2Shape {
475 readonly getThreadShell: (
476 threadId: ThreadId,
477 ) => Effect.Effect<OrchestrationV2ThreadShell | null, ProjectionStoreV2Error>;
478 + /** The thread whose current guest share has this id. Scans thread rows; only redeem uses it. */
479 + readonly findGuestShareThreadId: (
480 + shareId: GuestShareId,
481 + ) => Effect.Effect<ThreadId | null, ProjectionStoreV2Error>;
482 readonly getThread: (
483 threadId: ThreadId,
484 ) => Effect.Effect<OrchestrationV2AppThread, ProjectionStoreV2Error>;
@@ -826,6 +833,7 @@ export function applyToProjection(
833 case "thread.interaction-mode-updated":
834 case "thread.model-selection-updated":
835 case "thread.provider-switched":
836 + case "thread.guest-share-updated":
837 return {
838 ...base,
839 thread: event.payload,
@@ -1666,6 +1674,7 @@ export function threadShellFromProjection(
1674 providerSession?.lastError ?? null,
1675 ),
1676 pendingRuntimeRequest,
1677 + pendingGuestMessageCount: pendingGuestMessageCount(projection.thread.guestShare),
1678 // Thread detail owns message bodies. Keeping them out of shell rows makes
1679 // initial hydration and streaming updates independent of transcript size.
1680 latestVisibleMessage: null,
@@ -1923,6 +1932,7 @@ function shellFromState(input: {
1932 lastErrorCode: input.state.lastErrorCode,
1933 usageLimitResetAt: input.state.usageLimitResetAt,
1934 pendingRuntimeRequest: input.state.pendingRuntimeRequest,
1935 + pendingGuestMessageCount: pendingGuestMessageCount(input.state.thread.guestShare),
1936 latestVisibleMessage: null,
1937 latestUserMessageAt: input.state.latestUserMessageAt,
1938 latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt,
@@ -2005,7 +2015,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2015 case "thread.runtime-mode-updated":
2016 case "thread.interaction-mode-updated":
2017 case "thread.model-selection-updated":
2008 - case "thread.provider-switched": {
2018 + case "thread.provider-switched":
2019 + case "thread.guest-share-updated": {
2020 const payloadJson = yield* encodeThreadPayload(event.payload);
2021 const payload = parseEncodedPayload(payloadJson);
2022 yield* sql`
@@ -2838,7 +2849,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2849 event.type !== "thread.runtime-mode-updated" &&
2850 event.type !== "thread.interaction-mode-updated" &&
2851 event.type !== "thread.model-selection-updated" &&
2841 - event.type !== "thread.provider-switched"
2852 + event.type !== "thread.provider-switched" &&
2853 + event.type !== "thread.guest-share-updated"
2854 ) {
2855 const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt);
2856 yield* sql`
@@ -5288,11 +5300,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5300 WHERE thread_id = ${threadId}
5301 AND type = 'dynamic_tool'
5302 AND (payload_json LIKE '%htmlRender%' OR payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`})
5303 + `,
5304 + // A guest's waiting files are pending uploads that no message row holds yet.
5305 + sql<{ id: string }>`
5306 + SELECT DISTINCT json_extract(attachment.value, '$.id') AS id
5307 + FROM orchestration_v2_projection_threads AS thread,
5308 + json_each(thread.payload_json, '$.guestShare.messages') AS message,
5309 + json_each(message.value, '$.attachments') AS attachment
5310 + WHERE thread.thread_id = ${threadId}
5311 + AND json_extract(message.value, '$.status') = 'pending'
5312 `,
5313 ]).pipe(
5293 - Effect.map(([messages, renders]) => [
5314 + Effect.map(([messages, renders, guestFiles]) => [
5315 ...new Set([
5316 ...messages.map((row) => row.id),
5317 + ...guestFiles.map((row) => row.id),
5318 ...threadHtmlRenderAttachmentIds(
5319 threadId,
5320 renders.map((row) => {
@@ -6175,6 +6197,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6197 activityRunStatus: null,
6198 activityRunStartedAt: null,
6199 pendingRuntimeRequest: null,
6200 + pendingGuestMessageCount: pendingGuestMessageCount(thread.guestShare),
6201 pendingBackgroundTasks: derivePendingBackgroundWork({
6202 latestRun:
6203 latestRunId === null || status === "idle"
@@ -6553,6 +6576,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6576 Effect.mapError(shellSnapshotReadError),
6577 );
6578
6579 + const findGuestShareThreadId = Effect.fn("ProjectionStore.findGuestShareThreadId")(function* (
6580 + shareId: GuestShareId,
6581 + ) {
6582 + const rows = yield* sql<{ readonly thread_id: string }>`
6583 + SELECT thread_id
6584 + FROM orchestration_v2_projection_threads
6585 + WHERE json_extract(payload_json, '$.guestShare.id') = ${shareId}
6586 + LIMIT 1
6587 + `;
6588 + return rows[0] === undefined ? null : ThreadId.make(rows[0].thread_id);
6589 + }, Effect.mapError(shellSnapshotReadError));
6590 +
6591 const getThreadShell: ProjectionStoreV2Shape["getThreadShell"] = (threadId) =>
6592 sql
6593 .withTransaction(
@@ -6648,6 +6683,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6683 listActiveSubagentThreadIds: readOnReader(listActiveSubagentThreadIds),
6684 readShellSnapshot: readOnReader(readShellSnapshot),
6685 getThreadShell: readOnReader(getThreadShell),
6686 + findGuestShareThreadId: readOnReader(findGuestShareThreadId),
6687 getThread: readOnReader(getThread),
6688 getSettlementCandidates: readOnReader(getSettlementCandidates),
6689 getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests),
@@ -6795,6 +6831,15 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6831 .pipe(Effect.map(threadShellFromProjection));
6832 return shell.deletedAt === null ? shell : null;
6833 }),
6834 + findGuestShareThreadId: Effect.fn("ProjectionStore.findGuestShareThreadId")(
6835 + function* (shareId) {
6836 + const existing = (yield* Ref.get(replayState)).projections;
6837 + for (const { thread } of existing.values()) {
6838 + if (thread.guestShare?.id === shareId) return thread.id;
6839 + }
6840 + return null;
6841 + },
6842 + ),
6843 getThread: Effect.fn("ProjectionStore.getThread")(function* (threadId) {
6844 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6845 if (projection === undefined) {
@@ -7008,6 +7053,11 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
7053 ...projection.messages.flatMap((message) =>
7054 message.attachments.map((attachment) => attachment.id),
7055 ),
7056 + ...(projection.thread.guestShare?.messages ?? []).flatMap((message) =>
7057 + message.status === "pending"
7058 + ? (message.attachments ?? []).map((attachment) => attachment.id)
7059 + : [],
7060 + ),
7061 ...threadHtmlRenderAttachmentIds(
7062 threadId,
7063 projection.turnItems.flatMap((item) =>
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+1
@@ -214,6 +214,7 @@ it.effect(
214 listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),
215 readShellSnapshot: () => Effect.die("unused readShellSnapshot"),
216 getThreadShell: () => Effect.die("unused getThreadShell"),
217 + findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
218 getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
219 getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
220 getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
apps/server/src/orchestration-v2/ThreadForkService.ts
+2
@@ -110,6 +110,8 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
110 settledAt: null,
111 snoozedUntil: null,
112 snoozedAt: null,
113 + // A guest link belongs to the thread it was made for.
114 + guestShare: null,
115 lastVisitedAt: null,
116 // A fork is a new thread; it does not inherit how often the source was opened.
117 opens: null,
apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts
+74 -11
@@ -7,6 +7,8 @@ import {
7 ChatAttachmentId,
8 CommandId,
9 EventId,
10 + GuestMessageId,
11 + MessageId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
@@ -18,7 +20,11 @@ import {
20 import * as DateTime from "effect/DateTime";
21 import * as Effect from "effect/Effect";
22 import * as Layer from "effect/Layer";
21 -import { createPendingAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
23 +import {
24 + createAttachmentId,
25 + createPendingAttachmentId,
26 + resolveAttachmentPath,
27 +} from "../attachmentStore.ts";
28 import * as ServerConfig from "../config.ts";
29 import * as ServerSettings from "../serverSettings.ts";
30 import {
@@ -32,18 +38,21 @@ const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
38 prefix: "t3-question-intake-",
39 }).pipe(Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ServerSettings.layerTest()));
40
41 +const layerFailingDispatchHandler =
42 + (captured: OrchestrationV2ServerCommand[]) => (command: OrchestrationV2ServerCommand) => {
43 + captured.push(command);
44 + return Effect.fail(
45 + new OrchestratorDispatchError({
46 + commandId: command.commandId,
47 + commandType: command.type,
48 + cause: "Stop after intake",
49 + }),
50 + );
51 + };
52 +
53 const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) =>
54 Layer.mock(ThreadManagementService.ThreadManagementService)({
37 - dispatch: (command) => {
38 - captured.push(command);
39 - return Effect.fail(
40 - new OrchestratorDispatchError({
41 - commandId: command.commandId,
42 - commandType: command.type,
43 - cause: "Stop after intake",
44 - }),
45 - );
46 - },
55 + dispatch: layerFailingDispatchHandler(captured),
56 });
57
58 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", () =>
368 ).toHaveLength(2);
369 }).pipe(Effect.provide(layerIntakeTest)),
370 );
371 +
372 +it.effect("sends a guest message with the guest's files, never ones the client names", () =>
373 + Effect.gen(function* () {
374 + const config = yield* ServerConfig.ServerConfig;
375 + const guestFile = {
376 + type: "image" as const,
377 + id: ChatAttachmentId.make(createAttachmentId("thread-guest")!),
378 + name: "screen.png",
379 + mimeType: "image/png",
380 + sizeBytes: 3,
381 + };
382 + NodeFS.writeFileSync(
383 + NodePath.join(config.attachmentsDir, `${guestFile.id}.png`),
384 + new Uint8Array([1, 2, 3]),
385 + );
386 + const guestMessageId = GuestMessageId.make("guest-message:files");
387 + const captured: OrchestrationV2ServerCommand[] = [];
388 + const layerGuestShare = Layer.mock(ThreadManagementService.ThreadManagementService)({
389 + dispatch: layerFailingDispatchHandler(captured),
390 + // Only the share is read.
391 + getThreadSnapshotWindow: () =>
392 + Effect.succeed({
393 + projection: {
394 + thread: {
395 + guestShare: {
396 + messages: [{ id: guestMessageId, status: "pending", attachments: [guestFile] }],
397 + },
398 + },
399 + },
400 + } as unknown as Effect.Success<
401 + ReturnType<
402 + ThreadManagementService.ThreadManagementServiceShape["getThreadSnapshotWindow"]
403 + >
404 + >),
405 + });
406 + yield* dispatchCommand({
407 + type: "message.dispatch",
408 + commandId: CommandId.make("send-guest-message"),
409 + threadId: ThreadId.make("thread-guest"),
410 + messageId: MessageId.make("message-guest"),
411 + guestMessageId,
412 + text: "",
413 + attachments: [{ ...guestFile, id: ChatAttachmentId.make("thread-guest-owner-file") }],
414 + dispatchMode: { type: "queue_after_active" },
415 + createdBy: "user",
416 + creationSource: "web",
417 + }).pipe(Effect.provide(layerGuestShare), Effect.result);
418 + const command = captured[0];
419 + if (command?.type !== "message.dispatch") throw new Error("Expected a message dispatch.");
420 + expect(command.attachments).toHaveLength(1);
421 + // The guest's file, which is already the thread's.
422 + expect(command.attachments).toEqual([guestFile]);
423 + }).pipe(Effect.provide(layerIntakeTest)),
424 +);
apps/server/src/orchestration-v2/ThreadMessageIntake.ts
+31 -1
@@ -53,9 +53,39 @@ const releaseUnusedClaims = Effect.fn("ThreadMessageIntake.releaseUnusedClaims")
53 );
54 });
55
56 +/**
57 + * A guest message goes out with the files the guest attached, never ones a client names. They
58 + * are already the thread's attachments. A message no longer waiting gets none; the orchestrator
59 + * then refuses or replays the send.
60 + */
61 +const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments")(function* (
62 + command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
63 +) {
64 + if (command.guestMessageId === undefined) return command;
65 + const threads = yield* ThreadManagement.ThreadManagementService;
66 + // Only the thread record is needed; the window keeps the read small.
67 + const { projection } = yield* threads
68 + .getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })
69 + .pipe(
70 + Effect.mapError(
71 + (cause) =>
72 + new AttachmentClaims.AttachmentClaimError({
73 + message: "Failed to read the guest message.",
74 + cause,
75 + }),
76 + ),
77 + );
78 + const message = projection.thread.guestShare?.messages.find(
79 + (candidate) => candidate.id === command.guestMessageId && candidate.status === "pending",
80 + );
81 + return { ...command, attachments: message?.attachments ?? [] };
82 +});
83 +
84 export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
57 - command: OrchestrationV2Command,
85 + incoming: OrchestrationV2Command,
86 ) {
87 + const command =
88 + incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming;
89 const threads = yield* ThreadManagement.ThreadManagementService;
90 if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
91 const config = yield* ServerConfig.ServerConfig;
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+15
@@ -141,6 +141,21 @@ describe("isAutoSettlementCandidate", () => {
141 ).toBe(true);
142 });
143
144 + it("never settles, or keeps snoozed, a thread whose guest is waiting on the owner", () => {
145 + expect(
146 + ThreadSettlementService.isAutoSettlementCandidate(
147 + shell({ pendingGuestMessageCount: 1 }),
148 + NOW_MS,
149 + ),
150 + ).toBe(false);
151 + const snoozed = shell({
152 + snoozedUntil: at(60 * 60 * 1_000),
153 + snoozedAt: at(-60 * 60 * 1_000),
154 + pendingGuestMessageCount: 1,
155 + });
156 + expect(ThreadSettlementService.isSnoozed(snoozed, NOW_MS)).toBe(false);
157 + });
158 +
159 it("keeps snoozed threads parked until a fresh failure or timer wake", () => {
160 const snoozed = shell({
161 snoozedUntil: at(60 * 60 * 1_000),
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+10 -1
@@ -152,6 +152,8 @@ export function isAutoSettlementCandidate(
152 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
153 if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false;
154 if (thread.pendingRuntimeRequest !== null) return false;
155 + // A guest is waiting on the owner; settling would hide the Request.
156 + if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
157 if (thread.activityRunStatus != null) return false;
158 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false;
159 if (threadHasQueuedTurnStart(thread, nowMs)) return false;
@@ -166,13 +168,20 @@ export function isAutoSettlementCandidate(
168 export function isSnoozed(
169 thread: Pick<
170 ProjectionStore.ProjectionSettlementCandidate,
169 - "snoozedUntil" | "snoozedAt" | "latestRunCompletedAt" | "status" | "pendingRuntimeRequest"
171 + | "snoozedUntil"
172 + | "snoozedAt"
173 + | "latestRunCompletedAt"
174 + | "status"
175 + | "pendingRuntimeRequest"
176 + | "pendingGuestMessageCount"
177 >,
178 nowMs: number,
179 ): boolean {
180 const snoozedUntilMs = toMillis(thread.snoozedUntil);
181 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
182 if (thread.pendingRuntimeRequest !== null) return false;
183 + // Same as the client: a waiting guest message wakes the thread, and the snooze stays stored.
184 + if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
185 const snoozedAtMs = toMillis(thread.snoozedAt);
186 const completedAtMs = toMillis(thread.latestRunCompletedAt);
187 const wokeOnError =
apps/server/src/orchestration-v2/runtimeLayer.ts
+4
@@ -1,3 +1,4 @@
1 +import * as GuestShareService from "../guest/GuestShareService.ts";
2 import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";
3 import * as Scheduler from "../scheduling/Scheduler.ts";
4 import * as Layer from "effect/Layer";
@@ -367,6 +368,9 @@ export const layerProduction = Layer.mergeAll(
368 layerThreadLifecycleProvided,
369 layerScheduledTaskProvided,
370 layerSecretRequestsProvided,
371 + GuestShareService.layer.pipe(
372 + Layer.provide(Layer.merge(layerOrchestratorProvided, layerCommandOutputHubProvided)),
373 + ),
374 UsageLimitRecoveryWorker.layer.pipe(
375 Layer.provide(
376 Layer.mergeAll(
apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+2
@@ -135,6 +135,8 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
135 case "thread.archive":
136 case "thread.unarchive":
137 case "thread.delete":
138 + case "thread.guest-share.close":
139 + case "thread.guest-message.dismiss":
140 case "thread.settle":
141 case "thread.auto-settle":
142 case "thread.unsettle":
apps/server/src/relay/AgentAwarenessRelay.ts
+1
@@ -104,6 +104,7 @@ function shouldPublishAgentAwarenessEvent(
104 return true;
105 // Unsettling must not re-alert a dismissed result.
106 case "thread.unsettled":
107 + case "thread.guest-share-updated":
108 case "thread.snoozed":
109 case "thread.unsnoozed":
110 case "thread.auto-settle-set":
apps/server/src/server.ts
+2
@@ -141,6 +141,7 @@ import {
141 } from "./cloud/config.ts";
142 import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
143 import * as CloudHttp from "./cloud/http.ts";
144 +import * as GuestHttp from "./guest/http.ts";
145 import * as CloudLink from "./cloud/CloudLink.ts";
146 import * as ConnectReachability from "./cloud/ConnectReachability.ts";
147 import { pendingServiceUpdateExists } from "./cloud/updateHandoff.ts";
@@ -719,6 +720,7 @@ const layerMakeRoutes = Layer.mergeAll(
720 ServerHttp.layerOtlpTracesProxyRoute,
721 ServerHttp.layerAssetRoute,
722 ServerHttp.layerAttachmentUploadRoute,
723 + GuestHttp.layer,
724 DeviceHubProxy.layer,
725 ServerBrowserStream.routeLayer,
726 ServerHttp.layerStaticAndDevRoute,
apps/server/src/ws.test.ts
+2
@@ -69,6 +69,7 @@ import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
69 import * as ReviewService from "./review/ReviewService.ts";
70 import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
71 import * as SecretRequests from "./secrets/SecretRequests.ts";
72 +import * as GuestShareService from "./guest/GuestShareService.ts";
73 import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
74 import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
75 import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
@@ -405,6 +406,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
406 Layer.mock(ReviewService.ReviewService)({}),
407 Layer.mock(ScheduledTasks.ScheduledTaskService)({}),
408 Layer.mock(SecretRequests.SecretRequests)({}),
409 + Layer.mock(GuestShareService.GuestShareService)({}),
410 Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}),
411 Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}),
412 Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}),
apps/server/src/ws.ts
+6
@@ -121,6 +121,7 @@ import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"
121 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
122 import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
123 import * as SecretRequests from "./secrets/SecretRequests.ts";
124 +import * as GuestShareService from "./guest/GuestShareService.ts";
125 import {
126 archivedShellStreamItemFromThreadShell,
127 buildActiveShellSnapshot,
@@ -1268,6 +1269,7 @@ export const layerWsRpc = (
1269 const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2;
1270 const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService;
1271 const secretRequests = yield* SecretRequests.SecretRequests;
1272 + const guestShares = yield* GuestShareService.GuestShareService;
1273 const pullRequests = yield* PullRequestService.PullRequestService;
1274 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
1275 const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor;
@@ -2162,6 +2164,10 @@ export const layerWsRpc = (
2164 Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe(
2165 Effect.andThen(scheduledTasks.rotateWebhookToken(input)),
2166 ),
2167 + [WS_METHODS.guestShareCreate]: (input) =>
2168 + Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
2169 + Effect.andThen(guestShares.create(input)),
2170 + ),
2171 [WS_METHODS.secretsAnswerRequest]: (input) =>
2172 Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
2173 Effect.andThen(secretRequests.answer(input)),
apps/web/src/components/ChatView.tsx
+66 -25
@@ -165,6 +165,7 @@ import {
165 } from "../previewMiniPlayerStore";
166 import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.logic";
167 import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog";
168 +import { GuestPendingMessages } from "./chat/GuestShareControls";
169 import { useDeviceState } from "~/state/device";
170 import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
171 import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
@@ -2960,23 +2961,53 @@ export default function ChatView(props: ChatViewProps) {
2961 const sendPreviewAnnotationStable = useStableCallback(sendPreviewAnnotation);
2962 const onComposerResumeStable = useStableCallback(onResume);
2963 const onComposerCompactContextStable = useStableCallback(onCompactContext);
2964 + // Read from the projection the footer renders, so the scroll below sees the new message.
2965 + const pendingGuestMessageIds =
2966 + serverProjection?.thread.guestShare?.messages.flatMap((message) =>
2967 + message.status === "pending" ? [message.id] : [],
2968 + ) ?? [];
2969 + const pendingGuestMessageCount = pendingGuestMessageIds.length;
2970 + const pendingGuestMessageKey = pendingGuestMessageIds.join(",");
2971 + const previousPendingGuestMessagesRef = useRef({
2972 + threadKey: routeThreadKey,
2973 + key: pendingGuestMessageKey,
2974 + });
2975 + useEffect(() => {
2976 + const previous = previousPendingGuestMessagesRef.current;
2977 + previousPendingGuestMessagesRef.current = {
2978 + threadKey: routeThreadKey,
2979 + key: pendingGuestMessageKey,
2980 + };
2981 + // Opening another thread is not a new message; its own scroll position wins.
2982 + if (previous.threadKey !== routeThreadKey) return;
2983 + // Pending guest messages sit in the list footer, which the list does not follow on its own.
2984 + // The follow flag reflects the owner's position before the footer grew; a live measure may not.
2985 + // Any new id counts, even when another one was resolved in the same update.
2986 + const previousIds = new Set(previous.key.split(","));
2987 + const hasNewMessage = pendingGuestMessageKey
2988 + .split(",")
2989 + .some((id) => id !== "" && !previousIds.has(id));
2990 + if (hasNewMessage && timelineLiveFollowEnabled) scrollToEnd(true);
2991 + }, [routeThreadKey, pendingGuestMessageKey, timelineLiveFollowEnabled, scrollToEnd]);
2992 const queuedRunsControl =
2993 isServerThread && activeThread ? (
2965 - <QueuedRunsControl
2966 - ref={queuedRunsControlRef}
2967 - steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {
2968 - context: { terminalFocus: false },
2969 - })}
2970 - editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {
2971 - context: { composerFocus: true },
2972 - })}
2973 - environmentId={activeThread.environmentId}
2974 - threadId={activeThread.id}
2975 - optimisticMessages={optimisticUserMessages}
2976 - editingRunId={queuedRunEdit.editingRunId}
2977 - onEditQueuedRun={queuedRunEdit.beginEdit}
2978 - onCancelEdit={queuedRunEdit.cancelEdit}
2979 - />
2994 + <>
2995 + <QueuedRunsControl
2996 + ref={queuedRunsControlRef}
2997 + steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {
2998 + context: { terminalFocus: false },
2999 + })}
3000 + editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {
3001 + context: { composerFocus: true },
3002 + })}
3003 + environmentId={activeThread.environmentId}
3004 + threadId={activeThread.id}
3005 + optimisticMessages={optimisticUserMessages}
3006 + editingRunId={queuedRunEdit.editingRunId}
3007 + onEditQueuedRun={queuedRunEdit.beginEdit}
3008 + onCancelEdit={queuedRunEdit.cancelEdit}
3009 + />
3010 + </>
3011 ) : null;
3012 // One-shot: the resend "Work locally" queued fires once, then the marker clears.
3013 const resendAfterWorkLocally = () => {
@@ -3316,18 +3347,28 @@ export default function ChatView(props: ChatViewProps) {
3347 {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
3348 isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree}
3349 footer={
3319 - paintOnlyDisplayedTimeline ? null : pendingHandoff === null ? (
3320 - threadStatusLine
3321 - ) : (
3350 + paintOnlyDisplayedTimeline ||
3351 + (pendingHandoff === null &&
3352 + pendingGuestMessageCount === 0 &&
3353 + threadStatusLine === null) ? null : (
3354 <>
3323 - <div className="chat-content-lane">
3324 - <HandoffRow
3325 - environmentId={environmentId}
3326 - endpoints={pendingHandoff}
3327 - providers={providerStatuses}
3328 - pending
3355 + {pendingHandoff === null ? null : (
3356 + <div className="chat-content-lane">
3357 + <HandoffRow
3358 + environmentId={environmentId}
3359 + endpoints={pendingHandoff}
3360 + providers={providerStatuses}
3361 + pending
3362 + />
3363 + </div>
3364 + )}
3365 + {pendingGuestMessageCount > 0 && isServerThread && activeThread ? (
3366 + <GuestPendingMessages
3367 + threadRef={scopeThreadRef(activeThread.environmentId, activeThread.id)}
3368 + onImageExpand={onExpandTimelineImageStable}
3369 + onFileOpen={openFileAttachmentStable}
3370 />
3330 - </div>
3371 + ) : null}
3372 {threadStatusLine}
3373 </>
3374 )
apps/web/src/components/CommandPalette.tsx
+20
@@ -64,6 +64,7 @@ import {
64 SettingsIcon,
65 SquarePenIcon,
66 TextSearchIcon,
67 + UserPlusIcon,
68 } from "lucide-react";
69 import { requestThreadFindOpen } from "./chat/threadFindActionBus";
70 import {
@@ -217,6 +218,8 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
218 import { Checkbox } from "./ui/checkbox";
219 import { ProjectFilePicker } from "./files/ProjectFilePicker";
220 import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";
221 +import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
222 +import { openGuestShareDialog } from "./chat/guestShareDialogState";
223 import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
224 import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";
225 import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
@@ -540,6 +543,9 @@ function OpenCommandPaletteDialog(props: {
543 const activeThreadServerConfig = useServerConfigs().get(
544 activeThread?.environmentId ?? ("" as EnvironmentId),
545 );
546 + const canShareActiveThreadWithGuest = useAtomValue(
547 + canShareWithGuestAtom(activeThread?.environmentId ?? ("" as EnvironmentId)),
548 + );
549 const activeThreadReferenceCopyTarget =
550 referenceThreadRef === null || (pathname === "/pull-requests" && !openPanelPullRequestUrl)
551 ? null
@@ -1364,6 +1370,20 @@ function OpenCommandPaletteDialog(props: {
1370 }
1371 }
1372
1373 + if (activeThread !== null && canShareActiveThreadWithGuest) {
1374 + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
1375 + actionItems.push({
1376 + kind: "action",
1377 + value: "action:share-thread-with-guest",
1378 + searchTerms: ["share", "guest", "invite", "link", "teammate"],
1379 + title: "Share with guest",
1380 + icon: <UserPlusIcon className={ITEM_ICON_CLASS} />,
1381 + run: async () => {
1382 + openGuestShareDialog(threadRef);
1383 + },
1384 + });
1385 + }
1386 +
1387 if (activeThread !== null) {
1388 const thread = activeThread;
1389 actionItems.push({
apps/web/src/components/LegacySidebar.tsx
+11 -1
@@ -207,7 +207,10 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
207 import { useIsMobile } from "~/hooks/useMediaQuery";
208 import { CommandDialogTrigger } from "./ui/command";
209 import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
210 -import { primaryServerKeybindingsAtom } from "../state/server";
210 +import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server";
211 +import { appAtomRegistry } from "../rpc/atomRegistry";
212 +import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
213 +import { openGuestShareDialog } from "./chat/guestShareDialogState";
214 import {
215 derivePhysicalProjectKey,
216 deriveProjectGroupingOverrideKey,
@@ -2165,6 +2168,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2168 ? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
2169 : []),
2170 { id: "rename", label: "Rename thread", disabled: !canOperateThread },
2171 + ...(appAtomRegistry.get(canShareWithGuestAtom(thread.environmentId))
2172 + ? [{ id: "share-guest", label: "Share with guest" }]
2173 + : []),
2174 { id: "mark-unread", label: "Mark unread" },
2175 { id: "copy-path", label: "Copy Path" },
2176 { id: "copy-thread-id", label: "Copy Thread ID" },
@@ -2216,6 +2222,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2222 return;
2223 }
2224
2225 + if (clicked === "share-guest") {
2226 + openGuestShareDialog(threadRef);
2227 + return;
2228 + }
2229 if (clicked === "mark-unread") {
2230 markThreadUnread(threadRef);
2231 return;
apps/web/src/components/Sidebar.logic.test.ts
+13
@@ -272,6 +272,19 @@ describe("resolveSidebarThreadStatus", () => {
272 ).toBe("approval");
273 });
274
275 + it("shows a waiting guest message as a Request, below the agent's own requests", () => {
276 + expect(resolveSidebarThreadStatus({ ...idle, pendingGuestMessageCount: 1, runtime })).toBe(
277 + "request",
278 + );
279 + expect(
280 + resolveSidebarThreadStatus({
281 + ...idle,
282 + hasPendingUserInput: true,
283 + pendingGuestMessageCount: 1,
284 + }),
285 + ).toBe("input");
286 + });
287 +
288 it("keeps usage-limit stops Limited and visible until the thread recovers", () => {
289 const limited = {
290 ...runtime,
apps/web/src/components/Sidebar.logic.ts
+29 -3
@@ -589,6 +589,7 @@ export interface ThreadStatusPill {
589 | "Failed"
590 | "Pending Approval"
591 | "Awaiting Input"
592 + | "Guest Request"
593 | "Waiting"
594 | "Plan Ready";
595 colorClass: string;
@@ -599,6 +600,7 @@ export interface ThreadStatusPill {
600 const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
601 "Pending Approval": 5,
602 "Awaiting Input": 4,
603 + "Guest Request": 3.75,
604 Failed: 3.5,
605 Working: 3,
606 Connecting: 3,
@@ -613,6 +615,7 @@ type ThreadStatusInput = Pick<
615 | "hasPendingApprovals"
616 | "hasPendingUserInput"
617 | "pendingSubagentRequest"
618 + | "pendingGuestMessageCount"
619 | "interactionMode"
620 | "latestRun"
621 | "runtime"
@@ -866,6 +869,7 @@ export function isContextMenuPointerDown(input: {
869 export type SidebarThreadStatus =
870 | "approval"
871 | "input"
872 + | "request"
873 | "working"
874 | "waiting"
875 | "failed"
@@ -879,7 +883,14 @@ export function shouldRecedeSidebarThread(input: {
883 isActive: boolean;
884 isSelected: boolean;
885 }): boolean {
882 - if (input.isActive || input.isSelected || input.status === "input") return false;
886 + if (
887 + input.isActive ||
888 + input.isSelected ||
889 + input.status === "input" ||
890 + input.status === "request"
891 + ) {
892 + return false;
893 + }
894 if (input.status === "working" || input.status === "waiting") return true;
895 if (input.status === "ready" || input.status === "approval") {
896 return !input.isUnread && !input.isWoke;
@@ -892,6 +903,7 @@ type SidebarThreadStatusInput = Pick<
903 | "hasPendingApprovals"
904 | "hasPendingUserInput"
905 | "pendingSubagentRequest"
906 + | "pendingGuestMessageCount"
907 | "runtime"
908 | "blockedOnThreadWait"
909 >;
@@ -903,6 +915,10 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si
915 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
916 return "input";
917 }
918 + // A guest is waiting on the owner; the agent's own requests come first.
919 + if ((thread.pendingGuestMessageCount ?? 0) > 0) {
920 + return "request";
921 + }
922 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
923 return "waiting";
924 }
@@ -927,6 +943,7 @@ export type SidebarV2TopStatusKind =
943 | "failed"
944 | "limited"
945 | "input"
946 + | "request"
947 | "waiting"
948 | "woke"
949 | "working";
@@ -945,8 +962,8 @@ export function resolveSidebarV2TopStatus(input: {
962 if (input.status === "approval") {
963 return "approval";
964 }
948 - if (input.status === "input") {
949 - return "input";
965 + if (input.status === "input" || input.status === "request") {
966 + return input.status;
967 }
968 if (input.status === "failed" || input.status === "limited") {
969 return input.status;
@@ -1092,6 +1109,15 @@ export function resolveThreadStatusPill(input: {
1109 };
1110 }
1111
1112 + if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1113 + return {
1114 + label: "Guest Request",
1115 + colorClass: "text-guest-foreground",
1116 + dotClass: "bg-guest",
1117 + pulse: false,
1118 + };
1119 + }
1120 +
1121 if (
1122 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1123 thread.runtime?.status === "waiting"
apps/web/src/components/Sidebar.tsx
+10 -1
@@ -126,12 +126,15 @@ import {
126 useQuietThreadShells,
127 } from "../state/entities";
128 import { environmentPresentations } from "../state/presentation";
129 -import { primaryServerKeybindingsAtom } from "../state/server";
129 +import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server";
130 import { environmentProjects } from "../state/projects";
131 import { threadEnvironment } from "../state/threads";
132 import { useThreadSearch } from "../state/queries";
133 import { useOrchestrationCommand } from "../state/use-orchestration-command";
134 import { readEnvironmentScope } from "../state/session";
135 +import { appAtomRegistry } from "../rpc/atomRegistry";
136 +import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
137 +import { openGuestShareDialog } from "./chat/guestShareDialogState";
138 import { buildThreadRouteParams, resolveActiveThreadRouteRef } from "../threadRoutes";
139 import type { SidebarThreadSummary } from "../types";
140 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
@@ -2388,6 +2391,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2391 canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),
2392 isRegeneratingTitle,
2393 isRunning: !threadRuntimeCanArchive(thread.runtime),
2394 + canShareWithGuest: appAtomRegistry.get(
2395 + canShareWithGuestAtom(threadRef.environmentId),
2396 + ),
2397 supports: {
2398 settlement: supportsSettlement,
2399 autoSettleOptOut: supportsAutoSettleOptOut,
@@ -2484,6 +2490,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2490 case "rename":
2491 startThreadRename(threadRef, thread.title);
2492 return;
2493 + case "share-guest":
2494 + openGuestShareDialog(threadRef);
2495 + return;
2496 case "regenerate-title": {
2497 if (isRegeneratingTitle) return;
2498 const result = await updateThreadMetadata({
apps/web/src/components/ThreadNotificationCoordinator.tsx
+8 -2
@@ -139,7 +139,11 @@ function EnvironmentNotifications({
139 let status = resolveSidebarThreadStatus(thread);
140 if (status === "ready" && thread.latestRun?.status === "failed") status = "failed";
141 const attention =
142 - status === "input" || status === "approval" || status === "failed" || status === "limited"
142 + status === "input" ||
143 + status === "request" ||
144 + status === "approval" ||
145 + status === "failed" ||
146 + status === "limited"
147 ? `${thread.latestRun?.runId ?? ""}:${status}`
148 : null;
149 const completedAt = Date.parse(thread.latestRun?.completedAt ?? "");
@@ -170,7 +174,9 @@ function EnvironmentNotifications({
174 ? "Usage limit reached"
175 : status === "failed"
176 ? "Thread failed"
173 - : "Input needed";
177 + : status === "request"
178 + ? "Guest request"
179 + : "Input needed";
180 if (hasNotificationSound(mode)) {
181 void playNotificationSound(kind, () =>
182 hasNotificationSound(getClientSettings().notificationMode),
apps/web/src/components/chat/ChatHeader.tsx
+7
@@ -24,6 +24,9 @@ import { toastManager } from "../ui/toast";
24 import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
25 import { readLocalApi } from "~/localApi";
26 import { threadEnvironment } from "../../state/threads";
27 +import { serverEnvironment } from "../../state/server";
28 +import { canShareWithGuestAtom } from "./guestShareAvailability";
29 +import { useAtomValue } from "@effect/atom-react";
30 import { useOrchestrationCommand } from "../../state/use-orchestration-command";
31 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
32 import { ProjectFavicon } from "../ProjectFavicon";
@@ -37,6 +40,7 @@ import { observeResize } from "~/lib/observeResize";
40 import { cn } from "~/lib/utils";
41 import { textDirection } from "~/textDirection";
42 import { useClientSettings } from "../../hooks/useSettings";
43 +import { GuestShareIndicator } from "./GuestShareControls";
44
45 interface ChatHeaderProps {
46 activeThreadEnvironmentId: EnvironmentId;
@@ -88,6 +92,7 @@ export const ChatHeader = memo(function ChatHeader({
92 activeThreadEnvironmentId,
93 AuthOrchestrationOperateScope,
94 );
95 + const canShareWithGuest = useAtomValue(canShareWithGuestAtom(activeThreadEnvironmentId));
96 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
97 reportFailure: false,
98 });
@@ -191,6 +196,7 @@ export const ChatHeader = memo(function ChatHeader({
196 threadRef: isServerThread ? activeThreadRef : null,
197 projectCwd: activeProjectCwd,
198 onStartRename: startRename,
199 + canShareWithGuest,
200 });
201 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
202 const titleMenuTimerRef = useRef<number | null>(null);
@@ -406,6 +412,7 @@ export const ChatHeader = memo(function ChatHeader({
412 )}
413 </WorkspaceBreadcrumbItem>
414 </WorkspaceBreadcrumb>
415 + {isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
416 </div>
417 );
418 });
apps/web/src/components/chat/CommandOutputPanel.tsx
+10 -6
@@ -1,3 +1,4 @@
1 +import type { CommandOutputView } from "@t3tools/client-runtime/state/command-output";
2 import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
3 import { TERMINAL_PALETTES, terminalOutputSpans } from "@t3tools/shared/terminalOutput";
4 import { useLayoutEffect, useRef } from "react";
@@ -6,6 +7,7 @@ import { useTheme } from "../../hooks/useTheme";
7 import { useServerConfigs } from "../../state/entities";
8 import { orchestrationEnvironment } from "../../state/orchestration";
9 import { useEnvironmentQuery } from "../../state/query";
10 +import type { TurnItemSource } from "./timelineRowContext";
11
12 // Within this many pixels of the end still counts as following the output.
13 const FOLLOW_SLACK_PX = 8;
@@ -19,19 +21,21 @@ export function useCommandOutputStreaming(environmentId: EnvironmentId): boolean
21
22 /**
23 * Output of one expanded command row: streams while the command runs, then
22 - * shows its final output. Mount it only when `useCommandOutputStreaming` holds.
24 + * shows its final output. Mount it only when `useCommandOutputStreaming` holds
25 + * or a `source` serves the output.
26 * It subscribes only while mounted, so collapsed rows and other threads receive nothing.
27 */
28 export function CommandOutputPanel(props: {
29 readonly environmentId: EnvironmentId;
30 readonly threadId: ThreadId;
31 readonly itemId: TurnItemId;
32 + readonly source?: TurnItemSource["commandOutput"] | undefined;
33 }) {
30 - const { data, error } = useEnvironmentQuery(
31 - orchestrationEnvironment.v2.commandOutput({
32 - environmentId: props.environmentId,
33 - input: { threadId: props.threadId, itemId: props.itemId },
34 - }),
34 + const input = { threadId: props.threadId, itemId: props.itemId };
35 + const { data, error } = useEnvironmentQuery<CommandOutputView, unknown>(
36 + props.source
37 + ? props.source(input)
38 + : orchestrationEnvironment.v2.commandOutput({ environmentId: props.environmentId, input }),
39 );
40 const scrollRef = useRef<HTMLDivElement>(null);
41 // Follow new output until the reader scrolls up; scrolling back down resumes.
apps/web/src/components/chat/GuestMessageAttachments.tsx new
+102
@@ -0,0 +1,102 @@
1 +import type { ChatAttachment } from "@t3tools/contracts";
2 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
3 +
4 +import { useTheme } from "~/hooks/useTheme";
5 +import { cn } from "~/lib/utils";
6 +import { type ChatFileAttachment, isFileAttachment, isImageAttachment } from "../../types";
7 +import { AttachmentImage } from "../media/AttachmentImage";
8 +import { PierreEntryIcon } from "./PierreEntryIcon";
9 +
10 +const IMAGE_FRAME =
11 + "aspect-[4/3] overflow-hidden rounded-lg border border-border/80 bg-background/70";
12 +const FILE_ROW = "flex min-w-0 items-center gap-2 py-1 text-sm";
13 +
14 +/**
15 + * A guest message's files, drawn like a sent message's: image thumbnails, then file rows. The
16 + * owner opens them in the app; the guest loads them from the guest route.
17 + */
18 +export function GuestMessageAttachments(props: {
19 + readonly attachments: ReadonlyArray<ChatAttachment>;
20 + /** Where an image loads from; undefined while its URL is not ready. */
21 + readonly imageUrl: (attachment: ChatAttachment) => string | undefined;
22 + readonly onOpenImage: (attachment: ChatAttachment) => void;
23 + /** A file row as a link, or a button that calls `onOpenFile`. */
24 + readonly fileHref?: (attachment: ChatFileAttachment) => string;
25 + readonly onOpenFile?: (attachment: ChatFileAttachment) => void;
26 +}) {
27 + const { resolvedTheme } = useTheme();
28 + const images = props.attachments.filter(isImageAttachment);
29 + const files = props.attachments.filter(isFileAttachment);
30 + if (images.length === 0 && files.length === 0) return null;
31 + return (
32 + <div className="flex flex-col items-end gap-2">
33 + {images.length > 0 ? (
34 + <div className="grid w-[210px] grid-cols-2 gap-2">
35 + {images.map((image) => {
36 + const src = props.imageUrl(image);
37 + return (
38 + <div key={image.id} className={IMAGE_FRAME}>
39 + {src ? (
40 + <button
41 + type="button"
42 + className="block size-full cursor-zoom-in"
43 + aria-label={`Preview ${image.name}`}
44 + onClick={() => props.onOpenImage(image)}
45 + >
46 + <AttachmentImage
47 + name={image.name}
48 + mimeType={image.mimeType}
49 + src={src}
50 + alt={image.name}
51 + decoding="async"
52 + className="block size-full object-cover"
53 + />
54 + </button>
55 + ) : (
56 + <div className="flex size-full items-center justify-center px-2 text-center text-2xs text-muted-foreground/70">
57 + {image.name}
58 + </div>
59 + )}
60 + </div>
61 + );
62 + })}
63 + </div>
64 + ) : null}
65 + {files.map((file) => {
66 + const identity = (
67 + <>
68 + <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
69 + <span className="min-w-0 truncate">{file.name}</span>
70 + <span className="shrink-0 text-xs text-muted-foreground">
71 + {formatAttachmentSize(file.sizeBytes)}
72 + </span>
73 + </>
74 + );
75 + return props.fileHref ? (
76 + <a
77 + key={file.id}
78 + href={props.fileHref(file)}
79 + download={file.name}
80 + className={cn(FILE_ROW, "hover:underline")}
81 + >
82 + {identity}
83 + </a>
84 + ) : props.onOpenFile ? (
85 + <button
86 + key={file.id}
87 + type="button"
88 + aria-label={`Preview ${file.name}`}
89 + onClick={() => props.onOpenFile?.(file)}
90 + className={cn(FILE_ROW, "cursor-pointer hover:underline")}
91 + >
92 + {identity}
93 + </button>
94 + ) : (
95 + <div key={file.id} className={FILE_ROW}>
96 + {identity}
97 + </div>
98 + );
99 + })}
100 + </div>
101 + );
102 +}
apps/web/src/components/chat/GuestShareControls.tsx new
+326
@@ -0,0 +1,326 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + isAtomCommandInterrupted,
4 + squashAtomCommandFailure,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import {
7 + AuthOrchestrationOperateScope,
8 + type ChatAttachment,
9 + type GuestMessageId,
10 + type ScopedThreadRef,
11 + type ThreadGuestShare,
12 +} from "@t3tools/contracts";
13 +import { CheckIcon, CopyIcon, UserIcon } from "lucide-react";
14 +import { useState } from "react";
15 +
16 +import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
17 +import { useNowMinute } from "~/hooks/useNowMinute";
18 +import { appAtomRegistry } from "~/rpc/atomRegistry";
19 +import { useQuietThreadProjection } from "~/state/entities";
20 +import { serverEnvironment } from "~/state/server";
21 +import { useEnvironmentScope } from "~/state/session";
22 +import { threadEnvironment } from "~/state/threads";
23 +import { useAtomCommand } from "~/state/use-atom-command";
24 +import { cn } from "~/lib/utils";
25 +import { useOrchestrationCommand } from "~/state/use-orchestration-command";
26 +import { Button } from "../ui/button";
27 +import {
28 + Dialog,
29 + DialogDescription,
30 + DialogFooter,
31 + DialogHeader,
32 + DialogPanel,
33 + DialogPopup,
34 + DialogTitle,
35 +} from "../ui/dialog";
36 +import { Input } from "../ui/input";
37 +import { useAssetUrls } from "~/assets/assetUrls";
38 +import { type ChatFileAttachment, isImageAttachment } from "../../types";
39 +import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
40 +import { GuestMessageAttachments } from "./GuestMessageAttachments";
41 +import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle";
42 +import { guestShareDialogThreadAtom } from "./guestShareDialogState";
43 +
44 +function useThreadGuestShare(threadRef: ScopedThreadRef | null): ThreadGuestShare | null {
45 + return useQuietThreadProjection(threadRef)?.projection.thread.guestShare ?? null;
46 +}
47 +
48 +export function GuestShareDialogHost() {
49 + const threadRef = useAtomValue(guestShareDialogThreadAtom);
50 + if (threadRef === null) return null;
51 + return (
52 + <GuestShareDialog
53 + key={`${threadRef.environmentId}:${threadRef.threadId}`}
54 + threadRef={threadRef}
55 + onClose={() => appAtomRegistry.set(guestShareDialogThreadAtom, null)}
56 + />
57 + );
58 +}
59 +
60 +type CreateState =
61 + | { readonly status: "idle" }
62 + | { readonly status: "creating" }
63 + | { readonly status: "created"; readonly url: string }
64 + | { readonly status: "failed"; readonly message: string };
65 +
66 +function GuestShareDialog({
67 + threadRef,
68 + onClose,
69 +}: {
70 + readonly threadRef: ScopedThreadRef;
71 + readonly onClose: () => void;
72 +}) {
73 + const activeShare = useThreadGuestShare(threadRef);
74 + const canCreate = useAtomValue(
75 + serverEnvironment.createGuestShare.permissionAtom(threadRef.environmentId),
76 + );
77 + const createGuestShare = useAtomCommand(serverEnvironment.createGuestShare, {
78 + reportFailure: false,
79 + });
80 + const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "guest link" });
81 + const [state, setState] = useState<CreateState>({ status: "idle" });
82 +
83 + const create = async () => {
84 + setState({ status: "creating" });
85 + const result = await createGuestShare({
86 + environmentId: threadRef.environmentId,
87 + input: { threadId: threadRef.threadId },
88 + });
89 + if (result._tag === "Success") {
90 + setState({ status: "created", url: result.value.url });
91 + return;
92 + }
93 + if (isAtomCommandInterrupted(result)) {
94 + setState({ status: "idle" });
95 + return;
96 + }
97 + const error = squashAtomCommandFailure(result);
98 + setState({
99 + status: "failed",
100 + message: error instanceof Error ? error.message : "Could not create a guest link.",
101 + });
102 + };
103 +
104 + return (
105 + <Dialog
106 + open
107 + onOpenChange={(open) => {
108 + if (!open && state.status !== "creating") onClose();
109 + }}
110 + >
111 + <DialogPopup className="max-w-lg">
112 + <DialogHeader>
113 + <DialogTitle>Share with guest</DialogTitle>
114 + <DialogDescription>
115 + The guest sees the thread as you do, including command output and the agent&apos;s
116 + reasoning. Each message they send waits for you.
117 + </DialogDescription>
118 + </DialogHeader>
119 + <DialogPanel>
120 + {state.status === "created" ? (
121 + <div className="flex items-center gap-2">
122 + <Input
123 + readOnly
124 + aria-label="Guest link"
125 + value={state.url}
126 + onFocus={(event) => event.currentTarget.select()}
127 + />
128 + <Button size="sm" variant="outline" onClick={() => copyToClipboard(state.url)}>
129 + {isCopied ? <CheckIcon /> : <CopyIcon />}
130 + {isCopied ? "Copied" : "Copy"}
131 + </Button>
132 + </div>
133 + ) : (
134 + <p className="text-muted-foreground text-sm">
135 + {activeShare !== null
136 + ? "A new link ends the current one."
137 + : "The link works once and expires in 24 hours."}
138 + </p>
139 + )}
140 + {state.status === "failed" ? (
141 + <p role="alert" className="text-destructive text-xs">
142 + {state.message}
143 + </p>
144 + ) : null}
145 + </DialogPanel>
146 + <DialogFooter>
147 + {state.status === "created" ? (
148 + <Button size="sm" onClick={onClose}>
149 + Done
150 + </Button>
151 + ) : (
152 + <>
153 + <Button
154 + variant="outline"
155 + size="sm"
156 + onClick={onClose}
157 + disabled={state.status === "creating"}
158 + >
159 + Cancel
160 + </Button>
161 + <Button
162 + size="sm"
163 + onClick={() => void create()}
164 + disabled={!canCreate || state.status === "creating"}
165 + >
166 + {state.status === "creating" ? "Creating..." : "Create link"}
167 + </Button>
168 + </>
169 + )}
170 + </DialogFooter>
171 + </DialogPopup>
172 + </Dialog>
173 + );
174 +}
175 +
176 +/** Header status for a shared thread, with the way to end the share. */
177 +export function GuestShareIndicator({ threadRef }: { readonly threadRef: ScopedThreadRef }) {
178 + const share = useThreadGuestShare(threadRef);
179 + const closeGuestShare = useOrchestrationCommand(threadEnvironment.closeGuestShare, {
180 + label: "stop guest share",
181 + });
182 + const [closing, setClosing] = useState(false);
183 + if (share === null) return null;
184 + return (
185 + <div className="flex shrink-0 items-center gap-1 text-muted-foreground text-xs">
186 + <UserIcon aria-hidden className="size-3.5" />
187 + <GuestShareStatus share={share} />
188 + <Button
189 + size="xs"
190 + variant="ghost-muted"
191 + disabled={closing}
192 + onClick={async () => {
193 + setClosing(true);
194 + await closeGuestShare({
195 + environmentId: threadRef.environmentId,
196 + input: { threadId: threadRef.threadId },
197 + });
198 + setClosing(false);
199 + }}
200 + >
201 + Stop sharing
202 + </Button>
203 + </div>
204 + );
205 +}
206 +
207 +function GuestShareStatus({ share }: { readonly share: ThreadGuestShare }) {
208 + const nowMinute = useNowMinute();
209 + // The share stays on the thread after it expires, until the owner clears it.
210 + if (share.expiresAt.slice(0, 16) <= nowMinute) return <span>Guest link expired</span>;
211 + return (
212 + <span>{share.guestName !== null ? `${share.guestName} is a guest` : "Guest link active"}</span>
213 + );
214 +}
215 +
216 +/**
217 + * A guest's messages wait at the end of the timeline until the owner sends or dismisses each one.
218 + * Sent ones then show in the timeline as normal user messages with the guest's name.
219 + */
220 +export function GuestPendingMessages({
221 + threadRef,
222 + onImageExpand,
223 + onFileOpen,
224 +}: {
225 + readonly threadRef: ScopedThreadRef;
226 + readonly onImageExpand: (preview: ExpandedImagePreview) => void;
227 + readonly onFileOpen: (attachment: ChatFileAttachment) => void;
228 +}) {
229 + const share = useThreadGuestShare(threadRef);
230 + const canOperate = useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope);
231 + const resolveGuestMessage = useOrchestrationCommand(threadEnvironment.resolveGuestMessage, {
232 + label: "resolve guest message",
233 + });
234 + const [busyIds, setBusyIds] = useState<ReadonlySet<GuestMessageId>>(new Set());
235 + const pending = share?.messages.filter((message) => message.status === "pending") ?? [];
236 + // The files are the thread's attachments, which the owner's environment serves like any other.
237 + const images = pending.flatMap((message) => message.attachments ?? []).filter(isImageAttachment);
238 + const imageUrls = useAssetUrls(
239 + threadRef.environmentId,
240 + images.map((image) => ({ _tag: "attachment" as const, attachmentId: image.id })),
241 + );
242 + const imageUrlById = new Map(
243 + images.flatMap((image, index) => {
244 + const url = imageUrls[index];
245 + return url ? [[image.id, url] as const] : [];
246 + }),
247 + );
248 + if (share === null || pending.length === 0) return null;
249 + const guestName = share.guestName ?? "Guest";
250 + const openImage = (attachment: ChatAttachment) => {
251 + const preview = buildExpandedImagePreview(
252 + images.map((image) => ({ ...image, previewUrl: imageUrlById.get(image.id) ?? "" })),
253 + attachment.id,
254 + );
255 + if (preview) onImageExpand(preview);
256 + };
257 +
258 + const resolve = async (guestMessageId: GuestMessageId, decision: "send" | "dismiss") => {
259 + setBusyIds((ids) => new Set(ids).add(guestMessageId));
260 + await resolveGuestMessage({
261 + environmentId: threadRef.environmentId,
262 + input: { threadId: threadRef.threadId, guestMessageId, decision },
263 + });
264 + setBusyIds((ids) => {
265 + const next = new Set(ids);
266 + next.delete(guestMessageId);
267 + return next;
268 + });
269 + };
270 +
271 + return (
272 + <ol
273 + className="chat-content-lane flex flex-col gap-4 pb-4"
274 + aria-label={`${pending.length} guest message${pending.length === 1 ? "" : "s"} waiting`}
275 + aria-live="polite"
276 + >
277 + {pending.map((message) => {
278 + const busy = busyIds.has(message.id);
279 + return (
280 + <li key={message.id} className="flex flex-col items-end gap-1">
281 + <GuestMessageName name={guestName} />
282 + <div
283 + className={cn(
284 + "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-foreground",
285 + guestBubbleClassName(true),
286 + )}
287 + >
288 + <GuestMessageAttachments
289 + attachments={message.attachments ?? []}
290 + imageUrl={(attachment) => imageUrlById.get(attachment.id)}
291 + onOpenImage={openImage}
292 + onOpenFile={onFileOpen}
293 + />
294 + {message.text ? (
295 + <p className="text-sm leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]">
296 + {message.text}
297 + </p>
298 + ) : null}
299 + </div>
300 + {canOperate ? (
301 + <div className="flex items-center gap-1 pe-1">
302 + <Button
303 + size="xs"
304 + variant="ghost-muted"
305 + disabled={busy}
306 + aria-label={`Dismiss message from ${guestName}`}
307 + onClick={() => void resolve(message.id, "dismiss")}
308 + >
309 + Dismiss
310 + </Button>
311 + <Button
312 + size="xs"
313 + disabled={busy}
314 + aria-label={`Send message from ${guestName}`}
315 + onClick={() => void resolve(message.id, "send")}
316 + >
317 + Send
318 + </Button>
319 + </div>
320 + ) : null}
321 + </li>
322 + );
323 + })}
324 + </ol>
325 + );
326 +}
apps/web/src/components/chat/MessagesTimeline.tsx
+8 -2
@@ -212,15 +212,17 @@ interface MessagesTimelineProps {
212 paintOnly?: boolean;
213 /** Off where another region already speaks the thread's status, like a subagent's bar. */
214 announceTurnStatus?: boolean;
215 - onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
215 + onOpenTurnDiff?: (runId: RunId, filePath?: string) => void;
216 onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
217 + renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];
218 + turnItemSource?: TimelineRowSharedState["turnItemSource"];
219 parentThreadLink?: {
220 readonly threadId: ThreadId;
221 readonly title: string;
222 } | null;
223 /** Set on a workflow coordinator's thread: its script message renders as this opening. */
224 workflowOpening?: WorkflowOpening | null;
223 - onForkFromRun: (input: {
225 + onForkFromRun?: (input: {
226 readonly sourceThreadId: ThreadId;
227 readonly runId: RunId;
228 }) => Promise<void>;
@@ -328,6 +330,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
330 announceTurnStatus = true,
331 onOpenTurnDiff,
332 onOpenThread,
333 + renderHtmlRender,
334 + turnItemSource,
335 parentThreadLink = null,
336 workflowOpening = null,
337 onForkFromRun,
@@ -931,6 +935,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
935 openPullRequest,
936 onOpenTurnDiff,
937 onOpenThread,
938 + renderHtmlRender,
939 + turnItemSource,
940 workflowOpening,
941 onForkFromRun,
942 onRollbackCheckpoint,
apps/web/src/components/chat/QueuedRunsControl.tsx
+20 -3
@@ -119,12 +119,15 @@ export function QueuedRunsControl({
119 (message) => message.inputIntent === "queued_turn" && !acknowledgedMessageIds.has(message.id),
120 );
121 const items = [
122 - ...queued.map(({ run, text, attachments }, serverIndex) => ({
122 + ...queued.map(({ run, text, attachments, context }, serverIndex) => ({
123 key: run.id,
124 runId: run.id,
125 messageId: run.userMessageId,
126 serverIndex,
127 text,
128 + // A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.
129 + editable: context?.guest === undefined,
130 + guestName: context?.guest?.name,
131 attachments,
132 thumbnails: attachments
133 .filter((attachment) => attachment.type === "image")
@@ -141,6 +144,8 @@ export function QueuedRunsControl({
144 messageId: null,
145 serverIndex: null,
146 text: message.text,
147 + editable: true,
148 + guestName: undefined,
149 attachments: [] as ReadonlyArray<ContractChatAttachment>,
150 thumbnails: (message.attachments ?? [])
151 .filter(isImageAttachment)
@@ -202,7 +207,14 @@ export function QueuedRunsControl({
207 // moving the caret inside that draft.
208 editLatest(repeat) {
209 const latest = queued.at(-1);
205 - if (!latest || props.editingRunId !== null || busyRunId !== null) return false;
210 + if (
211 + !latest ||
212 + latest.context?.guest !== undefined ||
213 + props.editingRunId !== null ||
214 + busyRunId !== null
215 + ) {
216 + return false;
217 + }
218 if (!repeat) {
219 setExpanded(true);
220 props.onEditQueuedRun({
@@ -380,6 +392,9 @@ export function QueuedRunsControl({
392 ))}
393 </span>
394 ) : null}
395 + {item.guestName === undefined ? null : (
396 + <span className="shrink-0 text-guest-foreground">{item.guestName}</span>
397 + )}
398 <Tooltip>
399 <TooltipTrigger render={<span className="min-w-0 flex-1 truncate" />}>
400 {previewText}
@@ -408,7 +423,9 @@ export function QueuedRunsControl({
423 size="icon-xs"
424 variant="ghost-muted"
425 aria-label="Edit queued message"
411 - disabled={item.runId === null || busyRunId !== null}
426 + disabled={
427 + item.runId === null || !item.editable || busyRunId !== null
428 + }
429 onClick={() => {
430 if (item.runId !== null && item.messageId !== null) {
431 props.onEditQueuedRun({
apps/web/src/components/chat/TimelineAssistantRows.tsx
+16 -10
@@ -53,12 +53,14 @@ export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind
53 />
54 </AssistantCitationSource>
55 </div>
56 - <AssistantChangedFilesSection
57 - turnSummary={row.assistantTurnDiffSummary}
58 - routeThreadKey={ctx.routeThreadKey}
59 - resolvedTheme={ctx.resolvedTheme}
60 - onOpenTurnDiff={ctx.onOpenTurnDiff}
61 - />
56 + {ctx.onOpenTurnDiff ? (
57 + <AssistantChangedFilesSection
58 + turnSummary={row.assistantTurnDiffSummary}
59 + routeThreadKey={ctx.routeThreadKey}
60 + resolvedTheme={ctx.resolvedTheme}
61 + onOpenTurnDiff={ctx.onOpenTurnDiff}
62 + />
63 + ) : null}
64 {row.showAssistantMeta ? (
65 <AssistantMessageMeta
66 className="mt-1.5"
@@ -90,7 +92,8 @@ function AssistantForkButton({
92 capabilities: support.providerSession?.capabilities,
93 });
94
93 - if (!canFork || projectedItem.item.runId === null) return null;
95 + const onForkFromRun = ctx.onForkFromRun;
96 + if (!canFork || onForkFromRun === undefined || projectedItem.item.runId === null) return null;
97 const runId = projectedItem.item.runId;
98
99 return (
@@ -104,9 +107,9 @@ function AssistantForkButton({
107 disabled={busy}
108 onClick={() => {
109 setBusy(true);
107 - void ctx
108 - .onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId })
109 - .finally(() => setBusy(false));
110 + void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally(
111 + () => setBusy(false),
112 + );
113 }}
114 aria-label="Fork from this response"
115 />
@@ -244,6 +247,9 @@ export function HtmlRenderTimelineRow({
247 const { onAppFullscreenChange } = ctx;
248 const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);
249
250 + if (ctx.renderHtmlRender) {
251 + return <div className="min-w-0 px-1">{ctx.renderHtmlRender(row)}</div>;
252 + }
253 return (
254 <div className="min-w-0 px-1">
255 <HtmlRenderFrame
apps/web/src/components/chat/TimelineUserMessageRow.tsx
+15 -3
@@ -42,6 +42,7 @@ import {
42 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
43 SnapShotAttachmentDetails,
44 } from "./SnapShotAttachmentDetails";
45 +import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle";
46 import { MessageCopyButton } from "./MessageCopyButton";
47 import { promptLinkFor } from "../promptLinks/copyPromptLink";
48 import { PierreEntryIcon } from "./PierreEntryIcon";
@@ -303,7 +304,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
304 ? { environmentId: ctx.activeThreadEnvironmentId, threadId: senderThreadId }
305 : null,
306 );
306 - const resolvedContext = resolveUserMessageContext(row.message);
307 + const resolvedContext = resolveUserMessageContext(
308 + userMessage.attribution === "guest" ? { ...row.message, text: userMessage.text } : row.message,
309 + );
310 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
311 const revertTurnCount = row.revertTurnCount;
312 const chippedAttachmentIds = new Set(
@@ -427,13 +430,20 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
430 Sent by T3 Code
431 </p>
432 ) : null}
433 + {/* The row's heading already names the guest for screen readers. */}
434 + {userMessage.guestName !== undefined ? (
435 + <div aria-hidden>
436 + <GuestMessageName name={userMessage.guestName} />
437 + </div>
438 + ) : null}
439 {row.message.inputIntent === "steer" ||
440 row.message.inputIntent === "promoted_queued_to_steer" ? (
441 <UserMessageIntentMarker intent={row.message.inputIntent} />
442 ) : null}
443 <div
444 className={cn(
436 - "relative min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",
445 + "relative min-w-0 max-w-[80%] rounded-2xl text-message-foreground",
446 + userMessage.attribution === "guest" ? guestBubbleClassName(false) : "bg-message",
447 !folded && "p-3",
448 folded && expanded && "w-full",
449 )}
@@ -457,7 +467,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
467 folded && !ctx.findActive && "max-h-96 overflow-auto",
468 )}
469 >
460 - <MessageAuthorHeading>You</MessageAuthorHeading>
470 + <MessageAuthorHeading>
471 + {userMessage.guestName === undefined ? "You" : `${userMessage.guestName} (guest)`}
472 + </MessageAuthorHeading>
473 {(regularImages.length > 0 || userVideos.length > 0) && (
474 <div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
475 {regularImages.map((image) => (
apps/web/src/components/chat/TimelineV2EventRow.tsx
+2
@@ -126,6 +126,7 @@ export function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind:
126 onOpenTurnDiff={ctx.onOpenTurnDiff}
127 onRollbackCheckpoint={ctx.onRollbackCheckpoint}
128 onImageExpand={ctx.onImageExpand}
129 + source={ctx.turnItemSource}
130 />
131 </div>
132 </div>
@@ -201,6 +202,7 @@ export function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind:
202 onOpenTurnDiff={ctx.onOpenTurnDiff}
203 onRollbackCheckpoint={ctx.onRollbackCheckpoint}
204 onImageExpand={ctx.onImageExpand}
205 + source={ctx.turnItemSource}
206 />
207 </div>
208 </div>
apps/web/src/components/chat/TimelineWorkEntryRow.tsx
+2
@@ -534,6 +534,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
534 onOpenTurnDiff={ctx.onOpenTurnDiff}
535 onRollbackCheckpoint={ctx.onRollbackCheckpoint}
536 onImageExpand={ctx.onImageExpand}
537 + source={ctx.turnItemSource}
538 />
539 ) : (
540 <>
@@ -545,6 +546,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
546 projectedItem={workEntry.projectedItem}
547 environmentId={ctx.activeThreadEnvironmentId}
548 onImageExpand={onImageExpand}
549 + source={ctx.turnItemSource}
550 />
551 ) : null}
552 </>
apps/web/src/components/chat/V2ItemInspector.tsx
+27 -7
@@ -31,6 +31,7 @@ import { CommandOutputPanel, useCommandOutputStreaming } from "./CommandOutputPa
31 import { resolveExternalWebLinkHref } from "./externalLinkContextMenu";
32 import type { ExpandedImagePreview } from "./ExpandedImagePreview";
33 import { ShellCommandBlock } from "./ShellCommandBlock";
34 +import type { TurnItemSource } from "./timelineRowContext";
35
36 interface V2ItemInspectorProps {
37 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
@@ -38,12 +39,13 @@ interface V2ItemInspectorProps {
39 readonly cwd?: string | undefined;
40 readonly workspaceRoot?: string | undefined;
41 readonly onOpenThread: (threadId: ThreadId) => void;
41 - readonly onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
42 + readonly onOpenTurnDiff?: ((runId: RunId, filePath?: string) => void) | undefined;
43 readonly onRollbackCheckpoint?: (input: {
44 readonly checkpointId: string;
45 readonly scopeId: string;
46 }) => void;
47 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
48 + readonly source?: TurnItemSource | undefined;
49 }
50
51 function SyntaxTokens({
@@ -112,6 +114,7 @@ function StructuredValue({
114 function useFetchedTurnItem(
115 projectedItem: OrchestrationV2ProjectedTurnItem,
116 environmentId: EnvironmentId,
117 + source: TurnItemSource | undefined,
118 skip = false,
119 ) {
120 const wireItem = projectedItem.item;
@@ -125,6 +128,7 @@ function useFetchedTurnItem(
128 revision: turnItemDetailRevision(wireItem),
129 }
130 : null,
131 + source?.detail,
132 );
133 const fetchedItem = detail.data?.item;
134 const item = fetchedItem?.type === wireItem.type ? fetchedItem : wireItem;
@@ -188,8 +192,9 @@ export function FetchedToolOutput(props: {
192 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
193 readonly environmentId: EnvironmentId;
194 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
195 + readonly source?: TurnItemSource | undefined;
196 }) {
192 - const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId);
197 + const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId, props.source);
198 return (
199 <div className={cn("mt-1.5 space-y-1.5", monoClassName)}>
200 <ToolOutput {...output} onImageExpand={props.onImageExpand} />
@@ -236,10 +241,16 @@ function ToolCallBody(
241
242 export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) {
243 // Command rows stream their output, including the final output, from the server.
244 + const environmentStreamsOutput = useCommandOutputStreaming(props.environmentId);
245 const streamsOutput =
240 - useCommandOutputStreaming(props.environmentId) &&
246 + (props.source !== undefined || environmentStreamsOutput) &&
247 props.projectedItem.item.type === "command_execution";
242 - const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId, streamsOutput);
248 + const fetched = useFetchedTurnItem(
249 + props.projectedItem,
250 + props.environmentId,
251 + props.source,
252 + streamsOutput,
253 + );
254 const item = fetched.item;
255 const outputState = fetched.output;
256 const support = useV2ItemSupport({
@@ -275,6 +286,7 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec
286 environmentId={props.environmentId}
287 threadId={props.projectedItem.sourceThreadId}
288 itemId={props.projectedItem.sourceItemId}
289 + source={props.source?.commandOutput}
290 />
291 ) : undefined
292 }
@@ -293,11 +305,11 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec
305 <span className="text-diff-deletion">-{formatDiffCount(item.deletions ?? 0)}</span>
306 </span>
307 ) : null}
296 - {item.runId !== null ? (
308 + {item.runId !== null && props.onOpenTurnDiff ? (
309 <Button
310 size="xs"
311 variant="outline"
300 - onClick={() => props.onOpenTurnDiff(item.runId!, item.fileName)}
312 + onClick={() => props.onOpenTurnDiff?.(item.runId!, item.fileName)}
313 >
314 Open diff
315 </Button>
@@ -386,7 +398,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec
398
399 {item.type === "approval_request" ? <StructuredValue value={item.prompt} /> : null}
400 {item.type === "user_input_request" ? (
389 - <StructuredValue value={item.questions.map((question) => question.question).join("\n\n")} />
401 + <StructuredValue
402 + value={item.questions
403 + .map((question) =>
404 + [question.question, ...question.options.map((option) => `• ${option.label}`)].join(
405 + "\n",
406 + ),
407 + )
408 + .join("\n\n")}
409 + />
410 ) : null}
411 {item.type === "notification" ? <StructuredValue value={item.detail} /> : null}
412 {item.type === "system_notice" ? <StructuredValue value={item.message} /> : null}
apps/web/src/components/chat/guestMessageStyle.tsx new
+14
@@ -0,0 +1,14 @@
1 +/** Bubble classes for a guest's message. A pending one has a dashed edge and no fill. */
2 +export function guestBubbleClassName(pending: boolean): string {
3 + return pending ? "border border-dashed border-guest/50 bg-transparent" : "bg-guest-surface";
4 +}
5 +
6 +/** The guest's name above their message, where "Sent by T3 Code" sits for server messages. */
7 +export function GuestMessageName({ name }: { readonly name: string }) {
8 + return (
9 + <p className="me-1 text-2xs text-guest-foreground">
10 + {name}
11 + <span className="sr-only"> (guest)</span>
12 + </p>
13 + );
14 +}
apps/web/src/components/chat/guestShareAvailability.ts new
+18
@@ -0,0 +1,18 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import { Atom } from "effect/reactivity";
3 +
4 +import { environmentPresentations } from "~/state/presentation";
5 +import { serverEnvironment } from "~/state/server";
6 +
7 +/**
8 + * Whether this environment offers "Share with guest": the user may create links there, and its
9 + * Guest links beta is on (Settings > Beta). The server refuses links while the beta is off.
10 + */
11 +export const canShareWithGuestAtom = Atom.family((environmentId: EnvironmentId) =>
12 + Atom.make(
13 + (get) =>
14 + get(serverEnvironment.createGuestShare.permissionAtom(environmentId)) &&
15 + get(environmentPresentations.serverConfigsAtom).get(environmentId)?.settings
16 + .guestSharingEnabled === true,
17 + ).pipe(Atom.withLabel(`guest-share:available:${environmentId}`)),
18 +);
apps/web/src/components/chat/guestShareDialogState.ts new
+17
@@ -0,0 +1,17 @@
1 +import type { ScopedThreadRef } from "@t3tools/contracts";
2 +import { Atom } from "effect/reactivity";
3 +
4 +import { appAtomRegistry } from "~/rpc/atomRegistry";
5 +
6 +/**
7 + * Which thread has the guest share dialog open. The thread menu and the command palette both
8 + * close as their command runs, so the chat view renders the dialog once.
9 + */
10 +export const guestShareDialogThreadAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
11 + Atom.keepAlive,
12 + Atom.withLabel("guest-share:dialog-thread"),
13 +);
14 +
15 +export function openGuestShareDialog(threadRef: ScopedThreadRef): void {
16 + appAtomRegistry.set(guestShareDialogThreadAtom, threadRef);
17 +}
apps/web/src/components/chat/timelineRowContext.ts
+30 -6
@@ -8,9 +8,12 @@ import {
8 type ServerProviderSkill,
9 type RunId,
10 ThreadId,
11 + type TurnItemId,
12 } from "@t3tools/contracts";
13 +import type { AsyncResult, Atom } from "effect/reactivity";
14 +import type { CommandOutputView } from "@t3tools/client-runtime/state/command-output";
15 import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
13 -import { createContext, type MouseEvent } from "react";
16 +import { createContext, type MouseEvent, type ReactNode } from "react";
17 import { type LegendListRef } from "@legendapp/list/react";
18 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
19 import { type ChatFileAttachment } from "../../types";
@@ -18,8 +21,21 @@ import { ExpandedImagePreview } from "./ExpandedImagePreview";
21 import { type AssistantCitationTarget } from "./AssistantCitationSource";
22 import { type MessagesTimelineRow, type WorkGroupScrollAnchor } from "./MessagesTimeline.logic";
23 import { type TimestampFormat } from "@t3tools/contracts/settings";
24 +import type { TurnItemDetailSource } from "../../state/queries";
25 import { type HandoffTimelineRun } from "./V2LifecycleRow";
26
27 +/**
28 + * Where an expanded row reads an item's detail and a command's output. The owner's rows read them
29 + * from the environment; the guest page reads them through its own routes.
30 + */
31 +export interface TurnItemSource {
32 + readonly detail: TurnItemDetailSource;
33 + readonly commandOutput: (target: {
34 + readonly threadId: ThreadId;
35 + readonly itemId: TurnItemId;
36 + }) => Atom.Atom<AsyncResult.AsyncResult<CommandOutputView, unknown>>;
37 +}
38 +
39 export interface TimelineRowSharedState {
40 citationRequest: AssistantCitationTarget | null;
41 listRef: React.RefObject<LegendListRef | null>;
@@ -40,13 +56,21 @@ export interface TimelineRowSharedState {
56 findActive: boolean;
57 onImageExpand: (preview: ExpandedImagePreview) => void;
58 displayThreadKey?: string;
43 - onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
59 + /** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */
60 + onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined;
61 + /**
62 + * Draws a published HTML visual. Unset, the row loads it from the environment; the guest page
63 + * loads it through its own route.
64 + */
65 + renderHtmlRender: ((row: Extract<TimelineRow, { kind: "html-render" }>) => ReactNode) | undefined;
66 + /** Unset, expanded rows read detail and command output from the environment. */
67 + turnItemSource: TurnItemSource | undefined;
68 onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
69 workflowOpening: WorkflowOpening | null;
46 - onForkFromRun: (input: {
47 - readonly sourceThreadId: ThreadId;
48 - readonly runId: RunId;
49 - }) => Promise<void>;
70 + /** Absent hides "Fork from this response", as in the guest view. */
71 + onForkFromRun:
72 + | ((input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => Promise<void>)
73 + | undefined;
74 onRollbackCheckpoint: (input: {
75 readonly checkpointId: string;
76 readonly scopeId: string;
apps/web/src/components/guest/GuestHtmlRender.tsx new
+93
@@ -0,0 +1,93 @@
1 +import { GUEST_RENDER_ROUTE, GUEST_SHARE_PARAM } from "@t3tools/contracts";
2 +import {
3 + type HtmlRenderReference,
4 + HTML_RENDER_COLUMN_WIDTH,
5 + htmlRenderFrameHeight,
6 + htmlRenderResult,
7 + htmlRenderThemeFragment,
8 + htmlRenderThemeMessage,
9 + readHtmlRenderContentHeight,
10 + readHtmlRenderLinkRequest,
11 +} from "@t3tools/shared/htmlRender";
12 +import { useEffect, useLayoutEffect, useRef, useState } from "react";
13 +
14 +import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
15 +import { observeResize } from "~/lib/observeResize";
16 +
17 +/**
18 + * A visual the agent published, as the guest sees it. The server sends it with a sandbox CSP and
19 + * the frame is sandboxed too, so the page runs scripts in an opaque origin. It can size itself
20 + * and ask to open a web link; it cannot reach the guest's session.
21 + */
22 +export function GuestHtmlRender({
23 + itemId,
24 + reference,
25 + shareId,
26 +}: {
27 + readonly itemId: string;
28 + readonly reference: HtmlRenderReference;
29 + readonly shareId: string;
30 +}) {
31 + const theme = useHtmlRenderTheme();
32 + const boxRef = useRef<HTMLDivElement>(null);
33 + const frameRef = useRef<HTMLIFrameElement>(null);
34 + const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);
35 + const [contentHeight, setContentHeight] = useState<number>();
36 + // The theme rides in the fragment for the first paint; later changes are posted.
37 + const [src] = useState(
38 + () =>
39 + `${GUEST_RENDER_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}${htmlRenderThemeFragment(theme)}`,
40 + );
41 + useLayoutEffect(() => {
42 + const box = boxRef.current;
43 + if (!box) return;
44 + setWidth(box.clientWidth);
45 + return observeResize(box, ([entry]) => {
46 + if (entry) setWidth(entry.contentRect.width);
47 + });
48 + }, []);
49 + useEffect(() => {
50 + frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
51 + }, [theme]);
52 + useEffect(() => {
53 + const onMessage = (event: MessageEvent) => {
54 + const frame = frameRef.current;
55 + if (frame === null || event.source !== frame.contentWindow) return;
56 + const height = readHtmlRenderContentHeight(event.data);
57 + if (height !== undefined) {
58 + setContentHeight(height);
59 + return;
60 + }
61 + // Only while the reader is using this frame, so a page cannot open links on its own.
62 + const link = readHtmlRenderLinkRequest(event.data);
63 + if (
64 + link === undefined ||
65 + document.activeElement !== frame ||
66 + navigator.userActivation?.isActive === false
67 + ) {
68 + return;
69 + }
70 + window.open(link.url, "_blank", "noopener,noreferrer");
71 + frame.contentWindow?.postMessage(htmlRenderResult(link.id), "*");
72 + };
73 + window.addEventListener("message", onMessage);
74 + return () => window.removeEventListener("message", onMessage);
75 + }, []);
76 +
77 + return (
78 + <div
79 + ref={boxRef}
80 + style={{
81 + height: htmlRenderFrameHeight(reference, width, contentHeight),
82 + }}
83 + >
84 + <iframe
85 + ref={frameRef}
86 + src={src}
87 + title={reference.title}
88 + sandbox="allow-scripts allow-forms allow-popups allow-downloads"
89 + className="block size-full rounded-lg border border-border"
90 + />
91 + </div>
92 + );
93 +}
apps/web/src/components/guest/GuestPage.browser.test.tsx new
+400
@@ -0,0 +1,400 @@
1 +import {
2 + EventId,
3 + GUEST_COMMAND_OUTPUT_ROUTE,
4 + GUEST_RENDER_ROUTE,
5 + GuestMessageId,
6 + GuestShareId,
7 + GuestStreamEvent,
8 + MessageId,
9 + ProviderDriverKind,
10 + RunId,
11 + TurnItemId,
12 + type GuestShareView,
13 + type OrchestrationV2Run,
14 + type OrchestrationV2TurnItem,
15 +} from "@t3tools/contracts";
16 +import * as DateTime from "effect/DateTime";
17 +import * as Schema from "effect/Schema";
18 +import { describe, expect, it, vi } from "vite-plus/test";
19 +import { userEvent } from "vite-plus/test/browser";
20 +
21 +import "~/index.css";
22 +
23 +import { render } from "../../../test/render";
24 +import { makeThreadProjectionFixture } from "../../test-fixtures";
25 +import { GuestPage } from "./GuestPage";
26 +
27 +const SHARE_ID = "share-1";
28 +const encodeEvent = Schema.encodeSync(Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)));
29 +
30 +const fixture = makeThreadProjectionFixture();
31 +const threadId = fixture.thread.id;
32 +const started = DateTime.makeUnsafe("2026-10-23T10:00:00.000Z");
33 +const finished = DateTime.makeUnsafe("2026-10-23T10:00:05.000Z");
34 +
35 +const run = (id: string, ordinal: number, status: OrchestrationV2Run["status"]) =>
36 + ({
37 + id: RunId.make(id),
38 + threadId,
39 + ordinal,
40 + providerInstanceId: fixture.thread.providerInstanceId,
41 + modelSelection: fixture.thread.modelSelection,
42 + providerThreadId: null,
43 + userMessageId: MessageId.make(`user-${id}`),
44 + rootNodeId: null,
45 + activeAttemptId: null,
46 + status,
47 + requestedAt: started,
48 + startedAt: started,
49 + completedAt: status === "running" ? null : finished,
50 + checkpointId: null,
51 + contextHandoffId: null,
52 + }) satisfies OrchestrationV2Run;
53 +
54 +const itemBase = (id: string, ordinal: number, runId = "run-1") => ({
55 + id: TurnItemId.make(id),
56 + threadId,
57 + runId: RunId.make(runId),
58 + nodeId: null,
59 + providerThreadId: null,
60 + providerTurnId: null,
61 + nativeItemRef: null,
62 + parentItemId: null,
63 + ordinal,
64 + status: "completed" as const,
65 + title: null,
66 + startedAt: started,
67 + completedAt: finished,
68 + updatedAt: finished,
69 +});
70 +
71 +const reply = (id: string, ordinal: number, text: string, runId?: string) =>
72 + ({
73 + ...itemBase(id, ordinal, runId),
74 + type: "assistant_message",
75 + messageId: MessageId.make(id),
76 + text,
77 + streaming: false,
78 + }) satisfies OrchestrationV2TurnItem;
79 +
80 +const items: ReadonlyArray<OrchestrationV2TurnItem> = [
81 + {
82 + ...itemBase("user", 0),
83 + type: "user_message",
84 + createdBy: "user",
85 + creationSource: "web",
86 + messageId: MessageId.make("user"),
87 + inputIntent: "turn_start",
88 + text: "Run the checks",
89 + attachments: [],
90 + },
91 + // As the owner's stream sends it: the output loads when the row expands.
92 + {
93 + ...itemBase("command", 1),
94 + type: "command_execution",
95 + input: "vp run check:changed",
96 + outputOmitted: true,
97 + exitCode: 0,
98 + },
99 + {
100 + ...itemBase("visual", 2),
101 + type: "dynamic_tool",
102 + toolName: "mcp__t3-code__html_render",
103 + input: null,
104 + output: { htmlRender: { attachmentId: "thread-a-1", title: "Chart", height: 200 } },
105 + },
106 + reply("reply", 3, "All checks pass."),
107 +];
108 +
109 +const view: GuestShareView = {
110 + shareId: GuestShareId.make(SHARE_ID),
111 + title: "Fix login",
112 + guestName: "Sam",
113 + expiresAt: "2026-10-24T10:00:00.000Z",
114 + messages: [],
115 + model: { driver: ProviderDriverKind.make("codex"), name: "GPT-5.4", shortName: "5.4" },
116 +};
117 +
118 +/** The stream's opening, as the server sends it: the share, then the owner's snapshot. */
119 +const opening = (
120 + runs: ReadonlyArray<OrchestrationV2Run>,
121 + turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
122 +): ReadonlyArray<GuestStreamEvent> => [
123 + { type: "view", view },
124 + {
125 + type: "thread",
126 + item: {
127 + kind: "snapshot",
128 + snapshotSequence: 1,
129 + projection: {
130 + ...fixture,
131 + runs,
132 + turnItems,
133 + visibleTurnItems: turnItems.map((item, position) => ({
134 + position,
135 + visibility: "local",
136 + sourceThreadId: threadId,
137 + sourceItemId: item.id,
138 + item,
139 + })),
140 + },
141 + },
142 + },
143 +];
144 +
145 +/** One of the owner's thread events, numbered after the snapshot. */
146 +const threadEvent = (
147 + sequence: number,
148 + event:
149 + | { readonly type: "turn-item.updated"; readonly payload: OrchestrationV2TurnItem }
150 + | { readonly type: "run.updated"; readonly payload: OrchestrationV2Run },
151 +): GuestStreamEvent => {
152 + const common = {
153 + id: EventId.make(`event-${sequence}`),
154 + threadId,
155 + providerInstanceId: fixture.thread.providerInstanceId,
156 + occurredAt: finished,
157 + };
158 + return {
159 + type: "thread",
160 + item: {
161 + kind: "event",
162 + sequence,
163 + event:
164 + event.type === "run.updated"
165 + ? { ...common, type: "run.updated", runId: event.payload.id, payload: event.payload }
166 + : {
167 + ...common,
168 + type: "turn-item.updated",
169 + driver: ProviderDriverKind.make("codex"),
170 + payload: event.payload,
171 + },
172 + },
173 + };
174 +};
175 +
176 +const finalOutput = JSON.stringify({
177 + kind: "replace",
178 + text: "4 files checked\n",
179 + truncated: false,
180 + running: false,
181 +});
182 +
183 +/**
184 + * Delivers the opening as soon as the page subscribes, or a command's final output. `sources`
185 + * collects the streams, so a test can send more events.
186 + */
187 +function fakeEventSource(
188 + events: ReadonlyArray<GuestStreamEvent>,
189 + sources: Array<EventTarget> = [],
190 +) {
191 + return class extends EventTarget {
192 + static readonly CLOSED = 2;
193 + readyState = 1;
194 + constructor(readonly url: string) {
195 + super();
196 + sources.push(this);
197 + const frames = url.startsWith(GUEST_COMMAND_OUTPUT_ROUTE)
198 + ? [finalOutput]
199 + : events.map((event) => encodeEvent(event));
200 + queueMicrotask(() => {
201 + for (const data of frames) this.dispatchEvent(new MessageEvent("message", { data }));
202 + });
203 + }
204 + close() {
205 + this.readyState = 2;
206 + }
207 + };
208 +}
209 +
210 +function visit(path: string): Disposable {
211 + const previous = `${window.location.pathname}${window.location.search}`;
212 + window.history.replaceState(window.history.state, "", path);
213 + return {
214 + [Symbol.dispose]: () => window.history.replaceState(window.history.state, "", previous),
215 + };
216 +}
217 +
218 +describe("GuestPage", () => {
219 + it("shows the shared thread in the real timeline without opening an environment connection", async () => {
220 + using _page = visit(`/guest?share=${SHARE_ID}`);
221 + using _session = vi
222 + .spyOn(window, "fetch")
223 + .mockImplementation(async () => new Response(null, { status: 204 }));
224 + using _stream = vi
225 + .spyOn(window, "EventSource")
226 + .mockImplementation(fakeEventSource(opening([run("run-1", 1, "completed")], items)) as never);
227 + using socket = vi.spyOn(window, "WebSocket");
228 + const container = document.createElement("div");
229 + container.style.cssText = "height: 900px; width: 900px; display: flex; flex-direction: column;";
230 + await using screen = await render(<GuestPage />, { container });
231 +
232 + await expect.element(screen.getByText("All checks pass.")).toBeVisible();
233 + // A finished turn folds its work, as it does for the owner; the command is inside.
234 + await userEvent.click(screen.getByRole("button", { name: /Worked for/ }));
235 + await expect.element(screen.getByText("vp run check:changed")).toBeVisible();
236 + // Expanding the command shows its output, read through the guest route.
237 + await userEvent.click(screen.getByText("vp run check:changed"));
238 + await expect.element(screen.getByText("4 files checked")).toBeVisible();
239 + await expect
240 + .element(screen.getByTitle("Chart"))
241 + .toHaveAttribute(
242 + "src",
243 + expect.stringContaining(`${GUEST_RENDER_ROUTE}?share=${SHARE_ID}&item=visual`),
244 + );
245 + // Guests cannot act on the thread, so no control offers to.
246 + expect(screen.container.querySelector('[aria-label="Fork from this response"]')).toBeNull();
247 + expect(socket).not.toHaveBeenCalled();
248 + // The composer names the thread's model, as the owner's does, with nothing to pick.
249 + await expect.element(screen.getByLabelText("Model: 5.4")).toBeVisible();
250 + });
251 +
252 + it("sends attached files with the message, as form data", async () => {
253 + using _page = visit(`/guest?share=${SHARE_ID}`);
254 + using fetchSpy = vi
255 + .spyOn(window, "fetch")
256 + .mockImplementation(async () => new Response(null, { status: 204 }));
257 + using _stream = vi
258 + .spyOn(window, "EventSource")
259 + .mockImplementation(fakeEventSource(opening([run("run-1", 1, "completed")], items)) as never);
260 + await using screen = await render(<GuestPage />);
261 +
262 + await expect.element(screen.getByLabelText("Attach files")).toBeVisible();
263 + const notes = new File(["hello"], "notes.txt", { type: "text/plain" });
264 + await userEvent.upload(screen.getByLabelText("Files to attach"), notes);
265 + await expect.element(screen.getByText("notes.txt")).toBeVisible();
266 + await userEvent.click(screen.getByRole("button", { name: "Send" }));
267 + await vi.waitFor(() =>
268 + expect(fetchSpy).toHaveBeenCalledWith(
269 + `/api/guest/messages?share=${SHARE_ID}`,
270 + expect.objectContaining({ method: "POST" }),
271 + ),
272 + );
273 + const body = fetchSpy.mock.calls.find(
274 + ([url]) => url === `/api/guest/messages?share=${SHARE_ID}`,
275 + )?.[1]?.body;
276 + expect(body).toBeInstanceOf(FormData);
277 + const form = body as FormData;
278 + expect(form.get("shareId")).toBe(SHARE_ID);
279 + expect(form.get("text")).toBe("");
280 + expect((form.get("file") as File).name).toBe("notes.txt");
281 + // Sent files leave the composer.
282 + await expect.element(screen.getByText("notes.txt")).not.toBeInTheDocument();
283 + });
284 +
285 + it("follows the end as replies stream, and shows the guest's own message even after they scrolled up", async () => {
286 + using _page = visit(`/guest?share=${SHARE_ID}`);
287 + using _session = vi
288 + .spyOn(window, "fetch")
289 + .mockImplementation(async () => new Response(null, { status: 204 }));
290 + const sources: Array<EventTarget> = [];
291 + // Enough turns that the thread overflows the page.
292 + const longItems = Array.from({ length: 12 }, (_, index) =>
293 + reply(
294 + `reply-${index}`,
295 + index,
296 + `Reply ${index}\n\n${"A long paragraph about the change. ".repeat(20)}`,
297 + ),
298 + );
299 + using _stream = vi
300 + .spyOn(window, "EventSource")
301 + .mockImplementation(
302 + fakeEventSource(opening([run("run-1", 1, "running")], longItems), sources) as never,
303 + );
304 + const send = (event: GuestStreamEvent) =>
305 + sources.at(-1)!.dispatchEvent(new MessageEvent("message", { data: encodeEvent(event) }));
306 + const container = document.createElement("div");
307 + container.style.cssText = "height: 600px; width: 900px; display: flex; flex-direction: column;";
308 + await using screen = await render(<GuestPage />, { container });
309 + await expect.element(screen.getByText("Reply 11")).toBeInTheDocument();
310 + const scroller = () =>
311 + screen.container.querySelector<HTMLElement>(".messages-timeline-scroll")!;
312 + const expectAtEnd = () =>
313 + vi.waitFor(() => {
314 + const node = scroller();
315 + expect(node.scrollHeight - node.scrollTop - node.clientHeight).toBeLessThan(2);
316 + });
317 + await expectAtEnd();
318 +
319 + // A new reply streams in at the end.
320 + send(
321 + threadEvent(2, {
322 + type: "turn-item.updated",
323 + payload: {
324 + ...reply(
325 + "reply-new",
326 + 20,
327 + `Newest reply\n\n${"More words as the agent writes. ".repeat(30)}`,
328 + ),
329 + streaming: true,
330 + },
331 + }),
332 + );
333 + await expect.element(screen.getByText("Newest reply")).toBeInTheDocument();
334 + await expectAtEnd();
335 +
336 + // The guest reads back a little, then sends: their message comes into view anyway, as the
337 + // owner's own send does.
338 + const node = scroller();
339 + node.dispatchEvent(new WheelEvent("wheel", { deltaY: -400, bubbles: true }));
340 + node.scrollTop = node.scrollTop - 400;
341 + node.dispatchEvent(new Event("scroll"));
342 + await expect.element(screen.getByRole("button", { name: /scroll to/i })).toBeVisible();
343 +
344 + // The guest's own message waits at the end for the owner.
345 + const waiting = {
346 + id: GuestMessageId.make("guest-1"),
347 + text: "Can you also check the logout flow?",
348 + status: "pending" as const,
349 + submittedAt: "2026-10-23T10:01:00.000Z",
350 + };
351 + send({ type: "view", view: { ...view, messages: [waiting] } });
352 + await expect.element(screen.getByText(waiting.text)).toBeInTheDocument();
353 + await expectAtEnd();
354 +
355 + // The owner sends it: the run ends, the message becomes a row, and a new run's reply grows.
356 + const sent = { ...waiting, status: "sent" as const };
357 + send(threadEvent(3, { type: "run.updated", payload: run("run-1", 1, "completed") }));
358 + send({ type: "view", view: { ...view, messages: [sent] } });
359 + send(threadEvent(4, { type: "run.updated", payload: run("run-2", 2, "running") }));
360 + send(
361 + threadEvent(5, {
362 + type: "turn-item.updated",
363 + payload: {
364 + ...itemBase("guest-row", 30, "run-2"),
365 + type: "user_message",
366 + createdBy: "user",
367 + creationSource: "web",
368 + messageId: MessageId.make("guest-row"),
369 + inputIntent: "turn_start",
370 + text: `Message from guest Sam, sent by the owner: ${sent.text}`,
371 + attachments: [],
372 + context: {
373 + version: 1,
374 + guest: { guestMessageId: sent.id, name: "Sam", text: sent.text },
375 + records: [],
376 + },
377 + },
378 + }),
379 + );
380 + await expectAtEnd();
381 + for (const [index, words] of [10, 40, 120].entries()) {
382 + send(
383 + threadEvent(6 + index, {
384 + type: "turn-item.updated",
385 + payload: {
386 + ...reply(
387 + "logout-reply",
388 + 31,
389 + `Logout reply\n\n${"Checking the logout flow now. ".repeat(words)}`,
390 + "run-2",
391 + ),
392 + streaming: true,
393 + },
394 + }),
395 + );
396 + await expectAtEnd();
397 + await expect.element(screen.getByText("Logout reply")).toBeInTheDocument();
398 + }
399 + });
400 +});
apps/web/src/components/guest/GuestPage.tsx new
+763
@@ -0,0 +1,763 @@
1 +import {
2 + EnvironmentId,
3 + GUEST_MESSAGE_MAX_LENGTH,
4 + GUEST_NAME_MAX_LENGTH,
5 + GUEST_ROUTE_PREFIX,
6 + GUEST_SHARE_PARAM,
7 + GuestMessageId,
8 + type GuestRedeemRequest,
9 + type GuestShareView,
10 + type GuestThreadModel,
11 + type OrchestrationV2ThreadProjection,
12 + type ThreadGuestMessage,
13 + type ThreadGuestMessageStatus,
14 +} from "@t3tools/contracts";
15 +import type { LegendListRef } from "@legendapp/list/react";
16 +import * as Option from "effect/Option";
17 +import * as Schema from "effect/Schema";
18 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
19 +import {
20 + deriveRunlessWorkStartedAt,
21 + deriveThreadActivityRun,
22 + deriveThreadStructureRuntime,
23 +} from "@t3tools/client-runtime/state/thread-execution";
24 +import { createQuestionHistoryProjector } from "@t3tools/client-runtime/state/thread-requests";
25 +import { ArrowUpIcon, PaperclipIcon, XIcon } from "lucide-react";
26 +import {
27 + createRef,
28 + useEffect,
29 + useReducer,
30 + useRef,
31 + useState,
32 + type ClipboardEvent,
33 + type FormEvent,
34 + type KeyboardEvent,
35 +} from "react";
36 +
37 +import { useIncrementalTimelineEntries } from "~/hooks/useIncrementalTimelineEntries";
38 +import { useNowMinute } from "~/hooks/useNowMinute";
39 +import { useStableCallback } from "~/hooks/useStableCallback";
40 +import { useTheme } from "~/hooks/useTheme";
41 +import { observeResize } from "~/lib/observeResize";
42 +import { cn } from "~/lib/utils";
43 +import { deriveActiveWorkStartedAt, derivePhase } from "~/session-logic";
44 +import type { ChatComposerHandle } from "../chat/ChatComposer";
45 +import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl";
46 +import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview";
47 +import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";
48 +import { PierreEntryIcon } from "../chat/PierreEntryIcon";
49 +import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";
50 +import { MessagesTimeline } from "../chat/MessagesTimeline";
51 +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
52 +import { getTriggerDisplayModelName } from "../chat/providerIconUtils";
53 +import { ScrollToEndButton } from "../chat/TimelineOverlays";
54 +import type { TimelineRow } from "../chat/timelineRowContext";
55 +import { useTimelineFollow } from "../chat/useTimelineFollow";
56 +import { GuestHtmlRender } from "./GuestHtmlRender";
57 +import { Button } from "../ui/button";
58 +import { Input } from "../ui/input";
59 +import {
60 + applyGuestStreamEvent,
61 + formatGuestExpiry,
62 + guestAttachmentUrl,
63 + createGuestAttachmentUrls,
64 + guestFilesProblem,
65 + initialGuestStreamState,
66 + inviteShareId,
67 + type GuestStreamState,
68 + parseGuestStreamEvent,
69 + unplacedGuestMessages,
70 +} from "./guestStream.logic";
71 +import { guestTurnItemSource } from "./guestTurnItemSource";
72 +
73 +interface GuestEntry {
74 + /** Unspent invite from the URL hash, if this load came from a link. */
75 + readonly credential: string | null;
76 + readonly shareId: string | null;
77 +}
78 +
79 +let capturedEntry: GuestEntry | null = null;
80 +
81 +// A reload keeps the tab's session, so it keeps which messages still wait for a row too.
82 +const AWAITING_ROWS_KEY = "t3:guest-awaiting-rows";
83 +const AWAITING_ROWS_LIMIT = 50;
84 +
85 +function readAwaitingRowIds(): ReadonlySet<GuestMessageId> {
86 + try {
87 + const stored: unknown = JSON.parse(sessionStorage.getItem(AWAITING_ROWS_KEY) ?? "[]");
88 + return new Set(
89 + Array.isArray(stored)
90 + ? stored.filter((id) => typeof id === "string").map((id) => GuestMessageId.make(id))
91 + : [],
92 + );
93 + } catch {
94 + return new Set();
95 + }
96 +}
97 +
98 +function writeAwaitingRowIds(ids: ReadonlySet<GuestMessageId>) {
99 + try {
100 + sessionStorage.setItem(AWAITING_ROWS_KEY, JSON.stringify([...ids].slice(-AWAITING_ROWS_LIMIT)));
101 + } catch {}
102 +}
103 +
104 +/**
105 + * The invite credential travels in the URL hash so it never reaches a server log. It is read
106 + * once and removed from history, so it lives only in memory. Opening the page never redeems it:
107 + * only submitting a name does, so a reload before that leaves the link usable.
108 + */
109 +function takeGuestEntry(): GuestEntry {
110 + if (capturedEntry === null) {
111 + // A malformed fragment is an invalid link, not a crash.
112 + let credential = "";
113 + try {
114 + credential = decodeURIComponent(window.location.hash.slice(1)).trim();
115 + } catch {}
116 + const shareId =
117 + credential !== ""
118 + ? inviteShareId(credential)
119 + : new URLSearchParams(window.location.search).get(GUEST_SHARE_PARAM);
120 + // The share stays in the URL, so a reload or bookmark finds this browser's session for it.
121 + window.history.replaceState(
122 + window.history.state,
123 + "",
124 + shareId === null
125 + ? window.location.pathname
126 + : `${window.location.pathname}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
127 + );
128 + capturedEntry = { credential: credential === "" ? null : credential, shareId };
129 + }
130 + return capturedEntry;
131 +}
132 +
133 +const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({ message: Schema.String }));
134 +
135 +/** Resolves to null on success, or to a message the guest can read. */
136 +async function postGuest(
137 + path: "redeem" | `messages?${string}`,
138 + body: typeof GuestRedeemRequest.Encoded | FormData,
139 +): Promise<string | null> {
140 + try {
141 + const response = await fetch(
142 + `${GUEST_ROUTE_PREFIX}/${path}`,
143 + body instanceof FormData
144 + ? { method: "POST", body }
145 + : {
146 + method: "POST",
147 + headers: { "content-type": "application/json" },
148 + body: JSON.stringify(body),
149 + },
150 + );
151 + if (response.ok) return null;
152 + const json: unknown = await response.json().catch(() => null);
153 + return Option.match(decodeErrorBody(json), {
154 + onNone: () => "Something went wrong. Try again.",
155 + onSome: ({ message }) => message,
156 + });
157 + } catch {
158 + return "Could not reach the server.";
159 + }
160 +}
161 +
162 +const STATUS_LABEL: Record<ThreadGuestMessageStatus, string> = {
163 + pending: "Waiting for approval",
164 + sent: "Sent",
165 + dismissed: "Not sent",
166 +};
167 +
168 +/** Same column as the owner's timeline, so both views wrap text at the same width. */
169 +const LANE = "chat-content-lane px-4";
170 +
171 +type GuestAccess = "checking" | "session" | "name" | "none";
172 +
173 +export function GuestPage() {
174 + const [{ credential, shareId }] = useState(takeGuestEntry);
175 + // A browser that already joined this share goes straight back in, even from the spent link.
176 + // Sessions are per share, so one for another link never stands in for this one.
177 + const [access, setAccess] = useState<GuestAccess>(shareId === null ? "none" : "checking");
178 + useEffect(() => {
179 + if (shareId === null) return;
180 + let live = true;
181 + void fetch(`${GUEST_ROUTE_PREFIX}/session?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`)
182 + .then(
183 + (response): GuestAccess =>
184 + response.ok ? "session" : credential !== null ? "name" : "none",
185 + // Offline: an invite still needs the name form; without one, the stream reports what
186 + // it finds once the network is back.
187 + (): GuestAccess => (credential !== null ? "name" : "session"),
188 + )
189 + .then((next) => {
190 + if (live) setAccess(next);
191 + });
192 + return () => {
193 + live = false;
194 + };
195 + }, [credential, shareId]);
196 + // Pasting another guest link into this tab changes only the hash, which does not reload the
197 + // page; reload so the new invite is read instead of the one already captured.
198 + useEffect(() => {
199 + const onHashChange = () => {
200 + if (window.location.hash !== "") window.location.reload();
201 + };
202 + window.addEventListener("hashchange", onHashChange);
203 + return () => window.removeEventListener("hashchange", onHashChange);
204 + }, []);
205 +
206 + return (
207 + <div className="flex h-dvh flex-col bg-background text-foreground">
208 + {access === "checking" ? (
209 + <Notice title="Connecting..." />
210 + ) : access === "name" && credential !== null ? (
211 + <NameForm
212 + credential={credential}
213 + onJoined={() => {
214 + // The invite is spent; a remount must open the session, not the name form again.
215 + capturedEntry = { credential: null, shareId };
216 + setAccess("session");
217 + }}
218 + />
219 + ) : access === "session" && shareId !== null ? (
220 + <GuestSession shareId={shareId} />
221 + ) : (
222 + <Notice
223 + title="This link has ended or is not valid"
224 + detail="Ask the owner for a new link. Each link works in one browser."
225 + />
226 + )}
227 + </div>
228 + );
229 +}
230 +
231 +function GuestSession({ shareId }: { readonly shareId: string }) {
232 + const [stream, dispatch] = useReducer(applyGuestStreamEvent, null, () => ({
233 + ...initialGuestStreamState,
234 + awaitingRowIds: readAwaitingRowIds(),
235 + }));
236 + useEffect(() => writeAwaitingRowIds(stream.awaitingRowIds), [stream.awaitingRowIds]);
237 + // EventSource closes for good only on a non-200 response, which the guest routes send for a
238 + // missing, invalid, or ended session. Network drops reconnect on their own.
239 + const [rejected, setRejected] = useState(false);
240 +
241 + useEffect(() => {
242 + if (stream.view) document.title = stream.view.title;
243 + }, [stream.view]);
244 +
245 + useEffect(() => {
246 + const source = new EventSource(
247 + `${GUEST_ROUTE_PREFIX}/stream?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
248 + );
249 + source.addEventListener("message", (message) => {
250 + const event = parseGuestStreamEvent(message.data);
251 + if (event === null) return;
252 + dispatch(event);
253 + if (event.type === "ended") source.close();
254 + });
255 + source.addEventListener("error", () => {
256 + if (source.readyState === EventSource.CLOSED) setRejected(true);
257 + });
258 + return () => source.close();
259 + }, [shareId]);
260 +
261 + if (stream.ended || (rejected && stream.view !== null)) {
262 + return <Notice title="This link has ended" detail="The owner stopped sharing this thread." />;
263 + }
264 + if (stream.view !== null) {
265 + if (stream.projection === null) return <Notice title="Connecting..." />;
266 + return (
267 + <GuestThread
268 + view={stream.view}
269 + projection={stream.projection}
270 + awaitingRowIds={stream.awaitingRowIds}
271 + />
272 + );
273 + }
274 + if (!rejected) return <Notice title="Connecting..." />;
275 + return (
276 + <Notice
277 + title="This link has ended or is not valid"
278 + detail="Ask the owner for a new link. Each link works in one browser."
279 + />
280 + );
281 +}
282 +
283 +function Notice({ title, detail }: { readonly title: string; readonly detail?: string }) {
284 + return (
285 + <div className="m-auto flex max-w-sm flex-col gap-1 p-6 text-center">
286 + <p className="text-sm font-medium">{title}</p>
287 + {detail ? <p className="text-xs text-muted-foreground">{detail}</p> : null}
288 + </div>
289 + );
290 +}
291 +
292 +function NameForm({
293 + credential,
294 + onJoined,
295 +}: {
296 + readonly credential: string;
297 + readonly onJoined: () => void;
298 +}) {
299 + const [name, setName] = useState("");
300 + const [submitting, setSubmitting] = useState(false);
301 + const [error, setError] = useState<string | null>(null);
302 + const submit = async (event: FormEvent) => {
303 + event.preventDefault();
304 + const trimmed = name.trim();
305 + if (trimmed === "" || submitting) return;
306 + setSubmitting(true);
307 + const failure = await postGuest("redeem", { credential, name: trimmed });
308 + setSubmitting(false);
309 + if (failure === null) onJoined();
310 + else setError(failure);
311 + };
312 + return (
313 + <form className="m-auto flex w-full max-w-xs flex-col gap-3 p-6" onSubmit={submit}>
314 + <h1 className="text-base font-medium">Join a shared thread</h1>
315 + <label className="flex flex-col gap-1.5 text-sm" htmlFor="guest-name">
316 + Your name
317 + <Input
318 + id="guest-name"
319 + autoFocus
320 + autoComplete="name"
321 + maxLength={GUEST_NAME_MAX_LENGTH}
322 + value={name}
323 + onChange={(event) => setName(event.target.value)}
324 + />
325 + </label>
326 + {error !== null ? (
327 + <p role="alert" className="text-sm text-destructive">
328 + {error}
329 + </p>
330 + ) : null}
331 + <Button type="submit" disabled={submitting || name.trim() === ""}>
332 + Join
333 + </Button>
334 + <p className="text-xs text-muted-foreground">
335 + The owner sees your name and approves each message before the agent gets it.
336 + </p>
337 + </form>
338 + );
339 +}
340 +
341 +// The timeline needs an environment id to key its rows. Nothing behind it loads on this page;
342 +// see isGuestPage.
343 +const GUEST_ENVIRONMENT_ID = EnvironmentId.make("guest");
344 +const NO_COMPOSER = createRef<ChatComposerHandle>();
345 +const NO_TURN_DIFFS: ReadonlyArray<never> = [];
346 +const NO_OPTIMISTIC_MESSAGES: ReadonlyArray<never> = [];
347 +const ignore = () => {};
348 +
349 +/**
350 + * The owner's timeline, read-only: every action that would reach the owner's machine (fork,
351 + * revert, diffs, files, other threads, shell) is left out, so its control does not render.
352 + */
353 +function GuestThread({
354 + view: { shareId, title, expiresAt, messages, model },
355 + projection,
356 + awaitingRowIds,
357 +}: {
358 + readonly view: GuestShareView;
359 + readonly projection: OrchestrationV2ThreadProjection;
360 + readonly awaitingRowIds: GuestStreamState["awaitingRowIds"];
361 +}) {
362 + // No ":" so the timeline finds no environment thread behind the key.
363 + const threadKey = `guest-${shareId}`;
364 + const listRef = useRef<LegendListRef | null>(null);
365 + const { resolvedTheme } = useTheme();
366 + // The rest is what ChatView derives from the same projection.
367 + const [projectQuestionHistory] = useState(() => createQuestionHistoryProjector());
368 + const items = projectQuestionHistory(projection);
369 + // Files load through the guest route.
370 + const [attachmentUrls] = useState(() => createGuestAttachmentUrls(shareId));
371 + // Expanded rows read detail and command output through the guest routes.
372 + const [turnItemSource] = useState(() => guestTurnItemSource(shareId));
373 + const attachmentUrlById = attachmentUrls(items);
374 + const entries = useIncrementalTimelineEntries(threadKey, {
375 + visibleTurnItems: items,
376 + optimisticMessages: NO_OPTIMISTIC_MESSAGES,
377 + attachmentUrlById,
378 + attempts: projection.attempts,
379 + nodes: projection.nodes,
380 + plans: projection.plans,
381 + });
382 + const openFile = useStableCallback((file: { readonly id: string }) =>
383 + openInNewTab(guestAttachmentUrl(shareId, file.id)),
384 + );
385 + const activityRun = deriveThreadActivityRun(projection);
386 + const runtime = deriveThreadStructureRuntime(projection);
387 + const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection);
388 + const isWorking = derivePhase(runtime) === "running" || runlessWorkStartedAt !== null;
389 + const workStartedAt =
390 + deriveActiveWorkStartedAt(activityRun, runtime, null) ?? runlessWorkStartedAt;
391 + const runningRunId = runtime?.activeRunId ?? null;
392 + const follow = useTimelineFollow({
393 + legendListRef: listRef,
394 + composerRef: NO_COMPOSER,
395 + composerOverlayElement: null,
396 + composerTimelineInset: 0,
397 + routeThreadKey: threadKey,
398 + activeThreadKey: threadKey,
399 + activeThreadId: undefined,
400 + // Not a server thread: new turns follow the end instead of anchoring near the top.
401 + isServerThread: false,
402 + serverProjection: null,
403 + threadStatus: "live",
404 + activeActivityRun: activityRun,
405 + activeRunningTurnId: runningRunId,
406 + timelineEntries: entries,
407 + timelineAnchorMessageId: null,
408 + setTimelineAnchor: ignore,
409 + });
410 + const renderHtmlRender = useStableCallback(
411 + (row: Extract<TimelineRow, { kind: "html-render" }>) => (
412 + <GuestHtmlRender itemId={row.id} reference={row.htmlRender} shareId={shareId} />
413 + ),
414 + );
415 + const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds);
416 + // The guest's waiting messages sit in the list footer, which the list does not follow on its
417 + // own (the owner's view does the same in ChatView). A new one is the guest's own send, so it
418 + // comes into view even if they had scrolled up, as the owner's send does. While following, the
419 + // footer stays in view as it grows, such as when its images load.
420 + const unplacedKey = unplaced.map((message) => message.id).join(",");
421 + const previousUnplacedKey = useRef(unplacedKey);
422 + const following = useRef(follow.timelineLiveFollowEnabled);
423 + const scrollToEnd = useStableCallback(follow.scrollToEnd);
424 + useEffect(() => {
425 + following.current = follow.timelineLiveFollowEnabled;
426 + const previous = new Set(previousUnplacedKey.current.split(","));
427 + previousUnplacedKey.current = unplacedKey;
428 + if (unplacedKey.split(",").some((id) => id !== "" && !previous.has(id))) scrollToEnd(true);
429 + }, [follow.timelineLiveFollowEnabled, unplacedKey, scrollToEnd, following, previousUnplacedKey]);
430 + const footerRef = useRef<HTMLOListElement>(null);
431 + const hasFooter = unplaced.length > 0;
432 + useEffect(() => {
433 + const footer = footerRef.current;
434 + if (!hasFooter || footer === null) return;
435 + return observeResize(footer, () => {
436 + if (following.current) scrollToEnd();
437 + });
438 + }, [hasFooter, scrollToEnd, following]);
439 + return (
440 + <>
441 + <header className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5">
442 + <h1 className="min-w-0 flex-1 truncate text-sm font-medium">{title}</h1>
443 + <ExpiryLabel expiresAt={expiresAt} />
444 + </header>
445 + <div className="relative min-h-0 flex-1">
446 + <MessagesTimeline
447 + listRef={listRef}
448 + timelineEntries={entries}
449 + isWorking={isWorking}
450 + activeTurnInProgress={isWorking}
451 + activeTurnStartedAt={workStartedAt}
452 + latestRun={activityRun}
453 + runningRunId={runningRunId}
454 + turnDiffSummaries={NO_TURN_DIFFS}
455 + runs={projection.runs}
456 + routeThreadKey={threadKey}
457 + onOpenThread={ignore}
458 + onRollbackCheckpoint={ignore}
459 + supportsConversationRollback={false}
460 + onRevertToTurnCount={ignore}
461 + isRevertingCheckpoint={false}
462 + onImageExpand={openExpandedImage}
463 + onFileOpen={openFile}
464 + onFileDownload={openFile}
465 + renderHtmlRender={renderHtmlRender}
466 + turnItemSource={turnItemSource}
467 + activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}
468 + markdownCwd={undefined}
469 + resolvedTheme={resolvedTheme}
470 + timestampFormat="locale"
471 + workspaceRoot={undefined}
472 + anchorMessageId={null}
473 + onAnchorReady={ignore}
474 + onAnchorSizeChanged={ignore}
475 + contentInsetEndAdjustment={0}
476 + emptyPlaceholderInset={0}
477 + liveFollowEnabled={follow.timelineLiveFollowEnabled}
478 + onIsAtEndChange={follow.onIsAtEndChangeStable}
479 + onManualNavigation={follow.cancelTimelineLiveFollowForUserNavigationStable}
480 + cancelPositionRestoreRef={follow.cancelPositionRestoreRef}
481 + footer={
482 + unplaced.length === 0 ? null : (
483 + <ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">
484 + {unplaced.map((message) => (
485 + <li key={message.id}>
486 + <UnplacedGuestMessage shareId={shareId} message={message} />
487 + </li>
488 + ))}
489 + </ol>
490 + )
491 + }
492 + />
493 + {follow.showScrollToBottom ? (
494 + <ScrollToEndButton bottom={4} onScrollToEnd={() => follow.scrollToEnd(true)} />
495 + ) : null}
496 + </div>
497 + <div className={cn(LANE, "shrink-0 pb-4")}>
498 + <GuestComposer shareId={shareId} model={model} />
499 + </div>
500 + </>
501 + );
502 +}
503 +
504 +function ExpiryLabel({ expiresAt }: { readonly expiresAt: string }) {
505 + const nowMinute = useNowMinute();
506 + return (
507 + <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
508 + {formatGuestExpiry(expiresAt, Date.parse(`${nowMinute}Z`))}
509 + </span>
510 + );
511 +}
512 +
513 +const BUBBLE =
514 + "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]";
515 +
516 +const openInNewTab = (url: string) => window.open(url, "_blank", "noopener,noreferrer");
517 +/** Guests have no image viewer; the browser shows the picture in its own tab. */
518 +const openExpandedImage = (preview: ExpandedImagePreview) => {
519 + const src = preview.images[preview.index]?.src;
520 + if (src) openInNewTab(src);
521 +};
522 +
523 +/** A guest message the owner has not sent yet, or chose not to send. */
524 +function UnplacedGuestMessage({
525 + shareId,
526 + message,
527 +}: {
528 + readonly shareId: GuestShareView["shareId"];
529 + readonly message: ThreadGuestMessage;
530 +}) {
531 + // A dismissed message's files are deleted, so only their names remain.
532 + const served = message.status !== "dismissed";
533 + const url = (attachment: { readonly id: string }) => guestAttachmentUrl(shareId, attachment.id);
534 + return (
535 + <div className="flex flex-col items-end gap-1">
536 + <GuestMessageName name="You" />
537 + <div
538 + className={cn(
539 + BUBBLE,
540 + guestBubbleClassName(message.status !== "sent"),
541 + message.status === "dismissed" ? "text-muted-foreground" : "text-message-foreground",
542 + )}
543 + >
544 + <GuestMessageAttachments
545 + attachments={message.attachments ?? []}
546 + imageUrl={(attachment) => (served ? url(attachment) : undefined)}
547 + onOpenImage={(attachment) => openInNewTab(url(attachment))}
548 + {...(served ? { fileHref: url } : {})}
549 + />
550 + {message.text ? <span>{message.text}</span> : null}
551 + </div>
552 + <p className="me-1 text-2xs text-muted-foreground">{STATUS_LABEL[message.status]}</p>
553 + </div>
554 + );
555 +}
556 +
557 +/** The thread's model, labeled as the owner's composer labels it, with no way to change it. */
558 +function GuestModelLabel({ model }: { readonly model: GuestThreadModel }) {
559 + const label = getTriggerDisplayModelName({ slug: model.name, ...model });
560 + return (
561 + <ComposerControl
562 + render={<span />}
563 + aria-label={`Model: ${label}`}
564 + className="pointer-events-none min-w-0 shrink"
565 + >
566 + {model.driver === null ? null : (
567 + <ProviderInstanceIcon
568 + driverKind={model.driver}
569 + displayName={label}
570 + className="size-4"
571 + iconClassName="size-4"
572 + />
573 + )}
574 + <span className="min-w-0 truncate" data-chat-provider-model-picker-label="true">
575 + {label}
576 + </span>
577 + </ComposerControl>
578 + );
579 +}
580 +
581 +interface StagedFile {
582 + readonly key: string;
583 + readonly file: File;
584 +}
585 +
586 +/** A staged image's thumbnail; its object URL lives as long as the element. */
587 +function StagedImage({ file }: { readonly file: File }) {
588 + return (
589 + <img
590 + alt={file.name}
591 + className="size-full object-cover"
592 + ref={(image) => {
593 + if (!image) return;
594 + const url = URL.createObjectURL(file);
595 + image.src = url;
596 + return () => URL.revokeObjectURL(url);
597 + }}
598 + />
599 + );
600 +}
601 +
602 +function GuestComposer({
603 + shareId,
604 + model,
605 +}: {
606 + readonly shareId: GuestShareView["shareId"];
607 + readonly model: GuestThreadModel;
608 +}) {
609 + const [text, setText] = useState("");
610 + const [files, setFiles] = useState<ReadonlyArray<StagedFile>>([]);
611 + const [sending, setSending] = useState(false);
612 + const [error, setError] = useState<string | null>(null);
613 + const fileInputRef = useRef<HTMLInputElement>(null);
614 + const nextFileKey = useRef(0);
615 + const { resolvedTheme } = useTheme();
616 + const addFiles = (added: ReadonlyArray<File>) => {
617 + if (added.length === 0) return;
618 + const next = [
619 + ...files,
620 + ...added.map((file) => ({ key: `staged-${nextFileKey.current++}`, file })),
621 + ];
622 + const problem = guestFilesProblem(next.map((staged) => staged.file));
623 + setError(problem);
624 + if (problem === null) setFiles(next);
625 + };
626 + const send = async () => {
627 + const trimmed = text.trim();
628 + if ((trimmed === "" && files.length === 0) || sending) return;
629 + setSending(true);
630 + const sentFiles = files;
631 + const form = new FormData();
632 + form.append("shareId", shareId);
633 + form.append("text", trimmed);
634 + for (const staged of sentFiles) form.append("file", staged.file, staged.file.name);
635 + const failure = await postGuest(
636 + `messages?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
637 + form,
638 + );
639 + setSending(false);
640 + setError(failure);
641 + // Keep anything typed or attached while the request was in flight.
642 + if (failure === null) {
643 + setText((current) => (current.trim() === trimmed ? "" : current));
644 + setFiles((current) => current.filter((staged) => !sentFiles.includes(staged)));
645 + }
646 + };
647 + const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
648 + // Same as the app composer: Enter sends, Shift+Enter adds a line, IME composition is left alone.
649 + if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
650 + event.preventDefault();
651 + void send();
652 + }
653 + };
654 + // As in the app composer: pasted images attach, and other files attach when no text came along.
655 + const onPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
656 + const pasted = Array.from(event.clipboardData.files);
657 + const hasImage = pasted.some((file) => file.type.startsWith("image/"));
658 + if (pasted.length === 0 || (!hasImage && event.clipboardData.getData("text/plain") !== "")) {
659 + return;
660 + }
661 + event.preventDefault();
662 + addFiles(pasted);
663 + };
664 + return (
665 + <form
666 + 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"
667 + onSubmit={(event) => {
668 + event.preventDefault();
669 + void send();
670 + }}
671 + onDragOver={(event) => {
672 + if (event.dataTransfer.types.includes("Files")) event.preventDefault();
673 + }}
674 + onDrop={(event) => {
675 + if (event.dataTransfer.files.length === 0) return;
676 + event.preventDefault();
677 + addFiles(Array.from(event.dataTransfer.files));
678 + }}
679 + >
680 + {files.length > 0 ? (
681 + <ul className="flex flex-wrap gap-2" aria-label="Attached files">
682 + {files.map((staged) => (
683 + <li
684 + key={staged.key}
685 + className="flex h-14 min-w-0 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background/70 pe-1"
686 + >
687 + {staged.file.type.startsWith("image/") ? (
688 + <span className="size-14 shrink-0">
689 + <StagedImage file={staged.file} />
690 + </span>
691 + ) : (
692 + <span className="flex min-w-0 items-center gap-2 ps-2 text-sm">
693 + <PierreEntryIcon pathValue={staged.file.name} kind="file" theme={resolvedTheme} />
694 + <span className="max-w-40 truncate">{staged.file.name}</span>
695 + <span className="shrink-0 text-xs text-muted-foreground">
696 + {formatAttachmentSize(staged.file.size)}
697 + </span>
698 + </span>
699 + )}
700 + <Button
701 + size="icon-xs"
702 + variant="ghost-muted"
703 + aria-label={`Remove ${staged.file.name}`}
704 + onClick={() => {
705 + setError(null);
706 + setFiles((current) => current.filter((candidate) => candidate !== staged));
707 + }}
708 + >
709 + <XIcon />
710 + </Button>
711 + </li>
712 + ))}
713 + </ul>
714 + ) : null}
715 + <textarea
716 + aria-label="Message"
717 + placeholder="Message"
718 + rows={2}
719 + maxLength={GUEST_MESSAGE_MAX_LENGTH}
720 + value={text}
721 + onChange={(event) => setText(event.target.value)}
722 + onKeyDown={onKeyDown}
723 + onPaste={onPaste}
724 + className="max-h-60 min-h-12 w-full resize-none bg-transparent text-sm outline-none field-sizing-content placeholder:text-placeholder"
725 + />
726 + <div className="flex items-center gap-3">
727 + <input
728 + ref={fileInputRef}
729 + type="file"
730 + multiple
731 + hidden
732 + aria-label="Files to attach"
733 + onChange={(event) => {
734 + addFiles(Array.from(event.target.files ?? []));
735 + // The same file can be picked again after it is removed.
736 + event.target.value = "";
737 + }}
738 + />
739 + <ComposerControl aria-label="Attach files" onClick={() => fileInputRef.current?.click()}>
740 + <ComposerControlIcon icon={PaperclipIcon} />
741 + </ComposerControl>
742 + <GuestModelLabel model={model} />
743 + {error !== null ? (
744 + <p role="alert" className="min-w-0 flex-1 text-xs text-destructive">
745 + {error}
746 + </p>
747 + ) : (
748 + <p className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
749 + The owner approves each message
750 + </p>
751 + )}
752 + <button
753 + type="submit"
754 + aria-label="Send"
755 + disabled={sending || (text.trim() === "" && files.length === 0)}
756 + 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"
757 + >
758 + <ArrowUpIcon aria-hidden className="size-4" />
759 + </button>
760 + </div>
761 + </form>
762 + );
763 +}
apps/web/src/components/guest/guestStream.logic.test.ts new
+222
@@ -0,0 +1,222 @@
1 +import {
2 + EventId,
3 + GuestMessageId,
4 + GuestShareId,
5 + MessageId,
6 + ProviderDriverKind,
7 + RunId,
8 + TurnItemId,
9 + type GuestShareView,
10 + type GuestStreamEvent,
11 + type OrchestrationV2TurnItem,
12 + type ThreadGuestMessage,
13 +} from "@t3tools/contracts";
14 +import * as DateTime from "effect/DateTime";
15 +import { describe, expect, it } from "vite-plus/test";
16 +
17 +import { makeThreadProjectionFixture } from "../../test-fixtures";
18 +import {
19 + applyGuestStreamEvent,
20 + formatGuestExpiry,
21 + guestFilesProblem,
22 + initialGuestStreamState,
23 + inviteShareId,
24 + parseGuestStreamEvent,
25 + unplacedGuestMessages,
26 + type GuestStreamState,
27 +} from "./guestStream.logic";
28 +
29 +const view: GuestShareView = {
30 + shareId: GuestShareId.make("share-1"),
31 + title: "Fix login",
32 + guestName: "Sam",
33 + expiresAt: "2026-10-24T00:00:00.000Z",
34 + messages: [],
35 + model: { driver: null, name: "gpt-5.4" },
36 +};
37 +
38 +const projection = makeThreadProjectionFixture();
39 +const now = DateTime.makeUnsafe("2026-10-23T10:00:00.000Z");
40 +
41 +const base = {
42 + threadId: projection.thread.id,
43 + runId: RunId.make("run-1"),
44 + nodeId: null,
45 + providerThreadId: null,
46 + providerTurnId: null,
47 + nativeItemRef: null,
48 + parentItemId: null,
49 + ordinal: 1,
50 + status: "completed",
51 + title: null,
52 + startedAt: now,
53 + completedAt: now,
54 + updatedAt: now,
55 +} as const;
56 +
57 +const reply = (id: string, text: string): OrchestrationV2TurnItem => ({
58 + ...base,
59 + id: TurnItemId.make(id),
60 + type: "assistant_message",
61 + messageId: MessageId.make(id),
62 + text,
63 + streaming: false,
64 +});
65 +
66 +const guestMessageRow = (id: string, guestMessageId: GuestMessageId): OrchestrationV2TurnItem => ({
67 + ...base,
68 + id: TurnItemId.make(id),
69 + type: "user_message",
70 + createdBy: "user",
71 + creationSource: "web",
72 + messageId: MessageId.make(id),
73 + inputIntent: "turn_start",
74 + text: "Why?",
75 + context: { version: 1, records: [], guest: { guestMessageId, name: "Sam", text: "Why?" } },
76 + attachments: [],
77 +});
78 +
79 +const snapshot = (snapshotSequence = 1): GuestStreamEvent => ({
80 + type: "thread",
81 + item: { kind: "snapshot", snapshotSequence, projection },
82 +});
83 +
84 +const itemEvent = (sequence: number, item: OrchestrationV2TurnItem): GuestStreamEvent => ({
85 + type: "thread",
86 + item: {
87 + kind: "event",
88 + sequence,
89 + event: {
90 + id: EventId.make(`event-${sequence}`),
91 + type: "turn-item.updated",
92 + threadId: projection.thread.id,
93 + driver: ProviderDriverKind.make("codex"),
94 + providerInstanceId: projection.thread.providerInstanceId,
95 + occurredAt: now,
96 + payload: item,
97 + },
98 + },
99 +});
100 +
101 +const apply = (events: ReadonlyArray<GuestStreamEvent>, state = initialGuestStreamState) =>
102 + events.reduce<GuestStreamState>(applyGuestStreamEvent, state);
103 +
104 +const itemIds = (state: GuestStreamState) =>
105 + state.projection?.visibleTurnItems.map((row) => row.item.id) ?? [];
106 +
107 +describe("applyGuestStreamEvent", () => {
108 + it("builds the thread from the snapshot and applies each later event once", () => {
109 + const once = apply([{ type: "view", view }, snapshot(1), itemEvent(2, reply("a1", "Hi"))]);
110 + expect(itemIds(once)).toEqual(["a1"]);
111 + // A replayed or older event changes nothing.
112 + expect(apply([itemEvent(2, reply("a1", "Changed"))], once)).toBe(once);
113 + });
114 +
115 + it("replaces the thread on a new snapshot, as after a reconnect", () => {
116 + const before = apply([snapshot(1), itemEvent(2, reply("a1", "Hi")), { type: "ended" }]);
117 + const after = apply([snapshot(1)], { ...before, ended: false });
118 + expect(itemIds(after)).toEqual([]);
119 + });
120 +
121 + it("ends when the view names another link than the page's", () => {
122 + const state = apply([
123 + { type: "view", view },
124 + { type: "view", view: { ...view, shareId: GuestShareId.make("share-2") } },
125 + ]);
126 + expect(state.ended).toBe(true);
127 + expect(state.view?.shareId).toBe(view.shareId);
128 + });
129 +
130 + it("remembers a waiting message across a reconnect until its row arrives", () => {
131 + const waiting = {
132 + id: GuestMessageId.make("m1"),
133 + text: "Why?",
134 + status: "pending" as const,
135 + submittedAt: "2026-10-23T10:00:00.000Z",
136 + };
137 + const sent = { ...waiting, status: "sent" as const };
138 + const queued = apply([
139 + { type: "view", view: { ...view, messages: [waiting] } },
140 + snapshot(1),
141 + { type: "view", view: { ...view, messages: [sent] } },
142 + ]);
143 + expect([...queued.awaitingRowIds]).toEqual([waiting.id]);
144 +
145 + // Once placed, a later snapshot whose window no longer holds the row must not resurrect it.
146 + const placed = apply([itemEvent(2, guestMessageRow("u1", waiting.id)), snapshot(3)], queued);
147 + expect(placed.awaitingRowIds.size).toBe(0);
148 + });
149 +});
150 +
151 +describe("parseGuestStreamEvent", () => {
152 + it("decodes a valid frame and rejects malformed ones", () => {
153 + expect(parseGuestStreamEvent(JSON.stringify({ type: "ended" }))).toEqual({ type: "ended" });
154 + expect(parseGuestStreamEvent("{not json")).toBeNull();
155 + expect(parseGuestStreamEvent(JSON.stringify({ type: "unknown" }))).toBeNull();
156 + });
157 +});
158 +
159 +describe("unplacedGuestMessages", () => {
160 + const message = (id: string, status: ThreadGuestMessage["status"], submittedAt: string) => ({
161 + id: GuestMessageId.make(id),
162 + text: id,
163 + status,
164 + submittedAt,
165 + });
166 +
167 + it("shows pending ones, and resolved ones only if this page saw them waiting", () => {
168 + const messages = [
169 + message("late", "pending", "2026-10-23T10:05:00.000Z"),
170 + message("placed", "sent", "2026-10-23T10:00:00.000Z"),
171 + message("queued", "sent", "2026-10-23T09:59:00.000Z"),
172 + message("dismissed", "dismissed", "2026-10-23T10:01:00.000Z"),
173 + message("old-history", "sent", "2026-10-23T09:00:00.000Z"),
174 + ];
175 + const seen = new Set(
176 + ["placed", "queued", "dismissed", "late"].map((id) => GuestMessageId.make(id)),
177 + );
178 + const items = [
179 + {
180 + position: 0,
181 + visibility: "local" as const,
182 + sourceThreadId: projection.thread.id,
183 + sourceItemId: TurnItemId.make("u1"),
184 + item: guestMessageRow("u1", GuestMessageId.make("placed")),
185 + },
186 + ];
187 + expect(unplacedGuestMessages(messages, items, seen).map((m) => m.id)).toEqual([
188 + "queued",
189 + "dismissed",
190 + "late",
191 + ]);
192 + });
193 +});
194 +
195 +describe("formatGuestExpiry", () => {
196 + const now = Date.parse("2026-10-23T00:00:00.000Z");
197 + it("shows whole hours, then minutes, then expired", () => {
198 + expect(formatGuestExpiry("2026-10-23T23:59:00.000Z", now)).toBe("23h left");
199 + expect(formatGuestExpiry("2026-10-23T00:45:30.000Z", now)).toBe("45m left");
200 + expect(formatGuestExpiry("2026-10-23T00:00:00.000Z", now)).toBe("Expired");
201 + });
202 +});
203 +
204 +describe("inviteShareId", () => {
205 + it("reads the share id before the signature and rejects anything else", () => {
206 + expect(inviteShareId("k3J9xQ2mT8vL5nR1pW7yZa.sig")).toBe("k3J9xQ2mT8vL5nR1pW7yZa");
207 + expect(inviteShareId("no-signature")).toBeNull();
208 + expect(inviteShareId(".sig")).toBeNull();
209 + expect(inviteShareId("")).toBeNull();
210 + });
211 +});
212 +
213 +describe("guestFilesProblem", () => {
214 + const file = (type: string, size = 1) => ({ type, size });
215 + it("takes up to four files and 10 MB, with images in the types the owner's composer takes", () => {
216 + expect(guestFilesProblem([file("image/png"), file("application/pdf"), file("")])).toBeNull();
217 + expect(guestFilesProblem([1, 2, 3, 4, 5].map(() => file("image/png")))).toMatch(/up to 4/);
218 + expect(guestFilesProblem([file("image/png", 10 * 1024 * 1024 + 1)])).toMatch(/10 MB/);
219 + expect(guestFilesProblem([file("image/svg+xml")])).toMatch(/PNG, JPEG, GIF, or WebP/);
220 + expect(guestFilesProblem([file("text/plain", 0)])).toMatch(/cannot be attached/);
221 + });
222 +});
apps/web/src/components/guest/guestStream.logic.ts new
+232
@@ -0,0 +1,232 @@
1 +import {
2 + GUEST_ATTACHMENT_ROUTE,
3 + GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
4 + GUEST_MESSAGE_MAX_ATTACHMENTS,
5 + GUEST_SHARE_PARAM,
6 + GuestStreamEvent,
7 + isProviderSendTurnSupportedImageMimeType,
8 + type GuestMessageId,
9 + type GuestShareView,
10 + type OrchestrationV2ProjectedTurnItem,
11 + type OrchestrationV2ThreadProjection,
12 + type OrchestrationV2TurnItem,
13 + type ThreadGuestMessage,
14 +} from "@t3tools/contracts";
15 +import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";
16 +import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
17 +import * as Option from "effect/Option";
18 +import * as Schema from "effect/Schema";
19 +
20 +export interface GuestStreamState {
21 + readonly view: GuestShareView | null;
22 + /** The thread as the owner's client holds it, built with the same reducer. */
23 + readonly projection: OrchestrationV2ThreadProjection | null;
24 + readonly sequence: number;
25 + /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */
26 + readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null;
27 + readonly ended: boolean;
28 + /**
29 + * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a
30 + * message leaves once its row arrives, so a later bounded snapshot cannot bring it back.
31 + */
32 + readonly awaitingRowIds: ReadonlySet<GuestMessageId>;
33 +}
34 +
35 +export const initialGuestStreamState: GuestStreamState = {
36 + view: null,
37 + projection: null,
38 + sequence: 0,
39 + partial: null,
40 + ended: false,
41 + awaitingRowIds: new Set(),
42 +};
43 +
44 +const guestMessageIdOf = (item: OrchestrationV2TurnItem) =>
45 + item.type === "user_message" ? item.context?.guest?.guestMessageId : undefined;
46 +
47 +function withPendingFrom(
48 + awaiting: ReadonlySet<GuestMessageId>,
49 + view: GuestShareView,
50 +): ReadonlySet<GuestMessageId> {
51 + const pending = view.messages.filter((message) => message.status === "pending");
52 + if (pending.every((message) => awaiting.has(message.id))) return awaiting;
53 + return new Set([...awaiting, ...pending.map((message) => message.id)]);
54 +}
55 +
56 +function withoutPlaced(
57 + awaiting: ReadonlySet<GuestMessageId>,
58 + items: ReadonlyArray<OrchestrationV2TurnItem>,
59 +): ReadonlySet<GuestMessageId> {
60 + const placed = items.flatMap((item) => {
61 + const id = guestMessageIdOf(item);
62 + return id !== undefined && awaiting.has(id) ? [id] : [];
63 + });
64 + if (placed.length === 0) return awaiting;
65 + const next = new Set(awaiting);
66 + for (const id of placed) next.delete(id);
67 + return next;
68 +}
69 +
70 +const decodeGuestStreamEvent = Schema.decodeUnknownOption(
71 + Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)),
72 +);
73 +
74 +/** Returns null for anything the server would never send, so a bad frame is skipped, not fatal. */
75 +export const parseGuestStreamEvent = (data: string): GuestStreamEvent | null =>
76 + Option.getOrNull(decodeGuestStreamEvent(data));
77 +
78 +/**
79 + * Applies the owner's thread stream the way the owner's client does (see
80 + * EnvironmentThreadState in client-runtime): a snapshot replaces the thread, and later events
81 + * pass through the same projection reducer, once each.
82 + */
83 +export function applyGuestStreamEvent(
84 + state: GuestStreamState,
85 + event: GuestStreamEvent,
86 +): GuestStreamState {
87 + switch (event.type) {
88 + case "view":
89 + // The page follows the share it names; a view of another one means the link changed.
90 + if (state.view !== null && state.view.shareId !== event.view.shareId) {
91 + return { ...state, ended: true };
92 + }
93 + return {
94 + ...state,
95 + view: event.view,
96 + awaitingRowIds: withPendingFrom(state.awaitingRowIds, event.view),
97 + };
98 + case "thread": {
99 + const item = event.item;
100 + if (item.kind === "snapshot") {
101 + const projection = boundedSnapshotProjection(item);
102 + return {
103 + ...state,
104 + projection,
105 + sequence: item.snapshotSequence,
106 + partial:
107 + item.hasMoreHistory === true || (item.historyCursor ?? null) !== null
108 + ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null }
109 + : null,
110 + awaitingRowIds: withoutPlaced(
111 + state.awaitingRowIds,
112 + projection.visibleTurnItems.map((row) => row.item),
113 + ),
114 + };
115 + }
116 + if (item.kind === "synchronized" || item.sequence <= state.sequence) return state;
117 + if (item.kind === "unknown-event") return { ...state, sequence: item.sequence };
118 + const projection =
119 + applyOrchestrationV2ProjectionEvent(
120 + state.projection,
121 + item.event,
122 + state.partial === null ? undefined : { partialTimeline: true, ...state.partial },
123 + ) ?? state.projection;
124 + const turnItem = item.event.type === "turn-item.updated" ? item.event.payload : null;
125 + const watermark = state.partial?.latestLocalTurnOrdinal ?? null;
126 + return {
127 + ...state,
128 + projection,
129 + sequence: item.sequence,
130 + partial:
131 + state.partial !== null &&
132 + turnItem !== null &&
133 + (watermark === null || turnItem.ordinal > watermark)
134 + ? { latestLocalTurnOrdinal: turnItem.ordinal }
135 + : state.partial,
136 + awaitingRowIds:
137 + turnItem === null
138 + ? state.awaitingRowIds
139 + : withoutPlaced(state.awaitingRowIds, [turnItem]),
140 + };
141 + }
142 + case "ended":
143 + return { ...state, ended: true };
144 + }
145 +}
146 +
147 +/**
148 + * The guest's messages to show after the transcript, oldest first. Pending ones always show. A
149 + * sent or dismissed one shows only while it awaits a row (see `awaitingRowIds`): a queued send, or
150 + * a dismissal to report. The transcript is a bounded window, so any other resolved message is old
151 + * history, not something to place at the end.
152 + */
153 +export function unplacedGuestMessages(
154 + messages: ReadonlyArray<ThreadGuestMessage>,
155 + items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
156 + awaitingRowIds: ReadonlySet<GuestMessageId>,
157 +): ReadonlyArray<ThreadGuestMessage> {
158 + const placed = new Set(items.flatMap((row) => guestMessageIdOf(row.item) ?? []));
159 + return messages
160 + .filter(
161 + (message) =>
162 + !placed.has(message.id) && (message.status === "pending" || awaitingRowIds.has(message.id)),
163 + )
164 + .toSorted((a, b) => a.submittedAt.localeCompare(b.submittedAt));
165 +}
166 +
167 +/** "23h left" or "5m left", rounded down, for the guest page header. */
168 +export function formatGuestExpiry(expiresAt: string, nowMs: number): string {
169 + const minutes = Math.floor((Date.parse(expiresAt) - nowMs) / 60_000);
170 + if (minutes <= 0) return "Expired";
171 + return minutes >= 60 ? `${Math.floor(minutes / 60)}h left` : `${minutes}m left`;
172 +}
173 +
174 +/**
175 + * The share an invite (`<shareId>.<signature>`) opens. Only used to name the share in the page
176 + * URL and to find this browser's session for it; the server checks the signature.
177 + */
178 +export function inviteShareId(credential: string): string | null {
179 + const [shareId, signature] = credential.split(".");
180 + return shareId && signature ? shareId : null;
181 +}
182 +
183 +/** Where the guest page loads a file of the shared thread or of a waiting message. */
184 +export const guestAttachmentUrl = (shareId: string, attachmentId: string) =>
185 + `${GUEST_ATTACHMENT_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&id=${encodeURIComponent(attachmentId)}`;
186 +
187 +/**
188 + * Why these files cannot go with one message, or null. The server checks the same limits; this
189 + * only says so before the upload.
190 + */
191 +export function guestFilesProblem(
192 + files: ReadonlyArray<Pick<File, "type" | "size">>,
193 +): string | null {
194 + if (files.length > GUEST_MESSAGE_MAX_ATTACHMENTS) {
195 + return `Attach up to ${GUEST_MESSAGE_MAX_ATTACHMENTS} files to a message.`;
196 + }
197 + if (files.reduce((total, file) => total + file.size, 0) > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) {
198 + return "Attached files can total up to 10 MB per message.";
199 + }
200 + const unsupported = files.some(
201 + (file) =>
202 + file.size === 0 ||
203 + (file.type.toLowerCase().startsWith("image/") &&
204 + !isProviderSendTurnSupportedImageMimeType(file.type)),
205 + );
206 + return unsupported
207 + ? "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP."
208 + : null;
209 +}
210 +
211 +/**
212 + * Image URLs for the thread's messages, which the timeline shows as previews. The map keeps its
213 + * identity while the rows do, because the timeline rebuilds its entries when it changes.
214 + */
215 +export function createGuestAttachmentUrls(shareId: string) {
216 + let previousItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> | null = null;
217 + let previous: ReadonlyMap<string, string> = new Map();
218 + return (items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>): ReadonlyMap<string, string> => {
219 + if (items === previousItems) return previous;
220 + previousItems = items;
221 + previous = new Map(
222 + items.flatMap(({ item }) =>
223 + item.type === "user_message"
224 + ? item.attachments.map(
225 + (attachment) => [attachment.id, guestAttachmentUrl(shareId, attachment.id)] as const,
226 + )
227 + : [],
228 + ),
229 + );
230 + return previous;
231 + };
232 +}
apps/web/src/components/guest/guestTurnItemSource.ts new
+102
@@ -0,0 +1,102 @@
1 +import {
2 + applyCommandOutputFrame,
3 + EMPTY_COMMAND_OUTPUT,
4 +} from "@t3tools/client-runtime/state/command-output";
5 +import {
6 + GUEST_COMMAND_OUTPUT_ROUTE,
7 + GUEST_ITEM_ROUTE,
8 + GUEST_SHARE_PARAM,
9 + OrchestrationV2CommandOutputFrame,
10 + OrchestrationV2GetTurnItemResult,
11 +} from "@t3tools/contracts";
12 +import * as Cause from "effect/Cause";
13 +import * as Data from "effect/Data";
14 +import * as Effect from "effect/Effect";
15 +import * as Option from "effect/Option";
16 +import * as Queue from "effect/Queue";
17 +import * as Schema from "effect/Schema";
18 +import * as Stream from "effect/Stream";
19 +import { Atom } from "effect/reactivity";
20 +
21 +import type { TurnItemSource } from "../chat/timelineRowContext";
22 +
23 +/** What an expanded guest row says when it cannot read the item. */
24 +class GuestItemReadError extends Data.TaggedError("GuestItemReadError")<{
25 + readonly message: string;
26 +}> {}
27 +
28 +const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
29 +const decodeFrame = Schema.decodeUnknownOption(
30 + Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
31 +);
32 +
33 +const itemUrl = (route: string, shareId: string, itemId: string) =>
34 + `${route}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}`;
35 +
36 +/** `item` is null when the thread no longer has the item, or the share ended. */
37 +async function fetchGuestItemDetail(
38 + shareId: string,
39 + itemId: string,
40 +): Promise<OrchestrationV2GetTurnItemResult> {
41 + const response = await fetch(itemUrl(GUEST_ITEM_ROUTE, shareId, itemId));
42 + if (response.status === 403) return { item: null };
43 + if (!response.ok) throw new Error(`Guest item request failed with ${response.status}.`);
44 + return decodeDetail(await response.json());
45 +}
46 +
47 +// Keys are JSON so a share id or item id can never run into the next part.
48 +const guestItemDetailAtom = Atom.family((key: string) => {
49 + const [shareId, itemId] = JSON.parse(key) as [string, string, string];
50 + return Atom.make(
51 + Effect.tryPromise({
52 + try: () => fetchGuestItemDetail(shareId, itemId),
53 + catch: () => new GuestItemReadError({ message: "Could not load this item." }),
54 + }),
55 + );
56 +});
57 +
58 +/** Ends after the frame of a settled command, so the browser does not reconnect to it. */
59 +const guestCommandOutputAtom = Atom.family((key: string) => {
60 + const [shareId, itemId] = JSON.parse(key) as [string, string];
61 + const frames = Stream.callback<OrchestrationV2CommandOutputFrame, GuestItemReadError>((queue) =>
62 + Effect.acquireRelease(
63 + Effect.sync(() => {
64 + const source = new EventSource(itemUrl(GUEST_COMMAND_OUTPUT_ROUTE, shareId, itemId));
65 + source.addEventListener("message", (message) => {
66 + const frame = decodeFrame(message.data);
67 + if (Option.isNone(frame)) return;
68 + Queue.offerUnsafe(queue, frame.value);
69 + if (!frame.value.running) {
70 + source.close();
71 + Queue.endUnsafe(queue);
72 + }
73 + });
74 + // A non-200 response closes the source for good: the share ended or the item is gone.
75 + source.addEventListener("error", () => {
76 + if (source.readyState === EventSource.CLOSED) {
77 + Queue.failCauseUnsafe(
78 + queue,
79 + Cause.fail(new GuestItemReadError({ message: "Output is no longer available." })),
80 + );
81 + }
82 + });
83 + return source;
84 + }),
85 + (source) => Effect.sync(() => source.close()),
86 + ),
87 + );
88 + // `scan` emits its seed first; skipping it keeps the row "loading" until the first frame.
89 + return Atom.make(
90 + frames.pipe(
91 + Stream.scan(() => EMPTY_COMMAND_OUTPUT, applyCommandOutputFrame),
92 + Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),
93 + ),
94 + );
95 +});
96 +
97 +/** Expanded rows on the guest page read through the guest routes, with the page's share cookie. */
98 +export const guestTurnItemSource = (shareId: string): TurnItemSource => ({
99 + detail: ({ itemId, revision }) =>
100 + guestItemDetailAtom(JSON.stringify([shareId, itemId, revision])),
101 + commandOutput: ({ itemId }) => guestCommandOutputAtom(JSON.stringify([shareId, itemId])),
102 +});
apps/web/src/components/settings/BetaSettingsPanel.tsx new
+106
@@ -0,0 +1,106 @@
1 +import { useAuth } from "@clerk/react";
2 +import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
3 +import { Link } from "@tanstack/react-router";
4 +
5 +import { hasCloudPublicConfig } from "~/cloud/publicConfig";
6 +import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
7 +import { Button } from "../ui/button";
8 +import { Switch } from "../ui/switch";
9 +import { ScopedSwitch } from "./ScopedSwitch";
10 +import {
11 + SettingResetButton,
12 + SettingsPageContainer,
13 + SettingsRow,
14 + SettingsSection,
15 +} from "./settingsLayout";
16 +import { searchableSetting } from "./settingsSearch";
17 +import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
18 +
19 +/** Features that are still settling in. Each is off until turned on here. */
20 +export function BetaSettingsPanel() {
21 + const settings = useScopedSettings();
22 + const updateSettings = useUpdateScopedSettings();
23 + return (
24 + <SettingsPageContainer>
25 + <SettingsSection id="beta" title="Beta">
26 + <SettingsRow
27 + {...searchableSetting("working-shelf")}
28 + description="Fold working and monitoring threads into a Working section. They return to the top of the inbox when they need you."
29 + resetAction={
30 + settings.sidebarWorkingShelfEnabled !==
31 + DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? (
32 + <SettingResetButton
33 + label="working section"
34 + onClick={() =>
35 + updateSettings({
36 + sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled,
37 + })
38 + }
39 + />
40 + ) : null
41 + }
42 + control={
43 + <Switch
44 + checked={settings.sidebarWorkingShelfEnabled}
45 + onCheckedChange={(checked) =>
46 + updateSettings({ sidebarWorkingShelfEnabled: Boolean(checked) })
47 + }
48 + aria-label="Working section"
49 + />
50 + }
51 + />
52 + {/* Clerk is only mounted when this build has T3 Connect. */}
53 + {hasCloudPublicConfig() ? <GuestLinksRowWithSignIn /> : <GuestLinksRow />}
54 + </SettingsSection>
55 + </SettingsPageContainer>
56 + );
57 +}
58 +
59 +/** Signed out of T3 Connect, the row offers to sign in instead of its switch. */
60 +function GuestLinksRowWithSignIn() {
61 + const { isSignedIn } = useAuth();
62 + const { openAuthPrompt } = useT3ConnectAuthPrompt();
63 + // `isSignedIn` is undefined until Clerk loads.
64 + if (isSignedIn !== false) return <GuestLinksRow />;
65 + return (
66 + <SettingsRow
67 + {...searchableSetting("guest-links")}
68 + 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."
69 + control={
70 + <Button size="sm" variant="outline" onClick={openAuthPrompt}>
71 + Sign in
72 + </Button>
73 + }
74 + />
75 + );
76 +}
77 +
78 +function GuestLinksRow() {
79 + const settings = useScopedSettings();
80 + const updateSettings = useUpdateScopedSettings();
81 + return (
82 + <SettingsRow
83 + serverScoped
84 + {...searchableSetting("guest-links")}
85 + settingKeys={["guestSharingEnabled"]}
86 + description={
87 + <>
88 + Share a thread with a guest who watches it live in their browser and sends messages you
89 + approve. Needs T3 Connect: sign in and link this machine in{" "}
90 + <Link to="/settings/connections" className="underline underline-offset-2">
91 + Connections
92 + </Link>
93 + . While it is off, every guest link stops working.
94 + </>
95 + }
96 + control={
97 + <ScopedSwitch
98 + settingKeys={["guestSharingEnabled"]}
99 + checked={settings.guestSharingEnabled}
100 + onCheckedChange={(checked) => updateSettings({ guestSharingEnabled: Boolean(checked) })}
101 + aria-label="Guest links"
102 + />
103 + }
104 + />
105 + );
106 +}
apps/web/src/components/settings/SettingsPanels.tsx
-27
@@ -975,33 +975,6 @@ export function GeneralSettingsPanel() {
975 }
976 />
977
978 - <SettingsRow
979 - {...searchableSetting("working-shelf")}
980 - description="Fold working and monitoring threads into a Working section. They return to the top of the inbox when they need you."
981 - resetAction={
982 - settings.sidebarWorkingShelfEnabled !==
983 - DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? (
984 - <SettingResetButton
985 - label="working section"
986 - onClick={() =>
987 - updateSettings({
988 - sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled,
989 - })
990 - }
991 - />
992 - ) : null
993 - }
994 - control={
995 - <Switch
996 - checked={settings.sidebarWorkingShelfEnabled}
997 - onCheckedChange={(checked) =>
998 - updateSettings({ sidebarWorkingShelfEnabled: Boolean(checked) })
999 - }
1000 - aria-label="Working section (beta)"
1001 - />
1002 - }
1003 - />
1004 -
978 <SettingsRow
979 serverScoped
980 settingKeys={["idleCompaction", "compactIdleThreads"]}
apps/web/src/components/settings/SettingsSidebarNav.tsx
+2
@@ -9,6 +9,7 @@ import {
9 } from "react";
10 import {
11 ArchiveIcon,
12 + FlaskConicalIcon,
13 BlocksIcon,
14 BotIcon,
15 createLucideIcon,
@@ -87,6 +88,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
88 "/settings/source-control": GitBranchIcon,
89 "/settings/storage": HardDriveIcon,
90 "/settings/connections": Link2Icon,
91 + "/settings/beta": FlaskConicalIcon,
92 "/settings/archived": ArchiveIcon,
93 };
94
apps/web/src/components/settings/settingsSearch.ts
+13 -3
@@ -29,6 +29,7 @@ export type SettingsPath =
29 | "/settings/source-control"
30 | "/settings/storage"
31 | "/settings/connections"
32 + | "/settings/beta"
33 | "/settings/archived";
34
35 export type SettingsSearchScope =
@@ -87,6 +88,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
88 "/settings/source-control": "Source Control",
89 "/settings/storage": "Storage",
90 "/settings/connections": "Connections",
91 + "/settings/beta": "Beta",
92 "/settings/archived": "Archive",
93 };
94
@@ -347,9 +349,16 @@ export const SETTINGS_SEARCH_ITEMS = [
349 },
350 {
351 id: "working-shelf",
350 - title: "Working section (beta)",
351 - to: "/settings/general",
352 - searchTerms: ["hide fold running monitoring threads inbox sidebar shelf"],
352 + title: "Working section",
353 + to: "/settings/beta",
354 + searchTerms: ["beta hide fold running monitoring threads inbox sidebar shelf"],
355 + },
356 + {
357 + id: "guest-links",
358 + title: "Guest links",
359 + to: "/settings/beta",
360 + scope: "environment",
361 + searchTerms: ["beta share guest invite link teammate watch t3 connect tunnel"],
362 },
363 {
364 id: "auto-settle-inactive-threads",
@@ -1045,6 +1054,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScop
1054 "/settings/storage": "project-defaults",
1055 "/settings/connections": "connections",
1056 "/settings/scheduled-tasks": null,
1057 + "/settings/beta": null,
1058 "/settings/archived": "project-defaults",
1059 };
1060
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+27 -18
@@ -44,6 +44,7 @@ import {
44 SquarePenIcon,
45 TerminalIcon,
46 Undo2Icon,
47 + UserRoundIcon,
48 XIcon,
49 } from "lucide-react";
50 import {
@@ -673,31 +674,37 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
674 icon: "input" as const,
675 className: "text-indigo-600 dark:text-indigo-300",
676 }
676 - : status === "limited"
677 + : status === "request"
678 ? {
678 - label: "Limited",
679 - icon: "failed" as const,
680 - className: "text-warning",
679 + label: "Request",
680 + icon: "request" as const,
681 + className: "text-guest-foreground",
682 }
682 - : status === "failed"
683 + : status === "limited"
684 ? {
684 - label: "Failed",
685 + label: "Limited",
686 icon: "failed" as const,
686 - className: "text-error",
687 + className: "text-warning",
688 }
688 - : isWoke
689 + : status === "failed"
690 ? {
690 - label: "Woke",
691 - icon: "woke" as const,
692 - className: "text-warning",
691 + label: "Failed",
692 + icon: "failed" as const,
693 + className: "text-error",
694 }
694 - : isUnread
695 + : isWoke
696 ? {
696 - label: "Done",
697 - icon: "done" as const,
698 - className: "text-success",
697 + label: "Woke",
698 + icon: "woke" as const,
699 + className: "text-warning",
700 }
700 - : null;
701 + : isUnread
702 + ? {
703 + label: "Done",
704 + icon: "done" as const,
705 + className: "text-success",
706 + }
707 + : null;
708 const isWokeStatus = topStatus?.icon === "woke";
709
710 const branchMismatch = resolveLocalCheckoutBranchMismatch({
@@ -968,7 +975,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
975 "truncate",
976 shouldRecede
977 ? "text-secondary-label"
971 - : isUnread || isWoke || status === "input"
978 + : isUnread || isWoke || status === "input" || status === "request"
979 ? "text-foreground"
980 : status === "failed"
981 ? "text-foreground/95"
@@ -978,7 +985,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
985 "truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
986 shouldRecede
987 ? "text-secondary-label/70"
981 - : props.isActive || isWoke || status === "input"
988 + : props.isActive || isWoke || status === "input" || status === "request"
989 ? "text-foreground"
990 : isUnread
991 ? "text-muted-foreground"
@@ -1335,6 +1342,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
1342 <CircleDotDashedIcon aria-hidden className="size-4 shrink-0" />
1343 ) : topStatus.icon === "input" ? (
1344 <MessageCircleQuestionIcon aria-hidden className="size-4 shrink-0" />
1345 + ) : topStatus.icon === "request" ? (
1346 + <UserRoundIcon aria-hidden className="size-4 shrink-0" />
1347 ) : topStatus.icon === "approval" ? (
1348 <ShieldQuestionIcon aria-hidden className="size-4 shrink-0" />
1349 ) : topStatus.icon === "failed" ? (
apps/web/src/components/threadActionMenu.logic.ts
+7
@@ -18,6 +18,7 @@ export type ThreadActionMenuId =
18 | "rename"
19 | "regenerate-title"
20 | "mark-unread"
21 + | "share-guest"
22 | "copy"
23 | "copy-path"
24 | "copy-branch"
@@ -86,6 +87,8 @@ export interface ThreadActionMenuState {
87 readonly titleRegeneration: boolean;
88 };
89 readonly snoozePresets: ReadonlyArray<SnoozePreset>;
90 + /** Guest links need their own grant, so the caller checks it instead of `canOperate`. */
91 + readonly canShareWithGuest?: boolean;
92 }
93
94 /** Local navigation, read markers, and copying remain available to read-only clients. */
@@ -94,6 +97,7 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean
97 "new-thread-on-branch",
98 "project-settings",
99 "mark-unread",
100 + "share-guest",
101 "copy",
102 "copy-path",
103 "copy-branch",
@@ -159,6 +163,9 @@ export function buildThreadActionMenuItems(
163 ]
164 : []),
165 { id: "mark-unread", label: "Mark unread", icon: "mail-open" },
166 + ...(state.canShareWithGuest
167 + ? [{ id: "share-guest" as const, label: "Share with guest", icon: "user-plus" }]
168 + : []),
169 ...(state.projectFilter
170 ? [
171 {
apps/web/src/connection/runtime.browser.test.ts new
+29
@@ -0,0 +1,29 @@
1 +import * as Cause from "effect/Cause";
2 +import { AsyncResult, AtomRegistry } from "effect/reactivity";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { connectionAtomRuntime } from "./runtime";
6 +
7 +function visit(path: string): Disposable {
8 + const previous = `${window.location.pathname}${window.location.search}`;
9 + window.history.replaceState(window.history.state, "", path);
10 + return {
11 + [Symbol.dispose]: () => window.history.replaceState(window.history.state, "", previous),
12 + };
13 +}
14 +
15 +describe("connectionAtomRuntime", () => {
16 + it("connects to no environment on the guest page", async () => {
17 + using _page = visit("/guest?share=share-1");
18 + using socket = vi.spyOn(window, "WebSocket");
19 + const registry = AtomRegistry.make();
20 + using _mounted = { [Symbol.dispose]: registry.mount(connectionAtomRuntime) };
21 + await vi.waitFor(() => {
22 + const result = registry.get(connectionAtomRuntime);
23 + expect(AsyncResult.isFailure(result) && String(Cause.squash(result.cause))).toContain(
24 + "The guest page has no environment connection.",
25 + );
26 + });
27 + expect(socket).not.toHaveBeenCalled();
28 + });
29 +});
apps/web/src/connection/runtime.ts
+17 -1
@@ -5,9 +5,12 @@ import {
5 ThreadHistoryController,
6 } from "@t3tools/client-runtime/state/threads";
7 import { PullRequestDiffLoader } from "@t3tools/client-runtime/state/pull-requests";
8 +import * as Effect from "effect/Effect";
9 import * as Layer from "effect/Layer";
10 import { Atom } from "effect/reactivity";
11
12 +import { isGuestPage } from "../guestPage";
13 +
14 import * as Runtime from "../lib/runtime";
15 import * as BackgroundActivityReporter from "../lib/backgroundActivityReporter";
16 import * as ConnectionPlatform from "./platform";
@@ -50,7 +53,20 @@ const layerConnection = BackgroundActivityReporter.layer.pipe(
53 Layer.provideMerge(layerProvidedClientConnection),
54 );
55
56 +/**
57 + * A guest has no session here. Building the connection would open the page origin's environment
58 + * with whatever cookie this browser holds, plus every environment saved in it, so on the guest
59 + * page the runtime fails to build and every atom on it keeps its empty value.
60 + */
61 +const layerForPage = Layer.unwrap(
62 + Effect.suspend((): Effect.Effect<typeof layerConnection> =>
63 + isGuestPage()
64 + ? Effect.die(new Error("The guest page has no environment connection."))
65 + : Effect.succeed(layerConnection),
66 + ),
67 +);
68 +
69 export const connectionAtomRuntime: Atom.AtomRuntime<
70 Layer.Success<ConnectionLayerSource>,
71 Layer.Error<ConnectionLayerSource>
56 -> = Atom.runtime(layerConnection);
72 +> = Atom.runtime(layerForPage);
apps/web/src/contextMenuFallback.ts
+6
@@ -110,6 +110,12 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri
110 },
111 { tag: "circle", attrs: { cx: "12", cy: "12", r: "3" } },
112 ],
113 + "user-plus": [
114 + { tag: "path", attrs: { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" } },
115 + { tag: "circle", attrs: { cx: "9", cy: "7", r: "4" } },
116 + { tag: "line", attrs: { x1: "19", x2: "19", y1: "8", y2: "14" } },
117 + { tag: "line", attrs: { x1: "22", x2: "16", y1: "11", y2: "11" } },
118 + ],
119 "folder-tree": [
120 {
121 tag: "path",
apps/web/src/guestPage.ts new
+6
@@ -0,0 +1,6 @@
1 +/** The page a guest link opens. It shows one shared thread to a browser with no T3 session. */
2 +export const GUEST_PAGE_PATH = "/guest";
3 +
4 +export function isGuestPage(): boolean {
5 + return window.location.pathname === GUEST_PAGE_PATH;
6 +}
apps/web/src/hooks/useThreadActionMenu.test.ts
+1
@@ -156,6 +156,7 @@ const createMenu = () =>
156 threadRef: target,
157 projectCwd: "/project",
158 onStartRename: () => recordEffect("rename"),
159 + canShareWithGuest: false,
160 });
161
162 beforeEach(() => {
apps/web/src/hooks/useThreadActionMenu.ts
+7 -1
@@ -1,5 +1,6 @@
1 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2 import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
3 +import { openGuestShareDialog } from "../components/chat/guestShareDialogState";
4 import {
5 type AtomCommandResult,
6 isAtomCommandInterrupted,
@@ -61,8 +62,9 @@ export function useThreadActionMenu(input: {
62 readonly threadRef: ScopedThreadRef | null;
63 readonly projectCwd: string | null;
64 readonly onStartRename: () => void;
65 + readonly canShareWithGuest: boolean;
66 }) {
65 - const { threadRef, projectCwd, onStartRename } = input;
67 + const { threadRef, projectCwd, onStartRename, canShareWithGuest } = input;
68 const router = useRouter();
69 const projects = useProjects();
70 const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -141,6 +143,7 @@ export function useThreadActionMenu(input: {
143 isRunning: !threadRuntimeCanArchive(thread.runtime),
144 supports,
145 snoozePresets,
146 + canShareWithGuest,
147 });
148 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
149 if (clicked._tag === "Failure" || clicked.value === null) return;
@@ -243,6 +246,9 @@ export function useThreadActionMenu(input: {
246 case "mark-unread":
247 markThreadUnread(threadRef);
248 return;
249 + case "share-guest":
250 + openGuestShareDialog(threadRef);
251 + return;
252 case "copy-path": {
253 const workspacePath = thread.worktreePath ?? projectCwd;
254 if (!workspacePath) {
apps/web/src/index.css
+8
@@ -240,6 +240,9 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
240 --color-diff-deletion-foreground: var(--diff-deletion-foreground);
241 --color-info-foreground: var(--info-foreground);
242 --color-info: var(--info);
243 + --color-guest: var(--guest);
244 + --color-guest-foreground: var(--guest-foreground);
245 + --color-guest-surface: var(--guest-surface);
246 --color-destructive-foreground: var(--destructive-foreground);
247 --color-ring: var(--ring);
248 --color-input: var(--contrast-input);
@@ -1132,6 +1135,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
1135 --destructive-foreground: var(--error-foreground);
1136 --info: var(--color-blue-500);
1137 --info-foreground: var(--color-blue-700);
1138 + /* Messages from a guest link, and the sidebar Request status. */
1139 + --guest: var(--color-fuchsia-500);
1140 + --guest-foreground: var(--color-fuchsia-600);
1141 + --guest-surface: color-mix(in srgb, var(--guest) 14%, var(--message-surface));
1142 --success: var(--color-emerald-500);
1143 --success-foreground: var(--color-emerald-700);
1144 --warning: var(--color-amber-500);
@@ -1183,6 +1190,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
1190 --border: --alpha(var(--color-white) / 6%);
1191 --input: --alpha(var(--color-white) / 8%);
1192 --info-foreground: var(--color-blue-400);
1193 + --guest-foreground: var(--color-fuchsia-300);
1194 --success-foreground: var(--color-emerald-400);
1195 --warning-foreground: var(--color-amber-400);
1196 --warning-surface: color-mix(in srgb, var(--warning) 16%, transparent);
apps/web/src/routeTree.gen.ts
+42
@@ -13,6 +13,7 @@ import { Route as WelcomeRouteImport } from './routes/welcome'
13 import { Route as UsageRouteImport } from './routes/usage'
14 import { Route as SettingsRouteImport } from './routes/settings'
15 import { Route as PairRouteImport } from './routes/pair'
16 +import { Route as GuestRouteImport } from './routes/guest'
17 import { Route as ConnectAgentRouteImport } from './routes/connect-agent'
18 import { Route as ConnectRouteImport } from './routes/connect'
19 import { Route as ChatRouteImport } from './routes/_chat'
@@ -29,6 +30,7 @@ import { Route as SettingsIntegrationsRouteImport } from './routes/settings.inte
30 import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
31 import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
32 import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
33 +import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
34 import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
35 import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
36 import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'
@@ -57,6 +59,11 @@ const PairRoute = PairRouteImport.update({
59 path: '/pair',
60 getParentRoute: () => rootRouteImport,
61 } as any)
62 +const GuestRoute = GuestRouteImport.update({
63 + id: '/guest',
64 + path: '/guest',
65 + getParentRoute: () => rootRouteImport,
66 +} as any)
67 const ConnectAgentRoute = ConnectAgentRouteImport.update({
68 id: '/connect-agent',
69 path: '/connect-agent',
@@ -137,6 +144,11 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
144 path: '/connections',
145 getParentRoute: () => SettingsRoute,
146 } as any)
147 +const SettingsBetaRoute = SettingsBetaRouteImport.update({
148 + id: '/beta',
149 + path: '/beta',
150 + getParentRoute: () => SettingsRoute,
151 +} as any)
152 const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
153 id: '/archived',
154 path: '/archived',
@@ -178,6 +190,7 @@ export interface FileRoutesByFullPath {
190 '/': typeof ChatIndexRoute
191 '/connect': typeof ConnectRoute
192 '/connect-agent': typeof ConnectAgentRoute
193 + '/guest': typeof GuestRoute
194 '/pair': typeof PairRoute
195 '/settings': typeof SettingsRouteWithChildren
196 '/usage': typeof UsageRoute
@@ -187,6 +200,7 @@ export interface FileRoutesByFullPath {
200 '/projects/$projectKey': typeof ProjectsProjectKeyRoute
201 '/settings/appearance': typeof SettingsAppearanceRoute
202 '/settings/archived': typeof SettingsArchivedRoute
203 + '/settings/beta': typeof SettingsBetaRoute
204 '/settings/connections': typeof SettingsConnectionsRoute
205 '/settings/diagnostics': typeof SettingsDiagnosticsRoute
206 '/settings/general': typeof SettingsGeneralRoute
@@ -205,6 +219,7 @@ export interface FileRoutesByFullPath {
219 export interface FileRoutesByTo {
220 '/connect': typeof ConnectRoute
221 '/connect-agent': typeof ConnectAgentRoute
222 + '/guest': typeof GuestRoute
223 '/pair': typeof PairRoute
224 '/settings': typeof SettingsRouteWithChildren
225 '/usage': typeof UsageRoute
@@ -214,6 +229,7 @@ export interface FileRoutesByTo {
229 '/projects/$projectKey': typeof ProjectsProjectKeyRoute
230 '/settings/appearance': typeof SettingsAppearanceRoute
231 '/settings/archived': typeof SettingsArchivedRoute
232 + '/settings/beta': typeof SettingsBetaRoute
233 '/settings/connections': typeof SettingsConnectionsRoute
234 '/settings/diagnostics': typeof SettingsDiagnosticsRoute
235 '/settings/general': typeof SettingsGeneralRoute
@@ -235,6 +251,7 @@ export interface FileRoutesById {
251 '/_chat': typeof ChatRouteWithChildren
252 '/connect': typeof ConnectRoute
253 '/connect-agent': typeof ConnectAgentRoute
254 + '/guest': typeof GuestRoute
255 '/pair': typeof PairRoute
256 '/settings': typeof SettingsRouteWithChildren
257 '/usage': typeof UsageRoute
@@ -244,6 +261,7 @@ export interface FileRoutesById {
261 '/projects/$projectKey': typeof ProjectsProjectKeyRoute
262 '/settings/appearance': typeof SettingsAppearanceRoute
263 '/settings/archived': typeof SettingsArchivedRoute
264 + '/settings/beta': typeof SettingsBetaRoute
265 '/settings/connections': typeof SettingsConnectionsRoute
266 '/settings/diagnostics': typeof SettingsDiagnosticsRoute
267 '/settings/general': typeof SettingsGeneralRoute
@@ -266,6 +284,7 @@ export interface FileRouteTypes {
284 | '/'
285 | '/connect'
286 | '/connect-agent'
287 + | '/guest'
288 | '/pair'
289 | '/settings'
290 | '/usage'
@@ -275,6 +294,7 @@ export interface FileRouteTypes {
294 | '/projects/$projectKey'
295 | '/settings/appearance'
296 | '/settings/archived'
297 + | '/settings/beta'
298 | '/settings/connections'
299 | '/settings/diagnostics'
300 | '/settings/general'
@@ -293,6 +313,7 @@ export interface FileRouteTypes {
313 to:
314 | '/connect'
315 | '/connect-agent'
316 + | '/guest'
317 | '/pair'
318 | '/settings'
319 | '/usage'
@@ -302,6 +323,7 @@ export interface FileRouteTypes {
323 | '/projects/$projectKey'
324 | '/settings/appearance'
325 | '/settings/archived'
326 + | '/settings/beta'
327 | '/settings/connections'
328 | '/settings/diagnostics'
329 | '/settings/general'
@@ -322,6 +344,7 @@ export interface FileRouteTypes {
344 | '/_chat'
345 | '/connect'
346 | '/connect-agent'
347 + | '/guest'
348 | '/pair'
349 | '/settings'
350 | '/usage'
@@ -331,6 +354,7 @@ export interface FileRouteTypes {
354 | '/projects/$projectKey'
355 | '/settings/appearance'
356 | '/settings/archived'
357 + | '/settings/beta'
358 | '/settings/connections'
359 | '/settings/diagnostics'
360 | '/settings/general'
@@ -352,6 +376,7 @@ export interface RootRouteChildren {
376 ChatRoute: typeof ChatRouteWithChildren
377 ConnectRoute: typeof ConnectRoute
378 ConnectAgentRoute: typeof ConnectAgentRoute
379 + GuestRoute: typeof GuestRoute
380 PairRoute: typeof PairRoute
381 SettingsRoute: typeof SettingsRouteWithChildren
382 UsageRoute: typeof UsageRoute
@@ -389,6 +414,13 @@ declare module '@tanstack/react-router' {
414 preLoaderRoute: typeof PairRouteImport
415 parentRoute: typeof rootRouteImport
416 }
417 + '/guest': {
418 + id: '/guest'
419 + path: '/guest'
420 + fullPath: '/guest'
421 + preLoaderRoute: typeof GuestRouteImport
422 + parentRoute: typeof rootRouteImport
423 + }
424 '/connect-agent': {
425 id: '/connect-agent'
426 path: '/connect-agent'
@@ -501,6 +533,13 @@ declare module '@tanstack/react-router' {
533 preLoaderRoute: typeof SettingsConnectionsRouteImport
534 parentRoute: typeof SettingsRoute
535 }
536 + '/settings/beta': {
537 + id: '/settings/beta'
538 + path: '/beta'
539 + fullPath: '/settings/beta'
540 + preLoaderRoute: typeof SettingsBetaRouteImport
541 + parentRoute: typeof SettingsRoute
542 + }
543 '/settings/archived': {
544 id: '/settings/archived'
545 path: '/archived'
@@ -574,6 +613,7 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
613 interface SettingsRouteChildren {
614 SettingsAppearanceRoute: typeof SettingsAppearanceRoute
615 SettingsArchivedRoute: typeof SettingsArchivedRoute
616 + SettingsBetaRoute: typeof SettingsBetaRoute
617 SettingsConnectionsRoute: typeof SettingsConnectionsRoute
618 SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
619 SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -591,6 +631,7 @@ interface SettingsRouteChildren {
631 const SettingsRouteChildren: SettingsRouteChildren = {
632 SettingsAppearanceRoute: SettingsAppearanceRoute,
633 SettingsArchivedRoute: SettingsArchivedRoute,
634 + SettingsBetaRoute: SettingsBetaRoute,
635 SettingsConnectionsRoute: SettingsConnectionsRoute,
636 SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
637 SettingsGeneralRoute: SettingsGeneralRoute,
@@ -613,6 +654,7 @@ const rootRouteChildren: RootRouteChildren = {
654 ChatRoute: ChatRouteWithChildren,
655 ConnectRoute: ConnectRoute,
656 ConnectAgentRoute: ConnectAgentRoute,
657 + GuestRoute: GuestRoute,
658 PairRoute: PairRoute,
659 SettingsRoute: SettingsRouteWithChildren,
660 UsageRoute: UsageRoute,
apps/web/src/routes/__root.tsx
+16
@@ -19,6 +19,7 @@ import { resolveServerBackedAppDisplayName } from "../branding.logic";
19 import { AppSidebarLayout } from "../components/AppSidebarLayout";
20 import { CommandPalette } from "../components/CommandPalette";
21 import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
22 +import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
23 import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
24 import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
25 import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
@@ -67,6 +68,7 @@ import { useUiStateStore } from "../uiStateStore";
68 import { syncBrowserChromeTheme } from "../hooks/useTheme";
69 import { configureClientTracing } from "../observability/clientTracing";
70 import { resolveInitialServerAuthGateState } from "../environments/primary";
71 +import { GUEST_PAGE_PATH } from "../guestPage";
72 import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
73 import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
74 import { isLocalEnvironmentDisabled } from "../localEnvironment";
@@ -89,6 +91,16 @@ import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
91
92 export const Route = createRootRoute({
93 beforeLoad: async ({ location }) => {
94 + // Guest links open on the owner's tunnel host in a browser with no T3 session, and must
95 + // not trigger pairing or an environment connection.
96 + if (location.pathname === GUEST_PAGE_PATH) {
97 + return {
98 + authGateState: {
99 + status: "guest",
100 + } as const,
101 + };
102 + }
103 +
104 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
105 return {
106 authGateState: {
@@ -153,6 +165,8 @@ function RootRouteView() {
165 authGateState.status === "hosted-static",
166 );
167
168 + if (pathname === GUEST_PAGE_PATH) return <Outlet />;
169 +
170 if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
171 return (
172 <>
@@ -187,6 +201,7 @@ function RootRouteView() {
201 <FontAppearanceSync />
202 <ProviderAuthCallbackCoordinator />
203 <CustomSnoozeDialogHost />
204 + <GuestShareDialogHost />
205 <CommandPalette>
206 <AppSidebarLayout>
207 <Outlet />
@@ -242,6 +257,7 @@ function RootRouteView() {
257 <ReopenClosedViewShortcut />
258 <ConfirmDialogHost />
259 <CustomSnoozeDialogHost />
260 + <GuestShareDialogHost />
261 <SlowRpcRequestToastCoordinator />
262 <HostFreezeToastCoordinator />
263 <PermissionUpdateNotice />
apps/web/src/routes/guest.tsx new
+7
@@ -0,0 +1,7 @@
1 +import { createFileRoute } from "@tanstack/react-router";
2 +
3 +import { GuestPage } from "../components/guest/GuestPage";
4 +
5 +export const Route = createFileRoute("/guest")({
6 + component: GuestPage,
7 +});
apps/web/src/routes/pair.tsx
+5 -1
@@ -15,7 +15,11 @@ export const Route = createFileRoute("/pair")({
15 };
16 }
17
18 - if (authGateState.status === "authenticated" || authGateState.status === "hosted-static") {
18 + if (
19 + authGateState.status === "authenticated" ||
20 + authGateState.status === "hosted-static" ||
21 + authGateState.status === "guest"
22 + ) {
23 throw redirect({ to: "/", replace: true });
24 }
25 return {
apps/web/src/routes/settings.beta.tsx new
+5
@@ -0,0 +1,5 @@
1 +import { createFileRoute } from "@tanstack/react-router";
2 +
3 +import { BetaSettingsPanel } from "../components/settings/BetaSettingsPanel";
4 +
5 +export const Route = createFileRoute("/settings/beta")({ component: BetaSettingsPanel });
apps/web/src/state/queries.ts
+17 -5
@@ -15,6 +15,7 @@ import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
15 import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
16 import type {
17 EnvironmentId,
18 + OrchestrationV2GetTurnItemResult,
19 ProjectContentMatch,
20 ProjectEntry,
21 ProjectEntryKind,
@@ -402,6 +403,13 @@ export function useCheckpointDiff(
403 return fullThreadTarget === null ? turn : fullThread;
404 }
405
406 +/** Reads one item's detail from somewhere other than the environment, as the guest page does. */
407 +export type TurnItemDetailSource = (input: {
408 + readonly threadId: ThreadId;
409 + readonly itemId: TurnItemId;
410 + readonly revision: string;
411 +}) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>;
412 +
413 export function useTurnItemDetail(
414 target: {
415 readonly environmentId: EnvironmentId;
@@ -409,13 +417,17 @@ export function useTurnItemDetail(
417 readonly itemId: TurnItemId;
418 readonly revision: string;
419 } | null,
420 + source?: TurnItemDetailSource,
421 ) {
413 - return useEnvironmentQuery(
422 + const input =
423 target === null
424 ? null
416 - : orchestrationEnvironment.turnItem({
417 - environmentId: target.environmentId,
418 - input: { threadId: target.threadId, itemId: target.itemId, revision: target.revision },
419 - }),
425 + : { threadId: target.threadId, itemId: target.itemId, revision: target.revision };
426 + return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>(
427 + target === null || input === null
428 + ? null
429 + : source
430 + ? source(input)
431 + : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }),
432 );
433 }
docs/README.md
+1
@@ -19,6 +19,7 @@
19 - [Usage and limits](./user/usage.md)
20 - [Product usage data](./user/telemetry.md)
21 - [Remote access](./user/remote-access.md)
22 +- [Guest links](./user/guest-links.md)
23 - [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md)
24 - [Outside agents (MCP)](./user/outside-agents.md)
25 - [Running in the background](./user/background-service.md)
docs/internals/environment-auth.md
+12
@@ -27,6 +27,18 @@ model. DPoP binds a token to a client's proof key; an invalid proof must fail
27 rather than fall back to bearer authentication. The OAuth token-exchange
28 vocabulary gives these grants a familiar meaning.
29
30 +### Guest links are not sessions
31 +
32 +A [guest link](../user/guest-links.md) gives one browser read access to one
33 +thread and a way to propose messages. Its tokens are HMACs of the thread and
34 +share id under a server key ([GuestShareService](../../apps/server/src/guest/GuestShareService.ts)),
35 +so nothing secret is stored. The share in the thread projection is the only
36 +state: replacing, closing, or archiving it revokes every token, and the
37 +orchestrator's serial commands make redeeming and sending happen once. Guest
38 +tokens never enter `SessionStore`, so no RPC, WebSocket, or MCP path can accept
39 +one. Guest routes also require T3 Connect to still serve the link's hostname;
40 +the request's Host header is not checked, because a LAN client can forge it.
41 +
42 ### MCP clients are a separate audience
43
44 Agents T3 Code did not launch sign in to `/mcp` through a narrow OAuth
docs/user/guest-links.md new
+48
@@ -0,0 +1,48 @@
1 +# Guest links
2 +
3 +A guest link lets a teammate follow one thread in their browser and ask the agent questions, with no
4 +account. They see your messages and the agent's replies as they stream. Each message they send waits
5 +until you send or dismiss it.
6 +
7 +## Share a thread
8 +
9 +Guest links are a beta. Turn on **Settings → Beta → Guest links** for the machine that runs the
10 +thread. They also need [T3 Connect](./remote-access.md): sign in and link that machine, because the
11 +link points at its T3 Connect address. The machine must stay online while the guest uses it.
12 +While the setting is off, every guest link on that machine stops working; links that have not
13 +expired work again when you turn it back on.
14 +
15 +1. Right-click the thread in the sidebar and choose **Share with guest**. It is also in the thread
16 + menu and the command palette.
17 +2. Copy the link and send it to one person. It works in one browser and expires after 24 hours.
18 + Opening it again in that browser takes them back to the thread.
19 +3. When they send a message, it appears at the end of the thread and the sidebar shows **Request**.
20 + Choose **Send** to run it as a normal turn, or **Dismiss**. Files they attached show with the
21 + message, and **Send** includes them.
22 +
23 +Choose **Stop sharing** to end the link at once. Archiving the thread, creating a new link, or
24 +unlinking the machine from T3 Connect also ends it. You can send or dismiss guest messages from the mobile app.
25 +
26 +## What the guest sees
27 +
28 +The guest sees the thread's recent history and everything after, in the same timeline you see, as
29 +it streams: messages and their files, the agent's replies and reasoning, plans, questions, and its
30 +work, with command output when they expand a command. Their composer shows the thread's model, but
31 +they cannot change it. They do not see diffs, and they cannot act on the thread: no forking,
32 +reverting, opening files on your machine, or answering the agent for you.
33 +
34 +Anything the agent read or printed can show, such as a value from a file. Share only threads you
35 +are comfortable showing.
36 +
37 +## Guest attachments
38 +
39 +Guests can attach images and other files to a message: use the paperclip, paste, or drop them on
40 +the message box. A message holds up to 4 files and 10 MB in total. Images must be PNG, JPEG, GIF, or
41 +WebP. While messages wait for you, their files can total 20 MB; the guest can attach more once you
42 +send or dismiss some.
43 +
44 +Dismissing a message, ending the link, or archiving the thread deletes the files of messages that
45 +still wait. A sent message keeps its files, like any message in the thread.
46 +
47 +The guest's text and files run with the thread's current permission mode once you send them. Check
48 +them before you choose **Send**, as you would anything pasted from a chat.
docs/user/thread-sidebar.md
+1 -1
@@ -118,7 +118,7 @@ open.
118
119 ### Fold working threads (beta)
120
121 -Turn on **Settings → General → Working section (beta)** on web and desktop, or **Settings →
121 +Turn on **Settings → Beta → Working section** on web and desktop, or **Settings →
122 Thread behavior → Working section** on iOS and Android, to move threads that are working or
123 waiting on work they will resume from into a collapsed **Working** section below the active list.
124 That includes subagents, watched pull requests, and background commands or monitors the agent
packages/client-runtime/src/operations/commands.ts
+43 -2
@@ -8,7 +8,7 @@ import {
8 OrchestrationV2CheckpointUnavailableError,
9 WS_METHODS,
10 type ChatAttachment,
11 - type MessageId,
11 + MessageId,
12 type ModelSelection,
13 type NodeId,
14 type OrchestrationV2Command,
@@ -26,6 +26,7 @@ import {
26 type ThreadId,
27 type ThreadEnvMode,
28 type UploadChatAttachment,
29 + type GuestMessageId,
30 } from "@t3tools/contracts";
31 import { modelSelectionCommandType } from "@t3tools/shared/model";
32 import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
@@ -418,7 +419,8 @@ function simpleThreadCommand(
419 | "thread.unarchive"
420 | "thread.settle"
421 | "thread.pin"
421 - | "thread.unpin",
422 + | "thread.unpin"
423 + | "thread.guest-share.close",
424 input: ThreadCommandInput,
425 ) {
426 return allocateCommandId(input).pipe(
@@ -432,6 +434,45 @@ export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(functi
434 return yield* simpleThreadCommand("thread.delete", input);
435 });
436
437 +export type CloseGuestShareInput = ThreadCommandInput;
438 +export const closeGuestShare = Effect.fn("EnvironmentCommands.closeGuestShare")(function* (
439 + input: CloseGuestShareInput,
440 +) {
441 + return yield* simpleThreadCommand("thread.guest-share.close", input);
442 +});
443 +
444 +export interface ResolveGuestMessageInput extends ThreadCommandInput {
445 + readonly guestMessageId: GuestMessageId;
446 + readonly decision: "send" | "dismiss";
447 + readonly creationSource?: "web" | "mobile";
448 +}
449 +/** Send runs the guest's text as a normal turn; the server supplies the text, not the client. */
450 +export const resolveGuestMessage = Effect.fn("EnvironmentCommands.resolveGuestMessage")(function* (
451 + input: ResolveGuestMessageInput,
452 +) {
453 + const commandId = yield* allocateCommandId(input);
454 + if (input.decision === "dismiss") {
455 + return yield* dispatch({
456 + type: "thread.guest-message.dismiss",
457 + commandId,
458 + threadId: input.threadId,
459 + guestMessageId: input.guestMessageId,
460 + });
461 + }
462 + return yield* dispatch({
463 + type: "message.dispatch",
464 + commandId,
465 + threadId: input.threadId,
466 + messageId: MessageId.make(commandId),
467 + guestMessageId: input.guestMessageId,
468 + text: "",
469 + attachments: [],
470 + dispatchMode: { type: "queue_after_active" },
471 + createdBy: "user",
472 + creationSource: input.creationSource ?? "web",
473 + });
474 +});
475 +
476 export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
477 input: ArchiveThreadInput,
478 ) {
packages/client-runtime/src/state/models.ts
+3
@@ -156,6 +156,8 @@ export interface EnvironmentThreadShell {
156 readonly hasPendingApprovals: boolean;
157 readonly hasPendingUserInput: boolean;
158 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
159 + /** Guest messages waiting for the owner to send or dismiss. */
160 + readonly pendingGuestMessageCount?: number;
161 readonly hasActionableProposedPlan: boolean;
162 readonly pendingBackgroundTasks: ReadonlyArray<
163 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
@@ -312,6 +314,7 @@ export function presentThreadShell(
314 thread.pendingRuntimeRequest?.kind === "user_input" &&
315 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
316 pendingSubagentRequest,
317 + pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
318 hasActionableProposedPlan: thread.hasActionableProposedPlan,
319 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
320 providerInstanceHistory: thread.providerInstanceHistory ?? [],
packages/client-runtime/src/state/orchestrationV2Projection.ts
+1
@@ -276,6 +276,7 @@ export function applyOrchestrationV2ProjectionEvent(
276 case "thread.interaction-mode-updated":
277 case "thread.model-selection-updated":
278 case "thread.provider-switched":
279 + case "thread.guest-share-updated":
280 return { ...base, thread: event.payload };
281 // Visited tracking is read state, not activity: skip the updatedAt bump.
282 case "thread.visited":
packages/client-runtime/src/state/server.ts
+4
@@ -1336,6 +1336,10 @@ export function createServerEnvironmentAtoms<R, E>(
1336 scheduler: configScheduler,
1337 concurrency: configConcurrency,
1338 }),
1339 + createGuestShare: createEnvironmentRpcCommand(runtime, {
1340 + label: "environment-data:server:guest-share:create",
1341 + tag: WS_METHODS.guestShareCreate,
1342 + }),
1343 // Off the config lane: answering a card must not queue behind settings
1344 // edits. One answer per card at a time.
1345 answerSecretRequest: createEnvironmentRpcCommand(runtime, {
packages/client-runtime/src/state/threadCommands.ts
+16
@@ -47,6 +47,8 @@ import {
47 type StartThreadTurnInput,
48 type StopThreadSessionInput,
49 type UnarchiveThreadInput,
50 + type CloseGuestShareInput,
51 + type ResolveGuestMessageInput,
52 type UnlinkThreadPullRequestInput,
53 type UnpinThreadInput,
54 type WatchThreadPullRequestInput,
@@ -55,6 +57,8 @@ import {
57 type UpdateThreadMetadataInput,
58 type VisitThreadInput,
59 archiveThread,
60 + closeGuestShare,
61 + resolveGuestMessage,
62 cancelQueuedRun,
63 createThread,
64 deleteThread,
@@ -201,6 +205,18 @@ export function createThreadEnvironmentAtoms<R, E>(
205 scheduler,
206 concurrency,
207 }),
208 + closeGuestShare: createEnvironmentCommand(runtime, {
209 + label: "environment-data:commands:thread:close-guest-share",
210 + execute: (input: CloseGuestShareInput) => closeGuestShare(input),
211 + scheduler,
212 + concurrency,
213 + }),
214 + resolveGuestMessage: createEnvironmentCommand(runtime, {
215 + label: "environment-data:commands:thread:resolve-guest-message",
216 + execute: (input: ResolveGuestMessageInput) => resolveGuestMessage(input),
217 + scheduler,
218 + concurrency,
219 + }),
220 archive: createEnvironmentCommand(runtime, {
221 label: "environment-data:commands:thread:archive",
222 execute: (input: ArchiveThreadInput) => archiveThread(input),
packages/client-runtime/src/state/threadSettled.ts
+5
@@ -77,6 +77,7 @@ export interface ThreadSnoozeShell extends QueuedThreadShell {
77 readonly hasPendingApprovals: boolean;
78 readonly hasPendingUserInput: boolean;
79 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
80 + readonly pendingGuestMessageCount?: number;
81 }
82
83 /**
@@ -88,6 +89,7 @@ export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean
89 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
90 if (shell.source?.pendingRuntimeRequest != null) return true;
91 if (shell.pendingSubagentRequest != null) return true;
92 + if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
93 const failedAt = failureEdgeAt(shell);
94 return (
95 failedAt !== undefined &&
@@ -114,6 +116,7 @@ export function canSnooze(
116 | "hasPendingApprovals"
117 | "hasPendingUserInput"
118 | "pendingSubagentRequest"
119 + | "pendingGuestMessageCount"
120 | "latestUserMessageAt"
121 | "latestTurn"
122 | "latestRun"
@@ -127,6 +130,8 @@ export function canSnooze(
130 // The server rejects snoozing even for nonblocking questions.
131 if (shell.source?.pendingRuntimeRequest != null) return false;
132 if (shell.pendingSubagentRequest != null) return false;
133 + // A waiting guest message would wake it at once.
134 + if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
135 if (hasQueuedTurnStart(shell, options)) return false;
136 return true;
137 }
packages/client-runtime/src/state/threadWorkflows.ts
+2 -1
@@ -143,7 +143,8 @@ export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQu
143 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
144 return {
145 run,
146 - text: message?.text ?? "Queued message",
146 + // A queued guest message shows the guest's words; the agent still gets the attributed text.
147 + text: message?.context?.guest?.text ?? message?.text ?? "Queued message",
148 attachments: message?.attachments ?? [],
149 messageId: run.userMessageId,
150 ...(message?.context ? { context: message.context } : {}),
packages/client-runtime/src/userMessage.test.ts
+19
@@ -1,5 +1,7 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 +import { GuestMessageId } from "@t3tools/contracts";
4 +
5 import { resolveUserMessagePresentation } from "./userMessage.ts";
6
7 describe("resolveUserMessagePresentation", () => {
@@ -19,6 +21,23 @@ describe("resolveUserMessagePresentation", () => {
21 }
22 });
23
24 + it("shows a guest's own words and name, not the attributed text the agent reads", () => {
25 + expect(
26 + resolveUserMessagePresentation({
27 + role: "user",
28 + createdBy: "user",
29 + text: "Message from guest Sam, sent by the owner:\n\nWhy?",
30 + context: {
31 + guest: {
32 + guestMessageId: GuestMessageId.make("guest-message:one"),
33 + name: "Sam",
34 + text: "Why?",
35 + },
36 + },
37 + }),
38 + ).toEqual({ text: "Why?", attribution: "guest", scheduledTaskId: undefined, guestName: "Sam" });
39 + });
40 +
41 it("attributes older server-sent restart continuations to T3 Code, not another agent", () => {
42 const text = "Note: the T3 server restarted.";
43 expect(
packages/client-runtime/src/userMessage.ts
+15 -1
@@ -1,4 +1,5 @@
1 import {
2 + type GuestMessageAttribution,
3 type OrchestrationV2Actor,
4 type OrchestrationV2CreationSource,
5 type OrchestrationV2IdleCompaction,
@@ -27,14 +28,27 @@ export function resolveUserMessagePresentation(message: {
28 readonly createdBy?: OrchestrationV2Actor;
29 readonly creationSource?: OrchestrationV2CreationSource;
30 readonly scheduledTaskId?: ScheduledTaskId;
31 + readonly context?: { readonly guest?: GuestMessageAttribution | undefined } | undefined;
32 }): {
33 readonly text: string;
32 - readonly attribution: "automation" | "agent" | "t3code" | null;
34 + readonly attribution: "automation" | "agent" | "t3code" | "guest" | null;
35 readonly scheduledTaskId: ScheduledTaskId | undefined;
36 + /** Set when `attribution` is "guest". */
37 + readonly guestName?: string;
38 } {
39 if (message.role !== "user") {
40 return { text: message.text, attribution: null, scheduledTaskId: undefined };
41 }
42 + // The stored text names the guest for the agent; people see the guest's own words.
43 + const guest = message.context?.guest;
44 + if (guest !== undefined) {
45 + return {
46 + text: guest.text,
47 + attribution: "guest",
48 + scheduledTaskId: undefined,
49 + guestName: guest.name,
50 + };
51 + }
52 if (message.scheduledTaskId !== undefined) {
53 return {
54 text: message.text,
packages/contracts/src/baseSchemas.ts
+4
@@ -279,6 +279,10 @@ export const RunAttemptId = makeEntityId("RunAttemptId");
279 export type RunAttemptId = typeof RunAttemptId.Type;
280 export const NodeId = makeEntityId("NodeId");
281 export type NodeId = typeof NodeId.Type;
282 +export const GuestShareId = makeEntityId("GuestShareId");
283 +export type GuestShareId = typeof GuestShareId.Type;
284 +export const GuestMessageId = makeEntityId("GuestMessageId");
285 +export type GuestMessageId = typeof GuestMessageId.Type;
286 export const AuthSessionId = makeEntityId("AuthSessionId");
287 export type AuthSessionId = typeof AuthSessionId.Type;
288 export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
packages/contracts/src/clientRpcPermissions.ts
+3
@@ -1,6 +1,7 @@
1 import * as Schema from "effect/Schema";
2 import { GitPreparePullRequestThreadInput, GitRunStackedActionInput } from "./git.ts";
3 import {
4 + AuthAccessWriteScope,
5 AuthOrchestrationOperateScope,
6 AuthOrchestrationReadScope,
7 AuthPreviewOperateScope,
@@ -49,6 +50,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
50 [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope,
51 [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope,
52 [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,
53 + // A guest link hands thread access to someone outside, like a pairing link.
54 + [WS_METHODS.guestShareCreate]: AuthAccessWriteScope,
55 } as const;
56 export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;
57
packages/contracts/src/composerContext.ts
+17
@@ -3,11 +3,14 @@ import * as Schema from "effect/Schema";
3 import {
4 EnvironmentId,
5 ForwardCompatibleArray,
6 + GuestMessageId,
7 + GuestShareId,
8 NonNegativeInt,
9 PositiveInt,
10 ThreadId,
11 TrimmedNonEmptyString,
12 } from "./baseSchemas.ts";
13 +import { GUEST_MESSAGE_MAX_LENGTH, GUEST_NAME_MAX_LENGTH } from "./guestShare.ts";
14
15 /**
16 * Bytes never live here: image and file records bind to a `ChatAttachment` by id.
@@ -258,9 +261,23 @@ export type ComposerContextRecord = typeof ComposerContextRecord.Type;
261 export const COMPOSER_CONTEXT_MAX_RECORDS = 200;
262 const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000;
263
264 +/**
265 + * Marks a user message as a guest's, sent by the owner. The message `text` keeps the attributed
266 + * form the agent reads; clients show `text` here with `name` beside it. Only the server sets it.
267 + */
268 +export const GuestMessageAttribution = Schema.Struct({
269 + guestMessageId: GuestMessageId,
270 + name: TrimmedNonEmptyString.check(Schema.isMaxLength(GUEST_NAME_MAX_LENGTH)),
271 + text: Schema.String.check(Schema.isMaxLength(GUEST_MESSAGE_MAX_LENGTH)),
272 + /** The link the guest used. Only that link's guest may load the message's files. */
273 + shareId: Schema.optional(GuestShareId),
274 +});
275 +export type GuestMessageAttribution = typeof GuestMessageAttribution.Type;
276 +
277 /** Structured context riding on a user message. Undecodable records are dropped, not fatal. */
278 export const OrchestrationMessageContext = Schema.Struct({
279 version: Schema.Literal(1),
280 + guest: Schema.optional(GuestMessageAttribution),
281 records: Schema.Array(Schema.Unknown)
282 .check(
283 Schema.isMaxLength(COMPOSER_CONTEXT_MAX_RECORDS),
packages/contracts/src/guestShare.test.ts new
+22
@@ -0,0 +1,22 @@
1 +import * as Schema from "effect/Schema";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { GuestRedeemRequest } from "./guestShare.ts";
5 +
6 +const isRedeem = Schema.is(GuestRedeemRequest);
7 +
8 +describe("GuestRedeemRequest", () => {
9 + it("accepts a one-line name and rejects names that break the attribution line", () => {
10 + expect(isRedeem({ credential: "invite", name: "Maya Chen" })).toBe(true);
11 + for (const name of [
12 + "Maya\nowner",
13 + "Maya
owner",
14 + "Maya
owner",
15 + "Maya\u0007",
16 + "Theo\u202E (owner)",
17 + "Theo\u2066x",
18 + ]) {
19 + expect(isRedeem({ credential: "invite", name })).toBe(false);
20 + }
21 + });
22 +});
packages/contracts/src/guestShare.ts new
+138
@@ -0,0 +1,138 @@
1 +import * as Schema from "effect/Schema";
2 +
3 +import { ChatAttachment } from "./chatAttachment.ts";
4 +import {
5 + GuestMessageId,
6 + GuestShareId,
7 + IsoDateTime,
8 + ThreadId,
9 + TrimmedNonEmptyString,
10 + TrimmedString,
11 +} from "./baseSchemas.ts";
12 +
13 +/**
14 + * A guest share lets one unauthenticated browser watch a thread over T3 Connect and propose
15 + * messages the owner must send or dismiss. The thread projection holds this public state; the
16 + * credentials are derived from the share id with a server key and never stored.
17 + */
18 +export const GUEST_SHARE_TTL_MS = 24 * 60 * 60 * 1000;
19 +export const GUEST_MESSAGE_MAX_LENGTH = 4_000;
20 +export const GUEST_NAME_MAX_LENGTH = 40;
21 +export const GUEST_PENDING_MESSAGE_LIMIT = 3;
22 +/** Resolved messages kept so the guest can see what happened to what they sent. */
23 +export const GUEST_RESOLVED_MESSAGE_LIMIT = 20;
24 +/** Files a guest can attach to one message, and their total size. */
25 +export const GUEST_MESSAGE_MAX_ATTACHMENTS = 4;
26 +export const GUEST_MESSAGE_MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
27 +/** Total size of the files in a share's waiting messages, so a guest cannot fill the disk. */
28 +export const GUEST_PENDING_ATTACHMENT_BYTES_LIMIT = 20 * 1024 * 1024;
29 +
30 +export const ThreadGuestMessageStatus = Schema.Literals(["pending", "sent", "dismissed"]);
31 +export type ThreadGuestMessageStatus = typeof ThreadGuestMessageStatus.Type;
32 +
33 +export const ThreadGuestMessage = Schema.Struct({
34 + id: GuestMessageId,
35 + text: Schema.String,
36 + status: ThreadGuestMessageStatus,
37 + submittedAt: IsoDateTime,
38 + /** The thread's attachments, deleted if the message is dismissed. Absent on older messages. */
39 + attachments: Schema.optional(Schema.Array(ChatAttachment)),
40 +});
41 +export type ThreadGuestMessage = typeof ThreadGuestMessage.Type;
42 +
43 +export const ThreadGuestShare = Schema.Struct({
44 + id: GuestShareId,
45 + /** The T3 Connect tunnel hostname the link points at. Guest routes require it to still serve. */
46 + host: TrimmedNonEmptyString,
47 + createdAt: IsoDateTime,
48 + expiresAt: IsoDateTime,
49 + /** Set once, when the guest redeems the link. */
50 + guestName: Schema.NullOr(TrimmedNonEmptyString),
51 + messages: Schema.Array(ThreadGuestMessage),
52 +});
53 +export type ThreadGuestShare = typeof ThreadGuestShare.Type;
54 +
55 +export const pendingGuestMessageCount = (share: ThreadGuestShare | null | undefined): number =>
56 + share?.messages.filter((message) => message.status === "pending").length ?? 0;
57 +
58 +export const GuestShareCreateInput = Schema.Struct({ threadId: ThreadId });
59 +export type GuestShareCreateInput = typeof GuestShareCreateInput.Type;
60 +
61 +export const GuestShareCreateResult = Schema.Struct({
62 + url: TrimmedNonEmptyString,
63 + share: ThreadGuestShare,
64 +});
65 +export type GuestShareCreateResult = typeof GuestShareCreateResult.Type;
66 +
67 +const GUEST_SHARE_CREATE_MESSAGES = {
68 + disabled: "Guest links are off. Turn them on in Settings > Beta.",
69 + connect_unavailable: "Guest links need a running T3 Connect tunnel.",
70 + thread_unavailable: "This thread cannot be shared.",
71 + read_failed: "Failed to read the shared thread.",
72 + changed: "The guest link changed while it was being created.",
73 +} as const;
74 +
75 +export class GuestShareCreateError extends Schema.TaggedError<GuestShareCreateError>()(
76 + "GuestShareCreateError",
77 + {
78 + reason: Schema.Literals([
79 + "disabled",
80 + "connect_unavailable",
81 + "thread_unavailable",
82 + "read_failed",
83 + "changed",
84 + ]),
85 + },
86 +) {
87 + override get message(): string {
88 + return GUEST_SHARE_CREATE_MESSAGES[this.reason];
89 + }
90 +}
91 +
92 +// The name lands in the agent's attribution line, so it must stay one plain line, and the owner
93 +// reads it, so direction overrides cannot make it look like another name.
94 +const NAME_BREAKING_CHARACTER = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/u;
95 +
96 +export const GuestRedeemRequest = Schema.Struct({
97 + credential: TrimmedNonEmptyString,
98 + name: TrimmedNonEmptyString.check(
99 + Schema.isMaxLength(GUEST_NAME_MAX_LENGTH),
100 + Schema.makeFilter((name) => !NAME_BREAKING_CHARACTER.test(name), {
101 + description: "a single line of text",
102 + }),
103 + ),
104 +});
105 +export type GuestRedeemRequest = typeof GuestRedeemRequest.Type;
106 +
107 +/**
108 + * The fields of a guest message. The page posts them as multipart form data, with each file as a
109 + * `file` part; text can be empty when files are attached.
110 + */
111 +export const GuestSubmitRequest = Schema.Struct({
112 + /** The share the page shows, so a message from a page for a replaced link is refused instead
113 + of reaching the new one. */
114 + shareId: GuestShareId,
115 + text: TrimmedString.check(Schema.isMaxLength(GUEST_MESSAGE_MAX_LENGTH)),
116 +});
117 +export type GuestSubmitRequest = typeof GuestSubmitRequest.Type;
118 +
119 +export const GUEST_ROUTE_PREFIX = "/api/guest";
120 +/** The guest page and guest routes name the share they mean with this query parameter. */
121 +export const GUEST_SHARE_PARAM = "share";
122 +
123 +/**
124 + * One session cookie per share, so a guest keeps every link they joined on a host, and a page
125 + * for one share never acts with another share's session.
126 + */
127 +export const guestSessionCookieName = (shareId: string) => `t3_guest_${shareId}`;
128 +/** Serves one HTML render in the shared thread: `?share=<share id>&item=<turn item id>`. */
129 +export const GUEST_RENDER_ROUTE = `${GUEST_ROUTE_PREFIX}/render`;
130 +/** One item of the shared thread, as an expanded row loads it: `?share=<share id>&item=<id>`. */
131 +export const GUEST_ITEM_ROUTE = `${GUEST_ROUTE_PREFIX}/item`;
132 +/** Server-sent output frames of one command in the shared thread: `?share=<share id>&item=<id>`. */
133 +export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output`;
134 +/**
135 + * A file in the shared thread or a guest's waiting message: `?share=<share id>&id=<attachment id>`.
136 + * Images load inline; other files download.
137 + */
138 +export const GUEST_ATTACHMENT_ROUTE = `${GUEST_ROUTE_PREFIX}/attachment`;
packages/contracts/src/guestStream.ts new
+42
@@ -0,0 +1,42 @@
1 +import * as Schema from "effect/Schema";
2 +
3 +import { GuestShareId, IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas.ts";
4 +import { ThreadGuestMessage } from "./guestShare.ts";
5 +import { OrchestrationV2ThreadStreamItem } from "./orchestrationV2.ts";
6 +import { ProviderDriverKind } from "./providerInstance.ts";
7 +
8 +// This lives apart from guestShare.ts because orchestrationV2.ts imports that file.
9 +
10 +/**
11 + * What the composer's model label shows; nothing else from the owner's provider settings. The
12 + * driver is null when the thread's provider is no longer configured.
13 + */
14 +export const GuestThreadModel = Schema.Struct({
15 + driver: Schema.NullOr(ProviderDriverKind),
16 + name: TrimmedNonEmptyString,
17 + shortName: Schema.optional(TrimmedNonEmptyString),
18 + subProvider: Schema.optional(TrimmedNonEmptyString),
19 +});
20 +export type GuestThreadModel = typeof GuestThreadModel.Type;
21 +
22 +export const GuestShareView = Schema.Struct({
23 + shareId: GuestShareId,
24 + title: Schema.String,
25 + guestName: TrimmedNonEmptyString,
26 + expiresAt: IsoDateTime,
27 + messages: Schema.Array(ThreadGuestMessage),
28 + model: GuestThreadModel,
29 +});
30 +export type GuestShareView = typeof GuestShareView.Type;
31 +
32 +/**
33 + * The shared thread as the owner's client gets it: `thread` carries the same stream items the
34 + * owner's thread subscription sends, starting with a snapshot on every (re)connect. `view` is the
35 + * share itself, sent first and again when it changes.
36 + */
37 +export const GuestStreamEvent = Schema.Union([
38 + Schema.Struct({ type: Schema.Literal("view"), view: GuestShareView }),
39 + Schema.Struct({ type: Schema.Literal("thread"), item: OrchestrationV2ThreadStreamItem }),
40 + Schema.Struct({ type: Schema.Literal("ended") }),
41 +]);
42 +export type GuestStreamEvent = typeof GuestStreamEvent.Type;
packages/contracts/src/index.ts
+2
@@ -37,6 +37,8 @@ export * from "./pullRequestReviewGuide.ts";
37 export * from "./orchestrationDispatch.ts";
38 export * from "./orchestrationProject.ts";
39 export * from "./orchestrationV2.ts";
40 +export * from "./guestShare.ts";
41 +export * from "./guestStream.ts";
42 export * from "./applicationEvent.ts";
43 export * from "./orchestratorMcp.ts";
44 export * from "./threadMetadataMcp.ts";
packages/contracts/src/orchestrationV2.ts
+46
@@ -13,6 +13,8 @@ import {
13 ContextHandoffId,
14 ContextTransferId,
15 EventId,
16 + GuestMessageId,
17 + GuestShareId,
18 IsoDateTime,
19 MessageId,
20 NodeId,
@@ -37,6 +39,7 @@ import {
39 TurnItemId,
40 } from "./baseSchemas.ts";
41 import { ChatAttachment } from "./chatAttachment.ts";
42 +import { ThreadGuestShare } from "./guestShare.ts";
43 import {
44 OrchestrationGetFullThreadDiffInput,
45 OrchestrationGetFullThreadDiffResult,
@@ -434,6 +437,7 @@ export const OrchestrationV2AppThread = Schema.Struct({
437 snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
438 lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
439 limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)),
440 + guestShare: Schema.optional(Schema.NullOr(ThreadGuestShare)),
441 pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
442 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
443 pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
@@ -1704,6 +1708,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([
1708 "thread.interaction-mode-updated",
1709 "thread.model-selection-updated",
1710 "thread.provider-switched",
1711 + "thread.guest-share-updated",
1712 ]),
1713 payload: OrchestrationV2AppThread,
1714 }),
@@ -1918,6 +1923,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
1923 lastErrorCode: Schema.optional(Schema.NullOr(Schema.String)),
1924 usageLimitResetAt: Schema.optional(Schema.NullOr(IsoDateTime)),
1925 pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary),
1926 + /** Guest messages waiting for the owner to send or dismiss. Absent from older servers. */
1927 + pendingGuestMessageCount: Schema.optional(NonNegativeInt),
1928 latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary),
1929 latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc),
1930 /**
@@ -2551,6 +2558,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
2558 "thread.interaction-mode-updated",
2559 "thread.model-selection-updated",
2560 "thread.provider-switched",
2561 + "thread.guest-share-updated",
2562 ]),
2563 payload: OrchestrationV2AppThreadJson,
2564 }),
@@ -2714,6 +2722,17 @@ export const OrchestrationV2Command = Schema.Union([
2722 commandId: CommandId,
2723 threadId: ThreadId,
2724 }),
2725 + Schema.Struct({
2726 + type: Schema.Literal("thread.guest-share.close"),
2727 + commandId: CommandId,
2728 + threadId: ThreadId,
2729 + }),
2730 + Schema.Struct({
2731 + type: Schema.Literal("thread.guest-message.dismiss"),
2732 + commandId: CommandId,
2733 + threadId: ThreadId,
2734 + guestMessageId: GuestMessageId,
2735 + }),
2736 Schema.Struct({
2737 type: Schema.Literal("thread.unarchive"),
2738 commandId: CommandId,
@@ -2908,6 +2927,8 @@ export const OrchestrationV2Command = Schema.Union([
2927 Schema.Struct({
2928 type: Schema.Literal("message.dispatch"),
2929 notification: Schema.optional(OrchestrationV2Notification),
2930 + /** Sends this pending guest message; the server uses the guest's text, not `text`. */
2931 + guestMessageId: Schema.optional(GuestMessageId),
2932 ...OrchestrationV2CreationFields,
2933 scheduledTaskId: Schema.optional(ScheduledTaskId),
2934 senderThreadId: Schema.optional(ThreadId),
@@ -3139,6 +3160,31 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type;
3160 * send them.
3161 */
3162 const OrchestrationV2InternalCommand = Schema.Union([
3163 + // Guest share commands the server issues after checking T3 Connect and the guest token.
3164 + Schema.Struct({
3165 + type: Schema.Literal("thread.guest-share.open"),
3166 + commandId: CommandId,
3167 + threadId: ThreadId,
3168 + shareId: GuestShareId,
3169 + host: TrimmedNonEmptyString,
3170 + expiresAt: IsoDateTime,
3171 + }),
3172 + Schema.Struct({
3173 + type: Schema.Literal("thread.guest-share.redeem"),
3174 + commandId: CommandId,
3175 + threadId: ThreadId,
3176 + shareId: GuestShareId,
3177 + guestName: TrimmedNonEmptyString,
3178 + }),
3179 + Schema.Struct({
3180 + type: Schema.Literal("thread.guest-message.submit"),
3181 + commandId: CommandId,
3182 + threadId: ThreadId,
3183 + shareId: GuestShareId,
3184 + guestMessageId: GuestMessageId,
3185 + text: Schema.String,
3186 + attachments: Schema.optional(Schema.Array(ChatAttachment)),
3187 + }),
3188 Schema.Struct({
3189 type: Schema.Literal("thread.pull-request-watch.sync"),
3190 commandId: CommandId,
packages/contracts/src/rpc.ts
+13
@@ -161,6 +161,11 @@ import {
161 ProviderUploadFeedbackResult,
162 } from "./provider.ts";
163 import { ProviderInstanceId, ProviderInstanceMutation } from "./providerInstance.ts";
164 +import {
165 + GuestShareCreateError,
166 + GuestShareCreateInput,
167 + GuestShareCreateResult,
168 +} from "./guestShare.ts";
169 import { PullRequestReviewGuideResult } from "./pullRequestReviewGuide.ts";
170 import {
171 PullRequestActionInput,
@@ -520,6 +525,7 @@ export const WS_METHODS = {
525 scheduledTasksRunNow: "scheduledTasks.runNow",
526 scheduledTasksRotateWebhookToken: "scheduledTasks.rotateWebhookToken",
527 secretsAnswerRequest: "secrets.answerRequest",
528 + guestShareCreate: "guestShare.create",
529 scheduledTasksListWebhookDeliveries: "scheduledTasks.listWebhookDeliveries",
530 scheduledTasksGetWebhookDelivery: "scheduledTasks.getWebhookDelivery",
531
@@ -1854,6 +1860,12 @@ const WsScheduledTasksRotateWebhookTokenRpc = Rpc.make(
1860 },
1861 );
1862
1863 +const WsGuestShareCreateRpc = Rpc.make(WS_METHODS.guestShareCreate, {
1864 + payload: GuestShareCreateInput,
1865 + success: GuestShareCreateResult,
1866 + error: Schema.Union([GuestShareCreateError, EnvironmentAuthorizationError]),
1867 +});
1868 +
1869 const WsSecretsAnswerRequestRpc = Rpc.make(WS_METHODS.secretsAnswerRequest, {
1870 payload: SecretRequestAnswerInput,
1871 error: Schema.Union([SecretRequestError, EnvironmentAuthorizationError]),
@@ -1904,6 +1916,7 @@ export class RpcScopeAuthorization extends RpcMiddleware.Service<RpcScopeAuthori
1916 ) {}
1917
1918 export const WsRpcGroup = RpcGroup.make(
1919 + WsGuestShareCreateRpc,
1920 WsServerProbeRpc,
1921 WsServerGetConfigRpc,
1922 WsServerRefreshProvidersRpc,
packages/contracts/src/settings.ts
+3
@@ -1204,6 +1204,8 @@ export const ServerSettings = Schema.Struct({
1204 idleCompaction: Schema.optionalKey(IdleCompactionMode),
1205 snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1206 autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1207 + /** Beta: guest links for this machine's threads. Off refuses new links and pauses existing ones. */
1208 + guestSharingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1209 sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(
1210 Schema.withDecodingDefault(Effect.succeed(false)),
1211 ),
@@ -1572,6 +1574,7 @@ export const ServerSettingsPatch = Schema.Struct({
1574 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
1575 autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),
1576 snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean),
1577 + guestSharingEnabled: Schema.optionalKey(Schema.Boolean),
1578 backgroundActivity: Schema.optionalKey(
1579 Schema.Struct({
1580 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
packages/provider-core/src/server/subagentProjection.ts
+2
@@ -82,6 +82,8 @@ export function makeSubagentChildThread(input: {
82 settledAt: null,
83 snoozedUntil: null,
84 snoozedAt: null,
85 + // A guest link belongs to the thread it was made for.
86 + guestShare: null,
87 lastVisitedAt: null,
88 deletedAt: null,
89 };