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 ? ( ; }; +type GroupingMessage = Parameters[0] & + Parameters[0]; + +/** Messages group only under one sender, so each change of person gets its name line. */ +function bySender( + message: GroupingMessage, + previous: GroupingMessage | undefined, + next: GroupingMessage | undefined, + grouping: ReturnType, +): ReturnType { + const sender = resolveMessageSender(message); + const groupedWithPrevious = + grouping.groupedWithPrevious && + previous !== undefined && + sameMessageSender(sender, resolveMessageSender(previous)); + return { + groupedWithPrevious, + groupedWithNext: + grouping.groupedWithNext && + next !== undefined && + sameMessageSender(sender, resolveMessageSender(next)), + continuesSteer: grouping.continuesSteer && groupedWithPrevious, + }; +} + export function createThreadFeedGrouping() { const rows = new WeakMap(); const ungrouped = resolveUserMessageGrouping(undefined, undefined, undefined); @@ -76,13 +102,18 @@ export function createThreadFeedGrouping() { }; return feed.map((entry, index) => { const message = groupingMessage(index); + const previousMessage = + index - 1 === options.setupAnchorIndex ? undefined : groupingMessage(index - 1); + const nextMessage = + index === options.setupAnchorIndex ? undefined : groupingMessage(index + 1); const grouping = message === undefined ? ungrouped - : resolveUserMessageGrouping( + : bySender( message, - index - 1 === options.setupAnchorIndex ? undefined : groupingMessage(index - 1), - index === options.setupAnchorIndex ? undefined : groupingMessage(index + 1), + previousMessage, + nextMessage, + resolveUserMessageGrouping(message, previousMessage, nextMessage), ); const previous = rows.get(entry); if ( diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index ed85709f30059..2335af6f7a9dc 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -145,6 +145,8 @@ export interface ThreadFeedMessage { readonly scheduledTaskId?: ScheduledTaskId; readonly senderThreadId?: ThreadId; readonly linkedSender?: import("@t3tools/contracts").OrchestrationV2LinkedSender; + /** The signed-in client a person sent it from, stamped by the server. */ + readonly sentBy?: import("@t3tools/contracts").OrchestrationV2MessageSentBy; readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction; readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"]; readonly sourceThreadId: ThreadId; @@ -2499,6 +2501,7 @@ export function buildThreadFeed( ...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}), ...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}), ...(item.linkedSender ? { linkedSender: item.linkedSender } : {}), + ...(item.sentBy ? { sentBy: item.sentBy } : {}), ...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}), } : {}), diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 365203e03db2c..30bba243af9ea 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -290,6 +290,37 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), ); + it.effect("lets a client name another client's person but never its own", () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const sessions = yield* SessionStore.SessionStore; + const desktop = (label: string) => + sessions.issue({ + subject: "browser-pairing", + method: "browser-session-cookie", + client: { label, deviceType: "desktop" }, + }); + const admin = yield* desktop("Owner"); + const laptop = yield* desktop("Work laptop"); + const bot = yield* serverAuth.issueSession({ label: "Bot" }); + + expect( + yield* serverAuth.setClientSessionFounder(admin.sessionId, laptop.sessionId, "jeff"), + ).toBe(true); + expect((yield* serverAuth.messageSenderOf(laptop.sessionId)).founder).toBe("jeff"); + + const selfAssign = yield* Effect.flip( + serverAuth.setClientSessionFounder(laptop.sessionId, laptop.sessionId, "kameron"), + ); + expect(selfAssign._tag).toBe("ServerAuthForbiddenOperationError"); + expect((yield* serverAuth.messageSenderOf(laptop.sessionId)).founder).toBe("jeff"); + // A bot is never a person. + expect( + yield* serverAuth.setClientSessionFounder(admin.sessionId, bot.sessionId, "jeff"), + ).toBe(false); + }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), + ); + it.effect("prefers a bearer token over an empty primary cookie", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 2731d660ad806..5798cd3076924 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -20,6 +20,8 @@ import { type ServerAuthSessionMethod, type AuthWebSocketTicketResult, type AuthWebSocketTicketUse, + type Founder, + type OrchestrationV2MessageSentBy, DpopFailureReason, type DpopFailureReason as DpopFailureReasonType, mcpClientScopes, @@ -30,6 +32,7 @@ import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -350,6 +353,17 @@ export class ServerAuthConnectDevicesError extends Schema.TaggedError()( + "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,24 @@ export class EnvironmentAuth extends Context.Service< readonly revokeOtherClientSessions: ( currentSessionId: AuthSessionId, ) => Effect.Effect; + /** + * Records who uses another client session, or clears it with null; false when that session is + * not live or is a bot. A client may not name itself, so who sent a message is always set by a + * different trusted client than the one that sends it. + */ + readonly setClientSessionFounder: ( + currentSessionId: AuthSessionId, + 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 +1457,57 @@ export const make = Effect.gen(function* () { return yield* revokeSession(targetSessionId); }); + const setClientSessionFounder: EnvironmentAuth["Service"]["setClientSessionFounder"] = Effect.fn( + "EnvironmentAuth.setClientSessionFounder", + )(function* (currentSessionId, targetSessionId, founder) { + if (currentSessionId === targetSessionId) { + return yield* new ServerAuthForbiddenOperationError({}); + } + // Another session on the caller's own device key is the same device naming itself. + const toFounderError = (cause: unknown) => new ServerAuthSessionFounderError({ cause }); + const [currentKey, targetKey] = yield* Effect.all([ + sessions.proofKeyThumbprintOf(currentSessionId), + sessions.proofKeyThumbprintOf(targetSessionId), + ]).pipe(Effect.mapError(toFounderError)); + if (Option.isSome(currentKey) && Option.getOrUndefined(targetKey) === currentKey.value) { + return yield* new ServerAuthForbiddenOperationError({}); + } + return yield* sessions + .setFounder(targetSessionId, founder) + .pipe(Effect.mapError(toFounderError)); + }); + + 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 +1731,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..c03d4c686a1a5 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,34 @@ const make = Effect.gen(function* () { }, ); + const setFounder: SessionStore["Service"]["setFounder"] = Effect.fn("SessionStore.setFounder")( + function* (sessionId, founder) { + const now = yield* DateTime.now; + const updated = yield* authSessions + .setFounder({ sessionId, founder, now }) + .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 +1271,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..d593aab6563e7 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -137,7 +137,9 @@ export function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope ); } -function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_allowed") { +function failEnvironmentOperationForbidden( + reason: "current_session_revoke_not_allowed" | "current_session_founder_not_allowed", +) { return currentEnvironmentTraceId.pipe( Effect.flatMap((traceId) => Effect.fail( @@ -538,6 +540,28 @@ export const layer = HttpApiBuilder.group( ), ), ) + .handle( + "setClientFounder", + Effect.fn("environment.auth.setClientFounder")( + function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + const session = yield* requireEnvironmentScope(AuthAccessWriteScope); + const updated = yield* serverAuth.setClientSessionFounder( + session.sessionId, + args.payload.sessionId, + args.payload.founder, + ); + return { updated }; + }, + Effect.catchTags({ + ServerAuthForbiddenOperationError: () => + failEnvironmentOperationForbidden("current_session_founder_not_allowed"), + }), + 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/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 972174638e10f..2b7fb836a7b69 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -276,6 +276,8 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { commandId: yield* newCommandId(), requestId, answers, + // An agent's answer is an agent's message, never a person's. + createdBy: "agent", }) .pipe(Effect.mapError(dispatchFailure)); return { sequence: result.sequence }; 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..bab699fa65912 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3046,6 +3046,7 @@ 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 +6082,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 +6228,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 +6250,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 +7496,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 +7792,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 +8211,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 +8238,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 +9009,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 +9033,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, @@ -11018,8 +11028,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: command.feedback, attachments: [], streaming: false, - createdBy: "user", + createdBy: command.createdBy ?? "user", creationSource: "server", + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), createdAt: now, updatedAt: now, }, @@ -11175,8 +11186,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: MessageId.make(`async-answer:${command.requestId}`), text: replies.join("\n\n"), attachments: [], - createdBy: "user" as const, + createdBy: command.createdBy ?? ("user" as const), creationSource: "server" as const, + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), dispatchMode, }; yield* dispatchMessage(answer, events, effects); @@ -11568,6 +11580,7 @@ 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 }), @@ -11786,6 +11799,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const emitEvent = emit(events, command); const editedAttachments = command.attachments === undefined ? {} : { attachments: command.attachments }; + // The edited words are the editor's: a person's client stamps itself, and an agent's edit + // drops the old stamp rather than leave someone else's name on text they did not write. + const withEditor = < + T extends { readonly sentBy?: OrchestrationV2ConversationMessage["sentBy"] }, + >( + item: T, + ): T => { + const { sentBy: _previous, ...rest } = item; + return (command.sentBy === undefined ? rest : { ...rest, sentBy: command.sentBy }) as T; + }; yield* emitEvent({ type: "message.updated", threadId: command.threadId, @@ -11794,7 +11817,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: queuedRun.providerInstanceId, occurredAt: now, payload: withoutGuestAttribution({ - ...queuedMessage, + ...withEditor(queuedMessage), text: command.text, ...editedAttachments, ...(command.context ? { context: command.context } : {}), @@ -11810,7 +11833,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: queuedRun.providerInstanceId, occurredAt: now, payload: withoutGuestAttribution({ - ...queuedTurnItem, + ...withEditor(queuedTurnItem), text: command.text, ...editedAttachments, ...(command.context ? { context: command.context } : {}), 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..efeb3a99f71a5 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,40 @@ 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 "queued-run.edit": { + // The editor's own stamp replaces the original sender's, since the words are now theirs. + const { sentBy: _sentBy, ...rest } = command; + return provenance.sentBy === undefined ? rest : { ...rest, sentBy: provenance.sentBy }; + } + case "runtime-request.respond": { + const { sentBy: _sentBy, createdBy: _createdBy, ...rest } = command; + return { + ...rest, + createdBy: provenance.createdBy, + ...(provenance.sentBy === undefined ? {} : { sentBy: provenance.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..3385454dd2a3f 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,52 @@ 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 is known by its + * server-made id; a message the server stamped with a person's client is a person's regardless. + */ +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("$.sentBy")} IS NOT NULL + OR ${field("$.id")} NOT LIKE 'scheduled-task-message:%') + 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 +327,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 +578,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 +599,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 +655,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 +686,17 @@ export const make = Effect.gen(function* () { }, ]), ); - const titleHits: ThreadSearchHit[] = 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, - }), + // 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 +712,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 +722,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..7ef35c10e433c 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,13 @@ export const SetAuthSessionLastConnectedAtInput = Schema.Struct({ }); export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type; +export const SetAuthSessionFounderInput = Schema.Struct({ + sessionId: AuthSessionId, + founder: Schema.NullOr(Founder), + now: Schema.DateTimeUtcFromString, +}); +export type SetAuthSessionFounderInput = typeof SetAuthSessionFounderInput.Type; + export class AuthSessionRepository extends Context.Service< AuthSessionRepository, { @@ -137,6 +147,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>; @@ -146,6 +160,9 @@ export class AuthSessionRepository extends Context.Service< } >()("t3/persistence/AuthSessions/AuthSessionRepository") {} +/** The subject of the local desktop app's sessions; there is one such app per server. */ +const DESKTOP_BOOTSTRAP_SUBJECT = "desktop-bootstrap"; + const AuthSessionDbRow = Schema.Struct({ sessionId: AuthSessionId, subject: Schema.String, @@ -161,6 +178,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 +196,7 @@ const AuthSessionRawDbRow = Schema.Struct({ expiresAt: Schema.Unknown, lastConnectedAt: Schema.Unknown, revokedAt: Schema.Unknown, + founder: Schema.Unknown, }); const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow); @@ -200,6 +219,7 @@ function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionReco expiresAt: row.expiresAt, lastConnectedAt: row.lastConnectedAt, revokedAt: row.revokedAt, + founder: row.founder, }; } @@ -284,7 +304,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 +313,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 +326,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 +349,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 +369,52 @@ export const make = Effect.gen(function* () { `, }); + const setFounderRows = SqlSchema.findAll({ + Request: SetAuthSessionFounderInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ sessionId, founder, now }) => + sql` + UPDATE auth_sessions + SET founder = ${founder} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + AND expires_at > ${now} + AND client_device_type IS NOT 'bot' + RETURNING session_id AS "sessionId" + `, + }); + + // A device keeps its person across new sessions only where the server can tell it is the same + // device: one proof key (a T3 Connect device renewing hourly) or the local desktop app's + // bootstrap. Other subjects can span several devices, so they never inherit a person. + const inheritFounderRow = SqlSchema.void({ + Request: CreateAuthSessionInput, + execute: (input) => + sql` + UPDATE auth_sessions + SET founder = ( + SELECT prior.founder + FROM auth_sessions AS prior + WHERE prior.session_id <> ${input.sessionId} + AND ${ + input.proofKeyThumbprint === undefined + ? sql`prior.subject = ${DESKTOP_BOOTSTRAP_SUBJECT} + AND prior.proof_key_thumbprint IS NULL` + : sql`prior.proof_key_thumbprint = ${input.proofKeyThumbprint}` + } + ORDER BY prior.issued_at DESC + LIMIT 1 + ) + WHERE session_id = ${input.sessionId} + AND founder IS NULL + AND client_device_type IS NOT 'bot' + `, + }); + const inheritFounder = (input: CreateAuthSessionInput) => + input.proofKeyThumbprint !== undefined || input.subject === DESKTOP_BOOTSTRAP_SUBJECT + ? inheritFounderRow(input) + : Effect.void; + const revokeSessionRows = SqlSchema.findAll({ Request: RevokeAuthSessionInput, Result: Schema.Struct({ sessionId: AuthSessionId }), @@ -413,15 +481,17 @@ export const make = Effect.gen(function* () { }); const create: AuthSessionRepository["Service"]["create"] = (input) => - createSessionRow(input).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "AuthSessionRepository.create:query", - "AuthSessionRepository.create:encodeRequest", - { sessionId: input.sessionId }, + sql + .withTransaction(createSessionRow(input).pipe(Effect.andThen(inheritFounder(input)))) + .pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.create:query", + "AuthSessionRepository.create:encodeRequest", + { sessionId: input.sessionId }, + ), ), - ), - ); + ); const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = ( input, @@ -431,6 +501,23 @@ export const make = Effect.gen(function* () { revokeActiveSessionsForReplacement(input).pipe( Effect.flatMap((revokedRows) => createSessionRow(input.session).pipe( + Effect.andThen(inheritFounder(input.session)), + 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, + now: input.revokedAt, + }) + : Effect.void; + }), Effect.as(revokedRows.map((row) => row.sessionId)), ), ), @@ -557,6 +644,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 +692,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..0a621e39cd31a 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,25 @@ 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" || + command.type === "queued-run.edit" || + command.type === "runtime-request.respond" + ? 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 +2258,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 +2296,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..3e13cd32a2be9 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; @@ -94,6 +101,7 @@ export function ThreadFindBar(props: ThreadFindBarProps) { ref={inputRef} type="search" size="sm" + className="min-w-24" value={props.query} aria-label="Find in thread" placeholder="Find in thread" @@ -104,6 +112,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. + // A message still on its way has no server stamp yet (no createdBy); it is the user's own. + const unsent = row.message.createdBy === undefined && row.message.sentBy === undefined; + const showSender = sender.kind === "person" && !row.groupedWithPrevious && !unsent; + const personHeading = sender.kind === "person" && !unsent ? 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 +864,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 +886,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 +910,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..282e27ee1df33 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,30 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({

+ {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. + + ) : null} {!clientSession.current ? (