driftnet 0.10.2 → 0.11.0

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/public/index.html CHANGED
@@ -15,7 +15,7 @@
15
15
  <style>
16
16
  :root {
17
17
  --bg: #f7f7f5; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e4e4df;
18
- --accent: #2f6fdb; --accent-soft: #e8effc; --warn: #b4540a; --star: #c58a00; --star-soft: #fff4d6;
18
+ --accent: #2f6fdb; --accent-soft: #e8effc; --warn: #b4540a; --star: #8a6100; --star-soft: #fff4d6;
19
19
  --danger: #c62828; --danger-soft: #fde8e8; --ok: #2e7d32; --ok-soft: #e6f4ea;
20
20
  font-family: ui-sans-serif, system-ui, -apple-system, "PingFang TC", "Noto Sans TC", sans-serif;
21
21
  /* Branch colours for folders (map, badges, sidebar dots). */
@@ -71,6 +71,15 @@
71
71
  body.readonly .tools, body.readonly .link-btn[data-act="note"], body.readonly nav .more, body.readonly nav [data-new],
72
72
  body.readonly .trash-bar, body.readonly .map-bar [data-map="new"], body.readonly #new-note, body.readonly .hint.swipe-hint { display: none !important; }
73
73
  .lang { border: 1px solid var(--line); background: var(--bg); border-radius: 10px; padding: 8px 12px; font-size: 13px; cursor: pointer; min-height: 40px; }
74
+ .hbtn { display: inline-grid; place-items: center; padding: 8px 10px; min-width: 40px; }
75
+ body.readonly #add-btn { display: none; }
76
+ .add-q { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: 0 2px; font-size: 13px; color: var(--muted); }
77
+ .add-q .btn { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; overflow-wrap: anywhere; text-align: left; }
78
+ .empty .btn { display: inline-flex; align-items: center; gap: 6px; }
79
+ .empty.first, .empty.nomatch { display: grid; gap: 14px; justify-items: center; }
80
+ .set-adv { margin: 0 0 16px; }
81
+ .set-adv > summary { cursor: pointer; font-weight: 650; font-size: 14px; padding: 6px 0; }
82
+ .set-adv > small { display: block; margin: 0 0 10px; color: var(--muted); }
74
83
 
75
84
  .layout { display: grid; grid-template-columns: 256px 1fr; max-width: 1200px; margin: 0 auto; }
76
85
  nav { padding: 16px 12px; border-right: 1px solid var(--line); position: sticky; top: 65px; align-self: start; max-height: calc(100vh - 65px); overflow: auto; }
@@ -266,6 +275,8 @@
266
275
  body.map-view.selecting .toast { top: calc(env(safe-area-inset-top) + 136px); bottom: auto; }
267
276
  .pick .qk, .keys kbd { font: 600 12px/1 ui-monospace, monospace; border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 5px; padding: 3px 6px; color: var(--muted); background: var(--bg); }
268
277
  .pick .qk { margin-right: 6px; }
278
+ /* Touch screens: no keyboard, so no key hints. */
279
+ @media (hover: none) { .chip kbd, .pick .qk, .kb-only { display: none; } }
269
280
  .keys { display: grid; grid-template-columns: auto 1fr; gap: 8px 14px; margin: 0 0 12px; font-size: 14px; align-items: center; }
270
281
  .keys h4 { grid-column: 1 / -1; margin: 6px 0 0; font-size: 13px; color: var(--muted); font-weight: 600; }
271
282
  .keys dt { justify-self: end; white-space: nowrap; }
@@ -391,7 +402,7 @@
391
402
  .swipe:target .card, .card:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
392
403
  .top { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; padding-right: 0; }
393
404
  @media (hover: hover) and (pointer: fine) { .top { padding-right: 150px; } }
394
- a.name { color: var(--text); font-weight: 700; font-size: 17px; text-decoration: none; letter-spacing: -.01em; }
405
+ a.name { color: var(--text); font-weight: 700; font-size: 17px; text-decoration: none; letter-spacing: -.01em; overflow-wrap: anywhere; min-width: 0; }
395
406
  a.name:hover { color: var(--accent); }
396
407
  .badge { font-size: 12px; padding: 1px 9px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); white-space: nowrap; }
397
408
  .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 2px; }
