-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathTaskSessionView.tsx
More file actions
1108 lines (1042 loc) · 33.9 KB
/
Copy pathTaskSessionView.tsx
File metadata and controls
1108 lines (1042 loc) · 33.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
ArrowDown,
Brain,
CaretRight,
CloudArrowDown,
Robot,
} from "phosphor-react-native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
FlatList,
Pressable,
Text,
View,
} from "react-native";
import {
AgentMessage,
deriveToolKind,
HumanMessage,
ToolMessage,
type ToolStatus,
} from "@/features/chat";
import { getRandomThinkingActivity } from "@/features/chat/utils/thinkingMessages";
import { useThemeColors } from "@/lib/theme";
import type {
CloudPendingPermissionRequest,
PlanEntry,
SessionEvent,
SessionNotification,
SessionNotificationAttachment,
} from "../types";
import { PlanApprovalCard } from "./PlanApprovalCard";
import { PlanStatusBar } from "./PlanStatusBar";
import { QuestionCard } from "./QuestionCard";
interface PermissionResponseArgs {
toolCallId: string;
optionId: string;
answers?: Record<string, string>;
customInput?: string;
displayText: string;
}
interface OptimisticUserMessage {
text: string;
attachments?: SessionNotificationAttachment[];
// Submit-time epoch ms. Dedup only fires against user messages whose `ts`
// is at or after this — protects against a text-identical historical turn
// suppressing the new optimistic echo.
setAt: number;
}
interface TaskSessionViewProps {
events: SessionEvent[];
pendingPermissions?: Record<string, CloudPendingPermissionRequest>;
isConnecting?: boolean;
isThinking?: boolean;
terminalStatus?: "failed" | "completed";
lastError?: string | null;
onRetry?: () => void;
onOpenTask?: (taskId: string) => void;
onSendPermissionResponse?: (args: PermissionResponseArgs) => void;
/** Current task model + setter, forwarded to the plan-approval card so the
* user can swap the model inline before approving. */
model?: string;
onModelChange?: (model: string) => void;
contentContainerStyle?: object;
// Renders a user message at the bottom of the thread before the SSE echo
// arrives — for the gap between submit and the live session catching up.
// Suppressed automatically once a real user_message_chunk with matching
// text appears in `events`.
optimisticUserMessage?: OptimisticUserMessage;
}
interface ToolData {
toolName: string;
rawToolName?: string;
toolCallId: string;
status: ToolStatus;
args?: Record<string, unknown>;
result?: unknown;
isAgent?: boolean;
parentToolCallId?: string;
}
interface ParsedMessage {
id: string;
type: "user" | "agent" | "thought" | "tool" | "connecting" | "thinking";
content: string;
ts?: number;
toolData?: ToolData;
children?: ParsedMessage[];
attachments?: SessionNotificationAttachment[];
}
function mapToolStatus(
status?: "pending" | "in_progress" | "completed" | "failed" | null,
): ToolStatus {
switch (status) {
case "pending":
return "pending";
case "in_progress":
return "running";
case "completed":
return "completed";
case "failed":
return "error";
default:
return "pending";
}
}
type ParsedNotification =
| {
type: "user";
content: string;
attachments?: SessionNotificationAttachment[];
}
| { type: "agent" | "agent_complete" | "thought"; content: string }
| { type: "tool" | "tool_update"; toolData: ToolData }
| { type: "plan"; entries: PlanEntry[] };
function parseSessionNotification(
notification: SessionNotification,
): ParsedNotification | null {
const { update } = notification;
if (!update?.sessionUpdate) {
return null;
}
switch (update.sessionUpdate) {
case "user_message_chunk":
case "agent_message_chunk": {
const hasText = update.content?.type === "text";
const isUser = update.sessionUpdate === "user_message_chunk";
if (isUser) {
const attachments = update.attachments;
// Drop only if there's neither text nor attachments to render.
if (!hasText && (!attachments || attachments.length === 0)) {
return null;
}
return {
type: "user",
content: hasText ? (update.content?.text ?? "") : "",
attachments,
};
}
if (hasText) {
return {
type: "agent",
content: update.content?.text ?? "",
};
}
return null;
}
// `agent_message` is the aggregated final message emitted by the server
// once a response is complete. If we already received streaming chunks,
// this is a duplicate — replace pending text instead of appending.
case "agent_message": {
if (update.content?.type === "text") {
return {
type: "agent_complete" as const,
content: update.content.text,
};
}
return null;
}
case "agent_thought_chunk": {
if (update.content?.type === "text") {
return { type: "thought", content: update.content.text };
}
return null;
}
case "tool_call": {
const meta = update._meta?.claudeCode;
const isAgent = meta?.toolName === "Agent" || meta?.toolName === "Task";
return {
type: "tool",
toolData: {
toolName: update.title ?? "Unknown Tool",
rawToolName: meta?.toolName,
toolCallId: update.toolCallId ?? "",
status: mapToolStatus(update.status),
args: update.rawInput,
isAgent,
parentToolCallId: meta?.parentToolCallId,
},
};
}
case "tool_call_update": {
const meta = update._meta?.claudeCode;
return {
type: "tool_update",
toolData: {
toolName: update.title ?? "Unknown Tool",
rawToolName: meta?.toolName,
toolCallId: update.toolCallId ?? "",
status: mapToolStatus(update.status),
args: update.rawInput,
result: update.rawOutput,
parentToolCallId: meta?.parentToolCallId,
},
};
}
case "plan": {
if (Array.isArray(update.entries)) {
return { type: "plan", entries: update.entries };
}
return null;
}
default:
return null;
}
}
interface ProcessedEvents {
messages: ParsedMessage[];
plan: PlanEntry[] | null;
}
function isQuestionTool(toolData?: ToolData): boolean {
if (!toolData) return false;
if (toolData.toolName.toLowerCase().includes("question")) return true;
if (Array.isArray(toolData.args?.questions)) return true;
return false;
}
function hasPendingQuestionMessage(message: ParsedMessage): boolean {
const isPendingQuestion =
message.type === "tool" &&
isQuestionTool(message.toolData) &&
(message.toolData?.status === "pending" ||
message.toolData?.status === "running");
if (isPendingQuestion) {
return true;
}
return message.children?.some(hasPendingQuestionMessage) ?? false;
}
function isPlanApprovalTool(
toolData?: ToolData,
permission?: CloudPendingPermissionRequest,
): boolean {
if (permission?.toolCall.kind === "switch_mode") return true;
if (toolData?.rawToolName === "ExitPlanMode") return true;
return typeof toolData?.args?.plan === "string";
}
function isInteractivePermissionTool(
toolData?: ToolData,
permission?: CloudPendingPermissionRequest,
): boolean {
return isQuestionTool(toolData) || isPlanApprovalTool(toolData, permission);
}
// Mutable processor state persisted across renders via useRef.
// Only new events (past processedIdx) are processed on each call.
interface EventProcessorState {
messages: ParsedMessage[];
plan: PlanEntry[] | null;
pendingAgentText: string;
pendingAgentTs?: number;
pendingThoughtText: string;
lastAgentMsgIdx: number | null;
agentMessageCount: number;
thoughtMessageCount: number;
userMessageCount: number;
toolMessages: Map<string, ParsedMessage>;
// Maps agent toolCallId → agent ParsedMessage for nesting children
agentTools: Map<string, ParsedMessage>;
processedIdx: number;
// Snapshot tracking: only create a new array ref when messages grow.
// Mutations (tool_update, agent_complete replacing content) reuse the
// same snapshot so FlatList doesn't re-layout and reset scroll position.
lastSnapshot: ParsedMessage[];
lastSnapshotLength: number;
}
function createProcessorState(): EventProcessorState {
return {
messages: [],
plan: null,
pendingAgentText: "",
pendingThoughtText: "",
lastAgentMsgIdx: null,
agentMessageCount: 0,
thoughtMessageCount: 0,
userMessageCount: 0,
toolMessages: new Map(),
agentTools: new Map(),
processedIdx: 0,
lastSnapshot: [],
lastSnapshotLength: 0,
};
}
function processNewEvents(
state: EventProcessorState,
events: SessionEvent[],
): ProcessedEvents {
// If events shrank (e.g. session reset), start fresh
if (events.length < state.processedIdx) {
Object.assign(state, createProcessorState());
}
// Nothing new to process
if (events.length === state.processedIdx) {
return { messages: state.messages, plan: state.plan };
}
let hasItemMutation = false;
const flushAgentText = () => {
if (!state.pendingAgentText) return;
// If the last message is an in-progress agent message from a previous
// batch, append to it instead of creating a new bubble. This keeps
// streaming chunks that arrive across multiple SSE batches unified
// into a single rendered message.
if (
state.lastAgentMsgIdx !== null &&
state.messages[state.lastAgentMsgIdx]?.type === "agent"
) {
state.messages[state.lastAgentMsgIdx].content += state.pendingAgentText;
hasItemMutation = true;
} else {
const msg: ParsedMessage = {
id: `agent-${state.agentMessageCount++}`,
type: "agent",
content: state.pendingAgentText,
ts: state.pendingAgentTs,
};
state.messages.push(msg);
state.lastAgentMsgIdx = state.messages.length - 1;
}
state.pendingAgentText = "";
state.pendingAgentTs = undefined;
};
const flushThoughtText = () => {
if (!state.pendingThoughtText) return;
// Merge consecutive thoughts into one message instead of many rows
const lastMsg = state.messages[state.messages.length - 1];
if (lastMsg?.type === "thought") {
lastMsg.content += state.pendingThoughtText;
} else {
state.messages.push({
id: `thought-${state.thoughtMessageCount++}`,
type: "thought",
content: state.pendingThoughtText,
});
}
state.pendingThoughtText = "";
};
const flushPending = () => {
flushThoughtText();
flushAgentText();
};
for (let i = state.processedIdx; i < events.length; i++) {
const event = events[i];
if (event.type !== "session_update") continue;
const parsed = parseSessionNotification(event.notification);
if (!parsed) continue;
switch (parsed.type) {
case "user":
flushPending();
state.messages.push({
id: `user-${state.userMessageCount++}`,
type: "user",
content: parsed.content ?? "",
ts: event.ts,
attachments: parsed.attachments,
});
state.lastAgentMsgIdx = null;
break;
case "agent":
flushThoughtText();
if (!state.pendingAgentTs) state.pendingAgentTs = event.ts;
state.pendingAgentText += parsed.content ?? "";
break;
case "agent_complete":
flushThoughtText();
// Replace accumulated chunks with the finalized message
if (
state.lastAgentMsgIdx !== null &&
state.messages[state.lastAgentMsgIdx]?.type === "agent"
) {
state.messages[state.lastAgentMsgIdx].content = parsed.content ?? "";
if (!state.messages[state.lastAgentMsgIdx].ts) {
state.messages[state.lastAgentMsgIdx].ts = event.ts;
}
hasItemMutation = true;
state.pendingAgentText = "";
state.pendingAgentTs = undefined;
} else {
state.pendingAgentText = parsed.content ?? "";
if (!state.pendingAgentTs) state.pendingAgentTs = event.ts;
}
break;
case "thought":
flushAgentText();
state.pendingThoughtText += parsed.content ?? "";
break;
case "plan":
state.plan = parsed.entries;
break;
case "tool":
flushPending();
if (parsed.toolData) {
const existing = state.toolMessages.get(parsed.toolData.toolCallId);
if (existing?.toolData) {
existing.toolData = {
...existing.toolData,
...parsed.toolData,
};
} else {
const msg: ParsedMessage = {
id: `tool-${parsed.toolData.toolCallId}`,
type: "tool",
content: "",
toolData: parsed.toolData,
children: parsed.toolData.isAgent ? [] : undefined,
};
state.toolMessages.set(parsed.toolData.toolCallId, msg);
// Agent tools: register for child nesting
if (parsed.toolData.isAgent) {
state.agentTools.set(parsed.toolData.toolCallId, msg);
}
// Child tools: nest under parent agent instead of top-level
const parentId = parsed.toolData.parentToolCallId;
const parent = parentId
? state.agentTools.get(parentId)
: undefined;
if (parent?.children) {
parent.children.push(msg);
hasItemMutation = true;
} else {
state.messages.push(msg);
}
}
}
state.lastAgentMsgIdx = null;
break;
case "tool_update":
if (parsed.toolData) {
const existing = state.toolMessages.get(parsed.toolData.toolCallId);
if (existing?.toolData) {
existing.toolData.status = parsed.toolData.status;
existing.toolData.result = parsed.toolData.result;
if (parsed.toolData.args) {
existing.toolData.args = parsed.toolData.args;
}
hasItemMutation = true;
}
}
break;
}
}
flushPending();
state.processedIdx = events.length;
// Create a new array reference when messages were added or when a tool
// received args for the first time (so the diff view can render).
// Pure status/text mutations reuse the prior snapshot to avoid jumps.
if (state.messages.length !== state.lastSnapshotLength || hasItemMutation) {
state.lastSnapshot = [...state.messages];
state.lastSnapshotLength = state.messages.length;
}
return { messages: state.lastSnapshot, plan: state.plan };
}
const THOUGHT_COLLAPSED_LINE_COUNT = 5;
function CollapsedThought({ content }: { content: string }) {
const themeColors = useThemeColors();
const [expanded, setExpanded] = useState(false);
const [showAllLines, setShowAllLines] = useState(false);
const hasContent = content.trim().length > 0;
const contentLines = content.split("\n");
const isLineCollapsible =
hasContent && contentLines.length > THOUGHT_COLLAPSED_LINE_COUNT;
const hiddenLineCount = contentLines.length - THOUGHT_COLLAPSED_LINE_COUNT;
const displayedContent =
showAllLines || !isLineCollapsible
? content
: contentLines.slice(0, THOUGHT_COLLAPSED_LINE_COUNT).join("\n");
return (
<View className="px-4 py-0.5">
<Pressable
onPress={() => {
if (!hasContent) return;
setExpanded((v) => !v);
if (!expanded) setShowAllLines(false);
}}
className="flex-row items-center gap-2"
>
<Brain size={12} color={themeColors.gray[11]} />
<Text className="text-[13px] text-gray-11">Thinking</Text>
</Pressable>
{expanded && hasContent && (
<View className="mt-1 ml-5 overflow-hidden rounded-lg border border-gray-6 px-3 py-2">
<Text
className="font-mono text-[12px] text-gray-11 leading-4"
selectable
>
{displayedContent}
</Text>
{isLineCollapsible && !showAllLines && (
<Pressable
onPress={() => setShowAllLines(true)}
className="mt-1 self-start"
hitSlop={6}
>
<Text className="text-[12px] text-gray-10">
+{hiddenLineCount} more lines
</Text>
</Pressable>
)}
</View>
)}
</View>
);
}
// Detect objects like {"0":"E","1":"r","2":"r",...,"isError":true} — a string
// serialized as char-per-key (possibly with extra metadata keys mixed in).
function tryReassembleString(obj: Record<string, unknown>): string | null {
const numericKeys = Object.keys(obj).filter((k) => /^\d+$/.test(k));
if (numericKeys.length < 3) return null;
if (
numericKeys.every(
(k) => typeof obj[k] === "string" && (obj[k] as string).length === 1,
)
) {
return numericKeys
.sort((a, b) => Number(a) - Number(b))
.map((k) => obj[k])
.join("");
}
return null;
}
function extractErrorText(result: unknown): string | null {
if (typeof result === "string") return result;
if (Array.isArray(result)) {
const texts = result.map(extractErrorText).filter(Boolean);
return texts.length > 0 ? texts.join("\n") : null;
}
if (!result || typeof result !== "object") return null;
const obj = result as Record<string, unknown>;
// Reassemble char-per-key strings: {"0":"E","1":"r",...}
const reassembled = tryReassembleString(obj);
if (reassembled) return reassembled;
// Check simple string fields, recurse into nested objects
for (const key of [
"error",
"message",
"stderr",
"output",
"text",
"content",
]) {
if (typeof obj[key] === "string") return obj[key] as string;
if (obj[key] && typeof obj[key] === "object") {
const nested = extractErrorText(obj[key]);
if (nested) return nested;
}
}
// Last resort: stringify the result so *something* shows
try {
const str = JSON.stringify(result, null, 2);
if (str && str !== "{}") return str;
} catch {
// ignore
}
return null;
}
function agentPromptSummary(args?: Record<string, unknown>): string | null {
if (!args) return null;
const prompt =
typeof args.prompt === "string"
? args.prompt
: typeof args.description === "string"
? args.description
: null;
if (!prompt) return null;
// Take the first meaningful line, truncated
const firstLine = prompt
.split("\n")
.find((l) => l.trim())
?.trim();
if (!firstLine) return null;
return firstLine.length > 120 ? `${firstLine.slice(0, 120)}…` : firstLine;
}
function AgentToolCard({
item,
onOpenTask,
}: {
item: ParsedMessage;
onOpenTask?: (taskId: string) => void;
}) {
const themeColors = useThemeColors();
const [expanded, setExpanded] = useState(false);
const toolData = item.toolData;
const children = item.children ?? [];
if (!toolData) return null;
const isLoading =
toolData.status === "pending" || toolData.status === "running";
const isFailed = toolData.status === "error";
const childCount = children.length;
const subtitle = agentPromptSummary(toolData.args);
const errorText = isFailed ? extractErrorText(toolData.result) : null;
return (
<View className="mx-4 my-1 overflow-hidden rounded-lg border border-gray-6 bg-gray-2">
{/* Header */}
<Pressable onPress={() => setExpanded(!expanded)} className="px-3 py-2">
<View className="flex-row items-center gap-2">
{isLoading ? (
<ActivityIndicator size={12} color={themeColors.accent[9]} />
) : (
<Robot
size={14}
color={
isFailed ? themeColors.status.error : themeColors.accent[9]
}
/>
)}
<Text
className="flex-1 font-mono text-[13px] text-gray-12"
numberOfLines={1}
>
{toolData.toolName}
</Text>
{childCount > 0 && (
<Text className="font-mono text-[11px] text-gray-9">
{childCount} {childCount === 1 ? "tool" : "tools"}
</Text>
)}
{isFailed && (
<Text className="font-mono text-[11px] text-status-error">
Failed
</Text>
)}
<CaretRight
size={12}
color={themeColors.gray[9]}
style={{
transform: [{ rotate: expanded ? "90deg" : "0deg" }],
}}
/>
</View>
{subtitle && (
<Text
className="mt-1 ml-5 text-[12px] text-gray-9 leading-4"
numberOfLines={2}
>
{subtitle}
</Text>
)}
</Pressable>
{/* Error message + nested tool calls */}
{expanded && (
<View className="border-gray-6 border-t">
{errorText && (
<View className="mx-3 my-2 rounded bg-status-error/10 px-3 py-2">
<Text
className="font-mono text-[12px] text-status-error leading-4"
selectable
>
{errorText}
</Text>
</View>
)}
{children.map((child) => {
if (!child.toolData) return null;
return (
<ToolMessage
key={child.id}
toolName={child.toolData.toolName}
rawToolName={child.toolData.rawToolName}
kind={deriveToolKind(
child.toolData.rawToolName ?? child.toolData.toolName,
)}
status={child.toolData.status}
args={child.toolData.args}
result={child.toolData.result}
onOpenTask={onOpenTask}
/>
);
})}
</View>
)}
</View>
);
}
function formatElapsed(seconds: number): string {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return m > 0 ? `${m}m ${s}s` : `${s}s`;
}
function useElapsedTimer() {
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
setElapsed(0);
const interval = setInterval(() => {
setElapsed((e) => e + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return elapsed;
}
function ThinkingIndicator() {
const [dots, setDots] = useState(1);
const [activity, setActivity] = useState(getRandomThinkingActivity);
const elapsed = useElapsedTimer();
const themeColors = useThemeColors();
useEffect(() => {
const interval = setInterval(() => {
setDots((d) => (d % 3) + 1);
}, 500);
return () => clearInterval(interval);
}, []);
useEffect(() => {
const interval = setInterval(() => {
setActivity(getRandomThinkingActivity());
}, 2000);
return () => clearInterval(interval);
}, []);
return (
<View className="px-4 py-0.5">
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<Brain size={12} color={themeColors.gray[8]} />
<Text className="font-mono text-[12px] text-gray-8">
{activity}
{".".repeat(dots)}
</Text>
</View>
<Text className="font-mono text-[12px] text-gray-8">
{formatElapsed(elapsed)}
</Text>
</View>
</View>
);
}
function ConnectingIndicator() {
const [dots, setDots] = useState(1);
const elapsed = useElapsedTimer();
const themeColors = useThemeColors();
useEffect(() => {
const interval = setInterval(() => {
setDots((d) => (d % 3) + 1);
}, 500);
return () => clearInterval(interval);
}, []);
return (
<View className="px-4 py-0.5">
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<CloudArrowDown size={12} color={themeColors.gray[8]} />
<Text className="font-mono text-[12px] text-gray-8">
Connecting{".".repeat(dots)}
</Text>
</View>
<Text className="font-mono text-[12px] text-gray-8">
{formatElapsed(elapsed)}
</Text>
</View>
</View>
);
}
export function TaskSessionView({
events,
pendingPermissions,
isConnecting,
isThinking,
terminalStatus,
lastError,
onRetry,
onOpenTask,
onSendPermissionResponse,
model,
onModelChange,
contentContainerStyle,
optimisticUserMessage,
}: TaskSessionViewProps) {
const processorRef = useRef(createProcessorState());
const prevEventsRef = useRef(events);
// Reset processor when events array shrinks or changes identity completely
// (e.g., navigating between tasks while Expo Router reuses the component).
if (
events.length === 0 ||
(events !== prevEventsRef.current && events[0] !== prevEventsRef.current[0])
) {
processorRef.current = createProcessorState();
}
prevEventsRef.current = events;
const { messages, plan } = useMemo(
() => processNewEvents(processorRef.current, events),
[events],
);
// When the agent stops (cancel, completion, terminal), sweep any
// tools still stuck in pending/running to "completed" so their
// spinners stop.
const agentActive = isConnecting || isThinking;
const prevAgentActive = useRef(agentActive);
if (prevAgentActive.current && !agentActive) {
const state = processorRef.current;
let swept = false;
for (const msg of state.toolMessages.values()) {
const permission = msg.toolData
? pendingPermissions?.[msg.toolData.toolCallId]
: undefined;
if (
msg.toolData &&
(msg.toolData.status === "pending" ||
msg.toolData.status === "running") &&
!isInteractivePermissionTool(msg.toolData, permission)
) {
msg.toolData.status = "completed";
swept = true;
}
}
if (swept) {
state.lastSnapshot = [...state.messages];
state.lastSnapshotLength = state.messages.length;
}
}
prevAgentActive.current = agentActive;
// Append the optimistic user echo (if any) as the newest message, unless a
// real `user` message with matching text *and a ts at or after submit time*
// has already arrived via SSE. Gating on `ts` prevents a text-identical
// historical turn from suppressing a freshly-submitted echo.
const messagesWithOptimistic = useMemo(() => {
if (!optimisticUserMessage) return messages;
const alreadyEchoed = messages.some(
(m) =>
m.type === "user" &&
m.content === optimisticUserMessage.text &&
(m.ts ?? 0) >= optimisticUserMessage.setAt,
);
if (alreadyEchoed) return messages;
const optimistic: ParsedMessage = {
id: "optimistic-user",
type: "user",
content: optimisticUserMessage.text,
attachments: optimisticUserMessage.attachments,
};
return [...messages, optimistic];
}, [messages, optimisticUserMessage]);
// Inverted FlatList renders data[0] at the visual bottom.
// Reverse so newest messages are at index 0 = bottom.
const reversedMessages = useMemo(
() => [...messagesWithOptimistic].reverse(),
[messagesWithOptimistic],
);
const themeColors = useThemeColors();
const flatListRef = useRef<FlatList>(null);
const hasPendingQuestion = useMemo(
() => messages.some(hasPendingQuestionMessage),
[messages],
);
const showActivityIndicator = agentActive && !hasPendingQuestion;
const effectiveContentContainerStyle = useMemo(() => {
const baseStyle = (contentContainerStyle ?? {}) as {
paddingTop?: number;
[key: string]: unknown;
};
if (!showActivityIndicator) {
return baseStyle;
}
return {
...baseStyle,
// In the inverted list, paddingTop becomes visual bottom spacing.
// Reserve enough room so the floating activity indicator never
// covers the last visible row while the agent is working.
// 28pt was tight at default text sizes and let cards (e.g. the
// Agent loading card) peek into the indicator strip — 44pt gives
// a real buffer plus headroom for larger dynamic-type settings.
paddingTop: (baseStyle.paddingTop ?? 0) + 44,
};
}, [contentContainerStyle, showActivityIndicator]);
// Inverted FlatList: scrollY is the distance from the visual bottom, so
// any non-trivial value means the user has scrolled up from the latest
// message. Use a small threshold to ignore iOS bounce.
const [scrolledFromBottom, setScrolledFromBottom] = useState(false);
const scrollToBottom = useCallback(() => {
// Optimistically hide the button — the scroll animation will fire
// onScroll events too, but the throttle can leave the button visible
// for a beat after tap if we rely on those alone.
setScrolledFromBottom(false);
flatListRef.current?.scrollToOffset({ offset: 0, animated: true });
}, []);
const handleScroll = useCallback(
(e: { nativeEvent: { contentOffset: { y: number } } }) => {
setScrolledFromBottom(e.nativeEvent.contentOffset.y > 100);
},
[],
);
const renderMessage = useCallback(
({ item }: { item: ParsedMessage }) => {
switch (item.type) {
case "user":
return (
<HumanMessage
content={item.content}
timestamp={item.ts}
attachments={item.attachments}
/>
);
case "agent":
return (
<AgentMessage
content={item.content}
onOpenTask={onOpenTask}
timestamp={item.ts}
/>
);
case "thought":
return <CollapsedThought content={item.content} />;
case "tool":
if (!item.toolData) return null;
if (
isPlanApprovalTool(
item.toolData,
pendingPermissions?.[item.toolData.toolCallId],
)
) {
return (
<PlanApprovalCard
toolData={item.toolData}
permission={pendingPermissions?.[item.toolData.toolCallId]}
onSendPermissionResponse={onSendPermissionResponse}
model={model}
onModelChange={onModelChange}
/>
);
}
if (isQuestionTool(item.toolData)) {
return (
<QuestionCard
toolData={item.toolData}
onSendPermissionResponse={onSendPermissionResponse}
/>
);
}
if (item.toolData.isAgent) {
return <AgentToolCard item={item} onOpenTask={onOpenTask} />;
}
return (
<ToolMessage
toolName={item.toolData.toolName}
rawToolName={item.toolData.rawToolName}
kind={deriveToolKind(
item.toolData.rawToolName ?? item.toolData.toolName,
)}
status={item.toolData.status}
args={item.toolData.args}
result={item.toolData.result}
onOpenTask={onOpenTask}
/>
);