Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,19 @@ it.effect("shells read founder @-mentions only from assistant replies and founde
id,
);
}
// The shell also says when the mentioning message was written, so a founder who has read past
// it can be told apart from one who has not. Both the SQL and in-memory paths must agree.
const mentionedAt = Effect.gen(function* () {
const sql = (yield* store.getThreadShell(threadId))?.attentionMentionsAt;
const memory = ProjectionStore.threadShellFromProjection(
yield* store.getThreadProjection(threadId),
).attentionMentionsAt;
return [
sql === undefined ? undefined : DateTime.formatIso(sql),
memory === undefined ? undefined : DateTime.formatIso(memory),
];
});
assert.deepEqual(yield* mentionedAt, [undefined, undefined]);
// An assistant reply that writes at a founder does.
assert.deepEqual(
yield* send("assistant", {
Expand All @@ -1709,11 +1722,14 @@ it.effect("shells read founder @-mentions only from assistant replies and founde
}),
[["kameron"], ["kameron"]],
);
const assistantAt = DateTime.formatIso(DateTime.add(at, { seconds: 3 }));
assert.deepEqual(yield* mentionedAt, [assistantAt, assistantAt]);
// A later incoming message does not replace what the assistant said, and never adds a name.
assert.deepEqual(
yield* send("later-digest", { role: "user", createdBy: "agent", text: "fyi @jeff" }),
[["kameron"], ["kameron"]],
);
assert.deepEqual(yield* mentionedAt, [assistantAt, assistantAt]);
// A founder's own note to the other founder still pings.
assert.deepEqual(
yield* send("note", {
Expand All @@ -1724,6 +1740,62 @@ it.effect("shells read founder @-mentions only from assistant replies and founde
}),
[["jeff"], ["jeff"]],
);
// A newer mention carries a newer time, which is what shows a founder a fresh pill.
const noteAt = DateTime.formatIso(DateTime.add(at, { seconds: 5 }));
assert.deepEqual(yield* mentionedAt, [noteAt, noteAt]);
}).pipe(Effect.provide(layerTest)),
);

it.effect("shells keep each founder's read cursor on the server snapshot path", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const threadId = yield* addRolledBackRecoveryCandidate("founder-visits");
const at = (yield* store.getThreadProjection(threadId)).updatedAt;
const kameronVisitedAt = DateTime.add(at, { seconds: 10 });
// A named founder reading a shared thread moves only their own cursor; the shared watermark
// stays put, so the founder's read is visible nowhere but visitsByFounder.
yield* store.apply({
id: EventId.make("event:founder-visits:recorded"),
type: "thread.visit-recorded",
threadId,
occurredAt: kameronVisitedAt,
payload: {
lastVisitedAt: at,
visitsByFounder: { kameron: kameronVisitedAt, jeff: at },
},
});
const iso = (
visits:
| {
readonly kameron?: DateTime.Utc | undefined;
readonly jeff?: DateTime.Utc | undefined;
}
| undefined,
) =>
visits === undefined
? undefined
: {
kameron: visits.kameron === undefined ? undefined : DateTime.formatIso(visits.kameron),
jeff: visits.jeff === undefined ? undefined : DateTime.formatIso(visits.jeff),
};
const expected = {
kameron: DateTime.formatIso(kameronVisitedAt),
jeff: DateTime.formatIso(at),
};
const fromSnapshot = (yield* store.getShellSnapshot()).threads.find(
(shell) => shell.id === threadId,
);
assert.deepEqual(
[
iso(fromSnapshot?.visitsByFounder),
iso((yield* store.getThreadShell(threadId))?.visitsByFounder),
iso(
ProjectionStore.threadShellFromProjection(yield* store.getThreadProjection(threadId))
.visitsByFounder,
),
],
[expected, expected, expected],
);
}).pipe(Effect.provide(layerTest)),
);

Expand Down
46 changes: 35 additions & 11 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1341,7 +1341,8 @@ type ShellThreadRow = {
readonly pending_link_request_payload_json: string | null;
readonly latest_user_message_at: string | null;
readonly latest_user_authored_message_at: string | null;
readonly latest_visible_text: string | null;
/** The message's `updated_at`, a unit separator, then its text; see `latestVisibleFromRow`. */
readonly latest_visible: string | null;
readonly has_actionable_proposed_plan: number;
};

Expand Down Expand Up @@ -1948,9 +1949,24 @@ const isFounderPingSource = (message: {
readonly humanNote?: boolean | undefined;
}) => message.role === "assistant" || message.humanNote === true;