@@ -466,7 +477,7 @@
466
477
  @media (max-width: 720px) {
467
478
  header { padding: 10px 16px; padding-top: max(10px, env(safe-area-inset-top)); gap: 8px 10px; }
468
479
  .stats { display: none; }
469
- .lang { margin-left: auto; }
480
+ #lock:not([hidden]), #lock[hidden] + #add-btn { margin-left: auto; }
470
481
  .search { order: 3; flex-basis: 100%; max-width: none; margin: 0; font-size: 16px; /* 16px: iOS doesn't zoom in */ }
471
482
  .layout { grid-template-columns: 1fr; }
472
483
  /* The sidebar becomes a drawer behind the ☰ button. */
@@ -512,7 +523,7 @@
512
523
  .md-top .prev .ico { transform: rotate(180deg); }
513
524
  .md-scroll { overflow: auto; padding: 0 18px 12px; flex: 1; min-height: 0; overscroll-behavior: contain; }
514
525
  .md-scroll h3 { margin: 12px 0 6px; font-size: 21px; letter-spacing: -.01em; }
515
- .md-scroll h3 a { color: var(--text); text-decoration: none; }
526
+ .md-scroll h3 a { color: var(--text); text-decoration: none; overflow-wrap: anywhere; }
516
527
  .md-scroll h3 a:hover { color: var(--accent); }
517
528
  .md-sub { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; margin: 0 0 10px; color: var(--muted); font-size: 13px; }
518
529
  .md-one { margin: 0 0 6px; font-size: 16px; }
@@ -591,6 +602,9 @@
591
602
  <symbol id="i-split" viewBox="0 0 24 24"><rect x="3" y="4.5" width="18" height="15" rx="2"/><path d="M12 4.5v15"/></symbol>
592
603
  <symbol id="i-inbox" viewBox="0 0 24 24"><path d="M3.5 13.5 6 5.5h12l2.5 8M3.5 13.5V18a1.5 1.5 0 0 0 1.5 1.5h14a1.5 1.5 0 0 0 1.5-1.5v-4.5M3.5 13.5H8a4 4 0 0 0 8 0h4.5"/></symbol>
593
604
  <symbol id="i-sparkle" viewBox="0 0 24 24"><path d="M10 4l1.8 5.2L17 11l-5.2 1.8L10 18l-1.8-5.2L3 11l5.2-1.8zM18 3v4M16 5h4M18 16v4M16 18h4"/></symbol>
605
+ <symbol id="i-check" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M8.5 12.2l2.4 2.4 4.8-5"/></symbol>
606
+ <symbol id="i-tag" viewBox="0 0 24 24"><path d="M3.5 12.2V4.5a1 1 0 0 1 1-1h7.7l8.3 8.3a1.5 1.5 0 0 1 0 2.1l-6.2 6.2a1.5 1.5 0 0 1-2.1 0zM8 8h.01"/></symbol>
607
+ <symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></symbol>
594
608
  <symbol id="i-eye" viewBox="0 0 24 24"><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="3"/></symbol>
595
609
  </defs>
596
610
  </svg>
@@ -604,7 +618,9 @@
604
618
  <span class="update" id="update" hidden><a id="update-link" target="_blank" rel="noopener noreferrer"></a><button id="update-x" type="button">✕</button></span>
605
619
  <input id="q" class="search" type="search" enterkeyhint="search">
606
620
  <button id="lock" class="lock" type="button" hidden></button>
621
+ <button id="add-btn" class="lang hbtn" type="button" aria-haspopup="dialog"></button>
607
622
  <button id="palette-btn" class="lang" type="button" aria-haspopup="dialog"></button>
623
+ <button id="settings-btn" class="lang hbtn" type="button" aria-haspopup="dialog"></button>
608
624
  <button id="lang" class="lang" type="button"></button>
609
625
  </header>
610
626
  <button id="crumb" class="crumb" type="button" aria-controls="nav"></button>
@@ -711,8 +727,17 @@
711
727
  <input id="cmd-input" type="text" role="combobox" aria-expanded="true" aria-controls="cmd-list" aria-autocomplete="list" autocomplete="off" spellcheck="false">
712
728
  <div id="cmd-list" role="listbox"></div>
713
729
  </dialog>
730
+ <dialog id="add-dlg" aria-labelledby="ad-title">
731
+ <form id="add-dlg-form" method="dialog">
732
+ <h3 id="ad-title"></h3>
733
+ <p class="dlg-error" id="ad-error"></p>
734
+ <label><span id="ad-help"></span><input id="ad-url" type="text" inputmode="url" autocapitalize="off" autocomplete="off" spellcheck="false"></label>
735
+ <div class="dlg-actions"><span class="spacer"></span>
736
+ <button class="btn" id="ad-cancel" type="button"></button><button class="btn primary" id="ad-ok" type="submit"></button></div>
737
+ </form>
738
+ </dialog>
714
739
  <dialog id="keys-dlg" aria-labelledby="ky-title">
715
- <h3 id="ky-title"></h3>
740
+ <h3 id="ky-title" tabindex="-1"></h3>
716
741
  <dl class="keys" id="ky-body"></dl>
717
742
  <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="ky-close" type="button"></button></div>
718
743
  </dialog>
@@ -724,12 +749,16 @@
724
749
  </dialog>
725
750
  <div class="toast" id="toast" role="status"><span id="toast-text"></span><button id="toast-undo" type="button"></button></div>
726
751
  <script>
752
+ const cardsN = (n) => `${n} ${n === 1 ? "card" : "cards"}`;
727
753
  const STRINGS = {
728
754
  en: {
729
755
  search: "Search tools, tags, links…", all: "All", favorites: "Favorites", trash: "Trash", any: "Any",
730
756
  kind: "Kind", switchTo: "中文", nav: "Views and categories",
731
757
  stats: (n, s) => `${n} ${n === 1 ? "item" : "items"} · shared ${s}×`, shared: (n) => `shared ${n}×`,
732
- empty: "Nothing here yet — drop a link in your chat.", emptyFav: "No favorites yet — swipe a card right, or tap the star.",
758
+ empty: "Nothing here yet.", emptyStart: "Nothing here yet. Paste a link below to start — or save one with the Chrome extension, or run npx driftnet add <link>.",
759
+ noMatch: (q, v) => `No cards match “${q}” in ${v}.`, searchAll: "Search everything", searchIn: (v) => `Search ${v}…`,
760
+ addTitle: "Add a link", addHelp: "A link to a tool, post or video (example.com works too)", addThis: (u) => `Add this link: ${u}`, kAdd: "Add a link",
761
+ addedAlready: "Already saved — here it is", addNothing: "No link found in that.", noSuggestion: "No suggestion for this card — press m to pick a folder", emptyFav: "No favorites yet — swipe a card right, or tap the star.",
733
762
  pageMore: (n) => `Show more (${n} left)`, emptyTrash: "The trash is empty.", hint: "Swipe right to favorite, left to remove.", hintTrash: "Swipe right to restore.",
734
763
  kinds: { repo: "Repos", product: "Products", video: "Videos", article: "Articles", post: "Posts", other: "Other" },
735
764
  kind1: { repo: "Repo", product: "Product", video: "Video", article: "Article", post: "Post", other: "Other" },
@@ -745,13 +774,13 @@
745
774
  folders: "Folders", newFolder: "New folder", newSub: "New folder inside", editFolder: "Edit folder", folderName: "Name",
746
775
  folderDesc: "What goes here? (driftnet's AI reads this to sort new links)", folderParent: "Inside", topLevel: "— Top level —",
747
776
  save: "Save", cancel: "Cancel", del: "Delete folder", delSure: "Delete? Links move up",
748
- refresh: "Refresh (fetch and summarise again)", refreshed: (n) => `Refreshed “${n}”`, refreshBusy: "Already refreshing this one.", refreshWait: "Refreshed a moment ago — try again in a minute.", refreshFailed: (why) => `Couldn’t refresh${why ? `: ${why}` : ""}`,
777
+ refresh: "Refresh (fetch and summarise again)", refreshShort: "Re-summarise", refreshed: (n) => `Refreshed “${n}”`, refreshBusy: "Already refreshing this one.", refreshWait: "Refreshed a moment ago — try again in a minute.", refreshFailed: (why) => `Couldn’t refresh${why ? `: ${why}` : ""}`,
749
778
  moveTo: "Move to…", moveTitle: (n) => `Move “${n}” to`, moved: (n, f) => `Moved “${n}” to ${f}`, expand: "Show sub-folders",
750
779
  dragHint: "Drag onto a folder in the sidebar", foundIn: "Found in this post:", related: "Related:", folderMoved: (n, f) => `“${n}” is now inside ${f}`,
751
780
  topLevelShort: "the top level",
752
781
  pkShare: "Share as pack…", pkTitle: "Share as pack", pkHelp: "A pack is this folder, its sub-folders and the cards in them as one file. Someone else imports it with one click. Your notes, chat text and counters are never included.", pkName: "Pack name", pkDesc: "Description", pkDownload: "Download pack", pkLinkL: "Link to share", pkCopy: "Copy link", pkCopied: "Link copied", pkSigned: "Anyone with this link can download this one pack, and nothing else in your catalogue.", pkOpen: "Anyone who can reach this address can download this pack.", pkNoLink: "No public address is set, so there is no link to share yet. Set one in Settings → Access, or start a tunnel. You can still download the file.", pkClose: "Close", pkTooBig: "This folder is too big to share as a pack.",
753
782
  mapAll: "All", focusCrumb: "Mind map location", focusUp: "Up one level", focusFolder: "Focus on this folder", mapTree: "Mind map",
754
- mapHintFocus: "Double-click a folder (or press z on it) to focus on it.",
783
+ mapHintFocus: "Double-click a folder (or press z on it) to focus on it.", mapHintFocusTouch: "To show one folder on its own, tap its ⋯ and choose Focus on this folder.",
755
784
  kTreeNav: "Mind map: next / previous node", kTreeOpen: "Open a folder, or step into it", kTreeClose: "Close a folder, or step out to its parent", kTreeEnds: "First / last node", kTreeType: "Type a name", kTreeTypeText: "Jump to the node starting with it",
756
785
  kFocus: "Focus on the folder (mind map)", kFocusUp: "Back up one level (mind map)", keysMap: "Mind map",
757
786
  map: "Mind map", mapHint: "Tap a folder to open it, tap a card to preview it. To file a card: drag it onto a folder — on a phone, hold it a moment, let go, then tap the folder. ⋯ renames a folder.",
@@ -765,12 +794,12 @@
765
794
  histActor: (a) => a === "admin" ? "You" : a === "system:refresh" ? "Refresh" : a === "system" ? "System" : a.replace(/^agent:/, "agent "),
766
795
  notes: "Notes", note: "Note", addNote: "Add a note", editNote: "Edit note", noteFor: (n) => `Note on “${n}”`,
767
796
  noteHelp: "Only for you: what you thought, whether you tried it…", newNote: "New note", noteTitle: "Title",
768
- noteBody: "Markdown. Write #12 to link card 12.", delNote: "Delete note", delNoteSure: "Really delete?", untitled: "Untitled",
769
- emptyNotes: "No notes yet. Notes can link cards: write #12.", exportMd: "Download a backup (Markdown)", exportVault: "Download for Obsidian / Notion",
797
+ noteBody: "Type # and a card number (e.g. #3) to link a card.", delNote: "Delete note", delNoteSure: "Really delete?", untitled: "Untitled",
798
+ emptyNotes: "No notes yet. A note can link cards: type # and a card number (e.g. #3).", exportMd: "Export as Markdown", exportVault: "Download for Obsidian / Notion",
770
799
  saved: "Saved", tagsEdit: "Edit tags", tagsHelp: "Tags, separated by commas (up to 8)", purge: "Delete forever", purgeSure: "Click again to delete forever", purged: (n) => `“${n}” deleted for good`,
771
- emptyTrashBtn: "Empty trash", emptyTrashSure: (n) => `Click again to delete ${n} for good`, trashEmptied: (n) => `${n} cards deleted for good`, settings: "Settings", pickedUp: (n) => `Picked up “${n}” — tap the folder it goes into`, alreadyThere: "It's already in that folder",
800
+ emptyTrashBtn: "Empty trash", emptyTrashSure: (n) => `Click again to delete ${n} for good`, trashEmptied: (n) => `${n} ${n === 1 ? "card" : "cards"} deleted for good`, settings: "Settings", pickedUp: (n) => `Picked up “${n}” — tap the folder it goes into`, alreadyThere: "It's already in that folder",
772
801
  readOnlyNudge: "You can only look here — tap Unlock at the top to change things", filterFolders: "Type to find a folder…", undoHint: "z undoes",
773
- tplTitle: "Start with folders for:", tplAi: "AI & coding", tplResearch: "Research", tplEveryday: "Everyday", tplSkip: "Keep the default", tplFailed: "Can't change the folders now: you already have cards or changed them.",
802
+ tplTitle: "Pick a starter set of folders (it replaces the current default folders):", tplAi: "AI & coding", tplResearch: "Research", tplEveryday: "Everyday", tplSkip: "Keep the default", tplFailed: "Can't change the folders now: you already have cards or changed them.",
774
803
  addLink: "Add", addPlaceholder: "Paste a link to a tool, post or video…", added: "Saved — sorting it now",
775
804
  shortcuts: "Keys: j / k next / previous · f favorite · m move · n note · # trash · / search · g m mind map",
776
805
  keysTitle: "Keyboard shortcuts", keysMove: "Move, favorite, trash", keysSelect: "Select several cards", keysGo: "Go to", keysQuick: "File into your most-used folders",
@@ -786,17 +815,18 @@
786
815
  inbox: "Inbox", emptyInbox: "Inbox zero — every card has a folder you chose.", hintInbox: "Tap a folder to file the card. Not filed yet: the cards below.",
787
816
  chipOther: "Other folder…", chipTitle: (p) => `Confidence ${p}%`,
788
817
  keysInbox: "In the Inbox", kChip: "File into the card's suggested folder 1–3", kSkip: "Skip: focus the next card", kQuickInbox: "In the Inbox, 1–3 pick the focused card's suggested folders instead; 4–9 still file into your most-used folders.",
789
- planBtn: "Suggest folders", planNoModel: "Needs an AI model (Settings → AI)", planTitle: "Suggested folder changes",
818
+ planBtn: "Suggest folders", planNoModel: "Needs an AI model — set one in ⚙ Settings → AI", planTitle: "Suggested folder changes",
790
819
  planIntro: "The AI only proposes. Tick what you want, then apply; nothing changes until then, and Undo reverts the whole plan. Cards you filed by hand are never moved.",
791
820
  planThinking: "Asking the model…", planNone: "The model found nothing worth changing.", planApply: (n) => `Apply ${n} selected`,
792
821
  planCreate: (p) => `Create “${p}”`, planRename: (a, b) => `Rename “${a}” to “${b}”`, planMove: (n, d) => `Move ${n} ${n === 1 ? "card" : "cards"} to “${d}”`,
793
822
  planMerge: (a, b) => `Merge “${a}” into “${b}”`, planApplied: (n) => `Applied ${n} ${n === 1 ? "change" : "changes"} to your folders`, planNeeds: "Needs the folder it creates",
794
823
  nSelected: (n) => `${n} selected`, selectAll: "Select all", clearSel: "Clear", trashShort: "Trash",
795
824
  moveTitleMany: (n) => `Move ${n} cards to`, pickedMany: (n) => `Picked up ${n} cards — tap the folder they go into`,
796
- bulkMoved: (n, f) => `Moved ${n} cards to ${f}`, bulkRemoved: (n) => `${n} cards moved to the trash`, bulkRestored: (n) => `${n} cards restored`,
797
- bulkFaved: (n) => `${n} cards added to favorites`, bulkUnfaved: (n) => `${n} cards removed from favorites`,
825
+ bulkMoved: (n, f) => `Moved ${cardsN(n)} to ${f}`, bulkRemoved: (n) => `${cardsN(n)} moved to the trash`, bulkRestored: (n) => `${cardsN(n)} restored`,
826
+ bulkFaved: (n) => `${cardsN(n)} added to favorites`, bulkUnfaved: (n) => `${cardsN(n)} removed from favorites`,
798
827
  st: {
799
- title: "Settings", save: "Save", welcome: "Welcome! Pick a model below to get summaries — or none: links are still sorted into folders, just without a summary. Then paste a link.",
828
+ title: "Settings", save: "Save", welcome: "Welcome! Pick a model below to get summaries and links sorted into folders. Without one, links are still saved: they wait in Other (and the Inbox) for you to file, and an agent you connect can write the summaries. Then paste a link.",
829
+ advanced: "Advanced", advancedHelp: "Other providers' settings, search by meaning, extra keys and video tool paths.", openSettings: "Open Settings",
800
830
  display: "This browser", sort: "Order", sorts: { best: "Best first", newest: "Newest first", shared: "Most shared first" },
801
831
  compact: "Compact cards (one line each)", tags: "Show tags", said: "Show what people said in chat",
802
832
  theme: "Theme", themes: { auto: "Follow the system", light: "Light", dark: "Dark" },
@@ -855,7 +885,7 @@
855
885
  loginAdvanced: "Forgot it (you set it up)? Open driftnet on the computer it runs on — Settings there sets a new one. On a server: From your computer run ssh -L PORT:127.0.0.1:PORT <server> and open http://localhost:PORT.",
856
886
  keyWrong: "That's neither the admin password nor a share key.",
857
887
  labels: {
858
- DRIFTNET_LLM_PROVIDER: ["Model provider", "Summaries. None: links are still sorted, only without a summary."],
888
+ DRIFTNET_LLM_PROVIDER: ["Model provider", "Writes the summaries and sorts links into folders. None: links are saved and wait in Other / the Inbox for you to file; an agent can write the summaries."],
859
889
  DRIFTNET_LLM_MODEL: ["Model", "e.g. claude-haiku-5-5, gpt-5-mini, gemini-3.8-flash, qwen3"],
860
890
  DRIFTNET_LLM_BASE_URL: ["API URL", "For OpenAI-compatible APIs: Gemini, Grok, OpenRouter, Ollama (http://127.0.0.1:11434/v1)…"],
861
891
  DRIFTNET_LLM_API_KEY: ["API key", ""],
@@ -905,7 +935,7 @@
905
935
  choices: {
906
936
  DRIFTNET_LLM_PROVIDER: { "": "None", anthropic: "Anthropic (API key)", openai: "OpenAI-compatible (OpenAI, Grok, Ollama…)", gemini: "Google Gemini (API key)", bedrock: "Amazon Bedrock", vertex: "Google Vertex AI", "claude-cli": "Claude subscription (Claude Code CLI)", "gemini-cli": "Google account (Gemini CLI)" },
907
937
  DRIFTNET_LLM_EFFORT: { "": "Default", low: "Low", medium: "Medium", high: "High", xhigh: "Extra high" },
908
- DRIFTNET_JUDGE: { "": "Jev if a key is set", jev: "Jev", rules: "Rules (free, no model)", llm: "The model decides", heuristic: "The model decides", off: "No judge" },
938
+ DRIFTNET_JUDGE: { "": "Jev if a key is set", jev: "Jev", rules: "Rules (free, no model)", llm: "The model decides", heuristic: "No judge: unsorted links go to Other", off: "No judge" },
909
939
  DRIFTNET_SUMMARY_DEPTH: { "": "Standard (default)", brief: "Brief: one line, 2 highlights, what you see", standard: "Standard", detailed: "Detailed: more highlights, use cases, how to try it" },
910
940
  DRIFTNET_LOCALE: { "": "Same as the summaries", en: "English", "zh-TW": "繁體中文" },
911
941
  DRIFTNET_REPLY_STYLE: { "": "Rich (default)", rich: "Rich: cards and vote buttons", text: "Plain text" },
@@ -926,7 +956,10 @@
926
956
  search: "搜尋工具、標籤、連結…", all: "全部", favorites: "最愛", trash: "垃圾桶", any: "不限",
927
957
  kind: "類型", switchTo: "EN", nav: "檢視與分類",
928
958
  stats: (n, s) => `${n} 則 · 分享 ${s} 次`, shared: (n) => `分享 ${n} 次`,
929
- empty: "還沒有內容,把連結丟進聊天室吧。", emptyFav: "還沒有最愛,把卡片往右滑或按星號。",
959
+ empty: "這裡還沒有內容。", emptyStart: "還沒有內容。在下面貼一個連結開始,或用 Chrome 擴充功能收錄,也可以執行 npx driftnet add <連結>。",
960
+ noMatch: (q, v) => `「${v}」裡沒有符合「${q}」的卡片。`, searchAll: "搜尋全部", searchIn: (v) => `在「${v}」裡搜尋…`,
961
+ addTitle: "收錄連結", addHelp: "工具、貼文或影片的連結(只打 example.com 也可以)", addThis: (u) => `收錄這個連結:${u}`, kAdd: "收錄連結",
962
+ addedAlready: "已經收過了,就是這張", addNothing: "裡面找不到連結。", noSuggestion: "這張卡片沒有建議的資料夾,按 m 自己選", emptyFav: "還沒有最愛,把卡片往右滑或按星號。",
930
963
  pageMore: (n) => `再顯示 ${n} 張`, emptyTrash: "垃圾桶是空的。", hint: "往右滑加入最愛,往左滑移到垃圾桶。", hintTrash: "往右滑還原。",
931
964
  kinds: { repo: "程式庫", product: "產品", video: "影片", article: "文章", post: "貼文", other: "其他" },
932
965
  worth: { skip: "略過", low: "次要", normal: "值得看", "must-see": "必看" },
@@ -941,13 +974,13 @@
941
974
  folders: "資料夾", newFolder: "新資料夾", newSub: "在裡面新增資料夾", editFolder: "編輯資料夾", folderName: "名稱",
942
975
  folderDesc: "放什麼?(driftnet 的 AI 會照這段說明把新連結分進來)", folderParent: "放在", topLevel: "— 最上層 —",
943
976
  save: "儲存", cancel: "取消", del: "刪除資料夾", delSure: "確定刪除?內容移到上一層",
944
- refresh: "重新整理(再抓一次並重新摘要)", refreshed: (n) => `已重新整理「${n}」`, refreshBusy: "這張卡片正在重新整理。", refreshWait: "剛剛才整理過,請一分鐘後再試。", refreshFailed: (why) => `重新整理失敗${why ? `:${why}` : ""}`,
977
+ refresh: "重新整理(再抓一次並重新摘要)", refreshShort: "重新摘要", refreshed: (n) => `已重新整理「${n}」`, refreshBusy: "這張卡片正在重新整理。", refreshWait: "剛剛才整理過,請一分鐘後再試。", refreshFailed: (why) => `重新整理失敗${why ? `:${why}` : ""}`,
945
978
  moveTo: "移動到…", moveTitle: (n) => `把「${n}」移動到`, moved: (n, f) => `已將「${n}」移到 ${f}`, expand: "展開子資料夾",
946
979
  dragHint: "拖到側邊欄的資料夾", foundIn: "從這篇找到:", related: "相關卡片:", folderMoved: (n, f) => `「${n}」已移到 ${f} 底下`,
947
980
  topLevelShort: "最上層",
948
981
  pkShare: "分享成資料夾包…", pkTitle: "分享成資料夾包", pkHelp: "資料夾包把這個資料夾、底下的子資料夾和裡面的卡片包成一個檔案,別人一鍵就能匯入。你的筆記、聊天內容和各種計數都不會放進去。", pkName: "資料夾包名稱", pkDesc: "說明", pkDownload: "下載資料夾包", pkLinkL: "分享連結", pkCopy: "複製連結", pkCopied: "已複製連結", pkSigned: "拿到這個連結的人只能下載這一個資料夾包,看不到你目錄裡的其他內容。", pkOpen: "任何連得到這個位址的人都能下載這個資料夾包。", pkNoLink: "還沒設定公開網址,所以暫時沒有可分享的連結。請到「設定 → 存取」設定,或啟動通道。現在仍可以下載檔案。", pkClose: "關閉", pkTooBig: "這個資料夾太大,無法分享成資料夾包。",
949
982
  mapAll: "全部", focusCrumb: "樹狀圖位置", focusUp: "回上一層", focusFolder: "聚焦這個資料夾", mapTree: "樹狀圖",
950
- mapHintFocus: "連點兩下資料夾(或在資料夾上按 z)可以只看這個資料夾。",
983
+ mapHintFocus: "連點兩下資料夾(或在資料夾上按 z)可以只看這個資料夾。", mapHintFocusTouch: "想只看一個資料夾:點它的 ⋯,再選「聚焦這個資料夾」。",
951
984
  kTreeNav: "樹狀圖:下一個/上一個節點", kTreeOpen: "展開資料夾,或進入第一個子項", kTreeClose: "收合資料夾,或回到上一層", kTreeEnds: "第一個/最後一個節點", kTreeType: "直接輸入名稱", kTreeTypeText: "跳到名稱開頭相符的節點",
952
985
  kFocus: "聚焦這個資料夾(樹狀圖)", kFocusUp: "回上一層(樹狀圖)", keysMap: "樹狀圖",
953
986
  map: "樹狀圖", mapHint: "點資料夾展開,點卡片預覽。整理卡片:把它拖到資料夾上;手機上按住卡片一下、放開,再點要放進去的資料夾。按 ⋯ 可以改資料夾名稱。",
@@ -961,12 +994,12 @@
961
994
  histActor: (a) => a === "admin" ? "你" : a === "system:refresh" ? "重新整理" : a === "system" ? "系統" : a.replace(/^agent:/, "agent "),
962
995
  notes: "筆記", note: "筆記", addNote: "加筆記", editNote: "改筆記", noteFor: (n) => `「${n}」的筆記`,
963
996
  noteHelp: "只有你看得到:心得、試用結果、要注意的地方…", newNote: "新筆記", noteTitle: "標題",
964
- noteBody: "支援 Markdown。寫 #12 就會連到第 12 張卡片。", delNote: "刪除筆記", delNoteSure: "確定刪除?", untitled: "未命名",
965
- emptyNotes: "還沒有筆記。筆記可以連到卡片:寫 #12。", exportMd: "下載備份(Markdown)", exportVault: "下載給 Obsidian/Notion",
997
+ noteBody: "輸入 # 加卡片編號(例如 #3)就能連到那張卡片。", delNote: "刪除筆記", delNoteSure: "確定刪除?", untitled: "未命名",
998
+ emptyNotes: "還沒有筆記。筆記可以連到卡片:輸入 # 加卡片編號(例如 #3)。", exportMd: "匯出成 Markdown", exportVault: "下載給 Obsidian/Notion",
966
999
  saved: "已儲存", tagsEdit: "編輯標籤", tagsHelp: "標籤,用逗號分隔(最多 8 個)", purge: "永久刪除", purgeSure: "再按一次即永久刪除", purged: (n) => `已永久刪除「${n}」`,
967
1000
  emptyTrashBtn: "清空垃圾桶", emptyTrashSure: (n) => `再按一次,永久刪除這 ${n} 張`, trashEmptied: (n) => `已永久刪除 ${n} 張卡片`, settings: "設定", pickedUp: (n) => `已拿起「${n}」,點要放進去的資料夾`, alreadyThere: "它已經在這個資料夾裡了",
968
1001
  readOnlyNudge: "目前只能看。要修改,請點上方的「解鎖」", filterFolders: "輸入文字找資料夾…", undoHint: "按 z 復原",
969
- tplTitle: "從這些資料夾開始:", tplAi: "AI 與程式", tplResearch: "研究", tplEveryday: "日常生活", tplSkip: "維持預設", tplFailed: "現在不能換資料夾了:已經有卡片,或資料夾被你改過。",
1002
+ tplTitle: "選一組起始資料夾(會取代目前的預設資料夾):", tplAi: "AI 與程式", tplResearch: "研究", tplEveryday: "日常生活", tplSkip: "維持預設", tplFailed: "現在不能換資料夾了:已經有卡片,或資料夾被你改過。",
970
1003
  addLink: "收錄", addPlaceholder: "貼上工具、貼文或影片的連結…", added: "收到,正在整理",
971
1004
  shortcuts: "快捷鍵:j/k 下一張/上一張 · f 最愛 · m 移動 · n 筆記 · # 垃圾桶 · / 搜尋 · g m 樹狀圖",
972
1005
  keysTitle: "快捷鍵", keysMove: "移動、最愛、垃圾桶", keysSelect: "一次選多張卡片", keysGo: "切換畫面", keysQuick: "放進最常用的資料夾",
@@ -982,7 +1015,7 @@
982
1015
  inbox: "收件匣", emptyInbox: "收件匣清空了——每張卡片都有你選的資料夾。", hintInbox: "點一下資料夾就能歸檔。下面是還沒歸檔的卡片。",
983
1016
  chipOther: "其他資料夾…", chipTitle: (p) => `信心 ${p}%`,
984
1017
  keysInbox: "在收件匣", kChip: "歸到這張卡片建議的第 1–3 個資料夾", kSkip: "略過:移到下一張卡片", kQuickInbox: "在收件匣裡,1–3 改成選擇目前卡片的建議資料夾;4–9 仍然是放進最常用的資料夾。",
985
- planBtn: "建議整理資料夾", planNoModel: "需要先設定 AI 模型(設定 → AI)", planTitle: "建議的資料夾調整",
1018
+ planBtn: "建議整理資料夾", planNoModel: "需要 AI 模型:請到 ⚙ 設定 → AI 設定一個", planTitle: "建議的資料夾調整",
986
1019
  planIntro: "AI 只負責提議。勾選想要的項目再套用,套用前什麼都不會改;復原可以一次還原整份方案。你親手歸檔的卡片不會被移動。",
987
1020
  planThinking: "正在請模型想想…", planNone: "模型認為目前沒有值得調整的地方。", planApply: (n) => `套用選取的 ${n} 項`,
988
1021
  planCreate: (p) => `新增「${p}」`, planRename: (a, b) => `把「${a}」改名為「${b}」`, planMove: (n, d) => `把 ${n} 張卡片移到「${d}」`,
@@ -992,7 +1025,8 @@
992
1025
  bulkMoved: (n, f) => `已將 ${n} 張卡片移到 ${f}`, bulkRemoved: (n) => `已將 ${n} 張卡片移到垃圾桶`, bulkRestored: (n) => `已還原 ${n} 張卡片`,
993
1026
  bulkFaved: (n) => `已將 ${n} 張卡片加入最愛`, bulkUnfaved: (n) => `已將 ${n} 張卡片移出最愛`,
994
1027
  st: {
995
- title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型就會有摘要;不選也可以,連結一樣會分進資料夾,只是沒有摘要。接著貼一個連結試試看。",
1028
+ title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型,就會有摘要,連結也會自動分進資料夾。不選也可以:連結照樣會存下來,先放在「其他」(和收件匣)等你歸檔,接上的 agent 也能幫你寫摘要。接著貼一個連結試試看。",
1029
+ advanced: "進階", advancedHelp: "其他供應商的設定、語意搜尋、額外的金鑰和影片工具路徑。", openSettings: "開啟設定",
996
1030
  display: "這個瀏覽器", sort: "排序", sorts: { best: "值得看的在前", newest: "最新的在前", shared: "最多人分享的在前" },
997
1031
  compact: "精簡卡片(每張一行)", tags: "顯示標籤", said: "顯示大家在聊天室說的話",
998
1032
  theme: "外觀", themes: { auto: "跟系統一樣", light: "淺色", dark: "深色" },
@@ -1051,7 +1085,7 @@
1051
1085
  loginAdvanced: "密碼是你自己設的但忘了?到跑 driftnet 的那台電腦打開網頁,設定裡可以直接設新的。跑在伺服器上的話:在你的電腦執行 ssh -L PORT:127.0.0.1:PORT <伺服器> 再打開 http://localhost:PORT。",
1052
1086
  keyWrong: "這不是管理密碼,也不是分享碼。",
1053
1087
  labels: {
1054
- DRIFTNET_LLM_PROVIDER: ["模型來源", "用來寫摘要。選「不使用」也會分類,只是沒有摘要。"],
1088
+ DRIFTNET_LLM_PROVIDER: ["模型來源", "用來寫摘要,並把連結分進資料夾。選「不使用」:連結照樣存下來,放在「其他」/收件匣等你歸檔;接上的 agent 也能幫忙寫摘要。"],
1055
1089
  DRIFTNET_LLM_MODEL: ["模型", "例如 claude-haiku-5-5、gpt-5-mini、gemini-3.8-flash、qwen3"],
1056
1090
  DRIFTNET_LLM_BASE_URL: ["API 網址", "OpenAI 相容 API 用:Gemini、Grok、OpenRouter、Ollama(http://127.0.0.1:11434/v1)…"],
1057
1091
  DRIFTNET_LLM_API_KEY: ["API 金鑰", ""],
@@ -1101,7 +1135,7 @@
1101
1135
  choices: {
1102
1136
  DRIFTNET_LLM_PROVIDER: { "": "不使用", anthropic: "Anthropic(API 金鑰)", openai: "OpenAI 相容(OpenAI、Grok、Ollama…)", gemini: "Google Gemini(API 金鑰)", bedrock: "Amazon Bedrock", vertex: "Google Vertex AI", "claude-cli": "Claude 訂閱(Claude Code CLI)", "gemini-cli": "Google 帳號(Gemini CLI)" },
1103
1137
  DRIFTNET_LLM_EFFORT: { "": "預設", low: "低", medium: "中", high: "高", xhigh: "極高" },
1104
- DRIFTNET_JUDGE: { "": "有 Jev 金鑰就用 Jev", jev: "Jev", rules: "規則(免費,不用模型)", llm: "交給模型", heuristic: "交給模型", off: "不用判斷器" },
1138
+ DRIFTNET_JUDGE: { "": "有 Jev 金鑰就用 Jev", jev: "Jev", rules: "規則(免費,不用模型)", llm: "交給模型", heuristic: "不用判斷器:沒分類的連結放到「其他」", off: "不用判斷器" },
1105
1139
  DRIFTNET_SUMMARY_DEPTH: { "": "標準(預設)", brief: "簡短:一句話、2 個重點、看得到什麼", standard: "標準", detailed: "詳細:更多重點、使用情境、怎麼試用" },
1106
1140
  DRIFTNET_LOCALE: { "": "跟摘要一樣", en: "English", "zh-TW": "繁體中文" },
1107
1141
  DRIFTNET_REPLY_STYLE: { "": "豐富(預設)", rich: "豐富:卡片與投票按鈕", text: "純文字" },
@@ -1154,6 +1188,8 @@
1154
1188
  let role = "admin";
1155
1189
  let serverPort = 8787;
1156
1190
  let summaries = true;
1191
+ /** What /api/ui said last (local page, password set…). */
1192
+ let uiInfo = {};
1157
1193
  /** Something needs the password: ask in a dialog that checks it, and keep whatever the user was doing. */
1158
1194
  function needAdmin() {
1159
1195
  toast(T().needPassword);
@@ -1237,10 +1273,35 @@
1237
1273
  $("lang").textContent = T().switchTo;
1238
1274
  $("palette-btn").textContent = isMac ? "⌘K" : "Ctrl K";
1239
1275
  $("palette-btn").title = $("palette-btn").ariaLabel = T().palette;
1276
+ $("add-btn").innerHTML = ic("plus"); $("add-btn").title = $("add-btn").ariaLabel = `${T().addTitle} (a)`;
1277
+ $("settings-btn").innerHTML = ic("gear"); $("settings-btn").title = $("settings-btn").ariaLabel = T().settings;
1240
1278
  $("nav").setAttribute("aria-label", T().nav);
1241
1279
  $("menu").setAttribute("aria-label", T().menu);
1242
1280
  }
1243
1281
 
1282
+ // ── Back closes things (phones) ──────────────────────────────────────────
1283
+ // While a card, a dialog or the drawer is open there is one extra history entry ({dnLayer}); Back lands on the
1284
+ // entry before it and closes the top one. Closing it any other way takes the entry back, keeping the address it had.
1285
+ let layerTimer = 0, carryUrl = null;
1286
+ const layersOpen = () => !!document.querySelector("dialog[open]") || (document.body.classList.contains("menu-open") && isDrawer());
1287
+ function syncLayer() {
1288
+ clearTimeout(layerTimer);
1289
+ // A moment later: closing one dialog and opening the next (card → Move to…) must not step back and forth.
1290
+ layerTimer = setTimeout(() => {
1291
+ const open = layersOpen(), pushed = !!history.state?.dnLayer;
1292
+ if (open && !pushed) history.pushState({ dnLayer: 1 }, "", location.href);
1293
+ else if (!open && pushed) { carryUrl = location.href; history.back(); }
1294
+ }, 60);
1295
+ }
1296
+ addEventListener("popstate", () => {
1297
+ if (carryUrl) { const u = carryUrl; carryUrl = null; if (u !== location.href) history.replaceState(history.state, "", u); return; }
1298
+ const top = [...document.querySelectorAll("dialog[open]")].pop();
1299
+ if (top) top.close();
1300
+ else if (document.body.classList.contains("menu-open")) setMenu(false);
1301
+ syncLayer();
1302
+ });
1303
+ new MutationObserver(syncLayer).observe(document.body, { subtree: true, attributes: true, attributeFilter: ["open"] });
1304
+
1244
1305
  // ── Drawer (phones) ──────────────────────────────────────────────────────
1245
1306
  const isDrawer = () => matchMedia("(max-width: 720px)").matches;
1246
1307
  /** keyboard: move focus into the drawer and back (a tap doesn't need the focus ring). */
@@ -1251,6 +1312,7 @@
1251
1312
  document.querySelector("header").inert = open && isDrawer();
1252
1313
  document.querySelector(".skip").inert = open && isDrawer();
1253
1314
  $("menu").setAttribute("aria-expanded", String(open));
1315
+ syncLayer();
1254
1316
  if (!keyboard) return;
1255
1317
  if (open) $("nav").querySelector('[aria-pressed="true"]')?.focus({ preventScroll: true });
1256
1318
  else if (isDrawer()) $("menu").focus({ preventScroll: true });
@@ -1262,13 +1324,21 @@
1262
1324
  addEventListener("keydown", (e) => { if (e.key === "Escape" && document.body.classList.contains("menu-open")) setMenu(false, true); });
1263
1325
 
1264
1326
  /** One line under the header saying what is shown, so a closed drawer hides nothing. */
1265
- function updateCrumb() {
1327
+ /** What is shown, in words: the view, then the folder and kind filters. */
1328
+ function viewName() {
1266
1329
  const t = T();
1267
1330
  const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash : state.view === "inbox" ? t.inbox : state.view === "review" ? t.review
1268
1331
  : state.view === "notes" ? t.notes : state.view === "map" ? t.map : t.all];
1269
1332
  if (state.category) parts.push(catLabel(state.category));
1270
1333
  if (state.kind) parts.push(t.kinds[state.kind] ?? state.kind);
1271
- $("crumb").innerHTML = `${esc(t.showing)} <b>${esc(parts.join(" · "))}</b>`;
1334
+ return parts.join(" · ");
1335
+ }
1336
+ function updateCrumb() {
1337
+ const t = T(), name = viewName();
1338
+ $("crumb").innerHTML = `${esc(t.showing)} <b>${esc(name)}</b>`;
1339
+ // The search box says what it searches: everything, or only the view / folder on screen.
1340
+ const ph = state.view === "all" && !state.category && !state.kind ? t.search : t.searchIn(name);
1341
+ $("q").placeholder = ph; $("q").setAttribute("aria-label", ph);
1272
1342
  }
1273
1343
 
1274
1344
  async function load() {
@@ -1287,6 +1357,8 @@
1287
1357
  role = ui.role ?? "admin";
1288
1358
  serverPort = ui.port ?? 8787;
1289
1359
  summaries = ui.summaries ?? true;
1360
+ uiInfo = ui;
1361
+ if (state.category && !folders.some((f) => f.id === state.category)) state.category = "";
1290
1362
  document.body.classList.toggle("readonly", role !== "admin");
1291
1363
  $("lock").hidden = role === "admin";
1292
1364
  if (ui.setup && !store.get("driftnet-setup-seen")) { store.set("driftnet-setup-seen", "1"); setTimeout(() => openSettings(true), 300); }
@@ -1587,9 +1659,14 @@
1587
1659
  moveBest = null;
1588
1660
  $("mv-filter").placeholder = t.filterFolders;
1589
1661
  $("mv-filter").setAttribute("aria-label", t.filterFolders);
1590
- $("move-dlg").showModal();
1591
1662
  // Type to narrow the folders; Enter files into the first match; arrows walk the list.
1592
- $("mv-filter").focus();
1663
+ // A phone gets the list, not a keyboard popping up over it: the filter takes focus only with a mouse or trackpad.
1664
+ const fine = matchMedia("(pointer: fine)").matches;
1665
+ $("move-dlg").toggleAttribute("autofocus", !fine);
1666
+ $("move-dlg").tabIndex = -1;
1667
+ $("move-dlg").showModal();
1668
+ if (fine) $("mv-filter").focus();
1669
+ else if (document.activeElement === $("mv-filter")) $("move-dlg").focus();
1593
1670
  }
1594
1671
  $("mv-cancel").onclick = () => $("move-dlg").close();
1595
1672
  $("mv-filter").addEventListener("input", () => {
@@ -1623,15 +1700,13 @@
1623
1700
  else moveItem(moving, b.dataset.to);
1624
1701
  };
1625
1702
 
1626
- async function moveItem(id, to, quiet = false) {
1703
+ async function moveItem(id, to) {
1627
1704
  const item = find(id);
1628
1705
  if (!item || item.category === to) return;
1629
1706
  const from = item.category;
1630
- const token = store.get("driftnet-token");
1631
- const res = await fetch(`/api/items/${id}/move`, { method: "POST", body: JSON.stringify({ folder: to }),
1632
- headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) } }).catch(() => null);
1633
- if (res?.status === 401) return needAdmin();
1634
- if (!res?.ok) return toast(T().failed);
1707
+ // Through the bulk endpoint: its Undo puts the card back exactly as it was (still unfiled, in the Inbox, if it was).
1708
+ const r = await mapWrite("/api/items/bulk", "POST", { action: "move", ids: [id], folder: to });
1709
+ if (!r) return;
1635
1710
  item.category = to;
1636
1711
  const f = folderById(to); if (f) f.count++;
1637
1712
  const old = folderById(from); if (old) old.count--;
@@ -1650,7 +1725,15 @@
1650
1725
  if (onMap && onMap !== item) onMap.category = to;
1651
1726
  if (mapShown()) drawMap();
1652
1727
  bumpUse(to);
1653
- if (!quiet) { toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); renderKeep(); }); }
1728
+ refreshCounts();
1729
+ toast(T().moved(nameOf(item), folderPath(to)), async () => {
1730
+ if (!(await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo }))) return;
1731
+ item.category = from;
1732
+ if (onMap) onMap.category = from;
1733
+ await refreshFolders();
1734
+ await renderKeep();
1735
+ refreshCounts();
1736
+ });
1654
1737
  }
1655
1738
  const subtreeOf = (id) => { const out = new Set([id]); for (const q = [id]; q.length;) for (const k of kids(q.pop())) { out.add(k.id); q.push(k.id); } return out; };
1656
1739
  /** Re-draw just the tree's counts after a move. */
@@ -1720,7 +1803,7 @@
1720
1803
  /** The token list Settings last fetched, to warn when a new token repeats an active name. */
1721
1804
  let knownTokens = [];
1722
1805
  const nameTaken = (list, name) => list.some((k) => !k.revokedAt && k.name.toLowerCase() === name.toLowerCase());
1723
- async function openSettings(welcome = false) {
1806
+ async function openSettings(welcome = false, want = null) {
1724
1807
  const t = T(), st = t.st;
1725
1808
  const token = store.get("driftnet-token");
1726
1809
  const res = await fetch("/api/settings", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
@@ -1759,12 +1842,12 @@
1759
1842
  server = {
1760
1843
  general: group("language") + group("chat") + group("digest") + group("webhook") + group("updates") + importPanel() + backupPanel(serverSettings),
1761
1844
  access: accessStatus + accessPanel(serverSettings, field) + (agentTokens ? tokensPanel(serverSettings.access, agentTokens, minted) + pairPanel(serverSettings.access) : ""),
1762
- ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + group("model") + group("rules") +
1845
+ ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + aiPanel(serverSettings, field) +
1763
1846
  `<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`,
1764
1847
  };
1765
1848
  }
1766
1849
  // Three tabs instead of one long scroll: what you see, who gets in, which AI.
1767
- const tab = welcome ? "ai" : store.get("driftnet-settings-tab") || "general";
1850
+ const tab = want ?? (welcome ? "ai" : store.get("driftnet-settings-tab") || "general");
1768
1851
  const tabs = [["general", st.tabGeneral], ["access", st.tabAccess], ["ai", st.tabAi]];
1769
1852
  const section = (k, html) => `<section data-tab="${k}" role="tabpanel" id="panel-${k}" aria-labelledby="tab-${k}">${html}</section>`;
1770
1853
  $("st-title").textContent = st.title;
@@ -1775,12 +1858,39 @@
1775
1858
  ? section("general", local) + section("access", server) + section("ai", server)
1776
1859
  : section("general", local + server.general) + section("access", server.access) + section("ai", server.ai));
1777
1860
  $("st-body").dataset.tab = tab;
1861
+ placeAi();
1778
1862
  $("st-cancel").textContent = t.cancel;
1779
1863
  $("st-save").textContent = st.save;
1780
1864
  settingsOpener = isDrawer() ? $("menu") : document.activeElement;
1781
1865
  $("settings-dlg").showModal();
1782
1866
  $("st-body").querySelector('[data-tab-btn][aria-selected="true"]')?.focus();
1783
1867
  }
1868
+ /** Settings › AI: the chosen provider's own fields sit under it; other providers', embeddings and tool paths fold into Advanced. */
1869
+ const PROVIDER_FIELDS = { DRIFTNET_LLM_MODEL: "anthropic openai gemini bedrock vertex claude-cli gemini-cli", DRIFTNET_LLM_BASE_URL: "openai",
1870
+ DRIFTNET_LLM_API_KEY: "anthropic openai gemini vertex", DRIFTNET_LLM_EFFORT: "anthropic openai gemini", DRIFTNET_LLM_REGION: "bedrock vertex",
1871
+ AWS_ACCESS_KEY_ID: "bedrock", AWS_SECRET_ACCESS_KEY: "bedrock", AWS_SESSION_TOKEN: "bedrock", AWS_BEARER_TOKEN_BEDROCK: "bedrock",
1872
+ GOOGLE_CLOUD_PROJECT: "vertex", DRIFTNET_VERTEX_CREDENTIALS: "vertex" };
1873
+ const AI_ADVANCED = ["TYPESAFE_API_KEY", "GITHUB_TOKEN", "DRIFTNET_EMBED", "DRIFTNET_EMBED_PROVIDER", "DRIFTNET_EMBED_MODEL", "DRIFTNET_EMBED_BASE_URL",
1874
+ "DRIFTNET_EMBED_API_KEY", "DRIFTNET_EMBED_FLOOR", "DRIFTNET_YTDLP", "DRIFTNET_FFMPEG", "DRIFTNET_TESSERACT", "DRIFTNET_WHISPER"];
1875
+ function aiPanel(sv, field) {
1876
+ const st = T().st, all = sv.settings;
1877
+ const adv = new Set(AI_ADVANCED);
1878
+ if (all.find((x) => x.key === "DRIFTNET_JUDGE")?.value !== "rules") adv.add("DRIFTNET_JUDGE_RULES");
1879
+ const row = (s, n) => field(s).replace('<label class="set-row"', `<label class="set-row" data-n="${n}"${PROVIDER_FIELDS[s.key] ? ` data-for="${PROVIDER_FIELDS[s.key]}"` : ""}`);
1880
+ const pick = (test) => all.map((s, n) => (test(s) ? row(s, n) : "")).join("");
1881
+ const plain = (g) => (s) => s.group === g && !adv.has(s.key) && !PROVIDER_FIELDS[s.key] && s.key !== "DRIFTNET_LLM_PROVIDER";
1882
+ return `<fieldset class="set-group"><legend>${esc(st.model)}</legend>${pick((s) => s.key === "DRIFTNET_LLM_PROVIDER")}<div id="ai-prov"></div>${pick(plain("model"))}</fieldset>` +
1883
+ `<fieldset class="set-group"><legend>${esc(st.rules)}</legend>${pick(plain("rules"))}</fieldset>` +
1884
+ `<details class="set-adv"><summary>${esc(st.advanced)}</summary><small>${esc(st.advancedHelp)}</small><div id="ai-prov-other">${pick((s) => !!PROVIDER_FIELDS[s.key])}</div>${pick((s) => adv.has(s.key))}</details>`;
1885
+ }
1886
+ /** Move each provider field next to the provider select when that provider uses it, else into Advanced. */
1887
+ function placeAi() {
1888
+ const sel = $("st-body").querySelector('[data-key="DRIFTNET_LLM_PROVIDER"]'), here = $("ai-prov"), there = $("ai-prov-other");
1889
+ if (!sel || !here || !there) return;
1890
+ const rows = [...$("st-body").querySelectorAll("[data-for]")].sort((a, b) => a.dataset.n - b.dataset.n);
1891
+ for (const r of rows) (r.dataset.for.split(" ").includes(sel.value) ? here : there).append(r);
1892
+ }
1893
+ $("st-body").addEventListener("change", (e) => { if (e.target.dataset?.key === "DRIFTNET_LLM_PROVIDER") placeAi(); });
1784
1894
  /** Settings › Backup: download a zip (secrets only with the password typed again) or restore one (applied at the next start). */
1785
1895
  function backupPanel(sv) {
1786
1896
  const st = T().st;
@@ -2163,6 +2273,14 @@
2163
2273
  [/cloudflared is not installed/, () => zh ? "這台電腦還沒安裝 cloudflared。" : "cloudflared isn't installed on this computer."],
2164
2274
  [/set by the environment/, () => zh ? "這個設定由執行環境決定(例如 systemd),要在那裡改。" : "This one is set by the environment driftnet runs in; change it there."],
2165
2275
  [/already a folder called “(.+)” here/, (m) => zh ? `這裡已經有一個叫「${m[1]}」的資料夾了。` : `There's already a folder called “${m[1]}” here.`],
2276
+ [/^model: .*DRIFTNET_LLM_MODEL is required/, () => zh ? "還沒存:這個供應商要填「模型」名稱。" : "Not saved: this provider needs a model name."],
2277
+ [/^model: .*(API_KEY is required|needs an API key|needs a key)/i, () => zh ? "還沒存:這個供應商要填 API 金鑰。" : "Not saved: this provider needs an API key."],
2278
+ [/^model: (.+)/, (m) => zh ? `還沒存:模型設定不完整(${m[1]})。` : `Not saved: the model setup is incomplete (${m[1]}).`],
2279
+ // Why a link was not saved (POST /api/ingest answers 422).
2280
+ [/(\S+) (?:is|resolves to) a private or local address/, (m) => zh ? `沒有收錄:${m[1]} 是內網或本機位址,driftnet 不會去抓。` : `Not saved: ${m[1]} is a private or local address, so driftnet won't fetch it.`],
2281
+ [/(\S+) did not resolve/, (m) => zh ? `沒有收錄:找不到 ${m[1]} 這個網站,請檢查網址。` : `Not saved: ${m[1]} couldn't be found — check the address.`],
2282
+ [/links are not fetched|not a web link/, () => zh ? "沒有收錄:這不是網頁連結,要以 http:// 或 https:// 開頭。" : "Not saved: that isn't a web link — it needs to start with http:// or https://."],
2283
+ [/(\S+) is blocked in your settings/, (m) => zh ? `沒有收錄:${m[1]} 在你的封鎖清單裡(設定 → AI →「不要收錄的網域」)。` : `Not saved: ${m[1]} is on your blocked list (Settings → AI → Never catalogue these domains).`],
2166
2284
  [/too many wrong passwords/, () => zh ? "密碼錯太多次,請 15 分鐘後再試。" : "Too many wrong passwords — try again in 15 minutes."],
2167
2285
  ];
2168
2286
  for (const [re, f] of rules) { const m = re.exec(msg); if (m) return f(m); }
@@ -2186,7 +2304,7 @@
2186
2304
  function syncFocusHash() {
2187
2305
  const want = mapShown() && mapFocus ? `#focus=${encodeURIComponent(mapFocus)}` : "";
2188
2306
  if (want === location.hash || (!want && !location.hash.startsWith("#focus="))) return;
2189
- history.replaceState(null, "", location.pathname + location.search + want);
2307
+ history.replaceState(history.state, "", location.pathname + location.search + want);
2190
2308
  }
2191
2309
  /** Focus the map on a folder (null = back to everything), remembering where each view was. */
2192
2310
  async function setMapFocus(id) {
@@ -2236,7 +2354,8 @@
2236
2354
  : `<button type="button" data-map="focus" data-id="${esc(id)}">${esc(catLabel(id))}</button>`)).join("") + `</nav>`;
2237
2355
  })() : "";
2238
2356
  const allOpen = mapOpen.size > 0 || !!state.q;
2239
- const tip = store.get("driftnet-map-tip") ? "" : `<p class="hint map-tip"><span>${esc(t.mapHint)} ${esc(t.mapHintFocus)}</span><button class="link-btn" type="button" data-map="tip">${esc(t.gotIt)}</button></p>`;
2357
+ const kb = matchMedia("(hover: hover)").matches; // a touch screen gets no "press z"
2358
+ const tip = store.get("driftnet-map-tip") ? "" : `<p class="hint map-tip"><span>${esc(t.mapHint)} ${esc(kb ? t.mapHintFocus : t.mapHintFocusTouch)}</span><button class="link-btn" type="button" data-map="tip">${esc(t.gotIt)}</button></p>`;
2240
2359
  $("list").innerHTML = `<div class="map-bar">
2241
2360
  <button class="btn" type="button" data-map="${allOpen ? "collapse" : "expand"}">${ic(allOpen ? "collapse" : "expand")} ${esc(allOpen ? t.collapseAll : t.expandAll)}</button>
2242
2361
  <button class="btn" type="button" data-map="new">${ic("plus")} ${esc(t.newFolder)}</button>
@@ -2269,18 +2388,19 @@
2269
2388
  wrap.scrollTop = root.offsetTop * mapZoom - wrap.clientHeight / 2;
2270
2389
  wrap.scrollLeft = (root.offsetLeft + root.offsetWidth / 2) * mapZoom - wrap.clientWidth / 2;
2271
2390
  }
2272
- function fitWidth() {
2391
+ /** floor: never smaller than this; persist: false for split view, which must not change the full map's saved zoom. */
2392
+ function fitWidth(floor = 0.6, persist = true) {
2273
2393
  const wrap = $("map-wrap"), c = $("map-canvas");
2274
2394
  if (!wrap || !c) return;
2275
- mapZoomTo(Math.max(0.6, Math.min(1, (wrap.clientWidth - 8) / c.offsetWidth)));
2395
+ mapZoomTo(Math.max(floor, Math.min(1, (wrap.clientWidth - 8) / c.offsetWidth)), persist);
2276
2396
  const root = c.querySelector('.mnode[data-key="root"]');
2277
2397
  if (root) wrap.scrollTop = root.offsetTop * mapZoom - wrap.clientHeight / 2;
2278
2398
  }
2279
2399
  function fitMap() {
2280
2400
  const wrap = $("map-wrap"), c = $("map-canvas");
2281
2401
  if (!wrap || !c) return;
2282
- // Fit, but never so small the text can't be read (phones stop at 0.6, desktops at 0.45); then start at the root.
2283
- const floor = isDrawer() ? 0.6 : 0.45;
2402
+ // Fit: on a phone really fit (an overview to tap into), on a desktop stop at 0.45 so text stays readable; then start at the root.
2403
+ const floor = isDrawer() ? MIN_ZOOM_PHONE : 0.45;
2284
2404
  mapZoomTo(Math.max(floor, Math.min(1.3, (wrap.clientWidth - 8) / c.offsetWidth, (wrap.clientHeight - 8) / c.offsetHeight)));
2285
2405
  centreOnRoot();
2286
2406
  }
@@ -2289,7 +2409,14 @@
2289
2409
  const wrap = $("map-wrap");
2290
2410
  if (wrap) wrap.style.height = `${Math.max(320, innerHeight - wrap.getBoundingClientRect().top - 12)}px`;
2291
2411
  }
2292
- addEventListener("resize", () => { if (mapShown()) sizeMap(); if (splitOn()) sizeSplit(); });
2412
+ let lastW = innerWidth, fitTimer = 0;
2413
+ addEventListener("resize", () => {
2414
+ if (mapShown()) sizeMap();
2415
+ if (splitOn()) sizeSplit();
2416
+ // Split view: the pane changed width, so fit the map to it again (a height-only change, like a phone's toolbar, doesn't count).
2417
+ if (splitOn() && innerWidth !== lastW) { clearTimeout(fitTimer); fitTimer = setTimeout(() => { if (splitOn()) fitWidth(0.3, false); }, 150); }
2418
+ lastW = innerWidth;
2419
+ });
2293
2420
 
2294
2421
  /** Root → folders → sub-folders and cards, laid out left to right like XMind. */
2295
2422
  function drawMap() {
@@ -2446,12 +2573,13 @@
2446
2573
  if (first && q && wrap) wrap.scrollTo({ left: first.offsetLeft * mapZoom - wrap.clientWidth / 2, top: first.offsetTop * mapZoom - wrap.clientHeight / 2 });
2447
2574
  }
2448
2575
 
2449
- function mapZoomTo(z) {
2576
+ const MIN_ZOOM_PHONE = 0.15;
2577
+ function mapZoomTo(z, persist = true) {
2450
2578
  const wrap = $("map-wrap");
2451
2579
  // Zoom around the centre of what is on screen, not the top-left corner.
2452
2580
  const cx = wrap ? (wrap.scrollLeft + wrap.clientWidth / 2) / mapZoom : 0, cy = wrap ? (wrap.scrollTop + wrap.clientHeight / 2) / mapZoom : 0;
2453
- mapZoom = Math.min(2, Math.max(0.3, Math.round(z * 20) / 20));
2454
- store.set("driftnet-map-zoom", String(mapZoom));
2581
+ mapZoom = Math.min(2, Math.max(isDrawer() ? MIN_ZOOM_PHONE : 0.3, Math.round(z * 100) / 100));
2582
+ if (persist) store.set("driftnet-map-zoom", String(mapZoom));
2455
2583
  drawMap();
2456
2584
  if (wrap) { wrap.scrollLeft = cx * mapZoom - wrap.clientWidth / 2; wrap.scrollTop = cy * mapZoom - wrap.clientHeight / 2; }
2457
2585
  }
@@ -2486,7 +2614,8 @@
2486
2614
  });
2487
2615
  $("list").addEventListener("dblclick", (e) => {
2488
2616
  const node = e.target.closest(".mnode.folder");
2489
- if (!node) return;
2617
+ // The tap that drops a held card can land where the hold was and count as a double-tap: that is not "focus".
2618
+ if (!node || justDropped) return;
2490
2619
  clearTimeout(folderTap);
2491
2620
  setMapFocus(node.dataset.key.slice(2));
2492
2621
  });
@@ -2730,9 +2859,10 @@
2730
2859
  if (!i) return void (mdlDlg.open && mdlDlg.close());
2731
2860
  const t = T(), s = i.summary, admin = role === "admin", inTrash = state.view === "trash";
2732
2861
  const url = safeUrl(s?.primaryUrl || i.url), name = s?.name ?? i.title;
2733
- const ids = mdIds(), at = ids.indexOf(i.id);
2734
- $("md-pos").textContent = at >= 0 ? t.mdPos(at + 1, ids.length) : "";
2735
- for (const [id, label, off] of [["md-prev", t.mdPrev, at <= 0], ["md-next", t.mdNext, at < 0 || at >= ids.length - 1]]) {
2862
+ // "3 of 120": the whole list, not just the pages loaded so far (Next loads the next page).
2863
+ const ids = mdIds(), at = ids.indexOf(i.id), total = Math.max(ids.length, pageTotal);
2864
+ $("md-pos").textContent = at >= 0 ? t.mdPos(at + 1, total) : "";
2865
+ for (const [id, label, off] of [["md-prev", t.mdPrev, at <= 0], ["md-next", t.mdNext, at < 0 || at >= total - 1]]) {
2736
2866
  const b = $(id); b.innerHTML = ic("chev"); b.setAttribute("aria-label", label); b.title = label; b.hidden = at < 0; b.disabled = off;
2737
2867
  }
2738
2868
  $("md-close").setAttribute("aria-label", t.close); $("md-close").title = t.close;
@@ -2762,13 +2892,13 @@
2762
2892
  <div class="md-fine">${i.shareCount ? `<span>${esc(t.shared(i.shareCount))}</span>` : ""}<span>${esc(i.createdAt.slice(0, 10))}</span>${i.enrichedBy ? `<span>${esc(t.enrichedBy(i.enrichedBy.replace(/^agent:/, "")))}</span>` : ""}</div>`;
2763
2893
  paintRelated(i.id);
2764
2894
  const busy = refreshing.has(i.id);
2765
- const btn = (act, icon, label, extra = "") => `<button class="btn ${extra}" type="button" data-md="${act}">${ic(icon)} ${esc(label)}</button>`;
2895
+ const btn = (act, icon, label, extra = "", title = "") => `<button class="btn ${extra}" type="button" data-md="${act}"${title ? ` title="${esc(title)}"` : ""}>${ic(icon)} ${esc(label)}</button>`;
2766
2896
  $("md-actions").innerHTML = `<a class="btn primary" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${ic("link")} ${esc(t.openLink)}</a>` +
2767
2897
  (admin ? (inTrash ? btn("restore", "undo", t.restore) + btn("purge", "trash", t.purge, "danger")
2768
2898
  : btn("favorite", "star", i.favorite ? t.unfavorite : t.favorite, i.favorite ? "on" : "") + btn("move", "move", t.moveTo) +
2769
- `<button class="btn ${busy ? "spin" : ""}" type="button" data-md="refresh" ${busy ? "disabled" : ""}>${ic("refresh")} ${esc(t.refresh)}</button>` +
2770
- btn("health", "refresh", t.checkLink) + btn("note", "note", i.note ? t.editNote : t.addNote) + (s ? btn("tags", "note", t.tagsEdit) : "") + `<span class="spacer"></span>` + btn("trash", "trash", t.remove, "danger")) : "") +
2771
- btn("history", "undo", t.histBtn, histFor === i.id ? "on" : "") +
2899
+ `<button class="btn ${busy ? "spin" : ""}" type="button" data-md="refresh" title="${esc(t.refresh)}" ${busy ? "disabled" : ""}>${ic("refresh")} ${esc(t.refreshShort)}</button>` +
2900
+ btn("health", "check", t.checkLink) + btn("note", "note", i.note ? t.editNote : t.addNote) + (s ? btn("tags", "tag", t.tagsEdit) : "") + `<span class="spacer"></span>` + btn("trash", "trash", t.remove, "danger")) : "") +
2901
+ btn("history", "clock", t.histBtn, histFor === i.id ? "on" : "", t.histTitle) +
2772
2902
  (modalFrom === "map" ? btn("list", "list", t.showInList) : "");
