Compare commits
No commits in common. "main" and "codex/modify-details.js-to-request-message-ids" have entirely different histories.
main
...
codex/modi
11
AGENTS.md
|
@ -5,9 +5,8 @@ This file provides guidelines for codex agents contributing to the Sortana proje
|
||||||
## Repository Overview
|
## Repository Overview
|
||||||
|
|
||||||
- `background.js`: Handles startup tasks and coordinates message passing within the extension.
|
- `background.js`: Handles startup tasks and coordinates message passing within the extension.
|
||||||
- `modules/`: Contains reusable JavaScript modules such as `AiClassifier.js`,
|
- `modules/`: Contains reusable JavaScript modules such as `AiClassifier.js`.
|
||||||
`defaultParams.js` and `themeUtils.js`.
|
- `options/`: The options page HTML, JavaScript and Bulma CSS.
|
||||||
- `options/`: The options page HTML, JavaScript and bundled Bulma CSS (v1.0.3).
|
|
||||||
- `details.html` and `details.js`: View AI reasoning and clear cache for a message.
|
- `details.html` and `details.js`: View AI reasoning and clear cache for a message.
|
||||||
- `resources/`: Images and other static files.
|
- `resources/`: Images and other static files.
|
||||||
- `prompt_templates/`: Prompt template files for the AI service.
|
- `prompt_templates/`: Prompt template files for the AI service.
|
||||||
|
@ -28,7 +27,7 @@ This file provides guidelines for codex agents contributing to the Sortana proje
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
There are currently no automated tests for this project. If you add tests in the future, specify the commands to run them here. For now, verification must happen manually in Thunderbird. Do **not** run the `ps1` build script or the SVG processing script.
|
There are currently no automated tests for this project. If you add tests in the future, specify the commands to run them here. For now, verification must happen manually in Thunderbird.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
|
@ -42,7 +41,7 @@ Additional documentation exists outside this repository.
|
||||||
- Thunderbird Add-on Store Policies
|
- Thunderbird Add-on Store Policies
|
||||||
- [Third Party Library Usage](https://extensionworkshop.com/documentation/publish/third-party-library-usage/)
|
- [Third Party Library Usage](https://extensionworkshop.com/documentation/publish/third-party-library-usage/)
|
||||||
- Third Party Libraries
|
- Third Party Libraries
|
||||||
- [Bulma.css v1.0.3](https://github.com/jgthms/bulma/blob/1.0.3/css/bulma.css)
|
- [Bulma.css](https://github.com/jgthms/bulma)
|
||||||
- Issue tracker: [Thunderbird tracker on Bugzilla](https://bugzilla.mozilla.org/describecomponents.cgi?product=Thunderbird)
|
- Issue tracker: [Thunderbird tracker on Bugzilla](https://bugzilla.mozilla.org/describecomponents.cgi?product=Thunderbird)
|
||||||
|
|
||||||
|
|
||||||
|
@ -72,5 +71,5 @@ time the add-on loads after an update.
|
||||||
Toolbar and menu icons reside under `resources/img` and are provided in 16, 32
|
Toolbar and menu icons reside under `resources/img` and are provided in 16, 32
|
||||||
and 64 pixel variants. When changing these icons, pass a dictionary mapping the
|
and 64 pixel variants. When changing these icons, pass a dictionary mapping the
|
||||||
sizes to the paths in `browserAction.setIcon` or `messageDisplayAction.setIcon`.
|
sizes to the paths in `browserAction.setIcon` or `messageDisplayAction.setIcon`.
|
||||||
Use `resources/svg2img.ps1` to regenerate PNGs from the SVG sources.
|
Use `resources/svg/svg2img.ps1` to regenerate PNGs from the SVG sources.
|
||||||
|
|
||||||
|
|
39
README.md
|
@ -16,15 +16,11 @@ message meets a specified criterion.
|
||||||
- **Advanced parameters** – tune generation settings like temperature, top‑p and more from the options page.
|
- **Advanced parameters** – tune generation settings like temperature, top‑p and more from the options page.
|
||||||
- **Markdown conversion** – optionally convert HTML bodies to Markdown before sending them to the AI service.
|
- **Markdown conversion** – optionally convert HTML bodies to Markdown before sending them to the AI service.
|
||||||
- **Debug logging** – optional colorized logs help troubleshoot interactions with the AI service.
|
- **Debug logging** – optional colorized logs help troubleshoot interactions with the AI service.
|
||||||
- **Debug tab** – view the last request payload and a diff between the unaltered message text and the final prompt.
|
|
||||||
- **Light/Dark themes** – automatically match Thunderbird's appearance with optional manual override.
|
- **Light/Dark themes** – automatically match Thunderbird's appearance with optional manual override.
|
||||||
- **Automatic rules** – create rules that tag, move, copy, forward, reply, delete, archive, mark read/unread or flag/unflag messages based on AI classification. Rules can optionally apply only to unread messages and can ignore messages outside a chosen age range.
|
- **Automatic rules** – create rules that tag or move new messages based on AI classification.
|
||||||
- **Rule ordering** – drag rules to prioritize them and optionally stop processing after a match.
|
- **Rule ordering** – drag rules to prioritize them and optionally stop processing after a match.
|
||||||
- **Rule enable/disable** – temporarily turn a rule off without removing it.
|
|
||||||
- **Account & folder filters** – limit rules to specific accounts or folders.
|
|
||||||
- **Context menu** – apply AI rules from the message list or the message display action button.
|
- **Context menu** – apply AI rules from the message list or the message display action button.
|
||||||
- **Status icons** – toolbar icons show when classification is in progress and briefly display success states. If a failure occurs the icon turns red until you dismiss the notification.
|
- **Status icons** – toolbar icons show when classification is in progress and briefly display success or error states.
|
||||||
- **Error notification** – failed classification displays a notification with a button to clear the error and reset the icon.
|
|
||||||
- **View reasoning** – inspect why rules matched via the Details popup.
|
- **View reasoning** – inspect why rules matched via the Details popup.
|
||||||
- **Cache management** – clear cached results from the context menu or options page.
|
- **Cache management** – clear cached results from the context menu or options page.
|
||||||
- **Queue & timing stats** – monitor processing time on the Maintenance tab.
|
- **Queue & timing stats** – monitor processing time on the Maintenance tab.
|
||||||
|
@ -63,29 +59,21 @@ Sortana is implemented entirely with standard WebExtension scripts—no custom e
|
||||||
|
|
||||||
1. Ensure PowerShell is available (for Windows) or adapt the script for other
|
1. Ensure PowerShell is available (for Windows) or adapt the script for other
|
||||||
environments.
|
environments.
|
||||||
2. The Bulma stylesheet (v1.0.3) is already included as `options/bulma.css`.
|
2. Ensure the Bulma stylesheet (v1.0.4) is saved as `options/bulma.css`. You can
|
||||||
|
download it from <https://github.com/jgthms/bulma/blob/1.0.4/css/bulma.css>.
|
||||||
3. Run `powershell ./build-xpi.ps1` from the repository root. The script reads
|
3. Run `powershell ./build-xpi.ps1` from the repository root. The script reads
|
||||||
the version from `manifest.json` and creates an XPI in the `release` folder.
|
the version from `manifest.json` and creates an XPI in the `release` folder.
|
||||||
4. Install the generated XPI in Thunderbird via the Add-ons Manager. During
|
4. Install the generated XPI in Thunderbird via the Add-ons Manager. During
|
||||||
development you can also load the directory as a temporary add-on.
|
development you can also load the directory as a temporary add-on.
|
||||||
5. To regenerate PNG icons from the SVG sources, run `resources/svg2img.ps1`.
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
1. Open the add-on's options and set the URL of your classification service.
|
1. Open the add-on's options and set the URL of your classification service.
|
||||||
2. Use the **Classification Rules** section to add a criterion and optional
|
2. Use the **Classification Rules** section to add a criterion and optional
|
||||||
actions such as tagging, moving, copying, forwarding, replying,
|
actions such as tagging or moving a message when it matches. Drag rules to
|
||||||
deleting or archiving a message when it matches. Drag rules to
|
reorder them and check *Stop after match* to halt further processing.
|
||||||
reorder them, check *Only apply to unread messages* to skip read mail,
|
|
||||||
set optional minimum or maximum message age limits, select the accounts or
|
|
||||||
folders a rule should apply to. Use the
|
|
||||||
slashed-circle/check button to disable or re-enable a rule. The small
|
|
||||||
circle buttons for optional conditions show a filled dot when active, and
|
|
||||||
check *Stop after match* to halt further processing. Forward and reply actions
|
|
||||||
open a compose window using the account that received the message.
|
|
||||||
3. Save your settings. New mail will be evaluated automatically using the
|
3. Save your settings. New mail will be evaluated automatically using the
|
||||||
configured rules.
|
configured rules.
|
||||||
4. If the toolbar icon shows a red X, click the notification's **Dismiss** button to clear the error.
|
|
||||||
|
|
||||||
### Example Filters
|
### Example Filters
|
||||||
|
|
||||||
|
@ -113,7 +101,7 @@ Here are some useful and fun example criteria you can use in your filters. Filte
|
||||||
For when you're ready to filter based on vibes.
|
For when you're ready to filter based on vibes.
|
||||||
|
|
||||||
You can define as many filters as you'd like, each using a different prompt and
|
You can define as many filters as you'd like, each using a different prompt and
|
||||||
triggering tags, moves, copies, deletes, archives, read/unread changes or flag updates based on the model's classification.
|
triggering tags, moves, or actions based on the model's classification.
|
||||||
|
|
||||||
## Required Permissions
|
## Required Permissions
|
||||||
|
|
||||||
|
@ -121,14 +109,13 @@ Sortana requests the following Thunderbird permissions:
|
||||||
|
|
||||||
- `storage` – store configuration and cached classification results.
|
- `storage` – store configuration and cached classification results.
|
||||||
- `messagesRead` – read message contents for classification.
|
- `messagesRead` – read message contents for classification.
|
||||||
- `messagesMove` – move or copy messages when a rule specifies a target folder.
|
- `messagesMove` – move messages when a rule specifies a target folder.
|
||||||
- `messagesUpdate` – change message properties such as tags, junk status, read/unread state and flags.
|
- `messagesUpdate` – change message properties such as tags and junk status.
|
||||||
- `messagesTagsList` – retrieve existing message tags for rule actions.
|
- `messagesTagsList` – retrieve existing message tags for rule actions.
|
||||||
- `accountsRead` – list accounts and folders for move or copy actions.
|
- `accountsRead` – list accounts and folders for move actions.
|
||||||
- `menus` – add context menu commands.
|
- `menus` – add context menu commands.
|
||||||
- `tabs` – open new tabs and query the active tab.
|
- `tabs` – open new tabs and query the active tab.
|
||||||
- `notifications` – display error notifications.
|
- Host permissions (`*://*/*`) – allow network requests to your configured classification service.
|
||||||
- `compose` – create reply and forward compose windows for matching rules.
|
|
||||||
|
|
||||||
## Thunderbird Add-on Store Disclosures
|
## Thunderbird Add-on Store Disclosures
|
||||||
|
|
||||||
|
@ -137,12 +124,10 @@ requires disclosure of third party libraries that are included in the add-on. Ev
|
||||||
the disclosure is only required for add-on review, they'll be listed here as well. Sortana
|
the disclosure is only required for add-on review, they'll be listed here as well. Sortana
|
||||||
uses the following third party libraries:
|
uses the following third party libraries:
|
||||||
|
|
||||||
- [Bulma.css v1.0.3](https://github.com/jgthms/bulma/blob/1.0.3/css/bulma.css)
|
- [Bulma.css v1.0.4](https://github.com/jgthms/bulma/blob/1.0.4/css/bulma.css)
|
||||||
- MIT License
|
- MIT License
|
||||||
- [turndown v7.2.0](https://github.com/mixmark-io/turndown/tree/v7.2.0)
|
- [turndown v7.2.0](https://github.com/mixmark-io/turndown/tree/v7.2.0)
|
||||||
- MIT License
|
- MIT License
|
||||||
- [diff](https://github.com/google/diff-match-patch/blob/62f2e689f498f9c92dbc588c58750addec9b1654/javascript/diff_match_patch_uncompressed.js)
|
|
||||||
- Apache-2.0 license
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|
|
@ -18,20 +18,5 @@
|
||||||
"options.htmlToMarkdown": { "message": "Convert HTML body to Markdown" },
|
"options.htmlToMarkdown": { "message": "Convert HTML body to Markdown" },
|
||||||
"options.stripUrlParams": { "message": "Remove URL tracking parameters" },
|
"options.stripUrlParams": { "message": "Remove URL tracking parameters" },
|
||||||
"options.altTextImages": { "message": "Replace images with alt text" },
|
"options.altTextImages": { "message": "Replace images with alt text" },
|
||||||
"options.collapseWhitespace": { "message": "Collapse long whitespace" },
|
"options.collapseWhitespace": { "message": "Collapse long whitespace" }
|
||||||
"options.tokenReduction": { "message": "Aggressive token reduction" }
|
|
||||||
,"action.read": { "message": "read" }
|
|
||||||
,"action.flag": { "message": "flag" }
|
|
||||||
,"action.copy": { "message": "copy" }
|
|
||||||
,"action.delete": { "message": "delete" }
|
|
||||||
,"action.archive": { "message": "archive" }
|
|
||||||
,"action.forward": { "message": "forward" }
|
|
||||||
,"action.reply": { "message": "reply" }
|
|
||||||
,"param.markRead": { "message": "mark read" }
|
|
||||||
,"param.markUnread": { "message": "mark unread" }
|
|
||||||
,"param.flag": { "message": "flag" }
|
|
||||||
,"param.unflag": { "message": "unflag" }
|
|
||||||
,"param.address": { "message": "address" }
|
|
||||||
,"param.replyAll": { "message": "reply all" }
|
|
||||||
,"param.replySender": { "message": "reply sender" }
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -56,15 +56,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "img", "img", "{F266602F-175
|
||||||
resources\img\average-16.png = resources\img\average-16.png
|
resources\img\average-16.png = resources\img\average-16.png
|
||||||
resources\img\average-32.png = resources\img\average-32.png
|
resources\img\average-32.png = resources\img\average-32.png
|
||||||
resources\img\average-64.png = resources\img\average-64.png
|
resources\img\average-64.png = resources\img\average-64.png
|
||||||
resources\img\check-16.png = resources\img\check-16.png
|
|
||||||
resources\img\check-32.png = resources\img\check-32.png
|
|
||||||
resources\img\check-64.png = resources\img\check-64.png
|
|
||||||
resources\img\circle-16.png = resources\img\circle-16.png
|
resources\img\circle-16.png = resources\img\circle-16.png
|
||||||
resources\img\circle-32.png = resources\img\circle-32.png
|
resources\img\circle-32.png = resources\img\circle-32.png
|
||||||
resources\img\circle-64.png = resources\img\circle-64.png
|
resources\img\circle-64.png = resources\img\circle-64.png
|
||||||
resources\img\circledots-16.png = resources\img\circledots-16.png
|
|
||||||
resources\img\circledots-32.png = resources\img\circledots-32.png
|
|
||||||
resources\img\circledots-64.png = resources\img\circledots-64.png
|
|
||||||
resources\img\clipboarddata-16.png = resources\img\clipboarddata-16.png
|
resources\img\clipboarddata-16.png = resources\img\clipboarddata-16.png
|
||||||
resources\img\clipboarddata-32.png = resources\img\clipboarddata-32.png
|
resources\img\clipboarddata-32.png = resources\img\clipboarddata-32.png
|
||||||
resources\img\clipboarddata-64.png = resources\img\clipboarddata-64.png
|
resources\img\clipboarddata-64.png = resources\img\clipboarddata-64.png
|
||||||
|
@ -101,35 +95,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "img", "img", "{F266602F-175
|
||||||
resources\img\upload-16.png = resources\img\upload-16.png
|
resources\img\upload-16.png = resources\img\upload-16.png
|
||||||
resources\img\upload-32.png = resources\img\upload-32.png
|
resources\img\upload-32.png = resources\img\upload-32.png
|
||||||
resources\img\upload-64.png = resources\img\upload-64.png
|
resources\img\upload-64.png = resources\img\upload-64.png
|
||||||
resources\img\x-16.png = resources\img\x-16.png
|
|
||||||
resources\img\x-32.png = resources\img\x-32.png
|
|
||||||
resources\img\x-64.png = resources\img\x-64.png
|
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "js", "js", "{21D2A42C-3F85-465C-9141-C106AFD92B68}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "js", "js", "{21D2A42C-3F85-465C-9141-C106AFD92B68}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
resources\js\diff_match_patch_uncompressed.js = resources\js\diff_match_patch_uncompressed.js
|
|
||||||
resources\js\turndown.js = resources\js\turndown.js
|
resources\js\turndown.js = resources\js\turndown.js
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "svg", "svg", "{D4E9C905-4884-488E-B763-5BD39049C1B1}"
|
|
||||||
ProjectSection(SolutionItems) = preProject
|
|
||||||
resources\svg\average.svg = resources\svg\average.svg
|
|
||||||
resources\svg\check.svg = resources\svg\check.svg
|
|
||||||
resources\svg\circle.svg = resources\svg\circle.svg
|
|
||||||
resources\svg\circledots.svg = resources\svg\circledots.svg
|
|
||||||
resources\svg\clipboarddata.svg = resources\svg\clipboarddata.svg
|
|
||||||
resources\svg\download.svg = resources\svg\download.svg
|
|
||||||
resources\svg\eye.svg = resources\svg\eye.svg
|
|
||||||
resources\svg\flag.svg = resources\svg\flag.svg
|
|
||||||
resources\svg\gear.svg = resources\svg\gear.svg
|
|
||||||
resources\svg\reply.svg = resources\svg\reply.svg
|
|
||||||
resources\svg\settings.svg = resources\svg\settings.svg
|
|
||||||
resources\svg\trash.svg = resources\svg\trash.svg
|
|
||||||
resources\svg\upload.svg = resources\svg\upload.svg
|
|
||||||
resources\svg\x.svg = resources\svg\x.svg
|
|
||||||
EndProjectSection
|
|
||||||
EndProject
|
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
@ -143,6 +115,5 @@ Global
|
||||||
{68A87938-5C2B-49F5-8AAA-8A34FBBFD854} = {BCC6E6D2-343B-4C48-854D-5FE3BBC3CB70}
|
{68A87938-5C2B-49F5-8AAA-8A34FBBFD854} = {BCC6E6D2-343B-4C48-854D-5FE3BBC3CB70}
|
||||||
{F266602F-1755-4A95-A11B-6C90C701C5BF} = {68A87938-5C2B-49F5-8AAA-8A34FBBFD854}
|
{F266602F-1755-4A95-A11B-6C90C701C5BF} = {68A87938-5C2B-49F5-8AAA-8A34FBBFD854}
|
||||||
{21D2A42C-3F85-465C-9141-C106AFD92B68} = {68A87938-5C2B-49F5-8AAA-8A34FBBFD854}
|
{21D2A42C-3F85-465C-9141-C106AFD92B68} = {68A87938-5C2B-49F5-8AAA-8A34FBBFD854}
|
||||||
{D4E9C905-4884-488E-B763-5BD39049C1B1} = {68A87938-5C2B-49F5-8AAA-8A34FBBFD854}
|
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|
398
background.js
|
@ -26,36 +26,18 @@ let htmlToMarkdown = false;
|
||||||
let stripUrlParams = false;
|
let stripUrlParams = false;
|
||||||
let altTextImages = false;
|
let altTextImages = false;
|
||||||
let collapseWhitespace = false;
|
let collapseWhitespace = false;
|
||||||
let tokenReduction = false;
|
|
||||||
let maxTokens = 4096;
|
|
||||||
let TurndownService = null;
|
let TurndownService = null;
|
||||||
let userTheme = 'auto';
|
let userTheme = 'auto';
|
||||||
let currentTheme = 'light';
|
let currentTheme = 'light';
|
||||||
let detectSystemTheme;
|
|
||||||
let errorPending = false;
|
|
||||||
let showDebugTab = false;
|
|
||||||
const ERROR_NOTIFICATION_ID = 'sortana-error';
|
|
||||||
|
|
||||||
function normalizeRules(rules) {
|
function normalizeRules(rules) {
|
||||||
return Array.isArray(rules) ? rules.map(r => {
|
return Array.isArray(rules) ? rules.map(r => {
|
||||||
if (r.actions) {
|
if (r.actions) return r;
|
||||||
if (!Array.isArray(r.accounts)) r.accounts = [];
|
|
||||||
if (!Array.isArray(r.folders)) r.folders = [];
|
|
||||||
r.enabled = r.enabled !== false;
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
const actions = [];
|
const actions = [];
|
||||||
if (r.tag) actions.push({ type: 'tag', tagKey: r.tag });
|
if (r.tag) actions.push({ type: 'tag', tagKey: r.tag });
|
||||||
if (r.moveTo) actions.push({ type: 'move', folder: r.moveTo });
|
if (r.moveTo) actions.push({ type: 'move', folder: r.moveTo });
|
||||||
if (r.copyTarget || r.copyTo) actions.push({ type: 'copy', copyTarget: r.copyTarget || r.copyTo });
|
|
||||||
const rule = { criterion: r.criterion, actions };
|
const rule = { criterion: r.criterion, actions };
|
||||||
if (r.stopProcessing) rule.stopProcessing = true;
|
if (r.stopProcessing) rule.stopProcessing = true;
|
||||||
if (r.unreadOnly) rule.unreadOnly = true;
|
|
||||||
if (typeof r.minAgeDays === 'number') rule.minAgeDays = r.minAgeDays;
|
|
||||||
if (typeof r.maxAgeDays === 'number') rule.maxAgeDays = r.maxAgeDays;
|
|
||||||
if (Array.isArray(r.accounts)) rule.accounts = r.accounts;
|
|
||||||
if (Array.isArray(r.folders)) rule.folders = r.folders;
|
|
||||||
rule.enabled = r.enabled !== false;
|
|
||||||
return rule;
|
return rule;
|
||||||
}) : [];
|
}) : [];
|
||||||
}
|
}
|
||||||
|
@ -68,13 +50,30 @@ function iconPaths(name) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function detectSystemTheme() {
|
||||||
|
try {
|
||||||
|
const t = await browser.theme.getCurrent();
|
||||||
|
const scheme = t?.properties?.color_scheme;
|
||||||
|
if (scheme === 'dark' || scheme === 'light') {
|
||||||
|
return scheme;
|
||||||
|
}
|
||||||
|
const color = t?.colors?.frame || t?.colors?.toolbar;
|
||||||
|
if (color && /^#/.test(color)) {
|
||||||
|
const r = parseInt(color.slice(1, 3), 16);
|
||||||
|
const g = parseInt(color.slice(3, 5), 16);
|
||||||
|
const b = parseInt(color.slice(5, 7), 16);
|
||||||
|
const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||||
|
return lum < 0.5 ? 'dark' : 'light';
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
return 'light';
|
||||||
|
}
|
||||||
|
|
||||||
const ICONS = {
|
const ICONS = {
|
||||||
logo: () => 'resources/img/logo.png',
|
logo: () => 'resources/img/logo.png',
|
||||||
circledots: () => iconPaths('circledots'),
|
circledots: () => iconPaths('circledots'),
|
||||||
circle: () => iconPaths('circle'),
|
circle: () => iconPaths('circle'),
|
||||||
average: () => iconPaths('average'),
|
average: () => iconPaths('average')
|
||||||
error: () => iconPaths('x')
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function setIcon(path) {
|
function setIcon(path) {
|
||||||
|
@ -88,31 +87,19 @@ function setIcon(path) {
|
||||||
|
|
||||||
function updateActionIcon() {
|
function updateActionIcon() {
|
||||||
let path = ICONS.logo();
|
let path = ICONS.logo();
|
||||||
if (errorPending) {
|
if (processing || queuedCount > 0) {
|
||||||
path = ICONS.error();
|
|
||||||
} else if (processing || queuedCount > 0) {
|
|
||||||
path = ICONS.circledots();
|
path = ICONS.circledots();
|
||||||
}
|
}
|
||||||
setIcon(path);
|
setIcon(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
function showTransientIcon(factory, delay = 1500) {
|
function showTransientIcon(factory, delay = 1500) {
|
||||||
if (errorPending) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
clearTimeout(iconTimer);
|
clearTimeout(iconTimer);
|
||||||
const path = typeof factory === 'function' ? factory() : factory;
|
const path = typeof factory === 'function' ? factory() : factory;
|
||||||
setIcon(path);
|
setIcon(path);
|
||||||
iconTimer = setTimeout(updateActionIcon, delay);
|
iconTimer = setTimeout(updateActionIcon, delay);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function clearError() {
|
|
||||||
errorPending = false;
|
|
||||||
await storage.local.set({ errorPending: false });
|
|
||||||
await browser.notifications.clear(ERROR_NOTIFICATION_ID);
|
|
||||||
updateActionIcon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function refreshMenuIcons() {
|
function refreshMenuIcons() {
|
||||||
browser.menus.update('apply-ai-rules-list', { icons: iconPaths('eye') });
|
browser.menus.update('apply-ai-rules-list', { icons: iconPaths('eye') });
|
||||||
browser.menus.update('apply-ai-rules-display', { icons: iconPaths('eye') });
|
browser.menus.update('apply-ai-rules-display', { icons: iconPaths('eye') });
|
||||||
|
@ -128,16 +115,12 @@ function byteSize(str) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function replaceInlineBase64(text) {
|
function replaceInlineBase64(text) {
|
||||||
return text.replace(/(?:data:[^;]+;base64,)?[A-Za-z0-9+/=\r\n]{100,}/g,
|
return text.replace(/[A-Za-z0-9+/]{100,}={0,2}/g,
|
||||||
m => tokenReduction ? '__BASE64__' : `[base64: ${byteSize(m)} bytes]`);
|
m => `[base64: ${byteSize(m)} bytes]`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function sanitizeString(text) {
|
function sanitizeString(text) {
|
||||||
let t = String(text);
|
let t = String(text);
|
||||||
if (tokenReduction) {
|
|
||||||
t = t.replace(/<!--.*?-->/gs, '')
|
|
||||||
.replace(/url\([^\)]*\)/gi, 'url(__IMG__)');
|
|
||||||
}
|
|
||||||
if (stripUrlParams) {
|
if (stripUrlParams) {
|
||||||
t = t.replace(/https?:\/\/[^\s)]+/g, m => {
|
t = t.replace(/https?:\/\/[^\s)]+/g, m => {
|
||||||
const idx = m.indexOf('?');
|
const idx = m.indexOf('?');
|
||||||
|
@ -145,7 +128,7 @@ function sanitizeString(text) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (collapseWhitespace) {
|
if (collapseWhitespace) {
|
||||||
t = t.replace(/[\u200B-\u200D\u2060\s]{2,}/g, ' ').replace(/\n{3,}/g, '\n\n');
|
t = t.replace(/[ \t\u00A0]{2,}/g, ' ').replace(/\n{3,}/g, '\n\n');
|
||||||
}
|
}
|
||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
@ -164,26 +147,12 @@ function collectText(part, bodyParts, attachments) {
|
||||||
attachments.push(`${name} (${ct}, ${part.size || byteSize(body)} bytes)`);
|
attachments.push(`${name} (${ct}, ${part.size || byteSize(body)} bytes)`);
|
||||||
} else if (ct.startsWith("text/html")) {
|
} else if (ct.startsWith("text/html")) {
|
||||||
const doc = new DOMParser().parseFromString(body, 'text/html');
|
const doc = new DOMParser().parseFromString(body, 'text/html');
|
||||||
if (tokenReduction) {
|
if (altTextImages) {
|
||||||
doc.querySelectorAll('script,style').forEach(el => el.remove());
|
|
||||||
const walker = doc.createTreeWalker(doc, NodeFilter.SHOW_COMMENT);
|
|
||||||
let node;
|
|
||||||
while ((node = walker.nextNode())) {
|
|
||||||
node.parentNode.removeChild(node);
|
|
||||||
}
|
|
||||||
doc.querySelectorAll('*').forEach(el => {
|
|
||||||
for (const attr of Array.from(el.attributes)) {
|
|
||||||
if (!['href','src','alt'].includes(attr.name)) {
|
|
||||||
el.removeAttribute(attr.name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
doc.querySelectorAll('img').forEach(img => {
|
doc.querySelectorAll('img').forEach(img => {
|
||||||
const alt = img.getAttribute('alt') || '';
|
const alt = img.getAttribute('alt') || '';
|
||||||
const text = altTextImages ? alt : '__IMG__';
|
img.replaceWith(doc.createTextNode(alt));
|
||||||
img.replaceWith(doc.createTextNode(text));
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
if (stripUrlParams) {
|
if (stripUrlParams) {
|
||||||
doc.querySelectorAll('[href]').forEach(a => {
|
doc.querySelectorAll('[href]').forEach(a => {
|
||||||
const href = a.getAttribute('href');
|
const href = a.getAttribute('href');
|
||||||
|
@ -210,190 +179,16 @@ function collectText(part, bodyParts, attachments) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function collectRawText(part, bodyParts, attachments) {
|
function buildEmailText(full) {
|
||||||
if (part.parts && part.parts.length) {
|
|
||||||
for (const p of part.parts) collectRawText(p, bodyParts, attachments);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const ct = (part.contentType || "text/plain").toLowerCase();
|
|
||||||
const cd = (part.headers?.["content-disposition"]?.[0] || "").toLowerCase();
|
|
||||||
const body = String(part.body || "");
|
|
||||||
if (cd.includes("attachment") || !ct.startsWith("text/")) {
|
|
||||||
const nameMatch = /filename\s*=\s*"?([^";]+)/i.exec(cd) || /name\s*=\s*"?([^";]+)/i.exec(part.headers?.["content-type"]?.[0] || "");
|
|
||||||
const name = nameMatch ? nameMatch[1] : "";
|
|
||||||
attachments.push(`${name} (${ct}, ${part.size || byteSize(body)} bytes)`);
|
|
||||||
} else if (ct.startsWith("text/html")) {
|
|
||||||
const doc = new DOMParser().parseFromString(body, 'text/html');
|
|
||||||
bodyParts.push(doc.body.textContent || "");
|
|
||||||
} else {
|
|
||||||
bodyParts.push(body);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildEmailText(full, applyTransforms = true) {
|
|
||||||
const bodyParts = [];
|
const bodyParts = [];
|
||||||
const attachments = [];
|
const attachments = [];
|
||||||
const collect = applyTransforms ? collectText : collectRawText;
|
collectText(full, bodyParts, attachments);
|
||||||
collect(full, bodyParts, attachments);
|
|
||||||
const headers = Object.entries(full.headers || {})
|
const headers = Object.entries(full.headers || {})
|
||||||
.map(([k, v]) => `${k}: ${v.join(' ')}`)
|
.map(([k, v]) => `${k}: ${v.join(' ')}`)
|
||||||
.join('\n');
|
.join('\n');
|
||||||
const attachInfo = `Attachments: ${attachments.length}` +
|
const attachInfo = `Attachments: ${attachments.length}` + (attachments.length ? "\n" + attachments.map(a => ` - ${a}`).join('\n') : "");
|
||||||
(attachments.length ? "\n" + attachments.map(a => ` - ${a}`).join('\n') : "");
|
const combined = `${headers}\n${attachInfo}\n\n${bodyParts.join('\n')}`.trim();
|
||||||
let combined = `${headers}\n${attachInfo}\n\n${bodyParts.join('\n')}`.trim();
|
return sanitizeString(combined);
|
||||||
if (applyTransforms && tokenReduction) {
|
|
||||||
const seen = new Set();
|
|
||||||
combined = combined.split('\n').filter(l => {
|
|
||||||
if (seen.has(l)) return false;
|
|
||||||
seen.add(l);
|
|
||||||
return true;
|
|
||||||
}).join('\n');
|
|
||||||
}
|
|
||||||
return applyTransforms ? sanitizeString(combined) : combined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateTimingStats(elapsed) {
|
|
||||||
const t = timingStats;
|
|
||||||
t.count += 1;
|
|
||||||
t.total += elapsed;
|
|
||||||
t.last = elapsed;
|
|
||||||
const delta = elapsed - t.mean;
|
|
||||||
t.mean += delta / t.count;
|
|
||||||
t.m2 += delta * (elapsed - t.mean);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getAllMessageIds(list) {
|
|
||||||
const ids = [];
|
|
||||||
if (!list) {
|
|
||||||
return ids;
|
|
||||||
}
|
|
||||||
let page = list;
|
|
||||||
ids.push(...(page.messages || []).map(m => m.id));
|
|
||||||
while (page.id) {
|
|
||||||
page = await messenger.messages.continueList(page.id);
|
|
||||||
ids.push(...(page.messages || []).map(m => m.id));
|
|
||||||
}
|
|
||||||
return ids;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function processMessage(id) {
|
|
||||||
processing = true;
|
|
||||||
currentStart = Date.now();
|
|
||||||
queuedCount--;
|
|
||||||
updateActionIcon();
|
|
||||||
try {
|
|
||||||
const full = await messenger.messages.getFull(id);
|
|
||||||
const originalText = buildEmailText(full, false);
|
|
||||||
let text = buildEmailText(full);
|
|
||||||
if (tokenReduction && maxTokens > 0) {
|
|
||||||
const limit = Math.floor(maxTokens * 0.9);
|
|
||||||
if (text.length > limit) {
|
|
||||||
text = text.slice(0, limit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (showDebugTab) {
|
|
||||||
await storage.local.set({ lastFullText: originalText, lastPromptText: text });
|
|
||||||
}
|
|
||||||
let hdr;
|
|
||||||
let currentTags = [];
|
|
||||||
let alreadyRead = false;
|
|
||||||
let identityId = null;
|
|
||||||
try {
|
|
||||||
hdr = await messenger.messages.get(id);
|
|
||||||
currentTags = Array.isArray(hdr.tags) ? [...hdr.tags] : [];
|
|
||||||
alreadyRead = hdr.read === true;
|
|
||||||
const ids = await messenger.identities.list(hdr.folder.accountId);
|
|
||||||
identityId = ids[0]?.id || null;
|
|
||||||
} catch (e) {
|
|
||||||
currentTags = [];
|
|
||||||
alreadyRead = false;
|
|
||||||
identityId = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const rule of aiRules) {
|
|
||||||
if (rule.enabled === false) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (hdr && Array.isArray(rule.accounts) && rule.accounts.length &&
|
|
||||||
!rule.accounts.includes(hdr.folder.accountId)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (hdr && Array.isArray(rule.folders) && rule.folders.length &&
|
|
||||||
!rule.folders.includes(hdr.folder.path)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (rule.unreadOnly && alreadyRead) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (hdr && (typeof rule.minAgeDays === 'number' || typeof rule.maxAgeDays === 'number')) {
|
|
||||||
const msgTime = new Date(hdr.date).getTime();
|
|
||||||
if (!isNaN(msgTime)) {
|
|
||||||
const ageDays = (Date.now() - msgTime) / 86400000;
|
|
||||||
if (typeof rule.minAgeDays === 'number' && ageDays < rule.minAgeDays) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (typeof rule.maxAgeDays === 'number' && ageDays > rule.maxAgeDays) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const cacheKey = await AiClassifier.buildCacheKey(id, rule.criterion);
|
|
||||||
const matched = await AiClassifier.classifyText(text, rule.criterion, cacheKey);
|
|
||||||
if (matched) {
|
|
||||||
for (const act of (rule.actions || [])) {
|
|
||||||
if (act.type === 'tag' && act.tagKey) {
|
|
||||||
if (!currentTags.includes(act.tagKey)) {
|
|
||||||
currentTags.push(act.tagKey);
|
|
||||||
await messenger.messages.update(id, { tags: currentTags });
|
|
||||||
}
|
|
||||||
} else if (act.type === 'move' && act.folder) {
|
|
||||||
await messenger.messages.move([id], act.folder);
|
|
||||||
} else if (act.type === 'copy' && act.copyTarget) {
|
|
||||||
await messenger.messages.copy([id], act.copyTarget);
|
|
||||||
} else if (act.type === 'junk') {
|
|
||||||
await messenger.messages.update(id, { junk: !!act.junk });
|
|
||||||
} else if (act.type === 'read') {
|
|
||||||
await messenger.messages.update(id, { read: !!act.read });
|
|
||||||
} else if (act.type === 'flag') {
|
|
||||||
await messenger.messages.update(id, { flagged: !!act.flagged });
|
|
||||||
} else if (act.type === 'delete') {
|
|
||||||
await messenger.messages.delete([id]);
|
|
||||||
} else if (act.type === 'archive') {
|
|
||||||
await messenger.messages.archive([id]);
|
|
||||||
} else if (act.type === 'forward' && act.address && identityId) {
|
|
||||||
await browser.compose.beginForward(id, { to: [act.address], identityId });
|
|
||||||
} else if (act.type === 'reply' && act.replyType && identityId) {
|
|
||||||
await browser.compose.beginReply(id, { replyType: act.replyType, identityId });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (rule.stopProcessing) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
processing = false;
|
|
||||||
const elapsed = Date.now() - currentStart;
|
|
||||||
currentStart = 0;
|
|
||||||
updateTimingStats(elapsed);
|
|
||||||
await storage.local.set({ classifyStats: timingStats });
|
|
||||||
showTransientIcon(ICONS.circle);
|
|
||||||
} catch (e) {
|
|
||||||
processing = false;
|
|
||||||
const elapsed = Date.now() - currentStart;
|
|
||||||
currentStart = 0;
|
|
||||||
updateTimingStats(elapsed);
|
|
||||||
await storage.local.set({ classifyStats: timingStats, errorPending: true });
|
|
||||||
errorPending = true;
|
|
||||||
logger.aiLog("failed to apply AI rules", { level: 'error' }, e);
|
|
||||||
setIcon(ICONS.error());
|
|
||||||
browser.notifications.create(ERROR_NOTIFICATION_ID, {
|
|
||||||
type: 'basic',
|
|
||||||
iconUrl: browser.runtime.getURL('resources/img/logo.png'),
|
|
||||||
title: 'Sortana Error',
|
|
||||||
message: 'Failed to apply AI rules',
|
|
||||||
buttons: [{ title: 'Dismiss' }]
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
async function applyAiRules(idsInput) {
|
async function applyAiRules(idsInput) {
|
||||||
const ids = Array.isArray(idsInput) ? idsInput : [idsInput];
|
const ids = Array.isArray(idsInput) ? idsInput : [idsInput];
|
||||||
|
@ -408,7 +203,71 @@ async function applyAiRules(idsInput) {
|
||||||
const id = msg?.id ?? msg;
|
const id = msg?.id ?? msg;
|
||||||
queuedCount++;
|
queuedCount++;
|
||||||
updateActionIcon();
|
updateActionIcon();
|
||||||
queue = queue.then(() => processMessage(id));
|
queue = queue.then(async () => {
|
||||||
|
processing = true;
|
||||||
|
currentStart = Date.now();
|
||||||
|
queuedCount--;
|
||||||
|
updateActionIcon();
|
||||||
|
try {
|
||||||
|
const full = await messenger.messages.getFull(id);
|
||||||
|
const text = buildEmailText(full);
|
||||||
|
let currentTags = [];
|
||||||
|
try {
|
||||||
|
const hdr = await messenger.messages.get(id);
|
||||||
|
currentTags = Array.isArray(hdr.tags) ? [...hdr.tags] : [];
|
||||||
|
} catch (e) {
|
||||||
|
currentTags = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const rule of aiRules) {
|
||||||
|
const cacheKey = await AiClassifier.buildCacheKey(id, rule.criterion);
|
||||||
|
const matched = await AiClassifier.classifyText(text, rule.criterion, cacheKey);
|
||||||
|
if (matched) {
|
||||||
|
for (const act of (rule.actions || [])) {
|
||||||
|
if (act.type === 'tag' && act.tagKey) {
|
||||||
|
if (!currentTags.includes(act.tagKey)) {
|
||||||
|
currentTags.push(act.tagKey);
|
||||||
|
await messenger.messages.update(id, { tags: currentTags });
|
||||||
|
}
|
||||||
|
} else if (act.type === 'move' && act.folder) {
|
||||||
|
await messenger.messages.move([id], act.folder);
|
||||||
|
} else if (act.type === 'junk') {
|
||||||
|
await messenger.messages.update(id, { junk: !!act.junk });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rule.stopProcessing) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
processing = false;
|
||||||
|
const elapsed = Date.now() - currentStart;
|
||||||
|
currentStart = 0;
|
||||||
|
const t = timingStats;
|
||||||
|
t.count += 1;
|
||||||
|
t.total += elapsed;
|
||||||
|
t.last = elapsed;
|
||||||
|
const delta = elapsed - t.mean;
|
||||||
|
t.mean += delta / t.count;
|
||||||
|
t.m2 += delta * (elapsed - t.mean);
|
||||||
|
await storage.local.set({ classifyStats: t });
|
||||||
|
showTransientIcon(ICONS.circle);
|
||||||
|
} catch (e) {
|
||||||
|
processing = false;
|
||||||
|
const elapsed = Date.now() - currentStart;
|
||||||
|
currentStart = 0;
|
||||||
|
const t = timingStats;
|
||||||
|
t.count += 1;
|
||||||
|
t.total += elapsed;
|
||||||
|
t.last = elapsed;
|
||||||
|
const delta = elapsed - t.mean;
|
||||||
|
t.mean += delta / t.count;
|
||||||
|
t.m2 += delta * (elapsed - t.mean);
|
||||||
|
await storage.local.set({ classifyStats: t });
|
||||||
|
logger.aiLog("failed to apply AI rules", { level: 'error' }, e);
|
||||||
|
showTransientIcon(ICONS.average);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return queue;
|
return queue;
|
||||||
|
@ -439,7 +298,6 @@ async function clearCacheForMessages(idsInput) {
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
logger = await import(browser.runtime.getURL("logger.js"));
|
logger = await import(browser.runtime.getURL("logger.js"));
|
||||||
({ detectSystemTheme } = await import(browser.runtime.getURL('modules/themeUtils.js')));
|
|
||||||
try {
|
try {
|
||||||
AiClassifier = await import(browser.runtime.getURL("modules/AiClassifier.js"));
|
AiClassifier = await import(browser.runtime.getURL("modules/AiClassifier.js"));
|
||||||
logger.aiLog("AiClassifier imported", { debug: true });
|
logger.aiLog("AiClassifier imported", { debug: true });
|
||||||
|
@ -451,7 +309,7 @@ async function clearCacheForMessages(idsInput) {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const store = await storage.local.get(["endpoint", "templateName", "customTemplate", "customSystemPrompt", "aiParams", "debugLogging", "htmlToMarkdown", "stripUrlParams", "altTextImages", "collapseWhitespace", "tokenReduction", "aiRules", "theme", "errorPending", "showDebugTab"]);
|
const store = await storage.local.get(["endpoint", "templateName", "customTemplate", "customSystemPrompt", "aiParams", "debugLogging", "htmlToMarkdown", "stripUrlParams", "altTextImages", "collapseWhitespace", "aiRules", "theme"]);
|
||||||
logger.setDebug(store.debugLogging);
|
logger.setDebug(store.debugLogging);
|
||||||
await AiClassifier.setConfig(store);
|
await AiClassifier.setConfig(store);
|
||||||
userTheme = store.theme || 'auto';
|
userTheme = store.theme || 'auto';
|
||||||
|
@ -461,12 +319,6 @@ async function clearCacheForMessages(idsInput) {
|
||||||
stripUrlParams = store.stripUrlParams === true;
|
stripUrlParams = store.stripUrlParams === true;
|
||||||
altTextImages = store.altTextImages === true;
|
altTextImages = store.altTextImages === true;
|
||||||
collapseWhitespace = store.collapseWhitespace === true;
|
collapseWhitespace = store.collapseWhitespace === true;
|
||||||
tokenReduction = store.tokenReduction === true;
|
|
||||||
if (store.aiParams && typeof store.aiParams.max_tokens !== 'undefined') {
|
|
||||||
maxTokens = parseInt(store.aiParams.max_tokens) || maxTokens;
|
|
||||||
}
|
|
||||||
errorPending = store.errorPending === true;
|
|
||||||
showDebugTab = store.showDebugTab === true;
|
|
||||||
const savedStats = await storage.local.get('classifyStats');
|
const savedStats = await storage.local.get('classifyStats');
|
||||||
if (savedStats.classifyStats && typeof savedStats.classifyStats === 'object') {
|
if (savedStats.classifyStats && typeof savedStats.classifyStats === 'object') {
|
||||||
Object.assign(timingStats, savedStats.classifyStats);
|
Object.assign(timingStats, savedStats.classifyStats);
|
||||||
|
@ -482,25 +334,6 @@ async function clearCacheForMessages(idsInput) {
|
||||||
aiRules = normalizeRules(newRules);
|
aiRules = normalizeRules(newRules);
|
||||||
logger.aiLog("aiRules updated from storage change", { debug: true }, aiRules);
|
logger.aiLog("aiRules updated from storage change", { debug: true }, aiRules);
|
||||||
}
|
}
|
||||||
if (changes.endpoint || changes.templateName || changes.customTemplate || changes.customSystemPrompt || changes.aiParams || changes.debugLogging) {
|
|
||||||
const config = {};
|
|
||||||
if (changes.endpoint) config.endpoint = changes.endpoint.newValue;
|
|
||||||
if (changes.templateName) config.templateName = changes.templateName.newValue;
|
|
||||||
if (changes.customTemplate) config.customTemplate = changes.customTemplate.newValue;
|
|
||||||
if (changes.customSystemPrompt) config.customSystemPrompt = changes.customSystemPrompt.newValue;
|
|
||||||
if (changes.aiParams) {
|
|
||||||
config.aiParams = changes.aiParams.newValue;
|
|
||||||
if (changes.aiParams.newValue && typeof changes.aiParams.newValue.max_tokens !== 'undefined') {
|
|
||||||
maxTokens = parseInt(changes.aiParams.newValue.max_tokens) || maxTokens;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (changes.debugLogging) {
|
|
||||||
config.debugLogging = changes.debugLogging.newValue === true;
|
|
||||||
logger.setDebug(config.debugLogging);
|
|
||||||
}
|
|
||||||
await AiClassifier.setConfig(config);
|
|
||||||
logger.aiLog("AiClassifier config updated from storage change", { debug: true }, config);
|
|
||||||
}
|
|
||||||
if (changes.htmlToMarkdown) {
|
if (changes.htmlToMarkdown) {
|
||||||
htmlToMarkdown = changes.htmlToMarkdown.newValue === true;
|
htmlToMarkdown = changes.htmlToMarkdown.newValue === true;
|
||||||
logger.aiLog("htmlToMarkdown updated from storage change", { debug: true }, htmlToMarkdown);
|
logger.aiLog("htmlToMarkdown updated from storage change", { debug: true }, htmlToMarkdown);
|
||||||
|
@ -517,17 +350,6 @@ async function clearCacheForMessages(idsInput) {
|
||||||
collapseWhitespace = changes.collapseWhitespace.newValue === true;
|
collapseWhitespace = changes.collapseWhitespace.newValue === true;
|
||||||
logger.aiLog("collapseWhitespace updated from storage change", { debug: true }, collapseWhitespace);
|
logger.aiLog("collapseWhitespace updated from storage change", { debug: true }, collapseWhitespace);
|
||||||
}
|
}
|
||||||
if (changes.tokenReduction) {
|
|
||||||
tokenReduction = changes.tokenReduction.newValue === true;
|
|
||||||
logger.aiLog("tokenReduction updated from storage change", { debug: true }, tokenReduction);
|
|
||||||
}
|
|
||||||
if (changes.showDebugTab) {
|
|
||||||
showDebugTab = changes.showDebugTab.newValue === true;
|
|
||||||
}
|
|
||||||
if (changes.errorPending) {
|
|
||||||
errorPending = changes.errorPending.newValue === true;
|
|
||||||
updateActionIcon();
|
|
||||||
}
|
|
||||||
if (changes.theme) {
|
if (changes.theme) {
|
||||||
userTheme = changes.theme.newValue || 'auto';
|
userTheme = changes.theme.newValue || 'auto';
|
||||||
currentTheme = userTheme === 'auto' ? await detectSystemTheme() : userTheme;
|
currentTheme = userTheme === 'auto' ? await detectSystemTheme() : userTheme;
|
||||||
|
@ -602,16 +424,12 @@ async function clearCacheForMessages(idsInput) {
|
||||||
|
|
||||||
browser.menus.onClicked.addListener(async (info, tab) => {
|
browser.menus.onClicked.addListener(async (info, tab) => {
|
||||||
if (info.menuItemId === "apply-ai-rules-list" || info.menuItemId === "apply-ai-rules-display") {
|
if (info.menuItemId === "apply-ai-rules-list" || info.menuItemId === "apply-ai-rules-display") {
|
||||||
let ids = info.messageId ? [info.messageId] : [];
|
const ids = info.selectedMessages?.messages?.map(m => m.id) ||
|
||||||
if (info.selectedMessages) {
|
(info.messageId ? [info.messageId] : []);
|
||||||
ids = await getAllMessageIds(info.selectedMessages);
|
|
||||||
}
|
|
||||||
await applyAiRules(ids);
|
await applyAiRules(ids);
|
||||||
} else if (info.menuItemId === "clear-ai-cache-list" || info.menuItemId === "clear-ai-cache-display") {
|
} else if (info.menuItemId === "clear-ai-cache-list" || info.menuItemId === "clear-ai-cache-display") {
|
||||||
let ids = info.messageId ? [info.messageId] : [];
|
const ids = info.selectedMessages?.messages?.map(m => m.id) ||
|
||||||
if (info.selectedMessages) {
|
(info.messageId ? [info.messageId] : []);
|
||||||
ids = await getAllMessageIds(info.selectedMessages);
|
|
||||||
}
|
|
||||||
await clearCacheForMessages(ids);
|
await clearCacheForMessages(ids);
|
||||||
} else if (info.menuItemId === "view-ai-reason-list" || info.menuItemId === "view-ai-reason-display") {
|
} else if (info.menuItemId === "view-ai-reason-list" || info.menuItemId === "view-ai-reason-display") {
|
||||||
const [header] = await browser.messageDisplay.getDisplayedMessages(tab.id);
|
const [header] = await browser.messageDisplay.getDisplayedMessages(tab.id);
|
||||||
|
@ -753,18 +571,6 @@ async function clearCacheForMessages(idsInput) {
|
||||||
logger.aiLog("Unhandled promise rejection", { level: 'error' }, ev.reason);
|
logger.aiLog("Unhandled promise rejection", { level: 'error' }, ev.reason);
|
||||||
});
|
});
|
||||||
|
|
||||||
browser.notifications.onClicked.addListener(id => {
|
|
||||||
if (id === ERROR_NOTIFICATION_ID) {
|
|
||||||
clearError();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
browser.notifications.onButtonClicked.addListener((id) => {
|
|
||||||
if (id === ERROR_NOTIFICATION_ID) {
|
|
||||||
clearError();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
browser.runtime.onInstalled.addListener(async ({ reason }) => {
|
browser.runtime.onInstalled.addListener(async ({ reason }) => {
|
||||||
if (reason === "install") {
|
if (reason === "install") {
|
||||||
await browser.runtime.openOptionsPage();
|
await browser.runtime.openOptionsPage();
|
||||||
|
|
|
@ -1,9 +1,8 @@
|
||||||
const aiLog = (await import(browser.runtime.getURL("logger.js"))).aiLog;
|
const aiLog = (await import(browser.runtime.getURL("logger.js"))).aiLog;
|
||||||
const storage = (globalThis.messenger ?? browser).storage;
|
const storage = (globalThis.messenger ?? browser).storage;
|
||||||
const { detectSystemTheme } = await import(browser.runtime.getURL('modules/themeUtils.js'));
|
|
||||||
const { theme } = await storage.local.get('theme');
|
const { theme } = await storage.local.get('theme');
|
||||||
const mode = (theme || 'auto') === 'auto'
|
const mode = (theme || 'auto') === 'auto'
|
||||||
? await detectSystemTheme()
|
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||||
: theme;
|
: theme;
|
||||||
document.documentElement.dataset.theme = mode;
|
document.documentElement.dataset.theme = mode;
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"manifest_version": 2,
|
"manifest_version": 2,
|
||||||
"name": "Sortana",
|
"name": "Sortana",
|
||||||
"version": "2.2.0",
|
"version": "2.1.0",
|
||||||
"default_locale": "en-US",
|
"default_locale": "en-US",
|
||||||
"applications": {
|
"applications": {
|
||||||
"gecko": {
|
"gecko": {
|
||||||
|
@ -40,10 +40,8 @@
|
||||||
"messagesTagsList",
|
"messagesTagsList",
|
||||||
"accountsRead",
|
"accountsRead",
|
||||||
"menus",
|
"menus",
|
||||||
"notifications",
|
|
||||||
"scripting",
|
"scripting",
|
||||||
"tabs",
|
"tabs",
|
||||||
"theme",
|
"theme"
|
||||||
"compose"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
"use strict";
|
"use strict";
|
||||||
import { aiLog, setDebug } from "../logger.js";
|
import { aiLog, setDebug } from "../logger.js";
|
||||||
import { DEFAULT_AI_PARAMS } from "./defaultParams.js";
|
|
||||||
|
|
||||||
const storage = (globalThis.messenger ?? globalThis.browser).storage;
|
const storage = (globalThis.messenger ?? globalThis.browser).storage;
|
||||||
|
|
||||||
|
@ -34,7 +33,19 @@ let gCustomTemplate = "";
|
||||||
let gCustomSystemPrompt = DEFAULT_CUSTOM_SYSTEM_PROMPT;
|
let gCustomSystemPrompt = DEFAULT_CUSTOM_SYSTEM_PROMPT;
|
||||||
let gTemplateText = "";
|
let gTemplateText = "";
|
||||||
|
|
||||||
let gAiParams = Object.assign({}, DEFAULT_AI_PARAMS);
|
let gAiParams = {
|
||||||
|
max_tokens: 4096,
|
||||||
|
temperature: 0.6,
|
||||||
|
top_p: 0.95,
|
||||||
|
seed: -1,
|
||||||
|
repetition_penalty: 1.0,
|
||||||
|
top_k: 20,
|
||||||
|
min_p: 0,
|
||||||
|
presence_penalty: 0,
|
||||||
|
frequency_penalty: 0,
|
||||||
|
typical_p: 1,
|
||||||
|
tfs: 1,
|
||||||
|
};
|
||||||
|
|
||||||
let gCache = new Map();
|
let gCache = new Map();
|
||||||
let gCacheLoaded = false;
|
let gCacheLoaded = false;
|
||||||
|
@ -61,6 +72,10 @@ async function sha256Hex(str) {
|
||||||
return sha256HexSync(str);
|
return sha256HexSync(str);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function buildCacheKeySync(id, criterion) {
|
||||||
|
return sha256HexSync(`${id}|${criterion}`);
|
||||||
|
}
|
||||||
|
|
||||||
async function resolveHeaderId(id) {
|
async function resolveHeaderId(id) {
|
||||||
if (typeof id === "number" && typeof messenger?.messages?.get === "function") {
|
if (typeof id === "number" && typeof messenger?.messages?.get === "function") {
|
||||||
try {
|
try {
|
||||||
|
@ -78,7 +93,7 @@ async function resolveHeaderId(id) {
|
||||||
async function buildCacheKey(id, criterion) {
|
async function buildCacheKey(id, criterion) {
|
||||||
const resolvedId = await resolveHeaderId(id);
|
const resolvedId = await resolveHeaderId(id);
|
||||||
if (Services) {
|
if (Services) {
|
||||||
return sha256HexSync(`${resolvedId}|${criterion}`);
|
return buildCacheKeySync(resolvedId, criterion);
|
||||||
}
|
}
|
||||||
return sha256Hex(`${resolvedId}|${criterion}`);
|
return sha256Hex(`${resolvedId}|${criterion}`);
|
||||||
}
|
}
|
||||||
|
@ -118,6 +133,16 @@ async function loadCache() {
|
||||||
gCacheLoaded = true;
|
gCacheLoaded = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function loadCacheSync() {
|
||||||
|
if (!gCacheLoaded) {
|
||||||
|
if (!Services?.tm?.spinEventLoopUntil) {
|
||||||
|
throw new Error("loadCacheSync requires Services");
|
||||||
|
}
|
||||||
|
let done = false;
|
||||||
|
loadCache().finally(() => { done = true; });
|
||||||
|
Services.tm.spinEventLoopUntil(() => done);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function saveCache(updatedKey, updatedValue) {
|
async function saveCache(updatedKey, updatedValue) {
|
||||||
if (typeof updatedKey !== "undefined") {
|
if (typeof updatedKey !== "undefined") {
|
||||||
|
@ -208,8 +233,12 @@ function buildPrompt(body, criterion) {
|
||||||
|
|
||||||
function getCachedResult(cacheKey) {
|
function getCachedResult(cacheKey) {
|
||||||
if (!gCacheLoaded) {
|
if (!gCacheLoaded) {
|
||||||
|
if (Services?.tm?.spinEventLoopUntil) {
|
||||||
|
loadCacheSync();
|
||||||
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (cacheKey && gCache.has(cacheKey)) {
|
if (cacheKey && gCache.has(cacheKey)) {
|
||||||
aiLog(`[AiClassifier] Cache hit for key: ${cacheKey}`, {debug: true});
|
aiLog(`[AiClassifier] Cache hit for key: ${cacheKey}`, {debug: true});
|
||||||
const entry = gCache.get(cacheKey);
|
const entry = gCache.get(cacheKey);
|
||||||
|
@ -220,8 +249,12 @@ function getCachedResult(cacheKey) {
|
||||||
|
|
||||||
function getReason(cacheKey) {
|
function getReason(cacheKey) {
|
||||||
if (!gCacheLoaded) {
|
if (!gCacheLoaded) {
|
||||||
|
if (Services?.tm?.spinEventLoopUntil) {
|
||||||
|
loadCacheSync();
|
||||||
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
const entry = gCache.get(cacheKey);
|
const entry = gCache.get(cacheKey);
|
||||||
return cacheKey && entry ? entry.reason || null : null;
|
return cacheKey && entry ? entry.reason || null : null;
|
||||||
}
|
}
|
||||||
|
@ -297,6 +330,48 @@ async function getCacheSize() {
|
||||||
return gCache.size;
|
return gCache.size;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function classifyTextSync(text, criterion, cacheKey = null) {
|
||||||
|
if (!Services?.tm?.spinEventLoopUntil) {
|
||||||
|
throw new Error("classifyTextSync requires Services");
|
||||||
|
}
|
||||||
|
const cached = getCachedResult(cacheKey);
|
||||||
|
if (cached !== null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = buildPayload(text, criterion);
|
||||||
|
|
||||||
|
aiLog(`[AiClassifier] Sending classification request to ${gEndpoint}`, {debug: true});
|
||||||
|
|
||||||
|
let result;
|
||||||
|
let done = false;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(gEndpoint, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: payload,
|
||||||
|
});
|
||||||
|
if (response.ok) {
|
||||||
|
const json = await response.json();
|
||||||
|
aiLog(`[AiClassifier] Received response:`, {debug: true}, json);
|
||||||
|
result = parseMatch(json);
|
||||||
|
cacheEntry(cacheKey, result.matched, result.reason);
|
||||||
|
result = result.matched;
|
||||||
|
} else {
|
||||||
|
aiLog(`HTTP status ${response.status}`, {level: 'warn'});
|
||||||
|
result = false;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
aiLog(`HTTP request failed`, {level: 'error'}, e);
|
||||||
|
result = false;
|
||||||
|
} finally {
|
||||||
|
done = true;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
Services.tm.spinEventLoopUntil(() => done);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
async function classifyText(text, criterion, cacheKey = null) {
|
async function classifyText(text, criterion, cacheKey = null) {
|
||||||
if (!gCacheLoaded) {
|
if (!gCacheLoaded) {
|
||||||
|
@ -308,11 +383,6 @@ async function classifyText(text, criterion, cacheKey = null) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = buildPayload(text, criterion);
|
const payload = buildPayload(text, criterion);
|
||||||
try {
|
|
||||||
await storage.local.set({ lastPayload: JSON.parse(payload) });
|
|
||||||
} catch (e) {
|
|
||||||
aiLog('failed to save last payload', { level: 'warn' }, e);
|
|
||||||
}
|
|
||||||
|
|
||||||
aiLog(`[AiClassifier] Sending classification request to ${gEndpoint}`, {debug: true});
|
aiLog(`[AiClassifier] Sending classification request to ${gEndpoint}`, {debug: true});
|
||||||
aiLog(`[AiClassifier] Classification request payload:`, { debug: true }, payload);
|
aiLog(`[AiClassifier] Classification request payload:`, { debug: true }, payload);
|
||||||
|
@ -344,4 +414,4 @@ async function init() {
|
||||||
await loadCache();
|
await loadCache();
|
||||||
}
|
}
|
||||||
|
|
||||||
export { classifyText, setConfig, removeCacheEntries, clearCache, getReason, getCachedResult, buildCacheKey, getCacheSize, init };
|
export { classifyText, classifyTextSync, setConfig, removeCacheEntries, clearCache, getReason, getCachedResult, buildCacheKey, buildCacheKeySync, getCacheSize, init };
|
||||||
|
|
|
@ -1,16 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
export const DEFAULT_AI_PARAMS = {
|
|
||||||
max_tokens: 4096,
|
|
||||||
temperature: 0.6,
|
|
||||||
top_p: 0.95,
|
|
||||||
seed: -1,
|
|
||||||
repetition_penalty: 1.0,
|
|
||||||
top_k: 20,
|
|
||||||
min_p: 0,
|
|
||||||
presence_penalty: 0,
|
|
||||||
frequency_penalty: 0,
|
|
||||||
typical_p: 1,
|
|
||||||
tfs: 1,
|
|
||||||
};
|
|
||||||
|
|
|
@ -1,20 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
export async function detectSystemTheme() {
|
|
||||||
try {
|
|
||||||
const t = await browser.theme.getCurrent();
|
|
||||||
const scheme = t?.properties?.color_scheme;
|
|
||||||
if (scheme === 'dark' || scheme === 'light') {
|
|
||||||
return scheme;
|
|
||||||
}
|
|
||||||
const color = t?.colors?.frame || t?.colors?.toolbar;
|
|
||||||
if (color && /^#/.test(color)) {
|
|
||||||
const r = parseInt(color.slice(1, 3), 16);
|
|
||||||
const g = parseInt(color.slice(3, 5), 16);
|
|
||||||
const b = parseInt(color.slice(5, 7), 16);
|
|
||||||
const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
|
||||||
return lum < 0.5 ? 'dark' : 'light';
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
return 'light';
|
|
||||||
}
|
|
|
@ -31,10 +31,6 @@
|
||||||
.tag {
|
.tag {
|
||||||
--bulma-tag-h: 318;
|
--bulma-tag-h: 318;
|
||||||
}
|
}
|
||||||
#diff-display {
|
|
||||||
white-space: pre-wrap;
|
|
||||||
font-family: monospace;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
@ -51,7 +47,6 @@
|
||||||
<li class="is-active" data-tab="settings"><a><span class="icon is-small"><img data-icon="settings" data-size="16" src="../resources/img/settings-light-16.png" alt=""></span><span>Settings</span></a></li>
|
<li class="is-active" data-tab="settings"><a><span class="icon is-small"><img data-icon="settings" data-size="16" src="../resources/img/settings-light-16.png" alt=""></span><span>Settings</span></a></li>
|
||||||
<li data-tab="rules"><a><span class="icon is-small"><img data-icon="clipboarddata" data-size="16" src="../resources/img/clipboarddata-light-16.png" alt=""></span><span>Rules</span></a></li>
|
<li data-tab="rules"><a><span class="icon is-small"><img data-icon="clipboarddata" data-size="16" src="../resources/img/clipboarddata-light-16.png" alt=""></span><span>Rules</span></a></li>
|
||||||
<li data-tab="maintenance"><a><span class="icon is-small"><img data-icon="gear" data-size="16" src="../resources/img/gear-light-16.png" alt=""></span><span>Maintenance</span></a></li>
|
<li data-tab="maintenance"><a><span class="icon is-small"><img data-icon="gear" data-size="16" src="../resources/img/gear-light-16.png" alt=""></span><span>Maintenance</span></a></li>
|
||||||
<li id="debug-tab-button" class="is-hidden" data-tab="debug"><a><span class="icon is-small"><img data-icon="average" data-size="16" src="../resources/img/average-light-16.png" alt=""></span><span>Debug</span></a></li>
|
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -149,16 +144,6 @@
|
||||||
<input type="checkbox" id="collapse-whitespace"> Collapse long whitespace
|
<input type="checkbox" id="collapse-whitespace"> Collapse long whitespace
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
|
||||||
<label class="checkbox">
|
|
||||||
<input type="checkbox" id="token-reduction"> Aggressive token reduction
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<label class="checkbox">
|
|
||||||
<input type="checkbox" id="show-debug-tab"> Show debug information
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label class="label" for="max_tokens">Max tokens</label>
|
<label class="label" for="max_tokens">Max tokens</label>
|
||||||
<div class="control">
|
<div class="control">
|
||||||
|
@ -251,8 +236,6 @@
|
||||||
<tr><th>Last run time</th><td id="last-time">--:--:--</td></tr>
|
<tr><th>Last run time</th><td id="last-time">--:--:--</td></tr>
|
||||||
<tr><th>Average run time</th><td id="average-time">--:--:--</td></tr>
|
<tr><th>Average run time</th><td id="average-time">--:--:--</td></tr>
|
||||||
<tr><th>Total run time</th><td id="total-time">--:--:--</td></tr>
|
<tr><th>Total run time</th><td id="total-time">--:--:--</td></tr>
|
||||||
<tr><th>Messages per hour</th><td id="per-hour">0</td></tr>
|
|
||||||
<tr><th>Messages per day</th><td id="per-day">0</td></tr>
|
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<button class="button is-danger" id="clear-cache" type="button">
|
<button class="button is-danger" id="clear-cache" type="button">
|
||||||
|
@ -283,21 +266,8 @@
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="debug-tab" class="tab-content is-hidden">
|
|
||||||
<h2 class="title is-4">
|
|
||||||
<span class="icon is-small"><img data-icon="average" data-size="16" src="../resources/img/average-light-16.png" alt=""></span>
|
|
||||||
<span>Debug</span>
|
|
||||||
</h2>
|
|
||||||
<pre id="payload-display"></pre>
|
|
||||||
<div id="diff-container" class="mt-4 is-hidden">
|
|
||||||
<label class="label">Prompt diff</label>
|
|
||||||
<div id="diff-display" class="box content is-family-monospace"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="../resources/js/diff_match_patch_uncompressed.js"></script>
|
|
||||||
<script src="options.js"></script>
|
<script src="options.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
@ -3,8 +3,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
const logger = await import(browser.runtime.getURL('logger.js'));
|
const logger = await import(browser.runtime.getURL('logger.js'));
|
||||||
const AiClassifier = await import(browser.runtime.getURL('modules/AiClassifier.js'));
|
const AiClassifier = await import(browser.runtime.getURL('modules/AiClassifier.js'));
|
||||||
const dataTransfer = await import(browser.runtime.getURL('options/dataTransfer.js'));
|
const dataTransfer = await import(browser.runtime.getURL('options/dataTransfer.js'));
|
||||||
const { detectSystemTheme } = await import(browser.runtime.getURL('modules/themeUtils.js'));
|
|
||||||
const { DEFAULT_AI_PARAMS } = await import(browser.runtime.getURL('modules/defaultParams.js'));
|
|
||||||
const defaults = await storage.local.get([
|
const defaults = await storage.local.get([
|
||||||
'endpoint',
|
'endpoint',
|
||||||
'templateName',
|
'templateName',
|
||||||
|
@ -16,14 +14,9 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
'stripUrlParams',
|
'stripUrlParams',
|
||||||
'altTextImages',
|
'altTextImages',
|
||||||
'collapseWhitespace',
|
'collapseWhitespace',
|
||||||
'tokenReduction',
|
|
||||||
'aiRules',
|
'aiRules',
|
||||||
'aiCache',
|
'aiCache',
|
||||||
'theme',
|
'theme'
|
||||||
'showDebugTab',
|
|
||||||
'lastPayload',
|
|
||||||
'lastFullText',
|
|
||||||
'lastPromptText'
|
|
||||||
]);
|
]);
|
||||||
const tabButtons = document.querySelectorAll('#main-tabs li');
|
const tabButtons = document.querySelectorAll('#main-tabs li');
|
||||||
const tabs = document.querySelectorAll('.tab-content');
|
const tabs = document.querySelectorAll('.tab-content');
|
||||||
|
@ -49,6 +42,10 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
const themeSelect = document.getElementById('theme-select');
|
const themeSelect = document.getElementById('theme-select');
|
||||||
themeSelect.value = defaults.theme || 'auto';
|
themeSelect.value = defaults.theme || 'auto';
|
||||||
|
|
||||||
|
function systemTheme() {
|
||||||
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||||
|
}
|
||||||
|
|
||||||
function updateIcons(theme) {
|
function updateIcons(theme) {
|
||||||
document.querySelectorAll('img[data-icon]').forEach(img => {
|
document.querySelectorAll('img[data-icon]').forEach(img => {
|
||||||
const name = img.dataset.icon;
|
const name = img.dataset.icon;
|
||||||
|
@ -61,44 +58,30 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function applyTheme(setting) {
|
function applyTheme(setting) {
|
||||||
const mode = setting === 'auto' ? await detectSystemTheme() : setting;
|
const mode = setting === 'auto' ? systemTheme() : setting;
|
||||||
document.documentElement.dataset.theme = mode;
|
document.documentElement.dataset.theme = mode;
|
||||||
updateIcons(mode);
|
updateIcons(mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
await applyTheme(themeSelect.value);
|
applyTheme(themeSelect.value);
|
||||||
const payloadDisplay = document.getElementById('payload-display');
|
themeSelect.addEventListener('change', () => {
|
||||||
const diffDisplay = document.getElementById('diff-display');
|
|
||||||
const diffContainer = document.getElementById('diff-container');
|
|
||||||
|
|
||||||
let lastFullText = defaults.lastFullText || '';
|
|
||||||
let lastPromptText = defaults.lastPromptText || '';
|
|
||||||
let lastPayload = defaults.lastPayload ? JSON.stringify(defaults.lastPayload, null, 2) : '';
|
|
||||||
|
|
||||||
if (lastPayload) {
|
|
||||||
payloadDisplay.textContent = lastPayload;
|
|
||||||
}
|
|
||||||
if (lastFullText && lastPromptText && diff_match_patch) {
|
|
||||||
const dmp = new diff_match_patch();
|
|
||||||
dmp.Diff_EditCost = 4;
|
|
||||||
const diffs = dmp.diff_main(lastFullText, lastPromptText);
|
|
||||||
dmp.diff_cleanupEfficiency(diffs);
|
|
||||||
const hasDiff = diffs.some(d => d[0] !== 0);
|
|
||||||
if (hasDiff) {
|
|
||||||
diffDisplay.innerHTML = dmp.diff_prettyHtml(diffs);
|
|
||||||
diffContainer.classList.remove('is-hidden');
|
|
||||||
} else {
|
|
||||||
diffDisplay.innerHTML = '';
|
|
||||||
diffContainer.classList.add('is-hidden');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
diffContainer.classList.add('is-hidden');
|
|
||||||
}
|
|
||||||
themeSelect.addEventListener('change', async () => {
|
|
||||||
markDirty();
|
markDirty();
|
||||||
await applyTheme(themeSelect.value);
|
applyTheme(themeSelect.value);
|
||||||
});
|
});
|
||||||
|
const DEFAULT_AI_PARAMS = {
|
||||||
|
max_tokens: 4096,
|
||||||
|
temperature: 0.6,
|
||||||
|
top_p: 0.95,
|
||||||
|
seed: -1,
|
||||||
|
repetition_penalty: 1.0,
|
||||||
|
top_k: 20,
|
||||||
|
min_p: 0,
|
||||||
|
presence_penalty: 0,
|
||||||
|
frequency_penalty: 0,
|
||||||
|
typical_p: 1,
|
||||||
|
tfs: 1
|
||||||
|
};
|
||||||
document.getElementById('endpoint').value = defaults.endpoint || 'http://127.0.0.1:5000/v1/completions';
|
document.getElementById('endpoint').value = defaults.endpoint || 'http://127.0.0.1:5000/v1/completions';
|
||||||
|
|
||||||
const templates = {
|
const templates = {
|
||||||
|
@ -147,20 +130,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
const collapseWhitespaceToggle = document.getElementById('collapse-whitespace');
|
const collapseWhitespaceToggle = document.getElementById('collapse-whitespace');
|
||||||
collapseWhitespaceToggle.checked = defaults.collapseWhitespace === true;
|
collapseWhitespaceToggle.checked = defaults.collapseWhitespace === true;
|
||||||
|
|
||||||
const tokenReductionToggle = document.getElementById('token-reduction');
|
|
||||||
tokenReductionToggle.checked = defaults.tokenReduction === true;
|
|
||||||
|
|
||||||
const debugTabToggle = document.getElementById('show-debug-tab');
|
|
||||||
const debugTabBtn = document.getElementById('debug-tab-button');
|
|
||||||
function updateDebugTab() {
|
|
||||||
const visible = debugTabToggle.checked;
|
|
||||||
debugTabBtn.classList.toggle('is-hidden', !visible);
|
|
||||||
}
|
|
||||||
debugTabToggle.checked = defaults.showDebugTab === true;
|
|
||||||
debugTabToggle.addEventListener('change', () => { updateDebugTab(); markDirty(); });
|
|
||||||
updateDebugTab();
|
|
||||||
|
|
||||||
|
|
||||||
const aiParams = Object.assign({}, DEFAULT_AI_PARAMS, defaults.aiParams || {});
|
const aiParams = Object.assign({}, DEFAULT_AI_PARAMS, defaults.aiParams || {});
|
||||||
for (const [key, val] of Object.entries(aiParams)) {
|
for (const [key, val] of Object.entries(aiParams)) {
|
||||||
const el = document.getElementById(key);
|
const el = document.getElementById(key);
|
||||||
|
@ -169,7 +138,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
|
|
||||||
let tagList = [];
|
let tagList = [];
|
||||||
let folderList = [];
|
let folderList = [];
|
||||||
let accountList = [];
|
|
||||||
try {
|
try {
|
||||||
tagList = await messenger.messages.tags.list();
|
tagList = await messenger.messages.tags.list();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
@ -177,7 +145,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const accounts = await messenger.accounts.list(true);
|
const accounts = await messenger.accounts.list(true);
|
||||||
accountList = accounts.map(a => ({ id: a.id, name: a.name }));
|
|
||||||
const collect = (f, prefix='') => {
|
const collect = (f, prefix='') => {
|
||||||
folderList.push({ id: f.id ?? f.path, name: prefix + f.name });
|
folderList.push({ id: f.id ?? f.path, name: prefix + f.name });
|
||||||
(f.subFolders || []).forEach(sf => collect(sf, prefix + f.name + '/'));
|
(f.subFolders || []).forEach(sf => collect(sf, prefix + f.name + '/'));
|
||||||
|
@ -199,19 +166,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
const rulesContainer = document.getElementById('rules-container');
|
const rulesContainer = document.getElementById('rules-container');
|
||||||
const addRuleBtn = document.getElementById('add-rule');
|
const addRuleBtn = document.getElementById('add-rule');
|
||||||
|
|
||||||
const ruleCountEl = document.getElementById('rule-count');
|
|
||||||
const cacheCountEl = document.getElementById('cache-count');
|
|
||||||
const queueCountEl = document.getElementById('queue-count');
|
|
||||||
const currentTimeEl = document.getElementById('current-time');
|
|
||||||
const lastTimeEl = document.getElementById('last-time');
|
|
||||||
const averageTimeEl = document.getElementById('average-time');
|
|
||||||
const totalTimeEl = document.getElementById('total-time');
|
|
||||||
const perHourEl = document.getElementById('per-hour');
|
|
||||||
const perDayEl = document.getElementById('per-day');
|
|
||||||
let timingLogged = false;
|
|
||||||
ruleCountEl.textContent = (defaults.aiRules || []).length;
|
|
||||||
cacheCountEl.textContent = defaults.aiCache ? Object.keys(defaults.aiCache).length : 0;
|
|
||||||
|
|
||||||
function createActionRow(action = {type: 'tag'}) {
|
function createActionRow(action = {type: 'tag'}) {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'action-row field is-grouped mb-2';
|
row.className = 'action-row field is-grouped mb-2';
|
||||||
|
@ -219,7 +173,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
const typeWrapper = document.createElement('div');
|
const typeWrapper = document.createElement('div');
|
||||||
typeWrapper.className = 'select is-small mr-2';
|
typeWrapper.className = 'select is-small mr-2';
|
||||||
const typeSelect = document.createElement('select');
|
const typeSelect = document.createElement('select');
|
||||||
['tag','move','copy','junk','read','flag','delete','archive','forward','reply'].forEach(t => {
|
['tag','move','junk'].forEach(t => {
|
||||||
const opt = document.createElement('option');
|
const opt = document.createElement('option');
|
||||||
opt.value = t;
|
opt.value = t;
|
||||||
opt.textContent = t;
|
opt.textContent = t;
|
||||||
|
@ -246,7 +200,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
sel.value = action.tagKey || '';
|
sel.value = action.tagKey || '';
|
||||||
wrap.appendChild(sel);
|
wrap.appendChild(sel);
|
||||||
paramSpan.appendChild(wrap);
|
paramSpan.appendChild(wrap);
|
||||||
} else if (typeSelect.value === 'move' || typeSelect.value === 'copy') {
|
} else if (typeSelect.value === 'move') {
|
||||||
const wrap = document.createElement('div');
|
const wrap = document.createElement('div');
|
||||||
wrap.className = 'select is-small';
|
wrap.className = 'select is-small';
|
||||||
const sel = document.createElement('select');
|
const sel = document.createElement('select');
|
||||||
|
@ -257,7 +211,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
opt.textContent = f.name;
|
opt.textContent = f.name;
|
||||||
sel.appendChild(opt);
|
sel.appendChild(opt);
|
||||||
}
|
}
|
||||||
sel.value = action.folder || action.copyTarget || '';
|
sel.value = action.folder || '';
|
||||||
wrap.appendChild(sel);
|
wrap.appendChild(sel);
|
||||||
paramSpan.appendChild(wrap);
|
paramSpan.appendChild(wrap);
|
||||||
} else if (typeSelect.value === 'junk') {
|
} else if (typeSelect.value === 'junk') {
|
||||||
|
@ -270,45 +224,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
sel.value = String(action.junk ?? true);
|
sel.value = String(action.junk ?? true);
|
||||||
wrap.appendChild(sel);
|
wrap.appendChild(sel);
|
||||||
paramSpan.appendChild(wrap);
|
paramSpan.appendChild(wrap);
|
||||||
} else if (typeSelect.value === 'read') {
|
|
||||||
const wrap = document.createElement('div');
|
|
||||||
wrap.className = 'select is-small';
|
|
||||||
const sel = document.createElement('select');
|
|
||||||
sel.className = 'read-select';
|
|
||||||
sel.appendChild(new Option('mark read','true'));
|
|
||||||
sel.appendChild(new Option('mark unread','false'));
|
|
||||||
sel.value = String(action.read ?? true);
|
|
||||||
wrap.appendChild(sel);
|
|
||||||
paramSpan.appendChild(wrap);
|
|
||||||
} else if (typeSelect.value === 'flag') {
|
|
||||||
const wrap = document.createElement('div');
|
|
||||||
wrap.className = 'select is-small';
|
|
||||||
const sel = document.createElement('select');
|
|
||||||
sel.className = 'flag-select';
|
|
||||||
sel.appendChild(new Option('flag','true'));
|
|
||||||
sel.appendChild(new Option('unflag','false'));
|
|
||||||
sel.value = String(action.flagged ?? true);
|
|
||||||
wrap.appendChild(sel);
|
|
||||||
paramSpan.appendChild(wrap);
|
|
||||||
} else if (typeSelect.value === 'forward') {
|
|
||||||
const input = document.createElement('input');
|
|
||||||
input.type = 'text';
|
|
||||||
input.className = 'input is-small forward-input';
|
|
||||||
input.placeholder = 'address@example.com';
|
|
||||||
input.value = action.address || '';
|
|
||||||
paramSpan.appendChild(input);
|
|
||||||
} else if (typeSelect.value === 'reply') {
|
|
||||||
const wrap = document.createElement('div');
|
|
||||||
wrap.className = 'select is-small';
|
|
||||||
const sel = document.createElement('select');
|
|
||||||
sel.className = 'reply-select';
|
|
||||||
sel.appendChild(new Option('all','all'));
|
|
||||||
sel.appendChild(new Option('sender','sender'));
|
|
||||||
sel.value = action.replyType || 'all';
|
|
||||||
wrap.appendChild(sel);
|
|
||||||
paramSpan.appendChild(wrap);
|
|
||||||
} else if (typeSelect.value === 'delete' || typeSelect.value === 'archive') {
|
|
||||||
paramSpan.appendChild(document.createElement('span'));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -328,41 +243,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createConditionButton(label, sectionEl, checkbox, clearFn) {
|
|
||||||
const btn = document.createElement('button');
|
|
||||||
btn.type = 'button';
|
|
||||||
btn.className = 'button is-small is-light';
|
|
||||||
const icon = document.createElement('img');
|
|
||||||
icon.width = 16;
|
|
||||||
icon.height = 16;
|
|
||||||
icon.className = 'mr-1';
|
|
||||||
btn.appendChild(icon);
|
|
||||||
btn.append(label);
|
|
||||||
|
|
||||||
let active = checkbox ? checkbox.checked : sectionEl && !sectionEl.classList.contains('is-hidden');
|
|
||||||
|
|
||||||
function update() {
|
|
||||||
btn.classList.toggle('is-active', active);
|
|
||||||
icon.src = browser.runtime.getURL(`resources/svg/${active ? 'circledot' : 'circle'}.svg`);
|
|
||||||
if (sectionEl) sectionEl.classList.toggle('is-hidden', !active);
|
|
||||||
if (checkbox) checkbox.checked = active;
|
|
||||||
if (!active && typeof clearFn === 'function') {
|
|
||||||
clearFn();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
btn.addEventListener('click', () => {
|
|
||||||
active = !active;
|
|
||||||
markDirty();
|
|
||||||
update();
|
|
||||||
});
|
|
||||||
|
|
||||||
update();
|
|
||||||
return btn;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderRules(rules = []) {
|
function renderRules(rules = []) {
|
||||||
ruleCountEl.textContent = rules.length;
|
|
||||||
rulesContainer.innerHTML = '';
|
rulesContainer.innerHTML = '';
|
||||||
for (const rule of rules) {
|
for (const rule of rules) {
|
||||||
const article = document.createElement('article');
|
const article = document.createElement('article');
|
||||||
|
@ -394,67 +275,13 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
|
|
||||||
const header = document.createElement('div');
|
const header = document.createElement('div');
|
||||||
header.className = 'message-header';
|
header.className = 'message-header';
|
||||||
|
header.appendChild(critInput);
|
||||||
const leftWrap = document.createElement('div');
|
|
||||||
leftWrap.style.display = 'flex';
|
|
||||||
leftWrap.style.alignItems = 'center';
|
|
||||||
leftWrap.style.flexGrow = '1';
|
|
||||||
|
|
||||||
const statusSpan = document.createElement('span');
|
|
||||||
statusSpan.className = 'rule-status has-text-weight-semibold mr-2';
|
|
||||||
|
|
||||||
leftWrap.appendChild(statusSpan);
|
|
||||||
leftWrap.appendChild(critInput);
|
|
||||||
header.appendChild(leftWrap);
|
|
||||||
|
|
||||||
const btnWrap = document.createElement('div');
|
|
||||||
btnWrap.style.display = 'flex';
|
|
||||||
btnWrap.style.gap = '0.25em';
|
|
||||||
|
|
||||||
let enabled = rule.enabled !== false;
|
|
||||||
|
|
||||||
const toggleBtn = document.createElement('button');
|
|
||||||
toggleBtn.type = 'button';
|
|
||||||
toggleBtn.className = 'button is-small is-light rule-toggle';
|
|
||||||
const toggleIcon = document.createElement('img');
|
|
||||||
toggleIcon.width = 16;
|
|
||||||
toggleIcon.height = 16;
|
|
||||||
toggleBtn.appendChild(toggleIcon);
|
|
||||||
|
|
||||||
const delBtn = document.createElement('button');
|
const delBtn = document.createElement('button');
|
||||||
delBtn.type = 'button';
|
delBtn.className = 'delete';
|
||||||
delBtn.className = 'button is-small is-danger is-light rule-delete';
|
delBtn.setAttribute('aria-label', 'delete');
|
||||||
const delIcon = document.createElement('img');
|
delBtn.addEventListener('click', () => article.remove());
|
||||||
delIcon.src = browser.runtime.getURL('resources/svg/trash.svg');
|
header.appendChild(delBtn);
|
||||||
delIcon.width = 16;
|
|
||||||
delIcon.height = 16;
|
|
||||||
delBtn.appendChild(delIcon);
|
|
||||||
|
|
||||||
function updateToggle() {
|
|
||||||
toggleIcon.src = browser.runtime.getURL(
|
|
||||||
`resources/svg/${enabled ? 'circleslash' : 'check'}.svg`
|
|
||||||
);
|
|
||||||
statusSpan.textContent = enabled ? '' : '(Disabled)';
|
|
||||||
article.dataset.enabled = String(enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
toggleBtn.addEventListener('click', () => {
|
|
||||||
enabled = !enabled;
|
|
||||||
markDirty();
|
|
||||||
updateToggle();
|
|
||||||
});
|
|
||||||
|
|
||||||
delBtn.addEventListener('click', () => {
|
|
||||||
article.remove();
|
|
||||||
ruleCountEl.textContent = rulesContainer.querySelectorAll('.rule').length;
|
|
||||||
markDirty();
|
|
||||||
});
|
|
||||||
|
|
||||||
btnWrap.appendChild(toggleBtn);
|
|
||||||
btnWrap.appendChild(delBtn);
|
|
||||||
header.appendChild(btnWrap);
|
|
||||||
|
|
||||||
updateToggle();
|
|
||||||
|
|
||||||
const actionsContainer = document.createElement('div');
|
const actionsContainer = document.createElement('div');
|
||||||
actionsContainer.className = 'rule-actions mb-2';
|
actionsContainer.className = 'rule-actions mb-2';
|
||||||
|
@ -470,7 +297,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
addAction.addEventListener('click', () => actionsContainer.appendChild(createActionRow()));
|
addAction.addEventListener('click', () => actionsContainer.appendChild(createActionRow()));
|
||||||
|
|
||||||
const stopLabel = document.createElement('label');
|
const stopLabel = document.createElement('label');
|
||||||
stopLabel.className = 'checkbox mt-2 is-hidden';
|
stopLabel.className = 'checkbox mt-2';
|
||||||
const stopCheck = document.createElement('input');
|
const stopCheck = document.createElement('input');
|
||||||
stopCheck.type = 'checkbox';
|
stopCheck.type = 'checkbox';
|
||||||
stopCheck.className = 'stop-processing';
|
stopCheck.className = 'stop-processing';
|
||||||
|
@ -478,130 +305,11 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
stopLabel.appendChild(stopCheck);
|
stopLabel.appendChild(stopCheck);
|
||||||
stopLabel.append(' Stop after match');
|
stopLabel.append(' Stop after match');
|
||||||
|
|
||||||
const unreadLabel = document.createElement('label');
|
|
||||||
unreadLabel.className = 'checkbox mt-2 ml-4 is-hidden';
|
|
||||||
const unreadCheck = document.createElement('input');
|
|
||||||
unreadCheck.type = 'checkbox';
|
|
||||||
unreadCheck.className = 'unread-only';
|
|
||||||
unreadCheck.checked = rule.unreadOnly === true;
|
|
||||||
unreadLabel.appendChild(unreadCheck);
|
|
||||||
unreadLabel.append(' Only apply to unread messages');
|
|
||||||
|
|
||||||
const ageBox = document.createElement('div');
|
|
||||||
ageBox.className = 'field is-grouped mt-2 is-hidden';
|
|
||||||
const minInput = document.createElement('input');
|
|
||||||
minInput.type = 'number';
|
|
||||||
minInput.placeholder = 'Min days';
|
|
||||||
minInput.className = 'input is-small min-age mr-2';
|
|
||||||
minInput.style.width = '6em';
|
|
||||||
if (typeof rule.minAgeDays === 'number') minInput.value = rule.minAgeDays;
|
|
||||||
const maxInput = document.createElement('input');
|
|
||||||
maxInput.type = 'number';
|
|
||||||
maxInput.placeholder = 'Max days';
|
|
||||||
maxInput.className = 'input is-small max-age';
|
|
||||||
maxInput.style.width = '6em';
|
|
||||||
if (typeof rule.maxAgeDays === 'number') maxInput.value = rule.maxAgeDays;
|
|
||||||
ageBox.appendChild(minInput);
|
|
||||||
ageBox.appendChild(maxInput);
|
|
||||||
|
|
||||||
const acctBox = document.createElement('div');
|
|
||||||
acctBox.className = 'field mt-2 is-hidden';
|
|
||||||
const acctLabel = document.createElement('label');
|
|
||||||
acctLabel.className = 'label';
|
|
||||||
acctLabel.textContent = 'Accounts';
|
|
||||||
const acctControl = document.createElement('div');
|
|
||||||
const acctWrap = document.createElement('div');
|
|
||||||
acctWrap.className = 'select is-multiple is-small';
|
|
||||||
const acctSel = document.createElement('select');
|
|
||||||
acctSel.className = 'account-select';
|
|
||||||
acctSel.multiple = true;
|
|
||||||
acctSel.size = Math.min(accountList.length, 4) || 1;
|
|
||||||
for (const a of accountList) {
|
|
||||||
const opt = document.createElement('option');
|
|
||||||
opt.value = a.id;
|
|
||||||
opt.textContent = a.name;
|
|
||||||
if ((rule.accounts || []).includes(a.id)) opt.selected = true;
|
|
||||||
acctSel.appendChild(opt);
|
|
||||||
}
|
|
||||||
acctWrap.appendChild(acctSel);
|
|
||||||
acctControl.appendChild(acctWrap);
|
|
||||||
acctBox.appendChild(acctLabel);
|
|
||||||
acctBox.appendChild(acctControl);
|
|
||||||
|
|
||||||
const folderBox = document.createElement('div');
|
|
||||||
folderBox.className = 'field mt-2 is-hidden';
|
|
||||||
const folderLabel = document.createElement('label');
|
|
||||||
folderLabel.className = 'label';
|
|
||||||
folderLabel.textContent = 'Folders';
|
|
||||||
const folderControl = document.createElement('div');
|
|
||||||
const folderWrap = document.createElement('div');
|
|
||||||
folderWrap.className = 'select is-multiple is-small';
|
|
||||||
const folderSel = document.createElement('select');
|
|
||||||
folderSel.className = 'folder-filter-select';
|
|
||||||
folderSel.multiple = true;
|
|
||||||
folderSel.size = Math.min(folderList.length, 6) || 1;
|
|
||||||
for (const f of folderList) {
|
|
||||||
const opt = document.createElement('option');
|
|
||||||
opt.value = f.id;
|
|
||||||
opt.textContent = f.name;
|
|
||||||
if ((rule.folders || []).includes(f.id)) opt.selected = true;
|
|
||||||
folderSel.appendChild(opt);
|
|
||||||
}
|
|
||||||
folderWrap.appendChild(folderSel);
|
|
||||||
folderControl.appendChild(folderWrap);
|
|
||||||
folderBox.appendChild(folderLabel);
|
|
||||||
folderBox.appendChild(folderControl);
|
|
||||||
|
|
||||||
if (typeof rule.minAgeDays === 'number' || typeof rule.maxAgeDays === 'number') {
|
|
||||||
ageBox.classList.remove('is-hidden');
|
|
||||||
}
|
|
||||||
if ((rule.accounts || []).length) {
|
|
||||||
acctBox.classList.remove('is-hidden');
|
|
||||||
}
|
|
||||||
if ((rule.folders || []).length) {
|
|
||||||
folderBox.classList.remove('is-hidden');
|
|
||||||
}
|
|
||||||
|
|
||||||
const condButtons = document.createElement('div');
|
|
||||||
condButtons.className = 'field is-grouped is-grouped-multiline mb-2';
|
|
||||||
|
|
||||||
function addCond(btn) {
|
|
||||||
const p = document.createElement('p');
|
|
||||||
p.className = 'control';
|
|
||||||
p.appendChild(btn);
|
|
||||||
condButtons.appendChild(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
addCond(createConditionButton('Stop', null, stopCheck, () => {
|
|
||||||
stopCheck.checked = false;
|
|
||||||
}));
|
|
||||||
addCond(createConditionButton('Unread', null, unreadCheck, () => {
|
|
||||||
unreadCheck.checked = false;
|
|
||||||
}));
|
|
||||||
addCond(createConditionButton('Age', ageBox, null, () => {
|
|
||||||
minInput.value = '';
|
|
||||||
maxInput.value = '';
|
|
||||||
}));
|
|
||||||
addCond(createConditionButton('Accounts', acctBox, null, () => {
|
|
||||||
for (const opt of acctSel.options) opt.selected = false;
|
|
||||||
}));
|
|
||||||
addCond(createConditionButton('Folders', folderBox, null, () => {
|
|
||||||
for (const opt of folderSel.options) opt.selected = false;
|
|
||||||
}));
|
|
||||||
|
|
||||||
const body = document.createElement('div');
|
const body = document.createElement('div');
|
||||||
body.className = 'message-body';
|
body.className = 'message-body';
|
||||||
body.appendChild(actionsContainer);
|
body.appendChild(actionsContainer);
|
||||||
body.appendChild(addAction);
|
body.appendChild(addAction);
|
||||||
const condDivider = document.createElement('hr');
|
|
||||||
condDivider.className = 'mt-3 mb-2';
|
|
||||||
body.appendChild(condDivider);
|
|
||||||
body.appendChild(condButtons);
|
|
||||||
body.appendChild(stopLabel);
|
body.appendChild(stopLabel);
|
||||||
body.appendChild(unreadLabel);
|
|
||||||
body.appendChild(ageBox);
|
|
||||||
body.appendChild(acctBox);
|
|
||||||
body.appendChild(folderBox);
|
|
||||||
|
|
||||||
article.appendChild(header);
|
article.appendChild(header);
|
||||||
article.appendChild(body);
|
article.appendChild(body);
|
||||||
|
@ -621,65 +329,38 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
if (type === 'move') {
|
if (type === 'move') {
|
||||||
return { type, folder: row.querySelector('.folder-select').value };
|
return { type, folder: row.querySelector('.folder-select').value };
|
||||||
}
|
}
|
||||||
if (type === 'copy') {
|
|
||||||
return { type, copyTarget: row.querySelector('.folder-select').value };
|
|
||||||
}
|
|
||||||
if (type === 'junk') {
|
if (type === 'junk') {
|
||||||
return { type, junk: row.querySelector('.junk-select').value === 'true' };
|
return { type, junk: row.querySelector('.junk-select').value === 'true' };
|
||||||
}
|
}
|
||||||
if (type === 'read') {
|
|
||||||
return { type, read: row.querySelector('.read-select').value === 'true' };
|
|
||||||
}
|
|
||||||
if (type === 'flag') {
|
|
||||||
return { type, flagged: row.querySelector('.flag-select').value === 'true' };
|
|
||||||
}
|
|
||||||
if (type === 'delete' || type === 'archive') {
|
|
||||||
return { type };
|
|
||||||
}
|
|
||||||
return { type };
|
return { type };
|
||||||
});
|
});
|
||||||
const stopProcessing = ruleEl.querySelector('.stop-processing')?.checked;
|
const stopProcessing = ruleEl.querySelector('.stop-processing')?.checked;
|
||||||
const unreadOnly = ruleEl.querySelector('.unread-only')?.checked;
|
return { criterion, actions, stopProcessing };
|
||||||
const enabled = ruleEl.dataset.enabled !== 'false';
|
|
||||||
const minAgeDays = parseFloat(ruleEl.querySelector('.min-age')?.value);
|
|
||||||
const maxAgeDays = parseFloat(ruleEl.querySelector('.max-age')?.value);
|
|
||||||
const accounts = [...(ruleEl.querySelector('.account-select')?.selectedOptions || [])].map(o => o.value);
|
|
||||||
const folders = [...(ruleEl.querySelector('.folder-filter-select')?.selectedOptions || [])].map(o => o.value);
|
|
||||||
const rule = { criterion, actions, enabled };
|
|
||||||
if (unreadOnly) rule.unreadOnly = true;
|
|
||||||
if (stopProcessing) rule.stopProcessing = true;
|
|
||||||
if (!isNaN(minAgeDays)) rule.minAgeDays = minAgeDays;
|
|
||||||
if (!isNaN(maxAgeDays)) rule.maxAgeDays = maxAgeDays;
|
|
||||||
if (accounts.length) rule.accounts = accounts;
|
|
||||||
if (folders.length) rule.folders = folders;
|
|
||||||
return rule;
|
|
||||||
});
|
});
|
||||||
data.push({ criterion: '', actions: [], unreadOnly: false, stopProcessing: false, enabled: true, accounts: [], folders: [] });
|
data.push({ criterion: '', actions: [], stopProcessing: false });
|
||||||
renderRules(data);
|
renderRules(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
renderRules((defaults.aiRules || []).map(r => {
|
renderRules((defaults.aiRules || []).map(r => {
|
||||||
if (r.actions) {
|
if (r.actions) return r;
|
||||||
if (!Array.isArray(r.accounts)) r.accounts = [];
|
|
||||||
if (!Array.isArray(r.folders)) r.folders = [];
|
|
||||||
if (r.enabled !== false) r.enabled = true; else r.enabled = false;
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
const actions = [];
|
const actions = [];
|
||||||
if (r.tag) actions.push({ type: 'tag', tagKey: r.tag });
|
if (r.tag) actions.push({ type: 'tag', tagKey: r.tag });
|
||||||
if (r.moveTo) actions.push({ type: 'move', folder: r.moveTo });
|
if (r.moveTo) actions.push({ type: 'move', folder: r.moveTo });
|
||||||
if (r.copyTarget || r.copyTo) actions.push({ type: 'copy', copyTarget: r.copyTarget || r.copyTo });
|
|
||||||
const rule = { criterion: r.criterion, actions };
|
const rule = { criterion: r.criterion, actions };
|
||||||
if (r.stopProcessing) rule.stopProcessing = true;
|
if (r.stopProcessing) rule.stopProcessing = true;
|
||||||
if (r.unreadOnly) rule.unreadOnly = true;
|
|
||||||
if (typeof r.minAgeDays === 'number') rule.minAgeDays = r.minAgeDays;
|
|
||||||
if (typeof r.maxAgeDays === 'number') rule.maxAgeDays = r.maxAgeDays;
|
|
||||||
if (Array.isArray(r.accounts)) rule.accounts = r.accounts;
|
|
||||||
if (Array.isArray(r.folders)) rule.folders = r.folders;
|
|
||||||
rule.enabled = r.enabled !== false;
|
|
||||||
return rule;
|
return rule;
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const ruleCountEl = document.getElementById('rule-count');
|
||||||
|
const cacheCountEl = document.getElementById('cache-count');
|
||||||
|
const queueCountEl = document.getElementById('queue-count');
|
||||||
|
const currentTimeEl = document.getElementById('current-time');
|
||||||
|
const lastTimeEl = document.getElementById('last-time');
|
||||||
|
const averageTimeEl = document.getElementById('average-time');
|
||||||
|
const totalTimeEl = document.getElementById('total-time');
|
||||||
|
let timingLogged = false;
|
||||||
|
ruleCountEl.textContent = (defaults.aiRules || []).length;
|
||||||
|
cacheCountEl.textContent = defaults.aiCache ? Object.keys(defaults.aiCache).length : 0;
|
||||||
|
|
||||||
function format(ms) {
|
function format(ms) {
|
||||||
if (ms < 0) return '--:--:--';
|
if (ms < 0) return '--:--:--';
|
||||||
|
@ -720,10 +401,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
}
|
}
|
||||||
averageTimeEl.textContent = stats.runs > 0 ? format(stats.average) : '--:--:--';
|
averageTimeEl.textContent = stats.runs > 0 ? format(stats.average) : '--:--:--';
|
||||||
totalTimeEl.textContent = format(stats.total);
|
totalTimeEl.textContent = format(stats.total);
|
||||||
const perHour = stats.average > 0 ? Math.round(3600000 / stats.average) : 0;
|
|
||||||
const perDay = stats.average > 0 ? Math.round(86400000 / stats.average) : 0;
|
|
||||||
perHourEl.textContent = perHour;
|
|
||||||
perDayEl.textContent = perDay;
|
|
||||||
if (!timingLogged) {
|
if (!timingLogged) {
|
||||||
logger.aiLog('retrieved timing stats', {debug: true});
|
logger.aiLog('retrieved timing stats', {debug: true});
|
||||||
timingLogged = true;
|
timingLogged = true;
|
||||||
|
@ -734,48 +411,14 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
lastTimeEl.textContent = '--:--:--';
|
lastTimeEl.textContent = '--:--:--';
|
||||||
averageTimeEl.textContent = '--:--:--';
|
averageTimeEl.textContent = '--:--:--';
|
||||||
totalTimeEl.textContent = '--:--:--';
|
totalTimeEl.textContent = '--:--:--';
|
||||||
perHourEl.textContent = '0';
|
|
||||||
perDayEl.textContent = '0';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ruleCountEl.textContent = document.querySelectorAll('#rules-container .rule').length;
|
||||||
try {
|
try {
|
||||||
const { aiCache } = await storage.local.get('aiCache');
|
cacheCountEl.textContent = await AiClassifier.getCacheSize();
|
||||||
cacheCountEl.textContent = aiCache ? Object.keys(aiCache).length : 0;
|
|
||||||
} catch {
|
} catch {
|
||||||
cacheCountEl.textContent = '?';
|
cacheCountEl.textContent = '?';
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
if (debugTabToggle.checked) {
|
|
||||||
const latest = await storage.local.get(['lastPayload', 'lastFullText', 'lastPromptText']);
|
|
||||||
const payloadStr = latest.lastPayload ? JSON.stringify(latest.lastPayload, null, 2) : '';
|
|
||||||
if (payloadStr !== lastPayload) {
|
|
||||||
lastPayload = payloadStr;
|
|
||||||
payloadDisplay.textContent = payloadStr;
|
|
||||||
}
|
|
||||||
if (latest.lastFullText !== lastFullText || latest.lastPromptText !== lastPromptText) {
|
|
||||||
lastFullText = latest.lastFullText || '';
|
|
||||||
lastPromptText = latest.lastPromptText || '';
|
|
||||||
if (lastFullText && lastPromptText && diff_match_patch) {
|
|
||||||
const dmp = new diff_match_patch();
|
|
||||||
dmp.Diff_EditCost = 4;
|
|
||||||
const diffs = dmp.diff_main(lastFullText, lastPromptText);
|
|
||||||
dmp.diff_cleanupEfficiency(diffs);
|
|
||||||
const hasDiff = diffs.some(d => d[0] !== 0);
|
|
||||||
if (hasDiff) {
|
|
||||||
diffDisplay.innerHTML = dmp.diff_prettyHtml(diffs);
|
|
||||||
diffContainer.classList.remove('is-hidden');
|
|
||||||
} else {
|
|
||||||
diffDisplay.innerHTML = '';
|
|
||||||
diffContainer.classList.add('is-hidden');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
diffDisplay.innerHTML = '';
|
|
||||||
diffContainer.classList.add('is-hidden');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshMaintenance();
|
refreshMaintenance();
|
||||||
|
@ -830,50 +473,20 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
if (type === 'move') {
|
if (type === 'move') {
|
||||||
return { type, folder: row.querySelector('.folder-select').value };
|
return { type, folder: row.querySelector('.folder-select').value };
|
||||||
}
|
}
|
||||||
if (type === 'copy') {
|
|
||||||
return { type, copyTarget: row.querySelector('.folder-select').value };
|
|
||||||
}
|
|
||||||
if (type === 'junk') {
|
if (type === 'junk') {
|
||||||
return { type, junk: row.querySelector('.junk-select').value === 'true' };
|
return { type, junk: row.querySelector('.junk-select').value === 'true' };
|
||||||
}
|
}
|
||||||
if (type === 'read') {
|
|
||||||
return { type, read: row.querySelector('.read-select').value === 'true' };
|
|
||||||
}
|
|
||||||
if (type === 'flag') {
|
|
||||||
return { type, flagged: row.querySelector('.flag-select').value === 'true' };
|
|
||||||
}
|
|
||||||
if (type === 'forward') {
|
|
||||||
return { type, address: row.querySelector('.forward-input').value.trim() };
|
|
||||||
}
|
|
||||||
if (type === 'reply') {
|
|
||||||
return { type, replyType: row.querySelector('.reply-select').value };
|
|
||||||
}
|
|
||||||
return { type };
|
return { type };
|
||||||
});
|
});
|
||||||
const stopProcessing = ruleEl.querySelector('.stop-processing')?.checked;
|
const stopProcessing = ruleEl.querySelector('.stop-processing')?.checked;
|
||||||
const unreadOnly = ruleEl.querySelector('.unread-only')?.checked;
|
return { criterion, actions, stopProcessing };
|
||||||
const enabled = ruleEl.dataset.enabled !== 'false';
|
|
||||||
const minAgeDays = parseFloat(ruleEl.querySelector('.min-age')?.value);
|
|
||||||
const maxAgeDays = parseFloat(ruleEl.querySelector('.max-age')?.value);
|
|
||||||
const accounts = [...(ruleEl.querySelector('.account-select')?.selectedOptions || [])].map(o => o.value);
|
|
||||||
const folders = [...(ruleEl.querySelector('.folder-filter-select')?.selectedOptions || [])].map(o => o.value);
|
|
||||||
const rule = { criterion, actions, enabled };
|
|
||||||
if (unreadOnly) rule.unreadOnly = true;
|
|
||||||
if (stopProcessing) rule.stopProcessing = true;
|
|
||||||
if (!isNaN(minAgeDays)) rule.minAgeDays = minAgeDays;
|
|
||||||
if (!isNaN(maxAgeDays)) rule.maxAgeDays = maxAgeDays;
|
|
||||||
if (accounts.length) rule.accounts = accounts;
|
|
||||||
if (folders.length) rule.folders = folders;
|
|
||||||
return rule;
|
|
||||||
}).filter(r => r.criterion);
|
}).filter(r => r.criterion);
|
||||||
const stripUrlParams = stripUrlToggle.checked;
|
const stripUrlParams = stripUrlToggle.checked;
|
||||||
const altTextImages = altTextToggle.checked;
|
const altTextImages = altTextToggle.checked;
|
||||||
const collapseWhitespace = collapseWhitespaceToggle.checked;
|
const collapseWhitespace = collapseWhitespaceToggle.checked;
|
||||||
const tokenReduction = tokenReductionToggle.checked;
|
|
||||||
const showDebugTab = debugTabToggle.checked;
|
|
||||||
const theme = themeSelect.value;
|
const theme = themeSelect.value;
|
||||||
await storage.local.set({ endpoint, templateName, customTemplate: customTemplateText, customSystemPrompt, aiParams: aiParamsSave, debugLogging, htmlToMarkdown, stripUrlParams, altTextImages, collapseWhitespace, tokenReduction, aiRules: rules, theme, showDebugTab });
|
await storage.local.set({ endpoint, templateName, customTemplate: customTemplateText, customSystemPrompt, aiParams: aiParamsSave, debugLogging, htmlToMarkdown, stripUrlParams, altTextImages, collapseWhitespace, aiRules: rules, theme });
|
||||||
await applyTheme(theme);
|
applyTheme(theme);
|
||||||
try {
|
try {
|
||||||
await AiClassifier.setConfig({ endpoint, templateName, customTemplate: customTemplateText, customSystemPrompt, aiParams: aiParamsSave, debugLogging });
|
await AiClassifier.setConfig({ endpoint, templateName, customTemplate: customTemplateText, customSystemPrompt, aiParams: aiParamsSave, debugLogging });
|
||||||
logger.setDebug(debugLogging);
|
logger.setDebug(debugLogging);
|
||||||
|
|
Before Width: | Height: | Size: 413 B |
Before Width: | Height: | Size: 828 B |
Before Width: | Height: | Size: 1.7 KiB |
Before Width: | Height: | Size: 408 B |
Before Width: | Height: | Size: 813 B |
Before Width: | Height: | Size: 1.7 KiB |
Before Width: | Height: | Size: 392 B |
Before Width: | Height: | Size: 768 B |
Before Width: | Height: | Size: 1.6 KiB |
Before Width: | Height: | Size: 393 B |
Before Width: | Height: | Size: 764 B |
Before Width: | Height: | Size: 1.5 KiB |
Before Width: | Height: | Size: 199 B |
Before Width: | Height: | Size: 301 B |
Before Width: | Height: | Size: 431 B |
Before Width: | Height: | Size: 215 B |
Before Width: | Height: | Size: 305 B |
Before Width: | Height: | Size: 457 B |
|
@ -1,4 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" data-attribution="cc0-icons" viewBox="0 0 24 24">
|
|
||||||
<path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"/>
|
|
||||||
<path d="M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z"/>
|
|
||||||
</svg>
|
|
Before Width: | Height: | Size: 357 B |
|
@ -1,3 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" data-attribution="cc0-icons" viewBox="0 0 24 24">
|
|
||||||
<path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Zm-7-3L19 5"/>
|
|
||||||
</svg>
|
|
Before Width: | Height: | Size: 317 B |
|
@ -1,3 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" data-attribution="cc0-icons" viewBox="0 0 24 24">
|
|
||||||
<path d="M21 12H3m9-9v18"/>
|
|
||||||
</svg>
|
|
Before Width: | Height: | Size: 250 B |