Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 91 additions & 13 deletions src/main/browser/BrowserPanelManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { saveClipboardImageFile } from "../attachments/localFiles";
import { IPC_EVENT_CHANNELS } from "@/shared/ipc";
import { BrowserLoginCaptureCoordinator } from "./BrowserLoginCaptureCoordinator";
import { BrowserTab, resolveWebContentsById } from "./BrowserTab";
import { BrowserHistoryStore, fetchSearchSuggestions } from "./browserHistory";
import { BrowserBookmarkStore, type BrowserBookmark } from "./browserBookmarks";
import { PICKER_COMMIT_ORIGIN, onPickerCommit } from "./picker/pickerProtocol";
import { buildPickerScript } from "./picker/pickerScript";

Expand Down Expand Up @@ -46,26 +48,34 @@ type PickerPayload =
title: string;
};

interface BrowserPanelManagerOptions {
isExtracted?: () => boolean;
focusExtractedWindow?: () => void;
}

export class BrowserPanelManager {
private tabs: BrowserTab[] = [];
private activeTabId: string | null = null;
private host: BrowserWindow | null = null;
private hosts = new Set<BrowserWindow>();
private pendingPicker: PendingPicker | null = null;
private unsubscribePicker: (() => void) | null = null;
private persistTimer: ReturnType<typeof setTimeout> | null = null;
private readonly history = new BrowserHistoryStore();
private readonly bookmarks = new BrowserBookmarkStore();
private restored = false;
private pickerKeyCleanup: (() => void) | null = null;
private readonly loginCoordinator = new BrowserLoginCaptureCoordinator({
createTab: (payload) => this.createTab(payload),
closeTab: (tabId) => this.closeTab(tabId),
findTab: (tabId) => this.findTab(tabId),
emit: (event) => this.emit(event),
hasHostWindow: () => this.host !== null && !this.host.isDestroyed(),
hasHostWindow: () => this.hasHostWindow(),
});

constructor(
private readonly paths: LightcodePaths,
private readonly browserUserAgent: string,
private readonly options: BrowserPanelManagerOptions = {},
) {
this.unsubscribePicker = onPickerCommit((commit) => this.onPickerCommit(commit));
}
Expand Down Expand Up @@ -112,16 +122,21 @@ export class BrowserPanelManager {
}

bindHost(window: BrowserWindow): void {
this.host = window;
window.webContents.on("before-input-event", (event, input) => {
this.hosts.add(window);
const onBeforeInputEvent = (event: Electron.Event, input: Electron.Input) => {
if (!this.pendingPicker || !isEscapeKeyDown(input)) return;
event.preventDefault();
this.cancelPicker();
});
};
window.webContents.on("before-input-event", onBeforeInputEvent);
window.once("closed", () => {
this.dispose();
this.hosts.delete(window);
try {
window.webContents.removeListener("before-input-event", onBeforeInputEvent);
} catch {}
});
void this.restoreFromDisk();
this.emitState();
}

dispose(): void {
Expand All @@ -138,6 +153,7 @@ export class BrowserPanelManager {
}
this.tabs = [];
this.activeTabId = null;
this.hosts.clear();
}

private clearPickerShortcut(): void {
Expand All @@ -164,20 +180,40 @@ export class BrowserPanelManager {
}

private emit(event: BrowserEvent): void {
if (!this.host || this.host.isDestroyed()) return;
try {
this.host.webContents.send(IPC_EVENT_CHANNELS.browserEvent, event);
} catch {}
for (const host of this.hosts) {
if (host.isDestroyed()) {
this.hosts.delete(host);
continue;
}
try {
host.webContents.send(IPC_EVENT_CHANNELS.browserEvent, event);
} catch {}
}
}

private emitState(): void {
this.emit({ type: "state", state: this.snapshot() });
}

notifyState(): void {
this.emitState();
}

revealPanel(): void {
if (this.options.isExtracted?.()) {
this.options.focusExtractedWindow?.();
return;
}
this.emit({ type: "open-panel" });
}

private hasHostWindow(): boolean {
for (const host of this.hosts) {
if (!host.isDestroyed()) return true;
}
return false;
}

private readLinkSettings(): {
linkOpenTarget: BrowserLinkOpenTarget;
linkPresentationMode: BrowserLinkPresentationMode;
Expand Down Expand Up @@ -218,7 +254,11 @@ export class BrowserPanelManager {
return this.openSystemBrowser(url.toString());
}

this.emit({ type: "open-panel", mode: settings.linkPresentationMode });
if (this.options.isExtracted?.()) {
this.options.focusExtractedWindow?.();
} else {
this.emit({ type: "open-panel", mode: settings.linkPresentationMode });
}
void this.createTab({ url: url.toString(), activate: true }).catch(() => {});
return true;
}
Expand All @@ -241,20 +281,43 @@ export class BrowserPanelManager {
return {
tabs: this.tabs.map((t) => this.toInfo(t)),
activeTabId: this.activeTabId,
extracted: this.options.isExtracted?.() === true,
bookmarks: this.bookmarks.list(),
bookmarkBarVisible: this.bookmarks.isBarVisible(),
};
}

addBookmark(bookmark: BrowserBookmark): void {
this.bookmarks.add(bookmark);
this.emitState();
}

removeBookmark(url: string): void {
this.bookmarks.remove(url);
this.emitState();
}

setBookmarkBarVisible(visible: boolean): void {
this.bookmarks.setBarVisible(visible);
this.emitState();
}

private findTab(tabId: string): BrowserTab | undefined {
return this.tabs.find((t) => t.tabId === tabId);
}

attachWebContents(tabId: string, webContentsId: number): void {
const tab = this.findTab(tabId);
if (!tab) return;
if (this.host?.webContents.id === webContentsId) return;
// Reject a host window's own WebContents by id first, before resolving it.
for (const host of this.hosts) {
if (host.webContents.id === webContentsId) return;
}
const wc = resolveWebContentsById(webContentsId);
if (!wc) return;
if (this.host?.webContents === wc) return;
for (const host of this.hosts) {
if (host.webContents === wc) return;
}
tab.attach(wc);
}

Expand All @@ -266,6 +329,7 @@ export class BrowserPanelManager {
userAgent: this.browserUserAgent,
onUpdate: (snap) => {
this.emit({ type: "tab-updated", tab: { ...snap } });
if (!snap.loading) this.history.record(snap.url, snap.title, Date.now());
this.schedulePersist();
},
onAttention: (id) => {
Expand Down Expand Up @@ -374,11 +438,25 @@ export class BrowserPanelManager {
}

async clearHistory(tabId: string): Promise<void> {
this.history.clear();
const t = this.findTab(tabId);
if (!t) return;
t.clearHistory();
}

async suggest(query: string): Promise<{
history: Array<{ url: string; title: string }>;
suggestions: string[];
}> {
const history = this.history.query(query, 6).map((e) => ({ url: e.url, title: e.title }));
const suggestions = await fetchSearchSuggestions(query, this.browserUserAgent);
return { history, suggestions };
}

recentHistory(limit: number): Array<{ url: string; title: string }> {
return this.history.recent(limit).map((e) => ({ url: e.url, title: e.title }));
}

async clearCookies(tabId: string): Promise<void> {
const t = this.findTab(tabId);
if (!t) return;
Expand Down
50 changes: 50 additions & 0 deletions src/main/browser/browserBookmarks.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

const state = new Map<string, string>();
vi.mock("../db", () => ({
dbGetState: (k: string) => state.get(k) ?? null,
dbSetState: (k: string, v: string) => {
state.set(k, v);
},
}));

import { BrowserBookmarkStore } from "./browserBookmarks";

describe("BrowserBookmarkStore", () => {
beforeEach(() => state.clear());

it("adds and dedupes by url", () => {
const s = new BrowserBookmarkStore();
s.add({ url: "https://a.com/", title: "A", createdAt: 1 });
s.add({ url: "https://a.com/", title: "A again", createdAt: 2 });
expect(s.list()).toHaveLength(1);
expect(s.list()[0]?.title).toBe("A");
});

it("ignores non-http(s) urls", () => {
const s = new BrowserBookmarkStore();
s.add({ url: "about:blank", title: "x", createdAt: 1 });
expect(s.list()).toHaveLength(0);
});

it("removes by url", () => {
const s = new BrowserBookmarkStore();
s.add({ url: "https://a.com/", title: "A", createdAt: 1 });
s.remove("https://a.com/");
expect(s.list()).toHaveLength(0);
});

it("persists across instances", () => {
const s = new BrowserBookmarkStore();
s.add({ url: "https://a.com/", title: "A", createdAt: 1 });
expect(new BrowserBookmarkStore().list()).toHaveLength(1);
});

it("toggles and persists bar visibility", () => {
const s = new BrowserBookmarkStore();
expect(s.isBarVisible()).toBe(false);
s.setBarVisible(true);
expect(s.isBarVisible()).toBe(true);
expect(new BrowserBookmarkStore().isBarVisible()).toBe(true);
});
});
90 changes: 90 additions & 0 deletions src/main/browser/browserBookmarks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { dbGetState, dbSetState } from "../db";

const BOOKMARKS_KEY = "browser-bookmarks-v1";
const BAR_VISIBLE_KEY = "browser-bookmark-bar-visible-v1";

export interface BrowserBookmark {
url: string;
title: string;
faviconUrl?: string;
createdAt: number;
}

/**
* Persistent bookmarks + bookmark-bar visibility, stored as app state (same
* mechanism as tabs/history). Deduped by URL.
*/
export class BrowserBookmarkStore {
private bookmarks: BrowserBookmark[] = [];
private barVisible = false;
private loaded = false;

private load(): void {
if (this.loaded) return;
this.loaded = true;
try {
const raw = dbGetState(BOOKMARKS_KEY);
if (raw) {
const arr = JSON.parse(raw) as BrowserBookmark[];
if (Array.isArray(arr)) {
this.bookmarks = arr.filter(
(b): b is BrowserBookmark =>
!!b && typeof b.url === "string" && typeof b.title === "string",
);
}
}
} catch {}
try {
this.barVisible = dbGetState(BAR_VISIBLE_KEY) === "1";
} catch {}
}

list(): BrowserBookmark[] {
this.load();
return this.bookmarks;
}

isBarVisible(): boolean {
this.load();
return this.barVisible;
}

add(bookmark: BrowserBookmark): void {
this.load();
if (!/^https?:\/\//i.test(bookmark.url)) return;
if (this.bookmarks.some((b) => b.url === bookmark.url)) return;
this.bookmarks = [
...this.bookmarks,
{
url: bookmark.url,
title: bookmark.title || bookmark.url,
createdAt: bookmark.createdAt,
...(bookmark.faviconUrl ? { faviconUrl: bookmark.faviconUrl } : {}),
},
];
this.persist();
}

remove(url: string): void {
this.load();
const next = this.bookmarks.filter((b) => b.url !== url);
if (next.length === this.bookmarks.length) return;
this.bookmarks = next;
this.persist();
}

setBarVisible(visible: boolean): void {
this.load();
if (this.barVisible === visible) return;
this.barVisible = visible;
try {
dbSetState(BAR_VISIBLE_KEY, visible ? "1" : "0");
} catch {}
}

private persist(): void {
try {
dbSetState(BOOKMARKS_KEY, JSON.stringify(this.bookmarks));
} catch {}
}
}
Loading