@myrialabs/clopen 0.2.13 → 0.2.15

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.
Files changed (43) hide show
  1. package/backend/snapshot/helpers.ts +8 -0
  2. package/backend/snapshot/snapshot-service.ts +9 -7
  3. package/backend/ws/snapshot/timeline.ts +6 -2
  4. package/bin/clopen.ts +377 -100
  5. package/frontend/components/chat/ChatInterface.svelte +6 -1
  6. package/frontend/components/chat/formatters/Tools.svelte +3 -1
  7. package/frontend/components/chat/input/components/EngineModelPicker.svelte +12 -1
  8. package/frontend/components/chat/input/components/LoadingIndicator.svelte +2 -2
  9. package/frontend/components/chat/message/ChatMessage.svelte +0 -29
  10. package/frontend/components/chat/message/ChatMessages.svelte +2 -2
  11. package/frontend/components/chat/message/MessageBubble.svelte +0 -6
  12. package/frontend/components/chat/message/MessageHeader.svelte +0 -16
  13. package/frontend/components/chat/tools/SkillTool.svelte +21 -0
  14. package/frontend/components/chat/tools/index.ts +1 -0
  15. package/frontend/components/chat/widgets/ContextIndicator.svelte +186 -0
  16. package/frontend/components/checkpoint/TimelineModal.svelte +3 -1
  17. package/frontend/components/common/overlay/Dialog.svelte +2 -2
  18. package/frontend/components/history/HistoryModal.svelte +3 -3
  19. package/frontend/components/preview/browser/BrowserPreview.svelte +7 -0
  20. package/frontend/components/preview/browser/components/Canvas.svelte +8 -0
  21. package/frontend/components/settings/engines/AIEnginesSettings.svelte +1 -1
  22. package/frontend/components/settings/general/AuthModeSettings.svelte +2 -2
  23. package/frontend/components/settings/model/EngineModelPicker.svelte +9 -0
  24. package/frontend/components/tunnel/TunnelInactive.svelte +4 -4
  25. package/frontend/components/workspace/PanelHeader.svelte +4 -0
  26. package/frontend/components/workspace/panels/ChatPanel.svelte +6 -0
  27. package/frontend/services/chat/chat.service.ts +44 -1
  28. package/frontend/services/terminal/project.service.ts +52 -0
  29. package/frontend/stores/ui/settings-modal.svelte.ts +1 -1
  30. package/frontend/stores/ui/theme.svelte.ts +11 -11
  31. package/frontend/stores/ui/workspace.svelte.ts +1 -1
  32. package/frontend/utils/chat/message-grouper.ts +33 -5
  33. package/frontend/utils/chat/message-processor.ts +2 -1
  34. package/frontend/utils/chat/tool-handler.ts +38 -3
  35. package/frontend/utils/context-manager.ts +35 -237
  36. package/index.html +2 -2
  37. package/package.json +1 -1
  38. package/shared/types/messaging/index.ts +1 -0
  39. package/shared/types/messaging/tool.ts +24 -1
  40. package/shared/utils/anonymous-user.ts +4 -4
  41. package/shared/utils/ws-client.ts +23 -1
  42. package/frontend/components/chat/modal/TokenUsageModal.svelte +0 -124
  43. package/frontend/components/chat/widgets/TokenUsage.svelte +0 -78
@@ -1,257 +1,55 @@
1
1
  /**
2
- * Context Window Management (Simplified)
2
+ * Context Window Usage
3
3
  *
4
- * NOTE: Claude SDK now handles context management internally with efficient resume.
5
- * This module is simplified to provide token counting utilities only.
6
- * The SDK's native context management with compact boundaries is more efficient.
4
+ * Calculates actual context window usage from assistant message token data.
5
+ * Each API call sends the full conversation, so input_tokens on the last
6
+ * assistant message represents total context consumed at that turn.
7
7
  */
8
8
 
9
9
  import type { SDKMessage } from '$shared/types/messaging';
10
10
 
