driftnet 0.10.2 → 1.0.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; }
@@ -299,7 +310,13 @@
299
310
  .tabs button[aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
300
311
  #st-body section[data-tab] { display: none; }
301
312
  #st-body[data-tab="general"] section[data-tab="general"], #st-body[data-tab="access"] section[data-tab="access"],
302
- #st-body[data-tab="ai"] section[data-tab="ai"] { display: block; }
313
+ #st-body[data-tab="ai"] section[data-tab="ai"], #st-body[data-tab="chats"] section[data-tab="chats"] { display: block; }
314
+ .chat-st { font-size: 13px; margin: 0 0 8px; display: flex; gap: 8px; align-items: baseline; overflow-wrap: anywhere; }
315
+ .chat-st::before { content: ""; flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); transform: translateY(-1px); }
316
+ .chat-st[data-state="connected"]::before, .chat-st[data-state="webhook"]::before { background: var(--ok); }
317
+ .chat-st[data-state="error"] { color: var(--danger); } .chat-st[data-state="error"]::before { background: var(--danger); }
318
+ .chat-st[data-state="starting"]::before { background: var(--accent); }
319
+ .chat-help { display: block; color: var(--muted); margin: 0 0 8px; } .chat-help a { color: var(--accent); }
303
320
  .set-row { overflow-wrap: anywhere; }
304
321
  #st-body:not(.show-env) .envname { display: none; }
305
322
  .tabs { background: var(--bg); box-shadow: 0 -8px 0 var(--panel); margin-bottom: 16px; }
@@ -369,6 +386,8 @@
369
386
  .crumb b { color: var(--accent); font-weight: 600; }
370
387
  main { padding: 16px 20px 48px; display: grid; gap: 12px; align-content: start; }
371
388
  .hint { color: var(--muted); font-size: 13px; margin: -4px 2px 0; }
389
+ .hint.corrected button { all: unset; color: var(--accent); text-decoration: underline; cursor: pointer; }
390
+ .hint.corrected button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
372
391
 
373
392
  /* A card sits on top of two action strips that show while it is dragged. */
374
393
  .swipe { content-visibility: auto; contain-intrinsic-size: auto 150px; position: relative; border-radius: 12px; overflow: hidden; scroll-margin-top: 90px; transition: height .25s ease, margin .25s ease, opacity .25s ease; }
@@ -391,7 +410,7 @@
391
410
  .swipe:target .card, .card:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
392
411
  .top { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; padding-right: 0; }
393
412
  @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; }
413
+ a.name { color: var(--text); font-weight: 700; font-size: 17px; text-decoration: none; letter-spacing: -.01em; overflow-wrap: anywhere; min-width: 0; }
395
414
  a.name:hover { color: var(--accent); }
396
415
  .badge { font-size: 12px; padding: 1px 9px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); white-space: nowrap; }
397
416
  .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 2px; }
