TypeScript
fix(mobile): show plans and fold settled progress notes (#21393)
maria77e4f561f58b
diff --git a/apps/mobile/src/features/threads/ProposedPlanCard.tsx b/apps/mobile/src/features/threads/ProposedPlanCard.tsxnew file mode 100644index 00000000000..781790937fb--- /dev/null+++ b/apps/mobile/src/features/threads/ProposedPlanCard.tsx@@ -0,0 +1,85 @@+import { useAtomValue } from "@effect/atom-react";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import type { EnvironmentId } from "@t3tools/contracts";+import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "@t3tools/shared/proposedPlanText";+import { useRef, useState, type ReactNode } from "react";+import { View } from "react-native";++import { AppText as Text } from "../../components/ui/AppText";+import { Button } from "../../components/ui/Button";+import * as Dialog from "../../components/ui/Dialog";+import { projectEnvironment } from "../../state/projects";+import { useAtomCommand } from "../../state/use-atom-command";+import { CopyTextButton } from "./CopyTextButton";++export function ProposedPlanCard(props: {+ readonly environmentId: EnvironmentId;+ readonly workspaceRoot: string | null | undefined;+ readonly markdown: string;+ readonly renderMarkdown: (text: string) => ReactNode;+}) {+ const canWrite = useAtomValue(projectEnvironment.writeFile.permissionAtom(props.environmentId));+ const writeFile = useAtomCommand(projectEnvironment.writeFile, { reportFailure: false });+ const inFlight = useRef(false);+ const [saving, setSaving] = useState(false);+ const [lastPath, setLastPath] = useState("plan.md");+ const contents = `${props.markdown.trimEnd()}\n`;++ const save = async (path: string) => {+ const relativePath = path.trim();+ if (!canWrite || !props.workspaceRoot || inFlight.current) return;+ if (!relativePath) {+ Dialog.alert("Enter a workspace path");+ return;+ }+ inFlight.current = true;+ setSaving(true);+ setLastPath(relativePath);+ const result = await writeFile({+ environmentId: props.environmentId,+ input: { cwd: props.workspaceRoot, relativePath, contents },+ }).finally(() => {+ inFlight.current = false;+ setSaving(false);+ });+ if (result._tag === "Success") {+ Dialog.alert("Plan saved to workspace", result.value.relativePath);+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ Dialog.alert("Could not save plan", error instanceof Error ? error.message : String(error));+ }+ };++ return (+ <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">+ <View className="flex-row items-center gap-2">+ <Text accessibilityRole="header" className="flex-1 font-t3-bold text-base text-foreground">+ {proposedPlanTitle(props.markdown) ?? "Proposed plan"}+ </Text>+ <CopyTextButton accessibilityLabel="Copy plan" text={contents} />+ </View>+ {props.renderMarkdown(stripDisplayedPlanMarkdown(props.markdown))}+ <View className="flex-row">+ <Button+ label={saving ? "Saving..." : "Save to workspace"}+ tone="secondary"+ disabled={!canWrite || !props.workspaceRoot || saving}+ onPress={() =>+ Dialog.prompt({+ title: "Save plan to workspace",+ // The write replaces an existing file, and the RPC has no create-only mode.+ message:+ "Enter a path relative to the thread's workspace. A file already at that path is replaced.",+ initialValue: lastPath,+ confirmText: "Save",+ onConfirm: (path) => void save(path),+ })+ }+ />+ </View>+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 727cf578244..a96d071b4ec 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -1445,6 +1445,7 @@ function renderFeedEntry(activities={entry.activities}continuesWorkLog={entry.continuesWorkLog}environmentId={props.environmentId}+ workspaceRoot={props.workspaceRoot}anchorKey={entry.id}copiedRowId={props.copiedRowId}expandedRows={props.expandedWorkRows}diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsxindex b347227caec..b056bab4b64 100644--- a/apps/mobile/src/features/threads/thread-work-log.tsx+++ b/apps/mobile/src/features/threads/thread-work-log.tsx@@ -1,6 +1,7 @@import { Button } from "../../components/ui/Button";import { SubagentStatusDot } from "./SubagentStatusDot";import { ThreadSubagentGroup } from "./thread-subagent-group";+import { ProposedPlanCard } from "./ProposedPlanCard";import {WorkLogLabel,WorkLogBlock,@@ -483,6 +484,7 @@ interface ThreadWorkLogProps {readonly activities: ReadonlyArray<ThreadFeedActivity>;readonly anchorKey: string;readonly environmentId: EnvironmentId;+ readonly workspaceRoot?: string | null | undefined;readonly copiedRowId: string | null;readonly expandedRows: Readonly<Record<string, boolean>>;readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;@@ -521,6 +523,18 @@ export function ThreadWorkLog(props: ThreadWorkLogProps) {return null;}+ const plan = props.activities[0]?.projectedItem.item;+ if (plan?.type === "proposed_plan") {+ return (+ <ProposedPlanCard+ environmentId={props.environmentId}+ workspaceRoot={props.workspaceRoot}+ markdown={plan.markdown}+ renderMarkdown={props.renderReasoning}+ />+ );+ }+if (props.activities[0]?.projectedItem.item.type === "subagent") {return <ThreadSubagentGroup {...props} />;}diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.tsindex b443c0e3f7a..3587d7a87b9 100644--- a/apps/mobile/src/lib/threadActivity.test.ts+++ b/apps/mobile/src/lib/threadActivity.test.ts@@ -60,7 +60,26 @@ it("keeps historical plan detail accessible from its paged turn item", () => {entry.type === "activity-group" ? entry.activities : [],)[0];expect(activity?.detail).toBe("Full historical plan text");- expect(activity?.getFullDetail()).toContain("Full historical plan text");+ expect(activity?.getFullDetail()).toBe("Full historical plan text");+ expect(activity?.getCopyText()).toBe("Full historical plan text\n");+ expect(activity?.prominent).toBe(true);+ const presented = deriveThreadFeedPresentation(+ buildThreadFeed([+ projected(userMessage(), 0),+ projected(command(), 1),+ projected(item, 2),+ projected(assistantMessage(), 3),+ ]),+ null,+ new Set(),+ );+ expect(presented.map((entry) => entry.type)).toEqual([+ "message",+ "run-fold",+ "activity-group",+ "message",+ ]);+ expect(presented[2]).toMatchObject({ activities: [{ projectedItem: { item } }] });});it("shows only the structured path in expanded mobile read details", () => {@@ -245,6 +264,56 @@ describe("buildThreadFeed", () => {expect(buildThreadFeed([projected(reply, 0)])[0]?.type).toBe("message");});+ it.each([false, true])(+ "keeps answered questions outside settled work (attachments only: %s)",+ (attachmentsOnly) => {+ const requestId = RuntimeRequestId.make("answered-question");+ const question: OrchestrationV2TurnItem = {+ ...base("answered-question", "2026-06-20T00:00:02.500Z", 2),+ type: "user_input_request",+ requestId,+ questions: [],+ questionAnswer: {+ requestId,+ questionTextById: { color: "Which color?" },+ answers: { color: attachmentsOnly ? "" : "Blue" },+ attachmentsByQuestionId: attachmentsOnly+ ? {+ color: [+ {+ type: "file",+ id: "color-file",+ name: "color.txt",+ mimeType: "text/plain",+ sizeBytes: 4,+ },+ ],+ }+ : {},+ },+ };+ const feed = buildThreadFeed([+ projected(userMessage(), 0),+ projected(command(), 1),+ projected(question, 2),+ projected(assistantMessage(), 3),+ ]);+ const presented = deriveThreadFeedPresentation(feed, null, new Set());+ expect(presented.map((entry) => entry.type)).toEqual([+ "message",+ "run-fold",+ "activity-group",+ "message",+ ]);+ expect(presented[2]).toMatchObject({+ activities: [{ workEntry: { questionAnswer: question.questionAnswer } }],+ });+ expect(+ deriveThreadFeedPresentation(feed, null, new Set([runId])).map((entry) => entry.type),+ ).toEqual(["message", "run-fold", "activity-group", "activity-group", "message"]);+ },+ );+it("does not create a work group for a message and checkpoint", () => {const checkpoint: OrchestrationV2TurnItem = {...base("checkpoint", "2026-06-20T00:00:04.000Z", 3),@@ -844,7 +913,7 @@ describe("buildThreadFeed", () => {).toBe(false);});- it("keeps opening and final assistant messages around the first hidden work", () => {+ it("folds progress messages while keeping the final assistant answer visible", () => {const opening = {...assistantMessage("2026-06-20T00:00:01.500Z"),id: TurnItemId.make("item-opening"),@@ -874,30 +943,40 @@ describe("buildThreadFeed", () => {const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());expect(collapsed.map((entry) => entry.id)).toEqual(["message-user",- "message-opening","run-fold:run-1","message-assistant",]);- expect(collapsed[1]).toMatchObject({ message: { text: opening.text } });- expect(collapsed[2]).toMatchObject({+ expect(collapsed[1]).toMatchObject({type: "run-fold",- createdAt: "2026-06-20T00:00:02.000Z",+ createdAt: "2026-06-20T00:00:01.500Z",label: "Worked for 2.0s",});const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));expect(expanded.map((entry) => entry.type)).toEqual([- "message","message","run-fold",+ "message","activity-group","message","message",]);expect(expanded[4]).toMatchObject({ message: { id: middle.messageId, text: middle.text } });++ const active = deriveThreadFeedPresentation(+ feed,+ { ...latestRun, status: "running", completedAt: null },+ new Set(),+ );+ expect(active.filter((entry) => entry.type === "message").map((entry) => entry.id)).toEqual([+ "message-user",+ "message-opening",+ "message-middle",+ "message-assistant",+ ]);});- it("does not fold a response that only has opening and final messages", () => {+ it("folds progress even when a response has no tool calls", () => {const feed = buildThreadFeed([projected(userMessage(), 0),projected(@@ -915,7 +994,7 @@ describe("buildThreadFeed", () => {const presented = deriveThreadFeedPresentation(feed, null, new Set());expect(presented.map((entry) => entry.id)).toEqual(["message-user",- "message-opening",+ "run-fold:run-1","message-assistant",]);});@@ -1230,7 +1309,7 @@ describe("buildThreadFeed", () => {new Set(),"2026-06-20T00:01:00.000Z",)- .slice(0, 4)+ .slice(0, 3).map((entry) => (entry.type === "message" ? entry.message.role : entry.type));expect(@@ -1239,7 +1318,7 @@ describe("buildThreadFeed", () => {id: TurnItemId.make("new-prompt"),messageId: MessageId.make("new-prompt"),}),- ).toEqual(["user", "assistant", "run-fold", "assistant"]);+ ).toEqual(["user", "run-fold", "assistant"]);expect(presented({...base("wake", "2026-06-20T00:01:00.000Z", 4),@@ -1248,7 +1327,7 @@ describe("buildThreadFeed", () => {outcome: "completed",summary: "Background task finished",}),- ).toEqual(["user", "assistant", "run-fold", "assistant"]);+ ).toEqual(["user", "run-fold", "assistant"]);});it("keeps a provider-native subagent's runless tool call live while it works", () => {@@ -2247,7 +2326,6 @@ describe("subagent continued by a later turn", () => {"answer-1","prompt-2",`run-fold:${run2}`,- "answer-2","closing-2",]);});diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex ff68fa56f2e..c703d223878 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -467,6 +467,7 @@ function itemIsProminent(item: OrchestrationV2TurnItem): boolean {item.type === "fork" ||item.type === "thread_created" ||item.type === "system_notice" ||+ item.type === "proposed_plan" ||item.type === "secret_request");}@@ -823,19 +824,23 @@ function toFeedActivity(? collectToolFilePaths(item): null;const getFullDetail = memoizeValue(() =>- readPaths- ? readPaths.join("\n") || null- : item.type === "notification"- ? item.detail?.trim() || null- : formatItemFullDetail(row, item),+ item.type === "proposed_plan"+ ? item.markdown+ : readPaths+ ? readPaths.join("\n") || null+ : item.type === "notification"+ ? item.detail?.trim() || null+ : formatItemFullDetail(row, item),);const getCopyText = memoizeValue(() =>- [summary, detail, getFullDetail()]- .filter(- (value, index, values): value is string =>- Boolean(value) && values.indexOf(value) === index,- )- .join("\n"),+ item.type === "proposed_plan"+ ? `${item.markdown.trimEnd()}\n`+ : [summary, detail, getFullDetail()]+ .filter(+ (value, index, values): value is string =>+ Boolean(value) && values.indexOf(value) === index,+ )+ .join("\n"),);return {id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,@@ -955,6 +960,7 @@ function groupAdjacentActivities(}const isStandaloneActivity =+ entry.activity.workEntry.questionAnswer !== undefined ||entry.activity.projectedItem.item.type === "compaction" ||entry.activity.projectedItem.item.type === "handoff" ||entry.activity.projectedItem.item.type === "notification";@@ -1059,7 +1065,6 @@ function deriveThreadFeedRunFolds(runlessWorkActive: boolean,feedFailedRunIds: ReadonlySet<RunId>,): ReadonlyMap<string, ThreadFeedRunFold> {- const firstAssistantMessageIdByRun = new Map<RunId, string>();const terminalAssistantMessageIdByRun = new Map<RunId, string>();const interruptedRunIds = new Set<RunId>();const failedRunIds = new Set(feedFailedRunIds);@@ -1114,9 +1119,6 @@ function deriveThreadFeedRunFolds(}group.entries.push(entry);if (entry.type === "message") {- if (!firstAssistantMessageIdByRun.has(runId)) {- firstAssistantMessageIdByRun.set(runId, entry.id);- }terminalAssistantMessageIdByRun.set(runId, entry.id);}if (entry.type !== "activity-group") continue;@@ -1146,13 +1148,11 @@ function deriveThreadFeedRunFolds() {continue;}- const firstAssistantId = firstAssistantMessageIdByRun.get(runId);const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);const hiddenEntryIds = new Set(group.entries.filter((entry) =>- entry.id !== firstAssistantId &&entry.id !== terminalAssistantId &&entry.type !== "html-render" &&entry.type !== "mcp-app" &&@@ -1161,6 +1161,7 @@ function deriveThreadFeedRunFolds(entry.activities.some((activity) =>activity.prominent ||+ activity.workEntry.questionAnswer !== undefined ||activity.projectedItem.item.type === "notification" ||activity.projectedItem.item.type === "handoff" ||// A child still working outlives its settled launching run;