diff options
| -rw-r--r-- | desktop/modules/assistant/AssistantModule.qml | 29 | ||||
| -rw-r--r-- | desktop/modules/assistant/AssistantPage.qml | 60 | ||||
| -rw-r--r-- | desktop/modules/assistant/Config.js | 12 | ||||
| -rw-r--r-- | desktop/modules/assistant/README.md | 10 | ||||
| -rw-r--r-- | desktop/modules/assistant/test_config.js | 13 |
5 files changed, 93 insertions, 31 deletions
diff --git a/desktop/modules/assistant/AssistantModule.qml b/desktop/modules/assistant/AssistantModule.qml index 6aefb1f..b56b163 100644 --- a/desktop/modules/assistant/AssistantModule.qml +++ b/desktop/modules/assistant/AssistantModule.qml @@ -79,7 +79,8 @@ Module { property var fetched: ({}) property string fetching: "" // Tool switches flipped but not saved: name -> wanted on; and the same - // for each tool's cloud = true, which offers it to cloud chats. + // for each tool's cloud: true (every cloud chat), "safe" (chats with a + // provider marked safe) or false. property var toolsWanted: ({}) property var cloudWanted: ({}) // Fields holding a value that cannot be written; Save waits for none. @@ -227,10 +228,10 @@ Module { function setEnv(key, value) { am.draft = C.setEnv(am.draft, key, value); } function quote(s) { return C.quote(s); } - // patch is {name}, {url}, {key_cmd} or {models}; i === cloudCount adds one. + // patch is {name}, {url}, {key_cmd}, {models} or {safe}; i === cloudCount adds one. function editCloud(i, patch) { const list = (am.clouds ?? []).map(c => Object.assign({}, c)); - if (i === list.length) list.push({ name: "", url: "", key_cmd: "", models: [] }); + if (i === list.length) list.push({ name: "", url: "", key_cmd: "", models: [], safe: false }); Object.assign(list[i], patch); am.draft = C.setClouds(am.draft, list); } @@ -259,7 +260,8 @@ Module { + " on = p.endswith('.toml')\n" + " name = os.path.basename(p).removesuffix('.off').removesuffix('.toml')\n" + " try:\n t = tomllib.load(open(p, 'rb'))\n" - + " d, cloud = t.get('description', ''), t.get('cloud') is True\n" + + " d, c = t.get('description', ''), t.get('cloud')\n" + + " cloud = c if c is True or c == 'safe' else False\n" + " except Exception as e:\n d, cloud = f'unreadable: {e}', False\n" + " out.append({'name': name, 'on': on, 'cloud': cloud, 'description': d})\n" + "print(json.dumps(sorted(out, key=lambda t: t['name'])))\n" @@ -277,25 +279,30 @@ Module { if (!am.toolOn(t) === t.on) delete next[t.name]; else next[t.name] = !am.toolOn(t); am.toolsWanted = next; } - // Whether a tool goes to cloud chats in the draft, as toolOn. + // Where a tool goes in the draft, as toolOn: true, "safe" or false. function toolCloud(t) { return am.cloudWanted[t.name] ?? t.cloud; } - function toggleCloud(t) { + function setCloud(t, v) { const next = Object.assign({}, am.cloudWanted); - if (!am.toolCloud(t) === t.cloud) delete next[t.name]; else next[t.name] = !am.toolCloud(t); + if (v === t.cloud) delete next[t.name]; else next[t.name] = v; + am.cloudWanted = next; + } + function setAllCloud(v) { + const next = {}; + for (const t of am.tools) if (t.cloud !== v) next[t.name] = v; am.cloudWanted = next; } - // Sets or drops a tool file's top-level cloud line, validated with + // Sets (all: true, safe: "safe") or drops (off) a tool file's top-level cloud line, validated with // tomllib and replaced atomically, like config.toml. The file is // name.toml or, switched off, name.toml.off. Added as the first line: // a top-level key is valid there whatever the file holds below. readonly property string clouder: "import os, re, sys, tomllib\n" - + "p, on = sys.argv[1], sys.argv[2] == '1'\n" + + "p, v = sys.argv[1], sys.argv[2]\n" + "if not os.path.exists(p):\n p += '.off'\n" + "lines = open(p).read().split('\\n')\n" + "head = next((i for i, l in enumerate(lines) if l.lstrip().startswith('[')), len(lines))\n" + "lines = [l for i, l in enumerate(lines) if i >= head or not re.match(r'\\s*cloud\\s*=', l)]\n" - + "if on:\n lines.insert(0, 'cloud = true')\n" + + "if v != 'off':\n lines.insert(0, 'cloud = true' if v == 'all' else 'cloud = \"safe\"')\n" + "t = '\\n'.join(lines)\n" + "try:\n tomllib.loads(t)\n" + "except tomllib.TOMLDecodeError as e:\n sys.exit(f'{os.path.basename(p)}: not valid TOML: {e}')\n" @@ -307,7 +314,7 @@ Module { if (names.length === 0) { done(); return; } const name = names[0]; am.run([am.python, "-c", am.clouder, am.toolsDir + "/" + name + ".toml", - am.cloudWanted[name] ? "1" : "0"], null, (code, out, err) => { + {"true": "all", "safe": "safe"}[String(am.cloudWanted[name])] ?? "off"], null, (code, out, err) => { if (code !== 0) { am.error = err.trim() || "could not change " + name; am.listTools(); return; } const next = Object.assign({}, am.cloudWanted); delete next[name]; diff --git a/desktop/modules/assistant/AssistantPage.qml b/desktop/modules/assistant/AssistantPage.qml index a952b4f..680692f 100644 --- a/desktop/modules/assistant/AssistantPage.qml +++ b/desktop/modules/assistant/AssistantPage.qml @@ -444,7 +444,8 @@ Column { wrapMode: Text.Wrap text: "Providers with an OpenAI-compatible API, offered in the canvas's model menu. A cloud " + "chat is sent its history, attachments and the results of the tools marked " - + "cloud = true; voice is still transcribed here. The key command prints the API key: " + + "set to All cloud, and to Safe too when the provider is marked safe (trusted, no " + + "retention); voice is still transcribed here. The key command prints the API key: " + "the assistant runs it at startup and on Fetch, which saves this page first." } @@ -462,7 +463,7 @@ Column { delegate: Rectangle { id: prov required property int index - readonly property var c: page.asst.clouds?.[index] ?? { name: "", url: "", key_cmd: "", models: [] } + readonly property var c: page.asst.clouds?.[index] ?? { name: "", url: "", key_cmd: "", models: [], safe: false } readonly property var got: page.asst.fetched[prov.c.name] objectName: "cloud:" + index width: page.width @@ -505,6 +506,22 @@ Column { onEdited: t => page.asst.editCloud(prov.index, { key_cmd: t.trim() }) } } + Item { + width: provCol.width + height: 28 + Switch { + id: safeSw + anchors { left: parent.left; verticalCenter: parent.verticalCenter } + checked: prov.c.safe + onToggled: on => page.asst.editCloud(prov.index, { safe: on }) + } + Text { + anchors { left: safeSw.right; leftMargin: 10; verticalCenter: parent.verticalCenter } + text: "Safe: also gets the tools set to Safe" + color: prov.c.safe ? Theme.text : Theme.subtext + font { family: Theme.fontFamily; pixelSize: Theme.fontSize - 3 } + } + } Row { spacing: 6 Button { @@ -664,7 +681,25 @@ Column { width: page.width wrapMode: Text.Wrap text: "What the model may call. Off renames the file to .toml.off, which the daemon skips. " - + "Cloud also offers it to cloud chats, which then receive its results." + + "Local keeps it out of cloud chats; Safe offers it to providers marked safe, All cloud " + + "to every provider. Those chats then receive its results." + } + + Row { + spacing: 6 + Button { text: "All tools: Safe"; onClicked: page.asst.setAllCloud("safe") } + Button { text: "All tools: All cloud"; onClicked: page.asst.setAllCloud(true) } + } + + // Safe goes nowhere until a provider is marked safe: say so rather + // than look like it reaches the cloud. + Small { + width: page.width + visible: !(page.asst.clouds ?? []).some(c => c.safe) + && page.asst.tools.some(t => page.asst.toolCloud(t) === "safe") + wrapMode: Text.Wrap + text: "No provider is marked safe: tools set to Safe reach no cloud chat." + color: Theme.red } Repeater { @@ -683,18 +718,27 @@ Column { checked: page.asst.toolOn(toolRow.modelData) onToggled: page.asst.toggleTool(toolRow.modelData) } - // nf-fa-cloud, then the tool's cloud = true. - Switch { + // nf-fa-cloud, then the tool's cloud: false, "safe" or true. + Row { id: cloudSw anchors { right: parent.right; verticalCenter: parent.verticalCenter } - checked: page.asst.toolCloud(toolRow.modelData) - onToggled: page.asst.toggleCloud(toolRow.modelData) + spacing: 4 + Repeater { + model: [[false, "Local"], ["safe", "Safe"], [true, "All cloud"]] + delegate: Button { + required property var modelData + text: modelData[1] + color: page.asst.toolCloud(toolRow.modelData) === modelData[0] + ? Qt.alpha(Theme.accent, 0.45) : Qt.alpha(Theme.surface, 0.8) + onClicked: page.asst.setCloud(toolRow.modelData, modelData[0]) + } + } } Text { id: cloudMark anchors { right: cloudSw.left; rightMargin: 8; verticalCenter: parent.verticalCenter } text: "\uf0c2" - color: page.asst.toolCloud(toolRow.modelData) ? Theme.text : Theme.subtext + color: page.asst.toolCloud(toolRow.modelData) !== false ? Theme.text : Theme.subtext font { family: Theme.iconFamily; pixelSize: Theme.fontSize - 4 } } Column { diff --git a/desktop/modules/assistant/Config.js b/desktop/modules/assistant/Config.js index 4c71b14..5c76e3b 100644 --- a/desktop/modules/assistant/Config.js +++ b/desktop/modules/assistant/Config.js @@ -142,8 +142,9 @@ function setEnv(text, key, val) { return lines.join("\n"); } -// [[cloud]] tables, the daemon's providers: name, url and key_cmd strings -// and a one-line models array, as setClouds writes them. +// [[cloud]] tables, the daemon's providers: name, url and key_cmd strings, +// a one-line models array and an optional safe boolean, as setClouds +// writes them. const CLOUD = /^\s*\[\[cloud\]\]\s*(#.*)?$/; // A one-line array of strings, ["a", "b"]; null for anything else. @@ -175,14 +176,14 @@ function cloudBlocks(lines) { return out; } -// [{name, url, key_cmd, models}] in file order, or null when a table holds +// [{name, url, key_cmd, models, safe}] in file order, or null when a table holds // a line this cannot read (a multi-line array, another key): the page then // leaves them to be edited by hand rather than rewrite what it did not read. function clouds(text) { const lines = text.split("\n"); const out = []; for (const b of cloudBlocks(lines)) { - const c = { name: "", url: "", key_cmd: "", models: [] }; + const c = { name: "", url: "", key_cmd: "", models: [], safe: false }; for (let i = b.start + 1; i < b.end; i++) { if (/^\s*(#.*)?$/.test(lines[i])) continue; const m = KEY.exec(lines[i]); @@ -191,6 +192,8 @@ function clouds(text) { const a = strings(m[4]); if (a === null) return null; c.models = a; + } else if (m[3] === "safe" && /^(true|false)\s*(#.*)?$/.test(m[4])) { + c.safe = m[4].startsWith("true"); } else if (["name", "url", "key_cmd"].includes(m[3]) && m[4].startsWith('"')) { c[m[3]] = value(m[4]).v; } else return null; @@ -209,6 +212,7 @@ function setClouds(text, list) { for (const c of list) lines.push("", "[[cloud]]", "name = " + quote(c.name), "url = " + quote(c.url), "key_cmd = " + quote(c.key_cmd), + ...(c.safe ? ["safe = true"] : []), "models = [" + c.models.map(quote).join(", ") + "]"); return lines.join("\n") + "\n"; } diff --git a/desktop/modules/assistant/README.md b/desktop/modules/assistant/README.md index a1ce840..c16e594 100644 --- a/desktop/modules/assistant/README.md +++ b/desktop/modules/assistant/README.md @@ -13,12 +13,14 @@ are never copied here. A refused number is outlined and holds Save back. The system prompt also has "Use the default". The tool environment (`[env]`) is one row per key, with an add row below. A tool's switch, once saved, renames `tools/<name>.toml` -to `<name>.toml.off`, which the daemon's `*.toml` glob skips. Its cloud switch sets or drops -`cloud = true` at the top of the file, which offers the tool to cloud -chats; the file is checked with `tomllib` and replaced atomically. +to `<name>.toml.off`, which the daemon's `*.toml` glob skips. Its Local / Safe / All cloud +choice drops the `cloud` line or sets `cloud = "safe"` (only providers +marked safe) or `cloud = true` (every provider) at the top of the file; +"All tools" sets every tool at once, in the draft. The file is checked with `tomllib` and replaced atomically. **Cloud** edits the daemon's `[[cloud]]` tables: name, URL and key -command per provider. Fetch saves the page, then runs `assistant.py +command per provider, and Safe, which also gives it the tools set to +Safe. Fetch saves the page, then runs `assistant.py --cloud-models <name>`, which runs the key command and lists the provider's ids; the switches choose which the canvas offers. The key never reaches this page. A table holding more than the page writes (a diff --git a/desktop/modules/assistant/test_config.js b/desktop/modules/assistant/test_config.js index f79f4e1..b3e9f0f 100644 --- a/desktop/modules/assistant/test_config.js +++ b/desktop/modules/assistant/test_config.js @@ -93,6 +93,7 @@ const withCloud = file + [ 'name = "hetzner"', 'url = "https://llm.example.org/v1" # a comment', 'key_cmd = "pass llm/x"', + "safe = true", 'models = ["a/b", "c:d"]', "", "[[cloud]]", @@ -103,16 +104,20 @@ const withCloud = file + [ "", ].join("\n"); assert.deepStrictEqual(C.clouds(withCloud), [ - { name: "hetzner", url: "https://llm.example.org/v1", key_cmd: "pass llm/x", models: ["a/b", "c:d"] }, - { name: "two", url: "u", key_cmd: "k", models: [] }]); + { name: "hetzner", url: "https://llm.example.org/v1", key_cmd: "pass llm/x", models: ["a/b", "c:d"], safe: true }, + { name: "two", url: "u", key_cmd: "k", models: [], safe: false }]); +assert.strictEqual(C.clouds(withCloud.replace("safe = true", 'safe = "yes"')), null); assert.deepStrictEqual(C.clouds(file), []); assert.deepStrictEqual(C.env(withCloud), C.env(file)); // [env] ends at the table // A table this cannot read in full is not offered for editing. assert.strictEqual(C.clouds(withCloud.replace('models = ["a/b", "c:d"]', 'models = [\n "a/b",\n]')), null); assert.strictEqual(C.clouds(withCloud.replace('name = "two"', 'name = "two"\nextra = 1')), null); // Rewritten at the end of the file; everything else stays. -const one = C.setClouds(withCloud, [{ name: "n", url: "u", key_cmd: 'pass "q"', models: ["m"] }]); -assert.deepStrictEqual(C.clouds(one), [{ name: "n", url: "u", key_cmd: 'pass "q"', models: ["m"] }]); +const one = C.setClouds(withCloud, [{ name: "n", url: "u", key_cmd: 'pass "q"', models: ["m"], safe: false }]); +assert.deepStrictEqual(C.clouds(one), [{ name: "n", url: "u", key_cmd: 'pass "q"', models: ["m"], safe: false }]); +assert.ok(!one.includes("safe"), one); // false is left out +const safe = C.setClouds(one, [{ name: "n", url: "u", key_cmd: "k", models: [], safe: true }]); +assert.strictEqual(C.clouds(safe)[0].safe, true); assert.deepStrictEqual(C.env(one), C.env(file)); assert.deepStrictEqual(C.scalars(one, KEYS), C.scalars(file, KEYS)); assert.ok(one.includes("# Cloud models.") && one.endsWith('models = ["m"]\n'), one); |