@@ -466,7 +485,7 @@
466
485
  @media (max-width: 720px) {
467
486
  header { padding: 10px 16px; padding-top: max(10px, env(safe-area-inset-top)); gap: 8px 10px; }
468
487
  .stats { display: none; }
469
- .lang { margin-left: auto; }
488
+ #lock:not([hidden]), #lock[hidden] + #add-btn { margin-left: auto; }
470
489
  .search { order: 3; flex-basis: 100%; max-width: none; margin: 0; font-size: 16px; /* 16px: iOS doesn't zoom in */ }
471
490
  .layout { grid-template-columns: 1fr; }
472
491
  /* The sidebar becomes a drawer behind the ☰ button. */
@@ -512,7 +531,7 @@
512
531
  .md-top .prev .ico { transform: rotate(180deg); }
513
532
  .md-scroll { overflow: auto; padding: 0 18px 12px; flex: 1; min-height: 0; overscroll-behavior: contain; }
514
533
  .md-scroll h3 { margin: 12px 0 6px; font-size: 21px; letter-spacing: -.01em; }
515
- .md-scroll h3 a { color: var(--text); text-decoration: none; }
534
+ .md-scroll h3 a { color: var(--text); text-decoration: none; overflow-wrap: anywhere; }
516
535
  .md-scroll h3 a:hover { color: var(--accent); }
517
536
  .md-sub { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; margin: 0 0 10px; color: var(--muted); font-size: 13px; }
518
537
  .md-one { margin: 0 0 6px; font-size: 16px; }
@@ -591,6 +610,9 @@
591
610
  <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
611
  <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
612
  <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>
613
+ <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>
614
+ <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>
615
+ <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
616
  <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
617
  </defs>
596
618
  </svg>
@@ -604,7 +626,9 @@
604
626
  <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
627
  <input id="q" class="search" type="search" enterkeyhint="search">
606
628
  <button id="lock" class="lock" type="button" hidden></button>
629
+ <button id="add-btn" class="lang hbtn" type="button" aria-haspopup="dialog"></button>
607
630
  <button id="palette-btn" class="lang" type="button" aria-haspopup="dialog"></button>
631
+ <button id="settings-btn" class="lang hbtn" type="button" aria-haspopup="dialog"></button>
608
632
  <button id="lang" class="lang" type="button"></button>
609
633
  </header>
610
634
  <button id="crumb" class="crumb" type="button" aria-controls="nav"></button>
@@ -711,8 +735,17 @@
711
735
  <input id="cmd-input" type="text" role="combobox" aria-expanded="true" aria-controls="cmd-list" aria-autocomplete="list" autocomplete="off" spellcheck="false">
712
736
  <div id="cmd-list" role="listbox"></div>
713
737
  </dialog>
738
+ <dialog id="add-dlg" aria-labelledby="ad-title">
739
+ <form id="add-dlg-form" method="dialog">
740
+ <h3 id="ad-title"></h3>
741
+ <p class="dlg-error" id="ad-error"></p>
742
+ <label><span id="ad-help"></span><input id="ad-url" type="text" inputmode="url" autocapitalize="off" autocomplete="off" spellcheck="false"></label>
743
+ <div class="dlg-actions"><span class="spacer"></span>
744
+ <button class="btn" id="ad-cancel" type="button"></button><button class="btn primary" id="ad-ok" type="submit"></button></div>
745
+ </form>
746
+ </dialog>
714
747
  <dialog id="keys-dlg" aria-labelledby="ky-title">
715
- <h3 id="ky-title"></h3>
748
+ <h3 id="ky-title" tabindex="-1"></h3>
716
749
  <dl class="keys" id="ky-body"></dl>
717
750
  <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="ky-close" type="button"></button></div>
718
751
  </dialog>
@@ -724,12 +757,17 @@
724
757
  </dialog>
725
758
  <div class="toast" id="toast" role="status"><span id="toast-text"></span><button id="toast-undo" type="button"></button></div>
726
759
  <script>
760
+ const cardsN = (n) => `${n} ${n === 1 ? "card" : "cards"}`;
727
761
  const STRINGS = {
728
762
  en: {
729
763
  search: "Search tools, tags, links…", all: "All", favorites: "Favorites", trash: "Trash", any: "Any",
730
764
  kind: "Kind", switchTo: "中文", nav: "Views and categories",
731
765
  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.",
766
+ 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>.",
767
+ noMatch: (q, v) => `No cards match “${q}” in ${v}.`, searchAll: "Search everything", searchIn: (v) => `Search ${v}…`,
768
+ showingFor: (c) => `Showing results for “${c}”`, searchInstead: (q) => `search for “${q}” instead`,
769
+ 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",
770
+ 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
771
  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
772
  kinds: { repo: "Repos", product: "Products", video: "Videos", article: "Articles", post: "Posts", other: "Other" },
735
773
  kind1: { repo: "Repo", product: "Product", video: "Video", article: "Article", post: "Post", other: "Other" },
@@ -745,13 +783,13 @@
745
783
  folders: "Folders", newFolder: "New folder", newSub: "New folder inside", editFolder: "Edit folder", folderName: "Name",
746
784
  folderDesc: "What goes here? (driftnet's AI reads this to sort new links)", folderParent: "Inside", topLevel: "— Top level —",
747
785
  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}` : ""}`,
786
+ 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
787
  moveTo: "Move to…", moveTitle: (n) => `Move “${n}” to`, moved: (n, f) => `Moved “${n}” to ${f}`, expand: "Show sub-folders",
750
788
  dragHint: "Drag onto a folder in the sidebar", foundIn: "Found in this post:", related: "Related:", folderMoved: (n, f) => `“${n}” is now inside ${f}`,
751
789
  topLevelShort: "the top level",
752
790
  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
791
  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.",
792
+ 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
793
  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
794
  kFocus: "Focus on the folder (mind map)", kFocusUp: "Back up one level (mind map)", keysMap: "Mind map",
757
795
  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 +803,12 @@
765
803
  histActor: (a) => a === "admin" ? "You" : a === "system:refresh" ? "Refresh" : a === "system" ? "System" : a.replace(/^agent:/, "agent "),
766
804
  notes: "Notes", note: "Note", addNote: "Add a note", editNote: "Edit note", noteFor: (n) => `Note on “${n}”`,
767
805
  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",
806
+ noteBody: "Type # and a card number (e.g. #3) to link a card.", delNote: "Delete note", delNoteSure: "Really delete?", untitled: "Untitled",
807
+ 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
808
  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",
809
+ 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
810
  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.",
811
+ 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
812
  addLink: "Add", addPlaceholder: "Paste a link to a tool, post or video…", added: "Saved — sorting it now",
775
813
  shortcuts: "Keys: j / k next / previous · f favorite · m move · n note · # trash · / search · g m mind map",
776
814
  keysTitle: "Keyboard shortcuts", keysMove: "Move, favorite, trash", keysSelect: "Select several cards", keysGo: "Go to", keysQuick: "File into your most-used folders",
@@ -786,17 +824,18 @@
786
824
  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
825
  chipOther: "Other folder…", chipTitle: (p) => `Confidence ${p}%`,
788
826
  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",
827
+ planBtn: "Suggest folders", planNoModel: "Needs an AI model — set one in ⚙ Settings → AI", planTitle: "Suggested folder changes",
790
828
  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
829
  planThinking: "Asking the model…", planNone: "The model found nothing worth changing.", planApply: (n) => `Apply ${n} selected`,
792
830
  planCreate: (p) => `Create “${p}”`, planRename: (a, b) => `Rename “${a}” to “${b}”`, planMove: (n, d) => `Move ${n} ${n === 1 ? "card" : "cards"} to “${d}”`,
793
831
  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
832
  nSelected: (n) => `${n} selected`, selectAll: "Select all", clearSel: "Clear", trashShort: "Trash",
795
833
  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`,
834
+ bulkMoved: (n, f) => `Moved ${cardsN(n)} to ${f}`, bulkRemoved: (n) => `${cardsN(n)} moved to the trash`, bulkRestored: (n) => `${cardsN(n)} restored`,
835
+ bulkFaved: (n) => `${cardsN(n)} added to favorites`, bulkUnfaved: (n) => `${cardsN(n)} removed from favorites`,
798
836
  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.",
837
+ 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.",
838
+ advanced: "Advanced", advancedHelp: "Other providers' settings, search by meaning, extra keys and video tool paths.", openSettings: "Open Settings",
800
839
  display: "This browser", sort: "Order", sorts: { best: "Best first", newest: "Newest first", shared: "Most shared first" },
801
840
  compact: "Compact cards (one line each)", tags: "Show tags", said: "Show what people said in chat",
802
841
  theme: "Theme", themes: { auto: "Follow the system", light: "Light", dark: "Dark" },
@@ -805,7 +844,17 @@
805
844
  status: (e) => `Now: sorting by ${({ jev: "Jev", llm: "the model", heuristic: "built-in rules" })[e.judge] ?? e.judge}, summaries: ${e.summarizer === "off" ? "off" : e.summarizer}`, keep: "set — leave empty to keep", unset: "not set",
806
845
  locked: "set by the environment driftnet runs in", forbidden: "Server settings can only be changed on the computer running driftnet (or set DRIFTNET_TOKEN). Display settings still work.",
807
846
  savedServer: "Saved — already in effect", chat: "Chat replies", webhook: "Outgoing webhook", digest: "Scheduled digest", feed: "Feed (RSS)", genCopied: "New password generated and copied — press Save to keep it",
808
- tabGeneral: "General", tabAccess: "Access", tabAi: "AI",
847
+ tabGeneral: "General", tabAccess: "Access", tabAi: "AI", tabChats: "Chats",
848
+ chatsIntro: "Paste a bot's token and press Save: driftnet connects right away, no restart. Then send the bot a link.",
849
+ chatsAdvanced: "Advanced", chatsAdvancedHelp: "Limit the bots to some chats or channels, and Slack without Socket Mode (needs a public URL).",
850
+ chatState: { off: "Not connected — paste a token below", starting: "Connecting…", connected: (n) => n ? `Connected as ${n}` : "Connected",
851
+ webhook: (url) => `Ready — messages arrive at ${url}`, error: (e) => `Problem: ${e}`, needs: (f) => `Also needs: ${f}`, publicUrl: "your public URL" },
852
+ chatHelp: {
853
+ telegram: ["In Telegram, open @BotFather, send /newbot and paste the token it gives you. For groups, also send /setprivacy → Disable so the bot sees links.", [["https://t.me/BotFather", "Open @BotFather"]]],
854
+ discord: ["In the Discord Developer Portal, create an application, open Bot, press Reset Token and turn on Message Content Intent on the same page. Invite it with OAuth2 → URL Generator → bot.", [["https://discord.com/developers/applications", "Discord Developer Portal"]]],
855
+ slack: ["Create an app at api.slack.com, turn on Socket Mode (that makes the xapp- token), add the bot scopes channels:history, groups:history, chat:write and the message events, then install it and copy the xoxb- Bot User OAuth Token.", [["https://api.slack.com/apps", "Slack apps"]]],
856
+ line: ["In LINE Developers, create a Messaging API channel: the Channel secret is under Basic settings, the access token under Messaging API. LINE has to reach driftnet from the internet, so it needs a public URL; set the webhook to that URL + /webhooks/line.", [["https://developers.line.biz/console/", "LINE Developers"], ["https://github.com/KevinChu1110/driftnet/blob/main/docs/online.md", "Putting it online"]]],
857
+ },
809
858
  updates: "Updates", bkTitle: "Backup", bkHelp: "One zip with your whole catalogue (cards, folders, notes, tokens) and your settings. Passwords and keys are left out unless you tick the box.",
810
859
  bkDownload: "Download backup", bkSecrets: "Include passwords and keys (enter the admin password again)", bkPassword: "Admin password",
811
860
  bkRestoreFile: "Restore from a backup file", bkRestoreHelp: "The backup is checked first. Nothing changes until you restart driftnet; your current data is kept next to it as a before-restore copy.",
@@ -855,7 +904,7 @@
855
904
  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
905
  keyWrong: "That's neither the admin password nor a share key.",
857
906
  labels: {
858
- DRIFTNET_LLM_PROVIDER: ["Model provider", "Summaries. None: links are still sorted, only without a summary."],
907
+ 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
908
  DRIFTNET_LLM_MODEL: ["Model", "e.g. claude-haiku-5-5, gpt-5-mini, gemini-3.8-flash, qwen3"],
860
909
  DRIFTNET_LLM_BASE_URL: ["API URL", "For OpenAI-compatible APIs: Gemini, Grok, OpenRouter, Ollama (http://127.0.0.1:11434/v1)…"],
861
910
  DRIFTNET_LLM_API_KEY: ["API key", ""],
@@ -901,11 +950,20 @@
901
950
  DRIFTNET_WHISPER: ["whisper path", "Only if whisper or whisper-cli (speech) is not on PATH."],
902
951
  DRIFTNET_VIDEO_FRAMES: ["Show frames to the model", "Off by default. When on, and a reel or short is still thin after the local tools, up to 8 distinct frames are attached to the same summary request, so they go to the model you configured and nowhere else. The model must accept pictures (Ollama: a vision model)."],
903
952
  DRIFTNET_WEBHOOK_ALLOW_LOCAL: ["Allow a local webhook", "Needed when the receiver is on your own network (n8n on a LAN). Only that exact address is allowed."],
953
+ TELEGRAM_BOT_TOKEN: ["Bot token", "Looks like 123456789:AA…"],
954
+ DRIFTNET_TELEGRAM_CHATS: ["Telegram: only these chats", "Comma-separated chat ids. Empty: anyone who finds the bot. The log prints the id of each new chat."],
955
+ DISCORD_BOT_TOKEN: ["Bot token", "From Bot → Reset Token (not the client secret)."],
956
+ DISCORD_CHANNELS: ["Discord: only these channels", "Comma-separated channel ids (right-click a channel → Copy Channel ID). Empty: every channel the bot can read."],
957
+ SLACK_APP_TOKEN: ["App-level token", "Starts with xapp- (Basic Information → App-Level Tokens, scope connections:write)."],
958
+ SLACK_BOT_TOKEN: ["Bot token", "Starts with xoxb- (OAuth & Permissions)."],
959
+ SLACK_SIGNING_SECRET: ["Slack signing secret", "Only for Slack without Socket Mode: events go to your public URL + /webhooks/slack."],
960
+ LINE_CHANNEL_SECRET: ["Channel secret", "32 letters and digits, under Basic settings."],
961
+ LINE_CHANNEL_ACCESS_TOKEN: ["Channel access token", "Messaging API → Channel access token (long-lived) → Issue."],
904
962
  },
905
963
  choices: {
906
964
  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
965
  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" },
966
+ 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
967
  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
968
  DRIFTNET_LOCALE: { "": "Same as the summaries", en: "English", "zh-TW": "繁體中文" },
911
969
  DRIFTNET_REPLY_STYLE: { "": "Rich (default)", rich: "Rich: cards and vote buttons", text: "Plain text" },
@@ -926,7 +984,11 @@
926
984
  search: "搜尋工具、標籤、連結…", all: "全部", favorites: "最愛", trash: "垃圾桶", any: "不限",
927
985
  kind: "類型", switchTo: "EN", nav: "檢視與分類",
928
986
  stats: (n, s) => `${n} 則 · 分享 ${s} 次`, shared: (n) => `分享 ${n} 次`,
929
- empty: "還沒有內容,把連結丟進聊天室吧。", emptyFav: "還沒有最愛,把卡片往右滑或按星號。",
987
+ empty: "這裡還沒有內容。", emptyStart: "還沒有內容。在下面貼一個連結開始,或用 Chrome 擴充功能收錄,也可以執行 npx driftnet add <連結>。",
988
+ noMatch: (q, v) => `「${v}」裡沒有符合「${q}」的卡片。`, searchAll: "搜尋全部", searchIn: (v) => `在「${v}」裡搜尋…`,
989
+ showingFor: (c) => `顯示「${c}」的搜尋結果`, searchInstead: (q) => `改搜尋「${q}」`,
990
+ addTitle: "收錄連結", addHelp: "工具、貼文或影片的連結(只打 example.com 也可以)", addThis: (u) => `收錄這個連結:${u}`, kAdd: "收錄連結",
991
+ addedAlready: "已經收過了,就是這張", addNothing: "裡面找不到連結。", noSuggestion: "這張卡片沒有建議的資料夾,按 m 自己選", emptyFav: "還沒有最愛,把卡片往右滑或按星號。",
930
992
  pageMore: (n) => `再顯示 ${n} 張`, emptyTrash: "垃圾桶是空的。", hint: "往右滑加入最愛,往左滑移到垃圾桶。", hintTrash: "往右滑還原。",
931
993
  kinds: { repo: "程式庫", product: "產品", video: "影片", article: "文章", post: "貼文", other: "其他" },
932
994
  worth: { skip: "略過", low: "次要", normal: "值得看", "must-see": "必看" },
@@ -941,13 +1003,13 @@
941
1003
  folders: "資料夾", newFolder: "新資料夾", newSub: "在裡面新增資料夾", editFolder: "編輯資料夾", folderName: "名稱",
942
1004
  folderDesc: "放什麼?(driftnet 的 AI 會照這段說明把新連結分進來)", folderParent: "放在", topLevel: "— 最上層 —",
943
1005
  save: "儲存", cancel: "取消", del: "刪除資料夾", delSure: "確定刪除?內容移到上一層",
944
- refresh: "重新整理(再抓一次並重新摘要)", refreshed: (n) => `已重新整理「${n}」`, refreshBusy: "這張卡片正在重新整理。", refreshWait: "剛剛才整理過,請一分鐘後再試。", refreshFailed: (why) => `重新整理失敗${why ? `:${why}` : ""}`,
1006
+ refresh: "重新整理(再抓一次並重新摘要)", refreshShort: "重新摘要", refreshed: (n) => `已重新整理「${n}」`, refreshBusy: "這張卡片正在重新整理。", refreshWait: "剛剛才整理過,請一分鐘後再試。", refreshFailed: (why) => `重新整理失敗${why ? `:${why}` : ""}`,
945
1007
  moveTo: "移動到…", moveTitle: (n) => `把「${n}」移動到`, moved: (n, f) => `已將「${n}」移到 ${f}`, expand: "展開子資料夾",
946
1008
  dragHint: "拖到側邊欄的資料夾", foundIn: "從這篇找到:", related: "相關卡片:", folderMoved: (n, f) => `「${n}」已移到 ${f} 底下`,
947
1009
  topLevelShort: "最上層",
948
1010
  pkShare: "分享成資料夾包…", pkTitle: "分享成資料夾包", pkHelp: "資料夾包把這個資料夾、底下的子資料夾和裡面的卡片包成一個檔案,別人一鍵就能匯入。你的筆記、聊天內容和各種計數都不會放進去。", pkName: "資料夾包名稱", pkDesc: "說明", pkDownload: "下載資料夾包", pkLinkL: "分享連結", pkCopy: "複製連結", pkCopied: "已複製連結", pkSigned: "拿到這個連結的人只能下載這一個資料夾包,看不到你目錄裡的其他內容。", pkOpen: "任何連得到這個位址的人都能下載這個資料夾包。", pkNoLink: "還沒設定公開網址,所以暫時沒有可分享的連結。請到「設定 → 存取」設定,或啟動通道。現在仍可以下載檔案。", pkClose: "關閉", pkTooBig: "這個資料夾太大,無法分享成資料夾包。",
949
1011
  mapAll: "全部", focusCrumb: "樹狀圖位置", focusUp: "回上一層", focusFolder: "聚焦這個資料夾", mapTree: "樹狀圖",
950
- mapHintFocus: "連點兩下資料夾(或在資料夾上按 z)可以只看這個資料夾。",
1012
+ mapHintFocus: "連點兩下資料夾(或在資料夾上按 z)可以只看這個資料夾。", mapHintFocusTouch: "想只看一個資料夾:點它的 ⋯,再選「聚焦這個資料夾」。",
951
1013
  kTreeNav: "樹狀圖:下一個/上一個節點", kTreeOpen: "展開資料夾,或進入第一個子項", kTreeClose: "收合資料夾,或回到上一層", kTreeEnds: "第一個/最後一個節點", kTreeType: "直接輸入名稱", kTreeTypeText: "跳到名稱開頭相符的節點",
952
1014
  kFocus: "聚焦這個資料夾(樹狀圖)", kFocusUp: "回上一層(樹狀圖)", keysMap: "樹狀圖",
953
1015
  map: "樹狀圖", mapHint: "點資料夾展開,點卡片預覽。整理卡片:把它拖到資料夾上;手機上按住卡片一下、放開,再點要放進去的資料夾。按 ⋯ 可以改資料夾名稱。",
@@ -961,12 +1023,12 @@
961
1023
  histActor: (a) => a === "admin" ? "你" : a === "system:refresh" ? "重新整理" : a === "system" ? "系統" : a.replace(/^agent:/, "agent "),
962
1024
  notes: "筆記", note: "筆記", addNote: "加筆記", editNote: "改筆記", noteFor: (n) => `「${n}」的筆記`,
963
1025
  noteHelp: "只有你看得到:心得、試用結果、要注意的地方…", newNote: "新筆記", noteTitle: "標題",
964
- noteBody: "支援 Markdown。寫 #12 就會連到第 12 張卡片。", delNote: "刪除筆記", delNoteSure: "確定刪除?", untitled: "未命名",
965
- emptyNotes: "還沒有筆記。筆記可以連到卡片:寫 #12。", exportMd: "下載備份(Markdown)", exportVault: "下載給 Obsidian/Notion",
1026
+ noteBody: "輸入 # 加卡片編號(例如 #3)就能連到那張卡片。", delNote: "刪除筆記", delNoteSure: "確定刪除?", untitled: "未命名",
1027
+ emptyNotes: "還沒有筆記。筆記可以連到卡片:輸入 # 加卡片編號(例如 #3)。", exportMd: "匯出成 Markdown", exportVault: "下載給 Obsidian/Notion",
966
1028
  saved: "已儲存", tagsEdit: "編輯標籤", tagsHelp: "標籤,用逗號分隔(最多 8 個)", purge: "永久刪除", purgeSure: "再按一次即永久刪除", purged: (n) => `已永久刪除「${n}」`,
967
1029
  emptyTrashBtn: "清空垃圾桶", emptyTrashSure: (n) => `再按一次,永久刪除這 ${n} 張`, trashEmptied: (n) => `已永久刪除 ${n} 張卡片`, settings: "設定", pickedUp: (n) => `已拿起「${n}」,點要放進去的資料夾`, alreadyThere: "它已經在這個資料夾裡了",
968
1030
  readOnlyNudge: "目前只能看。要修改,請點上方的「解鎖」", filterFolders: "輸入文字找資料夾…", undoHint: "按 z 復原",
969
- tplTitle: "從這些資料夾開始:", tplAi: "AI 與程式", tplResearch: "研究", tplEveryday: "日常生活", tplSkip: "維持預設", tplFailed: "現在不能換資料夾了:已經有卡片,或資料夾被你改過。",
1031
+ tplTitle: "選一組起始資料夾(會取代目前的預設資料夾):", tplAi: "AI 與程式", tplResearch: "研究", tplEveryday: "日常生活", tplSkip: "維持預設", tplFailed: "現在不能換資料夾了:已經有卡片,或資料夾被你改過。",
970
1032
  addLink: "收錄", addPlaceholder: "貼上工具、貼文或影片的連結…", added: "收到,正在整理",
971
1033
  shortcuts: "快捷鍵:j/k 下一張/上一張 · f 最愛 · m 移動 · n 筆記 · # 垃圾桶 · / 搜尋 · g m 樹狀圖",
972
1034
  keysTitle: "快捷鍵", keysMove: "移動、最愛、垃圾桶", keysSelect: "一次選多張卡片", keysGo: "切換畫面", keysQuick: "放進最常用的資料夾",
@@ -982,7 +1044,7 @@
982
1044
  inbox: "收件匣", emptyInbox: "收件匣清空了——每張卡片都有你選的資料夾。", hintInbox: "點一下資料夾就能歸檔。下面是還沒歸檔的卡片。",
983
1045
  chipOther: "其他資料夾…", chipTitle: (p) => `信心 ${p}%`,
984
1046
  keysInbox: "在收件匣", kChip: "歸到這張卡片建議的第 1–3 個資料夾", kSkip: "略過:移到下一張卡片", kQuickInbox: "在收件匣裡,1–3 改成選擇目前卡片的建議資料夾;4–9 仍然是放進最常用的資料夾。",
985
- planBtn: "建議整理資料夾", planNoModel: "需要先設定 AI 模型(設定 → AI)", planTitle: "建議的資料夾調整",
1047
+ planBtn: "建議整理資料夾", planNoModel: "需要 AI 模型:請到 ⚙ 設定 → AI 設定一個", planTitle: "建議的資料夾調整",
986
1048
  planIntro: "AI 只負責提議。勾選想要的項目再套用,套用前什麼都不會改;復原可以一次還原整份方案。你親手歸檔的卡片不會被移動。",
987
1049
  planThinking: "正在請模型想想…", planNone: "模型認為目前沒有值得調整的地方。", planApply: (n) => `套用選取的 ${n} 項`,
988
1050
  planCreate: (p) => `新增「${p}」`, planRename: (a, b) => `把「${a}」改名為「${b}」`, planMove: (n, d) => `把 ${n} 張卡片移到「${d}」`,
@@ -992,7 +1054,8 @@
992
1054
  bulkMoved: (n, f) => `已將 ${n} 張卡片移到 ${f}`, bulkRemoved: (n) => `已將 ${n} 張卡片移到垃圾桶`, bulkRestored: (n) => `已還原 ${n} 張卡片`,
993
1055
  bulkFaved: (n) => `已將 ${n} 張卡片加入最愛`, bulkUnfaved: (n) => `已將 ${n} 張卡片移出最愛`,
994
1056
  st: {
995
- title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型就會有摘要;不選也可以,連結一樣會分進資料夾,只是沒有摘要。接著貼一個連結試試看。",
1057
+ title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型,就會有摘要,連結也會自動分進資料夾。不選也可以:連結照樣會存下來,先放在「其他」(和收件匣)等你歸檔,接上的 agent 也能幫你寫摘要。接著貼一個連結試試看。",
1058
+ advanced: "進階", advancedHelp: "其他供應商的設定、語意搜尋、額外的金鑰和影片工具路徑。", openSettings: "開啟設定",
996
1059
  display: "這個瀏覽器", sort: "排序", sorts: { best: "值得看的在前", newest: "最新的在前", shared: "最多人分享的在前" },
997
1060
  compact: "精簡卡片(每張一行)", tags: "顯示標籤", said: "顯示大家在聊天室說的話",
998
1061
  theme: "外觀", themes: { auto: "跟系統一樣", light: "淺色", dark: "深色" },
@@ -1001,7 +1064,17 @@
1001
1064
  status: (e) => `目前:分類用 ${({ jev: "Jev", llm: "模型", heuristic: "內建規則" })[e.judge] ?? e.judge},摘要用 ${e.summarizer === "off" ? "(未開啟)" : e.summarizer}`, keep: "已設定,留空就不變", unset: "未設定",
1002
1065
  locked: "由執行環境設定", forbidden: "伺服器設定只能在執行 driftnet 的那台電腦上改(或設定 DRIFTNET_TOKEN)。顯示設定照常可用。",
1003
1066
  savedServer: "已儲存,馬上生效", chat: "聊天室回覆", webhook: "對外 Webhook", digest: "定時摘要", feed: "訂閱源(RSS)", genCopied: "已產生新密碼並複製,按「儲存」才會生效",
1004
- tabGeneral: "一般", tabAccess: "存取", tabAi: "AI",
1067
+ tabGeneral: "一般", tabAccess: "存取", tabAi: "AI", tabChats: "聊天室",
1068
+ chatsIntro: "貼上機器人的權杖,按「儲存」就會馬上連線,不用重新啟動。接著傳一個連結給機器人試試。",
1069
+ chatsAdvanced: "進階", chatsAdvancedHelp: "只讓機器人在某些聊天室或頻道運作,以及不用 Socket Mode 的 Slack(需要公開網址)。",
1070
+ chatState: { off: "尚未連線,請在下面貼上權杖", starting: "連線中…", connected: (n) => n ? `已連線:${n}` : "已連線",
1071
+ webhook: (url) => `已就緒,訊息會送到 ${url}`, error: (e) => `有問題:${e}`, needs: (f) => `還需要填:${f}`, publicUrl: "你的公開網址" },
1072
+ chatHelp: {
1073
+ telegram: ["在 Telegram 找 @BotFather,傳 /newbot,把它給你的權杖貼到這裡。要在群組用的話,再傳 /setprivacy → Disable,機器人才看得到連結。", [["https://t.me/BotFather", "開啟 @BotFather"]]],
1074
+ discord: ["在 Discord Developer Portal 建立應用程式,進 Bot 頁按 Reset Token,並在同一頁打開 Message Content Intent。再用 OAuth2 → URL Generator → bot 邀請它進伺服器。", [["https://discord.com/developers/applications", "Discord Developer Portal"]]],
1075
+ slack: ["在 api.slack.com 建立 app,打開 Socket Mode(會產生 xapp- 開頭的權杖),加上 bot 權限 channels:history、groups:history、chat:write 和 message 事件,安裝後複製 xoxb- 開頭的 Bot User OAuth Token。", [["https://api.slack.com/apps", "Slack apps"]]],
1076
+ line: ["在 LINE Developers 建立 Messaging API channel:Channel secret 在 Basic settings,存取權杖在 Messaging API 頁。LINE 要從網路連到 driftnet,所以需要公開網址;把 webhook 設成該網址加上 /webhooks/line。", [["https://developers.line.biz/console/", "LINE Developers"], ["https://github.com/KevinChu1110/driftnet/blob/main/docs/zh-TW/online.md", "放上網路"]]],
1077
+ },
1005
1078
  updates: "更新", bkTitle: "備份", bkHelp: "一個 zip 檔,包含整個收藏(卡片、資料夾、筆記、權杖)和設定。除非勾選,否則不會包含密碼和金鑰。",
1006
1079
  bkDownload: "下載備份", bkSecrets: "包含密碼和金鑰(需要再輸入一次管理員密碼)", bkPassword: "管理員密碼",
1007
1080
  bkRestoreFile: "從備份檔還原", bkRestoreHelp: "會先檢查備份檔。重新啟動 driftnet 之前不會有任何改變;目前的資料會留在旁邊,檔名帶有 before-restore。",
@@ -1051,7 +1124,7 @@
1051
1124
  loginAdvanced: "密碼是你自己設的但忘了?到跑 driftnet 的那台電腦打開網頁,設定裡可以直接設新的。跑在伺服器上的話:在你的電腦執行 ssh -L PORT:127.0.0.1:PORT <伺服器> 再打開 http://localhost:PORT。",
1052
1125
  keyWrong: "這不是管理密碼,也不是分享碼。",
1053
1126
  labels: {
1054
- DRIFTNET_LLM_PROVIDER: ["模型來源", "用來寫摘要。選「不使用」也會分類,只是沒有摘要。"],
1127
+ DRIFTNET_LLM_PROVIDER: ["模型來源", "用來寫摘要,並把連結分進資料夾。選「不使用」:連結照樣存下來,放在「其他」/收件匣等你歸檔;接上的 agent 也能幫忙寫摘要。"],
1055
1128
  DRIFTNET_LLM_MODEL: ["模型", "例如 claude-haiku-5-5、gpt-5-mini、gemini-3.8-flash、qwen3"],
1056
1129
  DRIFTNET_LLM_BASE_URL: ["API 網址", "OpenAI 相容 API 用:Gemini、Grok、OpenRouter、Ollama(http://127.0.0.1:11434/v1)…"],
1057
1130
  DRIFTNET_LLM_API_KEY: ["API 金鑰", ""],
@@ -1097,11 +1170,20 @@
1097
1170
  DRIFTNET_WHISPER: ["whisper 路徑", "只有 whisper 或 whisper-cli(語音轉文字)不在 PATH 時才需要。"],
1098
1171
  DRIFTNET_VIDEO_FRAMES: ["把畫面交給模型看", "預設關閉。開啟後,reel 或 short 在本機工具讀完後仍然太少時,最多 8 張不重複的畫面會附在同一次摘要請求裡,只送給你設定的模型。模型必須看得懂圖片(Ollama:要用視覺模型)。"],
1099
1172
  DRIFTNET_WEBHOOK_ALLOW_LOCAL: ["允許本機 Webhook", "接收端在你自己的區域網路時需要(例如內網的 n8n)。只放行你填的那個位址。"],
1173
+ TELEGRAM_BOT_TOKEN: ["機器人權杖", "長得像 123456789:AA…"],
1174
+ DRIFTNET_TELEGRAM_CHATS: ["Telegram:只限這些聊天室", "以逗號分隔的聊天室 ID。留空:任何找到機器人的人都能用。記錄檔會印出每個新聊天室的 ID。"],
1175
+ DISCORD_BOT_TOKEN: ["機器人權杖", "在 Bot → Reset Token 取得(不是 client secret)。"],
1176
+ DISCORD_CHANNELS: ["Discord:只限這些頻道", "以逗號分隔的頻道 ID(在頻道上按右鍵 → 複製頻道 ID)。留空:機器人看得到的所有頻道。"],
1177
+ SLACK_APP_TOKEN: ["App-level 權杖", "xapp- 開頭(Basic Information → App-Level Tokens,權限 connections:write)。"],
1178
+ SLACK_BOT_TOKEN: ["機器人權杖", "xoxb- 開頭(OAuth & Permissions 頁)。"],
1179
+ SLACK_SIGNING_SECRET: ["Slack 簽章密鑰", "只有不用 Socket Mode 時才需要:事件會送到你的公開網址 + /webhooks/slack。"],
1180
+ LINE_CHANNEL_SECRET: ["Channel secret", "32 個英數字,在 Basic settings 頁。"],
1181
+ LINE_CHANNEL_ACCESS_TOKEN: ["Channel access token", "Messaging API → Channel access token (long-lived) → Issue。"],
1100
1182
  },
1101
1183
  choices: {
1102
1184
  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
1185
  DRIFTNET_LLM_EFFORT: { "": "預設", low: "低", medium: "中", high: "高", xhigh: "極高" },
1104
- DRIFTNET_JUDGE: { "": "有 Jev 金鑰就用 Jev", jev: "Jev", rules: "規則(免費,不用模型)", llm: "交給模型", heuristic: "交給模型", off: "不用判斷器" },
1186
+ DRIFTNET_JUDGE: { "": "有 Jev 金鑰就用 Jev", jev: "Jev", rules: "規則(免費,不用模型)", llm: "交給模型", heuristic: "不用判斷器:沒分類的連結放到「其他」", off: "不用判斷器" },
1105
1187
  DRIFTNET_SUMMARY_DEPTH: { "": "標準(預設)", brief: "簡短:一句話、2 個重點、看得到什麼", standard: "標準", detailed: "詳細:更多重點、使用情境、怎麼試用" },
1106
1188
  DRIFTNET_LOCALE: { "": "跟摘要一樣", en: "English", "zh-TW": "繁體中文" },
1107
1189
  DRIFTNET_REPLY_STYLE: { "": "豐富(預設)", rich: "豐富:卡片與投票按鈕", text: "純文字" },
@@ -1154,6 +1236,8 @@
1154
1236
  let role = "admin";
1155
1237
  let serverPort = 8787;
1156
1238
  let summaries = true;
1239
+ /** What /api/ui said last (local page, password set…). */
1240
+ let uiInfo = {};
1157
1241
  /** Something needs the password: ask in a dialog that checks it, and keep whatever the user was doing. */
1158
1242
  function needAdmin() {
1159
1243
  toast(T().needPassword);
@@ -1200,7 +1284,11 @@
1200
1284
  }
1201
1285
  if (res.status === 401) throw Object.assign(new Error("unauthorized"), { unauthorized: true });
1202
1286
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
1203
- if (meta) meta.total = Number(res.headers.get("x-total-count"));
1287
+ if (meta) {
1288
+ meta.total = Number(res.headers.get("x-total-count"));
1289
+ // A search that matched nothing as typed was run with its misspelt words corrected.
1290
+ try { meta.corrected = decodeURIComponent(res.headers.get("x-search-corrected") ?? ""); } catch { meta.corrected = ""; }
1291
+ }
1204
1292
  return res.json();
1205
1293
  }
1206
1294
 
@@ -1237,10 +1325,35 @@
1237
1325
  $("lang").textContent = T().switchTo;
1238
1326
  $("palette-btn").textContent = isMac ? "⌘K" : "Ctrl K";
1239
1327
  $("palette-btn").title = $("palette-btn").ariaLabel = T().palette;
1328
+ $("add-btn").innerHTML = ic("plus"); $("add-btn").title = $("add-btn").ariaLabel = `${T().addTitle} (a)`;
1329
+ $("settings-btn").innerHTML = ic("gear"); $("settings-btn").title = $("settings-btn").ariaLabel = T().settings;
1240
1330
  $("nav").setAttribute("aria-label", T().nav);
1241
1331
  $("menu").setAttribute("aria-label", T().menu);
1242
1332
  }
1243
1333
 
1334
+ // ── Back closes things (phones) ──────────────────────────────────────────
1335
+ // While a card, a dialog or the drawer is open there is one extra history entry ({dnLayer}); Back lands on the
1336
+ // entry before it and closes the top one. Closing it any other way takes the entry back, keeping the address it had.
1337
+ let layerTimer = 0, carryUrl = null;
1338
+ const layersOpen = () => !!document.querySelector("dialog[open]") || (document.body.classList.contains("menu-open") && isDrawer());
1339
+ function syncLayer() {
1340
+ clearTimeout(layerTimer);
1341
+ // A moment later: closing one dialog and opening the next (card → Move to…) must not step back and forth.
1342
+ layerTimer = setTimeout(() => {
1343
+ const open = layersOpen(), pushed = !!history.state?.dnLayer;
1344
+ if (open && !pushed) history.pushState({ dnLayer: 1 }, "", location.href);
1345
+ else if (!open && pushed) { carryUrl = location.href; history.back(); }
1346
+ }, 60);
1347
+ }
1348
+ addEventListener("popstate", () => {
1349
+ if (carryUrl) { const u = carryUrl; carryUrl = null; if (u !== location.href) history.replaceState(history.state, "", u); return; }
1350
+ const top = [...document.querySelectorAll("dialog[open]")].pop();
1351
+ if (top) top.close();
1352
+ else if (document.body.classList.contains("menu-open")) setMenu(false);
1353
+ syncLayer();
1354
+ });
1355
+ new MutationObserver(syncLayer).observe(document.body, { subtree: true, attributes: true, attributeFilter: ["open"] });
1356
+
1244
1357
  // ── Drawer (phones) ──────────────────────────────────────────────────────
1245
1358
  const isDrawer = () => matchMedia("(max-width: 720px)").matches;
1246
1359
  /** keyboard: move focus into the drawer and back (a tap doesn't need the focus ring). */
@@ -1251,6 +1364,7 @@
1251
1364
  document.querySelector("header").inert = open && isDrawer();
1252
1365
  document.querySelector(".skip").inert = open && isDrawer();
1253
1366
  $("menu").setAttribute("aria-expanded", String(open));
1367
+ syncLayer();
1254
1368
  if (!keyboard) return;
1255
1369
  if (open) $("nav").querySelector('[aria-pressed="true"]')?.focus({ preventScroll: true });
1256
1370
  else if (isDrawer()) $("menu").focus({ preventScroll: true });
@@ -1262,13 +1376,21 @@
1262
1376
  addEventListener("keydown", (e) => { if (e.key === "Escape" && document.body.classList.contains("menu-open")) setMenu(false, true); });
1263
1377
 
1264
1378
  /** One line under the header saying what is shown, so a closed drawer hides nothing. */
1265
- function updateCrumb() {
1379
+ /** What is shown, in words: the view, then the folder and kind filters. */
1380
+ function viewName() {
1266
1381
  const t = T();
1267
1382
  const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash : state.view === "inbox" ? t.inbox : state.view === "review" ? t.review
1268
1383
  : state.view === "notes" ? t.notes : state.view === "map" ? t.map : t.all];
1269
1384
  if (state.category) parts.push(catLabel(state.category));
1270
1385
  if (state.kind) parts.push(t.kinds[state.kind] ?? state.kind);
1271
- $("crumb").innerHTML = `${esc(t.showing)} <b>${esc(parts.join(" · "))}</b>`;
1386
+ return parts.join(" · ");
1387
+ }
1388
+ function updateCrumb() {
1389
+ const t = T(), name = viewName();
1390
+ $("crumb").innerHTML = `${esc(t.showing)} <b>${esc(name)}</b>`;
1391
+ // The search box says what it searches: everything, or only the view / folder on screen.
1392
+ const ph = state.view === "all" && !state.category && !state.kind ? t.search : t.searchIn(name);
1393
+ $("q").placeholder = ph; $("q").setAttribute("aria-label", ph);
1272
1394
  }
1273
1395
 
1274
1396
  async function load() {
@@ -1287,6 +1409,8 @@
1287
1409
  role = ui.role ?? "admin";
1288
1410
  serverPort = ui.port ?? 8787;
1289
1411
  summaries = ui.summaries ?? true;
1412
+ uiInfo = ui;
1413
+ if (state.category && !folders.some((f) => f.id === state.category)) state.category = "";
1290
1414
  document.body.classList.toggle("readonly", role !== "admin");
1291
1415
  $("lock").hidden = role === "admin";
1292
1416
  if (ui.setup && !store.get("driftnet-setup-seen")) { store.set("driftnet-setup-seen", "1"); setTimeout(() => openSettings(true), 300); }
@@ -1587,9 +1711,14 @@
1587
1711
  moveBest = null;
1588
1712
  $("mv-filter").placeholder = t.filterFolders;
1589
1713
  $("mv-filter").setAttribute("aria-label", t.filterFolders);
1590
- $("move-dlg").showModal();
1591
1714
  // Type to narrow the folders; Enter files into the first match; arrows walk the list.
1592
- $("mv-filter").focus();
1715
+ // A phone gets the list, not a keyboard popping up over it: the filter takes focus only with a mouse or trackpad.
1716
+ const fine = matchMedia("(pointer: fine)").matches;
1717
+ $("move-dlg").toggleAttribute("autofocus", !fine);
1718
+ $("move-dlg").tabIndex = -1;
1719
+ $("move-dlg").showModal();
1720
+ if (fine) $("mv-filter").focus();
1721
+ else if (document.activeElement === $("mv-filter")) $("move-dlg").focus();
1593
1722
  }
1594
1723
  $("mv-cancel").onclick = () => $("move-dlg").close();
1595
1724
  $("mv-filter").addEventListener("input", () => {
@@ -1623,15 +1752,13 @@
1623
1752
  else moveItem(moving, b.dataset.to);
1624
1753
  };
1625
1754
 
1626
- async function moveItem(id, to, quiet = false) {
1755
+ async function moveItem(id, to) {
1627
1756
  const item = find(id);
1628
1757
  if (!item || item.category === to) return;
1629
1758
  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);
1759
+ // Through the bulk endpoint: its Undo puts the card back exactly as it was (still unfiled, in the Inbox, if it was).
1760
+ const r = await mapWrite("/api/items/bulk", "POST", { action: "move", ids: [id], folder: to });
1761
+ if (!r) return;
1635
1762
  item.category = to;
1636
1763
  const f = folderById(to); if (f) f.count++;
1637
1764
  const old = folderById(from); if (old) old.count--;
@@ -1650,7 +1777,15 @@
1650
1777
  if (onMap && onMap !== item) onMap.category = to;
1651
1778
  if (mapShown()) drawMap();
1652
1779
  bumpUse(to);
1653
- if (!quiet) { toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); renderKeep(); }); }
1780
+ refreshCounts();
1781
+ toast(T().moved(nameOf(item), folderPath(to)), async () => {
1782
+ if (!(await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo }))) return;
1783
+ item.category = from;
1784
+ if (onMap) onMap.category = from;
1785
+ await refreshFolders();
1786
+ await renderKeep();
1787
+ refreshCounts();
1788
+ });
1654
1789
  }
1655
1790
  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
1791
  /** Re-draw just the tree's counts after a move. */
@@ -1720,7 +1855,7 @@
1720
1855
  /** The token list Settings last fetched, to warn when a new token repeats an active name. */
1721
1856
  let knownTokens = [];
1722
1857
  const nameTaken = (list, name) => list.some((k) => !k.revokedAt && k.name.toLowerCase() === name.toLowerCase());
1723
- async function openSettings(welcome = false) {
1858
+ async function openSettings(welcome = false, want = null) {
1724
1859
  const t = T(), st = t.st;
1725
1860
  const token = store.get("driftnet-token");
1726
1861
  const res = await fetch("/api/settings", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
@@ -1757,30 +1892,113 @@
1757
1892
  const yes = (b) => (b ? "✓" : "—");
1758
1893
  const accessStatus = `<p class="set-status">${esc(st.accessStatus(yes(a.passwordSet), yes(a.readKey), a.tunnel.running ? a.tunnel.url : "—"))}</p>`;
1759
1894
  server = {
1760
- general: group("language") + group("chat") + group("digest") + group("webhook") + group("updates") + importPanel() + backupPanel(serverSettings),
1895
+ general: group("language") + group("digest") + group("webhook") + group("updates") + importPanel() + backupPanel(serverSettings),
1761
1896
  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") +
1897
+ ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + aiPanel(serverSettings, field) +
1763
1898
  `<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`,
1899
+ chats: chatsPanel(serverSettings, field) + group("chat"),
1764
1900
  };
1765
1901
  }
1766
- // 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";
1768
- const tabs = [["general", st.tabGeneral], ["access", st.tabAccess], ["ai", st.tabAi]];
1902
+ // Tabs instead of one long scroll: what you see, who gets in, which AI, which chats.
1903
+ const tab = want ?? (welcome ? "ai" : store.get("driftnet-settings-tab") || "general");
1904
+ const tabs = [["general", st.tabGeneral], ["access", st.tabAccess], ["ai", st.tabAi], ["chats", st.tabChats]];
1769
1905
  const section = (k, html) => `<section data-tab="${k}" role="tabpanel" id="panel-${k}" aria-labelledby="tab-${k}">${html}</section>`;
1770
1906
  $("st-title").textContent = st.title;
1771
1907
  $("st-error").textContent = "";
1772
1908
  $("st-body").innerHTML = (welcome ? `<p class="welcome">${esc(st.welcome)}</p>` : "") +
1773
1909
  `<div class="tabs" role="tablist">${tabs.map(([k, l]) => `<button type="button" role="tab" id="tab-${k}" aria-controls="panel-${k}" tabindex="${k === tab ? 0 : -1}" data-tab-btn="${k}" aria-selected="${k === tab}">${esc(l)}</button>`).join("")}</div>` +
1774
1910
  (typeof server === "string"
1775
- ? section("general", local) + section("access", server) + section("ai", server)
1776
- : section("general", local + server.general) + section("access", server.access) + section("ai", server.ai));
1911
+ ? section("general", local) + section("access", server) + section("ai", server) + section("chats", server)
1912
+ : section("general", local + server.general) + section("access", server.access) + section("ai", server.ai) + section("chats", server.chats));
1777
1913
  $("st-body").dataset.tab = tab;
1914
+ placeAi();
1778
1915
  $("st-cancel").textContent = t.cancel;
1779
1916
  $("st-save").textContent = st.save;
1780
- settingsOpener = isDrawer() ? $("menu") : document.activeElement;
1781
- $("settings-dlg").showModal();
1917
+ // Re-drawn while open (after saving a chat token): keep who opened it.
1918
+ if (!$("settings-dlg").open) {
1919
+ settingsOpener = isDrawer() ? $("menu") : document.activeElement;
1920
+ $("settings-dlg").showModal();
1921
+ }
1782
1922
  $("st-body").querySelector('[data-tab-btn][aria-selected="true"]')?.focus();
1783
- }
1923
+ pollChats();
1924
+ }
1925
+ /** Settings › Chats: one section per platform with its status, where to get the token, and its fields. */
1926
+ const CHAT_FIELDS = { telegram: ["TELEGRAM_BOT_TOKEN"], discord: ["DISCORD_BOT_TOKEN"], slack: ["SLACK_APP_TOKEN", "SLACK_BOT_TOKEN"],
1927
+ line: ["LINE_CHANNEL_SECRET", "LINE_CHANNEL_ACCESS_TOKEN"] };
1928
+ const CHAT_ADVANCED = ["DRIFTNET_TELEGRAM_CHATS", "DISCORD_CHANNELS", "SLACK_SIGNING_SECRET"];
1929
+ const CHAT_NAMES = { telegram: "Telegram", discord: "Discord", slack: "Slack", line: "LINE" };
1930
+ function chatStatusText(p, c) {
1931
+ const cs = T().st.chatState;
1932
+ if (!c) return "";
1933
+ if (c.state === "connected") return cs.connected(c.name);
1934
+ // A half-filled platform: name the missing field the way the form does.
1935
+ const needs = /^also needs (.+)$/.exec(c.error ?? "");
1936
+ if (c.state === "error" && needs) return cs.needs(needs[1].split(" and ").map((k) => T().st.labels[k]?.[0] ?? k).join(", "));
1937
+ if (c.state === "error") return cs.error(c.error ?? "");
1938
+ if (c.state === "webhook") return cs.webhook(`${(serverSettings?.access?.publicUrl ?? cs.publicUrl).replace(/\/$/, "")}/webhooks/${p}`);
1939
+ return cs[c.state] ?? "";
1940
+ }
1941
+ function chatsPanel(sv, field) {
1942
+ const st = T().st, byKey = (k) => sv.settings.find((x) => x.key === k);
1943
+ const rows = (keys) => keys.map(byKey).filter(Boolean).map(field).join("");
1944
+ const sections = Object.entries(CHAT_FIELDS).map(([p, keys]) => {
1945
+ const [help, links] = st.chatHelp[p];
1946
+ const c = sv.chats?.[p];
1947
+ const status = c ? `<p class="chat-st" data-chat-status="${p}" data-state="${esc(c.state)}" role="status">${esc(chatStatusText(p, c))}</p>` : "";
1948
+ return `<fieldset class="set-group" id="chat-${p}"><legend>${esc(CHAT_NAMES[p])}</legend>${status}
1949
+ <small class="chat-help">${esc(help)} ${links.map(([u, l]) => `<a href="${esc(u)}" target="_blank" rel="noopener noreferrer">${esc(l)}</a>`).join(" · ")}</small>${rows(keys)}</fieldset>`;
1950
+ }).join("");
1951
+ return `<p class="set-status">${esc(st.chatsIntro)}</p>` + sections +
1952
+ `<details class="set-adv"><summary>${esc(st.chatsAdvanced)}</summary><small>${esc(st.chatsAdvancedHelp)}</small>${rows(CHAT_ADVANCED)}</details>`;
1953
+ }
1954
+ /** While a bot is connecting, refresh the status lines (not the fields) every 2 s, for up to 30 s. */
1955
+ let chatPoll = null;
1956
+ function pollChats() {
1957
+ clearTimeout(chatPoll);
1958
+ let n = 0;
1959
+ const tick = async () => {
1960
+ const open = $("settings-dlg").open && serverSettings?.chats;
1961
+ if (!open || !Object.values(serverSettings.chats).some((c) => c.state === "starting") || ++n > 15) return;
1962
+ const token = store.get("driftnet-token");
1963
+ const r = await fetch("/api/settings", { headers: token ? { authorization: `Bearer ${token}` } : {} }).then((x) => x.ok ? x.json() : null).catch(() => null);
1964
+ if (r?.chats && serverSettings) {
1965
+ serverSettings.chats = r.chats;
1966
+ for (const el of $("st-body").querySelectorAll("[data-chat-status]")) {
1967
+ const c = r.chats[el.dataset.chatStatus];
1968
+ el.dataset.state = c.state;
1969
+ el.textContent = chatStatusText(el.dataset.chatStatus, c);
1970
+ }
1971
+ }
1972
+ chatPoll = setTimeout(tick, 2000);
1973
+ };
1974
+ chatPoll = setTimeout(tick, 2000);
1975
+ }
1976
+ /** Settings › AI: the chosen provider's own fields sit under it; other providers', embeddings and tool paths fold into Advanced. */
1977
+ const PROVIDER_FIELDS = { DRIFTNET_LLM_MODEL: "anthropic openai gemini bedrock vertex claude-cli gemini-cli", DRIFTNET_LLM_BASE_URL: "openai",
1978
+ DRIFTNET_LLM_API_KEY: "anthropic openai gemini vertex", DRIFTNET_LLM_EFFORT: "anthropic openai gemini", DRIFTNET_LLM_REGION: "bedrock vertex",
1979
+ AWS_ACCESS_KEY_ID: "bedrock", AWS_SECRET_ACCESS_KEY: "bedrock", AWS_SESSION_TOKEN: "bedrock", AWS_BEARER_TOKEN_BEDROCK: "bedrock",
1980
+ GOOGLE_CLOUD_PROJECT: "vertex", DRIFTNET_VERTEX_CREDENTIALS: "vertex" };
1981
+ const AI_ADVANCED = ["TYPESAFE_API_KEY", "GITHUB_TOKEN", "DRIFTNET_EMBED", "DRIFTNET_EMBED_PROVIDER", "DRIFTNET_EMBED_MODEL", "DRIFTNET_EMBED_BASE_URL",
1982
+ "DRIFTNET_EMBED_API_KEY", "DRIFTNET_EMBED_FLOOR", "DRIFTNET_YTDLP", "DRIFTNET_FFMPEG", "DRIFTNET_TESSERACT", "DRIFTNET_WHISPER"];
1983
+ function aiPanel(sv, field) {
1984
+ const st = T().st, all = sv.settings;
1985
+ const adv = new Set(AI_ADVANCED);
1986
+ if (all.find((x) => x.key === "DRIFTNET_JUDGE")?.value !== "rules") adv.add("DRIFTNET_JUDGE_RULES");
1987
+ 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]}"` : ""}`);
1988
+ const pick = (test) => all.map((s, n) => (test(s) ? row(s, n) : "")).join("");
1989
+ const plain = (g) => (s) => s.group === g && !adv.has(s.key) && !PROVIDER_FIELDS[s.key] && s.key !== "DRIFTNET_LLM_PROVIDER";
1990
+ 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>` +
1991
+ `<fieldset class="set-group"><legend>${esc(st.rules)}</legend>${pick(plain("rules"))}</fieldset>` +
1992
+ `<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>`;
1993
+ }
1994
+ /** Move each provider field next to the provider select when that provider uses it, else into Advanced. */
1995
+ function placeAi() {
1996
+ const sel = $("st-body").querySelector('[data-key="DRIFTNET_LLM_PROVIDER"]'), here = $("ai-prov"), there = $("ai-prov-other");
1997
+ if (!sel || !here || !there) return;
1998
+ const rows = [...$("st-body").querySelectorAll("[data-for]")].sort((a, b) => a.dataset.n - b.dataset.n);
1999
+ for (const r of rows) (r.dataset.for.split(" ").includes(sel.value) ? here : there).append(r);
2000
+ }
2001
+ $("st-body").addEventListener("change", (e) => { if (e.target.dataset?.key === "DRIFTNET_LLM_PROVIDER") placeAi(); });
1784
2002
  /** Settings › Backup: download a zip (secrets only with the password typed again) or restore one (applied at the next start). */
