-
Notifications
You must be signed in to change notification settings - Fork 249
[Prototype] AI-based formula bar #3442
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
luke-quadratic
wants to merge
15
commits into
qa
Choose a base branch
from
cell-based-ai
base: qa
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 12 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
9d12199
init
luke-quadratic d4e54c3
updates
luke-quadratic e9d3e80
updates
luke-quadratic 168fe19
update
luke-quadratic 3030154
updates
luke-quadratic 4de89c5
update
luke-quadratic 6d53040
update
luke-quadratic 9facd3f
update
luke-quadratic 4808a62
small
luke-quadratic faf4d03
graphite
luke-quadratic 80cdb75
graphite
luke-quadratic b7ea9f9
update
luke-quadratic f2547db
dseign
luke-quadratic fed2748
update
luke-quadratic 514e051
graphite
luke-quadratic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
269 changes: 269 additions & 0 deletions
269
quadratic-client/src/app/ai/utils/aiCodeCellSummaryStore.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,269 @@ | ||
/** | ||
* Client-side storage for AI-generated code cell summaries | ||
* This stores summaries in memory and optionally persists them to localStorage | ||
*/ | ||
|
||
import { events } from '@/app/events/events'; | ||
import type { JsUpdateCodeCell } from '@/app/quadratic-core-types'; | ||
|
||
interface CodeCellSummary { | ||
sheetId: string; | ||
x: number; | ||
y: number; | ||
summary: string; | ||
codeString: string; // Store code string to detect changes | ||
timestamp: number; | ||
} | ||
|
||
class AICodeCellSummaryStore { | ||
private summaries = new Map<string, CodeCellSummary>(); | ||
private readonly STORAGE_KEY = 'quadratic_ai_code_cell_summaries'; | ||
private readonly MAX_SUMMARIES = 1000; // Limit to prevent memory issues | ||
private saveTimeoutId: NodeJS.Timeout | null = null; | ||
private readonly SAVE_DEBOUNCE_MS = 500; // Debounce localStorage writes by 500ms | ||
|
||
constructor() { | ||
this.loadFromStorage(); | ||
|
||
// Listen for code cell updates to clean up deleted cells | ||
events.on('updateCodeCells', this.handleCodeCellUpdates); | ||
|
||
// Ensure data is saved before page unload | ||
if (typeof window !== 'undefined') { | ||
window.addEventListener('beforeunload', () => { | ||
this.flushToStorage(); | ||
}); | ||
} | ||
luke-quadratic marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
private getKey(sheetId: string, x: number, y: number): string { | ||
return `${sheetId}:${x}:${y}`; | ||
} | ||
|
||
/** | ||
* Handle code cell updates to clean up AI summaries for deleted cells | ||
*/ | ||
private handleCodeCellUpdates = (updateCodeCells: JsUpdateCodeCell[]): void => { | ||
let hasChanges = false; | ||
|
||
for (const update of updateCodeCells) { | ||
// If render_code_cell is null, the code cell was deleted | ||
if (!update.render_code_cell) { | ||
const sheetId = update.sheet_id.id; | ||
const x = Number(update.pos.x); | ||
const y = Number(update.pos.y); | ||
const key = this.getKey(sheetId, x, y); | ||
|
||
if (this.summaries.has(key)) { | ||
console.log('[aiCodeCellSummaryStore] Cleaning up AI summary for deleted code cell:', key); | ||
this.summaries.delete(key); | ||
hasChanges = true; | ||
} | ||
} | ||
} | ||
|
||
// Only trigger save if we actually removed summaries | ||
if (hasChanges) { | ||
this.debouncedSaveToStorage(); | ||
} | ||
}; | ||
|
||
/** | ||
* Store a summary for an AI-generated code cell | ||
*/ | ||
setSummary(sheetId: string, x: number, y: number, summary: string, codeString: string): void { | ||
const key = this.getKey(sheetId, x, y); | ||
console.log('[aiCodeCellSummaryStore] Storing summary for key:', key, 'summary:', summary); | ||
|
||
this.summaries.set(key, { | ||
sheetId, | ||
x, | ||
y, | ||
summary, | ||
codeString, | ||
timestamp: Date.now(), | ||
}); | ||
|
||
// Limit the number of stored summaries | ||
if (this.summaries.size > this.MAX_SUMMARIES) { | ||
this.cleanupOldSummaries(); | ||
} | ||
|
||
this.debouncedSaveToStorage(); | ||
console.log('[aiCodeCellSummaryStore] Total summaries stored:', this.summaries.size); | ||
} | ||
|
||
/** | ||
* Get a summary for a code cell | ||
* Returns null if no summary exists or if the code has changed | ||
*/ | ||
getSummary(sheetId: string, x: number, y: number, currentCodeString?: string): string | null { | ||
const key = this.getKey(sheetId, x, y); | ||
const summary = this.summaries.get(key); | ||
console.log('[aiCodeCellSummaryStore] Getting summary for key:', key, 'found:', !!summary); | ||
|
||
if (!summary) { | ||
console.log('[aiCodeCellSummaryStore] No summary found for key:', key); | ||
return null; | ||
} | ||
|
||
// If code has changed, remove the outdated summary | ||
if (currentCodeString && summary.codeString !== currentCodeString) { | ||
console.log('[aiCodeCellSummaryStore] Code changed, removing outdated summary for key:', key); | ||
this.summaries.delete(key); | ||
this.debouncedSaveToStorage(); | ||
return null; | ||
} | ||
|
||
console.log('[aiCodeCellSummaryStore] Returning summary for key:', key, 'summary:', summary.summary); | ||
return summary.summary; | ||
} | ||
|
||
/** | ||
* Check if a code cell has an AI summary | ||
*/ | ||
hasSummary(sheetId: string, x: number, y: number): boolean { | ||
const key = this.getKey(sheetId, x, y); | ||
return this.summaries.has(key); | ||
} | ||
|
||
/** | ||
* Remove a summary for a code cell | ||
*/ | ||
removeSummary(sheetId: string, x: number, y: number): void { | ||
const key = this.getKey(sheetId, x, y); | ||
this.summaries.delete(key); | ||
this.debouncedSaveToStorage(); | ||
} | ||
|
||
/** | ||
* Clear all summaries for a sheet | ||
*/ | ||
clearSheet(sheetId: string): void { | ||
for (const [key, summary] of this.summaries.entries()) { | ||
if (summary.sheetId === sheetId) { | ||
this.summaries.delete(key); | ||
} | ||
} | ||
this.debouncedSaveToStorage(); | ||
} | ||
|
||
/** | ||
* Clean up old summaries to prevent memory issues | ||
*/ | ||
private cleanupOldSummaries(): void { | ||
const entries = Array.from(this.summaries.entries()); | ||
entries.sort((a, b) => a[1].timestamp - b[1].timestamp); | ||
|
||
// Remove oldest 20% of summaries | ||
const toRemove = Math.floor(entries.length * 0.2); | ||
for (let i = 0; i < toRemove; i++) { | ||
this.summaries.delete(entries[i][0]); | ||
} | ||
} | ||
|
||
/** | ||
* Debounced save to localStorage to prevent excessive writes | ||
*/ | ||
private debouncedSaveToStorage(): void { | ||
// Clear existing timeout | ||
if (this.saveTimeoutId) { | ||
clearTimeout(this.saveTimeoutId); | ||
} | ||
|
||
// Set new timeout | ||
this.saveTimeoutId = setTimeout(() => { | ||
this.saveToStorage(); | ||
this.saveTimeoutId = null; | ||
}, this.SAVE_DEBOUNCE_MS); | ||
} | ||
|
||
/** | ||
* Force immediate save to localStorage (used for critical operations) | ||
*/ | ||
private saveToStorage(): void { | ||
try { | ||
const data = Array.from(this.summaries.entries()); | ||
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(data)); | ||
console.log('[aiCodeCellSummaryStore] Saved summaries to localStorage'); | ||
} catch (error) { | ||
console.warn('Failed to save AI code cell summaries to localStorage:', error); | ||
// If localStorage is full, try to clear some space | ||
if (error instanceof Error && error.name === 'QuotaExceededError') { | ||
this.handleStorageQuotaExceeded(); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Handle localStorage quota exceeded by cleaning up old summaries | ||
*/ | ||
private handleStorageQuotaExceeded(): void { | ||
console.warn('[aiCodeCellSummaryStore] localStorage quota exceeded, cleaning up old summaries'); | ||
|
||
// Remove 50% of summaries to free up space | ||
const entries = Array.from(this.summaries.entries()); | ||
entries.sort((a, b) => a[1].timestamp - b[1].timestamp); | ||
|
||
const toRemove = Math.floor(entries.length * 0.5); | ||
for (let i = 0; i < toRemove; i++) { | ||
this.summaries.delete(entries[i][0]); | ||
} | ||
|
||
// Try saving again | ||
try { | ||
const data = Array.from(this.summaries.entries()); | ||
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(data)); | ||
console.log('[aiCodeCellSummaryStore] Successfully saved after cleanup'); | ||
} catch (retryError) { | ||
console.error('[aiCodeCellSummaryStore] Failed to save even after cleanup:', retryError); | ||
} | ||
} | ||
|
||
/** | ||
* Load summaries from localStorage | ||
*/ | ||
private loadFromStorage(): void { | ||
try { | ||
const data = localStorage.getItem(this.STORAGE_KEY); | ||
if (data) { | ||
const entries: [string, CodeCellSummary][] = JSON.parse(data); | ||
this.summaries = new Map(entries); | ||
} | ||
} catch (error) { | ||
console.warn('Failed to load AI code cell summaries from localStorage:', error); | ||
this.summaries.clear(); | ||
} | ||
} | ||
|
||
/** | ||
* Force immediate save (useful for critical operations or before page unload) | ||
*/ | ||
public flushToStorage(): void { | ||
if (this.saveTimeoutId) { | ||
clearTimeout(this.saveTimeoutId); | ||
this.saveTimeoutId = null; | ||
} | ||
this.saveToStorage(); | ||
} | ||
|
||
/** | ||
* Cleanup method to clear pending timeouts and event listeners | ||
*/ | ||
public destroy(): void { | ||
// Clean up event listener | ||
events.off('updateCodeCells', this.handleCodeCellUpdates); | ||
|
||
// Clear pending timeout | ||
if (this.saveTimeoutId) { | ||
clearTimeout(this.saveTimeoutId); | ||
this.saveTimeoutId = null; | ||
} | ||
|
||
// Force final save before destruction | ||
this.saveToStorage(); | ||
} | ||
} | ||
|
||
// Export a singleton instance | ||
export const aiCodeCellSummaryStore = new AICodeCellSummaryStore(); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Timer leak vulnerability: saveTimeoutId is declared as NodeJS.Timeout but in browser environments, setTimeout returns a number. This type mismatch can cause clearTimeout to fail silently, leading to timer leaks and potential memory issues. Change type to
number | null
for browser compatibility.Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.