unlimited ai usage for affine
This commit is contained in:
@@ -204,3 +204,73 @@ chat SSE endpoint also passed, including automatic profile routing.
|
||||
Only the server now owns the imported rotating session; the local active
|
||||
credential copy was removed after remote verification. Images and attachments
|
||||
remain unsupported and are not advertised by the profile.
|
||||
|
||||
## AFFiNE managed trial counter versus provider limits
|
||||
|
||||
`currentUser.copilot.quota { limit used }` describes AFFiNE's managed AI trial,
|
||||
not the connected ChatGPT account's remaining usage. It must not be presented as
|
||||
an OpenAI allowance or an invoice. BYOK execution is authorized independently
|
||||
from quota-backed managed routes and records usage as `byok_server`.
|
||||
|
||||
The pinned release has a legacy accounting edge case: deleted sessions retain
|
||||
`messageCost`, while the BYOK exemption query joins usage billing units to live
|
||||
message rows. Removing test conversations can therefore leave a misleading
|
||||
managed-trial cost after their BYOK message rows disappear. The observed `8/10`
|
||||
was explained by eight such retained units; the connected provider's request
|
||||
history was tagged BYOK, not AFFiNE-managed usage.
|
||||
|
||||
Do not fix this by resetting usage, promoting a plan, granting unlimited quota,
|
||||
or weakening server enforcement. The raw quota and all provider/quota errors
|
||||
remain unchanged. A self-hosted UI should instead identify AI as self-hosted
|
||||
and explain that provider and server limits may apply, without a managed-trial
|
||||
progress bar, Free badge or AFFiNE upgrade action. Cloud quota presentation
|
||||
continues to use the original managed allowance.
|
||||
|
||||
ChatGPT subscription access is already paid for by the account owner; it is not
|
||||
unlimited. OpenAI still enforces the account's model, usage-window and app-access
|
||||
limits. This connector does not add an API-key billing fallback.
|
||||
|
||||
### Verified self-hosted usage rollout
|
||||
|
||||
On 2026-11-06, frontend static package
|
||||
`3s22k6a5p9731xmlr6x33icilcsfkzv2-affine-frontend-static-0.27.4` was copied to
|
||||
`hectic-lab` and mounted over the unchanged backend's static directory. This
|
||||
was a bounded systemd override, **not** a NixOS generation switch: the active
|
||||
and boot generation remain `6rb81fr95gngs99x1dvjw9vzzd7snkn5`. A whole-host
|
||||
build was interrupted rather than activating unrelated package updates.
|
||||
|
||||
The root-owned persistent drop-in is
|
||||
`/etc/systemd/system.control/affine-native.service.d/99-frontend-static-rollout.conf`.
|
||||
It resets `BindReadOnlyPaths` and supplies only the new static bind. This
|
||||
control directory is used because NixOS's `/etc/systemd/system` points into
|
||||
the immutable store. GC roots `affine-frontend-static-rollout` and
|
||||
`affine-frontend-static-rollback` under `/nix/var/nix/gcroots` retain the new
|
||||
bundle and the previous `hrg3dkcacg5drizifiinjx481k6k33d5` bundle.
|
||||
|
||||
Only `affine-native.service` restarted. The migration unit's active timestamp,
|
||||
PostgreSQL, Redis and ChatGPT gateway process IDs and active timestamps stayed
|
||||
unchanged. The running application's mount namespace was checked against the
|
||||
new package's `index.html`; HTTPS `/info` remained healthy. An authenticated
|
||||
headless browser verified the sidebar and account settings on desktop and a
|
||||
Pixel 5 viewport: neutral self-hosted text, no trial count, progress bar or
|
||||
billing action, in both English and Russian. This stable release serves the
|
||||
responsive web application to mobile browsers; upstream's separate mobile shell
|
||||
is canary-only. The separate
|
||||
mobile component is covered by the source-level rendering check.
|
||||
|
||||
A real BYOK text probe succeeded after deployment. AFFiNE's raw managed quota
|
||||
remained `{ limit: 10, used: 8 }` before and after; no accounting records or
|
||||
provider limits were altered. Existing browser sessions need a hard refresh.
|
||||
|
||||
The drop-in survives reboots and NixOS generation rollbacks, and masks future
|
||||
declarative frontend changes until removed. During the next reviewed NixOS
|
||||
switch containing the desired `frontendPackage`, remove this exact drop-in,
|
||||
run `systemctl daemon-reload`, and restart only `affine-native.service` so the
|
||||
declared bind takes effect. Remove the temporary GC roots only after checking
|
||||
that the active generation retains the desired package and rollback retention
|
||||
is no longer needed. Do not use a broad `systemctl revert` operation.
|
||||
|
||||
To roll back this bounded rollout while the original generation remains active,
|
||||
remove that exact drop-in, daemon-reload and restart `affine-native.service`.
|
||||
Its declared unit still binds the previous `hrg3dkcacg5drizifiinjx481k6k33d5`
|
||||
bundle. Confirm health and the effective bind before removing any GC root.
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
openssl,
|
||||
inputs,
|
||||
system,
|
||||
frontendPatches ? [ ./gitea-document-typography.patch ./byok-model-picker.patch ],
|
||||
frontendPatches ? [ ./gitea-document-typography.patch ./byok-model-picker.patch ./self-hosted-ai-usage.patch ],
|
||||
}:
|
||||
|
||||
let
|
||||
@@ -188,11 +188,12 @@ let
|
||||
cp -R packages/frontend/apps/mobile/dist "$out/mobile"
|
||||
runHook postInstall
|
||||
'';
|
||||
} // lib.optionalAttrs (builtins.elem ./byok-model-picker.patch frontendPatches) {
|
||||
} // lib.optionalAttrs (builtins.elem ./byok-model-picker.patch frontendPatches || builtins.elem ./self-hosted-ai-usage.patch frontendPatches) {
|
||||
doCheck = true;
|
||||
checkPhase = ''
|
||||
runHook preCheck
|
||||
AFFINE_SOURCE_DIR="$PWD" ${nodejs}/bin/node ${../../test/package/affine/test/model-picker.cjs}
|
||||
${lib.optionalString (builtins.elem ./byok-model-picker.patch frontendPatches) ''AFFINE_SOURCE_DIR="$PWD" ${nodejs}/bin/node ${../../test/package/affine/test/model-picker.cjs}''}
|
||||
${lib.optionalString (builtins.elem ./self-hosted-ai-usage.patch frontendPatches) ''AFFINE_SOURCE_DIR="$PWD" ${nodejs}/bin/node ${../../test/package/affine/test/ai-usage.cjs}''}
|
||||
runHook postCheck
|
||||
'';
|
||||
});
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
diff --git a/packages/frontend/core/src/components/root-app-sidebar/user-info/ai-usage.tsx b/packages/frontend/core/src/components/root-app-sidebar/user-info/ai-usage.tsx
|
||||
--- a/packages/frontend/core/src/components/root-app-sidebar/user-info/ai-usage.tsx
|
||||
+++ b/packages/frontend/core/src/components/root-app-sidebar/user-info/ai-usage.tsx
|
||||
@@ -1,8 +1,10 @@
|
||||
import {
|
||||
+ ServerService,
|
||||
SubscriptionService,
|
||||
UserCopilotQuotaService,
|
||||
} from '@affine/core/modules/cloud';
|
||||
import { WorkspaceDialogService } from '@affine/core/modules/dialogs';
|
||||
+import { ServerDeploymentType } from '@affine/graphql';
|
||||
import { useI18n } from '@affine/i18n';
|
||||
import { useLiveData, useService } from '@toeverything/infra';
|
||||
import { cssVar } from '@toeverything/theme';
|
||||
@@ -15,6 +17,12 @@ import * as styles from './index.css';
|
||||
export const AIUsage = () => {
|
||||
const t = useI18n();
|
||||
const copilotQuotaService = useService(UserCopilotQuotaService);
|
||||
+ const serverService = useService(ServerService);
|
||||
+ const isSelfhosted = useLiveData(
|
||||
+ serverService.server.config$.selector(
|
||||
+ c => c.type === ServerDeploymentType.Selfhosted
|
||||
+ )
|
||||
+ );
|
||||
const subscriptionService = useService(SubscriptionService);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,6 +55,24 @@ export const AIUsage = () => {
|
||||
});
|
||||
}, [workspaceDialogService]);
|
||||
|
||||
+ if (isSelfhosted) {
|
||||
+ return (
|
||||
+ <div
|
||||
+ data-testid="selfhosted-ai-usage"
|
||||
+ className={clsx(styles.usageBlock, styles.cloudUsageBlock)}
|
||||
+ >
|
||||
+ <div className={styles.usageLabel}>
|
||||
+ <div className={styles.usageLabelTitle}>
|
||||
+ {t['com.affine.selfhosted-ai-usage.title']()}
|
||||
+ </div>
|
||||
+ </div>
|
||||
+ <div className={styles.usageLabel}>
|
||||
+ {t['com.affine.selfhosted-ai-usage.description']()}
|
||||
+ </div>
|
||||
+ </div>
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
if (loading) {
|
||||
if (loadError) console.error(loadError);
|
||||
return null;
|
||||
diff --git a/packages/frontend/core/src/desktop/dialogs/setting/account-setting/ai-usage-panel.tsx b/packages/frontend/core/src/desktop/dialogs/setting/account-setting/ai-usage-panel.tsx
|
||||
--- a/packages/frontend/core/src/desktop/dialogs/setting/account-setting/ai-usage-panel.tsx
|
||||
+++ b/packages/frontend/core/src/desktop/dialogs/setting/account-setting/ai-usage-panel.tsx
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
SubscriptionService,
|
||||
UserCopilotQuotaService,
|
||||
} from '@affine/core/modules/cloud';
|
||||
-import { SubscriptionPlan } from '@affine/graphql';
|
||||
+import { ServerDeploymentType, SubscriptionPlan } from '@affine/graphql';
|
||||
import { useI18n } from '@affine/i18n';
|
||||
import { track } from '@affine/track';
|
||||
import { useLiveData, useService } from '@toeverything/infra';
|
||||
@@ -26,6 +26,11 @@ export const AIUsagePanel = ({
|
||||
const hasPaymentFeature = useLiveData(
|
||||
serverService.server.features$.map(f => f?.payment)
|
||||
);
|
||||
+ const isSelfhosted = useLiveData(
|
||||
+ serverService.server.config$.selector(
|
||||
+ c => c.type === ServerDeploymentType.Selfhosted
|
||||
+ )
|
||||
+ );
|
||||
const subscriptionService = useService(SubscriptionService);
|
||||
const aiSubscription = useLiveData(subscriptionService.subscription.ai$);
|
||||
useEffect(() => {
|
||||
@@ -53,6 +58,17 @@ export const AIUsagePanel = ({
|
||||
track.$.settingsPanel.accountUsage.viewPlans({ plan: SubscriptionPlan.AI });
|
||||
}, [onChangeSettingState]);
|
||||
|
||||
+ if (isSelfhosted) {
|
||||
+ return (
|
||||
+ <SettingRow
|
||||
+ data-testid="selfhosted-ai-usage"
|
||||
+ name={t['com.affine.selfhosted-ai-usage.title']()}
|
||||
+ desc={t['com.affine.selfhosted-ai-usage.description']()}
|
||||
+ spreadCol={false}
|
||||
+ />
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
if (loading) {
|
||||
if (loadError) {
|
||||
return (
|
||||
diff --git a/packages/frontend/core/src/mobile/dialogs/setting/user-usage/index.tsx b/packages/frontend/core/src/mobile/dialogs/setting/user-usage/index.tsx
|
||||
--- a/packages/frontend/core/src/mobile/dialogs/setting/user-usage/index.tsx
|
||||
+++ b/packages/frontend/core/src/mobile/dialogs/setting/user-usage/index.tsx
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
UserCopilotQuotaService,
|
||||
UserQuotaService,
|
||||
} from '@affine/core/modules/cloud';
|
||||
+import { ServerDeploymentType } from '@affine/graphql';
|
||||
+import { useI18n } from '@affine/i18n';
|
||||
import { useLiveData, useService } from '@toeverything/infra';
|
||||
import { cssVar } from '@toeverything/theme';
|
||||
import { cssVarV2 } from '@toeverything/theme/v2';
|
||||
@@ -30,16 +32,20 @@ const Progress = ({
|
||||
desc,
|
||||
color,
|
||||
children,
|
||||
+ hideBar = false,
|
||||
+ 'data-testid': testId,
|
||||
}: {
|
||||
name: ReactNode;
|
||||
desc: ReactNode;
|
||||
percent?: number;
|
||||
color?: string | null;
|
||||
children?: React.ReactNode;
|
||||
+ hideBar?: boolean;
|
||||
+ 'data-testid'?: string;
|
||||
}) => {
|
||||
return (
|
||||
- <div className={styles.progressRoot}>
|
||||
+ <div className={styles.progressRoot} data-testid={testId}>
|
||||
<div className={styles.progressInfoRow}>
|
||||
<span className={styles.progressName}>{name}</span>
|
||||
<span className={styles.progressDesc}>{desc}</span>
|
||||
</div>
|
||||
@@ -46 +52 @@ const Progress = ({
|
||||
- {children ?? (
|
||||
+ {!hideBar && (children ?? (
|
||||
@@ -56 +62 @@ const Progress = ({
|
||||
- )}
|
||||
+ ))}
|
||||
@@ -110,6 +116,13 @@ const CloudUsage = () => {
|
||||
};
|
||||
const AiUsage = () => {
|
||||
+ const t = useI18n();
|
||||
const copilotQuotaService = useService(UserCopilotQuotaService);
|
||||
+ const serverService = useService(ServerService);
|
||||
+ const isSelfhosted = useLiveData(
|
||||
+ serverService.server.config$.selector(
|
||||
+ c => c.type === ServerDeploymentType.Selfhosted
|
||||
+ )
|
||||
+ );
|
||||
|
||||
const copilotActionLimit = useLiveData(
|
||||
copilotQuotaService.copilotQuota.copilotActionLimit$
|
||||
@@ -124,6 +137,17 @@ const AiUsage = () => {
|
||||
copilotQuotaService.copilotQuota.revalidate();
|
||||
}, [copilotQuotaService]);
|
||||
|
||||
+ if (isSelfhosted) {
|
||||
+ return (
|
||||
+ <Progress
|
||||
+ data-testid="selfhosted-ai-usage"
|
||||
+ name={t['com.affine.selfhosted-ai-usage.title']()}
|
||||
+ desc={t['com.affine.selfhosted-ai-usage.description']()}
|
||||
+ hideBar
|
||||
+ />
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
if (loading || loadError) {
|
||||
return <Loading />;
|
||||
}
|
||||
diff --git a/packages/frontend/i18n/src/resources/en.json b/packages/frontend/i18n/src/resources/en.json
|
||||
--- a/packages/frontend/i18n/src/resources/en.json
|
||||
+++ b/packages/frontend/i18n/src/resources/en.json
|
||||
@@ -931,6 +931,8 @@
|
||||
"com.affine.payment.ai.usage.purchase-button-label": "Purchase",
|
||||
"com.affine.payment.ai.usage.used-caption": "Times used",
|
||||
"com.affine.payment.ai.usage.used-detail": "{{used}}/{{limit}} times",
|
||||
+ "com.affine.selfhosted-ai-usage.title": "Self-hosted AI",
|
||||
+ "com.affine.selfhosted-ai-usage.description": "Provider and server limits may apply.",
|
||||
"com.affine.payment.subscription-status.active": "Active",
|
||||
"com.affine.payment.subscription-status.past-due": "Past-due bill",
|
||||
"com.affine.payment.subscription-status.trialing": "Trialing",
|
||||
diff --git a/packages/frontend/i18n/src/resources/ru.json b/packages/frontend/i18n/src/resources/ru.json
|
||||
--- a/packages/frontend/i18n/src/resources/ru.json
|
||||
+++ b/packages/frontend/i18n/src/resources/ru.json
|
||||
@@ -848,6 +848,8 @@
|
||||
"com.affine.payment.ai.usage.purchase-button-label": "Улучшить",
|
||||
"com.affine.payment.ai.usage.used-caption": "Использовалось",
|
||||
"com.affine.payment.ai.usage.used-detail": "\n{{used}}/{{limit}} Раз",
|
||||
+ "com.affine.selfhosted-ai-usage.title": "AI на своём сервере",
|
||||
+ "com.affine.selfhosted-ai-usage.description": "Могут действовать ограничения провайдера и сервера.",
|
||||
"com.affine.payment.subscription-status.active": "Активный",
|
||||
"com.affine.payment.subscription-status.past-due": "Просроченный счёт",
|
||||
"com.affine.payment.subscription-status.trialing": "Пробный период",
|
||||
@@ -0,0 +1,26 @@
|
||||
{ self, system, pkgs, ... }: let
|
||||
src = self.packages.${system}.affine.frontend.src;
|
||||
patched = pkgs.runCommand "affine-ai-usage-test-source" {
|
||||
nativeBuildInputs = [ pkgs.patch ];
|
||||
} ''
|
||||
mkdir -p "$out"
|
||||
for file in \
|
||||
packages/frontend/core/src/components/root-app-sidebar/user-info/ai-usage.tsx \
|
||||
packages/frontend/core/src/desktop/dialogs/setting/account-setting/ai-usage-panel.tsx \
|
||||
packages/frontend/core/src/mobile/dialogs/setting/user-usage/index.tsx \
|
||||
packages/frontend/i18n/src/resources/en.json \
|
||||
packages/frontend/i18n/src/resources/ru.json
|
||||
do
|
||||
install -Dm644 ${src}/"$file" "$out/$file"
|
||||
done
|
||||
patch --fuzz=0 -d "$out" -p1 < ${../../../package/affine/self-hosted-ai-usage.patch}
|
||||
'';
|
||||
in pkgs.runCommand "affine-ai-usage" {
|
||||
nativeBuildInputs = [ pkgs.nodejs_22 ];
|
||||
AFFINE_SOURCE_DIR = patched;
|
||||
TYPESCRIPT_PATH = "${pkgs.typescript}/lib/node_modules/typescript";
|
||||
} ''
|
||||
node ${./test/ai-usage.cjs}
|
||||
AI_USAGE_ESMODULE_INTEROP=false node ${./test/ai-usage.cjs}
|
||||
touch "$out"
|
||||
''
|
||||
@@ -17,6 +17,7 @@ let
|
||||
touch "$out"
|
||||
'';
|
||||
in pkgs.lib.optionalAttrs (system == "x86_64-linux") {
|
||||
affine-ai-usage = import ./ai-usage.nix { inherit self system pkgs; };
|
||||
affine-model-picker = pkgs.runCommand "affine-model-picker" {} ''
|
||||
test -s ${self.packages.${system}.affine-frontend-static}/index.html
|
||||
touch "$out"
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Module = require('node:module');
|
||||
|
||||
const sourceDir = path.resolve(process.env.AFFINE_SOURCE_DIR || process.argv[2] || '.');
|
||||
const typescript = require(process.env.TYPESCRIPT_PATH || path.join(sourceDir, 'node_modules/typescript'));
|
||||
|
||||
const SELFHOSTED_TITLE = 'Self-hosted AI';
|
||||
const SELFHOSTED_DESCRIPTION = 'Provider and server limits may apply.';
|
||||
|
||||
function signal(value) {
|
||||
return {
|
||||
value,
|
||||
map(transform) {
|
||||
return signal(transform(value));
|
||||
},
|
||||
selector(transform) {
|
||||
return signal(transform(value));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createReact() {
|
||||
const Fragment = Symbol('Fragment');
|
||||
const createElement = (type, props, ...children) => {
|
||||
const resolvedProps = { ...props };
|
||||
if (children.length === 1) resolvedProps.children = children[0];
|
||||
if (children.length > 1) resolvedProps.children = children;
|
||||
if (type === Fragment) return resolvedProps.children;
|
||||
if (typeof type === 'function') return type(resolvedProps);
|
||||
return { type, props: resolvedProps };
|
||||
};
|
||||
return { Fragment, createElement, useCallback: callback => callback, useEffect: () => {} };
|
||||
}
|
||||
|
||||
function loadTypeScript(relativePath, mocks) {
|
||||
const filename = path.join(sourceDir, relativePath);
|
||||
const source = fs.readFileSync(filename, 'utf8');
|
||||
const output = typescript.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
jsx: typescript.JsxEmit.ReactJSX,
|
||||
module: typescript.ModuleKind.CommonJS,
|
||||
target: typescript.ScriptTarget.ES2022,
|
||||
esModuleInterop: process.env.AI_USAGE_ESMODULE_INTEROP !== 'false',
|
||||
},
|
||||
}).outputText;
|
||||
const mod = new Module(filename);
|
||||
mod.filename = filename;
|
||||
mod.paths = Module._nodeModulePaths(path.dirname(filename));
|
||||
mod.require = request => {
|
||||
if (Object.hasOwn(mocks, request)) return mocks[request];
|
||||
return Module.prototype.require.call(mod, request);
|
||||
};
|
||||
mod._compile(output, filename);
|
||||
return mod.exports;
|
||||
}
|
||||
|
||||
function text(node) {
|
||||
if (node === null || node === undefined || typeof node === 'boolean') return '';
|
||||
if (typeof node === 'string' || typeof node === 'number') return String(node);
|
||||
if (Array.isArray(node)) return node.map(text).join('');
|
||||
return text(node.props?.children);
|
||||
}
|
||||
|
||||
function nodes(node) {
|
||||
if (!node || typeof node !== 'object') return [];
|
||||
if (Array.isArray(node)) return node.flatMap(nodes);
|
||||
return [node, ...nodes(node.props?.children)];
|
||||
}
|
||||
|
||||
function classNames(node) {
|
||||
return nodes(node)
|
||||
.map(item => item.props?.className)
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
function hasClick(node) {
|
||||
return nodes(node).some(item => typeof item.props?.onClick === 'function');
|
||||
}
|
||||
|
||||
function hasType(node, type) {
|
||||
return nodes(node).some(item => item.type === type);
|
||||
}
|
||||
|
||||
function createFixture({ selfhosted, limit = 10, used = 8, error = null }) {
|
||||
const react = createReact();
|
||||
const cloud = {
|
||||
AuthService: Symbol('AuthService'),
|
||||
ServerService: Symbol('ServerService'),
|
||||
SubscriptionService: Symbol('SubscriptionService'),
|
||||
UserCopilotQuotaService: Symbol('UserCopilotQuotaService'),
|
||||
UserQuotaService: Symbol('UserQuotaService'),
|
||||
};
|
||||
const dialogs = { WorkspaceDialogService: Symbol('WorkspaceDialogService') };
|
||||
const services = new Map();
|
||||
const server = {
|
||||
config$: signal({ type: selfhosted ? 'SELFHOSTED' : 'AFFINE' }),
|
||||
features$: signal({ payment: true, copilot: true }),
|
||||
};
|
||||
const copilotQuota = {
|
||||
copilotActionLimit$: signal(limit),
|
||||
copilotActionUsed$: signal(used),
|
||||
error$: signal(error),
|
||||
revalidate() {},
|
||||
};
|
||||
|
||||
services.set(cloud.AuthService, { session: { status$: signal('authenticated') } });
|
||||
services.set(cloud.ServerService, { server });
|
||||
services.set(cloud.SubscriptionService, {
|
||||
subscription: { ai$: signal(undefined), revalidate() {} },
|
||||
prices: { revalidate() {} },
|
||||
});
|
||||
services.set(cloud.UserCopilotQuotaService, { copilotQuota });
|
||||
services.set(cloud.UserQuotaService, {
|
||||
quota: {
|
||||
color$: signal('cloud-color'),
|
||||
usedFormatted$: signal('1 GB'),
|
||||
maxFormatted$: signal('10 GB'),
|
||||
percent$: signal(10),
|
||||
revalidate() {},
|
||||
},
|
||||
});
|
||||
services.set(dialogs.WorkspaceDialogService, { open() {} });
|
||||
|
||||
const styles = {
|
||||
usageBlock: 'usageBlock',
|
||||
cloudUsageBlock: 'cloudUsageBlock',
|
||||
aiUsageBlock: 'aiUsageBlock',
|
||||
usageLabel: 'usageLabel',
|
||||
usageLabelTitle: 'usageLabelTitle',
|
||||
cloudUsageBar: 'cloudUsageBar',
|
||||
cloudUsageBarInner: 'cloudUsageBarInner',
|
||||
freeTag: 'freeTag',
|
||||
progressRoot: 'progressRoot',
|
||||
progressInfoRow: 'progressInfoRow',
|
||||
progressName: 'progressName',
|
||||
progressDesc: 'progressDesc',
|
||||
progressTrack: 'progressTrack',
|
||||
progressBar: 'progressBar',
|
||||
storageProgressContainer: 'storageProgressContainer',
|
||||
storageProgressWrapper: 'storageProgressWrapper',
|
||||
storageProgressBar: 'storageProgressBar',
|
||||
};
|
||||
const translations = {
|
||||
'com.affine.selfhosted-ai-usage.title': SELFHOSTED_TITLE,
|
||||
'com.affine.selfhosted-ai-usage.description': SELFHOSTED_DESCRIPTION,
|
||||
'com.affine.payment.ai.usage-title': 'AFFiNE AI usage',
|
||||
'com.affine.payment.ai.usage.used-caption': 'Times used',
|
||||
'com.affine.payment.ai.usage.used-detail': '{{used}}/{{limit}} times',
|
||||
'com.affine.payment.ai.usage.purchase-button-label': 'Purchase',
|
||||
'com.affine.payment.ai.usage.change-button-label': 'Change plan',
|
||||
'com.affine.payment.ai.usage-description-purchased': 'Purchased',
|
||||
};
|
||||
const t = new Proxy({}, {
|
||||
get: (_target, key) => values => {
|
||||
const value = translations[key] || String(key);
|
||||
return value.replace('{{used}}', values?.used ?? '').replace('{{limit}}', values?.limit ?? '');
|
||||
},
|
||||
});
|
||||
const settingRow = props => ({ type: 'SettingRow', props: {
|
||||
...props, children: [props.name, props.desc, props.children],
|
||||
} });
|
||||
const clsx = (...values) => values.filter(Boolean).join(' ');
|
||||
clsx.default = clsx;
|
||||
const mocks = {
|
||||
'@affine/component': {
|
||||
Button: props => ({ type: 'Button', props }),
|
||||
ErrorMessage: props => ({ type: 'ErrorMessage', props }),
|
||||
Skeleton: props => ({ type: 'Skeleton', props }),
|
||||
},
|
||||
'@affine/component/setting-components': { SettingRow: settingRow },
|
||||
'@affine/core/modules/cloud': cloud,
|
||||
'@affine/core/modules/dialogs': dialogs,
|
||||
'@affine/graphql': {
|
||||
ServerDeploymentType: { Selfhosted: 'SELFHOSTED' },
|
||||
SubscriptionPlan: { AI: 'AI' },
|
||||
},
|
||||
'@affine/i18n': { useI18n: () => t },
|
||||
'@affine/track': {
|
||||
track: { $: { settingsPanel: { accountUsage: { viewPlans() {} } } } },
|
||||
},
|
||||
'@toeverything/infra': {
|
||||
useLiveData: data => data.value,
|
||||
useService: token => services.get(token),
|
||||
},
|
||||
'@toeverything/theme': { cssVar: name => name },
|
||||
'@toeverything/theme/v2': { cssVarV2: name => name },
|
||||
'@vanilla-extract/dynamic': { assignInlineVars: values => values },
|
||||
'@blocksuite/icons/rc': {},
|
||||
clsx,
|
||||
react,
|
||||
'react/jsx-runtime': {
|
||||
Fragment: react.Fragment,
|
||||
jsx: (type, props) => react.createElement(type, props),
|
||||
jsxs: (type, props) => react.createElement(type, props),
|
||||
},
|
||||
'../general-setting/plans/ai/actions': {
|
||||
AIResume: props => ({ type: 'AIResume', props }),
|
||||
AISubscribe: props => ({ type: 'AISubscribe', props }),
|
||||
},
|
||||
'./index.css': styles,
|
||||
'./storage-progress.css': styles,
|
||||
'./style.css': styles,
|
||||
'../group': { SettingGroup: props => ({ type: 'SettingGroup', props }) },
|
||||
};
|
||||
return { mocks };
|
||||
}
|
||||
|
||||
function renderAll(state) {
|
||||
const { mocks } = createFixture(state);
|
||||
const { AIUsage: SidebarUsage } = loadTypeScript(
|
||||
'packages/frontend/core/src/components/root-app-sidebar/user-info/ai-usage.tsx',
|
||||
mocks
|
||||
);
|
||||
const { AIUsagePanel: DesktopUsage } = loadTypeScript(
|
||||
'packages/frontend/core/src/desktop/dialogs/setting/account-setting/ai-usage-panel.tsx',
|
||||
mocks
|
||||
);
|
||||
const { UserUsage: MobileUsage } = loadTypeScript(
|
||||
'packages/frontend/core/src/mobile/dialogs/setting/user-usage/index.tsx',
|
||||
mocks
|
||||
);
|
||||
return [SidebarUsage(), DesktopUsage({}), MobileUsage()];
|
||||
}
|
||||
|
||||
function assertSelfhosted(tree, stateName) {
|
||||
for (const [index, view] of tree.entries()) {
|
||||
const indicator = nodes(view).find(item => item.props?.['data-testid'] === 'selfhosted-ai-usage');
|
||||
assert(indicator, `${stateName}: view ${index} provider indicator is present`);
|
||||
assert.match(text(indicator), /Self-hosted AI/);
|
||||
assert.match(text(indicator), /Provider and server limits may apply\./);
|
||||
assert.equal(hasClick(indicator), false, `${stateName}: no billing navigation`);
|
||||
assert.doesNotMatch(text(indicator), /(?:\d+\s*\/\s*\d+|Free|Purchase|Change plan|Times used)/);
|
||||
assert.doesNotMatch(
|
||||
classNames(indicator),
|
||||
/(?:cloudUsageBar|storageProgress(?:Container|Wrapper|Bar)|progressTrack|progressBar)/
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function testSelfhostedPresentation() {
|
||||
const states = [
|
||||
['usage', { limit: 10, used: 8 }],
|
||||
['exhausted', { limit: 10, used: 10 }],
|
||||
['loading', { limit: null, used: 8 }],
|
||||
['error', { limit: 10, used: 8, error: new Error('quota unavailable') }],
|
||||
];
|
||||
for (const [name, quota] of states) {
|
||||
assertSelfhosted(renderAll({ selfhosted: true, ...quota }), name);
|
||||
}
|
||||
}
|
||||
|
||||
function testCloudPresentation() {
|
||||
const [sidebar, desktop, mobile] = renderAll({ selfhosted: false });
|
||||
|
||||
assert.match(text(sidebar), /8\s*\/\s*10/);
|
||||
assert.match(text(sidebar), /Free/);
|
||||
assert.equal(hasClick(sidebar), true, 'cloud sidebar retains plan navigation');
|
||||
assert.match(classNames(sidebar), /cloudUsageBar/);
|
||||
|
||||
assert.match(text(desktop), /8\s*\/\s*10/);
|
||||
assert.equal(hasType(desktop, 'AISubscribe'), true, 'cloud desktop retains purchase link');
|
||||
assert.match(classNames(desktop), /storageProgressContainer/);
|
||||
|
||||
assert.match(text(mobile), /8\s*\/\s*10/);
|
||||
assert.match(classNames(mobile), /progressTrack/);
|
||||
}
|
||||
|
||||
function testLocalizedProviderLabels() {
|
||||
const resources = path.join(sourceDir, 'packages/frontend/i18n/src/resources');
|
||||
const english = JSON.parse(fs.readFileSync(path.join(resources, 'en.json'), 'utf8'));
|
||||
const russian = JSON.parse(fs.readFileSync(path.join(resources, 'ru.json'), 'utf8'));
|
||||
assert.equal(english['com.affine.selfhosted-ai-usage.title'], SELFHOSTED_TITLE);
|
||||
assert.equal(english['com.affine.selfhosted-ai-usage.description'], SELFHOSTED_DESCRIPTION);
|
||||
assert.equal(russian['com.affine.selfhosted-ai-usage.title'], 'AI на своём сервере');
|
||||
assert.equal(russian['com.affine.selfhosted-ai-usage.description'], 'Могут действовать ограничения провайдера и сервера.');
|
||||
}
|
||||
|
||||
try {
|
||||
testSelfhostedPresentation();
|
||||
testCloudPresentation();
|
||||
testLocalizedProviderLabels();
|
||||
process.stdout.write('AFFiNE self-hosted AI usage regression tests passed\n');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
Reference in New Issue
Block a user