-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tsx
More file actions
4498 lines (4283 loc) · 175 KB
/
Copy pathmain.tsx
File metadata and controls
4498 lines (4283 loc) · 175 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { invoke } from "@tauri-apps/api/core";
import { emitTo, listen } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { getVersion } from "@tauri-apps/api/app";
import { open as openUrl } from "@tauri-apps/plugin-shell";
import { diffWordsWithSpace, type Change } from "diff";
import { marked } from "marked";
import DOMPurify from "dompurify";
import * as Dialog from "@radix-ui/react-dialog";
import * as Tooltip from "@radix-ui/react-tooltip";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { motion, AnimatePresence } from "framer-motion";
import {
Settings as SettingsIcon,
Info as InfoIcon,
Sun,
Moon,
Monitor,
X,
Trash2,
RotateCcw,
Loader2,
CheckCircle2,
XCircle,
PlugZap,
ChevronDown,
Send,
BookOpen,
Sparkle,
Coffee,
Heart,
ExternalLink,
Minus,
Square,
} from "lucide-react";
import { useTheme, useThemeFollower, type ThemeChoice } from "./theme";
import { useLicense, LS_CHECKOUT_URL, type LicenseState, type UseLicense } from "./license";
import "./index.css";
import appIconUrl from "./icon.png";
// ---------- Action catalog ----------
type ActionId =
| "improve"
| "grammar"
| "shorten"
| "expand"
| "tone:professional"
| "tone:casual"
| "tone:friendly"
| "tone:confident"
| "prompt:compress"
| "prompt:distill"
| "prompt:structure"
| "custom";
const PRIMARY_ACTIONS: { id: ActionId; label: string }[] = [
{ id: "improve", label: "Improve" },
{ id: "grammar", label: "Fix grammar" },
{ id: "shorten", label: "Shorten" },
{ id: "expand", label: "Expand" },
];
const TONE_ACTIONS: { id: ActionId; label: string }[] = [
{ id: "tone:professional", label: "Professional" },
{ id: "tone:casual", label: "Casual" },
{ id: "tone:friendly", label: "Friendly" },
{ id: "tone:confident", label: "Confident" },
];
// Rewrite the selection as a prompt for an LLM / agent. Goal: cut tokens
// without losing instructions, constraints, examples, or named entities.
const PROMPT_ACTIONS: { id: ActionId; label: string }[] = [
{ id: "prompt:compress", label: "Compress tokens" },
{ id: "prompt:distill", label: "Distill intent" },
{ id: "prompt:structure", label: "Structure for agents" },
];
// ---------- LLM client ----------
interface RewriteOptions {
customPrompt?: string;
signal?: AbortSignal;
}
interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
}
interface LLMClient {
rewrite(input: string, action: ActionId, opts?: RewriteOptions): AsyncIterable<string>;
chat(messages: ChatMessage[], opts?: { signal?: AbortSignal }): AsyncIterable<string>;
}
const BASE_SYSTEM_PROMPT =
"You are an inline writing assistant. Rewrite the user's text per the instruction. " +
"Reply with ONLY the rewritten text — no preamble, no quotes, no explanation, no surrounding code fences. " +
"You MAY use Markdown when the rewrite is naturally structured: bullet or numbered lists for enumerations, " +
"blank-line-separated paragraphs for multi-paragraph prose, **bold** / *italic* for emphasis the user asked for or " +
"that the source clearly carried, headings for section titles, and `inline code` for code-like fragments. " +
"Do NOT add structure that isn't warranted: a single sentence stays a single sentence with no formatting.";
const EDU_MARK = "===R3W-EDU===";
const AFFIRM_MARK = "===R3W-AFFIRM===";
interface ParsedReply {
main: string;
edu: string;
affirm: string;
}
function parseFeedback(text: string): ParsedReply {
if (!text) return { main: "", edu: "", affirm: "" };
const eduIdx = text.indexOf(EDU_MARK);
const affIdx = text.indexOf(AFFIRM_MARK);
if (eduIdx < 0 && affIdx < 0) return { main: text, edu: "", affirm: "" };
const cuts = [eduIdx, affIdx].filter((i) => i >= 0).sort((a, b) => a - b);
const main = text.slice(0, cuts[0]).trimEnd();
let edu = "";
let affirm = "";
if (eduIdx >= 0) {
const next = cuts.find((i) => i > eduIdx);
edu = text.slice(eduIdx + EDU_MARK.length, next ?? text.length).trim();
}
if (affIdx >= 0) {
const next = cuts.find((i) => i > affIdx);
affirm = text.slice(affIdx + AFFIRM_MARK.length, next ?? text.length).trim();
}
return { main, edu, affirm };
}
function buildSystemPrompt(s: {
educational: boolean;
affirm: boolean;
styleGuide?: string;
protectedTerms?: string;
}): string {
let p = BASE_SYSTEM_PROMPT;
const sg = (s.styleGuide || "").trim();
if (sg) {
p += `\n\nStyle guide (apply to all rewrites unless the user's instruction explicitly overrides it):\n${sg}`;
}
const terms = parseProtectedTerms(s.protectedTerms || "");
if (terms.length > 0) {
p +=
"\n\nProtected terms — preserve these tokens VERBATIM (case + spelling): " +
terms.map((t) => `\`${t}\``).join(", ") +
". Do not translate, pluralize, hyphenate, or otherwise alter them.";
}
if (!s.educational && !s.affirm) return p;
p += "\n\nAdditional output channels (after the rewrite, in this order):";
if (s.educational) {
p +=
`\n- On a NEW LINE write the literal token "${EDU_MARK}" followed by 1–2 short, concrete sentences explaining the most important changes you made and why they improve the writing. Be specific to this rewrite, not generic.`;
}
if (s.affirm) {
p +=
`\n- ${s.educational ? "Then " : ""}On a NEW LINE write the literal token "${AFFIRM_MARK}" followed by ONE short sentence of specific, genuine encouragement about what the user did well in the original — what to keep doing.`;
}
p += "\nNever include these tokens or sections unless these instructions explicitly tell you to.";
return p;
}
// Split a comma- or newline-separated list of protected terms. Whitespace is
// trimmed and empties are dropped. Casing is preserved — the model is told to
// keep it verbatim.
function parseProtectedTerms(raw: string): string[] {
return raw
.split(/[\n,]/)
.map((s) => s.trim())
.filter((s) => s.length > 0)
.slice(0, 64);
}
// Rough token estimate — 4 chars per token is a standard approximation that
// works well enough for cost/length warnings without pulling in tiktoken.
function estimateTokens(s: string): number {
if (!s) return 0;
return Math.max(1, Math.ceil(s.length / 4));
}
function actionInstruction(action: ActionId, customPrompt?: string): string {
switch (action) {
case "improve":
return "Improve clarity, flow, and word choice while preserving meaning and approximate length.";
case "grammar":
return "Fix grammar, spelling, and punctuation. Preserve meaning, tone, and length.";
case "shorten":
return "Shorten by roughly 30–40% while preserving meaning and key details.";
case "expand":
return "Expand with relevant detail and supporting examples while preserving the original tone.";
case "prompt:compress":
return (
"Rewrite the text as an LLM/agent prompt with the smallest possible token count. " +
"Preserve every instruction, constraint, requirement, example, named entity, identifier, and quoted string verbatim. " +
"Cut filler, hedges, politeness, redundant phrasings, and meta-commentary; merge restatements; prefer imperatives and short clauses. " +
"Do not add new requirements, examples, or formatting that wasn't in the original."
);
case "prompt:distill":
return (
"Distill the text to the core intent of an LLM/agent prompt. " +
"Keep only what is strictly required to produce the desired output: the goal, hard constraints, output format, and any literal values that must appear verbatim. " +
"Drop background, motivation, soft preferences, and anything decorative. Output only the rewritten prompt."
);
case "prompt:structure":
return (
"Restructure the text as an LLM/agent prompt using these sections, in this order, omitting any section that has no content: " +
"`Role` (one line), `Goal` (one sentence), `Inputs`, `Constraints`, `Output format`, `Examples`. " +
"Use short imperatives and bullet points. Preserve every original requirement and any literal values verbatim. Do not invent new requirements."
);
case "custom":
return customPrompt?.trim() || "Rewrite the text.";
default:
if (action.startsWith("tone:")) {
return `Rewrite in a ${action.slice("tone:".length)} tone while preserving meaning.`;
}
return "Rewrite the text.";
}
}
// ---------- Markdown helpers ----------
marked.setOptions({ breaks: true, gfm: true });
function markdownToHtml(markdown: string): string {
const html = marked.parse(markdown, { async: false }) as string;
return DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
}
function markdownToPlain(markdown: string): string {
if (!markdown) return "";
const html = marked.parse(markdown, { async: false }) as string;
// Render to a detached DOM node, then collapse to text. Block elements get
// double-newline separation so list items and paragraphs read naturally
// when pasted into a plain-text target.
const root = document.createElement("div");
root.innerHTML = DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
const blockTags = new Set([
"P", "DIV", "H1", "H2", "H3", "H4", "H5", "H6",
"UL", "OL", "LI", "BLOCKQUOTE", "PRE", "TABLE", "TR",
]);
const out: string[] = [];
function walk(node: Node) {
if (node.nodeType === Node.TEXT_NODE) {
out.push(node.textContent ?? "");
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const el = node as HTMLElement;
const tag = el.tagName;
if (tag === "BR") {
out.push("\n");
return;
}
if (tag === "LI") {
out.push("\n");
el.childNodes.forEach(walk);
return;
}
el.childNodes.forEach(walk);
if (blockTags.has(tag)) out.push("\n\n");
}
root.childNodes.forEach(walk);
return out.join("").replace(/\n{3,}/g, "\n\n").trim();
}
const RenderedMarkdown = React.memo(function RenderedMarkdown({
markdown,
}: {
markdown: string;
}) {
const html = useMemo(() => markdownToHtml(markdown), [markdown]);
return (
<div
className="prose-r3w break-words text-fg"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
});
function phraseFor(elapsedSec: number): string {
return elapsedSec < 2
? "Thinking"
: elapsedSec < 5
? "Generating"
: elapsedSec < 15
? "Working on it"
: "Still working — large input?";
}
const ThinkingIndicator = React.memo(function ThinkingIndicator({
startedAt,
model,
}: {
startedAt: number | null;
model?: string;
}) {
const phraseTextRef = useRef<HTMLSpanElement>(null);
const elapsedRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
if (startedAt == null) return;
let rafId = 0;
let lastPhrase = "";
const tick = () => {
const elapsed = Math.max(0, (Date.now() - startedAt) / 1000);
if (elapsedRef.current) elapsedRef.current.textContent = elapsed.toFixed(1) + "s";
const next = phraseFor(elapsed);
if (next !== lastPhrase && phraseTextRef.current) {
phraseTextRef.current.textContent = next;
lastPhrase = next;
}
rafId = requestAnimationFrame(tick);
};
rafId = requestAnimationFrame(tick);
return () => cancelAnimationFrame(rafId);
}, [startedAt]);
return (
<div className="flex items-center gap-2 text-fg-muted">
<span
aria-hidden
className="inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-border-strong border-t-accent"
/>
<span className="text-fg">
<span ref={phraseTextRef}>Thinking</span>
<span aria-hidden className="thinking-dots ml-0.5">
<span>.</span>
<span>.</span>
<span>.</span>
</span>
</span>
{model && <span className="hidden text-fg-subtle sm:inline">· {model}</span>}
<span ref={elapsedRef} className="ml-auto tabular-nums text-fg-subtle">
0.0s
</span>
</div>
);
});
interface HotkeyBinding {
ctrl: boolean;
alt: boolean;
shift: boolean;
meta: boolean;
code: string; // DOM KeyboardEvent.code, e.g. "KeyG"
}
const DEFAULT_HOTKEY: HotkeyBinding = {
ctrl: true,
alt: true,
shift: false,
meta: false,
code: "KeyG",
};
function sameHotkey(a: HotkeyBinding, b: HotkeyBinding): boolean {
return (
a.ctrl === b.ctrl &&
a.alt === b.alt &&
a.shift === b.shift &&
a.meta === b.meta &&
a.code === b.code
);
}
function formatHotkey(h: HotkeyBinding): string {
const parts: string[] = [];
if (h.ctrl) parts.push("Ctrl");
if (h.alt) parts.push("Alt");
if (h.shift) parts.push("Shift");
if (h.meta) parts.push("Win");
parts.push(prettyKeyCode(h.code));
return parts.join(" + ");
}
function keyMatchesBinding(e: KeyboardEvent, b: HotkeyBinding): boolean {
// Treat numpad Enter as the same physical key for binding purposes.
const eCode = e.code === "NumpadEnter" ? "Enter" : e.code;
const bCode = b.code === "NumpadEnter" ? "Enter" : b.code;
return (
eCode === bCode &&
e.ctrlKey === b.ctrl &&
e.altKey === b.alt &&
e.shiftKey === b.shift &&
e.metaKey === b.meta
);
}
type BubbleShortcutId =
| "improve"
| "grammar"
| "shorten"
| "expand"
| "custom"
| "accept"
| "regenerate";
type BubbleShortcuts = Record<BubbleShortcutId, HotkeyBinding>;
const DEFAULT_BUBBLE_SHORTCUTS: BubbleShortcuts = {
improve: { ctrl: false, alt: false, shift: false, meta: false, code: "Digit1" },
grammar: { ctrl: false, alt: false, shift: false, meta: false, code: "Digit2" },
shorten: { ctrl: false, alt: false, shift: false, meta: false, code: "Digit3" },
expand: { ctrl: false, alt: false, shift: false, meta: false, code: "Digit4" },
custom: { ctrl: false, alt: false, shift: false, meta: false, code: "KeyC" },
accept: { ctrl: false, alt: false, shift: false, meta: false, code: "Enter" },
regenerate: { ctrl: false, alt: false, shift: false, meta: false, code: "KeyR" },
};
function prettyKeyCode(code: string): string {
if (code.startsWith("Key") && code.length === 4) return code.slice(3);
if (code.startsWith("Digit") && code.length === 6) return code.slice(5);
if (/^F\d{1,2}$/.test(code)) return code;
switch (code) {
case "Space": return "Space";
case "Tab": return "Tab";
case "Enter": return "Enter";
case "Backspace": return "Backspace";
case "ArrowUp": return "↑";
case "ArrowDown": return "↓";
case "ArrowLeft": return "←";
case "ArrowRight": return "→";
case "Comma": return ",";
case "Period": return ".";
case "Slash": return "/";
case "Backquote": return "`";
case "Minus": return "-";
case "Equal": return "=";
case "Semicolon": return ";";
case "Quote": return "'";
case "BracketLeft": return "[";
case "BracketRight": return "]";
case "Backslash": return "\\";
default: return code;
}
}
// Catalog of supported model providers. "ollama-cloud" / "ollama-local" are
// the original two; the rest were added as part of the multi-provider rollout.
// Legacy "cloud" / "local" values in localStorage are migrated below.
type Provider =
| "ollama-cloud"
| "ollama-local"
| "gemini"
| "openai"
| "anthropic"
| "groq"
| "openrouter";
// "free" — runs on the user's hardware, no key required.
// "free-tier" — cloud provider with a free quota; BYO key.
// "byok" — cloud provider, paid-only; BYO key.
type ProviderTier = "free" | "free-tier" | "byok";
const PROVIDER_LABELS: Record<Provider, string> = {
"ollama-cloud": "Ollama Cloud",
"ollama-local": "Local Ollama",
"gemini": "Google Gemini",
"openai": "OpenAI",
"anthropic": "Anthropic",
"groq": "Groq",
"openrouter": "OpenRouter",
};
const PROVIDER_DEFAULTS: Record<
Provider,
{ baseUrl: string; model: string; needsKey: boolean; tier: ProviderTier; keyHint?: string }
> = {
"ollama-cloud": { baseUrl: "https://ollama.com", model: "gemma4:31b-cloud", needsKey: true, tier: "free-tier", keyHint: "ollama-…" },
"ollama-local": { baseUrl: "http://localhost:11434", model: "llama3.2", needsKey: false, tier: "free" },
"gemini": { baseUrl: "https://generativelanguage.googleapis.com", model: "gemini-2.5-flash", needsKey: true, tier: "free-tier", keyHint: "AIza…" },
"openai": { baseUrl: "https://api.openai.com", model: "gpt-4.1-mini", needsKey: true, tier: "byok", keyHint: "sk-…" },
"anthropic": { baseUrl: "https://api.anthropic.com", model: "claude-sonnet-4-6", needsKey: true, tier: "byok", keyHint: "sk-ant-…" },
"groq": { baseUrl: "https://api.groq.com", model: "llama-3.3-70b-versatile", needsKey: true, tier: "free-tier", keyHint: "gsk_…" },
"openrouter": { baseUrl: "https://openrouter.ai", model: "anthropic/claude-sonnet-4", needsKey: true, tier: "free-tier", keyHint: "sk-or-…" },
};
// Display order for the Settings → Provider dropdown. Free / free-tier on top
// so users land on a zero-cost path; default (ollama-cloud) is first within
// that group so it stays the obvious choice for new installs.
const PROVIDER_ORDER: Provider[] = [
"ollama-cloud",
"ollama-local",
"gemini",
"groq",
"openrouter",
"openai",
"anthropic",
];
function providerTierLabel(p: Provider): string {
const t = PROVIDER_DEFAULTS[p].tier;
if (t === "free") return "Free";
if (t === "free-tier") return "Free tier · BYO key";
return "BYO key";
}
interface SavedTemplate {
id: string;
name: string;
prompt: string;
}
type ViewMode = "rendered" | "diff";
type PopupAnchor = "mouse" | "selection" | "center";
interface OllamaSettings {
provider: Provider;
baseUrl: string;
model: string;
apiKey: string;
educational: boolean;
affirm: boolean;
hotkey: HotkeyBinding;
bubbleShortcuts: BubbleShortcuts;
// v2 additions — all optional via DEFAULT_SETTINGS so older payloads merge
// cleanly. See loadSettings for migration of legacy provider values.
viewMode: ViewMode;
lastAction: ActionId | null;
customPromptHistory: string[];
savedTemplates: SavedTemplate[];
styleGuide: string;
protectedTerms: string;
pasteFormat: "plain" | "markdown";
clickOutsideDismiss: boolean;
autostart: boolean;
hasOnboarded: boolean;
originalExpanded: boolean;
popupAnchor: PopupAnchor;
}
const DEFAULT_SETTINGS: OllamaSettings = {
provider: "ollama-cloud",
baseUrl: "https://ollama.com",
model: "gemma4:31b-cloud",
apiKey: "",
educational: false,
affirm: false,
hotkey: DEFAULT_HOTKEY,
bubbleShortcuts: DEFAULT_BUBBLE_SHORTCUTS,
viewMode: "rendered",
lastAction: null,
customPromptHistory: [],
savedTemplates: [],
styleGuide: "",
protectedTerms: "",
pasteFormat: "plain",
clickOutsideDismiss: true,
autostart: false,
hasOnboarded: false,
originalExpanded: false,
popupAnchor: "mouse",
};
const SETTINGS_KEY = "r3write.settings.v1";
function loadSettings(): OllamaSettings {
try {
const raw = localStorage.getItem(SETTINGS_KEY);
if (!raw) return DEFAULT_SETTINGS;
const parsed = JSON.parse(raw) as Partial<OllamaSettings> & { provider?: string };
// Migrate legacy provider names from v1 ("cloud"/"local") into the new
// multi-provider taxonomy. Anything else passes through.
let provider = parsed.provider as Provider | undefined;
if ((parsed.provider as string) === "cloud") provider = "ollama-cloud";
else if ((parsed.provider as string) === "local") provider = "ollama-local";
const merged: OllamaSettings = {
...DEFAULT_SETTINGS,
...parsed,
provider: provider ?? DEFAULT_SETTINGS.provider,
};
// Deep-merge bubbleShortcuts so storing an older partial set doesn't drop
// any of the keys the runtime expects.
merged.bubbleShortcuts = {
...DEFAULT_BUBBLE_SHORTCUTS,
...(parsed.bubbleShortcuts || {}),
};
return merged;
} catch {
return DEFAULT_SETTINGS;
}
}
function saveSettings(s: OllamaSettings) {
// apiKey is persisted via Windows Credential Manager (see saveApiKey),
// never written to localStorage.
const sanitized = { ...s, apiKey: "" };
localStorage.setItem(SETTINGS_KEY, JSON.stringify(sanitized));
}
// Read-modify-write helper for cross-window settings nudges (e.g. the popup
// persisting viewMode or lastAction without trampling fields it never touched).
function patchSettings(patch: Partial<OllamaSettings>): OllamaSettings {
const current = loadSettings();
const next = { ...current, ...patch };
saveSettings(next);
return next;
}
// Each provider gets its own keyring entry so switching providers doesn't
// drop the user's other keys. Backwards-compat: the legacy entry name was
// `ollama-api-key`; it now belongs to ollama-cloud.
function apiKeyEntryName(provider: Provider): string {
if (provider === "ollama-cloud") return "ollama-api-key";
return `r3write-api-key-${provider}`;
}
export const API_KEY_NAME = apiKeyEntryName("ollama-cloud");
async function loadApiKey(provider: Provider = "ollama-cloud"): Promise<string> {
try {
const v = await invoke<string | null>("secret_get", { name: apiKeyEntryName(provider) });
return v ?? "";
} catch (e) {
console.error("[r3write] secret_get failed:", e);
return "";
}
}
async function saveApiKey(provider: Provider, key: string): Promise<void> {
try {
if (key) {
await invoke("secret_set", { name: apiKeyEntryName(provider), value: key });
} else {
await invoke("secret_delete", { name: apiKeyEntryName(provider) });
}
} catch (e) {
console.error("[r3write] secret persistence failed:", e);
}
}
async function clearApiKeyFor(provider: Provider): Promise<void> {
try {
await invoke("secret_delete", { name: apiKeyEntryName(provider) });
} catch (e) {
console.error("[r3write] secret_delete failed:", e);
}
}
// In production builds the Tauri webview's URL is `http://tauri.localhost`,
// and tauri-plugin-http auto-injects that as the `Origin` header on every
// request unless we explicitly set one. Ollama's CORS check rejects unknown
// origins with a flat 403 — including the local server on `localhost:11434`.
// Match Origin to the target URL's own origin so Ollama always sees a
// same-origin request and accepts it.
function originFor(baseUrl: string): string {
try {
return new URL(baseUrl).origin;
} catch {
return baseUrl;
}
}
function defaultsForProvider(provider: Provider): Pick<OllamaSettings, "baseUrl" | "model"> {
const d = PROVIDER_DEFAULTS[provider];
return { baseUrl: d.baseUrl, model: d.model };
}
// True when the provider speaks the Ollama /api/chat dialect. All Ollama-style
// servers stream NDJSON of `{ message: { content }, done }`. OpenAI-compatible
// providers stream SSE (`data: { choices: [...] }`). Anthropic streams a
// different SSE shape with `content_block_delta` events.
function isOllamaStyle(p: Provider): boolean {
return p === "ollama-cloud" || p === "ollama-local";
}
function isOpenAIStyle(p: Provider): boolean {
return p === "openai" || p === "groq" || p === "openrouter";
}
function isGemini(p: Provider): boolean {
return p === "gemini";
}
// ---------- Streaming clients ----------
//
// One client per dialect family; the factory at the bottom picks based on
// settings.provider. All clients yield raw text deltas; the caller buffers,
// concatenates, and renders.
// Stream Server-Sent Events as `data: {…}` lines. Yields each parsed object.
async function* parseSse(
body: ReadableStream<Uint8Array>,
signal?: AbortSignal,
): AsyncIterable<unknown> {
const reader = body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
if (signal?.aborted) return;
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) !== -1) {
const line = buf.slice(0, nl).trimEnd();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const payload = line.slice(5).trim();
if (!payload || payload === "[DONE]") continue;
try {
yield JSON.parse(payload);
} catch {
// Tolerate keep-alive comments and partial frames; the next chunk
// will deliver a complete one.
}
}
}
}
class OllamaClient implements LLMClient {
constructor(private settings: OllamaSettings) {}
async *chat(
messages: ChatMessage[],
opts?: { signal?: AbortSignal },
): AsyncIterable<string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
Origin: originFor(this.settings.baseUrl),
};
if (this.settings.provider === "ollama-cloud") {
// Prefer the in-memory key so Settings → Test works with an unsaved
// draft. Fall back to the keyring so the quick-edit popup — which is
// a separate window and may have mounted before the key was saved —
// picks up the current value.
const apiKey = this.settings.apiKey || (await loadApiKey(this.settings.provider));
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
}
const body = JSON.stringify({
model: this.settings.model,
stream: true,
messages,
});
const res = await tauriFetch(`${this.settings.baseUrl.replace(/\/$/, "")}/api/chat`, {
method: "POST",
headers,
body,
signal: opts?.signal,
});
if (!res.ok || !res.body) {
throw new Error(`Ollama HTTP ${res.status}: ${await res.text().catch(() => "")}`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
if (opts?.signal?.aborted) return;
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) !== -1) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line) continue;
try {
const obj = JSON.parse(line) as {
message?: { content?: string };
done?: boolean;
error?: string;
};
if (obj.error) throw new Error(obj.error);
const piece = obj.message?.content;
if (piece) yield piece;
if (obj.done) return;
} catch (e) {
if (e instanceof SyntaxError) continue;
throw e;
}
}
}
}
async *rewrite(
input: string,
action: ActionId,
opts?: RewriteOptions,
): AsyncIterable<string> {
const instruction = actionInstruction(action, opts?.customPrompt);
yield* this.chat(
[
{ role: "system", content: buildSystemPrompt(this.settings) },
{ role: "user", content: `${instruction}\n\nText:\n${input}` },
],
{ signal: opts?.signal },
);
}
}
// OpenAI, Groq, and OpenRouter all speak the same /v1/chat/completions
// dialect, just at different base URLs. Same streaming format too.
class OpenAIStyleClient implements LLMClient {
constructor(private settings: OllamaSettings) {}
private endpoint(): string {
const base = this.settings.baseUrl.replace(/\/$/, "");
// OpenRouter doesn't include /v1 in its conventional base URL; the others do.
if (this.settings.provider === "openrouter") return `${base}/api/v1/chat/completions`;
return `${base}/v1/chat/completions`;
}
async *chat(
messages: ChatMessage[],
opts?: { signal?: AbortSignal },
): AsyncIterable<string> {
const apiKey = this.settings.apiKey || (await loadApiKey(this.settings.provider));
if (!apiKey) throw new Error(`${PROVIDER_LABELS[this.settings.provider]}: API key not set`);
const headers: Record<string, string> = {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
Origin: originFor(this.settings.baseUrl),
};
if (this.settings.provider === "openrouter") {
headers["HTTP-Referer"] = "https://r3write.app";
headers["X-Title"] = "R3write";
}
const res = await tauriFetch(this.endpoint(), {
method: "POST",
headers,
body: JSON.stringify({
model: this.settings.model,
stream: true,
messages,
}),
signal: opts?.signal,
});
if (!res.ok || !res.body) {
throw new Error(
`${PROVIDER_LABELS[this.settings.provider]} HTTP ${res.status}: ${await res.text().catch(() => "")}`,
);
}
for await (const event of parseSse(res.body, opts?.signal)) {
const obj = event as {
choices?: { delta?: { content?: string } }[];
error?: { message?: string };
};
if (obj.error) throw new Error(obj.error.message ?? "Provider error");
const piece = obj.choices?.[0]?.delta?.content;
if (piece) yield piece;
}
}
async *rewrite(input: string, action: ActionId, opts?: RewriteOptions): AsyncIterable<string> {
const instruction = actionInstruction(action, opts?.customPrompt);
yield* this.chat(
[
{ role: "system", content: buildSystemPrompt(this.settings) },
{ role: "user", content: `${instruction}\n\nText:\n${input}` },
],
{ signal: opts?.signal },
);
}
}
// Anthropic's Messages API is similar but takes the system prompt out-of-band
// and streams content_block_delta events.
class AnthropicClient implements LLMClient {
constructor(private settings: OllamaSettings) {}
async *chat(
messages: ChatMessage[],
opts?: { signal?: AbortSignal },
): AsyncIterable<string> {
const apiKey = this.settings.apiKey || (await loadApiKey(this.settings.provider));
if (!apiKey) throw new Error("Anthropic: API key not set");
const system = messages.find((m) => m.role === "system")?.content;
const turns = messages
.filter((m) => m.role !== "system")
.map((m) => ({ role: m.role, content: m.content }));
const res = await tauriFetch(`${this.settings.baseUrl.replace(/\/$/, "")}/v1/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true",
Origin: originFor(this.settings.baseUrl),
},
body: JSON.stringify({
model: this.settings.model,
max_tokens: 4096,
stream: true,
system,
messages: turns,
}),
signal: opts?.signal,
});
if (!res.ok || !res.body) {
throw new Error(`Anthropic HTTP ${res.status}: ${await res.text().catch(() => "")}`);
}
for await (const event of parseSse(res.body, opts?.signal)) {
const obj = event as {
type?: string;
delta?: { type?: string; text?: string };
error?: { message?: string };
};
if (obj.error) throw new Error(obj.error.message ?? "Anthropic error");
if (obj.type === "content_block_delta" && obj.delta?.type === "text_delta") {
if (obj.delta.text) yield obj.delta.text;
}
}
}
async *rewrite(input: string, action: ActionId, opts?: RewriteOptions): AsyncIterable<string> {
const instruction = actionInstruction(action, opts?.customPrompt);
yield* this.chat(
[
{ role: "system", content: buildSystemPrompt(this.settings) },
{ role: "user", content: `${instruction}\n\nText:\n${input}` },
],
{ signal: opts?.signal },
);
}
}
// Gemini's Generative Language API takes the system prompt out-of-band via
// `systemInstruction`, names the assistant role `model`, and wraps text in a
// `parts: [{text}]` envelope. Streams SSE on `:streamGenerateContent?alt=sse`.
class GeminiClient implements LLMClient {
constructor(private settings: OllamaSettings) {}
async *chat(
messages: ChatMessage[],
opts?: { signal?: AbortSignal },
): AsyncIterable<string> {
const apiKey = this.settings.apiKey || (await loadApiKey(this.settings.provider));
if (!apiKey) throw new Error("Gemini: API key not set");
const system = messages.find((m) => m.role === "system")?.content;
const contents = messages
.filter((m) => m.role !== "system")
.map((m) => ({
role: m.role === "assistant" ? "model" : "user",
parts: [{ text: m.content }],
}));
const base = this.settings.baseUrl.replace(/\/$/, "");
const url = `${base}/v1beta/models/${encodeURIComponent(this.settings.model)}:streamGenerateContent?alt=sse`;
const res = await tauriFetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-goog-api-key": apiKey,
Origin: originFor(this.settings.baseUrl),
},
body: JSON.stringify({
contents,
...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
generationConfig: { maxOutputTokens: 4096 },
}),
signal: opts?.signal,
});
if (!res.ok || !res.body) {
throw new Error(`Gemini HTTP ${res.status}: ${await res.text().catch(() => "")}`);
}
for await (const event of parseSse(res.body, opts?.signal)) {
const obj = event as {
candidates?: { content?: { parts?: { text?: string }[] } }[];
error?: { message?: string };
};
if (obj.error) throw new Error(obj.error.message ?? "Gemini error");
const parts = obj.candidates?.[0]?.content?.parts;
if (parts) {
for (const p of parts) {
if (p.text) yield p.text;
}
}
}
}
async *rewrite(input: string, action: ActionId, opts?: RewriteOptions): AsyncIterable<string> {
const instruction = actionInstruction(action, opts?.customPrompt);
yield* this.chat(
[
{ role: "system", content: buildSystemPrompt(this.settings) },
{ role: "user", content: `${instruction}\n\nText:\n${input}` },
],
{ signal: opts?.signal },
);
}
}
function makeClient(settings: OllamaSettings): LLMClient {
if (isOpenAIStyle(settings.provider)) return new OpenAIStyleClient(settings);
if (settings.provider === "anthropic") return new AnthropicClient(settings);
if (isGemini(settings.provider)) return new GeminiClient(settings);
return new OllamaClient(settings);
}