@@ -1,10 +1,11 @@
1import { COLORS, isColor, type GroupColor } from "../shared/colors";
1import { COLORS, isColor, type GroupColor } from "../shared/colors";
2−import { labelOf, repairLabel, safeEmoji, stripTitle } from "../shared/label";
2+import { labelOf, repairLabel, safeEmoji, stripTitle, titleKey } from "../shared/label";
3import { colorFor, isInternalUrl, promptAddress, provisionalTitle } from "../shared/url";
3import { colorFor, isInternalUrl, promptAddress, provisionalTitle } from "../shared/url";
4import { pathKey } from "./engine";
4import { pathKey } from "./engine";
5import { membersHash, memberUrls, settled, toItems, type Member, type NameItem } from "./naming";
5import { membersHash, memberUrls, settled, toItems, type Member, type NameItem } from "./naming";
6import { addToGroup, createManagedGroup, groupExists, ungroup, type Runtime } from "./runtime";
6import { addToGroup, createManagedGroup, groupExists, ungroup, type Runtime } from "./runtime";
7+import type { HostReply } from "./host";
7−import { markDirty, type State } from "./state";
8+import { markDirty, type GroupRecord, type HostError, type HostErrorCode, type State, type TabRecord } from "./state";
9/** Section 3/9: "Organize all tabs" — cluster ungrouped tabs in batches sized to the model's window. */
10/** Section 3/9: "Organize all tabs" — cluster ungrouped tabs in batches sized to the model's window. */
@@ -26,6 +27,8 @@ export interface ExistingGroup {
26export interface OrganizePayload {
27export interface OrganizePayload {
27 items: NameItem[];
28 items: NameItem[];
28 existingGroups: ExistingGroup[];
29 existingGroups: ExistingGroup[];
30+ /** Every group label in the window: a new group the host names must not repeat one. */
31+ siblingTitles?: string[];
29 allowNew: boolean;
32 allowNew: boolean;
30 maxGroups: number;
33 maxGroups: number;
31 minGroupSize: number;
34 minGroupSize: number;
@@ -151,88 +154,198 @@ export interface OrganizeReport {
151 error?: string;
154 error?: string;
154−/** Existing groups a batch may add tabs to: extension-managed topic groups in this window. */
157+/** Existing groups a batch may add tabs to: Diagonal's topic groups in this window, the ones in use first. */
155export function existingGroupsFor(state: State, windowId: number, extraIds: number[] = []): { ids: number[]; list: ExistingGroup[] } {
158export function existingGroupsFor(state: State, windowId: number, extraIds: number[] = []): { ids: number[]; list: ExistingGroup[] } {
159+ const members = new Map<number, TabRecord[]>();
160+ for (const t of Object.values(state.tabs)) if (t.groupId !== -1) members.set(t.groupId, [...(members.get(t.groupId) ?? []), t]);
161+ const inUse = (g: GroupRecord): number =>
162+ Math.max(g.dirtyAt ?? 0, g.lastNamedAt ?? 0, ...(members.get(g.id) ?? []).map((t) => t.lastActivatedAt ?? 0));
156 const groups = Object.values(state.groups)
163 const groups = Object.values(state.groups)
157− .filter((g) => g.windowId === windowId && g.managed && g.origin !== "tidy" && (g.stripTitle || g.title))
164+ .filter((g) => g.windowId === windowId && g.managed && g.origin !== "tidy" && !g.restored && (g.stripTitle || g.title))
165+ .map((g) => ({ g, first: extraIds.includes(g.id), at: inUse(g) }))
158− .sort((a, b) => Number(extraIds.includes(b.id)) - Number(extraIds.includes(a.id)))
166+ .sort((a, b) => Number(b.first) - Number(a.first) || b.at - a.at)
159− .slice(0, EXISTING_GROUPS_CAP);
167+ .slice(0, EXISTING_GROUPS_CAP)
160 const list = groups.map((g, i) => ({
169 const list = groups.map((g, i) => ({
162 title: labelOf(g.stripTitle || g.title),
171 title: labelOf(g.stripTitle || g.title),
163− samples: Object.values(state.tabs)
164− .filter((t) => t.groupId === g.id)
166− .map((t) => t.title.slice(0, 60)),
172+ samples: (members.get(g.id) ?? []).slice(0, 2).map((t) => t.title.slice(0, 60)),
168 return { ids: groups.map((g) => g.id), list };
174 return { ids: groups.map((g) => g.id), list };
177+/** Errors about what was sent rather than about the host: a smaller or plainer request may go through. */
178+const CONTENT_ERRORS = new Set<HostErrorCode>(["OVER_BUDGET", "GUARDRAIL", "BAD_MODEL_OUTPUT"]);
179+const MAX_TIMEOUT_SPLITS = 1;
181+/** One organize call, with the retries that can rescue the same tabs: strict output, then no page text. */
171−export async function organizeWindow(rt: Runtime, windowId: number): Promise<OrganizeReport> {
182+async function askOrganize(rt: Runtime, part: Member[], windowId: number, existingGroups: ExistingGroup[], withDescriptions: boolean): Promise<HostReply<OrganizeResult>> {
183+ const settings = rt.settings();
184+ const s = rt.state();
185+ const payload: OrganizePayload = {
186+ items: toItems(part, settings, withDescriptions),
188+ siblingTitles: Object.values(s.groups)
189+ .filter((g) => g.windowId === windowId && g.origin !== "tidy")
190+ .map((g) => labelOf(g.stripTitle || g.title))
193+ allowNew: part.length >= 2,
194+ maxGroups: maxGroupsFor(part.length),
195+ minGroupSize: settings.organizeMinGroupSize,
197+ let reply = await rt.host<OrganizeResult>("organize", payload);
198+ if (!reply.ok && reply.error.code === "BAD_MODEL_OUTPUT") reply = await rt.host<OrganizeResult>("organize", payload, { strict: true });
199+ if (!reply.ok && reply.error.code === "GUARDRAIL" && payload.items.some((i) => i.description)) {
200+ // What a page says is the likeliest thing to trip Apple's filter; its title and address rarely do.
201+ payload.items = toItems(part, settings, false);
202+ reply = await rt.host<OrganizeResult>("organize", payload);
207+/** One organize run over a window: what it made, what it moved, and whether the host stopped it. */
208+export interface SortRun {
210+ createdIds: number[];
211+ previous: Record<number, number>;
214+ timeoutSplits: number;
215+ /** Auto-organize: remember what was looked at, so the same tabs are not sent again unchanged. */
217+ stopped?: HostError;
220+export const newRun = (windowId: number, stamp: boolean): SortRun => ({ windowId, createdIds: [], previous: {}, grouped: 0, left: 0, timeoutSplits: 0, stamp });
223+ * Sort one part of a window. A reply about the tabs themselves (too long, refused by Apple's filter, not
224+ * valid output) splits the part in halves, so one page the model won't handle leaves the others sorted; a
225+ * tab that fails alone is set aside until its page or title changes. Tabs that changed while the model was
226+ * thinking are left out of its answer.
228+export async function sortPart(rt: Runtime, part: Member[], run: SortRun, probe = false): Promise<void> {
229+ if (!part.length || run.stopped) return;
230+ const { ids: existingIds, list: existingGroups } = existingGroupsFor(rt.state(), run.windowId, run.createdIds);
231+ if (part.length < 2 && !existingIds.length && !probe) {
232+ run.left += part.length;
233+ return; // one tab and nothing to join: no call can place it (a probe still learns whether the model takes it)
235+ const reply = await askOrganize(rt, part, run.windowId, existingGroups, true);
237+ const e = reply.error;
238+ const timedOut = e.code === "TIMEOUT" && part.length > 4 && run.timeoutSplits < MAX_TIMEOUT_SPLITS;
239+ if (part.length > 1 && (CONTENT_ERRORS.has(e.code) || timedOut)) {
240+ if (timedOut) run.timeoutSplits++;
241+ const half = Math.ceil(part.length / 2);
242+ await sortPart(rt, part.slice(0, half), run, true);
243+ await sortPart(rt, part.slice(half), run, true);
246+ if (CONTENT_ERRORS.has(e.code)) {
247+ const rec = rt.state().tabs[part[0].id];
248+ if (rec) rec.organizeRefused = organizedKeyOf(part[0]);
249+ rt.log("organize: set aside a tab the model would not sort", e.code);
172 const settings = rt.settings();
256 const settings = rt.settings();
257+ const plan = planFromResult(reply.result, part.map((m) => m.id), existingIds, settings.organizeMinGroupSize, maxGroupsFor(part.length), (ids) =>
258+ colorFor(part.find((m) => m.id === ids[0])?.url ?? ""),
260+ const unchanged = await stillAsSent(rt, part, run.windowId);
261+ const trimmed = trimPlan(rt.state(), plan, unchanged, settings.organizeMinGroupSize);
262+ const failed = await applyPlan(rt, trimmed, run.windowId, part, run.previous, run.createdIds);
263+ const placed = [...trimmed.joins, ...trimmed.creates].reduce((n, x) => n + x.tabIds.filter((id) => !failed.has(id)).length, 0);
264+ run.grouped += placed;
265+ run.left += part.length - placed;
267+ const s = rt.state();
268+ for (const m of part) {
269+ const rec = s.tabs[m.id];
270+ if (rec && unchanged.has(m.id) && !failed.has(m.id)) rec.organizedKey = organizedKeyOf(m);
275+/** The tabs of a part that are still loose, in this window, on the page and title the model saw. */
276+async function stillAsSent(rt: Runtime, part: Member[], windowId: number): Promise<Set<number>> {
277+ const live = new Map((await chrome.tabs.query({ windowId }).catch(() => [])).map((t) => [t.id!, t]));
278+ const s = rt.state();
282+ const t = live.get(m.id);
283+ return !!t && organizable(t) && !s.tabs[m.id]?.keepLoose && organizedKeyOf(t) === organizedKeyOf(m);
289+/** A plan with the tabs that moved on taken out: a new group left too small is not made, a join into a group gone is dropped. */
290+export function trimPlan(state: State, plan: Plan, keep: Set<number>, minGroupSize: number): Plan {
291+ const out: Plan = { joins: [], creates: [], leftovers: plan.leftovers.filter((id) => keep.has(id)) };
292+ for (const j of plan.joins) {
293+ const tabIds = j.tabIds.filter((id) => keep.has(id));
294+ const g = state.groups[j.groupId];
295+ if (tabIds.length && g?.managed && !g.restored) out.joins.push({ ...j, tabIds });
296+ else out.leftovers.push(...tabIds);
298+ for (const c of plan.creates) {
299+ const tabIds = c.tabIds.filter((id) => keep.has(id));
300+ if (tabIds.length >= Math.max(2, minGroupSize)) out.creates.push({ ...c, tabIds });
301+ else out.leftovers.push(...tabIds);
306+export async function organizeWindow(rt: Runtime, windowId: number): Promise<OrganizeReport> {
307+ const s0 = rt.state();
173 const tabs = (await chrome.tabs.query({ windowId })).filter((t) => organizable(t)).sort((a, b) => a.index - b.index);
308 const tabs = (await chrome.tabs.query({ windowId })).filter((t) => organizable(t)).sort((a, b) => a.index - b.index);
174 const report: OrganizeReport = { grouped: 0, groups: 0, left: 0 };
309 const report: OrganizeReport = { grouped: 0, groups: 0, left: 0 };
310+ // A tab the model already would not sort, on the same page, is not sent again.
311+ const sendable = tabs.filter((t) => s0.tabs[t.id!]?.organizeRefused !== organizedKeyOf(t));
175− if (tabs.length < 2) {
312+ if (sendable.length < 2) {
176 report.left = tabs.length;
313 report.left = tabs.length;
177 return report;
314 return report;
179− const members: Member[] = tabs.map((t) => ({
316+ const run = newRun(windowId, true); // auto-organize need not send the same tabs again right after
183− title: t.title ?? "",
185− description: rt.state().tabs[t.id!]?.description,
186− lastActive: t.lastAccessed ?? 0,
188− const previous: Record<number, number> = {};
189− const createdIds: number[] = [];
190− const queue = makeBatches(members);
191 rt.state().inFlight = { groupId: -1, startedAt: rt.now() };
317 rt.state().inFlight = { groupId: -1, startedAt: rt.now() };
192 rt.refreshBadge();
318 rt.refreshBadge();
194− while (queue.length) {
320+ for (const batch of makeBatches(sendable.map((t) => toMember(rt.state(), t)))) {
195− const batch = queue.shift()!;
321+ await sortPart(rt, batch, run);
196− const { ids: existingIds, list: existingGroups } = existingGroupsFor(rt.state(), windowId, createdIds);
197− const maxGroups = maxGroupsFor(batch.length);
198− const payload: OrganizePayload = {
199− items: toItems(batch, settings),
203− minGroupSize: settings.organizeMinGroupSize,
205− let reply = await rt.host<OrganizeResult>("organize", payload);
206− if (!reply.ok && reply.error.code === "OVER_BUDGET" && batch.length > 1) {
207− const half = Math.ceil(batch.length / 2);
208− queue.unshift(batch.slice(0, half), batch.slice(half));
211− if (!reply.ok && reply.error.code === "BAD_MODEL_OUTPUT") reply = await rt.host<OrganizeResult>("organize", payload, { strict: true });
213− report.error = `${reply.error.code}: ${reply.error.message}`;
214− report.left += batch.length + queue.flat().length;
215− break;
322+ if (run.stopped) break;
217− const batchIds = batch.map((m) => m.id);
218− const plan = planFromResult(reply.result, batchIds, existingIds, settings.organizeMinGroupSize, maxGroups, (ids) =>
219− colorFor(members.find((m) => m.id === ids[0])?.url ?? ""),
221− await applyPlan(rt, plan, windowId, members, previous, createdIds);
222− report.grouped += plan.joins.reduce((n, j) => n + j.tabIds.length, 0) + plan.creates.reduce((n, c) => n + c.tabIds.length, 0);
223− report.left += plan.leftovers.length;
225 } finally {
324 } finally {
226 const s = rt.state();
325 const s = rt.state();
227 if (s.inFlight?.groupId === -1) s.inFlight = undefined;
326 if (s.inFlight?.groupId === -1) s.inFlight = undefined;
327+ report.grouped = run.grouped;
228− report.groups = createdIds.length;
328+ report.groups = run.createdIds.length;
329+ report.left = tabs.length - run.grouped;
330+ if (run.stopped) report.error = `${run.stopped.code}: ${run.stopped.message}`;
229− if (Object.keys(previous).length) s.lastOrganize = { at: rt.now(), previous };
331+ if (Object.keys(run.previous).length) s.lastOrganize = { at: rt.now(), previous: run.previous };
230 rt.commit();
332 rt.commit();
231 rt.refreshBadge();
333 rt.refreshBadge();
233 return report;
335 return report;
338+const toMember = (s: State, t: chrome.tabs.Tab): Member => ({
342+ title: t.title ?? "",
344+ description: s.tabs[t.id!]?.description,
345+ lastActive: t.lastAccessed ?? 0,
348+/** Carry out a plan; returns the tabs whose move failed, which stay as they were. */
236export async function applyPlan(
349export async function applyPlan(
237 rt: Runtime,
350 rt: Runtime,
238 plan: Plan,
351 plan: Plan,
@@ -240,11 +353,15 @@ export async function applyPlan(
240 members: Member[],
353 members: Member[],
241 previous: Record<number, number>,
354 previous: Record<number, number>,
242 createdIds: number[],
355 createdIds: number[],
243−): Promise<void> {
356+): Promise<Set<number>> {
244 const settings = rt.settings();
357 const settings = rt.settings();
245 const byId = new Map(members.map((m) => [m.id, m]));
358 const byId = new Map(members.map((m) => [m.id, m]));
359+ const failed = new Set<number>();
246 for (const j of plan.joins) {
360 for (const j of plan.joins) {
247− if (!(await addToGroup(rt, j.tabIds, j.groupId))) continue;
361+ if (!(await addToGroup(rt, j.tabIds, j.groupId))) {
362+ for (const id of j.tabIds) failed.add(id);
248 for (const id of j.tabIds) previous[id] = -1;
365 for (const id of j.tabIds) previous[id] = -1;
249 const g = rt.state().groups[j.groupId];
366 const g = rt.state().groups[j.groupId];
@@ -265,7 +382,10 @@ export async function applyPlan(
265 lastNamedAt: named ? rt.now() : undefined,
382 lastNamedAt: named ? rt.now() : undefined,
266 dirty: false,
383 dirty: false,
268− if (groupId === undefined) continue;
385+ if (groupId === undefined) {
386+ for (const id of c.tabIds) failed.add(id);
269 createdIds.push(groupId);
389 createdIds.push(groupId);
270 for (const id of c.tabIds) previous[id] = -1;
390 for (const id of c.tabIds) previous[id] = -1;
271 const g = rt.state().groups[groupId];
391 const g = rt.state().groups[groupId];
@@ -274,6 +394,7 @@ export async function applyPlan(
274 rt.naming.touch(groupId);
394 rt.naming.touch(groupId);
279/** Undo within the hour: every tab goes back to the group it was in (organize only takes loose tabs). */
400/** Undo within the hour: every tab goes back to the group it was in (organize only takes loose tabs). */
@@ -301,7 +422,7 @@ export async function undoOrganize(rt: Runtime): Promise<number> {
303/** What auto-organize remembers about a tab: it looks again only when the page or title changes. */
424/** What auto-organize remembers about a tab: it looks again only when the page or title changes. */
304−export const organizedKeyOf = (t: { url?: string; title?: string }): string => `${pathKey(t.url)}\n${t.title ?? ""}`;
425+export const organizedKeyOf = (t: { url?: string; title?: string }): string => `${pathKey(t.url)}\n${titleKey(t.title)}`;
306export const AUTO_RETRY_MS = 300_000;
427export const AUTO_RETRY_MS = 300_000;
307export const AUTO_CONTINUE_MS = 1_500;
428export const AUTO_CONTINUE_MS = 1_500;
@@ -379,59 +500,25 @@ export class AutoOrganizer {
379 const s = rt.state();
500 const s = rt.state();
380 // Still-loading tabs are skipped here; finishing the load touches the window again. Discarded tabs keep
501 // Still-loading tabs are skipped here; finishing the load touches the window again. Discarded tabs keep
381 // their title and address, so they're sorted like loaded ones.
502 // their title and address, so they're sorted like loaded ones.
382− const loose = tabs.filter((t) => organizable(t) && settled(t) && !s.tabs[t.id!]?.keepLoose);
503+ const loose = tabs.filter((t) => {
504+ const rec = s.tabs[t.id!];
505+ return organizable(t) && settled(t) && !rec?.keepLoose && rec?.organizeRefused !== organizedKeyOf(t);
383 const fresh = loose.filter((t) => s.tabs[t.id!]?.organizedKey !== organizedKeyOf(t));
507 const fresh = loose.filter((t) => s.tabs[t.id!]?.organizedKey !== organizedKeyOf(t));
384 if (!fresh.length) return;
508 if (!fresh.length) return;
385− const { ids: existingIds, list: existingGroups } = existingGroupsFor(s, windowId);
386− if (loose.length < 2 && !existingIds.length) return; // one loose tab and nothing to join: wait for company
509+ if (loose.length < 2 && !existingGroupsFor(s, windowId).ids.length) return; // one loose tab and nothing to join: wait for company
387− const toMember = (t: chrome.tabs.Tab): Member => ({
391− title: t.title ?? "",
393− description: s.tabs[t.id!]?.description,
394− lastActive: t.lastAccessed ?? 0,
396− const ordered = [...fresh, ...loose.filter((t) => !fresh.includes(t))].map(toMember);
510+ const ordered = [...fresh, ...loose.filter((t) => !fresh.includes(t))].map((t) => toMember(s, t));
397 const batch = makeBatches(ordered)[0];
511 const batch = makeBatches(ordered)[0];
398− const maxGroups = maxGroupsFor(batch.length);
512+ const run = newRun(windowId, true);
399− const payload: OrganizePayload = {
513+ await sortPart(rt, batch, run);
400− items: toItems(batch, settings),
514+ rt.commit();
401− existingGroups,
515+ if (run.stopped) {
402− allowNew: batch.length >= 2,
404− minGroupSize: settings.organizeMinGroupSize,
406− let reply = await rt.host<OrganizeResult>("organize", payload);
407− if (!reply.ok && reply.error.code === "OVER_BUDGET" && batch.length > 1) {
408− // Rare with the budgeted batch; try once with half, the rest follows on the next run.
409− const half = batch.slice(0, Math.ceil(batch.length / 2));
410− payload.items = toItems(half, settings);
411− payload.maxGroups = maxGroupsFor(half.length);
412− payload.allowNew = half.length >= 2;
413− batch.length = half.length;
414− reply = await rt.host<OrganizeResult>("organize", payload);
416− if (!reply.ok && reply.error.code === "BAD_MODEL_OUTPUT") reply = await rt.host<OrganizeResult>("organize", payload, { strict: true });
418− rt.log("auto-organize", reply.error.code);
516+ rt.log("auto-organize", run.stopped.code);
419 this.deps.scheduleFallback(rt.now() + AUTO_RETRY_MS);
517 this.deps.scheduleFallback(rt.now() + AUTO_RETRY_MS);
422− const batchIds = batch.map((m) => m.id);
520+ const sent = new Set(batch.map((m) => m.id));
423− const plan = planFromResult(reply.result, batchIds, existingIds, settings.organizeMinGroupSize, payload.maxGroups, (ids) =>
424− colorFor(batch.find((m) => m.id === ids[0])?.url ?? ""),
426− await applyPlan(rt, plan, windowId, batch, {}, []);
427− const live = rt.state();
428− for (const m of batch) {
429− const rec = live.tabs[m.id];
430− if (rec) rec.organizedKey = organizedKeyOf(m);
433− const remaining = fresh.filter((t) => !batchIds.includes(t.id!));
434− if (remaining.length) this.touch(windowId, AUTO_CONTINUE_MS);
521+ if (fresh.some((t) => !sent.has(t.id!))) this.touch(windowId, AUTO_CONTINUE_MS);