-
Notifications
You must be signed in to change notification settings - Fork 800
Expand file tree
/
Copy pathPixelAgentsViewProvider.ts
More file actions
424 lines (390 loc) · 15.7 KB
/
PixelAgentsViewProvider.ts
File metadata and controls
424 lines (390 loc) · 15.7 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
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import {
getAllProjectDirPaths,
getProjectDirPath,
launchNewTerminal,
persistAgents,
removeAgent,
restoreAgents,
sendExistingAgents,
sendLayout,
} from './agentManager.js';
import {
loadCharacterSprites,
loadDefaultLayout,
loadFloorTiles,
loadFurnitureAssets,
loadWallTiles,
sendAssetsToWebview,
sendCharacterSpritesToWebview,
sendFloorTilesToWebview,
sendWallTilesToWebview,
} from './assetLoader.js';
import {
GLOBAL_KEY_SOUND_ENABLED,
LAYOUT_REVISION_KEY,
WORKSPACE_KEY_AGENT_SEATS,
} from './constants.js';
import { ensureProjectScan } from './fileWatcher.js';
import type { LayoutWatcher } from './layoutPersistence.js';
import { readLayoutFromFile, watchLayoutFile, writeLayoutToFile } from './layoutPersistence.js';
import type { AgentState } from './types.js';
export class PixelAgentsViewProvider implements vscode.WebviewViewProvider {
nextAgentId = { current: 1 };
nextTerminalIndex = { current: 1 };
agents = new Map<number, AgentState>();
webviewView: vscode.WebviewView | undefined;
// Per-agent timers
fileWatchers = new Map<number, fs.FSWatcher>();
pollingTimers = new Map<number, ReturnType<typeof setInterval>>();
waitingTimers = new Map<number, ReturnType<typeof setTimeout>>();
jsonlPollTimers = new Map<number, ReturnType<typeof setInterval>>();
permissionTimers = new Map<number, ReturnType<typeof setTimeout>>();
// /clear detection: project-level scan for new JSONL files
activeAgentId = { current: null as number | null };
knownJsonlFiles = new Set<string>();
projectScanTimer = { current: null as ReturnType<typeof setInterval> | null };
// Bundled default layout (loaded from assets/default-layout.json)
defaultLayout: Record<string, unknown> | null = null;
// Cross-window layout sync
layoutWatcher: LayoutWatcher | null = null;
constructor(private readonly context: vscode.ExtensionContext) {}
private get extensionUri(): vscode.Uri {
return this.context.extensionUri;
}
private get webview(): vscode.Webview | undefined {
return this.webviewView?.webview;
}
private persistAgents = (): void => {
persistAgents(this.agents, this.context);
};
resolveWebviewView(webviewView: vscode.WebviewView) {
this.webviewView = webviewView;
webviewView.webview.options = { enableScripts: true };
webviewView.webview.html = getWebviewContent(webviewView.webview, this.extensionUri);
webviewView.webview.onDidReceiveMessage(async (message) => {
if (message.type === 'openAgent') {
await launchNewTerminal(
this.nextAgentId,
this.nextTerminalIndex,
this.agents,
this.activeAgentId,
this.knownJsonlFiles,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
this.jsonlPollTimers,
this.projectScanTimer,
this.webview,
this.persistAgents,
message.agentType as string,
message.folderPath as string | undefined,
);
} else if (message.type === 'focusAgent') {
const agent = this.agents.get(message.id);
if (agent) {
agent.terminalRef.show();
}
} else if (message.type === 'closeAgent') {
const agent = this.agents.get(message.id);
if (agent) {
agent.terminalRef.dispose();
}
} else if (message.type === 'saveAgentSeats') {
// Store seat assignments in a separate key (never touched by persistAgents)
console.log(`[Pixel Agents] saveAgentSeats:`, JSON.stringify(message.seats));
this.context.workspaceState.update(WORKSPACE_KEY_AGENT_SEATS, message.seats);
} else if (message.type === 'saveLayout') {
this.layoutWatcher?.markOwnWrite();
writeLayoutToFile(message.layout as Record<string, unknown>);
} else if (message.type === 'setSoundEnabled') {
this.context.globalState.update(GLOBAL_KEY_SOUND_ENABLED, message.enabled);
} else if (message.type === 'webviewReady') {
restoreAgents(
this.context,
this.nextAgentId,
this.nextTerminalIndex,
this.agents,
this.knownJsonlFiles,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
this.jsonlPollTimers,
this.projectScanTimer,
this.activeAgentId,
this.webview,
this.persistAgents,
);
// Send persisted settings to webview
const soundEnabled = this.context.globalState.get<boolean>(GLOBAL_KEY_SOUND_ENABLED, true);
this.webview?.postMessage({ type: 'settingsLoaded', soundEnabled });
// Send workspace folders to webview (only when multi-root)
const wsFolders = vscode.workspace.workspaceFolders;
if (wsFolders && wsFolders.length > 1) {
this.webview?.postMessage({
type: 'workspaceFolders',
folders: wsFolders.map((f) => ({ name: f.name, path: f.uri.fsPath })),
});
}
// Ensure project scan runs even with no restored agents (to adopt external terminals)
const projectDirs = getAllProjectDirPaths();
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
console.log('[Extension] workspaceRoot:', workspaceRoot);
console.log('[Extension] projectDirs:', projectDirs);
if (projectDirs.length > 0) {
ensureProjectScan(
projectDirs,
this.knownJsonlFiles,
this.projectScanTimer,
this.activeAgentId,
this.nextAgentId,
this.agents,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
this.webview,
this.persistAgents,
);
// Load furniture assets BEFORE sending layout
(async () => {
try {
console.log('[Extension] Loading furniture assets...');
const extensionPath = this.extensionUri.fsPath;
console.log('[Extension] extensionPath:', extensionPath);
// Check bundled location first: extensionPath/dist/assets/
const bundledAssetsDir = path.join(extensionPath, 'dist', 'assets');
let assetsRoot: string | null = null;
if (fs.existsSync(bundledAssetsDir)) {
console.log('[Extension] Found bundled assets at dist/');
assetsRoot = path.join(extensionPath, 'dist');
} else if (workspaceRoot) {
// Fall back to workspace root (development or external assets)
console.log('[Extension] Trying workspace for assets...');
assetsRoot = workspaceRoot;
}
if (!assetsRoot) {
console.log('[Extension] ⚠️ No assets directory found');
if (this.webview) {
sendLayout(this.context, this.webview, this.defaultLayout);
this.startLayoutWatcher();
}
return;
}
console.log('[Extension] Using assetsRoot:', assetsRoot);
// Load bundled default layout
this.defaultLayout = loadDefaultLayout(assetsRoot);
// Load character sprites
const charSprites = await loadCharacterSprites(assetsRoot);
if (charSprites && this.webview) {
console.log('[Extension] Character sprites loaded, sending to webview');
sendCharacterSpritesToWebview(this.webview, charSprites);
}
// Load floor tiles
const floorTiles = await loadFloorTiles(assetsRoot);
if (floorTiles && this.webview) {
console.log('[Extension] Floor tiles loaded, sending to webview');
sendFloorTilesToWebview(this.webview, floorTiles);
}
// Load wall tiles
const wallTiles = await loadWallTiles(assetsRoot);
if (wallTiles && this.webview) {
console.log('[Extension] Wall tiles loaded, sending to webview');
sendWallTilesToWebview(this.webview, wallTiles);
}
const assets = await loadFurnitureAssets(assetsRoot);
if (assets && this.webview) {
console.log('[Extension] ✅ Assets loaded, sending to webview');
sendAssetsToWebview(this.webview, assets);
}
} catch (err) {
console.error('[Extension] ❌ Error loading assets:', err);
}
// Always send saved layout (or null for default)
if (this.webview) {
console.log('[Extension] Sending saved layout');
sendLayout(this.context, this.webview, this.defaultLayout);
this.startLayoutWatcher();
}
})();
} else {
// No project dir — still try to load floor/wall tiles, then send saved layout
(async () => {
try {
const ep = this.extensionUri.fsPath;
const bundled = path.join(ep, 'dist', 'assets');
if (fs.existsSync(bundled)) {
const distRoot = path.join(ep, 'dist');
this.defaultLayout = loadDefaultLayout(distRoot);
const cs = await loadCharacterSprites(distRoot);
if (cs && this.webview) {
sendCharacterSpritesToWebview(this.webview, cs);
}
const ft = await loadFloorTiles(distRoot);
if (ft && this.webview) {
sendFloorTilesToWebview(this.webview, ft);
}
const wt = await loadWallTiles(distRoot);
if (wt && this.webview) {
sendWallTilesToWebview(this.webview, wt);
}
}
} catch {
/* ignore */
}
if (this.webview) {
sendLayout(this.context, this.webview, this.defaultLayout);
this.startLayoutWatcher();
}
})();
}
sendExistingAgents(this.agents, this.context, this.webview);
} else if (message.type === 'openSessionsFolder') {
const projectDir = getProjectDirPath('claude'); // Use claude as default
if (projectDir && fs.existsSync(projectDir)) {
vscode.env.openExternal(vscode.Uri.file(projectDir));
}
} else if (message.type === 'exportLayout') {
const layout = readLayoutFromFile();
if (!layout) {
vscode.window.showWarningMessage('Pixel Agents: No saved layout to export.');
return;
}
const uri = await vscode.window.showSaveDialog({
filters: { 'JSON Files': ['json'] },
defaultUri: vscode.Uri.file(path.join(os.homedir(), 'pixel-agents-layout.json')),
});
if (uri) {
fs.writeFileSync(uri.fsPath, JSON.stringify(layout, null, 2), 'utf-8');
vscode.window.showInformationMessage('Pixel Agents: Layout exported successfully.');
}
} else if (message.type === 'importLayout') {
const uris = await vscode.window.showOpenDialog({
filters: { 'JSON Files': ['json'] },
canSelectMany: false,
});
if (!uris || uris.length === 0) return;
try {
const raw = fs.readFileSync(uris[0].fsPath, 'utf-8');
const imported = JSON.parse(raw) as Record<string, unknown>;
if (imported.version !== 1 || !Array.isArray(imported.tiles)) {
vscode.window.showErrorMessage('Pixel Agents: Invalid layout file.');
return;
}
this.layoutWatcher?.markOwnWrite();
writeLayoutToFile(imported);
this.webview?.postMessage({ type: 'layoutLoaded', layout: imported });
vscode.window.showInformationMessage('Pixel Agents: Layout imported successfully.');
} catch {
vscode.window.showErrorMessage('Pixel Agents: Failed to read or parse layout file.');
}
}
});
vscode.window.onDidChangeActiveTerminal((terminal) => {
this.activeAgentId.current = null;
if (!terminal) return;
for (const [id, agent] of this.agents) {
if (agent.terminalRef === terminal) {
this.activeAgentId.current = id;
webviewView.webview.postMessage({ type: 'agentSelected', id });
break;
}
}
});
vscode.window.onDidCloseTerminal((closed) => {
for (const [id, agent] of this.agents) {
if (agent.terminalRef === closed) {
if (this.activeAgentId.current === id) {
this.activeAgentId.current = null;
}
removeAgent(
id,
this.agents,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
this.jsonlPollTimers,
this.persistAgents,
);
webviewView.webview.postMessage({ type: 'agentClosed', id });
}
}
});
}
/** Export current saved layout as a versioned default-layout-{N}.json (dev utility) */
exportDefaultLayout(): void {
const layout = readLayoutFromFile();
if (!layout) {
vscode.window.showWarningMessage('Pixel Agents: No saved layout found.');
return;
}
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
if (!workspaceRoot) {
vscode.window.showErrorMessage('Pixel Agents: No workspace folder found.');
return;
}
const assetsDir = path.join(workspaceRoot, 'webview-ui', 'public', 'assets');
// Find the next revision number
let maxRevision = 0;
if (fs.existsSync(assetsDir)) {
for (const file of fs.readdirSync(assetsDir)) {
const match = /^default-layout-(\d+)\.json$/.exec(file);
if (match) {
maxRevision = Math.max(maxRevision, parseInt(match[1], 10));
}
}
}
const nextRevision = maxRevision + 1;
layout[LAYOUT_REVISION_KEY] = nextRevision;
const targetPath = path.join(assetsDir, `default-layout-${nextRevision}.json`);
const json = JSON.stringify(layout, null, 2);
fs.writeFileSync(targetPath, json, 'utf-8');
vscode.window.showInformationMessage(
`Pixel Agents: Default layout exported as revision ${nextRevision} to ${targetPath}`,
);
}
private startLayoutWatcher(): void {
if (this.layoutWatcher) return;
this.layoutWatcher = watchLayoutFile((layout) => {
console.log('[Pixel Agents] External layout change — pushing to webview');
this.webview?.postMessage({ type: 'layoutLoaded', layout });
});
}
dispose() {
this.layoutWatcher?.dispose();
this.layoutWatcher = null;
for (const id of [...this.agents.keys()]) {
removeAgent(
id,
this.agents,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
this.jsonlPollTimers,
this.persistAgents,
);
}
if (this.projectScanTimer.current) {
clearInterval(this.projectScanTimer.current);
this.projectScanTimer.current = null;
}
}
}
export function getWebviewContent(webview: vscode.Webview, extensionUri: vscode.Uri): string {
const distPath = vscode.Uri.joinPath(extensionUri, 'dist', 'webview');
const indexPath = vscode.Uri.joinPath(distPath, 'index.html').fsPath;
let html = fs.readFileSync(indexPath, 'utf-8');
html = html.replace(/(href|src)="\.\/([^"]+)"/g, (_match, attr, filePath) => {
const fileUri = vscode.Uri.joinPath(distPath, filePath);
const webviewUri = webview.asWebviewUri(fileUri);
return `${attr}="${webviewUri}"`;
});
return html;
}