2773
2903
  if (histFor === i.id) paintHistory(i);
2774
2904
  }
@@ -2831,19 +2961,24 @@
2831
2961
  if (!wasOpen) mdlDlg.showModal();
2832
2962
  $("md-scroll").scrollTop = 0;
2833
2963
  mdlDlg.style.transform = "";
2834
- history.replaceState(null, "", `${location.pathname}${location.search}#item-${id}`);
2964
+ // Its own history entry, so Back (a phone's above all) closes the card instead of leaving driftnet.
2965
+ if (!history.state?.dnLayer) history.pushState({ dnLayer: 1 }, "", location.href);
2966
+ history.replaceState(history.state, "", `${location.pathname}${location.search}#item-${id}`);
2835
2967
  }
2836
2968
  /** Step to the previous / next card in the list the modal came from. */
2837
- function stepModal(d) {
2838
- const ids = mdIds(), at = ids.indexOf(modalId), to = ids[at + d];
2839
- if (at < 0 || to == null) return;
2969
+ async function stepModal(d) {
2970
+ let ids = mdIds(), at = ids.indexOf(modalId);
2971
+ if (at < 0) return;
2972
+ if (ids[at + d] == null && d > 0 && items.length < pageTotal) { await loadMore(); ids = mdIds(); at = ids.indexOf(modalId); }
2973
+ const to = ids[at + d];
2974
+ if (to == null || !mdlDlg.open) return;
2840
2975
  openModal(to, modalFrom);
2841
2976
  }
2842
2977
  mdlDlg.addEventListener("close", () => {
2843
2978
  if (mdlDlg.open) return; // reopened (a link, a hash) before this queued event ran
2844
2979
  const id = modalId, from = modalFrom;
2845
2980
  // Only this card's own hash: a late close event must not wipe the link of a card opened since.
2846
- if (!keepHash && location.hash === `#item-${id}`) history.replaceState(null, "", location.pathname + location.search);
2981
+ if (!keepHash && location.hash === `#item-${id}`) history.replaceState(history.state, "", location.pathname + location.search);
2847
2982
  keepHash = false;
2848
2983
  mdlDlg.style.transform = "";
2849
2984
  // Focus goes back to the card you ended on (the one you opened, or the last one you stepped to).
@@ -2907,7 +3042,7 @@
2907
3042
  if (act1 === "list") {
2908
3043
  keepHash = true; mdlDlg.close();
2909
3044
  Object.assign(state, { view: "all", category: "", kind: "" });
2910
- history.replaceState(null, "", `#item-${id}`);
3045
+ history.replaceState(history.state, "", `#item-${id}`);
2911
3046
  return load();
2912
3047
  }
2913
3048
  if (act1 === "history") {
@@ -3005,16 +3140,18 @@
3005
3140
  if (!item || !to) return;
3006
3141
  if (item.category === to) return toast(T().alreadyThere);
3007
3142
  const from = item.category;
3008
- if (!(await mapWrite(`/api/items/${id}/move`, "POST", { folder: to }))) return;
3143
+ const r = await mapWrite("/api/items/bulk", "POST", { action: "move", ids: [id], folder: to });
3144
+ if (!r) return;
3009
3145
  item.category = to;
3010
3146
  // Filing many cards in a row: the target stays as it was (no sudden expansion); its count pulses instead.
3011
3147
  drawMap();
3012
3148
  pulse(`f:${to}`);
3013
3149
  bumpUse(to);
3014
3150
  toast(T().moved(nameOf(item), folderPath(to)), async () => {
3015
- if (await mapWrite(`/api/items/${id}/move`, "POST", { folder: from })) { item.category = from; drawMap(); refreshFolders(); }
3151
+ if (await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo })) { item.category = from; drawMap(); refreshFolders(); refreshCounts(); }
3016
3152
  });
3017
3153
  refreshFolders();
3154
+ refreshCounts();
3018
3155
  }
3019
3156
  async function mapMoveFolder(id, to) {
3020
3157
  if (id === to || (to && subtreeOf(id).has(to))) return;
@@ -3081,16 +3218,27 @@
3081
3218
  const withKey = (u) => (a?.private || a?.readKey ? `${u}?key=${key}` : u);
3082
3219
  // With an admin password set, agent cards offer their own token instead of the password.
3083
3220
  const canMint = !!a?.passwordSet;
3221
+ // No password on a page opened on this computer: nothing to authorise, so the commands carry no header.
3222
+ const open = !!a && !a.passwordSet && !!uiInfo.local;
3084
3223
  const secrets = {};
3085
3224
  const card = (id, title, desc, code, agent) => `<div class="conn" id="cc-${id}"><div class="conn-head"><h4>${esc(title)}</h4>
3086
3225
  <button class="btn copy" type="button" data-copy="#cx-${id}">${esc(st.copy)}</button></div><p>${esc(desc)}</p><pre id="cx-${id}">${esc(code)}</pre>
3087
3226
  ${agent && canMint ? `<div class="conn-mint"><input id="cn-${id}" class="conn-name" maxlength="60" value="${esc(agent)}" autocomplete="off" aria-label="${esc(st.tokCardName)}"><button class="btn" type="button" data-mint="${id}">${esc(st.tokCardCreate)}</button></div>` : ""}</div>`;
3088
3227
  const cards = [
3228
+ card("init", zh ? "推薦:一次接好你的 AI 工具" : "Recommended: connect your AI apps in one go",
3229
+ isLocalUrl
3230
+ ? (zh ? "在這台電腦的終端機執行。會一次幫 Claude Code、Claude Desktop、Cursor、Windsurf、Codex 接上 driftnet;想先看會改什麼,加 --dry-run。"
3231
+ : "Run in a terminal on this computer. Connects Claude Code, Claude Desktop, Cursor, Windsurf and Codex in one go; add --dry-run to see what it would change first.")
3232
+ : (zh ? "在要連線的那台電腦執行。會一次幫 Claude Code、Claude Desktop、Cursor、Windsurf、Codex 接上這個 driftnet。" : "Run on the computer you want to connect. Connects Claude Code, Claude Desktop, Cursor, Windsurf and Codex to this driftnet in one go."),
3233
+ isLocalUrl ? "npx driftnet init" : `npx driftnet init --remote ${base} --token ${pw}`, isLocalUrl ? "" : "init"),
3089
3234
  card("ccp", zh ? "Claude Code:裝插件" : "Claude Code: the plugin", zh ? "在 Claude Code 裡輸入。會裝好 skill 和本機 MCP。" : "Type it inside Claude Code. Brings the skill and a local MCP server.",
3090
3235
  `/plugin install driftnet --marketplace KevinChu1110/driftnet`),
3091
- card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet",
3092
- zh ? "在終端機執行。先 export DRIFTNET_TOKEN=你的管理密碼,指令會自動帶入。" : "Run in a terminal. Export DRIFTNET_TOKEN=<your admin password> first; the command reads it.",
3093
- `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"`, "Claude Code"),
3236
+ open
3237
+ ? card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet", zh ? "在終端機執行。" : "Run in a terminal.",
3238
+ `claude mcp add --transport http driftnet ${base}/mcp`)
3239
+ : card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet",
3240
+ zh ? "在終端機執行。先 export DRIFTNET_TOKEN=你的管理密碼,指令會自動帶入。" : "Run in a terminal. Export DRIFTNET_TOKEN=<your admin password> first; the command reads it.",
3241
+ `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"`, "Claude Code"),
3094
3242
  card("claude", zh ? "Claude 網頁版/桌面版(自訂 connector)" : "Claude.ai / Claude Desktop (custom connector)",
3095
3243
  zh ? "設定 → Connectors → 新增自訂 connector,貼上這個網址。用分享碼連線,只能搜尋和查看,不能改。" : "Settings → Connectors → Add custom connector, paste this URL. The share key makes it read-only: search and look, no changes.",
3096
3244
  withKey(`${base}/mcp`)),