1785
2003
  function backupPanel(sv) {
1786
2004
  const st = T().st;
@@ -2121,9 +2339,9 @@
2121
2339
  for (const el of body.querySelectorAll("[data-pref]")) prefs[el.dataset.pref] = el.type === "checkbox" ? el.checked : el.value;
2122
2340
  store.set("driftnet-prefs", JSON.stringify(prefs));
2123
2341
  applyPrefs();
2124
- let serverSaved = false;
2342
+ let serverSaved = false, values = null;
2125
2343
  if (serverSettings) {
2126
- const values = {};
2344
+ values = {};
2127
2345
  for (const el of body.querySelectorAll("[data-key]:not([disabled])")) {
2128
2346
  const s = serverSettings.settings.find((x) => x.key === el.dataset.key);
2129
2347
  if (s.secret ? el.value.trim() : el.value.trim() !== (s.value ?? "").trim()) values[s.key] = el.value.trim() === "" ? null : el.value;
@@ -2139,12 +2357,14 @@
2139
2357
  if ("DRIFTNET_TOKEN" in values) values.DRIFTNET_TOKEN ? store.set("driftnet-token", values.DRIFTNET_TOKEN.trim()) : store.set("driftnet-token", "");
2140
2358
  }
2141
2359
  }
2142
- return { serverSaved };
2360
+ return { serverSaved, chats: serverSaved && Object.keys(values ?? {}).some((k) => serverSettings.settings.find((x) => x.key === k)?.group === "chats") };
2143
2361
  }
