@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
@@ -59,7 +59,50 @@ class ChatService {
59
59
  'Create a full-stack e-commerce platform with Next.js, Stripe, and PostgreSQL',
60
60
  'Build a real-time chat application using Socket.io with room support and typing indicators',
61
61
  'Create a SaaS dashboard with user management, billing, and analytics',
62
- // ... (keep the same placeholder texts as before)
62
+ 'Build a REST API with authentication, rate limiting, and Swagger documentation',
63
+ 'Create a CLI tool in TypeScript that scaffolds new projects with custom templates',
64
+ // Debugging & fixing
65
+ 'Debug a memory leak in a Node.js service causing it to crash every 24 hours',
66
+ 'Fix race conditions in a concurrent queue processor causing duplicate jobs',
67
+ 'Fix a CORS issue blocking requests between a frontend and backend on different origins',
68
+ 'Fix broken JWT refresh logic that logs users out unexpectedly',
69
+ 'Fix flaky tests that pass locally but fail randomly in CI',
70
+ // Code review & refactoring
71
+ 'Refactor a 1000-line monolithic function into clean, testable modules',
72
+ 'Convert a class-based React codebase to functional components with hooks',
73
+ 'Migrate a JavaScript project to TypeScript with strict mode enabled',
74
+ 'Refactor database queries to use an ORM with proper migrations',
75
+ 'Clean up and standardize error handling across an entire Express application',
76
+ // Writing tests
77
+ 'Write unit tests for a payment processing module with 100% coverage',
78
+ 'Add end-to-end tests using Playwright for a multi-step checkout flow',
79
+ 'Set up integration tests for a REST API using a real test database',
80
+ 'Write property-based tests to find edge cases in a data validation library',
81
+ 'Set up test coverage reporting and enforce a minimum threshold in CI',
82
+ // Performance & optimization
83
+ 'Optimize a slow PostgreSQL query that runs 10 seconds on a 5M-row table',
84
+ 'Implement Redis caching to reduce database load by 80%',
85
+ 'Reduce bundle size of a React app from 4MB to under 500KB',
86
+ 'Profile and optimize a Python data pipeline processing 1M records per hour',
87
+ 'Add lazy loading and virtualization to a list rendering 10,000 items',
88
+ // Architecture & design
89
+ 'Design a scalable event-driven architecture using Kafka for a high-traffic app',
90
+ 'Plan a migration from a monolith to microservices without downtime',
91
+ 'Design a multi-tenant SaaS architecture with data isolation per customer',
92
+ 'Create an authentication system supporting SSO, OAuth, and MFA',
93
+ 'Architect a real-time notification system using WebSockets and a message queue',
94
+ // DevOps & infrastructure
95
+ 'Write a Dockerfile and docker-compose setup for a full-stack app with hot reload',
96
+ 'Set up a GitHub Actions CI/CD pipeline with testing, linting, and auto-deploy',
97
+ 'Configure Nginx as a reverse proxy with SSL termination and load balancing',
98
+ 'Create Terraform scripts to provision a production-ready AWS infrastructure',
99
+ 'Set up monitoring and alerting using Prometheus and Grafana',
100
+ // AI & data
101
+ 'Build a RAG pipeline using LangChain, embeddings, and a vector database',
102
+ 'Create a sentiment analysis API using a fine-tuned transformer model',
103
+ 'Build a data scraper that extracts and structures product data at scale',
104
+ 'Implement a recommendation engine using collaborative filtering',
105
+ 'Create a real-time data dashboard ingesting from multiple streaming sources',
63
106
  ];
64
107
 