@@ -3103,11 +3251,15 @@
3103
3251
  : `Read ${withKey(`${base}/llms.txt`)} — it's my catalogue of AI tools. Find me one for: (your task).`),
3104
3252
  card("feed", st.feed, zh ? "RSS/Atom 訂閱源:最新 50 張卡片。給 RSS 閱讀器或 n8n、Zapier 用;加上 ?folder=資料夾代號 可只看一個資料夾。" : "RSS / Atom feed of the newest 50 cards, for feed readers, n8n or Zapier. Add ?folder=<folder-id> for one folder.",
3105
3253
  withKey(`${base}/feed.xml`)),
3106
- card("agents", "Hermes / OpenClaw / pi", zh ? "這些 agent 的 MCP 設定。把裡面的 <你的管理密碼> 換成真的密碼;有了它,agent 可以收錄、投票、幫忙讀佇列裡的連結。" : "MCP settings for these agents. Replace <your-admin-password> with the real one; with it they can save, vote and work the queue.",
3107
- JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2), "Hermes"),
3254
+ open
3255
+ ? card("agents", "Hermes / OpenClaw / pi", zh ? "這些 agent 的 MCP 設定。agent 可以收錄、投票、幫忙讀佇列裡的連結。" : "MCP settings for these agents. With it they can save, vote and work the queue.",
3256
+ JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp` } } }, null, 2))
3257
+ : card("agents", "Hermes / OpenClaw / pi", zh ? "這些 agent 的 MCP 設定。把裡面的 <你的管理密碼> 換成真的密碼;有了它,agent 可以收錄、投票、幫忙讀佇列裡的連結。" : "MCP settings for these agents. Replace <your-admin-password> with the real one; with it they can save, vote and work the queue.",
3258
+ JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2), "Hermes"),
3108
3259
  ].join("");
3109
3260
  // What each agent card shows once it has its own token.
3110
3261
  snippets = {
3262
+ init: (tok) => `npx driftnet init --remote ${base} --token ${tok}`,
3111
3263
  cc: (tok) => `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer ${tok}"`,
3112
3264
  agents: (tok) => JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${tok}` } } } }, null, 2),
3113
3265
  };
@@ -3270,7 +3422,7 @@
3270
3422
  function jumpTo(id) {
3271
3423
  Object.assign(state, { view: "all", category: "", kind: "", q: "" });
3272
3424
  $("q").value = "";
3273
- history.replaceState(null, "", `#item-${id}`);
3425
+ history.replaceState(history.state, "", `#item-${id}`);
3274
3426
  load();
3275
3427
  }
