@comergehq/studio 0.1.25 → 0.1.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +881 -273
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +875 -267
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/components/chat/AgentProgressCard.tsx +82 -0
- package/src/components/chat/BundleProgressCard.tsx +75 -0
- package/src/components/chat/ChatMessageBubble.tsx +48 -4
- package/src/components/chat/ChatMessageList.tsx +56 -36
- package/src/components/chat/ChatPage.tsx +1 -1
- package/src/components/merge-requests/ReviewMergeRequestCard.tsx +1 -1
- package/src/components/overlays/EdgeGlowFrame.tsx +1 -1
- package/src/components/preview/PreviewStatusBadge.tsx +1 -1
- package/src/components/primitives/MarkdownText.tsx +50 -40
- package/src/data/agent-progress/repository.ts +179 -0
- package/src/data/agent-progress/types.ts +67 -0
- package/src/studio/ComergeStudio.tsx +16 -1
- package/src/studio/hooks/useAgentRunProgress.ts +357 -0
- package/src/studio/hooks/useBundleManager.ts +26 -4
- package/src/studio/ui/ChatPanel.tsx +13 -2
- package/src/studio/ui/RuntimeRenderer.tsx +6 -1
- package/src/studio/ui/StudioOverlay.tsx +3 -0
- package/src/studio/ui/preview-panel/PreviewMetaSection.tsx +1 -1
- package/src/theme/tokens.ts +8 -8
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { getSupabaseClient } from '../../core/services/supabase';
|
|
2
|
+
import { subscribeManagedChannel } from '../../core/services/supabase/realtimeManager';
|
|
3
|
+
import type { AgentRun, AgentRunEvent } from './types';
|
|
4
|
+
|
|
5
|
+
type DbAgentRunRow = {
|
|
6
|
+
id: string;
|
|
7
|
+
app_id: string;
|
|
8
|
+
thread_id: string;
|
|
9
|
+
queue_item_id: string | null;
|
|
10
|
+
status: AgentRun['status'];
|
|
11
|
+
current_phase: AgentRun['currentPhase'];
|
|
12
|
+
last_seq: number;
|
|
13
|
+
summary: Record<string, unknown> | null;
|
|
14
|
+
error_code: string | null;
|
|
15
|
+
error_message: string | null;
|
|
16
|
+
started_at: string;
|
|
17
|
+
finished_at: string | null;
|
|
18
|
+
created_at: string;
|
|
19
|
+
updated_at: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type DbAgentRunEventRow = {
|
|
23
|
+
id: string;
|
|
24
|
+
run_id: string;
|
|
25
|
+
app_id: string;
|
|
26
|
+
thread_id: string;
|
|
27
|
+
queue_item_id: string | null;
|
|
28
|
+
seq: number;
|
|
29
|
+
event_type: AgentRunEvent['eventType'];
|
|
30
|
+
phase: AgentRunEvent['phase'];
|
|
31
|
+
tool_name: string | null;
|
|
32
|
+
path: string | null;
|
|
33
|
+
payload: Record<string, unknown> | null;
|
|
34
|
+
created_at: string;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function mapRun(row: DbAgentRunRow): AgentRun {
|
|
38
|
+
return {
|
|
39
|
+
id: row.id,
|
|
40
|
+
appId: row.app_id,
|
|
41
|
+
threadId: row.thread_id,
|
|
42
|
+
queueItemId: row.queue_item_id,
|
|
43
|
+
status: row.status,
|
|
44
|
+
currentPhase: row.current_phase,
|
|
45
|
+
lastSeq: Number(row.last_seq || 0),
|
|
46
|
+
summary: (row.summary || {}) as Record<string, unknown>,
|
|
47
|
+
errorCode: row.error_code,
|
|
48
|
+
errorMessage: row.error_message,
|
|
49
|
+
startedAt: row.started_at,
|
|
50
|
+
finishedAt: row.finished_at,
|
|
51
|
+
createdAt: row.created_at,
|
|
52
|
+
updatedAt: row.updated_at,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function mapEvent(row: DbAgentRunEventRow): AgentRunEvent {
|
|
57
|
+
return {
|
|
58
|
+
id: row.id,
|
|
59
|
+
runId: row.run_id,
|
|
60
|
+
appId: row.app_id,
|
|
61
|
+
threadId: row.thread_id,
|
|
62
|
+
queueItemId: row.queue_item_id,
|
|
63
|
+
seq: Number(row.seq || 0),
|
|
64
|
+
eventType: row.event_type,
|
|
65
|
+
phase: row.phase,
|
|
66
|
+
toolName: row.tool_name,
|
|
67
|
+
path: row.path,
|
|
68
|
+
payload: (row.payload || {}) as Record<string, unknown>,
|
|
69
|
+
createdAt: row.created_at,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface AgentProgressRepository {
|
|
74
|
+
getLatestRun(threadId: string): Promise<AgentRun | null>;
|
|
75
|
+
listEvents(runId: string, afterSeq?: number): Promise<AgentRunEvent[]>;
|
|
76
|
+
subscribeThreadRuns(
|
|
77
|
+
threadId: string,
|
|
78
|
+
handlers: {
|
|
79
|
+
onInsert?: (run: AgentRun) => void;
|
|
80
|
+
onUpdate?: (run: AgentRun) => void;
|
|
81
|
+
}
|
|
82
|
+
): () => void;
|
|
83
|
+
subscribeRunEvents(
|
|
84
|
+
runId: string,
|
|
85
|
+
handlers: {
|
|
86
|
+
onInsert?: (event: AgentRunEvent) => void;
|
|
87
|
+
onUpdate?: (event: AgentRunEvent) => void;
|
|
88
|
+
}
|
|
89
|
+
): () => void;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
class AgentProgressRepositoryImpl implements AgentProgressRepository {
|
|
93
|
+
async getLatestRun(threadId: string): Promise<AgentRun | null> {
|
|
94
|
+
if (!threadId) return null;
|
|
95
|
+
const supabase = getSupabaseClient();
|
|
96
|
+
const { data, error } = await (supabase as any)
|
|
97
|
+
.from('agent_run')
|
|
98
|
+
.select('*')
|
|
99
|
+
.eq('thread_id', threadId)
|
|
100
|
+
.order('started_at', { ascending: false })
|
|
101
|
+
.limit(1)
|
|
102
|
+
.maybeSingle();
|
|
103
|
+
if (error) throw new Error(error.message || 'Failed to fetch latest agent run');
|
|
104
|
+
if (!data) return null;
|
|
105
|
+
return mapRun(data as DbAgentRunRow);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async listEvents(runId: string, afterSeq?: number): Promise<AgentRunEvent[]> {
|
|
109
|
+
if (!runId) return [];
|
|
110
|
+
const supabase = getSupabaseClient();
|
|
111
|
+
let query = (supabase as any).from('agent_run_event').select('*').eq('run_id', runId).order('seq', { ascending: true });
|
|
112
|
+
if (typeof afterSeq === 'number' && Number.isFinite(afterSeq) && afterSeq > 0) {
|
|
113
|
+
query = query.gt('seq', afterSeq);
|
|
114
|
+
}
|
|
115
|
+
const { data, error } = await query;
|
|
116
|
+
if (error) throw new Error(error.message || 'Failed to fetch agent run events');
|
|
117
|
+
const rows = Array.isArray(data) ? (data as DbAgentRunEventRow[]) : [];
|
|
118
|
+
return rows.map(mapEvent);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
subscribeThreadRuns(
|
|
122
|
+
threadId: string,
|
|
123
|
+
handlers: {
|
|
124
|
+
onInsert?: (run: AgentRun) => void;
|
|
125
|
+
onUpdate?: (run: AgentRun) => void;
|
|
126
|
+
}
|
|
127
|
+
): () => void {
|
|
128
|
+
return subscribeManagedChannel(`agent-progress:runs:thread:${threadId}`, (channel) => {
|
|
129
|
+
channel
|
|
130
|
+
.on(
|
|
131
|
+
'postgres_changes',
|
|
132
|
+
{ event: 'INSERT', schema: 'public', table: 'agent_run', filter: `thread_id=eq.${threadId}` },
|
|
133
|
+
(payload) => {
|
|
134
|
+
const row = payload.new as DbAgentRunRow;
|
|
135
|
+
handlers.onInsert?.(mapRun(row));
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
.on(
|
|
139
|
+
'postgres_changes',
|
|
140
|
+
{ event: 'UPDATE', schema: 'public', table: 'agent_run', filter: `thread_id=eq.${threadId}` },
|
|
141
|
+
(payload) => {
|
|
142
|
+
const row = payload.new as DbAgentRunRow;
|
|
143
|
+
handlers.onUpdate?.(mapRun(row));
|
|
144
|
+
}
|
|
145
|
+
);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
subscribeRunEvents(
|
|
150
|
+
runId: string,
|
|
151
|
+
handlers: {
|
|
152
|
+
onInsert?: (event: AgentRunEvent) => void;
|
|
153
|
+
onUpdate?: (event: AgentRunEvent) => void;
|
|
154
|
+
}
|
|
155
|
+
): () => void {
|
|
156
|
+
return subscribeManagedChannel(`agent-progress:events:run:${runId}`, (channel) => {
|
|
157
|
+
channel
|
|
158
|
+
.on(
|
|
159
|
+
'postgres_changes',
|
|
160
|
+
{ event: 'INSERT', schema: 'public', table: 'agent_run_event', filter: `run_id=eq.${runId}` },
|
|
161
|
+
(payload) => {
|
|
162
|
+
const row = payload.new as DbAgentRunEventRow;
|
|
163
|
+
handlers.onInsert?.(mapEvent(row));
|
|
164
|
+
}
|
|
165
|
+
)
|
|
166
|
+
.on(
|
|
167
|
+
'postgres_changes',
|
|
168
|
+
{ event: 'UPDATE', schema: 'public', table: 'agent_run_event', filter: `run_id=eq.${runId}` },
|
|
169
|
+
(payload) => {
|
|
170
|
+
const row = payload.new as DbAgentRunEventRow;
|
|
171
|
+
handlers.onUpdate?.(mapEvent(row));
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export const agentProgressRepository: AgentProgressRepository = new AgentProgressRepositoryImpl();
|
|
179
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export type AgentRunStatus = 'running' | 'succeeded' | 'failed' | 'cancelled';
|
|
2
|
+
|
|
3
|
+
export type AgentProgressPhase =
|
|
4
|
+
| 'planning'
|
|
5
|
+
| 'reasoning'
|
|
6
|
+
| 'analyzing'
|
|
7
|
+
| 'editing'
|
|
8
|
+
| 'executing'
|
|
9
|
+
| 'working'
|
|
10
|
+
| 'validating'
|
|
11
|
+
| 'finalizing';
|
|
12
|
+
|
|
13
|
+
export type AgentRunEventType =
|
|
14
|
+
| 'run_started'
|
|
15
|
+
| 'phase_changed'
|
|
16
|
+
| 'step_started'
|
|
17
|
+
| 'file_changed'
|
|
18
|
+
| 'todo_updated'
|
|
19
|
+
| 'run_completed'
|
|
20
|
+
| 'run_failed'
|
|
21
|
+
| 'run_cancelled';
|
|
22
|
+
|
|
23
|
+
export type AgentRun = {
|
|
24
|
+
id: string;
|
|
25
|
+
appId: string;
|
|
26
|
+
threadId: string;
|
|
27
|
+
queueItemId: string | null;
|
|
28
|
+
status: AgentRunStatus;
|
|
29
|
+
currentPhase: AgentProgressPhase | null;
|
|
30
|
+
lastSeq: number;
|
|
31
|
+
summary: Record<string, unknown>;
|
|
32
|
+
errorCode: string | null;
|
|
33
|
+
errorMessage: string | null;
|
|
34
|
+
startedAt: string;
|
|
35
|
+
finishedAt: string | null;
|
|
36
|
+
createdAt: string;
|
|
37
|
+
updatedAt: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type AgentRunEvent = {
|
|
41
|
+
id: string;
|
|
42
|
+
runId: string;
|
|
43
|
+
appId: string;
|
|
44
|
+
threadId: string;
|
|
45
|
+
queueItemId: string | null;
|
|
46
|
+
seq: number;
|
|
47
|
+
eventType: AgentRunEventType;
|
|
48
|
+
phase: AgentProgressPhase | null;
|
|
49
|
+
toolName: string | null;
|
|
50
|
+
path: string | null;
|
|
51
|
+
payload: Record<string, unknown>;
|
|
52
|
+
createdAt: string;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export type AgentTodoSummary = {
|
|
56
|
+
total: number;
|
|
57
|
+
pending: number;
|
|
58
|
+
inProgress: number;
|
|
59
|
+
completed: number;
|
|
60
|
+
currentTask: string | null;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export type AgentProgressSnapshot = {
|
|
64
|
+
run: AgentRun | null;
|
|
65
|
+
events: AgentRunEvent[];
|
|
66
|
+
};
|
|
67
|
+
|
|
@@ -16,6 +16,7 @@ import { StudioOverlay } from './ui/StudioOverlay';
|
|
|
16
16
|
import { LiquidGlassResetProvider } from '../components/utils/liquidGlassReset';
|
|
17
17
|
import { useEditQueue } from './hooks/useEditQueue';
|
|
18
18
|
import { useEditQueueActions } from './hooks/useEditQueueActions';
|
|
19
|
+
import { useAgentRunProgress } from './hooks/useAgentRunProgress';
|
|
19
20
|
import { appsRepository } from '../data/apps/repository';
|
|
20
21
|
import type { SyncUpstreamStatus } from '../data/apps/types';
|
|
21
22
|
|
|
@@ -26,6 +27,7 @@ export type ComergeStudioProps = {
|
|
|
26
27
|
onNavigateHome?: () => void;
|
|
27
28
|
style?: ViewStyle;
|
|
28
29
|
showBubble?: boolean;
|
|
30
|
+
enableAgentProgress?: boolean;
|
|
29
31
|
studioControlOptions?: import('@comergehq/studio-control').StudioControlOptions;
|
|
30
32
|
embeddedBaseBundles?: EmbeddedBaseBundles;
|
|
31
33
|
};
|
|
@@ -37,6 +39,7 @@ export function ComergeStudio({
|
|
|
37
39
|
onNavigateHome,
|
|
38
40
|
style,
|
|
39
41
|
showBubble = true,
|
|
42
|
+
enableAgentProgress = true,
|
|
40
43
|
studioControlOptions,
|
|
41
44
|
embeddedBaseBundles,
|
|
42
45
|
}: ComergeStudioProps) {
|
|
@@ -72,6 +75,7 @@ export function ComergeStudio({
|
|
|
72
75
|
captureTargetRef={captureTargetRef}
|
|
73
76
|
style={style}
|
|
74
77
|
showBubble={showBubble}
|
|
78
|
+
enableAgentProgress={enableAgentProgress}
|
|
75
79
|
studioControlOptions={studioControlOptions}
|
|
76
80
|
embeddedBaseBundles={embeddedBaseBundles}
|
|
77
81
|
/>
|
|
@@ -96,6 +100,7 @@ type InnerProps = {
|
|
|
96
100
|
captureTargetRef: React.RefObject<View | null>;
|
|
97
101
|
style?: ViewStyle;
|
|
98
102
|
showBubble: boolean;
|
|
103
|
+
enableAgentProgress: boolean;
|
|
99
104
|
studioControlOptions?: import('@comergehq/studio-control').StudioControlOptions;
|
|
100
105
|
embeddedBaseBundles?: EmbeddedBaseBundles;
|
|
101
106
|
};
|
|
@@ -114,6 +119,7 @@ function ComergeStudioInner({
|
|
|
114
119
|
captureTargetRef,
|
|
115
120
|
style,
|
|
116
121
|
showBubble,
|
|
122
|
+
enableAgentProgress,
|
|
117
123
|
studioControlOptions,
|
|
118
124
|
embeddedBaseBundles,
|
|
119
125
|
}: InnerProps) {
|
|
@@ -179,6 +185,7 @@ function ComergeStudioInner({
|
|
|
179
185
|
const threadId = app?.threadId ?? '';
|
|
180
186
|
const thread = useThreadMessages(threadId);
|
|
181
187
|
const editQueue = useEditQueue(activeAppId);
|
|
188
|
+
const agentProgress = useAgentRunProgress(threadId, { enabled: enableAgentProgress });
|
|
182
189
|
const editQueueActions = useEditQueueActions(activeAppId);
|
|
183
190
|
const [lastEditQueueInfo, setLastEditQueueInfo] = React.useState<{
|
|
184
191
|
queueItemId?: string | null;
|
|
@@ -251,14 +258,20 @@ function ComergeStudioInner({
|
|
|
251
258
|
const [upstreamSyncStatus, setUpstreamSyncStatus] = React.useState<SyncUpstreamStatus | null>(null);
|
|
252
259
|
const isMrTestBuildInProgress = bundle.loading && bundle.loadingMode === 'test';
|
|
253
260
|
const isBaseBundleDownloading = bundle.loading && bundle.loadingMode === 'base' && !bundle.isTesting;
|
|
261
|
+
const runtimePreparingText =
|
|
262
|
+
bundle.bundleStatus === 'pending'
|
|
263
|
+
? 'Bundling app… this may take a few minutes'
|
|
264
|
+
: 'Preparing app…';
|
|
254
265
|
|
|
255
266
|
// Show typing dots when the last message isn't an outcome (agent still working).
|
|
256
267
|
const chatShowTypingIndicator = React.useMemo(() => {
|
|
268
|
+
if (agentProgress.hasLiveProgress) return false;
|
|
257
269
|
if (!thread.raw || thread.raw.length === 0) return false;
|
|
258
270
|
const last = thread.raw[thread.raw.length - 1];
|
|
259
271
|
const payloadType = typeof (last.payload as any)?.type === 'string' ? String((last.payload as any).type) : undefined;
|
|
260
272
|
return payloadType !== 'outcome';
|
|
261
|
-
}, [thread.raw]);
|
|
273
|
+
}, [agentProgress.hasLiveProgress, thread.raw]);
|
|
274
|
+
const showChatProgress = agentProgress.hasLiveProgress || Boolean(agentProgress.view.bundle?.active);
|
|
262
275
|
|
|
263
276
|
React.useEffect(() => {
|
|
264
277
|
updateLastEditQueueInfo(null);
|
|
@@ -311,6 +324,7 @@ function ComergeStudioInner({
|
|
|
311
324
|
<RuntimeRenderer
|
|
312
325
|
appKey={appKey}
|
|
313
326
|
bundlePath={bundle.bundlePath}
|
|
327
|
+
preparingText={runtimePreparingText}
|
|
314
328
|
forcePreparing={showPostEditPreparing}
|
|
315
329
|
renderToken={bundle.renderToken}
|
|
316
330
|
allowInitialPreparing={!embeddedBaseBundles}
|
|
@@ -377,6 +391,7 @@ function ComergeStudioInner({
|
|
|
377
391
|
onSendChat={(text, attachments) => actions.sendEdit({ prompt: text, attachments })}
|
|
378
392
|
chatQueueItems={chatQueueItems}
|
|
379
393
|
onRemoveQueueItem={(id) => editQueueActions.cancel(id)}
|
|
394
|
+
chatProgress={showChatProgress ? agentProgress.view : null}
|
|
380
395
|
onNavigateHome={onNavigateHome}
|
|
381
396
|
showBubble={showBubble}
|
|
382
397
|
studioControlOptions={studioControlOptions}
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
|
|
3
|
+
import { agentProgressRepository } from '../../data/agent-progress/repository';
|
|
4
|
+
import type { AgentProgressPhase, AgentRun, AgentRunEvent, AgentTodoSummary } from '../../data/agent-progress/types';
|
|
5
|
+
import { useForegroundSignal } from './useForegroundSignal';
|
|
6
|
+
|
|
7
|
+
type BundleStage = 'queued' | 'building' | 'fixing' | 'retrying' | 'finalizing' | 'ready' | 'failed';
|
|
8
|
+
|
|
9
|
+
export type AgentBundleProgressView = {
|
|
10
|
+
active: boolean;
|
|
11
|
+
status: 'loading' | 'succeeded' | 'failed';
|
|
12
|
+
phaseLabel: string;
|
|
13
|
+
progressValue: number;
|
|
14
|
+
errorMessage: string | null;
|
|
15
|
+
platform: 'ios' | 'android' | 'both';
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type AgentRunProgressView = {
|
|
19
|
+
runId: string | null;
|
|
20
|
+
status: AgentRun['status'] | null;
|
|
21
|
+
phase: AgentProgressPhase | null;
|
|
22
|
+
latestMessage: string | null;
|
|
23
|
+
changedFilesCount: number;
|
|
24
|
+
recentFiles: string[];
|
|
25
|
+
todoSummary: AgentTodoSummary | null;
|
|
26
|
+
bundle: AgentBundleProgressView | null;
|
|
27
|
+
events: AgentRunEvent[];
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export type UseAgentRunProgressResult = {
|
|
31
|
+
run: AgentRun | null;
|
|
32
|
+
view: AgentRunProgressView;
|
|
33
|
+
loading: boolean;
|
|
34
|
+
error: Error | null;
|
|
35
|
+
hasLiveProgress: boolean;
|
|
36
|
+
refetch: () => Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function upsertBySeq(prev: AgentRunEvent[], next: AgentRunEvent): AgentRunEvent[] {
|
|
40
|
+
const map = new Map<number, AgentRunEvent>();
|
|
41
|
+
for (const item of prev) map.set(item.seq, item);
|
|
42
|
+
map.set(next.seq, next);
|
|
43
|
+
return Array.from(map.values()).sort((a, b) => a.seq - b.seq);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function mergeMany(prev: AgentRunEvent[], incoming: AgentRunEvent[]): AgentRunEvent[] {
|
|
47
|
+
if (incoming.length === 0) return prev;
|
|
48
|
+
const map = new Map<number, AgentRunEvent>();
|
|
49
|
+
for (const item of prev) map.set(item.seq, item);
|
|
50
|
+
for (const item of incoming) map.set(item.seq, item);
|
|
51
|
+
return Array.from(map.values()).sort((a, b) => a.seq - b.seq);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function toMs(v: string | null | undefined): number {
|
|
55
|
+
if (!v) return 0;
|
|
56
|
+
const n = Date.parse(v);
|
|
57
|
+
return Number.isFinite(n) ? n : 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function shouldSwitchRun(current: AgentRun | null, candidate: AgentRun): boolean {
|
|
61
|
+
if (!current) return true;
|
|
62
|
+
if (candidate.id === current.id) return true;
|
|
63
|
+
return toMs(candidate.startedAt) >= toMs(current.startedAt);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function toInt(value: unknown): number {
|
|
67
|
+
const n = Number(value);
|
|
68
|
+
return Number.isFinite(n) ? n : 0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function toBundleStage(value: unknown): BundleStage | null {
|
|
72
|
+
if (value === 'queued') return 'queued';
|
|
73
|
+
if (value === 'building') return 'building';
|
|
74
|
+
if (value === 'fixing') return 'fixing';
|
|
75
|
+
if (value === 'retrying') return 'retrying';
|
|
76
|
+
if (value === 'finalizing') return 'finalizing';
|
|
77
|
+
if (value === 'ready') return 'ready';
|
|
78
|
+
if (value === 'failed') return 'failed';
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function toBundlePlatform(value: unknown): 'ios' | 'android' | 'both' {
|
|
83
|
+
if (value === 'ios' || value === 'android') return value;
|
|
84
|
+
return 'both';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function clamp01(value: number): number {
|
|
88
|
+
if (value <= 0) return 0;
|
|
89
|
+
if (value >= 1) return 1;
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function defaultBundleLabel(stage: BundleStage): string {
|
|
94
|
+
if (stage === 'queued') return 'Queued for build';
|
|
95
|
+
if (stage === 'building') return 'Building bundle';
|
|
96
|
+
if (stage === 'fixing') return 'Applying auto-fix';
|
|
97
|
+
if (stage === 'retrying') return 'Retrying bundle';
|
|
98
|
+
if (stage === 'finalizing') return 'Finalizing artifacts';
|
|
99
|
+
if (stage === 'ready') return 'Bundle ready';
|
|
100
|
+
if (stage === 'failed') return 'Bundle failed';
|
|
101
|
+
return 'Building bundle';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function fallbackBundleProgress(stage: BundleStage, startedAtMs: number, nowMs: number): number {
|
|
105
|
+
if (stage === 'ready') return 1;
|
|
106
|
+
if (stage === 'failed') return 0.96;
|
|
107
|
+
const elapsed = Math.max(0, nowMs - startedAtMs);
|
|
108
|
+
const expectedMs = 60_000;
|
|
109
|
+
if (elapsed <= expectedMs) {
|
|
110
|
+
const t = clamp01(elapsed / expectedMs);
|
|
111
|
+
return 0.05 + 0.85 * (1 - Math.pow(1 - t, 2));
|
|
112
|
+
}
|
|
113
|
+
const over = elapsed - expectedMs;
|
|
114
|
+
return Math.min(0.9 + 0.07 * (1 - Math.exp(-over / 25_000)), 0.97);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function deriveView(run: AgentRun | null, events: AgentRunEvent[], nowMs: number): AgentRunProgressView {
|
|
118
|
+
const files: string[] = [];
|
|
119
|
+
const fileSeen = new Set<string>();
|
|
120
|
+
let todoSummary: AgentTodoSummary | null = null;
|
|
121
|
+
let latestMessage: string | null = null;
|
|
122
|
+
let phase = run?.currentPhase ?? null;
|
|
123
|
+
let bundleStage: BundleStage | null = null;
|
|
124
|
+
let bundleLabel: string | null = null;
|
|
125
|
+
let bundleError: string | null = null;
|
|
126
|
+
let bundleProgressHint: number | null = null;
|
|
127
|
+
let bundlePlatform: 'ios' | 'android' | 'both' = 'both';
|
|
128
|
+
let bundleStartedAtMs: number | null = null;
|
|
129
|
+
let lastBundleSig: string | null = null;
|
|
130
|
+
|
|
131
|
+
for (const ev of events) {
|
|
132
|
+
if (ev.eventType === 'phase_changed') {
|
|
133
|
+
if (typeof ev.payload?.message === 'string') latestMessage = ev.payload.message;
|
|
134
|
+
if (ev.phase) phase = ev.phase;
|
|
135
|
+
}
|
|
136
|
+
if (ev.eventType === 'file_changed') {
|
|
137
|
+
if (ev.path && !fileSeen.has(ev.path)) {
|
|
138
|
+
fileSeen.add(ev.path);
|
|
139
|
+
files.push(ev.path);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (ev.eventType === 'todo_updated') {
|
|
143
|
+
todoSummary = {
|
|
144
|
+
total: toInt(ev.payload?.total),
|
|
145
|
+
pending: toInt(ev.payload?.pending),
|
|
146
|
+
inProgress: toInt(ev.payload?.inProgress),
|
|
147
|
+
completed: toInt(ev.payload?.completed),
|
|
148
|
+
currentTask: typeof ev.payload?.currentTask === 'string' ? ev.payload.currentTask : null,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const stageType = typeof ev.payload?.stage === 'string' ? ev.payload.stage : null;
|
|
153
|
+
if (stageType !== 'bundle') continue;
|
|
154
|
+
const nextStage = toBundleStage(ev.payload?.bundlePhase);
|
|
155
|
+
if (!nextStage) continue;
|
|
156
|
+
const nextPlatform = toBundlePlatform(ev.payload?.platform);
|
|
157
|
+
const message = typeof ev.payload?.message === 'string' ? ev.payload.message : null;
|
|
158
|
+
const phaseLabel = message || (typeof ev.payload?.message === 'string' ? ev.payload.message : null);
|
|
159
|
+
const hintRaw = Number(ev.payload?.progressHint);
|
|
160
|
+
const progressHint = Number.isFinite(hintRaw) ? clamp01(hintRaw) : null;
|
|
161
|
+
const errorText = typeof ev.payload?.error === 'string' ? ev.payload.error : null;
|
|
162
|
+
const sig = `${ev.seq}:${nextStage}:${nextPlatform}:${progressHint ?? 'none'}:${phaseLabel ?? 'none'}:${errorText ?? 'none'}`;
|
|
163
|
+
if (sig === lastBundleSig) continue;
|
|
164
|
+
lastBundleSig = sig;
|
|
165
|
+
bundleStage = nextStage;
|
|
166
|
+
bundlePlatform = nextPlatform;
|
|
167
|
+
if (phaseLabel) bundleLabel = phaseLabel;
|
|
168
|
+
if (progressHint != null) bundleProgressHint = progressHint;
|
|
169
|
+
if (errorText) bundleError = errorText;
|
|
170
|
+
const evMs = toMs(ev.createdAt);
|
|
171
|
+
if (!bundleStartedAtMs && evMs > 0) bundleStartedAtMs = evMs;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (!latestMessage) {
|
|
175
|
+
if (phase === 'planning') latestMessage = 'Planning changes...';
|
|
176
|
+
else if (phase === 'analyzing') latestMessage = 'Analyzing relevant files...';
|
|
177
|
+
else if (phase === 'editing') latestMessage = 'Applying code updates...';
|
|
178
|
+
else if (phase === 'validating') latestMessage = 'Validating updates...';
|
|
179
|
+
else if (phase === 'finalizing') latestMessage = 'Finalizing response...';
|
|
180
|
+
else if (phase) latestMessage = `Working (${phase})...`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const runFinished = run?.status === 'succeeded' || run?.status === 'failed' || run?.status === 'cancelled';
|
|
184
|
+
let bundle: AgentBundleProgressView | null = null;
|
|
185
|
+
if (bundleStage && !runFinished) {
|
|
186
|
+
const baseTime = bundleStartedAtMs ?? toMs(run?.startedAt) ?? nowMs;
|
|
187
|
+
const fallback = fallbackBundleProgress(bundleStage, baseTime || nowMs, nowMs);
|
|
188
|
+
const value = bundleProgressHint != null ? Math.max(fallback, bundleProgressHint) : fallback;
|
|
189
|
+
const status = bundleStage === 'failed' ? 'failed' : bundleStage === 'ready' ? 'succeeded' : 'loading';
|
|
190
|
+
bundle = {
|
|
191
|
+
active: status === 'loading',
|
|
192
|
+
status,
|
|
193
|
+
phaseLabel: bundleLabel || defaultBundleLabel(bundleStage),
|
|
194
|
+
progressValue: clamp01(value),
|
|
195
|
+
errorMessage: bundleError,
|
|
196
|
+
platform: bundlePlatform,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
runId: run?.id ?? null,
|
|
202
|
+
status: run?.status ?? null,
|
|
203
|
+
phase,
|
|
204
|
+
latestMessage,
|
|
205
|
+
changedFilesCount: fileSeen.size,
|
|
206
|
+
recentFiles: files.slice(-5),
|
|
207
|
+
todoSummary,
|
|
208
|
+
bundle,
|
|
209
|
+
events,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function useAgentRunProgress(threadId: string, opts?: { enabled?: boolean }): UseAgentRunProgressResult {
|
|
214
|
+
const enabled = Boolean(opts?.enabled ?? true);
|
|
215
|
+
const [run, setRun] = React.useState<AgentRun | null>(null);
|
|
216
|
+
const [events, setEvents] = React.useState<AgentRunEvent[]>([]);
|
|
217
|
+
const [loading, setLoading] = React.useState(false);
|
|
218
|
+
const [error, setError] = React.useState<Error | null>(null);
|
|
219
|
+
const activeRequestIdRef = React.useRef(0);
|
|
220
|
+
const lastSeqRef = React.useRef(0);
|
|
221
|
+
const runRef = React.useRef<AgentRun | null>(null);
|
|
222
|
+
const foregroundSignal = useForegroundSignal(Boolean(threadId) && enabled);
|
|
223
|
+
const [bundleTick, setBundleTick] = React.useState(0);
|
|
224
|
+
|
|
225
|
+
React.useEffect(() => {
|
|
226
|
+
lastSeqRef.current = 0;
|
|
227
|
+
runRef.current = null;
|
|
228
|
+
}, [threadId]);
|
|
229
|
+
|
|
230
|
+
React.useEffect(() => {
|
|
231
|
+
runRef.current = run;
|
|
232
|
+
}, [run]);
|
|
233
|
+
|
|
234
|
+
const refetch = React.useCallback(async () => {
|
|
235
|
+
if (!threadId || !enabled) {
|
|
236
|
+
setRun(null);
|
|
237
|
+
setEvents([]);
|
|
238
|
+
setLoading(false);
|
|
239
|
+
setError(null);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const requestId = ++activeRequestIdRef.current;
|
|
243
|
+
setLoading(true);
|
|
244
|
+
setError(null);
|
|
245
|
+
try {
|
|
246
|
+
const latestRun = await agentProgressRepository.getLatestRun(threadId);
|
|
247
|
+
if (activeRequestIdRef.current !== requestId) return;
|
|
248
|
+
if (!latestRun) {
|
|
249
|
+
setRun(null);
|
|
250
|
+
setEvents([]);
|
|
251
|
+
lastSeqRef.current = 0;
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const initialEvents = await agentProgressRepository.listEvents(latestRun.id);
|
|
255
|
+
if (activeRequestIdRef.current !== requestId) return;
|
|
256
|
+
const sorted = [...initialEvents].sort((a, b) => a.seq - b.seq);
|
|
257
|
+
setRun(latestRun);
|
|
258
|
+
setEvents(sorted);
|
|
259
|
+
lastSeqRef.current = sorted.length > 0 ? sorted[sorted.length - 1]!.seq : 0;
|
|
260
|
+
} catch (e) {
|
|
261
|
+
if (activeRequestIdRef.current !== requestId) return;
|
|
262
|
+
setError(e instanceof Error ? e : new Error(String(e)));
|
|
263
|
+
setRun(null);
|
|
264
|
+
setEvents([]);
|
|
265
|
+
lastSeqRef.current = 0;
|
|
266
|
+
} finally {
|
|
267
|
+
if (activeRequestIdRef.current === requestId) setLoading(false);
|
|
268
|
+
}
|
|
269
|
+
}, [enabled, threadId]);
|
|
270
|
+
|
|
271
|
+
React.useEffect(() => {
|
|
272
|
+
void refetch();
|
|
273
|
+
}, [refetch]);
|
|
274
|
+
|
|
275
|
+
React.useEffect(() => {
|
|
276
|
+
if (!threadId || !enabled) return;
|
|
277
|
+
if (foregroundSignal <= 0) return;
|
|
278
|
+
void refetch();
|
|
279
|
+
}, [enabled, foregroundSignal, refetch, threadId]);
|
|
280
|
+
|
|
281
|
+
React.useEffect(() => {
|
|
282
|
+
if (!threadId || !enabled) return;
|
|
283
|
+
const unsubRuns = agentProgressRepository.subscribeThreadRuns(threadId, {
|
|
284
|
+
onInsert: (nextRun) => {
|
|
285
|
+
const currentRun = runRef.current;
|
|
286
|
+
if (!shouldSwitchRun(currentRun, nextRun)) return;
|
|
287
|
+
setRun(nextRun);
|
|
288
|
+
runRef.current = nextRun;
|
|
289
|
+
if (!currentRun || currentRun.id !== nextRun.id) {
|
|
290
|
+
lastSeqRef.current = 0;
|
|
291
|
+
setEvents([]);
|
|
292
|
+
void agentProgressRepository
|
|
293
|
+
.listEvents(nextRun.id)
|
|
294
|
+
.then((initial) => {
|
|
295
|
+
if (runRef.current?.id !== nextRun.id) return;
|
|
296
|
+
setEvents((prev) => mergeMany(prev, initial));
|
|
297
|
+
const maxSeq = initial.length > 0 ? initial[initial.length - 1]!.seq : 0;
|
|
298
|
+
if (maxSeq > lastSeqRef.current) lastSeqRef.current = maxSeq;
|
|
299
|
+
})
|
|
300
|
+
.catch(() => {});
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
onUpdate: (nextRun) => {
|
|
304
|
+
const currentRun = runRef.current;
|
|
305
|
+
if (!shouldSwitchRun(currentRun, nextRun)) return;
|
|
306
|
+
setRun(nextRun);
|
|
307
|
+
runRef.current = nextRun;
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
return unsubRuns;
|
|
311
|
+
}, [enabled, threadId, foregroundSignal]);
|
|
312
|
+
|
|
313
|
+
React.useEffect(() => {
|
|
314
|
+
if (!enabled || !run?.id) return;
|
|
315
|
+
const runId = run.id;
|
|
316
|
+
const processIncoming = (incoming: AgentRunEvent) => {
|
|
317
|
+
if (runRef.current?.id !== runId) return;
|
|
318
|
+
setEvents((prev) => upsertBySeq(prev, incoming));
|
|
319
|
+
if (incoming.seq > lastSeqRef.current) {
|
|
320
|
+
const expectedNext = lastSeqRef.current + 1;
|
|
321
|
+
const seenSeq = incoming.seq;
|
|
322
|
+
const currentLast = lastSeqRef.current;
|
|
323
|
+
lastSeqRef.current = seenSeq;
|
|
324
|
+
if (seenSeq > expectedNext) {
|
|
325
|
+
void agentProgressRepository
|
|
326
|
+
.listEvents(runId, currentLast)
|
|
327
|
+
.then((missing) => {
|
|
328
|
+
if (runRef.current?.id !== runId) return;
|
|
329
|
+
setEvents((prev) => mergeMany(prev, missing));
|
|
330
|
+
if (missing.length > 0) {
|
|
331
|
+
const maxSeq = missing[missing.length - 1]!.seq;
|
|
332
|
+
if (maxSeq > lastSeqRef.current) lastSeqRef.current = maxSeq;
|
|
333
|
+
}
|
|
334
|
+
})
|
|
335
|
+
.catch(() => {});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
const unsubscribe = agentProgressRepository.subscribeRunEvents(runId, {
|
|
340
|
+
onInsert: processIncoming,
|
|
341
|
+
onUpdate: processIncoming,
|
|
342
|
+
});
|
|
343
|
+
return unsubscribe;
|
|
344
|
+
}, [enabled, run?.id, foregroundSignal]);
|
|
345
|
+
|
|
346
|
+
const view = React.useMemo(() => deriveView(run, events, Date.now()), [bundleTick, events, run]);
|
|
347
|
+
React.useEffect(() => {
|
|
348
|
+
if (!view.bundle?.active) return;
|
|
349
|
+
const interval = setInterval(() => {
|
|
350
|
+
setBundleTick((v) => v + 1);
|
|
351
|
+
}, 300);
|
|
352
|
+
return () => clearInterval(interval);
|
|
353
|
+
}, [view.bundle?.active]);
|
|
354
|
+
const hasLiveProgress = Boolean(run) && run?.status === 'running';
|
|
355
|
+
return { run, view, loading, error, hasLiveProgress, refetch };
|
|
356
|
+
}
|
|
357
|
+
|