diff --git a/.agents/skills/test-t3-app/references/feature-map.md b/.agents/skills/test-t3-app/references/feature-map.md index 5f782ae36ab5a..106a343211f2c 100644 --- a/.agents/skills/test-t3-app/references/feature-map.md +++ b/.agents/skills/test-t3-app/references/feature-map.md @@ -37,7 +37,7 @@ Code: apps/web/src/components/sidebar/ - **sidebar.working-section** — collapsed "Working" section for threads busy with background work. Turn off in **Settings → General → Working section**. - **sidebar.snoozed-shelf** — "Snoozed" threads, hidden until their wake time. - **sidebar.settled-shelf** — "Settled" finished threads. Drag a thread onto the header to settle it. -- **sidebar.bots-group** — "Bots" group for standing bot threads. +- **sidebar.bots-group** — "My Bots" and "Shared Bots" groups for standing bot threads. Shared bots are the ones filed to the Shared inbox. - **sidebar.project-folder** — per-project folders when **Settings → Labs → Boring sidebar (group by project)** is on; "Pin project" / "Unpin project", "Project settings". - **sidebar.thread-row** — one thread: title, status, PR badge, hover actions. Click opens `/$environmentId/$threadId`. Drop files on it to attach them. - **sidebar.thread-status** — row status labels: "Working", "Waiting", "Needs you", "Needs action", "Usage limit reached", "Failed", "Woke", "Unsent draft". diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index d4501cf2d9503..b731160f6d7d3 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -26,7 +26,6 @@ import * as Cause from "effect/Cause"; import { AsyncResult, Atom } from "effect/reactivity"; import { createDebugLogger } from "../lib/debugLog"; -import { buildSeenMarker } from "@t3tools/client-runtime/seen-marker"; import { scopedThreadKey } from "../lib/scopedEntities"; import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn"; import { serializeComposerMessageForServer, uploadedComposerContext } from "../lib/composerContext"; @@ -948,9 +947,6 @@ export function createThreadOutboxDelivery(): { if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) return true; } if (!hasAccess()) return true; - const seenMarker = buildSeenMarker( - scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId), - ); const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { environmentId: queuedMessage.environmentId, input: { @@ -980,7 +976,6 @@ export function createThreadOutboxDelivery(): { createdAt: queuedMessage.createdAt, dispatchMode: queuedMessage.dispatchMode ?? "start", ...(queuedMessage.freshContext ? { freshContext: true } : {}), - ...(seenMarker ? { seenMarker } : {}), resendAfterSocketLoss: false, }, }); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ad3cce997779b..ffdadd4060e33 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6,7 +6,14 @@ import type { OrchestrationV2ThreadHistoryPage, ProjectId, } from "@t3tools/contracts"; -import { makeThreadInbox, routeThreadInbox, type ThreadInbox } from "@t3tools/contracts"; +import { + makeThreadInbox, + nextFounderSeenMessage, + nextFounderVisits, + rewindFounderVisit, + routeThreadInbox, + type ThreadInbox, +} from "@t3tools/contracts"; import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; import { latestExecutedRun, @@ -3937,6 +3944,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const movesForward = thread.lastVisitedAt === null || DateTime.toEpochMillis(visitedAt.value) > DateTime.toEpochMillis(thread.lastVisitedAt); + // A named founder on a shared thread moves only their unread cursor. The shared watermark + // stays, so the other founder's unread mark does not clear. The message they were shown is + // stored for any named founder and still starts no turn. + const namedFounder = command.founder; + const sharedFounder = + namedFounder !== undefined && thread.inbox?.audience === "shared" ? namedFounder : null; + const nextVisits = + sharedFounder === null + ? undefined + : nextFounderVisits(thread, sharedFounder, visitedAt.value); + const founderMoved = nextVisits !== undefined && nextVisits !== thread.visitsByFounder; + const nextSeen = + namedFounder === undefined || command.lastSeenMessageId === undefined + ? undefined + : nextFounderSeenMessage(thread, namedFounder, command.lastSeenMessageId); + const seenMoved = nextSeen !== undefined && nextSeen !== thread.seenMessageByFounder; + const globalMoves = sharedFounder === null && movesForward; const occurredAt = yield* DateTime.now; // Opens are timed by the server clock so devices with skewed clocks agree. const opens = command.opened @@ -3946,7 +3970,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.searchQuery, ) : null; - if (!movesForward && opens === null) return; + if (!globalMoves && !founderMoved && !seenMoved && opens === null) return; // Viewing a thread changes read state only. Loading its transcript, bumping // updatedAt, or copying the thread into the event makes a read receipt scale with it. yield* emit( @@ -3958,8 +3982,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: thread.providerInstanceId, occurredAt, payload: { - lastVisitedAt: movesForward ? visitedAt.value : thread.lastVisitedAt, + lastVisitedAt: globalMoves ? visitedAt.value : thread.lastVisitedAt, ...(opens ? { opens } : {}), + ...(founderMoved && nextVisits !== undefined ? { visitsByFounder: nextVisits } : {}), + ...(seenMoved && nextSeen !== undefined ? { seenMessageByFounder: nextSeen } : {}), }, }); }); @@ -4884,12 +4910,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const snoozeExpired = thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) <= DateTime.toEpochMillis(now); + const snoozeClear = snoozeExpired + ? { snoozedUntil: null, snoozedAt: null, lastSnoozeWakeAt: thread.snoozedUntil } + : {}; + // A named founder marking a shared thread unread rewinds only their cursor. + if ( + command.founder !== undefined && + thread.inbox?.audience === "shared" && + markUnreadVisitedAt !== null + ) { + return { + ...thread, + visitsByFounder: rewindFounderVisit(thread, command.founder, markUnreadVisitedAt), + ...snoozeClear, + }; + } return { ...thread, lastVisitedAt: markUnreadVisitedAt, - ...(snoozeExpired - ? { snoozedUntil: null, snoozedAt: null, lastSnoozeWakeAt: thread.snoozedUntil } - : {}), + ...snoozeClear, }; } case "thread.metadata.update": { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 06ff339bac6b5..ec80c05040283 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1928,6 +1928,12 @@ export function threadShellFromProjection( ...(projection.thread.tags?.length ? { tags: projection.thread.tags } : {}), ...(projection.thread.standing ? { standing: projection.thread.standing } : {}), lastVisitedAt: projection.thread.lastVisitedAt, + ...(projection.thread.visitsByFounder === undefined + ? {} + : { visitsByFounder: projection.thread.visitsByFounder }), + ...(projection.thread.seenMessageByFounder === undefined + ? {} + : { seenMessageByFounder: projection.thread.seenMessageByFounder }), opens: projection.thread.opens ?? null, titleRegeneration: projection.thread.titleRegeneration ?? null, lastTitleRegeneration: projection.thread.lastTitleRegeneration ?? null, diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 69c8e4577bbbf..8276c7aa58aa6 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -1,5 +1,5 @@ import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; -import { formatSeenMarkerForProvider } from "@t3tools/shared/seenMarker"; +import { formatSeenMarkerForProvider, formatSharedSenderForProvider } from "@t3tools/shared/seenMarker"; import { MessageId, type ModelSelection, @@ -437,6 +437,7 @@ export const layer: Layer.Layer< const loaded = yield* load({ ...input, operation: "steer" }); if (Option.isNone(loaded.session)) return; const { message, run } = loaded.context; + const { thread } = yield* projections.getThreadRecords(input.threadId, []); if (message === undefined || run === undefined) { return yield* new ProviderTurnControlError({ threadId: input.threadId, @@ -457,11 +458,15 @@ export const layer: Layer.Layer< message: { messageId: message.id, text: formatSeenMarkerForProvider( - projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }), + formatSharedSenderForProvider( + projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }), + thread.inbox?.audience === "shared" ? (message.sentBy?.founder ?? null) : null, + ), message.seenMarker, + thread.inbox?.audience === "shared" ? (message.sentBy?.founder ?? null) : null, ), attachments: message.attachments, createdBy: message.createdBy, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index afbe74a9a1784..91912a7e41ef9 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1,6 +1,6 @@ import { modelSelectionsEqual } from "@t3tools/shared/model"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; -import { formatSeenMarkerForProvider } from "@t3tools/shared/seenMarker"; +import { formatSeenMarkerForProvider, formatSharedSenderForProvider } from "@t3tools/shared/seenMarker"; import { CommandId, latestProviderTurnForAttempt, @@ -911,12 +911,18 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; + const sharedFounder = + projection.thread.inbox?.audience === "shared" ? (providerMessage.sentBy?.founder ?? null) : null; const userText = formatSeenMarkerForProvider( - projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }), + formatSharedSenderForProvider( + projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }), + sharedFounder, + ), providerMessage.seenMarker, + sharedFounder, ); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index f40c62181701d..9a8fdf2f9f007 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2,6 +2,7 @@ import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { creditUnassignedSender } from "@t3tools/shared/seenMarker"; import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -2030,6 +2031,20 @@ export const layerWsRpc = ( return yield* mutateProjectWithClone(projectService, projectCloneTracker, mutation); }); + // A session names a person only when another client assigned it. A person's unassigned + // client credits this machine's owner; a bot never does, and a null owner stays unnamed. + const messageSender = serverAuth.messageSenderOf(currentSessionId).pipe( + Effect.filterOrElse( + (sentBy) => sentBy.founder !== null || sentBy.deviceType === "bot", + (sentBy) => + serverSettings.getSettings.pipe( + Effect.map((settings) => creditUnassignedSender(sentBy, settings.ownerFounder)), + // A settings read must not fail the send. Leave the sender unassigned. + Effect.orElseSucceed(() => sentBy), + ), + ), + ); + const handlers = ServerWsRpcGroup.of({ [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => Effect.annotateCurrentSpan({ @@ -2049,15 +2064,15 @@ export const layerWsRpc = ( ? { "orchestration_v2.source_thread_id": command.sourceThreadId } : {}), }).pipe( - Effect.andThen( - startup + Effect.andThen(() => { + const dispatched = startup .enqueueCommand( (command.type === "prepared-run.retry" ? threadLaunch.retryPreparation(command) : (command.type === "message.dispatch" || command.type === "queued-run.edit" || command.type === "runtime-request.respond" - ? serverAuth.messageSenderOf(currentSessionId).pipe(Effect.asSome) + ? messageSender.pipe(Effect.asSome) : Effect.succeed(Option.none()) ).pipe( Effect.flatMap((sentBy) => @@ -2091,8 +2106,23 @@ export const layerWsRpc = ( cause, }); }), + ); + // A bot reading a thread writes no visit. A sender lookup that fails still records + // the visit, matching a client the server cannot name. + if (command.type !== "thread.visit") return dispatched; + return messageSender.pipe( + Effect.map((sentBy) => sentBy.deviceType === "bot"), + Effect.orElseSucceed(() => false), + Effect.flatMap((bot) => + bot + ? applicationEvents.latestApplicationSequence.pipe( + Effect.map((sequence) => ({ sequence })), + Effect.orElseSucceed(() => ({ sequence: 0 })), + ) + : dispatched, ), - ), + ); + }), ), [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input), [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: (input) => @@ -2259,9 +2289,7 @@ export const layerWsRpc = ( }) .pipe( Effect.andThen( - input.initialMessage === undefined - ? Effect.undefined - : serverAuth.messageSenderOf(currentSessionId), + input.initialMessage === undefined ? Effect.undefined : messageSender, ), Effect.flatMap((sentBy) => ThreadMessageIntake.launchThread({ diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index e528246e7aea1..0ce45ce9227e0 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1,5 +1,9 @@ import { toServerClock } from "@t3tools/client-runtime/clock"; -import { type OrchestrationV2ProviderTurn, type RunAttemptId } from "@t3tools/contracts"; +import { + type Founder, + type OrchestrationV2ProviderTurn, + type RunAttemptId, +} from "@t3tools/contracts"; import { deriveLatestThreadRun, deriveThreadRuntime, @@ -1459,6 +1463,7 @@ export function presentThreadShellFromProjection( readonly updatedAt: ThreadProjection["updatedAt"]; readonly lastVisitedAt: ThreadProjection["thread"]["lastVisitedAt"]; }, + viewer: Founder | null = null, ) { const { updatedAt, lastVisitedAt } = live; const latestRun = deriveLatestThreadRun(projection); @@ -1494,7 +1499,7 @@ export function presentThreadShellFromProjection( itemCount: projection.turnItems.length, visibleItemCount: projection.visibleTurnItems.length, updatedAt, - }), + }, null, viewer), latestRun, runtime, }; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 50ee2cf4aa0ee..c66eaafb5ea23 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -78,6 +78,7 @@ import { type ServerProvider, type ScopedThreadRef, type ThreadId, + type ThreadSeenMarker, ProviderInteractionMode, resolveIdleCompaction, RuntimeMode, @@ -120,7 +121,7 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { type SeenMessage } from "@t3tools/client-runtime/seen-marker"; +import { CATCH_ME_UP_TEXT, type SeenMessage } from "@t3tools/client-runtime/seen-marker"; import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model"; import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -287,6 +288,7 @@ import { useThreadCheckpointSummaries, } from "../state/entities"; import { useEnvironmentShellHasSnapshot } from "../state/shell"; +import { CatchMeUpControl } from "./chat/CatchMeUpControl"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog"; @@ -405,9 +407,7 @@ import { makeThreadErrorSetter, } from "./ChatView.logic"; -const activityCollapsedThreadsSchema = Schema.NullOr( - Schema.Record(Schema.String, Schema.Boolean), -); +const activityCollapsedThreadsSchema = Schema.NullOr(Schema.Record(Schema.String, Schema.Boolean)); const EMPTY_SEEN_MESSAGES: ReadonlyArray = []; const EMPTY_PROVIDERS: ServerProvider[] = []; @@ -503,6 +503,9 @@ export default function ChatView(props: ChatViewProps) { const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false, }); + const visitThread = useOrchestrationCommand(threadEnvironment.visit, { + reportFailure: false, + }); const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false, refresh: true, @@ -537,16 +540,23 @@ export default function ChatView(props: ChatViewProps) { const serverThreadProjection = useQuietThreadProjection(routeThreadDetailRef); const serverProjection = serverThreadProjection?.projection ?? null; // Only the shell-less fallback needs these; with a shell, the shell carries them. + const viewerFounder = useClientSettings((settings) => settings.founderInboxOwner ?? null); const fallbackDetailRef = serverThreadShell === null ? routeThreadDetailRef : null; const fallbackUpdatedAt = useThreadUpdatedAt(fallbackDetailRef); const fallbackLastVisitedAt = useThreadLastVisitedAt(fallbackDetailRef); const serverThread = serverThreadShell !== null || serverProjection === null || fallbackUpdatedAt === null ? serverThreadShell - : presentThreadShellFromProjection(environmentId, threadId, serverProjection, { - updatedAt: fallbackUpdatedAt, - lastVisitedAt: fallbackLastVisitedAt, - }); + : presentThreadShellFromProjection( + environmentId, + threadId, + serverProjection, + { + updatedAt: fallbackUpdatedAt, + lastVisitedAt: fallbackLastVisitedAt, + }, + viewerFounder, + ); const promptRef = useRef(""); const localComposerRef = useRef(null); const composerRef = useComposerHandleContext() ?? localComposerRef; @@ -1628,10 +1638,28 @@ export default function ChatView(props: ChatViewProps) { ); const timelineEmpty = timelineEntries.length === 0 && !hasStreamedTimelineRows; const displayedTimelineKey = activeThreadKey ?? routeThreadKey; + const recordSeenPlace = useStableCallback((messageId: MessageId, seenAt: string) => { + if (!isServerThread || activeThreadId === null || viewerFounder == null) return; + void visitThread({ + environmentId, + input: { + threadId: activeThreadId, + visitedAt: seenAt, + founder: viewerFounder, + lastSeenMessageId: messageId, + }, + }); + }); useSeenMarkerTracking({ threadKey: isServerThread ? activeThreadKey : null, + founder: viewerFounder, getScrollNode: () => legendListRef.current?.getScrollableNode() ?? null, messages: serverProjection?.messages ?? EMPTY_SEEN_MESSAGES, + notBeforeMessageId: + viewerFounder == null + ? null + : (activeThreadShell?.source.seenMessageByFounder?.[viewerFounder] ?? null), + onRecorded: recordSeenPlace, }); const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey); const { @@ -2001,6 +2029,26 @@ export default function ChatView(props: ChatViewProps) { } }; const sendAppMessageStable = useStableCallback(sendAppMessage); + const onCatchUp = useStableCallback(async (marker: ThreadSeenMarker) => { + if (!isServerThread || activeThreadId === null) return false; + const result = await startThreadTurn({ + environmentId, + input: { + threadId: activeThreadId, + message: { + messageId: newMessageId(), + role: "user", + text: CATCH_ME_UP_TEXT, + attachments: [], + }, + runtimeMode, + interactionMode: DEFAULT_INTERACTION_MODE, + seenMarker: marker, + dispatchMode: "queue", + }, + }); + return result._tag !== "Failure"; + }); const queuedRunsControlRef = useRef(null); const { @@ -3533,6 +3581,7 @@ export default function ChatView(props: ChatViewProps) { draftEntries={isServerThread ? null : draftTimelineEntries} activeThreadKey={activeThreadKey} collapseActivity={isStandingBot && activityCollapsed} + sharedThread={activeThreadShell?.source.inbox?.audience === "shared"} syncing={threadSyncPhase !== null} detailLoading={threadDetailLoading} citationRequest={citationRequest} @@ -3716,6 +3765,24 @@ export default function ChatView(props: ChatViewProps) { } /> ) : null} + {isServerThread ? ( + + ) : null} {!composerMounted ? null : ( ) : null} {!isSearchingThreads ? ( - + <> + + + ) : null} {!isSearchingThreads ? ( { it.each(["Pending Approval", "Awaiting Input", "Guest Request", "Plan Ready"] as const)( @@ -37,9 +42,7 @@ describe("resolveBotPresence", () => { }); expect( resolveBotPresence({ label: "Failed", errorClass: "provider_error" }, "Ops").avatarState, - ).toBe( - "failed", - ); + ).toBe("failed"); }); it("falls back to the role line when idle", () => { @@ -83,3 +86,18 @@ describe("splitStandingThreads", () => { expect(rest.map((thread) => thread.id)).toEqual(["a", "e"]); }); }); + +describe("partitionBotGroups", () => { + it("puts shared-inbox bots in their own group and leaves the rest as mine", () => { + const thread = (id: string, audience?: string) => ({ + id, + source: { inbox: audience === undefined ? null : { audience } }, + }); + expect( + partitionBotGroups([thread("shared", "shared"), thread("jeff", "jeff"), thread("open")]), + ).toEqual({ + shared: [thread("shared", "shared")], + mine: [thread("jeff", "jeff"), thread("open")], + }); + }); +}); diff --git a/apps/web/src/components/bots/botPresence.ts b/apps/web/src/components/bots/botPresence.ts index 5fc7bd22e048b..229aa5987e0f2 100644 --- a/apps/web/src/components/bots/botPresence.ts +++ b/apps/web/src/components/bots/botPresence.ts @@ -62,3 +62,23 @@ export function splitStandingThreads( for (const thread of threads) (thread.standing != null ? bots : rest).push(thread); return { bots, rest }; } + +/** A shared bot belongs to both founders; every other standing bot is one's own. */ +export function isSharedBotThread(thread: { + readonly source: { readonly inbox?: { readonly audience?: string } | null | undefined }; +}): boolean { + return thread.source.inbox?.audience === "shared"; +} + +/** + * The two bot groups the sidebar shows without an inbox filter: the viewer's own bots, then the + * bots both founders share. A shared bot is never also listed as one's own. + */ +export function partitionBotGroups< + T extends { readonly source: { readonly inbox?: { readonly audience?: string } | null } }, +>(threads: readonly T[]): { readonly mine: T[]; readonly shared: T[] } { + const mine: T[] = []; + const shared: T[] = []; + for (const thread of threads) (isSharedBotThread(thread) ? shared : mine).push(thread); + return { mine, shared }; +} diff --git a/apps/web/src/components/chat/CatchMeUpControl.tsx b/apps/web/src/components/chat/CatchMeUpControl.tsx new file mode 100644 index 0000000000000..180fea099c476 --- /dev/null +++ b/apps/web/src/components/chat/CatchMeUpControl.tsx @@ -0,0 +1,79 @@ +import { + CATCH_ME_UP_TEXT, + catchUpOffer, + type SeenMessage, +} from "@t3tools/client-runtime/seen-marker"; +import type { Founder, MessageId, ThreadSeenMarker } from "@t3tools/contracts"; +import { useEffect, useState } from "react"; + +import { Button } from "../ui/button"; + +interface CatchUpSnapshot { + readonly key: string; + readonly messageId: MessageId | null; + readonly seenAt: string | null; +} + +/** + * One catch-up offer per open of a thread, taken from the place this founder had already been + * shown. Scrolling updates that place for next time and does not start a turn. The button does. + */ +export function CatchMeUpControl(props: { + readonly threadKey: string | null; + readonly viewer: Founder | null; + readonly shellReady: boolean; + readonly lastSeenMessageId: MessageId | null; + readonly seenAt: string | null; + readonly messages: ReadonlyArray; + readonly canSend: boolean; + readonly onCatchUp: (marker: ThreadSeenMarker) => Promise; +}) { + const key = + props.threadKey !== null && props.viewer !== null ? `${props.viewer}:${props.threadKey}` : null; + const [snapshot, setSnapshot] = useState(null); + const [dismissedKey, setDismissedKey] = useState(null); + const [sending, setSending] = useState(false); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- capture this founder's place once per open, before this visit advances it + useEffect(() => { + if (key === null || !props.shellReady) return; + setSnapshot((current) => + current?.key === key + ? current + : { key, messageId: props.lastSeenMessageId, seenAt: props.seenAt }, + ); + }, [key, props.shellReady, props.lastSeenMessageId, props.seenAt]); + + const offer = + key === null || dismissedKey === key + ? null + : catchUpOffer({ + messages: props.messages, + lastSeenMessageId: snapshot?.key === key ? snapshot.messageId : null, + seenAt: snapshot?.key === key ? snapshot.seenAt : null, + }); + if (offer === null || !props.canSend) return null; + + return ( +
+ +
+ ); +} diff --git a/apps/web/src/components/chat/MessageSenderLine.tsx b/apps/web/src/components/chat/MessageSenderLine.tsx index b62cdc82da6dc..fee5e25f481e6 100644 --- a/apps/web/src/components/chat/MessageSenderLine.tsx +++ b/apps/web/src/components/chat/MessageSenderLine.tsx @@ -1,7 +1,8 @@ import { useAtomValue } from "@effect/atom-react"; -import type { EnvironmentId, RunId } from "@t3tools/contracts"; +import type { EnvironmentId, Founder, RunId } from "@t3tools/contracts"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; import { + founderSenderBadge, messageSenderDetail, messageSenderLabel, type MessageSender, @@ -66,3 +67,23 @@ export function useRunModelSender( }); return { kind: "model", provider, model }; } + +/** Kameron or Jeff, on a person's message in a shared thread. */ +export function FounderSenderBadge({ founder }: { readonly founder: Founder }) { + const badge = founderSenderBadge(founder); + const tint = founder === "kameron" ? "bg-foreground/15" : "bg-foreground/40"; + return ( +

+ + {badge.initial} + + {badge.name} +

+ ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 43131f4d76b29..48ef5a93f798e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -348,6 +348,8 @@ interface MessagesTimelineProps { * Off by default; a standing thread turns it on. */ collapseActivity?: boolean; + /** Person messages name which founder sent them. */ + sharedThread?: boolean; } export function MessagesTimeline(props: MessagesTimelineProps) { @@ -396,6 +398,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ findNavigationId = 0, findSender = null, collapseActivity = false, + sharedThread = false, latestRun, announcedRun = null, detailBehindShell = false, @@ -1220,6 +1223,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ skills, runs, activeThreadEnvironmentId, + sharedThread, onRevertToTurnCount, onRunShellCommand, findActive, diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.tsx index a60147aed86af..27d0094da3373 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.tsx @@ -4,6 +4,7 @@ import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-v import { type ScopedThreadRef } from "@t3tools/contracts"; import { environmentCatalog } from "../../connection/catalog"; +import { getClientSettings } from "../../hooks/useSettings"; import { useUiStateStore } from "../../uiStateStore"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; @@ -11,6 +12,7 @@ const threadVisitTracker = createThreadVisitTracker({ threadShellAtom: environmentThreadShells.threadShellAtom, sessionGenerationAtom: environmentCatalog.sessionGenerationAtom, visit: threadEnvironment.visit, + visitFounder: () => getClientSettings().founderInboxOwner ?? null, markLocalVisit: (ref, visitedAt) => useUiStateStore.getState().markThreadVisited(scopedThreadKey(ref), visitedAt), }); diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 513fc883da04e..c1ba8c23f2c0a 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,6 +1,6 @@ import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { messageSenderLabel, resolveMessageSender } from "@t3tools/client-runtime/message-sender"; -import { MessageSenderLine } from "./MessageSenderLine"; +import { FounderSenderBadge, MessageSenderLine } from "./MessageSenderLine"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { CHAT_USER_MARKDOWN_REMARK_PLUGINS, @@ -280,7 +280,7 @@ function UserMessageContent({ row }: { row: Extract ) : ( - + ); } @@ -433,7 +433,13 @@ function UserMessageProjectedStatus({ row }: { row: Extract }) { +function UserTimelineRow({ + row, + sharedThread, +}: { + row: Extract; + sharedThread: boolean; +}) { const ctx = use(TimelineRowCtx); const { onImageExpand, onFileOpen } = ctx; const coarsePointer = useMediaQuery({ pointer: "coarse" }); @@ -866,7 +872,11 @@ function UserTimelineRow({ row }: { row: Extract - + {sharedThread && sender.kind === "person" && sender.sentBy?.founder != null ? ( + + ) : ( + + )} ) : null} {/* The row's heading already names the guest for screen readers. */} diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 5ac580ec8d3dd..6c70c66248087 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -63,6 +63,8 @@ export interface TimelineRowSharedState { skills: ReadonlyArray; runs: ReadonlyArray; activeThreadEnvironmentId: EnvironmentId; + /** Person messages in a shared thread show which founder sent them. */ + sharedThread?: boolean; onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void; onUseArtifactTemplate: (template: CodexArtifactTemplate) => void; onSendAppMessage: ((text: string) => Promise) | undefined; diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 44c155dd95859..0df3e650593ca 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -30,7 +30,6 @@ import { RuntimeMode, } from "@t3tools/contracts"; import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; -import { buildSeenMarker } from "@t3tools/client-runtime/seen-marker"; import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors"; import { declinePendingApprovals, @@ -274,11 +273,6 @@ interface ComposerSendInput { readonly linkCheckoutPullRequest: (threadRef: ScopedThreadRef, url: string) => void; } -export function seenMarkerForSend(threadKey: string) { - const seenMarker = buildSeenMarker(threadKey); - return seenMarker ? { seenMarker } : {}; -} - /** * Everything the composer's send button can start: a turn on this thread or a new one, * a multiple-model start, a queued or steering message, a plan follow-up or implementation @@ -1476,7 +1470,6 @@ export function useComposerSend(input: ComposerSendInput) { dispatchMode: turnDispatchMode, ...(freshArm === undefined ? {} : { freshContext: true }), ...(bootstrap ? { bootstrap } : {}), - ...seenMarkerForSend(scopedThreadKey(scopeThreadRef(environmentId, threadIdForSend))), createdAt: messageCreatedAt, }, } diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index f94d40e5dbcc3..4f27c18b75c7d 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -78,7 +78,6 @@ import { Atom } from "effect/reactivity"; import { environmentThreadDetails } from "../../state/threads"; import { resolveThreadOpenRoute } from "../../lib/sideChatPane"; import type { useLocalDispatchState } from "./useLocalDispatchState"; -import { seenMarkerForSend } from "./useComposerSend"; const RELATED_THREAD_SHELL_WAIT_MS = 1_000; const NO_RUN_STOP_ATOM = Atom.make(null).pipe( Atom.withLabel("web-thread-run-stop:empty"), @@ -556,7 +555,6 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { modelSelection: context.selectedModelSelection, runtimeMode, interactionMode: DEFAULT_INTERACTION_MODE, - ...seenMarkerForSend(scopedThreadKey(scopeThreadRef(environmentId, threadId))), createdAt, }, }); diff --git a/apps/web/src/components/sidebar/SidebarBotsGroup.tsx b/apps/web/src/components/sidebar/SidebarBotsGroup.tsx index 1b4b1d1189d17..45894c0fcf220 100644 --- a/apps/web/src/components/sidebar/SidebarBotsGroup.tsx +++ b/apps/web/src/components/sidebar/SidebarBotsGroup.tsx @@ -30,13 +30,21 @@ export function SidebarBotsGroup( props: BotRowHandlers & { readonly threads: readonly EnvironmentThreadShell[]; readonly activeThreadKey: string | null; + /** The group's heading; "Bots" keeps the single group for a search or an older list. */ + readonly label?: string; + readonly testId?: string; }, ) { if (props.threads.length === 0) return null; + const label = props.label ?? "Bots"; return ( -
+
- Bots + {label}
    diff --git a/apps/web/src/components/sidebar/threadListFilter.logic.test.ts b/apps/web/src/components/sidebar/threadListFilter.logic.test.ts index ca4170986265c..caa25638de462 100644 --- a/apps/web/src/components/sidebar/threadListFilter.logic.test.ts +++ b/apps/web/src/components/sidebar/threadListFilter.logic.test.ts @@ -35,6 +35,16 @@ describe("thread list filter", () => { matchesThreadListFilter(candidate, filter); expect(visible(thread(laptop, kameron))).toBe(true); expect(visible(thread(laptop, bot))).toBe(true); + // Shared threads stay visible without opening the filter. + expect( + visible({ + environmentId: laptop, + source: { + inbox: makeThreadInbox({ actor: kameron, routing: { audience: "shared" } }), + createdBy: undefined, + }, + }), + ).toBe(true); // Agent threads from before inbox routing count as Agents. expect(visible(thread(laptop, null, "agent"))).toBe(true); expect(visible(thread(laptop, jeff))).toBe(false); @@ -94,7 +104,7 @@ describe("thread list filter", () => { environments: false, from: false, }); - const reordered = { ...unchanged, inboxes: ["agents", "jeff"] as const }; + const reordered = { ...unchanged, inboxes: ["agents", "jeff", "shared"] as const }; expect(changedThreadListFilters(reordered, "jeff", environments).inboxes).toBe(false); // A hidden environment that was since removed is not a visible filter. const removed = { ...unchanged, hiddenEnvironmentIds: [EnvironmentId.make("gone")] }; diff --git a/apps/web/src/hooks/useSeenMarkerTracking.ts b/apps/web/src/hooks/useSeenMarkerTracking.ts index 6601bc2cd5424..c526f491b188a 100644 --- a/apps/web/src/hooks/useSeenMarkerTracking.ts +++ b/apps/web/src/hooks/useSeenMarkerTracking.ts @@ -1,4 +1,4 @@ -import type { MessageId } from "@t3tools/contracts"; +import type { Founder, MessageId } from "@t3tools/contracts"; import { createSeenMarkerSession, type SeenMessage, @@ -44,16 +44,23 @@ export function visibleMessageIds(node: SeenScrollNode): MessageId[] { export function startSeenMarkerSampling(input: { host: SeenSamplingHost; threadKey: string; + founder?: Founder | null; getScrollNode: () => SeenScrollNode | null | undefined; getMessages: () => ReadonlyArray; now?: () => Date; timers?: SeenTimers; + /** Stored place for this founder. A dwell on an earlier message does not replace it. */ + notBefore?: () => MessageId | null | undefined; + onRecorded?: (messageId: MessageId, seenAt: string) => void; }) { const { window: win, document: doc } = input.host; const session = createSeenMarkerSession({ threadKey: input.threadKey, + ...(input.founder === undefined ? {} : { founder: input.founder }), getMessages: input.getMessages, seenAt: () => (input.now ?? (() => new Date()))().toISOString(), + ...(input.notBefore === undefined ? {} : { notBefore: input.notBefore }), + ...(input.onRecorded === undefined ? {} : { onRecorded: input.onRecorded }), timers: input.timers ?? { set: (callback, ms) => setTimeout(callback, ms), clear: (handle) => clearTimeout(handle as ReturnType), @@ -104,12 +111,21 @@ export function startSeenMarkerSampling(input: { export function useSeenMarkerTracking(input: { threadKey: string | null; + founder?: Founder | null; getScrollNode: () => SeenScrollNode | null | undefined; messages: ReadonlyArray; + /** This founder's stored message. Scrolling back must not replace it. */ + notBeforeMessageId?: MessageId | null; + /** Persist the place that was shown. Must not start a model turn. */ + onRecorded?: (messageId: MessageId, seenAt: string) => void; }) { - const { threadKey, messages } = input; + const { threadKey, founder = null, messages, onRecorded } = input; const getScrollNode = useEffectEvent(() => input.getScrollNode()); const getMessages = useEffectEvent(() => messages); + const onRecordedRef = useRef(onRecorded); + onRecordedRef.current = onRecorded; + const notBeforeRef = useRef(input.notBeforeMessageId); + notBeforeRef.current = input.notBeforeMessageId; const samplingRef = useRef | null>(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus, visibility and scroll listeners plus the dwell timer for this thread @@ -118,15 +134,18 @@ export function useSeenMarkerTracking(input: { const sampling = startSeenMarkerSampling({ host: { window, document }, threadKey, + founder, getScrollNode, getMessages, + notBefore: () => notBeforeRef.current, + onRecorded: (messageId, seenAt) => onRecordedRef.current?.(messageId, seenAt), }); samplingRef.current = sampling; return () => { sampling.dispose(); samplingRef.current = null; }; - }, [threadKey]); + }, [threadKey, founder]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resamples the visible DOM rows when the thread's messages change useEffect(() => { diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index d1b6389ffe8e5..5c428e3977444 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -31,6 +31,7 @@ import { environmentServerConfigsAtom } from "../state/server"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { orchestrationEnvironment } from "../state/orchestration"; import { projectEnvironment } from "../state/projects"; +import { getClientSettings } from "./useSettings"; import { threadEnvironment } from "../state/threads"; import { vcsEnvironment } from "../state/vcs"; import { useNewThreadHandler } from "./useHandleNewThread"; @@ -225,7 +226,12 @@ function useMarkThreadUnread() { if (readEnvironmentServerConfigLoaded(target.environmentId)) { void markThreadUnreadMutation({ environmentId: target.environmentId, - input: { threadId: target.threadId }, + input: { + threadId: target.threadId, + ...(getClientSettings().founderInboxOwner === undefined + ? {} + : { founder: getClientSettings().founderInboxOwner }), + }, }); return; } @@ -241,7 +247,13 @@ export function useAcknowledgeThreadWoke() { if (readEnvironmentServerConfigLoaded(target.environmentId)) { void visitThreadMutation({ environmentId: target.environmentId, - input: { threadId: target.threadId, visitedAt: wokeAt }, + input: { + threadId: target.threadId, + visitedAt: wokeAt, + ...(getClientSettings().founderInboxOwner === undefined + ? {} + : { founder: getClientSettings().founderInboxOwner }), + }, }); return; } diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 9e164f425736e..cbd50972a39a7 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -15,6 +15,7 @@ import { import { inboxOriginFor, type EnvironmentId, + type Founder, type OrchestrationV2ThreadShell, type ThreadId, } from "@t3tools/contracts"; @@ -25,7 +26,11 @@ import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; import { serverEnvironment } from "./server"; import { environmentShell } from "./shell"; -import { getClientSettings } from "../hooks/useSettings"; +import { + getClientSettings, + subscribeClientSettings, + subscribeClientSettingsHydration, +} from "../hooks/useSettings"; export const threadFamilies = createThreadFamilyAtoms( connectionAtomRuntime, @@ -44,10 +49,18 @@ const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRunti export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( environmentThreads.stateAtom, ); +/** The founder this browser is signed in as. Shared threads show that founder's unread mark. */ +export const viewerFounderAtom = Atom.make((get): Founder | null => { + get.addFinalizer(subscribeClientSettings(() => get.refreshSelf())); + get.addFinalizer(subscribeClientSettingsHydration(() => get.refreshSelf())); + return getClientSettings().founderInboxOwner ?? null; +}).pipe(Atom.withLabel("web-viewer-founder")); + export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + viewerFounderAtom, }); export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, diff --git a/packages/client-runtime/src/messageSender.test.ts b/packages/client-runtime/src/messageSender.test.ts index f0d829420fc84..58c01fd81bdc6 100644 --- a/packages/client-runtime/src/messageSender.test.ts +++ b/packages/client-runtime/src/messageSender.test.ts @@ -2,6 +2,7 @@ import { AuthSessionId, EnvironmentId, ScheduledTaskId, ThreadId } from "@t3tool import { describe, expect, it } from "vite-plus/test"; import { + founderSenderBadge, messageSenderDetail, messageSenderLabel, messageSenderMatches, @@ -103,3 +104,10 @@ describe("resolveMessageSender", () => { expect(sameMessageSender(a, c)).toBe(false); }); }); + +describe("founderSenderBadge", () => { + it("uses the founder's initial and name", () => { + expect(founderSenderBadge("kameron")).toEqual({ name: "Kameron", initial: "K" }); + expect(founderSenderBadge("jeff")).toEqual({ name: "Jeff", initial: "J" }); + }); +}); diff --git a/packages/client-runtime/src/messageSender.ts b/packages/client-runtime/src/messageSender.ts index 28ec319d4d517..53424464a15df 100644 --- a/packages/client-runtime/src/messageSender.ts +++ b/packages/client-runtime/src/messageSender.ts @@ -101,6 +101,12 @@ export function resolveMessageSender( const FOUNDER_NAMES = { kameron: "Kameron", jeff: "Jeff" } satisfies Record; +/** The initial and name on a shared-thread message. */ +export function founderSenderBadge(founder: Founder) { + const name = FOUNDER_NAMES[founder]; + return { name, initial: name.slice(0, 1) } as const; +} + const DEVICE_TYPE_NAMES = { desktop: "Desktop", mobile: "Phone", diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 5b7f7dfe39030..f4bd8ff40f6d6 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -138,9 +138,16 @@ export interface VisitThreadInput extends ThreadCommandInput { /** Counts toward search frecency; `searchQuery` is the palette query that picked it. */ readonly opened?: boolean; readonly searchQuery?: string; + /** Whose read cursor this visit moves. Shared threads leave the other founder unread. */ + readonly founder?: import("@t3tools/contracts").Founder; + /** Last message this founder was shown. The visit still does not start a turn. */ + readonly lastSeenMessageId?: import("@t3tools/contracts").MessageId; } -export type MarkThreadUnreadInput = ThreadCommandInput; +export interface MarkThreadUnreadInput extends ThreadCommandInput { + /** On a shared thread, rewind only this founder's cursor. */ + readonly founder?: import("@t3tools/contracts").Founder; +} export interface UpdateThreadMetadataInput extends ThreadCommandInput { readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecoveryUpdate | null; @@ -690,6 +697,10 @@ export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function visitedAt: input.visitedAt, ...(input.opened ? { opened: true } : {}), ...(input.searchQuery ? { searchQuery: input.searchQuery } : {}), + ...(input.founder === undefined ? {} : { founder: input.founder }), + ...(input.lastSeenMessageId === undefined + ? {} + : { lastSeenMessageId: input.lastSeenMessageId }), }); }); @@ -700,6 +711,7 @@ export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread" type: "thread.mark-unread", commandId: yield* allocateCommandId(input), threadId: input.threadId, + ...(input.founder === undefined ? {} : { founder: input.founder }), }); }); diff --git a/packages/client-runtime/src/seenMarker.test.ts b/packages/client-runtime/src/seenMarker.test.ts index 17334d0da6ac4..eac45af2b4ba9 100644 --- a/packages/client-runtime/src/seenMarker.test.ts +++ b/packages/client-runtime/src/seenMarker.test.ts @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test"; import { buildSeenMarker, + catchUpOffer, createSeenMarkerSession, pickNewestMessageId, resetSeenMarkersForTest, @@ -125,3 +126,100 @@ describe("seen dwell", () => { tracker.dispose(); }); }); + +describe("stored place", () => { + it("does not record a message at or before the stored one", () => { + const afterId = MessageId.make("message-after"); + const recorded: Array = []; + const clock = manualTimers(); + const tracker = createSeenMarkerSession({ + threadKey: "env:thread", + getMessages: () => [...messages, { id: afterId, role: "assistant" }], + seenAt: () => seenAt, + timers: clock.timers, + notBefore: () => laterId, + onRecorded: (messageId) => { + recorded.push(messageId); + }, + }); + tracker.update({ active: true, visibleIds: [assistantId] }); + clock.fireNext(); + expect(recorded).toEqual([]); + expect(buildSeenMarker("env:thread")).toBeUndefined(); + tracker.update({ active: true, visibleIds: [afterId] }); + clock.fireNext(); + expect(recorded).toEqual([afterId]); + expect(buildSeenMarker("env:thread")?.lastSeenMessageId).toBe(afterId); + tracker.dispose(); + }); +}); + +describe("catch-up offer", () => { + it("offers a marker only when a finished assistant message is still unseen", () => { + expect( + catchUpOffer({ + messages, + lastSeenMessageId: assistantId, + seenAt, + }), + ).toEqual({ lastSeenMessageId: assistantId, seenAt }); + expect( + catchUpOffer({ + messages, + lastSeenMessageId: laterId, + seenAt, + }), + ).toBeNull(); + expect( + catchUpOffer({ + messages: [ + ...messages, + { id: MessageId.make("streaming"), role: "assistant", streaming: true }, + ], + lastSeenMessageId: laterId, + seenAt, + }), + ).toBeNull(); + expect(catchUpOffer({ messages, lastSeenMessageId: null, seenAt })).toBeNull(); + expect(catchUpOffer({ messages, lastSeenMessageId: assistantId, seenAt: null })).toBeNull(); + expect( + catchUpOffer({ + messages, + lastSeenMessageId: MessageId.make("missing"), + seenAt, + }), + ).toEqual({ lastSeenMessageId: MessageId.make("missing"), seenAt }); + }); +}); + +describe("per founder", () => { + it("keeps a separate place for each founder of one thread", () => { + const clock = manualTimers(); + const jeff = createSeenMarkerSession({ + threadKey: "env:thread", + founder: "jeff", + getMessages: () => messages, + seenAt: () => seenAt, + timers: clock.timers, + }); + jeff.update({ active: true, visibleIds: [assistantId] }); + clock.fireNext(); + expect(buildSeenMarker("env:thread", "jeff")?.lastSeenMessageId).toBe(assistantId); + expect(buildSeenMarker("env:thread", "kameron")).toBeUndefined(); + expect(buildSeenMarker("env:thread")).toBeUndefined(); + + const kameron = createSeenMarkerSession({ + threadKey: "env:thread", + founder: "kameron", + getMessages: () => messages, + seenAt: () => seenAt, + timers: clock.timers, + }); + kameron.update({ active: true, visibleIds: [userId] }); + clock.fireNext(); + expect(buildSeenMarker("env:thread", "kameron")?.lastSeenMessageId).toBe(userId); + expect(buildSeenMarker("env:thread", "jeff")?.lastSeenMessageId).toBe(assistantId); + jeff.dispose(); + kameron.dispose(); + }); +}); diff --git a/packages/client-runtime/src/seenMarker.ts b/packages/client-runtime/src/seenMarker.ts index 0f3f4769e1b32..9bbca3a536697 100644 --- a/packages/client-runtime/src/seenMarker.ts +++ b/packages/client-runtime/src/seenMarker.ts @@ -1,4 +1,4 @@ -import type { MessageId, ThreadSeenMarker } from "@t3tools/contracts"; +import type { Founder, MessageId, ThreadSeenMarker } from "@t3tools/contracts"; const SEEN_DWELL_MS = 2_000; @@ -63,20 +63,35 @@ interface SeenEntry { const seenByThreadKey = new Map(); +/** Unassigned viewers keep the bare thread key, so a browser with no founder behaves as before. */ +function seenMarkerKey(threadKey: string, founder?: Founder | null) { + return founder == null ? threadKey : `${founder}:${threadKey}`; +} + function recordSeenMessage(input: { threadKey: string; + founder?: Founder | null; messageId: MessageId; messages: ReadonlyArray; seenAt: string; + /** A place already stored for this founder. A dwell behind it does not rewind the marker. */ + notBeforeMessageId?: MessageId | null; }): boolean { + const key = seenMarkerKey(input.threadKey, input.founder); const nextIndex = input.messages.findIndex((message) => message.id === input.messageId); if (nextIndex < 0 || input.messages[nextIndex]?.streaming === true) return false; - const previous = seenByThreadKey.get(input.threadKey); + if (input.notBeforeMessageId != null) { + const floorIndex = input.messages.findIndex( + (message) => message.id === input.notBeforeMessageId, + ); + if (floorIndex >= 0 && nextIndex <= floorIndex) return false; + } + const previous = seenByThreadKey.get(key); if (previous) { const previousIndex = input.messages.findIndex((message) => message.id === previous.messageId); if (previousIndex >= nextIndex) return false; } - seenByThreadKey.set(input.threadKey, { messageId: input.messageId, seenAt: input.seenAt }); + seenByThreadKey.set(key, { messageId: input.messageId, seenAt: input.seenAt }); return true; } @@ -93,8 +108,33 @@ export function pickNewestMessageId( return null; } -export function buildSeenMarker(threadKey: string): ThreadSeenMarker | undefined { - const seen = seenByThreadKey.get(threadKey); +/** + * The catch-up offer for messages after the place this founder had already been shown. + * Opening a thread does not call this. The Catch me up button is the only caller that + * starts a turn, and only with the marker it returns. + */ +export function catchUpOffer(input: { + readonly messages: ReadonlyArray; + readonly lastSeenMessageId: MessageId | null | undefined; + readonly seenAt: string | null | undefined; +}): ThreadSeenMarker | null { + if (input.lastSeenMessageId == null || input.seenAt == null || input.seenAt === "") return null; + const index = input.messages.findIndex((message) => message.id === input.lastSeenMessageId); + const after = index < 0 ? input.messages : input.messages.slice(index + 1); + const unseen = after.some( + (message) => message.role === "assistant" && message.streaming !== true, + ); + if (!unseen) return null; + return { lastSeenMessageId: input.lastSeenMessageId, seenAt: input.seenAt }; +} + +export const CATCH_ME_UP_TEXT = "Catch me up"; + +export function buildSeenMarker( + threadKey: string, + founder?: Founder | null, +): ThreadSeenMarker | undefined { + const seen = seenByThreadKey.get(seenMarkerKey(threadKey, founder)); if (!seen) return undefined; return { lastSeenMessageId: seen.messageId, seenAt: seen.seenAt }; } @@ -106,19 +146,31 @@ export interface SeenMarkerSession { export function createSeenMarkerSession(input: { threadKey: string; + /** Whose place this is. Two founders on one browser keep two positions. */ + founder?: Founder | null; getMessages: () => ReadonlyArray; seenAt: () => string; timers: SeenTimers; dwellMs?: number; + /** The stored place. Read on each dwell so a late shell still blocks a rewind. */ + notBefore?: () => MessageId | null | undefined; + /** Fired when a human's place moves. Callers persist it. They must not start a turn. */ + onRecorded?: (messageId: MessageId, seenAt: string) => void; }): SeenMarkerSession { const tracker = createSeenDwellTracker({ - onSeen: (messageId) => - recordSeenMessage({ + onSeen: (messageId) => { + const seenAt = input.seenAt(); + const notBefore = input.notBefore?.() ?? null; + const recorded = recordSeenMessage({ threadKey: input.threadKey, + ...(input.founder !== undefined ? { founder: input.founder } : {}), messageId, messages: input.getMessages(), - seenAt: input.seenAt(), - }), + seenAt, + ...(notBefore == null ? {} : { notBeforeMessageId: notBefore }), + }); + if (recorded) input.onRecorded?.(messageId, seenAt); + }, timers: input.timers, ...(input.dwellMs !== undefined ? { dwellMs: input.dwellMs } : {}), }); diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 09e793c702f00..0ae7a7f406311 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -3,6 +3,7 @@ import { threadPullRequestsOf } from "../threadPullRequests.ts"; import type { ThreadLinkedPullRequest, EnvironmentId, + Founder, MessageId, OrchestrationProjectShell, OrchestrationV2ProviderGoal, @@ -216,6 +217,34 @@ function nullableIso(value: DateTime.Utc | null): string | null { return value === null ? null : iso(value); } +/** + * The read cursor this viewer should use. A shared thread with per-founder cursors returns that + * founder's stamp (or null when they have none). Every other thread keeps the shared watermark, + * including `undefined` from a server that does not track visits. + */ +export function seenCursorForViewer( + thread: { + readonly lastVisitedAt?: DateTime.Utc | null | undefined; + readonly inbox?: { readonly audience?: string } | null | undefined; + readonly visitsByFounder?: + | { + readonly kameron?: DateTime.Utc | undefined; + readonly jeff?: DateTime.Utc | undefined; + } + | undefined; + }, + viewer: Founder | null, +): DateTime.Utc | null | undefined { + if ( + viewer == null || + thread.inbox?.audience !== "shared" || + thread.visitsByFounder === undefined + ) { + return thread.lastVisitedAt; + } + return thread.visitsByFounder[viewer] ?? null; +} + function terminalRunStatus(status: OrchestrationV2RunStatus): boolean { return ( status === "completed" || @@ -268,8 +297,10 @@ export function presentThreadShell( environmentId: EnvironmentId, thread: OrchestrationV2ThreadShell, pendingSubagentRequest: PendingSubagentRequest | null = null, + viewer: Founder | null = null, ): EnvironmentThreadShell { const updatedAt = iso(thread.updatedAt); + const seenAt = seenCursorForViewer(thread, viewer); const latestRun = thread.latestRunId === null ? null @@ -348,9 +379,7 @@ export function presentThreadShell( autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null), pinOrderKey: thread.pinOrderKey ?? null, activeOrderKey: thread.activeOrderKey ?? null, - ...(thread.lastVisitedAt === undefined - ? {} - : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }), + ...(seenAt === undefined ? {} : { lastVisitedAt: nullableIso(seenAt) }), opens: thread.opens ?? null, titleRegeneration: thread.titleRegeneration == null diff --git a/packages/client-runtime/src/state/seenCursor.test.ts b/packages/client-runtime/src/state/seenCursor.test.ts new file mode 100644 index 0000000000000..afb8d7548bef0 --- /dev/null +++ b/packages/client-runtime/src/state/seenCursor.test.ts @@ -0,0 +1,40 @@ +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { seenCursorForViewer } from "./models.ts"; + +const earlier = DateTime.makeUnsafe("2026-11-20T12:00:00.000Z"); +const later = DateTime.makeUnsafe("2026-11-20T13:00:00.000Z"); + +describe("seenCursorForViewer", () => { + it("keeps the shared watermark until a founder map exists", () => { + expect( + seenCursorForViewer({ lastVisitedAt: earlier, inbox: { audience: "shared" } }, "jeff"), + ).toBe(earlier); + expect(seenCursorForViewer({ lastVisitedAt: undefined }, "jeff")).toBeUndefined(); + }); + + it("uses only the viewer's stamp on a shared thread", () => { + const thread = { + lastVisitedAt: later, + inbox: { audience: "shared" as const }, + visitsByFounder: { kameron: earlier }, + }; + expect(seenCursorForViewer(thread, "kameron")).toBe(earlier); + expect(seenCursorForViewer(thread, "jeff")).toBeNull(); + expect(seenCursorForViewer(thread, null)).toBe(later); + }); + + it("ignores a founder map on a thread that is not shared", () => { + expect( + seenCursorForViewer( + { + lastVisitedAt: later, + inbox: { audience: "jeff" }, + visitsByFounder: { jeff: earlier }, + }, + "jeff", + ), + ).toBe(later); + }); +}); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 36998a906635d..9241ca8cc5631 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + Founder, OrchestrationV2ShellSnapshot, ProjectId, ScopedProjectRef, @@ -256,7 +257,15 @@ export function createEnvironmentThreadShellAtoms(input: { readonly hiddenThreadTagsAtom: ( environmentId: EnvironmentId, ) => Atom.Atom | null>; + /** + * The founder reading this client. Shared threads present that founder's read cursor. + * Absent on clients that have no founder, which keep the shared watermark. + */ + readonly viewerFounderAtom?: Atom.Atom; }) { + const viewerFounderAtom = input.viewerFounderAtom; + const viewerOf = (get: (atom: Atom.Atom) => Founder | null): Founder | null => + viewerFounderAtom === undefined ? null : get(viewerFounderAtom); // Point reads and aggregate lists share values without keeping an atom alive // for every listed thread. Replaced source objects can be collected. const scopedThreads = new WeakMap< @@ -267,6 +276,7 @@ export function createEnvironmentThreadShellAtoms(input: { environmentId: EnvironmentId, thread: OrchestrationV2ThreadShell, subagentRequests: ReadonlyMap, + viewer: Founder | null, ) => { let byEnvironment = scopedThreads.get(thread); if (byEnvironment === undefined) { @@ -274,10 +284,10 @@ export function createEnvironmentThreadShellAtoms(input: { scopedThreads.set(thread, byEnvironment); } const request = subagentRequests.get(thread.id) ?? null; - const key = request === null ? environmentId : `${environmentId}:${request}`; + const key = `${request === null ? environmentId : `${environmentId}:${request}`}:${viewer ?? ""}`; let value = byEnvironment.get(key); if (value === undefined) { - value = presentThreadShell(environmentId, thread, request); + value = presentThreadShell(environmentId, thread, request, viewer); byEnvironment.set(key, value); } return value; @@ -463,6 +473,7 @@ export function createEnvironmentThreadShellAtoms(input: { ref.environmentId, source, get(pendingSubagentRequestsAtom(ref.environmentId)), + viewerOf(get), ); }).pipe(Atom.withLabel(`environment-thread-shell:${key}`)); }); @@ -517,6 +528,7 @@ export function createEnvironmentThreadShellAtoms(input: { const seen = new Set([key]); const pending = [key]; const next: EnvironmentThreadShell[] = []; + const viewer = viewerOf(get); for (const parent of pending) { for (const { environmentId, thread } of children.get(parent) ?? []) { const childKey = threadKey({ environmentId, threadId: thread.id }); @@ -525,7 +537,12 @@ export function createEnvironmentThreadShellAtoms(input: { pending.push(childKey); if (subagentRequest(thread) !== null || sideChatRequest(thread) !== null) { next.push( - scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))), + scopedThread( + environmentId, + thread, + get(pendingSubagentRequestsAtom(environmentId)), + viewer, + ), ); } } @@ -561,8 +578,9 @@ export function createEnvironmentThreadShellAtoms(input: { return previous; } const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId)); + const viewer = viewerOf(get); const next = sideChats.map((thread) => - scopedThread(ref.environmentId, thread, subagentRequests), + scopedThread(ref.environmentId, thread, subagentRequests, viewer), ); if ( previous.length === next.length && @@ -588,6 +606,7 @@ export function createEnvironmentThreadShellAtoms(input: { return Atom.make((get) => { const next: EnvironmentThreadShell[] = []; const seen = new Set(); + const viewer = viewerOf(get); for (const projectRef of projectRefs) { const refs = get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get( @@ -604,7 +623,7 @@ export function createEnvironmentThreadShellAtoms(input: { seen.add(key); const thread = threads.get(ref.threadId); if (thread !== undefined) { - next.push(scopedThread(ref.environmentId, thread, subagentRequests)); + next.push(scopedThread(ref.environmentId, thread, subagentRequests, viewer)); } } } @@ -632,10 +651,11 @@ export function createEnvironmentThreadShellAtoms(input: { let previousThreadShells: ReadonlyArray = []; const threadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; + const viewer = viewerOf(get); for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); for (const thread of get(environmentThreadsAtom(environmentId))) { - next.push(scopedThread(environmentId, thread, subagentRequests)); + next.push(scopedThread(environmentId, thread, subagentRequests, viewer)); } } if (arrayElementsEqual(previousThreadShells, next)) { @@ -747,6 +767,7 @@ export function createEnvironmentThreadShellAtoms(input: { const next: EnvironmentThreadShell[] = []; const underParent = get(delegatedUnderParentAtom); const hidden = get(hiddenThreadKeysAtom); + const viewer = viewerOf(get); for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); for (const thread of get(environmentThreadsAtom(environmentId))) { @@ -757,7 +778,7 @@ export function createEnvironmentThreadShellAtoms(input: { ) { continue; } - next.push(scopedThread(environmentId, thread, subagentRequests)); + next.push(scopedThread(environmentId, thread, subagentRequests, viewer)); } } if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells; diff --git a/packages/client-runtime/src/state/threadVisits.ts b/packages/client-runtime/src/state/threadVisits.ts index 4d71a1960fd67..008d92e98f3da 100644 --- a/packages/client-runtime/src/state/threadVisits.ts +++ b/packages/client-runtime/src/state/threadVisits.ts @@ -1,5 +1,5 @@ // @effect-diagnostics globalTimers:off globalDate:off - The tracker runs in atom subscriptions, outside an Effect runtime. -import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import type { EnvironmentId, Founder, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; import { AsyncResult, Atom } from "effect/reactivity"; import { parseThreadKey, threadKey } from "./entities.ts"; @@ -44,6 +44,8 @@ export interface ThreadVisitTrackerOptions { * that keeps its own watermark for them records the visit here instead. */ readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void; + /** The founder this client is. Shared-thread visits move only that cursor. */ + readonly visitFounder?: () => Founder | null | undefined; } /** @@ -95,6 +97,7 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { lastDispatchedUpdatedAt = visitedAt; lastDispatchAt = Date.now(); lastDispatchGeneration = registry.get(sessionGenerationAtom); + const founder = options.visitFounder?.() ?? undefined; void runAtomCommand( registry, options.visit, @@ -104,6 +107,7 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { threadId: shell.id, visitedAt, ...(opened ? { opened: true } : {}), + ...(founder == null ? {} : { founder }), }, }, { reportFailure: false }, diff --git a/packages/contracts/src/founderVisits.test.ts b/packages/contracts/src/founderVisits.test.ts new file mode 100644 index 0000000000000..a4cd08a16e8d2 --- /dev/null +++ b/packages/contracts/src/founderVisits.test.ts @@ -0,0 +1,150 @@ +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { MessageId } from "./baseSchemas.ts"; +import { + applyOrchestrationV2ThreadVisit, + nextFounderSeenMessage, + nextFounderVisits, + OrchestrationV2ThreadVisitJson, + rewindFounderVisit, +} from "./orchestrationV2.ts"; + +const earlier = DateTime.makeUnsafe("2026-11-20T12:00:00.000Z"); +const later = DateTime.makeUnsafe("2026-11-20T13:00:00.000Z"); +const newest = DateTime.makeUnsafe("2026-11-20T14:00:00.000Z"); + +describe("per-founder read cursors", () => { + it("seeds the other founder from the shared cursor, then advances only the reader", () => { + const seeded = nextFounderVisits( + { lastVisitedAt: earlier, visitsByFounder: undefined }, + "jeff", + later, + ); + expect(seeded.kameron).toBe(earlier); + expect(seeded.jeff).toBe(later); + + const sameVisit = nextFounderVisits( + { lastVisitedAt: earlier, visitsByFounder: seeded }, + "jeff", + later, + ); + expect(sameVisit).toBe(seeded); + + const kameronReads = nextFounderVisits( + { lastVisitedAt: earlier, visitsByFounder: seeded }, + "kameron", + newest, + ); + expect(kameronReads.jeff).toBe(later); + expect(kameronReads.kameron).toBe(newest); + }); + + it("persists the split when the first named visit is not newer than the shared cursor", () => { + const seeded = nextFounderVisits( + { lastVisitedAt: later, visitsByFounder: undefined }, + "jeff", + earlier, + ); + expect(seeded.kameron).toBe(later); + expect(seeded.jeff).toBe(later); + }); + + it("marks both founders read as of the first visit, so a later reply is unread for the other", () => { + const seeded = nextFounderVisits( + { lastVisitedAt: null, visitsByFounder: undefined }, + "kameron", + later, + ); + expect(seeded.kameron).toBe(later); + expect(seeded.jeff).toBe(later); + + const jeffReadsLater = nextFounderVisits( + { lastVisitedAt: null, visitsByFounder: seeded }, + "jeff", + newest, + ); + expect(jeffReadsLater.kameron).toBe(later); + expect(jeffReadsLater.jeff).toBe(newest); + }); + + it("rewinds one founder and leaves the other where they were", () => { + const current = { kameron: later, jeff: later }; + const rewound = rewindFounderVisit( + { lastVisitedAt: later, visitsByFounder: current }, + "jeff", + earlier, + ); + expect(rewound.jeff).toBe(earlier); + expect(rewound.kameron).toBe(later); + expect(current.jeff).toBe(later); + }); + + it("copies a founder map onto the thread and leaves the shared watermark as the payload says", () => { + const thread = { id: "thread", lastVisitedAt: earlier } as Parameters< + typeof applyOrchestrationV2ThreadVisit + >[0]; + const next = applyOrchestrationV2ThreadVisit(thread, { + lastVisitedAt: earlier, + visitsByFounder: { kameron: earlier, jeff: later }, + }); + expect(next.lastVisitedAt).toBe(earlier); + expect(next.visitsByFounder?.jeff).toBe(later); + expect(next.visitsByFounder?.kameron).toBe(earlier); + + const globalOnly = applyOrchestrationV2ThreadVisit(next, { lastVisitedAt: newest }); + expect(globalOnly.lastVisitedAt).toBe(newest); + expect(globalOnly.visitsByFounder).toBe(next.visitsByFounder); + }); + + it("records one founder's message and leaves the other founder's message", () => { + const jeffMessage = MessageId.make("message-jeff"); + const kameronMessage = MessageId.make("message-kameron"); + const jeffSeen = nextFounderSeenMessage( + { seenMessageByFounder: undefined }, + "jeff", + jeffMessage, + ); + expect(jeffSeen.jeff).toBe(jeffMessage); + expect(jeffSeen.kameron).toBeUndefined(); + + const same = nextFounderSeenMessage({ seenMessageByFounder: jeffSeen }, "jeff", jeffMessage); + expect(same).toBe(jeffSeen); + + const both = nextFounderSeenMessage( + { seenMessageByFounder: jeffSeen }, + "kameron", + kameronMessage, + ); + expect(both.jeff).toBe(jeffMessage); + expect(both.kameron).toBe(kameronMessage); + expect(jeffSeen.kameron).toBeUndefined(); + }); + + it("keeps a stored message map when a later visit does not include one", () => { + const thread = { id: "thread", lastVisitedAt: earlier } as Parameters< + typeof applyOrchestrationV2ThreadVisit + >[0]; + const jeffMessage = MessageId.make("message-jeff"); + const withSeen = applyOrchestrationV2ThreadVisit(thread, { + lastVisitedAt: earlier, + seenMessageByFounder: { jeff: jeffMessage }, + }); + const laterVisit = applyOrchestrationV2ThreadVisit(withSeen, { lastVisitedAt: newest }); + expect(laterVisit.seenMessageByFounder).toBe(withSeen.seenMessageByFounder); + expect(laterVisit.lastVisitedAt).toBe(newest); + }); + + it("decodes founder visit timestamps stored as strings", () => { + const visit = Schema.decodeSync(OrchestrationV2ThreadVisitJson)({ + lastVisitedAt: "2026-11-20T12:00:00.000Z", + visitsByFounder: { + kameron: "2026-11-20T12:00:00.000Z", + jeff: "2026-11-20T13:00:00.000Z", + }, + }); + expect(DateTime.formatIso(visit.lastVisitedAt!)).toBe("2026-11-20T12:00:00.000Z"); + expect(DateTime.formatIso(visit.visitsByFounder!.jeff!)).toBe("2026-11-20T13:00:00.000Z"); + }); +}); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 1d0863345b133..28158b54aba21 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -488,6 +488,25 @@ const OrchestrationV2LastTitleRegeneration = Schema.Struct({ completedAt: Schema.DateTimeUtc, }); +/** One read cursor per founder. Absent until a named founder visits a shared thread. */ +export const FounderVisits = Schema.Struct({ + kameron: Schema.optional(Schema.DateTimeUtc), + jeff: Schema.optional(Schema.DateTimeUtc), +}); +export type FounderVisits = typeof FounderVisits.Type; + +const FounderVisitsJson = Schema.Struct({ + kameron: Schema.optional(Schema.DateTimeUtcFromString), + jeff: Schema.optional(Schema.DateTimeUtcFromString), +}); + +/** The last message each founder has actually been shown. Absent until they open or scroll. */ +export const FounderSeenMessages = Schema.Struct({ + kameron: Schema.optional(MessageId), + jeff: Schema.optional(MessageId), +}); +export type FounderSeenMessages = typeof FounderSeenMessages.Type; + export const OrchestrationV2AppThread = Schema.Struct({ ...OrchestrationV2CreationFields, inbox: Schema.optionalKey(ThreadInbox), @@ -545,6 +564,13 @@ export const OrchestrationV2AppThread = Schema.Struct({ lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), + /** + * Per-founder read cursors. A shared thread keeps these apart so one founder reading does not + * move the other's unread mark. Absent on threads that still share `lastVisitedAt`. + */ + visitsByFounder: Schema.optional(FounderVisits), + /** Last message each founder was shown. Writing it does not start a turn. */ + seenMessageByFounder: Schema.optional(FounderSeenMessages), opens: Schema.optional(LenientThreadOpens), titleRegeneration: Schema.optional( Schema.NullOr( @@ -572,6 +598,8 @@ export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type; export const OrchestrationV2ThreadVisit = Schema.Struct({ lastVisitedAt: OrchestrationV2AppThread.fields.lastVisitedAt, opens: OrchestrationV2AppThread.fields.opens, + visitsByFounder: Schema.optional(FounderVisits), + seenMessageByFounder: Schema.optional(FounderSeenMessages), }); export type OrchestrationV2ThreadVisit = typeof OrchestrationV2ThreadVisit.Type; @@ -583,9 +611,67 @@ export function applyOrchestrationV2ThreadVisit, + founder: Founder, + visitedAt: DateTime.Utc, +): FounderVisits { + const current = thread.visitsByFounder; + const seeded: FounderVisits = + current ?? + (thread.lastVisitedAt === null + ? { kameron: visitedAt, jeff: visitedAt } + : { kameron: thread.lastVisitedAt, jeff: thread.lastVisitedAt }); + const previous = seeded[founder]; + if ( + previous !== undefined && + DateTime.toEpochMillis(previous) >= DateTime.toEpochMillis(visitedAt) + ) { + return current ?? seeded; + } + return { ...seeded, [founder]: visitedAt }; +} + +/** Mark-unread rewinds one founder's cursor and leaves the other's where it is. */ +export function rewindFounderVisit( + thread: Pick, + founder: Founder, + visitedAt: DateTime.Utc, +): FounderVisits { + const current = thread.visitsByFounder; + const seeded: FounderVisits = + current ?? + (thread.lastVisitedAt === null + ? {} + : { kameron: thread.lastVisitedAt, jeff: thread.lastVisitedAt }); + return { ...seeded, [founder]: visitedAt }; +} + +/** The message map after `founder` is shown a message. The same id returns the existing map. */ +export function nextFounderSeenMessage( + thread: Pick, + founder: Founder, + messageId: MessageId, +): FounderSeenMessages { + const current = thread.seenMessageByFounder; + if (current?.[founder] === messageId) return current ?? { [founder]: messageId }; + return { ...(current ?? {}), [founder]: messageId }; +} + /** A thread another agent drives: a local subagent or a task delegated from a linked environment. */ export const isDelegatedAppThread = ( thread: Pick, @@ -2341,6 +2427,9 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ /** Bot persona for a standing thread; absent or null is an ordinary thread. Independent of pinning. */ standing: Schema.optional(StoredThreadStanding), lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + /** Per-founder read cursors. Older servers omit them; clients then keep the shared cursor. */ + visitsByFounder: Schema.optional(FounderVisits), + seenMessageByFounder: Schema.optional(FounderSeenMessages), opens: Schema.optional(LenientThreadOpens), titleRegeneration: Schema.optional( Schema.NullOr( @@ -2532,6 +2621,7 @@ export const OrchestrationV2AppThreadJson = OrchestrationV2AppThread.mapFields(( lastVisitedAt: Schema.NullOr(Schema.DateTimeUtcFromString).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), + visitsByFounder: Schema.optional(FounderVisitsJson), titleRegeneration: Schema.optional( Schema.NullOr( Schema.Struct({ @@ -2555,6 +2645,8 @@ export type OrchestrationV2AppThreadJson = typeof OrchestrationV2AppThreadJson.T export const OrchestrationV2ThreadVisitJson = Schema.Struct({ lastVisitedAt: OrchestrationV2AppThreadJson.fields.lastVisitedAt, opens: OrchestrationV2AppThreadJson.fields.opens, + visitsByFounder: Schema.optional(FounderVisitsJson), + seenMessageByFounder: Schema.optional(FounderSeenMessages), }); export const OrchestrationV2RunJson = OrchestrationV2Run.mapFields((fields) => ({ @@ -2988,6 +3080,7 @@ export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFiel pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), + visitsByFounder: Schema.optional(FounderVisitsJson), titleRegeneration: Schema.optional( Schema.NullOr( Schema.Struct({ @@ -3348,11 +3441,23 @@ export const OrchestrationV2Command = Schema.Union([ // Older servers ignore both fields and only move the read watermark. opened: Schema.optional(Schema.Boolean), searchQuery: Schema.optional(Schema.String.check(Schema.isMaxLength(200))), + /** + * Whose cursor this visit moves. On a shared thread the other founder's cursor stays. + * Older servers ignore it and move the one shared watermark. + */ + founder: Schema.optional(Founder), + /** + * The last message this founder was shown. Recorded with the visit so unread can move. + * It never starts a turn. + */ + lastSeenMessageId: Schema.optional(MessageId), }), Schema.Struct({ type: Schema.Literal("thread.mark-unread"), commandId: CommandId, threadId: ThreadId, + /** On a shared thread, rewind only this founder's cursor. Older servers ignore it. */ + founder: Schema.optional(Founder), }), Schema.Struct({ type: Schema.Literal("thread.metadata.update"), diff --git a/packages/contracts/src/threadInbox.test.ts b/packages/contracts/src/threadInbox.test.ts index 97fb266ed09e7..6445ef3dfcb39 100644 --- a/packages/contracts/src/threadInbox.test.ts +++ b/packages/contracts/src/threadInbox.test.ts @@ -39,7 +39,7 @@ describe("shared fleet organizational inbox", () => { expect(matchesInboxView(j, "all")).toBe(true); expect(matchesInboxView(k, "all")).toBe(true); }); - it("keeps All until a founder is chosen, then defaults to that founder plus Agents", () => { + it("keeps All until a founder is chosen, then defaults to that founder plus Agents and Shared", () => { const decode = Schema.decodeUnknownSync(ClientSettingsSchema); const encode = Schema.encodeSync(ClientSettingsSchema); // Settings saved by the single-choice selector still decode; that choice is not carried over. @@ -54,10 +54,16 @@ describe("shared fleet organizational inbox", () => { expect(matchesInboxFilter(undefined, effectiveInboxFilter(upgraded))).toBe(true); const jeffClient = decode(encode({ ...upgraded, founderInboxOwner: "jeff" })); const filter = effectiveInboxFilter(jeffClient); - expect(filter).toEqual(["jeff", "agents"]); + expect(filter).toEqual(["jeff", "agents", "shared"]); expect(matchesInboxFilter(makeThreadInbox({ actor: jeff }), filter)).toBe(true); expect(matchesInboxFilter(makeThreadInbox({ actor: bot }), filter)).toBe(true); expect(matchesInboxFilter(makeThreadInbox({ actor: kameron }), filter)).toBe(false); + expect( + matchesInboxFilter( + makeThreadInbox({ actor: kameron, routing: { audience: "shared" } }), + filter, + ), + ).toBe(true); expect(matchesInboxFilter(undefined, filter)).toBe(false); const picked = decode(encode({ ...jeffClient, founderInboxFilter: ["kameron", "shared"] })); expect([effectiveInboxFilter(picked), picked.founderInboxOwner]).toEqual([ @@ -90,6 +96,7 @@ describe("shared fleet organizational inbox", () => { expect(effectiveInboxFilter({ founderInboxOwner: "jeff", founderInboxFilter: [] })).toEqual([ "jeff", "agents", + "shared", ]); // Every inbox is All, which keeps unclassified history. const every = ["shared", "jeff", "agents", "kameron"] as const; diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index c13d8c0ea84c8..b67815001fc1e 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -263,8 +263,9 @@ export function founderInboxLane(inbox: ThreadInbox | null | undefined, founder: } /** - * The inboxes the sidebar lists: the chosen ones, else the chosen founder's plus Agents, else - * every inbox so unclassified history stays visible. + * The inboxes the sidebar lists: the chosen ones, else the chosen founder's plus Agents and + * Shared, else every inbox so unclassified history stays visible. Shared is a default so both + * founders see shared bots without opening the filter. */ export const effectiveInboxFilter = (settings: { readonly founderInboxFilter?: ReadonlyArray | undefined; @@ -275,7 +276,7 @@ export const effectiveInboxFilter = (settings: { ? settings.founderInboxFilter : settings.founderInboxOwner === undefined ? InboxChoice.literals - : [settings.founderInboxOwner, "agents"]; + : [settings.founderInboxOwner, "agents", "shared"]; /** Choosing every inbox means All, which also keeps unclassified history. */ const isAllInboxes = (filter: ReadonlyArray) => diff --git a/packages/shared/src/seenMarker.test.ts b/packages/shared/src/seenMarker.test.ts index 1190ed7a666ef..883dffd96014f 100644 --- a/packages/shared/src/seenMarker.test.ts +++ b/packages/shared/src/seenMarker.test.ts @@ -1,7 +1,11 @@ import { MessageId } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; -import { formatSeenMarkerForProvider } from "./seenMarker.ts"; +import { + creditUnassignedSender, + formatSeenMarkerForProvider, + formatSharedSenderForProvider, +} from "./seenMarker.ts"; const seenAt = "2026-11-20T03:00:00.000Z"; describe("formatSeenMarkerForProvider", () => { @@ -40,3 +44,44 @@ describe("formatSeenMarkerForProvider", () => { expect(prose.endsWith("Review the diff")).toBe(true); }); }); + +describe("formatSharedSenderForProvider", () => { + it("names the founder on a shared send and leaves a command alone", () => { + expect(formatSharedSenderForProvider("Ship the fix", "jeff")).toBe( + "[From: Jeff]\n\nShip the fix", + ); + expect(formatSharedSenderForProvider("Ship the fix", "kameron")).toBe( + "[From: Kameron]\n\nShip the fix", + ); + expect(formatSharedSenderForProvider("Ship the fix", null)).toBe("Ship the fix"); + expect(formatSharedSenderForProvider("/compact", "jeff")).toBe("/compact"); + }); +}); + +describe("creditUnassignedSender", () => { + const desktop = { founder: null, deviceType: "desktop", sessionId: "s" } as const; + + it("credits a person's unassigned client to the machine owner", () => { + expect(creditUnassignedSender(desktop, "kameron")).toEqual({ ...desktop, founder: "kameron" }); + }); + + it("keeps an assigned founder, a bot, and a machine with no owner", () => { + expect(creditUnassignedSender({ ...desktop, founder: "jeff" }, "kameron").founder).toBe("jeff"); + expect(creditUnassignedSender({ ...desktop, deviceType: "bot" }, "kameron").founder).toBeNull(); + expect(creditUnassignedSender(desktop, null)).toEqual(desktop); + }); +}); + +describe("a shared catch-up", () => { + it("asks for two lines about the founder who was away", () => { + const text = formatSeenMarkerForProvider( + "Ship the fix", + { lastSeenMessageId: MessageId.make("message-user-1"), seenAt, unseenCount: 2 }, + "jeff", + ); + expect(text).toContain( + "Jeff last saw message message-user-1; 2 messages since are unseen. Open the reply with two lines on only those, while they were away.", + ); + expect(text.endsWith("Ship the fix")).toBe(true); + }); +}); diff --git a/packages/shared/src/seenMarker.ts b/packages/shared/src/seenMarker.ts index edaa492a118fa..25195d7ea61fa 100644 --- a/packages/shared/src/seenMarker.ts +++ b/packages/shared/src/seenMarker.ts @@ -1,14 +1,45 @@ -import type { ThreadSeenMarkerSummary } from "@t3tools/contracts"; +import type { Founder, ThreadSeenMarkerSummary } from "@t3tools/contracts"; + +const FOUNDER_NAMES = { kameron: "Kameron", jeff: "Jeff" } satisfies Record; + +/** `[From: Kameron]` on a shared thread, so the model knows which founder typed it. */ +export function formatSharedSenderForProvider( + text: string, + founder: Founder | null | undefined, +) { + if (founder == null) return text; + if (text.trim().startsWith("/")) return text; + return `[From: ${FOUNDER_NAMES[founder]}]\n\n${text}`; +} + +/** + * A person whose client nobody has named credits this machine's owner. An assigned client, a + * bot, and a machine with no owner stay as they are. + */ +export function creditUnassignedSender( + sentBy: T, + ownerFounder: Founder | null, +): T { + if (sentBy.founder !== null || sentBy.deviceType === "bot" || ownerFounder === null) { + return sentBy; + } + return { ...sentBy, founder: ownerFounder }; +} export function formatSeenMarkerForProvider( text: string, marker: ThreadSeenMarkerSummary | undefined, + founder?: Founder | null, ) { if (marker === undefined || marker.unseenCount === 0) return text; const noun = marker.unseenCount === 1 ? "message" : "messages"; + const who = founder ? FOUNDER_NAMES[founder] : null; + const catchUp = who + ? `${who} last saw message ${marker.lastSeenMessageId}; ${marker.unseenCount} ${noun} since are unseen. Open the reply with two lines on only those, while they were away.` + : `The user last saw message ${marker.lastSeenMessageId}; ${marker.unseenCount} ${noun} since are unseen. Open the reply with a short catch-up on only those.`; const block = [ ``, - `The user last saw message ${marker.lastSeenMessageId}; ${marker.unseenCount} ${noun} since are unseen. Open the reply with a short catch-up on only those.`, + catchUp, "", ].join("\n"); if (text.trim().startsWith("/")) return text;