3276
3428
 
@@ -3286,24 +3438,61 @@
3286
3438
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
3287
3439
  }
3288
3440
 
3289
- /** The first link, straight from the page (the empty list offers this). */
3290
- async function addLink(e) {
3291
- e.preventDefault();
3292
- const url = $("add-url").value.trim();
3293
- if (!/^https?:\/\//.test(url)) return toast(T().addPlaceholder);
3294
- const b = e.submitter; if (b) b.disabled = true;
3441
+ /**
3442
+ * Save one link from the page (the + dialog, the empty list, a link typed into search). The server adds https://
3443
+ * to a bare domain and says why it refused one; `say` shows that reason (a toast unless a dialog has its own line).
3444
+ * True only when a card was really saved.
3445
+ */
3446
+ async function addUrl(url, say = toast) {
3447
+ url = url.trim();
3448
+ if (!url) return false;
3295
3449
  const token = store.get("driftnet-token");
3296
3450
  const res = await fetch("/api/ingest", { method: "POST", body: JSON.stringify({ url }),
3297
3451
  headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) } }).catch(() => null);
3298
- if (b) b.disabled = false;
3299
- if (res?.status === 401) return needAdmin();
3300
- if (!res?.ok) return toast(T().failed);
3301
- toast(T().added);
3302
- load();
3452
+ if (res?.status === 401) { needAdmin(); return false; }
3453
+ const data = await res?.json().catch(() => null);
3454
+ if (!res?.ok) { say(friendlyError(data?.error) ?? T().failed); return false; }
3455
+ const got = Array.isArray(data) ? data[0] : null;
3456
+ if (!got?.item?.id) { say(T().addNothing); return false; }
3457
+ toast(got.cached ? T().addedAlready : T().added);
3458
+ $("q").value = ""; state.q = "";
3459
+ jumpTo(got.item.id);
3460
+ return true;
3461
+ }
3462
+ async function addLink(e) {
3463
+ e.preventDefault();
3464
+ const b = e.submitter; if (b) b.disabled = true;
3465
+ await addUrl($("add-url").value);
3466
+ if (b?.isConnected) b.disabled = false;
3303
3467
  }