2144
2362
  $("settings-form").onsubmit = async (e) => {
2145
2363
  e.preventDefault();
2146
2364
  const saved = await saveSettings();
2147
2365
  if (!saved) return;
2366
+ // A chat token: stay on Chats and show whether it connects.
2367
+ if (saved.chats) { toast(T().st.savedServer); return openSettings(false, "chats"); }
2148
2368
  $("settings-dlg").close();
2149
2369
  toast(saved.serverSaved ? T().st.savedServer : T().saved);
2150
2370
  load();
@@ -2163,6 +2383,17 @@
2163
2383
  [/cloudflared is not installed/, () => zh ? "這台電腦還沒安裝 cloudflared。" : "cloudflared isn't installed on this computer."],
2164
2384
  [/set by the environment/, () => zh ? "這個設定由執行環境決定(例如 systemd),要在那裡改。" : "This one is set by the environment driftnet runs in; change it there."],
2165
2385
  [/already a folder called “(.+)” here/, (m) => zh ? `這裡已經有一個叫「${m[1]}」的資料夾了。` : `There's already a folder called “${m[1]}” here.`],
2386
+ [/^model: .*DRIFTNET_LLM_MODEL is required/, () => zh ? "還沒存:這個供應商要填「模型」名稱。" : "Not saved: this provider needs a model name."],
2387
+ [/^model: .*(API_KEY is required|needs an API key|needs a key)/i, () => zh ? "還沒存:這個供應商要填 API 金鑰。" : "Not saved: this provider needs an API key."],
2388
+ [/^model: (.+)/, (m) => zh ? `還沒存:模型設定不完整(${m[1]})。` : `Not saved: the model setup is incomplete (${m[1]}).`],
2389
+ // Why a link was not saved (POST /api/ingest answers 422).
2390
+ [/(\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.`],
2391
+ [/(\S+) did not resolve/, (m) => zh ? `沒有收錄:找不到 ${m[1]} 這個網站,請檢查網址。` : `Not saved: ${m[1]} couldn't be found — check the address.`],
2392
+ [/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://."],
2393
+ [/(\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).`],
2394
+ // A chat token of the wrong shape (Settings › Chats): name the field, and say what it should look like.
2395
+ [/^([A-Z_]+) doesn't look right: it (.+)/, (m) => { const l = T().st.labels[m[1]]?.[0] ?? m[1], hint = T().st.labels[m[1]]?.[1] ?? "";
2396
+ return zh ? `「${l}」看起來不對,請確認貼的是正確的值。${hint}` : `“${l}” doesn't look right: it ${m[2]}.`; }],
2166
2397
  [/too many wrong passwords/, () => zh ? "密碼錯太多次,請 15 分鐘後再試。" : "Too many wrong passwords — try again in 15 minutes."],
2167
2398
  ];
2168
2399
  for (const [re, f] of rules) { const m = re.exec(msg); if (m) return f(m); }
@@ -2186,7 +2417,7 @@
2186
2417
  function syncFocusHash() {
2187
2418
  const want = mapShown() && mapFocus ? `#focus=${encodeURIComponent(mapFocus)}` : "";
2188
2419
  if (want === location.hash || (!want && !location.hash.startsWith("#focus="))) return;
2189
- history.replaceState(null, "", location.pathname + location.search + want);
2420
+ history.replaceState(history.state, "", location.pathname + location.search + want);
2190
2421
  }
2191
2422
  /** Focus the map on a folder (null = back to everything), remembering where each view was. */
2192
2423
  async function setMapFocus(id) {
@@ -2236,7 +2467,8 @@
2236
2467
  : `<button type="button" data-map="focus" data-id="${esc(id)}">${esc(catLabel(id))}</button>`)).join("") + `</nav>`;
2237
2468
  })() : "";
2238
2469
  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>`;
2470
+ const kb = matchMedia("(hover: hover)").matches; // a touch screen gets no "press z"
2471
+ 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
2472
  $("list").innerHTML = `<div class="map-bar">
2241
2473
  <button class="btn" type="button" data-map="${allOpen ? "collapse" : "expand"}">${ic(allOpen ? "collapse" : "expand")} ${esc(allOpen ? t.collapseAll : t.expandAll)}</button>
2242
2474
  <button class="btn" type="button" data-map="new">${ic("plus")} ${esc(t.newFolder)}</button>
@@ -2269,18 +2501,19 @@
2269
2501
  wrap.scrollTop = root.offsetTop * mapZoom - wrap.clientHeight / 2;
2270
2502
  wrap.scrollLeft = (root.offsetLeft + root.offsetWidth / 2) * mapZoom - wrap.clientWidth / 2;
2271
2503
  }
