From dd5d7ed00a6a7d129096934c758de407ad671dd3 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:09:53 +0000 Subject: [PATCH 1/3] feat(threads): show who sent every message Each message now names its sender: Kameron or Jeff (stamped by the server from the signed-in client session, so a client cannot spoof it), another thread or agent (named and linked, and a relay keeps its real sender), the thread's own model reply (provider and model), or system/automated events. Old messages show a sender only where stored data proves it; otherwise "Unknown sender". Adds a "From" filter to in-thread find and a sender filter to cross-thread thread search (people and model replies, which the search index covers). Connections settings can assign a paired client to Kameron or Jeff. Model: claude-opus-5-5 Task: message sender labels in every T3 thread Agent: Claude Code Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 15 ++ apps/mobile/src/lib/threadActivity.ts | 3 + apps/server/src/auth/EnvironmentAuth.ts | 70 ++++++ apps/server/src/auth/SessionStore.ts | 62 ++++++ apps/server/src/auth/http.ts | 17 ++ apps/server/src/mcp/OrchestratorMcpService.ts | 2 + .../src/orchestration-v2/EffectWorker.ts | 3 + .../src/orchestration-v2/Orchestrator.ts | 15 ++ .../orchestration-v2/ThreadLaunchService.ts | 6 + .../ThreadManagementService.ts | 25 ++- .../src/orchestration-v2/ThreadSearch.test.ts | 79 ++++++- .../src/orchestration-v2/ThreadSearch.ts | 75 ++++++- apps/server/src/persistence/AuthSessions.ts | 64 +++++- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/097_AuthSessionFounder.ts | 20 ++ apps/server/src/ws.ts | 30 ++- .../src/components/chat/MessageSenderLine.tsx | 68 ++++++ .../chat/MessagesTimeline.logic.test.ts | 67 +++++- .../components/chat/MessagesTimeline.logic.ts | 36 ++- .../src/components/chat/MessagesTimeline.tsx | 14 +- .../web/src/components/chat/ThreadFindBar.tsx | 29 +++ .../components/chat/TimelineAssistantRows.tsx | 11 +- .../chat/TimelineUserMessageRow.tsx | 19 +- .../src/components/chat/threadFindStore.ts | 13 ++ apps/web/src/components/chat/useThreadFind.ts | 9 + .../src/components/chat/useTimelineRows.ts | 18 ++ .../settings/AuthorizedClientsSettings.tsx | 31 +++ .../settings/ConnectionsSettings.tsx | 30 +++ apps/web/src/environments/primary/auth.ts | 2 + apps/web/src/session-logic.ts | 1 + apps/web/src/types.ts | 2 + apps/web/test/environmentHttpTest.ts | 1 + packages/client-runtime/package.json | 4 + .../client-runtime/src/messageSender.test.ts | 94 ++++++++ packages/client-runtime/src/messageSender.ts | 207 ++++++++++++++++++ packages/client-runtime/src/state/auth.ts | 12 + packages/client-runtime/src/userMessage.ts | 4 +- packages/contracts/src/auth.ts | 15 ++ packages/contracts/src/environmentHttp.ts | 11 + packages/contracts/src/orchestrationV2.ts | 23 +- packages/contracts/src/orchestratorMcp.ts | 9 + packages/contracts/src/threadSearch.ts | 34 ++- 42 files changed, 1214 insertions(+), 38 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/097_AuthSessionFounder.ts create mode 100644 apps/web/src/components/chat/MessageSenderLine.tsx create mode 100644 packages/client-runtime/src/messageSender.test.ts create mode 100644 packages/client-runtime/src/messageSender.ts diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 3e1ee80f2831f..c48e9a16280cb 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1,3 +1,8 @@ +import { + messageSenderDetail, + messageSenderLabel, + resolveMessageSender, +} from "@t3tools/client-runtime/message-sender"; import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; @@ -2100,6 +2105,7 @@ function renderFeedEntry( if (isUser) { const enterAnimated = isFreshTimestamp(message.createdAt); const foldRowId = presentation.attribution === "agent" ? `agent:${message.id}` : null; + const sender = resolveMessageSender(message); // A linked environment's agent sent it from a thread there. const senderRef = message.linkedSender ?? @@ -2164,6 +2170,15 @@ function renderFeedEntry( {presentation.guestName !== undefined ? ( ) : null} + {sender.kind === "person" && !props.userMessageGrouping.groupedWithPrevious ? ( + + {messageSenderLabel(sender)} + {messageSenderDetail(sender) === null ? "" : ` · ${messageSenderDetail(sender)}`} + + ) : null} {mediaAttachments.length + pendingMedia.length > 0 ? ( ()( + "ServerAuthSessionFounderError", + { + ...serverAuthInternalErrorContext, + }, +) { + override get message(): string { + return "Failed to read or record who uses a client."; + } +} + export const ServerAuthInternalError = Schema.Union([ ServerAuthBootstrapCredentialValidationError, ServerAuthSessionCredentialValidationError, @@ -374,6 +388,7 @@ export const ServerAuthInternalError = Schema.Union([ ServerAuthCloudHealthJwtSigningError, ServerAuthCloudMintJwtSigningError, ServerAuthConnectDevicesError, + ServerAuthSessionFounderError, ]); export type ServerAuthInternalError = typeof ServerAuthInternalError.Type; export const isServerAuthInternalError = Schema.is(ServerAuthInternalError); @@ -591,6 +606,17 @@ export class EnvironmentAuth extends Context.Service< readonly revokeOtherClientSessions: ( currentSessionId: AuthSessionId, ) => Effect.Effect; + /** Records who uses a client session, or clears it with null; false when it is not live. */ + readonly setClientSessionFounder: ( + targetSessionId: AuthSessionId, + founder: Founder | null, + ) => Effect.Effect; + /** + * Who sent a message on this session, read from the server's own record of it. A session it + * cannot read still names itself by id with no person, so a message never claims one it lacks + * and is never refused for want of a label. + */ + readonly messageSenderOf: (sessionId: AuthSessionId) => Effect.Effect; readonly authenticateHttpRequest: ( request: HttpServerRequest.HttpServerRequest, ) => Effect.Effect; @@ -1424,6 +1450,48 @@ export const make = Effect.gen(function* () { return yield* revokeSession(targetSessionId); }); + const setClientSessionFounder: EnvironmentAuth["Service"]["setClientSessionFounder"] = ( + targetSessionId, + founder, + ) => + sessions.setFounder(targetSessionId, founder).pipe( + Effect.mapError((cause) => new ServerAuthSessionFounderError({ cause })), + Effect.withSpan("EnvironmentAuth.setClientSessionFounder"), + ); + + const messageSenderOf: EnvironmentAuth["Service"]["messageSenderOf"] = (sessionId) => + sessions.senderOf(sessionId).pipe( + Effect.map( + (sender): OrchestrationV2MessageSentBy => ({ + sessionId, + device: Option.match(sender, { + onNone: () => "", + onSome: (value) => value.label ?? "", + }), + deviceType: Option.match(sender, { + onNone: () => "unknown" as const, + onSome: (value) => value.deviceType, + }), + founder: Option.match(sender, { + onNone: () => null, + onSome: (value) => value.founder, + }), + }), + ), + Effect.catchCause((cause) => + Effect.logWarning("Could not read who uses a client; its message names no person.").pipe( + Effect.annotateLogs({ sessionId, cause: Cause.pretty(cause) }), + Effect.as({ + sessionId, + device: "", + deviceType: "unknown" as const, + founder: null, + }), + ), + ), + Effect.withSpan("EnvironmentAuth.messageSenderOf"), + ); + const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = Effect.fn("EnvironmentAuth.revokeOtherClientSessions")(function* (currentSessionId) { const currentProofKey = yield* sessions @@ -1647,6 +1715,8 @@ export const make = Effect.gen(function* () { revokeSession, listClientSessions, revokeClientSession, + setClientSessionFounder, + messageSenderOf, revokeOtherClientSessions, authenticateHttpRequest, authenticateWebSocketUpgrade, diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index 2bd40e186ff7c..447751ee1ac62 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -5,6 +5,7 @@ import { type AuthClientMetadata, type AuthClientSession, type AuthEnvironmentScope, + type Founder, AuthWebSocketTicketUse, RuntimeMode, type ServerAuthSessionMethod, @@ -362,6 +363,18 @@ export class ProofKeySessionsError extends Schema.TaggedError()( + "SessionFounderUpdateError", + { + sessionId: AuthSessionId, + ...sessionCredentialInternalErrorContext, + }, +) { + override get message(): string { + return "Failed to record who uses this client."; + } +} + export const SessionCredentialInternalError = Schema.Union([ SessionClaimsEncodingError, SessionCredentialIssueError, @@ -372,6 +385,7 @@ export const SessionCredentialInternalError = Schema.Union([ SessionRevocationError, OtherSessionsRevocationError, ProofKeySessionsError, + SessionFounderUpdateError, ]); export type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type; @@ -381,6 +395,12 @@ export const SessionCredentialError = Schema.Union([ ]); export type SessionCredentialError = typeof SessionCredentialError.Type; +export interface AuthSessionSender { + readonly label: string | null; + readonly deviceType: AuthClientMetadata["deviceType"]; + readonly founder: Founder | null; +} + export class SessionStore extends Context.Service< SessionStore, { @@ -446,6 +466,15 @@ export class SessionStore extends Context.Service< readonly revokeAllExcept: ( sessionId: AuthSessionId, ) => Effect.Effect; + /** Records who uses a live session, or clears it with null; false when it is not live. */ + readonly setFounder: ( + sessionId: AuthSessionId, + founder: Founder | null, + ) => Effect.Effect; + /** The stored name, kind and assigned person of a session, for stamping who sent a message. */ + readonly senderOf: ( + sessionId: AuthSessionId, + ) => Effect.Effect, SessionCredentialInternalError>; readonly proofKeyThumbprintOf: ( sessionId: AuthSessionId, ) => Effect.Effect, SessionCredentialInternalError>; @@ -610,6 +639,7 @@ const make = Effect.gen(function* () { expiresAt: row.value.expiresAt, lastConnectedAt: row.value.lastConnectedAt, connected, + ...(row.value.founder === null ? {} : { founder: row.value.founder }), }), ); }); @@ -1056,6 +1086,7 @@ const make = Effect.gen(function* () { expiresAt: row.expiresAt, lastConnectedAt: row.lastConnectedAt, connected: connectedSessions.has(row.sessionId), + ...(row.founder === null ? {} : { founder: row.founder }), }), ); }, @@ -1083,6 +1114,35 @@ const make = Effect.gen(function* () { }, ); + const setFounder: SessionStore["Service"]["setFounder"] = Effect.fn("SessionStore.setFounder")( + function* (sessionId, founder) { + const updated = yield* authSessions + .setFounder({ sessionId, founder }) + .pipe(Effect.mapError((cause) => new SessionFounderUpdateError({ sessionId, cause }))); + if (updated) { + const session = yield* loadActiveSession(sessionId).pipe( + Effect.mapError((cause) => new SessionFounderUpdateError({ sessionId, cause })), + ); + if (Option.isSome(session)) yield* emitUpsert(session.value); + } + return updated; + }, + ); + + const senderOf: SessionStore["Service"]["senderOf"] = (sessionId) => + authSessions.getById({ sessionId }).pipe( + Effect.map( + Option.map( + (row): AuthSessionSender => ({ + label: row.client.label, + deviceType: row.client.deviceType, + founder: row.founder, + }), + ), + ), + Effect.mapError((cause) => new ActiveSessionsListError({ cause })), + ); + const proofKeyThumbprintOf: SessionStore["Service"]["proofKeyThumbprintOf"] = (sessionId) => authSessions .getProofKeyThumbprint({ sessionId }) @@ -1212,6 +1272,8 @@ const make = Effect.gen(function* () { }, revoke, revokeAllExcept, + setFounder, + senderOf, proofKeyThumbprintOf, revokeByProofKey, markConnected, diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index b8b49a1d1b347..4e1860c6bb42f 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -538,6 +538,23 @@ export const layer = HttpApiBuilder.group( ), ), ) + .handle( + "setClientFounder", + Effect.fn("environment.auth.setClientFounder")( + function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthAccessWriteScope); + const updated = yield* serverAuth.setClientSessionFounder( + args.payload.sessionId, + args.payload.founder, + ); + return { updated }; + }, + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => + failEnvironmentInternal("client_session_founder_failed", error), + ), + ), + ) .handle( "approveConnectDevice", Effect.fn("environment.auth.approveConnectDevice")( diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8698aa87b82b7..d7011fb06033d 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1184,6 +1184,8 @@ function timelineItem(input: { createdBy: message?.createdBy ?? null, creationSource: message?.creationSource ?? null, ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), + ...(message?.linkedSender === undefined ? {} : { linkedSender: message.linkedSender }), + ...(message?.sentBy === undefined ? {} : { sentBy: message.sentBy }), type: input.row.item.type, status: input.row.item.status, title: input.row.item.title, diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index c6aa09efd5e69..8781151e30bc8 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -424,6 +424,9 @@ export const layerExecutor: Layer.Layer< ...(message.linkedSender === undefined ? {} : { linkedSender: message.linkedSender }), + ...(message.sentBy === undefined + ? {} + : { sentBy: message.sentBy }), }) .pipe( // A disabled instance cannot retry this completed turn; its result stands. diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 10453a2a54fb3..0e3ccb947ca99 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3046,6 +3046,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(queuedMessage.linkedSender === undefined ? {} : { linkedSender: queuedMessage.linkedSender }), + ...(queuedMessage.sentBy === undefined + ? {} + : { sentBy: queuedMessage.sentBy }), ...(queuedMessage.idleCompaction === undefined ? {} : { idleCompaction: queuedMessage.idleCompaction }), @@ -6081,6 +6084,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"]; readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"]; readonly linkedSender?: OrchestrationV2ConversationMessage["linkedSender"]; + readonly sentBy?: OrchestrationV2ConversationMessage["sentBy"]; readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"]; readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"]; readonly notification?: OrchestrationV2ConversationMessage["notification"]; @@ -6226,6 +6230,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: input.scheduledTaskId }), ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }), ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }), + ...(input.sentBy === undefined ? {} : { sentBy: input.sentBy }), ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }), id: input.messageId, threadId: input.command.threadId, @@ -6247,6 +6252,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: input.scheduledTaskId }), ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }), ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }), + ...(input.sentBy === undefined ? {} : { sentBy: input.sentBy }), ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }), id: idAllocator.derive.userTurnItem({ messageId: input.messageId }), threadId: input.command.threadId, @@ -7492,6 +7498,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), forceRestart: dispatchMode.type === "restart_active", }); @@ -7787,6 +7794,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined ? { followsThreadSelection: true as const } @@ -8205,6 +8213,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined ? { followsThreadSelection: true as const } @@ -8231,6 +8240,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), threadId: command.threadId, @@ -9001,6 +9011,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: command.messageId, threadId: command.threadId, @@ -9024,6 +9035,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), threadId: command.threadId, @@ -11568,6 +11580,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(queuedMessage.linkedSender === undefined ? {} : { linkedSender: queuedMessage.linkedSender }), + ...(queuedMessage.sentBy === undefined + ? {} + : { sentBy: queuedMessage.sentBy }), ...(queuedMessage.idleCompaction === undefined ? {} : { idleCompaction: queuedMessage.idleCompaction }), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 5810575fe67a6..c0045f7aa8058 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -12,6 +12,7 @@ import { type OrchestrationV2Actor, type OrchestrationV2CreationSource, type OrchestrationV2DelegatedFrom, + type OrchestrationV2MessageSentBy, type OrchestrationV2LinkOrigin, type OrchestrationV2ProviderThreadNativeMetadata, type OrchestrationV2ThreadProjection, @@ -83,6 +84,8 @@ export interface ThreadLaunchInitialMessage { readonly messageId?: MessageId; readonly scheduledTaskId?: ScheduledTaskId; readonly senderThreadId?: ThreadId; + /** The signed-in client a person typed this on. Only the server's WebSocket handler sets it. */ + readonly sentBy?: OrchestrationV2MessageSentBy; readonly text: string; readonly attachments: ReadonlyArray; readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined; @@ -1291,6 +1294,9 @@ const make = Effect.gen(function* () { ...(input.initialMessage.senderThreadId === undefined ? {} : { senderThreadId: input.initialMessage.senderThreadId }), + ...(input.initialMessage.sentBy === undefined + ? {} + : { sentBy: input.initialMessage.sentBy }), attachments: input.initialMessage.attachments, ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}), ...(input.generateTitle === true ? { titleSeed: input.title } : {}), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 5d9eb00052977..6069a39da15e8 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -28,6 +28,7 @@ import { type OrchestrationV2ConversationMessage, type OrchestrationV2CreationSource, type OrchestrationV2LinkedSender, + type OrchestrationV2MessageSentBy, type OrchestrationV2Run, type OrchestrationV2ThreadShellSnapshot, type OrchestrationV2ThreadProjection, @@ -78,6 +79,8 @@ export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart"; export interface ThreadManagementProvenance { readonly createdBy: OrchestrationV2Actor; readonly creationSource: OrchestrationV2CreationSource; + /** The signed-in client a person typed a message on. Only the server knows it. */ + readonly sentBy?: OrchestrationV2MessageSentBy; } export function withCreationProvenance( @@ -95,11 +98,27 @@ export function withCreationProvenance( } = command; return { ...rest, ...provenance }; } - case "message.dispatch": + case "message.dispatch": { + // Who sent a message is the server's to say. A client cannot pass itself off as another + // thread, a notification, a scheduled task, an idle compaction or another person's device. + const { + senderThreadId: _senderThreadId, + linkedSender: _linkedSender, + notification: _notification, + scheduledTaskId: _scheduledTaskId, + idleCompaction: _idleCompaction, + sentBy: _sentBy, + ...rest + } = command; + const { sentBy, ...actor } = provenance; + return { ...rest, ...actor, ...(sentBy === undefined ? {} : { sentBy }) }; + } case "thread.fork": case "thread.merge_back": - case "delegated_task.request": - return { ...command, ...provenance }; + case "delegated_task.request": { + const { sentBy: _sentBy, ...actor } = provenance; + return { ...command, ...actor }; + } default: return command; } diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 399224533089d..1bcade72198a5 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + AuthSessionId, EnvironmentId, EventId, MessageId, @@ -9,6 +10,8 @@ import { RunId, ThreadId, TurnItemId, + type OrchestrationV2ConversationMessage as ConversationMessage, + type OrchestrationSearchSenderFilter, type OrchestrationV2DomainEvent, type ThreadLinkedPullRequest, } from "@t3tools/contracts"; @@ -132,8 +135,11 @@ const message = ( options: { readonly minute?: number; readonly streaming?: boolean; - readonly createdBy?: "user" | "agent"; + readonly createdBy?: "user" | "agent" | "system"; readonly runId?: RunId; + readonly extra?: Partial< + Pick + >; } = {}, ): OrchestrationV2DomainEvent => ({ id: EventId.make(`message:${id}`), @@ -154,6 +160,7 @@ const message = ( streaming: options.streaming ?? false, createdAt: at(options.minute ?? 1), updatedAt: at(options.minute ?? 1), + ...options.extra, }, }); @@ -291,7 +298,7 @@ it.layer(layerTest)("ThreadSearch", (it) => { for (const match of ['"needle"', null]) { const plan = yield* sql<{ readonly detail: string; - }>`EXPLAIN QUERY PLAN ${ThreadSearch.messageHitsQuery(sql, { match, substrings: "[]", shortSpellings: "[]", projectId: null, excludedThreadIds: "[]" })}`; + }>`EXPLAIN QUERY PLAN ${ThreadSearch.messageHitsQuery(sql, { match, substrings: "[]", shortSpellings: "[]", projectId: null, excludedThreadIds: "[]", sender: null })}`; assert.isFalse( plan.some((row) => row.detail.includes("TEMP B-TREE")), plan.map((row) => row.detail).join("\n"), @@ -1500,3 +1507,71 @@ it.effect("searches on the reader worker while the writer is busy", () => }).pipe(Effect.provide(layerFile)); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + +it.effect("ThreadSearch filters messages by who sent them, keeping a relay's real sender", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const search = yield* ThreadSearch.ThreadSearch; + const project = ProjectId.make("project:senders"); + const threadId = ThreadId.make("thread:senders"); + const sentBy = (founder: "kameron" | "jeff" | null) => ({ + sessionId: AuthSessionId.make(`session:${founder ?? "unassigned"}`), + device: `${founder ?? "spare"} laptop`, + deviceType: "desktop" as const, + founder, + }); + yield* createProject(project); + yield* Effect.forEach( + [ + thread(threadId, project), + message(threadId, "from-kameron", "user", "deploy the harbor build", { + minute: 1, + extra: { sentBy: sentBy("kameron") }, + }), + message(threadId, "from-jeff", "user", "harbor invoices are due", { + minute: 2, + extra: { sentBy: sentBy("jeff") }, + }), + // Pasted in by another thread on Kameron's behalf: still that thread's message. + message(threadId, "relayed", "user", "relay: harbor build finished", { + minute: 3, + createdBy: "agent", + extra: { + senderThreadId: ThreadId.make("thread:relay"), + linkedSender: { + environmentId: EnvironmentId.make("environment:local"), + threadId: ThreadId.make("thread:relay"), + title: "Relay lane", + }, + }, + }), + message(threadId, "legacy", "user", "harbor notes from before stamping", { minute: 4 }), + message(threadId, "reply", "assistant", "harbor build is green", { minute: 5 }), + message(threadId, "notice", "user", "harbor compacted", { + minute: 6, + createdBy: "system", + extra: { creationSource: "server" }, + }), + ], + projections.apply, + { discard: true }, + ); + const ids = (sender: OrchestrationSearchSenderFilter, query = "") => + search + .search({ query, sender }) + .pipe(Effect.map(({ matches }) => matches.map((match) => match.messageId).toSorted())); + assert.deepEqual(yield* ids("kameron"), [MessageId.make("from-kameron")]); + assert.deepEqual(yield* ids("jeff", "invoices"), [MessageId.make("from-jeff")]); + assert.deepEqual(yield* ids("jeff", "deploy"), []); + assert.deepEqual(yield* ids("model"), [MessageId.make("reply")]); + // A relay is the sending thread's, never the person it relays for, and a notice is + // T3 Code's; neither is a person's. Search keeps one hit per thread: the newest person's, + // an unstamped old message that proves no founder. + assert.deepEqual(yield* ids("people", "harbor"), [MessageId.make("legacy")]); + assert.deepEqual(yield* ids("people", "relay"), []); + assert.deepEqual(yield* ids("people", "compacted"), []); + assert.deepEqual(yield* ids("kameron", "relay"), []); + // Without a sender, a one-letter query still finds nothing. + assert.deepEqual((yield* search.search({ query: "h" })).matches, []); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index 3ad48b26f172d..caf1d30d79c6c 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -1,6 +1,7 @@ import { IsoDateTime, MessageId, + OrchestrationSearchSenderFilter, OrchestrationThreadSearchSource, OrchestrationV2AppThreadJson, OrchestrationV2ThreadOpens, @@ -79,6 +80,8 @@ const SearchRequest = Schema.Struct({ projectId: Schema.NullOr(ProjectId), /** Threads the caller already lists, left out before the hit limit. */ excludedThreadIds: TokenList, + /** Only messages from this sender, or null for anyone's. */ + sender: Schema.NullOr(OrchestrationSearchSenderFilter), }); const SearchRow = Schema.Struct({ messageRowid: Schema.Number, @@ -163,8 +166,13 @@ function accentInsensitiveGlob(token: string): string { function buildMessageSearch( query: string, hasIndex: boolean, -): Omit | null { + bySender: boolean, +): Omit | null { const { long, short } = messageSearchTokens(query); + // With a sender and no words, every one of that sender's newest messages is a hit. + if (long.length === 0 && short.length === 0 && bySender) { + return { match: null, substrings: [], shortSpellings: [] }; + } if (long.length === 0) return null; // Two-character CJK words are too short for trigrams. const indexed = hasIndex && long.every((token) => Array.from(token).length >= 3); @@ -213,13 +221,50 @@ export function buildSearchSnippet(text: string, matchStart: number): string { return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`; } +/** + * Whether the message aliased `messages` is from `sender`, sorted as `resolveMessageSender` in + * client-runtime sorts it. Only stored fields count, so an old message names no person: it is + * among "people" but never Kameron's or Jeff's. A legacy scheduled-task prompt whose only mark is + * its text prefix stays with people here, where the client calls it an automation. + */ +export const messageSenderCondition = ( + sql: SqlClient.SqlClient, + sender: OrchestrationSearchSenderFilter | null, +) => { + if (sender === null) return sql`1`; + if (sender === "model") return sql`messages.role = 'assistant'`; + const field = (path: string) => sql`json_extract(messages.payload_json, ${path})`; + // The index holds only messages people typed (createdBy 'user') and the model's replies, so + // what remains is whether a person typed it, as opposed to a guest, an automation or a relay. + const guest = sql`${field("$.context.guest")} IS NOT NULL`; + const person = sql`(NOT ${guest} + AND ${field("$.idleCompaction")} IS NULL + AND ${field("$.scheduledTaskId")} IS NULL + AND ${field("$.senderThreadId")} IS NULL + AND ${field("$.linkedSender")} IS NULL)`; + switch (sender) { + case "kameron": + case "jeff": + return sql`(messages.role = 'user' AND ${person} AND ${field("$.sentBy.founder")} = ${sender})`; + case "people": + return sql`(messages.role = 'user' AND (${guest} OR ${person}))`; + } +}; + // Filter hidden subagents and side chats before the hit limit; JS checks word starts and ranking. // Both paths narrow ASCII tokens with Latin-1 and Extended-A/B/Additional accent variants. // Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages; // accented queries and non-Latin case can still miss: "fermée"/"fermee", "ОШИБКА"/"ошибка". export const messageHitsQuery = ( sql: SqlClient.SqlClient, - { match, substrings, shortSpellings, projectId, excludedThreadIds }: typeof SearchRequest.Encoded, + { + match, + substrings, + shortSpellings, + projectId, + excludedThreadIds, + sender, + }: typeof SearchRequest.Encoded, ) => sql` WITH eligible AS MATERIALIZED ( SELECT threads.thread_id, threads.project_id @@ -280,6 +325,7 @@ export const messageHitsQuery = ( -- Answers to an agent's question show inside its question card, where -- neither find nor a jump can reach them. AND messages.message_id NOT LIKE 'async-answer:%' + AND ${messageSenderCondition(sql, sender)} -- Nor can they reach a rolled-back turn, or a message of a stopped turn -- that no shown item carries, such as a queued prompt that never ran. AND NOT EXISTS ( @@ -530,13 +576,18 @@ export const make = Effect.gen(function* () { const index = yield* sql` SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search' `; - const messageSearch = buildMessageSearch(input.query, index.length > 0); + const messageSearch = buildMessageSearch( + input.query, + index.length > 0, + input.sender !== undefined, + ); return messageSearch === null ? [] : yield* searchRows({ ...messageSearch, projectId: input.projectId, excludedThreadIds: [...(input.excludedThreadIds ?? [])], + sender: input.sender ?? null, }); }), ); @@ -546,7 +597,8 @@ export const make = Effect.gen(function* () { // for "rust") never add to a whole word's count. const hitCounts = new Map(); const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1; - const matchMessage = messageMatcher(input.query); + const anyText = input.sender !== undefined && foldSearchQuery(input.query).trim() === ""; + const matchMessage = anyText ? () => ({ quality: 1, offset: 0 }) : messageMatcher(input.query); for (const row of rows) { const text = row.text.replace(MARKDOWN_LINK, "$1"); const match = matchMessage(text); @@ -601,11 +653,14 @@ export const make = Effect.gen(function* () { }); const search: ThreadSearch["Service"]["search"] = (input) => - searchMessages({ ...input, projectId: null }); + input.sender === undefined && input.query.trim().length < 2 + ? Effect.succeed({ matches: [] }) + : searchMessages({ ...input, projectId: null }); const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn( "ThreadSearch.searchThreads", )(function* (input) { + if (input.sender === undefined && input.query.trim().length < 2) return { matches: [] }; const limit = input.limit ?? 50; const normalizedQuery = foldSearchQuery(input.query); const now = DateTime.toEpochMillis(yield* DateTime.now); @@ -629,12 +684,16 @@ export const make = Effect.gen(function* () { }, ]), ); - const titleHits: ThreadSearchHit[] = rankSearchItems(candidates, (row, options) => + // A sender filter is about messages, so titles neither match nor take slots. + const titleHits: ThreadSearchHit[] = (input.sender === undefined + ? rankSearchItems(candidates, (row, options) => // An agent's search has no use for the user's palette picks. scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, { ...options, picks: false, }), + ) + : [] ) .slice(0, limit) .map(({ item }) => ({ @@ -650,6 +709,7 @@ export const make = Effect.gen(function* () { projectId: input.projectId ?? null, excludedThreadIds: shown, picks: false, + ...(input.sender === undefined ? {} : { sender: input.sender }), }); const messageHits = matches .filter((match) => subjectById.has(match.threadId)) @@ -659,7 +719,8 @@ export const make = Effect.gen(function* () { })); // Titles come first, but a fifth of the slots stay for message matches, // as the palette keeps its "In messages" section. - const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5)); + const messageSlots = + input.sender === undefined ? Math.min(messageHits.length, Math.floor(limit / 5)) : limit; return { matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit), }; diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts index d140af3444203..1d92c0f0262bc 100644 --- a/apps/server/src/persistence/AuthSessions.ts +++ b/apps/server/src/persistence/AuthSessions.ts @@ -11,6 +11,7 @@ import { AuthClientMetadataDeviceType, AuthEnvironmentScopes, AuthSessionId, + Founder, ServerAuthSessionMethod, } from "@t3tools/contracts"; @@ -41,6 +42,8 @@ export const AuthSessionRecord = Schema.Struct({ expiresAt: Schema.DateTimeUtcFromString, lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString), revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + /** Who an admin says uses this client; null until assigned. */ + founder: Schema.NullOr(Founder), }); export type AuthSessionRecord = typeof AuthSessionRecord.Type; @@ -106,6 +109,12 @@ export const SetAuthSessionLastConnectedAtInput = Schema.Struct({ }); export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type; +export const SetAuthSessionFounderInput = Schema.Struct({ + sessionId: AuthSessionId, + founder: Schema.NullOr(Founder), +}); +export type SetAuthSessionFounderInput = typeof SetAuthSessionFounderInput.Type; + export class AuthSessionRepository extends Context.Service< AuthSessionRepository, { @@ -137,6 +146,10 @@ export class AuthSessionRepository extends Context.Service< readonly setLastConnectedAt: ( input: SetAuthSessionLastConnectedAtInput, ) => Effect.Effect; + /** Records who uses a live session; false when it is revoked or unknown. */ + readonly setFounder: ( + input: SetAuthSessionFounderInput, + ) => Effect.Effect; readonly getProofKeyThumbprint: ( input: GetAuthSessionByIdInput, ) => Effect.Effect, AuthSessionRepositoryError>; @@ -161,6 +174,7 @@ const AuthSessionDbRow = Schema.Struct({ expiresAt: Schema.DateTimeUtcFromString, lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString), revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + founder: Schema.NullOr(Founder), }); const AuthSessionRawDbRow = Schema.Struct({ @@ -178,6 +192,7 @@ const AuthSessionRawDbRow = Schema.Struct({ expiresAt: Schema.Unknown, lastConnectedAt: Schema.Unknown, revokedAt: Schema.Unknown, + founder: Schema.Unknown, }); const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow); @@ -200,6 +215,7 @@ function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionReco expiresAt: row.expiresAt, lastConnectedAt: row.lastConnectedAt, revokedAt: row.revokedAt, + founder: row.founder, }; } @@ -284,7 +300,8 @@ export const make = Effect.gen(function* () { issued_at AS "issuedAt", expires_at AS "expiresAt", last_connected_at AS "lastConnectedAt", - revoked_at AS "revokedAt" + revoked_at AS "revokedAt", + founder AS "founder" FROM auth_sessions WHERE session_id = ${sessionId} `, @@ -292,7 +309,7 @@ export const make = Effect.gen(function* () { const revokeActiveSessionsForReplacement = SqlSchema.findAll({ Request: CreateReplacingActiveAuthSessionInput, - Result: Schema.Struct({ sessionId: AuthSessionId }), + Result: Schema.Struct({ sessionId: AuthSessionId, founder: Schema.NullOr(Founder) }), execute: ({ session, revokedAt, replaceSessionId }) => sql` UPDATE auth_sessions @@ -305,7 +322,7 @@ export const make = Effect.gen(function* () { AND method = ${session.method} AND revoked_at IS NULL AND expires_at > ${revokedAt} - RETURNING session_id AS "sessionId" + RETURNING session_id AS "sessionId", founder AS "founder" `, }); @@ -328,7 +345,8 @@ export const make = Effect.gen(function* () { issued_at AS "issuedAt", expires_at AS "expiresAt", last_connected_at AS "lastConnectedAt", - revoked_at AS "revokedAt" + revoked_at AS "revokedAt", + founder AS "founder" FROM auth_sessions WHERE revoked_at IS NULL AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)}) @@ -347,6 +365,19 @@ export const make = Effect.gen(function* () { `, }); + const setFounderRows = SqlSchema.findAll({ + Request: SetAuthSessionFounderInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ sessionId, founder }) => + sql` + UPDATE auth_sessions + SET founder = ${founder} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + RETURNING session_id AS "sessionId" + `, + }); + const revokeSessionRows = SqlSchema.findAll({ Request: RevokeAuthSessionInput, Result: Schema.Struct({ sessionId: AuthSessionId }), @@ -431,6 +462,18 @@ export const make = Effect.gen(function* () { revokeActiveSessionsForReplacement(input).pipe( Effect.flatMap((revokedRows) => createSessionRow(input.session).pipe( + Effect.andThen(() => { + // Re-pairing one named client keeps who uses it. Replacing every session for a + // subject could span several devices, so that never carries a person over. + const founders = new Set(revokedRows.map((row) => row.founder)); + const [founder] = founders; + return input.replaceSessionId !== undefined && + founders.size === 1 && + founder !== null && + founder !== undefined + ? setFounderRows({ sessionId: input.session.sessionId, founder }) + : Effect.void; + }), Effect.as(revokedRows.map((row) => row.sessionId)), ), ), @@ -557,6 +600,18 @@ export const make = Effect.gen(function* () { ), ); + const setFounder: AuthSessionRepository["Service"]["setFounder"] = (input) => + setFounderRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.setFounder:query", + "AuthSessionRepository.setFounder:decodeRows", + { sessionId: input.sessionId }, + ), + ), + Effect.map((rows) => rows.length > 0), + ); + const getProofKeyThumbprint: AuthSessionRepository["Service"]["getProofKeyThumbprint"] = ( input, ) => @@ -593,6 +648,7 @@ export const make = Effect.gen(function* () { extend, revokeAllExcept, setLastConnectedAt, + setFounder, getProofKeyThumbprint, revokeByProofKey, } satisfies AuthSessionRepository["Service"]; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 55c2f67c8c4aa..6118c51093f9c 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -104,6 +104,7 @@ import Migration0093 from "./Migrations/093_ProviderTurnAttemptIndex.ts"; import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts"; import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts"; +import Migration0097 from "./Migrations/097_AuthSessionFounder.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -203,6 +204,7 @@ const migrationEntries = [ [94, "TurnItemMessageOrdinalIndex", Migration0094], [95, "TurnItemInlineWorkOutput", Migration0095], [96, "RepairStaleTitleRegeneration", Migration0096], + [97, "AuthSessionFounder", Migration0097], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/097_AuthSessionFounder.ts b/apps/server/src/persistence/Migrations/097_AuthSessionFounder.ts new file mode 100644 index 0000000000000..3f56cb408dd35 --- /dev/null +++ b/apps/server/src/persistence/Migrations/097_AuthSessionFounder.ts @@ -0,0 +1,20 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Who an admin says uses a signed-in client, so messages sent from it name that person. + * Null until someone assigns it; nothing guesses a value for existing sessions. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_sessions) + `; + if (!columns.some((column) => column.name === "founder")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN founder TEXT + `; + } +}); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 34678f8ae2bd6..da87f5b9c3166 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -62,6 +62,7 @@ import { SETTINGS_SECRET_REFERENCES_CAPABILITY, ORCHESTRATION_PROTOCOL_VERSION, OrchestrationV2DispatchCommandError, + type OrchestrationV2MessageSentBy, OrchestrationV2GetShellSnapshotError, OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, @@ -2052,12 +2053,23 @@ export const layerWsRpc = ( .enqueueCommand( (command.type === "prepared-run.retry" ? threadLaunch.retryPreparation(command) - : ThreadMessageIntake.dispatchCommand( - ThreadManagementService.withCreationProvenance(command, { - createdBy: "user", - creationSource: - "creationSource" in command ? command.creationSource : "web", - }), + : (command.type === "message.dispatch" + ? serverAuth.messageSenderOf(currentSessionId).pipe(Effect.asSome) + : Effect.succeed(Option.none()) + ).pipe( + Effect.flatMap((sentBy) => + ThreadMessageIntake.dispatchCommand( + ThreadManagementService.withCreationProvenance(command, { + createdBy: "user", + creationSource: + "creationSource" in command ? command.creationSource : "web", + ...Option.match(sentBy, { + onNone: () => ({}), + onSome: (value) => ({ sentBy: value }), + }), + }), + ), + ), ) ).pipe(Effect.provide(intakeContext)), ) @@ -2244,6 +2256,11 @@ export const layerWsRpc = ( }) .pipe( Effect.andThen( + input.initialMessage === undefined + ? Effect.undefined + : serverAuth.messageSenderOf(currentSessionId), + ), + Effect.flatMap((sentBy) => ThreadMessageIntake.launchThread({ commandId: input.commandId, ...(input.inboxOrigin === undefined @@ -2277,6 +2294,7 @@ export const layerWsRpc = ( ...(input.initialMessage.context === undefined ? {} : { context: input.initialMessage.context }), + ...(sentBy === undefined ? {} : { sentBy }), }, }), createdBy: "user", diff --git a/apps/web/src/components/chat/MessageSenderLine.tsx b/apps/web/src/components/chat/MessageSenderLine.tsx new file mode 100644 index 0000000000000..b62cdc82da6dc --- /dev/null +++ b/apps/web/src/components/chat/MessageSenderLine.tsx @@ -0,0 +1,68 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId, RunId } from "@t3tools/contracts"; +import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; +import { + messageSenderDetail, + messageSenderLabel, + type MessageSender, +} from "@t3tools/client-runtime/message-sender"; + +import { brandProviderInstanceEntries, deriveProviderInstanceEntries } from "../../providerInstances"; +import { serverEnvironment } from "../../state/server"; +import { getTriggerDisplayModelName } from "./providerIconUtils"; + +/** "Kameron · Work laptop", "Unknown sender", or "Claude · Opus 5.5": who wrote the message. */ +export function MessageSenderLine({ + sender, + align, +}: { + readonly sender: MessageSender; + readonly align: "start" | "end"; +}) { + const label = messageSenderLabel(sender); + const detail = messageSenderDetail(sender); + return ( +

+ {label} + {detail === null ? null : · {detail}} +

+ ); +} + +/** The provider and model of the run behind an assistant message, by their names in the picker. */ +export function useRunModelSender( + environmentId: EnvironmentId, + runs: ReadonlyArray, + runId: RunId | null, +): MessageSender { + const run = runId === null ? undefined : runs.find((candidate) => candidate.id === runId); + const settings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId)); + const providersAtom = serverEnvironment.providersValueAtom(environmentId); + const entryOf = (providers: Parameters[0] | null) => { + if (run === undefined) return undefined; + const derived = deriveProviderInstanceEntries(providers ?? []); + const entries = settings ? brandProviderInstanceEntries(derived, settings) : derived; + return entries.find((candidate) => candidate.instanceId === run.modelSelection.instanceId); + }; + // Select strings: provider status pushes replace the list even when names are unchanged. + const provider = useAtomValue(providersAtom, (providers) => { + if (run === undefined) return null; + return entryOf(providers)?.displayName ?? run.modelSelection.instanceId; + }); + const model = useAtomValue(providersAtom, (providers) => { + if (run === undefined) return null; + const entry = entryOf(providers); + const known = entry?.models.find((candidate) => candidate.slug === run.modelSelection.model); + return known === undefined + ? run.modelSelection.model + : getTriggerDisplayModelName(known, entry?.driverKind); + }); + return { kind: "model", provider, model }; +} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 1cd8066dbcd32..8d05c43e39d43 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -25,10 +25,11 @@ import { } from "../../test-fixtures"; import type { TurnDiffSummary } from "../../types"; import { describe, expect, it } from "vite-plus/test"; -import { MessageId, RunId } from "@t3tools/contracts"; +import { AuthSessionId, MessageId, RunId } from "@t3tools/contracts"; import { computeStableMessagesTimelineRows, deriveMessagesTimelineRows, + filterTimelineRowsBySender, timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, deriveMessagesTimelineRowsWithState, @@ -5158,3 +5159,67 @@ describe("isTimelineMinimapTurnVisible", () => { expect(isTimelineMinimapTurnVisible(10, 500, null, null)).toBe(false); }); }); + +describe("message senders in the timeline", () => { + const runId = RunId.make("sender-run"); + const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString(); + const sentBy = (founder: "kameron" | "jeff") => ({ + sessionId: AuthSessionId.make(`session:${founder}`), + device: `${founder} laptop`, + deviceType: "desktop" as const, + founder, + }); + const message = ( + id: string, + second: number, + role: "user" | "assistant", + extra: Partial["message"] = undefined, + ): TimelineEntry => ({ + kind: "message", + id, + createdAt: time(second), + message: { + id: MessageId.make(id), + role, + text: id, + runId, + createdAt: time(second), + updatedAt: time(second), + streaming: false, + ...extra, + }, + }); + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + message("kameron-1", 0, "user", { sentBy: sentBy("kameron") } as never), + message("kameron-2", 1, "user", { sentBy: sentBy("kameron") } as never), + message("jeff-1", 2, "user", { sentBy: sentBy("jeff") } as never), + message("reply", 3, "assistant"), + ], + latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) }, + isWorking: false, + expandedRunIds: new Set(), + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + + it("groups consecutive messages only under one sender", () => { + const byId = new Map(rows.map((row) => [row.id, row])); + expect(byId.get("kameron-1")).toMatchObject({ groupedWithNext: true }); + expect(byId.get("kameron-2")).toMatchObject({ + groupedWithPrevious: true, + groupedWithNext: false, + }); + // Jeff's message starts a new group, so it shows his name. + expect(byId.get("jeff-1")).not.toHaveProperty("groupedWithPrevious", true); + }); + + it("keeps only the chosen sender's messages", () => { + expect(filterTimelineRowsBySender(rows, null)).toBe(rows); + expect(filterTimelineRowsBySender(rows, "jeff").map((row) => row.id)).toEqual(["jeff-1"]); + expect(filterTimelineRowsBySender(rows, "model").map((row) => row.id)).toEqual(["reply"]); + const kameron = filterTimelineRowsBySender(rows, "kameron"); + expect(kameron.map((row) => row.id)).toEqual(["kameron-1", "kameron-2"]); + expect(kameron[1]).toMatchObject({ groupedWithPrevious: false }); + }); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 5c4f99d76dc44..c4869c99cea24 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -13,6 +13,12 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; +import { + messageSenderMatches, + resolveMessageSender, + sameMessageSender, +} from "@t3tools/client-runtime/message-sender"; +import type { OrchestrationMessageSenderFilter } from "@t3tools/contracts"; import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; import { commandDisplayText, @@ -2361,8 +2367,15 @@ export function deriveMessagesTimelineRows(input: { } if (!timelineRowIsOwnUserMessage(row)) return row; const previous = result[index - 1]; - const groupedWithNext = timelineRowIsOwnUserMessage(result[index + 1]); - const groupedWithPrevious = timelineRowIsOwnUserMessage(previous); + const next = result[index + 1]; + // Messages group only under one sender, so each change of sender gets its name. + const sender = resolveMessageSender(row.message); + const groupedWithNext = + timelineRowIsOwnUserMessage(next) && + sameMessageSender(sender, resolveMessageSender(next.message)); + const groupedWithPrevious = + timelineRowIsOwnUserMessage(previous) && + sameMessageSender(sender, resolveMessageSender(previous.message)); const continuesSteer = groupedWithPrevious && messageIsSteer(row.message) && messageIsSteer(previous.message); if (!groupedWithNext && !groupedWithPrevious) return row; @@ -2370,6 +2383,25 @@ export function deriveMessagesTimelineRows(input: { }); } +/** + * The timeline with only `sender`'s messages, for find's "From" filter. Tool calls, plans and + * other rows say nothing about who sent them, so they drop out too. + */ +export function filterTimelineRowsBySender( + rows: MessagesTimelineRow[], + sender: OrchestrationMessageSenderFilter | null, +): MessagesTimelineRow[] { + if (sender === null) return rows; + return rows.flatMap((row) => { + if (row.kind !== "message") return []; + if (!messageSenderMatches(resolveMessageSender(row.message), sender)) return []; + // Neighbours are gone, so each kept message stands alone. + return row.groupedWithNext || row.groupedWithPrevious + ? [{ ...row, groupedWithNext: false, groupedWithPrevious: false, continuesSteer: false }] + : [row]; + }); +} + function timelineRowIsOwnUserMessage( row: MessagesTimelineRow | undefined, ): row is Extract { diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index b9653da6b315b..e381e295d7e1c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -7,7 +7,7 @@ import { MarkdownFindContext } from "./markdownFindContext"; import { useChatCanvas } from "./ChatCanvasContext"; import { WorkLogBlock } from "./WorkLog"; import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow"; -import type { WorktreeSetupSnapshot } from "@t3tools/contracts"; +import type { OrchestrationMessageSenderFilter, WorktreeSetupSnapshot } from "@t3tools/contracts"; import { deriveTimelineMinimapItems } from "./timelineMinimapItems"; import { type AssistantCitation, @@ -139,7 +139,12 @@ import { } from "./timelineViewport"; import { useThreadFindPositionReader } from "./useThreadFindPositionReader"; import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer"; -import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows"; +import { + useSenderFilteredRows, + useStableHandoffRuns, + useIncrementalTimelineRows, + useStableRows, +} from "./useTimelineRows"; import { useClientSettings } from "../../hooks/useSettings"; function timelineListStateFor(identity: string): { @@ -326,6 +331,7 @@ interface MessagesTimelineProps { findQuery?: string; activeFindMatch?: ThreadFindMatch | null; findNavigationId?: number; + findSender?: OrchestrationMessageSenderFilter | null; } export function MessagesTimeline(props: MessagesTimelineProps) { @@ -372,6 +378,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ findQuery = "", activeFindMatch = null, findNavigationId = 0, + findSender = null, latestRun, announcedRun = null, detailBehindShell = false, @@ -754,7 +761,8 @@ const ConversationTimeline = memo(function ConversationTimeline({ toolCallVisibility, revealedMessageId, }); - const rows = useStableRows(rawRows, listIdentityKey); + const stableRows = useStableRows(rawRows, listIdentityKey); + const rows = useSenderFilteredRows(stableRows, findSender); const matchedApprovalRequestIds = new Set(); for (const row of pendingApprovalRequestIds.size > 0 ? rows : []) { const entries = diff --git a/apps/web/src/components/chat/ThreadFindBar.tsx b/apps/web/src/components/chat/ThreadFindBar.tsx index 5ef0485ff4f50..c40e24cee5731 100644 --- a/apps/web/src/components/chat/ThreadFindBar.tsx +++ b/apps/web/src/components/chat/ThreadFindBar.tsx @@ -9,6 +9,10 @@ import { type ThreadFindAnnouncement, } from "./threadFind"; import { THREAD_DETAILS_CARD_GAP } from "./threadDetailsCardLayout"; +import type { OrchestrationMessageSenderFilter } from "@t3tools/contracts"; +import { MESSAGE_SENDER_FILTER_LABELS } from "@t3tools/client-runtime/message-sender"; + +const SENDER_FILTERS = Object.keys(MESSAGE_SENDER_FILTER_LABELS) as OrchestrationMessageSenderFilter[]; interface ThreadFindBarProps { readonly open: boolean; @@ -24,6 +28,9 @@ interface ThreadFindBarProps { readonly settled: boolean; readonly focusRequestId: number; readonly onQueryChange: (query: string) => void; + /** Only messages from this sender stay in the timeline while find is open. */ + readonly sender?: OrchestrationMessageSenderFilter | null; + readonly onSenderChange?: (sender: OrchestrationMessageSenderFilter | null) => void; readonly onNext: () => void; readonly onPrevious: () => void; readonly onClose: () => void; @@ -104,6 +111,28 @@ export function ThreadFindBar(props: ThreadFindBarProps) { onKeyDown={handleKeyDown} /> + {props.onSenderChange ? ( + + ) : null} {announcement.text} diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index b62f6f8e4b10f..f3b978b91d5aa 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -32,6 +32,8 @@ import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; +import { messageSenderLabel } from "@t3tools/client-runtime/message-sender"; +import { MessageSenderLine, useRunModelSender } from "./MessageSenderLine"; import { useAtomValue } from "@effect/atom-react"; import { AsyncResult, Atom } from "effect/reactivity"; import { vcsEnvironment } from "../../state/vcs"; @@ -48,11 +50,12 @@ export function AssistantTimelineRow({ row }: { row: Extract
- T3 Code + {messageSenderLabel(sender)}
) : null} + {/* Who replied stays visible: the provider and model of the run that wrote it. */} + {row.showAssistantMeta && !row.message.streaming && sender.kind === "model" && sender.provider !== null ? ( +
+ +
+ ) : null} {row.showAssistantMeta ? ( !isImageAttachment(attachment) && !isFileAttachment(attachment), ); const userMessage = resolveUserMessagePresentation(row.message); + const sender = resolveMessageSender(row.message); + // Name a person's message where the sender changes; agents, guests and T3 Code name themselves. + const showSender = sender.kind === "person" && !row.groupedWithPrevious; + const personHeading = + sender.kind === "person" && sender.sentBy !== null ? messageSenderLabel(sender) : "You"; // Messages from other agents fold to one line so the user's own messages stay easy to find. const folded = userMessage.attribution === "agent"; const [expanded, setExpanded] = useState(false); @@ -856,6 +866,11 @@ function UserTimelineRow({ row }: { row: Extract ) : null} + {showSender ? ( +
+ +
+ ) : null} {/* The row's heading already names the guest for screen readers. */} {userMessage.guestName !== undefined ? (
@@ -873,7 +888,7 @@ function UserTimelineRow({ row }: { row: Extract {/* The heading leads the media so screen readers reach it before the images. */} - You + {personHeading} {mediaBlock}
) : null} @@ -897,7 +912,7 @@ function UserTimelineRow({ row }: { row: Extract )} diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.ts index ea52de6c2747e..2258ba23db929 100644 --- a/apps/web/src/components/chat/threadFindStore.ts +++ b/apps/web/src/components/chat/threadFindStore.ts @@ -1,4 +1,5 @@ import type { + OrchestrationMessageSenderFilter, OrchestrationThreadSearchMatch, OrchestrationV2SearchThreadResult, ScopedThreadRef, @@ -30,6 +31,8 @@ export interface ThreadFindState { readonly navigationId: number; readonly requestId: number; readonly localSelection: ThreadFindLocalSelection | null; + /** Show only messages from this sender, or null for everyone's. */ + readonly sender: OrchestrationMessageSenderFilter | null; } export const CLOSED_THREAD_FIND: ThreadFindState = { @@ -41,6 +44,7 @@ export const CLOSED_THREAD_FIND: ThreadFindState = { navigationId: 0, requestId: 0, localSelection: null, + sender: null, }; export const useThreadFindStore = create(() => CLOSED_THREAD_FIND); @@ -142,6 +146,15 @@ export function setThreadFindQuery(threadKey: string, query: string): void { })); } +export function setThreadFindSender( + threadKey: string, + sender: OrchestrationMessageSenderFilter | null, +): void { + useThreadFindStore.setState((previous) => + previous.threadKey === threadKey ? { sender } : previous, + ); +} + export function closeThreadFind(): void { useThreadFindStore.setState(CLOSED_THREAD_FIND); } diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.ts index ada7955e1c2ad..e0caba173cf68 100644 --- a/apps/web/src/components/chat/useThreadFind.ts +++ b/apps/web/src/components/chat/useThreadFind.ts @@ -1,3 +1,4 @@ +import type { OrchestrationMessageSenderFilter } from "@t3tools/contracts"; import type { InlineSkill } from "@t3tools/shared/inlineSkills"; import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tools/contracts"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; @@ -11,6 +12,7 @@ import { CLOSED_THREAD_FIND, closeThreadFind, setThreadFindQuery, + setThreadFindSender, useThreadFindOpen, useThreadFindStore, type ThreadFindLocalSelection, @@ -83,6 +85,7 @@ export function useThreadFind({ ? { entryId, runId: runId ?? null, occurrence } : null, findNavigationId: navigationId, + findSender: isOpen ? state.sender : null, }; // Keep timeline identity stable during count and response updates to avoid extra jumps. const [storedTimeline, setTimeline] = useState(nextTimeline); @@ -222,6 +225,10 @@ export function useThreadFind({ onQueryChange: (query: string) => { if (threadKey !== null) setThreadFindQuery(threadKey, query); }, + sender: state.sender, + onSenderChange: (sender: OrchestrationMessageSenderFilter | null) => { + if (threadKey !== null) setThreadFindSender(threadKey, sender); + }, onNext: () => step(1), onPrevious: () => step(-1), onClose: closeThreadFind, @@ -236,6 +243,7 @@ export interface TimelineFields { readonly findQuery: string; readonly activeFindMatch: ThreadFindMatch | null; readonly findNavigationId: number; + readonly findSender: OrchestrationMessageSenderFilter | null; } function sameTimeline(a: TimelineFields, b: TimelineFields) { @@ -246,6 +254,7 @@ function sameTimeline(a: TimelineFields, b: TimelineFields) { a.findExpanded === b.findExpanded && a.findQuery === b.findQuery && a.findNavigationId === b.findNavigationId && + a.findSender === b.findSender && (aMatch === null || bMatch === null ? aMatch === bMatch : aMatch.entryId === bMatch.entryId && diff --git a/apps/web/src/components/chat/useTimelineRows.ts b/apps/web/src/components/chat/useTimelineRows.ts index 847dcc594af7a..c7b8a9738d001 100644 --- a/apps/web/src/components/chat/useTimelineRows.ts +++ b/apps/web/src/components/chat/useTimelineRows.ts @@ -1,3 +1,4 @@ +import type { OrchestrationMessageSenderFilter } from "@t3tools/contracts"; import { useState } from "react"; import { computeStableMessagesTimelineRows, @@ -5,6 +6,7 @@ import { type MessagesTimelineRowsInput, sameRowsInput, deriveMessagesTimelineRowsWithState, + filterTimelineRowsBySender, type StableMessagesTimelineRowsState, type MessagesTimelineRow, } from "./MessagesTimeline.logic"; @@ -76,3 +78,19 @@ export function useStableRows( setState({ identity, source: rows, stable }); return stable.result; } + +/** Rows kept to one sender's messages; the same array while rows and sender are unchanged. */ +export function useSenderFilteredRows( + rows: MessagesTimelineRow[], + sender: OrchestrationMessageSenderFilter | null, +): MessagesTimelineRow[] { + const [state, setState] = useState<{ + readonly source: MessagesTimelineRow[] | null; + readonly sender: OrchestrationMessageSenderFilter | null; + readonly value: MessagesTimelineRow[]; + }>({ source: null, sender: null, value: rows }); + if (state.source === rows && state.sender === sender) return state.value; + const value = filterTimelineRowsBySender(rows, sender); + setState({ source: rows, sender, value }); + return value; +} diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index 577bdd40f8c45..d52ca6ea784af 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -1,3 +1,4 @@ +import type { Founder } from "@t3tools/contracts"; import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions"; import { PlugIcon, PlusIcon, QrCodeIcon } from "lucide-react"; import { type ReactNode, memo, useId, useState } from "react"; @@ -480,6 +481,10 @@ type ConnectedClientListRowProps = { clientSession: ServerClientSessionRecord; revokingClientSessionId: string | null; onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void; + onSetFounder?: ( + sessionId: ServerClientSessionRecord["sessionId"], + founder: Founder | null, + ) => void; canRevoke: boolean; }; @@ -487,6 +492,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({ clientSession, revokingClientSessionId, onRevokeSession, + onSetFounder, canRevoke, }: ConnectedClientListRowProps) { const nowMs = useNowSecond(); @@ -540,6 +546,25 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({

+ {onSetFounder ? ( + // Messages sent from this client show this person's name. + + ) : null} {!clientSession.current ? (
- {onSetFounder ? ( - // Messages sent from this client show this person's name. + {onSetFounder && clientSession.client.deviceType !== "bot" ? ( + // Messages sent from this client show this person's name. The server refuses a client + // naming itself, so the current one is set from another trusted client.