65
108
  constructor() {
@@ -9,6 +9,7 @@ import { terminalStore } from '$frontend/stores/features/terminal.svelte';
9
9
  import type { TerminalSession } from '$shared/types/terminal';
10
10
  import { terminalService } from './terminal.service';
11
11
  import { debug } from '$shared/utils/logger';
12
+ import { onWsReconnect } from '$frontend/utils/ws';
12
13
  interface ProjectTerminalContext {
13
14
  projectId: string;
14
15
  projectPath: string;
@@ -838,6 +839,57 @@ class TerminalProjectManager {
838
839
 
839
840
  debug.log('terminal', '✅ Terminal collaborative listeners registered');
840
841
  });
842
+
843
+ // Validate terminal sessions after WebSocket reconnect.
844
+ // When the server restarts, all PTY sessions die. We need to detect
845
+ // dead tabs and clean them up, then auto-create a fresh session.
846
+ onWsReconnect(() => {
847
+ this.validateSessionsAfterReconnect();
848
+ });
849
+ }
850
+
851
+ /**
852
+ * After WebSocket reconnects, check which terminal sessions are still
853
+ * alive on the backend. Remove dead tabs and auto-create a new one
854
+ * if none remain.
855
+ */
856
+ private async validateSessionsAfterReconnect(): Promise<void> {
857
+ if (!this.currentProjectId) return;
858
+ const context = this.projectContexts.get(this.currentProjectId);
859
+ if (!context || context.sessionIds.length === 0) return;
860
+
861
+ debug.log('terminal', 'Validating terminal sessions after reconnect...');
862
+
863
+ try {
864
+ // Query backend for alive PTY sessions
865
+ const aliveSessions = await terminalService.listProjectSessions(this.currentProjectId);
866
+ const aliveSessionIds = new Set(aliveSessions.map(s => s.sessionId));
867
+
868
+ // Find dead sessions (in UI but not on backend)
869
+ const deadSessionIds = context.sessionIds.filter(id => !aliveSessionIds.has(id));
870
+
871
+ if (deadSessionIds.length === 0) {
872
+ debug.log('terminal', 'All terminal sessions still alive after reconnect');
873
+ return;
874
+ }
875
+
876
+ debug.log('terminal', `Found ${deadSessionIds.length} dead terminal session(s) after reconnect, cleaning up`);
877
+
878
+ // Remove dead sessions from context and store
879
+ for (const sessionId of deadSessionIds) {
880
+ this.removeSessionFromContext(sessionId);
881
+ terminalStore.removeSessionFromStore(sessionId);
882
+ terminalService.cleanupListeners(sessionId);
883
+ }
884
+
885
+ // If no sessions remain, auto-create a new one
886
+ if (context.sessionIds.length === 0) {
887
+ debug.log('terminal', 'All terminal sessions dead after reconnect, creating new session');
888
+ await this.createProjectTerminalSessions(this.currentProjectId, context.projectPath);
889
+ }
890
+ } catch (err) {
891
+ debug.error('terminal', 'Failed to validate terminal sessions after reconnect:', err);
892
+ }
841
893
  }
842
894
 