11
- // Configuration (for display purposes only - SDK handles actual limits)
12
- const DISPLAY_MAX_TOKENS = 200000; // Display token limit
13
- const WARNING_THRESHOLD = 0.8; // Warn when reaching 80% of max tokens
14
- const TOKEN_ESTIMATE_RATIO = 3.5; // Estimate: 1 token ≈ 3.5 characters
11
+ const WARNING_THRESHOLD = 0.8;
15
12
 
16
- export interface ManagedContext {
17
- messages: SDKMessage[];
18
- summary?: string;
19
- totalTokens: number;
20
- isCompressed: boolean;
21
- tokenUsage: {
22
- current: number;
23
- max: number;
24
- percentage: number;
25
- nearLimit: boolean;
26
- };
27
- }
28
-
29
- /**
30
- * Estimate token count for a text string
31
- * Uses a more sophisticated estimation that accounts for different text patterns
32
- */
33
- export function estimateTokens(text: string): number {
34
- if (!text || text.length === 0) return 0;
35
-
36
- // More accurate estimation accounting for:
37
- // - Whitespace and punctuation
38
- // - Code blocks (different tokenization)
39
- // - Common patterns
40
-
41
- let adjustedLength = text.length;
42
-
43
- // Code blocks tend to have more tokens per character
44
- const codeBlockMatches = text.match(/```[\s\S]*?```/g);
45
- if (codeBlockMatches) {
46
- const codeLength = codeBlockMatches.reduce((sum, block) => sum + block.length, 0);
47
- // Code has ~1 token per 2.5 characters
48
- adjustedLength = adjustedLength - codeLength + (codeLength / 2.5);
49
- }
50
-
51
- // Account for whitespace - multiple spaces/newlines count as fewer tokens
52
- const whitespaceReduced = text.replace(/\s+/g, ' ').length;
53
- adjustedLength = Math.min(adjustedLength, whitespaceReduced * 1.2);
54
-
55
- // Apply base ratio with minimum of 1 token for non-empty text
56
- return Math.max(1, Math.ceil(adjustedLength / TOKEN_ESTIMATE_RATIO));
57
- }
58
-
59
- // Token calculation cache to prevent recalculation
60
- const tokenCache = new Map<string, number>();
61
-
62
- /**
63
- * Calculate total tokens for a set of messages using only actual token usage data
64
- * Returns 0 if no actual usage data is available (no estimates)
65
- */
66
- export function calculateMessageTokens(messages: SDKMessage[]): number {
67
- if (!messages || messages.length === 0) return 0;
68
-
69
- // Only use actual token usage data from API responses
70
- const messagesWithUsage = messages.filter(msg => {
71
- if (msg.type === 'assistant' && 'message' in msg && msg.message.usage) {
72
- return true;
73
- }
74
- return false;
75
- });
76
-
77
- if (messagesWithUsage.length === 0) {
78
- // No actual usage data available - return 0 instead of estimates
79
- return 0;
80
- }
81
-
82
- // Calculate actual total tokens from API responses
83
- return messagesWithUsage.reduce((total, msg) => {
84
- if (msg.type === 'assistant' && 'message' in msg && msg.message.usage) {
85
- const usage = msg.message.usage;
86
- return total + (usage.input_tokens || 0) + (usage.output_tokens || 0);
87
- }
88
- return total;
89
- }, 0);
13
+ export interface ContextUsage {
14
+ current: number;
15
+ max: number;
16
+ percentage: number;
17
+ nearLimit: boolean;
90
18
  }
91
19
 
92
20
  /**
93
- * Create a summary of older messages
94
- */
95
- export function summarizeMessages(messages: SDKMessage[]): string {
96
- if (messages.length === 0) return '';
97
-
98
- // Group messages by role for better summarization
99
- const userMessages: string[] = [];
100
- const assistantMessages: string[] = [];
101
-
102
- messages.forEach(msg => {
103
- if (msg.type === 'user' && 'message' in msg) {
104
- // Extract key points from user messages
105
- const content = typeof msg.message.content === 'string' ? msg.message.content : JSON.stringify(msg.message.content);
106
- const keyPoints = extractKeyPoints(content);
107
- if (keyPoints) userMessages.push(keyPoints);
108
- } else if (msg.type === 'assistant' && 'message' in msg) {
109
- // Extract key actions/responses from assistant
110
- const content = Array.isArray(msg.message.content)
111
- ? msg.message.content.map(c => c.type === 'text' ? c.text : JSON.stringify(c)).join(' ')
112
- : JSON.stringify(msg.message.content);
113
- const keyActions = extractKeyActions(content);
114
- if (keyActions) assistantMessages.push(keyActions);
21
+ * Get context window usage from the last assistant message.
22
+ *
23
+ * Cache tokens (creation + read) also count toward the context window.
24
+ */
25
+ export function getContextUsage(messages: SDKMessage[], contextWindow: number): ContextUsage {
26
+ // Find the last assistant message with usage data (iterate backwards)
27
+ let lastUsage: { input_tokens: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number } | null = null;
28
+ for (let i = messages.length - 1; i >= 0; i--) {
29
+ const msg = messages[i];
30
+ if (msg.type === 'assistant' && 'message' in msg) {
31
+ const usage = (msg as any).message?.usage;
32
+ if (usage && typeof usage.input_tokens === 'number') {
33
+ lastUsage = usage;
34
+ break;
35
+ }
115
36
  }
116
- });
117
-
118
- // Build summary
119
- const summaryParts: string[] = [];
120
-
121
- if (userMessages.length > 0) {
122
- summaryParts.push(`Previous user requests: ${userMessages.join('; ')}`);
123
- }
124
-
125
- if (assistantMessages.length > 0) {
126
- summaryParts.push(`Previous assistant actions: ${assistantMessages.join('; ')}`);
127
- }
128
-
129
- return summaryParts.join('\n');
130
- }
131
-
132
- /**
133
- * Extract key points from user messages
134
- */
135
- function extractKeyPoints(content: string): string {
136
- // Handle both string and ContentBlock array formats
137
- const textContent = content;
138
-
139
- // Look for questions, commands, or important keywords
140
- const lines = textContent.split('\n').filter(line => line.trim());
141
-
142
- // Prioritize lines with questions or commands
143
- const importantLines = lines.filter(line =>
144
- line.includes('?') ||
145
- line.includes('please') ||
146
- line.includes('help') ||
147
- line.includes('create') ||
148
- line.includes('update') ||
149
- line.includes('fix') ||
150
- line.includes('implement') ||
151
- line.includes('add') ||
152
- line.includes('remove') ||
153
- line.includes('show') ||
154
- line.includes('explain')
155
- );
156
-
157
- if (importantLines.length > 0) {
158
- // Take first important line as summary
159
- return importantLines[0].substring(0, 100);
160
37
  }
161
-
162
- // Fallback to first line
163
- return lines[0]?.substring(0, 100) || '';
164
- }
165
38
 
166
- /**
167
- * Extract key actions from assistant messages
168
- */
169
- function extractKeyActions(content: string): string {
170
- // Look for action indicators
171
- const actionPatterns = [
172
- /created (.+)/i,
173
- /updated (.+)/i,
174
- /implemented (.+)/i,
175
- /fixed (.+)/i,
176
- /added (.+)/i,
177
- /removed (.+)/i,
178
- /modified (.+)/i,
179
- /explained (.+)/i,
180
- /I will (.+)/i,
181
- /I have (.+)/i,
182
- /I've (.+)/i
183
- ];
184
-
185
- for (const pattern of actionPatterns) {
186
- const match = content.match(pattern);
187
- if (match) {
188
- return match[0].substring(0, 100);
189
- }
190
- }
191
-
192
- // Look for code blocks as actions
193
- if (content.includes('```')) {
194
- return 'provided code implementation';
39
+ if (!lastUsage) {
40
+ return { current: 0, max: contextWindow, percentage: 0, nearLimit: false };
195
41
  }
196
-
197
- // Fallback to first line
198
- const firstLine = content.split('\n')[0];
199
- return firstLine?.substring(0, 100) || '';
200
- }
201
-
202
- /**
203
- * Calculate token usage statistics with smoothing
204
- */
205
- function calculateTokenUsage(currentTokens: number): ManagedContext['tokenUsage'] {
206
- // Ensure non-negative values
207
- const safeTokens = Math.max(0, currentTokens);
208
- const percentage = Math.min(100, (safeTokens / DISPLAY_MAX_TOKENS) * 100);
209
-
210
- return {
211
- current: safeTokens,
212
- max: DISPLAY_MAX_TOKENS,
213
- percentage: Math.round(percentage * 10) / 10, // Round to 1 decimal place for smoother transitions
214
- nearLimit: safeTokens >= (DISPLAY_MAX_TOKENS * WARNING_THRESHOLD)
215
- };
216
- }
217
42
 
218
- /**
219
- * Get conversation context info (SDK handles actual context management)
220
- * @deprecated Use SDK's native context management with resume feature
221
- */
222
- export function manageConversationContext(messages: SDKMessage[]): ManagedContext {
223
- if (messages.length === 0) {
224
- return {
225
- messages: [],
226
- totalTokens: 0,
227
- isCompressed: false,
228
- tokenUsage: calculateTokenUsage(0)
229
- };
230
- }
43
+ const current = (lastUsage.input_tokens || 0)
44
+ + (lastUsage.cache_creation_input_tokens || 0)
45
+ + (lastUsage.cache_read_input_tokens || 0);
231
46
 
232
- // Calculate total tokens for display purposes
233
- const totalTokens = calculateMessageTokens(messages);
47
+ const percentage = Math.min(100, Math.round((current / contextWindow) * 1000) / 10);
234
48
 
235
- // SDK handles context internally, we just return info for UI
236
49
  return {
237
- messages,
238
- summary: undefined,
239
- totalTokens,
240
- isCompressed: false,
241
- tokenUsage: calculateTokenUsage(totalTokens)
50
+ current,
51
+ max: contextWindow,
52
+ percentage,
53
+ nearLimit: current >= contextWindow * WARNING_THRESHOLD
242
54
  };
243
55
  }
244
-
245
- /**
246
- * Build conversation prompt
247
- * @deprecated SDK handles prompt building internally with resume feature
248
- */
249
- export function buildConversationPrompt(
250
- messages: SDKMessage[],
251
- currentPrompt: string,
252
- summary?: string
253
- ): string {
254
- // SDK handles this internally now, just return the prompt
255
- // This function is kept for backward compatibility
256
- return currentPrompt;
257
- }
package/index.html CHANGED
@@ -20,8 +20,8 @@
20
20
  (function() {
21
21
  // Check for saved theme preference
22
22
  try {
23
- const savedTheme = localStorage.getItem('claude-theme');
24
- const isManualTheme = localStorage.getItem('claude-theme-manual') === 'true';
23
+ const savedTheme = localStorage.getItem('clopen-theme');
24
+ const isManualTheme = localStorage.getItem('clopen-theme-manual') === 'true';
25
25
 
26
26
  let isDark = false;
27
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "All-in-one web workspace for Claude Code & OpenCode — chat, terminal, git, browser preview, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",
@@ -129,6 +129,7 @@ export type {
129
129
  EnterWorktreeToolInput,
130
130
  AgentToolInput,
131
131
  EnterPlanModeToolInput,
132
+ SkillToolInput,
132
133
  SubAgentActivity,
133
134
  ToolInput,
134
135
 
@@ -323,6 +323,28 @@ export interface EnterPlanModeToolInput {
323
323
  metadata?: ToolMetadata;
324
324
  }
325
325
 
326
+ /**
327
+ * Skill tool input — manually defined (not from SDK).
328
+ *
329
+ * Neither @anthropic-ai/claude-agent-sdk nor @opencode-ai/sdk export a
330
+ * SkillInput type. The shape is inferred from observed tool_use payloads
331
+ * where `input.skill` is the slash-command name and `input.args` is an
332
+ * optional argument string.
333
+ */
334
+ export interface SkillToolInput {
335
+ type: 'tool_use';
336
+ id: string;
337
+ name: 'Skill';
338
+ input: {
339
+ skill: string;
340
+ args?: string;
341
+ };
342
+ $result?: ToolResult;
343
+ /** Expanded skill prompt (from synthetic user message) */
344
+ $skillPrompt?: string;
345
+ metadata?: ToolMetadata;
346
+ }
347
+
326
348
  // ============================================================
327
349
  // Union of All Tool Input Types
328
350
  // ============================================================
@@ -348,4 +370,5 @@ export type ToolInput =
348
370
  | ConfigToolInput
349
371
  | EnterWorktreeToolInput
350
372
  | AgentToolInput
351
- | EnterPlanModeToolInput;
373
+ | EnterPlanModeToolInput
374
+ | SkillToolInput;
@@ -56,7 +56,7 @@ export async function getOrCreateAnonymousUser(): Promise<AnonymousUser | null>
56
56
  return null;
57
57
  }
58
58
 
59
- const stored = localStorage.getItem('claude-anonymous-user');
59
+ const stored = localStorage.getItem('clopen-anonymous-user');
60
60
 
61
61
  if (stored) {
62
62
  try {
@@ -76,7 +76,7 @@ export async function getOrCreateAnonymousUser(): Promise<AnonymousUser | null>
76
76
  const newUser = await generateAnonymousUserFromServer();
77
77
 
78
78
  if (newUser) {
79
- localStorage.setItem('claude-anonymous-user', JSON.stringify(newUser));
79
+ localStorage.setItem('clopen-anonymous-user', JSON.stringify(newUser));
80
80
  return newUser;
81
81
  }
82
82
 
@@ -93,7 +93,7 @@ export function getCurrentAnonymousUser(): AnonymousUser | null {
93
93
  return null;
94
94
  }
95
95
 
96
- const stored = localStorage.getItem('claude-anonymous-user');
96
+ const stored = localStorage.getItem('clopen-anonymous-user');
97
97
 
98
98
  if (stored) {
99
99
  try {
@@ -146,7 +146,7 @@ export async function updateAnonymousUserName(newName: string): Promise<Anonymou
146
146
  });
147
147
 
148
148
  // Save to localStorage
149
- localStorage.setItem('claude-anonymous-user', JSON.stringify(response));
149
+ localStorage.setItem('clopen-anonymous-user', JSON.stringify(response));
150
150
  debug.log('user', '✅ Updated user name:', response.name);
151
151
  return response;
152
152
  } catch (error) {
@@ -584,11 +584,33 @@ export class WSClient<TAPI extends { client: any; server: any }> {
584
584
 
585
585
  /**
586
586
  * Manual reconnect
587
+ * Unlike disconnect(), this preserves all registered listeners
588
+ * so that services (chat, terminal, etc.) continue receiving events.
587
589
  */
588
590
  reconnect(): void {
589
- this.disconnect();
591
+ // Cancel any pending auto-reconnect
592
+ if (this.reconnectTimeout) {
593
+ clearTimeout(this.reconnectTimeout);
594
+ this.reconnectTimeout = null;
595
+ }
596
+
597
+ // Close existing socket without triggering onclose reconnect
598
+ if (this.ws) {
599
+ try {
600
+ this.ws.onclose = null;
601
+ this.ws.onerror = null;
602
+ this.ws.onmessage = null;
603
+ this.ws.close();
604
+ } catch {
605
+ // Ignore close errors on stale socket
606
+ }
607
+ this.ws = null;
608
+ }
609
+
610
+ this.isConnected = false;
590
611
  this.shouldReconnect = true;
591
612
  this.reconnectAttempts = 0;
613
+ // NOTE: listeners and messageQueue are intentionally preserved
592
614
  this.connect();
593
615
  }
594
616
 
@@ -1,124 +0,0 @@
1
- <!--
2
- Token Usage Modal Component
3
-
4
- Features:
5
- - Display token usage statistics
6
- - Cache read and creation stats
7
- - Request information
8
- -->
9
-
10
- <script lang="ts">
11
- import Modal from '$frontend/components/common/overlay/Modal.svelte';
12
- import Icon from '$frontend/components/common/display/Icon.svelte';
13
-
14
- let {
15
- isOpen = $bindable(),
16
- tokenUsage,
17
- timestamp,
18
- onClose
19
- }: {
20
- isOpen: boolean;
21
- tokenUsage: any;
22
- timestamp: string;
23
- onClose: () => void;
24
- } = $props();
25
-
26
- // Format timestamp
27
- const formatTime = (timestamp?: string) => {
28
- if (!timestamp) return 'Unknown';
29
- const date = new Date(timestamp);
30
- return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
31
- };
32
- </script>
33
-
34
- <Modal
35
- bind:isOpen
36
- title="Token Usage"
37
- size="md"
38
- {onClose}
39
- >
40
- {#snippet children()}
41
- {#if tokenUsage}
42
- <div class="space-y-4">
43
- <!-- Token Usage Stats -->
44
- <div class="bg-violet-50 dark:bg-violet-900/20 rounded-lg p-4">
45
- <h4 class="font-medium text-violet-900 dark:text-violet-100 mb-2 flex items-center gap-2">
46
- <Icon name="lucide:zap" class="w-4 h-4" />
47
- Token Usage
48
- </h4>
49
- <div class="space-y-3 text-slate-600 dark:text-slate-400">
50
- <div class="flex justify-between items-center">
51
- <span class="text-sm">Input Tokens:</span>
52
- <span class="font-mono font-semibold text-violet-600 dark:text-violet-400">
53
- {(tokenUsage.input_tokens ?? 0).toLocaleString()}
54
- </span>
55
- </div>
56
- <div class="flex justify-between items-center">
57
- <span class="text-sm">Output Tokens:</span>
58
- <span class="font-mono font-semibold text-violet-600 dark:text-violet-400">
59
- {(tokenUsage.output_tokens ?? 0).toLocaleString()}
60
- </span>
61
- </div>
62
- <div class="flex justify-between items-center">
63
- <span class="text-sm">Cache Read:</span>
64
- <span class="font-mono font-semibold text-green-600 dark:text-green-400">
65
- {(tokenUsage.cache_read_input_tokens ?? 0).toLocaleString()}
66
- </span>
67
- </div>
68
- <div class="flex justify-between items-center">
69
- <span class="text-sm">Cache Creation:</span>
70
- <span class="font-mono font-semibold text-violet-600 dark:text-violet-400">
71
- {(tokenUsage.cache_creation_input_tokens ?? 0).toLocaleString()}
72
- </span>
73
- </div>
74
- <!-- Total -->
75
- <div class="border-t border-violet-200/50 dark:border-violet-800/50 pt-3 mt-3">
76
- <div class="flex justify-between items-center">
77
- <span class="text-sm font-medium">Total Tokens:</span>
78
- <span class="font-mono font-bold text-lg text-violet-600 dark:text-violet-400">
79
- {((tokenUsage.input_tokens || 0) + (tokenUsage.output_tokens || 0)).toLocaleString()}
80
- </span>
81
- </div>
82
- </div>
83
- </div>
84
- </div>
85
-
86
- <!-- Request Info -->
87
- <div class="bg-slate-50 dark:bg-slate-800 rounded-lg p-4 border border-slate-200 dark:border-slate-700">
88
- <h4 class="font-medium text-slate-900 dark:text-slate-100 mb-2 flex items-center gap-2">
89
- <Icon name="lucide:info" class="w-4 h-4" />
90
- Request Info
91
- </h4>
92
- <div class="space-y-2">
93
- <div class="flex justify-between items-center">
94
- <span class="text-sm text-slate-600 dark:text-slate-400">Time:</span>
95
- <span class="text-sm font-mono text-slate-900 dark:text-slate-100">
96
- {formatTime(timestamp || new Date().toISOString())}
97
- </span>
98
- </div>
99
- <div class="flex justify-between items-center">
100
- <span class="text-sm text-slate-600 dark:text-slate-400">Date:</span>
101
- <span class="text-sm font-mono text-slate-900 dark:text-slate-100">
102
- {timestamp ? new Date(timestamp).toLocaleDateString() : 'Unknown'}
103
- </span>
104
- </div>
105
- {#if tokenUsage.service_tier}
106
- <div class="flex justify-between items-center">
107
- <span class="text-sm text-slate-600 dark:text-slate-400">Service Tier:</span>
108
- <span class="text-sm font-medium capitalize text-slate-900 dark:text-slate-100">
109
- {tokenUsage.service_tier}
110
- </span>
111
- </div>
112
- {/if}
113
- </div>
114
- </div>
115
- </div>
116
- {:else}
117
- <div class="text-center py-8">
118
- <Icon name="lucide:info" class="w-12 h-12 text-slate-400 mx-auto mb-2" />
119
- <p class="text-slate-600 dark:text-slate-400">No token usage data available</p>
120
- <p class="text-sm text-slate-500 dark:text-slate-500 mt-1">This message doesn't contain token usage information</p>
121
- </div>
122
- {/if}
123
- {/snippet}
124
- </Modal>
@@ -1,78 +0,0 @@
1
- <script lang="ts">
2
- import { sessionState } from '$frontend/stores/core/sessions.svelte';
3
- import { addNotification } from '$frontend/stores/ui/notification.svelte';
4
- import { manageConversationContext } from '$frontend/utils/context-manager';
5
- import Icon from '$frontend/components/common/display/Icon.svelte';
6
-
7
- const tokenUsage = $derived.by(() => {
8
- const context = manageConversationContext(sessionState.messages);
9
- return context.tokenUsage;
10
- });
11
-
12
- const usageColor = $derived.by(() => {
13
- if (tokenUsage.percentage >= 90) return 'text-red-500';
14
- if (tokenUsage.percentage >= 80) return 'text-amber-500';
15
- if (tokenUsage.percentage >= 60) return 'text-yellow-500';
16
- return 'text-emerald-500';
17
- });
18
-
19
- const bgColor = $derived.by(() => {
20
- if (tokenUsage.percentage >= 90) return 'bg-red-500/20';
21
- if (tokenUsage.percentage >= 80) return 'bg-amber-500/20';
22
- if (tokenUsage.percentage >= 60) return 'bg-yellow-500/20';
23
- return 'bg-emerald-500/20';
24
- });
25
-
26
- const progressColor = $derived.by(() => {
27
- if (tokenUsage.percentage >= 90) return 'bg-red-500';
28
- if (tokenUsage.percentage >= 80) return 'bg-amber-500';
29
- if (tokenUsage.percentage >= 60) return 'bg-yellow-500';
30
- return 'bg-emerald-500';
31
- });
32
-
33
- const previousNearLimit = $state(false);
34
-
35
- // DISABLED - Token limit notifications
36
- /*
37
- $effect(() => {
38
- // Show notification when first approaching limit
39
- if (tokenUsage.nearLimit && !previousNearLimit) {
40
- addNotification({
41
- type: 'warning',
42
- title: 'Approaching token limit',
43
- message: 'Older messages will be automatically summarized to save space when the limit is reached.',
44
- duration: 8000
45
- });
46
- }
47
- previousNearLimit = tokenUsage.nearLimit;
48
- });
49
- */
50
- </script>
51
-
52
- <div class="relative">
53
- <!-- Token Usage Display -->
54
- <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg {bgColor}">
55
- <Icon
56
- name="lucide:brain"
57
- class="w-4 h-4 {usageColor}"
58
- />
59
- <div class="flex flex-col">
60
- <div class="flex items-center gap-2">
61
- <span class="text-xs font-medium {usageColor}">
62
- {tokenUsage.percentage}%
63
- </span>
64
- <span class="text-xs text-slate-500 dark:text-slate-400">
65
- ({tokenUsage.current.toLocaleString()} / {tokenUsage.max.toLocaleString()} tokens)
66
- </span>
67
- </div>
68
- <!-- Progress Bar -->
69
- <div class="w-32 h-1 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden mt-1">
70
- <div
71
- class="{progressColor} h-full transition-all duration-300"
72
- style="width: {Math.min(tokenUsage.percentage, 100)}%"
73
- ></div>
74
- </div>
75
- </div>
76
- </div>
77
- </div>
78
-