3468
+ function openAdd(prefill = "") {
3469
+ if (role !== "admin") return needAdmin();
3470
+ if (document.querySelector("dialog[open]")) return;
3471
+ const t = T();
3472
+ $("ad-title").textContent = t.addTitle; $("ad-help").textContent = t.addHelp;
3473
+ $("ad-url").placeholder = t.addPlaceholder; $("ad-error").textContent = "";
3474
+ $("ad-cancel").textContent = t.cancel; $("ad-ok").textContent = t.addLink;
3475
+ $("ad-url").value = prefill;
3476
+ $("add-dlg").showModal();
3477
+ $("ad-url").focus();
3478
+ }
3479
+ $("add-btn").onclick = () => openAdd();
3480
+ $("settings-btn").onclick = () => openSettings();
3481
+ $("ad-cancel").onclick = () => $("add-dlg").close();
3482
+ $("add-dlg").addEventListener("click", (e) => { if (e.target === $("add-dlg")) $("add-dlg").close(); });
3483
+ $("add-dlg-form").onsubmit = async (e) => {
3484
+ e.preventDefault();
3485
+ $("ad-ok").disabled = true; $("ad-error").textContent = "";
3486
+ const ok = await addUrl($("ad-url").value, (why) => { $("ad-error").textContent = why; });
3487
+ $("ad-ok").disabled = false;
3488
+ if (ok) $("add-dlg").close();
3489
+ };
3490
+ /** Search text that is a link (a URL, or a bare domain like example.com): offer to save it instead. */
3491
+ const linkLike = (q) => /^(https?:\/\/\S+|[\w-]+(\.[\w-]+)*\.[a-z]{2,}(\/\S*)?)$/i.test(q.trim());
3304
3492
 