2272
- function fitWidth() {
2504
+ /** floor: never smaller than this; persist: false for split view, which must not change the full map's saved zoom. */
2505
+ function fitWidth(floor = 0.6, persist = true) {
2273
2506
  const wrap = $("map-wrap"), c = $("map-canvas");
2274
2507
  if (!wrap || !c) return;
2275
- mapZoomTo(Math.max(0.6, Math.min(1, (wrap.clientWidth - 8) / c.offsetWidth)));
2508
+ mapZoomTo(Math.max(floor, Math.min(1, (wrap.clientWidth - 8) / c.offsetWidth)), persist);
2276
2509
  const root = c.querySelector('.mnode[data-key="root"]');
2277
2510
  if (root) wrap.scrollTop = root.offsetTop * mapZoom - wrap.clientHeight / 2;
2278
2511
  }
2279
2512
  function fitMap() {
2280
2513
  const wrap = $("map-wrap"), c = $("map-canvas");
2281
2514
  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;
2515
+ // 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.
2516
+ const floor = isDrawer() ? MIN_ZOOM_PHONE : 0.45;
2284
2517
  mapZoomTo(Math.max(floor, Math.min(1.3, (wrap.clientWidth - 8) / c.offsetWidth, (wrap.clientHeight - 8) / c.offsetHeight)));
2285
2518
  centreOnRoot();
2286
2519
  }
@@ -2289,7 +2522,14 @@
2289
2522
  const wrap = $("map-wrap");
2290
2523
  if (wrap) wrap.style.height = `${Math.max(320, innerHeight - wrap.getBoundingClientRect().top - 12)}px`;
2291
2524
  }
