dsh-feiyu-memgate 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +73 -12
  2. package/README.md +68 -11
  3. package/README.zh.md +93 -36
  4. package/client/README.md +267 -0
  5. package/client/art/mascot-asleep.webp +0 -0
  6. package/client/art/mascot-busy.webp +0 -0
  7. package/client/art/mascot-nag.webp +0 -0
  8. package/client/art/mascot-ready.webp +0 -0
  9. package/client/art/mascot-trouble.webp +0 -0
  10. package/client/client.js +4226 -1269
  11. package/client/src/clipboard.cjs +52 -0
  12. package/client/src/constants.cjs +43 -0
  13. package/client/src/fields.cjs +960 -0
  14. package/client/src/hooks.cjs +220 -0
  15. package/client/src/i18n.cjs +444 -0
  16. package/client/src/index.cjs +69 -0
  17. package/client/src/kit/controls.cjs +189 -0
  18. package/client/src/kit/icons.cjs +40 -0
  19. package/client/src/kit/layout.cjs +124 -0
  20. package/client/src/layout.cjs +143 -0
  21. package/client/src/model/changelog.cjs +29 -0
  22. package/client/src/model/feedback.cjs +168 -0
  23. package/client/src/model/form.cjs +83 -0
  24. package/client/src/model/models.cjs +87 -0
  25. package/client/src/model/overview.cjs +111 -0
  26. package/client/src/model/page.cjs +104 -0
  27. package/client/src/model/status.cjs +57 -0
  28. package/client/src/model/trial.cjs +111 -0
  29. package/client/src/net.cjs +101 -0
  30. package/client/src/react.cjs +11 -0
  31. package/client/src/theme/page.css +1284 -0
  32. package/client/src/theme/styles.cjs +43 -0
  33. package/client/src/view/feedback.cjs +180 -0
  34. package/client/src/view/field-row.cjs +98 -0
  35. package/client/src/view/hero.cjs +54 -0
  36. package/client/src/view/markdown.cjs +96 -0
  37. package/client/src/view/models.cjs +154 -0
  38. package/client/src/view/page.cjs +199 -0
  39. package/client/src/view/settings-tab.cjs +78 -0
  40. package/client/src/view/tabs.cjs +71 -0
  41. package/client/src/view/trial.cjs +84 -0
  42. package/docs/DETAIL.en.md +55 -6
  43. package/docs/DETAIL.md +63 -14
  44. package/locale/zh.json +1 -1
  45. package/package.json +2 -1
  46. package/python/GATEWAY_VERSION.json +37 -31
  47. package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
  48. package/python/feiyu_memgate/backends/base.py +121 -6
  49. package/python/feiyu_memgate/backends/embedding.py +265 -178
  50. package/python/feiyu_memgate/backends/hybrid.py +330 -83
  51. package/python/feiyu_memgate/backends/inmemory.py +115 -24
  52. package/python/feiyu_memgate/backends/openviking.py +7 -10
  53. package/python/feiyu_memgate/backends/sqlite.py +129 -145
  54. package/python/feiyu_memgate/builtins.py +1 -0
  55. package/python/feiyu_memgate/cli.py +124 -20
  56. package/python/feiyu_memgate/client/block.py +4 -2
  57. package/python/feiyu_memgate/client/http.py +106 -19
  58. package/python/feiyu_memgate/client/local.py +4 -3
  59. package/python/feiyu_memgate/config.py +118 -24
  60. package/python/feiyu_memgate/core/limits.py +2 -1
  61. package/python/feiyu_memgate/core/pool.py +29 -2
  62. package/python/feiyu_memgate/core/recall.py +179 -10
  63. package/python/feiyu_memgate/core/redact.py +4 -2
  64. package/python/feiyu_memgate/core/stages.py +52 -9
  65. package/python/feiyu_memgate/core/tidy.py +2 -1
  66. package/python/feiyu_memgate/core/watch.py +3 -2
  67. package/python/feiyu_memgate/core/write.py +9 -3
  68. package/python/feiyu_memgate/forgetting/archive.py +38 -10
  69. package/python/feiyu_memgate/forgetting/engine.py +46 -10
  70. package/python/feiyu_memgate/forgetting/stage.py +4 -2
  71. package/python/feiyu_memgate/gateway/app.py +168 -272
  72. package/python/feiyu_memgate/gateway/fields.py +121 -0
  73. package/python/feiyu_memgate/gateway/policies.py +162 -0
  74. package/python/feiyu_memgate/gateway/server.py +12 -4
  75. package/python/feiyu_memgate/gateway/tokens.py +137 -0
  76. package/python/feiyu_memgate/gateway/validate.py +120 -0
  77. package/python/feiyu_memgate/identity.py +152 -0
  78. package/python/feiyu_memgate/model.py +170 -2
  79. package/python/feiyu_memgate/registry.py +6 -3
  80. package/python/feiyu_memgate/tools/crypto.py +5 -4
  81. package/python/feiyu_memgate/tools/evaluate.py +2 -1
  82. package/python/feiyu_memgate/tools/tenants.py +2 -0
  83. package/src/block.js +9 -3
  84. package/src/capture.js +98 -0
  85. package/src/catalogue.js +4 -4
  86. package/src/changelog.js +72 -0
  87. package/src/client.js +145 -10
  88. package/src/commands.js +112 -62
  89. package/src/config.js +139 -62
  90. package/src/followup.js +139 -0
  91. package/src/gateway.js +79 -4
  92. package/src/migrate.py +54 -9
  93. package/src/mirror.py +44 -7
  94. package/src/plugin.js +416 -412
  95. package/src/pool.js +298 -0
  96. package/src/recent.js +68 -0
  97. package/src/relevance.js +80 -0
  98. package/src/routes.js +320 -0
  99. package/src/setup.js +36 -36
  100. package/src/shared.js +77 -0
  101. package/src/tiers.js +4 -4
  102. package/src/time.js +27 -0
  103. package/src/tools.js +164 -0