3305
3493
  async function render() {
3306
3494
  updateCrumb();
3495
+ store.set("driftnet-view", JSON.stringify({ view: state.view, category: state.category }));
3307
3496
  const viewKey = [state.view, state.category, state.kind, state.q].join("|");
3308
3497
  if (viewKey !== lastViewKey) { lastViewKey = viewKey; selected.clear(); selAnchor = null; }
3309
3498
  document.body.classList.toggle("map-view", mapShown());
@@ -3324,6 +3513,7 @@
3324
3513
  await renderMap(); // the map first: the selection check then knows both sides
3325
3514
  await inPane($("split-list"), renderCards);
3326
3515
  sizeSplit();
3516
+ fitWidth(0.3, false); // the map pane is narrow: show its whole width
3327
3517
  syncSelection();
3328
3518
  };
3329
3519
  return (splitQueue = splitQueue.catch(() => {}).then(run));
@@ -3485,13 +3675,23 @@
3485
3675
  pageBusy = false;
3486
3676
  pageObserver?.disconnect();
3487
3677
  const t = T();
3488
- const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : state.view === "inbox" ? t.emptyInbox : state.view === "review" ? t.emptyReview : t.empty;
3678
+ const fresh = state.view === "all" && !state.q && !state.category && !state.kind && role === "admin";
3679
+ const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : state.view === "inbox" ? t.emptyInbox : state.view === "review" ? t.emptyReview : fresh ? t.emptyStart : t.empty;
3680
+ // A link typed into search: offer to save it (right away for a full URL, otherwise only when nothing matched).
3681
+ const addQ = role === "admin" && state.q && linkLike(state.q) && (!items.length || /^(https?:\/\/|www\.)/i.test(state.q))
3682
+ ? `<div class="add-q"><button class="btn primary" type="button" data-add-q>${ic("plus")} ${esc(t.addThis(state.q))}</button></div>` : "";
3683
+ const scoped = state.view !== "all" || state.category || state.kind;
3489
3684
  $("list").innerHTML = items.length
