feat(files): download from anywhere — a link box, a pasted link, the palette; the running downloads in a tray

- Files toolbar link box (paste button, Enter); a lone http(s) link pasted onto any page opens the one
  app-wide download dialog, which now names the link; the palette's "Download from a link…" focuses
  the box on its history entry.
- The download tray, bottom right on every page: what waits, runs, is paused or failed (reason +
  Retry, the queue's right-click / "…" menu), and what finished in this tab as "Done · Open" until
  closed; folds to a pill (per-account pref); closed, it stays shut — across a reload — until the
  work changes or something finishes. Back to top steps up over it, the page end keeps clear.
- A finish is announced once: "Downloaded: …", whether a phone plays it, Copy link + Open (toasts
  and notices may carry a second action).
- The inbox's ready notice opens the file in its folder: download_done carries job_id + folder_id.
- GET /api/downloads is the queue only (in flight, failed, finished in the last 10 minutes), with
  each row's source key.
This commit is contained in:
2026-10-11 16:56:13 +02:00
parent d22c64f4dd
commit 1c4f0042d2
42 changed files with 1509 additions and 162 deletions
+7 -1
View File
@@ -118,6 +118,12 @@ export interface DownloadJob {
position_seconds?: number;
}
// A row of the queue (the tray's poll): what is in flight or failed, and what finished a moment ago,
// with where it came from as the library names it.
export interface QueueJob extends DownloadJob {
source_key: string;
}
export interface ShareRecipient {
id: number;
email: string;
@@ -211,7 +217,7 @@ export const downloadsApi = {
req("/api/downloads/clip", { method: "POST", body: JSON.stringify(body) }),
downloadStoryboard: (id: number): Promise<StoryboardMeta> =>
req(`/api/downloads/${id}/storyboard`),
downloads: (): Promise<DownloadJob[]> => req("/api/downloads"),
downloads: (): Promise<QueueJob[]> => req("/api/downloads"),
downloadIndex: (): Promise<Record<string, DownloadStatus>> => req("/api/downloads/index"),
pauseDownload: (id: number): Promise<DownloadJob> =>
req(`/api/downloads/${id}/pause`, { method: "POST" }, { idempotent: true }),
+51
View File
@@ -0,0 +1,51 @@
import { ensureNavId, peekNavId } from "./history";
import { createStore } from "./store";
// Downloading a link is an action you start anywhere: the Files page's link box, a link pasted onto
// any page, the command palette. They all hand the link to ONE app-wide download dialog
// (components/DownloadIntake), so none of them mounts a dialog of its own.
const pending = createStore<string | null>(null);
/** An http(s) link, alone — what a paste or the link box may download; anything else is not one. */
export function asDownloadLink(text: string | null | undefined): string | null {
const s = text?.trim() ?? "";
return /^https?:\/\/\S+$/i.test(s) ? s : null;
}
/** Whether a paste here is the page's to take: not typed into a field, and no dialog on top (the
* reader is busy with that, and a link pasted at it is not a request to download). */
export function pasteIsForThePage(target: EventTarget | null): boolean {
const el = target instanceof Element ? target : null;
if (el?.closest("input, textarea, select, [contenteditable]:not([contenteditable='false'])"))
return false;
return !document.querySelector("[aria-modal='true']");
}
/** Ask to download `url`: the app's download dialog opens on it. */
export const requestDownload = (url: string): void => pending.set(url);
/** The link the dialog is open on (null = closed). DownloadIntake only. */
export const usePendingDownload = (): string | null => pending.useValue();
/** The dialog closed, downloading or not. */
export const clearPendingDownload = (): void => pending.set(null);
// The palette's "Download from link…" takes the reader to the Files page's link box. A token for the
// history entry the navigation made (as lib/homeIntent's): Files is a lazy module, often not mounted
// when it is asked, and a request that outlived its entry must not grab the focus on a later visit.
const linkBox = createStore<number | null>(null);
/** Ask the Files page to focus its link box on THIS entry — `setPage("files", requestLinkBox)`. */
export const requestLinkBox = (): void => linkBox.set(ensureNavId());
/** The pending request (null = none) — the render subscription that wakes the link box. */
export const useLinkBoxRequest = (): number | null => linkBox.useValue();
/** Take the request, clearing it; true only on the entry it was made for. */
export const takeLinkBox = (): boolean => {
const entry = linkBox.get();
if (entry === null) return false;
linkBox.set(null);
return entry === peekNavId();
};
@@ -0,0 +1,50 @@
// @vitest-environment jsdom
//
// The queue as a tab watches it: a finish is a job that is done now and was not on the last look —
// seen once, kept for the tray until it is closed, announced once. The first look only learns.
import { beforeEach, describe, expect, it } from "vitest";
import type { QueueJob } from "./api";
import {
clearFinished,
noteQueue,
resetQueueWatch,
takeUnannounced,
useFinished,
} from "./downloadQueue";
import { renderHook } from "@testing-library/react";
const job = (id: number, status: string) => ({ id, status }) as unknown as QueueJob;
const finishedIds = () => renderHook(() => useFinished()).result.current.map((j) => j.id);
beforeEach(resetQueueWatch);
describe("downloadQueue · a finish", () => {
it("the first look is old news: what is already done is not announced", () => {
noteQueue([job(1, "done"), job(2, "running")]);
expect(takeUnannounced()).toEqual([]);
expect(finishedIds()).toEqual([]);
});
it("a job that turns done is announced once and kept, newest first", () => {
noteQueue([job(1, "running"), job(2, "queued")]);
noteQueue([job(1, "done"), job(2, "running")]);
noteQueue([job(1, "done"), job(2, "done")]);
expect(takeUnannounced().map((j) => j.id)).toEqual([1, 2]);
expect(takeUnannounced()).toEqual([]);
expect(finishedIds()).toEqual([2, 1]);
});
it("a job first seen done after the first look finished meanwhile (a cache hit, another device)", () => {
noteQueue([]);
noteQueue([job(5, "done")]);
expect(takeUnannounced().map((j) => j.id)).toEqual([5]);
});
it("a failure is not a finish; closing the tray forgets what finished", () => {
noteQueue([job(1, "running"), job(2, "running")]);
noteQueue([job(1, "error"), job(2, "done")]);
expect(finishedIds()).toEqual([2]);
clearFinished();
expect(finishedIds()).toEqual([]);
});
});
+59
View File
@@ -0,0 +1,59 @@
import { api, type QueueJob } from "./api";
import { createStore } from "./store";
// The download queue as this tab has watched it: which jobs it has seen finish. The tray shows them
// ("Done · Open") until it is closed, and announces each once (the done notice).
//
// Watched where the queue is FETCHED, not in a component's effect: every reader of the queue (the
// tray, the Downloads page) fetches through `fetchQueue`, so a finish is seen once whichever of them
// polled, and nothing has to diff the previous render's data.
/** The statuses a job leaves on its own: it is waiting, or working. */
export const IN_FLIGHT: ReadonlySet<string> = new Set(["queued", "running", "paused"]);
let lastSeen: Map<number, string> | null = null;
const finished = createStore<QueueJob[]>([]);
const unannounced = createStore<QueueJob[]>([]);
/** Note a fresh queue: a job that is done now and was not on the last look has just finished. The
* first look only learns what is there — a file finished before this tab opened is old news. */
export function noteQueue(jobs: QueueJob[]): void {
const before = lastSeen;
lastSeen = new Map(jobs.map((j) => [j.id, j.status]));
if (!before) return;
const done = jobs.filter((j) => j.status === "done" && before.get(j.id) !== "done");
if (done.length === 0) return;
const ids = new Set(done.map((j) => j.id));
finished.set((list) => [...done, ...list.filter((j) => !ids.has(j.id))]);
unannounced.set((list) => [...list, ...done]);
}
/** The queue, noted (see above). Every reader of `qk.downloads()` fetches with this. */
export async function fetchQueue(): Promise<QueueJob[]> {
const jobs = await api.downloads();
noteQueue(jobs);
return jobs;
}
/** The jobs this tab saw finish, newest first, until the tray is closed. */
export const useFinished = (): QueueJob[] => finished.useValue();
/** The tray was closed: what finished is no longer shown. */
export const clearFinished = (): void => finished.set([]);
/** The finishes not yet announced — the render subscription that wakes the announcer. */
export const useUnannounced = (): QueueJob[] => unannounced.useValue();
/** Take the finishes to announce, clearing them: each is announced once. */
export function takeUnannounced(): QueueJob[] {
const list = unannounced.get();
if (list.length) unannounced.set([]);
return list;
}
/** Forget what was watched (a test starts from a tab that has looked at nothing). */
export function resetQueueWatch(): void {
lastSeen = null;
finished.set([]);
unannounced.set([]);
}
+8 -1
View File
@@ -60,6 +60,8 @@ export interface Notification {
title?: string;
message: string;
action?: NotifAction;
// A second, lesser action beside it (a done download's "Open" after its "Copy link").
secondaryAction?: NotifAction;
meta?: NotifMeta;
requiresInteraction: boolean;
duration?: number; // auto-dismiss ms (undefined when it stays until acted on)
@@ -82,6 +84,7 @@ export interface NotifyInput {
level?: NotifLevel;
title?: string;
action?: NotifAction;
secondaryAction?: NotifAction;
meta?: NotifMeta;
requiresInteraction?: boolean;
sound?: boolean; // force the alert tone (when sound is enabled) even for an info toast
@@ -185,6 +188,7 @@ function load(): Notification[] {
repeat: 1,
...(n as object),
action: undefined,
secondaryAction: undefined,
dismissed: true,
transient: false,
}) as Notification,
@@ -198,7 +202,9 @@ function persist() {
try {
// Transient status notices are live-session only — never write them to history,
// so a reload can't leave one stranded with no producer left to clear it.
const slim = items.filter((n) => !n.transient).map(({ action: _action, ...n }) => n);
const slim = items
.filter((n) => !n.transient)
.map(({ action: _action, secondaryAction: _second, ...n }) => n);
writeAccount(HISTORY_KEY, slim);
} catch {
/* ignore quota / serialization errors */
@@ -317,6 +323,7 @@ export function notify(input: NotifyInput): number {
title: input.title,
message: input.message,
action: input.action,
secondaryAction: input.secondaryAction,
meta: input.meta,
requiresInteraction,
duration,
+5
View File
@@ -21,6 +21,11 @@ export const LS = {
filesLayouts: "siftlode.filesLayouts",
filesSort: "siftlode.filesSort",
filesCardSize: "siftlode.filesCardSize",
// The download tray open or folded to its pill — a per-account mirror of the server pref.
downloadTray: "siftlode.downloadTray",
// The queue the reader closed the tray on (job ids, a failure marked) — it stays shut until that
// changes. Per-account mirror of the server pref.
downloadTrayClosed: "siftlode.downloadTrayClosed",
hints: "siftlode.hints",
lang: "siftlode.lang",
filters: "siftlode.filters",