@@ -0,0 +1,43 @@
1
+ 'use strict'
2
+ // Puts the page's stylesheet (theme/page.css) into the document, once, and takes it out again.
3
+ //
4
+ // The page cannot use inline styles alone: hover, keyboard focus, container widths and reduced
5
+ // motion only exist in a stylesheet. The host has no rule against a plugin adding a <style> element
6
+ // (it installs its own plugins' styles the same way), so that is what this does. The element is
7
+ // found again by its id, so loading the plugin twice never adds a second copy.
8
+
9
+ const CSS = require('./page.css')
10
+
11
+ const STYLE_ID = 'dsh-feiyu-memgate-styles'
12
+
13
+ /**
14
+ * Add the stylesheet to a document.
15
+ * @param {Document | undefined} doc the page's document; undefined outside a browser (tests)
16
+ * @returns {() => void} removes the stylesheet again (called when the plugin is unloaded)
17
+ */
18
+ function installStyles(doc) {
19
+ if (!doc || !doc.head || typeof doc.createElement !== 'function') return () => {}
20
+ let element = doc.getElementById(STYLE_ID)
21
+ if (!element) {
22
+ element = doc.createElement('style')
23
+ element.id = STYLE_ID
24
+ doc.head.appendChild(element)
25
+ }
26
+ // Written every time: after an update of the plugin the old element may still hold the old rules.
27
+ element.textContent = CSS
28
+ return () => {
29
+ if (element.parentNode) element.parentNode.removeChild(element)
30
+ }
31
+ }
32
+
33
+ /** Class names joined, skipping whatever is empty: cx('fmg-row', sub && 'fmg-row--sub'). */
34
+ function cx() {
35
+ let out = ''
36
+ for (let i = 0; i < arguments.length; i += 1) {
37
+ const part = arguments[i]
38
+ if (part) out += (out ? ' ' : '') + part
39
+ }
40
+ return out
41
+ }
42
+
43
+ module.exports = { STYLE_ID, installStyles, cx }
@@ -0,0 +1,180 @@
1
+ 'use strict'
2
+ // The Feedback tab: a few words to the people who make the plugin.
3
+ //
4
+ // Where the page knows a receiver (constants.cjs FEEDBACK_ENDPOINT) the tab is one thing: write, then
5
+ // Send. Send posts the report to the project's feedback receiver (feedback-worker/), where only the
6
+ // maintainers can read it; it needs no account anywhere.
7
+ //
8
+ // Two other ways exist, and each is a click the person makes:
9
+ // GitHub a plain link to GitHub's new-issue page with the title and the text filled in
10
+ // (model/feedback.cjs builds the address); the person reads it once more there and
11
+ // submits it under their own account. Public.
12
+ // Copy the whole report on the clipboard, to send any other way.
13
+ // They are what the tab offers while there is no receiver, and what it falls back to when a Send
14
+ // failed, so that what was written is never stuck. Next to a working Send they are not shown.
15
+ //
16
+ // What is attached besides the person's own words is shown in full before anything leaves: the
17
+ // environment lines are listed under the switch that attaches them, and they are the same lines that
18
+ // go into the report.
19
+ //
20
+ // Beside the title sits a small drawing with a speech bubble (Nag, below).
21
+ //
22
+ // The draft (kind, text, whether to attach the environment) is kept by the page
23
+ // (view/page.cjs), so that looking something up on another tab does not lose what was written.
24
+
25
+ const { h, useState } = require('../react.cjs')
26
+ const { ART_ROUTE, FEEDBACK_ENDPOINT, ID_PREFIX, LINKS } = require('../constants.cjs')
27
+ const { useCopy, useSend } = require('../hooks.cjs')
28
+ const { KINDS, MAX_TEXT, compose, environment, payload, reportText, usableEndpoint } = require('../model/feedback.cjs')
29
+ const { Button, Choices, Switch, TextArea } = require('../kit/controls.cjs')
30
+ const { Icon } = require('../kit/icons.cjs')
31
+ const { Facts, Group, Notice, Reveal } = require('../kit/layout.cjs')
32
+
33
+ // From this share of the limit on, the tab says how much room is left.
34
+ const COUNT_FROM = 0.8
35
+
36
+ /** The draft a page starts with: an idea, nothing written, the environment attached. */
37
+ function emptyFeedback() {
38
+ return { kind: KINDS[0], text: '', environment: true }
39
+ }
40
+
41
+ /**
42
+ * The small drawing at the head of the tab: the mascot points at a black cat asleep on the floor (the
43
+ * cat stands for the developers) and a speech bubble, which is text of the page and so follows the
44
+ * language, tells it to hurry up with the update. Decoration like the hero's drawing: it fades in when
45
+ * it has arrived, the bubble appears with it, and when the drawing cannot be loaded nothing is drawn.
46
+ * @param {{ t: Function }} props
47
+ */
48
+ function Nag(props) {
49
+ const { t } = props
50
+ // One object, so that the state of this component can be told from the other hooks' in tests.
51
+ const [art, setArt] = useState({ loaded: false, failed: false })
52
+ if (art.failed) return null
53
+ return h('div', { className: 'fmg-nag' },
54
+ h('img', {
55
+ src: ART_ROUTE + 'mascot-nag.webp',
56
+ alt: t('mascot.nag'),
57
+ draggable: false,
58
+ width: 360,
59
+ height: 378,
60
+ 'data-shown': art.loaded ? 'true' : 'false',
61
+ onLoad: () => setArt({ loaded: true, failed: false }),
62
+ onError: () => setArt({ loaded: false, failed: true }),
63
+ }),
64
+ // The alt text of the drawing already says it, so the bubble is not read out a second time.
65
+ art.loaded ? h('span', { className: 'fmg-nag__bubble', 'aria-hidden': 'true' }, t('feedback.nag')) : null)
66
+ }
67
+
68
+ /**
69
+ * @param {{ t: Function, status: { data: object | null },
70
+ * draft: { kind: string, text: string, environment: boolean },
71
+ * onChange: (patch: object) => void, endpoint?: string, send?: Function,
72
+ * copy?: (text: string) => Promise<boolean> }} props
73
+ * `onChange` merges a patch into the draft. `endpoint` replaces the receiver's address (tests and
74
+ * the preview; an empty text means there is none), `send` the browser's fetch for that one call,
75
+ * `copy` the clipboard.
76
+ */
77
+ function FeedbackTab(props) {
78
+ const { t, status, draft, onChange } = props
79
+ const endpoint = usableEndpoint(props.endpoint === undefined ? FEEDBACK_ENDPOINT : props.endpoint)
80
+ const copier = useCopy(props.copy)
81
+ const sender = useSend(endpoint, props.send)
82
+ const rows = environment(status.data)
83
+ const attached = draft.environment && rows.length > 0
84
+ const report = compose({ kind: draft.kind, text: draft.text, environment: attached ? rows : [], cutNote: t('feedback.cutNote') })
85
+ const whole = reportText(report)
86
+ const length = Array.from(draft.text).length
87
+ const sending = sender.phase === 'sending'
88
+
89
+ const kindId = ID_PREFIX + '-feedback-kind'
90
+ const textId = ID_PREFIX + '-feedback-text'
91
+ const envId = ID_PREFIX + '-feedback-environment'
92
+ const title = t('feedback.title')
93
+
94
+ // Send: on success the text is cleared, so the same report cannot be sent twice by a second click.
95
+ const send = () => {
96
+ sender.send(payload(draft, attached ? rows : [])).then((sent) => { if (sent) onChange({ text: '' }) })
97
+ }
98
+
99
+ // The other ways are on the tab while there is no receiver, and after a Send that failed.
100
+ const failed = sender.phase === 'failed'
101
+ const otherWays = !endpoint || failed
102
+
103
+ // The way to GitHub: a link when there is something to take there, a disabled button until then
104
+ // (a link cannot be disabled). It is the main action only while there is no receiver.
105
+ const githubText = [t('feedback.submit'), h(Icon, { key: 'icon', name: 'external', size: 13 })]
106
+ const github = report.ready
107
+ ? h('a', {
108
+ className: endpoint ? 'fmg-button' : 'fmg-button fmg-button--primary',
109
+ href: report.url,
110
+ target: '_blank',
111
+ rel: 'noreferrer noopener',
112
+ // A report too long for an address travels by the clipboard: copy it on the way out.
113
+ onClick: report.clipped ? () => { copier.copy(whole) } : undefined,
114
+ }, githubText)
115
+ : h(Button, { variant: endpoint ? undefined : 'primary', disabled: true }, githubText)
116
+
117
+ const copyButton = h(Button, { key: 'copy', disabled: !report.ready, onClick: () => { copier.copy(whole) } }, t('feedback.copy'))
118
+ const copySaid = copier.state ? h('span', { key: 'said', className: copier.state === 'copied' ? 'fmg-quiet' : 'fmg-row__error', role: 'status' },
119
+ t(copier.state === 'copied' ? 'feedback.copied' : 'feedback.copyFailed')) : null
120
+
121
+ // What became of the last Send. The thanks stay until the person starts writing again; a failure
122
+ // says why and brings the other two ways with it.
123
+ let outcome = null
124
+ if (sender.phase === 'sent' && !report.ready) {
125
+ outcome = h(Notice, { role: 'status' }, h('p', { className: 'fmg-actions' }, h(Icon, { name: 'check' }), t('feedback.sent')))
126
+ } else if (failed) {
127
+ outcome = h(Notice, { tone: 'warn', role: 'alert' },
128
+ h('p', null, sender.code === 'HTTP 429' ? t('feedback.failedBusy') : t('feedback.failed', { code: sender.code || '' })),
129
+ h('div', { className: 'fmg-actions' }, github, copyButton, copySaid))
130
+ }
131
+
132
+ return h('section', { className: 'fmg-section', 'aria-label': title },
133
+ h('div', { className: 'fmg-section__head fmg-feedback__head' },
134
+ h('div', { className: 'fmg-feedback__intro' },
135
+ h('h4', { className: 'fmg-section__title' }, title),
136
+ h('p', { className: 'fmg-note' }, t('feedback.intro'))),
137
+ h(Nag, { t })),
138
+ h(Group, null,
139
+ h('div', { className: 'fmg-row fmg-row--stack' },
140
+ h('div', { className: 'fmg-row__text' },
141
+ h('div', { className: 'fmg-row__label' }, h('span', { id: kindId + '-label' }, t('feedback.kind')))),
142
+ h('div', { className: 'fmg-row__control' },
143
+ h(Choices, {
144
+ labelledBy: kindId + '-label',
145
+ value: draft.kind,
146
+ disabled: sending,
147
+ options: KINDS.map((kind) => ({ value: kind, name: t('feedback.kind.' + kind), note: t('feedback.kind.' + kind + '.note') })),
148
+ onChange: (kind) => onChange({ kind }),
149
+ }))),
150
+ h('div', { className: 'fmg-row fmg-row--stack' },
151
+ h('div', { className: 'fmg-row__control fmg-row__control--stack' },
152
+ h(TextArea, { id: textId, value: draft.text, rows: 7, maxLength: MAX_TEXT, disabled: sending, label: t('feedback.text'), placeholder: t('feedback.placeholder'), onChange: (text) => onChange({ text }) }),
153
+ length >= MAX_TEXT * COUNT_FROM
154
+ ? h('span', { className: 'fmg-quiet', role: 'status' }, t('feedback.count', { count: length, max: MAX_TEXT }))
155
+ : null)),
156
+ h('div', { className: 'fmg-row' },
157
+ h('div', { className: 'fmg-row__text' },
158
+ h('div', { className: 'fmg-row__label' }, h('label', { htmlFor: envId }, t('feedback.env'))),
159
+ h('p', { className: 'fmg-row__help', id: envId + '-help' }, rows.length ? t('feedback.env.help') : t('feedback.env.none'))),
160
+ h('div', { className: 'fmg-row__control' },
161
+ h(Switch, {
162
+ id: envId, checked: attached, label: t('feedback.env'), describedBy: envId + '-help', disabled: rows.length === 0 || sending,
163
+ onChange: (next) => onChange({ environment: next }),
164
+ }))),
165
+ h(Reveal, { open: attached, id: envId + '-lines' }, h(Facts, { rows }))),
166
+ endpoint
167
+ ? h(Notice, { role: 'note' }, h('p', null, t('feedback.howDirect')))
168
+ : h(Notice, { role: 'note' }, h('p', null, t('feedback.how')), h('p', null, t('feedback.public'))),
169
+ outcome,
170
+ // The warning is about the address for GitHub, so it is shown where that link is.
171
+ report.clipped && otherWays ? h(Notice, { tone: 'warn', role: 'status' }, h('p', null, t('feedback.clipped'))) : null,
172
+ endpoint
173
+ ? h('div', { className: 'fmg-actions' },
174
+ h(Button, { variant: 'primary', disabled: !report.ready || sending, onClick: send }, t(sending ? 'feedback.sending' : 'feedback.send')))
175
+ : h('div', { className: 'fmg-actions' },
176
+ github, copyButton, copySaid,
177
+ h('a', { className: 'fmg-link fmg-actions__end', href: LINKS.issues, target: '_blank', rel: 'noreferrer noopener' }, t('feedback.others'))))
178
+ }
179
+
180
+ module.exports = { emptyFeedback, FeedbackTab, Nag }
@@ -0,0 +1,98 @@
1
+ 'use strict'
2
+ // One setting as one row: its name, what it does, and the control that fits its kind.
3
+ //
4
+ // boolean a switch at the right end of the row
5
+ // integer a stepper with its unit at the right end
6
+ // choice the options with their meanings, under the text
7
+ // string a text line under the text; a secret is write-only and shows only whether one is stored
8
+ //
9
+ // The row follows the host's settings conventions: an edit is staged, not written; a setting that
10
+ // differs from its inherited value carries a tag and a "Reset" that stages the return; a draft the
11
+ // field cannot accept shows why instead of the help text being lost (both are shown).
12
+
13
+ const { h } = require('../react.cjs')
14
+ const { ID_PREFIX } = require('../constants.cjs')
15
+ const { splitOption } = require('../model/page.cjs')
16
+ const { cx } = require('../theme/styles.cjs')
17
+ const { Button, Tag, Switch, TextInput, Stepper, Choices } = require('../kit/controls.cjs')
18
+
19
+ /** The element id of a setting's control: 'advanced.recallLimit' → 'feiyu-memgate-advanced-recallLimit'. */
20
+ function fieldId(k) {
21
+ return ID_PREFIX + '-' + k.replace('.', '-')
22
+ }
23
+
24
+ /** Why a draft is refused, in words. */
25
+ function invalidText(t, field) {
26
+ return field.kind === 'integer' ? t('invalidInteger', { min: field.min, max: field.max }) : t('invalidUrl')
27
+ }
28
+
29
+ /**
30
+ * @param {{ t: Function, lang: 'en' | 'zh', row: { view: object, parent: string | null }, disabled: boolean,
31
+ * edit: (k: string, value: unknown) => void, reset: (k: string) => void }} props
32
+ * `row` comes from model/page.cjs sectionView(); `edit` stages a value, `reset` stages a return to
33
+ * the inherited value (for a secret: clearing it).
34
+ */
35
+ function FieldRow(props) {
36
+ const { t, lang, row, disabled, edit, reset } = props
37
+ const view = row.view
38
+ const field = view.field
39
+ const k = view.k
40
+ const id = fieldId(k)
41
+ const labelId = id + '-label'
42
+ const helpId = id + '-help'
43
+ const label = t('f.' + k)
44
+
45
+ let control
46
+ let stacked = false
47
+ let labelled = true // whether the label element can point at one control with htmlFor
48
+ let help = t('h.' + k)
49
+ const tags = []
50
+ if (field.experimental) tags.push(h(Tag, { key: 'experimental', tone: 'blush' }, t('experimental')))
51
+
52
+ if (view.secret) {
53
+ stacked = true
54
+ if (view.configured !== null) tags.push(h(Tag, { key: 'stored', tone: view.configured ? 'ok' : undefined }, t(view.configured ? 'secretSet' : 'secretUnset')))
55
+ help = view.clearing ? t('secretClearing') : help + ' ' + t('secretHint')
56
+ control = h('div', { className: 'fmg-input-line' },
57
+ h(TextInput, { id, type: 'password', autoComplete: 'new-password', value: view.text, disabled, describedBy: helpId, onChange: (text) => edit(k, text) }),
58
+ view.configured || view.text ? h(Button, { variant: 'text', disabled: disabled || view.clearing, onClick: () => reset(k) }, t('secretClear')) : null)
59
+ } else if (field.kind === 'boolean') {
60
+ control = h(Switch, { id, checked: view.value === true, label, describedBy: helpId, disabled, onChange: (next) => edit(k, next) })
61
+ } else if (field.kind === 'integer') {
62
+ control = [
63
+ h(Stepper, {
64
+ key: 'stepper', id, text: view.text, min: field.min, max: field.max, invalid: view.invalid, disabled, describedBy: helpId,
65
+ labels: { down: t('stepDown'), up: t('stepUp') }, onChange: (text) => edit(k, text),
66
+ }),
67
+ field.unit ? h('span', { key: 'unit', className: 'fmg-quiet' }, field.unit[lang] || field.unit.en) : null,
68
+ ]
69
+ } else if (field.kind === 'choice') {
70
+ stacked = true
71
+ labelled = false
72
+ control = h(Choices, {
73
+ labelledBy: labelId, describedBy: helpId, value: view.value, disabled,
74
+ options: field.options.map((option) => Object.assign({ value: option.value }, splitOption(t('o.' + k + '.' + option.value)))),
75
+ onChange: (value) => edit(k, value),
76
+ })
77
+ } else {
78
+ stacked = true
79
+ control = h('div', { className: 'fmg-input-line' },
80
+ h(TextInput, { id, value: view.text, invalid: view.invalid, disabled, describedBy: helpId, onChange: (text) => edit(k, text) }))
81
+ }
82
+
83
+ if (view.overridden) {
84
+ tags.push(h(Tag, { key: 'changed', tone: 'sea' }, t('overridden')))
85
+ tags.push(h(Button, { key: 'reset', variant: 'text', disabled, onClick: () => reset(k) }, t('reset')))
86
+ }
87
+
88
+ return h('div', { className: cx('fmg-row', stacked && 'fmg-row--stack', row.parent && 'fmg-row--sub') },
89
+ h('div', { className: 'fmg-row__text' },
90
+ h('div', { className: 'fmg-row__label' },
91
+ labelled ? h('label', { id: labelId, htmlFor: id }, label) : h('span', { id: labelId }, label),
92
+ tags),
93
+ h('p', { className: 'fmg-row__help', id: helpId }, help),
94
+ view.invalid ? h('p', { className: 'fmg-row__error', role: 'alert' }, invalidText(t, field)) : null),
95
+ h('div', { className: 'fmg-row__control' }, control))
96
+ }
97
+
98
+ module.exports = { fieldId, invalidText, FieldRow }
@@ -0,0 +1,54 @@
1
+ 'use strict'
2
+ // The top of the page: how memory is doing, said three ways at once. A headline with a coloured dot,
3
+ // one line of explanation, and the mascot in the mood that fits (model/overview.cjs decides which).
4
+ //
5
+ // The drawing is the one decorative thing on the page and is treated as such: it is loaded from the
6
+ // plugin's own route, fades in when it has arrived, and when it cannot be loaded (an older host, a
7
+ // blocked request) the card simply has no drawing. Nothing a person needs is only in the picture.
8
+
9
+ const { h, useState } = require('../react.cjs')
10
+ const { ART_ROUTE } = require('../constants.cjs')
11
+ const { cx } = require('../theme/styles.cjs')
12
+
13
+ /** The address of the drawing for a mood ('ready' | 'busy' | 'asleep' | 'trouble'). */
14
+ function artUrl(mood) {
15
+ return ART_ROUTE + 'mascot-' + mood + '.webp'
16
+ }
17
+
18
+ /**
19
+ * @param {{ t: Function, summary: { mood: string, headline: object, line: object, facts: object[] } }} props
20
+ * `summary` is model/overview.cjs summarise().
21
+ */
22
+ function Hero(props) {
23
+ const { t, summary } = props
24
+ const mood = summary.mood
25
+ // Which drawings have arrived, and whether one failed (then none is tried again on this page).
26
+ const [art, setArt] = useState({ loaded: {}, failed: false })
27
+ const drawing = art.failed ? null : h('div', { className: 'fmg-hero__art' },
28
+ h('img', {
29
+ key: mood,
30
+ src: artUrl(mood),
31
+ alt: t('mascot.' + mood),
32
+ draggable: false,
33
+ 'data-shown': art.loaded[mood] ? 'true' : 'false',
34
+ onLoad: () => setArt((previous) => (previous.loaded[mood] ? previous : { loaded: Object.assign({}, previous.loaded, { [mood]: true }), failed: false })),
35
+ onError: () => setArt({ loaded: {}, failed: true }),
36
+ }))
37
+ return h('header', { className: 'fmg-hero' },
38
+ h('div', { className: 'fmg-hero__sea', 'aria-hidden': 'true' }, h('i'), h('i'), h('i')),
39
+ // role="status": a change of state is read out; the poll re-renders the same text without a change.
40
+ h('div', { className: 'fmg-hero__text', role: 'status' },
41
+ h('h4', { className: 'fmg-hero__head' },
42
+ h('span', { className: 'fmg-dot', 'data-mood': mood, 'aria-hidden': 'true' }),
43
+ t(summary.headline.key, summary.headline.params)),
44
+ h('p', { className: 'fmg-hero__line' }, t(summary.line.key, summary.line.params)),
45
+ summary.facts.length
46
+ ? h('ul', { className: 'fmg-hero__facts' }, summary.facts.map((fact) => h('li', {
47
+ key: fact.id,
48
+ className: cx('fmg-fact', fact.tone === 'warn' && 'fmg-fact--warn'),
49
+ }, t(fact.key, fact.params))))
50
+ : null),
51
+ drawing)
52
+ }
53
+
54
+ module.exports = { artUrl, Hero }
@@ -0,0 +1,96 @@
1
+ 'use strict'
2
+
3
+ // The changelog's Markdown subset: text in, React elements out. Headings, lists (one nested level),
4
+ // paragraphs, `code`, **bold** and https links; everything else stays text. The elements are built
5
+ // from strings here, so there is no path from the changelog file to raw HTML on the page.
6
+ // How they look is the stylesheet's business (`.fmg-md` in theme/page.css).
7
+
8
+ const { h } = require('../react.cjs')
9
+
10
+ const INLINE = /`([^`]+)`|\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)/g
11
+ const CJK = /[\u2e80-\u9fff\uf900-\ufaff\uff00-\uffef]/
12
+
13
+ /** Inline marks in a line of text: `code`, **bold**, [text](https://...). Anything else, tags included, stays text. */
14
+ function inlineMarkdown(text) {
15
+ const out = []
16
+ let last = 0
17
+ let n = 0
18
+ let match
19
+ INLINE.lastIndex = 0
20
+ while ((match = INLINE.exec(text)) !== null) {
21
+ if (match.index > last) out.push(text.slice(last, match.index))
22
+ n += 1
23
+ if (match[1] !== undefined) out.push(h('code', { key: 'c' + n, className: 'fmg-code' }, match[1]))
24
+ else if (match[2] !== undefined) out.push(h('strong', { key: 'b' + n }, match[2]))
25
+ else if (/^https:\/\//i.test(match[4])) out.push(h('a', { key: 'a' + n, href: match[4], target: '_blank', rel: 'noopener noreferrer', className: 'fmg-link' }, match[3]))
26
+ else out.push(match[3]) // any other address is shown as its text, not a link
27
+ last = match.index + match[0].length
28
+ }
29
+ if (last < text.length) out.push(text.slice(last))
30
+ return out
31
+ }
32
+
33
+ // Lines of one paragraph joined the way they read: no space between two Chinese characters.
34
+ function joinLines(lines) {
35
+ let out = ''
36
+ for (const line of lines) {
37
+ if (out && !(CJK.test(out[out.length - 1]) && CJK.test(line[0]))) out += ' '
38
+ out += line
39
+ }
40
+ return out
41
+ }
42
+
43
+ /**
44
+ * A changelog body as React elements: ### headings, - list items (one nested level, by indentation),
45
+ * paragraphs. Text goes in as text; there is no path from the file to raw HTML.
46
+ */
47
+ function renderMarkdown(body) {
48
+ const lines = String(body === undefined || body === null ? '' : body).replace(/\r\n?/g, '\n').split('\n')
49
+ const blocks = []
50
+ let para = null
51
+ let list = null
52
+ let tail = null // the item (top or nested) a continuation line belongs to
53
+ const flushPara = () => {
54
+ if (para) blocks.push(h('p', { key: 'p' + blocks.length }, inlineMarkdown(joinLines(para))))
55
+ para = null
56
+ }
57
+ const flushList = () => {
58
+ if (list) {
59
+ const key = 'l' + blocks.length
60
+ const items = (entries, prefix) => entries.map((item, index) => h('li', { key: prefix + index },
61
+ inlineMarkdown(item.text), item.children && item.children.length ? h('ul', null, items(item.children, prefix + index + '.')) : null))
62
+ blocks.push(h('ul', { key }, items(list, key)))
63
+ }
64
+ list = null
65
+ tail = null
66
+ }
67
+ for (const line of lines) {
68
+ let match
69
+ if (!line.trim()) {
70
+ flushPara()
71
+ flushList()
72
+ } else if ((match = /^#{1,6}[ \t]+(.+?)[ \t]*$/.exec(line))) {
73
+ flushPara()
74
+ flushList()
75
+ blocks.push(h('h5', { key: 'h' + blocks.length }, inlineMarkdown(match[1])))
76
+ } else if ((match = /^([ \t]*)[-*][ \t]+(.*)$/.exec(line))) {
77
+ flushPara()
78
+ if (!list) list = []
79
+ const item = { text: match[2].trim(), children: [] }
80
+ if (match[1].length >= 2 && list.length) list[list.length - 1].children.push(item)
81
+ else list.push(item)
82
+ tail = item
83
+ } else if (list && tail && /^[ \t]+\S/.test(line)) {
84
+ tail.text = joinLines([tail.text, line.trim()])
85
+ } else {
86
+ flushList()
87
+ if (!para) para = []
88
+ para.push(line.trim())
89
+ }
90
+ }
91
+ flushPara()
92
+ flushList()
93
+ return blocks
94
+ }
95
+
96
+ module.exports = { inlineMarkdown, joinLines, renderMarkdown }
@@ -0,0 +1,154 @@
1
+ 'use strict'
2
+ // The local embedding models: what each costs, where it stands, and its one button.
3
+ //
4
+ // Nothing here downloads or installs by itself. A click on "Download and enable" names what will be
5
+ // fetched; when the add-on plugin is missing, the page first says what installing it brings and
6
+ // waits for a second yes. The host half checks the same things again (src/setup.js): this file is
7
+ // the conversation, not the gate.
8
+
9
+ const { h, useState } = require('../react.cjs')
10
+ const { ID_PREFIX } = require('../constants.cjs')
11
+ const { useModels } = require('../hooks.cjs')
12
+ const { pickText, formatSize, memoryText, modelActions, chainLine, sameProblem } = require('../model/models.cjs')
13
+ const { Button, Tag } = require('../kit/controls.cjs')
14
+ const { Group, Notice, Progress } = require('../kit/layout.cjs')
15
+
16
+ // Where "measured retrieval quality" leads before the host half has answered with its own link.
17
+ const QUALITY_LINK = 'https://github.com/N0rmal-114/feiyu-memgate#部署档位'
18
+
19
+ /** A failure with what to do about it, as the host half worded it ({ title, todo }, each { en, zh }). */
20
+ function Problem(props) {
21
+ const { problem, lang, t } = props
22
+ if (!problem) return null
23
+ return h(Notice, { tone: 'warn', role: 'alert' },
24
+ h('p', null, pickText(problem.title, lang), ' ', h('strong', null, t('todo')), ' ', pickText(problem.todo, lang)))
25
+ }
26
+
27
+ /** An outside link that opens in a new tab without handing the page over to it. */
28
+ function OutLink(props) {
29
+ return h('a', { className: 'fmg-link', href: props.href, target: '_blank', rel: 'noreferrer noopener' }, props.children)
30
+ }
31
+
32
+ /**
33
+ * One model.
34
+ * @param {{ t: Function, lang: string, model: object, view: object, accepted: boolean, pending: boolean,
35
+ * onAccept: (id: string, value: boolean) => void, onAction: (action: string, model: object) => void }} props
36
+ */
37
+ function ModelRow(props) {
38
+ const { t, lang, model, view, accepted, onAccept, onAction, pending } = props
39
+ const acts = modelActions(model, view, accepted)
40
+ const languages = (model.languages || []).map((l) => (t('language.' + l) === 'language.' + l ? l : t('language.' + l))).join(lang === 'zh' ? '、' : ', ')
41
+ // The memory the add-on measured for the running model process (loaded), never the file size.
42
+ const memory = memoryText(model.memoryMB, t)
43
+ const licence = model.license
44
+ ? (model.license.url ? h(OutLink, { href: model.license.url }, model.license.name) : model.license.name)
45
+ : '?'
46
+ const acceptId = ID_PREFIX + '-accept-' + model.id
47
+ const press = (action) => () => { if (action) onAction(action, model) }
48
+ const downloading = model.state === 'downloading' && model.percent !== null && model.percent !== undefined
49
+ // The primary action is a button only while it can lead somewhere; a state that offers nothing to
50
+ // press ("In use", "Loading", "Downloading 42%") is said as text, not as a greyed-out button.
51
+ const primaryLabel = t(acts.primary.label[0], acts.primary.label[1])
52
+ const primary = acts.primary.action
53
+ ? h(Button, { variant: 'primary', disabled: pending || !acts.primary.enabled, onClick: press(acts.primary.action) }, primaryLabel)
54
+ : model.state === 'active' ? h(Tag, { tone: 'ok' }, primaryLabel) : h('span', { className: 'fmg-note', role: 'status' }, primaryLabel)
55
+ return h('li', { className: 'fmg-model' },
56
+ h('div', { className: 'fmg-model__text' },
57
+ h('div', { className: 'fmg-model__name' },
58
+ model.id,
59
+ model.tierLabel ? h(Tag, null, pickText(model.tierLabel, lang)) : null,
60
+ model.status === 'unverified' ? h(Tag, { tone: 'warn' }, t('unverified')) : null,
61
+ model.pinned ? h(Tag, null, t('pinned')) : null),
62
+ model.note ? h('p', { className: 'fmg-note' }, pickText(model.note, lang)) : null,
63
+ h('p', { className: 'fmg-model__facts' },
64
+ h('span', null, t('colSize') + ' ' + formatSize(model.sizeBytes)),
65
+ h('span', null, t('colMemory') + ' ' + memory),
66
+ h('span', null, t('colLanguages') + ' ' + (languages || '?')),
67
+ h('span', null, t('colLicence') + ' ', licence))),
68
+ h('div', { className: 'fmg-actions' },
69
+ primary,
70
+ acts.secondary ? h(Button, { disabled: pending, onClick: press(acts.secondary.action) }, t(acts.secondary.label[0])) : null),
71
+ downloading ? h('div', { className: 'fmg-model__wide' }, h(Progress, { percent: model.percent, label: t('actDownloading', { percent: model.percent }) })) : null,
72
+ model.requiresAcceptance && model.state === 'absent'
73
+ ? h('label', { className: 'fmg-check fmg-model__wide', htmlFor: acceptId },
74
+ h('input', { id: acceptId, type: 'checkbox', checked: accepted, onChange: (event) => onAccept(model.id, event.target.checked) }),
75
+ t('acceptLabel', { name: model.requiresAcceptance.name }),
76
+ model.requiresAcceptance.url ? h(OutLink, { href: model.requiresAcceptance.url }, model.requiresAcceptance.url) : null)
77
+ : null)
78
+ }
79
+
80
+ /**
81
+ * The panel: the introduction, whatever needs saying about the setup, and the list.
82
+ * @param {{ t: Function, lang: string, fetch: Function, onChange?: () => void }} props
83
+ * `onChange` is called when a model became active (the status has changed with it).
84
+ */
85
+ function ModelsPanel(props) {
86
+ const { t, lang } = props
87
+ const models = useModels(props.fetch, props.onChange)
88
+ const [accepted, setAccepted] = useState({}) // model id → the licence box is ticked
89
+ const [confirm, setConfirm] = useState(null) // the model waiting for the add-on confirmation
90
+ const [declined, setDeclined] = useState(false)
91
+ const view = models.view
92
+
93
+ // `confirmed`: the person pressed the button that names the download (and, when the add-on is
94
+ // missing, confirmed what it installs); the host route refuses an install without it.
95
+ const installBody = (model) => {
96
+ const body = { action: 'install', id: model.id, confirmed: true }
97
+ if (model.requiresAcceptance) body.acceptLicence = model.requiresAcceptance.name
98
+ return body
99
+ }
100
+ const onAction = (action, model) => {
101
+ setDeclined(false)
102
+ if (action === 'install' && view.addon.state === 'absent') {
103
+ setConfirm(model.id) // the add-on comes first: say what will be installed, then wait for a yes
104
+ return
105
+ }
106
+ if (action === 'install') return models.send(installBody(model))
107
+ const body = { action }
108
+ if (action !== 'cancel') body.id = model.id
109
+ models.send(body)
110
+ }
111
+
112
+ const intro = h('p', { className: 'fmg-note' }, t('modelsIntro'), ' ', h(OutLink, { href: view ? view.link : QUALITY_LINK }, t('modelsLink')))
113
+ if (!view) {
114
+ return h('div', { className: 'fmg-section' }, intro,
115
+ h('p', { className: 'fmg-note', role: 'status' }, models.error ? t('modelsFailed', { code: models.error }) : t('modelsLoading')))
116
+ }
117
+ const waiting = confirm ? view.models.find((model) => model.id === confirm) : null
118
+ const line = chainLine(view, t)
119
+ const chainError = view.chain && view.chain.error
120
+ return h('div', { className: 'fmg-section' },
121
+ intro,
122
+ models.error ? h('p', { className: 'fmg-note', role: 'status' }, t('modelsFailed', { code: models.error })) : null,
123
+ view.python && view.python.problem ? h(Problem, { problem: view.python.problem, lang, t }) : null,
124
+ line ? h(Notice, { role: 'status' }, h('p', null, line)) : null,
125
+ chainError ? h(Problem, { problem: chainError, lang, t }) : null,
126
+ // The answer to a click and the stored state of the setup often carry the same failure: show it once.
127
+ models.refusal && !sameProblem(models.refusal, chainError) ? h(Problem, { problem: models.refusal, lang, t }) : null,
128
+ declined ? h('p', { className: 'fmg-note', role: 'status' }, t('declined')) : null,
129
+ view.builds
130
+ ? h(Notice, { tone: 'warn', role: 'group', label: t('phase.builds') },
131
+ h('p', null, h('strong', null, t('phase.builds')), ' ', pickText(view.builds.note, lang)),
132
+ h('div', { className: 'fmg-actions' },
133
+ h(Button, { variant: 'primary', disabled: models.pending, onClick: () => models.send({ action: 'builds', allow: true, confirmed: true }) }, t('buildsAllow')),
134
+ h(Button, { disabled: models.pending, onClick: () => models.send({ action: 'builds', allow: false, confirmed: true }) }, t('buildsDeny'))))
135
+ : null,
136
+ waiting
137
+ ? h(Notice, { role: 'group', label: t('modelsTitle') },
138
+ h('p', null, view.confirm
139
+ ? pickText(view.confirm, lang).replace('{model}', waiting.id).replace('{size}', formatSize(waiting.sizeBytes))
140
+ : t('confirmAddon', { model: waiting.id, size: formatSize(waiting.sizeBytes) })),
141
+ h('div', { className: 'fmg-actions' },
142
+ h(Button, { variant: 'primary', disabled: models.pending, onClick: () => { setConfirm(null); models.send(installBody(waiting)) } }, t('confirmYes')),
143
+ h(Button, { disabled: models.pending, onClick: () => { setConfirm(null); setDeclined(true) } }, t('confirmNo'))))
144
+ : null,
145
+ h(Group, null, h('ul', { className: 'fmg-rows' },
146
+ view.models.map((model) => h(ModelRow, {
147
+ key: model.id, t, lang, model, view, pending: models.pending,
148
+ accepted: accepted[model.id] === true,
149
+ onAccept: (id, value) => setAccepted((previous) => Object.assign({}, previous, { [id]: value })),
150
+ onAction,
151
+ })))))
152
+ }
153
+
154
+ module.exports = { Problem, ModelRow, ModelsPanel }