3490
- ? (state.view === "trash" ? `<div class="trash-bar"><button class="btn danger" type="button" id="trash-empty">${ic("trash")} ${esc(t.emptyTrashBtn)}</button></div>` : "") + `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : state.view === "inbox" ? t.hintInbox : state.view === "review" ? t.hintReview : t.hint)}</p>` + items.map(card).join("") + moreHtml()
3491
- : `<div class="empty first"><span>${esc(empty)}</span>${state.view === "all" && !state.q && !state.category && role === "admin"
3492
- ? `<form class="add" id="add-form"><input id="add-url" type="url" inputmode="url" placeholder="${esc(t.addPlaceholder)}" aria-label="${esc(t.addPlaceholder)}">
3685
+ ? addQ + (state.view === "trash" ? `<div class="trash-bar"><button class="btn danger" type="button" id="trash-empty">${ic("trash")} ${esc(t.emptyTrashBtn)}</button></div>` : "") + `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : state.view === "inbox" ? t.hintInbox : state.view === "review" ? t.hintReview : t.hint)}</p>` + items.map(card).join("") + moreHtml()
3686
+ : state.q
3687
+ // Searching found nothing: say so (not "Inbox zero"), and offer the whole catalogue when only part of it was searched.
3688
+ ? `<div class="empty nomatch"><span>${esc(t.noMatch(state.q, viewName()))}</span>${scoped ? `<button class="btn" type="button" data-search-all>${esc(t.searchAll)}</button>` : ""}${addQ}</div>`
3689
+ : `<div class="empty first"><span>${esc(empty)}</span>${fresh
3690
+ ? `<form class="add" id="add-form"><input id="add-url" type="text" inputmode="url" autocapitalize="off" spellcheck="false" placeholder="${esc(t.addPlaceholder)}" aria-label="${esc(t.addPlaceholder)}">
3493
3691
  <button class="btn primary" type="submit">${ic("plus")} ${esc(t.addLink)}</button></form>
3494
3692
  <button class="btn" type="button" data-connect-empty>${ic("plug")} ${esc(t.st.connect)}</button>${templateChooser(t)}` : ""}</div>`;
3693
+ $("list").querySelector("[data-add-q]")?.addEventListener("click", (e) => { const b = e.currentTarget; b.disabled = true; addUrl(state.q).then(() => { if (b.isConnected) b.disabled = false; }); });
3694
+ $("list").querySelector("[data-search-all]")?.addEventListener("click", () => { Object.assign(state, { view: "all", category: "", kind: "" }); load(); });
3495
3695
  watchMore();
3496
3696
  if (keep) scrollTo({ top: y });
3497
3697
  $("add-form")?.addEventListener("submit", addLink);
@@ -3969,12 +4169,13 @@
3969
4169
  applyPrefs();
3970
4170
  }
3971
4171
  const commands = [
4172
+ { id: "add", label: { en: "Add a link…", "zh-TW": "收錄連結…" }, keys: ["a"], help: "kAdd", when: () => role === "admin", run: () => openAdd() },
3972
4173
  { id: "view-list", label: { en: "Show the card list", "zh-TW": "顯示卡片列表" }, keys: ["g", "a"], help: "kAll", run: () => showLayout("list") },
3973
4174
  { id: "view-map", label: { en: "Show the mind map", "zh-TW": "顯示樹狀圖" }, keys: ["g", "m"], help: "kMap", run: () => showLayout("map") },
3974
4175
  { id: "view-split", label: { en: "Show cards and mind map side by side", "zh-TW": "並排顯示卡片與樹狀圖" }, when: () => wideQuery.matches, run: () => showLayout("split") },
3975
4176
  { id: "move", label: { en: "Move the focused card…", "zh-TW": "移動目前選取的卡片…" }, when: () => role === "admin" && !!pal.focused, run: () => openMovePicker(pal.focused) },
3976
4177
  { id: "new-folder", label: { en: "New folder", "zh-TW": "新增資料夾" }, when: () => role === "admin", run: () => openFolderDialog(null, null) },
3977
- { id: "export-md", label: { en: "Download a backup (Markdown)", "zh-TW": "下載備份(Markdown)" }, run: () => download("markdown") },
4178
+ { id: "export-md", label: { en: "Export as Markdown", "zh-TW": "匯出成 Markdown" }, run: () => download("markdown") },
3978
4179
  { id: "export-vault", label: { en: "Download for Obsidian / Notion", "zh-TW": "下載給 Obsidian/Notion" }, run: () => download("vault") },
3979
4180
  { id: "settings", label: { en: "Settings", "zh-TW": "設定" }, run: () => openSettings() },
3980
4181
  { id: "dark", label: { en: "Toggle dark mode", "zh-TW": "切換深色模式" }, run: toggleDark },
@@ -4081,6 +4282,9 @@
4081
4282
  `<h4>${esc(t.keysMap)}</h4>` + row(["↓", "↑"], t.kTreeNav) + row(["→"], t.kTreeOpen) + row(["←"], t.kTreeClose) + row(["Home", "End"], t.kTreeEnds) +
4082
4283
  row([t.kTreeType], t.kTreeTypeText) + row(["z"], t.kFocus) + row(["Esc", "Backspace"], t.kFocusUp);
4083
4284
  $("keys-dlg").showModal();
4285
+ // Start at the top: focus would otherwise land on Close, at the bottom of a long list.
4286
+ $("ky-title").focus({ preventScroll: true });
4287
+ $("keys-dlg").scrollTop = 0;
4084
4288
  }
4085
4289
  $("ky-close").onclick = () => $("keys-dlg").close();
4086
4290
  $("keys-dlg").addEventListener("click", (e) => { if (e.target === $("keys-dlg")) $("keys-dlg").close(); });
@@ -4130,7 +4334,7 @@
4130
4334
  $("plan-body").addEventListener("change", syncPlan);
4131
4335
  async function openPlan() {
4132
4336
  const t = T();
4133
- if (!summaries) return toast(t.planNoModel);
4337
+ if (!summaries) return toast(t.planNoModel, () => openSettings(false, "ai"), t.st.openSettings);
4134
4338
  plan = null;
4135
4339
  $("pl-title").textContent = t.planTitle;
4136
4340
  $("pl-intro").textContent = t.planIntro;
@@ -4161,12 +4365,13 @@
4161
4365
 
4162
4366
  /** The newest undoable action, so z (or ⌘/Ctrl+Z) can undo it from the keyboard. */
4163
4367
  let lastUndo = null;
4164
- function toast(text, undo) {
4368
+ /** label: the button does something else than Undo (z then leaves it alone). */
4369
+ function toast(text, undo, label) {
4165
4370
  $("toast-text").textContent = text;
4166
4371
  const u = $("toast-undo");
4167
4372
  u.hidden = !undo;
4168
- u.textContent = T().undo;
4169
- lastUndo = undo ?? null;
4373
+ u.textContent = label ?? T().undo;
4374
+ lastUndo = label ? null : undo ?? null;
4170
4375
  u.onclick = async () => { clearTimeout(toastTimer); $("toast").classList.remove("show"); lastUndo = null; await undo?.(); };
4171
4376
  $("toast").classList.add("show");
4172
4377
  toastMs = Math.min(9000, 4500 + text.length * 45);
@@ -4201,12 +4406,25 @@
4201
4406
  // Inbox: 1–3 pick the focused card's suggestion chips (before the global "file into top-9 folders").
4202
4407
  if (state.view === "inbox" && /^[1-3]$/.test(k) && role === "admin" && focusedId() && !selected.size) {
4203
4408
  const chip = document.querySelectorAll(`#item-${focusedId()} [data-chip]`)[Number(k) - 1];
4204
- if (chip) { e.preventDefault(); inboxFile(focusedId(), chip.dataset.chip); return; }
4409
+ e.preventDefault();
4410
+ // No such suggestion: say so rather than quietly filing into a most-used folder.
4411
+ if (chip) inboxFile(focusedId(), chip.dataset.chip); else toast(T().noSuggestion);
4412
+ return;
4205
4413
  }
4206
4414
  if (/^[1-9]$/.test(k) && role === "admin" && !document.activeElement?.isContentEditable && quickMove(Number(k))) { e.preventDefault(); return; }
4207
4415
  if (k === "x" && role === "admin" && !document.activeElement?.isContentEditable && focusedId() && state.view !== "map") { e.preventDefault(); toggleSelect(focusedId()); return; }
4208
4416
  const chord = commands.find((c) => c.keys?.length === 2 && c.keys[0] === prev && c.keys[1] === k);
4209
4417
  if (chord) { chord.run(); return; }
4418
+ if (k === "a" && role === "admin" && prev !== "g") { e.preventDefault(); openAdd(); return; }
4419
+ // Cards selected: f, m and # act on all of them, not just the focused one.
4420
+ if (selected.size && role === "admin" && ["f", "#", "Delete", "m"].includes(k)) {
4421
+ e.preventDefault();
4422
+ const ids = [...selected];
4423
+ if (k === "m") openMovePickerFor(ids);
4424
+ else if (k === "f") bulkApply(ids.every((id) => find(id)?.favorite) ? "unfavorite" : "favorite", ids);
4425
+ else bulkApply(state.view === "trash" ? "restore" : "trash", ids);
4426
+ return;
4427
+ }
4210
4428
  const cards = [...$("list").querySelectorAll(".swipe .card")];
4211
4429
  if (!cards.length) return;
4212
4430
  const cur = document.activeElement?.closest?.(".card");
@@ -4236,6 +4454,13 @@
4236
4454
  };
4237
4455
  let timer;
4238
4456
  if (location.hash.startsWith("#focus=")) { mapFocus = focusFromHash(); state.view = "map"; }
4457
+ // A reload comes back to the view (and folder) you were on; a link to a card or a map folder decides for itself.
4458
+ else if (!location.hash) {
4459
+ try {
4460
+ const v = JSON.parse(store.get("driftnet-view") ?? "null");
4461
+ if (["all", "favorites", "inbox", "review", "map", "notes", "trash"].includes(v?.view)) Object.assign(state, { view: v.view, category: typeof v.category === "string" ? v.category : "" });
4462
+ } catch {}
4463
+ }
4239
4464
  $("q").oninput = (e) => { clearTimeout(timer); timer = setTimeout(() => { state.q = e.target.value.trim(); render(); }, 200); };
4240
4465
  // A scanned pairing link (#pair=<code>): take the code out of the address bar at once, swap it for this device's token.
4241
4466
  async function claimPairing() {