forked from winfunc/opcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutputCache.tsx
More file actions
195 lines (169 loc) · 5.64 KB
/
outputCache.tsx
File metadata and controls
195 lines (169 loc) · 5.64 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
import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { api } from './api';
// Use the same message interface as AgentExecution for consistency
export interface ClaudeStreamMessage {
type: "system" | "assistant" | "user" | "result";
subtype?: string;
message?: {
content?: any[];
usage?: {
input_tokens: number;
output_tokens: number;
};
};
usage?: {
input_tokens: number;
output_tokens: number;
};
[key: string]: any;
}
interface CachedSessionOutput {
output: string;
messages: ClaudeStreamMessage[];
lastUpdated: number;
status: string;
}
interface OutputCacheContextType {
getCachedOutput: (sessionId: number) => CachedSessionOutput | null;
setCachedOutput: (sessionId: number, data: CachedSessionOutput) => void;
updateSessionStatus: (sessionId: number, status: string) => void;
clearCache: (sessionId?: number) => void;
isPolling: boolean;
startBackgroundPolling: () => void;
stopBackgroundPolling: () => void;
}
const OutputCacheContext = createContext<OutputCacheContextType | null>(null);
export function useOutputCache() {
const context = useContext(OutputCacheContext);
if (!context) {
throw new Error('useOutputCache must be used within an OutputCacheProvider');
}
return context;
}
interface OutputCacheProviderProps {
children: React.ReactNode;
}
export function OutputCacheProvider({ children }: OutputCacheProviderProps) {
const [cache, setCache] = useState<Map<number, CachedSessionOutput>>(new Map());
const [isPolling, setIsPolling] = useState(false);
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(null);
const getCachedOutput = useCallback((sessionId: number): CachedSessionOutput | null => {
return cache.get(sessionId) || null;
}, [cache]);
const setCachedOutput = useCallback((sessionId: number, data: CachedSessionOutput) => {
setCache(prev => new Map(prev.set(sessionId, data)));
}, []);
const updateSessionStatus = useCallback((sessionId: number, status: string) => {
setCache(prev => {
const existing = prev.get(sessionId);
if (existing) {
const updated = new Map(prev);
updated.set(sessionId, { ...existing, status });
return updated;
}
return prev;
});
}, []);
const clearCache = useCallback((sessionId?: number) => {
if (sessionId) {
setCache(prev => {
const updated = new Map(prev);
updated.delete(sessionId);
return updated;
});
} else {
setCache(new Map());
}
}, []);
const parseOutput = useCallback((rawOutput: string): ClaudeStreamMessage[] => {
if (!rawOutput) return [];
const lines = rawOutput.split('\n').filter(line => line.trim());
const parsedMessages: ClaudeStreamMessage[] = [];
for (const line of lines) {
try {
const message = JSON.parse(line) as ClaudeStreamMessage;
parsedMessages.push(message);
} catch (err) {
console.error("Failed to parse message:", err, line);
// Add a fallback message for unparseable content
parsedMessages.push({
type: 'result',
subtype: 'error',
error: 'Failed to parse message',
raw_content: line
});
}
}
return parsedMessages;
}, []);
const updateSessionCache = useCallback(async (sessionId: number, status: string) => {
try {
const rawOutput = await api.getSessionOutput(sessionId);
const messages = parseOutput(rawOutput);
setCachedOutput(sessionId, {
output: rawOutput,
messages,
lastUpdated: Date.now(),
status
});
} catch (error) {
console.warn(`Failed to update cache for session ${sessionId}:`, error);
}
}, [parseOutput, setCachedOutput]);
const pollRunningSessions = useCallback(async () => {
try {
const runningSessions = await api.listRunningAgentSessions();
// Update cache for all running sessions
for (const session of runningSessions) {
if (session.id && session.status === 'running') {
await updateSessionCache(session.id, session.status);
}
}
// Clean up cache for sessions that are no longer running
const runningIds = new Set(runningSessions.map(s => s.id).filter(Boolean));
setCache(prev => {
const updated = new Map();
for (const [sessionId, data] of prev) {
if (runningIds.has(sessionId) || data.status !== 'running') {
updated.set(sessionId, data);
}
}
return updated;
});
} catch (error) {
console.warn('Failed to poll running sessions:', error);
}
}, [updateSessionCache]);
const startBackgroundPolling = useCallback(() => {
if (pollingInterval) return;
setIsPolling(true);
const interval = setInterval(pollRunningSessions, 3000); // Poll every 3 seconds
setPollingInterval(interval);
}, [pollingInterval, pollRunningSessions]);
const stopBackgroundPolling = useCallback(() => {
if (pollingInterval) {
clearInterval(pollingInterval);
setPollingInterval(null);
}
setIsPolling(false);
}, [pollingInterval]);
// Auto-start polling when provider mounts
useEffect(() => {
startBackgroundPolling();
return () => stopBackgroundPolling();
}, [startBackgroundPolling, stopBackgroundPolling]);
const value: OutputCacheContextType = {
getCachedOutput,
setCachedOutput,
updateSessionStatus,
clearCache,
isPolling,
startBackgroundPolling,
stopBackgroundPolling,
};
return (
<OutputCacheContext.Provider value={value}>
{children}
</OutputCacheContext.Provider>
);
}