Skip to content

Commit 1fc912c

Browse files
committed
fix(chat): fold mechanical prompts and preserve automation provenance
1 parent 81493ef commit 1fc912c

11 files changed

Lines changed: 435 additions & 12 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
1616
import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
1717
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
1818
import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
19-
import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
19+
import {
20+
backgroundActivityTrigger,
21+
resolveUserMessagePresentation,
22+
} from "@t3tools/client-runtime/user-message";
2023
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
2124
import {
2225
type OrchestrationMessageContext,
@@ -1174,6 +1177,23 @@ function renderFeedEntry(
11741177
!message.streaming;
11751178

11761179
if (isUser) {
1180+
const backgroundTrigger = backgroundActivityTrigger(message);
1181+
if (backgroundTrigger !== null && !props.expandedWorkRows[entry.id]) {
1182+
return (
1183+
<Pressable
1184+
accessibilityRole="button"
1185+
accessibilityLabel={`Background activity: ${backgroundTrigger}`}
1186+
accessibilityState={{ expanded: false }}
1187+
onPress={() => props.onToggleWorkRow(entry.id)}
1188+
className="mb-3 rounded-xl border border-border px-3 py-2"
1189+
>
1190+
<Text className="text-sm text-foreground-muted">Background activity · 1 event</Text>
1191+
<Text className="text-xs text-foreground-muted">
1192+
{backgroundTrigger} · {timestampLabel}
1193+
</Text>
1194+
</Pressable>
1195+
);
1196+
}
11771197
const enterAnimated = isFreshTimestamp(message.createdAt);
11781198
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
11791199
const referenceIds = new Set(
@@ -1194,6 +1214,22 @@ function renderFeedEntry(
11941214
className="mb-5 items-end"
11951215
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
11961216
>
1217+
{backgroundTrigger !== null ? (
1218+
<Pressable
1219+
accessibilityRole="button"
1220+
accessibilityLabel="Collapse background activity"
1221+
accessibilityState={{ expanded: true }}
1222+
onPress={() => props.onToggleWorkRow(entry.id)}
1223+
className="mb-2 px-2 py-1"
1224+
>
1225+
<Text className="text-xs text-foreground-muted">
1226+
{backgroundTrigger} · Hide details
1227+
</Text>
1228+
<Text selectable className="text-xs text-foreground-muted">
1229+
{message.id}
1230+
</Text>
1231+
</Pressable>
1232+
) : null}
11971233
{presentation.attribution === "automation" ? (
11981234
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
11991235
Sent by automation
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { RunId, ThreadId } from "@t3tools/contracts";
2+
import * as DateTime from "effect/DateTime";
3+
import { describe, expect, it } from "vite-plus/test";
4+
import type { ProjectionLimitRecoveryCandidate } from "./ProjectionStore.ts";
5+
import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts";
6+
7+
const stoppedAt = "2026-10-18T10:00:00.000Z";
8+
const resetAt = "2026-10-18T11:00:00.000Z";
9+
const candidate: ProjectionLimitRecoveryCandidate = {
10+
id: ThreadId.make("quota-test"),
11+
status: "failed",
12+
lastErrorClass: "usage_limit",
13+
latestRunId: RunId.make("stopped-run"),
14+
usageLimitResetAt: resetAt,
15+
archivedAt: null,
16+
settledOverride: "active",
17+
pendingRuntimeRequest: null,
18+
latestRunCompletedAt: DateTime.makeUnsafe(stoppedAt),
19+
updatedAt: DateTime.makeUnsafe(stoppedAt),
20+
limitRecovery: null,
21+
snoozedUntil: null,
22+
};
23+
24+
describe("bounded quota reset recovery", () => {
25+
it("does nothing when both controls are off, then arms a reset-bound recovery without a model dispatch", () => {
26+
expect(limitRecoveryCommand(candidate, false, Date.parse(stoppedAt))).toBeNull();
27+
const arm = limitRecoveryCommand(candidate, true, Date.parse(stoppedAt), true);
28+
expect(arm?.type).toBe("thread.metadata.update");
29+
if (arm?.type !== "thread.metadata.update") throw new Error("missing arm");
30+
expect(arm.limitRecovery).toMatchObject({
31+
runId: candidate.latestRunId,
32+
resetAt,
33+
autoResume: true,
34+
snooze: true,
35+
});
36+
});
37+
38+
it("emits the same original run/reset identity at the reset, attributed to automation", () => {
39+
const armed = {
40+
...candidate,
41+
limitRecovery: { runId: candidate.latestRunId!, resetAt, autoResume: true, snooze: true },
42+
};
43+
expect(limitRecoveryCommand(armed, true, Date.parse(resetAt) - 1)).toBeNull();
44+
const resume = limitRecoveryCommand(armed, true, Date.parse(resetAt));
45+
expect(resume).toMatchObject({
46+
type: "message.dispatch",
47+
createdBy: "agent",
48+
creationSource: "server",
49+
usageLimitContinuationOfRunId: candidate.latestRunId,
50+
});
51+
expect(resume?.commandId).toEqual(
52+
limitRecoveryCommand(armed, true, Date.parse(resetAt) + 1)?.commandId,
53+
);
54+
});
55+
56+
it("holds closed threads, unknown/expired resets, nonquota failures and cancelled recovery", () => {
57+
const recovery = { runId: candidate.latestRunId!, resetAt, autoResume: true, snooze: false };
58+
for (const patch of [
59+
{ archivedAt: DateTime.makeUnsafe(stoppedAt) },
60+
{ settledOverride: "settled" as const },
61+
{ usageLimitResetAt: null },
62+
{ usageLimitResetAt: "invalid" },
63+
{ usageLimitResetAt: stoppedAt },
64+
{ lastErrorClass: "unknown" as const },
65+
{ status: "completed" as const },
66+
{ limitRecovery: { ...recovery, autoResume: false } },
67+
])
68+
expect(
69+
limitRecoveryCommand(
70+
{ ...candidate, limitRecovery: recovery, ...patch },
71+
true,
72+
Date.parse(resetAt),
73+
),
74+
).toBeNull();
75+
});
76+
});

‎apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ export function limitRecoveryCommand(
6666
text: "Continue where you left off.",
6767
attachments: [],
6868
dispatchMode: { type: "start_immediately" },
69-
createdBy: "user",
69+
createdBy: "agent",
7070
creationSource: "server",
7171
};
7272
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import type { ReactNode } from "react";
2+
3+
/** Presentation only: original messages and model input stay intact. Callers
4+
* keep outcomes and decisions outside this group. */
5+
export function BackgroundActivityDisclosure({
6+
eventCount,
7+
children,
8+
}: {
9+
eventCount: number;
10+
children: ReactNode;
11+
}) {
12+
return (
13+
<details className="rounded-lg border border-border/60 px-3 py-2 text-sm text-muted-foreground">
14+
<summary className="cursor-pointer rounded-sm focus-visible:outline-2 focus-visible:outline-ring">
15+
Background activity · {eventCount} {eventCount === 1 ? "event" : "events"}
16+
</summary>
17+
<div className="mt-3 space-y-3">{children}</div>
18+
</details>
19+
);
20+
}

‎apps/web/src/components/chat/MessagesTimeline.logic.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
2+
import { backgroundActivityTrigger } from "@t3tools/client-runtime/user-message";
23
export { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
34
import { isLiveSubagentTurnItem } from "@t3tools/client-runtime/state/subagentRuntime";
45
import * as DateTime from "effect/DateTime";
@@ -519,6 +520,12 @@ export type MessagesTimelineRow = MessagesTimelineRowContent & {
519520
};
520521

521522
type MessagesTimelineRowContent =
523+
| {
524+
kind: "background-activity";
525+
id: string;
526+
createdAt: string;
527+
messages: ReadonlyArray<Extract<MessagesTimelineRow, { kind: "message" }>>;
528+
}
522529
| {
523530
kind: "worktree-setup";
524531
id: string;
@@ -655,6 +662,36 @@ export interface StableMessagesTimelineRowsState {
655662
result: MessagesTimelineRow[];
656663
}
657664

665+
/** Group only adjacent mechanical prompts. Never cross an owner message,
666+
* assistant outcome, failure, permission request, or tool event. */
667+
export function groupBackgroundActivityRows(
668+
rows: ReadonlyArray<MessagesTimelineRow>,
669+
): MessagesTimelineRow[] {
670+
const result: MessagesTimelineRow[] = [];
671+
let messages: Array<Extract<MessagesTimelineRow, { kind: "message" }>> = [];
672+
const flush = () => {
673+
const first = messages[0];
674+
if (!first) return;
675+
result.push({
676+
kind: "background-activity",
677+
id: first.id,
678+
createdAt: first.createdAt,
679+
messages,
680+
});
681+
messages = [];
682+
};
683+
for (const row of rows) {
684+
if (row.kind !== "message" || backgroundActivityTrigger(row.message) === null) {
685+
flush();
686+
result.push(row);
687+
continue;
688+
}
689+
messages.push(row);
690+
}
691+
flush();
692+
return result;
693+
}
694+
658695
export function computeMessageDurationStart(
659696
messages: ReadonlyArray<TimelineDurationMessage>,
660697
): Map<string, string> {
@@ -2247,6 +2284,13 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
22472284
if (a.kind !== b.kind || a.id !== b.id) return false;
22482285

22492286
switch (a.kind) {
2287+
case "background-activity": {
2288+
const group = b as typeof a;
2289+
return (
2290+
a.messages.length === group.messages.length &&
2291+
a.messages.every((row, index) => isRowUnchanged(row, group.messages[index]!))
2292+
);
2293+
}
22502294
case "working":
22512295
return a.createdAt === (b as typeof a).createdAt;
22522296
case "thinking": {

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ import {
3636
import { parseScopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3737
import { useAtomValue } from "@effect/atom-react";
3838
import { environmentThreadDetails } from "../../state/threads";
39-
import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
39+
import {
40+
backgroundActivityTrigger,
41+
resolveUserMessagePresentation,
42+
} from "@t3tools/client-runtime/user-message";
4043
import { Link } from "@tanstack/react-router";
4144
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
4245
import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";
@@ -186,6 +189,7 @@ import {
186189
timelineContentOverflowsViewport,
187190
} from "./timelineScrollAnchoring";
188191
import { MessageCopyButton } from "./MessageCopyButton";
192+
import { BackgroundActivityDisclosure } from "./BackgroundActivityDisclosure";
189193
import { promptLinkFor } from "../promptLinks/copyPromptLink";
190194
import { PierreEntryIcon } from "./PierreEntryIcon";
191195
import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
@@ -199,6 +203,7 @@ import {
199203
import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
200204
import {
201205
computeStableMessagesTimelineRows,
206+
groupBackgroundActivityRows,
202207
deriveMessagesTimelineRowsWithState,
203208
type MessagesTimelineRowsProjection,
204209
liveWorkEntryLabel,
@@ -948,7 +953,13 @@ const ConversationTimeline = memo(function ConversationTimeline({
948953
supportsConversationRollback,
949954
worktreeSetup,
950955
]);
951-
const rows = useStableRows(rawRows, listIdentityKey);
956+
// Search uses the original rows so matches inside a folded prompt can be
957+
// revealed and navigated without changing history or message identities.
958+
const backgroundRows = useMemo(
959+
() => (findActive ? rawRows : groupBackgroundActivityRows(rawRows)),
960+
[findActive, rawRows],
961+
);
962+
const rows = useStableRows(backgroundRows, listIdentityKey);
952963
// Run status/timestamps churn on every stream event; the shared row context
953964
// must not change with them or every timeline row re-renders per event.
954965
const runs = useStableHandoffRuns(runsProp);
@@ -2186,6 +2197,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
21862197
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
21872198
{row.kind === "attempt-fold" ? <AttemptFoldTimelineRow row={row} /> : null}
21882199
{row.kind === "context-compaction" ? <ContextCompactionTimelineRow row={row} /> : null}
2200+
{row.kind === "background-activity" ? <BackgroundActivityTimelineRow row={row} /> : null}
21892201
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
21902202
{row.kind === "message" && row.message.role === "assistant" ? (
21912203
<AssistantTimelineRow row={row} />
@@ -2309,6 +2321,34 @@ function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
23092321
// from selection so sighted users and copied text are unaffected.
23102322
const MESSAGE_HEADING_LEVEL = 3;
23112323

2324+
function BackgroundActivityTimelineRow({
2325+
row,
2326+
}: {
2327+
row: Extract<TimelineRow, { kind: "background-activity" }>;
2328+
}) {
2329+
const ctx = use(TimelineRowCtx);
2330+
return (
2331+
<BackgroundActivityDisclosure eventCount={row.messages.length}>
2332+
{row.messages.map((messageRow) => (
2333+
<div key={messageRow.id}>
2334+
<div className="mb-1 flex flex-wrap items-center gap-2 text-xs">
2335+
<span>{backgroundActivityTrigger(messageRow.message)}</span>
2336+
<TimelineRowTimestamp
2337+
createdAt={messageRow.createdAt}
2338+
timestampFormat={ctx.timestampFormat}
2339+
/>
2340+
<code className="break-all">{messageRow.message.id}</code>
2341+
{messageRow.message.runId ? (
2342+
<code className="break-all">{messageRow.message.runId}</code>
2343+
) : null}
2344+
</div>
2345+
<UserTimelineRow row={messageRow} />
2346+
</div>
2347+
))}
2348+
</BackgroundActivityDisclosure>
2349+
);
2350+
}
2351+
23122352
function MessageAuthorHeading({ children }: { children: string }) {
23132353
return <h3 className="sr-only select-none">{children}</h3>;
23142354
}
@@ -2527,7 +2567,15 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
25272567
<UserMessageIntentMarker intent={row.message.inputIntent} />
25282568
) : null}
25292569
<div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
2530-
<MessageAuthorHeading>You</MessageAuthorHeading>
2570+
<MessageAuthorHeading>
2571+
{userMessage.attribution === null
2572+
? "You"
2573+
: userMessage.attribution === "agent"
2574+
? "Another agent"
2575+
: userMessage.attribution === "automation"
2576+
? "Automation"
2577+
: "T3 Code"}
2578+
</MessageAuthorHeading>
25312579
{(regularImages.length > 0 || userVideos.length > 0) && (
25322580
<div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
25332581
{regularImages.map((image) => (

0 commit comments

Comments
 (0)