-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
3958 lines (3440 loc) · 143 KB
/
Copy pathagent.py
File metadata and controls
3958 lines (3440 loc) · 143 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
"""
AI Tab Optimizer — Local AI Server
FastAPI server with SQLite database for persistent per-URL tab analysis caching.
Uses local AI CLIs for analysis and stores state in SQLite.
"""
import asyncio
import json
import logging
import os
import re
import shutil
import tempfile
import time
from uuid import uuid4
from collections import Counter, defaultdict
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, Literal
from urllib.parse import parse_qs, unquote, urlparse
import aiosqlite
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
from server_core.constants import (
BATCH_SIZE,
CLAUDE_TIMEOUT_SECONDS,
CODEX_TIMEOUT_SECONDS,
LLM_LOG_RETENTION_DAYS,
MAX_RUNTIME_LOG_ENTRIES,
SUPPORTED_SERVER_AI_PROVIDERS,
URL_ANALYSIS_TTL_DAYS,
VALID_ACTIONS,
)
from server_core.provider_policy import (
classify_fallback_issue,
should_disable_provider_for_run,
summarize_provider_error,
)
from server_core.runtime_state import AnalysisRuntimeState
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger("ai-tab-optimizer")
# Clear Claude Code nesting env vars so claude CLI can be spawned from this server
for _env_key in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING"):
os.environ.pop(_env_key, None)
DB_PATH = Path(__file__).parent / "tab_analysis.db"
APP_ROOT = Path(__file__).parent
RETENTION_SWEEP_INTERVAL_SECONDS = 3600
analysis_runtime = AnalysisRuntimeState()
THEME_QUERY_KEYS = {"q", "query", "search", "text", "title", "topic", "s"}
THEME_STOPWORDS = {
"about", "account", "accounts", "agent", "agents", "all", "and", "app", "article",
"assistant", "auth", "blog", "browser", "chat", "chrome", "code", "codex", "com",
"course", "courses", "dashboard", "default", "demo", "docs", "document", "download",
"edu", "en", "error", "extensions", "for", "free", "from", "github", "google", "help",
"home", "how", "http", "https", "index", "info", "latest", "learn", "lesson", "lessons",
"list", "localhost", "login", "mail", "main", "manage", "menu", "net", "new", "news",
"notes", "open", "optimizer", "org", "page", "pages", "platform", "post", "pricing",
"product", "products", "profile", "project", "projects", "read", "ref", "results",
"review", "ru", "search", "service", "settings", "sign", "site", "start", "support",
"tab", "tabs", "team", "teams", "the", "this", "today", "tool", "tools", "topic",
"update", "user", "users", "video", "watch", "web", "what", "why", "with", "work",
"www", "xcom", "youtube", "your", "данные", "для", "или", "как", "курс", "курсы",
"модель", "модели", "новое", "новый", "обзор", "онлайн", "подборка", "посмотреть",
"после", "проект", "работа", "страница", "статья", "темы", "урок", "уроки",
"что", "это", "этот", "эти",
}
SYSTEM_PROMPT = """You are a browser tab analyst. You receive a list of open browser tabs and must analyze them.
Return a JSON object matching this exact schema:
{
"tabRecommendations": [
{
"tabId": 1,
"action": "keep" | "group" | "read_later" | "archive" | "close",
"confidence": 0.0 to 1.0,
"reason": "why this action",
"suggestedGroupName": "optional group name"
}
]
}
Rules:
- Every tab must have exactly one recommendation
- Actions: "keep" (actively useful), "group" (related tabs to organize), "read_later" (interesting but not urgent), "archive" (save reference then close), "close" (not needed)
- Detect duplicate/near-duplicate URLs and group them
- Identify stale tabs (generic new tab pages, error pages)
- Be conservative: when unsure, recommend "keep" with lower confidence
- Return ONLY valid JSON, no markdown fences, no extra text"""
CODEX_SCHEMA = {
"type": "object",
"properties": {
"tabRecommendations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"tabId": {"type": "integer"},
"action": {"type": "string"},
"confidence": {"type": "number"},
"reason": {"type": "string"},
"suggestedGroupName": {
"type": ["string", "null"]
},
},
"required": [
"tabId",
"action",
"confidence",
"reason",
"suggestedGroupName",
],
"additionalProperties": False,
},
}
},
"required": ["tabRecommendations"],
"additionalProperties": False,
}
# ─── Pydantic Models ──────────────────────────────────────
class TabInput(BaseModel):
id: int
title: str
url: str
domain: str
pinned: bool
active: bool
groupId: int | None = None
groupName: str | None = None
pageExcerpt: str | None = None
metaDescription: str | None = None
class AnalyzeRequest(BaseModel):
tabs: list[TabInput]
forceRefresh: bool = False
providerOrder: list[Literal["claude_code", "codex_cli"]] | None = None
class ProviderAttempt(BaseModel):
provider: Literal["claude_code", "codex_cli"]
model: str | None = None
status: Literal["succeeded", "failed"]
error: str | None = None
class AnalysisMetadata(BaseModel):
durationMs: int
durationApiMs: int
totalCostUsd: float | None
inputTokens: int
outputTokens: int
tabCount: int
providerUsed: Literal["claude_code", "codex_cli"] | None = None
modelUsed: str | None = None
providerAttempts: list[ProviderAttempt] = Field(default_factory=list)
providerStatus: dict[str, Any] | None = None
class CacheStats(BaseModel):
totalTabs: int
tabsFromCache: int
tabsAnalyzed: int
tabsSaved: int
cacheHitRate: float
class AnalyzeResponse(BaseModel):
result: dict[str, Any]
metadata: AnalysisMetadata
cacheStats: CacheStats
class TabAnalysisStatus(BaseModel):
tabId: int
url: str
title: str
domain: str
status: Literal["pending", "cached", "analyzed", "failed"]
source: Literal["pending", "database", "provider", "heuristic"]
action: Literal["keep", "group", "read_later", "archive", "close"] | None = None
confidence: float | None = None
reason: str | None = None
suggestedGroupName: str | None = None
analyzedAt: int | None = None
provider: Literal["claude_code", "codex_cli"] | None = None
model: str | None = None
class TabAnalysisStatusSummary(BaseModel):
total: int
cached: int = 0
analyzed: int = 0
pending: int = 0
failed: int = 0
class AnalysisRunSnapshot(BaseModel):
id: str
fingerprint: str
status: Literal["running", "stopped", "completed", "failed"]
phase: Literal[
"preparing",
"sending",
"analyzing",
"persisting",
"processing",
"stopping",
"stopped",
"completed",
"failed",
]
startedAt: int
updatedAt: int
analyzedAt: int | None = None
forceRefresh: bool = False
totalTabs: int
tabsCached: int = 0
tabsAnalyzed: int = 0
tabsProcessed: int = 0
tabsRemaining: int = 0
tabsSaved: int = 0
batchesTotal: int = 0
batchesCompleted: int = 0
currentBatch: int = 0
providerOrderOverride: list[Literal["claude_code", "codex_cli"]] = Field(default_factory=list)
fallbackNotice: str | None = None
result: dict[str, Any]
metadata: AnalysisMetadata
allTabs: list[TabInput]
pendingTabs: list[TabInput]
tabStatuses: list[TabAnalysisStatus] = Field(default_factory=list)
error: str | None = None
class CreateAnalysisRunRequest(BaseModel):
snapshot: AnalysisRunSnapshot
class UpdateAnalysisRunRequest(BaseModel):
snapshot: AnalysisRunSnapshot
class TabAnalysisStatusRequest(BaseModel):
tabs: list[TabInput]
forceRefresh: bool = False
class TabRecommendationInput(BaseModel):
tabId: int
action: Literal["keep", "group", "read_later", "archive", "close"]
confidence: float
reason: str
suggestedGroupName: str | None = None
class ImportUrlAnalysisRequest(BaseModel):
tabs: list[TabInput]
recommendations: list[TabRecommendationInput]
analysisSource: Literal["provider", "heuristic"] = "heuristic"
provider: Literal["claude_code", "codex_cli"] | None = None
model: str | None = None
analyzedAt: int | None = None
class RuntimeLogEntry(BaseModel):
id: int
timestamp: int
level: Literal["info", "warning", "error"]
category: Literal["analysis", "provider", "database"]
message: str
class LLMCallLogEntry(BaseModel):
id: int
timestamp: int
sessionTimestamp: int | None = None
batchIndex: int
provider: str
model: str | None = None
phase: str
durationMs: int | None = None
inputTokens: int = 0
outputTokens: int = 0
costUsd: float | None = None
promptChars: int = 0
responseChars: int = 0
tabCount: int = 0
errorMessage: str | None = None
requestSummary: str | None = None
responseSummary: str | None = None
class DatabaseStatus(BaseModel):
urlCacheEntries: int
analysisSessions: int
analysisRuns: int
historyEvents: int
snapshots: int
runtimeLogs: int
llmCallLogs: int
dbSizeBytes: int
lastAnalysisAt: int | None = None
lastLogAt: int | None = None
class AppSettings(BaseModel):
obsidianVaultPath: str = ""
protectedDomains: list[str] = Field(default_factory=list)
staleDaysThreshold: int = 7
maxStoredSnapshots: int = 30
aiProvider: Literal["anthropic", "openai", "ollama", "local_server", "none"] = "local_server"
serverAiProvider: Literal["none", "claude_code", "codex_cli"] = "claude_code"
fallbackAiProvider: Literal["none", "claude_code", "codex_cli"] = "codex_cli"
apiKey: str = ""
ollamaEndpoint: str = "http://localhost:11434"
localServerUrl: str = "http://localhost:8765"
claudeCliPath: str = ""
codexCliPath: str = ""
codexModel: str = "gpt-5.4"
autoSnapshotEnabled: bool = False
autoSnapshotIntervalHours: int = 4
historyRetentionDays: int = 30
class SaveSettingsRequest(BaseModel):
settings: dict[str, Any]
class HistoryEventRecord(BaseModel):
tabId: int
url: str
title: str
domain: str
event: str
timestamp: int
class HistoryImportRequest(BaseModel):
entries: list[HistoryEventRecord]
class HistoryPruneRequest(BaseModel):
retentionDays: int
class ClearDatabaseRequest(BaseModel):
preserveSettings: bool = True
class SnapshotTabRecord(BaseModel):
url: str
title: str
domain: str
pinned: bool
favIconUrl: str | None = None
groupName: str | None = None
class SnapshotWindowRecord(BaseModel):
windowId: int
focused: bool
tabs: list[SnapshotTabRecord]
class SnapshotStatsRecord(BaseModel):
totalTabs: int
totalWindows: int
topDomains: list[str]
class SnapshotRecord(BaseModel):
id: str
name: str
createdAt: int
trigger: str
windows: list[SnapshotWindowRecord]
stats: SnapshotStatsRecord
class SaveSnapshotRequest(BaseModel):
snapshot: SnapshotRecord
maxStoredSnapshots: int | None = None
class ImportSnapshotsRequest(BaseModel):
snapshots: list[SnapshotRecord]
maxStoredSnapshots: int | None = None
# ─── SQLite Setup ─────────────────────────────────────────
async def init_db(db: aiosqlite.Connection) -> None:
await db.executescript("""
CREATE TABLE IF NOT EXISTS url_analysis (
url TEXT PRIMARY KEY,
action TEXT NOT NULL,
confidence REAL NOT NULL,
reason TEXT NOT NULL,
suggested_group_name TEXT,
analyzed_at REAL NOT NULL,
analysis_source TEXT NOT NULL DEFAULT 'provider',
provider TEXT,
model TEXT
);
CREATE TABLE IF NOT EXISTS analysis_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL NOT NULL,
tab_count INTEGER NOT NULL,
tabs_from_cache INTEGER DEFAULT 0,
tabs_analyzed INTEGER DEFAULT 0,
duration_ms INTEGER DEFAULT 0,
duration_api_ms INTEGER DEFAULT 0,
wall_time_ms INTEGER DEFAULT 0,
total_cost_usd REAL,
input_tokens INTEGER DEFAULT 0,
output_tokens INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS analysis_runs (
id TEXT PRIMARY KEY,
fingerprint TEXT NOT NULL,
status TEXT NOT NULL,
started_at REAL NOT NULL,
updated_at REAL NOT NULL,
analyzed_at REAL,
state_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_analysis_runs_updated_at
ON analysis_runs(updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_analysis_runs_fingerprint
ON analysis_runs(fingerprint, updated_at DESC);
CREATE TABLE IF NOT EXISTS tab_history_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tab_id INTEGER NOT NULL,
url TEXT NOT NULL,
title TEXT NOT NULL,
domain TEXT NOT NULL,
event TEXT NOT NULL,
timestamp REAL NOT NULL,
UNIQUE(tab_id, url, event, timestamp)
);
CREATE INDEX IF NOT EXISTS idx_tab_history_events_timestamp
ON tab_history_events(timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_tab_history_events_url
ON tab_history_events(url);
CREATE TABLE IF NOT EXISTS snapshots (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
created_at REAL NOT NULL,
trigger TEXT NOT NULL,
total_tabs INTEGER NOT NULL,
total_windows INTEGER NOT NULL,
top_domains_json TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_snapshots_created_at
ON snapshots(created_at DESC);
CREATE TABLE IF NOT EXISTS app_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
settings_json TEXT NOT NULL,
updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS runtime_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL NOT NULL,
level TEXT NOT NULL,
category TEXT NOT NULL,
message TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_runtime_logs_timestamp
ON runtime_logs(timestamp DESC);
CREATE TABLE IF NOT EXISTS llm_call_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL NOT NULL,
session_timestamp REAL,
batch_index INTEGER NOT NULL DEFAULT 0,
provider TEXT NOT NULL,
model TEXT,
phase TEXT NOT NULL,
duration_ms INTEGER,
input_tokens INTEGER DEFAULT 0,
output_tokens INTEGER DEFAULT 0,
cost_usd REAL,
prompt_chars INTEGER DEFAULT 0,
response_chars INTEGER DEFAULT 0,
tab_count INTEGER DEFAULT 0,
error_message TEXT,
request_summary TEXT,
response_summary TEXT
);
CREATE INDEX IF NOT EXISTS idx_llm_call_logs_timestamp
ON llm_call_logs(timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_llm_call_logs_session
ON llm_call_logs(session_timestamp);
CREATE TABLE IF NOT EXISTS recommendation_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL NOT NULL,
tab_url TEXT NOT NULL,
tab_title TEXT,
ai_action TEXT NOT NULL,
user_action TEXT NOT NULL,
confidence REAL NOT NULL,
session_timestamp REAL
);
CREATE INDEX IF NOT EXISTS idx_recommendation_actions_timestamp
ON recommendation_actions(timestamp DESC);
CREATE TABLE IF NOT EXISTS topic_clusters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
tags_json TEXT NOT NULL DEFAULT '[]',
tab_urls_json TEXT NOT NULL DEFAULT '[]',
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_topic_clusters_updated
ON topic_clusters(updated_at DESC);
""")
# Schema migration: add action_breakdown_json column to analysis_sessions
try:
await db.execute("ALTER TABLE analysis_sessions ADD COLUMN action_breakdown_json TEXT")
await db.commit()
except Exception:
pass # Column already exists
for statement in (
"ALTER TABLE url_analysis ADD COLUMN analysis_source TEXT NOT NULL DEFAULT 'provider'",
"ALTER TABLE url_analysis ADD COLUMN provider TEXT",
"ALTER TABLE url_analysis ADD COLUMN model TEXT",
):
try:
await db.execute(statement)
await db.commit()
except Exception:
pass
await apply_retention_policies(db)
async def apply_retention_policies(db: aiosqlite.Connection) -> None:
url_cutoff = time.time() - URL_ANALYSIS_TTL_DAYS * 86400
log_cutoff = time.time() - LLM_LOG_RETENTION_DAYS * 86400
deleted_rows = 0
cursor = await db.execute("DELETE FROM url_analysis WHERE analyzed_at < ?", (url_cutoff,))
deleted_rows += max(cursor.rowcount, 0)
cursor = await db.execute("DELETE FROM llm_call_logs WHERE timestamp < ?", (log_cutoff * 1000,))
deleted_rows += max(cursor.rowcount, 0)
await db.commit()
if deleted_rows > 0:
try:
await db.execute("VACUUM")
except Exception:
logger.exception("SQLite VACUUM failed after retention cleanup")
async def retention_worker(db: aiosqlite.Connection) -> None:
while True:
await asyncio.sleep(RETENTION_SWEEP_INTERVAL_SECONDS)
try:
await apply_retention_policies(db)
except Exception:
logger.exception("Periodic retention cleanup failed")
@asynccontextmanager
async def lifespan(application: FastAPI):
db = await aiosqlite.connect(str(DB_PATH))
db.row_factory = aiosqlite.Row
await init_db(db)
application.state.db = db
retention_task = asyncio.create_task(retention_worker(db))
logger.info(f"SQLite database opened: {DB_PATH}")
yield
retention_task.cancel()
try:
await retention_task
except asyncio.CancelledError:
pass
await db.close()
logger.info("SQLite database closed")
app = FastAPI(title="AI Tab Optimizer Server", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def get_db(request: Request) -> aiosqlite.Connection:
return request.app.state.db
# ─── DB Helpers ───────────────────────────────────────────
async def get_cached_urls(
db: aiosqlite.Connection,
urls: list[str],
cache_namespace: str,
) -> dict[str, dict[str, Any]]:
if not urls:
return {}
cutoff = time.time() - URL_ANALYSIS_TTL_DAYS * 86400
cache_key_map = {
f"{cache_namespace}::{url}": url
for url in urls
}
placeholders = ",".join("?" for _ in cache_key_map)
cursor = await db.execute(
f"SELECT url, action, confidence, reason, suggested_group_name, analyzed_at, "
f"analysis_source, provider, model "
f"FROM url_analysis WHERE url IN ({placeholders}) AND analyzed_at >= ?",
[*cache_key_map.keys(), cutoff],
)
rows = await cursor.fetchall()
return {
cache_key_map[row["url"]]: {
"action": row["action"],
"confidence": row["confidence"],
"reason": row["reason"],
"suggestedGroupName": row["suggested_group_name"],
"analyzedAt": row["analyzed_at"],
"analysisSource": row["analysis_source"] or "provider",
"provider": row["provider"],
"model": row["model"],
}
for row in rows
}
async def save_url_analyses(
db: aiosqlite.Connection,
entries: list[dict[str, Any]],
) -> None:
if not entries:
return
await db.executemany(
"INSERT OR REPLACE INTO url_analysis "
"(url, action, confidence, reason, suggested_group_name, analyzed_at, analysis_source, provider, model) "
"VALUES (:url, :action, :confidence, :reason, :suggestedGroupName, :analyzedAt, :analysisSource, :provider, :model)",
entries,
)
await db.commit()
def build_tab_status_summary(statuses: list[TabAnalysisStatus]) -> TabAnalysisStatusSummary:
summary = TabAnalysisStatusSummary(total=len(statuses))
for status in statuses:
if status.status == "cached":
summary.cached += 1
elif status.status == "analyzed":
summary.analyzed += 1
elif status.status == "failed":
summary.failed += 1
else:
summary.pending += 1
return summary
def dedupe_strings(values: list[str]) -> list[str]:
return list(dict.fromkeys(values))
def normalize_theme_token(token: str) -> str | None:
normalized = token.strip(" _-+.#").lower()
if len(normalized) < 3:
return None
if normalized.isdigit():
return None
if normalized in THEME_STOPWORDS:
return None
return normalized
def tokenize_theme_text(text: str) -> list[str]:
if not text:
return []
cleaned = re.sub(r"[^0-9A-Za-zА-Яа-яЁё]+", " ", text.lower())
tokens = []
for part in cleaned.split():
normalized = normalize_theme_token(part)
if normalized:
tokens.append(normalized)
return dedupe_strings(tokens)
def extract_theme_tokens(tab: TabInput) -> list[str]:
parts = [tab.title, tab.groupName or ""]
try:
parsed = urlparse(tab.url)
parts.append(unquote(parsed.path).replace("/", " "))
query = parse_qs(parsed.query)
for key in THEME_QUERY_KEYS:
for value in query.get(key, [])[:1]:
parts.append(unquote(value))
except Exception:
pass
tokens: list[str] = []
for part in parts:
tokens.extend(tokenize_theme_text(part))
return dedupe_strings(tokens)
def format_theme_name(tokens: list[str]) -> str:
if not tokens:
return "Mixed Topic"
return " ".join(token.capitalize() for token in tokens[:2])
def build_topic_clusters_from_tabs(tabs: list[TabInput]) -> list[dict[str, Any]]:
if len(tabs) < 2:
return []
token_map = {tab.id: extract_theme_tokens(tab) for tab in tabs}
doc_freq: Counter[str] = Counter()
for tokens in token_map.values():
doc_freq.update(set(tokens))
max_common_frequency = max(6, int(len(tabs) * 0.45))
shared_tokens = {
tab.id: [
token
for token in token_map[tab.id]
if 2 <= doc_freq[token] <= max_common_frequency
][:8]
for tab in tabs
}
draft_clusters: list[dict[str, Any]] = []
for tab in sorted(tabs, key=lambda current: len(shared_tokens.get(current.id, [])), reverse=True):
tokens = shared_tokens.get(tab.id, [])
if not tokens:
continue
token_set = set(tokens)
best_index: int | None = None
best_score = 0
for index, cluster in enumerate(draft_clusters):
keywords = [token for token, _ in cluster["token_counts"].most_common(6)]
overlap = token_set & set(keywords)
if not overlap:
continue
top_overlap_frequency = max(doc_freq[token] for token in overlap)
score = len(overlap)
if score > best_score and (score >= 2 or top_overlap_frequency <= max(4, len(tabs) // 6 or 1)):
best_index = index
best_score = score
if best_index is None:
draft_clusters.append({
"tabs": [tab],
"token_counts": Counter(tokens),
})
continue
cluster_tabs = draft_clusters[best_index]["tabs"]
if all(existing.id != tab.id for existing in cluster_tabs):
cluster_tabs.append(tab)
draft_clusters[best_index]["token_counts"].update(tokens)
final_clusters: list[dict[str, Any]] = []
seen_signatures: set[tuple[str, tuple[int, ...]]] = set()
for cluster in draft_clusters:
cluster_tabs: list[TabInput] = cluster["tabs"]
if len(cluster_tabs) < 2:
continue
keywords = [token for token, _ in cluster["token_counts"].most_common(4)]
if not keywords:
continue
tab_ids = [tab.id for tab in cluster_tabs]
name = format_theme_name(keywords)
signature = (name.lower(), tuple(sorted(tab_ids)))
if signature in seen_signatures:
continue
seen_signatures.add(signature)
final_clusters.append({
"name": name,
"tabIds": tab_ids,
"tabUrls": [tab.url for tab in cluster_tabs],
"description": f"{len(tab_ids)} tabs around {', '.join(keywords[:3])}",
"tags": keywords,
})
final_clusters.sort(key=lambda cluster: (-len(cluster["tabIds"]), cluster["name"].lower()))
return final_clusters[:15]
def build_main_themes(tabs: list[TabInput], topic_clusters: list[dict[str, Any]]) -> list[str]:
if topic_clusters:
return [cluster["name"] for cluster in topic_clusters[:5]]
doc_freq: Counter[str] = Counter()
for tab in tabs:
doc_freq.update(set(extract_theme_tokens(tab)))
themes: list[str] = []
for token, count in doc_freq.most_common():
if count < 2:
continue
themes.append(format_theme_name([token]))
if len(themes) >= 5:
break
return themes
async def get_tab_analysis_statuses(
db: aiosqlite.Connection,
tabs: list[TabInput],
settings: AppSettings,
force_refresh: bool = False,
) -> list[TabAnalysisStatus]:
if not tabs:
return []
if force_refresh:
return [
TabAnalysisStatus(
tabId=tab.id,
url=tab.url,
title=tab.title,
domain=tab.domain,
status="pending",
source="pending",
)
for tab in tabs
]
cached = await get_cached_urls(
db,
[tab.url for tab in tabs],
build_cache_namespace(settings),
)
statuses: list[TabAnalysisStatus] = []
for tab in tabs:
entry = cached.get(tab.url)
if entry is None:
statuses.append(
TabAnalysisStatus(
tabId=tab.id,
url=tab.url,
title=tab.title,
domain=tab.domain,
status="pending",
source="pending",
)
)
continue
analyzed_at = entry.get("analyzedAt")
statuses.append(
TabAnalysisStatus(
tabId=tab.id,
url=tab.url,
title=tab.title,
domain=tab.domain,
status="cached",
source="database",
action=entry.get("action"),
confidence=float(entry["confidence"]) if entry.get("confidence") is not None else None,
reason=entry.get("reason"),
suggestedGroupName=entry.get("suggestedGroupName"),
analyzedAt=int(float(analyzed_at) * 1000) if analyzed_at is not None else None,
provider=entry.get("provider"),
model=entry.get("model"),
)
)
return statuses
async def save_session(db: aiosqlite.Connection, session: dict[str, Any]) -> None:
await db.execute(
"INSERT INTO analysis_sessions "
"(timestamp, tab_count, tabs_from_cache, tabs_analyzed, duration_ms, duration_api_ms, "
"wall_time_ms, total_cost_usd, input_tokens, output_tokens, action_breakdown_json) "
"VALUES (:timestamp, :tab_count, :tabs_from_cache, :tabs_analyzed, :duration_ms, "
":duration_api_ms, :wall_time_ms, :total_cost_usd, :input_tokens, :output_tokens, "
":action_breakdown_json)",
session,
)
await db.commit()
async def save_analysis_run(
db: aiosqlite.Connection,
snapshot: AnalysisRunSnapshot,
) -> None:
await db.execute(
"INSERT INTO analysis_runs "
"(id, fingerprint, status, started_at, updated_at, analyzed_at, state_json) "
"VALUES (?, ?, ?, ?, ?, ?, ?) "
"ON CONFLICT(id) DO UPDATE SET "
"fingerprint = excluded.fingerprint, "
"status = excluded.status, "
"started_at = excluded.started_at, "
"updated_at = excluded.updated_at, "
"analyzed_at = excluded.analyzed_at, "
"state_json = excluded.state_json",
(
snapshot.id,
snapshot.fingerprint,
snapshot.status,
snapshot.startedAt / 1000,
snapshot.updatedAt / 1000,
(snapshot.analyzedAt / 1000) if snapshot.analyzedAt is not None else None,
snapshot.model_dump_json(),
),
)
await db.commit()
async def get_analysis_run(
db: aiosqlite.Connection,
run_id: str,
) -> AnalysisRunSnapshot | None:
cursor = await db.execute(
"SELECT state_json FROM analysis_runs WHERE id = ?",
(run_id,),
)
row = await cursor.fetchone()
if row is None:
return None
return AnalysisRunSnapshot.model_validate_json(row["state_json"])
async def get_latest_analysis_run(
db: aiosqlite.Connection,
fingerprint: str | None = None,
) -> AnalysisRunSnapshot | None:
if fingerprint:
cursor = await db.execute(
"SELECT state_json FROM analysis_runs WHERE fingerprint = ? ORDER BY updated_at DESC, id DESC LIMIT 1",
(fingerprint,),
)
else:
cursor = await db.execute(
"SELECT state_json FROM analysis_runs ORDER BY updated_at DESC, id DESC LIMIT 1"
)
row = await cursor.fetchone()
if row is None:
return None
return AnalysisRunSnapshot.model_validate_json(row["state_json"])
async def trim_runtime_logs(db: aiosqlite.Connection) -> None:
await db.execute(
"DELETE FROM runtime_logs "
"WHERE id NOT IN (SELECT id FROM runtime_logs ORDER BY timestamp DESC, id DESC LIMIT ?)",
(MAX_RUNTIME_LOG_ENTRIES,),
)
await db.commit()