-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.mjs
More file actions
5646 lines (5270 loc) · 255 KB
/
Copy pathextension.mjs
File metadata and controls
5646 lines (5270 loc) · 255 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Extension: session-dashboard
// Multi-session monitor — shows status of all Copilot CLI sessions in a live browser dashboard
// Updated: 2026-05-12
import { createServer } from "node:http";
import { request as httpsRequest } from "node:https";
import { joinSession } from "@github/copilot-sdk/extension";
import { exec, spawn, execSync } from "node:child_process";
import { readdirSync, readFileSync, existsSync, statSync, writeFileSync, renameSync, mkdirSync, unlinkSync, rmSync, openSync, readSync, closeSync } from "node:fs";
import { join, basename } from "node:path";
import { homedir } from "node:os";
const SESSION_STATE_DIR = join(homedir(), ".copilot", "session-state");
const POLL_INTERVAL_MS = 3000;
const sseClients = new Set();
let serverPort = null;
let mainSession = null; // set after joinSession
const NOTES_FILE = join(homedir(), ".copilot", "session-dashboard-notes.json");
const WORKSPACE_FILE = join(homedir(), ".copilot", "saved-workspace.json");
const TODOS_FILE = join(homedir(), ".copilot", "session-dashboard-todos.json");
const CONFIG_FILE = join(homedir(), ".copilot", "session-dashboard-config.json");
let _configCache = null;
let _configCacheTime = 0;
const CONFIG_CACHE_TTL_MS = 30000; // 30 seconds
function loadDashboardConfig() {
const now = Date.now();
if (_configCache && (now - _configCacheTime) < CONFIG_CACHE_TTL_MS) {
return _configCache;
}
try {
if (existsSync(CONFIG_FILE)) {
_configCache = JSON.parse(readFileSync(CONFIG_FILE, "utf-8")) || {};
} else {
_configCache = {};
}
} catch {
_configCache = {};
}
_configCacheTime = now;
return _configCache;
}
function resolveUserAlias() {
// Priority: env var → config file → git user.email local part → "user"
const fromEnv = process.env.COPILOT_DASHBOARD_USER_ALIAS;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const cfg = loadDashboardConfig();
if (cfg.userAlias && typeof cfg.userAlias === "string" && cfg.userAlias.trim()) return cfg.userAlias.trim();
try {
const email = execSync("git config --global user.email", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
const local = email.split("@")[0];
if (local) return local;
} catch {}
return "user";
}
const USER_ALIAS = resolveUserAlias();
function resolveCopilotCommand() {
// Priority: env var → config file → default "copilot".
// Override this if you launch the Copilot CLI via a wrapper script (e.g.
// "agency copilot" on an internal Microsoft build).
const fromEnv = process.env.COPILOT_DASHBOARD_CLI_COMMAND;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const cfg = loadDashboardConfig();
if (cfg.copilotCommand && typeof cfg.copilotCommand === "string" && cfg.copilotCommand.trim()) {
return cfg.copilotCommand.trim();
}
return "copilot";
}
const COPILOT_CMD = resolveCopilotCommand();
const AUTO_SAVE_INTERVAL_MS = 60 * 1000; // 1 minute
const WORKSPACE_STARTUP_TIME = Date.now();
const WORKSPACE_STARTUP_GRACE_MS = 3 * 60 * 1000; // 3 min: refuse to shrink saved set during this window
const WORKSPACE_BACKUP_COUNT = 10; // keep N rolling snapshots (.1 = newest)
let lockTimer = null; // countdown timer for lock-after-dismiss
let screenBlankActive = false; // guard against double-spawning
let lockFlowActive = false; // guard against duplicate screen-dismissed calls
const LOCK_COUNTDOWN_SEC = 3;
const INTRUSION_FILE = join(homedir(), ".copilot", "session-dashboard-intrusion.json");
// --- Performance: HTML template cache (generated once, never changes) ---
const _htmlCache = {};
function cachedHtml(name, generator) {
if (!_htmlCache[name]) _htmlCache[name] = generator();
return _htmlCache[name];
}
// --- Performance: session scan cache ---
let _scanCache = null;
let _scanCacheTime = 0;
const SCAN_CACHE_TTL_MS = 2000; // 2 seconds
function getCachedSessions(forceRefresh = false) {
const now = Date.now();
if (!forceRefresh && _scanCache && (now - _scanCacheTime) < SCAN_CACHE_TTL_MS) {
return _scanCache;
}
_scanCache = _scanSessionsUncached();
_scanCacheTime = now;
return _scanCache;
}
function invalidateSessionCache() {
_scanCache = null;
_scanCacheTime = 0;
}
// Per-session events cache: avoids re-reading events.jsonl if mtime hasn't changed
const _sessionEventsCache = new Map(); // sessionId -> { mtimeMs, rawEvents, lastEvents, progressInfo }
function sendJson(res, data, statusCode = 200, extraHeaders = {}) {
const body = typeof data === "string" ? data : JSON.stringify(data);
res.writeHead(statusCode, {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
...extraHeaders,
});
res.end(body);
}
// --- Report generation (reads session history from disk on demand) ---
const REPORTS_DIR = join(homedir(), ".copilot", "activity", "reports");
function getISOWeek(date) {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
return { year: d.getUTCFullYear(), week: weekNo };
}
function getWeekBounds(year, week) {
const jan4 = new Date(Date.UTC(year, 0, 4));
const dayOfWeek = jan4.getUTCDay() || 7;
const mon = new Date(jan4);
mon.setUTCDate(jan4.getUTCDate() - dayOfWeek + 1 + (week - 1) * 7);
const sun = new Date(mon);
sun.setUTCDate(mon.getUTCDate() + 6);
sun.setUTCHours(23, 59, 59, 999);
return { start: mon, end: sun };
}
function getSessionsInRange(startDate, endDate) {
// Scan all sessions and filter by activity within the date range
if (!existsSync(SESSION_STATE_DIR)) return [];
const results = [];
let dirs;
try { dirs = readdirSync(SESSION_STATE_DIR); } catch { return []; }
for (const name of dirs) {
if (name === ".archive") continue;
const dir = join(SESSION_STATE_DIR, name);
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
const wsPath = join(dir, "workspace.yaml");
const eventsPath = join(dir, "events.jsonl");
let meta = {};
try { meta = parseYaml(readFileSync(wsPath, "utf-8")); } catch {}
const cwdVal = meta.cwd || "";
if (EXCLUDED_CWD_PATTERNS.some(p => p.test(cwdVal))) continue;
// Quick date check using metadata — skip sessions clearly outside range
const created = meta.created_at ? new Date(meta.created_at) : null;
const updated = meta.updated_at ? new Date(meta.updated_at) : null;
const createdInRange = created && created >= startDate && created <= endDate;
const updatedInRange = updated && updated >= startDate && updated <= endDate;
// If session was created after endDate or last updated before startDate, skip events scan
if (created && created > endDate && !updatedInRange) continue;
if (updated && updated < startDate && !createdInRange) continue;
// Also use file mtime as a cheap pre-check before reading the full events file
let eventsInRange = [];
let events = [];
try {
const evStat = statSync(eventsPath);
// If events file was last modified before the range start, no activity in range
if (evStat.mtime < startDate && !createdInRange && !updatedInRange) continue;
// Reuse per-session events cache if available and fresh
const cached = _sessionEventsCache.get(name);
let raw;
try {
const evMtime = statSync(eventsPath).mtimeMs;
if (cached && cached.mtimeMs === evMtime && cached.rawEvents) {
raw = cached.rawEvents;
} else {
raw = readFileSync(eventsPath, "utf-8");
}
} catch {
raw = readFileSync(eventsPath, "utf-8");
}
events = raw.trim().split("\n").map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
} catch {}
// Check if session had any activity in the date range
eventsInRange = events.filter(e => {
if (!e.timestamp) return false;
const t = new Date(e.timestamp);
return t >= startDate && t <= endDate;
});
if (eventsInRange.length === 0 && !createdInRange && !updatedInRange) continue;
// Count turns and tool calls from events in range
let turns = 0, toolCalls = 0, taskCompletes = 0, errors = 0;
for (const e of eventsInRange) {
if (e.type === "assistant.turn_end") turns++;
if (e.type === "tool.execution_start") toolCalls++;
if (e.type === "session.task_complete") taskCompletes++;
if (e.type === "session.error") errors++;
}
results.push({
id: name,
summary: meta.summary || "Untitled Session",
repository: meta.repository || "",
branch: meta.branch || "",
cwd: meta.cwd || "",
createdAt: meta.created_at || "",
turns, toolCalls, taskCompletes, errors,
});
}
return results.sort((a, b) => b.turns - a.turns);
}
function generateReport(startDate, endDate, type) {
const sessions = getSessionsInRange(startDate, endDate);
let totalTurns = 0, totalToolCalls = 0, totalTaskCompletes = 0;
const repoSet = new Set();
for (const s of sessions) {
totalTurns += s.turns;
totalToolCalls += s.toolCalls;
totalTaskCompletes += s.taskCompletes;
if (s.repository) repoSet.add(s.repository);
}
return {
type, generatedAt: new Date().toISOString(),
startDate: startDate.toISOString().slice(0, 10),
endDate: endDate.toISOString().slice(0, 10),
sessionCount: sessions.length,
totalTurns, totalToolCalls, totalTaskCompletes,
repositories: [...repoSet],
sessions,
};
}
function checkAndGenerateReports() {
try {
try { mkdirSync(REPORTS_DIR, { recursive: true }); } catch {}
const now = new Date();
// Generate missing weekly reports for completed weeks
for (let i = 1; i <= 12; i++) {
const pastDate = new Date(now);
pastDate.setDate(pastDate.getDate() - i * 7);
const { year, week } = getISOWeek(pastDate);
const wk = String(week).padStart(2, "0");
const reportPath = join(REPORTS_DIR, `weekly-${year}-W${wk}.json`);
if (existsSync(reportPath)) continue;
const { start, end } = getWeekBounds(year, week);
if (end >= now) continue;
const report = generateReport(start, end, "weekly");
if (report.sessionCount === 0) continue;
report.label = `Week ${week}, ${year}`;
const tmp = reportPath + ".tmp";
writeFileSync(tmp, JSON.stringify(report, null, 2));
renameSync(tmp, reportPath);
}
// Generate missing monthly reports for completed months
for (let i = 1; i <= 6; i++) {
const pastDate = new Date(now.getFullYear(), now.getMonth() - i, 1);
const ym = pastDate.toISOString().slice(0, 7);
const reportPath = join(REPORTS_DIR, `monthly-${ym}.json`);
if (existsSync(reportPath)) continue;
const monthStart = new Date(Date.UTC(pastDate.getFullYear(), pastDate.getMonth(), 1));
const monthEnd = new Date(Date.UTC(pastDate.getFullYear(), pastDate.getMonth() + 1, 0, 23, 59, 59, 999));
if (monthEnd >= now) continue;
const report = generateReport(monthStart, monthEnd, "monthly");
if (report.sessionCount === 0) continue;
const monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
report.label = `${monthNames[pastDate.getMonth()]} ${pastDate.getFullYear()}`;
const tmp = reportPath + ".tmp";
writeFileSync(tmp, JSON.stringify(report, null, 2));
renameSync(tmp, reportPath);
}
} catch {}
invalidateReportsCache();
}// In-memory cache for reports (invalidated on generation)
let reportsCache = null;
let reportsCacheTime = 0;
const REPORTS_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
function listReports() {
const now = Date.now();
if (reportsCache && (now - reportsCacheTime) < REPORTS_CACHE_TTL_MS) return reportsCache;
const reports = { weekly: [], monthly: [], range: [] };
try {
if (!existsSync(REPORTS_DIR)) return reports;
const files = readdirSync(REPORTS_DIR).sort().reverse();
for (const f of files) {
if (!f.endsWith(".json")) continue;
try {
const data = JSON.parse(readFileSync(join(REPORTS_DIR, f), "utf-8"));
if (f.startsWith("weekly-")) reports.weekly.push(data);
else if (f.startsWith("monthly-")) reports.monthly.push(data);
else if (f.startsWith("range-")) reports.range.push(data);
} catch {}
}
} catch {}
reportsCache = reports;
reportsCacheTime = now;
return reports;
}
function invalidateReportsCache() { reportsCache = null; reportsCacheTime = 0; }
function generateAndSaveSingleReport(type, startDateStr, endDateStr, label) {
try { mkdirSync(REPORTS_DIR, { recursive: true }); } catch {}
const startDate = new Date(startDateStr + "T00:00:00.000Z");
const endDate = new Date(endDateStr + "T23:59:59.999Z");
if (isNaN(startDate.getTime()) || isNaN(endDate.getTime()) || startDate > endDate) return { error: "Invalid date range" };
if (!["weekly", "monthly"].includes(type)) return { error: "Invalid type" };
const report = generateReport(startDate, endDate, type);
report.label = label || (type === "weekly" ? "Week Report" : "Month Report");
// Determine canonical filename
let filename;
if (type === "weekly") {
const { year, week } = getISOWeek(startDate);
filename = "weekly-" + year + "-W" + String(week).padStart(2, "0") + ".json";
} else {
filename = "monthly-" + startDateStr.slice(0, 7) + ".json";
}
const reportPath = join(REPORTS_DIR, filename);
const tmp = reportPath + "." + Date.now() + ".tmp";
writeFileSync(tmp, JSON.stringify(report, null, 2));
renameSync(tmp, reportPath);
invalidateReportsCache();
return report;
}
function generateRangeReport(startDateStr, endDateStr) {
try { mkdirSync(REPORTS_DIR, { recursive: true }); } catch {}
const startDate = new Date(startDateStr + "T00:00:00.000Z");
const endDate = new Date(endDateStr + "T23:59:59.999Z");
if (isNaN(startDate.getTime()) || isNaN(endDate.getTime()) || startDate > endDate) return { error: "Invalid date range" };
// Pre-generate any missing weekly/monthly reports that overlap this range
const now = new Date();
// Weekly: walk through weeks that overlap the range
const cursor = new Date(startDate);
while (cursor <= endDate) {
const { year, week } = getISOWeek(cursor);
const wk = String(week).padStart(2, "0");
const reportPath = join(REPORTS_DIR, "weekly-" + year + "-W" + wk + ".json");
if (!existsSync(reportPath)) {
const { start, end } = getWeekBounds(year, week);
if (end < now) {
const wr = generateReport(start, end, "weekly");
if (wr.sessionCount > 0) {
wr.label = "Week " + week + ", " + year;
const tmp = reportPath + "." + Date.now() + ".tmp";
writeFileSync(tmp, JSON.stringify(wr, null, 2));
renameSync(tmp, reportPath);
}
}
}
cursor.setDate(cursor.getDate() + 7);
}
// Monthly: walk through months that overlap the range
let mCursor = new Date(Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth(), 1));
while (mCursor <= endDate) {
const ym = mCursor.toISOString().slice(0, 7);
const reportPath = join(REPORTS_DIR, "monthly-" + ym + ".json");
if (!existsSync(reportPath)) {
const mStart = new Date(Date.UTC(mCursor.getUTCFullYear(), mCursor.getUTCMonth(), 1));
const mEnd = new Date(Date.UTC(mCursor.getUTCFullYear(), mCursor.getUTCMonth() + 1, 0, 23, 59, 59, 999));
if (mEnd < now) {
const mr = generateReport(mStart, mEnd, "monthly");
if (mr.sessionCount > 0) {
const monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
mr.label = monthNames[mCursor.getUTCMonth()] + " " + mCursor.getUTCFullYear();
const tmp = reportPath + "." + Date.now() + ".tmp";
writeFileSync(tmp, JSON.stringify(mr, null, 2));
renameSync(tmp, reportPath);
}
}
}
mCursor.setUTCMonth(mCursor.getUTCMonth() + 1);
}
// Generate the range report from raw session data for exact accuracy
const report = generateReport(startDate, endDate, "range");
report.label = "Range: " + startDateStr + " → " + endDateStr;
// Save to disk
const filename = "range-" + startDateStr + "_" + endDateStr + ".json";
const reportPath = join(REPORTS_DIR, filename);
const tmp = reportPath + "." + Date.now() + ".tmp";
writeFileSync(tmp, JSON.stringify(report, null, 2));
renameSync(tmp, reportPath);
invalidateReportsCache();
return report;
}
async function generateAISummary(report) {
// A session is "meaningful" if it has real activity. Sessions that never
// got a human-readable title (summary === "Untitled Session") can still
// be meaningful — week 20/2026, for example, has 27 such sessions with
// hundreds of turns each. We fall back to branch/cwd to label them for
// the LLM.
const meaningfulSessions = (report.sessions || []).filter(s => {
if ((s.turns || 0) === 0 && (s.toolCalls || 0) === 0) return false;
if (!s.summary && !s.branch && !s.cwd) return false;
return true;
});
if (meaningfulSessions.length === 0) return { error: "No meaningful sessions to summarize" };
// Build a concise context from the report data
const repoGroups = {};
for (const s of meaningfulSessions) {
const repo = s.repository || s.cwd || "Other";
if (!repoGroups[repo]) repoGroups[repo] = [];
let label = (s.summary && s.summary !== "Untitled Session") ? s.summary : null;
if (!label && s.branch) label = `(branch: ${s.branch})`;
if (!label) label = "untitled session";
label += ` [${s.turns || 0} turns, ${s.toolCalls || 0} tools]`;
repoGroups[repo].push(label);
}
const totalTurns = meaningfulSessions.reduce((a, s) => a + (s.turns || 0), 0);
const totalTools = meaningfulSessions.reduce((a, s) => a + (s.toolCalls || 0), 0);
const totalCompleted = meaningfulSessions.reduce((a, s) => a + (s.taskCompletes || 0), 0);
let context = `Period: ${report.startDate} to ${report.endDate}\n`;
context += `Stats: ${meaningfulSessions.length} sessions, ${totalTurns} turns, ${totalTools} tool calls, ${totalCompleted} tasks completed\n`;
context += `Repositories: ${(report.repositories || []).join(", ")}\n\n`;
context += "Sessions by repository (some sessions have no title — branch name is shown instead):\n";
for (const [repo, summaries] of Object.entries(repoGroups)) {
const shortName = repo.replace(/\\/g, "/").split("/").slice(-2).join("/");
context += `\n${shortName}:\n`;
for (const s of summaries) context += ` - ${s}\n`;
}
const systemPrompt = "You write concise activity report summaries for software developers. Write in first person. Focus on key themes, major features/fixes, and which areas saw the most activity. Be specific based on session names. No bullet points — flowing paragraphs only. No markdown headers.";
const userPrompt = `Based on the following coding session data, write 2-3 concise paragraphs summarizing what was accomplished:\n\n${context}`;
const result = await callCopilotChat(systemPrompt, userPrompt, { model: "gpt-4.1", maxTokens: 1000 });
if (result.error) return { error: result.error };
return { summary: result.content };
}
function findReportFile(type, startDate, endDate) {
if (!existsSync(REPORTS_DIR)) return null;
const files = readdirSync(REPORTS_DIR);
for (const f of files) {
if (!f.endsWith(".json")) continue;
try {
const data = JSON.parse(readFileSync(join(REPORTS_DIR, f), "utf-8"));
if (data.type === type && data.startDate === startDate && data.endDate === endDate) {
return { path: join(REPORTS_DIR, f), data };
}
} catch {}
}
return null;
}
async function autoGenerateAISummaries() {
if (!existsSync(REPORTS_DIR)) return;
const now = new Date();
const files = readdirSync(REPORTS_DIR).sort();
for (const f of files) {
if (!f.endsWith(".json")) continue;
// Only process completed period reports (weekly/monthly), not range reports
if (!f.startsWith("weekly-") && !f.startsWith("monthly-")) continue;
const filePath = join(REPORTS_DIR, f);
let data;
try { data = JSON.parse(readFileSync(filePath, "utf-8")); } catch { continue; }
// Skip if already has AI summary
if (data.aiSummary) continue;
// Skip if no sessions (nothing to summarize)
if (!data.sessionCount || data.sessionCount === 0) continue;
// Skip if no meaningful sessions (only untitled/empty ones)
const meaningful = (data.sessions || []).filter(s =>
s.summary && s.summary !== "Untitled Session" && ((s.turns || 0) > 0 || (s.toolCalls || 0) > 0));
if (meaningful.length === 0) continue;
// Skip if zero total activity
if ((data.totalTurns || 0) === 0 && (data.totalToolCalls || 0) === 0) continue;
// Skip if the period hasn't completed yet (endDate is in the future)
if (data.endDate) {
const endDate = new Date(data.endDate + "T23:59:59.999Z");
if (endDate >= now) continue;
}
// Generate AI summary
try {
const result = await generateAISummary(data);
if (result.summary) {
data.aiSummary = result.summary;
data.aiSummaryGeneratedAt = new Date().toISOString();
const tmp = filePath + "." + Date.now() + ".tmp";
writeFileSync(tmp, JSON.stringify(data, null, 2));
renameSync(tmp, filePath);
invalidateReportsCache();
}
} catch {}
}
}
// --- Warm PowerShell process for fast tab focusing ---
// Pre-loads UIAutomation assemblies so focus commands execute in ~100ms instead of ~1s
let focusWorker = null;
let focusWorkerReady = false;
const focusQueue = []; // callbacks waiting for worker readiness
const focusResultQueue = []; // callbacks waiting for RESULT: lines
function startFocusWorker() {
const initScript = `
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class FocusHelper {
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
function Do-Focus($title, $altTitle, $cwd) {
$cwdLeaf = if ($cwd) { Split-Path $cwd -Leaf } else { "" }
$root = [System.Windows.Automation.AutomationElement]::RootElement
$wtCond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ClassNameProperty, 'CASCADIA_HOSTING_WINDOW_CLASS')
$wts = $root.FindAll([System.Windows.Automation.TreeScope]::Children, $wtCond)
if ($wts.Count -eq 0) { return "NO_WT" }
foreach ($wt in $wts) {
$tabCond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, [System.Windows.Automation.ControlType]::TabItem)
$tabs = $wt.FindAll([System.Windows.Automation.TreeScope]::Descendants, $tabCond)
$i = 0
foreach ($tab in $tabs) {
$i++
$n = $tab.Current.Name
$matched = $false
if ($title -and $n -like "*$title*") { $matched = $true }
elseif ($altTitle -and $n -like "*$altTitle*") { $matched = $true }
elseif ($cwdLeaf -and $n -like "*$cwdLeaf*") { $matched = $true }
if ($matched) {
$h = $wt.Current.NativeWindowHandle
if ($h -ne 0) { [FocusHelper]::SetForegroundWindow([IntPtr]::new($h)) | Out-Null }
try { $tab.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Select(); return "SELECTED_TAB:$i" } catch {}
try { $tab.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke(); return "INVOKED_TAB:$i" } catch {}
}
}
}
$h = $wts[0].Current.NativeWindowHandle
if ($h -ne 0) { [FocusHelper]::SetForegroundWindow([IntPtr]::new($h)) | Out-Null }
return "FOCUSED_WINDOW"
}
Write-Host "READY"
while ($true) {
$line = [Console]::ReadLine()
if ($null -eq $line) { break }
try {
$cmd = $line | ConvertFrom-Json
$result = Do-Focus $cmd.title $cmd.altTitle $cmd.cwd
Write-Host "RESULT:$result"
} catch {
Write-Host "RESULT:ERROR"
}
}
`.replace(/\r?\n/g, "\n");
focusWorker = spawn("powershell", ["-NoProfile", "-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", "-"], {
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
});
focusWorker.stdin.write(initScript + "\n");
let buffer = "";
focusWorker.stdout.on("data", (chunk) => {
buffer += chunk.toString();
const lines = buffer.split("\n");
buffer = lines.pop(); // keep incomplete line
for (const line of lines) {
const trimmed = line.trim();
if (trimmed === "READY" && !focusWorkerReady) {
focusWorkerReady = true;
for (const cb of focusQueue) cb();
focusQueue.length = 0;
} else if (trimmed.startsWith("RESULT:")) {
const result = trimmed.slice(7);
const cb = focusResultQueue.shift();
if (cb) cb(result);
}
}
});
focusWorker.on("exit", () => {
focusWorker = null;
focusWorkerReady = false;
// Restart after a delay
setTimeout(startFocusWorker, 2000);
});
}
function sendFocusCommand(title, altTitle, cwd, onResult) {
const doSend = () => {
if (focusWorker && focusWorker.stdin.writable) {
const cmd = JSON.stringify({ title: title || "", altTitle: altTitle || "", cwd: cwd || "" });
if (onResult) focusResultQueue.push(onResult);
focusWorker.stdin.write(cmd + "\n");
} else if (onResult) {
onResult("ERROR");
}
};
if (focusWorkerReady) {
doSend();
} else {
focusQueue.push(doSend);
}
}
startFocusWorker();
// Fixed port: persist across restarts so the URL doesn't change
const PORT_FILE = join(homedir(), ".copilot", "session-dashboard-port");
const PREFERRED_PORT = (() => {
try { if (existsSync(PORT_FILE)) return Number(readFileSync(PORT_FILE, "utf-8").trim()); } catch {}
return 0; // fallback: let OS pick, then save it
})();
// Directories to exclude from session scanning
const EXCLUDED_CWD_PATTERNS = [
/Documents[\\/]Clawpilot/i,
];
// --- Session scanning ---
function parseYaml(text) {
// Minimal YAML parser for flat key: value files
const obj = {};
for (const line of text.split("\n")) {
const m = line.match(/^(\w[\w_]*)\s*:\s*(.*)$/);
if (m) obj[m[1]] = m[2].trim();
}
return obj;
}
// Cache process-alive checks per scan cycle (cleared every 2s with session cache)
let _pidAliveCache = new Map();
let _pidAliveCacheTime = 0;
function isProcessAlive(pid) {
const now = Date.now();
if (now - _pidAliveCacheTime > 2000) {
_pidAliveCache.clear();
_pidAliveCacheTime = now;
}
const key = Number(pid);
if (_pidAliveCache.has(key)) return _pidAliveCache.get(key);
let alive;
try { process.kill(key, 0); alive = true; } catch { alive = false; }
_pidAliveCache.set(key, alive);
return alive;
}
function deriveStatus(lastEvents, lockPid, isAlive) {
if (!isAlive) return { status: "inactive", label: "Inactive", icon: "⏹️" };
// Check if session is stale — alive process but no recent events (10+ min)
const STALE_THRESHOLD_MS = 10 * 60 * 1000;
if (lastEvents.length > 0) {
const lastTs = lastEvents[lastEvents.length - 1]?.timestamp;
if (lastTs && (Date.now() - new Date(lastTs).getTime()) > STALE_THRESHOLD_MS) {
return { status: "idle", label: "Stale — no activity for 10+ min", icon: "💤" };
}
}
// Determine if we're mid-turn: find the last turn_start and turn_end
let lastTurnStartIdx = -1;
let lastTurnEndIdx = -1;
for (let i = lastEvents.length - 1; i >= 0; i--) {
if (lastTurnStartIdx === -1 && lastEvents[i]?.type === "assistant.turn_start") lastTurnStartIdx = i;
if (lastTurnEndIdx === -1 && lastEvents[i]?.type === "assistant.turn_end") lastTurnEndIdx = i;
if (lastTurnStartIdx !== -1 && lastTurnEndIdx !== -1) break;
}
const midTurn = lastTurnStartIdx > lastTurnEndIdx;
// If mid-turn, the session is working — find the best label from recent events
if (midTurn) {
// Check for pending ask_user/permission tool (started but not yet completed)
const completedToolIds = {};
for (let i = lastEvents.length - 1; i >= 0; i--) {
const ev = lastEvents[i];
if (!ev || !ev.type) continue;
if (ev.type === "tool.execution_complete" && ev.data && ev.data.toolCallId) {
completedToolIds[ev.data.toolCallId] = true;
}
if (ev.type === "tool.execution_start" && ev.data && ev.data.toolCallId) {
if (!completedToolIds[ev.data.toolCallId]) {
const tn = ev.data.toolName || "";
if (tn === "ask_user") return { status: "waiting", label: "Waiting for Input", icon: "❓" };
}
}
}
for (let i = lastEvents.length - 1; i >= 0; i--) {
const ev = lastEvents[i];
if (!ev?.type) continue;
if (ev.type === "permission.requested") return { status: "waiting", label: "Waiting for Permission", icon: "🔐" };
if (ev.type === "elicitation.requested") return { status: "waiting", label: "Waiting for Input", icon: "❓" };
if (ev.type === "tool.execution_start") return { status: "working", label: "Running: " + (ev.data?.toolName || "tool"), icon: "⚙️" };
if (ev.type === "assistant.streaming_delta") return { status: "working", label: "Streaming Response", icon: "✍️" };
if (ev.type === "tool.execution_complete") return { status: "working", label: "Processing", icon: "🤖" };
if (ev.type === "assistant.message") return { status: "working", label: "Thinking", icon: "🤖" };
if (ev.type === "session.info") return { status: "working", label: "Processing", icon: "🤖" };
if (ev.type === "hook.start" || ev.type === "hook.end") continue;
}
return { status: "working", label: "Working", icon: "🤖" };
}
// Not mid-turn — check the last meaningful event
for (let i = lastEvents.length - 1; i >= 0; i--) {
const ev = lastEvents[i];
if (!ev?.type) continue;
if (ev.type === "session.task_complete") return { status: "completed", label: "Task Complete", icon: "✅" };
if (ev.type === "permission.requested") return { status: "waiting", label: "Waiting for Permission", icon: "🔐" };
if (ev.type === "elicitation.requested") return { status: "waiting", label: "Waiting for Input", icon: "❓" };
if (ev.type === "session.idle") return { status: "idle", label: "Idle", icon: "😴" };
if (ev.type === "session.error") return { status: "error", label: "Error", icon: "🔥" };
if (ev.type === "assistant.turn_end") {
// Check if this turn wrote/created plan.md → "Plan Ready for Review"
// or if the assistant's last message asks for user input (ends with ?)
let wrotePlan = false;
let lastAssistContent = "";
let askedQuestion = false;
for (let j = i - 1; j >= 0 && j >= i - 40; j--) {
const prev = lastEvents[j];
if (!prev?.type) continue;
// Stop scanning at the previous turn boundary
if (prev.type === "assistant.turn_start" || prev.type === "assistant.turn_end") break;
// Detect plan.md creation or edit
if ((prev.type === "tool.execution_start") && prev.data) {
const tn = prev.data.toolName || "";
const args = prev.data.arguments || {};
const filePath = args.path || args.file_path || "";
if ((tn === "create" || tn === "edit") && /plan\.md$/i.test(filePath)) {
wrotePlan = true;
}
}
// Capture last assistant message content
if (prev.type === "assistant.message" && prev.data?.content && !lastAssistContent) {
lastAssistContent = prev.data.content;
}
}
// Check if the assistant's message asks the user something
if (lastAssistContent) {
const trimmed = lastAssistContent.trim();
// Ends with a question mark, or contains common "waiting for you" phrases
if (/\?\s*$/.test(trimmed)) askedQuestion = true;
if (/\b(let me know|please (confirm|review|choose|decide|approve)|ready to proceed|what do you think|would you like|shall I)\b/i.test(trimmed)) askedQuestion = true;
}
if (wrotePlan) return { status: "waiting", label: "Plan Ready for Review", icon: "📋" };
if (askedQuestion) return { status: "waiting", label: "Waiting for Response", icon: "💬" };
return { status: "idle", label: "Turn Complete", icon: "😴" };
}
if (ev.type === "user.message") return { status: "working", label: "Processing Message", icon: "🤖" };
}
return { status: "active", label: "Active", icon: "🟢" };
}
function getProgressSummary(dir, eventsPath, preReadRaw) {
// 1. Read plan.md
let planContent = "";
let planGoal = "";
let planApproach = "";
try {
const planPath = join(dir, "plan.md");
if (existsSync(planPath)) {
planContent = readFileSync(planPath, "utf-8");
const lines = planContent.split("\n");
// Extract goal from first heading
const heading = lines.find(l => /^#+\s/.test(l));
if (heading) planGoal = heading.replace(/^#+\s*/, "").trim();
// Extract approach/problem section
for (let i = 0; i < lines.length && i < 30; i++) {
if (/^##\s*(Problem|Approach|Overview)/i.test(lines[i])) {
const nextLines = [];
for (let j = i + 1; j < lines.length && j < i + 5; j++) {
if (/^##/.test(lines[j])) break;
if (lines[j].trim()) nextLines.push(lines[j].trim());
}
if (nextLines.length) planApproach = nextLines.join(" ").slice(0, 200);
break;
}
}
}
} catch {}
// 2. Count events and extract recent conversation
let userMsgs = 0, assistMsgs = 0, toolCalls = 0, taskCompletes = 0;
let errors = 0, permissionRequests = 0;
let firstEventTime = null, lastEventTime = null;
let recentConversation = "";
let firstUserMsg = "";
let lastAssistMsg = "";
let latestIntent = "";
let lastTurnEndLine = -1, lastUserMsgLine = -1;
try {
let raw;
if (preReadRaw) {
raw = preReadRaw;
} else {
// For large files, only read the tail to avoid I/O bottlenecks
const TAIL_BYTES = 256 * 1024;
try {
const st = statSync(eventsPath);
if (st.size > TAIL_BYTES) {
const fd = openSync(eventsPath, "r");
try {
const buf = Buffer.alloc(TAIL_BYTES);
readSync(fd, buf, 0, TAIL_BYTES, st.size - TAIL_BYTES);
raw = buf.toString("utf-8");
} finally {
closeSync(fd);
}
// Strip partial first line
const nlIdx = raw.indexOf("\n");
if (nlIdx > 0) raw = raw.slice(nlIdx + 1);
} else {
raw = readFileSync(eventsPath, "utf-8");
}
} catch {
raw = readFileSync(eventsPath, "utf-8");
}
}
const lines = raw.trim().split("\n");
for (let li = 0; li < lines.length; li++) {
const line = lines[li];
if (line.includes('"user.message"')) { userMsgs++; lastUserMsgLine = li; }
if (line.includes('"assistant.message"')) assistMsgs++;
if (line.includes('"tool.execution_start"')) {
toolCalls++;
if (line.includes('"report_intent"')) {
try {
const ev = JSON.parse(line);
const intent = ev.data?.arguments?.intent;
if (intent) latestIntent = intent;
} catch {}
}
}
if (line.includes('"session.task_complete"')) { taskCompletes++; lastTurnEndLine = li; }
if (line.includes('"assistant.turn_end"')) lastTurnEndLine = li;
if (line.includes('"session.error"')) errors++;
if (line.includes('"permission.requested"')) permissionRequests++;
}
// Extract first/last event timestamps for duration
if (lines.length > 0) {
try { const ev = JSON.parse(lines[0]); if (ev.timestamp) firstEventTime = ev.timestamp; } catch {}
try { const ev = JSON.parse(lines[lines.length - 1]); if (ev.timestamp) lastEventTime = ev.timestamp; } catch {}
}
// First user message = original request/goal
for (const line of lines) {
if (line.includes('"user.message"')) {
try {
const ev = JSON.parse(line);
firstUserMsg = (ev.data?.content || "").slice(0, 300);
} catch {}
break;
}
}
// Last assistant message = current state
for (let i = lines.length - 1; i >= 0; i--) {
if (lines[i].includes('"assistant.message"')) {
try {
const ev = JSON.parse(lines[i]);
lastAssistMsg = (ev.data?.content || "").slice(0, 400);
} catch {}
break;
}
}
// Extract last few user + assistant messages for context
const convLines = [];
for (let i = lines.length - 1; i >= 0 && convLines.length < 6; i--) {
try {
if (lines[i].includes('"user.message"')) {
const ev = JSON.parse(lines[i]);
const txt = (ev.data?.content || "").slice(0, 300);
if (txt) convLines.unshift(`User: ${txt}`);
} else if (lines[i].includes('"assistant.message"')) {
const ev = JSON.parse(lines[i]);
const txt = (ev.data?.content || "").slice(0, 300);
if (txt) convLines.unshift(`Assistant: ${txt}`);
}
} catch {}
}
recentConversation = convLines.join("\n");
} catch {}
// 3. Build structured Goal/Stage/Progress
let goal = "";
if (planGoal) {
// Strip common prefixes like "Plan: ..."
goal = planGoal.replace(/^Plan:\s*/i, "").trim();
}
if (!goal && firstUserMsg) {
// Use first user message as goal (first sentence)
goal = firstUserMsg.split(/[.!?\n]/)[0]?.trim() || firstUserMsg.slice(0, 120);
}
let stage = "";
if (taskCompletes > 0 && userMsgs <= taskCompletes + 1) {
stage = "Complete";
} else if (planContent && toolCalls === 0) {
stage = "Planning";
} else if (toolCalls > 0 && taskCompletes === 0 && userMsgs <= 2) {
stage = "Implementing initial request";
} else if (toolCalls > 0 && taskCompletes === 0) {
stage = "Iterating (" + userMsgs + " exchanges)";
} else if (taskCompletes > 0 && userMsgs > taskCompletes + 1) {
stage = "Working on follow-up #" + (taskCompletes + 1);
}
let progressNote = "";
if (planApproach) {
progressNote = planApproach;
} else if (lastAssistMsg) {
// Extract first meaningful sentence from last assistant response
const sentences = lastAssistMsg.split(/(?<=[.!?])\s+/);
const meaningful = sentences.find(s => s.length > 15 && !s.startsWith("I ") && !s.startsWith("Let me"));
progressNote = meaningful?.slice(0, 150) || sentences[0]?.slice(0, 150) || "";
}
// Unseen = turn ended (or task completed) after the last user message
const unseen = lastTurnEndLine > lastUserMsgLine && lastTurnEndLine >= 0;
return {
goal,
stage,
progressNote,
planContent,
recentConversation,
latestIntent,
unseen,
turns: userMsgs,
toolCalls,
taskCompletes,
errors,
permissionRequests,
firstEventTime,
lastEventTime,
};
}
function _scanSessionsUncached() {
const results = [];
if (!existsSync(SESSION_STATE_DIR)) return results;
let dirs;
try { dirs = readdirSync(SESSION_STATE_DIR); } catch { return results; }
for (const name of dirs) {
if (name === ".archive") continue;
const dir = join(SESSION_STATE_DIR, name);
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
const wsPath = join(dir, "workspace.yaml");
const eventsPath = join(dir, "events.jsonl");
// Parse workspace.yaml
let meta = {};
try { meta = parseYaml(readFileSync(wsPath, "utf-8")); } catch {}
// Skip sessions in excluded directories
const cwdVal = meta.cwd || "";
if (EXCLUDED_CWD_PATTERNS.some(p => p.test(cwdVal))) continue;
// Check lock files — session is alive if ANY lock PID is alive
let lockPid = null;
let isAlive = false;
try {
const files = readdirSync(dir);
const locks = files.filter(f => f.startsWith("inuse.") && f.endsWith(".lock"));
for (const lock of locks) {
const pid = lock.replace("inuse.", "").replace(".lock", "");
if (isProcessAlive(pid)) {
lockPid = pid;
isAlive = true;
break;
}
}
if (!lockPid && locks.length > 0) {
lockPid = locks[0].replace("inuse.", "").replace(".lock", "");
}