@glassly/miniapp 0.4.3-dev.1200 → 0.4.3-dev.1205
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/display/index.d.ts +2 -1
- package/dist/display/index.d.ts.map +1 -1
- package/dist/display/index.js +1 -1
- package/dist/display/index.js.map +1 -1
- package/dist/display/profiles/index.d.ts +2 -0
- package/dist/display/profiles/index.d.ts.map +1 -1
- package/dist/display/profiles/index.js +1 -0
- package/dist/display/profiles/index.js.map +1 -1
- package/dist/display/profiles/textProfile.d.ts +24 -0
- package/dist/display/profiles/textProfile.d.ts.map +1 -0
- package/dist/display/profiles/textProfile.js +52 -0
- package/dist/display/profiles/textProfile.js.map +1 -0
- package/dist/display/scene/process.d.ts.map +1 -1
- package/dist/display/scene/process.js +2 -3
- package/dist/display/scene/process.js.map +1 -1
- package/dist/host/actionInvoke.d.ts +44 -0
- package/dist/host/actionInvoke.d.ts.map +1 -0
- package/dist/host/actionInvoke.js +87 -0
- package/dist/host/actionInvoke.js.map +1 -0
- package/dist/host/gestureClaims.d.ts +37 -0
- package/dist/host/gestureClaims.d.ts.map +1 -0
- package/dist/host/gestureClaims.js +45 -0
- package/dist/host/gestureClaims.js.map +1 -0
- package/dist/host/index.d.ts +8 -0
- package/dist/host/index.d.ts.map +1 -1
- package/dist/host/index.js +9 -0
- package/dist/host/index.js.map +1 -1
- package/dist/host/manifestActions.d.ts +69 -0
- package/dist/host/manifestActions.d.ts.map +1 -0
- package/dist/host/manifestActions.js +89 -0
- package/dist/host/manifestActions.js.map +1 -0
- package/dist/host/memory/MemoryStore.d.ts +178 -0
- package/dist/host/memory/MemoryStore.d.ts.map +1 -0
- package/dist/host/memory/MemoryStore.js +615 -0
- package/dist/host/memory/MemoryStore.js.map +1 -0
- package/dist/host/memory/search.d.ts +72 -0
- package/dist/host/memory/search.d.ts.map +1 -0
- package/dist/host/memory/search.js +188 -0
- package/dist/host/memory/search.js.map +1 -0
- package/dist/host/miniappPermissions.d.ts +16 -0
- package/dist/host/miniappPermissions.d.ts.map +1 -0
- package/dist/host/miniappPermissions.js +7 -0
- package/dist/host/miniappPermissions.js.map +1 -0
- package/dist/host/settingsBridge.d.ts +49 -0
- package/dist/host/settingsBridge.d.ts.map +1 -0
- package/dist/host/settingsBridge.js +110 -0
- package/dist/host/settingsBridge.js.map +1 -0
- package/dist/host/widgetPlacements.d.ts +44 -0
- package/dist/host/widgetPlacements.d.ts.map +1 -0
- package/dist/host/widgetPlacements.js +84 -0
- package/dist/host/widgetPlacements.js.map +1 -0
- package/dist/session.d.ts +6 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js.map +1 -1
- package/package.json +2 -2
- package/src/display/index.ts +3 -0
- package/src/display/profiles/index.ts +3 -0
- package/src/display/profiles/textProfile.ts +66 -0
- package/src/display/scene/process.ts +2 -3
- package/src/host/actionInvoke.ts +110 -0
- package/src/host/gestureClaims.ts +77 -0
- package/src/host/index.ts +10 -0
- package/src/host/manifestActions.ts +152 -0
- package/src/host/memory/MemoryStore.ts +704 -0
- package/src/host/memory/search.ts +214 -0
- package/src/host/miniappPermissions.ts +19 -0
- package/src/host/settingsBridge.ts +119 -0
- package/src/host/widgetPlacements.ts +135 -0
- package/src/session.ts +6 -0
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MemoryStore — the user's shared, phone-local memory timeline.
|
|
3
|
+
*
|
|
4
|
+
* One unified per-hour stream of what happened around the user — spoken
|
|
5
|
+
* transcript lines AND notes (manual, voice, auto) in one timeline — plus the
|
|
6
|
+
* hourly conversation summary that heads each session. Scoped to the Glassly
|
|
7
|
+
* USER (not to a miniapp): every miniapp that declares the MEMORY manifest
|
|
8
|
+
* permission reads and writes the same store through LocalMiniappRuntime's
|
|
9
|
+
* MEMORY_* handlers, and Settings > Memory manages it via engine.memory.
|
|
10
|
+
*
|
|
11
|
+
* A "session" is one clock hour that has entries, derived from entry
|
|
12
|
+
* timestamps at read time — nothing is stored per-session, so there is no
|
|
13
|
+
* session id to keep in sync.
|
|
14
|
+
*
|
|
15
|
+
* The store began life inside the Assist miniapp (its SessionStore); on first
|
|
16
|
+
* load it migrates Assist's per-app storage namespace into the shared
|
|
17
|
+
* user-scoped keys so existing history survives the move.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type {
|
|
21
|
+
MemoryBackup,
|
|
22
|
+
MemoryEntry,
|
|
23
|
+
MemoryImportResult,
|
|
24
|
+
MemoryNoteSource,
|
|
25
|
+
MemorySession,
|
|
26
|
+
MemorySummary,
|
|
27
|
+
} from "../../modules/memory"
|
|
28
|
+
import {searchMemoryEntries} from "./search"
|
|
29
|
+
|
|
30
|
+
const KEY_ROOT = "memory_"
|
|
31
|
+
const LOG_SUFFIX = "log"
|
|
32
|
+
const SUMMARY_SUFFIX = "summaries"
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The pre-memory-layer Assist miniapp whose storage namespace we migrate.
|
|
36
|
+
* Assist now ships as com.glassly.assistant; the timeline it reads is
|
|
37
|
+
* user-scoped (KEY_ROOT below), so the rename needs no second migration and
|
|
38
|
+
* this constant stays pinned to the old namespace.
|
|
39
|
+
*/
|
|
40
|
+
const LEGACY_ASSIST_PACKAGE = "com.tetramo.assistant"
|
|
41
|
+
const LEGACY_STORAGE_ROOT = "localstorage_"
|
|
42
|
+
const LEGACY_LOG_KEY = "assistant:session-log"
|
|
43
|
+
const LEGACY_SUMMARY_KEY = "assistant:hourly-summaries"
|
|
44
|
+
// Assist's own pre-unification keys, migrated for users who never ran the
|
|
45
|
+
// unified-schema Assist build.
|
|
46
|
+
const LEGACY_TRANSCRIPT_KEY = "assistant:transcript-log"
|
|
47
|
+
const LEGACY_NOTES_KEY = "assistant:notes"
|
|
48
|
+
|
|
49
|
+
const HOUR_MS = 60 * 60 * 1000
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Physical bounds. There is no age cap: the timeline stays until the user
|
|
53
|
+
* deletes it (clear()/removeScope). The entry cap bounds the write cost —
|
|
54
|
+
* every persist re-serializes the whole timeline, so it is a perf ceiling as
|
|
55
|
+
* much as a product number — and the summary cap keeps one row per hour for
|
|
56
|
+
* about half a year of round-the-clock use, far longer at a normal pace.
|
|
57
|
+
*/
|
|
58
|
+
export const MEMORY_BOUNDS = {
|
|
59
|
+
maxEntries: 24_000,
|
|
60
|
+
maxSummaries: 4320,
|
|
61
|
+
}
|
|
62
|
+
const QUERY_LIMIT_CAP = 200
|
|
63
|
+
const QUERY_LIMIT_DEFAULT = 60
|
|
64
|
+
/**
|
|
65
|
+
* How long transcript appends coalesce before hitting disk. Each write
|
|
66
|
+
* re-serializes the entire timeline, so at conversational pace (a final
|
|
67
|
+
* utterance every few seconds) this turns O(n) work per line into O(n) per
|
|
68
|
+
* window. Short enough that an unexpected kill loses only the last few lines.
|
|
69
|
+
*/
|
|
70
|
+
const DEFAULT_WRITE_DEBOUNCE_MS = 3000
|
|
71
|
+
|
|
72
|
+
export interface MemoryStoreBackend {
|
|
73
|
+
get(key: string): unknown | null
|
|
74
|
+
set(key: string, value: unknown): void
|
|
75
|
+
remove(key: string): void
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface MemoryStoreHooks {
|
|
79
|
+
getUserId: () => Promise<string>
|
|
80
|
+
backend: MemoryStoreBackend
|
|
81
|
+
/**
|
|
82
|
+
* Debounce window for transcript-line writes, in ms. Appends coalesce into
|
|
83
|
+
* one serialization instead of re-stringifying the whole timeline per
|
|
84
|
+
* utterance. Set to 0 to persist synchronously (tests).
|
|
85
|
+
*/
|
|
86
|
+
writeDebounceMs?: number
|
|
87
|
+
timers?: MemoryStoreTimers
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The host's background-safe timer (the Glassly App's BgTimer); global timers when absent. */
|
|
91
|
+
export interface MemoryStoreTimers {
|
|
92
|
+
setTimeout(cb: () => void, ms: number): unknown
|
|
93
|
+
clearTimeout(id: unknown): void
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const globalTimers: MemoryStoreTimers = {
|
|
97
|
+
setTimeout: (cb, ms) => setTimeout(cb, ms),
|
|
98
|
+
clearTimeout: (id) => clearTimeout(id as ReturnType<typeof setTimeout>),
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface MemoryStats {
|
|
102
|
+
entryCount: number
|
|
103
|
+
lineCount: number
|
|
104
|
+
noteCount: number
|
|
105
|
+
summaryCount: number
|
|
106
|
+
/** Epoch ms of the oldest entry, or null when empty. */
|
|
107
|
+
oldestAt: number | null
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Thrown by importBackup for anything that isn't a backup this build can read. */
|
|
111
|
+
export class MemoryBackupError extends Error {
|
|
112
|
+
constructor(message: string) {
|
|
113
|
+
super(message)
|
|
114
|
+
this.name = "MemoryBackupError"
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function hourStartOf(ms: number): number {
|
|
119
|
+
return Math.floor(ms / HOUR_MS) * HOUR_MS
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function dayStartOf(ms: number): number {
|
|
123
|
+
const d = new Date(ms)
|
|
124
|
+
d.setHours(0, 0, 0, 0)
|
|
125
|
+
return d.getTime()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function makeId(): string {
|
|
129
|
+
return `e-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export class MemoryStore {
|
|
133
|
+
private entries: MemoryEntry[] = []
|
|
134
|
+
private summaries: MemorySummary[] = []
|
|
135
|
+
/** User the in-memory cache was loaded for; reload when identity changes. */
|
|
136
|
+
private loadedUserId: string | null = null
|
|
137
|
+
private loadPromise: Promise<void> | null = null
|
|
138
|
+
private readonly changeListeners = new Set<() => void>()
|
|
139
|
+
/** Pending debounced log write (transcript appends), if any. */
|
|
140
|
+
private logFlushTimer: unknown = null
|
|
141
|
+
private logDirty = false
|
|
142
|
+
|
|
143
|
+
constructor(private readonly hooks: MemoryStoreHooks) {}
|
|
144
|
+
|
|
145
|
+
private get timers(): MemoryStoreTimers {
|
|
146
|
+
return this.hooks.timers ?? globalTimers
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Write any debounced changes out now. Call before the app backgrounds or
|
|
151
|
+
* terminates so a crash can't lose the coalesced tail of the timeline.
|
|
152
|
+
*/
|
|
153
|
+
async flush(): Promise<void> {
|
|
154
|
+
if (this.logFlushTimer) {
|
|
155
|
+
this.timers.clearTimeout(this.logFlushTimer)
|
|
156
|
+
this.logFlushTimer = null
|
|
157
|
+
}
|
|
158
|
+
if (this.logDirty) await this.persistLog()
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Subscribe to mutations (adds, edits, deletes, clears). */
|
|
162
|
+
onChanged(listener: () => void): () => void {
|
|
163
|
+
this.changeListeners.add(listener)
|
|
164
|
+
return () => this.changeListeners.delete(listener)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// === Writes ===
|
|
168
|
+
|
|
169
|
+
async appendLine(input: {
|
|
170
|
+
text: string
|
|
171
|
+
speakerId: string | null
|
|
172
|
+
/** Resolved enrolled-speaker name (on-device speaker ID), when known. */
|
|
173
|
+
resolvedSpeakerName?: string | null
|
|
174
|
+
language: string | null
|
|
175
|
+
at: number
|
|
176
|
+
}): Promise<void> {
|
|
177
|
+
if (!input.text.trim()) return
|
|
178
|
+
await this.ensureLoaded()
|
|
179
|
+
this.entries.push({
|
|
180
|
+
id: makeId(),
|
|
181
|
+
kind: "line",
|
|
182
|
+
text: input.text.trim(),
|
|
183
|
+
at: input.at,
|
|
184
|
+
speakerId: input.speakerId,
|
|
185
|
+
...(input.resolvedSpeakerName ? {resolvedSpeakerName: input.resolvedSpeakerName} : {}),
|
|
186
|
+
language: input.language,
|
|
187
|
+
})
|
|
188
|
+
this.prune()
|
|
189
|
+
// Transcript lines are the hot path (one per final utterance) and each
|
|
190
|
+
// persist re-serializes the whole timeline, so coalesce them. Everything
|
|
191
|
+
// else — notes, edits, deletes, summaries — still writes through
|
|
192
|
+
// immediately; those are user-visible and rare.
|
|
193
|
+
await this.schedulePersistLog()
|
|
194
|
+
this.emitChanged()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Add a note. `at` targets the hour it belongs to — pass a timestamp inside
|
|
199
|
+
* a past hour to append to that session. Dedupes on normalized text within
|
|
200
|
+
* the same hour (auto-notes re-extract); resolves null on duplicate/empty.
|
|
201
|
+
*/
|
|
202
|
+
async addNote(text: string, source: MemoryNoteSource, at: number = Date.now()): Promise<MemoryEntry | null> {
|
|
203
|
+
const body = text.trim()
|
|
204
|
+
if (!body) return null
|
|
205
|
+
await this.ensureLoaded()
|
|
206
|
+
const hour = hourStartOf(at)
|
|
207
|
+
const key = normalize(body)
|
|
208
|
+
if (this.entries.some((e) => e.kind === "note" && hourStartOf(e.at) === hour && normalize(e.text) === key)) {
|
|
209
|
+
return null
|
|
210
|
+
}
|
|
211
|
+
const entry: MemoryEntry = {id: makeId(), kind: "note", text: body, at, speakerId: null, language: null, source}
|
|
212
|
+
this.entries.push(entry)
|
|
213
|
+
this.entries.sort((a, b) => a.at - b.at)
|
|
214
|
+
this.prune()
|
|
215
|
+
await this.persistLog()
|
|
216
|
+
this.emitChanged()
|
|
217
|
+
return entry
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Rewrite a note's text in place (Settings > Memory edit). */
|
|
221
|
+
async updateNote(id: string, text: string): Promise<boolean> {
|
|
222
|
+
const body = text.trim()
|
|
223
|
+
if (!body) return false
|
|
224
|
+
await this.ensureLoaded()
|
|
225
|
+
const entry = this.entries.find((e) => e.id === id && e.kind === "note")
|
|
226
|
+
if (!entry) return false
|
|
227
|
+
entry.text = body
|
|
228
|
+
await this.persistLog()
|
|
229
|
+
this.emitChanged()
|
|
230
|
+
return true
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async removeEntry(id: string): Promise<boolean> {
|
|
234
|
+
await this.ensureLoaded()
|
|
235
|
+
const before = this.entries.length
|
|
236
|
+
this.entries = this.entries.filter((e) => e.id !== id)
|
|
237
|
+
if (this.entries.length === before) return false
|
|
238
|
+
await this.persistLog()
|
|
239
|
+
this.emitChanged()
|
|
240
|
+
return true
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Delete every entry (and summary) in an hour, or a whole day of hours. */
|
|
244
|
+
async removeScope(scope: "session" | "day", at: number): Promise<void> {
|
|
245
|
+
await this.ensureLoaded()
|
|
246
|
+
const inScope =
|
|
247
|
+
scope === "day"
|
|
248
|
+
? (ms: number) => dayStartOf(ms) === dayStartOf(at)
|
|
249
|
+
: (ms: number) => hourStartOf(ms) === hourStartOf(at)
|
|
250
|
+
this.entries = this.entries.filter((e) => !inScope(e.at))
|
|
251
|
+
this.summaries = this.summaries.filter((s) => !inScope(s.hourStart))
|
|
252
|
+
await this.persistLog()
|
|
253
|
+
await this.persistSummaries()
|
|
254
|
+
this.emitChanged()
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Drop the entire timeline: every entry and every summary. */
|
|
258
|
+
async clear(): Promise<void> {
|
|
259
|
+
await this.ensureLoaded()
|
|
260
|
+
this.entries = []
|
|
261
|
+
this.summaries = []
|
|
262
|
+
await this.persistLog()
|
|
263
|
+
await this.persistSummaries()
|
|
264
|
+
this.emitChanged()
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async addSummary(summary: MemorySummary): Promise<void> {
|
|
268
|
+
await this.ensureLoaded()
|
|
269
|
+
const {maxSummaries} = MEMORY_BOUNDS
|
|
270
|
+
this.summaries = this.summaries.filter((s) => s.hourStart !== summary.hourStart)
|
|
271
|
+
this.summaries.push(summary)
|
|
272
|
+
if (this.summaries.length > maxSummaries) {
|
|
273
|
+
this.summaries = this.summaries.sort((a, b) => a.hourStart - b.hourStart).slice(-maxSummaries)
|
|
274
|
+
}
|
|
275
|
+
await this.persistSummaries()
|
|
276
|
+
this.emitChanged()
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// === Reads === (the whole stored timeline; nothing is hidden by age)
|
|
280
|
+
|
|
281
|
+
/** Entries in [sinceMs, untilMs), newest last. */
|
|
282
|
+
async window(sinceMs: number, untilMs: number = Date.now()): Promise<MemoryEntry[]> {
|
|
283
|
+
await this.ensureLoaded()
|
|
284
|
+
return this.entries.filter((e) => e.at >= sinceMs && e.at < untilMs)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** All note entries, newest first (Settings > Memory list). */
|
|
288
|
+
async notes(): Promise<MemoryEntry[]> {
|
|
289
|
+
await this.ensureLoaded()
|
|
290
|
+
return this.entries.filter((e) => e.kind === "note").sort((a, b) => b.at - a.at)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async stats(): Promise<MemoryStats> {
|
|
294
|
+
await this.ensureLoaded()
|
|
295
|
+
const visible = this.entries
|
|
296
|
+
const noteCount = visible.filter((e) => e.kind === "note").length
|
|
297
|
+
return {
|
|
298
|
+
entryCount: visible.length,
|
|
299
|
+
lineCount: visible.length - noteCount,
|
|
300
|
+
noteCount,
|
|
301
|
+
summaryCount: this.summaries.filter((s) => s.text.trim()).length,
|
|
302
|
+
oldestAt: visible.length > 0 ? visible[0].at : null,
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** All sessions (hours with entries), newest hour first. */
|
|
307
|
+
async sessionList(): Promise<MemorySession[]> {
|
|
308
|
+
await this.ensureLoaded()
|
|
309
|
+
const byHour = new Map<number, MemoryEntry[]>()
|
|
310
|
+
for (const e of this.entries) {
|
|
311
|
+
const h = hourStartOf(e.at)
|
|
312
|
+
const list = byHour.get(h) ?? []
|
|
313
|
+
list.push(e)
|
|
314
|
+
byHour.set(h, list)
|
|
315
|
+
}
|
|
316
|
+
const summaryByHour = new Map(this.summaries.map((s) => [s.hourStart, s.text]))
|
|
317
|
+
return [...byHour.entries()]
|
|
318
|
+
.map(([hourStart, entries]) => {
|
|
319
|
+
entries.sort((a, b) => a.at - b.at)
|
|
320
|
+
return {
|
|
321
|
+
hourStart,
|
|
322
|
+
entries,
|
|
323
|
+
summary: (summaryByHour.get(hourStart) ?? "").trim() || null,
|
|
324
|
+
lineCount: entries.filter((e) => e.kind === "line").length,
|
|
325
|
+
noteCount: entries.filter((e) => e.kind === "note").length,
|
|
326
|
+
}
|
|
327
|
+
})
|
|
328
|
+
.sort((a, b) => b.hourStart - a.hourStart)
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Query the FULL store by absolute-time window and keyword — the executor
|
|
333
|
+
* behind LLM history-search tools. Newest last, so the limit keeps the most
|
|
334
|
+
* recent matches. `contains` is an exact substring; `terms` is fuzzy any-of
|
|
335
|
+
* matching (mistranscribed-name tolerant) — see search.ts.
|
|
336
|
+
*/
|
|
337
|
+
async query(q: {
|
|
338
|
+
sinceMs?: number
|
|
339
|
+
untilMs?: number
|
|
340
|
+
contains?: string
|
|
341
|
+
terms?: string[]
|
|
342
|
+
limit?: number
|
|
343
|
+
}): Promise<MemoryEntry[]> {
|
|
344
|
+
return (await this.search(q)).entries
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* query() plus `windowCount` — how many entries the TIME window held before
|
|
349
|
+
* keyword filtering, so an LLM caller can distinguish "keyword matched
|
|
350
|
+
* nothing" from "history doesn't reach that far back" without a retry.
|
|
351
|
+
*/
|
|
352
|
+
async search(q: {
|
|
353
|
+
sinceMs?: number
|
|
354
|
+
untilMs?: number
|
|
355
|
+
contains?: string
|
|
356
|
+
terms?: string[]
|
|
357
|
+
limit?: number
|
|
358
|
+
}): Promise<{entries: MemoryEntry[]; windowCount: number}> {
|
|
359
|
+
await this.ensureLoaded()
|
|
360
|
+
const limit = q.limit && q.limit > 0 ? Math.min(q.limit, QUERY_LIMIT_CAP) : QUERY_LIMIT_DEFAULT
|
|
361
|
+
return searchMemoryEntries(this.entries, {
|
|
362
|
+
sinceMs: q.sinceMs,
|
|
363
|
+
untilMs: q.untilMs,
|
|
364
|
+
contains: q.contains,
|
|
365
|
+
terms: q.terms,
|
|
366
|
+
limit,
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async summaryList(): Promise<MemorySummary[]> {
|
|
371
|
+
await this.ensureLoaded()
|
|
372
|
+
return [...this.summaries].sort((a, b) => b.hourStart - a.hourStart)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Most recent COMPLETED hour with lines but no summary, or null. */
|
|
376
|
+
async pendingSummaryHour(nowMs: number = Date.now()): Promise<number | null> {
|
|
377
|
+
await this.ensureLoaded()
|
|
378
|
+
const currentHour = hourStartOf(nowMs)
|
|
379
|
+
const summarized = new Set(this.summaries.map((s) => s.hourStart))
|
|
380
|
+
const hours = new Set<number>()
|
|
381
|
+
for (const e of this.entries) {
|
|
382
|
+
if (e.kind !== "line") continue
|
|
383
|
+
const h = hourStartOf(e.at)
|
|
384
|
+
if (h < currentHour && !summarized.has(h)) hours.add(h)
|
|
385
|
+
}
|
|
386
|
+
if (hours.size === 0) return null
|
|
387
|
+
return Math.max(...hours)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** The whole timeline as a backup file body (Settings > Memory, session.memory.exportFile). */
|
|
391
|
+
async exportBackup(): Promise<MemoryBackup> {
|
|
392
|
+
await this.ensureLoaded()
|
|
393
|
+
return {
|
|
394
|
+
format: "glassly-memory",
|
|
395
|
+
version: 1,
|
|
396
|
+
exportedAt: Date.now(),
|
|
397
|
+
entries: [...this.entries],
|
|
398
|
+
summaries: [...this.summaries].sort((a, b) => a.hourStart - b.hourStart),
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Merge a backup into the timeline. Skips entries whose id is stored, notes
|
|
404
|
+
* whose text is already in the same hour, and hours that already have a
|
|
405
|
+
* summary. Throws MemoryBackupError when `data` isn't a memory backup.
|
|
406
|
+
*/
|
|
407
|
+
async importBackup(data: unknown): Promise<MemoryImportResult> {
|
|
408
|
+
const backup = parseBackup(data)
|
|
409
|
+
await this.ensureLoaded()
|
|
410
|
+
const result: MemoryImportResult = {entries: 0, summaries: 0, skipped: 0}
|
|
411
|
+
|
|
412
|
+
const ids = new Set(this.entries.map((e) => e.id))
|
|
413
|
+
const noteKeys = new Set(this.entries.filter((e) => e.kind === "note").map(noteKey))
|
|
414
|
+
for (const entry of backup.entries) {
|
|
415
|
+
const key = entry.kind === "note" ? noteKey(entry) : null
|
|
416
|
+
if (ids.has(entry.id) || (key != null && noteKeys.has(key))) {
|
|
417
|
+
result.skipped++
|
|
418
|
+
continue
|
|
419
|
+
}
|
|
420
|
+
ids.add(entry.id)
|
|
421
|
+
if (key != null) noteKeys.add(key)
|
|
422
|
+
this.entries.push(entry)
|
|
423
|
+
result.entries++
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const byHour = new Map(this.summaries.map((s) => [s.hourStart, s]))
|
|
427
|
+
for (const summary of backup.summaries) {
|
|
428
|
+
if (byHour.get(summary.hourStart)?.text.trim()) {
|
|
429
|
+
result.skipped++
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
byHour.set(summary.hourStart, summary)
|
|
433
|
+
result.summaries++
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (result.entries > 0) {
|
|
437
|
+
this.entries.sort((a, b) => a.at - b.at)
|
|
438
|
+
this.prune()
|
|
439
|
+
await this.persistLog()
|
|
440
|
+
}
|
|
441
|
+
if (result.summaries > 0) {
|
|
442
|
+
this.summaries = [...byHour.values()].sort((a, b) => a.hourStart - b.hourStart).slice(-MEMORY_BOUNDS.maxSummaries)
|
|
443
|
+
await this.persistSummaries()
|
|
444
|
+
}
|
|
445
|
+
if (result.entries > 0 || result.summaries > 0) this.emitChanged()
|
|
446
|
+
return result
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Plain-text export of a scope, for the OS share sheet. */
|
|
450
|
+
async exportText(scope: "session" | "day" | "all", at?: number): Promise<string> {
|
|
451
|
+
const sessions = (await this.sessionList()).filter((s) => {
|
|
452
|
+
if (scope === "all") return true
|
|
453
|
+
if (at == null) return false
|
|
454
|
+
if (scope === "day") return dayStartOf(s.hourStart) === dayStartOf(at)
|
|
455
|
+
return s.hourStart === hourStartOf(at)
|
|
456
|
+
})
|
|
457
|
+
if (sessions.length === 0) return "No session history to export."
|
|
458
|
+
|
|
459
|
+
const dayFmt = (ms: number) =>
|
|
460
|
+
new Date(ms).toLocaleDateString(undefined, {weekday: "long", year: "numeric", month: "long", day: "numeric"})
|
|
461
|
+
const hourFmt = (ms: number) => new Date(ms).toLocaleTimeString(undefined, {hour: "numeric"})
|
|
462
|
+
const timeFmt = (ms: number) => new Date(ms).toLocaleTimeString(undefined, {hour: "numeric", minute: "2-digit"})
|
|
463
|
+
|
|
464
|
+
const parts: string[] = []
|
|
465
|
+
let lastDay: number | null = null
|
|
466
|
+
for (const s of [...sessions].sort((a, b) => a.hourStart - b.hourStart)) {
|
|
467
|
+
const day = dayStartOf(s.hourStart)
|
|
468
|
+
if (day !== lastDay) {
|
|
469
|
+
parts.push(`\n=== ${dayFmt(day)} ===`)
|
|
470
|
+
lastDay = day
|
|
471
|
+
}
|
|
472
|
+
parts.push(`\n[${hourFmt(s.hourStart)}–${hourFmt(s.hourStart + HOUR_MS)}]`)
|
|
473
|
+
if (s.summary) parts.push(`Summary: ${s.summary}`)
|
|
474
|
+
for (const e of s.entries) {
|
|
475
|
+
const who = e.kind === "note" ? "NOTE" : (e.speakerId ?? "—")
|
|
476
|
+
parts.push(` ${timeFmt(e.at)} ${who}: ${e.text}`)
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return `Memory session history\n${parts.join("\n").trim()}\n`
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// === Load / persist ===
|
|
483
|
+
|
|
484
|
+
private async ensureLoaded(): Promise<void> {
|
|
485
|
+
const userId = (await this.hooks.getUserId()).trim()
|
|
486
|
+
if (!userId) throw new Error("Glassly user identity is unavailable")
|
|
487
|
+
if (this.loadedUserId === userId) return
|
|
488
|
+
if (!this.loadPromise) {
|
|
489
|
+
this.loadPromise = this.loadFor(userId).finally(() => {
|
|
490
|
+
this.loadPromise = null
|
|
491
|
+
})
|
|
492
|
+
}
|
|
493
|
+
await this.loadPromise
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
private async loadFor(userId: string): Promise<void> {
|
|
497
|
+
// Don't let an identity switch discard lines still sitting in the debounce
|
|
498
|
+
// window — they belong to the OUTGOING user, whose key is still loaded.
|
|
499
|
+
await this.flush()
|
|
500
|
+
this.entries = []
|
|
501
|
+
this.summaries = []
|
|
502
|
+
const rawLog = this.hooks.backend.get(this.key(userId, LOG_SUFFIX))
|
|
503
|
+
if (rawLog != null) {
|
|
504
|
+
this.entries = parseArray(rawLog).filter(isEntry)
|
|
505
|
+
} else {
|
|
506
|
+
this.migrateFromAssist(userId)
|
|
507
|
+
}
|
|
508
|
+
const rawSummaries = this.hooks.backend.get(this.key(userId, SUMMARY_SUFFIX))
|
|
509
|
+
if (rawSummaries != null) {
|
|
510
|
+
this.summaries = parseArray(rawSummaries).filter(isSummary)
|
|
511
|
+
}
|
|
512
|
+
this.loadedUserId = userId
|
|
513
|
+
this.prune()
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* One-time migration: fold the Assist miniapp's per-app store (the previous
|
|
518
|
+
* home of this timeline) into the shared user-scoped keys. Assist's old keys
|
|
519
|
+
* are left in place; its new build reads through the memory bridge instead.
|
|
520
|
+
*/
|
|
521
|
+
private migrateFromAssist(userId: string): void {
|
|
522
|
+
const legacyPrefix = `${LEGACY_STORAGE_ROOT}${userId}_${LEGACY_ASSIST_PACKAGE}_`
|
|
523
|
+
try {
|
|
524
|
+
const migrated: MemoryEntry[] = []
|
|
525
|
+
const rawLog = this.hooks.backend.get(legacyPrefix + LEGACY_LOG_KEY)
|
|
526
|
+
if (rawLog != null) {
|
|
527
|
+
migrated.push(...parseArray(rawLog).filter(isEntry))
|
|
528
|
+
} else {
|
|
529
|
+
// Pre-unification Assist: separate transcript log + notes stores.
|
|
530
|
+
for (const v of parseArray(this.hooks.backend.get(legacyPrefix + LEGACY_TRANSCRIPT_KEY))) {
|
|
531
|
+
const e = v as Record<string, unknown>
|
|
532
|
+
if (typeof e.text === "string" && typeof e.at === "number") {
|
|
533
|
+
migrated.push({
|
|
534
|
+
id: makeId(),
|
|
535
|
+
kind: "line",
|
|
536
|
+
text: e.text,
|
|
537
|
+
at: e.at,
|
|
538
|
+
speakerId: typeof e.speakerId === "string" ? e.speakerId : null,
|
|
539
|
+
language: typeof e.language === "string" ? e.language : null,
|
|
540
|
+
})
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
for (const v of parseArray(this.hooks.backend.get(legacyPrefix + LEGACY_NOTES_KEY))) {
|
|
544
|
+
const n = v as Record<string, unknown>
|
|
545
|
+
if (typeof n.text === "string" && typeof n.createdAt === "number") {
|
|
546
|
+
migrated.push({
|
|
547
|
+
id: makeId(),
|
|
548
|
+
kind: "note",
|
|
549
|
+
text: n.text,
|
|
550
|
+
at: n.createdAt,
|
|
551
|
+
speakerId: null,
|
|
552
|
+
language: null,
|
|
553
|
+
source: n.source === "voice" || n.source === "auto" ? n.source : "ui",
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
migrated.sort((a, b) => a.at - b.at)
|
|
559
|
+
this.entries = migrated
|
|
560
|
+
if (migrated.length > 0) this.hooks.backend.set(this.key(userId, LOG_SUFFIX), JSON.stringify(migrated))
|
|
561
|
+
|
|
562
|
+
const rawSummaries = this.hooks.backend.get(legacyPrefix + LEGACY_SUMMARY_KEY)
|
|
563
|
+
if (rawSummaries != null) {
|
|
564
|
+
const summaries = parseArray(rawSummaries).filter(isSummary)
|
|
565
|
+
this.summaries = summaries
|
|
566
|
+
if (summaries.length > 0) this.hooks.backend.set(this.key(userId, SUMMARY_SUFFIX), JSON.stringify(summaries))
|
|
567
|
+
}
|
|
568
|
+
if (this.entries.length > 0 || this.summaries.length > 0) {
|
|
569
|
+
console.log(
|
|
570
|
+
`MemoryStore: migrated ${this.entries.length} entries + ${this.summaries.length} summaries from Assist`,
|
|
571
|
+
)
|
|
572
|
+
}
|
|
573
|
+
} catch (err) {
|
|
574
|
+
console.warn("MemoryStore: Assist migration failed:", err instanceof Error ? err.message : err)
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** Keep the newest MEMORY_BOUNDS.maxEntries; nothing goes for age — deleting is the user's call. */
|
|
579
|
+
private prune(): void {
|
|
580
|
+
const {maxEntries} = MEMORY_BOUNDS
|
|
581
|
+
if (this.entries.length > maxEntries) this.entries = this.entries.slice(-maxEntries)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
private key(userId: string, suffix: string): string {
|
|
585
|
+
return `${KEY_ROOT}${userId}_${suffix}`
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Mark the log dirty and arm the debounce timer. Repeated appends inside the
|
|
590
|
+
* window collapse into a single serialization; the first append after a
|
|
591
|
+
* flush starts a fresh window (trailing-edge, so a steady stream of speech
|
|
592
|
+
* still lands on disk every `writeDebounceMs`).
|
|
593
|
+
*/
|
|
594
|
+
private async schedulePersistLog(): Promise<void> {
|
|
595
|
+
const delay = this.hooks.writeDebounceMs ?? DEFAULT_WRITE_DEBOUNCE_MS
|
|
596
|
+
if (delay <= 0) return this.persistLog()
|
|
597
|
+
this.logDirty = true
|
|
598
|
+
if (this.logFlushTimer) return
|
|
599
|
+
this.logFlushTimer = this.timers.setTimeout(() => {
|
|
600
|
+
this.logFlushTimer = null
|
|
601
|
+
void this.persistLog().catch((err) =>
|
|
602
|
+
console.warn("MemoryStore: debounced log write failed:", err instanceof Error ? err.message : err),
|
|
603
|
+
)
|
|
604
|
+
}, delay)
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
private async persistLog(): Promise<void> {
|
|
608
|
+
// Any write of the full array satisfies whatever the debounce was holding.
|
|
609
|
+
this.logDirty = false
|
|
610
|
+
if (this.logFlushTimer) {
|
|
611
|
+
this.timers.clearTimeout(this.logFlushTimer)
|
|
612
|
+
this.logFlushTimer = null
|
|
613
|
+
}
|
|
614
|
+
if (this.loadedUserId == null) return
|
|
615
|
+
this.hooks.backend.set(this.key(this.loadedUserId, LOG_SUFFIX), JSON.stringify(this.entries))
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
private async persistSummaries(): Promise<void> {
|
|
619
|
+
if (this.loadedUserId == null) return
|
|
620
|
+
this.hooks.backend.set(this.key(this.loadedUserId, SUMMARY_SUFFIX), JSON.stringify(this.summaries))
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
private emitChanged(): void {
|
|
624
|
+
for (const listener of this.changeListeners) {
|
|
625
|
+
try {
|
|
626
|
+
listener()
|
|
627
|
+
} catch (err) {
|
|
628
|
+
console.warn("MemoryStore: onChanged listener threw:", err instanceof Error ? err.message : err)
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Stored values may be a JSON string (SimpleStorage writes) or a raw array. */
|
|
635
|
+
function parseArray(raw: unknown): unknown[] {
|
|
636
|
+
try {
|
|
637
|
+
if (typeof raw === "string") {
|
|
638
|
+
const parsed = JSON.parse(raw) as unknown
|
|
639
|
+
return Array.isArray(parsed) ? parsed : []
|
|
640
|
+
}
|
|
641
|
+
return Array.isArray(raw) ? raw : []
|
|
642
|
+
} catch {
|
|
643
|
+
return []
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function normalize(text: string): string {
|
|
648
|
+
return text
|
|
649
|
+
.toLowerCase()
|
|
650
|
+
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
|
651
|
+
.trim()
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function noteKey(entry: MemoryEntry): string {
|
|
655
|
+
return `${hourStartOf(entry.at)}:${normalize(entry.text)}`
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function parseBackup(data: unknown): {entries: MemoryEntry[]; summaries: MemorySummary[]} {
|
|
659
|
+
const raw = data as Record<string, unknown> | null
|
|
660
|
+
if (!raw || typeof raw !== "object" || raw.format !== "glassly-memory" || !Array.isArray(raw.entries)) {
|
|
661
|
+
throw new MemoryBackupError("Not a Glassly memory backup")
|
|
662
|
+
}
|
|
663
|
+
if (typeof raw.version !== "number" || raw.version > 1) {
|
|
664
|
+
throw new MemoryBackupError(`Unsupported memory backup version ${String(raw.version)}`)
|
|
665
|
+
}
|
|
666
|
+
const entries: MemoryEntry[] = []
|
|
667
|
+
for (const v of raw.entries) {
|
|
668
|
+
if (!isEntry(v) || !v.id || !v.text.trim() || !Number.isFinite(v.at)) continue
|
|
669
|
+
entries.push({
|
|
670
|
+
id: v.id,
|
|
671
|
+
kind: v.kind,
|
|
672
|
+
text: v.text.trim(),
|
|
673
|
+
at: v.at,
|
|
674
|
+
speakerId: typeof v.speakerId === "string" ? v.speakerId : null,
|
|
675
|
+
...(typeof v.resolvedSpeakerName === "string" && v.resolvedSpeakerName
|
|
676
|
+
? {resolvedSpeakerName: v.resolvedSpeakerName}
|
|
677
|
+
: {}),
|
|
678
|
+
language: typeof v.language === "string" ? v.language : null,
|
|
679
|
+
...(v.kind === "note" ? {source: v.source === "voice" || v.source === "auto" ? v.source : "ui"} : {}),
|
|
680
|
+
})
|
|
681
|
+
}
|
|
682
|
+
const summaries = (Array.isArray(raw.summaries) ? raw.summaries : [])
|
|
683
|
+
.filter(isSummary)
|
|
684
|
+
.filter((s) => s.text.trim() && Number.isFinite(s.hourStart))
|
|
685
|
+
.map((s) => ({hourStart: s.hourStart, text: s.text, createdAt: s.createdAt}))
|
|
686
|
+
return {entries, summaries}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function isEntry(v: unknown): v is MemoryEntry {
|
|
690
|
+
if (!v || typeof v !== "object") return false
|
|
691
|
+
const e = v as Record<string, unknown>
|
|
692
|
+
return (
|
|
693
|
+
typeof e.id === "string" &&
|
|
694
|
+
(e.kind === "line" || e.kind === "note") &&
|
|
695
|
+
typeof e.text === "string" &&
|
|
696
|
+
typeof e.at === "number"
|
|
697
|
+
)
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function isSummary(v: unknown): v is MemorySummary {
|
|
701
|
+
if (!v || typeof v !== "object") return false
|
|
702
|
+
const s = v as Record<string, unknown>
|
|
703
|
+
return typeof s.hourStart === "number" && typeof s.text === "string" && typeof s.createdAt === "number"
|
|
704
|
+
}
|