2292
- addEventListener("resize", () => { if (mapShown()) sizeMap(); if (splitOn()) sizeSplit(); });
2525
+ let lastW = innerWidth, fitTimer = 0;
2526
+ addEventListener("resize", () => {
2527
+ if (mapShown()) sizeMap();
2528
+ if (splitOn()) sizeSplit();
2529
+ // 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).
2530
+ if (splitOn() && innerWidth !== lastW) { clearTimeout(fitTimer); fitTimer = setTimeout(() => { if (splitOn()) fitWidth(0.3, false); }, 150); }
2531
+ lastW = innerWidth;
2532
+ });
2293
2533
 
2294
2534
  /** Root → folders → sub-folders and cards, laid out left to right like XMind. */
2295
2535
  function drawMap() {
@@ -2446,12 +2686,13 @@
2446
2686
  if (first && q && wrap) wrap.scrollTo({ left: first.offsetLeft * mapZoom - wrap.clientWidth / 2, top: first.offsetTop * mapZoom - wrap.clientHeight / 2 });
2447
2687
  }
2448
2688
 
2449
- function mapZoomTo(z) {
2689
+ const MIN_ZOOM_PHONE = 0.15;
2690
+ function mapZoomTo(z, persist = true) {
2450
2691
  const wrap = $("map-wrap");
2451
2692
  // Zoom around the centre of what is on screen, not the top-left corner.
2452
2693
  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));
2694
+ mapZoom = Math.min(2, Math.max(isDrawer() ? MIN_ZOOM_PHONE : 0.3, Math.round(z * 100) / 100));
2695
+ if (persist) store.set("driftnet-map-zoom", String(mapZoom));
2455
2696
  drawMap();
2456
2697
  if (wrap) { wrap.scrollLeft = cx * mapZoom - wrap.clientWidth / 2; wrap.scrollTop = cy * mapZoom - wrap.clientHeight / 2; }
2457
2698
  }
@@ -2486,7 +2727,8 @@
2486
2727
  });
2487
2728
  $("list").addEventListener("dblclick", (e) => {
2488
2729
  const node = e.target.closest(".mnode.folder");
2489
- if (!node) return;
2730
+ // The tap that drops a held card can land where the hold was and count as a double-tap: that is not "focus".
2731
+ if (!node || justDropped) return;
2490
2732
  clearTimeout(folderTap);
2491
2733
  setMapFocus(node.dataset.key.slice(2));
2492
2734
  });
@@ -2730,9 +2972,10 @@
2730
2972
  if (!i) return void (mdlDlg.open && mdlDlg.close());
2731
2973
  const t = T(), s = i.summary, admin = role === "admin", inTrash = state.view === "trash";
