-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworkspaces.py
More file actions
1439 lines (1274 loc) · 63.5 KB
/
Copy pathworkspaces.py
File metadata and controls
1439 lines (1274 loc) · 63.5 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
"""
API routes for workspaces — mirrors:
src/app/api/workspaces/route.ts GET /api/workspaces
src/app/api/workspaces/[id]/route.ts GET /api/workspaces/<id>
src/app/api/workspaces/[id]/tabs/route.ts GET /api/workspaces/<id>/tabs
"""
from __future__ import annotations
import json
import logging
import os
import re
import sqlite3
from pathlib import Path
import sys
from contextlib import closing, contextmanager
from datetime import datetime, timezone
from urllib.parse import unquote, urlparse
from flask import Blueprint, current_app, jsonify
from utils.workspace_path import resolve_workspace_path, get_cli_chats_path
from utils.cli_chat_reader import (
list_cli_projects,
traverse_blobs,
messages_to_bubbles,
)
from utils.path_helpers import (
normalize_file_path,
get_workspace_folder_paths,
get_workspace_display_name,
to_epoch_ms,
)
from utils.text_extract import extract_text_from_bubble, format_tool_action
from utils.tool_parser import parse_tool_call as _parse_tool_call
from utils.exclusion_rules import build_searchable_text, is_excluded_by_rules
from models import Bubble, Composer, SchemaError, Workspace
bp = Blueprint("workspaces", __name__)
_logger = logging.getLogger(__name__)
def _get_workspace_display_name(workspace_path: str, workspace_id: str) -> str:
"""
Return a human-readable display name for a workspace.
Reads the workspace's ``workspace.json`` to extract the last path segment
of the first configured folder, URL-decodes it, and returns it. Falls back
to ``"Other chats"`` for the virtual ``"global"`` workspace and to
*workspace_id* if the JSON cannot be read.
"""
if workspace_id == "global":
return "Other chats"
wj_path = os.path.join(workspace_path, workspace_id, "workspace.json")
try:
workspace = Workspace.from_dict(_read_json_file(wj_path), workspace_id=workspace_id)
name = get_workspace_display_name(workspace.raw)
if name:
return name
except (SchemaError, OSError, ValueError):
pass
return workspace_id
# ---------------------------------------------------------------------------
# Shared helpers (duplicated in tabs route in the Node.js project)
# ---------------------------------------------------------------------------
def _read_json_file(path: str):
return _resolve_workspace_descriptor(path)
def _uri_or_path_to_fs_path(value: str, base_dir: str | None = None) -> str:
"""Convert a file URI or plain path to a filesystem path."""
raw = (value or "").strip()
if not raw:
return ""
if raw.startswith("file://"):
parsed = urlparse(raw)
path = unquote(parsed.path or "")
if sys.platform == "win32" and path.startswith("/") and len(path) > 2 and path[2] == ":":
path = path[1:]
return os.path.normpath(path)
expanded = os.path.expanduser(raw)
if base_dir and not os.path.isabs(expanded):
expanded = os.path.join(base_dir, expanded)
return os.path.normpath(expanded)
def _resolve_workspace_descriptor(path: str, depth: int = 0):
"""
Read and normalize a workspace descriptor.
Handles indirection via {"workspace": "<uri|path>"} and resolves relative
folder paths in multi-root workspace files against the file's directory.
"""
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
# Cursor workspaceStorage entry may point to an external workspace file.
if (
isinstance(data, dict)
and data.get("workspace")
and not data.get("folder")
and not data.get("folders")
and depth < 3
):
target = _uri_or_path_to_fs_path(str(data.get("workspace", "")), base_dir=os.path.dirname(path))
if target and os.path.isfile(target):
return _resolve_workspace_descriptor(target, depth + 1)
if not isinstance(data, dict):
return data
out = dict(data)
base_dir = os.path.dirname(path)
folders = out.get("folders")
if isinstance(folders, list):
normalized = []
for folder in folders:
if isinstance(folder, dict):
fd = dict(folder)
p = fd.get("path")
if isinstance(p, str) and p:
if not p.startswith("file://") and not os.path.isabs(p):
fd["path"] = os.path.normpath(os.path.join(base_dir, p))
normalized.append(fd)
else:
normalized.append(folder)
out["folders"] = normalized
return out
def _basename_from_pathish(path_value: str | None) -> str | None:
"""Extract a readable leaf folder name from file URI or filesystem path."""
if not path_value:
return None
cleaned = re.sub(r"^file://", "", str(path_value).strip())
cleaned = unquote(cleaned).replace("\\", "/").rstrip("/")
if not cleaned:
return None
parts = [p for p in cleaned.split("/") if p]
if not parts:
return None
leaf = parts[-1]
return leaf or None
def _infer_workspace_name_from_context(workspace_path: str, workspace_id: str) -> str | None:
"""
Infer workspace display name from projectLayouts of chats in this workspace.
Useful when workspace.json only references a deleted/opaque workspace file.
"""
if workspace_id == "global":
return "Other chats"
# Composer IDs from per-workspace state db
local_db_path = os.path.join(workspace_path, workspace_id, "state.vscdb")
if not os.path.isfile(local_db_path):
return None
composer_ids: list[str] = []
try:
# closing() guarantees .close() on scope exit (issue #17).
# Path.as_uri() percent-encodes reserved chars (#, ?, spaces, etc.);
# naive f"file:{path}" breaks sqlite URI parsing.
_db_uri = Path(local_db_path).resolve().as_uri() + "?mode=ro"
with closing(sqlite3.connect(_db_uri, uri=True)) as lconn:
row = lconn.execute(
"SELECT value FROM ItemTable WHERE [key] = 'composer.composerData'"
).fetchone()
if row and row[0]:
data = json.loads(row[0])
for c in (data.get("allComposers") or []):
cid = c.get("composerId") if isinstance(c, dict) else None
if cid:
composer_ids.append(cid)
except Exception:
return None
if not composer_ids:
return None
# Gather folder-name hints from global messageRequestContext.projectLayouts
counts: dict[str, int] = {}
with _open_global_db(workspace_path) as (gconn, _):
if not gconn:
return None
for cid in composer_ids:
rows = gconn.execute(
"SELECT value FROM cursorDiskKV WHERE key LIKE ?",
(f"messageRequestContext:{cid}:%",),
).fetchall()
for row in rows:
try:
ctx = json.loads(row["value"])
except Exception:
continue
layouts = ctx.get("projectLayouts")
if not isinstance(layouts, list):
continue
for layout in layouts:
obj = None
if isinstance(layout, str):
try:
obj = json.loads(layout)
except Exception:
obj = None
elif isinstance(layout, dict):
obj = layout
if not isinstance(obj, dict):
continue
hint = _basename_from_pathish(obj.get("rootPath"))
if hint:
counts[hint] = counts.get(hint, 0) + 1
if not counts:
return None
return max(counts.items(), key=lambda kv: kv[1])[0]
def _get_project_from_file_path(
file_path: str,
workspace_entries: list[dict],
) -> str | None:
normalized_path = normalize_file_path(file_path)
best_match = None
best_len = 0
for entry in workspace_entries:
try:
wd = _read_json_file(entry["workspaceJsonPath"])
for folder in get_workspace_folder_paths(wd):
wp = normalize_file_path(folder)
if normalized_path.startswith(wp) and len(wp) > best_len:
best_len = len(wp)
best_match = entry["name"]
except Exception:
pass
return best_match
def _create_project_name_to_workspace_id_map(workspace_entries):
mapping = {}
for entry in workspace_entries:
try:
wd = _read_json_file(entry["workspaceJsonPath"])
for folder in get_workspace_folder_paths(wd):
wp = re.sub(r"^file://", "", folder)
parts = wp.replace("\\", "/").split("/")
folder_name = parts[-1] if parts else None
if folder_name:
mapping[folder_name] = entry["name"]
except Exception:
pass
return mapping
def _create_workspace_path_to_id_map(workspace_entries):
out = {}
for entry in workspace_entries:
try:
wd = _read_json_file(entry["workspaceJsonPath"])
for folder in get_workspace_folder_paths(wd):
normalized = normalize_file_path(folder)
out[normalized] = entry["name"]
except Exception:
pass
return out
def _determine_project_for_conversation(
composer_data: dict,
composer_id: str,
project_layouts_map: dict,
project_name_to_workspace_id: dict,
workspace_path_to_id: dict,
workspace_entries: list,
bubble_map: dict,
composer_id_to_workspace_id: dict | None = None,
invalid_workspace_ids: set[str] | None = None,
) -> str | None:
# Primary: definitive per-workspace mapping
if composer_id_to_workspace_id and composer_id in composer_id_to_workspace_id:
mapped = composer_id_to_workspace_id[composer_id]
if not invalid_workspace_ids or mapped not in invalid_workspace_ids:
return mapped
# Try projectLayouts
project_layouts = project_layouts_map.get(composer_id, [])
for root_path in project_layouts:
normalized = normalize_file_path(root_path)
workspace_id = workspace_path_to_id.get(normalized)
if not workspace_id:
parts = root_path.replace("\\", "/").split("/")
folder_name = parts[-1] if parts else ""
workspace_id = project_name_to_workspace_id.get(folder_name, "")
if workspace_id:
return workspace_id
# Fallback: newlyCreatedFiles
newly = composer_data.get("newlyCreatedFiles") or []
for file_entry in newly:
uri = file_entry.get("uri") if isinstance(file_entry, dict) else None
if isinstance(uri, dict) and uri.get("path"):
pid = _get_project_from_file_path(uri["path"], workspace_entries)
if pid:
return pid
# Fallback: codeBlockData
cbd = composer_data.get("codeBlockData")
if isinstance(cbd, dict):
for fp in cbd.keys():
pid = _get_project_from_file_path(re.sub(r"^file://", "", fp), workspace_entries)
if pid:
return pid
# Fallback: conversation headers -> bubble references
headers = composer_data.get("fullConversationHeadersOnly") or []
for header in headers:
bubble = bubble_map.get(header.get("bubbleId"))
if not bubble:
continue
for fp in (bubble.get("relevantFiles") or []):
if fp:
pid = _get_project_from_file_path(fp, workspace_entries)
if pid:
return pid
for uri in (bubble.get("attachedFileCodeChunksUris") or []):
if isinstance(uri, dict) and uri.get("path"):
pid = _get_project_from_file_path(uri["path"], workspace_entries)
if pid:
return pid
for fs_entry in (bubble.get("context", {}).get("fileSelections") or []):
if isinstance(fs_entry, dict):
uri = fs_entry.get("uri")
if isinstance(uri, dict) and uri.get("path"):
pid = _get_project_from_file_path(uri["path"], workspace_entries)
if pid:
return pid
# Last fallback: path-segment matching
path_segments = []
for f in newly:
if isinstance(f, dict):
uri = f.get("uri")
if isinstance(uri, dict) and uri.get("path"):
path_segments.append(normalize_file_path(uri["path"]))
if isinstance(cbd, dict):
for fp in cbd.keys():
path_segments.append(normalize_file_path(re.sub(r"^file://", "", fp)))
for header in headers:
bubble = bubble_map.get(header.get("bubbleId"))
if not bubble:
continue
for fp in (bubble.get("relevantFiles") or []):
if fp:
path_segments.append(normalize_file_path(fp))
for uri in (bubble.get("attachedFileCodeChunksUris") or []):
if isinstance(uri, dict) and uri.get("path"):
path_segments.append(normalize_file_path(uri["path"]))
for fs_entry in (bubble.get("context", {}).get("fileSelections") or []):
if isinstance(fs_entry, dict):
uri = fs_entry.get("uri")
if isinstance(uri, dict) and uri.get("path"):
path_segments.append(normalize_file_path(uri["path"]))
sep = "\\" if sys.platform == "win32" else "/"
folder_name_to_ws = []
for entry in workspace_entries:
try:
wd = _read_json_file(entry["workspaceJsonPath"])
for folder in get_workspace_folder_paths(wd):
name = re.sub(r"^file://", "", folder).replace("\\", "/").split("/")[-1]
if name:
folder_name_to_ws.append({"name": name, "id": entry["name"]})
except Exception:
pass
best_id = None
best_len = 0
for p in path_segments:
for item in folder_name_to_ws:
needle = sep + item["name"] + sep
needle_end = sep + item["name"]
if needle in p or p.endswith(needle_end):
if len(item["name"]) > best_len:
best_len = len(item["name"])
best_id = item["id"]
if best_id:
return best_id
return None
def _collect_workspace_entries(workspace_path: str) -> list[dict]:
"""Scan workspace directory and return entries with workspace.json."""
entries = []
try:
for name in os.listdir(workspace_path):
full = os.path.join(workspace_path, name)
if os.path.isdir(full):
wj = os.path.join(full, "workspace.json")
if os.path.isfile(wj):
entries.append({"name": name, "workspaceJsonPath": wj})
except Exception:
pass
return entries
def _collect_invalid_workspace_ids(workspace_entries: list[dict]) -> set[str]:
"""Workspace IDs whose descriptors have no resolvable folder paths."""
invalid: set[str] = set()
for entry in workspace_entries:
try:
wd = _read_json_file(entry["workspaceJsonPath"])
folders = get_workspace_folder_paths(wd)
if not folders:
invalid.add(entry["name"])
except Exception:
invalid.add(entry["name"])
return invalid
def _infer_invalid_workspace_aliases(
composer_rows: list,
project_layouts_map: dict,
project_name_map: dict,
workspace_path_map: dict,
workspace_entries: list,
bubble_map: dict,
composer_id_to_ws: dict,
invalid_workspace_ids: set[str],
) -> dict[str, str]:
"""
Infer replacement workspace IDs for invalid workspace entries.
For each composer mapped to an invalid workspace ID, compute an evidence-
based assignment (without trusting composer_id_to_ws). Use majority voting
to map each invalid workspace ID to the most likely valid workspace ID.
"""
votes: dict[str, dict[str, int]] = {}
for row in composer_rows:
cid = row["key"].split(":")[1]
mapped = composer_id_to_ws.get(cid)
if mapped not in invalid_workspace_ids:
continue
try:
# Validate via Composer.from_dict so a schema-drifted row can't
# steer the alias vote and misassign otherwise-valid composers to
# the wrong workspace. The downstream per-row loops in
# list_workspaces() / get_workspace_tabs() already drop drift,
# but this helper runs BEFORE that loop and its votes shape
# invalid_workspace_aliases for every other composer.
composer = Composer.from_dict(json.loads(row["value"]), composer_id=cid)
cd = composer.raw
except (SchemaError, json.JSONDecodeError, TypeError, ValueError):
continue
inferred = _determine_project_for_conversation(
cd,
cid,
project_layouts_map,
project_name_map,
workspace_path_map,
workspace_entries,
bubble_map,
composer_id_to_workspace_id=None,
invalid_workspace_ids=None,
)
if inferred and inferred not in invalid_workspace_ids:
votes.setdefault(mapped, {})
votes[mapped][inferred] = votes[mapped].get(inferred, 0) + 1
aliases: dict[str, str] = {}
for invalid_id, counts in votes.items():
if not counts:
continue
aliases[invalid_id] = max(counts.items(), key=lambda kv: kv[1])[0]
return aliases
def _build_composer_id_to_workspace_id(workspace_path: str, workspace_entries: list) -> dict:
"""Build mapping: composerId -> workspaceId from per-workspace state.vscdb."""
mapping = {}
for entry in workspace_entries:
db_path = os.path.join(workspace_path, entry["name"], "state.vscdb")
if not os.path.isfile(db_path):
continue
try:
# closing() guarantees .close() on scope exit (issue #17).
with closing(sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)) as conn:
row = conn.execute(
"SELECT value FROM ItemTable WHERE [key] = 'composer.composerData'"
).fetchone()
if row and row[0]:
data = json.loads(row[0])
all_composers = data.get("allComposers")
if isinstance(all_composers, list):
for c in all_composers:
cid = c.get("composerId")
if cid:
mapping[cid] = entry["name"]
except Exception:
pass
return mapping
@contextmanager
def _open_global_db(workspace_path: str):
"""Yield (conn, path) for the global-storage SQLite db (read-only).
Context-managed so the caller writes ``with _open_global_db(...) as (conn, _):``
and the connection is guaranteed to close on scope exit, including on
exception (issue #17). Yields ``(None, path)`` if the file is missing —
callers branch on ``conn is None`` exactly as before.
"""
global_db_path = os.path.join(workspace_path, "..", "globalStorage", "state.vscdb")
global_db_path = os.path.normpath(global_db_path)
if not os.path.isfile(global_db_path):
yield None, global_db_path
return
conn = sqlite3.connect(f"file:{global_db_path}?mode=ro", uri=True)
conn.row_factory = sqlite3.Row
try:
yield conn, global_db_path
finally:
conn.close()
# ---------------------------------------------------------------------------
# GET /api/workspaces
# ---------------------------------------------------------------------------
@bp.route("/api/workspaces")
def list_workspaces():
try:
workspace_path = resolve_workspace_path()
workspace_entries = _collect_workspace_entries(workspace_path)
invalid_workspace_ids = _collect_invalid_workspace_ids(workspace_entries)
project_name_map = _create_project_name_to_workspace_id_map(workspace_entries)
workspace_path_map = _create_workspace_path_to_id_map(workspace_entries)
composer_id_to_ws = _build_composer_id_to_workspace_id(workspace_path, workspace_entries)
conversation_map: dict[str, list] = {}
# closing semantics now baked into the context manager (issue #17).
with _open_global_db(workspace_path) as (global_db, _):
if global_db:
try:
# composerData rows
composer_rows = global_db.execute(
"SELECT key, value FROM cursorDiskKV WHERE key LIKE 'composerData:%' AND LENGTH(value) > 10"
).fetchall()
# messageRequestContext rows -> project layouts
ctx_rows = global_db.execute(
"SELECT key, value FROM cursorDiskKV WHERE key LIKE 'messageRequestContext:%'"
).fetchall()
project_layouts_map: dict[str, list] = {}
for row in ctx_rows:
parts = row["key"].split(":")
if len(parts) < 2:
continue
cid = parts[1]
try:
ctx = json.loads(row["value"])
layouts = ctx.get("projectLayouts")
if isinstance(layouts, list):
if cid not in project_layouts_map:
project_layouts_map[cid] = []
for layout in layouts:
if isinstance(layout, str):
try:
obj = json.loads(layout)
if isinstance(obj, dict) and obj.get("rootPath"):
project_layouts_map[cid].append(obj["rootPath"])
except Exception:
pass
except Exception:
pass
# bubbleId rows for project detection
bubble_rows = global_db.execute(
"SELECT key, value FROM cursorDiskKV WHERE key LIKE 'bubbleId:%'"
).fetchall()
bubble_map: dict[str, dict] = {}
for row in bubble_rows:
parts = row["key"].split(":")
if len(parts) >= 3:
bid = parts[2]
try:
bubble = Bubble.from_dict(json.loads(row["value"]), bubble_id=bid)
bubble_map[bid] = bubble.raw
except SchemaError as e:
# Drift surfaces in logs so an operator sees disappearing
# bubbles instead of guessing. The row is still skipped —
# one bad bubble must not 500 the endpoint.
print(f"Schema drift in bubble {bid}: {e}")
except (json.JSONDecodeError, ValueError):
pass
# Process each composer
invalid_workspace_aliases = _infer_invalid_workspace_aliases(
composer_rows=composer_rows,
project_layouts_map=project_layouts_map,
project_name_map=project_name_map,
workspace_path_map=workspace_path_map,
workspace_entries=workspace_entries,
bubble_map=bubble_map,
composer_id_to_ws=composer_id_to_ws,
invalid_workspace_ids=invalid_workspace_ids,
)
for row in composer_rows:
cid = row["key"].split(":")[1]
try:
composer = Composer.from_dict(json.loads(row["value"]), composer_id=cid)
except SchemaError as e:
print(f"Schema drift in composer {cid}: {e}")
continue
except (json.JSONDecodeError, TypeError, ValueError):
continue
try:
pid = _determine_project_for_conversation(
composer.raw, cid, project_layouts_map,
project_name_map, workspace_path_map,
workspace_entries, bubble_map, composer_id_to_ws, invalid_workspace_ids
)
mapped_ws = composer_id_to_ws.get(cid)
if not pid and mapped_ws in invalid_workspace_ids:
pid = invalid_workspace_aliases.get(mapped_ws)
assigned = pid if pid else "global"
headers = composer.full_conversation_headers_only
has_bubbles = any(bubble_map.get(h.get("bubbleId")) for h in headers)
if not has_bubbles:
continue
conversation_map.setdefault(assigned, []).append({
"composerId": cid,
"name": composer.name or f"Conversation {cid[:8]}",
"lastUpdatedAt": to_epoch_ms(composer.last_updated_at) or to_epoch_ms(composer.created_at) or 0,
"createdAt": to_epoch_ms(composer.created_at) or 0,
})
except Exception:
pass
except Exception:
pass
# Exclusion rules (optional)
rules = current_app.config.get("EXCLUSION_RULES") or []
# Build project list — merge workspace entries sharing the same folder
# Group workspace entries by normalized folder path
folder_to_entries: dict[str, list] = {}
entry_folder_map: dict[str, str] = {} # entry_name -> normalized folder
for entry in workspace_entries:
norm_folder = ""
try:
wd = _read_json_file(entry["workspaceJsonPath"])
folders = get_workspace_folder_paths(wd)
first_folder = folders[0] if folders else None
if first_folder:
norm_folder = normalize_file_path(first_folder)
except Exception:
pass
if not norm_folder:
norm_folder = entry["name"] # fallback to workspace ID
entry_folder_map[entry["name"]] = norm_folder
folder_to_entries.setdefault(norm_folder, []).append(entry)
projects = []
seen_folders = set()
for entry in workspace_entries:
norm_folder = entry_folder_map[entry["name"]]
if norm_folder in seen_folders:
continue
seen_folders.add(norm_folder)
group = folder_to_entries[norm_folder]
# Primary entry is the first one; use its ID as the canonical one
primary = group[0]
all_ws_ids = [e["name"] for e in group]
try:
mtime = max(
os.path.getmtime(os.path.join(workspace_path, e["name"], "state.vscdb"))
for e in group
if os.path.isfile(os.path.join(workspace_path, e["name"], "state.vscdb"))
)
except Exception:
mtime = 0
workspace_name = _get_workspace_display_name(workspace_path, primary["name"])
if workspace_name == primary["name"]:
inferred = _infer_workspace_name_from_context(workspace_path, primary["name"])
workspace_name = inferred or f"Project {primary['name'][:8]}"
# Skip entire workspace before iterating conversations
if is_excluded_by_rules(rules, workspace_name):
continue
# Merge conversations from all workspace IDs in the group; apply exclusion rules
convos = []
for ws_id in all_ws_ids:
for c in conversation_map.get(ws_id, []):
searchable = build_searchable_text(
project_name=workspace_name,
chat_title=c.get("name"),
)
if not is_excluded_by_rules(rules, searchable):
convos.append(c)
# Hide workspace shells that currently have no visible conversations.
if not convos:
continue
projects.append({
"id": primary["name"],
"name": workspace_name,
"path": primary["workspaceJsonPath"],
"conversationCount": len(convos),
"lastModified": datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat(),
# Include all workspace IDs for this folder
**({"aliasIds": all_ws_ids} if len(all_ws_ids) > 1 else {}),
})
# Global (unmatched) conversations; apply exclusion rules
global_convos = [
c for c in conversation_map.get("global", [])
if not is_excluded_by_rules(
rules,
build_searchable_text(project_name="Other chats", chat_title=c.get("name")),
)
]
if global_convos:
last_updated = max((c.get("lastUpdatedAt") or 0 for c in global_convos), default=0)
projects.append({
"id": "global",
"name": "Other chats",
"conversationCount": len(global_convos),
"lastModified": (
datetime.fromtimestamp(last_updated / 1000, tz=timezone.utc).isoformat()
if last_updated > 0
else datetime.now(tz=timezone.utc).isoformat()
),
})
# --- Cursor CLI projects ---
try:
cli_projects = list_cli_projects(get_cli_chats_path())
for cp in cli_projects:
ws_name = cp["workspace_name"] or cp["project_id"][:12]
if is_excluded_by_rules(rules, ws_name):
continue
convos = []
for s in cp["sessions"]:
session_name = s["meta"].get("name") or f"Session {s['session_id'][:8]}"
searchable = build_searchable_text(
project_name=ws_name,
chat_title=session_name,
)
if not is_excluded_by_rules(rules, searchable):
convos.append(session_name)
if not convos:
continue
last_ms = cp["last_updated_ms"]
projects.append({
"id": f"cli:{cp['project_id']}",
"name": ws_name,
"conversationCount": len(convos),
"lastModified": (
datetime.fromtimestamp(last_ms / 1000, tz=timezone.utc).isoformat()
if last_ms
else datetime.now(tz=timezone.utc).isoformat()
),
"source": "cli",
})
except Exception:
_logger.exception("Failed to load CLI projects")
projects.sort(key=lambda p: p["lastModified"], reverse=True)
return jsonify(projects)
except Exception:
_logger.exception("Failed to get workspaces")
return jsonify({"error": "Failed to get workspaces"}), 500
# ---------------------------------------------------------------------------
# GET /api/workspaces/<id>
# ---------------------------------------------------------------------------
@bp.route("/api/workspaces/<workspace_id>")
def get_workspace(workspace_id):
try:
if workspace_id == "global":
return jsonify({
"id": "global",
"name": "Other chats",
"path": None,
"folder": None,
"lastModified": datetime.now(tz=timezone.utc).isoformat(),
})
if workspace_id.startswith("cli:"):
project_id = workspace_id[4:]
cli_projects = list_cli_projects(get_cli_chats_path())
for cp in cli_projects:
if cp["project_id"] == project_id:
last_ms = cp["last_updated_ms"]
return jsonify({
"id": workspace_id,
"name": cp["workspace_name"] or project_id[:12],
"path": cp["workspace_path"],
"folder": cp["workspace_path"],
"lastModified": (
datetime.fromtimestamp(last_ms / 1000, tz=timezone.utc).isoformat()
if last_ms
else datetime.now(tz=timezone.utc).isoformat()
),
"source": "cli",
})
return jsonify({"error": "CLI project not found"}), 404
workspace_path = resolve_workspace_path()
db_path = os.path.join(workspace_path, workspace_id, "state.vscdb")
wj_path = os.path.join(workspace_path, workspace_id, "workspace.json")
if not os.path.isfile(db_path):
return jsonify({"error": "Workspace not found"}), 404
mtime = os.path.getmtime(db_path)
folder = None
workspace_name = workspace_id
try:
wd = _read_json_file(wj_path)
folder_paths = get_workspace_folder_paths(wd)
folder = folder_paths[0] if folder_paths else wd.get("folder")
derived_name = get_workspace_display_name(wd)
if derived_name:
workspace_name = derived_name
elif workspace_name == workspace_id:
inferred = _infer_workspace_name_from_context(workspace_path, workspace_id)
if inferred:
workspace_name = inferred
except Exception:
inferred = _infer_workspace_name_from_context(workspace_path, workspace_id)
if inferred:
workspace_name = inferred
return jsonify({
"id": workspace_id,
"name": workspace_name,
"path": db_path,
"folder": folder,
"lastModified": datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat(),
})
except Exception:
_logger.exception("Failed to get workspace")
return jsonify({"error": "Failed to get workspace"}), 500
# ---------------------------------------------------------------------------
# GET /api/workspaces/<id>/tabs
# ---------------------------------------------------------------------------
def _get_cli_workspace_tabs(workspace_id: str):
"""Return tabs for a Cursor CLI project (``workspace_id`` starts with ``cli:``)."""
try:
project_id = workspace_id[4:]
cli_projects = list_cli_projects(get_cli_chats_path())
project = next((cp for cp in cli_projects if cp["project_id"] == project_id), None)
if project is None:
return jsonify({"error": "CLI project not found"}), 404
rules = current_app.config.get("EXCLUSION_RULES") or []
ws_name = project["workspace_name"] or project_id[:12]
tabs = []
for session in project["sessions"]:
meta = session.get("meta", {})
session_id = session["session_id"]
created_ms: int = meta.get("createdAt") or int(datetime.now().timestamp() * 1000)
session_name = meta.get("name") or f"Session {session_id[:8]}"
try:
messages = traverse_blobs(session["db_path"])
except Exception: # noqa: BLE001 — best-effort per-session skip; one corrupted session must not 500 the endpoint, and the failure mode is logged with exc_info so the concrete type is preserved.
_logger.warning("CLI: could not read session %s", session_id, exc_info=True)
continue
bubbles = messages_to_bubbles(messages, created_ms)
if not bubbles:
continue
# Derive title from first user bubble when name is generic
title = session_name
if not title or title.startswith("New Agent"):
for b in bubbles:
if b["type"] == "user" and b.get("text"):
first_lines = [ln for ln in b["text"].split("\n") if ln.strip()]
if first_lines:
title = first_lines[0][:100]
if len(title) == 100:
title += "..."
break
searchable = build_searchable_text(project_name=ws_name, chat_title=title)
if is_excluded_by_rules(rules, searchable):
continue
# Aggregate metadata
total_tool_calls = 0
tool_breakdown: dict = {}
for b in bubbles:
tcs = (b.get("metadata") or {}).get("toolCalls") or []
total_tool_calls += len(tcs)
for tc in tcs:
tn = tc.get("name", "unknown")
tool_breakdown[tn] = tool_breakdown.get(tn, 0) + 1
tab_meta: dict | None = None
if total_tool_calls or tool_breakdown:
tab_meta = {"totalToolCalls": total_tool_calls or None}
if tool_breakdown:
tab_meta["toolBreakdown"] = tool_breakdown
tab = {
"id": session_id,
"title": title,
"timestamp": created_ms,
"bubbles": [
{
"type": b["type"],
"text": b.get("text", ""),
"timestamp": b.get("timestamp", created_ms),
**({"metadata": b["metadata"]} if b.get("metadata") else {}),
}
for b in bubbles
],
"source": "cli",
}
if tab_meta:
tab_meta_clean = {k: v for k, v in tab_meta.items() if v is not None}
if tab_meta_clean:
tab["metadata"] = tab_meta_clean
tabs.append(tab)
tabs.sort(key=lambda t: t.get("timestamp") or 0, reverse=True)
return jsonify({"tabs": tabs})
except Exception:
_logger.exception("Failed to get CLI workspace tabs")
return jsonify({"error": "Failed to get CLI workspace tabs"}), 500
def _extract_chat_id_from_bubble_key(key: str) -> str | None:
m = re.match(r"^bubbleId:([^:]+):", key)
return m.group(1) if m else None
def _extract_chat_id_from_code_block_diff_key(key: str) -> str | None:
m = re.match(r"^codeBlockDiff:([^:]+):", key)
return m.group(1) if m else None
@bp.route("/api/workspaces/<workspace_id>/tabs")
def get_workspace_tabs(workspace_id):
if workspace_id.startswith("cli:"):
return _get_cli_workspace_tabs(workspace_id)
# Global DB reads use `_open_global_db` (issue #17) — same lifecycle as
# list_workspaces; connection closes when the `with` block exits.
try:
workspace_path = resolve_workspace_path()
response = {"tabs": []}
workspace_entries = _collect_workspace_entries(workspace_path)
invalid_workspace_ids = _collect_invalid_workspace_ids(workspace_entries)
project_name_map = _create_project_name_to_workspace_id_map(workspace_entries)
workspace_path_map = _create_workspace_path_to_id_map(workspace_entries)
composer_id_to_ws = _build_composer_id_to_workspace_id(workspace_path, workspace_entries)
# Build set of all workspace IDs that share the same folder as workspace_id
# (handles Cursor creating multiple workspace entries for the same project)
matching_ws_ids = {workspace_id}
if workspace_id != "global":
target_folder = ""
wj_path = os.path.join(workspace_path, workspace_id, "workspace.json")
try:
wd = _read_json_file(wj_path)
folders = get_workspace_folder_paths(wd)