843
895
  /**
@@ -50,7 +50,7 @@ export const settingsSections: SettingsSectionMeta[] = [
50
50
  },
51
51
  {
52
52
  id: 'account',
53
- label: 'Account',
53
+ label: 'User Profile',
54
54
  icon: 'lucide:user',
55
55
  description: 'Your profile and access'
56
56
  },
@@ -3,7 +3,7 @@ import type { Theme } from '$shared/types/ui';
3
3
  // Theme store using Svelte 5 runes
4
4
  export const themeStore = $state({
5
5
  current: {
6
- name: 'claude-modern',
6
+ name: 'clopen-modern',
7
7
  primary: '#D97757',
8
8
  secondary: '#4F46E5',
9
9
  background: '#F9FAFB',
@@ -26,7 +26,7 @@ export function isDarkMode() {
26
26
  // Theme presets
27
27
  export const themes: Theme[] = [
28
28
  {
29
- name: 'claude-modern',
29
+ name: 'clopen-modern',
30
30
  primary: '#D97757',
31
31
  secondary: '#4F46E5',
32
32
  background: '#F9FAFB',
@@ -34,7 +34,7 @@ export const themes: Theme[] = [
34
34
  mode: 'light'
35
35
  },
36
36
  {
37
- name: 'claude-dark',
37
+ name: 'clopen-dark',
38
38
  primary: '#D97757',
39
39
  secondary: '#4F46E5',
40
40
  background: '#111827',
@@ -83,7 +83,7 @@ export function setTheme(theme: Theme) {
83
83
  }
84
84
 
85
85
  // Save to localStorage
86
- localStorage.setItem('claude-theme', JSON.stringify(theme));
86
+ localStorage.setItem('clopen-theme', JSON.stringify(theme));
87
87
  }
88
88
 
89
89
  // Helper function to update theme color meta tag
@@ -105,12 +105,12 @@ export function toggleDarkMode() {
105
105
  const newMode: 'light' | 'dark' = themeStore.isDark ? 'light' : 'dark';
106
106
 
107
107
  // Use predefined themes for consistency
108
- const newTheme = newMode === 'dark' ? themes[1] : themes[0]; // claude-dark or claude-modern
108
+ const newTheme = newMode === 'dark' ? themes[1] : themes[0]; // clopen-dark or clopen-modern
109
109
 
110
110
  setTheme(newTheme);
111
111
 
112
112
  // Mark as manual theme choice
113
- localStorage.setItem('claude-theme-manual', 'true');
113
+ localStorage.setItem('clopen-theme-manual', 'true');
114
114
  }
115
115
 
116
116
  export function initializeTheme() {
@@ -121,8 +121,8 @@ export function initializeTheme() {
121
121
  themeStore.isSystemDark = isSystemDark;
122
122
 
123
123
  // Check for saved theme preference
124
- const savedTheme = localStorage.getItem('claude-theme');
125
- const isManualTheme = localStorage.getItem('claude-theme-manual') === 'true';
124
+ const savedTheme = localStorage.getItem('clopen-theme');
125
+ const isManualTheme = localStorage.getItem('clopen-theme-manual') === 'true';
126
126
 
127
127
  let initialTheme: Theme;
128
128
 
@@ -160,7 +160,7 @@ export function initializeTheme() {
160
160
  themeStore.isSystemDark = e.matches;
161
161
 
162
162
  // Only follow system if no manual theme was set
163
- if (!localStorage.getItem('claude-theme-manual')) {
163
+ if (!localStorage.getItem('clopen-theme-manual')) {
164
164
  const newTheme = e.matches ? themes[1] : themes[0];
165
165
  setTheme(newTheme);
166
166
  }
@@ -169,11 +169,11 @@ export function initializeTheme() {
169
169
 
170
170
  export function setManualTheme(theme: Theme) {
171
171
  setTheme(theme);
172
- localStorage.setItem('claude-theme-manual', 'true');
172
+ localStorage.setItem('clopen-theme-manual', 'true');
173
173
  }
174
174
 
175
175
  export function useSystemTheme() {
176
- localStorage.removeItem('claude-theme-manual');
176
+ localStorage.removeItem('clopen-theme-manual');
177
177
  const defaultTheme = themeStore.isSystemDark ? themes[1] : themes[0];
178
178
  setTheme(defaultTheme);
179
179
  }
@@ -751,7 +751,7 @@ export function setActiveMobilePanel(panelId: PanelId): void {
751
751
  // PERSISTENCE
752
752
  // ============================================
753
753
 
754
- const STORAGE_KEY = 'claude-workspace-layout';
754
+ const STORAGE_KEY = 'clopen-workspace-layout';
755
755
 
756
756
  export function saveWorkspaceState(): void {
757
757
  try {
@@ -57,13 +57,18 @@ function getParentToolUseId(message: SDKMessageFormatter): string | null {
57
57
  export function groupMessages(messages: SDKMessageFormatter[]): {
58
58
  groups: ProcessedMessage[],
59
59
  toolUseMap: Map<string, ToolGroup>,
60
- subAgentMap: Map<string, SDKMessageFormatter[]>
60
+ subAgentMap: Map<string, SDKMessageFormatter[]>,
61
+ skillPromptMap: Map<string, string>
61
62
  } {
62
63
  const groups: ProcessedMessage[] = [];
63
64
  const toolUseMap = new Map<string, ToolGroup>();
64
65
  const agentToolUseIds = new Set<string>();
65
66
  const subAgentMap = new Map<string, SDKMessageFormatter[]>();
67
+ const skillToolUseIds = new Set<string>();
68
+ const skillPromptMap = new Map<string, string>();
66
69
  let lastCompactBoundaryIdx = -1;
70
+ // Track last Skill tool_use ID for associating synthetic user messages
71
+ let lastSkillToolUseId: string | null = null;
67
72
 
68
73
  // Rebuild compact summary map each call
69
74
  _compactSummaryMap = new WeakMap<SDKMessageFormatter, string>();
@@ -91,6 +96,7 @@ export function groupMessages(messages: SDKMessageFormatter[]): {
91
96
  // Handle compact boundary messages — track for synthetic user embedding
92
97
  if (isCompactBoundaryMessage(message)) {
93
98
  lastCompactBoundaryIdx = groups.length;
99
+ lastSkillToolUseId = null;
94
100
  groups.push(message as ProcessedMessage);
95
101
  return;
96
102
  }
@@ -98,6 +104,7 @@ export function groupMessages(messages: SDKMessageFormatter[]): {
98
104
  // Handle assistant messages with tool_use
99
105
  if (message.type === 'assistant' && 'message' in message && message.message?.content) {
100
106
  lastCompactBoundaryIdx = -1;
107
+ lastSkillToolUseId = null;
101
108
  const toolUses = extractToolUses(message.message.content);
102
109
 
103
110
  if (toolUses.length > 0) {
@@ -112,6 +119,11 @@ export function groupMessages(messages: SDKMessageFormatter[]): {
112
119
  if (toolUse.name === 'Agent') {
113
120
  agentToolUseIds.add(toolUse.id);
114
121
  }
122
+ // Track Skill tool IDs for synthetic user message capture
123
+ if (toolUse.name === 'Skill') {
124
+ skillToolUseIds.add(toolUse.id);
125
+ lastSkillToolUseId = toolUse.id;
126
+ }
115
127
  }
116
128
  });
117
129
  groups.push(message as ProcessedMessage);
@@ -134,11 +146,23 @@ export function groupMessages(messages: SDKMessageFormatter[]): {
134
146
  return;
135
147
  }
136
148
 
149
+ // Synthetic user messages after Skill tool: capture expanded skill prompt
150
+ if (isSyntheticUserMessage(message) && lastSkillToolUseId) {
151
+ const promptText = extractUserTextContent(message);
152
+ if (promptText) {
153
+ skillPromptMap.set(lastSkillToolUseId, promptText);
154
+ }
155
+ lastSkillToolUseId = null;
156
+ return;
157
+ }
158
+
137
159
  lastCompactBoundaryIdx = -1;
138
160
 
139
161
  const toolResults = extractToolResults(message.message.content);
140
162
  if (toolResults.length > 0) {
141
163
  // Group tool_result with corresponding tool_use
164
+ // Note: don't reset lastSkillToolUseId here — tool_result may precede
165
+ // the synthetic skill prompt user message
142
166
  toolResults.forEach((toolResult: any) => {
143
167
  if (toolResult.tool_use_id && toolUseMap.has(toolResult.tool_use_id)) {
144
168
  const group = toolUseMap.get(toolResult.tool_use_id);
@@ -149,7 +173,8 @@ export function groupMessages(messages: SDKMessageFormatter[]): {
149
173
  });
150
174
  // Don't add tool_result messages separately
151
175
  } else {
152
- // Regular user message
176
+ // Regular user message — reset skill tracking
177
+ lastSkillToolUseId = null;
153
178
  groups.push(message as ProcessedMessage);
154
179
  }
155
180
  return;
@@ -157,17 +182,19 @@ export function groupMessages(messages: SDKMessageFormatter[]): {
157
182
 
158
183
  // Include stream_event and other messages
159
184
  lastCompactBoundaryIdx = -1;
185
+ lastSkillToolUseId = null;
160
186
  groups.push(message as ProcessedMessage);
161
187
  });
162
188
 
163
- return { groups, toolUseMap, subAgentMap };
189
+ return { groups, toolUseMap, subAgentMap, skillPromptMap };
164
190
  }
165
191
 
166
192
  // Add tool results to messages
167
193
  export function embedToolResults(
168
194
  groups: ProcessedMessage[],
169
195
  toolUseMap: Map<string, ToolGroup>,
170
- subAgentMap: Map<string, SDKMessageFormatter[]>
196
+ subAgentMap: Map<string, SDKMessageFormatter[]>,
197
+ skillPromptMap: Map<string, string>
171
198
  ): ProcessedMessage[] {
172
199
  // Track background bash sessions
173
200
  const backgroundBashMap = trackBackgroundBashSessions(groups, toolUseMap);
@@ -182,7 +209,8 @@ export function embedToolResults(
182
209
  message,
183
210
  toolUseMap,
184
211
  backgroundBashMap,
185
- subAgentMap
212
+ subAgentMap,
213
+ skillPromptMap
186
214
  );
187
215
  return processedMessage;
188
216
  }
@@ -56,7 +56,8 @@ export const TOOLS_WITH_RESULTS: ToolInput['name'][] = [
56
56
  'Config',
57
57
  'EnterWorktree',
58
58
  'Agent',
59
- 'EnterPlanMode'
59
+ 'EnterPlanMode',
60
+ 'Skill'
60
61
  ];
61
62
 
62
63
  // Tools that should be hidden from display
@@ -18,6 +18,7 @@ export interface ToolUseWithResult {
18
18
  input: any;
19
19
  $result?: any;
20
20
  $subMessages?: SubAgentActivity[];
21
+ $skillPrompt?: string;
21
22
  metadata?: Record<string, unknown>;
22
23
  }
23
24
 
@@ -26,7 +27,8 @@ export function processToolMessage(
26
27
  message: ProcessedMessage,
27
28
  toolUseMap: Map<string, ToolGroup>,
28
29
  backgroundBashMap: Map<string, BackgroundBashData>,
29
- subAgentMap: Map<string, SDKMessageFormatter[]>
30
+ subAgentMap: Map<string, SDKMessageFormatter[]>,
31
+ skillPromptMap: Map<string, string> = new Map()
30
32
  ): ProcessedMessage {
31
33
  const messageAny = message as any;
32
34
  const content = messageAny.message?.content ?
@@ -39,7 +41,7 @@ export function processToolMessage(
39
41
  const modifiedContent = content
40
42
  .map((item: any): any => {
41
43
  if (typeof item === 'object' && item && 'type' in item && item.type === 'tool_use') {
42
- const processed = processToolUse(item, toolUseMap, backgroundBashMap, subAgentMap);
44
+ const processed = processToolUse(item, toolUseMap, backgroundBashMap, subAgentMap, skillPromptMap);
43
45
  // Propagate message-level interrupted flag to ALL tool_use blocks
44
46
  if (processed && isInterrupted) {
45
47
  return { ...processed, metadata: { ...processed.metadata, interrupted: true } };
@@ -65,7 +67,8 @@ function processToolUse(
65
67
  item: any,
66
68
  toolUseMap: Map<string, ToolGroup>,
67
69
  backgroundBashMap: Map<string, BackgroundBashData>,
68
- subAgentMap: Map<string, SDKMessageFormatter[]>
70
+ subAgentMap: Map<string, SDKMessageFormatter[]>,
71
+ skillPromptMap: Map<string, string>
69
72
  ): ToolUseWithResult | null {
70
73
  // Hide certain tools completely
71
74
  if (shouldHideTool(item.name)) {
@@ -85,6 +88,11 @@ function processToolUse(
85
88
  return handleAgentTool(item, toolUseMap, subAgentMap);
86
89
  }
87
90
 
91
+ // Special handling for Skill tool — embed expanded skill prompt
92
+ if (item.name === 'Skill' && item.id && skillPromptMap.has(item.id)) {
93
+ return handleSkillTool(item, toolUseMap, skillPromptMap);
94
+ }
95
+
88
96
  // Regular tool handling
89
97
  if (item.id && item.name && shouldEmbedResult(item.name) && toolUseMap.has(item.id)) {
90
98
  return handleRegularTool(item, toolUseMap);
@@ -165,6 +173,33 @@ function processSubAgentMessages(messages: SDKMessageFormatter[]): SubAgentActiv
165
173
  return activities;
166
174
  }
167
175
 
176
+ // Handle Skill tool — embed expanded skill prompt
177
+ function handleSkillTool(
178
+ item: any,
179
+ toolUseMap: Map<string, ToolGroup>,
180
+ skillPromptMap: Map<string, string>
181
+ ): ToolUseWithResult {
182
+ const skillPrompt = skillPromptMap.get(item.id);
183
+
184
+ // Also embed the $result if available
185
+ let result: any = undefined;
186
+ if (item.id && toolUseMap.has(item.id)) {
187
+ const group = toolUseMap.get(item.id);
188
+ if (group?.toolResultMessage) {
189
+ const resultMessage = group.toolResultMessage as any;
190
+ const resultContent = resultMessage.message ?
191
+ (Array.isArray(resultMessage.message.content) ? resultMessage.message.content : [resultMessage.message.content]) : [];
192
+ result = findToolResult(resultContent, item.id);
193
+ }
194
+ }
195
+
196
+ return {
197
+ ...item,
198
+ ...(result ? { $result: result } : {}),
199
+ ...(skillPrompt ? { $skillPrompt: skillPrompt } : {})
200
+ } as ToolUseWithResult;
201
+ }
202
+
168
203
  // Handle background bash commands
169
204
  function handleBackgroundBash(
170
205
  item: any,