2732
2974
  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]]) {
2975
+ // "3 of 120": the whole list, not just the pages loaded so far (Next loads the next page).
2976
+ const ids = mdIds(), at = ids.indexOf(i.id), total = Math.max(ids.length, pageTotal);
2977
+ $("md-pos").textContent = at >= 0 ? t.mdPos(at + 1, total) : "";
2978
+ for (const [id, label, off] of [["md-prev", t.mdPrev, at <= 0], ["md-next", t.mdNext, at < 0 || at >= total - 1]]) {
2736
2979
  const b = $(id); b.innerHTML = ic("chev"); b.setAttribute("aria-label", label); b.title = label; b.hidden = at < 0; b.disabled = off;
2737
2980
  }
2738
2981
  $("md-close").setAttribute("aria-label", t.close); $("md-close").title = t.close;
@@ -2762,13 +3005,13 @@
2762
3005
  <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
3006
  paintRelated(i.id);
2764
3007
  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>`;
3008
+ 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
3009
  $("md-actions").innerHTML = `<a class="btn primary" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${ic("link")} ${esc(t.openLink)}</a>` +
2767
3010
  (admin ? (inTrash ? btn("restore", "undo", t.restore) + btn("purge", "trash", t.purge, "danger")
2768
3011
  : 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" : "") +
3012
+ `<button class="btn ${busy ? "spin" : ""}" type="button" data-md="refresh" title="${esc(t.refresh)}" ${busy ? "disabled" : ""}>${ic("refresh")} ${esc(t.refreshShort)}</button>` +
3013
+ 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")) : "") +
3014
+ btn("history", "clock", t.histBtn, histFor === i.id ? "on" : "", t.histTitle) +
2772
3015
  (modalFrom === "map" ? btn("list", "list", t.showInList) : "");
2773
3016
  if (histFor === i.id) paintHistory(i);
2774
3017
  }
@@ -2831,19 +3074,24 @@
2831
3074
  if (!wasOpen) mdlDlg.showModal();
2832
3075
  $("md-scroll").scrollTop = 0;
2833
3076
  mdlDlg.style.transform = "";
2834
- history.replaceState(null, "", `${location.pathname}${location.search}#item-${id}`);
3077
+ // Its own history entry, so Back (a phone's above all) closes the card instead of leaving driftnet.
3078
+ if (!history.state?.dnLayer) history.pushState({ dnLayer: 1 }, "", location.href);
3079
+ history.replaceState(history.state, "", `${location.pathname}${location.search}#item-${id}`);
2835
3080
  }
