Skip to content
Merged
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
4 changes: 2 additions & 2 deletions FORK.md

Large diffs are not rendered by default.

25 changes: 16 additions & 9 deletions apps/web/src/components/chat/TimelineUserMessageRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import { useSharedMessageAuthor } from "../../j5/sharing/sharedTimeline";
import {
J5MessageAuthorLine,
J5OpenSenderThread,
j5PromptRow,
renderThreadA2ADelivery,
useJ5UserMessagePresentation,
} from "../../j5/a2a/ThreadA2ARenderer";
Expand Down Expand Up @@ -144,7 +145,8 @@ export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mes
environmentId={ctx.activeThreadEnvironmentId}
onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
/>
) : resolveUserMessagePresentation(row.message).attribution === "automation" ? (
) : resolveUserMessagePresentation(row.message).attribution === "automation" ||
j5PromptRow(row.message) !== null ? (
<AutomationMessageRow row={row} />
) : (
<UserTimelineRow row={row} />
Expand All @@ -156,7 +158,9 @@ function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mess
const ctx = use(TimelineRowCtx);
const [expanded, setExpanded] = useState(false);
const revealRef = findRevealRef(() => setExpanded(true));
const { text, scheduledTaskId } = resolveUserMessagePresentation(row.message);
// J5 (case 7): J5's platform prompts draw as this row, with their own label, title and words.
const j5Prompt = j5PromptRow(row.message);
const { text, scheduledTaskId } = j5Prompt ?? resolveUserMessagePresentation(row.message);
const tasksQuery = useEnvironmentQuery(
scheduledTaskId
? serverEnvironment.scheduledTasksLive({
Expand All @@ -166,29 +170,32 @@ function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mess
: null,
);
const taskTitle = tasksQuery.data?.tasks.find((task) => task.id === scheduledTaskId)?.title;
const summary = taskTitle ?? text.trim().split(/\r?\n/, 1)[0] ?? "";
const summary = j5Prompt?.summary ?? taskTitle ?? text.trim().split(/\r?\n/, 1)[0] ?? "";

const revertTurnCount = row.revertTurnCount;
const promptLink = promptLinkFor(text);
// Find reads the DOM, so a folded prompt stays mounted but hidden while find is open.
const bodyMounted = expanded || ctx.findActive;

return (
<div className="group flex flex-col items-end gap-1" data-user-message-attribution="automation">
<div
className="group flex flex-col items-start gap-1"
data-user-message-attribution="automation"
>
{row.message.inputIntent === "steer" ||
row.message.inputIntent === "promoted_queued_to_steer" ? (
<UserMessageIntentMarker intent={row.message.inputIntent} />
) : null}
<div
className={cn(
"min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",
expanded && "w-full",
"min-w-0 max-w-[80%] rounded-2xl border border-border",
(expanded || j5Prompt) && "w-full",
)}
>
<MessageAuthorHeading>Automation</MessageAuthorHeading>
<MessageAuthorHeading>{j5Prompt?.label ?? "Automation"}</MessageAuthorHeading>
<FoldedMessageHeader
icon={CalendarClockIcon}
label="Automation"
icon={j5Prompt?.icon ?? CalendarClockIcon}
label={j5Prompt?.label ?? "Automation"}
summary={summary}
expanded={expanded}
onToggle={() => setExpanded((value) => !value)}
Expand Down
117 changes: 117 additions & 0 deletions apps/web/src/j5/a2a/J5NoticeLine.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { MessageId } from "@t3tools/contracts";
import { expect, it } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";

import type { ChatMessage } from "~/types";

import { render } from "../../../test/render";
import { TimelineRowCtx } from "../../components/chat/timelineRowContext";
import { renderThreadA2ADelivery } from "./ThreadA2ARenderer";

const CREATED_AT = "2026-10-31T12:00:00.000Z";
const notice = (id: string, text: string, input: Partial<ChatMessage> = {}): ChatMessage => ({
id: MessageId.make(id),
role: "user",
text,
runId: null,
streaming: false,
createdBy: "system",
creationSource: "server",
createdAt: CREATED_AT,
updatedAt: CREATED_AT,
...input,
});

const notDelivered = notice(
"message:j5:a2a:delivery:one",
[
"[Cross-agent messaging system notice: message not delivered]",
"Your message m1 to agent:peer was not delivered: delivery failed 3 times",
"This is a platform-authored notice, not a peer reply.",
].join("\n\n"),
);

const rowContext = (findActive = false) =>
({
findActive,
participantLabels: new Map([["agent:peer", "Builder"]]),
skills: [],
threadRef: null,
markdownCwd: undefined,
}) as never;

it("folds a notice to one named line and opens to its detail", async () => {
await using screen = await render(
<TimelineRowCtx value={rowContext()}>
{renderThreadA2ADelivery({ message: notDelivered, timestampLabel: "8:00 AM" })}
</TimelineRowCtx>,
);
const line = screen.getByRole("button", { name: /Message to Builder not delivered/ });
await expect.element(line).toHaveAttribute("aria-expanded", "false");
await expect.element(screen.getByText("8:00 AM")).toBeVisible();
expect(screen.container.textContent).not.toContain("agent:peer");
expect(screen.container.textContent).not.toContain("Cross-agent");
expect(screen.container.textContent).not.toContain("delivery failed");

await userEvent.click(line);
await expect.element(screen.getByText(/Delivery failed 3 times/)).toBeVisible();
});

it("opens a folded notice when find matches its detail", async () => {
await using screen = await render(
<TimelineRowCtx value={rowContext(true)}>
{renderThreadA2ADelivery({ message: notDelivered })}
</TimelineRowCtx>,
);
const line = screen.getByRole("button", { name: /Message to Builder not delivered/ });
const detail = screen.container.querySelector<HTMLElement>("[data-j5-notice-detail]")!;
expect(detail.hidden).toBe(true);
expect(detail.querySelector("[data-thread-find-text]")?.textContent).toContain("Delivery failed");

detail.dispatchEvent(new Event("beforematch"));
await expect.element(line).toHaveAttribute("aria-expanded", "true");
});

it("draws a seat in trouble with its tone, opening to the error", async () => {
const report = [
"<j5_crew_gate>",
"proposal_id: p1",
"kind: addition",
"decision: approved",
"crew_name: Comedy",
"seat_failed: punchline | failed | provider_error",
"seat_pending: prosecutor",
"roster:",
"- punchline: participant_id=agent:p persona=advocate thread_id=thread:p start=failed",
"- prosecutor: participant_id=agent:q persona=critic thread_id=thread:q start=pending",
"</j5_crew_gate>",
].join("\n");
await using screen = await render(
<TimelineRowCtx value={rowContext()}>
{renderThreadA2ADelivery({ message: notice("message:crew", report) })}
</TimelineRowCtx>,
);
await expect.element(screen.getByText("punchline couldn't start")).toBeVisible();
await expect.element(screen.getByText("prosecutor hasn't confirmed it started")).toBeVisible();
expect(
[...screen.container.querySelectorAll("[data-j5-notice-tone]")].map((icon) =>
icon.getAttribute("data-j5-notice-tone"),
),
).toEqual(["bad", "warn"]);
await userEvent.click(screen.getByRole("button", { name: /punchline couldn't start/ }));
await expect.element(screen.getByText("provider_error")).toBeVisible();
});

it("draws a declined roster as one line", async () => {
const declined =
"<j5_crew_gate>\nproposal_id: p2\nkind: roster\ndecision: declined\ndecided_by: Priya\ncrew_name: Comedy\nrequested_seats: setup=scout\n</j5_crew_gate>\n\nThe user declined this crew request.";
await using screen = await render(
<TimelineRowCtx value={rowContext()}>
{renderThreadA2ADelivery({ message: notice("message:crew", declined) })}
</TimelineRowCtx>,
);
await userEvent.click(
screen.getByRole("button", { name: /Crew Comedy · roster declined by Priya/ }),
);
await expect.element(screen.getByText(/Requested: setup \(scout\)/)).toBeVisible();
});
146 changes: 146 additions & 0 deletions apps/web/src/j5/a2a/J5NoticeLine.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import { ChevronDownIcon, type LucideIcon } from "lucide-react";
import { use, useState, type ReactNode } from "react";

import ChatMarkdown from "../../components/ChatMarkdown";
import { findRevealRef } from "../../components/chat/markdownFindContext";
import { MESSAGE_HEADING_LEVEL } from "../../components/chat/TimelineRowParts";
import { TimelineRowCtx } from "../../components/chat/timelineRowContext";
import { InlineButton } from "../../components/ui/button";
import { cn } from "../../lib/utils";
import { buildThreadRouteParams } from "../../threadRoutes";

const TONE_CLASS = {
bad: "text-destructive",
warn: "text-warning",
none: "",
} as const;

/**
* A platform notice (group 4): one grey line on the left, with an icon, a plain summary, the time
* and, when there is something to open, a chevron. Opened, its detail hangs under a thin rule.
*/
export function J5NoticeLine(props: {
/** Which notice this is, for finding the row in tests and captures. */
readonly kind: string;
readonly icon: LucideIcon;
readonly tone?: keyof typeof TONE_CLASS;
readonly summary: string;
readonly timestampLabel?: string | undefined;
readonly children?: ReactNode;
}) {
const { findActive } = use(TimelineRowCtx);
const [expanded, setExpanded] = useState(false);
const revealRef = findRevealRef(() => setExpanded(true));
const Icon = props.icon;
const hasDetail = props.children !== undefined && props.children !== null;
const content = (
<>
<Icon
aria-hidden
className={cn("size-3.5 shrink-0", TONE_CLASS[props.tone ?? "none"])}
data-j5-notice-tone={props.tone}
/>
{/* Find can only show a match in a summary that isn't cut off. */}
<span className={cn("min-w-0", !findActive && "truncate")} data-thread-find-text="true">
{props.summary}
</span>
{props.timestampLabel ? (
<span className="shrink-0 tabular-nums text-muted-foreground/70">
{props.timestampLabel}
</span>
) : null}
</>
);
const lineClass = "flex min-w-0 max-w-full items-center gap-1.5 py-0.5 text-left";
return (
<div
className="flex min-w-0 max-w-[80%] flex-col items-start gap-1 text-xs text-muted-foreground"
data-j5-notice={props.kind}
>
{hasDetail ? (
<button
type="button"
aria-expanded={expanded}
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
className={cn(lineClass, "rounded-sm focus-visible:outline-2 focus-visible:outline-ring")}
>
{content}
<ChevronDownIcon
aria-hidden
className={cn("size-3.5 shrink-0 transition-transform", expanded && "rotate-180")}
/>
</button>
) : (
<div className={lineClass}>{content}</div>
)}
{/* Find reads the DOM, so a folded detail stays mounted but hidden while find is open. */}
{hasDetail && (expanded || findActive) ? (
<div
ref={revealRef}
hidden={!expanded}
className={cn(
"ms-1.5 min-w-0 max-w-full border-l border-border ps-3",
!findActive && "max-h-96 overflow-auto",
)}
data-j5-notice-detail
>
{props.children}
</div>
) : null}
</div>
);
}

/** A notice's words, as markdown so a link or a list in them reads as one. */
export function J5NoticeDetailText({ text }: { readonly text: string }) {
const ctx = use(TimelineRowCtx);
return (
<div data-thread-find-text="true">
<ChatMarkdown
text={text}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={ctx.skills}
className="text-xs text-muted-foreground"
lineBreaks
parseRawHtml={false}
headingLevelOffset={MESSAGE_HEADING_LEVEL}
/>
</div>
);
}

/** The row of things a notice opens, under its words. */
export function J5NoticeActions({ children }: { readonly children: ReactNode }) {
return (
<div className="mt-1 flex flex-wrap items-center gap-2" data-thread-find-ignore>
{children}
</div>
);
}

export function J5OpenThread({
threadRef,
label = "Open thread",
}: {
readonly threadRef: ScopedThreadRef;
readonly label?: string;
}) {
const navigate = useNavigate();
return (
<InlineButton
onClick={() =>
void navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(threadRef),
})
}
tone="muted"
>
{label}
</InlineButton>
);
}
Loading
Loading