const shellAttentionMentions = (text: string | null | undefined) => {
const attentionMentions = attentionMentionsFromText(text);
return attentionMentions === undefined ? {} : { attentionMentions };
const shellAttentionMentions = (
message: { readonly text: string; readonly updatedAt: DateTime.Utc } | null,
) => {
const attentionMentions = attentionMentionsFromText(message?.text);
return message === null || attentionMentions === undefined
? {}
: { attentionMentions, attentionMentionsAt: message.updatedAt };
};

/** Splits the SQL shell row's `updated_at` + unit separator + text pair back into a message. */
const latestVisibleFromRow = (value: string | null) => {
const split = value?.indexOf("\u001f") ?? -1;
return value === null || split < 0
? null
: {
text: value.slice(split + 1),
updatedAt: DateTime.makeUnsafe(value.slice(0, split)),
};
};

const shellInbox = (
Expand Down Expand Up @@ -2038,14 +2054,14 @@ export function threadShellFromProjection(
}
}
const latestUserMessage = userMessages[0] ?? null;
const latestVisibleText =
const latestVisibleMessage =
projection.messages
.filter((message) => idleCompactionOf(message) === undefined && isFounderPingSource(message))
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
right.id.localeCompare(left.id),
)[0]?.text ?? null;
)[0] ?? null;
const pendingBackgroundTasks = derivePendingBackgroundWork({
latestRun,
providerThreads: projection.providerThreads,
Expand Down Expand Up @@ -2119,7 +2135,7 @@ export function threadShellFromProjection(
// Thread detail owns message bodies. Keeping them out of shell rows makes
// initial hydration and streaming updates independent of transcript size.
latestVisibleMessage: null,
...shellAttentionMentions(latestVisibleText),
...shellAttentionMentions(latestVisibleMessage),
latestUserMessageAt: latestUserMessage?.updatedAt ?? null,
latestUserAuthoredMessageAt,
hasActionableProposedPlan: projection.plans.some(
Expand Down Expand Up @@ -2271,7 +2287,8 @@ type ShellThreadState = {
readonly pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null;
readonly latestUserMessageAt: DateTime.Utc | null;
readonly latestUserAuthoredMessageAt: DateTime.Utc | null;
readonly attentionMentions: OrchestrationV2ThreadShell["attentionMentions"];
readonly attentionMentions?: OrchestrationV2ThreadShell["attentionMentions"];
readonly attentionMentionsAt?: OrchestrationV2ThreadShell["attentionMentionsAt"];
readonly hasActionableProposedPlan: boolean;
readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"];
readonly providerInstanceHistory: OrchestrationV2ThreadShell["providerInstanceHistory"];
Expand Down Expand Up @@ -2462,6 +2479,9 @@ function shellFromState(input: {
...(input.state.attentionMentions === undefined
? {}
: { attentionMentions: input.state.attentionMentions }),
...(input.state.attentionMentionsAt === undefined
? {}
: { attentionMentionsAt: input.state.attentionMentionsAt }),
latestUserMessageAt: input.state.latestUserMessageAt,
latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt,
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
Expand Down Expand Up @@ -2494,6 +2514,10 @@ function shellFromState(input: {
}
: {}),
lastVisitedAt: input.state.thread.lastVisitedAt,
// Closura: a shared thread's per-founder read cursors; without them a named founder's read never clears their pill.
...(input.state.thread.visitsByFounder === undefined
? {}
: { visitsByFounder: input.state.thread.visitsByFounder }),
opens: input.state.thread.opens ?? null,
titleRegeneration: input.state.thread.titleRegeneration ?? null,
lastTitleRegeneration: input.state.thread.lastTitleRegeneration ?? null,
Expand Down Expand Up @@ -8923,7 +8947,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
LIMIT 1
) AS latest_user_authored_message_at,
(
SELECT substr(json_extract(message.payload_json, '$.text'), 1, ${ATTENTION_MENTION_TEXT_LIMIT})
SELECT message.updated_at || char(31) || substr(json_extract(message.payload_json, '$.text'), 1, ${ATTENTION_MENTION_TEXT_LIMIT})
FROM orchestration_v2_projection_messages message
INDEXED BY orchestration_v2_projection_messages_thread_updated_idx
WHERE message.thread_id = t.thread_id
Expand All @@ -8934,7 +8958,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND NOT ${isIdleCompactionMessage("message")}
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS latest_visible_text,
) AS latest_visible,
EXISTS (
SELECT 1
FROM orchestration_v2_projection_plans plan
Expand Down Expand Up @@ -9659,7 +9683,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
? null
: DateTime.makeUnsafe(row.latest_user_message_at),
latestUserAuthoredMessageAt,
attentionMentions: attentionMentionsFromText(row.latest_visible_text),
...shellAttentionMentions(latestVisibleFromRow(row.latest_visible)),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
pendingBackgroundTasks,
providerInstanceHistory: providerInstanceHistoryForShell({
Expand Down
165 changes: 165 additions & 0 deletions apps/web/src/components/sidebar/SidebarBotsGroup.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import {
DEFAULT_CLIENT_SETTINGS,
EnvironmentId,
ThreadId,
makeThreadInbox,
type Founder,
type LocalApi,
} from "@t3tools/contracts";
import { presentThreadShell } from "@t3tools/client-runtime/state/models";
import * as DateTime from "effect/DateTime";
import { expect, it, vi } from "vite-plus/test";

import { render } from "../../../test/render";
import { ensureClientSettingsHydrated } from "../../hooks/useSettings";
import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { makeThreadFixture } from "../../test-fixtures";
import { SidebarBotsGroup } from "./SidebarBotsGroup";

vi.mock("../../localApi", { spy: true });

const environmentId = EnvironmentId.make("bot-row-environment");
const noop = () => {};

/** Product Designer: a shared FYI conversation whose latest reply names a founder. */
function productDesigner(opts: {
readonly viewer: Founder;
readonly mentionedAt: string | null;
readonly visits?: Partial<Record<Founder, string>>;
readonly decision?: boolean;
}) {
const inbox = makeThreadInbox({
actor: { kind: "agent", id: "standing-product-designer" },
routing: { owner: null, audience: "shared", attentionKind: "FYI" },
});
// The app presents a shared thread with the viewing founder's own read cursor.
return presentThreadShell(
environmentId,
{
...makeThreadFixture().source,
id: ThreadId.make("standing-product-designer"),
title: "Product Designer",
standing: { name: "Product Designer", accent: "violet", avatarId: "halo", role: null },
inbox: opts.decision
? {
...inbox,
decisionRequest: {
founder: "kameron",
kind: "decision",
question: "Ship the new nav?",
requestedAt: "2026-11-30T11:00:00.000Z",
},
}
: inbox,
...(opts.mentionedAt === null
? {}
: {
attentionMentions: ["kameron" as const],
attentionMentionsAt: DateTime.makeUnsafe(opts.mentionedAt),
}),
visitsByFounder: Object.fromEntries(
Object.entries(opts.visits ?? {}).map(([founder, at]) => [
founder,
DateTime.makeUnsafe(at),
]),
),
},
null,
opts.viewer,
);
}

async function renderRow(
viewer: Founder,
thread: ReturnType<typeof productDesigner>,
): Promise<Awaited<ReturnType<typeof render>>> {
using _localApi = vi.spyOn(await import("../../localApi"), "ensureLocalApi").mockReturnValue({
persistence: {
getClientSettings: async () => ({ ...DEFAULT_CLIENT_SETTINGS, founderInboxOwner: viewer }),
setClientSettings: vi.fn().mockResolvedValue(undefined),
},
} as unknown as LocalApi);
await ensureClientSettingsHydrated();
return render(
<AppAtomRegistryProvider>
<SidebarBotsGroup
threads={[thread]}
activeThreadKey={null}
onThreadClick={noop}
onThreadActivate={noop}
onContextMenu={noop}
/>
</AppAtomRegistryProvider>,
);
}

const mark = (screen: Awaited<ReturnType<typeof render>>) =>
screen.getByTestId("sidebar-bot-row").element().querySelector("[data-bot-attention]");

it("badges a founder mention the viewer has not read", async () => {
await using screen = await renderRow(
"kameron",
productDesigner({
viewer: "kameron",
mentionedAt: "2026-11-30T12:00:00.000Z",
visits: { kameron: "2026-11-30T11:00:00.000Z" },
}),
);
expect(mark(screen)?.getAttribute("data-bot-attention")).toBe("badge");
expect(mark(screen)?.textContent).toBe("Kameron");
});

it("clears the founder's name pill once they have read past the message", async () => {
await using screen = await renderRow(
"kameron",
productDesigner({
viewer: "kameron",
mentionedAt: "2026-11-30T12:00:00.000Z",
visits: { kameron: "2026-11-30T12:05:00.000Z" },
}),
);
// The shared FYI dot stays; the bright name pill is gone.
expect(mark(screen)?.getAttribute("data-bot-attention")).toBe("fyi");
});

it("shows a fresh pill for a mention that arrives after the read", async () => {
await using screen = await renderRow(
"kameron",
productDesigner({
viewer: "kameron",
mentionedAt: "2026-11-30T13:00:00.000Z",
visits: { kameron: "2026-11-30T12:05:00.000Z" },
}),
);
expect(mark(screen)?.getAttribute("data-bot-attention")).toBe("badge");
});

it("judges each founder on their own read of a shared thread", async () => {
const visits = { kameron: "2026-11-30T12:05:00.000Z" };
const mentionedAt = "2026-11-30T12:00:00.000Z";
await using kameron = await renderRow(
"kameron",
productDesigner({ viewer: "kameron", mentionedAt, visits }),
);
expect(mark(kameron)?.getAttribute("data-bot-attention")).toBe("fyi");
// Jeff has not read it, so Kameron reading it does not silence Jeff's row.
await using jeff = await renderRow(
"jeff",
productDesigner({ viewer: "jeff", mentionedAt, visits }),
);
expect(mark(jeff)?.getAttribute("data-bot-attention")).toBe("badge");
});

it("keeps an open decision badged after the founder reads the thread", async () => {
await using screen = await renderRow(
"kameron",
productDesigner({
viewer: "kameron",
mentionedAt: "2026-11-30T12:00:00.000Z",
visits: { kameron: "2026-11-30T12:05:00.000Z" },
decision: true,
}),
);
expect(mark(screen)?.getAttribute("data-bot-attention")).toBe("badge");
expect(mark(screen)?.textContent).toBe("Decision");
});
Loading
Loading