2836
3081
  /** 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;
3082
+ async function stepModal(d) {
3083
+ let ids = mdIds(), at = ids.indexOf(modalId);
3084
+ if (at < 0) return;
3085
+ if (ids[at + d] == null && d > 0 && items.length < pageTotal) { await loadMore(); ids = mdIds(); at = ids.indexOf(modalId); }
3086
+ const to = ids[at + d];
3087
+ if (to == null || !mdlDlg.open) return;
2840
3088
  openModal(to, modalFrom);
2841
3089
  }
2842
3090
  mdlDlg.addEventListener("close", () => {
2843
3091
  if (mdlDlg.open) return; // reopened (a link, a hash) before this queued event ran
2844
3092
  const id = modalId, from = modalFrom;
2845
3093
  // 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);
3094
+ if (!keepHash && location.hash === `#item-${id}`) history.replaceState(history.state, "", location.pathname + location.search);
2847
3095
  keepHash = false;
2848
3096
  mdlDlg.style.transform = "";
2849
3097
  // Focus goes back to the card you ended on (the one you opened, or the last one you stepped to).
@@ -2907,7 +3155,7 @@
2907
3155
  if (act1 === "list") {
2908
3156
  keepHash = true; mdlDlg.close();
2909
3157
  Object.assign(state, { view: "all", category: "", kind: "" });
2910
- history.replaceState(null, "", `#item-${id}`);
3158
+ history.replaceState(history.state, "", `#item-${id}`);
2911
3159
  return load();
2912
3160
  }
2913
3161
  if (act1 === "history") {
@@ -3005,16 +3253,18 @@
3005
3253
  if (!item || !to) return;
3006
3254
  if (item.category === to) return toast(T().alreadyThere);
3007
3255
  const from = item.category;
3008
- if (!(await mapWrite(`/api/items/${id}/move`, "POST", { folder: to }))) return;
3256
+ const r = await mapWrite("/api/items/bulk", "POST", { action: "move", ids: [id], folder: to });
3257
+ if (!r) return;
3009
3258
  item.category = to;
3010
3259
  // Filing many cards in a row: the target stays as it was (no sudden expansion); its count pulses instead.
3011
3260
  drawMap();
3012
3261
  pulse(`f:${to}`);
3013
3262
  bumpUse(to);
3014
3263
  toast(T().moved(nameOf(item), folderPath(to)), async () => {
3015
- if (await mapWrite(`/api/items/${id}/move`, "POST", { folder: from })) { item.category = from; drawMap(); refreshFolders(); }
3264
+ if (await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo })) { item.category = from; drawMap(); refreshFolders(); refreshCounts(); }
3016
3265
  });
3017
3266
  refreshFolders();
3267
+ refreshCounts();
3018
3268
  }
3019
3269
  async function mapMoveFolder(id, to) {
3020
3270
  if (id === to || (to && subtreeOf(id).has(to))) return;
@@ -3081,16 +3331,27 @@
3081
3331
  const withKey = (u) => (a?.private || a?.readKey ? `${u}?key=${key}` : u);
3082
3332
  // With an admin password set, agent cards offer their own token instead of the password.
3083
3333
  const canMint = !!a?.passwordSet;
3334
+ // No password on a page opened on this computer: nothing to authorise, so the commands carry no header.
3335
+ const open = !!a && !a.passwordSet && !!uiInfo.local;
3084
3336
  const secrets = {};
3085
3337
  const card = (id, title, desc, code, agent) => `<div class="conn" id="cc-${id}"><div class="conn-head"><h4>${esc(title)}</h4>
3086
3338
  <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
3339
  ${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
3340
  const cards = [
3341
+ card("init", zh ? "推薦:一次接好你的 AI 工具" : "Recommended: connect your AI apps in one go",
3342
+ isLocalUrl
3343
+ ? (zh ? "在這台電腦的終端機執行。會一次幫 Claude Code、Claude Desktop、Cursor、Windsurf、Codex 接上 driftnet;想先看會改什麼,加 --dry-run。"
3344
+ : "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.")
3345
+ : (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."),
3346
+ isLocalUrl ? "npx driftnet init" : `npx driftnet init --remote ${base} --token ${pw}`, isLocalUrl ? "" : "init"),
3089
3347
  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
3348
  `/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"),
3349
+ open
3350
+ ? card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet", zh ? "在終端機執行。" : "Run in a terminal.",
3351
+ `claude mcp add --transport http driftnet ${base}/mcp`)
3352
+ : card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet",
3353
+ zh ? "在終端機執行。先 export DRIFTNET_TOKEN=你的管理密碼,指令會自動帶入。" : "Run in a terminal. Export DRIFTNET_TOKEN=<your admin password> first; the command reads it.",
3354
+ `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"`, "Claude Code"),
3094
3355
  card("claude", zh ? "Claude 網頁版/桌面版(自訂 connector)" : "Claude.ai / Claude Desktop (custom connector)",
3095
3356
  zh ? "設定 → Connectors → 新增自訂 connector,貼上這個網址。用分享碼連線,只能搜尋和查看,不能改。" : "Settings → Connectors → Add custom connector, paste this URL. The share key makes it read-only: search and look, no changes.",
3096
3357
  withKey(`${base}/mcp`)),
@@ -3103,11 +3364,15 @@
3103
3364
  : `Read ${withKey(`${base}/llms.txt`)} — it's my catalogue of AI tools. Find me one for: (your task).`),
3104
3365
  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
3366
  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"),
3367
+ open
3368
+ ? card("agents", "Hermes / OpenClaw / pi", zh ? "這些 agent 的 MCP 設定。agent 可以收錄、投票、幫忙讀佇列裡的連結。" : "MCP settings for these agents. With it they can save, vote and work the queue.",
3369
+ JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp` } } }, null, 2))
3370
+ : 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.",
3371
+ JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2), "Hermes"),
3108
3372
  ].join("");
3109
3373
  // What each agent card shows once it has its own token.
3110
3374
  snippets = {
3375
+ init: (tok) => `npx driftnet init --remote ${base} --token ${tok}`,
3111
3376
  cc: (tok) => `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer ${tok}"`,
3112
3377
  agents: (tok) => JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${tok}` } } } }, null, 2),
3113
3378
  };
@@ -3270,7 +3535,7 @@
3270
3535
  function jumpTo(id) {
3271
3536
  Object.assign(state, { view: "all", category: "", kind: "", q: "" });
3272
3537
  $("q").value = "";
3273
- history.replaceState(null, "", `#item-${id}`);
3538
+ history.replaceState(history.state, "", `#item-${id}`);
3274
3539
  load();
3275
3540
  }
3276
3541
 
@@ -3286,24 +3551,61 @@
3286
3551
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
3287
3552
  }
3288
3553
 
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;
3554
+ /**
3555
+ * Save one link from the page (the + dialog, the empty list, a link typed into search). The server adds https://
3556
+ * to a bare domain and says why it refused one; `say` shows that reason (a toast unless a dialog has its own line).
3557
+ * True only when a card was really saved.
3558
+ */
3559
+ async function addUrl(url, say = toast) {
3560
+ url = url.trim();
3561
+ if (!url) return false;
3295
3562
  const token = store.get("driftnet-token");
3296
3563
  const res = await fetch("/api/ingest", { method: "POST", body: JSON.stringify({ url }),
3297
3564
  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();
3565
+ if (res?.status === 401) { needAdmin(); return false; }
3566
+ const data = await res?.json().catch(() => null);
3567
+ if (!res?.ok) { say(friendlyError(data?.error) ?? T().failed); return false; }
3568
+ const got = Array.isArray(data) ? data[0] : null;
3569
+ if (!got?.item?.id) { say(T().addNothing); return false; }
3570
+ toast(got.cached ? T().addedAlready : T().added);
3571
+ $("q").value = ""; state.q = "";
3572
+ jumpTo(got.item.id);
3573
+ return true;
3303
3574
  }
3575
+ async function addLink(e) {
3576
+ e.preventDefault();
3577
+ const b = e.submitter; if (b) b.disabled = true;
3578
+ await addUrl($("add-url").value);
3579
+ if (b?.isConnected) b.disabled = false;
3580
+ }
3581
+ function openAdd(prefill = "") {
3582
+ if (role !== "admin") return needAdmin();
3583
+ if (document.querySelector("dialog[open]")) return;
3584
+ const t = T();
3585
+ $("ad-title").textContent = t.addTitle; $("ad-help").textContent = t.addHelp;
3586
+ $("ad-url").placeholder = t.addPlaceholder; $("ad-error").textContent = "";
3587
+ $("ad-cancel").textContent = t.cancel; $("ad-ok").textContent = t.addLink;
3588
+ $("ad-url").value = prefill;
3589
+ $("add-dlg").showModal();
3590
+ $("ad-url").focus();
3591
+ }
3592
+ $("add-btn").onclick = () => openAdd();
3593
+ $("settings-btn").onclick = () => openSettings();
3594
+ $("ad-cancel").onclick = () => $("add-dlg").close();
3595
+ $("add-dlg").addEventListener("click", (e) => { if (e.target === $("add-dlg")) $("add-dlg").close(); });
3596
+ $("add-dlg-form").onsubmit = async (e) => {
3597
+ e.preventDefault();
3598
+ $("ad-ok").disabled = true; $("ad-error").textContent = "";
3599
+ const ok = await addUrl($("ad-url").value, (why) => { $("ad-error").textContent = why; });
3600
+ $("ad-ok").disabled = false;
3601
+ if (ok) $("add-dlg").close();
3602
+ };
3603
+ /** Search text that is a link (a URL, or a bare domain like example.com): offer to save it instead. */
3604
+ const linkLike = (q) => /^(https?:\/\/\S+|[\w-]+(\.[\w-]+)*\.[a-z]{2,}(\/\S*)?)$/i.test(q.trim());
3304
3605
 
3305
3606
  async function render() {
3306
3607
  updateCrumb();
3608
+ store.set("driftnet-view", JSON.stringify({ view: state.view, category: state.category }));
3307
3609
  const viewKey = [state.view, state.category, state.kind, state.q].join("|");
3308
3610
  if (viewKey !== lastViewKey) { lastViewKey = viewKey; selected.clear(); selAnchor = null; }
3309
3611
  document.body.classList.toggle("map-view", mapShown());
@@ -3324,6 +3626,7 @@
3324
3626
  await renderMap(); // the map first: the selection check then knows both sides
3325
3627
  await inPane($("split-list"), renderCards);
3326
3628
  sizeSplit();
3629
+ fitWidth(0.3, false); // the map pane is narrow: show its whole width
3327
3630
  syncSelection();
3328
3631
  };
3329
3632
  return (splitQueue = splitQueue.catch(() => {}).then(run));
@@ -3400,12 +3703,15 @@
3400
3703
  /** Cards fetched per page; the rest come as the reader reaches the end of the list. */
3401
3704
  const PAGE = 60;
3402
3705
  let pageTotal = 0, pageGen = 0, pageBusy = false, pageObserver = null, pageHost = null, keepPages = false;
3706
+ /** The query the reader asked to search exactly as typed (no spelling correction). */
3707
+ let exactQ = "";
3403
3708
  const listParams = () => {
3404
3709
  const p = new URLSearchParams();
3405
3710
  if (prefs.sort !== "best") p.set("sort", prefs.sort);
3406
3711
  if (state.view === "review") p.set("health", "dead,archived,stale");
3407
3712
  else if (state.view !== "all") p.set("view", state.view);
3408
3713
  for (const k of ["category", "kind", "q"]) if (state[k]) p.set(k, state[k]);
3714
+ if (state.q && state.q === exactQ) p.set("fuzzy", "0");
3409
3715
  return p;
3410
3716
  };
3411
3717
  const moreHtml = () => items.length < pageTotal
@@ -3485,13 +3791,27 @@
3485
3791
  pageBusy = false;
3486
3792
  pageObserver?.disconnect();
3487
3793
  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;
3794
+ const fresh = state.view === "all" && !state.q && !state.category && !state.kind && role === "admin";
3795
+ 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;
3796
+ // A link typed into search: offer to save it (right away for a full URL, otherwise only when nothing matched).
3797
+ const addQ = role === "admin" && state.q && linkLike(state.q) && (!items.length || /^(https?:\/\/|www\.)/i.test(state.q))
3798
+ ? `<div class="add-q"><button class="btn primary" type="button" data-add-q>${ic("plus")} ${esc(t.addThis(state.q))}</button></div>` : "";
3799
+ const scoped = state.view !== "all" || state.category || state.kind;
3800
+ // Nothing matched the words as typed: say which spelling was searched, and offer the original.
3801
+ const fixed = items.length && state.q && meta.corrected
3802
+ ? `<p class="hint corrected">${esc(t.showingFor(meta.corrected))} — <button type="button" data-search-exact>${esc(t.searchInstead(state.q))}</button></p>` : "";
3489
3803
  $("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)}">
3804
+ ? fixed + 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()
3805
+ : state.q
3806
+ // Searching found nothing: say so (not "Inbox zero"), and offer the whole catalogue when only part of it was searched.
3807
+ ? `<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>`
3808
+ : `<div class="empty first"><span>${esc(empty)}</span>${fresh
3809
+ ? `<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
3810
  <button class="btn primary" type="submit">${ic("plus")} ${esc(t.addLink)}</button></form>
3494
3811
  <button class="btn" type="button" data-connect-empty>${ic("plug")} ${esc(t.st.connect)}</button>${templateChooser(t)}` : ""}</div>`;
3812
+ $("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; }); });
3813
+ $("list").querySelector("[data-search-all]")?.addEventListener("click", () => { Object.assign(state, { view: "all", category: "", kind: "" }); load(); });
3814
+ $("list").querySelector("[data-search-exact]")?.addEventListener("click", () => { exactQ = state.q; render(); });
3495
3815
  watchMore();
3496
3816
  if (keep) scrollTo({ top: y });
3497
3817
  $("add-form")?.addEventListener("submit", addLink);
@@ -3969,12 +4289,13 @@
3969
4289
  applyPrefs();
3970
4290
  }
3971
4291
  const commands = [
4292
+ { id: "add", label: { en: "Add a link…", "zh-TW": "收錄連結…" }, keys: ["a"], help: "kAdd", when: () => role === "admin", run: () => openAdd() },
3972
4293
  { id: "view-list", label: { en: "Show the card list", "zh-TW": "顯示卡片列表" }, keys: ["g", "a"], help: "kAll", run: () => showLayout("list") },
3973
4294
  { id: "view-map", label: { en: "Show the mind map", "zh-TW": "顯示樹狀圖" }, keys: ["g", "m"], help: "kMap", run: () => showLayout("map") },
3974
4295
  { id: "view-split", label: { en: "Show cards and mind map side by side", "zh-TW": "並排顯示卡片與樹狀圖" }, when: () => wideQuery.matches, run: () => showLayout("split") },
3975
4296
  { id: "move", label: { en: "Move the focused card…", "zh-TW": "移動目前選取的卡片…" }, when: () => role === "admin" && !!pal.focused, run: () => openMovePicker(pal.focused) },
3976
4297
  { 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") },
4298
+ { id: "export-md", label: { en: "Export as Markdown", "zh-TW": "匯出成 Markdown" }, run: () => download("markdown") },
3978
4299
  { id: "export-vault", label: { en: "Download for Obsidian / Notion", "zh-TW": "下載給 Obsidian/Notion" }, run: () => download("vault") },
3979
4300
  { id: "settings", label: { en: "Settings", "zh-TW": "設定" }, run: () => openSettings() },
3980
4301
  { id: "dark", label: { en: "Toggle dark mode", "zh-TW": "切換深色模式" }, run: toggleDark },
@@ -4081,6 +4402,9 @@
4081
4402
  `<h4>${esc(t.keysMap)}</h4>` + row(["↓", "↑"], t.kTreeNav) + row(["→"], t.kTreeOpen) + row(["←"], t.kTreeClose) + row(["Home", "End"], t.kTreeEnds) +
4082
4403
  row([t.kTreeType], t.kTreeTypeText) + row(["z"], t.kFocus) + row(["Esc", "Backspace"], t.kFocusUp);
4083
4404
  $("keys-dlg").showModal();
4405
+ // Start at the top: focus would otherwise land on Close, at the bottom of a long list.
4406
+ $("ky-title").focus({ preventScroll: true });
4407
+ $("keys-dlg").scrollTop = 0;
4084
4408
  }
4085
4409
  $("ky-close").onclick = () => $("keys-dlg").close();
4086
4410
  $("keys-dlg").addEventListener("click", (e) => { if (e.target === $("keys-dlg")) $("keys-dlg").close(); });
@@ -4130,7 +4454,7 @@
4130
4454
  $("plan-body").addEventListener("change", syncPlan);
4131
4455
  async function openPlan() {
4132
4456
  const t = T();
4133
- if (!summaries) return toast(t.planNoModel);
4457
+ if (!summaries) return toast(t.planNoModel, () => openSettings(false, "ai"), t.st.openSettings);
4134
4458
  plan = null;
4135
4459
  $("pl-title").textContent = t.planTitle;
4136
4460
  $("pl-intro").textContent = t.planIntro;
@@ -4161,12 +4485,13 @@
4161
4485
 
4162
4486
  /** The newest undoable action, so z (or ⌘/Ctrl+Z) can undo it from the keyboard. */
4163
4487
  let lastUndo = null;
4164
- function toast(text, undo) {
4488
+ /** label: the button does something else than Undo (z then leaves it alone). */
4489
+ function toast(text, undo, label) {
4165
4490
  $("toast-text").textContent = text;
4166
4491
  const u = $("toast-undo");
4167
4492
  u.hidden = !undo;
4168
- u.textContent = T().undo;
4169
- lastUndo = undo ?? null;
4493
+ u.textContent = label ?? T().undo;
4494
+ lastUndo = label ? null : undo ?? null;
4170
4495
  u.onclick = async () => { clearTimeout(toastTimer); $("toast").classList.remove("show"); lastUndo = null; await undo?.(); };
4171
4496
  $("toast").classList.add("show");
4172
4497
  toastMs = Math.min(9000, 4500 + text.length * 45);
@@ -4201,12 +4526,25 @@
4201
4526
  // Inbox: 1–3 pick the focused card's suggestion chips (before the global "file into top-9 folders").
4202
4527
  if (state.view === "inbox" && /^[1-3]$/.test(k) && role === "admin" && focusedId() && !selected.size) {
4203
4528
  const chip = document.querySelectorAll(`#item-${focusedId()} [data-chip]`)[Number(k) - 1];
4204
- if (chip) { e.preventDefault(); inboxFile(focusedId(), chip.dataset.chip); return; }
4529
+ e.preventDefault();
4530
+ // No such suggestion: say so rather than quietly filing into a most-used folder.
4531
+ if (chip) inboxFile(focusedId(), chip.dataset.chip); else toast(T().noSuggestion);
4532
+ return;
4205
4533
  }
4206
4534
  if (/^[1-9]$/.test(k) && role === "admin" && !document.activeElement?.isContentEditable && quickMove(Number(k))) { e.preventDefault(); return; }
4207
4535
  if (k === "x" && role === "admin" && !document.activeElement?.isContentEditable && focusedId() && state.view !== "map") { e.preventDefault(); toggleSelect(focusedId()); return; }
4208
4536
  const chord = commands.find((c) => c.keys?.length === 2 && c.keys[0] === prev && c.keys[1] === k);
4209
4537
  if (chord) { chord.run(); return; }
4538
+ if (k === "a" && role === "admin" && prev !== "g") { e.preventDefault(); openAdd(); return; }
4539
+ // Cards selected: f, m and # act on all of them, not just the focused one.
4540
+ if (selected.size && role === "admin" && ["f", "#", "Delete", "m"].includes(k)) {
4541
+ e.preventDefault();
4542
+ const ids = [...selected];
4543
+ if (k === "m") openMovePickerFor(ids);
4544
+ else if (k === "f") bulkApply(ids.every((id) => find(id)?.favorite) ? "unfavorite" : "favorite", ids);
4545
+ else bulkApply(state.view === "trash" ? "restore" : "trash", ids);
4546
+ return;
4547
+ }
4210
4548
  const cards = [...$("list").querySelectorAll(".swipe .card")];
4211
4549
  if (!cards.length) return;
4212
4550
  const cur = document.activeElement?.closest?.(".card");
@@ -4236,6 +4574,13 @@
4236
4574
  };
4237
4575
  let timer;
4238
4576
  if (location.hash.startsWith("#focus=")) { mapFocus = focusFromHash(); state.view = "map"; }
4577
+ // A reload comes back to the view (and folder) you were on; a link to a card or a map folder decides for itself.
4578
+ else if (!location.hash) {
4579
+ try {
4580
+ const v = JSON.parse(store.get("driftnet-view") ?? "null");
4581
+ if (["all", "favorites", "inbox", "review", "map", "notes", "trash"].includes(v?.view)) Object.assign(state, { view: v.view, category: typeof v.category === "string" ? v.category : "" });
4582
+ } catch {}
4583
+ }
4239
4584
  $("q").oninput = (e) => { clearTimeout(timer); timer = setTimeout(() => { state.q = e.target.value.trim(); render(); }, 200); };
4240
4585
  // A scanned pairing link (#pair=<code>): take the code out of the address bar at once, swap it for this device's token.
4241
4586
  async function claimPairing() {