diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 87b9ecfe..6feaffcb 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -27,7 +27,7 @@ ```text 例如: -- uv run main.py / uv run granian ... 启动正常 +- uv run granian ... app.main:app 启动正常 - 调用 /v1/chat/completions 返回符合预期 ``` diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index aa602991..1c756504 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -21,26 +21,19 @@ jobs: contents: read packages: write id-token: write - - strategy: - fail-fast: false - matrix: - include: - # AMD64 平台 - - platform: linux/amd64 - suffix: amd64 - # ARM64 平台 - - platform: linux/arm64 - suffix: arm64 steps: - name: Checkout repository uses: actions/checkout@v6 + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to Container Registry + if: github.event_name != 'pull_request' uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} @@ -53,57 +46,19 @@ jobs: with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | - # 分支推送 - type=ref,event=branch,suffix=-${{ matrix.suffix }} - # 语义化版本:完整版本号 - type=semver,pattern={{version}},suffix=-${{ matrix.suffix }} - # latest标签 - type=raw,value=latest-${{ matrix.suffix }},enable={{is_default_branch}} + # push main → latest(排除 tag 触发) + type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} + # tag 推送 → 版本号 + type=semver,pattern={{version}} - name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . - platforms: ${{ matrix.platform }} + platforms: linux/amd64,linux/arm64 push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha,scope=${{ matrix.suffix }} - cache-to: type=gha,mode=max,scope=${{ matrix.suffix }} - pull: true - - merge-manifests: - runs-on: ubuntu-latest - needs: build-and-push - if: github.event_name != 'pull_request' - permissions: - contents: read - packages: write - - steps: - - name: Log in to Container Registry - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract metadata - id: meta - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=ref,event=branch - type=semver,pattern={{version}} - type=raw,value=latest,enable={{is_default_branch}} - - - name: Create and push manifest - run: | - TAGS="${{ steps.meta.outputs.tags }}" - for tag in $TAGS; do - echo "合并标签: $tag" - docker buildx imagetools create -t $tag \ - ${tag}-amd64 \ - ${tag}-arm64 - done \ No newline at end of file + cache-from: type=gha + cache-to: type=gha,mode=max + pull: true \ No newline at end of file diff --git a/.gitignore b/.gitignore index 13ea1245..26eec291 100644 --- a/.gitignore +++ b/.gitignore @@ -54,5 +54,4 @@ app/data/ htmlcov/ # Project specific -config.local.toml .ace-tool/ diff --git a/Dockerfile b/Dockerfile index 2aa8c7ec..fe7c0fef 100644 --- a/Dockerfile +++ b/Dockerfile @@ -64,7 +64,6 @@ COPY --from=builder /opt/venv /opt/venv COPY config.defaults.toml ./ COPY app ./app COPY _public ./_public -COPY main.py ./ COPY scripts ./scripts RUN mkdir -p /app/data /app/logs \ @@ -74,4 +73,4 @@ EXPOSE 8000 ENTRYPOINT ["/app/scripts/entrypoint.sh"] -CMD ["sh", "-c", "granian --interface asgi --host ${SERVER_HOST:-0.0.0.0} --port ${SERVER_PORT:-8000} --workers ${SERVER_WORKERS:-1} main:app"] +CMD ["sh", "-c", "granian --interface asgi --host ${SERVER_HOST:-0.0.0.0} --port ${SERVER_PORT:-8000} --workers ${SERVER_WORKERS:-1} app.main:app"] diff --git a/app/assets/admin/pages/cache.html b/app/assets/admin/pages/cache.html deleted file mode 100644 index 16877a5b..00000000 --- a/app/assets/admin/pages/cache.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - Grok2API - 缓存管理 - - - - - - -
-
- -
-
-
-

缓存管理

-

查看和管理本地缓存文件。

-
- -
-
- -
-
-
图片数量
-
-
图片大小
-
-
视频数量
-
-
视频大小
-
- -
- - -
- -
-
-
- - - - -
-
- -
-
-
- - -
文件名大小操作
-
- -
-
- - - - -
- - - - - - - - diff --git a/app/assets/admin/pages/config.html b/app/assets/admin/pages/config.html deleted file mode 100644 index 0d8f9f0f..00000000 --- a/app/assets/admin/pages/config.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - Grok2API - 配置管理 - - - - - - -
-
- -
-
-
-

配置管理

-

管理 API 密钥及系统参数设置。

-
- -
-
-
-
加载中...
-
-
- - -
- - - - - - - - - diff --git a/app/assets/admin/pages/login.html b/app/assets/admin/pages/login.html deleted file mode 100644 index dfc9e2ce..00000000 --- a/app/assets/admin/pages/login.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - Grok2API - 登录 - - - - - -
-
-
- - - - -
-
- - - - - - - - diff --git a/app/assets/admin/pages/token.html b/app/assets/admin/pages/token.html deleted file mode 100644 index 16dc4cf7..00000000 --- a/app/assets/admin/pages/token.html +++ /dev/null @@ -1,186 +0,0 @@ - - - - - - Grok2API - Token 管理 - - - - - - -
-
- -
-
-
-

Token 列表

-

管理 Grok2API 的 Token 服务号池。

-
-
- - -
-
- -
- - -
-
-
Token 总数
-
-
正常
-
-
限流
-
-
失效
-
-
Chat 剩余
-
-
Image 剩余
-
-
Video 剩余
-
-
总调用
-
- - -
- - - - - - - -
- - -
-
-
- -
0 / 0
- -
-
-
- - -
- -
-
-
- - - - - - - - - - - -
Token类型状态额度备注操作
-
-
加载中...
- -
-
- - -
-
- 已选 - 0 -
- -
- - - - - - -
- -
- - - - - - - - - - - -
- - - - - - - - - - diff --git a/app/assets/css/app.css b/app/assets/css/app.css deleted file mode 100644 index b2de1d47..00000000 --- a/app/assets/css/app.css +++ /dev/null @@ -1,579 +0,0 @@ -/* ============================================================ - Grok2API — Unified Design System - Pure CSS, zero dependencies. Replaces Tailwind CDN + all page CSS. - ============================================================ */ - -/* ---------- 1. Variables ---------- */ -:root { - --bg: #fafafa; - --bg-card: #fff; - --fg: #000; - --fg-muted: #666; - --fg-subtle: #999; - --fg-dim: #444; - --border: #e5e5e5; - --border-hover: #000; - --radius: 6px; - --radius-lg: 10px; - --radius-xl: 14px; - --success: #059669; - --success-bg: #ecfdf5; - --error: #dc2626; - --error-bg: #fef2f2; - --warning: #f5a623; - --blue: #0070f3; - --purple: #7c3aed; - --orange: #f97316; - --shadow-sm: 0 1px 3px rgba(0,0,0,.06); - --shadow-md: 0 4px 16px rgba(0,0,0,.08); - --shadow-lg: 0 20px 50px rgba(0,0,0,.08); - --font-sans: 'Geist Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; - --font-mono: 'Geist Mono', ui-monospace, 'SF Mono', monospace; - --header-h: 56px; - --max-w: 960px; -} - -/* ---------- 2. Reset ---------- */ -*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } -html { -webkit-text-size-adjust: 100%; } -body { - font-family: var(--font-sans); - background: var(--bg); - color: var(--fg); - line-height: 1.5; - -webkit-font-smoothing: antialiased; - min-height: 100vh; -} -a { color: inherit; text-decoration: none; } -button, input, select, textarea { - font: inherit; border: none; outline: none; background: none; color: inherit; -} -button { cursor: pointer; } -img, video { display: block; max-width: 100%; } -table { border-collapse: collapse; width: 100%; } -::-webkit-scrollbar { width: 6px; height: 6px; } -::-webkit-scrollbar-thumb { background: #ccc; border-radius: 3px; } -.hidden { display: none !important; } -.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; } -.font-mono { font-family: var(--font-mono); } - -/* ---------- 3. Layout ---------- */ -.page { display: flex; flex-direction: column; min-height: 100vh; } -.page-body { flex: 1; max-width: var(--max-w); width: 100%; margin: 0 auto; padding: calc(var(--header-h) + 24px) 24px 64px; } -.page-body.wide { max-width: 1060px; } - -/* ---------- 4. Header ---------- */ -.app-header { - position: fixed; top: 0; left: 0; right: 0; z-index: 40; - height: var(--header-h); - background: rgba(250,250,250,.85); - backdrop-filter: blur(12px); - border-bottom: 1px solid var(--border); -} -.app-header-inner { - max-width: var(--max-w); margin: 0 auto; - height: 100%; padding: 0 24px; - display: flex; align-items: center; justify-content: space-between; -} -.header-left { display: flex; align-items: center; gap: 16px; min-width: 0; } -.header-right { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } -.brand { display: inline-flex; align-items: center; gap: 6px; font-weight: 600; font-size: 14px; white-space: nowrap; } -.brand svg { width: 16px; height: 16px; fill: currentColor; } -.brand-sub { font-size: 12px; color: var(--fg-muted); } -.header-sep { width: 1px; height: 16px; background: var(--border); flex-shrink: 0; } -.nav-link { font-size: 13px; color: var(--fg-muted); transition: color .15s; white-space: nowrap; } -.nav-link:hover { color: var(--fg); } -.nav-link.active { color: var(--fg); font-weight: 500; } -.header-btn { - height: 26px; padding: 0 10px; border-radius: 999px; - border: 1px solid var(--border); font-size: 11px; font-weight: 500; - color: var(--fg-muted); display: inline-flex; align-items: center; transition: all .15s; -} -.header-btn:hover { border-color: var(--fg); color: var(--fg); } -.header-btn.ready { background: #ecfdf3; border-color: #a7f3d0; color: #047857; } - -/* ---------- 5. Footer ---------- */ -.app-footer { - position: fixed; right: 16px; bottom: 12px; z-index: 10; - font-size: 12px; color: var(--fg-subtle); -} -.app-footer a:hover { color: var(--fg); } - -/* ---------- 6. Buttons ---------- */ -.btn { - height: 32px; padding: 0 14px; border-radius: 8px; - font-size: 13px; font-weight: 600; display: inline-flex; - align-items: center; justify-content: center; gap: 6px; - transition: opacity .15s; white-space: nowrap; -} -.btn:disabled { opacity: .45; pointer-events: none; } -.btn-primary { background: var(--fg); color: var(--bg-card); } -.btn-primary:hover { opacity: .88; } -.btn-outline { border: 1px solid var(--border); color: var(--fg); } -.btn-outline:hover { border-color: var(--fg); } -.btn-danger { background: var(--error); color: #fff; } -.btn-danger:hover { opacity: .88; } -.btn-ghost { color: var(--fg-muted); } -.btn-ghost:hover { color: var(--fg); background: rgba(0,0,0,.04); } -.btn-sm { height: 26px; padding: 0 10px; font-size: 12px; font-weight: 500; } -.btn-icon { width: 32px; padding: 0; } -.btn-icon svg { width: 14px; height: 14px; } -.btn-round { border-radius: 999px; } - -/* ---------- 7. Inputs ---------- */ -.input { - width: 100%; height: 34px; padding: 0 10px; - font-size: 13px; border-radius: 8px; - border: 1px solid var(--border); background: var(--bg-card); - transition: border-color .15s, box-shadow .15s; -} -.input:focus { border-color: #bbb; box-shadow: 0 0 0 2px rgba(0,0,0,.04); } -.input:disabled { background: #f5f5f5; color: var(--fg-muted); cursor: not-allowed; } -.input::placeholder { color: var(--fg-subtle); } -textarea.input { height: auto; padding: 8px 10px; resize: vertical; } -select.input { cursor: pointer; appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; padding-right: 28px; } - -/* ---------- 8. Cards ---------- */ -.card { - background: var(--bg-card); border-radius: var(--radius-lg); - border: 1px solid transparent; transition: border-color .15s; -} -.card:hover { border-color: var(--border); } -.stat-card { padding: 14px 18px; } -.stat-value { font-size: 20px; font-weight: 600; line-height: 1.2; letter-spacing: -.01em; } -.stat-label { font-size: 12px; color: var(--fg-muted); margin-top: 2px; } - -/* ---------- 9. Table ---------- */ -.table-shell { background: var(--bg-card); border-radius: var(--radius-lg); overflow: hidden; } -.table-shell table { min-width: 100%; } -.table-shell th { - font-size: 12px; font-weight: 500; color: var(--fg-muted); - padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--border); - background: #fafafa; white-space: nowrap; -} -.table-shell td { - font-size: 13px; padding: 10px 12px; - border-bottom: 1px solid #f5f5f5; vertical-align: middle; -} -.table-shell tr:last-child td { border-bottom: none; } -.table-shell tr.row-selected { background: #f8f8ff; } -.table-empty { color: var(--fg-muted); font-size: 12px; padding: 48px 0; text-align: center; } -.text-center { text-align: center; } -.text-right { text-align: right; } - -/* ---------- 10. Badges ---------- */ -.badge { - display: inline-flex; align-items: center; height: 20px; - padding: 0 8px; border-radius: 999px; font-size: 11px; font-weight: 500; - background: #f5f5f5; color: var(--fg-dim); -} -.badge-green { background: #ecfdf5; color: #059669; } -.badge-orange { background: #fff7ed; color: #ea580c; } -.badge-red { background: #fef2f2; color: #dc2626; } -.badge-purple { background: #f5f3ff; color: #7c3aed; } -.badge-blue { background: #eff6ff; color: #2563eb; } - -/* ---------- 11. Tabs ---------- */ -.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); overflow-x: auto; padding-bottom: -1px; } -.tabs::-webkit-scrollbar { display: none; } -.tab-item { - padding: 8px 12px; font-size: 13px; color: var(--fg-muted); - border-bottom: 2px solid transparent; transition: all .15s; - display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; flex-shrink: 0; -} -.tab-item:hover { color: var(--fg); } -.tab-item.active { color: var(--fg); font-weight: 500; border-bottom-color: var(--fg); } -.tab-sep { width: 1px; height: 16px; background: var(--border); align-self: center; flex-shrink: 0; } - -/* ---------- 12. Modal ---------- */ -.modal-overlay { - position: fixed; inset: 0; z-index: 100; - background: rgba(0,0,0,.4); display: flex; - align-items: center; justify-content: center; padding: 24px; - opacity: 0; transition: opacity .2s; -} -.modal-overlay.is-open { opacity: 1; } -.modal-content { - background: var(--bg-card); border-radius: var(--radius-xl); - width: 100%; box-shadow: var(--shadow-lg); padding: 20px 24px; - transform: translateY(8px); transition: transform .2s; -} -.modal-overlay.is-open .modal-content { transform: translateY(0); } -.modal-md { max-width: 460px; } -.modal-lg { max-width: 560px; } -.modal-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; } -.modal-title { font-size: 15px; font-weight: 600; } -.modal-close { width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border-radius: 6px; color: var(--fg-muted); } -.modal-close:hover { background: #f5f5f5; color: var(--fg); } -.modal-label { font-size: 12px; font-weight: 500; color: var(--fg-dim); } - -/* ---------- 13. Toast ---------- */ -.toast-container { - position: fixed; top: 24px; left: 50%; transform: translateX(-50%); - z-index: 200; display: flex; flex-direction: column; gap: 10px; - pointer-events: none; align-items: center; -} -.toast { - background: var(--bg-card); border: 1px solid var(--border); - border-radius: var(--radius); padding: 10px 14px; - display: flex; align-items: center; gap: 10px; - min-width: 260px; max-width: 400px; pointer-events: auto; - animation: toastIn .3s cubic-bezier(.16,1,.3,1) forwards; - box-shadow: var(--shadow-md); -} -.toast.out { animation: toastOut .2s ease forwards; } -.toast-icon { - flex-shrink: 0; width: 20px; height: 20px; - display: flex; align-items: center; justify-content: center; border-radius: 50%; -} -.toast-success .toast-icon { background: var(--success-bg); color: var(--success); } -.toast-error .toast-icon { background: var(--error-bg); color: var(--error); } -.toast-content { flex: 1; font-size: 12px; font-weight: 500; } -@keyframes toastIn { from { opacity:0; transform: translateY(16px) scale(.96); } to { opacity:1; transform: translateY(0) scale(1); } } -@keyframes toastOut { from { opacity:1; } to { opacity:0; transform: translateY(8px) scale(.96); } } - -/* ---------- 14. Notice dialog ---------- */ -.notice-backdrop { - position: fixed; inset: 0; background: rgba(0,0,0,.35); - display: flex; align-items: center; justify-content: center; - z-index: 200; padding: 24px; -} -.notice-dialog { - background: var(--bg-card); border-radius: 12px; - width: min(520px, 92vw); box-shadow: var(--shadow-lg); padding: 20px 22px 16px; -} -.notice-dialog-title { font-size: 14px; font-weight: 600; margin-bottom: 8px; } -.notice-dialog-content { font-size: 13px; line-height: 1.6; color: var(--fg-dim); } -.notice-dialog-actions { display: flex; justify-content: flex-end; margin-top: 16px; } - -/* ---------- 15. Login ---------- */ -.login-body { min-height: 100vh; display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden; } -.login-bg { - position: fixed; inset: 0; z-index: 0; - background: radial-gradient(600px 280px at 20% 20%, rgba(0,0,0,.06), transparent 60%), - radial-gradient(500px 260px at 80% 80%, rgba(0,0,0,.04), transparent 55%), - linear-gradient(180deg, #fafafa, #f6f6f6); -} -.login-shell { position: relative; z-index: 1; width: min(420px, 92vw); padding: 24px; } -.login-card { - background: var(--bg-card); border: 1px solid transparent; border-radius: var(--radius-xl); - padding: 22px; box-shadow: var(--shadow-lg); transition: border-color .2s, box-shadow .2s; -} -.login-card:hover { border-color: var(--fg); } -.login-brand { font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: var(--fg-muted); font-weight: 600; } -.login-title { margin-top: 6px; font-size: 18px; font-weight: 600; } -.login-subtitle { margin-top: 4px; font-size: 12px; color: var(--fg-muted); } -.login-form { margin-top: 16px; display: grid; gap: 10px; } - -/* ---------- 16. Config page ---------- */ -.config-section { margin-bottom: 32px; } -.config-section-title { font-size: 15px; font-weight: 600; margin-bottom: 8px; } -.config-section-desc { font-size: 13px; color: var(--fg-muted); margin-bottom: 16px; } -.config-grid { display: grid; gap: 16px; } -.config-field { display: grid; gap: 4px; } -.config-field-title { font-size: 13px; font-weight: 500; } -.config-field-desc { font-size: 12px; color: var(--fg-subtle); line-height: 1.4; } -.config-field-input { margin-top: 4px; } -.config-field.has-action { display: flex; align-items: flex-end; gap: 8px; } -.config-field.has-action .config-field-input { flex: 1; } - -/* ---------- 17. Token page ---------- */ -.pagination-bar { - display: flex; align-items: center; justify-content: space-between; - padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 12px; -} -.pagination-left { display: flex; align-items: center; gap: 8px; } -.pagination-right { display: flex; align-items: center; gap: 8px; } -.pagination-info { color: var(--fg-muted); font-size: 12px; } -.pagination-icon-btn { - width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; - border-radius: 6px; color: var(--fg-muted); transition: all .15s; -} -.pagination-icon-btn:hover { background: #f5f5f5; color: var(--fg); } -.pagination-icon-btn:disabled { opacity: .3; pointer-events: none; } -.pagination-size-select { - height: 28px; padding: 0 24px 0 8px; border-radius: 6px; - border: 1px solid var(--border); font-size: 12px; cursor: pointer; - appearance: none; - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); - background-repeat: no-repeat; background-position: right 6px center; -} -.select-menu-wrap { position: relative; } -.select-all-popover { - position: absolute; top: 100%; right: 0; margin-top: 4px; - background: var(--bg-card); border: 1px solid var(--border); - border-radius: 8px; padding: 4px; min-width: 120px; - box-shadow: var(--shadow-md); z-index: 30; -} -.select-all-option { - display: block; width: 100%; padding: 6px 10px; text-align: left; - font-size: 12px; border-radius: 6px; color: var(--fg-dim); -} -.select-all-option:hover { background: #f5f5f5; color: var(--fg); } -.pagination-action-btn { - height: 28px; padding: 0 10px; border-radius: 6px; - border: 1px solid var(--border); font-size: 12px; - display: inline-flex; align-items: center; gap: 4px; color: var(--fg-muted); -} -.pagination-action-btn:hover { border-color: var(--fg); color: var(--fg); } -.pagination-action-btn.is-active { background: var(--fg); color: var(--bg-card); border-color: var(--fg); } - -/* checkbox */ -.checkbox { width: 14px; height: 14px; cursor: pointer; accent-color: var(--fg); } - -/* Batch toolbar */ -.batch-toolbar { - position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%); - z-index: 30; background: var(--bg-card); border: 1px solid var(--border); - border-radius: 999px; padding: 6px 14px; - display: flex; align-items: center; gap: 10px; - box-shadow: var(--shadow-md); white-space: nowrap; - touch-action: none; user-select: none; -} -.toolbar-sep { width: 1px; height: 16px; background: var(--border); flex-shrink: 0; } -.batch-link { font-size: 12px; color: var(--fg-muted); text-decoration: underline; } -.batch-link:hover { color: var(--fg); } - -/* ---------- 18. Cache page ---------- */ -.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } -.grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; } -.grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; } - -/* ---------- 19. Toggle switch ---------- */ -.toggle { position: relative; display: inline-flex; align-items: center; cursor: pointer; } -.toggle input { position: absolute; opacity: 0; width: 0; height: 0; } -.toggle-track { - width: 36px; height: 20px; border-radius: 999px; - background: var(--fg-subtle); transition: background .2s; -} -.toggle-track::after { - content: ''; position: absolute; top: 2px; left: 2px; - width: 16px; height: 16px; border-radius: 50%; - background: #fff; transition: transform .2s; -} -.toggle input:checked + .toggle-track { background: var(--fg); } -.toggle input:checked + .toggle-track::after { transform: translateX(16px); } - -/* ---------- 20. Imagine page ---------- */ -.waterfall { display: flex; flex-wrap: wrap; gap: 8px; } -.waterfall-item { - border-radius: var(--radius); overflow: hidden; - cursor: pointer; position: relative; flex: 0 0 auto; -} -.waterfall-item img { width: 100%; height: auto; display: block; } -.lightbox { - position: fixed; inset: 0; z-index: 100; - background: rgba(0,0,0,.85); display: flex; - align-items: center; justify-content: center; -} -.lightbox img { max-width: 90vw; max-height: 90vh; object-fit: contain; border-radius: 8px; } -.lightbox-close { - position: absolute; top: 16px; right: 16px; - width: 36px; height: 36px; border-radius: 50%; - background: rgba(255,255,255,.2); color: #fff; - display: flex; align-items: center; justify-content: center; -} - -/* ---------- 21. Shared card components ---------- */ -.card-title { font-size: 14px; font-weight: 600; margin-bottom: 12px; } -.meta-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px; } -.meta-item { background: #fafafa; border-radius: 6px; padding: 8px 10px; } -.meta-label { font-size: 10px; color: var(--fg-subtle); text-transform: uppercase; letter-spacing: .05em; } -.meta-value { font-size: 12px; font-weight: 500; margin-top: 2px; } -.status-text { font-size: 12px; color: var(--fg-subtle); } -.status-text.connected { color: var(--success); } -.status-text.connecting { color: var(--warning); } -.status-text.error { color: var(--error); } -.field-label { font-size: 12px; font-weight: 500; color: var(--fg-dim); display: block; margin-bottom: 4px; } -.range-value { font-size: 12px; font-weight: 600; font-family: var(--font-mono); } - -/* ---------- 21b. Voice page ---------- */ -.voice-grid { display: grid; grid-template-columns: 1fr 320px; gap: 16px; } -.voice-card { background: var(--bg-card); border-radius: var(--radius-lg); padding: 16px; margin-bottom: 16px; border: 1px solid var(--border); } -.voice-hint { font-size: 11px; color: var(--fg-subtle); } -.voice-log { max-height: 300px; overflow-y: auto; background: #1a1a1a; color: #ccc; border-radius: var(--radius); padding: 10px; font-family: var(--font-mono); font-size: 12px; } -.voice-log p { margin-bottom: 2px; } -.voice-log .log-error { color: #f87171; } -.voice-log .log-warn { color: #fbbf24; } -.voice-log-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; } -.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } -.visualizer { display: flex; align-items: flex-end; gap: 2px; height: 40px; } -.visualizer .bar { width: 4px; background: var(--fg); border-radius: 2px; transition: height .15s; height: 6px; } -.log-box { - background: #1a1a1a; color: #ccc; border-radius: var(--radius); - padding: 12px; font-family: var(--font-mono); font-size: 12px; - max-height: 300px; overflow-y: auto; -} -.log-box p { margin-bottom: 2px; } -.log-box .log-error { color: #f87171; } -.log-box .log-warn { color: #fbbf24; } - -/* ---------- 22. Video page ---------- */ -.progress-bar { height: 6px; background: #f0f0f0; border-radius: 3px; overflow: hidden; position: relative; } -.progress-fill { height: 100%; background: var(--fg); border-radius: 3px; transition: width .3s; width: 0; } -.progress-bar.indeterminate .progress-fill { - width: 40% !important; animation: indeterminate 1.4s ease infinite; -} -@keyframes indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(350%); } } -.video-item { border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; margin-bottom: 12px; } -.video-item.is-pending { opacity: .6; } -.video-item-bar { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px; border-bottom: 1px solid #f5f5f5; } -.video-item-title { font-size: 13px; font-weight: 500; } -.video-item-actions { display: flex; gap: 6px; } -.video-item-body { padding: 12px 14px; } -.video-item-body video { width: 100%; border-radius: var(--radius); } -.video-item-placeholder { text-align: center; padding: 32px 0; color: var(--fg-subtle); font-size: 13px; } -.video-item-link { padding: 0 14px 10px; font-size: 11px; color: var(--fg-subtle); word-break: break-all; } - -/* ---------- 23. Chat page ---------- */ -.chat-layout { display: flex; height: 100vh; overflow: hidden; } -.chat-sidebar { - width: 260px; flex-shrink: 0; background: #f8f8f8; - border-right: 1px solid var(--border); display: flex; flex-direction: column; - transition: margin-left .2s; -} -.chat-sidebar.collapsed { margin-left: -260px; } -.chat-sidebar-header { padding: 12px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border); } -.chat-sidebar-list { flex: 1; overflow-y: auto; padding: 8px; } -.session-item { - padding: 8px 12px; border-radius: var(--radius); font-size: 13px; - cursor: pointer; margin-bottom: 2px; display: flex; align-items: center; justify-content: space-between; -} -.session-item:hover { background: #f0f0f0; } -.session-item.active { background: #e8e8e8; font-weight: 500; } -.chat-main { flex: 1; display: flex; flex-direction: column; min-width: 0; } -.chat-header { padding: 12px 16px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; } -.chat-messages { flex: 1; overflow-y: auto; padding: 16px; } -.chat-input-bar { padding: 12px 16px; border-top: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-end; } -.chat-input-bar textarea { flex: 1; resize: none; max-height: 120px; } -.chat-bubble { margin-bottom: 16px; max-width: 80%; } -.chat-bubble.user { margin-left: auto; } -.chat-bubble-inner { - padding: 10px 14px; border-radius: 12px; font-size: 14px; line-height: 1.6; -} -.chat-bubble.user .chat-bubble-inner { background: var(--fg); color: var(--bg-card); border-bottom-right-radius: 4px; } -.chat-bubble.assistant .chat-bubble-inner { background: #f0f0f0; border-bottom-left-radius: 4px; } -.chat-bubble-inner pre { background: #1a1a1a; color: #e5e5e5; padding: 12px; border-radius: 6px; overflow-x: auto; font-size: 13px; margin: 8px 0; } -.chat-bubble-inner code { font-family: var(--font-mono); font-size: .9em; } -.chat-bubble-inner p { margin-bottom: 8px; } -.chat-bubble-inner p:last-child { margin-bottom: 0; } -.chat-empty { text-align: center; padding: 80px 24px; color: var(--fg-subtle); } - -/* ---------- 23b. Divider ---------- */ -.divider { height: 1px; background: var(--border); margin-bottom: 24px; } - -/* ---------- 23c. Compat aliases (for JS-created elements) ---------- */ -.geist-button { height:32px;font-size:13px;font-weight:600;background:#000;color:#fff;border-radius:8px;padding:0 14px;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:opacity .15s;white-space:nowrap; } -.geist-button:hover { opacity:.88; } -.geist-button:disabled { opacity:.45;pointer-events:none; } -.geist-button-outline { height:32px;font-size:13px;font-weight:500;background:transparent;color:var(--fg);border:1px solid var(--border);border-radius:8px;padding:0 14px;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:all .15s;white-space:nowrap; } -.geist-button-outline:hover { border-color:#000; } -.geist-button-outline:disabled { opacity:.45;pointer-events:none; } -.geist-button-danger { height:32px;font-size:13px;font-weight:500;background:var(--error);color:#fff;border-radius:8px;padding:0 14px;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:opacity .15s;white-space:nowrap; } -.geist-button-danger:hover { opacity:.88; } -.geist-input { width:100%;font-size:13px;border-radius:8px;padding:6px 10px;border:1px solid var(--border);background:#fff;transition:border-color .15s; } -.geist-input:focus { border-color:#bbb; } -.geist-input:disabled { background:#f5f5f5;color:var(--fg-muted); } -.tracking-tight { letter-spacing: -0.025em; } -.hover\:bg-gray-100:hover { background: #f3f4f6; } -.hover\:bg-red-100:hover { background: #fee2e2; } -.min-h-screen { min-height: 100vh; } -.flex-1 { flex: 1; } -.container { width: 100%; margin: 0 auto; } -.mx-auto { margin-left: auto; margin-right: auto; } -.max-w-5xl { max-width: 960px; } -.px-6 { padding-left: 24px; padding-right: 24px; } -.py-8 { padding-top: 32px; padding-bottom: 32px; } -.inline-flex { display: inline-flex; } -.justify-center { justify-content: center; } -.rounded-lg { border-radius: 8px; } -.border { border: 1px solid var(--border); } -.border-0 { border: 0; } -.p-1 { padding: 4px; } -.gap-1 { gap: 4px; } -.mb-1 { margin-bottom: 4px; } -.mt-3 { margin-top: 12px; } -.pt-2 { padding-top: 8px; } -.h-px { height: 1px; } - -/* ---------- 24. Helpers ---------- */ -.flex { display: flex; } -.flex-col { flex-direction: column; } -.items-center { align-items: center; } -.justify-between { justify-content: space-between; } -.justify-end { justify-content: flex-end; } -.gap-2 { gap: 8px; } -.gap-3 { gap: 12px; } -.gap-4 { gap: 16px; } -.gap-6 { gap: 24px; } -.mt-1 { margin-top: 4px; } -.mt-2 { margin-top: 8px; } -.mt-4 { margin-top: 16px; } -.mb-2 { margin-bottom: 8px; } -.mb-4 { margin-bottom: 16px; } -.mb-6 { margin-bottom: 24px; } -.py-2 { padding-top: 8px; padding-bottom: 8px; } -.px-3 { padding-left: 12px; padding-right: 12px; } -.text-xs { font-size: 12px; } -.text-sm { font-size: 13px; } -.text-lg { font-size: 18px; } -.text-xl { font-size: 20px; } -.text-2xl { font-size: 24px; } -.font-medium { font-weight: 500; } -.font-semibold { font-weight: 600; } -.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.overflow-x-auto { overflow-x: auto; } -.text-success { color: var(--success); } -.text-error { color: var(--error); } -.text-orange { color: var(--orange); } -.text-blue { color: var(--blue); } -.text-muted { color: var(--fg-muted); } -.text-subtle { color: var(--fg-subtle); } -.w-full { width: 100%; } -.space-y-4 > * + * { margin-top: 16px; } -.space-y-6 > * + * { margin-top: 24px; } - -/* ---------- 25. Status indicator ---------- */ -.status-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; background: var(--fg-subtle); } -.status-dot.connected { background: var(--success); } -.status-dot.connecting { background: var(--warning); animation: pulse 1.5s infinite; } -.status-dot.error { background: var(--error); } -@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .4; } } - -/* ---------- 26. Speed range ---------- */ -input[type="range"] { - -webkit-appearance: none; appearance: none; - width: 100%; height: 4px; border-radius: 2px; - background: linear-gradient(to right, var(--fg) var(--range-progress, 50%), #ddd var(--range-progress, 50%)); -} -input[type="range"]::-webkit-slider-thumb { - -webkit-appearance: none; width: 16px; height: 16px; - border-radius: 50%; background: var(--fg); cursor: pointer; -} - -/* ---------- 27. Animations ---------- */ -.fade-in { animation: fadeIn .4s ease-out; } -@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } } -.spin { animation: spin 1s linear infinite; } -@keyframes spin { to { transform: rotate(360deg); } } - -/* ---------- 28. Responsive ---------- */ -@media (max-width: 768px) { - .page-body { padding: calc(var(--header-h) + 16px) 12px 64px; } - .app-header-inner { padding: 0 12px; } - .header-left { gap: 8px; overflow-x: auto; } - .header-left::-webkit-scrollbar { display: none; } - .brand span { display: none; } - .grid-4 { grid-template-columns: repeat(2, 1fr); } - .grid-3 { grid-template-columns: 1fr 1fr; } - .batch-toolbar { bottom: 12px; padding: 6px 10px; gap: 6px; font-size: 11px; } - .app-footer { right: 12px; left: 12px; text-align: center; } - .chat-sidebar { position: fixed; z-index: 50; left: 0; top: 0; bottom: 0; } - .chat-sidebar.collapsed { margin-left: -260px; } - .voice-grid { grid-template-columns: 1fr; } - .form-grid { grid-template-columns: 1fr; } -} -@media (max-width: 480px) { - .grid-2 { grid-template-columns: 1fr; } - .grid-4 { grid-template-columns: 1fr; } -} diff --git a/app/assets/favicon.ico b/app/assets/favicon.ico deleted file mode 100644 index 1e450588..00000000 Binary files a/app/assets/favicon.ico and /dev/null differ diff --git a/app/assets/function/pages/chat.html b/app/assets/function/pages/chat.html deleted file mode 100644 index def8285e..00000000 --- a/app/assets/function/pages/chat.html +++ /dev/null @@ -1,155 +0,0 @@ - - - - - - - Grok2API - Chat 聊天 - - - - - - - -
-
- -
-
- - - -
-
-
- -
-

Chat 聊天

-

通过 chat 接口与 Grok 进行会话聊天

-
-
- 就绪 -
- -
-
输入一条消息开始对话。
-
- -
-
- - - - -
-
- - - - - - grok-4.20-beta - - - - -
- - -
-
-
-
-
-
- - -
- - - - - - - - - diff --git a/app/assets/function/pages/imagine.html b/app/assets/function/pages/imagine.html deleted file mode 100644 index 13f00fbf..00000000 --- a/app/assets/function/pages/imagine.html +++ /dev/null @@ -1,247 +0,0 @@ - - - - - - - Grok2API - Imagine 瀑布流 - - - - - - - -
-
- -
-
-
-

Imagine 瀑布流

-

通过 WebSocket 持续生成图片,实时展示 base64 瀑布流。

-
- -
- -
-
-
-
生成设置
-
-
-
- - -
-
-
-
-
-
自动跟随
-
滚动到最新
-
- -
-
-
-
自动保存
-
自动保存图片
-
- -
-
-
-
-
- - -
-
- - -
-
-
-
-
-
-
自动过滤
-
过滤不达标图片
-
- -
-
-
-
-
- - -
-
- - -
-
-
-
-
-
-
反向新增
-
最新显示在上方
-
- -
-
-
-
-
- -
-
-
连接状态
- 未连接 - - - -
-
-
-
-
连接模式
-
- - - -
-
-
-
图片数量
-
0
-
-
-
活跃任务
-
0
-
-
-
平均耗时
-
-
-
-
-
-
-
- -
-
-
瀑布流
-
-
-
-
-
等待连接中
-
启动任务后,生成的图片会自动汇聚到这里
-
-
-
-
-
- - - - -
- - - - - - - -
- - -
- - - - - - - - - - diff --git a/app/assets/function/pages/login.html b/app/assets/function/pages/login.html deleted file mode 100644 index e845c5bf..00000000 --- a/app/assets/function/pages/login.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - Grok2API - Public - - - - - -
-
-
- - - - - -
-
- - - - - - - - diff --git a/app/assets/function/pages/video.html b/app/assets/function/pages/video.html deleted file mode 100644 index 6f835b3b..00000000 --- a/app/assets/function/pages/video.html +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - Grok2API - Video 视频生成 - - - - - - - -
-
- -
-
-
-
-

Video 视频生成

-

生成短视频,支持参考图与多种预设风格。

-
-
- - -
-
- -
- -
-
-
生成设置
-
-
- - -
多图参考可在提示词中使用 @图1 到 @图7,按参考图顺序对应。
-
-
- -
- -
-
- 未选择参考图 -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - - -
-
- - -
-
-
- -
-
-
运行状态
- 未连接 -
-
-
-
-
-
- 0% - 耗时 - -
-
-
-
-
比例
-
-
-
-
-
时长
-
-
-
-
-
分辨率
-
-
-
-
-
预设
-
-
-
-
-
-
- -
-
-
视频预览
-
- -
-
-
等待生成视频
- -
-
-
- - -
- - - - - - - - - diff --git a/app/assets/function/pages/voice.html b/app/assets/function/pages/voice.html deleted file mode 100644 index 2f057c5e..00000000 --- a/app/assets/function/pages/voice.html +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - Grok2API - LiveKit 陪聊 - - - - - - - -
-
- -
-
-
-

LiveKit 陪聊

-

LiveKit 语音会话,连接 Grok Voice。

-
-
- - -
-
-
- -
-
-
-
连接设置
-
-
- - -
-
- - -
-
-
- - 1.0x -
- -
-
-
-
-
-
会话日志
-
- - -
-
-
-
-
- -
-
- - -
- - - - - - - diff --git a/app/assets/i18n/README.md b/app/assets/i18n/README.md deleted file mode 100644 index cd737faa..00000000 --- a/app/assets/i18n/README.md +++ /dev/null @@ -1,213 +0,0 @@ -# Grok2API i18n Developer Guide - -## Architecture - -The i18n system is a single-file, zero-dependency module (`i18n.js`) that: - -1. **Detects** the user's language: `localStorage` > `?lang=` URL param > browser `navigator.language` > fallback (`zh`) -2. **Fetches** the matching locale JSON (`/static/i18n/locales/{lang}.json`) -3. **Applies** translations to the DOM via `data-i18n-*` attributes -4. **Exposes** a global `t(key, params)` function for JS-driven strings - -The script self-initializes on DOM ready. No import/export — it attaches `window.I18n` and `window.t`. - -## File structure - -``` -public/static/i18n/ - i18n.js # Core module (IIFE, ~110 lines) - locales/ - zh.json # Chinese (default/fallback) - en.json # English - README.md # This file -``` - -Each HTML page includes the script before page-specific JS: - -```html - - -``` - -## Translation key conventions - -Keys use **dot-notation** with a two-level namespace: `{page}.{name}` - -| Namespace | Scope | -|-----------|-------| -| `common` | Shared strings (save, cancel, loading, errors) | -| `nav` | Navigation links and header labels | -| `login` | Login pages (admin + public) | -| `config` | Admin config page | -| `token` | Token management page | -| `cache` | Cache management page | -| `chat` | Chat page | -| `imagine` | Image generation page | -| `video` | Video generation page | -| `voice` | Voice/LiveKit page | - -Naming patterns: -- `page.pageTitle` — browser tab `` -- `page.title` / `page.subtitle` — heading/subheading -- `page.placeholder` — main input placeholder -- `common.{verb}Failed` / `common.{verb}Error` — error messages -- `page.confirm{Action}` — confirmation dialog text - -## Translating a static HTML element - -Add one of these attributes to the HTML element: - -### `data-i18n` — sets `textContent` - -```html -<h2 data-i18n="chat.title">Chat 聊天</h2> -``` - -### `data-i18n-placeholder` — sets `placeholder` - -```html -<textarea data-i18n-placeholder="chat.placeholder" placeholder="询问任何内容"></textarea> -``` - -### `data-i18n-title` — sets `title` (tooltip) - -```html -<button data-i18n-title="chat.send" title="发送">▶</button> -``` - -### `data-i18n-html` — sets `innerHTML` (available, not currently used) - -```html -<span data-i18n-html="chat.richContent"></span> -``` - -> Use only when the translation contains HTML markup. Prefer `data-i18n` for plain text to avoid XSS risks. - -> Keep the Chinese fallback as the element's default content/attribute so the page renders correctly before translations load. - -## Translating a dynamic JS string - -Use the global `t(key, params?)` function: - -```js -showToast(t('cache.clearSuccess', { size: data.result.size_mb }), 'success'); -``` - -The `params` object replaces `{var}` placeholders in the locale string: - -```json -{ "clearSuccess": "Cleared successfully, freed {size} MB" } -``` - -### Guard pattern for shared modules - -Shared code (e.g., `toast.js`, `admin-auth.js`) may run before `i18n.js` loads. Guard with `typeof t`: - -```js -const label = typeof t === 'function' ? t('common.notice') : '提示'; -``` - -## Translating dynamically injected HTML - -When HTML is injected at runtime (e.g., fetching a header fragment), call `I18n.applyToDOM(container)` after insertion: - -```js -container.innerHTML = await res.text(); - -if (window.I18n) { - I18n.applyToDOM(container); -} -``` - -This scans the container for `data-i18n-*` attributes and applies translations. The language toggle button text is set separately since it isn't a translation key: - -```js -var toggle = container.querySelector('#lang-toggle'); -if (toggle) toggle.textContent = I18n.getLang() === 'zh' ? 'EN' : '中'; -``` - -## API reference - -| Method | Description | -|--------|-------------| -| `t(key, params?)` | Translate a key. Returns the key itself if not found. | -| `I18n.applyToDOM(root?)` | Scan `root` (default: `document`) for `data-i18n-*` attrs and apply translations. | -| `I18n.setLang(lang)` | Set language, persist to localStorage, reload page. | -| `I18n.toggleLang()` | Toggle between `zh` and `en`, reload. | -| `I18n.getLang()` | Return current language code (`'zh'` or `'en'`). | -| `I18n.onReady(cb)` | Run `cb` after translations have loaded. Runs immediately if already loaded. | - -## How to add a new language - -1. Create `public/static/i18n/locales/{code}.json` — copy `en.json` as a template -2. Translate every key (545+ keys across 10 namespaces) -3. In `i18n.js`, add the code to the `SUPPORTED` array: - ```js - var SUPPORTED = ['zh', 'en', 'ja']; - ``` -4. Update the `toggleLang` function if you want rotation instead of binary toggle -5. Update `#lang-toggle` button logic in `header.js` / `public-header.js` - -## How to add a new page - -Checklist: - -- [ ] Add a new namespace in both `zh.json` and `en.json` (e.g., `"mypage": { ... }`) -- [ ] In the HTML: add `<script src="/static/i18n/i18n.js"></script>` before your page JS -- [ ] In the HTML: add `data-i18n` / `data-i18n-placeholder` / `data-i18n-title` attributes to all user-visible elements -- [ ] In the JS: use `t('mypage.keyName')` for any strings built in code -- [ ] If injecting HTML dynamically: call `I18n.applyToDOM(container)` after insertion -- [ ] If the page loads before `i18n.js`: use the `typeof t === 'function'` guard - -## Common patterns - -### Button with icon + translated text - -```html -<button class="btn" type="button"> - <svg>...</svg> - <span data-i18n="voice.startSession">开始会话</span> -</button> -``` - -Wrap the text in a `<span>` so the icon is preserved. - -### Select options translated in JS - -```js -const option = document.createElement('option'); -option.value = 'value'; -option.textContent = t('voice.optionLabel'); -select.appendChild(option); -``` - -### Interpolation for dynamic values - -```js -// Locale: "lastClear": "Last cleared: {time}" -setText(el, t('cache.lastClear', { time: timeText })); -``` - -### Table rows with inline translated strings - -```js -body.innerHTML = `<tr><td colspan="5">${t('common.loading')}</td></tr>`; -``` - -## Gotchas - -1. **Script order matters.** `i18n.js` must be loaded before page JS if the page JS calls `t()` at the top level. Otherwise use the `typeof t === 'function'` guard. - -2. **`t()` returns the key on miss.** If you see a raw key like `chat.title` in the UI, the key is missing from the locale JSON or was misspelled. - -3. **Keep both locale files in sync.** Every key in `zh.json` must exist in `en.json` and vice versa. Missing keys fall through to displaying the raw key string. - -4. **`innerHTML` vs `textContent`.** Use `data-i18n-html` only when the translation contains HTML markup. For plain text, always use `data-i18n` to avoid XSS risks. - -5. **Default content is Chinese.** The HTML files keep Chinese as inline fallback text. This means the page briefly shows Chinese before translations load — this is intentional and ensures the page is never blank. - -6. **`setLang()` reloads the page.** Language switching is not live — it persists to localStorage and triggers a full page reload. - -7. **`applyToDOM()` is idempotent.** Safe to call multiple times on the same container. - -8. **Shared modules need guards.** Files under `common/js/` (toast, header, admin-auth) may be loaded by pages that don't include `i18n.js`. Always guard `t()` calls in shared code. diff --git a/app/assets/i18n/i18n.js b/app/assets/i18n/i18n.js deleted file mode 100644 index 67141c95..00000000 --- a/app/assets/i18n/i18n.js +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Grok2API i18n module — lightweight, zero-dependency internationalization. - * Detects language from: localStorage > ?lang= URL param > browser > fallback (zh). - * Translates static HTML via data-i18n / data-i18n-placeholder / data-i18n-title attrs. - * Provides global t(key, params) for dynamic JS strings with {var} interpolation. - */ -(function () { - 'use strict'; - - var STORAGE_KEY = 'grok2api_lang'; - var SUPPORTED = ['zh', 'en']; - var DEFAULT = 'zh'; - - var lang = DEFAULT; - var data = {}; - var ready = false; - var queue = []; - - function getStaticVersion() { - var script = document.querySelector('script[src*="?v="]'); - if (!script || !script.src) return ''; - var m = script.src.match(/[?&]v=([^&]+)/); - return m ? m[1] : ''; - } - - function detect() { - try { - var s = localStorage.getItem(STORAGE_KEY); - if (s && SUPPORTED.indexOf(s) !== -1) return s; - } catch (e) { /* ignore */ } - try { - var p = new URLSearchParams(location.search).get('lang'); - if (p && SUPPORTED.indexOf(p) !== -1) { - try { localStorage.setItem(STORAGE_KEY, p); } catch (e) { /* ignore */ } - return p; - } - } catch (e) { /* ignore */ } - var b = (navigator.language || '').split('-')[0]; - if (SUPPORTED.indexOf(b) !== -1) return b; - return DEFAULT; - } - - function get(obj, key) { - for (var parts = key.split('.'), i = 0; i < parts.length; i++) { - if (obj == null) return undefined; - obj = obj[parts[i]]; - } - return obj; - } - - function t(key, params) { - var v = get(data, key); - if (v === undefined) return key; - if (params) { - Object.keys(params).forEach(function (k) { - v = v.replace(new RegExp('\\{' + k + '\\}', 'g'), params[k]); - }); - } - return v; - } - - function applyToDOM(root) { - var c = root || document; - c.querySelectorAll('[data-i18n]').forEach(function (el) { - var v = get(data, el.getAttribute('data-i18n')); - if (v !== undefined) el.textContent = v; - }); - c.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) { - var v = get(data, el.getAttribute('data-i18n-placeholder')); - if (v !== undefined) el.placeholder = v; - }); - c.querySelectorAll('[data-i18n-title]').forEach(function (el) { - var v = get(data, el.getAttribute('data-i18n-title')); - if (v !== undefined) el.title = v; - }); - c.querySelectorAll('[data-i18n-aria-label]').forEach(function (el) { - var v = get(data, el.getAttribute('data-i18n-aria-label')); - if (v !== undefined) el.setAttribute('aria-label', v); - }); - c.querySelectorAll('[data-i18n-html]').forEach(function (el) { - var v = get(data, el.getAttribute('data-i18n-html')); - if (v !== undefined) el.innerHTML = v; - }); - } - - function init() { - lang = detect(); - document.documentElement.lang = lang === 'zh' ? 'zh-CN' : lang; - var version = getStaticVersion(); - var url = '/static/i18n/locales/' + lang + '.json' + (version ? ('?v=' + encodeURIComponent(version)) : ''); - fetch(url) - .then(function (r) { if (!r.ok) throw r; return r.json(); }) - .then(function (j) { data = j; }) - .catch(function () { data = {}; }) - .then(function () { - ready = true; - applyToDOM(document); - queue.forEach(function (cb) { cb(); }); - queue = []; - }); - } - - function setLang(l) { - if (SUPPORTED.indexOf(l) === -1) return; - try { localStorage.setItem(STORAGE_KEY, l); } catch (e) { /* ignore */ } - location.reload(); - } - - window.I18n = { - t: t, - applyToDOM: applyToDOM, - setLang: setLang, - toggleLang: function () { setLang(lang === 'zh' ? 'en' : 'zh'); }, - getLang: function () { return lang; }, - onReady: function (cb) { if (ready) cb(); else queue.push(cb); } - }; - window.t = t; - - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', init); - } else { - init(); - } -})(); diff --git a/app/assets/i18n/locales/en.json b/app/assets/i18n/locales/en.json deleted file mode 100644 index 999f699e..00000000 --- a/app/assets/i18n/locales/en.json +++ /dev/null @@ -1,589 +0,0 @@ -{ - "common": { - "save": "Save", - "cancel": "Cancel", - "confirm": "Confirm", - "delete": "Delete", - "loading": "Loading...", - "invalidKey": "Invalid key", - "connectionFailed": "Connection failed", - "requestFailed": "Request failed", - "operationSuccess": "Operation successful", - "gotIt": "Got it", - "notice": "Notice", - "rateLimitNotice": "The official GROK website update did not expose the rate-limits API, making it impossible to accurately calculate remaining Token usage. Please wait for the official API. Currently the count resets to 8 after auto-refresh.", - "pleaseConfirm": "Please confirm", - "ok": "OK", - "close": "Close", - "error": "Error", - "unknownError": "Unknown error", - "connectionInterrupted": "Connection interrupted", - "taskInProgress": "A task is already in progress", - "taskNoPause": "Current task does not support pausing", - "batchNoPause": "Current batch task does not support pausing", - "waitTaskFinish": "Please wait for the current task to finish", - "pause": "Pause", - "stop": "Stop", - "selectAll": "Select all", - "selected": "Selected", - "items": "items", - "export": "Export", - "refresh": "Refresh", - "load": "Load", - "files": "files", - "view": "View", - "retry": "Retry", - "copy": "Copy", - "edit": "Edit", - "loadFailed": "Load failed", - "loadError": "Load failed: {msg}", - "saveFailed": "Save failed", - "saveError": "Save error: {msg}", - "deleteFailed": "Delete failed", - "deleteSuccess": "Deleted successfully", - "notConnected": "Not connected", - "connecting": "Connecting", - "connected": "Connected", - "connectionError": "Connection error", - "generating": "Generating", - "done": "Done", - "failed": "Failed", - "stopped": "Stopped", - "terminated": "Terminated", - "sending": "Sending", - "fileReadFailed": "File read failed", - "noFileSelected": "No file selected", - "configurePublicKey": "Please configure Public Key first", - "enterPrompt": "Please enter a prompt", - "enterContent": "Please enter content", - "alreadyRunning": "Already running", - "createTaskFailed": "Failed to create task", - "copyFailed": "Copy failed", - "copied": "Copied", - "generationFailed": "Generation failed", - "partialError": "Partial error", - "loadingInProgress": "Loading in progress, please wait", - "cleaningInProgress": "Cleaning in progress, please wait", - "noTokenSelected": "No Token selected", - "clearCache": "Clear cache", - "failureDetails": "Failure Details", - "retryFailed": "Retry failed items" - }, - "nav": { - "tokenManage": "Token Mgmt", - "configManage": "Config Mgmt", - "cacheManage": "Cache Mgmt", - "chat": "Chat", - "imagine": "Imagine Gallery", - "video": "Video Generation", - "voice": "LiveKit Voice", - "feedback": "Feedback", - "logout": "Logout", - "adminPanel": "Admin Panel", - "storageMode": "Storage Mode" - }, - "login": { - "adminPageTitle": "Grok2API - Login", - "adminTitle": "Admin Panel", - "adminSubtitle": "Enter admin password to continue", - "adminPlaceholder": "Admin Password (app_key)", - "continue": "Continue", - "publicPageTitle": "Grok2API - Public", - "publicTitle": "Public Access", - "publicSubtitle": "Enter Public Key (leave empty if not configured)", - "publicPlaceholder": "Public Key", - "enter": "Enter", - "goToAdmin": "Go to Admin Panel" - }, - "config": { - "pageTitle": "Grok2API - Config", - "title": "Configuration", - "subtitle": "Manage API keys and system parameters.", - "saving": "Saving...", - "saved": "Saved", - "configSaved": "Configuration saved", - "invalidJson": "Invalid JSON: {field}", - "appKeyRequired": "app_key cannot be empty (admin password)", - "flaresolverrRequired": "FlareSolverr URL is required when auto-refresh is enabled", - "generate": "Generate", - "publicAccess": "Public Access", - "noDesc": "No description available. Please refer to the documentation.", - "sectionFallback": "{section} Settings", - "sections": { - "app": "App Settings", - "proxy": "Proxy Config", - "retry": "Retry Strategy", - "chat": "Chat Config", - "video": "Video Config", - "image": "Image Config", - "imagine_fast": "Imagine Fast Config", - "asset": "Asset Config", - "voice": "Voice Config", - "token": "Token Pool Mgmt", - "cache": "Cache Mgmt", - "nsfw": "NSFW Config", - "usage": "Usage Config" - }, - "sectionDescs": { - "proxy": "Incorrect configuration will cause 403 errors. The IP of the first request to Grok must match the IP used to obtain the CF Clearance. Subsequent IP changes will not cause 403." - }, - "fields": { - "app": { - "api_key": {"title": "API Key", "desc": "Token for calling Grok2API services (optional, supports multiple, comma-separated or array)."}, - "app_key": {"title": "Admin Password", "desc": "Password for logging into the Grok2API admin panel (required)."}, - "function_enabled": {"title": "Enable Function Access", "desc": "Whether to enable the function access entry (disabled means function pages are inaccessible)."}, - "function_key": {"title": "Function Password", "desc": "Access password for function pages (optional)."}, - "app_url": {"title": "App URL", "desc": "External access URL for the Grok2API service, used for file link access."}, - "image_format": {"title": "Image Format", "desc": "Default image format (url or base64)."}, - "video_format": {"title": "Video Format", "desc": "Default video format (html or url, url is the processed link)."}, - "temporary": {"title": "Temporary Chat", "desc": "Whether to enable temporary chat mode by default."}, - "disable_memory": {"title": "Disable Memory", "desc": "Whether to disable Grok memory feature by default."}, - "stream": {"title": "Streaming", "desc": "Whether to enable streaming output by default."}, - "thinking": {"title": "Chain of Thought", "desc": "Whether to enable chain of thought output by default."}, - "dynamic_statsig": {"title": "Dynamic Fingerprint", "desc": "Whether to enable dynamic Statsig fingerprint generation by default."}, - "custom_instruction": {"title": "Custom Instruction", "desc": "Multi-line text passed through as Grok request parameter customPersonality."}, - "filter_tags": {"title": "Filter Tags", "desc": "Configure automatic filtering of special tags in Grok responses."} - }, - "proxy": { - "base_proxy_url": {"title": "Base Proxy URL", "desc": "Base service address for proxying requests to Grok website."}, - "asset_proxy_url": {"title": "Asset Proxy URL", "desc": "Address for proxying static resource (image/video) requests to Grok website."}, - "skip_proxy_ssl_verify": {"title": "Skip Proxy SSL Verify", "desc": "Enable when your proxy uses a self-signed certificate (only bypasses proxy certificate validation)."}, - "enabled": {"title": "Enable CF Auto-Refresh", "desc": "When enabled, automatically obtains cf_clearance through FlareSolverr."}, - "flaresolverr_url": {"title": "FlareSolverr URL", "desc": "HTTP address of FlareSolverr service (e.g. http://flaresolverr:8191)."}, - "refresh_interval": {"title": "Refresh Interval (sec)", "desc": "Time interval for auto-refreshing cf_clearance, recommended minimum 300 seconds."}, - "timeout": {"title": "Challenge Timeout (sec)", "desc": "Maximum time to wait for FlareSolverr to solve CF challenge."}, - "cf_clearance": {"title": "CF Clearance", "desc": "Cloudflare Clearance Cookie for bypassing anti-bot verification. Automatically managed when auto-refresh is enabled."}, - "browser": {"title": "Browser Fingerprint", "desc": "curl_cffi browser fingerprint identifier (e.g. chrome136). Automatically managed when auto-refresh is enabled."}, - "user_agent": {"title": "User-Agent", "desc": "HTTP request User-Agent string. Automatically managed when auto-refresh is enabled."} - }, - "retry": { - "max_retry": {"title": "Max Retries", "desc": "Maximum number of retries when Grok service request fails."}, - "retry_status_codes": {"title": "Retry Status Codes", "desc": "HTTP status codes that trigger a retry."}, - "reset_session_status_codes": {"title": "Session Reset Status Codes", "desc": "HTTP status codes that trigger session rebuild (used for proxy rotation)."}, - "retry_backoff_base": {"title": "Backoff Base", "desc": "Base delay (seconds) for retry backoff."}, - "retry_backoff_factor": {"title": "Backoff Factor", "desc": "Exponential multiplier for retry backoff."}, - "retry_backoff_max": {"title": "Backoff Max", "desc": "Maximum delay (seconds) for a single retry wait."}, - "retry_budget": {"title": "Backoff Budget", "desc": "Maximum total retry time (seconds) for a single request."} - }, - "chat": { - "concurrent": {"title": "Concurrency Limit", "desc": "Reverse API concurrency limit."}, - "timeout": {"title": "Request Timeout", "desc": "Reverse API timeout (seconds)."}, - "stream_timeout": {"title": "Stream Idle Timeout", "desc": "Streaming idle timeout (seconds)."} - }, - "video": { - "enable_public_asset": {"title": "Public Asset Link", "desc": "Whether to create a public asset link after video generation finishes."}, - "concurrent": {"title": "Concurrency Limit", "desc": "Reverse API concurrency limit."}, - "timeout": {"title": "Request Timeout", "desc": "Reverse API timeout (seconds)."}, - "stream_timeout": {"title": "Stream Idle Timeout", "desc": "Streaming idle timeout (seconds)."}, - "upscale_timing": {"title": "Upscale Timing", "desc": "Basic pool 720p upscale mode: single upscales after each extension round, complete upscales once after all rounds."} - }, - "image": { - "timeout": {"title": "Request Timeout", "desc": "WebSocket request timeout (seconds)."}, - "stream_timeout": {"title": "Stream Idle Timeout", "desc": "WebSocket streaming idle timeout (seconds)."}, - "final_timeout": {"title": "Final Image Timeout", "desc": "Timeout (seconds) to wait for final image after receiving medium image."}, - "blocked_grace_seconds": {"title": "Review Grace Seconds", "desc": "Grace seconds for suspected review/censorship after receiving medium image (default 10, configurable)."}, - "nsfw": {"title": "NSFW Mode", "desc": "Whether to enable NSFW for WebSocket requests."}, - "medium_min_bytes": {"title": "Medium Min Bytes", "desc": "Minimum byte size for medium quality image detection."}, - "final_min_bytes": {"title": "Final Min Bytes", "desc": "Minimum byte size for final image detection (typically JPG > 100KB)."}, - "blocked_parallel_enabled": {"title": "Enable Parallel Compensation", "desc": "Whether to enable parallel compensation when suspected review/blocking occurs."}, - "blocked_parallel_attempts": {"title": "Block Compensation Concurrency", "desc": "Number of parallel compensation attempts when suspected review/blocking prevents final image."} - }, - "imagine_fast": { - "n": {"title": "Generation Count", "desc": "Server-side unified generation count for grok-imagine-1.0-fast only (1-10)."}, - "size": {"title": "Image Size", "desc": "Server-side unified size for grok-imagine-1.0-fast only."}, - "response_format": {"title": "Response Format", "desc": "Server-side unified response format for grok-imagine-1.0-fast only."} - }, - "asset": { - "upload_concurrent": {"title": "Upload Concurrency", "desc": "Maximum concurrent uploads. Recommended: 30."}, - "upload_timeout": {"title": "Upload Timeout", "desc": "Upload timeout (seconds). Recommended: 60."}, - "download_concurrent": {"title": "Download Concurrency", "desc": "Maximum concurrent downloads. Recommended: 30."}, - "download_timeout": {"title": "Download Timeout", "desc": "Download timeout (seconds). Recommended: 60."}, - "list_concurrent": {"title": "Query Concurrency", "desc": "Maximum concurrent asset queries. Recommended: 10."}, - "list_timeout": {"title": "Query Timeout", "desc": "Asset query timeout (seconds). Recommended: 60."}, - "list_batch_size": {"title": "Query Batch Size", "desc": "Number of tokens per query batch. Recommended: 10."}, - "delete_concurrent": {"title": "Delete Concurrency", "desc": "Maximum concurrent asset deletions. Recommended: 10."}, - "delete_timeout": {"title": "Delete Timeout", "desc": "Asset deletion timeout (seconds). Recommended: 60."}, - "delete_batch_size": {"title": "Delete Batch Size", "desc": "Number of tokens per delete batch. Recommended: 10."} - }, - "voice": { - "timeout": {"title": "Request Timeout", "desc": "Voice request timeout (seconds)."} - }, - "token": { - "auto_refresh": {"title": "Auto Refresh", "desc": "Whether to enable automatic Token refresh."}, - "refresh_interval_hours": {"title": "Refresh Interval", "desc": "Time interval (hours) for regular Token refresh."}, - "super_refresh_interval_hours": {"title": "Super Refresh Interval", "desc": "Time interval (hours) for Super Token refresh."}, - "fail_threshold": {"title": "Failure Threshold", "desc": "Number of consecutive failures before a Token is marked unavailable."}, - "save_delay_ms": {"title": "Save Delay", "desc": "Delay (ms) for batching Token change writes."}, - "usage_flush_interval_sec": {"title": "Usage Flush Interval", "desc": "Minimum interval (seconds) for writing usage data to database."}, - "reload_interval_sec": {"title": "Sync Interval", "desc": "Token state refresh interval (seconds) in multi-worker scenarios."} - }, - "cache": { - "enable_auto_clean": {"title": "Auto Clean", "desc": "Whether to enable automatic cache cleanup based on size limit."}, - "limit_mb": {"title": "Clean Threshold", "desc": "Cache size threshold (MB) that triggers cleanup."} - }, - "nsfw": { - "concurrent": {"title": "Concurrency Limit", "desc": "Maximum concurrent requests for batch NSFW enable. Recommended: 10."}, - "batch_size": {"title": "Batch Size", "desc": "Batch processing count for NSFW enable. Recommended: 50."}, - "timeout": {"title": "Request Timeout", "desc": "Timeout for NSFW-related requests (seconds). Recommended: 60."} - }, - "usage": { - "concurrent": {"title": "Concurrency Limit", "desc": "Maximum concurrent requests for batch usage refresh. Recommended: 10."}, - "batch_size": {"title": "Batch Size", "desc": "Batch processing count for usage refresh. Recommended: 50."}, - "timeout": {"title": "Request Timeout", "desc": "Usage query timeout (seconds). Recommended: 60."} - } - } - }, - "token": { - "pageTitle": "Grok2API - Token Mgmt", - "title": "Token List", - "subtitle": "Manage the Grok2API Token service pool.", - "import": "Import", - "add": "Add", - "statTotal": "Total Tokens", - "statActive": "Active", - "statCooling": "Rate Limited", - "statInvalid": "Invalid", - "statChatQuota": "Chat Remaining", - "statImageQuota": "Image Remaining", - "statChatConsumed": "Chat Consumed", - "statImageConsumed": "Image Consumed", - "statVideoQuota": "Video Remaining", - "statVideoUnavailable": "N/A", - "statTotalCalls": "Total Calls", - "tabAll": "All", - "tabActive": "Active", - "tabCooling": "Rate Limited", - "tabExpired": "Expired", - "tabNsfw": "NSFW On", - "tabNoNsfw": "NSFW Off", - "statusFilterAria": "Token status filter", - "tableToken": "Token", - "tableType": "Type", - "tableStatus": "Status", - "tableQuota": "Quota", - "tableQuotaConsumed": "Consumed", - "tableNote": "Note", - "tableActions": "Actions", - "refreshStatus": "Refresh status", - "emptyState": "No Tokens yet. Click Import or Add above.", - "emptyFilterState": "No results for current filter. Try a different filter.", - "selectPage": "Select page", - "selectAllFiltered": "Select all", - "clearSelection": "Clear selection", - "prevPage": "Prev", - "nextPage": "Next", - "perPage": "{size} / page", - "pagination": "Page {current} / {total} \u00b7 {count} items", - "batchExport": "Export", - "batchRefresh": "Refresh", - "batchDisable": "Disable", - "batchEnable": "Enable", - "batchDelete": "Delete", - "importTitle": "Batch Import Tokens", - "importTargetPool": "Target Pool", - "importTokenList": "Token List (one per line)", - "importPlaceholder": "Paste Tokens, one per line...", - "startImport": "Start Import", - "editTitle": "Edit Token", - "addTitle": "Add Token", - "editType": "Type", - "editQuota": "Quota", - "editNote": "Note", - "editNotePlaceholder": "Optional note", - "tokenEmpty": "Token cannot be empty", - "tokenExists": "Token already exists", - "confirmDelete": "Are you sure you want to delete this Token?", - "confirmDisable": "Are you sure you want to disable this Token?\n{token}", - "confirmEnable": "Are you sure you want to enable this Token?\n{token}", - "confirmBatchDelete": "Are you sure you want to delete {count} selected Tokens?", - "confirmBatchDisable": "Are you sure you want to disable {count} selected Tokens?", - "confirmBatchEnable": "Are you sure you want to enable {count} selected Tokens?", - "disableToken": "Disable", - "enableToken": "Enable", - "disableDone": "Token disabled", - "enableDone": "Token enabled", - "batchDisableDone": "Batch disable complete", - "batchEnableDone": "Batch enable complete", - "noTokenToDisable": "All selected Tokens are already disabled", - "noTokenToEnable": "All selected Tokens are already enabled", - "deleteDone": "Delete complete", - "refreshDone": "Refresh complete", - "refreshSuccess": "Refresh successful", - "refreshFailed": "Refresh failed", - "refreshError": "Refresh failed: {msg}", - "requestError": "Request error", - "notValidJson": "Response is not valid JSON (HTTP {status})", - "listEmpty": "List is empty", - "stopRefresh": "Refresh stopped", - "stopDelete": "Delete stopped", - "stopNsfw": "NSFW stopped", - "nsfwConfirm": "Enable NSFW mode for {count} selected Tokens?", - "nsfwEnable": "Enable NSFW", - "nsfwDone": "NSFW enable complete", - "nsfwResult": "NSFW enable complete: {ok} succeeded, {fail} failed", - "nsfwFailed": "Enable failed: {msg}", - "emptyResponse": "Empty response (HTTP {status})" - }, - "cache": { - "pageTitle": "Grok2API - Cache Mgmt", - "title": "Cache Management", - "subtitle": "Manage local resources and online asset cache.", - "localImages": "Local Images", - "localVideos": "Local Videos", - "onlineAssets": "Online Assets", - "tableFile": "File", - "tableSize": "Size", - "tableTime": "Time", - "tableActions": "Actions", - "tableToken": "Token", - "tableType": "Type", - "tableAssetCount": "Asset Count", - "tableLastClear": "Last Cleared", - "selectPage": "Select page", - "selectAllFiles": "Select all", - "clearSelection": "Clear selection", - "prevPage": "Prev", - "nextPage": "Next", - "perPageLabel": "Per page", - "perPage": "{size} / page", - "pagination": "Page {current} / {total} · {count} items", - "notLoaded": "Not loaded", - "noAccounts": "No accounts available", - "noFiles": "No files", - "noTokenAvailable": "No Token available", - "cannotConnect": "Cannot connect", - "lastClear": "Last cleared: {time}", - "clear": "Clear", - "clean": "Clean", - "confirmClearImage": "Clear all local image cache?", - "confirmClearVideo": "Clear all local video cache?", - "clearSuccess": "Cleanup successful, freed {size} MB", - "clearFailed": "Cleanup failed", - "confirmDeleteFile": "Are you sure you want to delete this file?", - "confirmBatchDeleteFiles": "Are you sure you want to delete {count} selected files?", - "noFilesSelected": "No files selected", - "deletedFiles": "Deleted {count} files", - "deleteResult": "Delete complete: {success} succeeded, {failed} failed", - "loadStatsFailed": "Failed to load statistics", - "selectAccountsToLoad": "Please select accounts to load", - "selectAccountsToClear": "Please select accounts to clear", - "confirmClearAccounts": "Clear online assets for {count} selected accounts?", - "confirmClearAccount": "Clear online assets for account {label}?", - "batchCleanInProgress": "Batch cleaning online assets, please wait...", - "cleanInProgress": "Cleaning online assets, please wait...", - "batchCleanDone": "Batch cleanup complete", - "cleanResult": "Cleanup complete (succeeded: {success}, failed: {failed})", - "cleanFailedEntry": "Cleanup failed", - "requestTimeout": "Request timed out or failed", - "loadDone": "Load complete", - "loadingStatus": "Loading", - "loadStopped": "Load stopped", - "loadFailedMsg": "Load failed: {msg}", - "stoppedLoadRequests": "Remaining load requests stopped", - "cleanStopped": "Clean stopped", - "cleanFailedMsg": "Clean failed: {msg}", - "stoppedCleanRequests": "Remaining clean requests stopped" - }, - "chat": { - "pageTitle": "Grok2API - Chat", - "title": "Chat", - "subtitle": "Chat with Grok via the chat API", - "sessions": "Sessions", - "newChat": "New", - "collapseSidebar": "Collapse", - "expandSidebar": "Expand", - "sessionList": "Session list", - "newSession": "New Session", - "ready": "Ready", - "emptyState": "Type a message to start a conversation.", - "uploadFile": "Upload file", - "placeholder": "Ask anything", - "settings": "Settings", - "send": "Send", - "temperature": "Temperature", - "topP": "Top P", - "systemPrompt": "System Prompt", - "systemPromptPlaceholder": "Optional, set system prompt", - "fileLabel": "[File]", - "compositeContent": "[Composite]", - "storageFull": "Local storage is full, some sessions were not saved", - "attachmentNoEdit": "Attachment messages cannot be edited yet", - "saveEdit": "Save", - "saveEditTitle": "Save edit", - "cancelEdit": "Cancel", - "cancelEditTitle": "Cancel edit", - "contentEmpty": "Content cannot be empty", - "editMessage": "Edit", - "editMessageTitle": "Edit message content", - "regenerate": "Regenerate", - "regenerateTitle": "Regenerate response from here", - "retryTitle": "Retry last response", - "editAnswer": "Edit", - "editAnswerTitle": "Edit response content", - "copyAnswer": "Copy", - "copyAnswerTitle": "Copy response content", - "feedback": "Feedback", - "feedbackTitle": "Feedback to Grok2API", - "noContentToCopy": "No content to copy", - "noChatToRetry": "No conversation to retry", - "requestFailedCheck": "Request failed, please check service status", - "requestFailedStatus": "Request failed: {status}", - "clickRetry": "Click to retry", - "thinking": "Thinking", - "thinkingSec": "Thinking {sec}s", - "thought": "Thought", - "thinkLabel": "Thinking", - "empty": "(empty)", - "toolWebSearch": "Web search", - "toolImageSearch": "Image search", - "toolAgentThink": "Reasoning", - "toolDefault": "Tool" - }, - "imagine": { - "pageTitle": "Grok2API - Imagine Gallery", - "title": "Imagine Gallery", - "subtitle": "Continuously generate images via WebSocket, real-time base64 gallery.", - "genSettings": "Generation Settings", - "prompt": "Prompt", - "promptPlaceholder": "Describe the image you want, e.g.: futuristic city neon rain at night, wide angle photography", - "autoFollow": "Auto Follow", - "autoFollowDesc": "Scroll to latest", - "autoSave": "Auto Save", - "autoSaveDesc": "Auto-save images", - "aspectRatio": "Aspect Ratio", - "ratio2_3": "2:3 Portrait", - "ratio1_1": "1:1 Square", - "ratio3_2": "3:2 Landscape", - "ratio16_9": "16:9 Wide", - "ratio9_16": "9:16 Tall", - "concurrent": "Concurrency", - "tasks": "{n} tasks", - "concurrentTask1": "1 task", - "concurrentTask2": "2 tasks", - "concurrentTask3": "3 tasks", - "autoFilter": "Auto Filter", - "autoFilterDesc": "Filter substandard images", - "nsfwLabel": "NSFW", - "nsfwOn": "On", - "nsfwOff": "Off", - "saveLocation": "Save Location", - "browserDefault": "Browser default location", - "reverseOrder": "Reverse Order", - "reverseOrderDesc": "Show newest on top", - "connectionStatus": "Connection Status", - "connectionMode": "Connection Mode", - "connectionModeAria": "Connection mode", - "imageCount": "Image Count", - "activeTasks": "Active Tasks", - "avgTime": "Avg Time", - "gallery": "Gallery", - "waitingTitle": "Waiting for connection", - "waitingSubtitle": "Generated images will appear here after starting a task", - "start": "Start", - "batch": "Batch", - "batchDownloadTitle": "Batch download", - "selectAll": "Select all", - "deselectAll": "Deselect all", - "download": "Download", - "startedTasks": "Started {count} concurrent tasks", - "startedTasksSSE": "Started {count} concurrent tasks (SSE)", - "generatingSSE": "Generating (SSE)", - "selectFolder": "Selected folder: {name}", - "selectFolderFailed": "Failed to select folder", - "noImagesSelected": "Please select images to download first", - "jszipFailed": "JSZip library failed to load, please refresh and try again", - "packing": "Packing {count} images...", - "packingBtn": "Packing...", - "packingProgress": "Packing... ({done}/{total})", - "noImagesDownloaded": "No images were downloaded successfully", - "generatingZip": "Generating ZIP...", - "packSuccess": "Successfully packed {count} images", - "packFailed": "Packing failed, please try again" - }, - "video": { - "pageTitle": "Grok2API - Video Generation", - "title": "Video Generation", - "subtitle": "Generate short videos with up to 7 reference images, @图N placeholders, and preset styles.", - "startGenerate": "Generate", - "genSettings": "Generation Settings", - "prompt": "Prompt", - "promptPlaceholder": "e.g.: @图1 neon rainy street at night, @图2 subject looking back and smiling, slow motion, film grain", - "promptTip": "Use @图1 to @图7 in the prompt to reference images by upload order.", - "referenceImage": "Reference Image", - "referenceImagePlaceholder": "One https://... or data:image/... per line, up to 7 images", - "aspectRatio": "Aspect Ratio", - "ratio3_2": "3:2 Landscape", - "ratio2_3": "2:3 Portrait", - "ratio16_9": "16:9 Wide", - "ratio9_16": "9:16 Tall", - "ratio1_1": "1:1 Square", - "duration": "Duration", - "seconds": "{n}s", - "resolution": "Resolution", - "stylePreset": "Style Preset", - "upload": "Upload", - "clearImage": "Clear", - "runStatus": "Run Status", - "elapsedTime": "Elapsed {sec}s", - "elapsedTimeNone": "Elapsed -", - "metaRatio": "Ratio", - "metaDuration": "Duration", - "metaResolution": "Resolution", - "metaPreset": "Preset", - "videoPreview": "Video Preview", - "clearPreview": "Clear", - "waitingGenerate": "Waiting for video generation", - "videoTitle": "Video {n}", - "open": "Open", - "generatingPlaceholder": "Generating...", - "superResolution": "Super Resolution", - "superResolutionInProgress": "Super resolution in progress", - "alreadyGenerating": "Already generating", - "referenceConflict": "Reference images: choose either URL/Base64 list or file upload", - "referenceLimit": "A maximum of 7 reference images is supported", - "noReferenceSelected": "No reference images selected", - "downloadFailed": "Download failed, please check if the video link is accessible", - "sec6": "6s", - "sec10": "10s", - "sec15": "15s" - }, - "voice": { - "pageTitle": "Grok2API - LiveKit Voice", - "title": "LiveKit Voice", - "subtitle": "LiveKit voice session, connect to Grok Voice.", - "startSession": "Start Session", - "stopSession": "Stop Session", - "connectionSettings": "Connection Settings", - "voiceLabel": "Voice", - "personalityLabel": "Personality", - "speedLabel": "Speed", - "settingsHint": "Tip: Voice / Personality settings are sent to the server before connecting.", - "sessionLog": "Session Log", - "clearLog": "Clear", - "copyLog": "Copy", - "sessionStatus": "Session Status", - "audioOutput": "Audio Output", - "audioHint": "Subscribed audio tracks will be automatically inserted here.", - "livekitSDKError": "Error: LiveKit SDK failed to load properly, please refresh the page", - "livekitLoadFailed": "LiveKit SDK failed to load", - "secureContextBrowser": "Please use a modern browser and allow microphone access", - "secureContextHTTPS": "Please use HTTPS or access from localhost", - "secureContextError": "Current environment does not support microphone access, {hint}", - "connectingStatus": "Connecting", - "fetchingToken": "Fetching Token...", - "fetchTokenFailed": "Failed to get Token: {status}", - "fetchTokenSuccess": "Token obtained successfully", - "participantConnected": "Participant connected: {identity}", - "participantDisconnected": "Participant disconnected: {identity}", - "trackSubscribed": "Track subscribed: {kind}", - "disconnected": "Disconnected", - "connectedToServer": "Connected to LiveKit server", - "inCall": "In call", - "openingMic": "Opening microphone...", - "voiceEnabled": "Voice enabled", - "voiceConnected": "Voice connected successfully", - "errorPrefix": "Error: {msg}", - "logCopied": "Log copied", - "copyLogFailed": "Copy failed, please select manually" - } -} diff --git a/app/assets/i18n/locales/zh.json b/app/assets/i18n/locales/zh.json deleted file mode 100644 index 329ed50b..00000000 --- a/app/assets/i18n/locales/zh.json +++ /dev/null @@ -1,589 +0,0 @@ -{ - "common": { - "save": "保存", - "cancel": "取消", - "confirm": "确认", - "delete": "删除", - "loading": "加载中...", - "invalidKey": "密钥无效", - "connectionFailed": "连接失败", - "requestFailed": "请求失败", - "operationSuccess": "操作成功", - "gotIt": "我知道了", - "notice": "提示", - "rateLimitNotice": "GROK 官方网页更新后未真实暴露 rate-limits 接口,导致无法准确计算 Token 剩余,请耐心等待官方接口上线,目前自动刷新后会更新为 8 次", - "pleaseConfirm": "请确认", - "ok": "确定", - "close": "关闭", - "error": "错误", - "unknownError": "未知错误", - "connectionInterrupted": "连接中断", - "taskInProgress": "当前有任务进行中", - "taskNoPause": "当前任务不支持暂停", - "batchNoPause": "当前批量任务不支持暂停", - "waitTaskFinish": "请等待当前任务结束", - "pause": "暂停", - "stop": "终止", - "selectAll": "全选", - "selected": "已选择", - "items": "项", - "export": "导出", - "refresh": "刷新", - "load": "加载", - "files": "个文件", - "view": "查看", - "retry": "重试", - "copy": "复制", - "edit": "编辑", - "loadFailed": "加载失败", - "loadError": "加载失败: {msg}", - "saveFailed": "保存失败", - "saveError": "保存错误: {msg}", - "deleteFailed": "删除失败", - "deleteSuccess": "删除成功", - "notConnected": "未连接", - "connecting": "连接中", - "connected": "连接正常", - "connectionError": "连接错误", - "generating": "生成中", - "done": "完成", - "failed": "失败", - "stopped": "已停止", - "terminated": "已终止", - "sending": "发送中", - "fileReadFailed": "文件读取失败", - "noFileSelected": "未选择文件", - "configurePublicKey": "请先配置 Public Key", - "enterPrompt": "请输入提示词", - "enterContent": "请输入内容", - "alreadyRunning": "已在运行中", - "createTaskFailed": "创建任务失败", - "copyFailed": "复制失败", - "copied": "已复制", - "generationFailed": "生成失败", - "partialError": "部分异常", - "loadingInProgress": "正在加载中,请稍候", - "cleaningInProgress": "正在清理中,请稍候", - "noTokenSelected": "未选择 Token", - "clearCache": "清空缓存", - "failureDetails": "失败详情", - "retryFailed": "重试失败项" - }, - "nav": { - "tokenManage": "Token管理", - "configManage": "配置管理", - "cacheManage": "缓存管理", - "chat": "Chat 聊天", - "imagine": "Imagine 瀑布流", - "video": "Video 视频生成", - "voice": "LiveKit 陪聊", - "feedback": "反馈", - "logout": "退出", - "adminPanel": "管理后台", - "storageMode": "存储模式" - }, - "login": { - "adminPageTitle": "Grok2API - 登录", - "adminTitle": "管理后台", - "adminSubtitle": "请输入后台密码以继续", - "adminPlaceholder": "后台密码 (app_key)", - "continue": "继续", - "publicPageTitle": "Grok2API - Public", - "publicTitle": "Public Access", - "publicSubtitle": "请输入 Public Key(如未配置可直接进入)", - "publicPlaceholder": "Public Key", - "enter": "进入", - "goToAdmin": "进入管理后台" - }, - "config": { - "pageTitle": "Grok2API - 配置管理", - "title": "配置管理", - "subtitle": "管理 API 密钥及系统参数设置。", - "saving": "保存中...", - "saved": "成功", - "configSaved": "配置已保存", - "invalidJson": "无效的 JSON: {field}", - "appKeyRequired": "app_key 不能为空(后台密码)", - "flaresolverrRequired": "启用自动刷新时必须填写 FlareSolverr 地址", - "generate": "生成", - "publicAccess": "功能玩法", - "noDesc": "暂无说明,请参考配置文档。", - "sectionFallback": "{section} 设置", - "sections": { - "app": "应用设置", - "proxy": "代理配置", - "retry": "重试策略", - "chat": "对话配置", - "video": "视频配置", - "image": "图像配置", - "imagine_fast": "Imagine Fast 配置", - "asset": "资产配置", - "voice": "语音配置", - "token": "Token 池管理", - "cache": "缓存管理", - "nsfw": "NSFW 配置", - "usage": "Usage 配置" - }, - "sectionDescs": { - "proxy": "配置不正确将导致 403 错误。服务首次请求 Grok 时的 IP 必须与获取 CF Clearance 时的 IP 一致,后续服务器请求 IP 变化不会导致 403。" - }, - "fields": { - "app": { - "api_key": {"title": "API 密钥", "desc": "调用 Grok2API 服务的 Token(可选,支持多个,逗号分隔或数组)。"}, - "app_key": {"title": "后台密码", "desc": "登录 Grok2API 管理后台的密码(必填)。"}, - "function_enabled": {"title": "启用功能玩法", "desc": "是否启用功能玩法入口(关闭则功能玩法页面不可访问)。"}, - "function_key": {"title": "Function 密码", "desc": "功能玩法页面的访问密码(可选)。"}, - "app_url": {"title": "应用地址", "desc": "当前 Grok2API 服务的外部访问 URL,用于文件链接访问。"}, - "image_format": {"title": "图片格式", "desc": "默认生成的图片格式(url 或 base64)。"}, - "video_format": {"title": "视频格式", "desc": "默认生成的视频格式(html 或 url,url 为处理后的链接)。"}, - "temporary": {"title": "临时对话", "desc": "是否默认启用临时对话模式。"}, - "disable_memory": {"title": "禁用记忆", "desc": "是否默认禁用 Grok 记忆功能。"}, - "stream": {"title": "流式响应", "desc": "是否默认启用流式输出。"}, - "thinking": {"title": "思维链", "desc": "是否默认启用思维链输出。"}, - "dynamic_statsig": {"title": "动态指纹", "desc": "是否默认启用动态生成 Statsig 指纹。"}, - "custom_instruction": {"title": "自定义指令", "desc": "多行文本,会透传为 Grok 请求参数 customPersonality。"}, - "filter_tags": {"title": "过滤标签", "desc": "设置自动过滤 Grok 响应中的特殊标签。"} - }, - "proxy": { - "base_proxy_url": {"title": "基础代理 URL", "desc": "代理请求到 Grok 官网的基础服务地址。"}, - "asset_proxy_url": {"title": "资源代理 URL", "desc": "代理请求到 Grok 官网的静态资源(图片/视频)地址。"}, - "skip_proxy_ssl_verify": {"title": "跳过代理 SSL 校验", "desc": "代理使用自签名证书时启用(仅放行代理证书校验)。"}, - "enabled": {"title": "启用 CF 自动刷新", "desc": "启用后将通过 FlareSolverr 自动获取 cf_clearance。"}, - "flaresolverr_url": {"title": "FlareSolverr 地址", "desc": "FlareSolverr 服务的 HTTP 地址(如 http://flaresolverr:8191)。"}, - "refresh_interval": {"title": "刷新间隔(秒)", "desc": "自动刷新 cf_clearance 的时间间隔,建议不低于 300 秒。"}, - "timeout": {"title": "挑战超时(秒)", "desc": "等待 FlareSolverr 解决 CF 挑战的最大时间。"}, - "cf_clearance": {"title": "CF Clearance", "desc": "Cloudflare Clearance Cookie,用于绕过反爬虫验证。启用自动刷新时由系统自动管理。"}, - "browser": {"title": "浏览器指纹", "desc": "curl_cffi 浏览器指纹标识(如 chrome136)。启用自动刷新时由系统自动管理。"}, - "user_agent": {"title": "User-Agent", "desc": "HTTP 请求的 User-Agent 字符串。启用自动刷新时由系统自动管理。"} - }, - "retry": { - "max_retry": {"title": "最大重试次数", "desc": "请求 Grok 服务失败时的最大重试次数。"}, - "retry_status_codes": {"title": "重试状态码", "desc": "触发重试的 HTTP 状态码列表。"}, - "reset_session_status_codes": {"title": "重建状态码", "desc": "触发重建 session 的 HTTP 状态码列表(用于轮换代理)。"}, - "retry_backoff_base": {"title": "退避基数", "desc": "重试退避的基础延迟(秒)。"}, - "retry_backoff_factor": {"title": "退避倍率", "desc": "重试退避的指数放大系数。"}, - "retry_backoff_max": {"title": "退避上限", "desc": "单次重试等待的最大延迟(秒)。"}, - "retry_budget": {"title": "退避预算", "desc": "单次请求的最大重试总耗时(秒)。"} - }, - "chat": { - "concurrent": {"title": "并发上限", "desc": "Reverse 接口并发上限。"}, - "timeout": {"title": "请求超时", "desc": "Reverse 接口超时时间(秒)。"}, - "stream_timeout": {"title": "流空闲超时", "desc": "流式空闲超时时间(秒)。"} - }, - "video": { - "enable_public_asset": {"title": "公开资产链接", "desc": "是否开启生成结束后创建 Public 资产。"}, - "concurrent": {"title": "并发上限", "desc": "Reverse 接口并发上限。"}, - "timeout": {"title": "请求超时", "desc": "Reverse 接口超时时间(秒)。"}, - "stream_timeout": {"title": "流空闲超时", "desc": "流式空闲超时时间(秒)。"}, - "upscale_timing": {"title": "超分时机", "desc": "Basic 号池 720p 超分模式:single 为每轮扩展后超分,complete 为全部扩展完成后再超分。"} - }, - "image": { - "timeout": {"title": "请求超时", "desc": "WebSocket 请求超时时间(秒)。"}, - "stream_timeout": {"title": "流空闲超时", "desc": "WebSocket 流式空闲超时时间(秒)。"}, - "final_timeout": {"title": "最终图超时", "desc": "收到中等图后等待最终图的超时秒数。"}, - "blocked_grace_seconds": {"title": "审查宽限秒数", "desc": "收到中等图后,判定疑似被审查的宽限秒数(默认 10 秒,可自定义)。"}, - "nsfw": {"title": "NSFW 模式", "desc": "WebSocket 请求是否启用 NSFW。"}, - "medium_min_bytes": {"title": "中等图最小字节", "desc": "判定中等质量图的最小字节数。"}, - "final_min_bytes": {"title": "最终图最小字节", "desc": "判定最终图的最小字节数(通常 JPG > 100KB)。"}, - "blocked_parallel_enabled": {"title": "启用并行补偿", "desc": "疑似审查/拦截时,是否启用并行补偿生成。"}, - "blocked_parallel_attempts": {"title": "拦截补偿并发次数", "desc": "疑似审查/拦截导致无最终图时,自动并行补偿生成次数。"} - }, - "imagine_fast": { - "n": {"title": "生成数量", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一生成数量(1-10)。"}, - "size": {"title": "图片尺寸", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一尺寸。"}, - "response_format": {"title": "响应格式", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一返回格式。"} - }, - "asset": { - "upload_concurrent": {"title": "上传并发", "desc": "上传接口的最大并发数。推荐 30。"}, - "upload_timeout": {"title": "上传超时", "desc": "上传接口超时时间(秒)。推荐 60。"}, - "download_concurrent": {"title": "下载并发", "desc": "下载接口的最大并发数。推荐 30。"}, - "download_timeout": {"title": "下载超时", "desc": "下载接口超时时间(秒)。推荐 60。"}, - "list_concurrent": {"title": "查询并发", "desc": "资产查询接口的最大并发数。推荐 10。"}, - "list_timeout": {"title": "查询超时", "desc": "资产查询接口超时时间(秒)。推荐 60。"}, - "list_batch_size": {"title": "查询批次大小", "desc": "单次查询可处理的 Token 数量。推荐 10。"}, - "delete_concurrent": {"title": "删除并发", "desc": "资产删除接口的最大并发数。推荐 10。"}, - "delete_timeout": {"title": "删除超时", "desc": "资产删除接口超时时间(秒)。推荐 60。"}, - "delete_batch_size": {"title": "删除批次大小", "desc": "单次删除可处理的 Token 数量。推荐 10。"} - }, - "voice": { - "timeout": {"title": "请求超时", "desc": "Voice 请求超时时间(秒)。"} - }, - "token": { - "auto_refresh": {"title": "自动刷新", "desc": "是否开启 Token 自动刷新机制。"}, - "refresh_interval_hours": {"title": "刷新间隔", "desc": "普通 Token 刷新的时间间隔(小时)。"}, - "super_refresh_interval_hours": {"title": "Super 刷新间隔", "desc": "Super Token 刷新的时间间隔(小时)。"}, - "fail_threshold": {"title": "失败阈值", "desc": "单个 Token 连续失败多少次后被标记为不可用。"}, - "save_delay_ms": {"title": "保存延迟", "desc": "Token 变更合并写入的延迟(毫秒)。"}, - "usage_flush_interval_sec": {"title": "用量落库间隔", "desc": "用量类字段写入数据库的最小间隔(秒)。"}, - "reload_interval_sec": {"title": "同步间隔", "desc": "多 worker 场景下 Token 状态刷新间隔(秒)。"} - }, - "cache": { - "enable_auto_clean": {"title": "自动清理", "desc": "是否启用缓存自动清理,开启后按上限自动回收。"}, - "limit_mb": {"title": "清理阈值", "desc": "缓存大小阈值(MB),超过阈值会触发清理。"} - }, - "nsfw": { - "concurrent": {"title": "并发上限", "desc": "批量开启 NSFW 模式时的并发请求上限。推荐 10。"}, - "batch_size": {"title": "批次大小", "desc": "批量开启 NSFW 模式的单批处理数量。推荐 50。"}, - "timeout": {"title": "请求超时", "desc": "NSFW 开启相关请求的超时时间(秒)。推荐 60。"} - }, - "usage": { - "concurrent": {"title": "并发上限", "desc": "批量刷新用量时的并发请求上限。推荐 10。"}, - "batch_size": {"title": "批次大小", "desc": "批量刷新用量的单批处理数量。推荐 50。"}, - "timeout": {"title": "请求超时", "desc": "用量查询接口的超时时间(秒)。推荐 60。"} - } - } - }, - "token": { - "pageTitle": "Grok2API - Token 管理", - "title": "Token 列表", - "subtitle": "管理 Grok2API 的 Token 服务号池。", - "import": "导入", - "add": "添加", - "statTotal": "Token 总数", - "statActive": "Token 正常", - "statCooling": "Token 限流", - "statInvalid": "Token 失效", - "statChatQuota": "Chat 剩余", - "statImageQuota": "Image 剩余", - "statChatConsumed": "Chat 已消耗", - "statImageConsumed": "Image 已消耗", - "statVideoQuota": "Video 剩余", - "statVideoUnavailable": "无法统计", - "statTotalCalls": "总调用次数", - "tabAll": "全部", - "tabActive": "正常", - "tabCooling": "限流", - "tabExpired": "失效", - "tabNsfw": "已开 NSFW", - "tabNoNsfw": "未开 NSFW", - "statusFilterAria": "Token 状态筛选", - "tableToken": "Token", - "tableType": "类型", - "tableStatus": "状态", - "tableQuota": "额度", - "tableQuotaConsumed": "已消耗", - "tableNote": "备注", - "tableActions": "操作", - "refreshStatus": "刷新状态", - "emptyState": "暂无 Token,请点击右上角导入或添加。", - "emptyFilterState": "当前筛选无结果,请切换筛选条件。", - "selectPage": "全选本页", - "selectAllFiltered": "全选全部", - "clearSelection": "取消全选", - "prevPage": "上一页", - "nextPage": "下一页", - "perPage": "{size} / 页", - "pagination": "第 {current} / {total} 页 · 共 {count} 条", - "batchExport": "导出", - "batchRefresh": "刷新", - "batchDisable": "禁用", - "batchEnable": "启用", - "batchDelete": "删除", - "importTitle": "批量导入 Token", - "importTargetPool": "目标 Pool", - "importTokenList": "Token 列表 (每行一个)", - "importPlaceholder": "粘贴 Token,一行一个...", - "startImport": "开始导入", - "editTitle": "编辑 Token", - "addTitle": "添加 Token", - "editType": "类型", - "editQuota": "额度", - "editNote": "备注", - "editNotePlaceholder": "可选备注", - "tokenEmpty": "Token 不能为空", - "tokenExists": "Token 已存在", - "confirmDelete": "确定要删除此 Token 吗?", - "confirmDisable": "确定要禁用该 Token 吗?\n{token}", - "confirmEnable": "确定要启用该 Token 吗?\n{token}", - "confirmBatchDelete": "确定要删除选中的 {count} 个 Token 吗?", - "confirmBatchDisable": "确定要禁用选中的 {count} 个 Token 吗?", - "confirmBatchEnable": "确定要启用选中的 {count} 个 Token 吗?", - "disableToken": "禁用", - "enableToken": "启用", - "disableDone": "Token 已禁用", - "enableDone": "Token 已启用", - "batchDisableDone": "批量禁用完成", - "batchEnableDone": "批量启用完成", - "noTokenToDisable": "选中的 Token 已全部是禁用状态", - "noTokenToEnable": "选中的 Token 已全部是启用状态", - "deleteDone": "删除完成", - "refreshDone": "刷新完成", - "refreshSuccess": "刷新成功", - "refreshFailed": "刷新失败", - "refreshError": "刷新失败: {msg}", - "requestError": "请求错误", - "notValidJson": "响应不是有效 JSON (HTTP {status})", - "listEmpty": "列表为空", - "stopRefresh": "已终止刷新", - "stopDelete": "已终止删除", - "stopNsfw": "已终止 NSFW", - "nsfwConfirm": "是否为选中的 {count} 个 Token 开启 NSFW 模式?", - "nsfwEnable": "开启 NSFW", - "nsfwDone": "NSFW 开启完成", - "nsfwResult": "NSFW 开启完成:成功 {ok},失败 {fail}", - "nsfwFailed": "开启失败: {msg}", - "emptyResponse": "空响应 (HTTP {status})" - }, - "cache": { - "pageTitle": "Grok2API - 缓存管理", - "title": "缓存管理", - "subtitle": "管理本地资源与在线资产缓存。", - "localImages": "本地图片", - "localVideos": "本地视频", - "onlineAssets": "在线资产", - "tableFile": "文件", - "tableSize": "大小", - "tableTime": "时间", - "tableActions": "操作", - "tableToken": "Token", - "tableType": "类型", - "tableAssetCount": "资产数", - "tableLastClear": "上次清空时间", - "selectPage": "全选本页", - "selectAllFiles": "全选全部", - "clearSelection": "取消全选", - "prevPage": "上一页", - "nextPage": "下一页", - "perPageLabel": "每页", - "perPage": "{size} / 页", - "pagination": "第 {current} / {total} 页 · 共 {count} 条", - "notLoaded": "未加载", - "noAccounts": "暂无可用账号", - "noFiles": "暂无文件", - "noTokenAvailable": "无可用 Token", - "cannotConnect": "无法连接", - "lastClear": "上次清空:{time}", - "clear": "清空", - "clean": "清理", - "confirmClearImage": "确定要清空本地图片缓存吗?", - "confirmClearVideo": "确定要清空本地视频缓存吗?", - "clearSuccess": "清理成功,释放 {size} MB", - "clearFailed": "清理失败", - "confirmDeleteFile": "确定要删除该文件吗?", - "confirmBatchDeleteFiles": "确定要删除选中的 {count} 个文件吗?", - "noFilesSelected": "未选择文件", - "deletedFiles": "已删除 {count} 个文件", - "deleteResult": "删除完成:成功 {success},失败 {failed}", - "loadStatsFailed": "加载统计失败", - "selectAccountsToLoad": "请选择要加载的账号", - "selectAccountsToClear": "请选择要清空的账号", - "confirmClearAccounts": "确定要清空选中的 {count} 个账号在线资产吗?", - "confirmClearAccount": "确定要清空账号 {label} 的在线资产吗?", - "batchCleanInProgress": "正在批量清理在线资产,请稍候...", - "cleanInProgress": "正在清理在线资产,请稍候...", - "batchCleanDone": "批量清理完成", - "cleanResult": "清理完成 (成功: {success}, 失败: {failed})", - "cleanFailedEntry": "清理失败", - "requestTimeout": "请求超时或失败", - "loadDone": "加载完成", - "loadingStatus": "加载中", - "loadStopped": "已终止加载", - "loadFailedMsg": "加载失败: {msg}", - "stoppedLoadRequests": "已终止剩余加载请求", - "cleanStopped": "已终止清理", - "cleanFailedMsg": "清理失败: {msg}", - "stoppedCleanRequests": "已终止剩余清理请求" - }, - "chat": { - "pageTitle": "Grok2API - Chat 聊天", - "title": "Chat 聊天", - "subtitle": "通过 chat 接口与 Grok 进行会话聊天", - "sessions": "会话", - "newChat": "新增", - "collapseSidebar": "折叠", - "expandSidebar": "展开", - "sessionList": "会话列表", - "newSession": "新会话", - "ready": "就绪", - "emptyState": "输入一条消息开始对话。", - "uploadFile": "上传文件", - "placeholder": "询问任何内容", - "settings": "设置", - "send": "发送", - "temperature": "温度", - "topP": "Top P", - "systemPrompt": "System Prompt", - "systemPromptPlaceholder": "可选,设置系统提示词", - "fileLabel": "[文件]", - "compositeContent": "[复合内容]", - "storageFull": "本地存储空间不足,部分会话未保存", - "attachmentNoEdit": "附件消息暂不支持编辑", - "saveEdit": "保存", - "saveEditTitle": "保存编辑", - "cancelEdit": "取消", - "cancelEditTitle": "取消编辑", - "contentEmpty": "内容不能为空", - "editMessage": "编辑", - "editMessageTitle": "编辑消息内容", - "regenerate": "重新生成", - "regenerateTitle": "从此处重新生成回复", - "retryTitle": "重试上一条回答", - "editAnswer": "编辑", - "editAnswerTitle": "编辑回答内容", - "copyAnswer": "复制", - "copyAnswerTitle": "复制回答内容", - "feedback": "反馈", - "feedbackTitle": "反馈到 Grok2API", - "noContentToCopy": "暂无内容可复制", - "noChatToRetry": "没有可重试的对话", - "requestFailedCheck": "请求失败,请检查服务状态", - "requestFailedStatus": "请求失败: {status}", - "clickRetry": "点击重试", - "thinking": "思考中", - "thinkingSec": "思考 {sec} 秒", - "thought": "已思考", - "thinkLabel": "思考", - "empty": "(空)", - "toolWebSearch": "网页搜索", - "toolImageSearch": "图片搜索", - "toolAgentThink": "思考推理", - "toolDefault": "工具" - }, - "imagine": { - "pageTitle": "Grok2API - Imagine 瀑布流", - "title": "Imagine 瀑布流", - "subtitle": "通过 WebSocket 持续生成图片,实时展示 base64 瀑布流。", - "genSettings": "生成设置", - "prompt": "提示词", - "promptPlaceholder": "描述你想要的画面,例如:未来城市霓虹雨夜,广角摄影", - "autoFollow": "自动跟随", - "autoFollowDesc": "滚动到最新", - "autoSave": "自动保存", - "autoSaveDesc": "自动保存图片", - "aspectRatio": "宽高比", - "ratio2_3": "2:3 竖图", - "ratio1_1": "1:1 方图", - "ratio3_2": "3:2 横图", - "ratio16_9": "16:9 宽屏", - "ratio9_16": "9:16 竖屏", - "concurrent": "并发数量", - "tasks": "{n} 个任务", - "concurrentTask1": "1 个任务", - "concurrentTask2": "2 个任务", - "concurrentTask3": "3 个任务", - "autoFilter": "自动过滤", - "autoFilterDesc": "过滤不达标图片", - "nsfwLabel": "是否 NSFW", - "nsfwOn": "开启", - "nsfwOff": "关闭", - "saveLocation": "保存位置", - "browserDefault": "浏览器默认位置", - "reverseOrder": "反向新增", - "reverseOrderDesc": "最新显示在上方", - "connectionStatus": "连接状态", - "connectionMode": "连接模式", - "connectionModeAria": "连接模式", - "imageCount": "图片数量", - "activeTasks": "活跃任务", - "avgTime": "平均耗时", - "gallery": "瀑布流", - "waitingTitle": "等待连接中", - "waitingSubtitle": "启动任务后,生成的图片会自动汇聚到这里", - "start": "开始", - "batch": "批量", - "batchDownloadTitle": "批量下载", - "selectAll": "全选", - "deselectAll": "取消全选", - "download": "下载", - "startedTasks": "已启动 {count} 个并发任务", - "startedTasksSSE": "已启动 {count} 个并发任务 (SSE)", - "generatingSSE": "生成中 (SSE)", - "selectFolder": "已选择文件夹: {name}", - "selectFolderFailed": "选择文件夹失败", - "noImagesSelected": "请先选择要下载的图片", - "jszipFailed": "JSZip 库加载失败,请刷新页面重试", - "packing": "正在打包 {count} 张图片...", - "packingBtn": "打包中...", - "packingProgress": "打包中... ({done}/{total})", - "noImagesDownloaded": "没有成功获取任何图片", - "generatingZip": "生成压缩包...", - "packSuccess": "成功打包 {count} 张图片", - "packFailed": "打包失败,请重试" - }, - "video": { - "pageTitle": "Grok2API - Video 视频生成", - "title": "Video 视频生成", - "subtitle": "生成短视频,支持最多 7 张参考图、@图N 引用与多种预设风格。", - "startGenerate": "开始生成", - "genSettings": "生成设置", - "prompt": "提示词", - "promptPlaceholder": "例如:@图1街头霓虹雨夜,@图2人物回头微笑,慢镜头,胶片质感", - "promptTip": "多图参考可在提示词中使用 @图1 到 @图7,按参考图顺序对应。", - "referenceImage": "参考图", - "referenceImagePlaceholder": "每行一个 https://... 或 data:image/...,最多 7 张", - "aspectRatio": "画面比例", - "ratio3_2": "3:2 横构图", - "ratio2_3": "2:3 竖构图", - "ratio16_9": "16:9 宽屏", - "ratio9_16": "9:16 竖屏", - "ratio1_1": "1:1 方形", - "duration": "视频时长", - "seconds": "{n} 秒", - "resolution": "分辨率", - "stylePreset": "风格预设", - "upload": "上传", - "clearImage": "清除", - "runStatus": "运行状态", - "elapsedTime": "耗时 {sec}s", - "elapsedTimeNone": "耗时 -", - "metaRatio": "比例", - "metaDuration": "时长", - "metaResolution": "分辨率", - "metaPreset": "预设", - "videoPreview": "视频预览", - "clearPreview": "清空", - "waitingGenerate": "等待生成视频", - "videoTitle": "视频 {n}", - "open": "打开", - "generatingPlaceholder": "生成中…", - "superResolution": "超分辨率", - "superResolutionInProgress": "超分辨率中", - "alreadyGenerating": "已在生成中", - "referenceConflict": "参考图只能选择其一:URL/Base64 列表 或 本地上传", - "referenceLimit": "参考图最多支持 7 张", - "noReferenceSelected": "未选择参考图", - "downloadFailed": "下载失败,请检查视频链接是否可访问", - "sec6": "6 秒", - "sec10": "10 秒", - "sec15": "15 秒" - }, - "voice": { - "pageTitle": "Grok2API - LiveKit 陪聊", - "title": "LiveKit 陪聊", - "subtitle": "LiveKit 语音会话,连接 Grok Voice。", - "startSession": "开始会话", - "stopSession": "停止会话", - "connectionSettings": "连接设置", - "voiceLabel": "声音 (Voice)", - "personalityLabel": "个性 (Personality)", - "speedLabel": "语速", - "settingsHint": "提示:Voice / Personality 会在建立连接前发送到服务端。", - "sessionLog": "会话日志", - "clearLog": "清空", - "copyLog": "复制", - "sessionStatus": "会话状态", - "audioOutput": "音频输出", - "audioHint": "订阅到的音轨会自动插入此区域。", - "livekitSDKError": "错误: LiveKit SDK 未能正确加载,请刷新页面重试", - "livekitLoadFailed": "LiveKit SDK 加载失败", - "secureContextBrowser": "请使用最新版浏览器并允许麦克风权限", - "secureContextHTTPS": "请使用 HTTPS 或在本机 localhost 访问", - "secureContextError": "当前环境不支持麦克风权限,{hint}", - "connectingStatus": "正在连接", - "fetchingToken": "正在获取 Token...", - "fetchTokenFailed": "获取 Token 失败: {status}", - "fetchTokenSuccess": "获取 Token 成功", - "participantConnected": "参与者已连接: {identity}", - "participantDisconnected": "参与者已断开: {identity}", - "trackSubscribed": "订阅音轨: {kind}", - "disconnected": "已断开连接", - "connectedToServer": "已连接到 LiveKit 服务器", - "inCall": "通话中", - "openingMic": "正在开启麦克风...", - "voiceEnabled": "语音已开启", - "voiceConnected": "语音连接成功", - "errorPrefix": "错误: {msg}", - "logCopied": "日志已复制", - "copyLogFailed": "复制失败,请手动选择" - } -} diff --git a/app/assets/js/admin/cache.js b/app/assets/js/admin/cache.js deleted file mode 100644 index f4e37886..00000000 --- a/app/assets/js/admin/cache.js +++ /dev/null @@ -1,109 +0,0 @@ -/* Cache management — simplified, updated API paths */ -let apiKey = ''; -let currentTab = 'image'; -let listPage = 1; -const PAGE_SIZE = 100; -let listData = { image: { items: [], total: 0 }, video: { items: [], total: 0 } }; - -const byId = id => document.getElementById(id); - -async function init() { - apiKey = await ensureAdminKey(); - if (!apiKey) return; - setupConfirmDialog(); - loadStats(); -} - -async function loadStats() { - try { - const res = await fetch(`${API_BASE}/cache`, { headers: buildAuthHeaders(apiKey) }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const data = await res.json(); - byId('img-count').textContent = data.local_image?.count ?? '-'; - byId('img-size').textContent = data.local_image?.size_mb != null ? data.local_image.size_mb + ' MB' : '-'; - byId('video-count').textContent = data.local_video?.count ?? '-'; - byId('video-size').textContent = data.local_video?.size_mb != null ? data.local_video.size_mb + ' MB' : '-'; - } catch (e) { showToast(e.message, 'error'); } - loadList(); -} - -async function loadList() { - try { - const res = await fetch(`${API_BASE}/cache/list?type=${currentTab}&page=${listPage}&page_size=${PAGE_SIZE}`, { headers: buildAuthHeaders(apiKey) }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const data = await res.json(); - listData[currentTab] = { items: data.items || [], total: data.total || 0 }; - renderList(); - } catch (e) { showToast(e.message, 'error'); } -} - -function renderList() { - const { items, total } = listData[currentTab]; - const pages = Math.max(1, Math.ceil(total / PAGE_SIZE)); - const tbody = byId('file-list-body'); - const empty = byId('file-empty'); - const info = byId('list-info'); - const prev = byId('list-prev'); - const next = byId('list-next'); - - if (info) info.textContent = `${total === 0 ? 0 : listPage} / ${pages} · ${total}`; - if (prev) prev.disabled = listPage <= 1; - if (next) next.disabled = listPage >= pages; - - if (!items.length) { - tbody.replaceChildren(); - empty?.classList.remove('hidden'); - return; - } - empty?.classList.add('hidden'); - - const frag = document.createDocumentFragment(); - items.forEach(f => { - const tr = document.createElement('tr'); - const sizeKB = f.size_bytes ? (f.size_bytes / 1024).toFixed(1) + ' KB' : '-'; - tr.innerHTML = ` - <td class="font-mono text-xs truncate" style="max-width:400px" title="${escapeHtml(f.name)}">${escapeHtml(f.name)}</td> - <td class="text-right text-xs text-muted">${sizeKB}</td> - <td class="text-center"> - <button onclick="deleteFile('${escapeHtml(f.name)}')" class="btn-ghost" style="padding:2px;color:var(--error)" title="删除"> - <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> - </button> - </td>`; - frag.appendChild(tr); - }); - tbody.replaceChildren(frag); -} - -function switchTab(tab) { - currentTab = tab; listPage = 1; - document.querySelectorAll('.tab-item').forEach(b => b.classList.toggle('active', b.dataset.tab === tab)); - loadList(); -} -function listPrev() { if (listPage > 1) { listPage--; loadList(); } } -function listNext() { const pages = Math.max(1, Math.ceil((listData[currentTab]?.total||0) / PAGE_SIZE)); if (listPage < pages) { listPage++; loadList(); } } - -async function deleteFile(name) { - if (!await confirmAction(`删除文件 ${name}?`)) return; - try { - const res = await fetch(`${API_BASE}/cache/item/delete`, { - method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, - body: JSON.stringify({ type: currentTab, name }) - }); - if (res.ok) { showToast('已删除', 'success'); loadStats(); } - else showToast('删除失败', 'error'); - } catch (e) { showToast(e.message, 'error'); } -} - -async function clearLocalCache() { - if (!await confirmAction(`清理全部${currentTab === 'image' ? '图片' : '视频'}缓存?`)) return; - try { - const res = await fetch(`${API_BASE}/cache/clear`, { - method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, - body: JSON.stringify({ type: currentTab }) - }); - if (res.ok) { showToast('已清理', 'success'); loadStats(); } - else showToast('清理失败', 'error'); - } catch (e) { showToast(e.message, 'error'); } -} - -window.onload = init; diff --git a/app/assets/js/admin/config.js b/app/assets/js/admin/config.js deleted file mode 100644 index 7045b448..00000000 --- a/app/assets/js/admin/config.js +++ /dev/null @@ -1,257 +0,0 @@ -let apiKey = ''; -let currentConfig = {}; -const byId = id => document.getElementById(id); - -const NUMERIC_FIELDS = new Set([ - 'timeout','max_retry','retry_backoff_base','retry_backoff_factor','retry_backoff_max', - 'retry_budget','refresh.interval_hours','refresh.super_interval_hours','runtime.fail_threshold', - 'limit_mb','refresh.on_demand_min_interval_sec','refresh.on_demand_max_tokens', - 'upload_concurrent','upload_timeout','download_concurrent','download_timeout', - 'list_concurrent','list_timeout','list_batch_size','delete_concurrent','delete_timeout', - 'delete_batch_size','reload_interval_sec','stream_timeout','final_timeout', - 'blocked_grace_seconds','final_min_bytes','medium_min_bytes','blocked_parallel_attempts', - 'concurrent','batch_size','max_file_size_mb','max_files','request_slow_ms' -]); - -const LOCALE_MAP = { - app:{label:"应用设置",api_key:{title:"API 密钥",desc:"调用 Grok2API 服务的 Token。"},app_key:{title:"后台密码",desc:"登录管理后台的密码(必填)。"},function_enabled:{title:"启用功能玩法",desc:"是否启用功能玩法入口。"},function_key:{title:"Function 密码",desc:"功能玩法页面的访问密码。"},app_url:{title:"应用地址",desc:"服务外部访问 URL。"},image_format:{title:"图片格式",desc:"默认图片格式。"},video_format:{title:"视频格式",desc:"默认视频格式。"},temporary:{title:"临时对话",desc:"默认启用临时对话。"},disable_memory:{title:"禁用记忆",desc:"默认禁用 Grok 记忆。"},stream:{title:"流式响应",desc:"默认启用流式输出。"},thinking:{title:"思维链",desc:"默认启用思维链。"},dynamic_statsig:{title:"动态指纹",desc:"动态生成 Statsig 指纹。"},custom_instruction:{title:"自定义指令",desc:"透传为 customPersonality。"},filter_tags:{title:"过滤标签",desc:"自动过滤响应中的特殊标签。"}}, - proxy:{label:"代理配置",base_proxy_url:{title:"基础代理 URL",desc:"代理到 Grok 的基础地址。"},asset_proxy_url:{title:"资源代理 URL",desc:"代理到 Grok 的资源地址。"},skip_proxy_ssl_verify:{title:"跳过 SSL 校验",desc:"代理自签名证书时启用。"},enabled:{title:"Managed Clearance",desc:"通过 FlareSolverr 维护 CF clearance。"},flaresolverr_url:{title:"FlareSolverr 地址",desc:"Managed clearance provider 地址。"},refresh_interval:{title:"预热间隔(秒)",desc:"预热间隔,建议≥300。"},timeout:{title:"挑战超时(秒)",desc:"等待解决挑战的最大时间。"},cf_clearance:{title:"CF Clearance",desc:"手动配置的 clearance cookie。"},browser:{title:"浏览器指纹",desc:"curl_cffi 浏览器指纹。"},user_agent:{title:"User-Agent",desc:"HTTP User-Agent。"}}, - retry:{label:"重试策略",max_retry:{title:"最大重试",desc:"最大重试次数。"},retry_status_codes:{title:"重试状态码",desc:"触发重试的 HTTP 状态码。"},reset_session_status_codes:{title:"重建状态码",desc:"触发重建 session 的状态码。"},retry_backoff_base:{title:"退避基数",desc:"基础延迟(秒)。"},retry_backoff_factor:{title:"退避倍率",desc:"指数放大系数。"},retry_backoff_max:{title:"退避上限",desc:"单次最大延迟(秒)。"},retry_budget:{title:"退避预算",desc:"最大重试总耗时(秒)。"}}, - chat:{label:"对话配置",concurrent:{title:"并发上限",desc:"Reverse 并发上限。"},timeout:{title:"请求超时",desc:"超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"}}, - video:{label:"视频配置",enable_public_asset:{title:"公开资产链接",desc:"生成后创建 Public 资产。"},concurrent:{title:"并发上限",desc:"并发上限。"},timeout:{title:"请求超时",desc:"超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"},upscale_timing:{title:"超分时机",desc:"720p 超分模式。"}}, - image:{label:"图像配置",timeout:{title:"请求超时",desc:"WebSocket 超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"},final_timeout:{title:"最终图超时",desc:"等待最终图的超时。"},blocked_grace_seconds:{title:"审查宽限",desc:"判定审查的宽限秒数。"},nsfw:{title:"NSFW 模式",desc:"启用 NSFW。"},medium_min_bytes:{title:"中等图最小字节",desc:"中等图最小字节数。"},final_min_bytes:{title:"最终图最小字节",desc:"最终图最小字节数。"},blocked_parallel_enabled:{title:"并行补偿",desc:"审查时并行补偿。"},blocked_parallel_attempts:{title:"补偿次数",desc:"补偿并发次数。"}}, - imagine_fast:{label:"Imagine Fast",n:{title:"生成数量",desc:"生成数量。"},size:{title:"图片尺寸",desc:"尺寸。"},response_format:{title:"响应格式",desc:"返回格式。"}}, - asset:{label:"资产配置",upload_concurrent:{title:"上传并发",desc:"上传最大并发。"},upload_timeout:{title:"上传超时",desc:"超时(秒)。"},download_concurrent:{title:"下载并发",desc:"下载最大并发。"},download_timeout:{title:"下载超时",desc:"超时(秒)。"},list_concurrent:{title:"查询并发",desc:"查询最大并发。"},list_timeout:{title:"查询超时",desc:"超时(秒)。"},list_batch_size:{title:"查询批次",desc:"单次批次大小。"},delete_concurrent:{title:"删除并发",desc:"删除最大并发。"},delete_timeout:{title:"删除超时",desc:"超时(秒)。"},delete_batch_size:{title:"删除批次",desc:"单次批次大小。"}}, - voice:{label:"语音配置",timeout:{title:"请求超时",desc:"超时(秒)。"}}, - account:{label:"Account 配置","runtime.consumed_mode_enabled":{title:"消耗模式",desc:"按 consumed 选号。"},"runtime.fail_threshold":{title:"失败阈值",desc:"连续失败阈值。"},"refresh.enabled":{title:"刷新调度",desc:"启用周期 refresh。"},"refresh.interval_hours":{title:"普通池间隔",desc:"普通池刷新间隔(小时)。"},"refresh.super_interval_hours":{title:"Super 池间隔",desc:"Super 池间隔(小时)。"},"refresh.on_demand_enabled":{title:"按需刷新",desc:"允许按需 refresh。"},"refresh.on_demand_min_interval_sec":{title:"按需最小间隔",desc:"最小间隔(秒)。"},"refresh.on_demand_max_tokens":{title:"按需最大数量",desc:"最多检查账号数。"}}, - log:{label:"日志配置",max_file_size_mb:{title:"单文件上限",desc:"上限(MB)。"},max_files:{title:"保留数",desc:"最多保留日志文件数。"},log_health_requests:{title:"记录健康检查",desc:"记录 /health。"},log_all_requests:{title:"记录全部请求",desc:"全部请求日志。"},request_slow_ms:{title:"慢请求阈值",desc:"阈值(毫秒)。"}}, - cache:{label:"缓存管理",enable_auto_clean:{title:"自动清理",desc:"自动清理缓存。"},limit_mb:{title:"清理阈值",desc:"阈值(MB)。"}}, - nsfw:{label:"NSFW 配置",concurrent:{title:"并发上限",desc:"并发上限。"},batch_size:{title:"批次大小",desc:"批次大小。"},timeout:{title:"请求超时",desc:"超时(秒)。"}}, - usage:{label:"Usage 配置",concurrent:{title:"并发上限",desc:"并发上限。"},batch_size:{title:"批次大小",desc:"批次大小。"},timeout:{title:"请求超时",desc:"超时(秒)。"}} -}; - -const SECTION_ORDER = new Map(Object.keys(LOCALE_MAP).map((k,i) => [k,i])); -const MANAGED_LOCKED = ['cf_clearance','browser','user_agent']; -const MANAGED_PROVIDER = ['flaresolverr_url','refresh_interval','timeout']; - -function getText(s, k) { - let ti = t('config.fields.'+s+'.'+k+'.title'); - let de = t('config.fields.'+s+'.'+k+'.desc'); - if (!ti.startsWith('config.fields.')) return {title:ti, desc: de.startsWith('config.fields.') ? '' : de}; - const m = LOCALE_MAP[s]; return m?.[k] || {title: k.replace(/_/g,' '), desc:''}; -} -function getSectionLabel(s) { - let l = t('config.sections.'+s); - return l.startsWith('config.sections.') ? (LOCALE_MAP[s]?.label || s) : l; -} -function sortByOrder(keys, order) { - if (!order) return keys; - return keys.sort((a,b) => { - const ia = order.get(a), ib = order.get(b); - if (ia !== undefined && ib !== undefined) return ia - ib; - if (ia !== undefined) return -1; - if (ib !== undefined) return 1; - return 0; - }); -} - -function setMeta(input, section, key) { input.dataset.section = section; input.dataset.key = key; } - -function buildBool(s, k, val) { - const label = document.createElement('label'); - label.className = 'toggle'; - const input = document.createElement('input'); - input.type = 'checkbox'; input.checked = val; input.className = 'sr-only'; - setMeta(input, s, k); - const track = document.createElement('div'); - track.className = 'toggle-track'; - label.append(input, track); - return {input, node: label}; -} - -function buildSelect(s, k, val, opts) { - const input = document.createElement('select'); - input.className = 'input'; setMeta(input, s, k); - opts.forEach(o => { - const opt = document.createElement('option'); - opt.value = o.val; opt.text = o.text; - if (val === o.val) opt.selected = true; - input.appendChild(opt); - }); - return {input, node: input}; -} - -function buildJson(s, k, val) { - const input = document.createElement('textarea'); - input.className = 'input font-mono'; input.rows = 4; - input.value = JSON.stringify(val, null, 2); - setMeta(input, s, k); input.dataset.type = 'json'; - return {input, node: input}; -} - -function buildText(s, k, val) { - const input = document.createElement('input'); - input.type = 'text'; input.className = 'input'; input.value = val; - setMeta(input, s, k); - return {input, node: input}; -} - -function buildTextarea(s, k, val, rows=5) { - const input = document.createElement('textarea'); - input.className = 'input'; input.rows = rows; input.value = val||''; - setMeta(input, s, k); - return {input, node: input}; -} - -function randomKey(len) { - const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - const buf = new Uint8Array(len); - crypto.getRandomValues(buf); - return Array.from(buf, b => chars[b % chars.length]).join(''); -} - -function buildSecret(s, k, val) { - const input = document.createElement('input'); - input.type = 'text'; input.className = 'input'; input.value = val; input.style.flex = '1'; - setMeta(input, s, k); - const wrap = document.createElement('div'); - wrap.className = 'flex gap-2'; - const genBtn = document.createElement('button'); - genBtn.className = 'btn btn-primary btn-icon'; genBtn.type = 'button'; genBtn.title = '生成'; - genBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7"/><polyline points="21 3 21 9 15 9"/></svg>'; - genBtn.onclick = () => { input.value = randomKey(16); }; - const copyBtn = document.createElement('button'); - copyBtn.className = 'btn btn-primary btn-icon'; copyBtn.type = 'button'; - copyBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>'; - copyBtn.onclick = () => copyToClipboard(input.value, copyBtn); - wrap.append(input, genBtn, copyBtn); - return {input, node: wrap}; -} - -function buildFieldCard(section, key, val) { - const text = getText(section, key); - const card = document.createElement('div'); - card.className = 'config-field'; - const title = document.createElement('div'); - title.className = 'config-field-title'; title.textContent = text.title; - card.appendChild(title); - if (text.desc) { - const desc = document.createElement('p'); - desc.className = 'config-field-desc'; desc.textContent = text.desc; - card.appendChild(desc); - } - const inputWrap = document.createElement('div'); - inputWrap.className = 'config-field-input'; - - let built; - if (section === 'app' && key === 'custom_instruction') built = buildTextarea(section, key, val, 6); - else if (typeof val === 'boolean') built = buildBool(section, key, val); - else if (key === 'image_format') built = buildSelect(section, key, val, [{val:'url',text:'URL'},{val:'base64',text:'Base64'}]); - else if (key === 'video_format') built = buildSelect(section, key, val, [{val:'html',text:'HTML'},{val:'url',text:'URL'}]); - else if (section==='video' && key==='upscale_timing') built = buildSelect(section, key, val, [{val:'single',text:'single'},{val:'complete',text:'complete'}]); - else if (section==='imagine_fast' && key==='size') built = buildSelect(section, key, val, [{val:'1024x1024',text:'1024x1024'},{val:'1280x720',text:'1280x720'},{val:'720x1280',text:'720x1280'},{val:'1792x1024',text:'1792x1024'},{val:'1024x1792',text:'1024x1792'}]); - else if (section==='imagine_fast' && key==='response_format') built = buildSelect(section, key, val, [{val:'url',text:'URL'},{val:'b64_json',text:'B64 JSON'},{val:'base64',text:'Base64'}]); - else if (Array.isArray(val) || typeof val === 'object') built = buildJson(section, key, val); - else if (['api_key','app_key','function_key'].includes(key)) built = buildSecret(section, key, val); - else built = buildText(section, key, val); - - if (built) inputWrap.appendChild(built.node); - card.appendChild(inputWrap); - - if (section==='proxy' && key==='enabled' && built) { - built.input.addEventListener('change', () => applyManagedState(built.input.checked)); - } - if (section==='app' && key==='function_enabled') { - card.classList.add('has-action'); - const link = document.createElement('a'); - link.href = '/login'; link.className = 'btn btn-primary btn-icon'; link.title = '访问'; - link.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17L17 7"/><path d="M7 7h10v10"/></svg>'; - link.style.display = val ? 'inline-flex' : 'none'; - card.appendChild(link); - if (built) built.input.addEventListener('change', () => { link.style.display = built.input.checked ? 'inline-flex' : 'none'; }); - } - return card; -} - -function applyManagedState(enabled) { - function setDisabled(k, disabled) { - const el = document.querySelector(`[data-section="proxy"][data-key="${k}"]`); - if (!el) return; - el.disabled = disabled; - const field = el.closest('.config-field'); - if (field) { field.style.opacity = disabled ? '.45' : ''; field.style.pointerEvents = disabled ? 'none' : ''; } - } - MANAGED_LOCKED.forEach(k => setDisabled(k, !!enabled)); - MANAGED_PROVIDER.forEach(k => setDisabled(k, !enabled)); -} - -function renderConfig(data) { - const container = byId('config-container'); - if (!container) return; - container.replaceChildren(); - const frag = document.createDocumentFragment(); - sortByOrder(Object.keys(data), SECTION_ORDER).forEach(section => { - const items = data[section]; - const localeSection = LOCALE_MAP[section]; - const keyOrder = localeSection ? new Map(Object.keys(localeSection).map((k,i) => [k,i])) : null; - const keys = sortByOrder(Object.keys(items), keyOrder).filter(k => !(section==='proxy' && k==='cf_cookies')); - if (!keys.length) return; - const card = document.createElement('div'); - card.className = 'config-section'; - card.innerHTML = `<div class="config-section-title">${getSectionLabel(section)}</div>`; - const grid = document.createElement('div'); - grid.className = 'config-grid'; - keys.forEach(k => grid.appendChild(buildFieldCard(section, k, items[k]))); - card.appendChild(grid); - frag.appendChild(card); - }); - container.appendChild(frag); - applyManagedState(data.proxy?.enabled); -} - -async function init() { - apiKey = await ensureAdminKey(); - if (!apiKey) return; - loadData(); -} - -async function loadData() { - try { - const res = await fetch(`${API_BASE}/config`, { headers: buildAuthHeaders(apiKey) }); - if (res.ok) { currentConfig = await res.json(); renderConfig(currentConfig); } - else if (res.status === 401) logout(); - } catch { showToast(t('common.connectionFailed'), 'error'); } -} - -async function saveConfig() { - const btn = byId('save-btn'); - const orig = btn.innerText; - btn.disabled = true; btn.innerText = t('config.saving') || '保存中...'; - try { - const cfg = structuredClone ? structuredClone(currentConfig) : JSON.parse(JSON.stringify(currentConfig)); - document.querySelectorAll('[data-section][data-key]').forEach(input => { - const s = input.dataset.section, k = input.dataset.key; - let val = input.value; - if (input.type === 'checkbox') val = input.checked; - else if (input.dataset.type === 'json') { try { val = JSON.parse(val); } catch { throw new Error(`Invalid JSON: ${getText(s,k).title}`); } } - else if (k === 'app_key' && !val.trim()) throw new Error('app_key 不能为空'); - else if (NUMERIC_FIELDS.has(k) && val.trim() !== '' && !isNaN(Number(val))) val = Number(val); - if (!cfg[s]) cfg[s] = {}; - cfg[s][k] = val; - }); - if (cfg.proxy?.enabled && !String(cfg.proxy.flaresolverr_url||'').trim()) { - showToast('启用 Managed Clearance 时需配置 FlareSolverr 地址', 'error'); - btn.disabled = false; btn.innerText = orig; return; - } - const res = await fetch(`${API_BASE}/config`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, - body: JSON.stringify(cfg) - }); - if (res.ok) { showToast(t('config.configSaved') || '配置已保存', 'success'); } - else { showToast(t('common.saveFailed') || '保存失败', 'error'); } - } catch (e) { showToast(e.message, 'error'); } - finally { btn.disabled = false; btn.innerText = orig; } -} - -window.onload = init; diff --git a/app/assets/js/admin/login.js b/app/assets/js/admin/login.js deleted file mode 100644 index a9d169c1..00000000 --- a/app/assets/js/admin/login.js +++ /dev/null @@ -1,21 +0,0 @@ -const input = document.getElementById('api-key-input'); -if (input) input.addEventListener('keypress', e => { if (e.key === 'Enter') login(); }); - -async function login() { - const key = (input ? input.value : '').trim(); - if (!key) return; - try { - if (await verifyKey(`${API_BASE}/verify`, key)) { - await storeAppKey(key); - window.location.href = '/admin/token'; - } else { - showToast(t('common.invalidKey'), 'error'); - } - } catch { showToast(t('common.connectionFailed'), 'error'); } -} - -(async () => { - const key = await getStoredAppKey(); - if (!key) return; - try { if (await verifyKey(`${API_BASE}/verify`, key)) window.location.href = '/admin/token'; } catch {} -})(); diff --git a/app/assets/js/admin/token.js b/app/assets/js/admin/token.js deleted file mode 100644 index 6b3338c6..00000000 --- a/app/assets/js/admin/token.js +++ /dev/null @@ -1,380 +0,0 @@ -/* Token management — full rewrite with updated API paths */ -let apiKey = ''; -let consumedModeEnabled = false; -let allTokens = {}; -let flatTokens = []; -let isBatchProcessing = false; -let currentBatchAction = null; -let currentBatchTaskId = null; -let batchEventSource = null; -let batchTotal = 0; -let batchProcessed = 0; -let currentFilter = 'all'; -let currentPage = 1; -let pageSize = 50; - -const byId = id => document.getElementById(id); -const DEFAULT_QUOTA = { ssoBasic: 80, ssoSuper: 140 }; - -function setText(id, text) { const el = byId(id); if (el) el.innerText = text; } - -function getSelectedTokens() { return flatTokens.filter(t => t._selected); } -function countSelected(tokens) { return tokens.filter(t => t._selected).length; } -function setSelectedForTokens(tokens, sel) { tokens.forEach(t => t._selected = sel); } - -function syncVisibleSelectionUI(sel) { - document.querySelectorAll('#token-table-body input[type="checkbox"]').forEach(i => i.checked = sel); - document.querySelectorAll('#token-table-body tr').forEach(r => r.classList.toggle('row-selected', sel)); -} - -function getFilteredTokens() { - if (currentFilter === 'all') return flatTokens; - return flatTokens.filter(t => { - if (currentFilter === 'active') return t.status === 'active'; - if (currentFilter === 'cooling') return t.status === 'cooling'; - if (currentFilter === 'expired') return t.status !== 'active' && t.status !== 'cooling'; - if (currentFilter === 'nsfw') return t.tags?.includes('nsfw'); - if (currentFilter === 'no-nsfw') return !t.tags?.includes('nsfw'); - return true; - }); -} - -function getPaginationData() { - const filtered = getFilteredTokens(); - const total = filtered.length; - const pages = Math.max(1, Math.ceil(total / pageSize)); - if (currentPage > pages) currentPage = pages; - const start = (currentPage - 1) * pageSize; - return { filtered, total, pages, visible: filtered.slice(start, start + pageSize) }; -} - -function getVisibleTokens() { return getPaginationData().visible; } - -async function init() { - apiKey = await ensureAdminKey(); - if (!apiKey) return; - setupConfirmDialog(); - setupSelectAllMenu(); - makeDraggable(byId('batch-actions')); - const poolSel = byId('edit-pool'); - const quotaIn = byId('edit-quota'); - if (poolSel && quotaIn) poolSel.addEventListener('change', () => { if (currentEditIndex < 0) quotaIn.value = DEFAULT_QUOTA[poolSel.value] || 80; }); - loadData(); -} - -async function loadData() { - try { - const res = await fetch(`${API_BASE}/tokens`, { headers: buildAuthHeaders(apiKey) }); - if (res.ok) { - const data = await res.json(); - allTokens = data.tokens; - consumedModeEnabled = data.consumed_mode_enabled || false; - processTokens(data.tokens); - updateStats(); - renderTable(); - } else if (res.status === 401) logout(); - else throw new Error(`HTTP ${res.status}`); - } catch (e) { showToast(e.message, 'error'); } -} - -function processTokens(data) { - flatTokens = []; - Object.entries(data).forEach(([pool, tokens]) => { - if (!Array.isArray(tokens)) return; - tokens.forEach(t => { - const o = typeof t === 'string' ? { token: t, status: 'active', quota: 0, tags: [] } : { ...t }; - flatTokens.push({ ...o, pool, _selected: false }); - }); - }); -} - -function updateStats() { - let total = flatTokens.length, active = 0, cooling = 0, invalid = 0, nsfw = 0, noNsfw = 0, quota = 0, calls = 0; - flatTokens.forEach(t => { - if (t.status === 'active') { active++; quota += (t.quota || 0); } - else if (t.status === 'cooling') cooling++; - else invalid++; - t.tags?.includes('nsfw') ? nsfw++ : noNsfw++; - calls += (t.use_count || 0); - }); - setText('stat-total', total.toLocaleString()); - setText('stat-active', active.toLocaleString()); - setText('stat-cooling', cooling.toLocaleString()); - setText('stat-invalid', invalid.toLocaleString()); - setText('stat-chat-quota', (consumedModeEnabled ? flatTokens.reduce((s,t) => s+(t.consumed||0), 0) : quota).toLocaleString()); - setText('stat-image-quota', Math.floor((consumedModeEnabled ? flatTokens.reduce((s,t) => s+(t.consumed||0), 0) : quota) / 2).toLocaleString()); - setText('stat-total-calls', calls.toLocaleString()); - const counts = { all: total, active, cooling, expired: invalid, nsfw, 'no-nsfw': noNsfw }; - Object.entries(counts).forEach(([k, v]) => { const el = byId(`tab-count-${k}`); if (el) el.textContent = v; }); -} - -function renderTable() { - const tbody = byId('token-table-body'); - const loading = byId('loading'); - const empty = byId('empty-state'); - if (loading) loading.classList.add('hidden'); - const { total, pages, visible } = getPaginationData(); - updatePagination(total, pages); - if (!visible.length) { - tbody.replaceChildren(); - if (empty) { empty.textContent = currentFilter === 'all' ? t('token.emptyState') : t('token.emptyFilterState'); empty.classList.remove('hidden'); } - updateSelectionState(); return; - } - if (empty) empty.classList.add('hidden'); - const idxMap = new Map(flatTokens.map((t, i) => [t, i])); - const frag = document.createDocumentFragment(); - visible.forEach(item => { - const idx = idxMap.get(item); - const tr = document.createElement('tr'); - tr.dataset.index = idx; - if (item._selected) tr.classList.add('row-selected'); - const short = item.token.length > 24 ? item.token.slice(0,8) + '...' + item.token.slice(-16) : item.token; - const statusClass = item.status === 'active' ? 'badge-green' : item.status === 'cooling' ? 'badge-orange' : item.status === 'expired' ? 'badge-red' : ''; - const nsfwBadge = item.tags?.includes('nsfw') ? ' <span class="badge badge-purple">nsfw</span>' : ''; - tr.innerHTML = ` - <td class="text-center"><input type="checkbox" class="checkbox" ${item._selected?'checked':''} onchange="toggleSelect(${idx})"></td> - <td><div class="flex items-center gap-2"><span class="font-mono text-xs text-muted" title="${escapeHtml(item.token)}">${escapeHtml(short)}</span><button class="btn-ghost" style="padding:2px" onclick="copyToClipboard('${escapeHtml(item.token)}',this)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button></div></td> - <td class="text-center"><span class="badge">${escapeHtml(item.pool)}</span></td> - <td class="text-center"><span class="badge ${statusClass}">${item.status}</span>${nsfwBadge}</td> - <td class="text-center font-mono text-xs">${consumedModeEnabled ? (item.consumed||0) : (item.quota||0)}</td> - <td class="text-xs text-muted truncate" style="max-width:150px">${escapeHtml(item.note||'-')}</td> - <td class="text-center"><div class="flex items-center justify-center gap-2"> - <button onclick="refreshStatus('${escapeHtml(item.token)}')" class="btn-ghost" style="padding:2px" title="${t('token.refreshStatus')}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></button> - <button onclick="openEditModal(${idx})" class="btn-ghost" style="padding:2px" title="${t('common.edit')}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button> - <button onclick="deleteToken(${idx})" class="btn-ghost" style="padding:2px;color:var(--error)" title="${t('common.delete')}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button> - </div></td>`; - frag.appendChild(tr); - }); - tbody.replaceChildren(frag); - updateSelectionState(); -} - -/* Selection */ -function toggleSelectAll() { const cb = byId('select-all'); setSelectedForTokens(getVisibleTokens(), cb?.checked); syncVisibleSelectionUI(cb?.checked); updateSelectionState(); } -function toggleSelect(idx) { flatTokens[idx]._selected = !flatTokens[idx]._selected; const r = document.querySelector(`#token-table-body tr[data-index="${idx}"]`); if (r) r.classList.toggle('row-selected', flatTokens[idx]._selected); updateSelectionState(); } - -function setupSelectAllMenu() { - document.addEventListener('click', e => { if (!byId('select-all-wrap')?.contains(e.target)) byId('select-all-popover')?.classList.add('hidden'); }); - document.addEventListener('keydown', e => { if (e.key === 'Escape') byId('select-all-popover')?.classList.add('hidden'); }); -} - -function handleSelectAllPrimary(e) { - e?.stopPropagation(); - if (countSelected(flatTokens) > 0) { clearAllSelection(); return; } - const p = byId('select-all-popover'); - p?.classList.toggle('hidden'); -} -function selectVisibleAllFromMenu() { setSelectedForTokens(getVisibleTokens(), true); syncVisibleSelectionUI(true); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); } -function selectAllFilteredFromMenu() { setSelectedForTokens(getFilteredTokens(), true); syncVisibleSelectionUI(true); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); } -function clearAllSelection() { setSelectedForTokens(flatTokens, false); syncVisibleSelectionUI(false); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); } - -function updateSelectionState() { - const sel = countSelected(flatTokens); - const vis = getVisibleTokens(); - const visSel = countSelected(vis); - const cb = byId('select-all'); - if (cb) { cb.checked = vis.length > 0 && visSel === vis.length; cb.indeterminate = visSel > 0 && visSel < vis.length; } - const label = byId('select-all-label'); - if (label) label.textContent = sel > 0 ? t('token.clearSelection') : t('common.selectAll'); - const trigger = byId('select-all-trigger'); - if (trigger) trigger.classList.toggle('is-active', sel > 0); - const caret = byId('select-all-caret'); - if (caret) caret.style.display = sel > 0 ? 'none' : 'inline'; - const countEl = byId('selected-count'); - if (countEl) countEl.textContent = sel; - if (sel > 0) byId('select-all-popover')?.classList.add('hidden'); - setActionButtons(sel); -} - -function setActionButtons(count = null) { - const c = count ?? countSelected(flatTokens); - const dis = isBatchProcessing; - ['btn-batch-export','btn-batch-update','btn-batch-disable','btn-batch-enable','btn-batch-nsfw','btn-batch-delete'].forEach(id => { - const b = byId(id); if (b) b.disabled = dis || c === 0; - }); -} - -/* Filtering & Pagination */ -function filterByStatus(status) { - currentFilter = status; currentPage = 1; - document.querySelectorAll('.tab-item').forEach(t => { t.classList.toggle('active', t.dataset.filter === status); }); - renderTable(); -} - -function updatePagination(total, pages) { - const info = byId('pagination-info'); - if (info) info.textContent = `${total === 0 ? 0 : currentPage} / ${pages} · ${total}`; - const prev = byId('page-prev'); if (prev) prev.disabled = currentPage <= 1; - const next = byId('page-next'); if (next) next.disabled = currentPage >= pages; -} -function goPrevPage() { if (currentPage > 1) { currentPage--; renderTable(); } } -function goNextPage() { const p = getPaginationData().pages; if (currentPage < p) { currentPage++; renderTable(); } } -function changePageSize() { const v = parseInt(byId('page-size')?.value); if (v) { pageSize = v; currentPage = 1; renderTable(); } } - -/* CRUD */ -let currentEditIndex = -1; -function addToken() { openEditModal(-1); } - -function openEditModal(idx) { - currentEditIndex = idx; - const isNew = idx < 0; - if (isNew) { - byId('edit-token-display').value = ''; byId('edit-token-display').disabled = false; - byId('edit-pool').value = 'ssoBasic'; byId('edit-quota').value = 80; byId('edit-note').value = ''; - document.querySelector('#edit-modal .modal-title').textContent = t('token.addTitle'); - } else { - const item = flatTokens[idx]; - byId('edit-token-display').value = item.token; byId('edit-token-display').disabled = true; - byId('edit-pool').value = item.pool; - byId('edit-quota').value = consumedModeEnabled ? (item.consumed||0) : item.quota; - byId('edit-note').value = item.note || ''; - document.querySelector('#edit-modal .modal-title').textContent = t('token.editTitle'); - } - openModal('edit-modal'); -} -function closeEditModal() { closeModal('edit-modal'); } - -async function saveEdit() { - const pool = byId('edit-pool').value.trim() || 'ssoBasic'; - const quota = parseInt(byId('edit-quota').value) || 0; - const note = byId('edit-note').value.trim().slice(0, 50); - if (currentEditIndex >= 0) { - const item = flatTokens[currentEditIndex]; - item.pool = pool; if (!consumedModeEnabled) item.quota = quota; item.note = note; - } else { - const token = byId('edit-token-display').value.trim(); - if (!token) return showToast(t('token.tokenEmpty'), 'error'); - if (flatTokens.some(t => t.token === token)) return showToast(t('token.tokenExists'), 'error'); - flatTokens.push({ token, pool, quota, consumed: 0, note, status: 'active', use_count: 0, tags: [], _selected: false }); - } - await syncToServer(); closeEditModal(); loadData(); -} - -async function deleteToken(idx) { - if (!await confirmAction(t('token.confirmDelete'), { okText: t('common.delete') })) return; - flatTokens.splice(idx, 1); - syncToServer().then(loadData); -} - -async function syncToServer() { - const data = {}; - flatTokens.forEach(t => { - if (!data[t.pool]) data[t.pool] = []; - const p = { token: t.token, status: t.status, quota: t.quota, consumed: t.consumed||0, note: t.note||'', fail_count: t.fail_count||0, use_count: t.use_count||0, tags: t.tags||[] }; - if (t.created_at) p.created_at = t.created_at; - if (t.last_used_at) p.last_used_at = t.last_used_at; - if (t.last_fail_at) p.last_fail_at = t.last_fail_at; - if (t.last_sync_at) p.last_sync_at = t.last_sync_at; - if (t.last_asset_clear_at) p.last_asset_clear_at = t.last_asset_clear_at; - if (t.last_fail_reason) p.last_fail_reason = t.last_fail_reason; - data[t.pool].push(p); - }); - try { - const res = await fetch(`${API_BASE}/tokens`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify(data) }); - if (!res.ok) showToast(t('common.saveFailed'), 'error'); - } catch (e) { showToast(e.message, 'error'); } -} - -/* Import/Export */ -function openImportModal() { openModal('import-modal'); } -function closeImportModal() { closeModal('import-modal', () => { const i = byId('import-text'); if (i) i.value = ''; }); } -async function submitImport() { - const pool = byId('import-pool').value.trim() || 'ssoBasic'; - const lines = byId('import-text').value.split('\n'); - lines.forEach(l => { const t = l.trim(); if (t && !flatTokens.some(ft => ft.token === t)) flatTokens.push({ token: t, pool, status: 'active', quota: DEFAULT_QUOTA[pool]||80, consumed: 0, note: '', tags: [], fail_count: 0, use_count: 0, _selected: false }); }); - await syncToServer(); closeImportModal(); loadData(); -} -function batchExport() { - const sel = getSelectedTokens(); - if (!sel.length) return showToast(t('common.noTokenSelected'), 'error'); - downloadTextFile(sel.map(t => t.token).join('\n')+'\n', `tokens_${new Date().toISOString().slice(0,10)}.txt`); -} - -/* Batch ops */ -async function refreshStatus(token) { - try { - const res = await fetch(`${API_BASE}/tokens/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify({ tokens: [token] }) }); - if (res.ok) { showToast(t('token.refreshSuccess'), 'success'); loadData(); } - else showToast(t('token.refreshFailed'), 'error'); - } catch { showToast(t('token.requestError'), 'error'); } -} - -async function batchUpdate() { await startBatchAsync('refresh', `${API_BASE}/tokens/refresh/async`); } -async function batchEnableNSFW() { - const sel = getSelectedTokens(); - if (!sel.length) return showToast(t('common.noTokenSelected'), 'error'); - if (!await confirmAction(t('token.nsfwConfirm', { count: sel.length }), { okText: t('token.nsfwEnable') })) return; - await startBatchAsync('nsfw', `${API_BASE}/tokens/nsfw/enable/async`); -} - -async function startBatchAsync(action, url) { - if (isBatchProcessing) return showToast(t('common.taskInProgress'), 'info'); - const sel = getSelectedTokens(); - if (!sel.length) return showToast(t('common.noTokenSelected'), 'error'); - isBatchProcessing = true; currentBatchAction = action; - batchTotal = sel.length; batchProcessed = 0; - updateBatchProgress(); setActionButtons(); - try { - const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify({ tokens: sel.map(t => t.token) }) }); - const data = await res.json(); - if (!res.ok || data.status !== 'success') throw new Error(data.detail || 'Failed'); - currentBatchTaskId = data.task_id; - BatchSSE.close(batchEventSource); - batchEventSource = BatchSSE.open(currentBatchTaskId, apiKey, { - onMessage: msg => { - if (msg.type === 'progress' || msg.type === 'snapshot') { - if (msg.total) batchTotal = msg.total; - if (msg.processed != null) batchProcessed = msg.processed; - updateBatchProgress(); - } else if (msg.type === 'done') { - batchProcessed = batchTotal; updateBatchProgress(); - finishBatch(false); showToast(action === 'nsfw' ? t('token.nsfwDone') : t('token.refreshDone'), 'success'); - closeBatchSSE(); - } else if (msg.type === 'cancelled') { - finishBatch(true); showToast(t('common.cancelled'), 'info'); closeBatchSSE(); - } else if (msg.type === 'error') { - finishBatch(true); showToast(msg.error || t('common.unknownError'), 'error'); closeBatchSSE(); - } - }, - onError: () => { finishBatch(true); showToast(t('common.connectionInterrupted'), 'error'); closeBatchSSE(); } - }); - } catch (e) { finishBatch(true); showToast(e.message, 'error'); } -} - -function closeBatchSSE() { currentBatchTaskId = null; BatchSSE.close(batchEventSource); batchEventSource = null; } -function stopBatchRefresh() { if (currentBatchTaskId) { BatchSSE.cancel(currentBatchTaskId, apiKey); closeBatchSSE(); } finishBatch(true); } -function finishBatch(aborted) { isBatchProcessing = false; currentBatchAction = null; updateBatchProgress(); setActionButtons(); updateSelectionState(); loadData(); } - -function updateBatchProgress() { - const c = byId('batch-progress'), txt = byId('batch-progress-text'), stop = byId('btn-stop-action'); - if (!c) return; - if (!isBatchProcessing) { c.classList.add('hidden'); stop?.classList.add('hidden'); return; } - c.classList.remove('hidden'); stop?.classList.remove('hidden'); - if (txt) txt.textContent = batchTotal ? `${Math.floor(batchProcessed/batchTotal*100)}%` : '...'; -} - -async function batchDelete() { - if (isBatchProcessing) return; - const sel = getSelectedTokens(); - if (!sel.length) return showToast(t('common.noTokenSelected'), 'error'); - if (!await confirmAction(t('token.confirmBatchDelete', { count: sel.length }), { okText: t('common.delete') })) return; - const remove = new Set(sel.map(t => t.token)); - flatTokens = flatTokens.filter(t => !remove.has(t.token)); - await syncToServer(); showToast(t('token.deleteDone'), 'success'); loadData(); -} - -async function batchSetStatus(target) { - if (isBatchProcessing) return; - const sel = getSelectedTokens(); - if (!sel.length) return showToast(t('common.noTokenSelected'), 'error'); - const targets = sel.filter(t => t.status !== target); - if (!targets.length) return; - const toDisabled = target === 'disabled'; - if (!await confirmAction(t(toDisabled ? 'token.confirmBatchDisable' : 'token.confirmBatchEnable', { count: targets.length }))) return; - targets.forEach(t => t.status = target); - await syncToServer(); loadData(); showToast(toDisabled ? t('token.batchDisableDone') : t('token.batchEnableDone'), 'success'); -} -function batchDisableTokens() { batchSetStatus('disabled'); } -function batchEnableTokens() { batchSetStatus('active'); } - -window.onload = init; diff --git a/app/assets/js/core/auth.js b/app/assets/js/core/auth.js deleted file mode 100644 index 0c5ef610..00000000 --- a/app/assets/js/core/auth.js +++ /dev/null @@ -1,129 +0,0 @@ -/* Core auth module — key storage, verification, session management */ -const API_BASE = '/admin/api'; // admin API prefix -const FN_BASE = '/function'; // function API prefix -const APP_KEY_STORAGE = 'grok2api_app_key'; -const FUNCTION_KEY_STORAGE = 'grok2api_function_key'; -const APP_KEY_XOR_PREFIX = 'enc:xor:'; -const APP_KEY_ENC_PREFIX = 'enc:v1:'; -const APP_KEY_SECRET = 'grok2api-admin-key'; - -let cachedAdminKey = null; -let cachedFunctionKey = null; - -const _enc = new TextEncoder(); -const _dec = new TextDecoder(); - -function _toB64(bytes) { let s = ''; bytes.forEach(b => s += String.fromCharCode(b)); return btoa(s); } -function _fromB64(b64) { const s = atob(b64); const a = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) a[i] = s.charCodeAt(i); return a; } -function _xor(data, key) { const o = new Uint8Array(data.length); for (let i = 0; i < data.length; i++) o[i] = data[i] ^ key[i % key.length]; return o; } - -function xorEncrypt(plain) { - return APP_KEY_XOR_PREFIX + _toB64(_xor(_enc.encode(plain), _enc.encode(APP_KEY_SECRET))); -} -function xorDecrypt(stored) { - if (!stored.startsWith(APP_KEY_XOR_PREFIX)) return stored; - return _dec.decode(_xor(_fromB64(stored.slice(APP_KEY_XOR_PREFIX.length)), _enc.encode(APP_KEY_SECRET))); -} - -async function _deriveKey(salt) { - const km = await crypto.subtle.importKey('raw', _enc.encode(APP_KEY_SECRET), 'PBKDF2', false, ['deriveKey']); - return crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' }, km, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']); -} - -async function encryptAppKey(plain) { - if (!plain) return ''; - if (!crypto?.subtle) return xorEncrypt(plain); - const salt = crypto.getRandomValues(new Uint8Array(16)); - const iv = crypto.getRandomValues(new Uint8Array(12)); - const key = await _deriveKey(salt); - const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, _enc.encode(plain)); - return `${APP_KEY_ENC_PREFIX}${_toB64(salt)}:${_toB64(iv)}:${_toB64(new Uint8Array(cipher))}`; -} - -async function decryptAppKey(stored) { - if (!stored) return ''; - if (stored.startsWith(APP_KEY_XOR_PREFIX)) return xorDecrypt(stored); - if (!stored.startsWith(APP_KEY_ENC_PREFIX)) return stored; - if (!crypto?.subtle) return ''; - const parts = stored.split(':'); - if (parts.length !== 5) return ''; - const [, , saltB64, ivB64, cipherB64] = parts; - const key = await _deriveKey(_fromB64(saltB64)); - return _dec.decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: _fromB64(ivB64) }, key, _fromB64(cipherB64))); -} - -async function getStoredAppKey() { - const s = localStorage.getItem(APP_KEY_STORAGE) || ''; - if (!s) return ''; - try { return await decryptAppKey(s); } catch { clearStoredAppKey(); return ''; } -} - -async function getStoredFunctionKey() { - const s = localStorage.getItem(FUNCTION_KEY_STORAGE) || ''; - if (!s) return ''; - try { return await decryptAppKey(s); } catch { clearStoredFunctionKey(); return ''; } -} - -async function storeAppKey(key) { - if (!key) { clearStoredAppKey(); return; } - localStorage.setItem(APP_KEY_STORAGE, await encryptAppKey(key) || ''); -} - -async function storeFunctionKey(key) { - if (!key) { clearStoredFunctionKey(); return; } - localStorage.setItem(FUNCTION_KEY_STORAGE, await encryptAppKey(key) || ''); -} - -function clearStoredAppKey() { localStorage.removeItem(APP_KEY_STORAGE); cachedAdminKey = null; } -function clearStoredFunctionKey() { localStorage.removeItem(FUNCTION_KEY_STORAGE); cachedFunctionKey = null; } - -async function verifyKey(url, key) { - const h = key ? { Authorization: `Bearer ${key}` } : {}; - return (await fetch(url, { headers: h })).ok; -} - -async function ensureAdminKey() { - if (cachedAdminKey) return cachedAdminKey; - const key = await getStoredAppKey(); - if (!key) { window.location.href = '/admin/login'; return null; } - try { - if (!await verifyKey(`${API_BASE}/verify`, key)) throw 0; - cachedAdminKey = `Bearer ${key}`; - return cachedAdminKey; - } catch { clearStoredAppKey(); window.location.href = '/admin/login'; return null; } -} - -async function ensureFunctionKey() { - if (cachedFunctionKey !== null) return cachedFunctionKey; - const key = await getStoredFunctionKey(); - if (!key) { - try { if (await verifyKey(`${FN_BASE}/voice/token`, '')) { cachedFunctionKey = ''; return ''; } } catch {} - return null; - } - try { - if (!await verifyKey(`${FN_BASE}/voice/token`, key)) throw 0; - cachedFunctionKey = `Bearer ${key}`; - return cachedFunctionKey; - } catch { clearStoredFunctionKey(); return null; } -} - -function buildAuthHeaders(apiKey) { return apiKey ? { Authorization: apiKey } : {}; } -function logout() { clearStoredAppKey(); clearStoredFunctionKey(); window.location.href = '/admin/login'; } -function functionLogout() { clearStoredFunctionKey(); window.location.href = '/login'; } - -async function fetchStorageType() { - const apiKey = await ensureAdminKey(); - if (!apiKey) return null; - try { - const r = await fetch(`${API_BASE}/storage`, { headers: buildAuthHeaders(apiKey) }); - if (!r.ok) return null; - const d = await r.json(); - return d?.type || null; - } catch { return null; } -} - -function formatStorageLabel(type) { - if (!type) return '-'; - const map = { local: 'local', mysql: 'mysql', pgsql: 'pgsql', postgres: 'pgsql', postgresql: 'pgsql', redis: 'redis' }; - return map[type.toLowerCase()] || '-'; -} diff --git a/app/assets/js/core/header.js b/app/assets/js/core/header.js deleted file mode 100644 index cc150a96..00000000 --- a/app/assets/js/core/header.js +++ /dev/null @@ -1,76 +0,0 @@ -/* Unified header injection — handles both admin and function pages */ -(function() { - const GITHUB_ICON = '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.58 2 12.26c0 4.5 2.87 8.32 6.84 9.67.5.1.68-.22.68-.48 0-.24-.01-.86-.01-1.69-2.78.62-3.37-1.37-3.37-1.37-.45-1.17-1.11-1.48-1.11-1.48-.91-.64.07-.63.07-.63 1.01.07 1.54 1.06 1.54 1.06.9 1.58 2.36 1.12 2.94.86.09-.67.35-1.12.63-1.38-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.04 1.03-2.76-.1-.26-.45-1.3.1-2.71 0 0 .84-.27 2.75 1.05A9.3 9.3 0 0 1 12 6.79c.85 0 1.7.12 2.5.36 1.9-1.32 2.74-1.05 2.74-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.64 1.03 2.76 0 3.94-2.34 4.81-4.58 5.06.36.32.68.95.68 1.92 0 1.38-.01 2.49-.01 2.83 0 .26.18.58.69.48A10.05 10.05 0 0 0 22 12.26C22 6.58 17.52 2 12 2Z"/></svg>'; - - var ADMIN_NAV = ` - <a href="/admin/token" class="nav-link" data-nav="/admin/token" data-i18n="nav.tokenManage">Token管理</a> - <a href="/admin/config" class="nav-link" data-nav="/admin/config" data-i18n="nav.configManage">配置管理</a> - <a href="/admin/cache" class="nav-link" data-nav="/admin/cache" data-i18n="nav.cacheManage">缓存管理</a>`; - - var ADMIN_RIGHT = ` - <button id="lang-toggle" type="button" class="header-btn">EN</button> - <button id="storage-mode-btn" type="button" class="header-btn">-</button> - <a href="https://github.com/chenyme/grok2api/issues" target="_blank" class="header-btn" data-i18n="nav.feedback">反馈</a> - <button onclick="logout()" type="button" class="header-btn" data-i18n="nav.logout">退出</button>`; - - var FUNCTION_NAV = ` - <a href="/chat" class="nav-link" data-nav="/chat">Chat</a> - <a href="/imagine" class="nav-link" data-nav="/imagine">Imagine</a> - <a href="/voice" class="nav-link" data-nav="/voice">Voice</a> - <a href="/video" class="nav-link" data-nav="/video">Video</a>`; - - var FUNCTION_RIGHT = ` - <button id="lang-toggle" class="header-btn">EN</button> - <button onclick="functionLogout()" class="header-btn" data-i18n="nav.logout">退出</button>`; - - var FOOTER_HTML = '<footer class="app-footer"><a href="https://github.com/chenyme/grok2api" target="_blank">Grok2API</a> Created By <a href="https://github.com/chenyme" target="_blank">@Chenyme</a></footer>'; - - var container = document.getElementById('app-header'); - if (container && !container.children.length) { - var type = container.dataset.type || 'admin'; - var isAdmin = type === 'admin'; - container.innerHTML = '<header class="app-header"><div class="app-header-inner">' + - '<div class="header-left">' + - '<a href="' + (isAdmin ? 'https://github.com/chenyme/grok2api' : '/') + '" ' + (isAdmin ? 'target="_blank" ' : '') + 'class="brand">' + GITHUB_ICON + '<span>Grok2API</span></a>' + - '<div class="header-sep"></div>' + - (isAdmin ? ADMIN_NAV : FUNCTION_NAV) + - '</div>' + - '<div class="header-right">' + - (isAdmin ? ADMIN_RIGHT : FUNCTION_RIGHT) + - '</div>' + - '</div></header>'; - } - - // Inject footer if placeholder exists - var footer = document.getElementById('app-footer'); - if (footer && !footer.children.length) { - footer.innerHTML = FOOTER_HTML; - } - - // Highlight active nav link - var path = location.pathname; - document.querySelectorAll('a[data-nav]').forEach(function(a) { - if (path === a.dataset.nav || (a.dataset.nav !== '/' && path.startsWith(a.dataset.nav))) { - a.classList.add('active'); - } - }); - - // Storage mode badge (admin only) - var btn = document.getElementById('storage-mode-btn'); - if (btn && typeof fetchStorageType === 'function') { - (async function() { - btn.textContent = '...'; - var type = await fetchStorageType(); - var label = formatStorageLabel(type); - btn.textContent = label === '-' ? '-' : label.toUpperCase(); - if (label !== '-') btn.classList.add('ready'); - })(); - } - - // Lang toggle - var langBtn = document.getElementById('lang-toggle'); - if (langBtn) { - langBtn.textContent = (window.I18n && I18n.getLang() === 'zh') ? 'EN' : '中'; - langBtn.addEventListener('click', function() { if (window.I18n) I18n.toggleLang(); }); - } -})(); diff --git a/app/assets/js/core/sse.js b/app/assets/js/core/sse.js deleted file mode 100644 index e075ef7f..00000000 --- a/app/assets/js/core/sse.js +++ /dev/null @@ -1,27 +0,0 @@ -/* Batch SSE helper */ -(function(g) { - function normalize(key) { - if (!key) return ''; - const s = String(key).trim(); - return s.startsWith('Bearer ') ? s.slice(7).trim() : s; - } - function open(taskId, apiKey, handlers = {}) { - if (!taskId) return null; - const raw = normalize(apiKey); - const url = `${API_BASE}/batch/${taskId}/stream?app_key=${encodeURIComponent(raw)}`; - const es = new EventSource(url); - es.onmessage = e => { - if (!e.data) return; - try { const msg = JSON.parse(e.data); if (handlers.onMessage) handlers.onMessage(msg); } catch {} - }; - es.onerror = () => { if (handlers.onError) handlers.onError(); }; - return es; - } - function close(es) { if (es) es.close(); } - async function cancel(taskId, apiKey) { - if (!taskId) return; - const raw = normalize(apiKey); - try { await fetch(`${API_BASE}/batch/${taskId}/cancel`, { method: 'POST', headers: raw ? { Authorization: `Bearer ${raw}` } : undefined }); } catch {} - } - g.BatchSSE = { open, close, cancel }; -})(window); diff --git a/app/assets/js/core/toast.js b/app/assets/js/core/toast.js deleted file mode 100644 index f014c43e..00000000 --- a/app/assets/js/core/toast.js +++ /dev/null @@ -1,23 +0,0 @@ -/* Toast notification system */ -function showToast(message, type = 'success') { - let c = document.getElementById('toast-container'); - if (!c) { - c = document.createElement('div'); - c.id = 'toast-container'; - c.className = 'toast-container'; - document.body.appendChild(c); - } - const el = document.createElement('div'); - const ok = type === 'success'; - const icon = ok - ? '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>' - : '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'; - el.className = `toast ${ok ? 'toast-success' : 'toast-error'}`; - const safe = String(message).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); - el.innerHTML = `<div class="toast-icon">${icon}</div><div class="toast-content">${safe}</div>`; - c.appendChild(el); - setTimeout(() => { - el.classList.add('out'); - el.addEventListener('animationend', () => el.remove()); - }, 3000); -} diff --git a/app/assets/js/core/ui.js b/app/assets/js/core/ui.js deleted file mode 100644 index 24b41093..00000000 --- a/app/assets/js/core/ui.js +++ /dev/null @@ -1,111 +0,0 @@ -/* Shared UI helpers: modal, draggable, confirm dialog */ - -function openModal(id) { - const m = document.getElementById(id); - if (!m) return null; - m.classList.remove('hidden'); - requestAnimationFrame(() => m.classList.add('is-open')); - return m; -} - -function closeModal(id, cb) { - const m = document.getElementById(id); - if (!m) return; - m.classList.remove('is-open'); - setTimeout(() => { m.classList.add('hidden'); if (cb) cb(); }, 200); -} - -/* Confirm dialog — requires #confirm-dialog, #confirm-message, #confirm-ok, #confirm-cancel in DOM */ -let _confirmResolve = null; - -function setupConfirmDialog() { - const d = document.getElementById('confirm-dialog'); - if (!d) return; - const ok = document.getElementById('confirm-ok'); - const cancel = document.getElementById('confirm-cancel'); - d.addEventListener('click', e => { if (e.target === d) _closeConfirm(false); }); - if (ok) ok.addEventListener('click', () => _closeConfirm(true)); - if (cancel) cancel.addEventListener('click', () => _closeConfirm(false)); -} - -function confirmAction(message, opts = {}) { - const d = document.getElementById('confirm-dialog'); - if (!d) return Promise.resolve(false); - const msg = document.getElementById('confirm-message'); - const ok = document.getElementById('confirm-ok'); - const cancel = document.getElementById('confirm-cancel'); - if (msg) msg.textContent = message; - if (ok) ok.textContent = opts.okText || t('common.ok'); - if (cancel) cancel.textContent = opts.cancelText || t('common.cancel'); - return new Promise(resolve => { - _confirmResolve = resolve; - d.classList.remove('hidden'); - requestAnimationFrame(() => d.classList.add('is-open')); - }); -} - -function _closeConfirm(ok) { - const d = document.getElementById('confirm-dialog'); - if (!d) return; - d.classList.remove('is-open'); - setTimeout(() => { d.classList.add('hidden'); if (_confirmResolve) { _confirmResolve(ok); _confirmResolve = null; } }, 200); -} - -/* Draggable element */ -function makeDraggable(el) { - if (!el) return; - let dragging = false, sx, sy, il, it; - el.style.touchAction = 'none'; - el.addEventListener('pointerdown', e => { - if (e.target.closest('button, a, input, select')) return; - e.preventDefault(); - dragging = true; - el.setPointerCapture(e.pointerId); - sx = e.clientX; sy = e.clientY; - const r = el.getBoundingClientRect(); - if (!el.style.left) { - el.style.left = r.left + 'px'; - el.style.top = r.top + 'px'; - el.style.transform = 'none'; - el.style.bottom = 'auto'; - } - il = parseFloat(el.style.left); - it = parseFloat(el.style.top); - }); - document.addEventListener('pointermove', e => { - if (!dragging) return; - el.style.left = (il + e.clientX - sx) + 'px'; - el.style.top = (it + e.clientY - sy) + 'px'; - }); - document.addEventListener('pointerup', e => { - if (dragging) { dragging = false; el.releasePointerCapture(e.pointerId); } - }); -} - -/* Escape HTML */ -function escapeHtml(s) { - if (!s) return ''; - return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); -} - -/* Copy to clipboard with button feedback */ -async function copyToClipboard(text, btn) { - if (!text) return; - try { - await navigator.clipboard.writeText(text); - if (!btn) return; - const orig = btn.innerHTML; - btn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>'; - btn.style.color = 'var(--success)'; - setTimeout(() => { btn.innerHTML = orig; btn.style.color = ''; }, 1500); - } catch {} -} - -/* Download text file */ -function downloadTextFile(content, filename) { - const url = URL.createObjectURL(new Blob([content], { type: 'text/plain' })); - const a = document.createElement('a'); - a.href = url; a.download = filename; - document.body.appendChild(a); a.click(); a.remove(); - URL.revokeObjectURL(url); -} diff --git a/app/assets/js/webui/chat.js b/app/assets/js/webui/chat.js deleted file mode 100644 index cfd45c1c..00000000 --- a/app/assets/js/webui/chat.js +++ /dev/null @@ -1,1836 +0,0 @@ -(() => { - const modelChip = document.getElementById('modelChip'); - const modelLabel = document.getElementById('modelLabel'); - const modelDropdown = document.getElementById('modelDropdown'); - let modelValue = 'grok-4.20-beta'; - let modelList = []; - const tempRange = document.getElementById('tempRange'); - const tempValue = document.getElementById('tempValue'); - const topPRange = document.getElementById('topPRange'); - const topPValue = document.getElementById('topPValue'); - const systemInput = document.getElementById('systemInput'); - const promptInput = document.getElementById('promptInput'); - const sendBtn = document.getElementById('sendBtn'); - const settingsToggle = document.getElementById('settingsToggle'); - const settingsPanel = document.getElementById('settingsPanel'); - const chatLog = document.getElementById('chatLog'); - const emptyState = document.getElementById('emptyState'); - const statusText = document.getElementById('statusText'); - const attachBtn = document.getElementById('attachBtn'); - const fileInput = document.getElementById('fileInput'); - const fileBadge = document.getElementById('fileBadge'); - const fileName = document.getElementById('fileName'); - const fileRemoveBtn = document.getElementById('fileRemoveBtn'); - const chatSidebar = document.getElementById('chatSidebar'); - const sidebarOverlay = document.getElementById('sidebarOverlay'); - const sidebarToggle = document.getElementById('sidebarToggle'); - const newChatBtn = document.getElementById('newChatBtn'); - const collapseSidebarBtn = document.getElementById('collapseSidebarBtn'); - const sidebarExpandBtn = document.getElementById('sidebarExpandBtn'); - const sessionListEl = document.getElementById('sessionList'); - - const STORAGE_KEY = 'grok2api_chat_sessions'; - const SIDEBAR_STATE_KEY = 'grok2api_chat_sidebar_collapsed'; - const MAX_CONTEXT_MESSAGES = 5; - - let messageHistory = []; - let isSending = false; - let abortController = null; - let attachment = null; - let activeStreamInfo = null; - const feedbackUrl = 'https://github.com/chenyme/grok2api/issues/new'; - const CHAT_COMPLETIONS_ENDPOINT = `${FN_BASE}/chat/completions`; - const DEFAULT_SESSION_TITLES = ['新会话', 'New Session']; - - let sessionsData = null; - - function generateId() { - return crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2); - } - - function isDefaultTitleValue(title) { - return DEFAULT_SESSION_TITLES.includes(title); - } - - function loadSessions() { - try { - const raw = localStorage.getItem(STORAGE_KEY); - if (raw) { - sessionsData = JSON.parse(raw); - if (!sessionsData || !Array.isArray(sessionsData.sessions)) { - sessionsData = null; - } - } - } catch (e) { - sessionsData = null; - } - if (!sessionsData || !sessionsData.sessions.length) { - const id = generateId(); - sessionsData = { - activeId: id, - sessions: [{ - id, - title: t('chat.newSession'), - isDefaultTitle: true, - createdAt: Date.now(), - updatedAt: Date.now(), - messages: [] - }] - }; - saveSessions(); - } - sessionsData.sessions.forEach((session) => { - if (session && typeof session.isDefaultTitle === 'undefined') { - session.isDefaultTitle = isDefaultTitleValue(session.title); - } - }); - if (!sessionsData.activeId || !sessionsData.sessions.find(s => s.id === sessionsData.activeId)) { - sessionsData.activeId = sessionsData.sessions[0].id; - } - restoreActiveSession(); - renderSessionList(); - } - - function getMessageDisplay(msg) { - if (!msg) return ''; - if (typeof msg.content === 'string') return msg.content; - if (typeof msg.display === 'string' && msg.display.trim()) return msg.display; - if (Array.isArray(msg.content)) { - const textParts = []; - let hasFile = false; - for (const block of msg.content) { - if (!block) continue; - if (block.type === 'text' && block.text) { - textParts.push(block.text); - } - if (block.type === 'file') { - hasFile = true; - } - } - const name = msg.attachmentName || ''; - const fileLabel = hasFile ? (name ? t('chat.fileLabel') + ' ' + name : t('chat.fileLabel')) : ''; - if (textParts.length && fileLabel) return `${textParts.join('\n')}\n${fileLabel}`; - if (textParts.length) return textParts.join('\n'); - return fileLabel || t('chat.compositeContent'); - } - return t('chat.compositeContent'); - } - - function serializeMessage(msg) { - if (!msg || typeof msg !== 'object') return msg; - if (Array.isArray(msg.content)) { - return { - ...msg, - content: getMessageDisplay(msg) - }; - } - return msg; - } - - function serializeSessions() { - if (!sessionsData) return null; - return { - activeId: sessionsData.activeId, - sessions: sessionsData.sessions.map((session) => ({ - ...session, - messages: Array.isArray(session.messages) - ? session.messages.map(serializeMessage) - : [] - })) - }; - } - - function saveSessions() { - if (!sessionsData) return; - const snapshot = serializeSessions(); - if (!snapshot) return; - try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot)); - } catch (e) { - toast(t('chat.storageFull'), 'error'); - } - } - - function trimMessageHistory(maxCount = MAX_CONTEXT_MESSAGES) { - if (!maxCount || maxCount <= 0) return; - if (messageHistory.length <= maxCount) return; - messageHistory = messageHistory.slice(-maxCount); - const session = getActiveSession(); - if (session) { - session.messages = messageHistory.slice(); - session.updatedAt = Date.now(); - saveSessions(); - renderSessionList(); - } - if (chatLog) { - const rows = Array.from(chatLog.querySelectorAll('.message-row')); - const removeCount = rows.length - messageHistory.length; - if (removeCount > 0) { - rows.slice(0, removeCount).forEach((row) => row.remove()); - } - } - if (!messageHistory.length) { - showEmptyState(); - } - } - - function getActiveSession() { - if (!sessionsData) return null; - return sessionsData.sessions.find(s => s.id === sessionsData.activeId) || null; - } - - function restoreActiveSession() { - const session = getActiveSession(); - if (!session) return; - messageHistory = session.messages.slice(); - trimMessageHistory(); - if (chatLog) chatLog.innerHTML = ''; - if (!messageHistory.length) { - showEmptyState(); - return; - } - hideEmptyState(); - for (const msg of messageHistory) { - const displayContent = getMessageDisplay(msg); - const editable = !msg.hasAttachment && typeof msg.content === 'string'; - const entry = createMessage(msg.role, displayContent, true, { editable }); - if (entry && msg.role === 'assistant') { - updateMessage(entry, displayContent, true); - } - } - if (activeStreamInfo && activeStreamInfo.sessionId === session.id && activeStreamInfo.entry.row) { - chatLog.appendChild(activeStreamInfo.entry.row); - } - scrollToBottom(); - } - - function createSession() { - const id = generateId(); - const session = { - id, - title: t('chat.newSession'), - isDefaultTitle: true, - createdAt: Date.now(), - updatedAt: Date.now(), - messages: [] - }; - sessionsData.sessions.unshift(session); - sessionsData.activeId = id; - messageHistory = []; - if (chatLog) chatLog.innerHTML = ''; - showEmptyState(); - saveSessions(); - renderSessionList(); - if (isMobileSidebar()) closeSidebar(); - } - - function deleteSession(id) { - const idx = sessionsData.sessions.findIndex(s => s.id === id); - if (idx === -1) return; - sessionsData.sessions.splice(idx, 1); - if (!sessionsData.sessions.length) { - createSession(); - return; - } - if (sessionsData.activeId === id) { - const newIdx = Math.min(idx, sessionsData.sessions.length - 1); - sessionsData.activeId = sessionsData.sessions[newIdx].id; - restoreActiveSession(); - } - saveSessions(); - renderSessionList(); - } - - function switchSession(id) { - if (sessionsData.activeId === id) return; - syncCurrentSession(); - syncSessionModel(); - sessionsData.activeId = id; - const target = getActiveSession(); - if (target) target.unread = false; - restoreActiveSession(); - restoreSessionModel(); - saveSessions(); - renderSessionList(); - if (isMobileSidebar()) closeSidebar(); - } - - function syncCurrentSession() { - const session = getActiveSession(); - if (!session) return; - session.messages = messageHistory.slice(); - session.updatedAt = Date.now(); - } - - function updateSessionTitle(session) { - if (!session) return; - if (session.isDefaultTitle === false) return; - const firstUser = session.messages.find(m => m.role === 'user'); - if (!firstUser) return; - const text = getMessageDisplay(firstUser); - if (!text) return; - const title = text.replace(/\n/g, ' ').trim().slice(0, 20); - if (title) { - session.title = title; - session.isDefaultTitle = false; - } - } - - function renameSession(id, newTitle) { - const session = sessionsData.sessions.find(s => s.id === id); - if (!session) return; - const trimmed = (newTitle || '').trim(); - session.title = trimmed || t('chat.newSession'); - session.isDefaultTitle = !trimmed && isDefaultTitleValue(session.title); - session.updatedAt = Date.now(); - saveSessions(); - renderSessionList(); - } - - function startRenameSession(sessionId, titleSpan) { - const session = sessionsData.sessions.find(s => s.id === sessionId); - if (!session) return; - const input = document.createElement('input'); - input.type = 'text'; - input.className = 'session-rename-input'; - input.value = session.title || ''; - input.maxLength = 40; - titleSpan.replaceWith(input); - input.focus(); - input.select(); - const commit = () => { - renameSession(sessionId, input.value); - }; - input.addEventListener('blur', commit); - input.addEventListener('keydown', (e) => { - if (e.key === 'Enter') { e.preventDefault(); input.blur(); } - if (e.key === 'Escape') { input.value = session.title || t('chat.newSession'); input.blur(); } - }); - } - - function syncSessionModel() { - const session = getActiveSession(); - if (!session) return; - session.model = modelValue || ''; - } - - function restoreSessionModel() { - const session = getActiveSession(); - if (!session || !session.model) return; - if (modelList.includes(session.model)) { - selectModel(session.model); - } - } - - function renderSessionList() { - if (!sessionListEl || !sessionsData) return; - sessionListEl.innerHTML = ''; - for (const session of sessionsData.sessions) { - const item = document.createElement('div'); - item.className = 'session-item' + (session.id === sessionsData.activeId ? ' active' : ''); - item.dataset.id = session.id; - - const titleSpan = document.createElement('span'); - titleSpan.className = 'session-title'; - titleSpan.textContent = session.title || t('chat.newSession'); - titleSpan.addEventListener('dblclick', (e) => { - e.stopPropagation(); - startRenameSession(session.id, titleSpan); - }); - item.appendChild(titleSpan); - - if (session.unread && session.id !== sessionsData.activeId) { - const dot = document.createElement('span'); - dot.className = 'session-unread'; - item.appendChild(dot); - } - - const delBtn = document.createElement('button'); - delBtn.className = 'session-delete'; - delBtn.type = 'button'; - delBtn.title = t('common.delete'); - delBtn.textContent = '×'; - delBtn.addEventListener('click', (e) => { - e.stopPropagation(); - deleteSession(session.id); - }); - item.appendChild(delBtn); - - item.addEventListener('click', () => switchSession(session.id)); - sessionListEl.appendChild(item); - } - } - - function isMobileSidebar() { - return window.matchMedia('(max-width: 1024px)').matches; - } - - function setSidebarCollapsed(collapsed) { - const layout = chatSidebar ? chatSidebar.closest('.chat-layout') : null; - if (!layout) return; - layout.classList.toggle('collapsed', collapsed); - try { - localStorage.setItem(SIDEBAR_STATE_KEY, collapsed ? '1' : '0'); - } catch (e) { - // ignore storage failures - } - } - - function openSidebar() { - if (isMobileSidebar()) { - if (chatSidebar) chatSidebar.classList.add('open'); - if (sidebarOverlay) sidebarOverlay.classList.add('open'); - return; - } - setSidebarCollapsed(false); - } - - function closeSidebar() { - if (isMobileSidebar()) { - if (chatSidebar) chatSidebar.classList.remove('open'); - if (sidebarOverlay) sidebarOverlay.classList.remove('open'); - return; - } - setSidebarCollapsed(true); - } - - function toggleSidebar() { - if (isMobileSidebar()) { - if (chatSidebar && chatSidebar.classList.contains('open')) { - closeSidebar(); - } else { - openSidebar(); - } - return; - } - const layout = chatSidebar ? chatSidebar.closest('.chat-layout') : null; - if (!layout) return; - setSidebarCollapsed(!layout.classList.contains('collapsed')); - } - - function toast(message, type) { - if (typeof showToast === 'function') { - showToast(message, type); - } - } - - function setStatus(state, text) { - if (!statusText) return; - statusText.textContent = text || t('chat.ready'); - statusText.classList.remove('connected', 'connecting', 'error'); - if (state) statusText.classList.add(state); - } - - function setSendingState(sending) { - isSending = sending; - if (sendBtn) sendBtn.disabled = sending; - } - - function updateRangeValues() { - if (tempValue && tempRange) { - tempValue.textContent = Number(tempRange.value).toFixed(2); - } - if (topPValue && topPRange) { - topPValue.textContent = Number(topPRange.value).toFixed(2); - } - } - - function scrollToBottom() { - const body = document.scrollingElement || document.documentElement; - if (!body) return; - const hasOwnScroll = chatLog && chatLog.scrollHeight > chatLog.clientHeight + 1; - if (hasOwnScroll) { - chatLog.scrollTop = chatLog.scrollHeight; - return; - } - body.scrollTop = body.scrollHeight; - } - - function hideEmptyState() { - if (emptyState) emptyState.classList.add('hidden'); - } - - function showEmptyState() { - if (emptyState) emptyState.classList.remove('hidden'); - } - - function setRenderedHTML(el, html) { - // html is pre-sanitized through renderMarkdown → escapeHtml pipeline; - // all user text is entity-escaped before any HTML construction. - el.innerHTML = html; - } - - function escapeHtml(value) { - return value - .replace(/&/g, '&') - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); - } - - function isSafeLinkUrl(url) { - const val = String(url || '').trim().toLowerCase(); - if (!val) return false; - return /^(https?:|mailto:|tel:|\/(?!\/)|\.\.?\/|#)/.test(val); - } - - function isSafeImageUrl(url) { - const val = String(url || '').trim().toLowerCase(); - if (!val) return false; - return /^(https?:|data:image\/(?:png|jpe?g|gif|webp|bmp|ico);base64,|\/(?!\/)|\.\.?\/)/.test(val); - } - - function renderBasicMarkdown(rawText) { - const text = (rawText || '').replace(/\\n/g, '\n'); - const escaped = escapeHtml(text); - const codeBlocks = []; - const fenced = escaped.replace(/```([a-zA-Z0-9_-]+)?\n([\s\S]*?)```/g, (match, lang, code) => { - const safeLang = lang ? escapeHtml(lang) : ''; - const html = `<pre class="code-block"><code${safeLang ? ` class="language-${safeLang}"` : ''}>${code}</code></pre>`; - const token = `@@CODEBLOCK_${codeBlocks.length}@@`; - codeBlocks.push(html); - return token; - }); - - const renderInline = (value) => { - const inlineCodes = []; - let output = value.replace(/`([^`]+)`/g, (match, code) => { - const token = `@@INLINE_${inlineCodes.length}@@`; - inlineCodes.push(`<code class="inline-code">${code}</code>`); - return token; - }); - - output = output - .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>') - .replace(/\*([^*]+)\*/g, '<em>$1</em>') - .replace(/~~([^~]+)~~/g, '<del>$1</del>'); - - output = output.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => { - const safeAlt = escapeHtml(alt || 'image'); - if (!isSafeImageUrl(url)) return safeAlt; - const safeUrl = escapeHtml(url || ''); - return `<img src="${safeUrl}" alt="${safeAlt}" loading="lazy">`; - }); - - output = output.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => { - const safeLabel = escapeHtml(label || ''); - if (!isSafeLinkUrl(url)) return safeLabel; - const safeUrl = escapeHtml(url || ''); - return `<a href="${safeUrl}" target="_blank" rel="noopener">${safeLabel}</a>`; - }); - - output = output.replace(/(data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)/g, (match, uri) => { - if (!isSafeImageUrl(uri)) return ''; - const safeUrl = escapeHtml(uri || ''); - return `<img src="${safeUrl}" alt="image" loading="lazy">`; - }); - - inlineCodes.forEach((html, i) => { - output = output.replace(new RegExp(`@@INLINE_${i}@@`, 'g'), html); - }); - - return output; - }; - - const lines = fenced.split(/\r?\n/); - const htmlParts = []; - let inUl = false; - let inUlTask = false; - let inOl = false; - let inTable = false; - let paragraphLines = []; - - const closeLists = () => { - if (inUl) { - htmlParts.push('</ul>'); - inUl = false; - inUlTask = false; - } - if (inOl) { - htmlParts.push('</ol>'); - inOl = false; - } - }; - - const closeTable = () => { - if (inTable) { - htmlParts.push('</tbody></table>'); - inTable = false; - } - }; - - const flushParagraph = () => { - if (!paragraphLines.length) return; - const joined = paragraphLines.join('<br>'); - htmlParts.push(`<p>${renderInline(joined)}</p>`); - paragraphLines = []; - }; - - const isTableSeparator = (line) => /^\s*\|?(?:\s*:?-+:?\s*\|)+\s*$/.test(line); - const splitTableRow = (line) => { - const trimmed = line.trim(); - const row = trimmed.replace(/^\|/, '').replace(/\|$/, ''); - return row.split('|').map(cell => cell.trim()); - }; - - for (let i = 0; i < lines.length; i += 1) { - const line = lines[i]; - const trimmed = line.trim(); - if (!trimmed) { - flushParagraph(); - closeLists(); - closeTable(); - continue; - } - - const codeTokenMatch = trimmed.match(/^@@CODEBLOCK_(\d+)@@$/); - if (codeTokenMatch) { - flushParagraph(); - closeLists(); - closeTable(); - htmlParts.push(trimmed); - continue; - } - - const headingMatch = trimmed.match(/^(#{1,6})\s+(.*)$/); - if (headingMatch) { - flushParagraph(); - closeLists(); - closeTable(); - const level = headingMatch[1].length; - htmlParts.push(`<h${level}>${renderInline(headingMatch[2])}</h${level}>`); - continue; - } - - if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { - flushParagraph(); - closeLists(); - closeTable(); - htmlParts.push('<hr>'); - continue; - } - - if (/^\s*>/.test(line)) { - flushParagraph(); - closeLists(); - closeTable(); - const quoteLines = []; - let j = i; - for (; j < lines.length; j += 1) { - const currentLine = lines[j]; - if (!/^\s*>/.test(currentLine)) break; - quoteLines.push(currentLine.replace(/^\s*>\s?/, '')); - } - i = j - 1; - const quoteText = quoteLines.join('\n'); - htmlParts.push(`<blockquote>${renderBasicMarkdown(quoteText)}</blockquote>`); - continue; - } - - if (trimmed.includes('|')) { - const nextLine = lines[i + 1] || ''; - if (!inTable && isTableSeparator(nextLine.trim())) { - flushParagraph(); - closeLists(); - const headers = splitTableRow(trimmed); - htmlParts.push('<div class="table-wrap"><table><thead><tr>'); - headers.forEach(cell => htmlParts.push(`<th>${renderInline(cell)}</th>`)); - htmlParts.push('</tr></thead><tbody>'); - inTable = true; - i += 1; - continue; - } - if (inTable && !isTableSeparator(trimmed)) { - const cells = splitTableRow(trimmed); - htmlParts.push('<tr>'); - cells.forEach(cell => htmlParts.push(`<td>${renderInline(cell)}</td>`)); - htmlParts.push('</tr>'); - continue; - } - } - - const taskMatch = trimmed.match(/^[-*+•·]\s+\[([ xX])\]\s+(.*)$/); - if (taskMatch) { - flushParagraph(); - if (inUl && !inUlTask) { - closeLists(); - } - if (!inUl) { - closeLists(); - closeTable(); - htmlParts.push('<ul class="task-list">'); - inUl = true; - inUlTask = true; - } - const checked = taskMatch[1].toLowerCase() === 'x'; - htmlParts.push(`<li class="task-item"><input type="checkbox" disabled${checked ? ' checked' : ''}>${renderInline(taskMatch[2])}</li>`); - continue; - } - - const ulMatch = trimmed.match(/^[-*+•·]\s+(.*)$/); - if (ulMatch) { - flushParagraph(); - if (!inUl) { - closeLists(); - closeTable(); - htmlParts.push('<ul>'); - inUl = true; - inUlTask = false; - } - htmlParts.push(`<li>${renderInline(ulMatch[1])}</li>`); - continue; - } - - const olMatch = trimmed.match(/^\d+[.)、]\s+(.*)$/); - if (olMatch) { - flushParagraph(); - if (!inOl) { - closeLists(); - closeTable(); - htmlParts.push('<ol>'); - inOl = true; - } - htmlParts.push(`<li>${renderInline(olMatch[1])}</li>`); - continue; - } - - paragraphLines.push(trimmed); - } - - flushParagraph(); - closeLists(); - closeTable(); - - let output = htmlParts.join(''); - codeBlocks.forEach((html, index) => { - output = output.replace(`@@CODEBLOCK_${index}@@`, html); - }); - return output; - } - - function parseThinkSections(raw) { - const parts = []; - let cursor = 0; - while (cursor < raw.length) { - const start = raw.indexOf('<think>', cursor); - if (start === -1) { - parts.push({ type: 'text', value: raw.slice(cursor) }); - break; - } - if (start > cursor) { - parts.push({ type: 'text', value: raw.slice(cursor, start) }); - } - const thinkStart = start + 7; - const end = raw.indexOf('</think>', thinkStart); - if (end === -1) { - parts.push({ type: 'think', value: raw.slice(thinkStart), open: true }); - cursor = raw.length; - } else { - parts.push({ type: 'think', value: raw.slice(thinkStart, end), open: false }); - cursor = end + 8; - } - } - return parts; - } - - function parseRolloutBlocks(text) { - const lines = (text || '').split(/\r?\n/); - const blocks = []; - let current = null; - for (const line of lines) { - const match = line.match(/^\s*\[([^\]]+)\]\[([^\]]+)\]\s*(.*)$/); - if (match) { - if (current) blocks.push(current); - current = { id: match[1], type: match[2], lines: [] }; - if (match[3]) current.lines.push(match[3]); - continue; - } - if (current) { - current.lines.push(line); - } - } - if (current) blocks.push(current); - return blocks; - } - - function parseAgentSections(text) { - const lines = (text || '').split(/\r?\n/); - const sections = []; - let current = { title: null, lines: [] }; - let hasAgentHeading = false; - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed) { - current.lines.push(line); - continue; - } - const agentMatch = trimmed.match(/^(Grok\s+Leader|(?:Grok\s+)?Agent\s*\d+)$/i); - if (agentMatch) { - hasAgentHeading = true; - if (current.lines.length) { - sections.push(current); - } - current = { title: agentMatch[1], lines: [] }; - continue; - } - current.lines.push(line); - } - if (current.lines.length) { - sections.push(current); - } - if (!hasAgentHeading) { - return [{ title: null, lines }]; - } - return sections; - } - - const toolTypeMap = { - websearch: { icon: '', label: t('chat.toolWebSearch') }, - searchimage: { icon: '', label: t('chat.toolImageSearch') }, - agentthink: { icon: '', label: t('chat.toolAgentThink') } - }; - const defaultToolType = { icon: '', label: t('chat.toolDefault') }; - - function getToolMeta(typeStr) { - const key = String(typeStr || '').trim().toLowerCase().replace(/\s+/g, ''); - return toolTypeMap[key] || defaultToolType; - } - - function renderThinkContent(text, openAll) { - const sections = parseAgentSections(text); - if (!sections.length) { - return renderBasicMarkdown(text); - } - const renderGroups = (blocks, openAllGroups) => { - const groups = []; - const map = new Map(); - for (const block of blocks) { - const key = block.id; - let group = map.get(key); - if (!group) { - group = { id: key, items: [] }; - map.set(key, group); - groups.push(group); - } - group.items.push(block); - } - return groups.map((group) => { - const items = group.items.map((item) => { - const body = renderBasicMarkdown(item.lines.join('\n').trim()); - const typeKey = String(item.type || '').trim().toLowerCase().replace(/\s+/g, ''); - const typeAttr = escapeHtml(typeKey); - const meta = getToolMeta(item.type); - const iconHtml = meta.icon ? `<span class="think-tool-icon">${meta.icon}</span>` : ''; - const typeLabel = `${iconHtml}${escapeHtml(meta.label)}`; - return `<div class="think-item-row think-tool-card" data-tool-type="${typeAttr}"><div class="think-item-type" data-type="${typeAttr}">${typeLabel}</div><div class="think-item-body">${body || '<em>' + t('chat.empty') + '</em>'}</div></div>`; - }).join(''); - const title = escapeHtml(group.id); - const openAttr = openAllGroups ? ' open' : ''; - return `<details class="think-rollout-group"${openAttr}><summary><span class="think-rollout-title">${title}</span></summary><div class="think-rollout-body">${items}</div></details>`; - }).join(''); - }; - - const agentBlocks = sections.map((section, idx) => { - const blocks = parseRolloutBlocks(section.lines.join('\n')); - const inner = blocks.length - ? renderGroups(blocks, openAll) - : `<div class="think-rollout-body">${renderBasicMarkdown(section.lines.join('\n').trim())}</div>`; - if (!section.title) { - return `<div class="think-agent-items">${inner}</div>`; - } - const title = escapeHtml(section.title); - const openAttr = openAll ? ' open' : (idx === 0 ? ' open' : ''); - return `<details class="think-agent"${openAttr}><summary>${title}</summary><div class="think-agent-items">${inner}</div></details>`; - }); - return `<div class="think-agents">${agentBlocks.join('')}</div>`; - } - - function renderMarkdown(text) { - const raw = text || ''; - const parts = parseThinkSections(raw); - return parts.map((part) => { - if (part.type === 'think') { - const body = renderThinkContent(part.value.trim(), part.open); - const openAttr = part.open ? ' open' : ''; - return `<details class="think-block" data-think="true"${openAttr}><summary class="think-summary">${t('chat.thinkLabel')}</summary><div class="think-content">${body || '<em>' + t('chat.empty') + '</em>'}</div></details>`; - } - return renderBasicMarkdown(part.value); - }).join(''); - } - - function deleteMessageByRow(row) { - if (!row || !chatLog) return; - if (activeStreamInfo && activeStreamInfo.entry.row === row) return; - const rows = chatLog.querySelectorAll('.message-row'); - const idx = Array.from(rows).indexOf(row); - if (idx === -1 || idx >= messageHistory.length) return; - messageHistory.splice(idx, 1); - row.remove(); - const session = getActiveSession(); - if (session) { - session.messages = messageHistory.slice(); - session.updatedAt = Date.now(); - saveSessions(); - } - if (!messageHistory.length) { - showEmptyState(); - } - } - - function editMessageByRow(row) { - if (isSending || !row || !chatLog) return; - const rows = chatLog.querySelectorAll('.message-row'); - const idx = Array.from(rows).indexOf(row); - if (idx === -1 || idx >= messageHistory.length) return; - const msg = messageHistory[idx]; - if (msg && (msg.hasAttachment || typeof msg.content !== 'string')) { - toast(t('chat.attachmentNoEdit'), 'error'); - return; - } - const currentText = typeof msg.content === 'string' ? msg.content : ''; - - const contentNode = row.querySelector('.message-content'); - if (!contentNode) return; - - const textarea = document.createElement('textarea'); - textarea.className = 'edit-msg-input'; - textarea.value = currentText; - textarea.rows = Math.max(3, currentText.split('\n').length); - - const btnWrap = document.createElement('div'); - btnWrap.className = 'edit-msg-actions'; - const saveBtn = createActionButton(t('chat.saveEdit'), t('chat.saveEditTitle'), () => commit()); - const cancelBtn = createActionButton(t('chat.cancelEdit'), t('chat.cancelEditTitle'), () => cancel()); - btnWrap.appendChild(saveBtn); - btnWrap.appendChild(cancelBtn); - - const savedChildren = Array.from(contentNode.childNodes).map(n => n.cloneNode(true)); - const originalClass = contentNode.className; - contentNode.className = 'message-content'; - contentNode.innerHTML = ''; - contentNode.appendChild(textarea); - contentNode.appendChild(btnWrap); - row.classList.add('editing'); - textarea.focus(); - - const actionsEl = row.querySelector('.message-actions'); - if (actionsEl) actionsEl.classList.add('hidden'); - - function finish() { - row.classList.remove('editing'); - if (actionsEl) actionsEl.classList.remove('hidden'); - } - - function commit() { - const newText = textarea.value.trim(); - if (!newText) { - toast(t('chat.contentEmpty'), 'error'); - return; - } - msg.content = newText; - contentNode.className = originalClass; - contentNode.textContent = ''; - if (msg.role === 'assistant') { - contentNode.classList.add('rendered'); - setRenderedHTML(contentNode, renderMarkdown(newText)); - } else { - contentNode.textContent = newText; - } - finish(); - const session = getActiveSession(); - if (session) { - session.messages = messageHistory.slice(); - session.updatedAt = Date.now(); - saveSessions(); - } - } - - function cancel() { - contentNode.className = originalClass; - contentNode.textContent = ''; - savedChildren.forEach(n => contentNode.appendChild(n)); - finish(); - } - } - - function regenerateFromRow(row) { - if (isSending || !row || !chatLog) return; - const rows = chatLog.querySelectorAll('.message-row'); - const idx = Array.from(rows).indexOf(row); - if (idx === -1 || idx >= messageHistory.length) return; - if (messageHistory[idx].role !== 'user') return; - - // 丢弃该用户消息之后的所有消息和 DOM - const allRows = Array.from(rows); - for (let i = allRows.length - 1; i > idx; i--) { - allRows[i].remove(); - } - messageHistory.splice(idx + 1); - - const session = getActiveSession(); - if (session) { - session.messages = messageHistory.slice(); - session.updatedAt = Date.now(); - saveSessions(); - } - - // 从该位置重新发送 - const sendSessionId = sessionsData.activeId; - const assistantEntry = createMessage('assistant', ''); - setSendingState(true); - setStatus('connecting', t('common.sending')); - - abortController = new AbortController(); - const payload = buildPayload(); - - (async () => { - let headers = { 'Content-Type': 'application/json' }; - try { - const authHeader = await ensureFunctionKey(); - headers = { ...headers, ...buildAuthHeaders(authHeader) }; - } catch (e) {} - - try { - const res = await fetch(CHAT_COMPLETIONS_ENDPOINT, { - method: 'POST', - headers, - body: JSON.stringify(payload), - signal: abortController.signal - }); - if (!res.ok) throw new Error(t('chat.requestFailedStatus', { status: res.status })); - await handleStream(res, assistantEntry, sendSessionId); - setStatus('connected', t('common.done')); - } catch (e) { - if (e && e.name === 'AbortError') { - updateMessage(assistantEntry, assistantEntry.raw || t('common.stopped'), true); - setStatus('error', t('common.stopped')); - if (!assistantEntry.committed) { - assistantEntry.committed = true; - commitToSession(sendSessionId, assistantEntry.raw || ''); - } - } else { - updateMessage(assistantEntry, t('chat.requestFailedStatus', { status: e.message || e }), true); - setStatus('error', t('common.failed')); - toast(t('chat.requestFailedCheck'), 'error'); - } - } finally { - setSendingState(false); - abortController = null; - scrollToBottom(); - } - })(); - } - - function createMessage(role, content, skipScroll, options) { - if (!chatLog) return null; - hideEmptyState(); - const row = document.createElement('div'); - row.className = `message-row ${role === 'user' ? 'user' : 'assistant'}`; - - const bubble = document.createElement('div'); - bubble.className = 'message-bubble'; - const contentNode = document.createElement('div'); - contentNode.className = 'message-content'; - contentNode.textContent = content || ''; - bubble.appendChild(contentNode); - row.appendChild(bubble); - - chatLog.appendChild(row); - if (!skipScroll) scrollToBottom(); - const entry = { - row, - contentNode, - role, - raw: content || '', - committed: false, - startedAt: Date.now(), - firstTokenAt: null, - hasThink: false, - thinkElapsed: null, - thinkAutoCollapsed: false - }; - if (role === 'user') { - const editable = options && options.editable === false ? false : true; - const actions = document.createElement('div'); - actions.className = 'message-actions'; - if (editable) { - actions.appendChild(createActionButton(t('chat.editMessage'), t('chat.editMessageTitle'), () => editMessageByRow(row))); - } - actions.appendChild(createActionButton(t('chat.regenerate'), t('chat.regenerateTitle'), () => regenerateFromRow(row))); - row.appendChild(actions); - } - return entry; - } - - function applyImageGrid(root) { - if (!root) return; - const isIgnorable = (node) => { - if (node.nodeType === Node.TEXT_NODE) { - return !node.textContent.trim(); - } - return node.nodeType === Node.ELEMENT_NODE && node.tagName === 'BR'; - }; - - const isImageLink = (node) => { - if (!node || node.nodeType !== Node.ELEMENT_NODE || node.tagName !== 'A') return false; - const children = Array.from(node.childNodes); - if (!children.length) return false; - return children.every((child) => { - if (child.nodeType === Node.TEXT_NODE) { - return !child.textContent.trim(); - } - return child.nodeType === Node.ELEMENT_NODE && child.tagName === 'IMG'; - }); - }; - - const extractImageItems = (node) => { - if (!node || node.nodeType !== Node.ELEMENT_NODE) return null; - if (node.classList && node.classList.contains('img-grid')) return null; - if (node.tagName === 'IMG') { - return { items: [node], removeNode: null }; - } - if (isImageLink(node)) { - return { items: [node], removeNode: null }; - } - if (node.tagName === 'P') { - const items = []; - const children = Array.from(node.childNodes); - if (!children.length) return null; - for (const child of children) { - if (child.nodeType === Node.TEXT_NODE) { - if (!child.textContent.trim()) continue; - return null; - } - if (child.nodeType === Node.ELEMENT_NODE) { - if (child.tagName === 'IMG' || isImageLink(child)) { - items.push(child); - continue; - } - if (child.tagName === 'BR') continue; - return null; - } - return null; - } - if (!items.length) return null; - return { items, removeNode: node }; - } - return null; - }; - - const wrapImagesInContainer = (container) => { - const children = Array.from(container.childNodes); - let group = []; - let groupStart = null; - let removeNodes = []; - - const flush = () => { - if (group.length < 2) { - group = []; - groupStart = null; - removeNodes = []; - return; - } - const wrapper = document.createElement('div'); - wrapper.className = 'img-grid'; - const cols = Math.min(4, group.length); - wrapper.style.setProperty('--cols', String(cols)); - if (groupStart) { - container.insertBefore(wrapper, groupStart); - } else { - container.appendChild(wrapper); - } - group.forEach((img) => wrapper.appendChild(img)); - removeNodes.forEach((n) => n.parentNode && n.parentNode.removeChild(n)); - group = []; - groupStart = null; - removeNodes = []; - }; - - children.forEach((node) => { - if (group.length && isIgnorable(node)) { - removeNodes.push(node); - return; - } - const extracted = extractImageItems(node); - if (extracted && extracted.items.length) { - if (!groupStart) groupStart = node; - group.push(...extracted.items); - if (extracted.removeNode) { - removeNodes.push(extracted.removeNode); - } - return; - } - flush(); - }); - flush(); - }; - - const containers = [root, ...root.querySelectorAll('.think-content, .think-item-body, .think-rollout-body, .think-agent-items')]; - containers.forEach((container) => { - if (!container || container.closest('.img-grid')) return; - if (!container.querySelector || !container.querySelector('img')) return; - wrapImagesInContainer(container); - }); - } - - function updateMessage(entry, content, finalize = false) { - if (!entry) return; - entry.raw = content || ''; - if (!entry.contentNode) return; - if (!entry.hasThink && entry.raw.includes('<think>')) { - entry.hasThink = true; - } - let savedThinkStates = null; - if (entry.hasThink && entry.thinkAutoCollapsed) { - const blocks = entry.contentNode.querySelectorAll('.think-block[data-think="true"]'); - if (blocks.length) { - savedThinkStates = Array.from(blocks).map(b => b.hasAttribute('open')); - } - } - if (finalize) { - entry.contentNode.classList.add('rendered'); - setRenderedHTML(entry.contentNode, renderMarkdown(entry.raw)); - } else { - if (entry.role === 'assistant') { - setRenderedHTML(entry.contentNode, renderMarkdown(entry.raw)); - } else { - entry.contentNode.textContent = entry.raw; - } - } - if (entry.hasThink) { - updateThinkSummary(entry, finalize ? (entry.thinkElapsed ?? 0) : entry.thinkElapsed); - const thinkBlocks = entry.contentNode.querySelectorAll('.think-block[data-think="true"]'); - thinkBlocks.forEach((block, i) => { - if (savedThinkStates && i < savedThinkStates.length) { - if (savedThinkStates[i]) { - block.setAttribute('open', ''); - } else { - block.removeAttribute('open'); - } - } else if (entry.thinkElapsed === null || entry.thinkElapsed === undefined) { - block.setAttribute('open', ''); - } else if (!entry.thinkAutoCollapsed) { - block.removeAttribute('open'); - entry.thinkAutoCollapsed = true; - } - }); - } - if (entry.role === 'assistant') { - applyImageGrid(entry.contentNode); - const thinkNodes = entry.contentNode.querySelectorAll('.think-content'); - thinkNodes.forEach((node) => { - node.scrollTop = node.scrollHeight; - }); - enhanceBrokenImages(entry.contentNode); - if (finalize && entry.row && !entry.row.querySelector('.message-actions')) { - attachAssistantActions(entry); - } - } - scrollToBottom(); - } - - function enhanceBrokenImages(root) { - if (!root) return; - const images = root.querySelectorAll('img'); - images.forEach((img) => { - if (img.dataset.retryBound) return; - img.dataset.retryBound = '1'; - img.addEventListener('error', () => { - if (img.dataset.failed) return; - img.dataset.failed = '1'; - const wrapper = document.createElement('button'); - wrapper.type = 'button'; - wrapper.className = 'img-retry'; - wrapper.textContent = t('chat.clickRetry'); - wrapper.addEventListener('click', () => { - wrapper.classList.add('loading'); - const original = img.getAttribute('src') || ''; - const cacheBust = original.includes('?') ? '&' : '?'; - img.dataset.failed = ''; - img.src = `${original}${cacheBust}t=${Date.now()}`; - }); - img.replaceWith(wrapper); - }); - img.addEventListener('load', () => { - if (img.dataset.failed) { - img.dataset.failed = ''; - } - }); - }); - } - - function updateThinkSummary(entry, elapsedSec) { - if (!entry || !entry.contentNode) return; - const summaries = entry.contentNode.querySelectorAll('.think-summary'); - if (!summaries.length) return; - const text = typeof elapsedSec === 'number' ? (elapsedSec > 0 ? t('chat.thinkingSec', { sec: elapsedSec }) : t('chat.thought')) : t('chat.thinking'); - summaries.forEach((node) => { - node.textContent = text; - const block = node.closest('.think-block'); - if (!block) return; - if (typeof elapsedSec === 'number') { - block.removeAttribute('data-thinking'); - } else { - block.setAttribute('data-thinking', 'true'); - } - }); - } - - function buildMessages() { - return buildMessagesFrom(messageHistory); - } - - function buildMessagesFrom(history) { - const payload = []; - const systemPrompt = systemInput ? systemInput.value.trim() : ''; - if (systemPrompt) { - payload.push({ role: 'system', content: systemPrompt }); - } - for (const msg of history) { - payload.push({ role: msg.role, content: msg.content }); - } - return payload; - } - - function buildPayload() { - const payload = { - model: modelValue || 'grok-3', - messages: buildMessages(), - stream: true, - temperature: Number(tempRange ? tempRange.value : 0.8), - top_p: Number(topPRange ? topPRange.value : 0.95) - }; - return payload; - } - - function buildPayloadFrom(history) { - const payload = { - model: modelValue || 'grok-3', - messages: buildMessagesFrom(history), - stream: true, - temperature: Number(tempRange ? tempRange.value : 0.8), - top_p: Number(topPRange ? topPRange.value : 0.95) - }; - return payload; - } - - function selectModel(value) { - modelValue = value; - if (modelLabel) modelLabel.textContent = value; - renderModelDropdown(); - } - - function renderModelDropdown() { - if (!modelDropdown) return; - modelDropdown.innerHTML = ''; - for (const id of modelList) { - const opt = document.createElement('div'); - opt.className = 'model-option' + (id === modelValue ? ' selected' : ''); - opt.dataset.value = id; - opt.textContent = id; - modelDropdown.appendChild(opt); - } - } - - function toggleModelDropdown(show) { - if (!modelDropdown || !modelChip) return; - if (typeof show === 'boolean') { - modelDropdown.classList.toggle('hidden', !show); - modelChip.classList.toggle('open', show); - return; - } - const visible = !modelDropdown.classList.contains('hidden'); - modelDropdown.classList.toggle('hidden', visible); - modelChip.classList.toggle('open', !visible); - } - - async function loadModels() { - if (!modelDropdown) return; - const fallback = ['grok-4.1-fast', 'grok-4', 'grok-3', 'grok-3-mini', 'grok-3-thinking', 'grok-4.20-beta', 'grok-imagine-1.0-fast']; - const preferred = 'grok-4.20-beta'; - try { - const res = await fetch('/v1/models', { cache: 'no-store' }); - if (!res.ok) throw new Error('models fetch failed'); - const data = await res.json(); - const items = Array.isArray(data && data.data) ? data.data : []; - const ids = items - .map(item => item && item.id) - .filter(Boolean) - .filter((id) => { - const name = String(id); - if (name.startsWith('grok-imagine')) { - return name === 'grok-imagine-1.0-fast'; - } - return !name.includes('video'); - }); - modelList = ids.length ? ids : fallback; - } catch (e) { - modelList = fallback; - } - if (modelList.includes(preferred)) { - modelValue = preferred; - } else { - modelValue = modelList[modelList.length - 1] || preferred; - } - if (modelLabel) modelLabel.textContent = modelValue; - renderModelDropdown(); - restoreSessionModel(); - } - - function showAttachmentBadge() { - if (!fileBadge || !fileName) return; - if (attachment) { - fileName.textContent = attachment.name; - fileBadge.classList.remove('hidden'); - } else { - fileBadge.classList.add('hidden'); - fileName.textContent = ''; - } - } - - function clearAttachment() { - attachment = null; - if (fileInput) fileInput.value = ''; - showAttachmentBadge(); - } - - function readFileAsDataUrl(file) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(reader.result); - reader.onerror = () => reject(new Error(t('common.fileReadFailed'))); - reader.readAsDataURL(file); - }); - } - - async function handleFileSelect(file) { - if (!file) return; - try { - const dataUrl = await readFileAsDataUrl(file); - attachment = { - name: file.name || 'file', - data: dataUrl - }; - showAttachmentBadge(); - } catch (e) { - toast(t('common.fileReadFailed'), 'error'); - } - } - - function createActionButton(label, title, onClick) { - const btn = document.createElement('button'); - btn.className = 'action-btn'; - btn.type = 'button'; - btn.textContent = label; - if (title) btn.title = title; - if (onClick) btn.addEventListener('click', onClick); - return btn; - } - - function attachAssistantActions(entry) { - if (!entry || !entry.row) return; - const actions = document.createElement('div'); - actions.className = 'message-actions'; - - const retryBtn = createActionButton(t('common.retry'), t('chat.retryTitle'), () => retryLast()); - const editBtn = createActionButton(t('chat.editAnswer'), t('chat.editAnswerTitle'), () => editMessageByRow(entry.row)); - const copyBtn = createActionButton(t('chat.copyAnswer'), t('chat.copyAnswerTitle'), () => copyToClipboard(entry.raw || '')); - const feedbackBtn = createActionButton(t('chat.feedback'), t('chat.feedbackTitle'), () => { - window.open(feedbackUrl, '_blank', 'noopener'); - }); - - actions.appendChild(retryBtn); - actions.appendChild(editBtn); - actions.appendChild(copyBtn); - actions.appendChild(feedbackBtn); - entry.row.appendChild(actions); - } - - async function copyToClipboard(text) { - if (!text) { - toast(t('chat.noContentToCopy'), 'error'); - return; - } - try { - if (navigator.clipboard && navigator.clipboard.writeText) { - await navigator.clipboard.writeText(text); - } else { - const temp = document.createElement('textarea'); - temp.value = text; - temp.style.position = 'fixed'; - temp.style.opacity = '0'; - document.body.appendChild(temp); - temp.select(); - document.execCommand('copy'); - document.body.removeChild(temp); - } - toast(t('common.copied'), 'success'); - } catch (e) { - toast(t('common.copyFailed'), 'error'); - } - } - - async function retryLast() { - if (isSending) return; - if (!messageHistory.length) return; - let lastUserIndex = -1; - for (let i = messageHistory.length - 1; i >= 0; i -= 1) { - if (messageHistory[i].role === 'user') { - lastUserIndex = i; - break; - } - } - if (lastUserIndex === -1) { - toast(t('chat.noChatToRetry'), 'error'); - return; - } - const historySlice = messageHistory.slice(0, lastUserIndex + 1); - const retrySessionId = sessionsData.activeId; - const assistantEntry = createMessage('assistant', ''); - setSendingState(true); - setStatus('connecting', t('common.sending')); - - abortController = new AbortController(); - const payload = buildPayloadFrom(historySlice); - - let headers = { 'Content-Type': 'application/json' }; - try { - const authHeader = await ensureFunctionKey(); - headers = { ...headers, ...buildAuthHeaders(authHeader) }; - } catch (e) { - // ignore auth helper failures - } - - try { - const res = await fetch(CHAT_COMPLETIONS_ENDPOINT, { - method: 'POST', - headers, - body: JSON.stringify(payload), - signal: abortController.signal - }); - - if (!res.ok) { - throw new Error(t('chat.requestFailedStatus', { status: res.status })); - } - - await handleStream(res, assistantEntry, retrySessionId); - setStatus('connected', t('common.done')); - } catch (e) { - updateMessage(assistantEntry, t('chat.requestFailedStatus', { status: e.message || e }), true); - setStatus('error', t('common.failed')); - toast(t('chat.requestFailedCheck'), 'error'); - } finally { - setSendingState(false); - abortController = null; - scrollToBottom(); - } - } - - async function sendMessage() { - if (isSending) return; - const prompt = promptInput ? promptInput.value.trim() : ''; - if (!prompt && !attachment) { - toast(t('common.enterContent'), 'error'); - return; - } - - let displayText = prompt || ''; - if (attachment) { - const label = t('chat.fileLabel') + ' ' + attachment.name; - displayText = displayText ? `${displayText}\n${label}` : label; - } - - createMessage('user', displayText, false, { editable: !attachment }); - - let content = prompt; - if (attachment) { - const blocks = []; - if (prompt) { - blocks.push({ type: 'text', text: prompt }); - } - blocks.push({ type: 'file', file: { file_data: attachment.data } }); - content = blocks; - } - - messageHistory.push({ - role: 'user', - content, - display: displayText, - hasAttachment: !!attachment, - attachmentName: attachment ? attachment.name : '' - }); - trimMessageHistory(); - if (promptInput) promptInput.value = ''; - clearAttachment(); - syncCurrentSession(); - syncSessionModel(); - updateSessionTitle(getActiveSession()); - saveSessions(); - renderSessionList(); - - const sendSessionId = sessionsData.activeId; - const assistantEntry = createMessage('assistant', ''); - setSendingState(true); - setStatus('connecting', t('common.sending')); - - abortController = new AbortController(); - const payload = buildPayload(); - - let headers = { 'Content-Type': 'application/json' }; - try { - const authHeader = await ensureFunctionKey(); - headers = { ...headers, ...buildAuthHeaders(authHeader) }; - } catch (e) { - // ignore auth helper failures - } - - try { - const res = await fetch(CHAT_COMPLETIONS_ENDPOINT, { - method: 'POST', - headers, - body: JSON.stringify(payload), - signal: abortController.signal - }); - - if (!res.ok) { - throw new Error(t('chat.requestFailedStatus', { status: res.status })); - } - - await handleStream(res, assistantEntry, sendSessionId); - setStatus('connected', t('common.done')); - } catch (e) { - if (e && e.name === 'AbortError') { - updateMessage(assistantEntry, assistantEntry.raw || t('common.stopped'), true); - if (assistantEntry.hasThink) { - const elapsed = assistantEntry.thinkElapsed || Math.max(1, Math.round((Date.now() - assistantEntry.startedAt) / 1000)); - updateThinkSummary(assistantEntry, elapsed); - } - setStatus('error', t('common.stopped')); - if (!assistantEntry.committed) { - assistantEntry.committed = true; - commitToSession(sendSessionId, assistantEntry.raw || ''); - } - } else { - updateMessage(assistantEntry, t('chat.requestFailedStatus', { status: e.message || e }), true); - setStatus('error', t('common.failed')); - toast(t('chat.requestFailedCheck'), 'error'); - } - } finally { - setSendingState(false); - abortController = null; - scrollToBottom(); - } - } - - function commitToSession(sessionId, assistantText) { - const session = sessionsData.sessions.find(s => s.id === sessionId); - if (!session) return; - session.messages.push({ role: 'assistant', content: assistantText }); - if (session.messages.length > MAX_CONTEXT_MESSAGES) { - session.messages = session.messages.slice(-MAX_CONTEXT_MESSAGES); - } - session.updatedAt = Date.now(); - updateSessionTitle(session); - if (sessionsData.activeId === sessionId) { - messageHistory = session.messages.slice(); - trimMessageHistory(); - } else { - session.unread = true; - } - saveSessions(); - renderSessionList(); - } - - async function handleStream(res, assistantEntry, targetSessionId) { - activeStreamInfo = { sessionId: targetSessionId, entry: assistantEntry }; - const reader = res.body.getReader(); - const decoder = new TextDecoder('utf-8'); - let buffer = ''; - let assistantText = ''; - - try { - while (true) { - const { value, done } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split('\n\n'); - buffer = parts.pop() || ''; - for (const part of parts) { - const lines = part.split('\n'); - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed.startsWith('data:')) continue; - const payload = trimmed.slice(5).trim(); - if (!payload) continue; - if (payload === '[DONE]') { - updateMessage(assistantEntry, assistantText, true); - if (assistantEntry.hasThink) { - const elapsed = assistantEntry.thinkElapsed || Math.max(1, Math.round((Date.now() - assistantEntry.startedAt) / 1000)); - updateThinkSummary(assistantEntry, elapsed); - } - assistantEntry.committed = true; - commitToSession(targetSessionId, assistantText); - return; - } - try { - const json = JSON.parse(payload); - const delta = json && json.choices && json.choices[0] && json.choices[0].delta - ? json.choices[0].delta.content - : ''; - if (delta) { - assistantText += delta; - if (!assistantEntry.firstTokenAt) { - assistantEntry.firstTokenAt = Date.now(); - } - if (!assistantEntry.hasThink && assistantText.includes('<think>')) { - assistantEntry.hasThink = true; - assistantEntry.thinkStartAt = Date.now(); - assistantEntry.thinkElapsed = null; - updateThinkSummary(assistantEntry, null); - } - if (assistantEntry.hasThink && assistantEntry.thinkStartAt && assistantEntry.thinkElapsed === null) { - if (assistantText.includes('</think>')) { - assistantEntry.thinkElapsed = Math.max(1, Math.round((Date.now() - assistantEntry.thinkStartAt) / 1000)); - updateThinkSummary(assistantEntry, assistantEntry.thinkElapsed); - } - } - if (sessionsData.activeId === targetSessionId) { - updateMessage(assistantEntry, assistantText, false); - } - } - } catch (e) { - // ignore parse errors - } - } - } - } - updateMessage(assistantEntry, assistantText, true); - if (assistantEntry.hasThink) { - const elapsed = assistantEntry.thinkElapsed || Math.max(1, Math.round((Date.now() - assistantEntry.startedAt) / 1000)); - updateThinkSummary(assistantEntry, elapsed); - } - assistantEntry.committed = true; - commitToSession(targetSessionId, assistantText); - } finally { - activeStreamInfo = null; - } - } - - function toggleSettings(show) { - if (!settingsPanel) return; - if (typeof show === 'boolean') { - settingsPanel.classList.toggle('hidden', !show); - return; - } - settingsPanel.classList.toggle('hidden'); - } - - function restoreSidebarState() { - try { - const raw = localStorage.getItem(SIDEBAR_STATE_KEY); - setSidebarCollapsed(raw === '1'); - } catch (e) {} - } - - function bindEvents() { - if (tempRange) tempRange.addEventListener('input', updateRangeValues); - if (topPRange) topPRange.addEventListener('input', updateRangeValues); - if (modelChip) { - modelChip.addEventListener('click', (event) => { - if (event.target.closest('.model-dropdown')) return; - event.stopPropagation(); - toggleModelDropdown(); - }); - } - if (modelDropdown) { - modelDropdown.addEventListener('click', (event) => { - const opt = event.target.closest('.model-option'); - if (!opt) return; - event.stopPropagation(); - selectModel(opt.dataset.value); - toggleModelDropdown(false); - }); - } - if (sendBtn) sendBtn.addEventListener('click', sendMessage); - if (settingsToggle) { - settingsToggle.addEventListener('click', (event) => { - event.stopPropagation(); - toggleSettings(); - }); - } - document.addEventListener('click', (event) => { - if (settingsPanel && !settingsPanel.classList.contains('hidden')) { - if (!settingsPanel.contains(event.target) && !(settingsToggle && settingsToggle.contains(event.target))) { - toggleSettings(false); - } - } - if (modelDropdown && !modelDropdown.classList.contains('hidden')) { - if (!(modelChip && modelChip.contains(event.target))) { - toggleModelDropdown(false); - } - } - }); - if (promptInput) { - let composing = false; - promptInput.addEventListener('compositionstart', () => { - composing = true; - }); - promptInput.addEventListener('compositionend', () => { - composing = false; - }); - promptInput.addEventListener('keydown', (event) => { - if (event.key === 'Enter' && !event.shiftKey) { - if (composing || event.isComposing) return; - event.preventDefault(); - sendMessage(); - } - }); - } - if (attachBtn && fileInput) { - attachBtn.addEventListener('click', () => fileInput.click()); - fileInput.addEventListener('change', () => { - if (fileInput.files && fileInput.files[0]) { - handleFileSelect(fileInput.files[0]); - } - }); - } - if (fileRemoveBtn) { - fileRemoveBtn.addEventListener('click', clearAttachment); - } - if (newChatBtn) { - newChatBtn.addEventListener('click', createSession); - } - if (collapseSidebarBtn) { - collapseSidebarBtn.addEventListener('click', toggleSidebar); - } - if (sidebarExpandBtn) { - sidebarExpandBtn.addEventListener('click', openSidebar); - } - if (sidebarToggle) { - sidebarToggle.addEventListener('click', toggleSidebar); - } - if (sidebarOverlay) { - sidebarOverlay.addEventListener('click', closeSidebar); - } - } - - updateRangeValues(); - loadModels(); - bindEvents(); - restoreSidebarState(); - - (async () => { - try { - const authResult = await ensureFunctionKey(); - if (authResult === null) { - window.location.href = '/login'; - return; - } - } catch (e) { - window.location.href = '/login'; - return; - } - loadSessions(); - })(); -})(); diff --git a/app/assets/js/webui/imagine.js b/app/assets/js/webui/imagine.js deleted file mode 100644 index 164dc2bb..00000000 --- a/app/assets/js/webui/imagine.js +++ /dev/null @@ -1,1304 +0,0 @@ -(() => { - const startBtn = document.getElementById('startBtn'); - const stopBtn = document.getElementById('stopBtn'); - const clearBtn = document.getElementById('clearBtn'); - const promptInput = document.getElementById('promptInput'); - const ratioSelect = document.getElementById('ratioSelect'); - const concurrentSelect = document.getElementById('concurrentSelect'); - const autoScrollToggle = document.getElementById('autoScrollToggle'); - const autoDownloadToggle = document.getElementById('autoDownloadToggle'); - const reverseInsertToggle = document.getElementById('reverseInsertToggle'); - const autoFilterToggle = document.getElementById('autoFilterToggle'); - const nsfwSelect = document.getElementById('nsfwSelect'); - const selectFolderBtn = document.getElementById('selectFolderBtn'); - const folderPath = document.getElementById('folderPath'); - const statusText = document.getElementById('statusText'); - const countValue = document.getElementById('countValue'); - const activeValue = document.getElementById('activeValue'); - const latencyValue = document.getElementById('latencyValue'); - const modeButtons = document.querySelectorAll('.mode-btn'); - const waterfall = document.getElementById('waterfall'); - const emptyState = document.getElementById('emptyState'); - const lightbox = document.getElementById('lightbox'); - const lightboxImg = document.getElementById('lightboxImg'); - const closeLightbox = document.getElementById('closeLightbox'); - - let wsConnections = []; - let sseConnections = []; - let imageCount = 0; - let totalLatency = 0; - let latencyCount = 0; - let lastRunId = ''; - let isRunning = false; - let connectionMode = 'ws'; - let modePreference = 'auto'; - const MODE_STORAGE_KEY = 'imagine_mode'; - let pendingFallbackTimer = null; - let currentTaskIds = []; - let directoryHandle = null; - let useFileSystemAPI = false; - let isSelectionMode = false; - let selectedImages = new Set(); - let streamSequence = 0; - const streamImageMap = new Map(); - let finalMinBytesDefault = 100000; - - function toast(message, type) { - if (typeof showToast === 'function') { - showToast(message, type); - } - } - - function setStatus(state, text) { - if (!statusText) return; - statusText.textContent = text || t('common.notConnected'); - statusText.classList.remove('connected', 'connecting', 'error'); - if (state) { - statusText.classList.add(state); - } - } - - function setButtons(connected) { - if (!startBtn || !stopBtn) return; - if (connected) { - startBtn.classList.add('hidden'); - stopBtn.classList.remove('hidden'); - } else { - startBtn.classList.remove('hidden'); - stopBtn.classList.add('hidden'); - startBtn.disabled = false; - } - } - - function updateCount(value) { - if (countValue) { - countValue.textContent = String(value); - } - } - - function updateActive() { - if (!activeValue) return; - if (connectionMode === 'sse') { - const active = sseConnections.filter(es => es && es.readyState === EventSource.OPEN).length; - activeValue.textContent = String(active); - return; - } - const active = wsConnections.filter(ws => ws && ws.readyState === WebSocket.OPEN).length; - activeValue.textContent = String(active); - } - - function setModePreference(mode, persist = true) { - if (!['auto', 'ws', 'sse'].includes(mode)) return; - modePreference = mode; - modeButtons.forEach(btn => { - if (btn.dataset.mode === mode) { - btn.classList.add('active'); - } else { - btn.classList.remove('active'); - } - }); - if (persist) { - try { - localStorage.setItem(MODE_STORAGE_KEY, mode); - } catch (e) { - // ignore - } - } - updateModeValue(); - } - - function updateModeValue() {} - - async function loadFilterDefaults() { - try { - const res = await fetch(`${FN_BASE}/imagine/config`, { cache: 'no-store' }); - if (!res.ok) return; - const data = await res.json(); - const value = parseInt(data && data.final_min_bytes, 10); - if (Number.isFinite(value) && value >= 0) { - finalMinBytesDefault = value; - } - if (nsfwSelect && typeof data.nsfw === 'boolean') { - nsfwSelect.value = data.nsfw ? 'true' : 'false'; - } - } catch (e) { - // ignore - } - } - - - function updateLatency(value) { - if (value) { - totalLatency += value; - latencyCount += 1; - const avg = Math.round(totalLatency / latencyCount); - if (latencyValue) { - latencyValue.textContent = `${avg} ms`; - } - } else { - if (latencyValue) { - latencyValue.textContent = '-'; - } - } - } - - function updateError(value) {} - - function setImageStatus(item, state, label) { - if (!item) return; - const statusEl = item.querySelector('.image-status'); - if (!statusEl) return; - statusEl.textContent = label; - statusEl.classList.remove('running', 'done', 'error'); - if (state) { - statusEl.classList.add(state); - } - } - - function isLikelyBase64(raw) { - if (!raw) return false; - if (raw.startsWith('data:')) return true; - if (raw.startsWith('http://') || raw.startsWith('https://')) return false; - const head = raw.slice(0, 16); - if (head.startsWith('/9j/') || head.startsWith('iVBOR') || head.startsWith('R0lGOD')) return true; - return /^[A-Za-z0-9+/=\s]+$/.test(raw); - } - - function inferMime(base64) { - if (!base64) return 'image/jpeg'; - if (base64.startsWith('iVBOR')) return 'image/png'; - if (base64.startsWith('/9j/')) return 'image/jpeg'; - if (base64.startsWith('R0lGOD')) return 'image/gif'; - return 'image/jpeg'; - } - - function estimateBase64Bytes(raw) { - if (!raw) return null; - if (raw.startsWith('http://') || raw.startsWith('https://')) { - return null; - } - if (raw.startsWith('/') && !isLikelyBase64(raw)) { - return null; - } - let base64 = raw; - if (raw.startsWith('data:')) { - const comma = raw.indexOf(','); - base64 = comma >= 0 ? raw.slice(comma + 1) : ''; - } - base64 = base64.replace(/\s/g, ''); - if (!base64) return 0; - let padding = 0; - if (base64.endsWith('==')) padding = 2; - else if (base64.endsWith('=')) padding = 1; - return Math.max(0, Math.floor((base64.length * 3) / 4) - padding); - } - - function getFinalMinBytes() { - return Number.isFinite(finalMinBytesDefault) && finalMinBytesDefault >= 0 ? finalMinBytesDefault : 100000; - } - - function dataUrlToBlob(dataUrl) { - const parts = (dataUrl || '').split(','); - if (parts.length < 2) return null; - const header = parts[0]; - const b64 = parts.slice(1).join(','); - const match = header.match(/data:(.*?);base64/); - const mime = match ? match[1] : 'application/octet-stream'; - try { - const byteString = atob(b64); - const ab = new ArrayBuffer(byteString.length); - const ia = new Uint8Array(ab); - for (let i = 0; i < byteString.length; i++) { - ia[i] = byteString.charCodeAt(i); - } - return new Blob([ab], { type: mime }); - } catch (e) { - return null; - } - } - - async function createImagineTask(prompt, ratio, authHeader, nsfwEnabled) { - const res = await fetch(`${FN_BASE}/imagine/start`, { - method: 'POST', - headers: { - ...buildAuthHeaders(authHeader), - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ prompt, aspect_ratio: ratio, nsfw: nsfwEnabled }) - }); - if (!res.ok) { - const text = await res.text(); - throw new Error(text || 'Failed to create task'); - } - const data = await res.json(); - return data && data.task_id ? String(data.task_id) : ''; - } - - async function createImagineTasks(prompt, ratio, concurrent, authHeader, nsfwEnabled) { - const tasks = []; - for (let i = 0; i < concurrent; i++) { - const taskId = await createImagineTask(prompt, ratio, authHeader, nsfwEnabled); - if (!taskId) { - throw new Error('Missing task id'); - } - tasks.push(taskId); - } - return tasks; - } - - async function stopImagineTasks(taskIds, authHeader) { - if (!taskIds || taskIds.length === 0) return; - try { - await fetch(`${FN_BASE}/imagine/stop`, { - method: 'POST', - headers: { - ...buildAuthHeaders(authHeader), - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ task_ids: taskIds }) - }); - } catch (e) { - // ignore - } - } - - async function saveToFileSystem(base64, filename) { - try { - if (!directoryHandle) { - return false; - } - - const mime = inferMime(base64); - const ext = mime === 'image/png' ? 'png' : 'jpg'; - const finalFilename = filename.endsWith(`.${ext}`) ? filename : `${filename}.${ext}`; - - const fileHandle = await directoryHandle.getFileHandle(finalFilename, { create: true }); - const writable = await fileHandle.createWritable(); - - // Convert base64 to blob - const byteString = atob(base64); - const ab = new ArrayBuffer(byteString.length); - const ia = new Uint8Array(ab); - for (let i = 0; i < byteString.length; i++) { - ia[i] = byteString.charCodeAt(i); - } - const blob = new Blob([ab], { type: mime }); - - await writable.write(blob); - await writable.close(); - return true; - } catch (e) { - console.error('File System API save failed:', e); - return false; - } - } - - function downloadImage(base64, filename) { - const mime = inferMime(base64); - const dataUrl = `data:${mime};base64,${base64}`; - const link = document.createElement('a'); - link.href = dataUrl; - link.download = filename; - link.style.display = 'none'; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - } - - function appendImage(base64, meta) { - if (!waterfall) return; - if (autoFilterToggle && autoFilterToggle.checked) { - const bytes = estimateBase64Bytes(base64 || ''); - const minBytes = getFinalMinBytes(); - if (bytes !== null && bytes < minBytes) { - return; - } - } - if (emptyState) { - emptyState.style.display = 'none'; - } - - const item = document.createElement('div'); - item.className = 'waterfall-item'; - - const checkbox = document.createElement('div'); - checkbox.className = 'image-checkbox'; - - const img = document.createElement('img'); - img.loading = 'lazy'; - img.decoding = 'async'; - img.alt = meta && meta.sequence ? `image-${meta.sequence}` : 'image'; - const mime = inferMime(base64); - const dataUrl = `data:${mime};base64,${base64}`; - img.src = dataUrl; - - const metaBar = document.createElement('div'); - metaBar.className = 'waterfall-meta'; - const left = document.createElement('div'); - left.textContent = meta && meta.sequence ? `#${meta.sequence}` : '#'; - const rightWrap = document.createElement('div'); - rightWrap.className = 'meta-right'; - const status = document.createElement('span'); - status.className = 'image-status done'; - status.textContent = t('common.done'); - const right = document.createElement('span'); - if (meta && meta.elapsed_ms) { - right.textContent = `${meta.elapsed_ms}ms`; - } else { - right.textContent = ''; - } - - rightWrap.appendChild(status); - rightWrap.appendChild(right); - metaBar.appendChild(left); - metaBar.appendChild(rightWrap); - - item.appendChild(checkbox); - item.appendChild(img); - item.appendChild(metaBar); - - const prompt = (meta && meta.prompt) ? String(meta.prompt) : (promptInput ? promptInput.value.trim() : ''); - item.dataset.imageUrl = dataUrl; - item.dataset.prompt = prompt || 'image'; - if (isSelectionMode) { - item.classList.add('selection-mode'); - } - - if (reverseInsertToggle && reverseInsertToggle.checked) { - waterfall.prepend(item); - } else { - waterfall.appendChild(item); - } - - if (autoScrollToggle && autoScrollToggle.checked) { - if (reverseInsertToggle && reverseInsertToggle.checked) { - window.scrollTo({ top: 0, behavior: 'smooth' }); - } else { - window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }); - } - } - - if (autoDownloadToggle && autoDownloadToggle.checked) { - const timestamp = Date.now(); - const seq = meta && meta.sequence ? meta.sequence : 'unknown'; - const ext = mime === 'image/png' ? 'png' : 'jpg'; - const filename = `imagine_${timestamp}_${seq}.${ext}`; - - if (useFileSystemAPI && directoryHandle) { - saveToFileSystem(base64, filename).catch(() => { - downloadImage(base64, filename); - }); - } else { - downloadImage(base64, filename); - } - } - } - - function upsertStreamImage(raw, meta, imageId, isFinal) { - if (!waterfall || !raw) return; - if (emptyState) { - emptyState.style.display = 'none'; - } - - if (isFinal && autoFilterToggle && autoFilterToggle.checked) { - const bytes = estimateBase64Bytes(raw); - const minBytes = getFinalMinBytes(); - if (bytes !== null && bytes < minBytes) { - const existing = imageId ? streamImageMap.get(imageId) : null; - if (existing) { - if (selectedImages.has(existing)) { - selectedImages.delete(existing); - updateSelectedCount(); - } - existing.remove(); - streamImageMap.delete(imageId); - if (imageCount > 0) { - imageCount -= 1; - updateCount(imageCount); - } - } - return; - } - } - - const isDataUrl = typeof raw === 'string' && raw.startsWith('data:'); - const looksLikeBase64 = typeof raw === 'string' && isLikelyBase64(raw); - const isHttpUrl = typeof raw === 'string' && (raw.startsWith('http://') || raw.startsWith('https://') || (raw.startsWith('/') && !looksLikeBase64)); - const mime = isDataUrl || isHttpUrl ? '' : inferMime(raw); - const dataUrl = isDataUrl || isHttpUrl ? raw : `data:${mime};base64,${raw}`; - - let item = imageId ? streamImageMap.get(imageId) : null; - let isNew = false; - if (!item) { - isNew = true; - streamSequence += 1; - const sequence = streamSequence; - - item = document.createElement('div'); - item.className = 'waterfall-item'; - - const checkbox = document.createElement('div'); - checkbox.className = 'image-checkbox'; - - const img = document.createElement('img'); - img.loading = 'lazy'; - img.decoding = 'async'; - img.alt = imageId ? `image-${imageId}` : 'image'; - img.src = dataUrl; - - const metaBar = document.createElement('div'); - metaBar.className = 'waterfall-meta'; - const left = document.createElement('div'); - left.textContent = `#${sequence}`; - const rightWrap = document.createElement('div'); - rightWrap.className = 'meta-right'; - const status = document.createElement('span'); - status.className = `image-status ${isFinal ? 'done' : 'running'}`; - status.textContent = isFinal ? t('common.done') : t('common.generating'); - const right = document.createElement('span'); - right.textContent = ''; - if (meta && meta.elapsed_ms) { - right.textContent = `${meta.elapsed_ms}ms`; - } - - rightWrap.appendChild(status); - rightWrap.appendChild(right); - metaBar.appendChild(left); - metaBar.appendChild(rightWrap); - - item.appendChild(checkbox); - item.appendChild(img); - item.appendChild(metaBar); - - const prompt = (meta && meta.prompt) ? String(meta.prompt) : (promptInput ? promptInput.value.trim() : ''); - item.dataset.imageUrl = dataUrl; - item.dataset.prompt = prompt || 'image'; - - if (isSelectionMode) { - item.classList.add('selection-mode'); - } - - if (reverseInsertToggle && reverseInsertToggle.checked) { - waterfall.prepend(item); - } else { - waterfall.appendChild(item); - } - - if (imageId) { - streamImageMap.set(imageId, item); - } - - imageCount += 1; - updateCount(imageCount); - } else { - const img = item.querySelector('img'); - if (img) { - img.src = dataUrl; - } - item.dataset.imageUrl = dataUrl; - const right = item.querySelector('.waterfall-meta .meta-right span:last-child'); - if (right && meta && meta.elapsed_ms) { - right.textContent = `${meta.elapsed_ms}ms`; - } - } - - setImageStatus(item, isFinal ? 'done' : 'running', isFinal ? t('common.done') : t('common.generating')); - updateError(''); - - if (isNew && autoScrollToggle && autoScrollToggle.checked) { - if (reverseInsertToggle && reverseInsertToggle.checked) { - window.scrollTo({ top: 0, behavior: 'smooth' }); - } else { - window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }); - } - } - - if (isFinal && autoDownloadToggle && autoDownloadToggle.checked) { - const timestamp = Date.now(); - const ext = mime === 'image/png' ? 'png' : 'jpg'; - const filename = `imagine_${timestamp}_${imageId || streamSequence}.${ext}`; - - if (useFileSystemAPI && directoryHandle) { - saveToFileSystem(raw, filename).catch(() => { - downloadImage(raw, filename); - }); - } else { - downloadImage(raw, filename); - } - } - } - - function handleMessage(raw) { - let data = null; - try { - data = JSON.parse(raw); - } catch (e) { - return; - } - if (!data || typeof data !== 'object') return; - - if (data.type === 'image_generation.partial_image' || data.type === 'image_generation.completed') { - const imageId = data.image_id || data.imageId; - const payload = data.b64_json || data.url || data.image; - if (!payload || !imageId) { - return; - } - const isFinal = data.type === 'image_generation.completed' || data.stage === 'final'; - upsertStreamImage(payload, data, imageId, isFinal); - } else if (data.type === 'image') { - imageCount += 1; - updateCount(imageCount); - updateLatency(data.elapsed_ms); - updateError(''); - appendImage(data.b64_json, data); - } else if (data.type === 'status') { - if (data.status === 'running') { - setStatus('connected', t('common.generating')); - lastRunId = data.run_id || ''; - } else if (data.status === 'stopped') { - if (data.run_id && lastRunId && data.run_id !== lastRunId) { - return; - } - setStatus('', t('common.stopped')); - } - } else if (data.type === 'error' || data.error) { - const message = data.message || (data.error && data.error.message) || t('common.generationFailed'); - const errorImageId = data.image_id || data.imageId; - if (errorImageId && streamImageMap.has(errorImageId)) { - setImageStatus(streamImageMap.get(errorImageId), 'error', t('common.failed')); - } - updateError(message); - toast(message, 'error'); - } - } - - function stopAllConnections() { - wsConnections.forEach(ws => { - if (ws && ws.readyState === WebSocket.OPEN) { - try { - ws.send(JSON.stringify({ type: 'stop' })); - } catch (e) { - // ignore - } - } - try { - ws.close(1000, 'client stop'); - } catch (e) { - // ignore - } - }); - wsConnections = []; - - sseConnections.forEach(es => { - try { - es.close(); - } catch (e) { - // ignore - } - }); - sseConnections = []; - updateActive(); - updateModeValue(); - } - - function normalizeAuthHeader(authHeader) { - if (!authHeader) return ''; - if (authHeader.startsWith('Bearer ')) { - return authHeader.slice(7).trim(); - } - return authHeader; - } - - function buildSseUrl(taskId, index, rawPublicKey) { - const httpProtocol = window.location.protocol === 'https:' ? 'https' : 'http'; - const base = `${httpProtocol}://${window.location.host}${FN_BASE}/imagine/sse`; - const params = new URLSearchParams(); - params.set('task_id', taskId); - params.set('t', String(Date.now())); - if (typeof index === 'number') { - params.set('conn', String(index)); - } - if (rawPublicKey) { - params.set('function_key', rawPublicKey); - } - return `${base}?${params.toString()}`; - } - - function startSSE(taskIds, rawPublicKey) { - connectionMode = 'sse'; - stopAllConnections(); - updateModeValue(); - - setStatus('connected', t('imagine.generatingSSE')); - setButtons(true); - toast(t('imagine.startedTasksSSE', { count: taskIds.length }), 'success'); - - for (let i = 0; i < taskIds.length; i++) { - const url = buildSseUrl(taskIds[i], i, rawPublicKey); - const es = new EventSource(url); - - es.onopen = () => { - updateActive(); - }; - - es.onmessage = (event) => { - handleMessage(event.data); - }; - - es.onerror = () => { - updateActive(); - const remaining = sseConnections.filter(e => e && e.readyState === EventSource.OPEN).length; - if (remaining === 0) { - setStatus('error', t('common.connectionError')); - setButtons(false); - isRunning = false; - startBtn.disabled = false; - updateModeValue(); - } - }; - - sseConnections.push(es); - } - } - - async function startConnection() { - const prompt = promptInput ? promptInput.value.trim() : ''; - if (!prompt) { - toast(t('common.enterPrompt'), 'error'); - return; - } - - const authHeader = await ensureFunctionKey(); - if (authHeader === null) { - toast(t('common.configurePublicKey'), 'error'); - window.location.href = '/login'; - return; - } - const rawPublicKey = normalizeAuthHeader(authHeader); - - const concurrent = concurrentSelect ? parseInt(concurrentSelect.value, 10) : 1; - const ratio = ratioSelect ? ratioSelect.value : '2:3'; - const nsfwEnabled = nsfwSelect ? nsfwSelect.value === 'true' : true; - - if (isRunning) { - toast(t('common.alreadyRunning'), 'warning'); - return; - } - - isRunning = true; - setStatus('connecting', t('common.connecting')); - startBtn.disabled = true; - - if (pendingFallbackTimer) { - clearTimeout(pendingFallbackTimer); - pendingFallbackTimer = null; - } - - let taskIds = []; - try { - taskIds = await createImagineTasks(prompt, ratio, concurrent, authHeader, nsfwEnabled); - } catch (e) { - setStatus('error', t('common.createTaskFailed')); - startBtn.disabled = false; - isRunning = false; - return; - } - currentTaskIds = taskIds; - - if (modePreference === 'sse') { - startSSE(taskIds, rawPublicKey); - return; - } - - connectionMode = 'ws'; - stopAllConnections(); - updateModeValue(); - - let opened = 0; - let fallbackDone = false; - let fallbackTimer = null; - if (modePreference === 'auto') { - fallbackTimer = setTimeout(() => { - if (!fallbackDone && opened === 0) { - fallbackDone = true; - startSSE(taskIds, rawPublicKey); - } - }, 1500); - } - pendingFallbackTimer = fallbackTimer; - - wsConnections = []; - - for (let i = 0; i < taskIds.length; i++) { - const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'; - const params = new URLSearchParams({ task_id: taskIds[i] }); - if (rawPublicKey) { - params.set('function_key', rawPublicKey); - } - const wsUrl = `${protocol}://${window.location.host}${FN_BASE}/imagine/ws?${params.toString()}`; - const ws = new WebSocket(wsUrl); - - ws.onopen = () => { - opened += 1; - updateActive(); - if (i === 0) { - setStatus('connected', t('common.generating')); - setButtons(true); - toast(t('imagine.startedTasks', { count: concurrent }), 'success'); - } - sendStart(prompt, ws); - }; - - ws.onmessage = (event) => { - handleMessage(event.data); - }; - - ws.onclose = () => { - updateActive(); - if (connectionMode !== 'ws') { - return; - } - const remaining = wsConnections.filter(w => w && w.readyState === WebSocket.OPEN).length; - if (remaining === 0 && !fallbackDone) { - setStatus('', t('common.notConnected')); - setButtons(false); - isRunning = false; - updateModeValue(); - } - }; - - ws.onerror = () => { - updateActive(); - if (modePreference === 'auto' && opened === 0 && !fallbackDone) { - fallbackDone = true; - if (fallbackTimer) { - clearTimeout(fallbackTimer); - } - startSSE(taskIds, rawPublicKey); - return; - } - if (i === 0 && wsConnections.filter(w => w && w.readyState === WebSocket.OPEN).length === 0) { - setStatus('error', t('common.connectionError')); - startBtn.disabled = false; - isRunning = false; - updateModeValue(); - } - }; - - wsConnections.push(ws); - } - } - - function sendStart(promptOverride, targetWs) { - const ws = targetWs || wsConnections[0]; - if (!ws || ws.readyState !== WebSocket.OPEN) return; - const prompt = promptOverride || (promptInput ? promptInput.value.trim() : ''); - const ratio = ratioSelect ? ratioSelect.value : '2:3'; - const nsfwEnabled = nsfwSelect ? nsfwSelect.value === 'true' : true; - const payload = { - type: 'start', - prompt, - aspect_ratio: ratio, - nsfw: nsfwEnabled - }; - ws.send(JSON.stringify(payload)); - updateError(''); - } - - async function stopConnection() { - if (pendingFallbackTimer) { - clearTimeout(pendingFallbackTimer); - pendingFallbackTimer = null; - } - - const authHeader = await ensureFunctionKey(); - if (authHeader !== null && currentTaskIds.length > 0) { - await stopImagineTasks(currentTaskIds, authHeader); - } - - stopAllConnections(); - currentTaskIds = []; - isRunning = false; - updateActive(); - updateModeValue(); - setButtons(false); - setStatus('', t('common.notConnected')); - } - - function clearImages() { - if (waterfall) { - waterfall.innerHTML = ''; - } - streamImageMap.clear(); - streamSequence = 0; - imageCount = 0; - totalLatency = 0; - latencyCount = 0; - updateCount(imageCount); - updateLatency(''); - updateError(''); - if (emptyState) { - emptyState.style.display = 'block'; - } - } - - if (startBtn) { - startBtn.addEventListener('click', () => startConnection()); - } - - if (stopBtn) { - stopBtn.addEventListener('click', () => { - stopConnection(); - }); - } - - if (clearBtn) { - clearBtn.addEventListener('click', () => clearImages()); - } - - if (promptInput) { - promptInput.addEventListener('keydown', (event) => { - if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { - event.preventDefault(); - startConnection(); - } - }); - } - - loadFilterDefaults(); - - if (ratioSelect) { - ratioSelect.addEventListener('change', () => { - if (isRunning) { - if (connectionMode === 'sse') { - stopConnection().then(() => { - setTimeout(() => startConnection(), 50); - }); - return; - } - wsConnections.forEach(ws => { - if (ws && ws.readyState === WebSocket.OPEN) { - sendStart(null, ws); - } - }); - } - }); - } - - if (modeButtons.length > 0) { - const saved = (() => { - try { - return localStorage.getItem(MODE_STORAGE_KEY); - } catch (e) { - return null; - } - })(); - if (saved) { - setModePreference(saved, false); - } else { - setModePreference('auto', false); - } - - modeButtons.forEach(btn => { - btn.addEventListener('click', () => { - const mode = btn.dataset.mode; - if (!mode) return; - setModePreference(mode); - if (isRunning) { - stopConnection().then(() => { - setTimeout(() => startConnection(), 50); - }); - } - }); - }); - } - - // File System API support check - if ('showDirectoryPicker' in window) { - if (selectFolderBtn) { - selectFolderBtn.disabled = false; - selectFolderBtn.addEventListener('click', async () => { - try { - directoryHandle = await window.showDirectoryPicker({ - mode: 'readwrite' - }); - useFileSystemAPI = true; - if (folderPath) { - folderPath.textContent = directoryHandle.name; - selectFolderBtn.style.color = '#059669'; - } - toast(t('imagine.selectFolder', { name: directoryHandle.name }), 'success'); - } catch (e) { - if (e.name !== 'AbortError') { - toast(t('imagine.selectFolderFailed'), 'error'); - } - } - }); - } - } - - // Enable/disable folder selection based on auto-download - if (autoDownloadToggle && selectFolderBtn) { - autoDownloadToggle.addEventListener('change', () => { - if (autoDownloadToggle.checked && 'showDirectoryPicker' in window) { - selectFolderBtn.disabled = false; - } else { - selectFolderBtn.disabled = true; - } - }); - } - - // Collapsible cards - 点击"连接状态"标题控制所有卡片 - const statusToggle = document.getElementById('statusToggle'); - - if (statusToggle) { - statusToggle.addEventListener('click', (e) => { - e.stopPropagation(); - const cards = document.querySelectorAll('.imagine-card-collapsible'); - const allCollapsed = Array.from(cards).every(card => card.classList.contains('collapsed')); - - cards.forEach(card => { - if (allCollapsed) { - card.classList.remove('collapsed'); - } else { - card.classList.add('collapsed'); - } - }); - }); - } - - // Batch download functionality - const batchDownloadBtn = document.getElementById('batchDownloadBtn'); - const selectionToolbar = document.getElementById('selectionToolbar'); - const toggleSelectAllBtn = document.getElementById('toggleSelectAllBtn'); - const downloadSelectedBtn = document.getElementById('downloadSelectedBtn'); - - function enterSelectionMode() { - isSelectionMode = true; - selectedImages.clear(); - selectionToolbar.classList.remove('hidden'); - - const items = document.querySelectorAll('.waterfall-item'); - items.forEach(item => { - item.classList.add('selection-mode'); - }); - - updateSelectedCount(); - } - - function exitSelectionMode() { - isSelectionMode = false; - selectedImages.clear(); - selectionToolbar.classList.add('hidden'); - - const items = document.querySelectorAll('.waterfall-item'); - items.forEach(item => { - item.classList.remove('selection-mode', 'selected'); - }); - } - - function toggleSelectionMode() { - if (isSelectionMode) { - exitSelectionMode(); - } else { - enterSelectionMode(); - } - } - - function toggleImageSelection(item) { - if (!isSelectionMode) return; - - if (item.classList.contains('selected')) { - item.classList.remove('selected'); - selectedImages.delete(item); - } else { - item.classList.add('selected'); - selectedImages.add(item); - } - - updateSelectedCount(); - } - - function updateSelectedCount() { - const countSpan = document.getElementById('selectedCount'); - if (countSpan) { - countSpan.textContent = selectedImages.size; - } - if (downloadSelectedBtn) { - downloadSelectedBtn.disabled = selectedImages.size === 0; - } - - // Update toggle select all button text - if (toggleSelectAllBtn) { - const items = document.querySelectorAll('.waterfall-item'); - const allSelected = items.length > 0 && selectedImages.size === items.length; - toggleSelectAllBtn.textContent = allSelected ? t('imagine.deselectAll') : t('imagine.selectAll'); - } - } - - function toggleSelectAll() { - const items = document.querySelectorAll('.waterfall-item'); - const allSelected = items.length > 0 && selectedImages.size === items.length; - - if (allSelected) { - // Deselect all - items.forEach(item => { - item.classList.remove('selected'); - }); - selectedImages.clear(); - } else { - // Select all - items.forEach(item => { - item.classList.add('selected'); - selectedImages.add(item); - }); - } - - updateSelectedCount(); - } - - async function downloadSelectedImages() { - if (selectedImages.size === 0) { - toast(t('imagine.noImagesSelected'), 'warning'); - return; - } - - if (typeof JSZip === 'undefined') { - toast(t('imagine.jszipFailed'), 'error'); - return; - } - - toast(t('imagine.packing', { count: selectedImages.size }), 'info'); - downloadSelectedBtn.disabled = true; - downloadSelectedBtn.textContent = t('imagine.packingBtn'); - - const zip = new JSZip(); - const imgFolder = zip.folder('images'); - let processed = 0; - - try { - for (const item of selectedImages) { - const url = item.dataset.imageUrl; - const prompt = item.dataset.prompt || 'image'; - - try { - let blob = null; - if (url && url.startsWith('data:')) { - blob = dataUrlToBlob(url); - } else if (url) { - const response = await fetch(url); - blob = await response.blob(); - } - if (!blob) { - throw new Error('empty blob'); - } - const filename = `${prompt.substring(0, 30).replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_')}_${processed + 1}.png`; - imgFolder.file(filename, blob); - processed++; - - // Update progress - downloadSelectedBtn.innerHTML = t('imagine.packingProgress', { done: processed, total: selectedImages.size }); - } catch (error) { - console.error('Failed to fetch image:', error); - } - } - - if (processed === 0) { - toast(t('imagine.noImagesDownloaded'), 'error'); - return; - } - - // Generate zip file - downloadSelectedBtn.textContent = t('imagine.generatingZip'); - const content = await zip.generateAsync({ type: 'blob' }); - - // Download zip - const link = document.createElement('a'); - link.href = URL.createObjectURL(content); - link.download = `imagine_${new Date().toISOString().slice(0, 10)}_${Date.now()}.zip`; - link.click(); - URL.revokeObjectURL(link.href); - - toast(t('imagine.packSuccess', { count: processed }), 'success'); - exitSelectionMode(); - } catch (error) { - console.error('Download failed:', error); - toast(t('imagine.packFailed'), 'error'); - } finally { - downloadSelectedBtn.disabled = false; - downloadSelectedBtn.innerHTML = `${t('imagine.download')} <span id="selectedCount" class="selected-count">${selectedImages.size}</span>`; - } - } - - if (batchDownloadBtn) { - batchDownloadBtn.addEventListener('click', toggleSelectionMode); - } - - if (toggleSelectAllBtn) { - toggleSelectAllBtn.addEventListener('click', toggleSelectAll); - } - - if (downloadSelectedBtn) { - downloadSelectedBtn.addEventListener('click', downloadSelectedImages); - } - - - // Handle image/checkbox clicks in waterfall - if (waterfall) { - waterfall.addEventListener('click', (e) => { - const item = e.target.closest('.waterfall-item'); - if (!item) return; - - if (isSelectionMode) { - // In selection mode, clicking anywhere on the item toggles selection - toggleImageSelection(item); - } else { - // In normal mode, only clicking the image opens lightbox - if (e.target.closest('.waterfall-item img')) { - const img = e.target.closest('.waterfall-item img'); - const images = getAllImages(); - const index = images.indexOf(img); - - if (index !== -1) { - updateLightbox(index); - lightbox.classList.add('active'); - } - } - } - }); - } - - // Lightbox for image preview with navigation - const lightboxPrev = document.getElementById('lightboxPrev'); - const lightboxNext = document.getElementById('lightboxNext'); - let currentImageIndex = -1; - - function getAllImages() { - return Array.from(document.querySelectorAll('.waterfall-item img')); - } - - function updateLightbox(index) { - const images = getAllImages(); - if (index < 0 || index >= images.length) return; - - currentImageIndex = index; - lightboxImg.src = images[index].src; - - // Update navigation buttons state - if (lightboxPrev) lightboxPrev.disabled = (index === 0); - if (lightboxNext) lightboxNext.disabled = (index === images.length - 1); - } - - function showPrevImage() { - if (currentImageIndex > 0) { - updateLightbox(currentImageIndex - 1); - } - } - - function showNextImage() { - const images = getAllImages(); - if (currentImageIndex < images.length - 1) { - updateLightbox(currentImageIndex + 1); - } - } - - if (lightbox && closeLightbox) { - closeLightbox.addEventListener('click', (e) => { - e.stopPropagation(); - lightbox.classList.remove('active'); - currentImageIndex = -1; - }); - - lightbox.addEventListener('click', () => { - lightbox.classList.remove('active'); - currentImageIndex = -1; - }); - - // Prevent closing when clicking on the image - if (lightboxImg) { - lightboxImg.addEventListener('click', (e) => { - e.stopPropagation(); - }); - } - - // Navigation buttons - if (lightboxPrev) { - lightboxPrev.addEventListener('click', (e) => { - e.stopPropagation(); - showPrevImage(); - }); - } - - if (lightboxNext) { - lightboxNext.addEventListener('click', (e) => { - e.stopPropagation(); - showNextImage(); - }); - } - - // Keyboard navigation - document.addEventListener('keydown', (e) => { - if (!lightbox.classList.contains('active')) return; - - if (e.key === 'Escape') { - lightbox.classList.remove('active'); - currentImageIndex = -1; - } else if (e.key === 'ArrowLeft') { - showPrevImage(); - } else if (e.key === 'ArrowRight') { - showNextImage(); - } - }); - } - - // Make floating actions draggable - const floatingActions = document.getElementById('floatingActions'); - if (floatingActions) { - let isDragging = false; - let startX, startY, initialLeft, initialTop; - - floatingActions.style.touchAction = 'none'; - - floatingActions.addEventListener('pointerdown', (e) => { - if (e.target.tagName.toLowerCase() === 'button' || e.target.closest('button')) return; - - e.preventDefault(); - isDragging = true; - floatingActions.setPointerCapture(e.pointerId); - startX = e.clientX; - startY = e.clientY; - - const rect = floatingActions.getBoundingClientRect(); - - if (!floatingActions.style.left || floatingActions.style.left === '') { - floatingActions.style.left = rect.left + 'px'; - floatingActions.style.top = rect.top + 'px'; - floatingActions.style.transform = 'none'; - floatingActions.style.bottom = 'auto'; - } - - initialLeft = parseFloat(floatingActions.style.left); - initialTop = parseFloat(floatingActions.style.top); - - floatingActions.classList.add('shadow-xl'); - }); - - document.addEventListener('pointermove', (e) => { - if (!isDragging) return; - - const dx = e.clientX - startX; - const dy = e.clientY - startY; - - floatingActions.style.left = `${initialLeft + dx}px`; - floatingActions.style.top = `${initialTop + dy}px`; - }); - - document.addEventListener('pointerup', (e) => { - if (isDragging) { - isDragging = false; - floatingActions.releasePointerCapture(e.pointerId); - floatingActions.classList.remove('shadow-xl'); - } - }); - } -})(); diff --git a/app/assets/js/webui/login.js b/app/assets/js/webui/login.js deleted file mode 100644 index ae0ec22b..00000000 --- a/app/assets/js/webui/login.js +++ /dev/null @@ -1,25 +0,0 @@ -const input = document.getElementById('function-key-input'); -if (input) input.addEventListener('keypress', e => { if (e.key === 'Enter') login(); }); - -async function requestFunctionLogin(key) { - const h = key ? { Authorization: `Bearer ${key}` } : {}; - return (await fetch(`${FN_BASE}/voice/token?voice=ara`, { headers: h })).ok; -} - -async function login() { - const key = (input ? input.value : '').trim(); - try { - const ok = await requestFunctionLogin(key); - if (ok) { await storeFunctionKey(key); window.location.href = '/chat'; } - else showToast(t('common.invalidKey'), 'error'); - } catch { showToast(t('common.connectionFailed'), 'error'); } -} - -(async () => { - try { - const stored = await getStoredFunctionKey(); - if (stored && await requestFunctionLogin(stored)) { window.location.href = '/chat'; return; } - if (stored) clearStoredFunctionKey(); - if (await requestFunctionLogin('')) window.location.href = '/chat'; - } catch {} -})(); diff --git a/app/assets/js/webui/video.js b/app/assets/js/webui/video.js deleted file mode 100644 index 298fcb13..00000000 --- a/app/assets/js/webui/video.js +++ /dev/null @@ -1,707 +0,0 @@ -(() => { - const startBtn = document.getElementById('startBtn'); - const stopBtn = document.getElementById('stopBtn'); - const clearBtn = document.getElementById('clearBtn'); - const promptInput = document.getElementById('promptInput'); - const imageUrlInput = document.getElementById('imageUrlInput'); - const imageFileInput = document.getElementById('imageFileInput'); - const imageFileName = document.getElementById('imageFileName'); - const clearImageFileBtn = document.getElementById('clearImageFileBtn'); - const selectImageFileBtn = document.getElementById('selectImageFileBtn'); - const ratioSelect = document.getElementById('ratioSelect'); - const lengthSelect = document.getElementById('lengthSelect'); - const resolutionSelect = document.getElementById('resolutionSelect'); - const presetSelect = document.getElementById('presetSelect'); - const statusText = document.getElementById('statusText'); - const progressBar = document.getElementById('progressBar'); - const progressFill = document.getElementById('progressFill'); - const progressText = document.getElementById('progressText'); - const durationValue = document.getElementById('durationValue'); - const aspectValue = document.getElementById('aspectValue'); - const lengthValue = document.getElementById('lengthValue'); - const resolutionValue = document.getElementById('resolutionValue'); - const presetValue = document.getElementById('presetValue'); - const videoEmpty = document.getElementById('videoEmpty'); - const videoStage = document.getElementById('videoStage'); - - let currentSource = null; - let currentTaskId = ''; - let isRunning = false; - let progressBuffer = ''; - let contentBuffer = ''; - let collectingContent = false; - let startAt = 0; - let fileDataUrls = []; - let elapsedTimer = null; - let lastProgress = 0; - let currentPreviewItem = null; - let previewCount = 0; - const DEFAULT_REASONING_EFFORT = 'low'; - const MAX_REFERENCE_IMAGES = 7; - - function toast(message, type) { - if (typeof showToast === 'function') { - showToast(message, type); - } - } - - function setStatus(state, text) { - if (!statusText) return; - statusText.textContent = text; - statusText.classList.remove('connected', 'connecting', 'error'); - if (state) { - statusText.classList.add(state); - } - } - - function setButtons(running) { - if (!startBtn || !stopBtn) return; - if (running) { - startBtn.classList.add('hidden'); - stopBtn.classList.remove('hidden'); - } else { - startBtn.classList.remove('hidden'); - stopBtn.classList.add('hidden'); - startBtn.disabled = false; - } - } - - function updateProgress(value) { - const safe = Math.max(0, Math.min(100, Number(value) || 0)); - lastProgress = safe; - if (progressFill) { - progressFill.style.width = `${safe}%`; - } - if (progressText) { - progressText.textContent = `${safe}%`; - } - } - - function updateMeta() { - if (aspectValue && ratioSelect) { - aspectValue.textContent = ratioSelect.value; - } - if (lengthValue && lengthSelect) { - lengthValue.textContent = `${lengthSelect.value}s`; - } - if (resolutionValue && resolutionSelect) { - resolutionValue.textContent = resolutionSelect.value; - } - if (presetValue && presetSelect) { - presetValue.textContent = presetSelect.value; - } - } - - function resetOutput(keepPreview) { - progressBuffer = ''; - contentBuffer = ''; - collectingContent = false; - lastProgress = 0; - currentPreviewItem = null; - updateProgress(0); - setIndeterminate(false); - if (!keepPreview) { - if (videoStage) { - videoStage.innerHTML = ''; - videoStage.classList.add('hidden'); - } - if (videoEmpty) { - videoEmpty.classList.remove('hidden'); - } - previewCount = 0; - } - if (durationValue) { - durationValue.textContent = t('video.elapsedTimeNone'); - } - } - - function initPreviewSlot() { - if (!videoStage) return; - previewCount += 1; - currentPreviewItem = document.createElement('div'); - currentPreviewItem.className = 'video-item'; - currentPreviewItem.dataset.index = String(previewCount); - currentPreviewItem.classList.add('is-pending'); - - const header = document.createElement('div'); - header.className = 'video-item-bar'; - - const title = document.createElement('div'); - title.className = 'video-item-title'; - title.textContent = t('video.videoTitle', { n: previewCount }); - - const actions = document.createElement('div'); - actions.className = 'video-item-actions'; - - const openBtn = document.createElement('a'); - openBtn.className = 'geist-button-outline text-xs px-3 video-open hidden'; - openBtn.target = '_blank'; - openBtn.rel = 'noopener'; - openBtn.textContent = t('video.open'); - - const downloadBtn = document.createElement('button'); - downloadBtn.className = 'geist-button-outline text-xs px-3 video-download'; - downloadBtn.type = 'button'; - downloadBtn.textContent = t('imagine.download'); - downloadBtn.disabled = true; - - actions.appendChild(openBtn); - actions.appendChild(downloadBtn); - header.appendChild(title); - header.appendChild(actions); - - const body = document.createElement('div'); - body.className = 'video-item-body'; - body.innerHTML = '<div class="video-item-placeholder">' + t('video.generatingPlaceholder') + '</div>'; - - const link = document.createElement('div'); - link.className = 'video-item-link'; - - currentPreviewItem.appendChild(header); - currentPreviewItem.appendChild(body); - currentPreviewItem.appendChild(link); - videoStage.appendChild(currentPreviewItem); - videoStage.classList.remove('hidden'); - if (videoEmpty) { - videoEmpty.classList.add('hidden'); - } - } - - function ensurePreviewSlot() { - if (!currentPreviewItem) { - initPreviewSlot(); - } - return currentPreviewItem; - } - - function updateItemLinks(item, url) { - if (!item) return; - const openBtn = item.querySelector('.video-open'); - const downloadBtn = item.querySelector('.video-download'); - const link = item.querySelector('.video-item-link'); - const safeUrl = url || ''; - item.dataset.url = safeUrl; - if (link) { - link.textContent = safeUrl; - link.classList.toggle('has-url', Boolean(safeUrl)); - } - if (openBtn) { - if (safeUrl) { - openBtn.href = safeUrl; - openBtn.classList.remove('hidden'); - } else { - openBtn.classList.add('hidden'); - openBtn.removeAttribute('href'); - } - } - if (downloadBtn) { - downloadBtn.dataset.url = safeUrl; - downloadBtn.disabled = !safeUrl; - } - if (safeUrl) { - item.classList.remove('is-pending'); - } - } - - function setIndeterminate(active) { - if (!progressBar) return; - if (active) { - progressBar.classList.add('indeterminate'); - } else { - progressBar.classList.remove('indeterminate'); - } - } - - function startElapsedTimer() { - stopElapsedTimer(); - if (!durationValue) return; - elapsedTimer = setInterval(() => { - if (!startAt) return; - const seconds = Math.max(0, Math.round((Date.now() - startAt) / 1000)); - durationValue.textContent = t('video.elapsedTime', { sec: seconds }); - }, 1000); - } - - function stopElapsedTimer() { - if (elapsedTimer) { - clearInterval(elapsedTimer); - elapsedTimer = null; - } - } - - function clearFileSelection() { - fileDataUrls = []; - if (imageFileInput) { - imageFileInput.value = ''; - } - if (imageFileName) { - imageFileName.textContent = t('video.noReferenceSelected'); - } - } - - function updateReferenceSummary(names) { - if (!imageFileName) return; - if (!names || !names.length) { - imageFileName.textContent = t('video.noReferenceSelected'); - return; - } - imageFileName.textContent = names.join('\n'); - } - - function parseReferenceUrls(value) { - return (value || '') - .split(/\r?\n/) - .map(item => item.trim()) - .filter(Boolean); - } - - function getReferenceImages() { - const rawUrls = imageUrlInput ? parseReferenceUrls(imageUrlInput.value) : []; - if (fileDataUrls.length && rawUrls.length) { - toast(t('video.referenceConflict'), 'error'); - throw new Error('invalid_reference'); - } - const images = fileDataUrls.length ? [...fileDataUrls] : rawUrls; - if (images.length > MAX_REFERENCE_IMAGES) { - toast(t('video.referenceLimit'), 'error'); - throw new Error('too_many_references'); - } - return images; - } - - function normalizeAuthHeader(authHeader) { - if (!authHeader) return ''; - if (authHeader.startsWith('Bearer ')) { - return authHeader.slice(7).trim(); - } - return authHeader; - } - - function buildSseUrl(taskId, rawPublicKey) { - const httpProtocol = window.location.protocol === 'https:' ? 'https' : 'http'; - const base = `${httpProtocol}://${window.location.host}/function/video/sse`; - const params = new URLSearchParams(); - params.set('task_id', taskId); - params.set('t', String(Date.now())); - if (rawPublicKey) { - params.set('function_key', rawPublicKey); - } - return `${base}?${params.toString()}`; - } - - async function createVideoTask(authHeader) { - const prompt = promptInput ? promptInput.value.trim() : ''; - const imageUrls = getReferenceImages(); - const res = await fetch(`${FN_BASE}/video/start`, { - method: 'POST', - headers: { - ...buildAuthHeaders(authHeader), - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - prompt, - image_urls: imageUrls, - reasoning_effort: DEFAULT_REASONING_EFFORT, - aspect_ratio: ratioSelect ? ratioSelect.value : '3:2', - video_length: lengthSelect ? parseInt(lengthSelect.value, 10) : 6, - resolution_name: resolutionSelect ? resolutionSelect.value : '480p', - preset: presetSelect ? presetSelect.value : 'normal' - }) - }); - if (!res.ok) { - const text = await res.text(); - throw new Error(text || 'Failed to create task'); - } - const data = await res.json(); - return data && data.task_id ? String(data.task_id) : ''; - } - - async function stopVideoTask(taskId, authHeader) { - if (!taskId) return; - try { - await fetch(`${FN_BASE}/video/stop`, { - method: 'POST', - headers: { - ...buildAuthHeaders(authHeader), - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ task_ids: [taskId] }) - }); - } catch (e) { - // ignore - } - } - - function extractVideoInfo(buffer) { - if (!buffer) return null; - if (buffer.includes('<video')) { - const matches = buffer.match(/<video[\s\S]*?<\/video>/gi); - if (matches && matches.length) { - return { html: matches[matches.length - 1] }; - } - } - const mdMatches = buffer.match(/\[video\]\(([^)]+)\)/g); - if (mdMatches && mdMatches.length) { - const last = mdMatches[mdMatches.length - 1]; - const urlMatch = last.match(/\[video\]\(([^)]+)\)/); - if (urlMatch) { - return { url: urlMatch[1] }; - } - } - const urlMatches = buffer.match(/https?:\/\/[^\s<)]+/g); - if (urlMatches && urlMatches.length) { - return { url: urlMatches[urlMatches.length - 1] }; - } - return null; - } - - function renderVideoFromHtml(html) { - const container = ensurePreviewSlot(); - if (!container) return; - const body = container.querySelector('.video-item-body'); - if (!body) return; - body.innerHTML = html; - const videoEl = body.querySelector('video'); - let videoUrl = ''; - if (videoEl) { - videoEl.controls = true; - videoEl.preload = 'metadata'; - const source = videoEl.querySelector('source'); - if (source && source.getAttribute('src')) { - videoUrl = source.getAttribute('src'); - } else if (videoEl.getAttribute('src')) { - videoUrl = videoEl.getAttribute('src'); - } - } - updateItemLinks(container, videoUrl); - } - - function renderVideoFromUrl(url) { - const container = ensurePreviewSlot(); - if (!container) return; - const safeUrl = url || ''; - const body = container.querySelector('.video-item-body'); - if (!body) return; - body.innerHTML = `\n <video controls preload="metadata">\n <source src="${safeUrl}" type="video/mp4">\n </video>\n `; - updateItemLinks(container, safeUrl); - } - - function handleDelta(text) { - if (!text) return; - if (text.includes('<think>') || text.includes('</think>')) { - return; - } - if (text.includes('超分辨率') || text.includes('super resolution')) { - setStatus('connecting', t('video.superResolutionInProgress')); - setIndeterminate(true); - if (progressText) { - progressText.textContent = t('video.superResolutionInProgress'); - } - return; - } - - if (!collectingContent) { - const maybeVideo = text.includes('<video') || text.includes('[video](') || text.includes('http://') || text.includes('https://'); - if (maybeVideo) { - collectingContent = true; - } - } - - if (collectingContent) { - contentBuffer += text; - const info = extractVideoInfo(contentBuffer); - if (info) { - if (info.html) { - renderVideoFromHtml(info.html); - } else if (info.url) { - renderVideoFromUrl(info.url); - } - } - return; - } - - progressBuffer += text; - const roundMatches = [...progressBuffer.matchAll(/\[round=(\d+)\/(\d+)\]\s*progress=([0-9]+(?:\.[0-9]+)?)%/g)]; - if (roundMatches.length) { - const last = roundMatches[roundMatches.length - 1]; - const round = parseInt(last[1], 10); - const total = parseInt(last[2], 10); - const value = parseFloat(last[3]); - setIndeterminate(false); - updateProgress(value); - if (progressText && Number.isFinite(round) && Number.isFinite(total) && total > 0) { - progressText.textContent = `${Math.round(value)}% · ${round}/${total}`; - } - progressBuffer = progressBuffer.slice(Math.max(0, progressBuffer.length - 300)); - return; - } - - const genericProgressMatches = [...progressBuffer.matchAll(/progress=([0-9]+(?:\.[0-9]+)?)%/g)]; - if (genericProgressMatches.length) { - const last = genericProgressMatches[genericProgressMatches.length - 1]; - const value = parseFloat(last[1]); - setIndeterminate(false); - updateProgress(value); - progressBuffer = progressBuffer.slice(Math.max(0, progressBuffer.length - 240)); - return; - } - - const matches = [...progressBuffer.matchAll(/进度\s*(\d+)%/g)]; - if (matches.length) { - const last = matches[matches.length - 1]; - const value = parseInt(last[1], 10); - setIndeterminate(false); - updateProgress(value); - progressBuffer = progressBuffer.slice(Math.max(0, progressBuffer.length - 200)); - } - } - - function closeSource() { - if (currentSource) { - try { - currentSource.close(); - } catch (e) { - // ignore - } - currentSource = null; - } - } - - async function startConnection() { - const prompt = promptInput ? promptInput.value.trim() : ''; - if (!prompt) { - toast(t('common.enterPrompt'), 'error'); - return; - } - - if (isRunning) { - toast(t('video.alreadyGenerating'), 'warning'); - return; - } - - const authHeader = await ensureFunctionKey(); - if (authHeader === null) { - toast(t('common.configurePublicKey'), 'error'); - window.location.href = '/login'; - return; - } - - isRunning = true; - startBtn.disabled = true; - updateMeta(); - resetOutput(true); - initPreviewSlot(); - setStatus('connecting', t('common.connecting')); - - let taskId = ''; - try { - taskId = await createVideoTask(authHeader); - } catch (e) { - setStatus('error', t('common.createTaskFailed')); - startBtn.disabled = false; - isRunning = false; - return; - } - - currentTaskId = taskId; - startAt = Date.now(); - setStatus('connected', t('common.generating')); - setButtons(true); - setIndeterminate(true); - startElapsedTimer(); - - const rawPublicKey = normalizeAuthHeader(authHeader); - const url = buildSseUrl(taskId, rawPublicKey); - closeSource(); - const es = new EventSource(url); - currentSource = es; - - es.onopen = () => { - setStatus('connected', t('common.generating')); - }; - - es.onmessage = (event) => { - if (!event || !event.data) return; - if (event.data === '[DONE]') { - finishRun(); - return; - } - let payload = null; - try { - payload = JSON.parse(event.data); - } catch (e) { - return; - } - if (payload && payload.error) { - toast(payload.error, 'error'); - setStatus('error', t('common.generationFailed')); - finishRun(true); - return; - } - const choice = payload.choices && payload.choices[0]; - const delta = choice && choice.delta ? choice.delta : null; - if (delta && delta.content) { - handleDelta(delta.content); - } - if (choice && choice.finish_reason === 'stop') { - finishRun(); - } - }; - - es.onerror = () => { - if (!isRunning) return; - setStatus('error', t('common.connectionError')); - finishRun(true); - }; - } - - async function stopConnection() { - const authHeader = await ensureFunctionKey(); - if (authHeader !== null) { - await stopVideoTask(currentTaskId, authHeader); - } - closeSource(); - isRunning = false; - currentTaskId = ''; - stopElapsedTimer(); - setButtons(false); - setStatus('', t('common.notConnected')); - } - - function finishRun(hasError) { - if (!isRunning) return; - closeSource(); - isRunning = false; - setButtons(false); - stopElapsedTimer(); - if (!hasError) { - setStatus('connected', t('common.done')); - setIndeterminate(false); - updateProgress(100); - } - if (durationValue && startAt) { - const seconds = Math.max(0, Math.round((Date.now() - startAt) / 1000)); - durationValue.textContent = t('video.elapsedTime', { sec: seconds }); - } - } - - if (startBtn) { - startBtn.addEventListener('click', () => startConnection()); - } - - if (stopBtn) { - stopBtn.addEventListener('click', () => stopConnection()); - } - - if (clearBtn) { - clearBtn.addEventListener('click', () => resetOutput()); - } - - if (videoStage) { - videoStage.addEventListener('click', async (event) => { - const target = event.target; - if (!(target instanceof HTMLElement)) return; - if (!target.classList.contains('video-download')) return; - event.preventDefault(); - const item = target.closest('.video-item'); - if (!item) return; - const url = item.dataset.url || target.dataset.url || ''; - const index = item.dataset.index || ''; - if (!url) return; - try { - const response = await fetch(url, { mode: 'cors' }); - if (!response.ok) { - throw new Error('download_failed'); - } - const blob = await response.blob(); - const blobUrl = URL.createObjectURL(blob); - const anchor = document.createElement('a'); - anchor.href = blobUrl; - anchor.download = index ? `grok_video_${index}.mp4` : 'grok_video.mp4'; - document.body.appendChild(anchor); - anchor.click(); - anchor.remove(); - URL.revokeObjectURL(blobUrl); - } catch (e) { - toast(t('video.downloadFailed'), 'error'); - } - }); - } - - if (imageFileInput) { - imageFileInput.addEventListener('change', () => { - const files = imageFileInput.files ? Array.from(imageFileInput.files) : []; - if (!files.length) { - clearFileSelection(); - return; - } - if (files.length > MAX_REFERENCE_IMAGES) { - clearFileSelection(); - toast(t('video.referenceLimit'), 'error'); - return; - } - if (imageUrlInput && imageUrlInput.value.trim()) { - imageUrlInput.value = ''; - } - Promise.all(files.map(file => new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - if (typeof reader.result === 'string') { - resolve({ name: file.name, data: reader.result }); - } else { - reject(new Error('read_failed')); - } - }; - reader.onerror = () => reject(new Error('read_failed')); - reader.readAsDataURL(file); - }))).then(items => { - fileDataUrls = items.map(item => item.data); - updateReferenceSummary(items.map((item, index) => `${index + 1}. ${item.name}`)); - }).catch(() => { - fileDataUrls = []; - toast(t('common.fileReadFailed'), 'error'); - updateReferenceSummary([]); - }); - }); - } - - if (selectImageFileBtn && imageFileInput) { - selectImageFileBtn.addEventListener('click', () => { - imageFileInput.click(); - }); - } - - if (clearImageFileBtn) { - clearImageFileBtn.addEventListener('click', () => { - clearFileSelection(); - }); - } - - if (imageUrlInput) { - imageUrlInput.addEventListener('input', () => { - const urls = parseReferenceUrls(imageUrlInput.value); - if (urls.length > MAX_REFERENCE_IMAGES) { - toast(t('video.referenceLimit'), 'error'); - } - if (imageUrlInput.value.trim() && fileDataUrls.length) { - clearFileSelection(); - } - if (urls.length) { - updateReferenceSummary(urls.map((url, index) => `${index + 1}. ${url}`)); - } else if (!fileDataUrls.length) { - updateReferenceSummary([]); - } - }); - } - - if (promptInput) { - promptInput.addEventListener('keydown', (event) => { - if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { - event.preventDefault(); - startConnection(); - } - }); - } - - updateMeta(); -})(); diff --git a/app/assets/js/webui/voice.js b/app/assets/js/webui/voice.js deleted file mode 100644 index 31a645b0..00000000 --- a/app/assets/js/webui/voice.js +++ /dev/null @@ -1,96 +0,0 @@ -/* Voice — LiveKit session, updated API paths */ -(() => { - let Room, createLocalTracks, RoomEvent, Track, room = null, visualizerTimer = null; - const $ = id => document.getElementById(id); - const startBtn=$('startBtn'), stopBtn=$('stopBtn'), statusText=$('statusText'), - logContainer=$('log'), voiceSelect=$('voiceSelect'), personalitySelect=$('personalitySelect'), - speedRange=$('speedRange'), speedValue=$('speedValue'), statusVoice=$('statusVoice'), - statusPersonality=$('statusPersonality'), statusSpeed=$('statusSpeed'), - audioRoot=$('audioRoot'), copyLogBtn=$('copyLogBtn'), clearLogBtn=$('clearLogBtn'), - visualizer=$('visualizer'); - - function log(msg, level='info') { - if (!logContainer) return; - const p = document.createElement('p'); - p.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`; - if (level === 'error') p.classList.add('log-error'); - else if (level === 'warn') p.classList.add('log-warn'); - logContainer.prepend(p); - } - function toast(msg, type) { if (typeof showToast === 'function') showToast(msg, type); else log(msg, type === 'error' ? 'error' : 'info'); } - function setStatus(state, text) { if (!statusText) return; statusText.textContent = text; statusText.className = 'status-text' + (state ? ' ' + state : ''); } - function setButtons(connected) { startBtn?.classList.toggle('hidden', connected); stopBtn?.classList.toggle('hidden', !connected); if (!connected && startBtn) startBtn.disabled = false; } - function updateMeta() { if (statusVoice) statusVoice.textContent = voiceSelect.value; if (statusPersonality) statusPersonality.textContent = personalitySelect.value; if (statusSpeed) statusSpeed.textContent = speedRange.value + 'x'; } - - function initLK() { const lk = window.LiveKitClient || window.LivekitClient; if (!lk) return false; Room=lk.Room; createLocalTracks=lk.createLocalTracks; RoomEvent=lk.RoomEvent; Track=lk.Track; return true; } - function ensureLK() { if (Room) return true; if (!initLK()) { log(t('voice.livekitSDKError'),'error'); toast(t('voice.livekitLoadFailed'),'error'); return false; } return true; } - - async function startSession() { - if (!ensureLK()) return; - const auth = await ensureFunctionKey(); - if (auth === null) { toast(t('common.configurePublicKey'),'error'); window.location.href='/login'; return; } - startBtn.disabled = true; updateMeta(); setStatus('connecting', t('voice.connectingStatus')); log(t('voice.fetchingToken')); - const params = new URLSearchParams({ voice: voiceSelect.value, personality: personalitySelect.value, speed: speedRange.value }); - try { - const res = await fetch(`${FN_BASE}/voice/token?${params}`, { headers: buildAuthHeaders(auth) }); - if (!res.ok) throw new Error(t('voice.fetchTokenFailed', { status: res.status })); - const { token, url } = await res.json(); - log(`${t('voice.fetchTokenSuccess')} (${voiceSelect.value}, ${personalitySelect.value}, ${speedRange.value}x)`); - room = new Room({ adaptiveStream: true, dynacast: true }); - room.on(RoomEvent.ParticipantConnected, p => log(t('voice.participantConnected', { identity: p.identity }))); - room.on(RoomEvent.ParticipantDisconnected, p => log(t('voice.participantDisconnected', { identity: p.identity }))); - room.on(RoomEvent.TrackSubscribed, track => { - log(t('voice.trackSubscribed', { kind: track.kind })); - if (track.kind === Track.Kind.Audio) { const el = track.attach(); (audioRoot || document.body).appendChild(el); } - }); - room.on(RoomEvent.Disconnected, () => { log(t('voice.disconnected')); resetUI(); }); - await room.connect(url, token); - log(t('voice.connectedToServer')); setStatus('connected', t('voice.inCall')); setButtons(true); - log(t('voice.openingMic')); - const tracks = await createLocalTracks({ audio: true, video: false }); - for (const tr of tracks) await room.localParticipant.publishTrack(tr); - log(t('voice.voiceEnabled')); toast(t('voice.voiceConnected'), 'success'); - } catch (err) { - const msg = err?.message || t('common.connectionFailed'); - log(t('voice.errorPrefix', { msg }), 'error'); toast(msg, 'error'); - setStatus('error', t('common.connectionError')); startBtn.disabled = false; - } - } - - async function stopSession() { if (room) await room.disconnect(); resetUI(); } - function resetUI() { setStatus('', t('common.notConnected')); setButtons(false); if (audioRoot) audioRoot.innerHTML = ''; } - - speedRange?.addEventListener('input', e => { - speedValue.textContent = Number(e.target.value).toFixed(1); - const pct = ((e.target.value - speedRange.min) / (speedRange.max - speedRange.min)) * 100; - speedRange.style.setProperty('--range-progress', pct + '%'); - updateMeta(); - }); - voiceSelect?.addEventListener('change', updateMeta); - personalitySelect?.addEventListener('change', updateMeta); - startBtn?.addEventListener('click', startSession); - stopBtn?.addEventListener('click', stopSession); - copyLogBtn?.addEventListener('click', async () => { - const lines = Array.from(logContainer.querySelectorAll('p')).map(p => p.textContent).join('\n'); - try { await navigator.clipboard.writeText(lines); toast(t('voice.logCopied'),'success'); } catch { toast(t('voice.copyLogFailed'),'error'); } - }); - clearLogBtn?.addEventListener('click', () => { if (logContainer) logContainer.innerHTML = ''; }); - - // Init - speedValue.textContent = Number(speedRange.value).toFixed(1); - { const pct = ((speedRange.value - speedRange.min) / (speedRange.max - speedRange.min)) * 100; speedRange.style.setProperty('--range-progress', pct + '%'); } - - function buildBars() { - if (!visualizer) return; - visualizer.innerHTML = ''; - const n = Math.max(36, Math.floor(visualizer.offsetWidth / 7)); - for (let i = 0; i < n; i++) { const b = document.createElement('div'); b.className = 'bar'; visualizer.appendChild(b); } - } - window.addEventListener('resize', buildBars); - buildBars(); updateMeta(); setStatus('', t('common.notConnected')); - visualizerTimer = setInterval(() => { - visualizer?.querySelectorAll('.bar').forEach(b => { - b.style.height = statusText?.classList.contains('connected') ? `${Math.random()*32+6}px` : '6px'; - }); - }, 150); -})(); diff --git a/app/control/account/__init__.py b/app/control/account/__init__.py index 2901f746..d0c8551b 100644 --- a/app/control/account/__init__.py +++ b/app/control/account/__init__.py @@ -16,6 +16,7 @@ from .repository import AccountRepository from .state_machine import AccountFeedback, StatePolicy, apply_feedback, clear_failures, derive_status, is_selectable from .quota_defaults import BASIC_QUOTA_DEFAULTS, SUPER_QUOTA_DEFAULTS, default_quota_set from .refresh import AccountRefreshService, RefreshResult +from .runtime import get_refresh_service, set_refresh_service from .scheduler import AccountRefreshScheduler, get_account_refresh_scheduler from .backends.factory import create_repository @@ -30,6 +31,7 @@ __all__ = [ "derive_status", "is_selectable", "BASIC_QUOTA_DEFAULTS", "SUPER_QUOTA_DEFAULTS", "default_quota_set", "AccountRefreshService", "RefreshResult", + "get_refresh_service", "set_refresh_service", "AccountRefreshScheduler", "get_account_refresh_scheduler", "create_repository", ] diff --git a/app/control/account/backends/factory.py b/app/control/account/backends/factory.py index a8fbbc0b..e4d26981 100644 --- a/app/control/account/backends/factory.py +++ b/app/control/account/backends/factory.py @@ -1,18 +1,21 @@ -"""Account repository factory — selects the backend from configuration.""" - -from __future__ import annotations +"""Account repository factory — selects the backend from startup env.""" +import os from pathlib import Path from typing import Any +from urllib.parse import urlsplit, urlunsplit -from app.platform.config.snapshot import get_config from ..repository import AccountRepository +_DEFAULT_LOCAL_PATH = "data/accounts.db" +_DEFAULT_REDIS_URL = "redis://localhost:6379/0" +_SUPPORTED_BACKENDS = {"local", "redis", "mysql", "postgresql"} + def create_repository() -> AccountRepository: """Instantiate the configured account storage backend. - Config key: ``account.storage`` (default: ``"local"``) + Startup env: ``ACCOUNT_STORAGE`` (default: ``"local"``) Supported values: ``local`` — SQLite (default, single-process) @@ -20,40 +23,96 @@ def create_repository() -> AccountRepository: ``mysql`` — MySQL via asyncmy / SQLAlchemy ``postgresql`` — PostgreSQL via asyncpg / SQLAlchemy """ - backend = get_config("account.storage", "local").strip().lower() + backend = get_repository_backend() if backend == "local": return _make_local() if backend == "redis": return _make_redis() - if backend in ("mysql", "mariadb"): + if backend == "mysql": return _make_sql("mysql") - if backend in ("postgresql", "postgres", "pgsql"): + if backend == "postgresql": return _make_sql("postgresql") raise ValueError(f"Unknown account storage backend: {backend!r}") +def describe_repository_target() -> tuple[str, str]: + """Return current storage backend and a log-safe target description.""" + backend = get_repository_backend() + + if backend == "local": + return "local", str(_resolve_local_db_path()) + if backend == "redis": + return "redis", _redact_url(_get_env("ACCOUNT_REDIS_URL", _DEFAULT_REDIS_URL)) + if backend == "mysql": + return "mysql", _redact_url(_get_env("ACCOUNT_MYSQL_URL")) + if backend == "postgresql": + return "postgresql", _redact_url(_get_env("ACCOUNT_POSTGRESQL_URL")) + return backend, "<unknown>" + + # --------------------------------------------------------------------------- # Backend constructors # --------------------------------------------------------------------------- +def get_repository_backend() -> str: + """Return the configured account storage backend from startup env.""" + backend = _get_env("ACCOUNT_STORAGE", "local").lower() + if backend not in _SUPPORTED_BACKENDS: + raise ValueError(f"Unknown account storage backend: {backend!r}") + return backend + + +def _get_env(name: str, default: str = "") -> str: + value = os.getenv(name) + if value is None: + return default + value = value.strip() + return value or default + + +def _resolve_local_db_path() -> Path: + path_str = _get_env("ACCOUNT_LOCAL_PATH", _DEFAULT_LOCAL_PATH) + db_path = Path(path_str) + if not db_path.is_absolute(): + db_path = Path(__file__).resolve().parents[4] / db_path + return db_path + + +def _redact_url(url: Any) -> str: + raw = str(url or "").strip() + if not raw: + return "<empty>" + try: + parts = urlsplit(raw) + except Exception: + return raw + if not parts.scheme: + return raw + hostname = parts.hostname or "" + if parts.port: + hostname = f"{hostname}:{parts.port}" + if parts.username: + auth = f"{parts.username}:***@" + elif parts.password: + auth = "***@" + else: + auth = "" + return urlunsplit((parts.scheme, f"{auth}{hostname}", parts.path, parts.query, parts.fragment)) + + def _make_local() -> AccountRepository: from .local import LocalAccountRepository - path_str = get_config("account.local.path", "data/accounts.db") - db_path = Path(path_str) - if not db_path.is_absolute(): - # Resolve relative to project root. - db_path = Path(__file__).resolve().parents[5] / db_path - return LocalAccountRepository(db_path) + return LocalAccountRepository(_resolve_local_db_path()) def _make_redis() -> AccountRepository: from redis.asyncio import Redis from .redis import RedisAccountRepository - url = get_config("account.redis.url", "redis://localhost:6379/0") + url = _get_env("ACCOUNT_REDIS_URL", _DEFAULT_REDIS_URL) r = Redis.from_url(url, decode_responses=False) return RedisAccountRepository(r) @@ -62,12 +121,12 @@ def _make_sql(dialect: str) -> AccountRepository: from .sql import SqlAccountRepository, create_mysql_engine, create_pgsql_engine if dialect == "mysql": - url = get_config("account.mysql.url", "") + url = _get_env("ACCOUNT_MYSQL_URL") engine = create_mysql_engine(url) else: - url = get_config("account.postgresql.url", "") + url = _get_env("ACCOUNT_POSTGRESQL_URL") engine = create_pgsql_engine(url) return SqlAccountRepository(engine, dialect=dialect) -__all__ = ["create_repository"] +__all__ = ["create_repository", "describe_repository_target", "get_repository_backend"] diff --git a/app/control/account/backends/local.py b/app/control/account/backends/local.py index a90e182d..974ad9b9 100644 --- a/app/control/account/backends/local.py +++ b/app/control/account/backends/local.py @@ -1,7 +1,5 @@ """SQLite account repository (WAL mode, single-process default backend).""" -from __future__ import annotations - import asyncio import json import sqlite3 @@ -21,7 +19,7 @@ from ..models import ( ) from ..quota_defaults import default_quota_set -_SCHEMA_VERSION = 2 +_SCHEMA_VERSION = 3 _TBL = "accounts" _META = "account_meta" @@ -67,6 +65,7 @@ class LocalAccountRepository: quota_auto TEXT NOT NULL DEFAULT '{{}}', quota_fast TEXT NOT NULL DEFAULT '{{}}', quota_expert TEXT NOT NULL DEFAULT '{{}}', + quota_heavy TEXT NOT NULL DEFAULT '{{}}', usage_use_count INTEGER NOT NULL DEFAULT 0, usage_fail_count INTEGER NOT NULL DEFAULT 0, usage_sync_count INTEGER NOT NULL DEFAULT 0, @@ -87,6 +86,21 @@ class LocalAccountRepository: CREATE INDEX IF NOT EXISTS idx_acc_deleted ON {_TBL} (deleted_at) WHERE deleted_at IS NOT NULL; """) + # Incremental schema migrations. + ver_row = conn.execute( + f"SELECT CAST(value AS INTEGER) FROM {_META} WHERE key = 'schema_version'" + ).fetchone() + ver = int(ver_row[0]) if ver_row else 1 + if ver < 3: + try: + conn.execute( + f"ALTER TABLE {_TBL} ADD COLUMN quota_heavy TEXT NOT NULL DEFAULT '{{}}'" + ) + except Exception: + pass # Column already exists in partial migrations. + conn.execute( + f"UPDATE {_META} SET value = '3' WHERE key = 'schema_version'" + ) conn.commit() def _bump_revision(self, conn: sqlite3.Connection) -> int: @@ -108,10 +122,13 @@ class LocalAccountRepository: def _row_to_record(row: sqlite3.Row) -> AccountRecord: d = dict(row) d["tags"] = json.loads(d.get("tags") or "[]") + heavy_raw = d.pop("quota_heavy", "{}") or "{}" + heavy_dict = json.loads(heavy_raw) d["quota"] = { "auto": json.loads(d.pop("quota_auto", "{}") or "{}"), "fast": json.loads(d.pop("quota_fast", "{}") or "{}"), "expert": json.loads(d.pop("quota_expert", "{}") or "{}"), + **({"heavy": heavy_dict} if heavy_dict else {}), } d["ext"] = json.loads(d.get("ext") or "{}") return AccountRecord.model_validate(d) @@ -129,6 +146,7 @@ class LocalAccountRepository: "quota_auto": json.dumps(qs.auto.to_dict()), "quota_fast": json.dumps(qs.fast.to_dict()), "quota_expert": json.dumps(qs.expert.to_dict()), + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", "usage_use_count": record.usage_use_count, "usage_fail_count": record.usage_fail_count, "usage_sync_count": record.usage_sync_count, @@ -156,21 +174,24 @@ class LocalAccountRepository: token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token except Exception: continue - qs = default_quota_set(item.pool) + pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic" + qs = default_quota_set(pool) conn.execute( f""" INSERT INTO {_TBL} ( token, pool, status, created_at, updated_at, - tags, quota_auto, quota_fast, quota_expert, + tags, quota_auto, quota_fast, quota_expert, quota_heavy, usage_use_count, usage_fail_count, usage_sync_count, ext, revision ) VALUES ( :token, :pool, 'active', :ts, :ts, - :tags, :qa, :qf, :qe, + :tags, :qa, :qf, :qe, :qh, 0, 0, 0, :ext, :rev ) ON CONFLICT(token) DO UPDATE SET pool = excluded.pool, + status = 'active', + deleted_at = NULL, updated_at = excluded.updated_at, tags = excluded.tags, ext = excluded.ext, @@ -178,12 +199,13 @@ class LocalAccountRepository: """, { "token": token, - "pool": item.pool if item.pool in ("basic", "super") else "basic", + "pool": pool, "ts": ts, "tags": json.dumps(item.tags), "qa": json.dumps(qs.auto.to_dict()), "qf": json.dumps(qs.fast.to_dict()), "qe": json.dumps(qs.expert.to_dict()), + "qh": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", "ext": json.dumps(item.ext), "rev": revision, }, @@ -211,6 +233,8 @@ class LocalAccountRepository: sets: dict[str, Any] = {"updated_at": ts, "revision": revision} + if patch.pool is not None: + sets["pool"] = patch.pool if patch.status is not None: sets["status"] = patch.status.value if patch.state_reason is not None: @@ -241,6 +265,8 @@ class LocalAccountRepository: sets["quota_fast"] = json.dumps(patch.quota_fast) if patch.quota_expert is not None: sets["quota_expert"] = json.dumps(patch.quota_expert) + if patch.quota_heavy is not None: + sets["quota_heavy"] = json.dumps(patch.quota_heavy) # Tags. tags = list(record.tags) diff --git a/app/control/account/backends/redis.py b/app/control/account/backends/redis.py index 00c0a8d8..5fc0a86b 100644 --- a/app/control/account/backends/redis.py +++ b/app/control/account/backends/redis.py @@ -7,8 +7,6 @@ Layout: accounts:revision_log — ZSET token → revision (for scan_changes) """ -from __future__ import annotations - import json from typing import Any @@ -68,6 +66,7 @@ class RedisAccountRepository: "quota_auto": json.dumps(qs.auto.to_dict()), "quota_fast": json.dumps(qs.fast.to_dict()), "quota_expert": json.dumps(qs.expert.to_dict()), + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", "usage_use_count": str(record.usage_use_count), "usage_fail_count": str(record.usage_fail_count), "usage_sync_count": str(record.usage_sync_count), @@ -103,6 +102,9 @@ class RedisAccountRepository: "auto": json.loads(_s("quota_auto") or "{}"), "fast": json.loads(_s("quota_fast") or "{}"), "expert": json.loads(_s("quota_expert") or "{}"), + **({ + "heavy": json.loads(_s("quota_heavy")) + } if _s("quota_heavy") and _s("quota_heavy") != "{}" else {}), }, "usage_use_count": int(_s("usage_use_count") or 0), "usage_fail_count": int(_s("usage_fail_count") or 0), @@ -205,7 +207,7 @@ class RedisAccountRepository: token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token except Exception: continue - pool = item.pool if item.pool in ("basic", "super") else "basic" + pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic" qs = default_quota_set(pool) ts = now_ms() record = AccountRecord( @@ -259,12 +261,16 @@ class RedisAccountRepository: updates["last_sync_at"] = str(patch.last_sync_at) if patch.last_clear_at is not None: updates["last_clear_at"] = str(patch.last_clear_at) + if patch.pool is not None: + updates["pool"] = patch.pool if patch.quota_auto is not None: updates["quota_auto"] = json.dumps(patch.quota_auto) if patch.quota_fast is not None: updates["quota_fast"] = json.dumps(patch.quota_fast) if patch.quota_expert is not None: updates["quota_expert"] = json.dumps(patch.quota_expert) + if patch.quota_heavy is not None: + updates["quota_heavy"] = json.dumps(patch.quota_heavy) # Usage counters. if patch.usage_use_delta is not None: diff --git a/app/control/account/backends/sql.py b/app/control/account/backends/sql.py index b33c8850..8ee3060c 100644 --- a/app/control/account/backends/sql.py +++ b/app/control/account/backends/sql.py @@ -4,8 +4,6 @@ Both dialects share the same table schema and query logic; only the DDL fragments and upsert syntax differ. """ -from __future__ import annotations - import json from typing import Any @@ -41,6 +39,7 @@ accounts_table = sa.Table( sa.Column("quota_auto", sa.Text, nullable=False, default="{}"), sa.Column("quota_fast", sa.Text, nullable=False, default="{}"), sa.Column("quota_expert", sa.Text, nullable=False, default="{}"), + sa.Column("quota_heavy", sa.Text, nullable=False, default="{}"), sa.Column("usage_use_count", sa.Integer, nullable=False, default=0), sa.Column("usage_fail_count", sa.Integer, nullable=False, default=0), sa.Column("usage_sync_count", sa.Integer, nullable=False, default=0), @@ -66,10 +65,13 @@ meta_table = sa.Table( def _row_to_record(row: Any) -> AccountRecord: d = dict(row._mapping) d["tags"] = json.loads(d.get("tags") or "[]") + heavy_raw = d.pop("quota_heavy", "{}") or "{}" + heavy_dict = json.loads(heavy_raw) d["quota"] = { "auto": json.loads(d.pop("quota_auto", "{}") or "{}"), "fast": json.loads(d.pop("quota_fast", "{}") or "{}"), "expert": json.loads(d.pop("quota_expert", "{}") or "{}"), + **({"heavy": heavy_dict} if heavy_dict else {}), } d["ext"] = json.loads(d.get("ext") or "{}") return AccountRecord.model_validate(d) @@ -203,7 +205,7 @@ class SqlAccountRepository: token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token except Exception: continue - pool = item.pool if item.pool in ("basic", "super") else "basic" + pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic" qs = default_quota_set(pool) row = { "token": token, @@ -211,10 +213,12 @@ class SqlAccountRepository: "status": "active", "created_at": ts, "updated_at": ts, + "deleted_at": None, # clear soft-delete on re-import "tags": json.dumps(item.tags), "quota_auto": json.dumps(qs.auto.to_dict()), "quota_fast": json.dumps(qs.fast.to_dict()), "quota_expert": json.dumps(qs.expert.to_dict()), + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", "usage_use_count": 0, "usage_fail_count": 0, "usage_sync_count": 0, @@ -245,6 +249,8 @@ class SqlAccountRepository: qs = record.quota_set() updates: dict[str, Any] = {"updated_at": ts, "revision": rev} + if patch.pool is not None: + updates["pool"] = patch.pool if patch.status is not None: updates["status"] = patch.status.value if patch.state_reason is not None: @@ -265,6 +271,8 @@ class SqlAccountRepository: updates["quota_fast"] = json.dumps(patch.quota_fast) if patch.quota_expert is not None: updates["quota_expert"] = json.dumps(patch.quota_expert) + if patch.quota_heavy is not None: + updates["quota_heavy"] = json.dumps(patch.quota_heavy) if patch.usage_use_delta is not None: updates["usage_use_count"] = max(0, record.usage_use_count + patch.usage_use_delta) if patch.usage_fail_delta is not None: diff --git a/app/control/account/commands.py b/app/control/account/commands.py index 9cd7b36a..bb626753 100644 --- a/app/control/account/commands.py +++ b/app/control/account/commands.py @@ -1,7 +1,5 @@ """Command / query objects for the account control plane.""" -from __future__ import annotations - from typing import Any from pydantic import BaseModel, Field @@ -28,6 +26,7 @@ class AccountPatch(BaseModel): """ token: str + pool: str | None = None # update pool type when inferred status: AccountStatus | None = None tags: list[str] | None = None add_tags: list[str] | None = None @@ -36,6 +35,7 @@ class AccountPatch(BaseModel): quota_auto: dict[str, Any] | None = None quota_fast: dict[str, Any] | None = None quota_expert: dict[str, Any] | None = None + quota_heavy: dict[str, Any] | None = None # Usage counters — delta values (added to existing counts). usage_use_delta: int | None = None usage_fail_delta: int | None = None diff --git a/app/control/account/enums.py b/app/control/account/enums.py index 1f3487bd..c6252849 100644 --- a/app/control/account/enums.py +++ b/app/control/account/enums.py @@ -1,7 +1,5 @@ """Control-plane account enumerations.""" -from __future__ import annotations - from enum import IntEnum, StrEnum diff --git a/app/control/account/models.py b/app/control/account/models.py index 87f49982..ae7e2e7c 100644 --- a/app/control/account/models.py +++ b/app/control/account/models.py @@ -1,7 +1,5 @@ """Control-plane account models — persistent record shape.""" -from __future__ import annotations - from dataclasses import dataclass from typing import Any @@ -69,19 +67,25 @@ class QuotaWindow: @dataclass(slots=True) class AccountQuotaSet: - """Three-dimensional quota set — one window per mode.""" + """Quota set — one window per mode (auto / fast / expert / heavy). + + ``heavy`` is ``None`` for basic and super accounts. + """ auto: QuotaWindow fast: QuotaWindow expert: QuotaWindow + heavy: QuotaWindow | None = None # heavy-pool accounts only - def get(self, mode_id: int) -> QuotaWindow: - """Return the quota window for *mode_id* (0=auto, 1=fast, 2=expert).""" + def get(self, mode_id: int) -> QuotaWindow | None: + """Return the quota window for *mode_id* (0=auto, 1=fast, 2=expert, 3=heavy).""" if mode_id == 0: return self.auto if mode_id == 1: return self.fast - return self.expert + if mode_id == 2: + return self.expert + return self.heavy # mode_id == 3 def set(self, mode_id: int, window: QuotaWindow) -> None: """Replace the quota window for *mode_id*.""" @@ -89,22 +93,29 @@ class AccountQuotaSet: self.auto = window elif mode_id == 1: self.fast = window - else: + elif mode_id == 2: self.expert = window + else: + self.heavy = window # mode_id == 3 def to_dict(self) -> dict[str, dict[str, Any]]: - return { + d: dict[str, dict[str, Any]] = { "auto": self.auto.to_dict(), "fast": self.fast.to_dict(), "expert": self.expert.to_dict(), } + if self.heavy is not None: + d["heavy"] = self.heavy.to_dict() + return d @classmethod def from_dict(cls, d: dict[str, Any]) -> "AccountQuotaSet": + heavy_d = d.get("heavy") return cls( auto = QuotaWindow.from_dict(d.get("auto", {})), fast = QuotaWindow.from_dict(d.get("fast", {})), expert = QuotaWindow.from_dict(d.get("expert", {})), + heavy = QuotaWindow.from_dict(heavy_d) if heavy_d else None, ) @@ -143,7 +154,7 @@ class AccountUsageStats: class AccountRecord(BaseModel): """Persistent account record — single source of truth for all backends. - ``pool`` values: ``"basic"`` | ``"super"`` + ``pool`` values: ``"basic"`` | ``"super"`` | ``"heavy"`` All timestamps are milliseconds since epoch. ``ext`` carries non-core extension data only. """ @@ -181,6 +192,10 @@ class AccountRecord(BaseModel): def is_super(self) -> bool: return self.pool == "super" + @property + def is_heavy(self) -> bool: + return self.pool == "heavy" + def is_deleted(self) -> bool: return self.deleted_at is not None @@ -224,10 +239,13 @@ class AccountRecord(BaseModel): @classmethod def _normalize_pool(cls, v: Any) -> str: val = str(v or "").strip().lower() - # Accept legacy pool names. - if val in ("ssosuper", "super"): + if val in ("super"): return "super" - if val in ("ssobasic", "basic", ""): + if val in ("heavy",): + return "heavy" + if val in ("ssobasic", "basic", "", "auto"): + # "auto" is a UI alias meaning "let quota sync decide"; + # save as basic for now — refresh will correct to the real type. return "basic" raise ValueError(f"Unknown pool: {v!r}") diff --git a/app/control/account/quota_defaults.py b/app/control/account/quota_defaults.py index f80cab10..620aee55 100644 --- a/app/control/account/quota_defaults.py +++ b/app/control/account/quota_defaults.py @@ -1,10 +1,28 @@ -"""Default quota windows applied when upstream data is unavailable.""" +"""Default quota windows and pool inference logic. -from __future__ import annotations +Canonical quota totals per pool type (from upstream rate-limits API): + + auto fast expert heavy + basic 20 60 8 — window: 72000 / 36000 s + super 50 140 50 — window: 7200 s + heavy 150 400 150 20 window: 7200 s + +Pool inference uses ``auto.total`` as the primary signal — the three values +(20 / 50 / 150) are mutually exclusive across pool types. +""" + +from typing import TYPE_CHECKING from .enums import QuotaSource from .models import AccountQuotaSet, QuotaWindow +if TYPE_CHECKING: + pass + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- def _w(remaining: int, total: int, window_seconds: int) -> QuotaWindow: return QuotaWindow( @@ -18,34 +36,75 @@ def _w(remaining: int, total: int, window_seconds: int) -> QuotaWindow: # --------------------------------------------------------------------------- -# Basic-pool defaults -# (static window — no API sync required) +# Per-pool default quota sets # --------------------------------------------------------------------------- + BASIC_QUOTA_DEFAULTS = AccountQuotaSet( - auto = _w(20, 20, 72_000), # 20 queries / 20 h - fast = _w(60, 60, 72_000), # 60 queries / 20 h - expert = _w(8, 8, 36_000), # 8 queries / 10 h + auto = _w(20, 20, 72_000), # 20 queries / 20 h + fast = _w(60, 60, 72_000), # 60 queries / 20 h + expert = _w(8, 8, 36_000), # 8 queries / 10 h ) -# --------------------------------------------------------------------------- -# Super-pool defaults -# (used only when upstream API call fails; real values fetched on import) -# --------------------------------------------------------------------------- SUPER_QUOTA_DEFAULTS = AccountQuotaSet( - auto = _w(20, 20, 72_000), - fast = _w(60, 60, 72_000), - expert = _w(8, 8, 36_000), + auto = _w(50, 50, 7_200), # 50 queries / 2 h + fast = _w(140, 140, 7_200), # 140 queries / 2 h + expert = _w(50, 50, 7_200), # 50 queries / 2 h ) +HEAVY_QUOTA_DEFAULTS = AccountQuotaSet( + auto = _w(150, 150, 7_200), # 150 queries / 2 h + fast = _w(400, 400, 7_200), # 400 queries / 2 h + expert = _w(150, 150, 7_200), # 150 queries / 2 h + heavy = _w(20, 20, 7_200), # 20 queries / 2 h +) + +# Map pool name → defaults object (used by backends on upsert). +_POOL_DEFAULTS: dict[str, AccountQuotaSet] = { + "basic": BASIC_QUOTA_DEFAULTS, + "super": SUPER_QUOTA_DEFAULTS, + "heavy": HEAVY_QUOTA_DEFAULTS, +} + +# --------------------------------------------------------------------------- +# Pool inference — keyed on auto.total (unique across pool types) +# --------------------------------------------------------------------------- + +_AUTO_TOTAL_TO_POOL: dict[int, str] = { + 20: "basic", + 50: "super", + 150: "heavy", +} + def default_quota_set(pool: str) -> AccountQuotaSet: """Return a fresh copy of the default quota set for *pool*.""" - src = SUPER_QUOTA_DEFAULTS if pool == "super" else BASIC_QUOTA_DEFAULTS - return AccountQuotaSet( + src = _POOL_DEFAULTS.get(pool, BASIC_QUOTA_DEFAULTS) + qs = AccountQuotaSet( auto = _w(src.auto.remaining, src.auto.total, src.auto.window_seconds), fast = _w(src.fast.remaining, src.fast.total, src.fast.window_seconds), expert = _w(src.expert.remaining, src.expert.total, src.expert.window_seconds), ) + if src.heavy is not None: + qs.heavy = _w(src.heavy.remaining, src.heavy.total, src.heavy.window_seconds) + return qs -__all__ = ["BASIC_QUOTA_DEFAULTS", "SUPER_QUOTA_DEFAULTS", "default_quota_set"] +def infer_pool(windows: dict[int, QuotaWindow]) -> str: + """Infer pool type from live quota windows returned by the rate-limits API. + + Uses ``auto.total`` (mode_id=0) as the discriminating signal. + Falls back to ``"basic"`` when the value is absent or unrecognised. + """ + auto_win = windows.get(0) + if auto_win is None: + return "basic" + return _AUTO_TOTAL_TO_POOL.get(auto_win.total, "basic") + + +__all__ = [ + "BASIC_QUOTA_DEFAULTS", + "SUPER_QUOTA_DEFAULTS", + "HEAVY_QUOTA_DEFAULTS", + "default_quota_set", + "infer_pool", +] diff --git a/app/control/account/refresh.py b/app/control/account/refresh.py index ad1bd06c..81c1b17d 100644 --- a/app/control/account/refresh.py +++ b/app/control/account/refresh.py @@ -1,7 +1,5 @@ """Account refresh service — mode-aware usage synchronisation.""" -from __future__ import annotations - import asyncio from dataclasses import dataclass, field from typing import TYPE_CHECKING @@ -10,10 +8,10 @@ from app.platform.config.snapshot import get_config from app.platform.logging.logger import logger from app.platform.runtime.clock import now_ms from app.platform.runtime.batch import run_batch -from app.control.model.enums import ALL_MODES, ModeId +from app.control.model.enums import ALL_MODES_WITH_HEAVY, ModeId from .enums import AccountStatus, FeedbackKind, QuotaSource from .models import AccountRecord, QuotaWindow -from .quota_defaults import default_quota_set +from .quota_defaults import default_quota_set, infer_pool from .state_machine import AccountFeedback, apply_feedback if TYPE_CHECKING: @@ -89,7 +87,11 @@ class AccountRefreshService: return RefreshResult(checked=len(records)) concurrency = get_config("account.refresh.usage_concurrency", 10) - results = await run_batch(active, self._refresh_one, concurrency=concurrency) + results = await run_batch( + active, + lambda r: self._refresh_one(r, apply_fallback=True), + concurrency=concurrency, + ) agg = RefreshResult(checked=len(records)) for r in results: agg.merge(r) @@ -101,17 +103,24 @@ class AccountRefreshService: if record is None or record.is_deleted(): return window = await self._fetch_mode_quota(token, mode_id) - await self._apply_single_mode(record, mode_id, window) + await self._apply_single_mode(record, mode_id, window, is_use=True, use_at_ms=now_ms()) - async def refresh_scheduled(self) -> RefreshResult: - """Periodic refresh — super: fetch API; basic: static reset check.""" + async def refresh_scheduled(self, pool: str | None = None) -> RefreshResult: + """Periodic refresh — fetch real quotas for all (or one pool's) accounts. + + Args: + pool: When set, only refreshes accounts belonging to that pool. + When ``None``, refreshes all pools (legacy / manual trigger path). + """ snapshot = await self._repo.runtime_snapshot() records = snapshot.items + if pool is not None: + records = [r for r in records if r.pool == pool] concurrency = get_config("account.refresh.usage_concurrency", 10) results = await run_batch( records, - self._refresh_one, + lambda r: self._refresh_one(r, apply_fallback=True), concurrency=concurrency, ) agg = RefreshResult() @@ -150,61 +159,87 @@ class AccountRefreshService: # Per-account refresh # ------------------------------------------------------------------ - async def _refresh_one(self, record: AccountRecord) -> RefreshResult: - """Fetch all 3 modes for any account type; apply real data or fall back gracefully.""" + async def _refresh_one( + self, + record: AccountRecord, + *, + apply_fallback: bool = False, + ) -> RefreshResult: + """Fetch all 3 modes from the usage API and persist real quota data. + + apply_fallback=True — used by scheduled/import paths: when API fails, + decrement REAL quotas or reset expired DEFAULT windows. + apply_fallback=False — used by manual/on-demand paths: if API fails, return + failed=1 immediately without touching stored data. + """ if record.is_deleted(): return RefreshResult() - windows = await self._fetch_all_quotas(record.token) - qs = record.quota_set() - now = now_ms() - patches: dict[str, dict] = {} + windows = await self._fetch_all_quotas(record.token) + + # API call completely failed — no real data available. + if windows is None: + if not apply_fallback: + return RefreshResult(checked=1, failed=1) + # Scheduled/import path: apply conservative fallback. + return await self._apply_fallback(record) + + # We got at least a response — apply real data per mode. + qs = record.quota_set() + now = now_ms() + patches: dict[str, dict] = {} refreshed = False - _MODE_KEYS = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert"} + _MODE_KEYS = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert", 3: "quota_heavy"} - for mode in ALL_MODES: + for mode in ALL_MODES_WITH_HEAVY: mode_id = int(mode) - - if windows and mode_id in windows: - # ✅ Got real data from API. + if mode_id in windows: patches[_MODE_KEYS[mode_id]] = windows[mode_id].to_dict() refreshed = True - continue - - # ❌ API failed for this mode — apply fallback strategy. - existing = qs.get(mode_id) - - if existing.source == QuotaSource.REAL: - # Had real data before: decrement by 1 (conservative estimate). - patches[_MODE_KEYS[mode_id]] = QuotaWindow( - remaining = max(0, existing.remaining - 1), - total = existing.total, - window_seconds = existing.window_seconds, - reset_at = existing.reset_at, - synced_at = existing.synced_at, - source = QuotaSource.ESTIMATED, - ).to_dict() - elif existing.is_window_expired(now): - # Default/estimated data and window has expired: reset to defaults. - default = default_quota_set(record.pool).get(mode_id) - patches[_MODE_KEYS[mode_id]] = QuotaWindow( - remaining = default.total, - total = default.total, - window_seconds = default.window_seconds, - reset_at = now + default.window_seconds * 1000, - synced_at = now, - source = QuotaSource.DEFAULT, - ).to_dict() - # else: window still valid, leave unchanged. + elif apply_fallback: + existing = qs.get(mode_id) + if existing is None: + continue + if existing.source == QuotaSource.REAL: + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining = max(0, existing.remaining - 1), + total = existing.total, + window_seconds = existing.window_seconds, + reset_at = existing.reset_at, + synced_at = existing.synced_at, + source = QuotaSource.ESTIMATED, + ).to_dict() + elif existing.is_window_expired(now): + default = default_quota_set(record.pool).get(mode_id) + if default is None: + continue + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining = default.total, + total = default.total, + window_seconds = default.window_seconds, + reset_at = now + default.window_seconds * 1000, + synced_at = now, + source = QuotaSource.DEFAULT, + ).to_dict() if not patches: - return RefreshResult(checked=1) + return RefreshResult(checked=1, failed=0 if refreshed else 1) + + # Infer pool type from live quota data and patch if it changed. + inferred = infer_pool(windows) # type: ignore[arg-type] + pool_patch = inferred if inferred != record.pool else None + if pool_patch: + logger.info( + "Pool auto-updated: token={}... {} → {}", + record.token[:10], record.pool, inferred, + ) from .commands import AccountPatch await self._repo.patch_accounts([ AccountPatch( token = record.token, + pool = pool_patch, last_sync_at = now_ms() if refreshed else None, usage_sync_delta = 1 if refreshed else None, **patches, # type: ignore[arg-type] @@ -214,14 +249,73 @@ class AccountRefreshService: return RefreshResult( checked=1, refreshed=1 if refreshed else 0, + failed=0 if refreshed else 1, recovered=1 if (was_cooling and refreshed) else 0, ) + async def _apply_fallback(self, record: AccountRecord) -> RefreshResult: + """Conservative fallback when API is unreachable (scheduled/import path only).""" + qs = record.quota_set() + now = now_ms() + patches: dict[str, dict] = {} + + _MODE_KEYS = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert", 3: "quota_heavy"} + + for mode in ALL_MODES_WITH_HEAVY: + mode_id = int(mode) + existing = qs.get(mode_id) + if existing is None: + continue + if existing.source == QuotaSource.REAL: + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining = max(0, existing.remaining - 1), + total = existing.total, + window_seconds = existing.window_seconds, + reset_at = existing.reset_at, + synced_at = existing.synced_at, + source = QuotaSource.ESTIMATED, + ).to_dict() + elif existing.is_window_expired(now): + default = default_quota_set(record.pool).get(mode_id) + if default is None: + continue + patches[_MODE_KEYS[mode_id]] = QuotaWindow( + remaining = default.total, + total = default.total, + window_seconds = default.window_seconds, + reset_at = now + default.window_seconds * 1000, + synced_at = now, + source = QuotaSource.DEFAULT, + ).to_dict() + + if patches: + from .commands import AccountPatch + await self._repo.patch_accounts([AccountPatch(token=record.token, **patches)]) # type: ignore[arg-type] + + return RefreshResult(checked=1, failed=1) + + async def record_failure_async(self, token: str, mode_id: int) -> None: + """Fire-and-forget: persist failure counter and timestamp after a failed call.""" + from .commands import AccountPatch + try: + await self._repo.patch_accounts([ + AccountPatch( + token = token, + usage_fail_delta = 1, + last_fail_at = now_ms(), + ) + ]) + except Exception as exc: + logger.debug("Failure record failed: token={}... error={}", token[:10], exc) + async def _apply_single_mode( self, record: AccountRecord, mode_id: int, window: QuotaWindow | None, + *, + is_use: bool = False, + use_at_ms: int | None = None, ) -> None: qs = record.quota_set() if window is not None: @@ -241,9 +335,11 @@ class AccountRefreshService: from .commands import AccountPatch await self._repo.patch_accounts([ AccountPatch( - token = record.token, - last_sync_at = now_ms() if window is not None else None, + token = record.token, + last_sync_at = now_ms() if window is not None else None, usage_sync_delta = 1 if window is not None else None, + usage_use_delta = 1 if is_use else None, + last_use_at = use_at_ms if is_use else None, **{mode_key: win.to_dict()}, # type: ignore[arg-type] ) ]) diff --git a/app/control/account/repository.py b/app/control/account/repository.py index a54af4d6..77604628 100644 --- a/app/control/account/repository.py +++ b/app/control/account/repository.py @@ -1,7 +1,5 @@ """Account repository protocol — the contract every backend must satisfy.""" -from __future__ import annotations - from typing import Protocol, runtime_checkable from .commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery diff --git a/app/control/account/runtime.py b/app/control/account/runtime.py new file mode 100644 index 00000000..00a5778c --- /dev/null +++ b/app/control/account/runtime.py @@ -0,0 +1,22 @@ +"""Account runtime singletons exposed without importing app.main.""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .refresh import AccountRefreshService + +_refresh_service: "AccountRefreshService | None" = None + + +def set_refresh_service(service: "AccountRefreshService | None") -> None: + """Register the process-global account refresh service.""" + global _refresh_service + _refresh_service = service + + +def get_refresh_service() -> "AccountRefreshService | None": + """Return the registered account refresh service, if any.""" + return _refresh_service + + +__all__ = ["get_refresh_service", "set_refresh_service"] diff --git a/app/control/account/scheduler.py b/app/control/account/scheduler.py index 65601dcb..fd289e75 100644 --- a/app/control/account/scheduler.py +++ b/app/control/account/scheduler.py @@ -1,6 +1,15 @@ -"""Background scheduler for periodic account quota refresh.""" +"""Background scheduler for periodic account quota refresh. -from __future__ import annotations +Runs one independent loop per pool type (basic / super / heavy), each with +its own configurable interval read from: + + account.refresh.basic_interval_sec (default 36000 — 10 h) + account.refresh.super_interval_sec (default 7200 — 2 h) + account.refresh.heavy_interval_sec (default 7200 — 2 h) + +Falls back to the legacy ``account.refresh.interval_sec`` key if the +pool-specific key is absent (backward compatibility with existing configs). +""" import asyncio @@ -8,37 +17,60 @@ from app.platform.config.snapshot import get_config from app.platform.logging.logger import logger from .refresh import AccountRefreshService +# Pool → (config key, built-in default seconds) +_POOL_CONFIG: dict[str, tuple[str, int]] = { + "basic": ("account.refresh.basic_interval_sec", 36_000), + "super": ("account.refresh.super_interval_sec", 7_200), + "heavy": ("account.refresh.heavy_interval_sec", 7_200), +} + + +def _interval(pool: str) -> int: + key, default = _POOL_CONFIG[pool] + # Pool-specific key takes precedence; legacy key as second fallback. + v = get_config(key, None) + if v is None: + v = get_config("account.refresh.interval_sec", None) + return int(v) if v is not None else default + class AccountRefreshScheduler: - """Runs ``AccountRefreshService.refresh_scheduled`` on a fixed interval. + """Runs one refresh loop per pool type at pool-specific intervals. - Lifecycle: ``start()`` → runs in background → ``stop()`` to cancel. + Lifecycle: ``start()`` → loops run in background → ``stop()`` to cancel. """ def __init__(self, refresh_service: AccountRefreshService) -> None: self._service = refresh_service - self._task: asyncio.Task | None = None + self._tasks: list[asyncio.Task] = [] self._stop = asyncio.Event() def start(self) -> None: - if self._task and not self._task.done(): + if self._tasks and not all(t.done() for t in self._tasks): return self._stop.clear() - self._task = asyncio.create_task(self._loop(), name="account-refresh-scheduler") - logger.info("AccountRefreshScheduler started.") + self._tasks = [ + asyncio.create_task(self._loop(pool), name=f"account-refresh-{pool}") + for pool in _POOL_CONFIG + ] + logger.info( + "AccountRefreshScheduler started — basic={}s super={}s heavy={}s", + _interval("basic"), _interval("super"), _interval("heavy"), + ) def stop(self) -> None: self._stop.set() - if self._task and not self._task.done(): - self._task.cancel() + for t in self._tasks: + if not t.done(): + t.cancel() logger.info("AccountRefreshScheduler stopped.") - async def _loop(self) -> None: + async def _loop(self, pool: str) -> None: while not self._stop.is_set(): - interval = int(get_config("account.refresh.interval_sec", 300)) + interval = _interval(pool) try: await asyncio.wait_for(self._stop.wait(), timeout=float(interval)) - break # stop was set + break # stop event fired except asyncio.TimeoutError: pass @@ -46,17 +78,15 @@ class AccountRefreshScheduler: break try: - result = await self._service.refresh_scheduled() + result = await self._service.refresh_scheduled(pool=pool) logger.info( - "Account refresh complete: checked={} refreshed={} recovered={} " - "expired={} disabled={} failed={}", - result.checked, result.refreshed, result.recovered, - result.expired, result.disabled, result.failed, + "Account refresh [{}]: checked={} refreshed={} recovered={} failed={}", + pool, result.checked, result.refreshed, result.recovered, result.failed, ) except asyncio.CancelledError: raise except Exception as exc: - logger.error("Account refresh error: {}", exc) + logger.error("Account refresh [{}] error: {}", pool, exc) # --------------------------------------------------------------------------- diff --git a/app/control/account/state_machine.py b/app/control/account/state_machine.py index 2b6009a2..c9db16fc 100644 --- a/app/control/account/state_machine.py +++ b/app/control/account/state_machine.py @@ -4,8 +4,6 @@ Applies feedback events to an AccountRecord, advancing its status and updating quota / usage fields accordingly. """ -from __future__ import annotations - from dataclasses import dataclass, field from typing import Any diff --git a/app/control/admin/service.py b/app/control/admin/service.py deleted file mode 100644 index aca253dd..00000000 --- a/app/control/admin/service.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Admin service layer — aggregates token CRUD and proxy management. - -Provides a service-level API that admin handlers call instead of -reaching directly into repositories. Centralises validation, audit -logging, and cross-cutting concerns. -""" - -from __future__ import annotations - -from typing import Any - -from app.platform.logging.logger import logger -from app.platform.runtime.clock import now_ms -from app.control.account.commands import ( - AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery, -) -from app.control.account.models import ( - AccountMutationResult, AccountPage, AccountRecord, -) -from app.control.account.repository import AccountRepository - - -class AccountAdminService: - """High-level account administration operations.""" - - def __init__(self, repo: AccountRepository) -> None: - self._repo = repo - - async def list_accounts(self, query: ListAccountsQuery) -> AccountPage: - return await self._repo.list_accounts(query) - - async def get_accounts(self, tokens: list[str]) -> list[AccountRecord]: - return await self._repo.get_accounts(tokens) - - async def upsert(self, items: list[AccountUpsert]) -> AccountMutationResult: - result = await self._repo.upsert_accounts(items) - logger.info("Admin upsert: {} accounts affected", result.upserted) - return result - - async def delete(self, tokens: list[str]) -> AccountMutationResult: - result = await self._repo.delete_accounts(tokens) - logger.info("Admin delete: {} accounts affected", result.deleted) - return result - - async def patch(self, patches: list[AccountPatch]) -> AccountMutationResult: - result = await self._repo.patch_accounts(patches) - logger.info("Admin patch: {} accounts affected", result.patched) - return result - - async def replace_pool(self, command: BulkReplacePoolCommand) -> AccountMutationResult: - result = await self._repo.replace_pool(command) - logger.info( - "Admin replace_pool({}): upserted={} deleted={}", - command.pool, result.upserted, result.deleted, - ) - return result - - -class ProxyAdminService: - """High-level proxy administration operations.""" - - def __init__(self) -> None: - self._directory = None - - async def _get_directory(self): - if self._directory is None: - from app.control.proxy import get_proxy_directory - self._directory = await get_proxy_directory() - return self._directory - - async def status(self) -> dict[str, Any]: - """Return current proxy status summary.""" - d = await self._get_directory() - return { - "egress_mode": d.egress_mode.value, - "clearance_mode": d.clearance_mode.value, - "node_count": d.node_count, - } - - async def reload(self) -> dict[str, Any]: - """Reload proxy configuration.""" - d = await self._get_directory() - await d.load() - logger.info("Admin proxy reload complete") - return await self.status() - - -__all__ = ["AccountAdminService", "ProxyAdminService"] diff --git a/app/control/model/enums.py b/app/control/model/enums.py index 6d04848d..6bb00307 100644 --- a/app/control/model/enums.py +++ b/app/control/model/enums.py @@ -1,7 +1,5 @@ """Control-plane model enumerations.""" -from __future__ import annotations - from enum import IntEnum, IntFlag @@ -14,6 +12,7 @@ class ModeId(IntEnum): AUTO = 0 # modeId="auto" FAST = 1 # modeId="fast" EXPERT = 2 # modeId="expert" + HEAVY = 3 # modeId="heavy" — only available on heavy-pool accounts def to_api_str(self) -> str: return self.name.lower() @@ -24,6 +23,7 @@ class Tier(IntEnum): BASIC = 0 # pool="basic" SUPER = 1 # pool="super" + HEAVY = 2 # pool="heavy" class Capability(IntFlag): @@ -42,8 +42,10 @@ MODE_STRINGS: dict[ModeId, str] = { ModeId.AUTO: "auto", ModeId.FAST: "fast", ModeId.EXPERT: "expert", + ModeId.HEAVY: "heavy", } -ALL_MODES: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT) +ALL_MODES: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT) +ALL_MODES_WITH_HEAVY: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT, ModeId.HEAVY) -__all__ = ["ModeId", "Tier", "Capability", "MODE_STRINGS", "ALL_MODES"] +__all__ = ["ModeId", "Tier", "Capability", "MODE_STRINGS", "ALL_MODES", "ALL_MODES_WITH_HEAVY"] diff --git a/app/control/model/registry.py b/app/control/model/registry.py index f57d4565..b48e2667 100644 --- a/app/control/model/registry.py +++ b/app/control/model/registry.py @@ -1,7 +1,5 @@ """Model registry — all supported model variants defined in one place.""" -from __future__ import annotations - from .enums import Capability, ModeId, Tier from .spec import ModelSpec @@ -11,21 +9,28 @@ from .spec import ModelSpec # --------------------------------------------------------------------------- MODELS: tuple[ModelSpec, ...] = ( - # ── Basic · Chat ──────────────────────────────────────────────────────── - ModelSpec("grok-3", ModeId.AUTO, Tier.BASIC, Capability.CHAT, True, "Grok 3"), - ModelSpec("grok-3-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 3 Fast"), - ModelSpec("grok-3-expert", ModeId.EXPERT, Tier.BASIC, Capability.CHAT, True, "Grok 3 Expert"), - ModelSpec("grok-4", ModeId.AUTO, Tier.BASIC, Capability.CHAT, True, "Grok 4"), - ModelSpec("grok-4-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4 Fast"), - ModelSpec("grok-4-expert", ModeId.EXPERT, Tier.BASIC, Capability.CHAT, True, "Grok 4 Expert"), - # ── Super · Chat ──────────────────────────────────────────────────────── - ModelSpec("grok-4-heavy", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4 Heavy"), - # ── Basic · Image ─────────────────────────────────────────────────────── - ModelSpec("grok-image", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Image"), - ModelSpec("grok-image-fast", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Image Fast"), - ModelSpec("grok-image-edit", ModeId.FAST, Tier.BASIC, Capability.IMAGE_EDIT, True, "Grok Image Edit"), - # ── Basic · Video ─────────────────────────────────────────────────────── - ModelSpec("grok-video", ModeId.FAST, Tier.BASIC, Capability.VIDEO, True, "Grok Video"), + # === Chat ============================================================== + # Basic + ModelSpec("grok-4.20-0309", ModeId.AUTO, Tier.BASIC, Capability.CHAT, True, "Grok 4.20-0309"), + ModelSpec("grok-4.20-0309-non-reasoning", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.20-0309-non-reasoning"), + ModelSpec("grok-4.20-0309-reasoning", ModeId.EXPERT, Tier.BASIC, Capability.CHAT, True, "Grok 4.20-0309-reasoning"), + # Heavy + ModelSpec("grok-4.20-multi-agent-0309", ModeId.HEAVY, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20-multi-agent-0309"), + + # === Image ============================================================== + # Basic + ModelSpec("grok-imagine-image-lite", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Imagine Image Lite"), + # Super + ModelSpec("grok-imagine-image", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image"), + ModelSpec("grok-imagine-image-pro", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image Pro"), + + # === Image Edit ========================================================= + # Super + ModelSpec("grok-imagine-image-edit", ModeId.AUTO, Tier.SUPER, Capability.IMAGE_EDIT, True, "Grok Imagine Image Edit"), + + # === Video ============================================================== + # Super + ModelSpec("grok-imagine-video", ModeId.AUTO, Tier.SUPER, Capability.VIDEO, True, "Grok Imagine Video"), ) # --------------------------------------------------------------------------- diff --git a/app/control/model/spec.py b/app/control/model/spec.py index 02f81957..6ed33ff4 100644 --- a/app/control/model/spec.py +++ b/app/control/model/spec.py @@ -1,7 +1,5 @@ """ModelSpec — the single source of truth for model metadata.""" -from __future__ import annotations - from dataclasses import dataclass from .enums import Capability, ModeId, Tier @@ -35,12 +33,26 @@ class ModelSpec: def is_voice(self) -> bool: return bool(self.capability & Capability.VOICE) def pool_name(self) -> str: - """Return the pool string expected by the account selector.""" - return "super" if self.tier == Tier.SUPER else "basic" + """Return the canonical pool string for this tier.""" + if self.tier == Tier.SUPER: return "super" + if self.tier == Tier.HEAVY: return "heavy" + return "basic" def pool_id(self) -> int: """Return the integer PoolId for the dataplane account table.""" return int(self.tier) + def pool_candidates(self) -> tuple[int, ...]: + """Return pool IDs to try in priority order. + + A higher-tier account can always serve a lower-tier model: + BASIC tier → try basic first, then super, then heavy + SUPER tier → try super first, then heavy + HEAVY tier → heavy only + """ + if self.tier == Tier.BASIC: return (0, 1, 2) # basic, super, heavy + if self.tier == Tier.SUPER: return (1, 2) # super, heavy + return (2,) # heavy only + __all__ = ["ModelSpec"] diff --git a/app/control/proxy/__init__.py b/app/control/proxy/__init__.py index 31d65454..505536d6 100644 --- a/app/control/proxy/__init__.py +++ b/app/control/proxy/__init__.py @@ -5,8 +5,6 @@ Selection delegates to the dataplane ProxyTable; this module owns configuration loading and clearance refresh lifecycle. """ -from __future__ import annotations - import asyncio from typing import Sequence @@ -30,11 +28,12 @@ class ProxyDirectory: """ def __init__(self) -> None: - self._nodes: list[EgressNode] = [] - self._bundles: dict[str, ClearanceBundle] = {} # affinity_key → bundle - self._lock = asyncio.Lock() - self._manual = ManualClearanceProvider() - self._flare = FlareSolverrClearanceProvider() + self._nodes: list[EgressNode] = [] + self._resource_nodes: list[EgressNode] = [] # for media downloads + self._bundles: dict[str, ClearanceBundle] = {} + self._lock = asyncio.Lock() + self._manual = ManualClearanceProvider() + self._flare = FlareSolverrClearanceProvider() self._egress_mode: EgressMode = EgressMode.DIRECT self._clearance_mode: ClearanceMode = ClearanceMode.NONE @@ -48,20 +47,28 @@ class ProxyDirectory: self._egress_mode = EgressMode(cfg.get_str("proxy.egress.mode", "direct")) self._clearance_mode = ClearanceMode(cfg.get_str("proxy.clearance.mode", "none")) - nodes: list[EgressNode] = [] + nodes: list[EgressNode] = [] + resource_nodes: list[EgressNode] = [] if self._egress_mode == EgressMode.SINGLE_PROXY: - url = cfg.get_str("proxy.egress.proxy_url", "") - if url: - nodes.append(EgressNode(node_id="single", proxy_url=url)) + base_url = cfg.get_str("proxy.egress.proxy_url", "") + res_url = cfg.get_str("proxy.egress.resource_proxy_url", "") + if base_url: + nodes.append(EgressNode(node_id="single", proxy_url=base_url)) + if res_url: + resource_nodes.append(EgressNode(node_id="res-single", proxy_url=res_url)) elif self._egress_mode == EgressMode.PROXY_POOL: - urls: list[str] = cfg.get_list("proxy.egress.proxy_pool", []) - for i, url in enumerate(urls): + base_pool: list[str] = cfg.get_list("proxy.egress.proxy_pool", []) + res_pool: list[str] = cfg.get_list("proxy.egress.resource_proxy_pool", []) + for i, url in enumerate(base_pool): nodes.append(EgressNode(node_id=f"pool-{i}", proxy_url=url)) + for i, url in enumerate(res_pool): + resource_nodes.append(EgressNode(node_id=f"res-pool-{i}", proxy_url=url)) async with self._lock: - self._nodes = nodes + self._nodes = nodes + self._resource_nodes = resource_nodes logger.info( "ProxyDirectory loaded: egress={} clearance={} nodes={}", @@ -75,14 +82,15 @@ class ProxyDirectory: async def acquire( self, *, - scope: ProxyScope = ProxyScope.APP, - kind: RequestKind = RequestKind.HTTP, + scope: ProxyScope = ProxyScope.APP, + kind: RequestKind = RequestKind.HTTP, + resource: bool = False, ) -> ProxyLease: """Return a ProxyLease for the next request. For DIRECT mode, returns a lease with no proxy or clearance. """ - proxy_url = await self._pick_proxy_url() + proxy_url = await self._pick_proxy_url(resource=resource) affinity = proxy_url or "direct" bundle = await self._get_or_build_bundle(affinity_key=affinity, proxy_url=proxy_url or "") @@ -117,20 +125,19 @@ class ProxyDirectory: # Internal # ------------------------------------------------------------------ - async def _pick_proxy_url(self) -> str | None: + async def _pick_proxy_url(self, resource: bool = False) -> str | None: if self._egress_mode == EgressMode.DIRECT: return None - if self._egress_mode == EgressMode.SINGLE_PROXY: - async with self._lock: - if self._nodes: - return self._nodes[0].proxy_url - return None - # PROXY_POOL: round-robin by inflight count (minimal implementation). async with self._lock: - if not self._nodes: + # Prefer resource-specific nodes when available; fall back to base nodes. + nodes = (self._resource_nodes if resource and self._resource_nodes + else self._nodes) + if not nodes: return None - node = min(self._nodes, key=lambda n: n.inflight) - return node.proxy_url + if self._egress_mode == EgressMode.SINGLE_PROXY: + return nodes[0].proxy_url + # PROXY_POOL: pick least-inflight node. + return min(nodes, key=lambda n: n.inflight).proxy_url async def _get_or_build_bundle( self, diff --git a/app/control/proxy/feedback.py b/app/control/proxy/feedback.py index a35dec95..c58ff1ca 100644 --- a/app/control/proxy/feedback.py +++ b/app/control/proxy/feedback.py @@ -1,7 +1,5 @@ """Classify upstream HTTP responses into proxy feedback categories.""" -from __future__ import annotations - from .models import ProxyFeedback, ProxyFeedbackKind diff --git a/app/control/proxy/models.py b/app/control/proxy/models.py index dd51bdef..30f8574a 100644 --- a/app/control/proxy/models.py +++ b/app/control/proxy/models.py @@ -1,7 +1,5 @@ """Control-plane proxy domain models.""" -from __future__ import annotations - from enum import IntEnum, StrEnum from typing import Any diff --git a/app/control/proxy/providers/flaresolverr.py b/app/control/proxy/providers/flaresolverr.py index 25ac8c74..b9183369 100644 --- a/app/control/proxy/providers/flaresolverr.py +++ b/app/control/proxy/providers/flaresolverr.py @@ -1,7 +1,5 @@ """FlareSolverr-backed managed clearance provider.""" -from __future__ import annotations - import asyncio import json import re diff --git a/app/control/proxy/providers/manual.py b/app/control/proxy/providers/manual.py index fdd051ae..3a1f741e 100644 --- a/app/control/proxy/providers/manual.py +++ b/app/control/proxy/providers/manual.py @@ -1,7 +1,5 @@ """Manual clearance provider — uses operator-supplied cookies directly.""" -from __future__ import annotations - from app.platform.config.snapshot import get_config from ..models import ClearanceBundle, ClearanceMode diff --git a/app/control/proxy/scheduler.py b/app/control/proxy/scheduler.py index b949532b..9902218b 100644 --- a/app/control/proxy/scheduler.py +++ b/app/control/proxy/scheduler.py @@ -4,8 +4,6 @@ Periodically refreshes ClearanceBundles for managed (FlareSolverr) mode. Previously inline in ProxyDirectory; extracted for separation of concerns. """ -from __future__ import annotations - import asyncio from app.platform.logging.logger import logger diff --git a/app/dataplane/account/__init__.py b/app/dataplane/account/__init__.py index c4f7acc2..3fd6114c 100644 --- a/app/dataplane/account/__init__.py +++ b/app/dataplane/account/__init__.py @@ -5,8 +5,6 @@ Bootstrap loads a full snapshot; incremental sync applies revision-based changesets without holding the selection lock. """ -from __future__ import annotations - import asyncio from typing import TYPE_CHECKING @@ -80,7 +78,7 @@ class AccountDirectory: async def reserve( self, - pool_id: int, + pool_candidates: tuple[int, ...] | int, mode_id: int, *, exclude_tokens: list[str] | None = None, @@ -89,12 +87,18 @@ class AccountDirectory: ) -> AccountLease | None: """Select and reserve the best available account slot. + ``pool_candidates`` is tried in order; the first pool with an available + account wins. A plain ``int`` is accepted for backward compatibility. + Returns an AccountLease, or None if no account is available. """ table = self._table if table is None: return None + pools: tuple[int, ...] = ( + (pool_candidates,) if isinstance(pool_candidates, int) else pool_candidates + ) ts = now_s_override if now_s_override is not None else now_s() # Resolve exclude set (O(n) once, before lock). @@ -112,25 +116,31 @@ class AccountDirectory: prefer_tag_idxs = set().union(*sets) async with self._lock: - idx = select( - table, - pool_id, - mode_id, - exclude_idxs = exclude_idxs, - prefer_tag_idxs = prefer_tag_idxs, - now_s = ts, - ) + idx: int | None = None + for pool_id in pools: + idx = select( + table, + pool_id, + mode_id, + exclude_idxs = exclude_idxs, + prefer_tag_idxs = prefer_tag_idxs, + now_s = ts, + ) + if idx is not None: + break + if idx is None: return None fb.increment_inflight(table, idx) fb.update_last_use(table, idx, ts) - token = table.get_token(idx) + token = table.get_token(idx) + actual_pool = table.get_pool_id(idx) return new_lease( idx = idx, token = token, - pool_id = pool_id, + pool_id = actual_pool, mode_id = mode_id, selected_at = ts, ) diff --git a/app/dataplane/account/feedback.py b/app/dataplane/account/feedback.py index 98a7bc7a..f204b3fa 100644 --- a/app/dataplane/account/feedback.py +++ b/app/dataplane/account/feedback.py @@ -4,9 +4,7 @@ The caller (AccountDirectory) is responsible for holding the state lock before calling these functions. """ -from __future__ import annotations - -from ..shared.enums import StatusId +from ..shared.enums import ALL_MODE_IDS, StatusId from .table import AccountRuntimeTable # Health adjustment constants. @@ -68,13 +66,13 @@ def apply_status_change(table: AccountRuntimeTable, idx: int, new_status_id: int if new_status_id != int(StatusId.ACTIVE): # Remove from all mode availability buckets. - for mode_id in (0, 1, 2): + for mode_id in ALL_MODE_IDS: bucket = table.mode_available.get((pool_id, mode_id)) if bucket: bucket.discard(idx) else: # Re-add to mode buckets where quota > 0. - for mode_id in (0, 1, 2): + for mode_id in ALL_MODE_IDS: if int(table._quota_col(mode_id)[idx]) > 0: table.mode_available.setdefault((pool_id, mode_id), set()).add(idx) diff --git a/app/dataplane/account/lease.py b/app/dataplane/account/lease.py index d13a04b0..41edb612 100644 --- a/app/dataplane/account/lease.py +++ b/app/dataplane/account/lease.py @@ -1,7 +1,5 @@ """AccountLease — minimal hot-path rental object.""" -from __future__ import annotations - from dataclasses import dataclass from app.platform.runtime.ids import next_id diff --git a/app/dataplane/account/selector.py b/app/dataplane/account/selector.py index cfd5ab22..53e661d4 100644 --- a/app/dataplane/account/selector.py +++ b/app/dataplane/account/selector.py @@ -5,9 +5,7 @@ overhead. The caller provides the frozen set of excluded indices and pre-resolved tag index set. """ -from __future__ import annotations - -from ..shared.enums import StatusId +from ..shared.enums import PoolId, StatusId from .table import AccountRuntimeTable # Scoring weights — tuned for throughput/fairness balance. @@ -65,7 +63,14 @@ def _maybe_reset_windows( pool_id: int, now_s: int, ) -> None: - """Reset expired windows for basic-pool accounts (no API call required).""" + """Reset expired windows for basic-pool accounts (no API call required). + + Only applies to the basic pool — super/heavy quotas are managed exclusively + by the periodic refresh service and must not be reset inline. + """ + if pool_id != int(PoolId.BASIC): + return + from app.control.account.quota_defaults import BASIC_QUOTA_DEFAULTS defaults = BASIC_QUOTA_DEFAULTS.get(mode_id) diff --git a/app/dataplane/account/sync.py b/app/dataplane/account/sync.py index 67239130..553fc95d 100644 --- a/app/dataplane/account/sync.py +++ b/app/dataplane/account/sync.py @@ -5,8 +5,6 @@ Two modes: incremental — revision-based change scan at runtime. """ -from __future__ import annotations - import asyncio from app.platform.logging.logger import logger @@ -30,15 +28,18 @@ def _record_to_slot_args(record: AccountRecord) -> dict: return 0 return int(ms_to_s(window.reset_at)) + heavy_w = qs.heavy return dict( pool_id = pool_id, status_id = status_id, quota_auto = max(0, qs.auto.remaining), quota_fast = max(0, qs.fast.remaining), quota_expert = max(0, qs.expert.remaining), + quota_heavy = max(0, heavy_w.remaining) if heavy_w is not None else -1, reset_auto = _reset_s(qs.auto), reset_fast = _reset_s(qs.fast), reset_expert = _reset_s(qs.expert), + reset_heavy = _reset_s(heavy_w) if heavy_w is not None else 0, health = 1.0, last_use_s = ms_to_s(record.last_use_at) if record.last_use_at else 0, last_fail_s = ms_to_s(record.last_fail_at) if record.last_fail_at else 0, diff --git a/app/dataplane/account/table.py b/app/dataplane/account/table.py index 0c756fa5..4add6c35 100644 --- a/app/dataplane/account/table.py +++ b/app/dataplane/account/table.py @@ -8,8 +8,6 @@ All quota, status, health, and counter fields are stored as typed ``array.array`` columns indexed by a compact integer slot index. """ -from __future__ import annotations - import array from dataclasses import dataclass, field from typing import Iterator @@ -25,8 +23,8 @@ from ..shared.enums import ALL_MODE_IDS, POOL_STR_TO_ID, STATUS_STR_TO_ID, PoolI # 'L' uint32 — epoch-second timestamps (valid until year 2106) # --------------------------------------------------------------------------- -_QUOTA_COLS = ("quota_auto", "quota_fast", "quota_expert") -_RESET_COLS = ("reset_auto", "reset_fast", "reset_expert") +_QUOTA_COLS = ("quota_auto", "quota_fast", "quota_expert", "quota_heavy") +_RESET_COLS = ("reset_auto", "reset_fast", "reset_expert", "reset_heavy") _INFLIGHT_CAP = 32_767 # avoid int16 overflow on quota # --------------------------------------------------------------------------- @@ -55,11 +53,13 @@ class AccountRuntimeTable: quota_auto_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h")) quota_fast_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h")) quota_expert_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h")) + quota_heavy_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h")) # --- Window reset timestamps (uint32 epoch-seconds; 0 = unknown) --- reset_auto_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L")) reset_fast_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L")) reset_expert_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L")) + reset_heavy_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L")) # --- Runtime counters (uint16) --- inflight_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("H")) @@ -89,12 +89,14 @@ class AccountRuntimeTable: def _quota_col(self, mode_id: int) -> "array.array[int]": if mode_id == 0: return self.quota_auto_by_idx if mode_id == 1: return self.quota_fast_by_idx - return self.quota_expert_by_idx + if mode_id == 2: return self.quota_expert_by_idx + return self.quota_heavy_by_idx def _reset_col(self, mode_id: int) -> "array.array[int]": if mode_id == 0: return self.reset_auto_at_by_idx if mode_id == 1: return self.reset_fast_at_by_idx - return self.reset_expert_at_by_idx + if mode_id == 2: return self.reset_expert_at_by_idx + return self.reset_heavy_at_by_idx def _add_to_indexes(self, idx: int) -> None: pool_id = int(self.pool_by_idx[idx]) @@ -128,20 +130,22 @@ class AccountRuntimeTable: def _append_slot( self, - token: str, - pool_id: int, - status_id: int, - quota_auto: int, - quota_fast: int, + token: str, + pool_id: int, + status_id: int, + quota_auto: int, + quota_fast: int, quota_expert: int, - reset_auto: int, - reset_fast: int, + quota_heavy: int, + reset_auto: int, + reset_fast: int, reset_expert: int, - health: float, - last_use_s: int, - last_fail_s: int, - fail_count: int, - tags: list[str], + reset_heavy: int, + health: float, + last_use_s: int, + last_fail_s: int, + fail_count: int, + tags: list[str], ) -> int: idx = len(self.token_by_idx) self.token_by_idx.append(token) @@ -151,9 +155,11 @@ class AccountRuntimeTable: self.quota_auto_by_idx.append(max(-1, min(quota_auto, 32767))) self.quota_fast_by_idx.append(max(-1, min(quota_fast, 32767))) self.quota_expert_by_idx.append(max(-1, min(quota_expert, 32767))) + self.quota_heavy_by_idx.append(max(-1, min(quota_heavy, 32767))) self.reset_auto_at_by_idx.append(reset_auto) self.reset_fast_at_by_idx.append(reset_fast) self.reset_expert_at_by_idx.append(reset_expert) + self.reset_heavy_at_by_idx.append(reset_heavy) self.inflight_by_idx.append(0) self.fail_count_by_idx.append(min(fail_count, 65535)) self.health_by_idx.append(health) @@ -170,36 +176,40 @@ class AccountRuntimeTable: def _update_slot( self, - idx: int, - pool_id: int, - status_id: int, - quota_auto: int, - quota_fast: int, + idx: int, + pool_id: int, + status_id: int, + quota_auto: int, + quota_fast: int, quota_expert: int, - reset_auto: int, - reset_fast: int, + quota_heavy: int, + reset_auto: int, + reset_fast: int, reset_expert: int, - health: float, - last_use_s: int, - last_fail_s: int, - fail_count: int, - old_tags: list[str], - new_tags: list[str], + reset_heavy: int, + health: float, + last_use_s: int, + last_fail_s: int, + fail_count: int, + old_tags: list[str], + new_tags: list[str], ) -> None: self._remove_from_indexes(idx) self._remove_from_tag_idx(idx, old_tags) - self.pool_by_idx[idx] = pool_id - self.status_by_idx[idx] = status_id - self.quota_auto_by_idx[idx] = max(-1, min(quota_auto, 32767)) - self.quota_fast_by_idx[idx] = max(-1, min(quota_fast, 32767)) - self.quota_expert_by_idx[idx] = max(-1, min(quota_expert, 32767)) - self.reset_auto_at_by_idx[idx] = reset_auto - self.reset_fast_at_by_idx[idx] = reset_fast - self.reset_expert_at_by_idx[idx] = reset_expert - self.fail_count_by_idx[idx] = min(fail_count, 65535) - self.last_use_at_by_idx[idx] = last_use_s - self.last_fail_at_by_idx[idx] = last_fail_s + self.pool_by_idx[idx] = pool_id + self.status_by_idx[idx] = status_id + self.quota_auto_by_idx[idx] = max(-1, min(quota_auto, 32767)) + self.quota_fast_by_idx[idx] = max(-1, min(quota_fast, 32767)) + self.quota_expert_by_idx[idx] = max(-1, min(quota_expert, 32767)) + self.quota_heavy_by_idx[idx] = max(-1, min(quota_heavy, 32767)) + self.reset_auto_at_by_idx[idx] = reset_auto + self.reset_fast_at_by_idx[idx] = reset_fast + self.reset_expert_at_by_idx[idx] = reset_expert + self.reset_heavy_at_by_idx[idx] = reset_heavy + self.fail_count_by_idx[idx] = min(fail_count, 65535) + self.last_use_at_by_idx[idx] = last_use_s + self.last_fail_at_by_idx[idx] = last_fail_s # health is not reset on update self._add_to_indexes(idx) diff --git a/app/dataplane/proxy/__init__.py b/app/dataplane/proxy/__init__.py index 106e6d6d..094f584b 100644 --- a/app/dataplane/proxy/__init__.py +++ b/app/dataplane/proxy/__init__.py @@ -5,8 +5,6 @@ Kept as a thin shim so callers in the dataplane need not import control modules directly. """ -from __future__ import annotations - from app.control.proxy import ProxyDirectory, get_proxy_directory from app.control.proxy.models import ( ProxyLease, ProxyFeedback, ProxyScope, RequestKind, @@ -22,10 +20,11 @@ class ProxyRuntime: async def acquire( self, *, - scope: ProxyScope = ProxyScope.APP, - kind: RequestKind = RequestKind.HTTP, + scope: ProxyScope = ProxyScope.APP, + kind: RequestKind = RequestKind.HTTP, + resource: bool = False, ) -> ProxyLease: - return await self._dir.acquire(scope=scope, kind=kind) + return await self._dir.acquire(scope=scope, kind=kind, resource=resource) async def feedback(self, lease: ProxyLease, result: ProxyFeedback) -> None: await self._dir.feedback(lease, result) diff --git a/app/dataplane/proxy/adapters/headers.py b/app/dataplane/proxy/adapters/headers.py index cc934716..be1866fa 100644 --- a/app/dataplane/proxy/adapters/headers.py +++ b/app/dataplane/proxy/adapters/headers.py @@ -3,8 +3,6 @@ All values are sanitized to ASCII-safe Latin-1 before use. """ -from __future__ import annotations - import base64 import random import re @@ -49,7 +47,7 @@ def _sanitize(value: Optional[str], *, field: str, strip_spaces: bool = False) - def _statsig_id() -> str: cfg = get_config() - if cfg.get_bool("app.dynamic_statsig", False): + if cfg.get_bool("features.dynamic_statsig", False): if random.choice((True, False)): rand = "".join(random.choices(string.ascii_lowercase + string.digits, k=5)) msg = f"e:TypeError: Cannot read properties of null (reading 'children['{rand}']')" diff --git a/app/dataplane/proxy/adapters/session.py b/app/dataplane/proxy/adapters/session.py index 5e321daa..6a438d11 100644 --- a/app/dataplane/proxy/adapters/session.py +++ b/app/dataplane/proxy/adapters/session.py @@ -1,7 +1,5 @@ """curl_cffi session builder for reverse-proxy requests.""" -from __future__ import annotations - import asyncio from typing import Any from urllib.parse import urlparse @@ -24,7 +22,10 @@ def _resolve_browser(lease: ProxyLease | None) -> str: def _skip_proxy_ssl(proxy_url: str) -> bool: if not proxy_url: return False - return get_config().get_bool("proxy.skip_proxy_ssl_verify", False) + cfg = get_config() + # New key; fall back to old key for backward compatibility. + return cfg.get_bool("proxy.egress.skip_ssl_verify", + cfg.get_bool("proxy.skip_proxy_ssl_verify", False)) def normalize_proxy_url(url: str) -> str: diff --git a/app/dataplane/proxy/selector.py b/app/dataplane/proxy/selector.py index a6d73688..3f4005a4 100644 --- a/app/dataplane/proxy/selector.py +++ b/app/dataplane/proxy/selector.py @@ -3,8 +3,6 @@ Extracted from ProxyDirectory.acquire() to formalize the dataplane separation. """ -from __future__ import annotations - from app.control.proxy.models import ( EgressMode, EgressNode, EgressNodeState, ProxyScope, RequestKind, diff --git a/app/dataplane/proxy/table.py b/app/dataplane/proxy/table.py index aa8bdb43..8696b6e3 100644 --- a/app/dataplane/proxy/table.py +++ b/app/dataplane/proxy/table.py @@ -5,8 +5,6 @@ dataplane/control-plane boundary. The control-plane ProxyDirectory owns mutation; this module provides a read-only snapshot for selector logic. """ -from __future__ import annotations - from dataclasses import dataclass, field from app.control.proxy.models import ( diff --git a/app/dataplane/reverse/classifier.py b/app/dataplane/reverse/classifier.py index 27129157..ac2bfeb6 100644 --- a/app/dataplane/reverse/classifier.py +++ b/app/dataplane/reverse/classifier.py @@ -3,8 +3,6 @@ Maps upstream HTTP status codes and response bodies to a ResultCategory. """ -from __future__ import annotations - from typing import Any from .types import ResultCategory diff --git a/app/dataplane/reverse/executor.py b/app/dataplane/reverse/executor.py index c218ba0b..af0403a0 100644 --- a/app/dataplane/reverse/executor.py +++ b/app/dataplane/reverse/executor.py @@ -7,8 +7,6 @@ directly continues to work; the executor wraps the same pattern with structured feedback and classification. """ -from __future__ import annotations - import asyncio from typing import Any @@ -57,7 +55,7 @@ async def execute( # Step 2: Acquire account directory = await get_account_directory() - lease = await directory.reserve(plan.pool_id, plan.mode_id) + lease = await directory.reserve(plan.pool_candidates, plan.mode_id) if lease is None: return ReverseResult( category=ResultCategory.RATE_LIMITED, diff --git a/app/dataplane/reverse/feedback.py b/app/dataplane/reverse/feedback.py index 440a103f..2c9053e8 100644 --- a/app/dataplane/reverse/feedback.py +++ b/app/dataplane/reverse/feedback.py @@ -3,8 +3,6 @@ Called after every upstream call to update account health/quota and proxy state. """ -from __future__ import annotations - from app.control.account.commands import AccountPatch from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind from app.platform.runtime.clock import now_ms diff --git a/app/dataplane/reverse/planner.py b/app/dataplane/reverse/planner.py index 1d046fd3..b034b967 100644 --- a/app/dataplane/reverse/planner.py +++ b/app/dataplane/reverse/planner.py @@ -4,8 +4,6 @@ Determines the endpoint URL, transport kind, pool/mode IDs, and timeout for a given operation. Does NOT execute anything — pure data transform. """ -from __future__ import annotations - from typing import Any from app.control.model.spec import ModelSpec @@ -41,12 +39,12 @@ def build_plan(spec: ModelSpec, request: dict[str, Any] | None = None) -> Revers defaults = _DEFAULTS.get(tkind, _DEFAULTS[TransportKind.HTTP_JSON]) return ReversePlan( - endpoint = endpoint, - transport_kind = tkind, - pool_id = spec.pool_id(), - mode_id = int(spec.mode_id), - timeout_s = defaults["timeout_s"], - content_type = defaults["content_type"], + endpoint = endpoint, + transport_kind = tkind, + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + timeout_s = defaults["timeout_s"], + content_type = defaults["content_type"], ) diff --git a/app/dataplane/reverse/protocol/xai_assets.py b/app/dataplane/reverse/protocol/xai_assets.py index b989c3ee..1438ee69 100644 --- a/app/dataplane/reverse/protocol/xai_assets.py +++ b/app/dataplane/reverse/protocol/xai_assets.py @@ -8,9 +8,8 @@ URL reference (from production reverse analysis): The app-chat upload endpoint is handled separately in transport/asset_upload.py. """ -from __future__ import annotations - -from typing import Any, Dict, List, Optional +import pathlib +import urllib.parse from urllib.parse import urlparse ASSETS_LIST_URL = "https://grok.com/rest/assets" @@ -21,7 +20,7 @@ ASSETS_DOWNLOAD_BASE = "https://assets.grok.com" APP_CHAT_UPLOAD_URL = "https://grok.com/rest/app-chat/upload-file" # MIME type mapping used for download content-type inference. -_EXTENSION_MIME: Dict[str, str] = { +_EXTENSION_MIME: dict[str, str] = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", @@ -30,10 +29,6 @@ _EXTENSION_MIME: Dict[str, str] = { ".webm": "video/webm", } -import pathlib -import urllib.parse - - def asset_delete_url(asset_id: str) -> str: return f"{ASSETS_DELETE_URL}/{asset_id}" @@ -57,14 +52,30 @@ def resolve_download_url(file_path: str) -> tuple[str, str, str]: return url, origin, f"{origin}/" -def infer_content_type(url: str) -> Optional[str]: +def infer_content_type(url: str) -> str | None: """Return a best-guess MIME type for *url* based on file extension.""" path = pathlib.Path(urllib.parse.urlparse(url).path) return _EXTENSION_MIME.get(path.suffix.lower()) +def resolve_asset_reference( + file_id: str, + file_uri: str, + *, + user_id: str | None = None, +) -> str | None: + """Return the absolute asset content URL used by image-edit requests.""" + if file_uri: + url, _, _ = resolve_download_url(file_uri) + return url + if file_id and user_id: + return f"{ASSETS_DOWNLOAD_BASE}/users/{user_id}/{file_id}/content" + return None + + __all__ = [ "ASSETS_LIST_URL", "ASSETS_DELETE_URL", "ASSETS_DOWNLOAD_BASE", "APP_CHAT_UPLOAD_URL", "asset_delete_url", "resolve_download_url", "infer_content_type", + "resolve_asset_reference", ] diff --git a/app/dataplane/reverse/protocol/xai_auth.py b/app/dataplane/reverse/protocol/xai_auth.py index 6da1049f..1ad20d1e 100644 --- a/app/dataplane/reverse/protocol/xai_auth.py +++ b/app/dataplane/reverse/protocol/xai_auth.py @@ -4,10 +4,9 @@ Each public function handles proxy acquisition, the upstream call, and proxy feedback, returning a simple result or raising ``UpstreamError``. """ -from __future__ import annotations - import datetime import random +from typing import TYPE_CHECKING from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config @@ -15,9 +14,13 @@ from app.platform.errors import UpstreamError from app.platform.net.grpc import GrpcClient, GrpcStatus from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs from app.dataplane.reverse.transport.grpc_web import post_grpc_web from app.dataplane.reverse.transport.http import post_json +if TYPE_CHECKING: + pass + # ------------------------------------------------------------------ # Endpoint URLs # ------------------------------------------------------------------ @@ -35,11 +38,11 @@ def build_accept_tos_payload() -> bytes: return GrpcClient.encode_payload(b"\x10\x01") -def build_nsfw_mgmt_payload() -> bytes: - """gRPC-Web payload that sets always_show_nsfw_content=true.""" +def build_nsfw_mgmt_payload(enabled: bool = True) -> bytes: + """gRPC-Web payload that sets always_show_nsfw_content to *enabled*.""" name = b"always_show_nsfw_content" inner = b"\x0a" + bytes([len(name)]) + name - protobuf = b"\x0a\x02\x10\x01\x12" + bytes([len(inner)]) + inner + protobuf = b"\x0a\x02\x10" + (b"\x01" if enabled else b"\x00") + b"\x12" + bytes([len(inner)]) + inner return GrpcClient.encode_payload(protobuf) @@ -72,59 +75,57 @@ async def _grpc_call( label: str, origin: str = "https://grok.com", referer: str = "https://grok.com/", + session: ResettableSession | None = None, + lease=None, ) -> GrpcStatus: - """Acquire a proxy lease, POST a gRPC-Web frame, report feedback, parse status.""" + """POST a gRPC-Web frame and parse the status. + + When *session* and *lease* are both provided the caller manages the proxy + lifecycle (no acquire / feedback is done here). This allows multiple calls + to share one TCP connection and one proxy lease, avoiding repeated TLS + handshakes. + + When called without *session* / *lease* (the default) the function acquires + its own lease and manages proxy feedback, preserving the original behaviour. + """ cfg = get_config() timeout_s = cfg.get_float("nsfw.timeout", 30.0) + shared = session is not None and lease is not None - proxy = await get_proxy_runtime() - lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP) + if not shared: + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP) try: _, trailers = await post_grpc_web( - url, - token, - payload, - lease = lease, - timeout_s = timeout_s, - origin = origin, - referer = referer, + url, token, payload, + lease=lease, timeout_s=timeout_s, origin=origin, referer=referer, + session=session, ) except UpstreamError as exc: - await proxy.feedback( - lease, - ProxyFeedback( - kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 - else ProxyFeedbackKind.FORBIDDEN, - status_code = exc.status or 502, - ), - ) + if not shared: + await proxy.feedback(lease, ProxyFeedback( + kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code=exc.status or 502, + )) raise except Exception as exc: - await proxy.feedback( - lease, - ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), - ) + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) raise UpstreamError(f"{label}: transport error: {exc}") from exc status = GrpcClient.get_status(trailers) if status.ok or status.code == -1: - await proxy.feedback( - lease, - ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), - ) + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) logger.debug("{}: gRPC ok (code={})", label, status.code) else: - await proxy.feedback( - lease, - ProxyFeedback( - kind = ProxyFeedbackKind.UPSTREAM_5XX, - status_code = status.http_equiv, - ), - ) + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.UPSTREAM_5XX, status_code=status.http_equiv)) raise UpstreamError( f"{label}: gRPC error code={status.code} message={status.message!r}", - status = status.http_equiv, + status=status.http_equiv, ) return status @@ -146,66 +147,111 @@ async def accept_tos(token: str) -> GrpcStatus: ) -async def enable_nsfw(token: str) -> GrpcStatus: - """Enable always_show_nsfw_content for *token* via gRPC-Web.""" +async def set_nsfw(token: str, enabled: bool) -> GrpcStatus: + """Set always_show_nsfw_content for *token* via gRPC-Web.""" return await _grpc_call( NSFW_MGMT_URL, token, - build_nsfw_mgmt_payload(), - label = "enable_nsfw", + build_nsfw_mgmt_payload(enabled), + label = "enable_nsfw" if enabled else "disable_nsfw", origin = "https://grok.com", referer = "https://grok.com/?_s=data", ) -async def set_birth_date(token: str) -> dict: - """Post a random adult birth date for *token* via REST.""" +async def enable_nsfw(token: str) -> GrpcStatus: + """Enable always_show_nsfw_content for *token* via gRPC-Web.""" + return await set_nsfw(token, True) + + +async def disable_nsfw(token: str) -> GrpcStatus: + """Disable always_show_nsfw_content for *token* via gRPC-Web.""" + return await set_nsfw(token, False) + + +async def set_birth_date( + token: str, + session: ResettableSession | None = None, + lease=None, +) -> dict: + """Post a random adult birth date for *token* via REST. + + Accepts optional *session* / *lease* for connection reuse (see ``_grpc_call``). + """ import orjson + cfg = get_config() + timeout_s = cfg.get_float("nsfw.timeout", 30.0) + shared = session is not None and lease is not None + + if not shared: + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP) + + payload = orjson.dumps(build_set_birth_payload()) + try: + result = await post_json( + SET_BIRTH_URL, token, payload, + lease=lease, timeout_s=timeout_s, + origin="https://grok.com", referer="https://grok.com/?_s=data", + session=session, + ) + except UpstreamError as exc: + if not shared: + await proxy.feedback(lease, ProxyFeedback( + kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code=exc.status or 502, + )) + raise + except Exception as exc: + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"set_birth_date: transport error: {exc}") from exc + + if not shared: + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + logger.debug("set_birth_date: ok") + return result + + +async def nsfw_sequence(token: str) -> None: + """Run set_birth_date → enable_nsfw sharing one session + lease. + + Compared to calling the two functions individually this saves one TCP+TLS + handshake per token, which matters in high-concurrency batch scenarios. + """ cfg = get_config() timeout_s = cfg.get_float("nsfw.timeout", 30.0) proxy = await get_proxy_runtime() lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP) - payload = orjson.dumps(build_set_birth_payload()) + kwargs = build_session_kwargs(lease=lease) try: - result = await post_json( - SET_BIRTH_URL, - token, - payload, - lease = lease, - timeout_s = timeout_s, - origin = "https://grok.com", - referer = "https://grok.com/?_s=home", - ) + async with ResettableSession(**kwargs) as session: + await set_birth_date(token, session=session, lease=lease) + await _grpc_call( + NSFW_MGMT_URL, token, build_nsfw_mgmt_payload(), + label="enable_nsfw", origin="https://grok.com", referer="https://grok.com/?_s=data", + session=session, lease=lease, + ) + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200)) + logger.debug("nsfw_sequence: completed for token={}", token[:8]) except UpstreamError as exc: - await proxy.feedback( - lease, - ProxyFeedback( - kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 - else ProxyFeedbackKind.FORBIDDEN, - status_code = exc.status or 502, - ), - ) + await proxy.feedback(lease, ProxyFeedback( + kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500 + else ProxyFeedbackKind.FORBIDDEN, + status_code=exc.status or 502, + )) raise except Exception as exc: - await proxy.feedback( - lease, - ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR), - ) - raise UpstreamError(f"set_birth_date: transport error: {exc}") from exc - - await proxy.feedback( - lease, - ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200), - ) - logger.debug("set_birth_date: ok") - return result + await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)) + raise UpstreamError(f"nsfw_sequence: transport error: {exc}") from exc __all__ = [ "ACCEPT_TOS_URL", "NSFW_MGMT_URL", "SET_BIRTH_URL", "build_accept_tos_payload", "build_nsfw_mgmt_payload", "build_set_birth_payload", - "accept_tos", "enable_nsfw", "set_birth_date", + "accept_tos", "set_nsfw", "enable_nsfw", "disable_nsfw", "set_birth_date", "nsfw_sequence", ] diff --git a/app/dataplane/reverse/protocol/xai_chat.py b/app/dataplane/reverse/protocol/xai_chat.py index 368df4f6..d6edbeb3 100644 --- a/app/dataplane/reverse/protocol/xai_chat.py +++ b/app/dataplane/reverse/protocol/xai_chat.py @@ -1,45 +1,32 @@ -"""XAI app-chat protocol — payload builder and response line classifier.""" - -from __future__ import annotations +"""XAI app-chat protocol — payload builder and SSE stream adapter.""" import re -import uuid +from dataclasses import dataclass from typing import Any import orjson from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config -from app.control.model.enums import ModeId - -# --------------------------------------------------------------------------- -# Mode → modeId string map (derived from browser JS reverse) -# Applies to SuperGrok multi-agent models that require modeId field. -# --------------------------------------------------------------------------- -_GROK_MODE_IDS: dict[str, str] = { - "MODEL_MODE_FAST": "fast", - "MODEL_MODE_EXPERT": "expert", - "MODEL_MODE_HEAVY": "heavy", - "MODEL_MODE_GROK_420": "expert", - "MODEL_MODE_GROK_4_1_THINKING": "expert", - "MODEL_MODE_GROK_4_1_MINI_THINKING": "expert", -} +from app.control.model.enums import ModeId, MODE_STRINGS +from app.dataplane.reverse.protocol.xai_chat_reasoning import ReasoningAggregator def build_chat_payload( *, - message: str, - model_name: str, - model_mode: str | None = None, - file_attachments: list[str] = (), - tool_overrides: dict[str, Any] | None = None, + message: str, + mode_id: ModeId, + file_attachments: list[str] = (), + tool_overrides: dict[str, Any] | None = None, model_config_override: dict[str, Any] | None = None, - request_overrides: dict[str, Any] | None = None, + request_overrides: dict[str, Any] | None = None, ) -> dict[str, Any]: """Build the JSON payload for POST /rest/app-chat/conversations/new.""" cfg = get_config() payload: dict[str, Any] = { + "collectionIds": [], + "connectors": [], "deviceEnvInfo": { "darkModeEnabled": False, "devicePixelRatio": 2, @@ -48,7 +35,7 @@ def build_chat_payload( "viewportHeight": 1083, "viewportWidth": 2056, }, - "disableMemory": cfg.get_bool("app.disable_memory", False), + "disableMemory": not cfg.get_bool("features.memory", False), "disableSearch": False, "disableSelfHarmShortCircuit": False, "disableTextFollowUps": False, @@ -61,31 +48,24 @@ def build_chat_payload( "imageAttachments": [], "imageGenerationCount": 2, "isAsyncChat": False, - "isReasoning": False, "message": message, - "modelMode": model_mode, - "modelName": model_name, - "responseMetadata": { - "requestModelDetails": {"modelId": model_name}, - }, + "modeId": MODE_STRINGS[mode_id], + "responseMetadata": {}, "returnImageBytes": False, "returnRawGrokInXaiRequest": False, + "searchAllConnectors": False, "sendFinalMetadata": True, - "temporary": cfg.get_bool("app.temporary", True), - "toolOverrides": tool_overrides or {}, + "temporary": cfg.get_bool("features.temporary", True), + "toolOverrides": tool_overrides or { + "gmailSearch": False, + "googleCalendarSearch": False, + "outlookSearch": False, + "outlookCalendarSearch": False, + "googleDriveSearch": False, + }, } - # For models that expose modeId, prefer it and strip modelName/modelMode - # (mirrors browser front-end logic). - if model_mode: - mode_id = _GROK_MODE_IDS.get(model_mode) - if mode_id: - payload["modeId"] = mode_id - payload.pop("modelName", None) - payload.pop("modelMode", None) - - # Optional operator-supplied system instruction. - custom = cfg.get_str("app.custom_instruction", "").strip() + custom = cfg.get_str("features.custom_instruction", "").strip() if custom: payload["customPersonality"] = custom @@ -96,24 +76,27 @@ def build_chat_payload( payload.update({k: v for k, v in request_overrides.items() if v is not None}) logger.debug( - "Chat payload: model={} mode={} msg_len={} files={}", - model_name, model_mode, len(message), len(file_attachments), + "Chat payload: mode={} msg_len={} files={}", + MODE_STRINGS[mode_id], len(message), len(file_attachments), ) return payload # --------------------------------------------------------------------------- -# Response line parsing +# SSE line classification (unchanged) # --------------------------------------------------------------------------- -_RESULT_TAG_RE = re.compile(r'"result"\s*:\s*"([^"]*)"') - -def classify_line(line: str) -> tuple[str, str]: +def classify_line(line: str | bytes) -> tuple[str, str]: """Return (event_type, data) for a raw SSE line. - event_type: 'data' | 'error' | 'done' | 'skip' + event_type: 'data' | 'done' | 'skip' + + Handles both standard SSE ``data: {...}`` lines and raw JSON lines + (upstream sometimes omits the ``data:`` prefix). """ + if isinstance(line, bytes): + line = line.decode("utf-8", "replace") line = line.strip() if not line: return "skip", "" @@ -124,35 +107,319 @@ def classify_line(line: str) -> tuple[str, str]: return "data", data if line.startswith("event:"): return "skip", "" + # Raw JSON line (no "data:" prefix) — treat as data. + if line.startswith("{"): + return "data", line return "skip", "" -def parse_token(data: str) -> str | None: - """Extract text token from a single SSE data payload.""" - try: - obj = orjson.loads(data) - except Exception: - return None +# --------------------------------------------------------------------------- +# FrameEvent — single output event from StreamAdapter.feed() +# --------------------------------------------------------------------------- - result = obj.get("result") - if not result: - return None +@dataclass(slots=True) +class FrameEvent: + """One parsed event produced by StreamAdapter.""" - # Text streaming token. - token = result.get("message", {}).get("token") - if token is not None: - return token + kind: str + """Event kind: + - ``text`` — cleaned final text token (content = token string) + - ``thinking`` — Grok main-model thinking (content = raw token) + - ``image`` — generated image final URL (content = full URL, image_id = upstream UUID) + - ``image_progress`` — generated image progress (content = percent string, image_id = upstream UUID) + - ``soft_stop`` — stream end signal + - ``skip`` — filtered frame, do nothing + """ + content: str = "" + image_id: str = "" + rollout_id: str = "" + message_tag: str = "" + message_step_id: int | None = None - # Complete message fallback. - msg = result.get("message", {}) - if msg.get("finalMetadata"): - return None - return None + +# --------------------------------------------------------------------------- +# StreamAdapter — stateful SSE frame parser +# --------------------------------------------------------------------------- + +_GROK_RENDER_RE = re.compile( + r'<grok:render\s+card_id="([^"]+)"\s+card_type="([^"]+)"\s+type="([^"]+)"' + r'[^>]*>.*?</grok:render>', + re.DOTALL, +) + +_IMAGE_BASE = "https://assets.grok.com/" + + +class StreamAdapter: + """Parse upstream SSE frames and emit :class:`FrameEvent` objects. + + One instance per HTTP request. Call :meth:`feed` for every ``data:`` + line; iterate over the returned list of events. + """ + + __slots__ = ( + "_card_cache", + "_citation_order", + "_citation_map", + "_emitted_reasoning_keys", + "_reasoning", + "thinking_buf", + "text_buf", + "image_urls", + ) + + def __init__(self) -> None: + self._card_cache: dict[str, dict] = {} + self._citation_order: list[str] = [] + self._citation_map: dict[str, int] = {} + self._emitted_reasoning_keys: set[str] = set() + self._reasoning = ReasoningAggregator() + self.thinking_buf: list[str] = [] + self.text_buf: list[str] = [] + self.image_urls: list[tuple[str, str]] = [] # [(url, imageUuid), ...] + + def references_suffix(self) -> str: + """Return a stable, language-neutral reference list for collected citations.""" + if not self._citation_order: + return "" + lines = [f"[{index}] {url}" for index, url in enumerate(self._citation_order, start=1)] + return "\n\n" + "\n".join(lines) + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + + def feed(self, data: str) -> list[FrameEvent]: + """Parse one JSON ``data:`` payload; return 0-N events.""" + try: + obj = orjson.loads(data) + except Exception: + return [] + + result = obj.get("result") + if not result: + return [] + resp = result.get("response") + if not resp: + return [] + + events: list[FrameEvent] = [] + + # ── cache every cardAttachment first ────────────────────── + card_raw = resp.get("cardAttachment") + if card_raw: + events.extend(self._handle_card(card_raw)) + + token = resp.get("token") + think = resp.get("isThinking") + tag = resp.get("messageTag") + rollout = resp.get("rolloutId") + step_id = resp.get("messageStepId") + + if tag == "tool_usage_card": + for line in self._summarize_tool_usage(resp, rollout=rollout, step_id=step_id): + self._append_reasoning( + events, + line, + rollout=rollout, + tag=tag, + step_id=step_id, + ) + return events # card events (if any) already added + + # ── raw_function_result ─────────────────────────────────── + if tag == "raw_function_result": + return events + + # ── toolUsageCardId-only follow-up frame ────────────────── + if resp.get("toolUsageCardId") and not resp.get("webSearchResults") and not resp.get("codeExecutionResult"): + return events + + # ── thinking token ──────────────────────────────────────── + if token is not None and think is True: + for line in self._reasoning.on_thinking( + str(token), + tag=tag, + rollout=rollout, + step_id=step_id if isinstance(step_id, int) else None, + ): + self._append_reasoning( + events, + line, + rollout=rollout, + tag=tag, + step_id=step_id, + ) + return events + + # ── final text token (needs cleaning) ───────────────────── + if token is not None and think is not True and tag == "final": + cleaned = self._clean_token(token) + if cleaned: + self.text_buf.append(cleaned) + events.append(FrameEvent("text", cleaned)) + return events + + # ── end signals ─────────────────────────────────────────── + if resp.get("isSoftStop"): + self._flush_pending_reasoning(events) + events.append(FrameEvent("soft_stop")) + return events + + if resp.get("finalMetadata"): + self._flush_pending_reasoning(events) + events.append(FrameEvent("soft_stop")) + return events + + return events + + # ------------------------------------------------------------------ + # Card attachment handling + # ------------------------------------------------------------------ + + def _handle_card(self, card_raw: dict) -> list[FrameEvent]: + """Cache card data; emit image event on progress=100.""" + try: + jd = orjson.loads(card_raw["jsonData"]) + except Exception: + return [] + + card_id = jd.get("id", "") + self._card_cache[card_id] = jd + + chunk = jd.get("image_chunk") + if chunk: + progress = chunk.get("progress") + uuid = chunk.get("imageUuid", "") + events: list[FrameEvent] = [] + try: + if progress is not None: + events.append(FrameEvent("image_progress", str(int(progress)), uuid)) + except (TypeError, ValueError): + pass + if chunk.get("progress") == 100 and not chunk.get("moderated"): + url = _IMAGE_BASE + chunk["imageUrl"] + self.image_urls.append((url, uuid)) + events.append(FrameEvent("image", url, uuid)) + return events + + return [] + + # ------------------------------------------------------------------ + # Token cleaning — <grok:render> → markdown + # ------------------------------------------------------------------ + + def _clean_token(self, token: str) -> str: + if "<grok:render" not in token: + return token + return _GROK_RENDER_RE.sub(self._render_replace, token) + + def _render_replace(self, m: re.Match) -> str: + card_id = m.group(1) + render_type = m.group(3) + card = self._card_cache.get(card_id) + if not card: + return "" + + if render_type == "render_searched_image": + img = card.get("image", {}) + title = img.get("title", "image") + thumb = img.get("thumbnail") or img.get("original", "") + link = img.get("link", "") + if link: + return f"[![{title}]({thumb})]({link})" + return f"![{title}]({thumb})" + + if render_type == "render_generated_image": + return "" # actual URL emitted by progress=100 card frame + + if render_type == "render_inline_citation": + url = card.get("url", "") + if not url: + return "" + index = self._citation_map.get(url) + if index is None: + self._citation_order.append(url) + index = len(self._citation_order) + self._citation_map[url] = index + return f" [{index}]" + + return "" + + def _append_reasoning( + self, + events: list[FrameEvent], + line: str, + *, + rollout: str | None, + tag: str | None, + step_id: Any, + ) -> None: + text = line.strip() + if not text: + return + + key = self._normalize_key(text) + if key in self._emitted_reasoning_keys: + return + + self._emitted_reasoning_keys.add(key) + formatted = text if text.endswith("\n") else text + "\n" + self.thinking_buf.append(formatted) + events.append(FrameEvent( + "thinking", + formatted, + rollout_id=rollout or "", + message_tag=tag or "", + message_step_id=step_id if isinstance(step_id, int) else None, + )) + + def _flush_pending_reasoning(self, events: list[FrameEvent]) -> None: + for line in self._reasoning.finalize(): + self._append_reasoning( + events, + line, + rollout="", + tag="summary", + step_id=None, + ) + + def _summarize_tool_usage(self, resp: dict[str, Any], *, rollout: str | None, step_id: int | None) -> list[str]: + card = resp.get("toolUsageCard") + if not isinstance(card, dict): + return [] + + tool_name = "" + args: dict[str, Any] = {} + for key, value in card.items(): + if key == "toolUsageCardId" or not isinstance(value, dict): + continue + tool_name = re.sub(r"(?<!^)([A-Z])", r"_\1", key).lower() + raw_args = value.get("args") + if isinstance(raw_args, dict): + args = raw_args + break + + if not tool_name: + return [] + + return self._reasoning.on_tool_usage( + tool_name, + args, + rollout=rollout, + step_id=step_id, + ) + + def _normalize_key(self, text: str) -> str: + lowered = text.lower() + lowered = re.sub(r"https?://\S+", "", lowered) + lowered = re.sub(r"[^\w\u4e00-\u9fff]+", "", lowered) + return lowered __all__ = [ "build_chat_payload", "classify_line", - "parse_token", - "_GROK_MODE_IDS", + "FrameEvent", + "StreamAdapter", ] diff --git a/app/dataplane/reverse/protocol/xai_chat_reasoning.py b/app/dataplane/reverse/protocol/xai_chat_reasoning.py new file mode 100644 index 00000000..3ddea7e5 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_chat_reasoning.py @@ -0,0 +1,633 @@ +"""Reasoning normalization and aggregation for XAI app-chat streams.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any + + +_GENERIC_HEADERS = { + "", + "thinking about your request", +} + +_PROGRESSIVE_HINTS = ( + "正在", "准备", "计划", "查找", "搜索", "浏览", "确认", "核对", "整合", "挖掘", "比对", + "checking", "browsing", "verifying", "integrating", "digging", "cross-checking", "searching", "planning", +) + +_FINDING_HINTS = ( + "尚未", "已经", "已", "确认", "表明", "说明", "显示", "主要", "通常", "支持", "出现", "启动", + "持续", "提升", "更新", "灰度", "发布", "上线", "多模态", "视觉", "专家", "context", "token", + "参数", "每天", "大潮", "小潮", "半日潮", "引力", "周期", "模式", "confirmed", "launched", + "released", "rollout", "testing", "native multimodal", "widely believed", "latest", +) + +_LOW_VALUE_PREFIXES = ( + "用户", "user", "i can", "我可以", "我收集", "建议", "need", "需要", "应该", "since instructions", + "proposed", "mermaid", "可以用", "我建议", +) + +_TRACK_RULES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("latest_updates", ("最新", "latest", "today", "recent", "最近", "update", "news", "本周", "4月", "april")), + ("release_status", ("release date", "released", "release", "launch", "上线", "发布", "正式发布", "current status")), + ("gray_rollout", ("灰度", "grayscale", "gray release", "灰度测试", "内测", "rollout")), + ("official_confirmation", ("official", "官网", "official site", "site:", "platform.deepseek.com", "deepseek.ai")), + ("ui_modes", ("vision", "视觉", "expert", "专家模式", "fast", "default", "ui", "界面", "mode")), + ("v4_lite", ("v4 lite", "sealion", "sealion-lite", "海狮")), + ("specs_architecture", ("specs", "parameters", "architecture", "engram", "mhc", "moe", "context", "benchmarks", "规格", "参数", "架构", "万亿")), + ("definition_basics", ("定义", "解释", "什么是", "what is", "phenomenon", "现象")), + ("causes_mechanism", ("成因", "原因", "cause", "causes", "gravity", "引力", "机制")), + ("categories_types", ("春潮", "小潮", "半日潮", "全日潮", "类型", "分类")), + ("impacts_applications", ("影响", "应用", "发电", "航运", "生活", "生态")), +) + +_ZH_LABELS = { + "understanding": "理解问题", + "scope": "检索范围", + "evidence": "核验与证据", + "finding": "关键发现", + "latest_updates": "最新动态", + "release_status": "发布状态与上线节奏", + "gray_rollout": "灰度进展", + "official_confirmation": "官方渠道确认", + "ui_modes": "Expert / Vision 模式关联", + "v4_lite": "V4 Lite 与 Sealion 线索", + "specs_architecture": "规格、架构与上下文能力", + "definition_basics": "定义与基础解释", + "causes_mechanism": "成因与机制", + "categories_types": "分类与相关类型", + "impacts_applications": "影响与应用", +} + +_EN_LABELS = { + "understanding": "Understanding", + "scope": "Research Scope", + "evidence": "Verification", + "finding": "Key Findings", + "latest_updates": "latest updates", + "release_status": "release status and rollout timing", + "gray_rollout": "gray rollout progress", + "official_confirmation": "official confirmation", + "ui_modes": "Expert / Vision mode signals", + "v4_lite": "V4 Lite and Sealion clues", + "specs_architecture": "specs, architecture, and context capability", + "definition_basics": "definition and basic explanation", + "causes_mechanism": "causes and mechanism", + "categories_types": "categories and related types", + "impacts_applications": "impacts and applications", +} + + +@dataclass(slots=True) +class ReasoningEvent: + section: str + text: str + track: str = "" + evidence_level: int = 0 + dedupe_key: str = "" + + +class ReasoningAggregator: + """Normalize raw stream fragments into enterprise-style reasoning output.""" + + __slots__ = ( + "_language", + "_en_votes", + "_zh_votes", + "_agent_search_started", + "_emitted_keys", + "_seen_tracks", + "_seen_findings", + "_pending_events", + "_section_started", + "_track_best_level", + "_track_emit_counts", + ) + + def __init__(self) -> None: + self._language: str | None = None + self._en_votes = 0 + self._zh_votes = 0 + self._agent_search_started = False + self._emitted_keys: set[str] = set() + self._seen_tracks: set[str] = set() + self._seen_findings: set[str] = set() + self._pending_events: list[ReasoningEvent] = [] + self._section_started: set[str] = set() + self._track_best_level: dict[tuple[str, str], int] = {} + self._track_emit_counts: dict[tuple[str, str], int] = {} + + def on_thinking( + self, + token: str, + *, + tag: str | None, + rollout: str | None, + step_id: int | None, + ) -> list[str]: + self._observe_language(token) + tag_name = str(tag or "").strip() + text = str(token or "").strip() + if not text: + return [] + + if tag_name == "header": + event = self._normalize_header(text, step_id=step_id) + return self._dispatch(event) if event else [] + + if tag_name == "summary": + event = self._normalize_summary(text, step_id=step_id) + return self._dispatch(event) if event else [] + + event = self._normalize_summary(text, step_id=step_id) + return self._dispatch(event) if event else [] + + def on_tool_usage( + self, + tool_name: str, + args: dict[str, Any], + *, + rollout: str | None, + step_id: int | None, + ) -> list[str]: + lines: list[str] = [] + self._observe_language(str(args.get("query") or args.get("message") or args.get("instructions") or "")) + + if tool_name == "web_search": + query = str(args.get("query") or args.get("q") or "").strip() + if not query: + return [] + if str(rollout or "").startswith("Agent") and not self._agent_search_started: + self._agent_search_started = True + lines.extend(self._dispatch(ReasoningEvent( + "scope", + self._localized_line("agents_started"), + dedupe_key="scope:agents_started", + ))) + track = self._infer_track(query) + if not track: + return lines + lines.extend(self._dispatch(ReasoningEvent( + "scope", + self._localized_track_line(track), + track=track, + evidence_level=1, + dedupe_key=f"scope:web:{track}", + ))) + return lines + + if tool_name in {"x_search", "x_keyword_search", "x_semantic_search"}: + query = str(args.get("query") or "").strip() + track = self._infer_track(query) + if not track: + return [] + return self._dispatch(ReasoningEvent( + "evidence", + self._localized_social_line(track), + track=track, + evidence_level=2, + dedupe_key=f"evidence:social:{track}", + )) + + if tool_name == "browse_page": + url = str(args.get("url") or "").strip() + source_kind, track = self._classify_page_source(url, args) + if not source_kind: + return [] + return self._dispatch(ReasoningEvent( + "evidence", + self._localized_browse_line(source_kind, track), + track=track or source_kind, + evidence_level=4 if source_kind in {"official", "product"} else 3, + dedupe_key=f"evidence:browse:{source_kind}:{track or ''}", + )) + + if tool_name in {"search_images", "image_search"}: + description = str(args.get("image_description") or args.get("imageDescription") or "").strip() + if not description: + return [] + topic = self._classify_image_topic(description) + if not topic: + return [] + return self._dispatch(ReasoningEvent( + "scope", + self._localized_image_line(topic), + track="visual_assets", + evidence_level=1, + dedupe_key=f"scope:image:{topic}", + )) + + if tool_name == "chatroom_send": + message = str(args.get("message") or "").strip() + if not message: + return [] + lines = [] + for section, text, track, level in self._extract_report_events(message): + lines.extend(self._dispatch(ReasoningEvent( + section, + text, + track=track, + evidence_level=level, + dedupe_key=f"{section}:report:{track}:{self._normalize_key(text)}", + ))) + return lines + + if tool_name == "code_execution": + return self._dispatch(ReasoningEvent( + "evidence", + self._localized_line("code_execution"), + dedupe_key="evidence:code_execution", + )) + + return [] + + def finalize(self) -> list[str]: + if not self._pending_events: + return [] + if self._language is None: + self._language = "en" if self._en_votes > 0 and self._zh_votes == 0 else "zh" + return self._flush_pending() + + def _normalize_header(self, text: str, *, step_id: int | None) -> ReasoningEvent | None: + stripped = text.strip() + if stripped.lower() in _GENERIC_HEADERS: + return None + section = "understanding" if not self._looks_like_verification(stripped) and (step_id or 0) <= 1 else "evidence" + return ReasoningEvent(section, self._to_bullet_text(stripped), dedupe_key=f"{section}:header:{self._normalize_key(stripped)}") + + def _normalize_summary(self, text: str, *, step_id: int | None) -> ReasoningEvent | None: + summary = text.lstrip("- ").strip() + if not summary: + return None + if summary.startswith(("建议搜索", "正在调用工具搜索")): + return None + + track = self._infer_track(summary) + if self._looks_like_progress(summary): + section = "evidence" if self._looks_like_verification(summary) else "scope" + return ReasoningEvent(section, self._to_bullet_text(summary), track=track, evidence_level=2 if section == "evidence" else 1, dedupe_key=f"{section}:summary:{self._normalize_key(summary)}") + + if self._looks_like_finding(summary): + if self._is_unconfirmed_signal(summary): + return ReasoningEvent("evidence", self._to_bullet_text(summary), track=track, evidence_level=2, dedupe_key=f"evidence:summary:{self._normalize_key(summary)}") + if not self._agent_search_started and (step_id or 0) <= 1: + return ReasoningEvent("understanding", self._to_bullet_text(summary), track=track, evidence_level=2, dedupe_key=f"understanding:summary:{self._normalize_key(summary)}") + return ReasoningEvent("finding", self._to_bullet_text(summary), track=track, evidence_level=3, dedupe_key=f"finding:summary:{self._normalize_key(summary)}") + + section = "understanding" if (step_id or 0) <= 1 else "scope" + return ReasoningEvent(section, self._to_bullet_text(summary), track=track, evidence_level=1, dedupe_key=f"{section}:summary:{self._normalize_key(summary)}") + + def _extract_report_events(self, message: str) -> list[tuple[str, str, str, int]]: + parts = re.split(r"(?:\n+|[。!?!?;;]+|\s+-\s+)", message.replace("\\n", "\n")) + candidates: list[tuple[int, str]] = [] + for raw_part in parts: + clause = self._clean_report_clause(raw_part) + if not clause: + continue + if self._language == "zh" and not re.search(r"[\u4e00-\u9fff]", clause): + continue + if self._language == "en" and re.search(r"[\u4e00-\u9fff]", clause): + continue + score = self._score_report_clause(clause) + if score <= 0: + continue + candidates.append((score, clause)) + + candidates.sort(key=lambda item: (-item[0], len(item[1]))) + results: list[tuple[str, str, str, int]] = [] + seen_local: set[str] = set() + seen_track_counts: dict[tuple[str, str], int] = {} + for _, clause in candidates: + key = self._normalize_key(clause) + if key in seen_local: + continue + seen_local.add(key) + track = self._infer_track(clause) + section = "finding" if self._looks_like_finding(clause) else "evidence" + if self._is_unconfirmed_signal(clause): + section = "evidence" + track_key = (section, track or "_") + current_track_count = seen_track_counts.get(track_key, 0) + max_track_count = 2 if section == "finding" else 1 + if current_track_count >= max_track_count: + continue + seen_track_counts[track_key] = current_track_count + 1 + level = self._infer_evidence_level(clause, default=3 if section == "finding" else 2) + results.append((section, self._to_bullet_text(clause), track, level)) + if len(results) >= 6: + break + results.sort(key=lambda item: (0 if item[0] == "evidence" else 1, item[2], -item[3])) + return results + + def _dispatch(self, event: ReasoningEvent) -> list[str]: + if self._language is None: + self._pending_events.append(event) + if self._zh_votes > 0: + self._language = "zh" + elif self._en_votes >= 3: + self._language = "en" + elif len(self._pending_events) < 4: + return [] + else: + self._language = "en" + return self._flush_pending() + + lines: list[str] = [] + if self._pending_events: + lines.extend(self._flush_pending()) + lines.extend(self._emit(event)) + return lines + + def _flush_pending(self) -> list[str]: + lines: list[str] = [] + pending = self._pending_events + self._pending_events = [] + for event in pending: + lines.extend(self._emit(event)) + return lines + + def _emit(self, event: ReasoningEvent) -> list[str]: + text = event.text.strip() + if not text: + return [] + if event.section == "scope" and ("evidence" in self._section_started or "finding" in self._section_started): + return [] + if event.section == "evidence" and "finding" in self._section_started: + if event.evidence_level >= 4 or event.track in { + "latest_updates", + "release_status", + "official_confirmation", + "specs_architecture", + "v4_lite", + }: + promoted_key = event.dedupe_key or f"evidence:{self._normalize_key(text)}" + event = ReasoningEvent( + "finding", + text, + track=event.track, + evidence_level=event.evidence_level, + dedupe_key=f"finding:promoted:{promoted_key}", + ) + else: + return [] + + dedupe_key = event.dedupe_key or f"{event.section}:{self._normalize_key(text)}" + if dedupe_key in self._emitted_keys: + return [] + + if event.track: + count_key = (event.section, event.track) + emitted_count = self._track_emit_counts.get(count_key, 0) + max_per_track = 1 if event.section in {"scope", "evidence"} else 2 + if emitted_count >= max_per_track and not dedupe_key.endswith("agents_started"): + return [] + best_key = (event.section, event.track) + best_level = self._track_best_level.get(best_key, -1) + if best_level > event.evidence_level: + return [] + self._track_best_level[best_key] = max(best_level, event.evidence_level) + self._track_emit_counts[count_key] = emitted_count + 1 + + self._emitted_keys.add(dedupe_key) + lines: list[str] = [] + if event.section not in self._section_started: + self._section_started.add(event.section) + lines.append(self._section_title(event.section) + "\n") + lines.append(text + "\n") + return lines + + def _observe_language(self, text: str) -> None: + if not text: + return + cjk_count = len(re.findall(r"[\u4e00-\u9fff]", text)) + en_count = len(re.findall(r"[A-Za-z]", text)) + if cjk_count >= 4 or cjk_count > max(2, en_count // 2): + self._zh_votes += 1 + if self._language is None: + self._language = "zh" + return + if en_count >= 4: + self._en_votes += 1 + + def _section_title(self, section: str) -> str: + labels = _ZH_LABELS if self._language != "en" else _EN_LABELS + return labels.get(section, section) + + def _localized_line(self, key: str) -> str: + zh_map = { + "agents_started": "- 已启动并行代理进行交叉检索与核验。", + "code_execution": "- 正在执行代码或生成可运行内容。", + } + en_map = { + "agents_started": "- Parallel agents have started cross-checking the topic.", + "code_execution": "- Executing code or generating runnable content.", + } + mapping = zh_map if self._language != "en" else en_map + return mapping[key] + + def _localized_track_line(self, track: str) -> str: + label = self._track_label(track) + if self._language == "en": + return f"- Parallel research: {label}." + return f"- 并行检索:{label}。" + + def _localized_social_line(self, track: str) -> str: + label = self._track_label(track) + if self._language == "en": + return f"- Social cross-check: {label}." + return f"- 社媒交叉核验:{label}。" + + def _localized_browse_line(self, source_kind: str, track: str) -> str: + track_label = self._track_label(track) if track else "" + if self._language == "en": + mapping = { + "official": "Page verification: official site and official pages", + "product": "Page verification: product page and live UI", + "community": "Page verification: public reports and community write-ups", + } + else: + mapping = { + "official": "页面核对:官网与官方页面", + "product": "页面核对:产品页面与实际界面", + "community": "页面核对:公开报道与社区文章", + } + base = mapping[source_kind] + if track_label: + connector = ", focusing on " if self._language == "en" else ",重点核对" + return f"- {base}{connector}{track_label}{'.' if self._language == 'en' else '。'}" + return f"- {base}{'.' if self._language == 'en' else '。'}" + + def _localized_image_line(self, topic: str) -> str: + if self._language == "en": + mapping = { + "diagram": "- Visual asset search: diagrams and explanatory graphics.", + "photo": "- Visual asset search: real-world comparison photos.", + "generic": "- Visual asset search: supporting image references.", + } + else: + mapping = { + "diagram": "- 视觉素材检索:示意图与结构说明素材。", + "photo": "- 视觉素材检索:实景对比图片。", + "generic": "- 视觉素材检索:补充说明图片。", + } + return mapping[topic] + + def _track_label(self, track: str) -> str: + labels = _ZH_LABELS if self._language != "en" else _EN_LABELS + return labels.get(track, track) + + def _infer_track(self, text: str) -> str: + lowered = self._compact_query(text).lower() + if not lowered: + return "" + for track, keywords in _TRACK_RULES: + if any(keyword in lowered for keyword in keywords): + return track + return "" + + def _classify_page_source(self, url: str, args: dict[str, Any]) -> tuple[str, str]: + lowered = url.lower() + instructions = str(args.get("instructions") or "") + track = self._pick_browse_track(f"{url} {instructions}") + if any(domain in lowered for domain in ("deepseek.ai", "deepseek.com")): + if "chat.deepseek.com" in lowered or "platform.deepseek.com" in lowered: + return "product", track or "ui_modes" + return "official", track or "official_confirmation" + if url: + return "community", track + return "", track + + def _pick_browse_track(self, text: str) -> str: + lowered = self._compact_query(text).lower() + priority = ( + ("ui_modes", ("expert", "vision", "mode", "界面", "ui")), + ("release_status", ("release", "released", "launch", "发布", "上线", "status")), + ("specs_architecture", ("spec", "parameter", "architecture", "context", "engram", "moe", "规格", "参数", "架构", "上下文")), + ("v4_lite", ("v4 lite", "sealion", "sealion-lite", "海狮")), + ("official_confirmation", ("official", "官网", "current models", "offering")), + ) + for track, keywords in priority: + if any(keyword in lowered for keyword in keywords): + return track + return self._infer_track(text) + + def _classify_image_topic(self, text: str) -> str: + lowered = text.lower() + if any(token in lowered for token in ("diagram", "示意图", "bulge")): + return "diagram" + if any(token in lowered for token in ("photo", "照片", "real", "high tide", "low tide", "高潮", "低潮")): + return "photo" + return "generic" + + def _looks_like_progress(self, text: str) -> bool: + lowered = text.lower() + return any(hint in lowered for hint in _PROGRESSIVE_HINTS) + + def _looks_like_verification(self, text: str) -> bool: + lowered = text.lower() + return any(token in lowered for token in ("确认", "核对", "浏览", "整合", "比对", "check", "verify", "browse", "integrat")) + + def _looks_like_finding(self, text: str) -> bool: + lowered = text.lower() + if self._looks_like_progress(text): + return False + return any(hint in lowered for hint in _FINDING_HINTS) + + def _clean_report_clause(self, raw_part: str) -> str: + clause = re.sub(r"\s+", " ", raw_part).strip(" -•\t") + if not clause: + return "" + delimiter = ":" if ":" in clause else ":" if ":" in clause else "" + if delimiter: + head, tail = clause.split(delimiter, 1) + head_lower = head.strip().lower() + if len(head.strip()) <= 18 or any(token in head_lower for token in ("总结", "最新", "关键", "补充", "latest", "summary", "note")): + clause = tail.strip() + clause = clause.strip(" -•\t") + clause = re.sub(r"^(?:我知道|我收集了可靠信息|我收集到的?信息|从搜索结果总结|详细解释要点(?:([^)]+))?|补充)\s*", "", clause) + clause = re.sub(r"^(?:that|it shows|it seems)\s+", "", clause, flags=re.IGNORECASE) + if len(clause) < 8: + return "" + lowered = clause.lower() + if any(lowered.startswith(prefix) for prefix in _LOW_VALUE_PREFIXES): + return "" + if "?" in clause or "?" in clause: + return "" + return self._compact_text(clause, limit=120) + + def _score_report_clause(self, clause: str) -> int: + lowered = clause.lower() + score = 0 + if any(hint in lowered for hint in _FINDING_HINTS): + score += 3 + if re.search(r"\b\d+(?:\.\d+)?\b", clause): + score += 2 + if any(token in clause for token in ("月", "日", "年", "小时", "分钟")): + score += 1 + if any(token in clause for token in ("重要", "航运", "渔业", "发电", "生态", "模式", "视觉")): + score += 1 + if any(token in lowered for token in ("可能", "rumor", "传闻", "widely believed", "believed")): + score -= 1 + if any(token in lowered for token in ("可以", "suggest", "建议", "should", "friendly", "reply")): + score -= 2 + if len(clause) > 150: + score -= 1 + return score + + def _infer_evidence_level(self, clause: str, *, default: int) -> int: + lowered = clause.lower() + if any(token in lowered for token in ("官网", "official", "chat ui", "界面更新", "页面")): + return 4 + if any(token in lowered for token in ("x平台", "x posts", "社区", "widely believed", "传闻", "rumor")): + return max(2, default - 1) + return default + + def _is_unconfirmed_signal(self, clause: str) -> bool: + lowered = clause.lower() + return any( + token in lowered + for token in ( + "x平台", "x posts", "社区", "community", "widely believed", "believed", + "传闻", "rumor", "曝光", "泄露", + ) + ) + + def _to_bullet_text(self, text: str) -> str: + stripped = text.strip() + if stripped.startswith("- "): + stripped = stripped[2:].strip() + stripped = self._ensure_terminal_punctuation(stripped) + return f"- {stripped}" + + def _ensure_terminal_punctuation(self, text: str) -> str: + stripped = text.strip() + if not stripped: + return "" + if stripped.endswith(("。", "!", "?", ".", "!", "?")): + return stripped + if re.search(r"[\u4e00-\u9fff]", stripped): + return stripped + "。" + return stripped + "." + + def _compact_query(self, text: str) -> str: + cleaned = re.sub(r"\b(?:or|and|site:[^\s]+|since:\S+|from:\S+|date:\S+)\b", " ", text, flags=re.IGNORECASE) + cleaned = re.sub(r"[()\"']", " ", cleaned) + cleaned = re.sub(r"\s+", " ", cleaned).strip() + return cleaned + + def _compact_text(self, text: str, *, limit: int) -> str: + compact = re.sub(r"\s+", " ", text).strip() + if len(compact) <= limit: + return compact + return compact[: limit - 3].rstrip() + "..." + + def _normalize_key(self, text: str) -> str: + lowered = text.lower() + lowered = re.sub(r"https?://\S+", "", lowered) + lowered = re.sub(r"[^\w\u4e00-\u9fff]+", "", lowered) + return lowered + + +__all__ = ["ReasoningAggregator", "ReasoningEvent"] diff --git a/app/dataplane/reverse/protocol/xai_image.py b/app/dataplane/reverse/protocol/xai_image.py index 7f08adda..a6ce59f1 100644 --- a/app/dataplane/reverse/protocol/xai_image.py +++ b/app/dataplane/reverse/protocol/xai_image.py @@ -1,27 +1,38 @@ -"""XAI Imagine WebSocket protocol — message builders and image classifier.""" - -from __future__ import annotations +"""XAI Imagine WebSocket protocol — message builders and frame parsers.""" import re import time import uuid -from typing import Any, Optional +from typing import Any - -_URL_PATTERN = re.compile(r"/images/([a-f0-9-]+)\.(png|jpg|jpeg)", re.IGNORECASE) +_URL_PATTERN = re.compile(r"/images/([a-f0-9\-]+)\.(png|jpg|jpeg)", re.IGNORECASE) WS_IMAGINE_URL = "wss://grok.com/ws/imagine/listen" +# --------------------------------------------------------------------------- +# Client message builders +# --------------------------------------------------------------------------- + +def build_reset_message() -> dict[str, Any]: + """Build the reset message that must be sent before each prompt.""" + return { + "type": "conversation.item.create", + "timestamp": int(time.time() * 1000), + "item": {"type": "message", "content": [{"type": "reset"}]}, + } + + def build_request_message( request_id: str, prompt: str, aspect_ratio: str = "2:3", enable_nsfw: bool = True, + enable_pro: bool = False, ) -> dict[str, Any]: - """Build the WebSocket conversation.item.create message.""" + """Build the image generation request message.""" return { - "type": "conversation.item.create", + "type": "conversation.item.create", "timestamp": int(time.time() * 1000), "item": { "type": "message", @@ -30,56 +41,72 @@ def build_request_message( "text": prompt, "type": "input_text", "properties": { - "section_count": 0, - "is_kids_mode": False, - "enable_nsfw": enable_nsfw, - "skip_upsampler": False, - "is_initial": False, - "aspect_ratio": aspect_ratio, + "section_count": 0, + "is_kids_mode": False, + "enable_nsfw": enable_nsfw, + "skip_upsampler": False, + "enable_side_by_side": True, + "is_initial": False, + "aspect_ratio": aspect_ratio, + "enable_pro": enable_pro, }, }], }, } -def classify_image( - url: str, - blob: str, - *, - final_min_bytes: int = 50_000, - medium_min_bytes: int = 5_000, -) -> dict[str, Any] | None: - """Classify a WebSocket image message into stage metadata. +# --------------------------------------------------------------------------- +# Server frame parsers +# --------------------------------------------------------------------------- - Returns a dict with keys: type, image_id, ext, stage, blob, blob_size, url, is_final. - Returns None if url or blob are empty. +def parse_image_url(url: str) -> tuple[str, str]: + """Extract (image_id, ext) from a /images/{id}.{ext} URL. + + Falls back to a random UUID and 'jpg' if pattern not found. """ - if not url or not blob: + match = _URL_PATTERN.search(url or "") + if match: + return match.group(1), match.group(2).lower() + return uuid.uuid4().hex, "jpg" + + +def parse_json_frame(msg: dict[str, Any]) -> dict[str, Any] | None: + """Parse a {type: "json"} frame. + + Returns a normalised dict on success, None if unrecognised status. + + Returned keys: + status "start_stage" | "completed" + image_id str + order int + width int + height int + moderated bool (only meaningful for "completed") + r_rated bool (only meaningful for "completed") + """ + status = msg.get("current_status") + if status not in ("start_stage", "completed"): return None - match = _URL_PATTERN.search(url) - image_id = match.group(1) if match else uuid.uuid4().hex - ext = match.group(2).lower() if match else "png" - blob_size = len(blob) - is_final = blob_size >= final_min_bytes - - if is_final: - stage = "final" - elif blob_size > medium_min_bytes: - stage = "medium" - else: - stage = "preview" + image_id = str(msg.get("image_id") or msg.get("job_id") or "") + if not image_id: + return None return { - "type": "image", + "status": status, "image_id": image_id, - "ext": ext, - "stage": stage, - "blob": blob, - "blob_size": blob_size, - "url": url, - "is_final": is_final, + "order": int(msg.get("order") or 0), + "width": int(msg.get("width") or 0), + "height": int(msg.get("height") or 0), + "moderated": bool(msg.get("moderated")), + "r_rated": bool(msg.get("r_rated")), } -__all__ = ["WS_IMAGINE_URL", "build_request_message", "classify_image"] +__all__ = [ + "WS_IMAGINE_URL", + "build_reset_message", + "build_request_message", + "parse_image_url", + "parse_json_frame", +] diff --git a/app/dataplane/reverse/protocol/xai_image_edit.py b/app/dataplane/reverse/protocol/xai_image_edit.py new file mode 100644 index 00000000..e1136868 --- /dev/null +++ b/app/dataplane/reverse/protocol/xai_image_edit.py @@ -0,0 +1,107 @@ +"""XAI image-edit protocol — payload builder and SSE field extractors.""" + +from typing import Any + +from app.platform.config.snapshot import get_config + +IMAGE_EDIT_MODEL_NAME = "imagine-image-edit" +IMAGE_EDIT_MODEL_KIND = "imagine" +IMAGE_POST_MEDIA_TYPE = "MEDIA_POST_TYPE_IMAGE" +IMAGE_EDIT_GENERATION_COUNT = 2 + + +def build_image_edit_payload( + *, + prompt: str, + image_references: list[str], + parent_post_id: str, +) -> dict[str, Any]: + """Build the JSON payload for imagine image-edit chat requests.""" + cfg = get_config() + return { + "temporary": cfg.get_bool("features.temporary", True), + "modelName": IMAGE_EDIT_MODEL_NAME, + "message": prompt, + "enableImageGeneration": True, + "returnImageBytes": False, + "returnRawGrokInXaiRequest": False, + "enableImageStreaming": True, + "imageGenerationCount": IMAGE_EDIT_GENERATION_COUNT, + "forceConcise": False, + "toolOverrides": {"imageGen": True}, + "enableSideBySide": True, + "sendFinalMetadata": True, + "isReasoning": False, + "disableTextFollowUps": True, + "responseMetadata": { + "modelConfigOverride": { + "modelMap": { + "imageEditModel": IMAGE_EDIT_MODEL_KIND, + "imageEditModelConfig": { + "imageReferences": image_references, + "parentPostId": parent_post_id, + }, + } + } + }, + "disableMemory": not cfg.get_bool("features.memory", False), + "forceSideBySide": False, + } + + +def extract_streaming_response(data: dict[str, Any]) -> dict[str, Any] | None: + """Return ``response.streamingImageGenerationResponse`` when present.""" + result = data.get("result") + if not isinstance(result, dict): + return None + response = result.get("response") + if not isinstance(response, dict): + return None + stream = response.get("streamingImageGenerationResponse") + return stream if isinstance(stream, dict) else None + + +def extract_model_response_urls(data: dict[str, Any]) -> list[str]: + """Return fallback ``modelResponse.generatedImageUrls`` values.""" + result = data.get("result") + if not isinstance(result, dict): + return [] + response = result.get("response") + if not isinstance(response, dict): + return [] + model_response = response.get("modelResponse") + if not isinstance(model_response, dict): + return [] + urls = model_response.get("generatedImageUrls") + if not isinstance(urls, list): + return [] + return [url for url in urls if isinstance(url, str) and url] + + +def extract_model_response_file_attachments(data: dict[str, Any]) -> list[str]: + """Return fallback ``modelResponse.fileAttachments`` asset IDs.""" + result = data.get("result") + if not isinstance(result, dict): + return [] + response = result.get("response") + if not isinstance(response, dict): + return [] + model_response = response.get("modelResponse") + if not isinstance(model_response, dict): + return [] + attachments = model_response.get("fileAttachments") + if not isinstance(attachments, list): + return [] + return [attachment for attachment in attachments if isinstance(attachment, str) and attachment] + + +__all__ = [ + "IMAGE_EDIT_MODEL_NAME", + "IMAGE_EDIT_MODEL_KIND", + "IMAGE_POST_MEDIA_TYPE", + "IMAGE_EDIT_GENERATION_COUNT", + "build_image_edit_payload", + "extract_streaming_response", + "extract_model_response_urls", + "extract_model_response_file_attachments", +] diff --git a/app/dataplane/reverse/protocol/xai_livekit.py b/app/dataplane/reverse/protocol/xai_livekit.py index ac973bcf..df18a5cc 100644 --- a/app/dataplane/reverse/protocol/xai_livekit.py +++ b/app/dataplane/reverse/protocol/xai_livekit.py @@ -5,8 +5,6 @@ a short-lived LiveKit access token. The WebSocket connection uses that access token as a query parameter on wss://livekit.grok.com/rtc. """ -from __future__ import annotations - from typing import Any, Dict from urllib.parse import urlencode diff --git a/app/dataplane/reverse/protocol/xai_usage.py b/app/dataplane/reverse/protocol/xai_usage.py index 5a04b1e8..1cd3dc26 100644 --- a/app/dataplane/reverse/protocol/xai_usage.py +++ b/app/dataplane/reverse/protocol/xai_usage.py @@ -1,7 +1,5 @@ """XAI rate-limits API protocol — fetch live quota data per mode.""" -from __future__ import annotations - import orjson from app.platform.logging.logger import logger @@ -18,13 +16,15 @@ _MODE_NAMES: dict[int, str] = { 0: "auto", 1: "fast", 2: "expert", + 3: "heavy", } # Default window durations used as fallback when API call fails. _DEFAULT_WINDOW_SECS: dict[int, int] = { - 0: 72_000, # auto — 20 h - 1: 72_000, # fast — 20 h - 2: 36_000, # expert — 10 h + 0: 72_000, # auto — 20 h (basic) / 2 h (super/heavy, real value overrides) + 1: 72_000, # fast — 20 h (basic) + 2: 36_000, # expert — 10 h (basic) + 3: 7_200, # heavy — 2 h (heavy-pool only) } @@ -141,16 +141,19 @@ async def _fetch_one(token: str, mode_id: int) -> object | None: # --------------------------------------------------------------------------- async def fetch_all_quotas(token: str) -> dict[int, object] | None: - """Fetch quota windows for all three modes (auto / fast / expert) concurrently. + """Fetch quota windows for all four modes (auto / fast / expert / heavy) concurrently. - Issues three requests in parallel. Returns ``{mode_id: QuotaWindow}`` - for every mode that responded successfully, or ``None`` if all failed. + Issues four requests in parallel. Mode 3 (heavy) will silently return + ``None`` for basic and super accounts — this is expected and harmless. + Returns ``{mode_id: QuotaWindow}`` for every mode that responded + successfully, or ``None`` if all four failed. """ import asyncio results = await asyncio.gather( _fetch_one(token, 0), _fetch_one(token, 1), _fetch_one(token, 2), + _fetch_one(token, 3), return_exceptions=False, ) windows = {mode_id: win for mode_id, win in enumerate(results) if win is not None} diff --git a/app/dataplane/reverse/protocol/xai_video.py b/app/dataplane/reverse/protocol/xai_video.py index dc6ea0b7..95757910 100644 --- a/app/dataplane/reverse/protocol/xai_video.py +++ b/app/dataplane/reverse/protocol/xai_video.py @@ -1,7 +1,5 @@ """XAI video creation protocol — payload builders for media/post/create endpoints.""" -from __future__ import annotations - from typing import Any MEDIA_POST_URL = "https://grok.com/rest/media/post/create" @@ -24,24 +22,6 @@ def build_media_post_payload( return payload -def build_video_request_payload( - *, - prompt: str, - aspect_ratio: str = "3:2", - video_length: int = 6, - resolution: str = "480p", - preset: str = "custom", -) -> dict[str, Any]: - """Build the app-chat request_overrides for video generation.""" - return { - "mediaType": "video", - "aspectRatio": aspect_ratio, - "videoDuration": video_length, - "resolution": resolution, - "preset": preset, - } - - def build_upscale_payload(video_id: str) -> dict[str, Any]: return {"videoId": video_id} @@ -57,6 +37,6 @@ def build_media_link_payload(post_id: str) -> dict[str, Any]: __all__ = [ "MEDIA_POST_URL", "MEDIA_LINK_URL", "VIDEO_UPSCALE_URL", - "build_media_post_payload", "build_video_request_payload", + "build_media_post_payload", "build_upscale_payload", "build_media_link_payload", ] diff --git a/app/dataplane/reverse/runtime/endpoint_table.py b/app/dataplane/reverse/runtime/endpoint_table.py index 4d2917d7..bb390e50 100644 --- a/app/dataplane/reverse/runtime/endpoint_table.py +++ b/app/dataplane/reverse/runtime/endpoint_table.py @@ -8,8 +8,6 @@ NOTE: gRPC-Web endpoints (accept_tos, nsfw_mgmt) live on different hosts (accounts.x.ai, grok.com with gRPC path), listed separately. """ -from __future__ import annotations - BASE = "https://grok.com" ASSETS_CDN = "https://assets.grok.com" diff --git a/app/dataplane/reverse/runtime/profiles.py b/app/dataplane/reverse/runtime/profiles.py index 8672b53b..b7976b9c 100644 --- a/app/dataplane/reverse/runtime/profiles.py +++ b/app/dataplane/reverse/runtime/profiles.py @@ -4,8 +4,6 @@ Pre-built profiles eliminate per-request config lookups in the hot path. Each profile specifies timeout, max retries, and retry-eligible status codes. """ -from __future__ import annotations - from dataclasses import dataclass, field diff --git a/app/dataplane/reverse/transport/asset_upload.py b/app/dataplane/reverse/transport/asset_upload.py index 0f9724a8..20d30804 100644 --- a/app/dataplane/reverse/transport/asset_upload.py +++ b/app/dataplane/reverse/transport/asset_upload.py @@ -4,8 +4,7 @@ Calls POST /rest/app-chat/upload-file with base64-encoded content and returns the file metadata ID used as a file attachment reference in chat. """ -from __future__ import annotations - +import asyncio import base64 import mimetypes import re @@ -17,11 +16,25 @@ from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config from app.platform.errors import UpstreamError, ValidationError from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.headers import build_sso_cookie from app.dataplane.proxy.adapters.headers import build_http_headers from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.protocol.xai_assets import resolve_asset_reference from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind _UPLOAD_URL = "https://grok.com/rest/app-chat/upload-file" +_X_USER_ID_RE = re.compile(r"(?:^|;\s*)x-userid=([^;]+)") + +# Global semaphore — limits concurrent upload_file() calls across all requests. +# Initialised lazily on first call so the event loop is guaranteed to be running. +_upload_sem: asyncio.Semaphore | None = None + +def _get_upload_sem() -> asyncio.Semaphore: + global _upload_sem + if _upload_sem is None: + n = max(1, int(get_config("batch.asset_upload_concurrency", 10))) + _upload_sem = asyncio.Semaphore(n) + return _upload_sem # --------------------------------------------------------------------------- @@ -90,6 +103,16 @@ async def upload_file( Raises: ``UpstreamError`` on HTTP failure. """ + async with _get_upload_sem(): + return await _upload_file_inner(token, filename, mime, b64) + + +async def _upload_file_inner( + token: str, + filename: str, + mime: str, + b64: str, +) -> tuple[str, str]: cfg = get_config() timeout_s = cfg.get_float("asset.upload_timeout", 60.0) @@ -113,7 +136,7 @@ async def upload_file( timeout = timeout_s, ) - body_bytes = await response.aread() + body_bytes = response.content if response.status_code != 200: body_text = body_bytes.decode("utf-8", "replace")[:300] logger.error( @@ -169,7 +192,7 @@ async def upload_from_input(token: str, file_input: str) -> tuple[str, str]: kwargs = build_session_kwargs(lease=lease) async with ResettableSession(**kwargs) as session: resp = await session.get(file_input, headers=headers, timeout=30.0) - raw = await resp.aread() + raw = resp.content if resp.status_code != 200: raise UpstreamError( f"Failed to fetch input URL: {resp.status_code}", @@ -189,4 +212,26 @@ async def upload_from_input(token: str, file_input: str) -> tuple[str, str]: return await upload_file(token, filename, mime, b64) -__all__ = ["upload_file", "upload_from_input", "parse_data_uri"] +def resolve_uploaded_asset_reference(token: str, file_id: str, file_uri: str) -> str: + """Resolve an uploaded asset to the content URL required by image-edit.""" + user_id = _extract_user_id(token) + url = resolve_asset_reference(file_id, file_uri, user_id=user_id) + if url: + return url + raise UpstreamError("Could not resolve uploaded asset reference URL") + + +def _extract_user_id(token: str) -> str | None: + cookie = build_sso_cookie(token) + match = _X_USER_ID_RE.search(cookie) + if match: + return match.group(1) + return None + + +__all__ = [ + "upload_file", + "upload_from_input", + "parse_data_uri", + "resolve_uploaded_asset_reference", +] diff --git a/app/dataplane/reverse/transport/assets.py b/app/dataplane/reverse/transport/assets.py index 03152640..527175f6 100644 --- a/app/dataplane/reverse/transport/assets.py +++ b/app/dataplane/reverse/transport/assets.py @@ -4,12 +4,30 @@ All functions acquire a proxy lease internally, execute the upstream call, give feedback, and return results to the caller. """ -from __future__ import annotations - +import asyncio from typing import Any, AsyncGenerator, Dict, Optional from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config + +# Global semaphores — limit concurrent transport calls across all callers. +# Lazily initialised so the event loop is guaranteed to be running on first use. +_list_sem: asyncio.Semaphore | None = None +_delete_sem: asyncio.Semaphore | None = None + +def _get_list_sem() -> asyncio.Semaphore: + global _list_sem + if _list_sem is None: + n = max(1, int(get_config("batch.asset_list_concurrency", 50))) + _list_sem = asyncio.Semaphore(n) + return _list_sem + +def _get_delete_sem() -> asyncio.Semaphore: + global _delete_sem + if _delete_sem is None: + n = max(1, int(get_config("batch.asset_delete_concurrency", 50))) + _delete_sem = asyncio.Semaphore(n) + return _delete_sem from app.platform.errors import UpstreamError from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind from app.dataplane.proxy import get_proxy_runtime @@ -40,6 +58,14 @@ async def list_assets( token: SSO session token. params: Optional query parameters (e.g. ``{"cursor": "...", "limit": 50}``). """ + async with _get_list_sem(): + return await _list_assets_inner(token, params) + + +async def _list_assets_inner( + token: str, + params: Optional[Dict[str, Any]] = None, +) -> dict: cfg = get_config() timeout_s = cfg.get_float("asset.list_timeout", 30.0) @@ -86,6 +112,11 @@ async def list_assets( async def delete_asset(token: str, asset_id: str) -> dict: """DELETE /rest/assets-metadata/{asset_id} and return the JSON body (may be {}).""" + async with _get_delete_sem(): + return await _delete_asset_inner(token, asset_id) + + +async def _delete_asset_inner(token: str, asset_id: str) -> dict: cfg = get_config() timeout_s = cfg.get_float("asset.delete_timeout", 30.0) diff --git a/app/dataplane/reverse/transport/grpc_web.py b/app/dataplane/reverse/transport/grpc_web.py index ec96f671..20fee808 100644 --- a/app/dataplane/reverse/transport/grpc_web.py +++ b/app/dataplane/reverse/transport/grpc_web.py @@ -5,8 +5,6 @@ Sends a pre-framed gRPC-Web request to *url* and returns the parsed the caller controls acquisition and feedback. """ -from __future__ import annotations - from typing import Dict, List, Tuple from app.platform.logging.logger import logger @@ -33,13 +31,17 @@ async def post_grpc_web( token: str, payload: bytes, *, - lease: ProxyLease | None = None, - timeout_s: float = 30.0, - origin: str = "https://grok.com", - referer: str = "https://grok.com/", + lease: ProxyLease | None = None, + timeout_s: float = 30.0, + origin: str = "https://grok.com", + referer: str = "https://grok.com/", + session: "ResettableSession | None" = None, ) -> Tuple[List[bytes], Dict[str, str]]: """POST a gRPC-Web frame to *url*. + Pass *session* to reuse an existing connection (avoids a new TLS handshake). + When *session* is ``None`` a fresh session is created and closed automatically. + Returns: ``(messages, trailers)`` — raw protobuf message payloads and the gRPC trailer map (includes ``grpc-status``, ``grpc-message``). @@ -56,35 +58,20 @@ async def post_grpc_web( ) headers.update(_GRPC_WEB_HEADERS) - kwargs = build_session_kwargs(lease=lease) - - async with ResettableSession(**kwargs) as session: - response = await session.post( - url, - headers = headers, - data = payload, - timeout = timeout_s, - ) - - body_bytes = await response.aread() + async def _do(s: "ResettableSession") -> Tuple[List[bytes], Dict[str, str]]: + response = await s.post(url, headers=headers, data=payload, timeout=timeout_s) + body_bytes = response.content if response.status_code != 200: body_text = body_bytes.decode("utf-8", "replace")[:300] - logger.error( - "gRPC-Web POST failed: url={} status={} body={}", - url, response.status_code, body_text, - ) - raise UpstreamError( - f"Upstream returned {response.status_code}", - status = response.status_code, - body = body_text, - ) + logger.error("gRPC-Web POST failed: url={} status={} body={}", url, response.status_code, body_text) + raise UpstreamError(f"Upstream returned {response.status_code}", status=response.status_code, body=body_text) + return GrpcClient.parse_response(body_bytes, content_type=response.headers.get("content-type"), headers=response.headers) - content_type = response.headers.get("content-type") - return GrpcClient.parse_response( - body_bytes, - content_type = content_type, - headers = response.headers, - ) + if session is not None: + return await _do(session) + + async with ResettableSession(**build_session_kwargs(lease=lease)) as s: + return await _do(s) __all__ = ["post_grpc_web"] diff --git a/app/dataplane/reverse/transport/http.py b/app/dataplane/reverse/transport/http.py index 8328e9c8..9de97e58 100644 --- a/app/dataplane/reverse/transport/http.py +++ b/app/dataplane/reverse/transport/http.py @@ -4,8 +4,6 @@ Wraps curl_cffi AsyncSession; handles proxy selection, header building, retry-on-reset, and timeout. """ -from __future__ import annotations - import asyncio from typing import Any, AsyncGenerator @@ -41,7 +39,8 @@ async def post_stream( ) kwargs = build_session_kwargs(lease=lease) - async with ResettableSession(**kwargs) as session: + session = ResettableSession(**kwargs) + try: response = await session.post( url, headers = headers, @@ -52,30 +51,37 @@ async def post_stream( if response.status_code != 200: try: - body = (await response.aread()).decode("utf-8", "replace")[:400] + body = (response.content).decode("utf-8", "replace")[:400] except Exception: body = "" logger.error( "HTTP POST failed: url={} status={} body={}", url, response.status_code, body, ) + await session.close() raise UpstreamError( f"Upstream returned {response.status_code}", status = response.status_code, body = body, ) + except Exception: + try: + await session.close() + except Exception: + pass + raise - async def _lines() -> AsyncGenerator[str, None]: + async def _lines() -> AsyncGenerator[str, None]: + try: + async for line in response.aiter_lines(): + yield line + finally: try: - async for line in response.aiter_lines(): - yield line - finally: - try: - await session.close() - except Exception: - pass + await session.close() + except Exception: + pass - return _lines() + return _lines() async def post_json( @@ -83,47 +89,36 @@ async def post_json( token: str, payload: bytes, *, - lease: ProxyLease | None = None, - timeout_s: float = 30.0, - content_type: str = "application/json", - origin: str = "https://grok.com", - referer: str = "https://grok.com/", + lease: ProxyLease | None = None, + timeout_s: float = 30.0, + content_type: str = "application/json", + origin: str = "https://grok.com", + referer: str = "https://grok.com/", + session: "ResettableSession | None" = None, ) -> dict: - """POST *url* and return parsed JSON response body.""" - headers = build_http_headers( - token, - content_type = content_type, - origin = origin, - referer = referer, - lease = lease, - ) - kwargs = build_session_kwargs(lease=lease) + """POST *url* and return parsed JSON response body. - async with ResettableSession(**kwargs) as session: - response = await session.post( - url, - headers = headers, - data = payload, - timeout = timeout_s, - ) + Pass *session* to reuse an existing connection (avoids a new TLS handshake). + When *session* is ``None`` a fresh session is created and closed automatically. + """ + headers = build_http_headers(token, content_type=content_type, origin=origin, referer=referer, lease=lease) - body_bytes = await response.aread() + import orjson + + async def _do(s: "ResettableSession") -> dict: + response = await s.post(url, headers=headers, data=payload, timeout=timeout_s) + body_bytes = response.content if response.status_code not in (200, 201, 204): body_text = body_bytes.decode("utf-8", "replace")[:400] - logger.error( - "HTTP POST JSON failed: url={} status={} body={}", - url, response.status_code, body_text, - ) - raise UpstreamError( - f"Upstream returned {response.status_code}", - status = response.status_code, - body = body_text, - ) + logger.error("HTTP POST JSON failed: url={} status={} body={}", url, response.status_code, body_text) + raise UpstreamError(f"Upstream returned {response.status_code}", status=response.status_code, body=body_text) + return orjson.loads(body_bytes) if body_bytes.strip() else {} - if not body_bytes.strip(): - return {} - import orjson - return orjson.loads(body_bytes) + if session is not None: + return await _do(session) + + async with ResettableSession(**build_session_kwargs(lease=lease)) as s: + return await _do(s) async def get_json( @@ -154,7 +149,7 @@ async def get_json( timeout = timeout_s, ) - body_bytes = await response.aread() + body_bytes = response.content if response.status_code != 200: body_text = body_bytes.decode("utf-8", "replace")[:400] logger.error( @@ -197,7 +192,7 @@ async def delete_json( timeout = timeout_s, ) - body_bytes = await response.aread() + body_bytes = response.content if response.status_code not in (200, 204): body_text = body_bytes.decode("utf-8", "replace")[:400] logger.error( @@ -241,7 +236,8 @@ async def get_bytes_stream( headers.update(extra_headers) kwargs = build_session_kwargs(lease=lease) - async with ResettableSession(**kwargs) as session: + session = ResettableSession(**kwargs) + try: response = await session.get( url, headers = headers, @@ -252,31 +248,38 @@ async def get_bytes_stream( if response.status_code != 200: try: - body = (await response.aread()).decode("utf-8", "replace")[:400] + body = (response.content).decode("utf-8", "replace")[:400] except Exception: body = "" logger.error( "HTTP GET stream failed: url={} status={} body={}", url, response.status_code, body, ) + await session.close() raise UpstreamError( f"Upstream returned {response.status_code}", status = response.status_code, body = body, ) + except Exception: + try: + await session.close() + except Exception: + pass + raise - async def _chunks() -> AsyncGenerator[bytes, None]: + async def _chunks() -> AsyncGenerator[bytes, None]: + try: + async for chunk in response.aiter_content(): + if chunk: + yield chunk + finally: try: - async for chunk in response.aiter_content(): - if chunk: - yield chunk - finally: - try: - await session.close() - except Exception: - pass + await session.close() + except Exception: + pass - return _chunks() + return _chunks() __all__ = ["post_stream", "post_json", "get_json", "delete_json", "get_bytes_stream"] diff --git a/app/dataplane/reverse/transport/imagine_ws.py b/app/dataplane/reverse/transport/imagine_ws.py index 8f779c04..6feca81f 100644 --- a/app/dataplane/reverse/transport/imagine_ws.py +++ b/app/dataplane/reverse/transport/imagine_ws.py @@ -1,14 +1,20 @@ """Imagine WebSocket reverse transport. -Connects to wss://grok.com/ws/imagine/listen and streams image events. -Handles blocked-state detection and parallel retry. -""" +Protocol (per round): + Client → reset message + Client → prompt message + Server → N × (start_stage json → image frames → completed json) + Server → [may close WS, or keep open for next round] -from __future__ import annotations +One WS connection is reused across rounds until the server closes it or n +images have been collected. This avoids a TLS handshake per round when +requesting more images than a single round produces (speed=6, quality=4). +""" import asyncio import time import uuid +from dataclasses import dataclass, field from typing import Any, AsyncGenerator import aiohttp @@ -16,22 +22,258 @@ import orjson from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config -from app.control.proxy.models import ProxyLease, ProxyScope, RequestKind +from app.control.proxy.models import ProxyScope, RequestKind from app.dataplane.proxy import get_proxy_runtime from app.dataplane.proxy.adapters.headers import build_ws_headers from app.dataplane.reverse.protocol.xai_image import ( - WS_IMAGINE_URL, build_request_message, classify_image, + WS_IMAGINE_URL, + build_reset_message, + build_request_message, + parse_image_url, + parse_json_frame, ) from .websocket import WebSocketClient - -class _BlockedError(Exception): - """Upstream is reviewing/blocking the image — safe to retry.""" - - _client = WebSocketClient() +_INTER_ROUND_WAIT_S = 2.0 +# --------------------------------------------------------------------------- +# Slot state +# --------------------------------------------------------------------------- + +@dataclass +class _Slot: + """Tracks one in-flight image generation slot.""" + image_id: str + order: int + width: int + height: int + last_blob: str = field(default="", repr=False) + last_url: str = "" + done: bool = False + progress: int = 0 + + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + +def _final_event(slot: _Slot, r_rated: bool = False) -> dict[str, Any]: + return { + "type": "image", + "image_id": slot.image_id, + "order": slot.order, + "stage": "final", + "blob": slot.last_blob, + "url": slot.last_url, + "width": slot.width, + "height": slot.height, + "is_final": True, + "moderated": False, + "r_rated": r_rated, + } + + +async def _probe_ws_closed(ws: aiohttp.ClientWebSocketResponse, wait_s: float) -> bool: + """Wait up to *wait_s* seconds for a CLOSE frame. + + Returns True if the server closed the connection, False if the connection + appears to still be alive (timeout expired with no CLOSE received). + """ + try: + msg = await asyncio.wait_for(ws.receive(), timeout=wait_s) + return msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR) + except asyncio.TimeoutError: + return False + except Exception: + return True + + +# --------------------------------------------------------------------------- +# Single-round generator +# --------------------------------------------------------------------------- + +async def _stream_round( + ws: aiohttp.ClientWebSocketResponse, + prompt: str, + *, + aspect_ratio: str, + enable_nsfw: bool, + enable_pro: bool, + needed: int, + stream_timeout_s: float, + round_timeout_s: float, + inter_round_wait_s: float, +) -> AsyncGenerator[dict[str, Any], None]: + """Drive one round of image generation on an already-open WS. + + Sends reset + prompt, then processes frames until all slots are completed + or the WS closes. Always yields a ``{type: "_meta", ws_closed: bool}`` + sentinel as the very last item so the caller knows whether to reconnect. + """ + request_id = str(uuid.uuid4()) + try: + await ws.send_json(build_reset_message()) + await ws.send_json(build_request_message( + request_id, prompt, aspect_ratio, enable_nsfw, enable_pro, + )) + except Exception as exc: + yield {"type": "error", "error_code": "send_failed", "error": str(exc)} + yield {"type": "_meta", "ws_closed": True} + return + + slots: dict[str, _Slot] = {} + round_completed: int = 0 + round_start = time.monotonic() + + while True: + elapsed = time.monotonic() - round_start + if elapsed >= round_timeout_s: + logger.warning("Imagine round timeout after {:.1f}s", elapsed) + for slot in slots.values(): + if not slot.done: + if slot.last_blob: + yield _final_event(slot) + else: + yield { + "type": "error", + "error_code": "slot_incomplete", + "error": f"slot {slot.image_id[:8]} timed out", + } + yield {"type": "_meta", "ws_closed": False} + return + + recv_timeout = min(stream_timeout_s, round_timeout_s - elapsed) + try: + ws_msg = await asyncio.wait_for(ws.receive(), timeout=recv_timeout) + except asyncio.TimeoutError: + # No frame arrived — check if all known slots are already done. + if slots and all(s.done for s in slots.values()): + ws_closed = await _probe_ws_closed(ws, inter_round_wait_s) + yield {"type": "_meta", "ws_closed": ws_closed} + return + continue + + # ── TEXT frames ────────────────────────────────────────────────────── + if ws_msg.type == aiohttp.WSMsgType.TEXT: + try: + msg = orjson.loads(ws_msg.data) + except Exception: + continue + + msg_type = msg.get("type") + + # JSON control frames (start_stage / completed) + if msg_type == "json": + parsed = parse_json_frame(msg) + if parsed is None: + continue + + if parsed["status"] == "start_stage": + iid = parsed["image_id"] + slots[iid] = _Slot( + image_id = iid, + order = parsed["order"], + width = parsed["width"], + height = parsed["height"], + ) + logger.debug( + "Imagine slot {} start order={} {}×{}", + iid[:8], parsed["order"], parsed["width"], parsed["height"], + ) + yield { + "type": "progress", + "image_id": iid, + "order": parsed["order"], + "progress": 10, + } + + elif parsed["status"] == "completed": + iid = parsed["image_id"] + slot = slots.get(iid) + if slot is None or slot.done: + continue + + slot.done = True + + if parsed["moderated"]: + logger.warning("Imagine slot {} moderated", iid[:8]) + yield {"type": "moderated", "image_id": iid, "order": slot.order} + else: + logger.debug("Imagine slot {} completed order={}", iid[:8], slot.order) + yield _final_event(slot, r_rated=parsed["r_rated"]) + round_completed += 1 + + all_done = slots and all(s.done for s in slots.values()) + if all_done: + ws_closed = await _probe_ws_closed(ws, inter_round_wait_s) + yield {"type": "_meta", "ws_closed": ws_closed} + return + + if round_completed >= needed: + # Have enough this round; leave remaining slots in flight. + yield {"type": "_meta", "ws_closed": False} + return + + # Image blob frames (intermediate previews) + elif msg_type == "image": + url = msg.get("url", "") + blob = msg.get("blob", "") + iid, _ext = parse_image_url(url) + slot = slots.get(iid) + if slot and not slot.done: + slot.last_blob = blob + slot.last_url = url + progress = msg.get("percentage_complete") + try: + parsed_progress = int(float(progress)) if progress is not None else 50 + except (TypeError, ValueError): + parsed_progress = 50 + parsed_progress = max(10, min(99, parsed_progress)) + if parsed_progress > slot.progress: + slot.progress = parsed_progress + yield { + "type": "progress", + "image_id": iid, + "order": slot.order, + "progress": parsed_progress, + } + + # Server-side error + elif msg_type == "error": + err_code = msg.get("err_code") or "upstream_error" + err_msg = msg.get("err_msg") or str(msg) + logger.warning("Imagine WS server error: {} {}", err_code, err_msg) + yield {"type": "error", "error_code": err_code, "error": err_msg} + yield {"type": "_meta", "ws_closed": True} + return + + # ── WS closed / error ──────────────────────────────────────────────── + elif ws_msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR): + # Yield best-effort finals for any slots that received a blob but + # never got a completed frame. + for slot in slots.values(): + if not slot.done: + if slot.last_blob: + logger.debug( + "Imagine WS closed: yielding best-effort final for slot {}", + slot.image_id[:8], + ) + yield _final_event(slot) + else: + logger.warning( + "Imagine WS closed: slot {} had no blob, skipping", + slot.image_id[:8], + ) + yield {"type": "_meta", "ws_closed": True} + return + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + async def stream_images( token: str, prompt: str, @@ -39,179 +281,91 @@ async def stream_images( aspect_ratio: str = "2:3", n: int = 1, enable_nsfw: bool = True, + enable_pro: bool = False, ) -> AsyncGenerator[dict[str, Any], None]: - """Stream image events from the Imagine WebSocket endpoint. + """Stream image events, collecting *n* final images. - Yields dicts with keys: type, image_id, ext, stage, blob, blob_size, url, is_final - (or type='error' on failure). + Reuses a single WS connection across multiple rounds when the server keeps + the connection open. Reconnects transparently if the server closes it. + + Yields: + ``{type: "image", is_final: True, ...}`` — final image per slot + ``{type: "moderated", ...}`` — censored slot + ``{type: "error", ...}`` — fatal error (stops iteration) """ - cfg = get_config() - timeout_s = cfg.get_float("image.timeout", 120.0) - stream_timeout_s = cfg.get_float("image.stream_timeout", 10.0) - final_timeout_s = cfg.get_float("image.final_timeout", 30.0) - blocked_grace_s = min(max(cfg.get_float("image.blocked_grace_seconds", 10.0), 1.0), final_timeout_s) - final_min_bytes = cfg.get_int("image.final_min_bytes", 50_000) - medium_min_bytes = cfg.get_int("image.medium_min_bytes", 5_000) - max_retries = max(1, cfg.get_int("image.max_retries", 1)) - parallel_ok = cfg.get_bool("image.blocked_parallel_enabled", True) + cfg = get_config() + timeout_s = cfg.get_float("image.timeout", 120.0) + stream_timeout_s = cfg.get_float("image.stream_timeout", 10.0) + inter_round_wait_s = _INTER_ROUND_WAIT_S - async def _once() -> list[dict[str, Any]]: - items: list[dict[str, Any]] = [] - async for ev in _stream_once( - token, prompt, - aspect_ratio = aspect_ratio, - n = n, - enable_nsfw = enable_nsfw, - timeout_s = timeout_s, - stream_timeout_s = stream_timeout_s, - final_timeout_s = final_timeout_s, - blocked_grace_s = blocked_grace_s, - final_min_bytes = final_min_bytes, - medium_min_bytes = medium_min_bytes, - ): - items.append(ev) - return items + collected = 0 + + while collected < n: + needed = n - collected + + # ── Establish connection ────────────────────────────────────────────── + proxy = await get_proxy_runtime() + lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WEBSOCKET) + headers = build_ws_headers(token=token, lease=lease) - for attempt in range(max_retries): try: - items = await _once() - for ev in items: - yield ev - return - except _BlockedError: - remaining = max_retries - attempt - 1 - if remaining > 0 and parallel_ok: - logger.warning("Imagine blocked; launching {} parallel retries", remaining) - tasks = [asyncio.create_task(_once()) for _ in range(remaining)] - results = await asyncio.gather(*tasks, return_exceptions=True) - for result in results: - if isinstance(result, Exception): - continue - if any(ev.get("is_final") for ev in result if isinstance(ev, dict)): - for ev in result: - yield ev - return - yield {"type": "error", "error_code": "blocked", "error": "blocked_no_final_image"} - return - if attempt + 1 < max_retries: - logger.warning("Imagine blocked, retry {}/{}", attempt + 1, max_retries) - continue - yield {"type": "error", "error_code": "blocked", "error": "blocked_no_final_image"} - return + conn = await _client.connect( + WS_IMAGINE_URL, + headers = headers, + timeout = timeout_s, + ws_kwargs = {"heartbeat": 20, "receive_timeout": stream_timeout_s}, + lease = lease, + ) except Exception as exc: - logger.error("Imagine stream error: {}", exc) - yield {"type": "error", "error_code": "stream_error", "error": str(exc)} + status = getattr(exc, "status", None) + logger.error("Imagine WS connect failed: {}", exc) + yield { + "type": "error", + "error_code": "rate_limit_exceeded" if status == 429 else "connection_failed", + "error": str(exc), + } return + # ── Run rounds on this connection ───────────────────────────────────── + try: + async with conn as ws: + while collected < n: + needed = n - collected + async for ev in _stream_round( + ws, prompt, + aspect_ratio = aspect_ratio, + enable_nsfw = enable_nsfw, + enable_pro = enable_pro, + needed = needed, + stream_timeout_s = stream_timeout_s, + round_timeout_s = timeout_s, + inter_round_wait_s = inter_round_wait_s, + ): + if ev["type"] == "_meta": + ws_closed = ev["ws_closed"] + break # exit inner for-loop; handle ws_closed below + if ev.get("is_final"): + collected += 1 + yield ev + if ev["type"] == "error": + return + else: + # _stream_round exhausted without a _meta — shouldn't happen + ws_closed = True -async def _stream_once( - token: str, - prompt: str, - *, - aspect_ratio: str, - n: int, - enable_nsfw: bool, - timeout_s: float, - stream_timeout_s: float, - final_timeout_s: float, - blocked_grace_s: float, - final_min_bytes: int, - medium_min_bytes: int, -) -> AsyncGenerator[dict[str, Any], None]: - request_id = str(uuid.uuid4()) - proxy = await get_proxy_runtime() - lease = await proxy.acquire( - scope = ProxyScope.APP, - kind = RequestKind.WEBSOCKET, - ) - headers = build_ws_headers(token=token, lease=lease) + if ws_closed or collected >= n: + break # exit inner while; reconnect or finish - try: - conn = await _client.connect( - WS_IMAGINE_URL, - headers = headers, - timeout = timeout_s, - ws_kwargs = {"heartbeat": 20, "receive_timeout": stream_timeout_s}, - lease = lease, - ) - except Exception as exc: - status = getattr(exc, "status", None) - logger.error("Imagine WebSocket connect failed: {}", exc) - yield { - "type": "error", - "error_code": "rate_limit_exceeded" if status == 429 else "connection_failed", - "error": str(exc), - } - return + except aiohttp.ClientError as exc: + logger.error("Imagine WS connection error: {}", exc) + yield {"type": "error", "error_code": "connection_failed", "error": str(exc)} + return - try: - async with conn as ws: - await ws.send_json(build_request_message(request_id, prompt, aspect_ratio, enable_nsfw)) - logger.info("Imagine request sent: prompt={!r:.50} ratio={}", prompt, aspect_ratio) + if collected >= n: + return - final_ids: set[str] = set() - completed: int = 0 - start = time.monotonic() - last_activity = start - medium_received_at: float | None = None - - while time.monotonic() - start < timeout_s: - try: - ws_msg = await asyncio.wait_for(ws.receive(), timeout=5.0) - except asyncio.TimeoutError: - now = time.monotonic() - if medium_received_at and completed == 0 and now - medium_received_at > blocked_grace_s: - logger.warning("Imagine blocked: medium received but no final in {:.1f}s", blocked_grace_s) - raise _BlockedError() - if completed > 0 and now - last_activity > 10.0: - break - continue - - if ws_msg.type == aiohttp.WSMsgType.TEXT: - last_activity = time.monotonic() - try: - msg = orjson.loads(ws_msg.data) - except Exception: - continue - - msg_type = msg.get("type") - if msg_type == "image": - info = classify_image( - msg.get("url", ""), msg.get("blob", ""), - final_min_bytes = final_min_bytes, - medium_min_bytes = medium_min_bytes, - ) - if not info: - continue - if info["stage"] == "medium" and medium_received_at is None: - medium_received_at = time.monotonic() - if info["is_final"] and info["image_id"] not in final_ids: - final_ids.add(info["image_id"]) - completed += 1 - yield info - - elif msg_type == "error": - logger.warning("Imagine WS error: {} {}", msg.get("err_code"), msg.get("err_msg")) - yield { - "type": "error", - "error_code": msg.get("err_code", ""), - "error": msg.get("err_msg", ""), - } - return - - if completed >= n: - break - - if medium_received_at and completed == 0 and time.monotonic() - medium_received_at > final_timeout_s: - logger.warning("Imagine final-timeout: no final image in {:.1f}s", final_timeout_s) - raise _BlockedError() - - elif ws_msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR): - yield {"type": "error", "error_code": "ws_closed", "error": str(ws_msg.type)} - return - - except aiohttp.ClientError as exc: - yield {"type": "error", "error_code": "connection_failed", "error": str(exc)} + # Server closed the connection but we still need more images → reconnect. + logger.info("Imagine reconnecting for {}/{} remaining images", n - collected, n) __all__ = ["stream_images"] diff --git a/app/dataplane/reverse/transport/livekit.py b/app/dataplane/reverse/transport/livekit.py index e2d66cb1..2a94015b 100644 --- a/app/dataplane/reverse/transport/livekit.py +++ b/app/dataplane/reverse/transport/livekit.py @@ -5,8 +5,6 @@ ``WebSocketConnection`` that the products layer can read/write. """ -from __future__ import annotations - from typing import Any, Dict, Optional import orjson diff --git a/app/dataplane/reverse/transport/media.py b/app/dataplane/reverse/transport/media.py index 9a9a11a6..ff9a6956 100644 --- a/app/dataplane/reverse/transport/media.py +++ b/app/dataplane/reverse/transport/media.py @@ -3,10 +3,6 @@ All three endpoints are simple JSON POST calls with proxy lifecycle. """ -from __future__ import annotations - -from typing import Any, Dict - import orjson from app.platform.logging.logger import logger @@ -85,6 +81,7 @@ async def create_media_post( media_type: str, media_url: str = "", prompt: str = "", + referer: str = "https://grok.com/imagine", ) -> dict: """POST /rest/media/post/create — create a media post.""" payload = build_media_post_payload( @@ -95,6 +92,7 @@ async def create_media_post( return await _post_with_proxy( MEDIA_POST_URL, token, payload, label = "create_media_post", + referer = referer, ) diff --git a/app/dataplane/reverse/transport/websocket.py b/app/dataplane/reverse/transport/websocket.py index 8d1034c0..071bdeec 100644 --- a/app/dataplane/reverse/transport/websocket.py +++ b/app/dataplane/reverse/transport/websocket.py @@ -1,7 +1,5 @@ """WebSocket transport with proxy and SOCKS support.""" -from __future__ import annotations - import ssl from typing import Any, Awaitable, Callable, Mapping, Optional from urllib.parse import urlparse @@ -108,7 +106,8 @@ class WebSocketClient: try: extra: dict[str, Any] = dict(ws_kwargs or {}) - skip_ssl = cfg.get_bool("proxy.skip_proxy_ssl_verify", False) and bool(proxy_url) + skip_ssl = cfg.get_bool("proxy.egress.skip_ssl_verify", + cfg.get_bool("proxy.skip_proxy_ssl_verify", False)) and bool(proxy_url) if skip_ssl and urlparse(proxy_url).scheme.lower() == "https": proxy_ssl = ssl.create_default_context() diff --git a/app/dataplane/reverse/types.py b/app/dataplane/reverse/types.py index 3f763332..c14abd08 100644 --- a/app/dataplane/reverse/types.py +++ b/app/dataplane/reverse/types.py @@ -1,7 +1,5 @@ """Reverse pipeline data types — ReversePlan, ReverseLeaseSet, ReverseResult.""" -from __future__ import annotations - from dataclasses import dataclass, field from enum import IntEnum, auto from typing import Any @@ -43,15 +41,15 @@ class TransportKind(IntEnum): @dataclass(slots=True) class ReversePlan: """Describes how a single upstream call should be executed.""" - endpoint: str # full URL - transport_kind: TransportKind - pool_id: int # 0=basic, 1=super - mode_id: int # 0=auto, 1=fast, 2=expert - timeout_s: float = 120.0 - content_type: str = "application/json" - origin: str = "https://grok.com" - referer: str = "https://grok.com/" - extra: dict[str, Any] = field(default_factory=dict) + endpoint: str # full URL + transport_kind: TransportKind + pool_candidates: tuple[int, ...] # ordered pool IDs to try (e.g. (0,1,2)) + mode_id: int # 0=auto, 1=fast, 2=expert, 3=heavy + timeout_s: float = 120.0 + content_type: str = "application/json" + origin: str = "https://grok.com" + referer: str = "https://grok.com/" + extra: dict[str, Any] = field(default_factory=dict) @dataclass(slots=True) diff --git a/app/dataplane/shared/enums.py b/app/dataplane/shared/enums.py index d633f056..516564f8 100644 --- a/app/dataplane/shared/enums.py +++ b/app/dataplane/shared/enums.py @@ -4,8 +4,6 @@ These mirror the control-plane enums but use IntEnum exclusively so they can be used directly as array indices with zero overhead. """ -from __future__ import annotations - from enum import IntEnum @@ -18,6 +16,7 @@ class ModeId(IntEnum): class PoolId(IntEnum): BASIC = 0 SUPER = 1 + HEAVY = 2 class StatusId(IntEnum): @@ -32,6 +31,7 @@ class StatusId(IntEnum): POOL_STR_TO_ID: dict[str, int] = { "basic": int(PoolId.BASIC), "super": int(PoolId.SUPER), + "heavy": int(PoolId.HEAVY), } STATUS_STR_TO_ID: dict[str, int] = { @@ -41,7 +41,7 @@ STATUS_STR_TO_ID: dict[str, int] = { "disabled": int(StatusId.DISABLED), } -ALL_MODE_IDS: tuple[int, ...] = (int(ModeId.AUTO), int(ModeId.FAST), int(ModeId.EXPERT)) +ALL_MODE_IDS: tuple[int, ...] = (int(ModeId.AUTO), int(ModeId.FAST), int(ModeId.EXPERT), 3) __all__ = [ "ModeId", "PoolId", "StatusId", diff --git a/app/main.py b/app/main.py index 3b000cff..b7bdffbb 100644 --- a/app/main.py +++ b/app/main.py @@ -4,8 +4,6 @@ Start with: uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app """ -from __future__ import annotations - import os import platform import sys @@ -20,6 +18,7 @@ from fastapi.staticfiles import StaticFiles from app.platform.logging.logger import logger, setup_logging, reload_logging from app.platform.config.snapshot import config as _config from app.platform.errors import AppError +from app.platform.meta import get_project_version # --------------------------------------------------------------------------- # Early logging setup (before config is loaded) @@ -44,10 +43,14 @@ async def lifespan(app: FastAPI): ) # 2. Initialise account repository and bootstrap runtime table. - from app.control.account.backends.factory import create_repository + from app.control.account.backends.factory import create_repository, describe_repository_target + from app.control.account.runtime import set_refresh_service from app.control.account.scheduler import get_account_refresh_scheduler from app.dataplane.account import get_account_directory + storage_backend, storage_target = describe_repository_target() + logger.info("Account storage: backend={} target={}", storage_backend, storage_target) + repo = create_repository() await repo.initialize() directory = await get_account_directory(repo) @@ -64,6 +67,7 @@ async def lifespan(app: FastAPI): # Expose refresh service for fire-and-forget post-call quota sync. app.state.refresh_service = refresh_svc + set_refresh_service(refresh_svc) # 4. Initialise proxy directory. from app.control.proxy import get_proxy_directory @@ -77,6 +81,7 @@ async def lifespan(app: FastAPI): # ----------- logger.info("Grok2API shutting down.") scheduler.stop() + set_refresh_service(None) await repo.close() @@ -87,7 +92,7 @@ async def lifespan(app: FastAPI): def create_app() -> FastAPI: app = FastAPI( title = "Grok2API", - version = "2.0.0", + version = get_project_version(), description = "OpenAI-compatible API gateway for Grok", lifespan = lifespan, ) @@ -120,7 +125,7 @@ def create_app() -> FastAPI: ) # Routers. - from app.products.web.routes import router as web_router + from app.products.web import router as web_router from app.products.openai.router import router as openai_router app.include_router(web_router) diff --git a/app/migrations/account_v1_to_v2.py b/app/migrations/account_v1_to_v2.py index d8123e10..7a540d8c 100644 --- a/app/migrations/account_v1_to_v2.py +++ b/app/migrations/account_v1_to_v2.py @@ -6,8 +6,6 @@ v1 schema (``data/account/v1/accounts.db``): v2 schema: current ``LocalAccountRepository`` (per-mode quota columns). """ -from __future__ import annotations - import sqlite3 from contextlib import closing from pathlib import Path diff --git a/app/migrations/runner.py b/app/migrations/runner.py index 7e098e0a..118b4ded 100644 --- a/app/migrations/runner.py +++ b/app/migrations/runner.py @@ -1,7 +1,5 @@ """Migration runner — import legacy token storage into the new account domain.""" -from __future__ import annotations - import argparse import asyncio import os diff --git a/app/platform/auth/middleware.py b/app/platform/auth/middleware.py index 3183d196..09dc6576 100644 --- a/app/platform/auth/middleware.py +++ b/app/platform/auth/middleware.py @@ -1,10 +1,8 @@ """API-key authentication dependencies for FastAPI routes.""" -from __future__ import annotations - import hmac -from fastapi import Header, HTTPException, status +from fastapi import Header, HTTPException, Query, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from app.platform.config.snapshot import get_config @@ -76,13 +74,18 @@ async def verify_api_key( async def verify_admin_key( authorization: str | None = Header(default=None), + app_key: str | None = Query(default=None), ) -> None: - """Validate Bearer token against ``app.app_key`` (admin access).""" + """Validate Bearer token against ``app.app_key`` (admin access). + + Accepts either ``Authorization: Bearer <key>`` header or ``?app_key=<key>`` + query parameter (the latter is needed for EventSource which cannot send headers). + """ key = get_admin_key() if not key: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Admin key is not configured.") - token = _extract_bearer(authorization) + token = _extract_bearer(authorization) or app_key if token is None: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing authentication token.") diff --git a/app/platform/config/loader.py b/app/platform/config/loader.py index 0958b352..d9f44ec5 100644 --- a/app/platform/config/loader.py +++ b/app/platform/config/loader.py @@ -1,7 +1,5 @@ """TOML configuration loader with environment-variable override support.""" -from __future__ import annotations - import os from pathlib import Path from typing import Any diff --git a/app/platform/config/snapshot.py b/app/platform/config/snapshot.py index 87ebe45c..ef3ad86f 100644 --- a/app/platform/config/snapshot.py +++ b/app/platform/config/snapshot.py @@ -1,7 +1,5 @@ """Typed configuration snapshot — built once at startup, read-only at runtime.""" -from __future__ import annotations - import asyncio from pathlib import Path from typing import Any @@ -9,6 +7,15 @@ from typing import Any from .loader import get_nested, load_config _BASE_DIR = Path(__file__).resolve().parents[3] # project root +_DATA_DIR = _BASE_DIR / "data" + + +def _resolve_defaults_path() -> Path: + return _BASE_DIR / "config.defaults.toml" + + +def _resolve_user_path() -> Path: + return _DATA_DIR / "config.toml" class ConfigSnapshot: @@ -30,8 +37,10 @@ class ConfigSnapshot: ) -> None: """Load configuration files. Idempotent — subsequent calls reload.""" async with self._lock: - dp = defaults_path or (_BASE_DIR / "config.defaults.toml") - up = user_path or (_BASE_DIR / "config.toml") + dp = defaults_path or _resolve_defaults_path() + up = user_path or _resolve_user_path() + if not dp.exists(): + raise RuntimeError(f"Missing required defaults config: {dp}") self._data = await asyncio.to_thread(load_config, dp, up) self._loaded = True @@ -86,12 +95,13 @@ class ConfigSnapshot: from .loader import _deep_merge self._data = _deep_merge(self._data, patch) # Persist to user config file. - user_path = _BASE_DIR / "config.toml" + user_path = _resolve_user_path() await asyncio.to_thread(self._write_toml, user_path, self._data) @staticmethod def _write_toml(path: Path, data: dict[str, Any]) -> None: """Write config dict to TOML file.""" + path.parent.mkdir(parents=True, exist_ok=True) try: import tomli_w with open(path, "wb") as fh: diff --git a/app/platform/errors.py b/app/platform/errors.py index 9279ba63..8fd2f318 100644 --- a/app/platform/errors.py +++ b/app/platform/errors.py @@ -1,7 +1,5 @@ """Platform-level exception hierarchy.""" -from __future__ import annotations - from enum import StrEnum diff --git a/app/platform/logging/logger.py b/app/platform/logging/logger.py index 0c6b901b..aa19f732 100644 --- a/app/platform/logging/logger.py +++ b/app/platform/logging/logger.py @@ -1,7 +1,5 @@ """Application logger — loguru with structured-field support.""" -from __future__ import annotations - import os import sys from pathlib import Path diff --git a/app/platform/meta.py b/app/platform/meta.py new file mode 100644 index 00000000..53892520 --- /dev/null +++ b/app/platform/meta.py @@ -0,0 +1,29 @@ +"""Project metadata helpers sourced from pyproject.toml.""" + +from functools import lru_cache +from pathlib import Path +import tomllib + + +_ROOT = Path(__file__).resolve().parents[2] +_PYPROJECT = _ROOT / "pyproject.toml" + + +@lru_cache(maxsize=1) +def get_project_meta() -> dict[str, str]: + data: dict[str, str] = {"name": "grok2api", "version": "0.0.0"} + if not _PYPROJECT.exists(): + return data + with _PYPROJECT.open("rb") as fh: + parsed = tomllib.load(fh) + project = parsed.get("project") or {} + name = str(project.get("name") or data["name"]).strip() or data["name"] + version = str(project.get("version") or data["version"]).strip() or data["version"] + return {"name": name, "version": version} + + +def get_project_version() -> str: + return get_project_meta()["version"] + + +__all__ = ["get_project_meta", "get_project_version"] diff --git a/app/platform/net/grpc.py b/app/platform/net/grpc.py index f334414d..52949058 100644 --- a/app/platform/net/grpc.py +++ b/app/platform/net/grpc.py @@ -4,8 +4,6 @@ Encodes data frames for gRPC-Web requests and parses response frames, including trailer extraction and gRPC status code mapping. """ -from __future__ import annotations - import base64 import json import re diff --git a/app/platform/net/http_pool.py b/app/platform/net/http_pool.py deleted file mode 100644 index 2d54a46f..00000000 --- a/app/platform/net/http_pool.py +++ /dev/null @@ -1,99 +0,0 @@ -"""Shared HTTP session pool for curl_cffi. - -Provides a module-level session pool that can be reused across requests, -avoiding the overhead of creating a new session per request. -""" - -from __future__ import annotations - -import asyncio -from contextlib import asynccontextmanager -from typing import AsyncGenerator - -from app.platform.logging.logger import logger - - -class HttpPool: - """Manages a pool of reusable curl_cffi AsyncSession instances. - - Sessions are created lazily and returned to the pool after use. - """ - - def __init__(self, max_size: int = 8) -> None: - self._max_size = max_size - self._pool: asyncio.Queue = asyncio.Queue(maxsize=max_size) - self._created = 0 - self._lock = asyncio.Lock() - - @asynccontextmanager - async def acquire(self, **session_kwargs) -> AsyncGenerator: - """Acquire a session from the pool, yield it, then return it. - - If the pool is empty and under max_size, a new session is created. - """ - session = await self._get_or_create(**session_kwargs) - try: - yield session - finally: - await self._return(session) - - async def _get_or_create(self, **session_kwargs): - # Try to get an existing session without waiting. - try: - return self._pool.get_nowait() - except asyncio.QueueEmpty: - pass - - async with self._lock: - if self._created < self._max_size: - self._created += 1 - return await self._create_session(**session_kwargs) - - # Pool full — wait for a return. - return await self._pool.get() - - async def _create_session(self, **session_kwargs): - from curl_cffi.requests import AsyncSession - return AsyncSession(**session_kwargs) - - async def _return(self, session) -> None: - try: - self._pool.put_nowait(session) - except asyncio.QueueFull: - # Pool is full, close the extra session. - try: - await session.close() - except Exception: - pass - async with self._lock: - self._created = max(0, self._created - 1) - - async def close_all(self) -> None: - """Close all sessions in the pool.""" - closed = 0 - while not self._pool.empty(): - try: - session = self._pool.get_nowait() - await session.close() - closed += 1 - except Exception: - pass - async with self._lock: - self._created = 0 - if closed: - logger.debug("HttpPool: closed {} sessions", closed) - - -# Module-level default pool. -_default_pool: HttpPool | None = None - - -def get_http_pool(max_size: int = 8) -> HttpPool: - """Return the module-level HTTP session pool.""" - global _default_pool - if _default_pool is None: - _default_pool = HttpPool(max_size=max_size) - return _default_pool - - -__all__ = ["HttpPool", "get_http_pool"] diff --git a/app/platform/runtime/batch.py b/app/platform/runtime/batch.py index bfd9138b..fcd51b96 100644 --- a/app/platform/runtime/batch.py +++ b/app/platform/runtime/batch.py @@ -1,7 +1,5 @@ """Bounded-concurrency batch processing utility.""" -from __future__ import annotations - import asyncio from collections.abc import Awaitable, Callable, Iterable from typing import Any, TypeVar diff --git a/app/platform/runtime/clock.py b/app/platform/runtime/clock.py index 0399b67c..3f276a9d 100644 --- a/app/platform/runtime/clock.py +++ b/app/platform/runtime/clock.py @@ -1,7 +1,5 @@ """Monotonic-safe time utilities for hot-path and control-plane use.""" -from __future__ import annotations - import time diff --git a/app/platform/runtime/ids.py b/app/platform/runtime/ids.py index bc2179c0..34ddd2ff 100644 --- a/app/platform/runtime/ids.py +++ b/app/platform/runtime/ids.py @@ -1,7 +1,5 @@ """Compact, monotonic lease-id generation without UUID overhead.""" -from __future__ import annotations - import threading _lock = threading.Lock() diff --git a/app/platform/runtime/task.py b/app/platform/runtime/task.py index ff30abcf..46c5a47c 100644 --- a/app/platform/runtime/task.py +++ b/app/platform/runtime/task.py @@ -1,7 +1,5 @@ """Async batch task model + in-memory store for SSE progress streaming.""" -from __future__ import annotations - import asyncio import time import uuid diff --git a/app/platform/storage/__init__.py b/app/platform/storage/__init__.py index e69de29b..65fd31df 100644 --- a/app/platform/storage/__init__.py +++ b/app/platform/storage/__init__.py @@ -0,0 +1,5 @@ +"""Platform storage helpers.""" + +from .media_paths import image_files_dir, video_files_dir + +__all__ = ["image_files_dir", "video_files_dir"] diff --git a/app/platform/storage/contract.py b/app/platform/storage/contract.py index a9ab19b2..632a785d 100644 --- a/app/platform/storage/contract.py +++ b/app/platform/storage/contract.py @@ -1,7 +1,5 @@ """Abstract storage contract used by all persistence backends.""" -from __future__ import annotations - from typing import Any, Protocol, runtime_checkable diff --git a/app/platform/storage/media_paths.py b/app/platform/storage/media_paths.py new file mode 100644 index 00000000..794f492a --- /dev/null +++ b/app/platform/storage/media_paths.py @@ -0,0 +1,22 @@ +"""Shared local media storage paths.""" + +from pathlib import Path + +_FILES_DIR = Path("data/files") +_IMAGE_DIR = _FILES_DIR / "images" +_VIDEO_DIR = _FILES_DIR / "videos" + + +def image_files_dir() -> Path: + """Return the local image storage directory.""" + _IMAGE_DIR.mkdir(parents=True, exist_ok=True) + return _IMAGE_DIR + + +def video_files_dir() -> Path: + """Return the local video storage directory.""" + _VIDEO_DIR.mkdir(parents=True, exist_ok=True) + return _VIDEO_DIR + + +__all__ = ["image_files_dir", "video_files_dir"] diff --git a/app/platform/storage/revision.py b/app/platform/storage/revision.py index 29cf4076..1e7c5e22 100644 --- a/app/platform/storage/revision.py +++ b/app/platform/storage/revision.py @@ -16,8 +16,6 @@ Backends that manage their own revision counter (e.g. SQLite, in-memory) can inherit from ``RevisionTracker`` to get a thread-safe bump + read helper. """ -from __future__ import annotations - import threading diff --git a/app/platform/update_check.py b/app/platform/update_check.py new file mode 100644 index 00000000..953fe6b4 --- /dev/null +++ b/app/platform/update_check.py @@ -0,0 +1,159 @@ +"""GitHub release update checks with lightweight in-process caching.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone +import re +import time +from typing import Any + +import aiohttp + +from app.platform.meta import get_project_version + +_RELEASES_URL = "https://api.github.com/repos/chenyme/grok2api/releases" +_CACHE_TTL_SECONDS = 1800.0 +_ERROR_TTL_SECONDS = 300.0 +_LOCK = asyncio.Lock() +_CACHE: dict[str, Any] = {"expires_at": 0.0, "payload": None} + + +def _utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _normalize_version(value: str) -> str: + text = str(value or "").strip() + if text.lower().startswith("v"): + text = text[1:] + return text + + +def _parse_version(value: str) -> tuple[int, int, int, int, int] | None: + normalized = _normalize_version(value) + match = re.match(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:(?:\.|-)?rc(\d+))?$", normalized, re.IGNORECASE) + if not match: + return None + major, minor, patch, rc = match.groups() + is_final = 1 if rc is None else 0 + rc_number = int(rc or 0) + return int(major or 0), int(minor or 0), int(patch or 0), is_final, rc_number + + +def _is_newer(latest: str, current: str) -> bool: + latest_parsed = _parse_version(latest) + current_parsed = _parse_version(current) + if latest_parsed and current_parsed: + return latest_parsed > current_parsed + return _normalize_version(latest) > _normalize_version(current) + + +def _release_version_key(release: dict[str, Any]) -> tuple[int, int, int, int, int] | None: + version = str(release.get("tag_name") or release.get("name") or "").strip() + return _parse_version(version) + + +def _select_latest_release(releases: list[dict[str, Any]]) -> dict[str, Any] | None: + candidates: list[tuple[tuple[int, int, int, int, int], dict[str, Any]]] = [] + for release in releases: + if not isinstance(release, dict) or bool(release.get("draft")): + continue + version_key = _release_version_key(release) + if version_key is None: + continue + candidates.append((version_key, release)) + if not candidates: + return None + candidates.sort(key=lambda item: item[0], reverse=True) + return candidates[0][1] + + +def _normalize_error_message(value: str) -> str: + text = str(value or "").strip() + lowered = text.lower() + if "rate limit exceeded" in lowered: + return "GitHub API rate limit exceeded." + if text.startswith("GitHub release query failed:"): + status_match = re.search(r"GitHub release query failed:\s*(\d{3})", text) + if status_match: + return f"GitHub release query failed ({status_match.group(1)})." + return "GitHub release query failed." + if text == "GitHub releases response invalid": + return "GitHub releases response invalid." + if text == "No valid GitHub releases found": + return "No valid GitHub releases found." + return text or "Update check failed." + + +def _build_payload(release: dict[str, Any] | None = None, error: str = "") -> dict[str, Any]: + current_version = get_project_version() + release = release or {} + latest_version = _normalize_version(str(release.get("tag_name") or release.get("name") or "")) + release_name = str(release.get("name") or "").strip() + release_url = str(release.get("html_url") or "").strip() + published_at = str(release.get("published_at") or "").strip() + release_notes = str(release.get("body") or "").strip() + has_remote = bool(release) + return { + "current_version": current_version, + "latest_version": latest_version, + "release_name": release_name, + "release_url": release_url, + "published_at": published_at, + "release_notes": release_notes, + "update_available": has_remote and bool(latest_version) and _is_newer(latest_version, current_version), + "checked_at": _utc_now_iso(), + "status": "error" if error else "ok", + "error": _normalize_error_message(error), + } + + +async def _fetch_latest_release() -> dict[str, Any]: + timeout = aiohttp.ClientTimeout(total=10) + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "grok2api-update-check", + } + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.get(_RELEASES_URL, headers=headers, params={"per_page": "100"}) as response: + if response.status != 200: + detail = (await response.text()).strip() + raise RuntimeError(f"GitHub release query failed: {response.status} {detail}".strip()) + data = await response.json() + if not isinstance(data, list): + raise RuntimeError("GitHub releases response invalid") + release = _select_latest_release(data) + if not release: + raise RuntimeError("No valid GitHub releases found") + return release + + +async def get_latest_release_info() -> dict[str, Any]: + now = time.monotonic() + cached = _CACHE.get("payload") + expires_at = float(_CACHE.get("expires_at") or 0.0) + if cached and expires_at > now: + return cached + + async with _LOCK: + cached = _CACHE.get("payload") + expires_at = float(_CACHE.get("expires_at") or 0.0) + now = time.monotonic() + if cached and expires_at > now: + return cached + + try: + release = await _fetch_latest_release() + payload = _build_payload(release=release) + ttl = _CACHE_TTL_SECONDS + except Exception as exc: + payload = _build_payload(error=str(exc)) + ttl = _ERROR_TTL_SECONDS + + _CACHE["payload"] = payload + _CACHE["expires_at"] = now + ttl + return payload + + +__all__ = ["get_latest_release_info"] diff --git a/app/products/admin/__init__.py b/app/products/admin/__init__.py deleted file mode 100644 index 5bc0c2e6..00000000 --- a/app/products/admin/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .router import router - -__all__ = ["router"] diff --git a/app/products/admin/handlers/__init__.py b/app/products/admin/handlers/__init__.py deleted file mode 100644 index c608b1ee..00000000 --- a/app/products/admin/handlers/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Admin handler sub-package.""" diff --git a/app/products/admin/handlers/batch_ops.py b/app/products/admin/handlers/batch_ops.py deleted file mode 100644 index 5b6e39ba..00000000 --- a/app/products/admin/handlers/batch_ops.py +++ /dev/null @@ -1,181 +0,0 @@ -"""Batch operations — NSFW enable, usage refresh, online cache clear. - -Supports both sync (default) and async mode (``?async=true`` → returns task_id). -""" - -from __future__ import annotations - -import asyncio - -from fastapi import APIRouter, HTTPException, Query -from fastapi.responses import JSONResponse -from pydantic import BaseModel - -from app.platform.logging.logger import logger -from app.platform.runtime.task import AsyncTask, create_task, expire_task -from app.control.account.commands import ListAccountsQuery -from app.control.account.repository import AccountRepository - -router = APIRouter(prefix="/batch") - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - - -def _get_repo() -> AccountRepository: - try: - from app.main import app as _app - return _app.state.repository - except Exception: - from app.control.account.backends.factory import create_repository - return create_repository() - - -def _mask(token: str) -> str: - return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token - - -async def _list_all_tokens() -> list[str]: - repo = _get_repo() - page_num, tokens = 1, [] - while True: - page = await repo.list_accounts(ListAccountsQuery(page=page_num, page_size=2000)) - tokens.extend(r.token for r in page.items) - if page_num * 2000 >= page.total: - break - page_num += 1 - return tokens - - -class BatchRequest(BaseModel): - tokens: list[str] = [] - - -async def _dispatch_batch( - tokens: list[str], - handler, - *, - use_async: bool, - label: str, -): - """Run *handler* per token sync or async; return appropriate response.""" - if use_async: - task = create_task(len(tokens)) - - async def _run(): - try: - results, ok_c, fail_c = {}, 0, 0 - for token in tokens: - if task.cancelled: - task.finish_cancelled() - return - try: - data = await handler(token) - ok_c += 1 - results[_mask(token)] = data - task.record(True) - except Exception as exc: - fail_c += 1 - results[_mask(token)] = {"error": str(exc)} - task.record(False, error=str(exc)) - task.finish({ - "status": "success", - "summary": {"total": len(tokens), "ok": ok_c, "fail": fail_c}, - "results": results, - }) - except Exception as exc: - task.fail_task(str(exc)) - finally: - asyncio.create_task(expire_task(task.id, 300)) - - asyncio.create_task(_run()) - return JSONResponse({"status": "success", "task_id": task.id, "total": len(tokens)}) - - # Sync path - results, ok_c, fail_c = {}, 0, 0 - for token in tokens: - try: - data = await handler(token) - ok_c += 1 - results[_mask(token)] = data - except Exception as exc: - fail_c += 1 - results[_mask(token)] = {"error": str(exc)} - return JSONResponse({ - "status": "success", - "summary": {"total": len(tokens), "ok": ok_c, "fail": fail_c}, - "results": results, - }) - - -# --------------------------------------------------------------------------- -# Per-token handlers -# --------------------------------------------------------------------------- - -async def _nsfw_one(token: str) -> dict: - from app.dataplane.reverse.protocol.xai_auth import accept_tos, set_birth_date, enable_nsfw - await accept_tos(token) - await set_birth_date(token) - await enable_nsfw(token) - return {"success": True} - - -async def _refresh_one(token: str) -> dict: - from app.control.account.refresh import AccountRefreshService - repo = _get_repo() - svc = AccountRefreshService(repo) - result = await svc.refresh_tokens([token]) - return {"refreshed": result.refreshed, "failed": result.failed} - - -async def _cache_clear_one(token: str) -> dict: - from app.dataplane.reverse.transport.assets import list_assets, delete_asset - assets_resp = await list_assets(token) - items = assets_resp.get("assets", assets_resp.get("items", [])) - deleted = 0 - for item in items: - asset_id = item.get("id") or item.get("assetId") - if asset_id: - await delete_asset(token, asset_id) - deleted += 1 - return {"deleted": deleted} - - -# --------------------------------------------------------------------------- -# Endpoints -# --------------------------------------------------------------------------- - -@router.post("/nsfw") -async def batch_nsfw( - req: BatchRequest, - async_mode: bool = Query(False, alias="async"), -): - tokens = [t.strip() for t in req.tokens if t.strip()] - if not tokens: - tokens = await _list_all_tokens() - if not tokens: - raise HTTPException(status_code=400, detail="No tokens available") - return await _dispatch_batch(tokens, _nsfw_one, use_async=async_mode, label="nsfw") - - -@router.post("/refresh") -async def batch_refresh( - req: BatchRequest, - async_mode: bool = Query(False, alias="async"), -): - tokens = [t.strip() for t in req.tokens if t.strip()] - if not tokens: - raise HTTPException(status_code=400, detail="No tokens provided") - return await _dispatch_batch(tokens, _refresh_one, use_async=async_mode, label="refresh") - - -@router.post("/cache-clear") -async def batch_cache_clear( - req: BatchRequest, - async_mode: bool = Query(False, alias="async"), -): - tokens = [t.strip() for t in req.tokens if t.strip()] - if not tokens: - raise HTTPException(status_code=400, detail="No tokens provided") - return await _dispatch_batch(tokens, _cache_clear_one, use_async=async_mode, label="cache-clear") diff --git a/app/products/admin/handlers/batch_stream.py b/app/products/admin/handlers/batch_stream.py deleted file mode 100644 index 7ae67bba..00000000 --- a/app/products/admin/handlers/batch_stream.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Generic SSE task stream + cancel for batch operations.""" - -from __future__ import annotations - -import asyncio - -import orjson -from fastapi import APIRouter, HTTPException, Request -from fastapi.responses import StreamingResponse - -from app.platform.auth.middleware import get_admin_key -from app.platform.runtime.task import get_task - -router = APIRouter(prefix="/batch") - - -@router.get("/{task_id}/stream") -async def batch_stream(task_id: str, request: Request): - # Auth via query param for SSE (Bearer header not always available in EventSource). - app_key = get_admin_key() - if app_key: - key = request.query_params.get("app_key") - if key != app_key: - raise HTTPException(status_code=401, detail="Invalid authentication token") - - task = get_task(task_id) - if not task: - raise HTTPException(status_code=404, detail="Task not found") - - async def event_stream(): - queue = task.attach() - try: - yield f"data: {orjson.dumps({'type': 'snapshot', **task.snapshot()}).decode()}\n\n" - - final = task.final_event() - if final: - yield f"data: {orjson.dumps(final).decode()}\n\n" - return - - while True: - try: - event = await asyncio.wait_for(queue.get(), timeout=15) - except asyncio.TimeoutError: - yield ": ping\n\n" - final = task.final_event() - if final: - yield f"data: {orjson.dumps(final).decode()}\n\n" - return - continue - - yield f"data: {orjson.dumps(event).decode()}\n\n" - if event.get("type") in ("done", "error", "cancelled"): - return - finally: - task.detach(queue) - - return StreamingResponse(event_stream(), media_type="text/event-stream") - - -@router.post("/{task_id}/cancel") -async def batch_cancel(task_id: str): - task = get_task(task_id) - if not task: - raise HTTPException(status_code=404, detail="Task not found") - task.cancel() - return {"status": "success"} diff --git a/app/products/admin/handlers/config.py b/app/products/admin/handlers/config.py deleted file mode 100644 index 5b29e069..00000000 --- a/app/products/admin/handlers/config.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Admin config CRUD + verify + storage info.""" - -from __future__ import annotations - -import os -import re - -from fastapi import APIRouter, HTTPException -from fastapi.responses import JSONResponse - -from app.platform.config.snapshot import config, get_config -from app.platform.logging.logger import logger, reload_logging - -router = APIRouter() - -# --------------------------------------------------------------------------- -# Proxy config sanitisation -# --------------------------------------------------------------------------- - -_CFG_CHAR_REPLACEMENTS = str.maketrans({ - "\u2010": "-", "\u2011": "-", "\u2012": "-", - "\u2013": "-", "\u2014": "-", "\u2212": "-", - "\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"', - "\u00a0": " ", "\u2007": " ", "\u202f": " ", - "\u200b": "", "\u200c": "", "\u200d": "", "\ufeff": "", -}) - - -def _sanitize_text(value, *, remove_all_spaces: bool = False) -> str: - text = "" if value is None else str(value) - text = text.translate(_CFG_CHAR_REPLACEMENTS) - if remove_all_spaces: - text = re.sub(r"\s+", "", text) - else: - text = text.strip() - return text.encode("latin-1", errors="ignore").decode("latin-1") - - -def _sanitize_proxy_config(data: dict) -> dict: - if not isinstance(data, dict): - return data - payload = dict(data) - proxy = payload.get("proxy") - if not isinstance(proxy, dict): - return payload - - sanitized = dict(proxy) - changed = False - for key, strip_spaces in [("user_agent", False), ("cf_cookies", False), ("cf_clearance", True)]: - if key in sanitized: - raw = sanitized[key] - val = _sanitize_text(raw, remove_all_spaces=strip_spaces) - if val != raw: - sanitized[key] = val - changed = True - if changed: - logger.warning("Sanitized proxy config fields before saving") - payload["proxy"] = sanitized - return payload - - -# --------------------------------------------------------------------------- -# Endpoints -# --------------------------------------------------------------------------- - -@router.get("/verify") -async def admin_verify(): - return {"status": "success"} - - -@router.get("/config") -async def get_config_endpoint(): - return JSONResponse(config.raw()) - - -@router.post("/config") -async def update_config(data: dict): - try: - await config.update(_sanitize_proxy_config(data)) - reload_logging() - return {"status": "success", "message": "配置已更新"} - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) - - -@router.get("/storage") -async def get_storage_mode(): - backend = get_config("account.storage", "local") - return {"type": str(backend).strip().lower() or "local"} diff --git a/app/products/admin/handlers/diagnostics.py b/app/products/admin/handlers/diagnostics.py deleted file mode 100644 index 3b9bb73f..00000000 --- a/app/products/admin/handlers/diagnostics.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Admin diagnostics — runtime status + force sync.""" - -from __future__ import annotations - -from fastapi import APIRouter -from fastapi.responses import JSONResponse - -router = APIRouter() - - -@router.get("/status") -async def runtime_status(): - from app.dataplane.account import _directory - if _directory is None: - return JSONResponse({"status": "not_initialised"}) - return JSONResponse({ - "status": "ok", - "size": _directory.size, - "revision": _directory.revision, - }) - - -@router.post("/sync") -async def force_sync(): - from app.dataplane.account import _directory - if _directory is None: - return JSONResponse({"error": "not_initialised"}, status_code=503) - changed = await _directory.sync_if_changed() - return JSONResponse({"changed": changed, "revision": _directory.revision}) diff --git a/app/products/admin/handlers/tokens.py b/app/products/admin/handlers/tokens.py deleted file mode 100644 index 9bf82ae6..00000000 --- a/app/products/admin/handlers/tokens.py +++ /dev/null @@ -1,185 +0,0 @@ -"""Admin token CRUD handlers.""" - -from __future__ import annotations - -import asyncio -import re - -from fastapi import APIRouter, Query -from fastapi.responses import JSONResponse -from pydantic import BaseModel - -from app.platform.logging.logger import logger -from app.control.account.commands import AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery -from app.control.account.repository import AccountRepository - -router = APIRouter() - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - -_TOKEN_TRANS = str.maketrans({ - "\u2010": "-", "\u2011": "-", "\u2012": "-", - "\u2013": "-", "\u2014": "-", "\u2212": "-", - "\u00a0": " ", "\u2007": " ", "\u202f": " ", - "\u200b": "", "\u200c": "", "\u200d": "", "\ufeff": "", -}) - - -def _sanitize(value: str) -> str: - tok = str(value or "").translate(_TOKEN_TRANS) - tok = re.sub(r"\s+", "", tok) - if tok.startswith("sso="): - tok = tok[4:] - return tok.encode("ascii", errors="ignore").decode("ascii") - - -def _mask(token: str) -> str: - return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token - - -def _get_repo() -> AccountRepository: - try: - from app.main import app as _app - return _app.state.repository - except Exception: - from app.control.account.backends.factory import create_repository - return create_repository() - - -# --------------------------------------------------------------------------- -# Request models -# --------------------------------------------------------------------------- - -class AddTokensRequest(BaseModel): - tokens: list[str] - pool: str = "basic" - tags: list[str] = [] - - -class ReplacePoolRequest(BaseModel): - pool: str - tokens: list[str] - tags: list[str] = [] - - -# --------------------------------------------------------------------------- -# Endpoints -# --------------------------------------------------------------------------- - -@router.post("/tokens") -async def save_tokens(data: dict): - """Full pool replace — accepts {pool_name: [token_objects]} dict (legacy frontend format).""" - repo = _get_repo() - total_upserted = 0 - all_upserted_tokens: list[str] = [] - for pool_name, items in data.items(): - if not isinstance(items, list): - continue - upserts = [] - for item in items: - token_data = {"token": item} if isinstance(item, str) else dict(item or {}) - token_val = _sanitize(token_data.get("token", "")) - if not token_val: - continue - upserts.append(AccountUpsert( - token = token_val, - pool = pool_name, - tags = token_data.get("tags") or [], - )) - if upserts: - cmd = BulkReplacePoolCommand(pool=pool_name, upserts=upserts) - await repo.replace_pool(cmd) - all_upserted_tokens.extend(u.token for u in upserts) - total_upserted += len(upserts) - logger.info("Admin: saved {} tokens across pools", total_upserted) - if all_upserted_tokens: - asyncio.create_task(_refresh_imported(all_upserted_tokens)) - return JSONResponse({"status": "success", "count": total_upserted}) - - -@router.delete("/tokens") -async def delete_tokens(tokens: list[str]): - repo = _get_repo() - cleaned = [t for t in (_sanitize(t) for t in tokens) if t] - if not cleaned: - return JSONResponse({"error": "No valid tokens provided"}, status_code=400) - await repo.delete_accounts(cleaned) - logger.info("Admin: deleted {} tokens", len(cleaned)) - return JSONResponse({"deleted": len(cleaned)}) - - -@router.put("/tokens/pool") -async def replace_pool(req: ReplacePoolRequest): - repo = _get_repo() - cleaned = [t for t in (_sanitize(t) for t in req.tokens) if t] - upserts = [AccountUpsert(token=t, pool=req.pool, tags=req.tags) for t in cleaned] - cmd = BulkReplacePoolCommand(pool=req.pool, upserts=upserts) - await repo.replace_pool(cmd) - logger.info("Admin: replaced pool={} with {} tokens", req.pool, len(cleaned)) - if cleaned: - asyncio.create_task(_refresh_imported(cleaned)) - return JSONResponse({"pool": req.pool, "count": len(cleaned)}) - - -async def _refresh_imported(tokens: list[str]) -> None: - """Fire-and-forget: fetch real quotas for newly imported tokens.""" - try: - from app.control.account.refresh import AccountRefreshService - svc = AccountRefreshService(_get_repo()) - await svc.refresh_on_import(tokens) - logger.info("Import quota sync complete for {} tokens", len(tokens)) - except Exception as exc: - logger.debug("Import quota sync failed: {}", exc) - - -def _quota_dict(r) -> dict: - """Return {auto, fast, expert} remaining/total dict for frontend display.""" - q = getattr(r, "quota", None) - if not isinstance(q, dict): - return {} - result = {} - for mode in ("auto", "fast", "expert"): - v = q.get(mode, {}) - if isinstance(v, dict): - result[mode] = {"remaining": int(v.get("remaining", 0) or 0), "total": int(v.get("total", 0) or 0)} - return result - - -@router.get("/tokens") -async def list_tokens(): - """Return all tokens grouped by pool (legacy format for frontend).""" - repo = _get_repo() - all_items = [] - page_num = 1 - while True: - query = ListAccountsQuery(page=page_num, page_size=2000) - page = await repo.list_accounts(query) - all_items.extend(page.items) - if page_num * 2000 >= page.total: - break - page_num += 1 - result: dict[str, list] = {} - for r in all_items: - pool = r.pool or "basic" - result.setdefault(pool, []).append({ - "token": r.token, - "status": r.status, - "quota": _quota_dict(r), - "consumed": 0, - "created_at": r.created_at, - "last_used_at": r.last_use_at, - "use_count": r.usage_use_count or 0, - "fail_count": r.usage_fail_count or 0, - "last_fail_at": r.last_fail_at, - "last_fail_reason": r.last_fail_reason, - "last_sync_at": r.last_sync_at, - "tags": r.tags or [], - "note": getattr(r, "note", "") or "", - "last_asset_clear_at": r.last_clear_at, - }) - return JSONResponse({ - "tokens": result, - "consumed_mode_enabled": False, - }) diff --git a/app/products/admin/router.py b/app/products/admin/router.py deleted file mode 100644 index d2b83380..00000000 --- a/app/products/admin/router.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Admin API router — slim aggregator for all admin sub-routers.""" - -from __future__ import annotations - -from fastapi import APIRouter, Depends - -from app.platform.auth.middleware import verify_admin_key -from .handlers.config import router as config_router -from .handlers.tokens import router as tokens_router -from .handlers.diagnostics import router as diagnostics_router -from .handlers.batch_ops import router as batch_ops_router -from .handlers.batch_stream import router as batch_stream_router -from .handlers.cache import router as cache_router - -router = APIRouter(prefix="/admin/api", dependencies=[Depends(verify_admin_key)]) -router.include_router(config_router) -router.include_router(tokens_router) -router.include_router(diagnostics_router) -router.include_router(batch_ops_router) -router.include_router(batch_stream_router) -router.include_router(cache_router) - -__all__ = ["router"] diff --git a/app/products/openai/_format.py b/app/products/openai/_format.py new file mode 100644 index 00000000..47ce8785 --- /dev/null +++ b/app/products/openai/_format.py @@ -0,0 +1,201 @@ +"""Response formatting utilities — pure functions, no async, no IO. + +Two sections: + - Chat Completions format (make_response_id, make_stream_chunk, …) + - Responses API format (make_resp_id, make_resp_object, …) +""" + +import math +import os +import re +import time +from typing import Any + +import orjson + +_SEGMENT_RE = re.compile(r"\w+|[^\w\s]", re.UNICODE) +_PROMPT_OVERHEAD = 4 + + +# --------------------------------------------------------------------------- +# Shared +# --------------------------------------------------------------------------- + +def estimate_tokens(value: Any) -> int: + """Lightweight token count estimate (UTF-8 bytes / 4, min 1 if non-empty).""" + if value is None: + return 0 + if not isinstance(value, str): + try: + value = orjson.dumps(value).decode() + except Exception: + value = str(value) + text = value.strip() + if not text: + return 0 + byte_est = math.ceil(len(text.encode()) / 4) + segment_est = math.ceil(len(_SEGMENT_RE.findall(text)) * 0.75) + return max(1, byte_est, segment_est) + + +# --------------------------------------------------------------------------- +# Chat Completions format +# --------------------------------------------------------------------------- + +def make_response_id() -> str: + return f"chatcmpl-{int(time.time() * 1000)}{os.urandom(4).hex()}" + + +def build_usage(prompt_tokens: int, completion_tokens: int, *, reasoning_tokens: int = 0) -> dict: + pt = max(0, prompt_tokens) + ct = max(0, completion_tokens) + rt = max(0, reasoning_tokens) + return { + "prompt_tokens": pt, + "completion_tokens": ct, + "total_tokens": pt + ct, + "prompt_tokens_details": { + "cached_tokens": 0, "text_tokens": pt, + "audio_tokens": 0, "image_tokens": 0, + }, + "completion_tokens_details": { + "text_tokens": ct - rt, "audio_tokens": 0, "reasoning_tokens": rt, + }, + } + + +def make_stream_chunk( + response_id: str, + model: str, + content: str, + *, + index: int = 0, + role: str = "assistant", + is_final: bool = False, + finish_reason: str | None = None, + usage: dict | None = None, +) -> dict: + choice: dict = { + "index": index, + "delta": {"role": role, "content": content}, + } + if is_final: + choice["finish_reason"] = finish_reason or "stop" + + chunk: dict = { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [choice], + } + if usage is not None: + chunk["usage"] = usage + return chunk + + +def make_thinking_chunk( + response_id: str, + model: str, + content: str, + *, + index: int = 0, + role: str = "assistant", +) -> dict: + """Stream chunk carrying reasoning_content (DeepSeek-R1 style thinking delta).""" + return { + "id": response_id, + "object": "chat.completion.chunk", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": index, + "delta": {"role": role, "reasoning_content": content}, + }], + } + + +def make_chat_response( + model: str, + content: str, + *, + response_id: str | None = None, + usage: dict | None = None, + reasoning_content: str | None = None, +) -> dict: + rid = response_id or make_response_id() + pt = estimate_tokens(content) + _PROMPT_OVERHEAD + ct = estimate_tokens(content) + rt = estimate_tokens(reasoning_content) if reasoning_content else 0 + ct += rt + + msg: dict = {"role": "assistant", "content": content} + if reasoning_content: + msg["reasoning_content"] = reasoning_content + + return { + "id": rid, + "object": "chat.completion", + "created": int(time.time()), + "model": model, + "choices": [{ + "index": 0, + "message": msg, + "finish_reason": "stop", + }], + "usage": usage or build_usage(pt, ct, reasoning_tokens=rt), + } + + +# --------------------------------------------------------------------------- +# Responses API format +# --------------------------------------------------------------------------- + +def make_resp_id(prefix: str) -> str: + """Generate a Responses API item ID, e.g. resp_xxx / rs_xxx / msg_xxx.""" + return f"{prefix}_{int(time.time() * 1000)}{os.urandom(4).hex()}" + + +def build_resp_usage(input_tokens: int, output_tokens: int, reasoning_tokens: int = 0) -> dict: + return { + "input_tokens": max(0, input_tokens), + "output_tokens": max(0, output_tokens), + "total_tokens": max(0, input_tokens + output_tokens), + "output_tokens_details": {"reasoning_tokens": max(0, reasoning_tokens)}, + } + + +def make_resp_object( + response_id: str, + model: str, + status: str, + output: list[dict], + usage: dict | None = None, +) -> dict: + obj: dict = { + "id": response_id, + "object": "response", + "created_at": int(time.time()), + "status": status, + "model": model, + "output": output, + } + if usage is not None: + obj["usage"] = usage + return obj + + +def format_sse(event: str, data: dict) -> str: + """Encode a single Responses API SSE event frame.""" + return f"event: {event}\ndata: {orjson.dumps(data).decode()}\n\n" + + +__all__ = [ + # shared + "estimate_tokens", + # chat completions + "make_response_id", "build_usage", + "make_stream_chunk", "make_thinking_chunk", "make_chat_response", + # responses api + "make_resp_id", "build_resp_usage", "make_resp_object", "format_sse", +] diff --git a/app/products/openai/chat.py b/app/products/openai/chat.py index 9b38e66e..0024bd75 100644 --- a/app/products/openai/chat.py +++ b/app/products/openai/chat.py @@ -1,8 +1,7 @@ """Chat completion service — orchestrates account selection, reverse, streaming.""" -from __future__ import annotations - import asyncio +import base64 from typing import Any, AsyncGenerator import orjson @@ -11,16 +10,19 @@ from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config from app.platform.errors import RateLimitError, UpstreamError from app.platform.runtime.clock import now_s +from app.platform.storage import image_files_dir +from app.control.account.runtime import get_refresh_service from app.control.model.registry import resolve as resolve_model +from app.control.model.enums import ModeId from app.control.account.enums import FeedbackKind -from app.dataplane.account import AccountDirectory +from app.dataplane.proxy.adapters.headers import build_http_headers from app.dataplane.proxy import get_proxy_runtime from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.protocol.xai_chat import build_chat_payload, classify_line, StreamAdapter from app.dataplane.reverse.runtime.endpoint_table import CHAT -from app.dataplane.reverse.protocol.xai_chat import build_chat_payload, classify_line -from app.dataplane.proxy.adapters.headers import build_http_headers -from .response import ( - make_response_id, make_stream_chunk, make_chat_response, +from app.dataplane.reverse.transport.asset_upload import upload_from_input +from ._format import ( + make_response_id, make_stream_chunk, make_thinking_chunk, make_chat_response, estimate_tokens, build_usage, ) @@ -28,14 +30,116 @@ from .response import ( async def _quota_sync(token: str, mode_id: int) -> None: """Fire-and-forget: fetch real quota after a successful call.""" try: - from app.main import app as _app - svc = getattr(_app.state, "refresh_service", None) + svc = get_refresh_service() if svc: await svc.refresh_call_async(token, mode_id) except Exception: pass +async def _fail_sync(token: str, mode_id: int) -> None: + """Fire-and-forget: persist failure counter after a failed call.""" + try: + svc = get_refresh_service() + if svc: + await svc.record_failure_async(token, mode_id) + except Exception: + pass + + +def _parse_retry_codes(s: str) -> frozenset[int]: + """Parse a comma-separated list of HTTP status codes into a frozenset.""" + result: set[int] = set() + for part in s.split(","): + part = part.strip() + if part.isdigit(): + result.add(int(part)) + return frozenset(result) + + +def _feedback_kind(exc: BaseException) -> "FeedbackKind": + """Map an upstream exception to the appropriate FeedbackKind.""" + status = getattr(exc, "status", 0) + if status == 429: + return FeedbackKind.RATE_LIMITED + if status == 401: + return FeedbackKind.AUTH_FAILURE + if status == 403: + return FeedbackKind.FORBIDDEN + return FeedbackKind.SERVER_ERROR + + +async def _download_image_bytes(token: str, url: str) -> tuple[bytes, str]: + """Download image bytes via the shared asset transport used by /v1/images.""" + from app.dataplane.reverse.protocol.xai_assets import infer_content_type + from app.dataplane.reverse.transport.assets import download_asset + + try: + stream, content_type = await download_asset(token, url) + chunks: list[bytes] = [] + async for chunk in stream: + chunks.append(chunk) + except UpstreamError: + raise + except Exception as exc: + raise UpstreamError(f"Image download failed: {exc}") from exc + return b"".join(chunks), (content_type or infer_content_type(url) or "image/jpeg") + + +def _save_image(raw: bytes, mime: str, image_id: str) -> str: + """Save raw bytes to data/files/images/, return the file ID.""" + img_dir = image_files_dir() + ext = ".png" if "png" in mime else ".jpg" + path = img_dir / f"{image_id}{ext}" + if not path.exists(): + path.write_bytes(raw) + return image_id + + +async def _resolve_image(token: str, url: str, image_id: str) -> str: + """Return the image embed text for the response body based on image_format config. + + Format values: + grok_url — raw CDN URL (no download) + local_url — download + serve locally, return accessible URL + grok_md — ![image](grok_cdn_url) markdown + local_md — ![image](local_url) markdown + base64 — ![image](data:...) markdown + """ + cfg = get_config() + fmt = cfg.get_str("features.image_format", "grok_url") + + # Backward compatibility: old "url" value → local_url + if fmt == "url": + fmt = "local_url" + + # Formats that don't need downloading + if fmt == "grok_url": + return url + if fmt == "grok_md": + return f"![image]({url})" + + # Formats that require downloading + try: + raw, mime = await _download_image_bytes(token, url) + except Exception as exc: + logger.warning("Image download failed, falling back to raw URL: {}", exc) + return url + + if fmt == "base64": + b64 = base64.b64encode(raw).decode() + return f"![image](data:{mime};base64,{b64})" + + # local_url / local_md: save to disk and return local path + file_id = _save_image(raw, mime, image_id) + app_url = cfg.get_str("app.app_url", "").rstrip("/") + local_url = f"{app_url}/v1/files/image?id={file_id}" if app_url else f"/v1/files/image?id={file_id}" + + if fmt == "local_url": + return local_url + return f"![image]({local_url})" # local_md + + def _extract_message(messages: list[dict]) -> tuple[str, list[str]]: """Flatten OpenAI messages into a single prompt string + file attachments.""" parts: list[str] = [] @@ -74,11 +178,21 @@ def _extract_message(messages: list[dict]) -> tuple[str, list[str]]: return "\n\n".join(parts), files +async def _prepare_file_attachments(token: str, file_inputs: list[str]) -> list[str]: + """Upload OpenAI-style multimodal inputs and return Grok chat attachment IDs.""" + attachments: list[str] = [] + for file_input in file_inputs: + if not file_input: + continue + file_id, _file_uri = await upload_from_input(token, file_input) + if file_id: + attachments.append(file_id) + return attachments + + async def _stream_chat( token: str, - model_name: str, - grok_model: str, - grok_mode: str, + mode_id: "ModeId", message: str, files: list[str], *, @@ -90,12 +204,12 @@ async def _stream_chat( """Yield raw SSE lines from the Grok app-chat endpoint.""" proxy = await get_proxy_runtime() lease = await proxy.acquire() + attachments = await _prepare_file_attachments(token, files) payload = build_chat_payload( message = message, - model_name = grok_model, - model_mode = grok_mode, - file_attachments = files, + mode_id = mode_id, + file_attachments = attachments, tool_overrides = tool_overrides, model_config_override = model_config_override, request_overrides = request_overrides, @@ -122,7 +236,7 @@ async def _stream_chat( if response.status_code != 200: try: - body = (await response.aread()).decode("utf-8", "replace")[:400] + body = response.content.decode("utf-8", "replace")[:400] except Exception: body = "" raise UpstreamError( @@ -140,6 +254,7 @@ async def completions( model: str, messages: list[dict], stream: bool | None = None, + thinking: bool | None = None, tools: list[dict] | None = None, tool_choice: Any = None, temperature: float = 0.8, @@ -149,137 +264,220 @@ async def completions( """Entry point for /v1/chat/completions. Returns an async generator for streaming, or a dict for non-streaming. + Supports transparent retry with a different account on configured HTTP + status codes (chat.retry_on_codes) up to chat.max_retries times. """ - cfg = get_config() - spec = resolve_model(model) - is_stream = stream if stream is not None else cfg.get_bool("app.stream", True) + cfg = get_config() + spec = resolve_model(model) + is_stream = stream if stream is not None else cfg.get_bool("features.stream", True) + emit_think = thinking if thinking is not None else cfg.get_bool("features.thinking", True) - # Map mode_id to upstream modeId string. - from app.control.model.enums import ModeId - _MODE_TO_UPSTREAM: dict[ModeId, str] = { - ModeId.AUTO: "MODEL_MODE_AUTO", - ModeId.FAST: "MODEL_MODE_FAST", - ModeId.EXPERT: "MODEL_MODE_EXPERT", - } - grok_mode = _MODE_TO_UPSTREAM.get(spec.mode_id, "MODEL_MODE_AUTO") + logger.info("Chat request: model={} stream={} msgs={}", model, is_stream, len(messages)) message, files = _extract_message(messages) if not message.strip(): raise UpstreamError("Empty message after extraction", status=400) - # Select account via the module-level singleton (bootstrapped at startup). from app.dataplane.account import _directory as _acct_dir if _acct_dir is None: raise RateLimitError("Account directory not initialised") directory = _acct_dir - ts = now_s() - acct = await directory.reserve( - pool_id = spec.pool_id(), - mode_id = int(spec.mode_id), - now_s_override = ts, - ) - if acct is None: - raise RateLimitError("No available accounts for this model tier") + max_retries = cfg.get_int("retry.max_retries", 1) + retry_codes = _parse_retry_codes(cfg.get_str("retry.on_codes", "429,503")) + response_id = make_response_id() + timeout_s = cfg.get_float("chat.timeout", 120.0) - token = acct.token - response_id = make_response_id() - - # Tool override payload. tool_overrides: dict | None = None if tools: tool_overrides = {"tools": tools, "toolChoice": tool_choice or "auto"} - timeout_s = cfg.get_float("chat.timeout", 120.0) + # ── Streaming path ──────────────────────────────────────────────────────── + if is_stream: + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct = await directory.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + exclude_tokens = excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") - async def _run_stream() -> AsyncGenerator[str, None]: - success = False - try: - async for line in _stream_chat( - token = token, - model_name = model, - grok_model = spec.model_name, - grok_mode = grok_mode, - message = message, - files = files, - tool_overrides = tool_overrides, - request_overrides = request_overrides, - timeout_s = timeout_s, - ): - event_type, data = classify_line(line) - if event_type == "done": - break - if event_type != "data" or not data: - continue + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() - # Parse token from SSE data. try: - obj = orjson.loads(data) - result = obj.get("result") or {} - token_text = result.get("message", {}).get("token") - if token_text is None: + try: + ended = False + async for line in _stream_chat( + token = token, + mode_id = spec.mode_id, + message = message, + files = files, + tool_overrides = tool_overrides, + request_overrides = request_overrides, + timeout_s = timeout_s, + ): + event_type, data = classify_line(line) + logger.debug("SSE: type={} data_len={}", event_type, len(data)) + if event_type == "done": + break + if event_type != "data" or not data: + continue + events = adapter.feed(data) + if not events: + logger.debug("StreamAdapter skip: data[:120]={}", data[:120]) + for ev in events: + if ev.kind == "text": + chunk = make_stream_chunk(response_id, model, ev.content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + elif ev.kind == "thinking" and emit_think: + chunk = make_thinking_chunk(response_id, model, ev.content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + elif ev.kind == "soft_stop": + ended = True + break + if ended: + break + + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + chunk = make_stream_chunk(response_id, model, img_text + "\n") + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + references = adapter.references_suffix() + if references: + chunk = make_stream_chunk(response_id, model, references) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + logger.info("Chat stream done (attempt {}/{}): model={} images={}", + attempt + 1, max_retries + 1, model, len(adapter.image_urls)) + + except UpstreamError as exc: + fail_exc = exc + if exc.status in retry_codes and attempt < max_retries: + _retry = True + logger.warning("Chat stream retry {}/{}: status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8]) + else: + raise + + finally: + await directory.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await directory.feedback(token, kind, int(spec.mode_id), now_s_val=now_s()) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + if success or not _retry: + return + excluded.append(token) + + return _run_stream() + + # ── Non-streaming path ──────────────────────────────────────────────────── + excluded: list[str] = [] + adapter = StreamAdapter() + for attempt in range(max_retries + 1): + acct = await directory.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + exclude_tokens = excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + + try: + try: + async for line in _stream_chat( + token = token, + mode_id = spec.mode_id, + message = message, + files = files, + tool_overrides = tool_overrides, + request_overrides = request_overrides, + timeout_s = timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: continue - except Exception: - continue + ended = False + for ev in adapter.feed(data): + if ev.kind == "soft_stop": + ended = True + break + if ended: + break + success = True - chunk = make_stream_chunk(response_id, model, token_text) - yield f"data: {orjson.dumps(chunk).decode()}\n\n" - - # Final chunk. - final = make_stream_chunk(response_id, model, "", is_final=True) - yield f"data: {orjson.dumps(final).decode()}\n\n" - yield "data: [DONE]\n\n" - success = True + except UpstreamError as exc: + fail_exc = exc + if exc.status in retry_codes and attempt < max_retries: + _retry = True + logger.warning("Chat retry {}/{}: status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8]) + else: + raise finally: await directory.release(acct) - kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR - await directory.feedback( - token, kind, int(spec.mode_id), now_s_val=now_s() - ) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await directory.feedback(token, kind, int(spec.mode_id)) if success: asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) - if is_stream: - return _run_stream() - - # Non-streaming: collect full response. - full_text = "" - async for line in _stream_chat( - token = token, - model_name = model, - grok_model = spec.model_name, - grok_mode = grok_mode, - message = message, - files = files, - tool_overrides = tool_overrides, - request_overrides = request_overrides, - timeout_s = timeout_s, - ): - event_type, data = classify_line(line) - if event_type == "done": + if success or not _retry: break - if event_type != "data" or not data: - continue - try: - obj = orjson.loads(data) - result = obj.get("result") or {} - tok = result.get("message", {}).get("token") - if tok: - full_text += tok - except Exception: - continue + excluded.append(token) - await directory.release(acct) - await directory.feedback(token, FeedbackKind.SUCCESS, int(spec.mode_id)) - asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + full_text = "".join(adapter.text_buf) + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + if full_text: + full_text += "\n\n" + full_text += img_text + + references = adapter.references_suffix() + if references: + full_text += references + + thinking_text = ("".join(adapter.thinking_buf) or None) if emit_think else None + + logger.info("Chat non-stream done (attempt {}/{}): model={} text_len={} think_len={} images={}", + attempt + 1, max_retries + 1, model, len(full_text), + len(thinking_text or ""), len(adapter.image_urls)) pt = estimate_tokens(message) + 4 ct = estimate_tokens(full_text) + rt = estimate_tokens(thinking_text) if thinking_text else 0 return make_chat_response( model, full_text, - response_id = response_id, - usage = build_usage(pt, ct), + response_id = response_id, + reasoning_content = thinking_text, + usage = build_usage(pt, ct + rt, reasoning_tokens=rt), ) diff --git a/app/products/openai/dto.py b/app/products/openai/dto.py deleted file mode 100644 index ec0dd320..00000000 --- a/app/products/openai/dto.py +++ /dev/null @@ -1,69 +0,0 @@ -"""OpenAI-compatible request/response DTOs.""" - -from __future__ import annotations - -from typing import Any, Dict, List, Optional, Union - -from pydantic import BaseModel, Field - - -class MessageItem(BaseModel): - role: str - content: Optional[Union[str, List[Dict[str, Any]]]] = None - tool_calls: Optional[List[Dict[str, Any]]] = None - tool_call_id: Optional[str] = None - name: Optional[str] = None - - -class ImageConfig(BaseModel): - n: Optional[int] = Field(1, ge=1, le=10) - size: Optional[str] = "1024x1024" - response_format: Optional[str] = None - - -class VideoConfig(BaseModel): - aspect_ratio: Optional[str] = "3:2" - video_length: Optional[int] = Field(6, ge=6, le=30) - resolution_name: Optional[str] = "480p" - preset: Optional[str] = "custom" - - -class ChatCompletionRequest(BaseModel): - model: str - messages: List[MessageItem] - stream: Optional[bool] = None - reasoning_effort: Optional[str] = None - temperature: Optional[float] = 0.8 - top_p: Optional[float] = 0.95 - image_config: Optional[ImageConfig] = None - video_config: Optional[VideoConfig] = None - tools: Optional[List[Dict[str, Any]]] = None - tool_choice: Optional[Union[str, Dict[str, Any]]] = None - parallel_tool_calls: Optional[bool] = True - max_tokens: Optional[int] = None - - -class ImageGenerationRequest(BaseModel): - model: str - prompt: str - n: Optional[int] = Field(1, ge=1, le=10) - size: Optional[str] = "1024x1024" - response_format: Optional[str] = "url" - - -class ImageEditRequest(BaseModel): - """OpenAI /v1/images/edits — edit an existing image with a prompt.""" - - model: str - prompt: str - image: str # URL or data-URI of the source image - mask: Optional[str] = None # ignored (not supported upstream) - n: Optional[int] = Field(1, ge=1, le=10) - size: Optional[str] = "1024x1024" - response_format: Optional[str] = "url" - - -__all__ = [ - "MessageItem", "ImageConfig", "VideoConfig", - "ChatCompletionRequest", "ImageGenerationRequest", "ImageEditRequest", -] diff --git a/app/products/openai/image.py b/app/products/openai/image.py deleted file mode 100644 index 61f7c5cc..00000000 --- a/app/products/openai/image.py +++ /dev/null @@ -1,173 +0,0 @@ -"""Image generation service — Imagine WebSocket + OpenAI format output.""" - -from __future__ import annotations - -import asyncio -import base64 -import time -from typing import Any, AsyncGenerator - -import orjson - -from app.platform.logging.logger import logger -from app.platform.config.snapshot import get_config -from app.platform.errors import RateLimitError, UpstreamError -from app.platform.runtime.clock import now_s -from app.control.model.registry import resolve as resolve_model -from app.control.account.enums import FeedbackKind -from app.dataplane.reverse.transport.imagine_ws import stream_images -from .response import make_response_id, make_stream_chunk, build_usage - -# Aspect-ratio alias table (size string or ratio string → canonical ratio). -_RATIO_MAP: dict[str, str] = { - "1280x720": "16:9", "16:9": "16:9", - "720x1280": "9:16", "9:16": "9:16", - "1792x1024": "3:2", "3:2": "3:2", - "1024x1792": "2:3", "2:3": "2:3", - "1024x1024": "1:1", "1:1": "1:1", -} - - -def resolve_aspect_ratio(size: str) -> str: - return _RATIO_MAP.get(size, "2:3") - - -def _wrap_image_markdown(content: str, response_format: str) -> str: - if not content: - return "" - if response_format == "url": - return f"![image]({content})" - return f"![image](data:image/png;base64,{content})" - - -async def generate( - *, - model: str, - prompt: str, - n: int = 1, - size: str = "1024x1024", - response_format: str = "url", - stream: bool = False, - chat_format: bool = False, -) -> dict | AsyncGenerator[str, None]: - """Generate images via the Imagine WebSocket reverse. - - Returns: - - Non-streaming: OpenAI images.generations response dict, or chat response if chat_format=True. - - Streaming: async generator of SSE strings (chat.completion.chunk format). - """ - cfg = get_config() - spec = resolve_model(model) - aspect_ratio = resolve_aspect_ratio(size) - enable_nsfw = cfg.get_bool("app.enable_nsfw", True) - - # Acquire account. - from app.dataplane.account import _directory as _acct_dir - if _acct_dir is None: - raise RateLimitError("Account directory not initialised") - - ts = now_s() - acct = await _acct_dir.reserve( - pool_id = spec.pool_id(), - mode_id = int(spec.mode_id), - now_s_override = ts, - ) - if acct is None: - raise RateLimitError("No available accounts for image generation") - - token = acct.token - - async def _collect() -> list[str]: - """Collect n final images and return as list of URL/base64 strings.""" - finals: list[str] = [] - async for ev in stream_images( - token, - prompt, - aspect_ratio = aspect_ratio, - n = n, - enable_nsfw = enable_nsfw, - ): - if ev.get("type") == "error": - logger.warning("Image generation error: {} {}", ev.get("error_code"), ev.get("error")) - raise UpstreamError(f"Image generation failed: {ev.get('error', 'unknown')}") - if ev.get("is_final"): - blob = ev.get("blob", "") - if response_format in ("b64_json", "base64"): - finals.append(blob) - else: - finals.append(ev.get("url", "")) - if len(finals) >= n: - break - return finals - - response_id = make_response_id() - - if stream: - # Stream each final image as a chat chunk. - async def _sse_stream() -> AsyncGenerator[str, None]: - success = False - try: - async for ev in stream_images( - token, prompt, - aspect_ratio = aspect_ratio, - n = n, - enable_nsfw = enable_nsfw, - ): - if ev.get("type") == "error": - raise UpstreamError(f"Image error: {ev.get('error', '')}") - if not ev.get("is_final"): - continue - blob = ev.get("blob", "") - content = ( - blob if response_format in ("b64_json", "base64") - else ev.get("url", "") - ) - if chat_format: - content = _wrap_image_markdown(content, response_format) - chunk = make_stream_chunk(response_id, model, content) - yield f"data: {orjson.dumps(chunk).decode()}\n\n" - - final = make_stream_chunk(response_id, model, "", is_final=True) - yield f"data: {orjson.dumps(final).decode()}\n\n" - yield "data: [DONE]\n\n" - success = True - finally: - await _acct_dir.release(acct) - kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR - await _acct_dir.feedback(token, kind, int(spec.mode_id)) - - return _sse_stream() - - # Non-streaming: collect all images first. - try: - finals = await _collect() - finally: - await _acct_dir.release(acct) - await _acct_dir.feedback(token, FeedbackKind.SUCCESS, int(spec.mode_id)) - - if chat_format: - # Return as chat.completion with markdown image(s). - content = "\n\n".join( - _wrap_image_markdown(img, response_format) for img in finals - ) - from .response import make_chat_response - return make_chat_response( - model, content, - response_id = response_id, - usage = build_usage(0, 0), - ) - - # Standard images.generations response. - data = [] - for img in finals: - if response_format in ("b64_json", "base64"): - data.append({"b64_json": img}) - else: - data.append({"url": img}) - return { - "created": int(time.time()), - "data": data, - } - - -__all__ = ["generate", "resolve_aspect_ratio"] diff --git a/app/products/openai/image_edit.py b/app/products/openai/image_edit.py deleted file mode 100644 index e26196ca..00000000 --- a/app/products/openai/image_edit.py +++ /dev/null @@ -1,310 +0,0 @@ -"""Image edit service — app-chat with file attachments + image generation. - -Uploads input images as file attachments, sends a chat request with the -imageGenerationCount override, and parses generated image URLs from the SSE -response stream. -""" - -from __future__ import annotations - -import time -from typing import Any, AsyncGenerator - -import orjson - -from app.platform.logging.logger import logger -from app.platform.config.snapshot import get_config -from app.platform.errors import RateLimitError, UpstreamError, ValidationError -from app.platform.runtime.clock import now_s -from app.control.model.registry import resolve as resolve_model -from app.control.account.enums import FeedbackKind -from app.dataplane.reverse.protocol.xai_chat import build_chat_payload, classify_line -from app.dataplane.reverse.transport.asset_upload import upload_from_input -from app.dataplane.proxy import get_proxy_runtime -from app.dataplane.proxy.adapters.headers import build_http_headers -from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs -from app.dataplane.reverse.runtime.endpoint_table import CHAT -from .response import make_response_id, make_stream_chunk, make_chat_response, build_usage - -# --------------------------------------------------------------------------- -# Upstream model / mode for image-edit requests -# --------------------------------------------------------------------------- -_EDIT_GROK_MODEL = "grok-4" -_EDIT_GROK_MODE = "MODEL_MODE_AUTO" - - -# --------------------------------------------------------------------------- -# Image URL extraction from SSE response -# --------------------------------------------------------------------------- - -def _collect_image_urls(obj: Any) -> list[str]: - """Recursively collect generated image URLs from a parsed SSE object.""" - urls: list[str] = [] - seen: set[str] = set() - - def _add(url: str) -> None: - if url and url not in seen: - seen.add(url) - urls.append(url) - - def _walk(value: Any) -> None: - if isinstance(value, dict): - for key, item in value.items(): - if key in {"generatedImageUrls", "imageUrls", "imageURLs"}: - if isinstance(item, list): - for url in item: - if isinstance(url, str): - _add(url) - elif isinstance(item, str): - _add(item) - else: - _walk(item) - elif isinstance(value, list): - for item in value: - _walk(item) - - _walk(obj) - return urls - - -def _parse_edit_line(data: str) -> list[str]: - """Extract image URLs from a single SSE data payload (image-edit format).""" - try: - obj = orjson.loads(data) - except Exception: - return [] - - result = obj.get("result") or {} - - # New-style: result.response.modelResponse - response = result.get("response") or {} - model_response = response.get("modelResponse") - if model_response: - urls = _collect_image_urls(model_response) - if urls: - return urls - - # Old-style / fallback: result.message with generatedImages - message = result.get("message") or {} - return _collect_image_urls(message) - - -# --------------------------------------------------------------------------- -# SSE stream runner (raw lines) -# --------------------------------------------------------------------------- - -async def _run_stream( - token: str, - message: str, - file_ids: list[str], - image_count: int, - *, - timeout_s: float = 120.0, -) -> AsyncGenerator[str, None]: - """Yield raw SSE lines from the Grok app-chat endpoint.""" - proxy = await get_proxy_runtime() - lease = await proxy.acquire() - - payload = build_chat_payload( - message = message, - model_name = _EDIT_GROK_MODEL, - model_mode = _EDIT_GROK_MODE, - file_attachments = file_ids, - request_overrides = {"imageGenerationCount": max(1, image_count)}, - ) - headers = build_http_headers(token, lease=lease) - kwargs = build_session_kwargs(lease=lease) - - async with ResettableSession(**kwargs) as session: - response = await session.post( - CHAT, - headers = headers, - data = orjson.dumps(payload), - timeout = timeout_s, - stream = True, - ) - if response.status_code != 200: - body = (await response.aread()).decode("utf-8", "replace")[:300] - raise UpstreamError( - f"Image-edit upstream returned {response.status_code}", - status = response.status_code, - body = body, - ) - async for line in response.aiter_lines(): - yield line - - -# --------------------------------------------------------------------------- -# Public entry point -# --------------------------------------------------------------------------- - -async def edit( - *, - model: str, - messages: list[dict], - n: int = 1, - size: str = "1024x1024", - response_format: str = "url", - stream: bool = False, - chat_format: bool = False, -) -> dict | AsyncGenerator[str, None]: - """Entry point for image-edit requests (model capability IMAGE_EDIT). - - Extracts prompt text and image inputs from *messages*, uploads images as - file attachments, then sends a chat request that produces generated images. - - Returns: - Non-streaming: OpenAI images.generations dict (or chat dict if chat_format=True). - Streaming: async generator of SSE strings. - """ - cfg = get_config() - spec = resolve_model(model) - timeout_s = cfg.get_float("chat.timeout", 120.0) - - # Extract prompt and image inputs from messages. - prompt = "" - image_inputs: list[str] = [] - - for msg in reversed(messages): - content = msg.get("content", "") - if isinstance(content, str) and content.strip(): - if not prompt: - prompt = content.strip() - elif isinstance(content, list): - for block in content: - if not isinstance(block, dict): - continue - btype = block.get("type") - if btype == "text" and not prompt: - prompt = (block.get("text") or "").strip() - elif btype == "image_url": - url = (block.get("image_url") or {}).get("url", "") - if url: - image_inputs.append(url) - - if not prompt: - raise ValidationError("Image edit requires a non-empty text prompt", param="messages") - if not image_inputs: - raise ValidationError( - "Image edit requires at least one image_url content block", param="messages" - ) - - # Acquire account. - from app.dataplane.account import _directory as _acct_dir - if _acct_dir is None: - raise RateLimitError("Account directory not initialised") - - ts = now_s() - acct = await _acct_dir.reserve( - pool_id = spec.pool_id(), - mode_id = int(spec.mode_id), - now_s_override = ts, - ) - if acct is None: - raise RateLimitError("No available accounts for image edit") - - token = acct.token - response_id = make_response_id() - - try: - # Upload images as file attachments (cap at 3 images like the old service). - imgs_to_upload = image_inputs[-3:] if len(image_inputs) > 3 else image_inputs - file_ids: list[str] = [] - for img_input in imgs_to_upload: - try: - fid, _ = await upload_from_input(token, img_input) - if fid: - file_ids.append(fid) - except Exception as exc: - logger.warning("Image edit upload failed for input: {}", exc) - - if not file_ids: - raise UpstreamError("All image uploads failed; cannot proceed with image edit") - - except Exception: - await _acct_dir.release(acct) - raise - - # ----------------------------------------------------------------------- - # Streaming path - # ----------------------------------------------------------------------- - if stream: - async def _sse_stream() -> AsyncGenerator[str, None]: - success = False - try: - final_urls: list[str] = [] - async for line in _run_stream( - token, prompt, file_ids, n, timeout_s=timeout_s, - ): - ev_type, data = classify_line(line) - if ev_type == "done": - break - if ev_type != "data" or not data: - continue - urls = _parse_edit_line(data) - for url in urls: - if url not in final_urls: - final_urls.append(url) - - for url in final_urls[:n]: - content = _format_image(url, response_format, chat_format) - chunk = make_stream_chunk(response_id, model, content) - yield f"data: {orjson.dumps(chunk).decode()}\n\n" - - final = make_stream_chunk(response_id, model, "", is_final=True) - yield f"data: {orjson.dumps(final).decode()}\n\n" - yield "data: [DONE]\n\n" - success = True - - finally: - await _acct_dir.release(acct) - kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR - await _acct_dir.feedback(token, kind, int(spec.mode_id)) - - return _sse_stream() - - # ----------------------------------------------------------------------- - # Non-streaming path - # ----------------------------------------------------------------------- - try: - final_urls: list[str] = [] - async for line in _run_stream(token, prompt, file_ids, n, timeout_s=timeout_s): - ev_type, data = classify_line(line) - if ev_type == "done": - break - if ev_type != "data" or not data: - continue - for url in _parse_edit_line(data): - if url not in final_urls: - final_urls.append(url) - finally: - await _acct_dir.release(acct) - await _acct_dir.feedback(token, FeedbackKind.SUCCESS, int(spec.mode_id)) - - images = final_urls[:n] - - if chat_format: - content = "\n\n".join(_format_image(u, response_format, chat_format=True) for u in images) - return make_chat_response( - model, content, - response_id = response_id, - usage = build_usage(0, 0), - ) - - data_list = [ - {"url": u} if response_format == "url" else {"b64_json": u} - for u in images - ] - return {"created": int(time.time()), "data": data_list} - - -def _format_image(url: str, response_format: str, chat_format: bool) -> str: - """Format a single image URL/b64 for inclusion in a response.""" - if chat_format: - if response_format == "url": - return f"![image]({url})" - return f"![image](data:image/png;base64,{url})" - return url - - -__all__ = ["edit"] diff --git a/app/products/openai/images.py b/app/products/openai/images.py new file mode 100644 index 00000000..6240d4d5 --- /dev/null +++ b/app/products/openai/images.py @@ -0,0 +1,1159 @@ +"""Image services — generation (/v1/images/generations) and editing (/v1/images/edits).""" + +import asyncio +import base64 +import binascii +import hashlib +import re +import time +from dataclasses import dataclass +from typing import Any, AsyncGenerator, Awaitable, Callable + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError, ValidationError +from app.platform.runtime.clock import now_s +from app.platform.storage import image_files_dir +from app.control.model.registry import resolve as resolve_model +from app.control.model.enums import ModeId +from app.control.model.spec import ModelSpec +from app.control.account.enums import FeedbackKind +from app.dataplane.reverse.transport.imagine_ws import stream_images +from app.dataplane.reverse.protocol.xai_chat import ( + StreamAdapter, + build_chat_payload, + classify_line, +) +from app.dataplane.reverse.protocol.xai_assets import infer_content_type, resolve_asset_reference, resolve_download_url +from app.dataplane.reverse.protocol.xai_image_edit import ( + IMAGE_EDIT_GENERATION_COUNT, + IMAGE_POST_MEDIA_TYPE, + build_image_edit_payload, + extract_model_response_file_attachments, + extract_model_response_urls, + extract_streaming_response, +) +from app.dataplane.reverse.transport.assets import download_asset +from app.dataplane.reverse.transport.asset_upload import ( + resolve_uploaded_asset_reference, + upload_from_input, +) +from app.dataplane.reverse.transport.media import create_media_post +from app.dataplane.proxy import get_proxy_runtime +from app.dataplane.proxy.adapters.headers import build_http_headers, build_sso_cookie +from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs +from app.dataplane.reverse.runtime.endpoint_table import CHAT +from ._format import ( + make_chat_response, + make_response_id, + make_stream_chunk, + make_thinking_chunk, +) +from .chat import _quota_sync, _fail_sync + +_X_USER_ID_RE = re.compile(r"(?:^|;\s*)x-userid=([^;]+)") + + +# --------------------------------------------------------------------------- +# Aspect-ratio helpers (generation) +# --------------------------------------------------------------------------- + +_RATIO_MAP: dict[str, str] = { + "1280x720": "16:9", "16:9": "16:9", + "720x1280": "9:16", "9:16": "9:16", + "1792x1024": "3:2", "3:2": "3:2", + "1024x1792": "2:3", "2:3": "2:3", + "1024x1024": "1:1", "1:1": "1:1", +} + + +def resolve_aspect_ratio(size: str) -> str: + return _RATIO_MAP.get(size, "2:3") + + +@dataclass(slots=True) +class _ImageOutput: + api_value: str + markdown_value: str + + +def _clamp_progress(value: int) -> int: + return max(0, min(100, int(value))) + + +def _compute_progress_percent(progress_map: dict[object, int], total: int) -> int: + if total <= 0: + return 100 + if not progress_map: + return 0 + values = sorted((_clamp_progress(value) for value in progress_map.values()), reverse=True)[:total] + return _clamp_progress(sum(values) // total) + + +def _progress_reason(label: str, progress: int, *, completed: int | None = None, total: int | None = None) -> str: + reason = f"{label}正在生成 {progress}%" + if completed is not None and total is not None and total > 0: + reason += f" ({completed}/{total})" + return reason + + +def _append_reason_update( + updates: list[str], + label: str, + progress: int, + *, + completed: int | None = None, + total: int | None = None, +) -> None: + reason = _progress_reason(label, progress, completed=completed, total=total) + if not updates or updates[-1] != reason: + updates.append(reason) + + +def _completed_items(progress_map: dict[object, int]) -> int: + return sum(1 for value in progress_map.values() if _clamp_progress(value) >= 100) + + +async def _lite_progress_updates( + *, + idx: int, + progress: int, + total: int, + progress_map: dict[int, int], + updates: list[str], + enabled: bool, +) -> None: + progress_map[idx] = _clamp_progress(progress) + if enabled: + _append_reason_update( + updates, + "图片", + _compute_progress_percent(progress_map, total), + completed=_completed_items(progress_map), + total=total, + ) + + +def _normalize_response_format(response_format: str) -> str: + fmt = (response_format or "url").strip().lower() + if fmt == "base64": + return "b64_json" + if fmt not in {"url", "b64_json"}: + raise ValidationError( + "response_format must be one of ['url', 'b64_json', 'base64']", + param="response_format", + ) + return fmt + + +def _app_url() -> str: + return get_config().get_str("app.app_url", "").rstrip("/") + + +def _local_image_url(file_id: str) -> str: + app_url = _app_url() + return f"{app_url}/v1/files/image?id={file_id}" + + +def _extract_image_file_id(url: str) -> str: + parts = [part for part in url.split("/") if part] + for part in reversed(parts): + stem = part.split(".", 1)[0] + if stem and stem not in {"image", "original", "thumbnail"}: + return stem + return hashlib.sha1(url.encode("utf-8")).hexdigest()[:32] + + +def _save_image(raw: bytes, mime: str, file_id: str) -> str: + img_dir = image_files_dir() + ext = ".png" if "png" in mime else ".jpg" + path = img_dir / f"{file_id}{ext}" + if not path.exists(): + path.write_bytes(raw) + return file_id + + +async def _download_image_bytes(token: str, url: str) -> tuple[bytes, str]: + try: + stream, content_type = await download_asset(token, url) + chunks: list[bytes] = [] + async for chunk in stream: + chunks.append(chunk) + except UpstreamError: + raise + except Exception as exc: + raise UpstreamError(f"Image download failed: {exc}") from exc + return b"".join(chunks), (content_type or infer_content_type(url) or "image/jpeg") + + +async def _resolve_image_output( + *, + token: str, + url: str, + response_format: str, + blob_b64: str | None = None, +) -> _ImageOutput: + fmt = _normalize_response_format(response_format) + if fmt == "url" and not _app_url(): + return _ImageOutput(api_value=url, markdown_value=f"![image]({url})") + + mime = infer_content_type(url) or "image/jpeg" + if blob_b64 is not None: + try: + raw = base64.b64decode(blob_b64) + except (ValueError, TypeError, binascii.Error) as exc: + raise UpstreamError(f"Invalid upstream image blob: {exc}") from exc + else: + raw, mime = await _download_image_bytes(token, url) + + if fmt == "b64_json": + b64 = blob_b64 or base64.b64encode(raw).decode() + data_uri = f"data:{mime};base64,{b64}" + return _ImageOutput(api_value=b64, markdown_value=f"![image]({data_uri})") + + file_id = _save_image(raw, mime, _extract_image_file_id(url)) + local_url = _local_image_url(file_id) + return _ImageOutput(api_value=local_url, markdown_value=f"![image]({local_url})") + + +def _output_content(image: _ImageOutput, *, chat_format: bool) -> str: + return image.markdown_value if chat_format else image.api_value + + +# --------------------------------------------------------------------------- +# Image generation +# --------------------------------------------------------------------------- + +# Models that use the chat endpoint for image generation (no WS, no params). +_LITE_IMAGE_MODELS = frozenset({"grok-imagine-image-lite"}) +# WS models that use quality mode (enable_pro=True). +_PRO_IMAGE_MODELS = frozenset({"grok-imagine-image-pro"}) + + +async def generate( + *, + model: str, + prompt: str, + n: int = 1, + size: str = "1024x1024", + response_format: str = "url", + stream: bool = False, + chat_format: bool = False, +) -> dict | AsyncGenerator[str, None]: + """Generate images. + + Routes to the appropriate backend based on model: + grok-imagine-image-lite → chat endpoint (no aspect-ratio control, all pools) + grok-imagine-image → WebSocket speed mode (super+) + grok-imagine-image-pro → WebSocket quality mode (super+) + + Returns: + Non-streaming: OpenAI images.generations dict, or chat dict if chat_format=True. + Streaming: async generator of SSE strings. + """ + cfg = get_config() + spec = resolve_model(model) + aspect_ratio = resolve_aspect_ratio(size) + enable_nsfw = cfg.get_bool("features.enable_nsfw", True) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + # Lite model: chat-based generation (no WS, ignores aspect_ratio). + if model in _LITE_IMAGE_MODELS: + return await _generate_lite( + spec = spec, + prompt = prompt, + n = n, + response_format = response_format, + stream = stream, + chat_format = chat_format, + ) + + acct = await _acct_dir.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for image generation") + + token = acct.token + response_id = make_response_id() + enable_pro = model in _PRO_IMAGE_MODELS + + if stream: + async def _sse_stream() -> AsyncGenerator[str, None]: + success = False + progress_map: dict[object, int] = {} + completed_ids: set[object] = set() + last_progress = -1 + try: + async for ev in stream_images( + token, prompt, + aspect_ratio = aspect_ratio, + n = n, + enable_nsfw = enable_nsfw, + enable_pro = enable_pro, + ): + ev_type = ev.get("type") + if ev_type == "error": + raise UpstreamError(f"Image error: {ev.get('error', '')}") + if ev_type == "moderated": + logger.warning("Image slot {} moderated (skipped)", ev.get("image_id", "")[:8]) + continue + if ev_type == "progress": + key = ev.get("image_id") or f"progress-{len(progress_map)}" + progress_map[key] = _clamp_progress(ev.get("progress") or 0) + aggregate = _compute_progress_percent(progress_map, n) + if chat_format and aggregate > last_progress: + last_progress = aggregate + reason = _progress_reason( + "图片", + aggregate, + completed=len(completed_ids), + total=n, + ) + chunk = make_thinking_chunk(response_id, model, reason) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + continue + if not ev.get("is_final"): + continue + key = ev.get("image_id") or f"final-{len(completed_ids)}" + progress_map[key] = 100 + completed_ids.add(key) + aggregate = _compute_progress_percent(progress_map, n) + if chat_format and aggregate > last_progress: + last_progress = aggregate + reason = _progress_reason("图片", aggregate, completed=len(completed_ids), total=n) + chunk = make_thinking_chunk(response_id, model, reason) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + image = await _resolve_image_output( + token=token, + url=ev.get("url", ""), + response_format=response_format, + blob_b64=ev.get("blob") or None, + ) + content = _output_content(image, chat_format=chat_format) + chunk = make_stream_chunk(response_id, model, content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + return _sse_stream() + + # Non-streaming: collect all final images. + finals: list[_ImageOutput] = [] + reasoning_updates: list[str] = [] + progress_map: dict[object, int] = {} + completed_ids: set[object] = set() + success = False + try: + async for ev in stream_images( + token, prompt, + aspect_ratio = aspect_ratio, + n = n, + enable_nsfw = enable_nsfw, + enable_pro = enable_pro, + ): + ev_type = ev.get("type") + if ev_type == "error": + raise UpstreamError(f"Image generation failed: {ev.get('error', 'unknown')}") + if ev_type == "moderated": + logger.warning("Image slot {} moderated (skipped)", ev.get("image_id", "")[:8]) + continue + if ev_type == "progress": + key = ev.get("image_id") or f"progress-{len(progress_map)}" + progress_map[key] = _clamp_progress(ev.get("progress") or 0) + if chat_format: + _append_reason_update( + reasoning_updates, + "图片", + _compute_progress_percent(progress_map, n), + completed=len(completed_ids), + total=n, + ) + continue + if ev.get("is_final"): + key = ev.get("image_id") or f"final-{len(completed_ids)}" + progress_map[key] = 100 + completed_ids.add(key) + if chat_format: + _append_reason_update( + reasoning_updates, + "图片", + _compute_progress_percent(progress_map, n), + completed=len(completed_ids), + total=n, + ) + image = await _resolve_image_output( + token=token, + url=ev.get("url", ""), + response_format=response_format, + blob_b64=ev.get("blob") or None, + ) + finals.append(image) + success = True + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + if chat_format: + content = "\n\n".join(image.markdown_value for image in finals) + reasoning = "\n".join(reasoning_updates) if reasoning_updates else None + return make_chat_response( + model, + content, + response_id=response_id, + reasoning_content=reasoning, + ) + + data = [ + {"b64_json": image.api_value} + if _normalize_response_format(response_format) == "b64_json" + else {"url": image.api_value} + for image in finals + ] + return {"created": int(time.time()), "data": data} + + +# --------------------------------------------------------------------------- +# Lite image generation (chat-based, no WS, no aspect-ratio control) +# --------------------------------------------------------------------------- + +async def _generate_lite( + *, + spec: ModelSpec, + prompt: str, + n: int, + response_format: str, + stream: bool, + chat_format: bool, +) -> dict | AsyncGenerator[str, None]: + """Generate images via the chat endpoint (Aurora model path). + + Does not support aspect ratio or quality control. All account pools + can serve this model. + """ + response_id = make_response_id() + cfg = get_config() + timeout_s = cfg.get_float("chat.timeout", 120.0) + logger.debug("Lite image fan-out: requests={} mode={}", n, spec.mode_id.name.lower()) + + if stream: + async def _sse_stream() -> AsyncGenerator[str, None]: + progress_map: dict[int, int] = {} + last_progress = -1 + queue: asyncio.Queue[tuple[int, int]] = asyncio.Queue() + + async def _progress(idx: int, progress: int) -> None: + progress_map[idx] = _clamp_progress(progress) + await queue.put(( + _compute_progress_percent(progress_map, n), + _completed_items(progress_map), + )) + + task = asyncio.create_task( + _run_lite_batch( + spec=spec, + prompt=prompt, + n=n, + timeout_s=timeout_s, + response_format=response_format, + progress_cb=_progress, + ) + ) + + while not task.done() or not queue.empty(): + try: + aggregate, completed = await asyncio.wait_for(queue.get(), timeout=0.1) + except asyncio.TimeoutError: + continue + if chat_format and aggregate > last_progress: + last_progress = aggregate + chunk = make_thinking_chunk( + response_id, + spec.model_name, + _progress_reason("图片", aggregate, completed=completed, total=n), + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + images = await task + for image in images: + chunk = make_stream_chunk( + response_id, + spec.model_name, + _output_content(image, chat_format=chat_format), + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, spec.model_name, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + + return _sse_stream() + + reasoning_updates: list[str] = [] + progress_map: dict[int, int] = {} + images = await _run_lite_batch( + spec=spec, + prompt=prompt, + n=n, + timeout_s=timeout_s, + response_format=response_format, + progress_cb=lambda idx, progress: _lite_progress_updates( + idx=idx, + progress=progress, + total=n, + progress_map=progress_map, + updates=reasoning_updates, + enabled=chat_format, + ), + ) + if chat_format: + content = "\n\n".join(image.markdown_value for image in images) + reasoning = "\n".join(reasoning_updates) if reasoning_updates else None + return make_chat_response( + spec.model_name, + content, + response_id=response_id, + reasoning_content=reasoning, + ) + + return { + "created": int(time.time()), + "data": [ + {"b64_json": image.api_value} + if _normalize_response_format(response_format) == "b64_json" + else {"url": image.api_value} + for image in images + ], + } + + +# --------------------------------------------------------------------------- +# Image editing +# --------------------------------------------------------------------------- + +_EDIT_MAX_REFERENCES = 5 +_EDIT_DEFAULT_SIZE = "1024x1024" +_EDIT_MAX_N = 2 +_EDIT_MAX_ATTEMPTS = 2 + + +def _normalize_edit_inputs(image_inputs: list[str]) -> list[str]: + """Validate and normalize image-edit reference inputs.""" + cleaned = [item.strip() for item in image_inputs if isinstance(item, str) and item.strip()] + if not cleaned: + raise ValidationError("Image edit requires at least one image_url content block", param="messages") + if len(cleaned) > _EDIT_MAX_REFERENCES: + raise ValidationError( + f"image edit supports at most {_EDIT_MAX_REFERENCES} reference images", + param="image", + ) + return cleaned + + +def _normalize_edit_size(size: str) -> str: + """Validate the only upstream-backed image-edit size.""" + normalized = (size or _EDIT_DEFAULT_SIZE).strip().lower() + if normalized != _EDIT_DEFAULT_SIZE: + raise ValidationError( + f"image edit currently only supports size {_EDIT_DEFAULT_SIZE!r}", + param="size", + ) + return _EDIT_DEFAULT_SIZE + + +async def _prepare_edit_reference(token: str, image_input: str, index: int) -> str: + """Upload one edit reference and resolve it to the upstream content URL.""" + try: + file_id, file_uri = await upload_from_input(token, image_input) + return resolve_uploaded_asset_reference(token, file_id, file_uri) + except ValidationError as exc: + raise ValidationError(exc.message, param=f"image.{index}") from exc + except UpstreamError as exc: + raise UpstreamError( + f"Image edit reference {index + 1} upload failed: {exc.message}", + status=exc.status, + body=exc.details.get("body", ""), + ) from exc + except Exception as exc: + raise UpstreamError(f"Image edit reference {index + 1} upload failed: {exc}") from exc + + +async def _prepare_edit_references(token: str, image_inputs: list[str]) -> list[str]: + """Upload edit references concurrently and preserve caller order.""" + results: list[str | None] = [None] * len(image_inputs) + + async def _runner(index: int, image_input: str) -> None: + results[index] = await _prepare_edit_reference(token, image_input, index) + + async with asyncio.TaskGroup() as tg: + for index, image_input in enumerate(image_inputs): + tg.create_task(_runner(index, image_input), name=f"image-edit-ref-{index}") + + return [result for result in results if result is not None] + + +def _extract_edit_prompt_and_inputs(messages: list[dict]) -> tuple[str, list[str]]: + """Extract the final prompt and ordered image references from messages.""" + prompt = "" + image_inputs: list[str] = [] + + for msg in messages: + content = msg.get("content", "") + if isinstance(content, str) and content.strip(): + prompt = content.strip() + continue + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type") + if btype == "text": + text = (block.get("text") or "").strip() + if text: + prompt = text + elif btype == "image_url": + url = (block.get("image_url") or {}).get("url", "") + if url: + image_inputs.append(url) + + if not prompt: + raise ValidationError("Image edit requires a non-empty text prompt", param="messages") + return prompt, _normalize_edit_inputs(image_inputs) + + +def _absolutize_asset_url(url: str) -> str: + """Resolve an assets URL/path to an absolute URL.""" + full_url, _, _ = resolve_download_url(url) + return full_url + + +def _extract_user_id(token: str) -> str | None: + cookie = build_sso_cookie(token) + match = _X_USER_ID_RE.search(cookie) + if match: + return match.group(1) + return None + + +def _resolve_edit_final_url( + *, + raw_url: str | None, + asset_id: str | None, + user_id: str | None, +) -> str | None: + """Prefer stable asset content URLs over generated image paths for image-edit finals.""" + if asset_id and user_id: + resolved = resolve_asset_reference(asset_id, "", user_id=user_id) + if resolved: + return resolved + if raw_url: + return _absolutize_asset_url(raw_url) + return None + + +def _collect_edit_results( + *, + obj: dict[str, Any], + final_urls: dict[int, str], + user_id: str | None, +) -> None: + """Update final edit image URLs from one parsed SSE payload.""" + stream = extract_streaming_response(obj) + if stream: + try: + progress = int(stream.get("progress") or 0) + except (TypeError, ValueError): + progress = 0 + if progress >= 100 and not stream.get("moderated"): + raw_url = stream.get("imageUrl") + asset_id = stream.get("assetId") + resolved_url = _resolve_edit_final_url( + raw_url=raw_url if isinstance(raw_url, str) and raw_url else None, + asset_id=asset_id if isinstance(asset_id, str) and asset_id else None, + user_id=user_id, + ) + if resolved_url: + index = _parse_image_index(stream.get("imageIndex")) + if index is not None: + final_urls[index] = resolved_url + + for index, asset_id in enumerate(extract_model_response_file_attachments(obj)): + resolved_url = _resolve_edit_final_url(raw_url=None, asset_id=asset_id, user_id=user_id) + if resolved_url: + final_urls.setdefault(index, resolved_url) + + for index, url in enumerate(extract_model_response_urls(obj)): + final_urls.setdefault(index, _absolutize_asset_url(url)) + + +def _parse_image_index(value: Any) -> int | None: + """Return a non-negative image index from upstream metadata.""" + try: + index = int(value) + except (TypeError, ValueError): + return None + return index if index >= 0 else None + + +async def _collect_edit_final_urls( + *, + token: str, + prompt: str, + image_references: list[str], + parent_post_id: str, + timeout_s: float, + progress_cb: Callable[[int, int], Awaitable[None]] | None = None, +) -> dict[int, str]: + """Collect final image URLs from the dedicated image-edit SSE stream.""" + final_urls: dict[int, str] = {} + user_id = _extract_user_id(token) + async for line in _stream_image_edit( + token, + prompt, + image_references, + parent_post_id, + timeout_s=timeout_s, + ): + ev_type, data = classify_line(line) + if ev_type == "done": + break + if ev_type != "data" or not data: + continue + try: + obj = orjson.loads(data) + except Exception: + continue + stream = extract_streaming_response(obj) + if stream and progress_cb is not None: + index = _parse_image_index(stream.get("imageIndex")) + if index is not None: + try: + progress = _clamp_progress(int(stream.get("progress") or 0)) + except (TypeError, ValueError): + progress = 0 + await progress_cb(index, progress) + _collect_edit_results(obj=obj, final_urls=final_urls, user_id=user_id) + + if not final_urls: + raise UpstreamError("Image edit returned no images") + return final_urls + + +async def _collect_edit_images( + *, + token: str, + prompt: str, + image_references: list[str], + parent_post_id: str, + requested_n: int, + response_format: str, + timeout_s: float, + progress_cb: Callable[[int, int], Awaitable[None]] | None = None, +) -> list[_ImageOutput]: + """Collect up to *requested_n* edit results. + + Upstream image-edit requests are issued with a fixed batch size of 2. + If one batch returns fewer usable finals than requested, issue one more + attempt and merge unique results. + """ + images: list[_ImageOutput] = [] + seen_urls: set[str] = set() + + for _ in range(_EDIT_MAX_ATTEMPTS): + final_urls = await _collect_edit_final_urls( + token=token, + prompt=prompt, + image_references=image_references, + parent_post_id=parent_post_id, + timeout_s=timeout_s, + progress_cb=progress_cb, + ) + for _, url in sorted(final_urls.items()): + if url in seen_urls: + continue + seen_urls.add(url) + images.append( + await _resolve_image_output( + token=token, + url=url, + response_format=response_format, + ) + ) + if len(images) >= requested_n: + return images[:requested_n] + + if len(images) >= requested_n: + break + + if len(images) < requested_n: + logger.warning( + "Image edit returned fewer images than requested: requested={} got={}", + requested_n, len(images), + ) + return images[:requested_n] + + +async def _stream_image_edit( + token: str, + prompt: str, + image_references: list[str], + parent_post_id: str, + *, + timeout_s: float = 120.0, +) -> AsyncGenerator[str, None]: + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + payload = build_image_edit_payload( + prompt=prompt, + image_references=image_references, + parent_post_id=parent_post_id, + ) + headers = build_http_headers( + token, + lease=lease, + origin="https://grok.com", + referer=f"https://grok.com/imagine/post/{parent_post_id}", + ) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.post( + CHAT, + headers=headers, + data=orjson.dumps(payload), + timeout=timeout_s, + stream=True, + ) + if response.status_code != 200: + body = response.content.decode("utf-8", "replace")[:300] + raise UpstreamError( + f"Image-edit upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) + async for line in response.aiter_lines(): + yield line + + +async def _stream_lite_generate( + token: str, + message: str, + mode_id: ModeId, + *, + timeout_s: float = 120.0, +) -> AsyncGenerator[str, None]: + proxy = await get_proxy_runtime() + lease = await proxy.acquire() + payload = build_chat_payload( + message = f"Drawing: {message}", + mode_id = mode_id, + file_attachments = [], + request_overrides = {"imageGenerationCount": 2}, + ) + headers = build_http_headers(token, lease=lease) + kwargs = build_session_kwargs(lease=lease) + + async with ResettableSession(**kwargs) as session: + response = await session.post( + CHAT, + headers = headers, + data = orjson.dumps(payload), + timeout = timeout_s, + stream = True, + ) + if response.status_code != 200: + body = response.content.decode("utf-8", "replace")[:300] + raise UpstreamError( + f"Image-generation upstream returned {response.status_code}", + status = response.status_code, + body = body, + ) + async for line in response.aiter_lines(): + yield line + + +async def _run_lite_request( + *, + spec: ModelSpec, + prompt: str, + timeout_s: float, + response_format: str, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _ImageOutput: + from app.dataplane.account import _directory as _acct_dir + + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + acct = await _acct_dir.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for image generation") + + token = acct.token + adapter = StreamAdapter() + success = False + try: + async for line in _stream_lite_generate( + token, + prompt, + spec.mode_id, + timeout_s=timeout_s, + ): + ev_type, data = classify_line(line) + if ev_type == "done": + break + if ev_type != "data" or not data: + continue + for ev in adapter.feed(data): + if ev.kind == "image_progress": + if progress_cb is not None: + try: + await progress_cb(_clamp_progress(int(ev.content or "0"))) + except ValueError: + pass + if ev.kind == "image" and ev.content: + if progress_cb is not None: + await progress_cb(100) + image = await _resolve_image_output( + token=token, + url=ev.content, + response_format=response_format, + ) + success = True + return image + raise UpstreamError("Image generation returned no images") + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + +async def _run_lite_batch( + *, + spec: ModelSpec, + prompt: str, + n: int, + timeout_s: float, + response_format: str, + progress_cb: Callable[[int, int], Awaitable[None]] | None = None, +) -> list[_ImageOutput]: + results: list[_ImageOutput | None] = [None] * n + + async def _runner(idx: int) -> None: + results[idx] = await _run_lite_request( + spec=spec, + prompt=prompt, + timeout_s=timeout_s, + response_format=response_format, + progress_cb=None if progress_cb is None else lambda progress: progress_cb(idx, progress), + ) + + async with asyncio.TaskGroup() as tg: + for idx in range(n): + tg.create_task(_runner(idx), name=f"lite-image-{idx}") + + return [result for result in results if result is not None] + + +async def edit( + *, + model: str, + messages: list[dict], + n: int = 1, + size: str = "1024x1024", + response_format: str = "url", + stream: bool = False, + chat_format: bool = False, +) -> dict | AsyncGenerator[str, None]: + """Edit images via media/post/create + imagine-image-edit chat payload.""" + cfg = get_config() + spec = resolve_model(model) + timeout_s = cfg.get_float("chat.timeout", 120.0) + if not (1 <= n <= _EDIT_MAX_N): + raise ValidationError("image edit n must be between 1 and 2", param="n") + _normalize_edit_size(size) + + prompt, image_inputs = _extract_edit_prompt_and_inputs(messages) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + acct = await _acct_dir.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for image edit") + + token = acct.token + response_id = make_response_id() + + try: + image_references = await _prepare_edit_references(token, image_inputs) + if not image_references: + raise UpstreamError("All image uploads failed; cannot proceed with image edit") + + post = await create_media_post( + token, + media_type=IMAGE_POST_MEDIA_TYPE, + prompt=prompt, + ) + post_data = post.get("post") + if not isinstance(post_data, dict): + raise UpstreamError("Image edit create-post returned no post payload") + parent_post_id = str(post_data.get("id") or "").strip() + if not parent_post_id: + raise UpstreamError("Image edit create-post returned no post id") + except Exception: + await _acct_dir.release(acct) + raise + + if stream: + async def _sse_stream() -> AsyncGenerator[str, None]: + success = False + progress_map: dict[int, int] = {} + last_progress = -1 + queue: asyncio.Queue[tuple[int, int]] = asyncio.Queue() + try: + async def _progress(index: int, progress: int) -> None: + progress_map[index] = _clamp_progress(progress) + await queue.put(( + _compute_progress_percent(progress_map, n), + _completed_items(progress_map), + )) + + task = asyncio.create_task( + _collect_edit_images( + token=token, + prompt=prompt, + image_references=image_references, + parent_post_id=parent_post_id, + requested_n=n, + response_format=response_format, + timeout_s=timeout_s, + progress_cb=_progress, + ) + ) + while not task.done() or not queue.empty(): + try: + aggregate, completed = await asyncio.wait_for(queue.get(), timeout=0.1) + except asyncio.TimeoutError: + continue + if chat_format and aggregate > last_progress: + last_progress = aggregate + chunk = make_thinking_chunk( + response_id, + model, + _progress_reason("图片", aggregate, completed=completed, total=n), + ) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + images = await task + for image in images: + content = _output_content(image, chat_format=chat_format) + chunk = make_stream_chunk(response_id, model, content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" + success = True + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + return _sse_stream() + + success = False + reasoning_updates: list[str] = [] + progress_map: dict[int, int] = {} + try: + async def _progress(index: int, progress: int) -> None: + progress_map[index] = _clamp_progress(progress) + if chat_format: + _append_reason_update( + reasoning_updates, + "图片", + _compute_progress_percent(progress_map, n), + completed=_completed_items(progress_map), + total=n, + ) + + images = await _collect_edit_images( + token=token, + prompt=prompt, + image_references=image_references, + parent_post_id=parent_post_id, + requested_n=n, + response_format=response_format, + timeout_s=timeout_s, + progress_cb=_progress, + ) + success = True + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + if chat_format: + content = "\n\n".join(image.markdown_value for image in images) + reasoning = "\n".join(reasoning_updates) if reasoning_updates else None + return make_chat_response( + model, + content, + response_id=response_id, + reasoning_content=reasoning, + ) + + data_list = [ + {"b64_json": image.api_value} + if _normalize_response_format(response_format) == "b64_json" + else {"url": image.api_value} + for image in images + ] + return {"created": int(time.time()), "data": data_list} + + +__all__ = ["generate", "edit", "resolve_aspect_ratio"] diff --git a/app/products/openai/response.py b/app/products/openai/response.py deleted file mode 100644 index c6d900a7..00000000 --- a/app/products/openai/response.py +++ /dev/null @@ -1,112 +0,0 @@ -"""OpenAI-compatible response formatting utilities.""" - -from __future__ import annotations - -import math -import os -import re -import time -from typing import Any - -import orjson - -_SEGMENT_RE = re.compile(r"\w+|[^\w\s]", re.UNICODE) -_PROMPT_OVERHEAD = 4 - - -def make_response_id() -> str: - return f"chatcmpl-{int(time.time() * 1000)}{os.urandom(4).hex()}" - - -def estimate_tokens(value: Any) -> int: - """Lightweight token count estimate (UTF-8 bytes / 4, min 1 if non-empty).""" - if value is None: - return 0 - if not isinstance(value, str): - try: - value = orjson.dumps(value).decode() - except Exception: - value = str(value) - text = value.strip() - if not text: - return 0 - byte_est = math.ceil(len(text.encode()) / 4) - segment_est = math.ceil(len(_SEGMENT_RE.findall(text)) * 0.75) - return max(1, byte_est, segment_est) - - -def build_usage(prompt_tokens: int, completion_tokens: int) -> dict: - pt = max(0, prompt_tokens) - ct = max(0, completion_tokens) - return { - "prompt_tokens": pt, - "completion_tokens": ct, - "total_tokens": pt + ct, - "prompt_tokens_details": { - "cached_tokens": 0, "text_tokens": pt, - "audio_tokens": 0, "image_tokens": 0, - }, - "completion_tokens_details": { - "text_tokens": ct, "audio_tokens": 0, "reasoning_tokens": 0, - }, - } - - -def make_stream_chunk( - response_id: str, - model: str, - content: str, - *, - index: int = 0, - role: str = "assistant", - is_final: bool = False, - finish_reason: str | None = None, - usage: dict | None = None, -) -> dict: - choice: dict = { - "index": index, - "delta": {"role": role, "content": content}, - } - if is_final: - choice["finish_reason"] = finish_reason or "stop" - - chunk: dict = { - "id": response_id, - "object": "chat.completion.chunk", - "created": int(time.time()), - "model": model, - "choices": [choice], - } - if usage is not None: - chunk["usage"] = usage - return chunk - - -def make_chat_response( - model: str, - content: str, - *, - response_id: str | None = None, - usage: dict | None = None, -) -> dict: - rid = response_id or make_response_id() - pt = estimate_tokens(content) + _PROMPT_OVERHEAD - ct = estimate_tokens(content) - return { - "id": rid, - "object": "chat.completion", - "created": int(time.time()), - "model": model, - "choices": [{ - "index": 0, - "message": {"role": "assistant", "content": content}, - "finish_reason": "stop", - }], - "usage": usage or build_usage(pt, ct), - } - - -__all__ = [ - "make_response_id", "estimate_tokens", "build_usage", - "make_stream_chunk", "make_chat_response", -] diff --git a/app/products/openai/responses.py b/app/products/openai/responses.py new file mode 100644 index 00000000..89eb42dc --- /dev/null +++ b/app/products/openai/responses.py @@ -0,0 +1,466 @@ +"""OpenAI Responses API handler (/v1/responses). + +Unsupported request fields are silently discarded. +Streaming emits standard Responses API SSE events. +""" + +import asyncio +from typing import Any, AsyncGenerator + +import orjson + +from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import RateLimitError, UpstreamError +from app.platform.runtime.clock import now_s +from app.control.model.registry import resolve as resolve_model +from app.control.account.enums import FeedbackKind +from app.dataplane.reverse.protocol.xai_chat import classify_line, StreamAdapter + +from .chat import _stream_chat, _extract_message, _resolve_image, _quota_sync, _fail_sync, _parse_retry_codes, _feedback_kind +from ._format import ( + estimate_tokens, + make_resp_id, build_resp_usage, make_resp_object, format_sse, +) + + +# --------------------------------------------------------------------------- +# Input normalisation +# --------------------------------------------------------------------------- + +def _parse_input(input_val: str | list) -> list[dict]: + """Convert Responses API input to our internal messages list.""" + if isinstance(input_val, str): + return [{"role": "user", "content": input_val}] + + messages: list[dict] = [] + for item in input_val: + if not isinstance(item, dict): + continue + item_type = item.get("type", "message" if "role" in item else None) + if item_type != "message": + continue # skip reasoning items, function_call_output, etc. + + role = item.get("role", "user") + content = item.get("content", "") + + if isinstance(content, list): + normalized: list[dict] = [] + for part in content: + if not isinstance(part, dict): + continue + ptype = part.get("type", "") + if ptype in ("input_text", "output_text"): + normalized.append({"type": "text", "text": part.get("text", "")}) + elif ptype == "image": + src = part.get("image_url") or part.get("source") or {} + url = src.get("url", "") + if url: + normalized.append({"type": "image_url", "image_url": {"url": url}}) + else: + normalized.append(part) + content = normalized + + messages.append({"role": role, "content": content}) + return messages + + +# --------------------------------------------------------------------------- +# Main handler +# --------------------------------------------------------------------------- + +async def create( + *, + model: str, + input_val: str | list, + instructions: str | None, + stream: bool, + emit_think: bool, + temperature: float, + top_p: float, +) -> dict | AsyncGenerator[str, None]: + + cfg = get_config() + spec = resolve_model(model) + + messages: list[dict] = [] + if instructions: + messages.append({"role": "system", "content": instructions}) + messages.extend(_parse_input(input_val)) + + message, files = _extract_message(messages) + if not message.strip(): + raise UpstreamError("Empty message after extraction", status=400) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + directory = _acct_dir + + max_retries = cfg.get_int("retry.max_retries", 1) + retry_codes = _parse_retry_codes(cfg.get_str("retry.on_codes", "429,503")) + response_id = make_resp_id("resp") + reasoning_id = make_resp_id("rs") + message_id = make_resp_id("msg") + timeout_s = cfg.get_float("chat.timeout", 120.0) + + # ------------------------------------------------------------------------- + # Streaming + # ------------------------------------------------------------------------- + async def _run_stream() -> AsyncGenerator[str, None]: + excluded: list[str] = [] + for attempt in range(max_retries + 1): + acct = await directory.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + exclude_tokens = excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + think_buf: list[str] = [] + text_buf: list[str] = [] + reasoning_started = False + reasoning_closed = False + message_started = False + + try: + try: + yield format_sse("response.created", { + "type": "response.created", + "response": make_resp_object(response_id, model, "in_progress", []), + }) + + ended = False + async for line in _stream_chat( + token = token, + mode_id = spec.mode_id, + message = message, + files = files, + timeout_s = timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + + for ev in adapter.feed(data): + + if ev.kind == "thinking" and emit_think and not reasoning_closed: + if not reasoning_started: + reasoning_started = True + yield format_sse("response.output_item.added", { + "type": "response.output_item.added", + "output_index": 0, + "item": { + "id": reasoning_id, "type": "reasoning", + "summary": [], "status": "in_progress", + }, + }) + yield format_sse("response.reasoning_summary_part.added", { + "type": "response.reasoning_summary_part.added", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "part": {"type": "summary_text", "text": ""}, + }) + think_buf.append(ev.content) + yield format_sse("response.reasoning_summary_text.delta", { + "type": "response.reasoning_summary_text.delta", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "delta": ev.content, + }) + + elif ev.kind == "text": + if reasoning_started and not reasoning_closed: + reasoning_closed = True + full_think = "".join(think_buf) + yield format_sse("response.reasoning_summary_text.done", { + "type": "response.reasoning_summary_text.done", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "text": full_think, + }) + yield format_sse("response.reasoning_summary_part.done", { + "type": "response.reasoning_summary_part.done", + "item_id": reasoning_id, + "output_index": 0, + "summary_index": 0, + "part": {"type": "summary_text", "text": full_think}, + }) + yield format_sse("response.output_item.done", { + "type": "response.output_item.done", + "output_index": 0, + "item": { + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }, + }) + + msg_idx = 1 if reasoning_started else 0 + if not message_started: + message_started = True + yield format_sse("response.output_item.added", { + "type": "response.output_item.added", + "output_index": msg_idx, + "item": { + "id": message_id, "type": "message", + "role": "assistant", "content": [], "status": "in_progress", + }, + }) + yield format_sse("response.content_part.added", { + "type": "response.content_part.added", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "part": {"type": "output_text", "text": "", "annotations": []}, + }) + + text_buf.append(ev.content) + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "delta": ev.content, + }) + + elif ev.kind == "soft_stop": + ended = True + break + + if ended: + break + + # Images + msg_idx = 1 if reasoning_started else 0 + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + img_md = img_text + "\n" + text_buf.append(img_md) + if message_started: + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "delta": img_md, + }) + + references = adapter.references_suffix() + if references: + text_buf.append(references) + if message_started: + yield format_sse("response.output_text.delta", { + "type": "response.output_text.delta", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "delta": references, + }) + + full_text = "".join(text_buf) + if message_started: + yield format_sse("response.output_text.done", { + "type": "response.output_text.done", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "text": full_text, + }) + yield format_sse("response.content_part.done", { + "type": "response.content_part.done", + "item_id": message_id, + "output_index": msg_idx, + "content_index": 0, + "part": {"type": "output_text", "text": full_text, "annotations": []}, + }) + yield format_sse("response.output_item.done", { + "type": "response.output_item.done", + "output_index": msg_idx, + "item": { + "id": message_id, + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": full_text, "annotations": []}], + "status": "completed", + }, + }) + + full_think = "".join(think_buf) + output: list[dict] = [] + if reasoning_started and full_think: + output.append({ + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }) + output.append({ + "id": message_id, + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": full_text, "annotations": []}], + "status": "completed", + }) + + pt = estimate_tokens(message) + 4 + ct = estimate_tokens(full_text) + rt = estimate_tokens(full_think) if full_think else 0 + yield format_sse("response.completed", { + "type": "response.completed", + "response": make_resp_object( + response_id, model, "completed", output, + build_resp_usage(pt, ct + rt, rt), + ), + }) + yield "data: [DONE]\n\n" + success = True + logger.info("Responses stream done (attempt {}/{}): model={} text_len={} think_len={} images={}", + attempt + 1, max_retries + 1, model, + len(full_text), len(full_think), len(adapter.image_urls)) + + except UpstreamError as exc: + fail_exc = exc + if exc.status in retry_codes and attempt < max_retries: + _retry = True + logger.warning("Responses stream retry {}/{}: status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8]) + else: + raise + + finally: + await directory.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await directory.feedback(token, kind, int(spec.mode_id), now_s_val=now_s()) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + if success or not _retry: + return + excluded.append(token) + + if stream: + return _run_stream() + + # ------------------------------------------------------------------------- + # Non-streaming + # ------------------------------------------------------------------------- + excluded: list[str] = [] + adapter = StreamAdapter() + for attempt in range(max_retries + 1): + acct = await directory.reserve( + pool_candidates = spec.pool_candidates(), + mode_id = int(spec.mode_id), + now_s_override = now_s(), + exclude_tokens = excluded or None, + ) + if acct is None: + raise RateLimitError("No available accounts for this model tier") + + token = acct.token + success = False + _retry = False + fail_exc: BaseException | None = None + adapter = StreamAdapter() + + try: + try: + async for line in _stream_chat( + token = token, + mode_id = spec.mode_id, + message = message, + files = files, + timeout_s = timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": + break + if event_type != "data" or not data: + continue + ended = False + for ev in adapter.feed(data): + if ev.kind == "soft_stop": + ended = True + break + if ended: + break + success = True + + except UpstreamError as exc: + fail_exc = exc + if exc.status in retry_codes and attempt < max_retries: + _retry = True + logger.warning("Responses retry {}/{}: status={} token={}...", + attempt + 1, max_retries, exc.status, token[:8]) + else: + raise + + finally: + await directory.release(acct) + kind = FeedbackKind.SUCCESS if success else _feedback_kind(fail_exc) if fail_exc else FeedbackKind.SERVER_ERROR + await directory.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + if success or not _retry: + break + excluded.append(token) + + full_text = "".join(adapter.text_buf) + for url, img_id in adapter.image_urls: + img_text = await _resolve_image(token, url, img_id) + if full_text: + full_text += "\n\n" + full_text += img_text + references = adapter.references_suffix() + if references: + full_text += references + + full_think = ("".join(adapter.thinking_buf) or "") if emit_think else "" + + logger.info("Responses non-stream done: model={} text_len={} think_len={} images={}", + model, len(full_text), len(full_think), len(adapter.image_urls)) + + output: list[dict] = [] + if full_think: + output.append({ + "id": reasoning_id, + "type": "reasoning", + "summary": [{"type": "summary_text", "text": full_think}], + "status": "completed", + }) + output.append({ + "id": message_id, + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": full_text, "annotations": []}], + "status": "completed", + }) + + pt = estimate_tokens(message) + 4 + ct = estimate_tokens(full_text) + rt = estimate_tokens(full_think) if full_think else 0 + return make_resp_object( + response_id, model, "completed", output, + build_resp_usage(pt, ct + rt, rt), + ) + + +__all__ = ["create"] diff --git a/app/products/openai/router.py b/app/products/openai/router.py index 0a8691bf..408c1647 100644 --- a/app/products/openai/router.py +++ b/app/products/openai/router.py @@ -1,20 +1,26 @@ """OpenAI-compatible API router (/v1/*).""" -from __future__ import annotations - -from typing import AsyncGenerator, AsyncIterable +import base64 +import binascii +import mimetypes +from typing import Annotated, AsyncGenerator, AsyncIterable, Literal import orjson -from fastapi import APIRouter, Depends -from fastapi.responses import JSONResponse, StreamingResponse +from fastapi import APIRouter, Depends, File, Form, Query, UploadFile +from fastapi.responses import JSONResponse, StreamingResponse, FileResponse from app.platform.auth.middleware import verify_api_key from app.platform.errors import AppError, ValidationError -from app.control.model.registry import list_enabled, resolve as resolve_model, get as get_model -from app.control.model.enums import Capability -from .dto import ChatCompletionRequest, ImageGenerationRequest, ImageEditRequest, VideoConfig, ImageConfig +from app.platform.storage import image_files_dir, video_files_dir +from app.control.model import registry as model_registry +from .schemas import ( + ChatCompletionRequest, + ImageGenerationRequest, + VideoConfig, + ImageConfig, + ResponsesCreateRequest, +) from .chat import completions as chat_completions -from .response import make_chat_response router = APIRouter(prefix="/v1", dependencies=[Depends(verify_api_key)]) @@ -34,16 +40,15 @@ async def list_models(): "owned_by": "xai", "name": m.public_name, } - for m in list_enabled() + for m in model_registry.list_enabled() ] return JSONResponse({"object": "list", "data": models}) @router.get("/models/{model_id}") -async def get_model(model_id: str): +async def get_model_endpoint(model_id: str): import time - from app.control.model.registry import get - spec = get(model_id) + spec = model_registry.get(model_id) if spec is None or not spec.enabled: return JSONResponse( {"error": {"message": f"Model {model_id!r} not found", "type": "invalid_request_error"}}, @@ -88,11 +93,12 @@ _VALID_ROLES = {"developer", "system", "user", "assistant", "tool"} _USER_BLOCK_TYPES = {"text", "image_url", "input_audio", "file"} _ALLOWED_SIZES = {"1280x720", "720x1280", "1792x1024", "1024x1792", "1024x1024"} _EFFORT_VALUES = {"none", "minimal", "low", "medium", "high", "xhigh"} +_LITE_IMAGE_MODELS = {"grok-imagine-image-lite"} def _validate_chat(req: ChatCompletionRequest) -> None: from app.platform.errors import ValidationError - spec = resolve_model(req.model) + spec = model_registry.resolve(req.model) if spec is None or not spec.enabled: raise ValidationError( f"Model {req.model!r} does not exist or you do not have access to it.", @@ -117,18 +123,53 @@ def _validate_chat(req: ChatCompletionRequest) -> None: ) +def _validate_image_n(model_name: str, n: int, *, param: str) -> None: + max_n = 4 if model_name in _LITE_IMAGE_MODELS else 10 + if not (1 <= n <= max_n): + raise ValidationError( + f"n must be between 1 and {max_n} for model {model_name!r}", + param=param, + ) + + +def _validate_image_edit_n(n: int, *, param: str) -> None: + if not (1 <= n <= 2): + raise ValidationError("n must be between 1 and 2 for image edit", param=param) + + +async def _upload_to_data_uri(upload: UploadFile, *, param: str) -> str: + raw = await upload.read() + if not raw: + raise ValidationError("Uploaded image cannot be empty", param=param) + + mime = ( + (upload.content_type or "").strip().lower() + or mimetypes.guess_type(upload.filename or "")[0] + or "application/octet-stream" + ) + if not mime.startswith("image/"): + raise ValidationError("Uploaded file must be an image", param=param) + + try: + blob_b64 = base64.b64encode(raw).decode("ascii") + except (ValueError, TypeError, binascii.Error) as exc: + raise ValidationError("Failed to encode uploaded image", param=param) from exc + return f"data:{mime};base64,{blob_b64}" + + @router.post("/chat/completions") async def chat_completions_endpoint(req: ChatCompletionRequest): _validate_chat(req) - spec = resolve_model(req.model) + spec = model_registry.resolve(req.model) messages = [m.model_dump(exclude_none=True) for m in req.messages] try: # Dispatch by model capability. if spec.is_image_edit(): - from .image_edit import edit as img_edit + from .images import edit as img_edit cfg = req.image_config or ImageConfig() + _validate_image_edit_n(cfg.n or 1, param="image_config.n") result = await img_edit( model = req.model, messages = messages, @@ -140,11 +181,12 @@ async def chat_completions_endpoint(req: ChatCompletionRequest): ) elif spec.is_image(): - from .image import generate as img_gen, resolve_aspect_ratio + from .images import generate as img_gen cfg = req.image_config or ImageConfig() size = cfg.size or "1024x1024" fmt = cfg.response_format or "url" n = cfg.n or 1 + _validate_image_n(req.model, n, param="image_config.n") # Extract prompt from last user message. prompt = next( (m.content for m in reversed(req.messages) @@ -164,14 +206,16 @@ async def chat_completions_endpoint(req: ChatCompletionRequest): elif spec.is_video(): from .video import completions as vid_comp vcfg = req.video_config or VideoConfig() + from .video import validate_video_length as _validate_video_length + _validate_video_length(vcfg.seconds or 6) result = await vid_comp( - model = req.model, - messages = messages, - stream = req.stream, - aspect_ratio = vcfg.aspect_ratio or "3:2", - video_length = vcfg.video_length or 6, - resolution = vcfg.resolution_name or "480p", - preset = vcfg.preset or "custom", + model = req.model, + messages = messages, + stream = req.stream, + seconds = vcfg.seconds or 6, + size = vcfg.size or "720x1280", + resolution_name = vcfg.resolution_name, + preset = vcfg.preset, ) else: @@ -179,6 +223,7 @@ async def chat_completions_endpoint(req: ChatCompletionRequest): model = req.model, messages = messages, stream = req.stream, + thinking = req.thinking, tools = req.tools, tool_choice = req.tool_choice, temperature = req.temperature or 0.8, @@ -189,8 +234,9 @@ async def chat_completions_endpoint(req: ChatCompletionRequest): raise except Exception as exc: if req.stream is not False: + _err_msg = str(exc) # capture before Python clears the except-scope variable async def _err_stream(): - payload = orjson.dumps({"error": {"message": str(exc), "type": "server_error"}}).decode() + payload = orjson.dumps({"error": {"message": _err_msg, "type": "server_error"}}).decode() yield f"event: error\ndata: {payload}\n\n" yield "data: [DONE]\n\n" return StreamingResponse(_err_stream(), media_type="text/event-stream", headers=_SSE_HEADERS) @@ -201,17 +247,84 @@ async def chat_completions_endpoint(req: ChatCompletionRequest): return StreamingResponse(_safe_sse(result), media_type="text/event-stream", headers=_SSE_HEADERS) +# --------------------------------------------------------------------------- +# /v1/responses (OpenAI Responses API) +# --------------------------------------------------------------------------- + +async def _safe_sse_responses(stream) -> AsyncGenerator[str, None]: + """SSE wrapper that converts errors to Responses API error events.""" + try: + async for chunk in stream: + yield chunk + except Exception as exc: + from app.platform.errors import AppError + if isinstance(exc, AppError): + err = exc.to_dict()["error"] + else: + err = {"message": str(exc), "type": "server_error", "code": None, "param": None} + payload = orjson.dumps({"type": "error", **err}).decode() + yield f"event: error\ndata: {payload}\n\n" + yield "data: [DONE]\n\n" + + +@router.post("/responses") +async def responses_endpoint(req: ResponsesCreateRequest): + from app.platform.config.snapshot import get_config + from app.platform.errors import ValidationError as _ValidationError + + spec = model_registry.resolve(req.model) + if spec is None or not spec.enabled: + raise _ValidationError( + f"Model {req.model!r} does not exist or you do not have access to it.", + param="model", code="model_not_found", + ) + if not req.input: + raise _ValidationError("input cannot be empty", param="input") + + cfg = get_config() + is_stream = req.stream if req.stream is not None else cfg.get_bool("features.stream", True) + + # Map reasoning param → emit_think flag. + # reasoning=None → use config; reasoning.effort="none" → off; otherwise on. + if req.reasoning is None: + emit_think = cfg.get_bool("features.thinking", True) + elif isinstance(req.reasoning, dict) and req.reasoning.get("effort") == "none": + emit_think = False + else: + emit_think = True + + from .responses import create as responses_create + result = await responses_create( + model = req.model, + input_val = req.input, + instructions = req.instructions, + stream = is_stream, + emit_think = emit_think, + temperature = req.temperature or 0.8, + top_p = req.top_p or 0.95, + ) + + if isinstance(result, dict): + return JSONResponse(result) + return StreamingResponse( + _safe_sse_responses(result), + media_type = "text/event-stream", + headers = _SSE_HEADERS, + ) + + # --------------------------------------------------------------------------- # /v1/images/generations (standalone image endpoint) # --------------------------------------------------------------------------- @router.post("/images/generations") async def image_generations(req: ImageGenerationRequest): - spec = get_model(req.model) + spec = model_registry.get(req.model) if spec is None or not spec.enabled or not spec.is_image(): raise ValidationError(f"Model {req.model!r} is not an image model", param="model") + _validate_image_n(req.model, req.n or 1, param="n") - from .image import generate as img_gen + from .images import generate as img_gen result = await img_gen( model = req.model, prompt = req.prompt, @@ -224,32 +337,133 @@ async def image_generations(req: ImageGenerationRequest): return JSONResponse(result) +# --------------------------------------------------------------------------- +# /v1/videos (OpenAI videos.create surface) +# --------------------------------------------------------------------------- + +@router.post("/videos") +async def videos_create( + model: Annotated[str, Form(...)], + prompt: Annotated[str, Form(...)], + seconds: Annotated[int, Form()] = 6, + size: Annotated[Literal["720x1280", "1280x720", "1024x1024", "1024x1792", "1792x1024"], Form()] = "720x1280", + resolution_name: Annotated[Literal["480p", "720p"] | None, Form()] = None, + preset: Annotated[Literal["fun", "normal", "spicy", "custom"] | None, Form()] = None, + input_reference: Annotated[UploadFile | None, File()] = None, +): + from .video import create_video + + reference_payload = None + if input_reference is not None: + reference_payload = { + "image_url": await _upload_to_data_uri(input_reference, param="input_reference"), + } + + result = await create_video( + model=model or "grok-video", + prompt=prompt, + seconds=seconds, + size=size or "720x1280", + resolution_name=resolution_name, + preset=preset, + input_reference=reference_payload, + ) + return JSONResponse(result) + + +@router.get("/videos/{video_id}") +async def videos_retrieve(video_id: str): + from .video import retrieve + return JSONResponse(await retrieve(video_id)) + + +@router.get("/videos/{video_id}/content") +async def videos_content(video_id: str): + from .video import content_path + path = await content_path(video_id) + return FileResponse(path, media_type="video/mp4", filename=f"{video_id}.mp4") + + # --------------------------------------------------------------------------- # /v1/images/edits (standalone image-edit endpoint) # --------------------------------------------------------------------------- @router.post("/images/edits") -async def image_edits(req: ImageEditRequest): - spec = get_model(req.model) +async def image_edits( + model: Annotated[str, Form(...)], + prompt: Annotated[str, Form(...)], + image: Annotated[list[UploadFile], File(..., alias="image[]")], + mask: Annotated[UploadFile | None, File()] = None, + n: Annotated[int, Form()] = 1, + size: Annotated[str, Form()] = "1024x1024", + response_format: Annotated[str, Form()] = "url", +): + spec = model_registry.get(model) if spec is None or not spec.enabled or not spec.is_image_edit(): - raise ValidationError(f"Model {req.model!r} is not an image-edit model", param="model") + raise ValidationError(f"Model {model!r} is not an image-edit model", param="model") + if mask is not None: + raise ValidationError("mask is not supported yet", param="mask") + _validate_image_edit_n(n, param="n") - from .image_edit import edit as img_edit + from .images import edit as img_edit + image_inputs = [ + await _upload_to_data_uri(item, param=f"image.{index}") + for index, item in enumerate(image) + ] # Wrap input into a single-message conversation. - messages = [{"role": "user", "content": [ - {"type": "text", "text": req.prompt}, - {"type": "image_url", "image_url": {"url": req.image}}, - ]}] + content = [{"type": "text", "text": prompt}] + content.extend( + {"type": "image_url", "image_url": {"url": image_input}} + for image_input in image_inputs + ) + messages = [{"role": "user", "content": content}] result = await img_edit( - model = req.model, + model = model, messages = messages, - n = req.n or 1, - size = req.size or "1024x1024", - response_format = req.response_format or "url", + n = n, + size = size, + response_format = response_format, stream = False, chat_format = False, ) return JSONResponse(result) +# --------------------------------------------------------------------------- +# /v1/files/image — serve locally saved images +# --------------------------------------------------------------------------- + +@router.get("/files/video") +async def serve_video(id: str = Query(..., description="Video file ID")): + """Serve a locally cached video by file ID.""" + import re + + if not re.fullmatch(r"[0-9a-f\-]{16,36}", id): + raise ValidationError("Invalid file ID", param="id") + + path = video_files_dir() / f"{id}.mp4" + if path.exists(): + return FileResponse(path, media_type="video/mp4") + + raise ValidationError(f"Video {id!r} not found", param="id") + + +@router.get("/files/image") +async def serve_image(id: str = Query(..., description="Image file ID")): + """Serve a locally cached image by file ID.""" + import re + + if not re.fullmatch(r"[0-9a-f\-]{16,36}", id): + raise ValidationError("Invalid file ID", param="id") + + img_dir = image_files_dir() + for ext in (".jpg", ".png"): + path = img_dir / f"{id}{ext}" + if path.exists(): + mime = "image/png" if ext == ".png" else "image/jpeg" + return FileResponse(path, media_type=mime) + + raise ValidationError(f"Image {id!r} not found", param="id") + + __all__ = ["router"] diff --git a/app/products/openai/schemas.py b/app/products/openai/schemas.py new file mode 100644 index 00000000..9c5cfeb5 --- /dev/null +++ b/app/products/openai/schemas.py @@ -0,0 +1,96 @@ +"""OpenAI-compatible request schemas (Pydantic models).""" + +from typing import Any, Literal + +from pydantic import BaseModel, Field + + +class MessageItem(BaseModel): + role: str + content: str | list[dict[str, Any]] | None = None + tool_calls: list[dict[str, Any]] | None = None + tool_call_id: str | None = None + name: str | None = None + + +class ImageConfig(BaseModel): + n: int | None = Field(1, ge=1, le=10) + size: str | None = "1024x1024" + response_format: str | None = None + + +class VideoConfig(BaseModel): + seconds: int | None = 6 + size: Literal["720x1280", "1280x720", "1024x1024", "1024x1792", "1792x1024"] | None = "720x1280" + resolution_name: Literal["480p", "720p"] | None = None + preset: Literal["fun", "normal", "spicy", "custom"] | None = None + + +class ChatCompletionRequest(BaseModel): + model: str + messages: list[MessageItem] + stream: bool | None = None + thinking: bool | None = None + reasoning_effort: str | None = None + temperature: float | None = 0.8 + top_p: float | None = 0.95 + image_config: ImageConfig | None = None + video_config: VideoConfig | None = None + tools: list[dict[str, Any]] | None = None + tool_choice: str | dict[str, Any] | None = None + parallel_tool_calls: bool | None = True + max_tokens: int | None = None + + +class ImageGenerationRequest(BaseModel): + model: str + prompt: str + n: int | None = Field(1, ge=1, le=10) + size: str | None = "1024x1024" + response_format: str | None = "url" + + +class ImageEditRequest(BaseModel): + model: str + prompt: str + image: str | list[str] + mask: str | None = None + n: int | None = Field(1, ge=1, le=2) + size: str | None = "1024x1024" + response_format: str | None = "url" + + +class ResponsesCreateRequest(BaseModel): + """OpenAI Responses API — /v1/responses. + + Only model/input/instructions/stream/reasoning/temperature/top_p are acted on. + All other fields are accepted and silently discarded. + """ + model: str + input: str | list[Any] + instructions: str | None = None + stream: bool | None = None + reasoning: dict[str, Any] | None = None + temperature: float | None = None + top_p: float | None = None + # silently ignored + max_output_tokens: int | None = None + tools: list[Any] | None = None + tool_choice: Any | None = None + previous_response_id: str | None = None + store: bool | None = None + metadata: dict[str, Any] | None = None + truncation: str | None = None + parallel_tool_calls: bool | None = None + include: list[str] | None = None + background: bool | None = None + + class Config: + extra = "ignore" + + +__all__ = [ + "MessageItem", "ImageConfig", "VideoConfig", + "ChatCompletionRequest", "ImageGenerationRequest", "ImageEditRequest", + "ResponsesCreateRequest", +] diff --git a/app/products/openai/video.py b/app/products/openai/video.py index 35609e57..a81cc542 100644 --- a/app/products/openai/video.py +++ b/app/products/openai/video.py @@ -1,240 +1,1012 @@ -"""Video generation service — app-chat SSE reverse with video config override.""" +"""Video generation service. -from __future__ import annotations +Supports: + - OpenAI-style async ``/v1/videos`` jobs + - ``/v1/chat/completions`` video output via the same core pipeline +""" -import math -import re +import asyncio +import hashlib +import html import time -from typing import Any, AsyncGenerator +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any, AsyncGenerator, Awaitable, Callable +from urllib.parse import urlparse import orjson -from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config -from app.platform.errors import RateLimitError, UpstreamError +from app.platform.errors import AppError, ErrorKind, RateLimitError, UpstreamError, ValidationError +from app.platform.logging.logger import logger from app.platform.runtime.clock import now_s -from app.control.model.registry import resolve as resolve_model -from app.control.model.enums import ModeId, Tier +from app.platform.storage import video_files_dir from app.control.account.enums import FeedbackKind -from app.dataplane.reverse.protocol.xai_chat import build_chat_payload, classify_line -from app.dataplane.reverse.runtime.endpoint_table import CHAT +from app.control.model import registry as model_registry +from app.control.model.registry import resolve as resolve_model +from app.dataplane.proxy import get_proxy_runtime from app.dataplane.proxy.adapters.headers import build_http_headers from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs -from app.dataplane.proxy import get_proxy_runtime -from .response import make_response_id, make_stream_chunk, make_chat_response, build_usage - -_POST_ID_RE = re.compile(r"/generated/([0-9a-fA-F-]{32,36})/") +from app.dataplane.reverse.protocol.xai_assets import resolve_asset_reference, resolve_download_url +from app.dataplane.reverse.protocol.xai_chat import classify_line +from app.dataplane.reverse.runtime.endpoint_table import CHAT +from app.dataplane.reverse.transport.asset_upload import ( + resolve_uploaded_asset_reference, + upload_from_input, +) +from app.dataplane.reverse.transport.assets import download_asset +from app.dataplane.reverse.transport.media import create_media_post +from ._format import ( + make_chat_response, + make_response_id, + make_stream_chunk, + make_thinking_chunk, +) +from .chat import _fail_sync, _quota_sync +_IMAGE_MEDIA_TYPE = "MEDIA_POST_TYPE_IMAGE" +_VIDEO_MEDIA_TYPE = "MEDIA_POST_TYPE_VIDEO" +_VIDEO_MODEL_NAME = "grok-3" +_VIDEO_QUALITY = "standard" +_VIDEO_OBJECT = "video" +_VIDEO_JOB_TTL_S = 3600 +_VIDEO_EXTENSION_REF_TYPE = "ORIGINAL_REF_TYPE_VIDEO_EXTENSION" +_SUPPORTED_VIDEO_LENGTHS = frozenset({6, 10, 12, 16, 20}) +_VIDEO_SIZE_MAP: dict[str, tuple[str, str]] = { + "720x1280": ("9:16", "720p"), + "1280x720": ("16:9", "720p"), + "1024x1024": ("1:1", "720p"), + "1024x1792": ("9:16", "720p"), + "1792x1024": ("16:9", "720p"), +} _PRESET_FLAGS = { - "fun": "--mode=extremely-crazy", + "fun": "--mode=extremely-crazy", "normal": "--mode=normal", - "spicy": "--mode=extremely-spicy-or-crazy", + "spicy": "--mode=extremely-spicy-or-crazy", "custom": "--mode=custom", } -def _build_message(prompt: str, preset: str) -> str: - flag = _PRESET_FLAGS.get(preset, "--mode=custom") - return f"{prompt} {flag}".strip() +@dataclass(slots=True) +class _VideoArtifact: + video_url: str + video_post_id: str + asset_id: str + thumbnail_url: str + remixed_from_video_id: str | None = None -def _build_video_model_config( - parent_post_id: str, +@dataclass(slots=True) +class _VideoReference: + content_url: str + post_id: str + + +@dataclass(slots=True) +class _VideoJob: + id: str + model: str + prompt: str + seconds: str + size: str + quality: str + created_at: int + status: str = "queued" + progress: int = 0 + completed_at: int | None = None + error: dict[str, Any] | None = None + remixed_from_video_id: str | None = None + video_url: str = "" + content_path: str = "" + + def to_dict(self) -> dict[str, Any]: + payload: dict[str, Any] = { + "id": self.id, + "object": _VIDEO_OBJECT, + "created_at": self.created_at, + "status": self.status, + "model": self.model, + "progress": self.progress, + "prompt": self.prompt, + "seconds": self.seconds, + "size": self.size, + "quality": self.quality, + } + if self.completed_at is not None: + payload["completed_at"] = self.completed_at + if self.error is not None: + payload["error"] = self.error + if self.remixed_from_video_id: + payload["remixed_from_video_id"] = self.remixed_from_video_id + return payload + + +_VIDEO_JOBS: dict[str, _VideoJob] = {} +_VIDEO_JOBS_LOCK = asyncio.Lock() + + +def _build_message(prompt: str, preset: str, *, reference_content_url: str | None = None) -> str: + message = f"{prompt} {_PRESET_FLAGS.get(preset, '--mode=custom')}".strip() + if reference_content_url: + return f"{reference_content_url} {message}" + return message + + +def _progress_reason(progress: int) -> str: + return f"视频正在生成 {max(0, min(100, int(progress)))}%" + + +def _coerce_seconds(value: str | int | None) -> int: + if value is None: + return 6 + if isinstance(value, int): + return value + text = str(value).strip() + if not text: + return 6 + try: + return int(text) + except ValueError as exc: + raise ValidationError("seconds must be an integer string", param="seconds") from exc + + +def validate_video_length(seconds: int) -> None: + if seconds not in _SUPPORTED_VIDEO_LENGTHS: + allowed = ", ".join(str(item) for item in sorted(_SUPPORTED_VIDEO_LENGTHS)) + raise ValidationError(f"seconds must be one of [{allowed}]", param="seconds") + + +def _resolve_video_size(size: str) -> tuple[str, str]: + normalized = (size or "720x1280").strip() + config = _VIDEO_SIZE_MAP.get(normalized) + if config is None: + allowed = ", ".join(_VIDEO_SIZE_MAP) + raise ValidationError(f"size must be one of [{allowed}]", param="size") + return config + + +def _resolve_video_resolution_name(value: str | None, *, default: str = "720p") -> str: + normalized = (value or default).strip().lower() + if normalized not in {"480p", "720p"}: + raise ValidationError("resolution_name must be one of [480p, 720p]", param="resolution_name") + return normalized + + +def _resolve_video_preset(value: str | None, *, default: str = "custom") -> str: + normalized = (value or default).strip().lower() + if normalized not in _PRESET_FLAGS: + allowed = ", ".join(sorted(_PRESET_FLAGS)) + raise ValidationError(f"preset must be one of [{allowed}]", param="preset") + return normalized + + +def _build_segment_lengths(seconds: int) -> list[int]: + if seconds == 6: + return [6] + if seconds == 10: + return [10] + if seconds == 12: + return [6, 6] + if seconds == 16: + return [10, 6] + if seconds == 20: + return [10, 10] + validate_video_length(seconds) + raise AssertionError("unreachable") + + +def _video_create_payload( *, - aspect_ratio: str, + prompt: str, + parent_post_id: str, + aspect_ratio: str, resolution_name: str, - video_length: int, + video_length: int, + preset: str, + reference_content_url: str | None = None, + file_attachments: list[str] | None = None, +) -> dict[str, Any]: + payload = { + "temporary": True, + "modelName": _VIDEO_MODEL_NAME, + "message": _build_message(prompt, preset, reference_content_url=reference_content_url), + "toolOverrides": {"videoGen": True}, + "enableSideBySide": True, + "responseMetadata": { + "experiments": [], + "modelConfigOverride": { + "modelMap": { + "videoGenModelConfig": { + "parentPostId": parent_post_id, + "aspectRatio": aspect_ratio, + "videoLength": video_length, + "resolutionName": resolution_name, + } + } + }, + }, + } + if file_attachments: + payload["fileAttachments"] = file_attachments + return payload + + +def _video_extend_start_time(seconds: int) -> float: + return round(seconds + (1.0 / 24.0), 6) + + +def _video_extend_payload( + *, + prompt: str, + parent_post_id: str, + extend_post_id: str, + aspect_ratio: str, + resolution_name: str, + video_length: int, + preset: str, + start_time_s: float, ) -> dict[str, Any]: return { - "modelMap": { - "videoGenModelConfig": { - "aspectRatio": aspect_ratio, - "parentPostId": parent_post_id, - "resolutionName": resolution_name, - "videoLength": video_length, - } - } + "temporary": True, + "modelName": _VIDEO_MODEL_NAME, + "message": _build_message(prompt, preset), + "toolOverrides": {"videoGen": True}, + "enableSideBySide": True, + "responseMetadata": { + "experiments": [], + "modelConfigOverride": { + "modelMap": { + "videoGenModelConfig": { + "isVideoExtension": True, + "videoExtensionStartTime": start_time_s, + "extendPostId": extend_post_id, + "stitchWithExtendPostId": True, + "originalPrompt": prompt, + "originalPostId": parent_post_id, + "originalRefType": _VIDEO_EXTENSION_REF_TYPE, + "mode": preset, + "aspectRatio": aspect_ratio, + "videoLength": video_length, + "resolutionName": resolution_name, + "parentPostId": parent_post_id, + "isVideoEdit": False, + } + } + }, + }, } -def _round_length(target: int, *, is_super: bool) -> int: - return 10 if is_super and target >= 10 else 6 +def _extract_streaming_video_response(data: dict[str, Any]) -> dict[str, Any] | None: + result = data.get("result") + if not isinstance(result, dict): + return None + response = result.get("response") + if not isinstance(response, dict): + return None + stream = response.get("streamingVideoGenerationResponse") + return stream if isinstance(stream, dict) else None -def _build_rounds(target: int, *, is_super: bool) -> list[int]: - """Return list of per-round video_length values.""" - base = _round_length(target, is_super=is_super) - extras = int(math.ceil(max(target - base, 0) / base)) - return [base] + [base] * extras +def _extract_model_response_file_attachments(data: dict[str, Any]) -> list[str]: + result = data.get("result") + if not isinstance(result, dict): + return [] + response = result.get("response") + if not isinstance(response, dict): + return [] + model_response = response.get("modelResponse") + if not isinstance(model_response, dict): + return [] + attachments = model_response.get("fileAttachments") + if not isinstance(attachments, list): + return [] + return [item for item in attachments if isinstance(item, str) and item] -async def _run_chat_stream( - token: str, - message: str, - grok_model: str, - grok_mode: str, - model_config_override: dict | None, +async def _stream_video_request( + token: str, + payload: dict[str, Any], *, + referer: str, timeout_s: float, ) -> AsyncGenerator[str, None]: proxy = await get_proxy_runtime() lease = await proxy.acquire() - - payload = build_chat_payload( - message = message, - model_name = grok_model, - model_mode = grok_mode, - model_config_override = model_config_override, + headers = build_http_headers( + token, + content_type="application/json", + origin="https://grok.com", + referer=referer, + lease=lease, ) - headers = build_http_headers(token, lease=lease) - kwargs = build_session_kwargs(lease=lease) + kwargs = build_session_kwargs(lease=lease) async with ResettableSession(**kwargs) as session: response = await session.post( - CHAT, headers=headers, data=orjson.dumps(payload), - timeout=timeout_s, stream=True, + CHAT, + headers=headers, + data=orjson.dumps(payload), + timeout=timeout_s, + stream=True, ) if response.status_code != 200: - body = (await response.aread()).decode("utf-8", "replace")[:300] - raise UpstreamError(f"Video upstream {response.status_code}", status=response.status_code, body=body) + body = response.content.decode("utf-8", "replace")[:300] + raise UpstreamError( + f"Video upstream returned {response.status_code}", + status=response.status_code, + body=body, + ) async for line in response.aiter_lines(): yield line -def _extract_video_url(data: str) -> str | None: - try: - obj = orjson.loads(data) - except Exception: - return None - result = obj.get("result") or {} - # Video URL appears in streamingState or message metadata. - video_url = ( - result.get("message", {}).get("videoUrl") - or result.get("streamingState", {}).get("videoUrl") - or result.get("videoUrl") +def _absolutize_video_url(url: str) -> str: + full_url, _, _ = resolve_download_url(url) + return full_url + + +def _is_upstream_asset_content_url(value: str) -> bool: + parsed = urlparse(value) + return ( + parsed.scheme == "https" + and parsed.netloc == "assets.grok.com" + and parsed.path.endswith("/content") ) - return video_url if isinstance(video_url, str) and video_url else None -def _extract_post_id(video_url: str) -> str: - m = _POST_ID_RE.search(video_url) - return m.group(1) if m else "" +async def _prepare_video_reference(token: str, input_reference: dict[str, Any]) -> _VideoReference: + file_id = str(input_reference.get("file_id") or "").strip() + image_input = str(input_reference.get("image_url") or "").strip() + + if file_id and image_input: + raise ValidationError("input_reference accepts only one of file_id or image_url", param="input_reference") + if file_id: + raise ValidationError("input_reference.file_id is not supported yet", param="input_reference.file_id") + if not image_input: + raise ValidationError("input_reference.image_url is required", param="input_reference.image_url") + + if _is_upstream_asset_content_url(image_input): + content_url = image_input + else: + try: + uploaded_file_id, uploaded_file_uri = await upload_from_input(token, image_input) + content_url = resolve_uploaded_asset_reference(token, uploaded_file_id, uploaded_file_uri) + except ValidationError as exc: + raise ValidationError(exc.message, param="input_reference.image_url") from exc + except UpstreamError as exc: + raise UpstreamError( + f"Video input reference upload failed: {exc.message}", + status=exc.status, + body=exc.details.get("body", ""), + ) from exc + except Exception as exc: + raise UpstreamError(f"Video input reference upload failed: {exc}") from exc + + post = await create_media_post( + token, + media_type=_IMAGE_MEDIA_TYPE, + media_url=content_url, + prompt="", + referer="https://grok.com/imagine", + ) + post_data = post.get("post") + if not isinstance(post_data, dict): + raise UpstreamError("Video image reference create-post returned no post payload") + post_id = str(post_data.get("id") or "").strip() + if not post_id: + raise UpstreamError("Video image reference create-post returned no post id") + return _VideoReference(content_url=content_url, post_id=post_id) -async def completions( +async def _collect_video_segment( *, - model: str, - messages: list[dict], - stream: bool | None = None, - aspect_ratio: str = "3:2", - video_length: int = 6, - resolution: str = "480p", - preset: str = "custom", -) -> dict | AsyncGenerator[str, None]: - """Entry point for video generation requests.""" - cfg = get_config() - spec = resolve_model(model) - is_stream = stream if stream is not None else cfg.get_bool("app.stream", False) - timeout_s = cfg.get_float("video.timeout", 180.0) - is_super = spec.tier == Tier.SUPER + token: str, + payload: dict[str, Any], + referer: str, + timeout_s: float, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _VideoArtifact: + final_url = "" + final_asset_id = "" + final_thumbnail = "" + video_post_id = "" - # Determine grok mode string. - _MODE_MAP = {ModeId.AUTO: "MODEL_MODE_AUTO", ModeId.FAST: "MODEL_MODE_FAST", ModeId.EXPERT: "MODEL_MODE_EXPERT"} - grok_mode = _MODE_MAP.get(spec.mode_id, "MODEL_MODE_AUTO") - - # Extract prompt from messages. - prompt = "" - for msg in reversed(messages): - content = msg.get("content", "") - if isinstance(content, str) and content.strip(): - prompt = content.strip() + async for line in _stream_video_request( + token, + payload, + referer=referer, + timeout_s=timeout_s, + ): + event_type, data = classify_line(line) + if event_type == "done": break - if isinstance(content, list): - parts = [b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text"] - if parts: - prompt = " ".join(p.strip() for p in parts if p.strip()) - break + if event_type != "data" or not data: + continue + try: + obj = orjson.loads(data) + except Exception: + continue - if not prompt: - raise UpstreamError("Video prompt cannot be empty", status=400) + stream = _extract_streaming_video_response(obj) + if stream: + try: + progress = int(stream.get("progress") or 0) + except (TypeError, ValueError): + progress = 0 + if progress_cb is not None: + await progress_cb(progress) - message = _build_message(prompt, preset) + video_post_id = str( + stream.get("videoPostId") + or stream.get("videoId") + or video_post_id + or "" + ).strip() + + if progress >= 100 and not stream.get("moderated"): + raw_url = stream.get("videoUrl") + asset_id = stream.get("assetId") + thumbnail = stream.get("thumbnailImageUrl") + if isinstance(raw_url, str) and raw_url: + final_url = _absolutize_video_url(raw_url) + if isinstance(asset_id, str) and asset_id: + final_asset_id = asset_id + if isinstance(thumbnail, str) and thumbnail: + final_thumbnail = _absolutize_video_url(thumbnail) + + attachments = _extract_model_response_file_attachments(obj) + if attachments and not final_asset_id: + final_asset_id = attachments[0] + + if not final_url and final_asset_id: + final_url = resolve_asset_reference(final_asset_id, "", user_id=None) or "" + + if not final_url and final_asset_id: + raise UpstreamError("Video segment returned only assetId without a resolvable URL") + if not final_url: + raise UpstreamError("Video generation returned no final video URL") + + return _VideoArtifact( + video_url=final_url, + video_post_id=video_post_id or final_asset_id, + asset_id=final_asset_id, + thumbnail_url=final_thumbnail, + ) + + +async def _download_video_bytes(token: str, url: str) -> tuple[bytes, str]: + try: + stream, content_type = await download_asset(token, url) + chunks: list[bytes] = [] + async for chunk in stream: + chunks.append(chunk) + except UpstreamError: + raise + except Exception as exc: + raise UpstreamError(f"Video download failed: {exc}") from exc + return b"".join(chunks), (content_type or "video/mp4") + + +def _save_video_bytes(raw: bytes, file_id: str) -> Path: + out_dir = video_files_dir() + path = out_dir / f"{file_id}.mp4" + if not path.exists(): + path.write_bytes(raw) + return path + + +def _local_video_url(file_id: str) -> str: + app_url = get_config().get_str("app.app_url", "").rstrip("/") + return f"{app_url}/v1/files/video?id={file_id}" if app_url else f"/v1/files/video?id={file_id}" + + +def _normalize_video_format(value: str | None) -> str: + fmt = (value or "grok_url").strip().lower() + if fmt not in {"grok_url", "local_url", "grok_html", "local_html"}: + raise ValidationError( + "video_format must be one of [grok_url, local_url, grok_html, local_html]", + param="features.video_format", + ) + return fmt + + +def _render_video_html(url: str) -> str: + safe_url = html.escape(url, quote=True) + return f'<video controls src="{safe_url}"></video>' + + +async def _resolve_video_output(*, token: str, url: str, file_id: str) -> str: + fmt = _normalize_video_format(get_config().get_str("features.video_format", "grok_url")) + if fmt == "grok_url": + return url + if fmt == "grok_html": + return _render_video_html(url) + + try: + raw, _mime = await _download_video_bytes(token, url) + _save_video_bytes(raw, file_id) + except Exception as exc: + logger.warning("Video download failed, falling back to upstream URL: {}", exc) + return url if fmt == "local_url" else _render_video_html(url) + + local_url = _local_video_url(file_id) + return local_url if fmt == "local_url" else _render_video_html(local_url) + + +async def _generate_video_with_token( + *, + token: str, + prompt: str, + aspect_ratio: str, + resolution_name: str, + seconds: int, + preset: str, + timeout_s: float, + input_reference: dict[str, Any] | None = None, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _VideoArtifact: + reference: _VideoReference | None = None + if input_reference: + reference = await _prepare_video_reference(token, input_reference) + parent_post_id = reference.post_id + else: + post = await create_media_post( + token, + media_type=_VIDEO_MEDIA_TYPE, + prompt=prompt, + referer="https://grok.com/imagine", + ) + post_data = post.get("post") + if not isinstance(post_data, dict): + raise UpstreamError("Video create-post returned no post payload") + parent_post_id = str(post_data.get("id") or "").strip() + if not parent_post_id: + raise UpstreamError("Video create-post returned no post id") + + segments = _build_segment_lengths(seconds) + total_segments = len(segments) + artifact: _VideoArtifact | None = None + extend_post_id = parent_post_id + elapsed_seconds = 0 + + for index, segment_length in enumerate(segments): + if index == 0: + payload = _video_create_payload( + prompt=prompt, + parent_post_id=parent_post_id, + aspect_ratio=aspect_ratio, + resolution_name=resolution_name, + video_length=segment_length, + preset=preset, + reference_content_url=reference.content_url if reference is not None else None, + file_attachments=[reference.post_id] if reference is not None else None, + ) + referer = "https://grok.com/imagine" + else: + payload = _video_extend_payload( + prompt=prompt, + parent_post_id=parent_post_id, + extend_post_id=extend_post_id, + aspect_ratio=aspect_ratio, + resolution_name=resolution_name, + video_length=segment_length, + preset=preset, + start_time_s=_video_extend_start_time(elapsed_seconds), + ) + referer = f"https://grok.com/imagine/post/{parent_post_id}" + + async def _segment_progress(progress: int) -> None: + if progress_cb is None: + return + scaled = int(((index + (max(0, min(100, progress)) / 100.0)) / total_segments) * 100) + await progress_cb(scaled) + + artifact = await _collect_video_segment( + token=token, + payload=payload, + referer=referer, + timeout_s=timeout_s, + progress_cb=_segment_progress if progress_cb is not None else None, + ) + if index == 0 and total_segments > 1: + artifact.remixed_from_video_id = artifact.video_post_id or parent_post_id + extend_post_id = artifact.video_post_id or artifact.asset_id or parent_post_id + elapsed_seconds += segment_length + + if artifact is None: + raise UpstreamError("Video generation returned no artifact") + return artifact + + +async def _run_video_generation( + *, + model: str, + prompt: str, + aspect_ratio: str, + resolution_name: str, + seconds: int, + preset: str = "custom", + input_reference: dict[str, Any] | None = None, + progress_cb: Callable[[int], Awaitable[None]] | None = None, +) -> _VideoArtifact: + async def _runner(token: str, timeout_s: float) -> _VideoArtifact: + return await _generate_video_with_token( + token=token, + prompt=prompt, + aspect_ratio=aspect_ratio, + resolution_name=resolution_name, + seconds=seconds, + preset=preset, + timeout_s=timeout_s, + input_reference=input_reference, + progress_cb=progress_cb, + ) + + return await _run_video_with_account(model=model, runner=_runner) + + +async def _run_video_with_account( + *, + model: str, + runner: Callable[[str, float], Awaitable[Any]], +) -> Any: + cfg = get_config() + timeout_s = cfg.get_float("video.timeout", 180.0) + spec = resolve_model(model) + if not spec.is_video(): + raise ValidationError(f"Model {model!r} is not a video model", param="model") - # Acquire account. from app.dataplane.account import _directory as _acct_dir if _acct_dir is None: raise RateLimitError("Account directory not initialised") - ts = now_s() acct = await _acct_dir.reserve( - pool_id = spec.pool_id(), - mode_id = int(spec.mode_id), - now_s_override = ts, + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), ) if acct is None: raise RateLimitError("No available accounts for video generation") - token = acct.token + token = acct.token + success = False + try: + artifact = await runner(token, timeout_s) + success = True + return artifact + finally: + await _acct_dir.release(acct) + kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR + await _acct_dir.feedback(token, kind, int(spec.mode_id)) + if success: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + +async def _put_video_job(job: _VideoJob) -> None: + async with _VIDEO_JOBS_LOCK: + _VIDEO_JOBS[job.id] = job + + +async def get_video_job(video_id: str) -> _VideoJob | None: + async with _VIDEO_JOBS_LOCK: + return _VIDEO_JOBS.get(video_id) + + +async def _expire_video_job(video_id: str, ttl_s: int = _VIDEO_JOB_TTL_S) -> None: + await asyncio.sleep(ttl_s) + async with _VIDEO_JOBS_LOCK: + _VIDEO_JOBS.pop(video_id, None) + + +async def _set_job_status(job: _VideoJob, *, status: str, progress: int | None = None) -> None: + async with _VIDEO_JOBS_LOCK: + job.status = status + if progress is not None: + job.progress = max(0, min(100, progress)) + + +def _job_error_payload(message: str) -> dict[str, Any]: + return {"code": "video_generation_failed", "message": message} + + +async def _run_video_job( + job: _VideoJob, + *, + size: str, + resolution_name: str | None, + prompt: str, + seconds: int, + preset: str | None, + input_reference: dict[str, Any] | None = None, +) -> None: + try: + await _set_job_status(job, status="in_progress", progress=1) + aspect_ratio, default_resolution_name = _resolve_video_size(size) + resolved_resolution_name = _resolve_video_resolution_name( + resolution_name, + default=default_resolution_name, + ) + resolved_preset = _resolve_video_preset(preset) + spec = resolve_model(job.model) + + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + raise RateLimitError("Account directory not initialised") + + acct = await _acct_dir.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), + ) + if acct is None: + raise RateLimitError("No available accounts for video generation") + + token = acct.token + try: + cfg = get_config() + timeout_s = cfg.get_float("video.timeout", 180.0) + + async def _progress(progress: int) -> None: + await _set_job_status(job, status="in_progress", progress=max(1, progress)) + + artifact = await _generate_video_with_token( + token=token, + prompt=prompt, + aspect_ratio=aspect_ratio, + resolution_name=resolved_resolution_name, + seconds=seconds, + preset=resolved_preset, + timeout_s=timeout_s, + input_reference=input_reference, + progress_cb=_progress, + ) + raw, _mime = await _download_video_bytes(token, artifact.video_url) + kind = FeedbackKind.SUCCESS + finally: + await _acct_dir.release(acct) + await _acct_dir.feedback(token, kind if "kind" in locals() else FeedbackKind.SERVER_ERROR, int(spec.mode_id)) + if "kind" in locals() and kind == FeedbackKind.SUCCESS: + asyncio.create_task(_quota_sync(token, int(spec.mode_id))) + else: + asyncio.create_task(_fail_sync(token, int(spec.mode_id))) + + path = _save_video_bytes(raw, job.id) + async with _VIDEO_JOBS_LOCK: + job.status = "completed" + job.progress = 100 + job.completed_at = int(time.time()) + job.video_url = artifact.video_url + job.content_path = str(path) + job.remixed_from_video_id = artifact.remixed_from_video_id + except Exception as exc: + logger.exception("Video job {} failed: {}", job.id, exc) + async with _VIDEO_JOBS_LOCK: + job.status = "failed" + job.error = _job_error_payload(str(exc)) + + +async def create_video( + *, + model: str, + prompt: str, + seconds: str | int | None = None, + size: str | None = None, + resolution_name: str | None = None, + preset: str | None = None, + input_reference: dict[str, Any] | None = None, +) -> dict[str, Any]: + spec = model_registry.get(model) + if spec is None or not spec.enabled or not spec.is_video(): + raise ValidationError(f"Model {model!r} is not a video model", param="model") + + cleaned_prompt = (prompt or "").strip() + if not cleaned_prompt: + raise ValidationError("prompt cannot be empty", param="prompt") + + normalized_seconds = _coerce_seconds(seconds) + validate_video_length(normalized_seconds) + normalized_size = (size or "720x1280").strip() + _aspect_ratio, default_resolution_name = _resolve_video_size(normalized_size) + _resolve_video_resolution_name(resolution_name, default=default_resolution_name) + _resolve_video_preset(preset) + + job = _VideoJob( + id=f"video_{uuid.uuid4().hex}", + model=model, + prompt=cleaned_prompt, + seconds=str(normalized_seconds), + size=normalized_size, + quality=_VIDEO_QUALITY, + created_at=int(time.time()), + ) + await _put_video_job(job) + asyncio.create_task( + _run_video_job( + job, + size=normalized_size, + resolution_name=resolution_name, + prompt=cleaned_prompt, + seconds=normalized_seconds, + preset=preset, + input_reference=input_reference, + ) + ) + asyncio.create_task(_expire_video_job(job.id)) + return job.to_dict() + + +async def retrieve(video_id: str) -> dict[str, Any]: + job = await get_video_job(video_id) + if job is None: + raise ValidationError(f"Video {video_id!r} not found", param="video_id") + return job.to_dict() + + +async def content_path(video_id: str) -> Path: + job = await get_video_job(video_id) + if job is None: + raise ValidationError(f"Video {video_id!r} not found", param="video_id") + if job.status != "completed" or not job.content_path: + raise AppError( + "Video content is not ready yet", + kind=ErrorKind.VALIDATION, + code="video_not_ready", + status=409, + ) + path = Path(job.content_path) + if not path.exists(): + raise ValidationError(f"Video content for {video_id!r} not found", param="video_id") + return path + + +def _extract_video_prompt_and_reference(messages: list[dict]) -> tuple[str, dict[str, Any] | None]: + prompt = "" + reference_url = "" + + for msg in reversed(messages): + content = msg.get("content", "") + if isinstance(content, str) and content.strip(): + prompt = content.strip() + if prompt: + break + continue + if not isinstance(content, list): + continue + + text_parts: list[str] = [] + block_reference = "" + for item in content: + if not isinstance(item, dict): + continue + item_type = item.get("type") + if item_type == "text": + text = str(item.get("text") or "").strip() + if text: + text_parts.append(text) + elif item_type == "image_url": + image_url = item.get("image_url") + if isinstance(image_url, dict): + block_reference = str(image_url.get("url") or "").strip() or block_reference + elif isinstance(image_url, str): + block_reference = image_url.strip() or block_reference + + if text_parts: + prompt = " ".join(text_parts) + if block_reference and not reference_url: + reference_url = block_reference + if prompt: + break + + if not prompt: + raise ValidationError("Video prompt cannot be empty", param="messages") + + input_reference: dict[str, Any] | None = None + if reference_url: + input_reference = {"image_url": reference_url} + return prompt, input_reference + + +async def completions( + *, + model: str, + messages: list[dict], + stream: bool | None = None, + seconds: int = 6, + size: str = "720x1280", + resolution_name: str | None = None, + preset: str | None = None, +) -> dict | AsyncGenerator[str, None]: + """Chat-completions video support on top of the same core flow.""" + validate_video_length(seconds) + aspect_ratio, default_resolution_name = _resolve_video_size(size) + resolved_resolution_name = _resolve_video_resolution_name( + resolution_name, + default=default_resolution_name, + ) + resolved_preset = _resolve_video_preset(preset) + prompt, input_reference = _extract_video_prompt_and_reference(messages) + + cfg = get_config() + is_stream = stream if stream is not None else cfg.get_bool("features.stream", False) response_id = make_response_id() - rounds = _build_rounds(video_length, is_super=is_super) - async def _run_video() -> str: - """Execute all rounds and return the final video URL.""" - parent_post_id = "" - video_url = "" - - for round_idx, round_len in enumerate(rounds): - model_cfg = _build_video_model_config( - parent_post_id, - aspect_ratio = aspect_ratio, - resolution_name = resolution, - video_length = round_len, + async def _run(progress_cb: Callable[[int], Awaitable[None]] | None = None) -> str: + async def _runner(token: str, timeout_s: float) -> str: + artifact = await _generate_video_with_token( + token=token, + prompt=prompt, + aspect_ratio=aspect_ratio, + resolution_name=resolved_resolution_name, + seconds=seconds, + preset=resolved_preset, + timeout_s=timeout_s, + input_reference=input_reference, + progress_cb=progress_cb, ) - logger.info( - "Video round {}/{}: len={}s resolution={} parent={}", - round_idx + 1, len(rounds), round_len, resolution, parent_post_id or "<seed>", + file_id = hashlib.sha1(artifact.video_url.encode("utf-8")).hexdigest()[:32] + return await _resolve_video_output( + token=token, + url=artifact.video_url, + file_id=file_id, ) - async for line in _run_chat_stream( - token, message, spec.model_name, grok_mode, model_cfg, timeout_s=timeout_s, - ): - ev_type, data = classify_line(line) - if ev_type != "data" or not data: - continue - url = _extract_video_url(data) - if url: - video_url = url - parent_post_id = _extract_post_id(url) - - return video_url + return await _run_video_with_account(model=model, runner=_runner) if is_stream: async def _sse() -> AsyncGenerator[str, None]: - success = False - try: - video_url = await _run_video() - content = f"![video]({video_url})" if video_url else "" - chunk = make_stream_chunk(response_id, model, content) - yield f"data: {orjson.dumps(chunk).decode()}\n\n" - final = make_stream_chunk(response_id, model, "", is_final=True) - yield f"data: {orjson.dumps(final).decode()}\n\n" - yield "data: [DONE]\n\n" - success = True - finally: - await _acct_dir.release(acct) - kind = FeedbackKind.SUCCESS if success else FeedbackKind.SERVER_ERROR - await _acct_dir.feedback(token, kind, int(spec.mode_id)) + queue: asyncio.Queue[int] = asyncio.Queue() + last_progress = -1 + + async def _progress(progress: int) -> None: + await queue.put(max(0, min(100, progress))) + + task = asyncio.create_task(_run(progress_cb=_progress)) + while not task.done() or not queue.empty(): + try: + progress = await asyncio.wait_for(queue.get(), timeout=0.1) + except asyncio.TimeoutError: + continue + if progress > last_progress: + last_progress = progress + chunk = make_thinking_chunk(response_id, model, _progress_reason(progress)) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + + content = await task + chunk = make_stream_chunk(response_id, model, content) + yield f"data: {orjson.dumps(chunk).decode()}\n\n" + final = make_stream_chunk(response_id, model, "", is_final=True) + yield f"data: {orjson.dumps(final).decode()}\n\n" + yield "data: [DONE]\n\n" return _sse() - try: - video_url = await _run_video() - finally: - await _acct_dir.release(acct) - await _acct_dir.feedback(token, FeedbackKind.SUCCESS, int(spec.mode_id)) + progress_updates: list[str] = [] - content = f"![video]({video_url})" if video_url else "" - return make_chat_response(model, content, response_id=response_id, usage=build_usage(0, 0)) + async def _progress(progress: int) -> None: + reason = _progress_reason(progress) + if not progress_updates or progress_updates[-1] != reason: + progress_updates.append(reason) + + content = await _run(progress_cb=_progress) + reasoning = "\n".join(progress_updates) if progress_updates else None + return make_chat_response( + model, + content, + response_id=response_id, + reasoning_content=reasoning, + ) -__all__ = ["completions"] +__all__ = [ + "create_video", + "retrieve", + "content_path", + "validate_video_length", + "completions", + "_build_segment_lengths", + "_resolve_video_size", +] diff --git a/app/products/web/__init__.py b/app/products/web/__init__.py index 258c7263..4f84059f 100644 --- a/app/products/web/__init__.py +++ b/app/products/web/__init__.py @@ -1 +1,5 @@ -"""Web product — new unified frontend (admin + webui pages & API).""" +"""Web product — unified frontend (admin + webui pages & API).""" + +from .router import router + +__all__ = ["router"] diff --git a/app/products/web/admin/__init__.py b/app/products/web/admin/__init__.py index d5321f1c..e78a63a5 100644 --- a/app/products/web/admin/__init__.py +++ b/app/products/web/admin/__init__.py @@ -4,17 +4,18 @@ All admin endpoints live under ``/admin/api`` with ``verify_admin_key`` guard. Heavy handlers are split into ``tokens`` and ``batch`` sub-modules. """ -from __future__ import annotations - -from pathlib import Path -from typing import TYPE_CHECKING +import re +from typing import TYPE_CHECKING, Any import orjson from fastapi import APIRouter, Depends, Request -from fastapi.responses import JSONResponse, Response +from fastapi.responses import Response +from pydantic import RootModel -from app.platform.auth.middleware import verify_admin_key, get_admin_key -from app.platform.config.snapshot import config, get_config +from app.control.account.backends.factory import get_repository_backend +from app.platform.auth.middleware import verify_admin_key +from app.platform.config.snapshot import config +from app.platform.errors import AppError, ErrorKind, ValidationError from app.platform.logging.logger import logger, reload_logging if TYPE_CHECKING: @@ -25,6 +26,81 @@ if TYPE_CHECKING: # Shared DI dependencies — inject via Depends, no try/except per call # --------------------------------------------------------------------------- +_CFG_CHAR_REPLACEMENTS = str.maketrans({ + "\u2010": "-", "\u2011": "-", "\u2012": "-", + "\u2013": "-", "\u2014": "-", "\u2212": "-", + "\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"', + "\u00a0": " ", "\u2007": " ", "\u202f": " ", + "\u200b": "", "\u200c": "", "\u200d": "", "\ufeff": "", +}) + +_STARTUP_ONLY_CONFIG_PREFIXES = ( + "account.storage", + "account.local", + "account.redis", + "account.mysql", + "account.postgresql", +) + + +class ConfigPatchRequest(RootModel[dict[str, Any]]): + """Loose config patch payload with explicit root typing.""" + + +def _sanitize_text(value: Any, *, remove_all_spaces: bool = False) -> str: + text = "" if value is None else str(value) + text = text.translate(_CFG_CHAR_REPLACEMENTS) + if remove_all_spaces: + text = re.sub(r"\s+", "", text) + else: + text = text.strip() + return text.encode("latin-1", errors="ignore").decode("latin-1") + + +def _sanitize_proxy_config(payload: dict[str, Any]) -> dict[str, Any]: + proxy = payload.get("proxy") + if not isinstance(proxy, dict): + return dict(payload) + + sanitized = dict(proxy) + changed = False + for key, strip_spaces in [("user_agent", False), ("cf_cookies", False), ("cf_clearance", True)]: + if key not in sanitized: + continue + raw = sanitized[key] + val = _sanitize_text(raw, remove_all_spaces=strip_spaces) + if val != raw: + sanitized[key] = val + changed = True + if not changed: + return dict(payload) + + logger.warning("Sanitized proxy config fields before saving") + result = dict(payload) + result["proxy"] = sanitized + return result + + +def _iter_patch_paths(value: Any, prefix: str = ""): + if isinstance(value, dict): + for key, child in value.items(): + path = f"{prefix}.{key}" if prefix else str(key) + if isinstance(child, dict): + yield from _iter_patch_paths(child, path) + else: + yield path + + +def _ensure_runtime_patch_allowed(payload: dict[str, Any]) -> None: + for path in _iter_patch_paths(payload): + for blocked in _STARTUP_ONLY_CONFIG_PREFIXES: + if path == blocked or path.startswith(f"{blocked}."): + raise ValidationError( + "Storage config is startup-only and must be set via env", + param=path, + code="startup_only_config", + ) + def get_repo(request: Request) -> "AccountRepository": """Resolve the singleton AccountRepository from app state.""" @@ -43,11 +119,15 @@ def get_refresh_svc(request: Request) -> "AccountRefreshService": router = APIRouter(prefix="/admin/api", dependencies=[Depends(verify_admin_key)]) # Mount sub-modules -from .tokens import router as _tokens_router # noqa: E402 -from .batch import router as _batch_router # noqa: E402 +from .tokens import router as _tokens_router # noqa: E402 +from .batch import router as _batch_router # noqa: E402 +from .assets import router as _assets_router # noqa: E402 +from .cache import router as _cache_router # noqa: E402 router.include_router(_tokens_router) router.include_router(_batch_router) +router.include_router(_assets_router) +router.include_router(_cache_router) # --------------------------------------------------------------------------- @@ -68,23 +148,29 @@ async def get_config_endpoint(): @router.post("/config") -async def update_config(data: dict): - await config.update(data) +async def update_config(req: ConfigPatchRequest): + patch = _sanitize_proxy_config(req.root) + _ensure_runtime_patch_allowed(patch) + await config.update(patch) reload_logging() return {"status": "success", "message": "配置已更新"} @router.get("/storage") async def get_storage_mode(): - backend = get_config("account.storage", "local") - return {"type": str(backend).strip().lower() or "local"} + return {"type": get_repository_backend()} @router.get("/status") async def runtime_status(): from app.dataplane.account import _directory if _directory is None: - return JSONResponse({"status": "not_initialised"}) + raise AppError( + "Account directory not initialised", + kind=ErrorKind.SERVER, + code="directory_not_initialised", + status=503, + ) return Response( content=orjson.dumps({ "status": "ok", @@ -99,7 +185,12 @@ async def runtime_status(): async def force_sync(): from app.dataplane.account import _directory if _directory is None: - return JSONResponse({"error": "not_initialised"}, status_code=503) + raise AppError( + "Account directory not initialised", + kind=ErrorKind.SERVER, + code="directory_not_initialised", + status=503, + ) changed = await _directory.sync_if_changed() return Response( content=orjson.dumps({"changed": changed, "revision": _directory.revision}), diff --git a/app/products/web/admin/assets.py b/app/products/web/admin/assets.py new file mode 100644 index 00000000..7d14af7c --- /dev/null +++ b/app/products/web/admin/assets.py @@ -0,0 +1,143 @@ +"""Admin online-asset management — list, delete, clear per token.""" + +import asyncio +from typing import TYPE_CHECKING + +import orjson +from fastapi import APIRouter, Depends +from fastapi.responses import Response +from pydantic import BaseModel + +from app.platform.errors import UpstreamError +from app.control.account.commands import ListAccountsQuery + +if TYPE_CHECKING: + from app.control.account.repository import AccountRepository + +from . import get_repo + +router = APIRouter(prefix="/assets") + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _mask(token: str) -> str: + return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token + + +async def _list_all_tokens(repo: "AccountRepository") -> list[str]: + page_num, tokens = 1, [] + while True: + page = await repo.list_accounts(ListAccountsQuery(page=page_num, page_size=2000)) + tokens.extend(r.token for r in page.items) + if page_num * 2000 >= page.total: + break + page_num += 1 + return tokens + + +async def _fetch_one(token: str) -> dict: + from app.dataplane.reverse.transport.assets import list_assets + try: + resp = await list_assets(token) + items = resp.get("assets", resp.get("items", [])) + return { + "token": token, + "masked": _mask(token), + "count": len(items), + "assets": [ + { + "id": item.get("id") or item.get("assetId") or "", + "name": item.get("fileName") or item.get("name") or "", + "file_path": item.get("filePath") or item.get("file_path") or "", + "content_type": item.get("contentType") or item.get("content_type") or "", + "size": item.get("fileSize") or item.get("size") or 0, + "created_at": item.get("createdAt") or item.get("created_at") or "", + } + for item in items + ], + "error": None, + } + except Exception as exc: + return { + "token": token, + "masked": _mask(token), + "count": 0, + "assets": [], + "error": str(exc), + } + + +# --------------------------------------------------------------------------- +# Request models +# --------------------------------------------------------------------------- + +class DeleteItemRequest(BaseModel): + token: str + asset_id: str + + +class ClearTokenRequest(BaseModel): + token: str + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@router.get("") +async def list_all_assets(repo: "AccountRepository" = Depends(get_repo)): + """Fetch asset lists for all tokens concurrently.""" + tokens = await _list_all_tokens(repo) + if not tokens: + return Response( + content=orjson.dumps({"tokens": [], "total_assets": 0}), + media_type="application/json", + ) + + # Concurrency is governed by the global list_assets semaphore in the transport layer. + results = await asyncio.gather(*[_fetch_one(t) for t in tokens]) + total = sum(r["count"] for r in results) + + return Response( + content=orjson.dumps({"tokens": list(results), "total_assets": total}), + media_type="application/json", + ) + + +@router.post("/delete-item") +async def delete_item(req: DeleteItemRequest): + """Delete a single asset by token + asset_id.""" + from app.dataplane.reverse.transport.assets import delete_asset + try: + await delete_asset(req.token, req.asset_id) + return {"status": "success"} + except Exception as exc: + raise UpstreamError(str(exc)) from exc + + +@router.post("/clear-token") +async def clear_token_assets(req: ClearTokenRequest): + """Delete all assets for one token concurrently.""" + from app.dataplane.reverse.transport.assets import list_assets, delete_asset + try: + resp = await list_assets(req.token) + items = resp.get("assets", resp.get("items", [])) + + async def _del(item: dict) -> int: + aid = item.get("id") or item.get("assetId") + if not aid: + return 0 + await delete_asset(req.token, aid) + return 1 + + results = await asyncio.gather(*[_del(i) for i in items], return_exceptions=True) + deleted = sum(r for r in results if isinstance(r, int)) + return {"status": "success", "deleted": deleted} + except Exception as exc: + raise UpstreamError(str(exc)) from exc + + +__all__ = ["router"] diff --git a/app/products/web/admin/batch.py b/app/products/web/admin/batch.py index 5eb754a1..39e7c87d 100644 --- a/app/products/web/admin/batch.py +++ b/app/products/web/admin/batch.py @@ -7,21 +7,19 @@ Performance notes: - Sync mode: concurrent execution, single JSON response """ -from __future__ import annotations - import asyncio from typing import TYPE_CHECKING, Any, Callable, Awaitable import orjson -from fastapi import APIRouter, Depends, HTTPException, Query, Request +from fastapi import APIRouter, Depends, Query, Request from fastapi.responses import Response, StreamingResponse from pydantic import BaseModel -from app.platform.logging.logger import logger +from app.platform.config.snapshot import get_config +from app.platform.errors import AppError, ErrorKind, UpstreamError, ValidationError from app.platform.runtime.batch import run_batch -from app.platform.runtime.task import AsyncTask, create_task, expire_task, get_task -from app.platform.auth.middleware import get_admin_key -from app.control.account.commands import ListAccountsQuery +from app.platform.runtime.task import create_task, expire_task, get_task +from app.control.account.commands import AccountPatch, ListAccountsQuery if TYPE_CHECKING: from app.control.account.refresh import AccountRefreshService @@ -35,6 +33,13 @@ router = APIRouter(prefix="/batch") # Helpers # --------------------------------------------------------------------------- +def _concurrency(override: int | None, config_key: str, fallback: int = 50) -> int: + """Resolve effective concurrency: query-param → config → fallback.""" + if override is not None: + return max(1, override) + v = get_config(config_key, fallback) + return max(1, int(v)) + def _mask(token: str) -> str: return f"{token[:8]}...{token[-8:]}" if len(token) > 20 else token @@ -127,15 +132,20 @@ async def _dispatch_async( if task.cancelled: return async with sem: + # Re-check after acquiring slot: cancel may have been set + # while this coroutine was waiting for a semaphore slot. + if task.cancelled: + return + masked = _mask(token) try: data = await handler(token) ok_c += 1 - results[_mask(token)] = data - task.record(True) + results[masked] = data + task.record(True, item=masked, detail=data) except Exception as exc: fail_c += 1 - results[_mask(token)] = {"error": str(exc)} - task.record(False, error=str(exc)) + results[masked] = {"error": str(exc)} + task.record(False, item=masked, error=str(exc)) await asyncio.gather(*[_one(t) for t in tokens]) @@ -160,25 +170,30 @@ async def _dispatch_async( # Per-token handlers # --------------------------------------------------------------------------- -async def _nsfw_one(token: str) -> dict: - from app.dataplane.reverse.protocol.xai_auth import accept_tos, set_birth_date, enable_nsfw - await accept_tos(token) - await set_birth_date(token) - await enable_nsfw(token) - return {"success": True} +async def _nsfw_one(repo: "AccountRepository", token: str, enabled: bool) -> dict: + from app.dataplane.reverse.protocol.xai_auth import set_birth_date, set_nsfw + if enabled: + await set_birth_date(token) + await set_nsfw(token, enabled) + patch = AccountPatch(token=token, add_tags=["nsfw"]) if enabled else AccountPatch(token=token, remove_tags=["nsfw"]) + await repo.patch_accounts([patch]) + return {"success": True, "tagged": enabled} async def _cache_clear_one(token: str) -> dict: from app.dataplane.reverse.transport.assets import list_assets, delete_asset - resp = await list_assets(token) + resp = await list_assets(token) items = resp.get("assets", resp.get("items", [])) - deleted = 0 - for item in items: + + async def _del(item: dict) -> int: aid = item.get("id") or item.get("assetId") - if aid: - await delete_asset(token, aid) - deleted += 1 - return {"deleted": deleted} + if not aid: + return 0 + await delete_asset(token, aid) + return 1 + + results = await asyncio.gather(*[_del(i) for i in items], return_exceptions=True) + return {"deleted": sum(r for r in results if isinstance(r, int))} # --------------------------------------------------------------------------- @@ -189,42 +204,58 @@ async def _cache_clear_one(token: str) -> dict: async def batch_nsfw( req: BatchRequest, async_mode: bool = Query(False, alias="async"), + concurrency: int | None = Query(None, ge=1), + enabled: bool = Query(True), repo: "AccountRepository" = Depends(get_repo), ): tokens = [t.strip() for t in req.tokens if t.strip()] if not tokens: tokens = await _list_all_tokens(repo) if not tokens: - raise HTTPException(400, "No tokens available") - return await _dispatch(tokens, _nsfw_one, use_async=async_mode) + raise ValidationError("No tokens available", param="tokens") + + async def _nsfw_and_tag(token: str) -> dict: + return await _nsfw_one(repo, token, enabled) + + c = _concurrency(concurrency, "batch.nsfw_concurrency") + return await _dispatch(tokens, _nsfw_and_tag, use_async=async_mode, concurrency=c) @router.post("/refresh") async def batch_refresh( req: BatchRequest, async_mode: bool = Query(False, alias="async"), + concurrency: int | None = Query(None, ge=1), refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), ): tokens = [t.strip() for t in req.tokens if t.strip()] if not tokens: - raise HTTPException(400, "No tokens provided") + raise ValidationError("No tokens provided", param="tokens") async def _refresh_one(token: str) -> dict: result = await refresh_svc.refresh_tokens([token]) - return {"refreshed": result.refreshed, "failed": result.failed} + if not result.refreshed: + raise UpstreamError("未获取到真实配额数据") + return {"refreshed": result.refreshed} - return await _dispatch(tokens, _refresh_one, use_async=async_mode) + c = _concurrency(concurrency, "batch.refresh_concurrency") + return await _dispatch(tokens, _refresh_one, use_async=async_mode, concurrency=c) @router.post("/cache-clear") async def batch_cache_clear( req: BatchRequest, async_mode: bool = Query(False, alias="async"), + concurrency: int | None = Query(None, ge=1), + repo: "AccountRepository" = Depends(get_repo), ): tokens = [t.strip() for t in req.tokens if t.strip()] if not tokens: - raise HTTPException(400, "No tokens provided") - return await _dispatch(tokens, _cache_clear_one, use_async=async_mode) + tokens = await _list_all_tokens(repo) + if not tokens: + raise ValidationError("No tokens available", param="tokens") + c = _concurrency(concurrency, "batch.asset_delete_concurrency") + return await _dispatch(tokens, _cache_clear_one, use_async=async_mode, concurrency=c) # --------------------------------------------------------------------------- @@ -233,16 +264,16 @@ async def batch_cache_clear( @router.get("/{task_id}/stream") async def batch_stream(task_id: str, request: Request): - # Auth via query param for EventSource (Bearer header unavailable). - app_key = get_admin_key() - if app_key: - key = request.query_params.get("app_key") - if key != app_key: - raise HTTPException(401, "Invalid authentication token") - + # Auth is handled by the parent router's verify_admin_key dependency, + # which accepts both Bearer header and ?app_key= query param (for EventSource). task = get_task(task_id) if not task: - raise HTTPException(404, "Task not found") + raise AppError( + "Task not found", + kind=ErrorKind.VALIDATION, + code="task_not_found", + status=404, + ) async def _stream(): queue = task.attach() @@ -278,6 +309,11 @@ async def batch_stream(task_id: str, request: Request): async def batch_cancel(task_id: str): task = get_task(task_id) if not task: - raise HTTPException(404, "Task not found") + raise AppError( + "Task not found", + kind=ErrorKind.VALIDATION, + code="task_not_found", + status=404, + ) task.cancel() return {"status": "success"} diff --git a/app/products/admin/handlers/cache.py b/app/products/web/admin/cache.py similarity index 59% rename from app/products/admin/handlers/cache.py rename to app/products/web/admin/cache.py index 1f688963..a9d4460d 100644 --- a/app/products/admin/handlers/cache.py +++ b/app/products/web/admin/cache.py @@ -1,34 +1,41 @@ -"""Local cache management — stats, list, clear, delete.""" - -from __future__ import annotations +"""Local media cache management — stats, list, clear, delete.""" from pathlib import Path -from typing import Any, Dict +from typing import Any, Literal -from fastapi import APIRouter, HTTPException, Query +from fastapi import APIRouter, Query +from pydantic import BaseModel + +from app.platform.errors import AppError, ErrorKind +from app.platform.storage import image_files_dir, video_files_dir router = APIRouter(prefix="/cache") # --------------------------------------------------------------------------- -# Lightweight local cache service (inlined to avoid external dep) +# Lightweight local media cache service. # --------------------------------------------------------------------------- - -_BASE = Path(__file__).resolve().parents[4] / "data" / "tmp" _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"} _VIDEO_EXTS = {".mp4", ".mov", ".m4v", ".webm", ".avi", ".mkv"} +class ClearCacheRequest(BaseModel): + type: Literal["image", "video"] = "image" + + +class DeleteCacheItemRequest(BaseModel): + type: Literal["image", "video"] = "image" + name: str + + def _dir(media_type: str) -> Path: - d = _BASE / ("image" if media_type == "image" else "video") - d.mkdir(parents=True, exist_ok=True) - return d + return image_files_dir() if media_type == "image" else video_files_dir() def _exts(media_type: str): return _IMAGE_EXTS if media_type == "image" else _VIDEO_EXTS -def _stats(media_type: str) -> Dict[str, Any]: +def _stats(media_type: str) -> dict[str, Any]: d = _dir(media_type) if not d.exists(): return {"count": 0, "size_mb": 0.0} @@ -38,7 +45,7 @@ def _stats(media_type: str) -> Dict[str, Any]: return {"count": len(files), "size_mb": round(total_size / 1024 / 1024, 2)} -def _list_files(media_type: str, page: int, page_size: int) -> Dict[str, Any]: +def _list_files(media_type: str, page: int, page_size: int) -> dict[str, Any]: d = _dir(media_type) if not d.exists(): return {"total": 0, "page": page, "page_size": page_size, "items": []} @@ -76,21 +83,19 @@ async def cache_stats(): @router.get("/list") async def list_local( - cache_type: str = "image", - type_: str = Query(default=None, alias="type"), + cache_type: Literal["image", "video"] = "image", + type_: Literal["image", "video"] | None = Query(default=None, alias="type"), page: int = 1, page_size: int = 1000, ): - if type_: - cache_type = type_ - return {"status": "success", **_list_files(cache_type, page, page_size)} + media_type = type_ or cache_type + return {"status": "success", **_list_files(media_type, page, page_size)} @router.post("/clear") -async def clear_local(data: dict): - media_type = data.get("type", "image") - d = _dir(media_type) - allowed = _exts(media_type) +async def clear_local(req: ClearCacheRequest): + d = _dir(req.type) + allowed = _exts(req.type) removed = 0 for f in d.glob("*"): if f.is_file() and f.suffix.lower() in allowed: @@ -100,13 +105,21 @@ async def clear_local(data: dict): @router.post("/item/delete") -async def delete_local_item(data: dict): - media_type = data.get("type", "image") - name = data.get("name") - if not name: - raise HTTPException(status_code=400, detail="Missing file name") - target = _dir(media_type) / name +async def delete_local_item(req: DeleteCacheItemRequest): + if not req.name: + raise AppError( + "Missing file name", + kind=ErrorKind.VALIDATION, + code="missing_file_name", + status=400, + ) + target = _dir(req.type) / req.name if not target.is_file(): - raise HTTPException(status_code=404, detail="File not found") + raise AppError( + "File not found", + kind=ErrorKind.VALIDATION, + code="file_not_found", + status=404, + ) target.unlink(missing_ok=True) - return {"status": "success", "result": {"deleted": name}} + return {"status": "success", "result": {"deleted": req.name}} diff --git a/app/products/web/admin/tokens.py b/app/products/web/admin/tokens.py index 64a7008a..2483d703 100644 --- a/app/products/web/admin/tokens.py +++ b/app/products/web/admin/tokens.py @@ -7,19 +7,19 @@ Performance notes: - Import refresh: reuses app.state.refresh_service singleton """ -from __future__ import annotations - import asyncio import re from typing import TYPE_CHECKING import orjson -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Body, Depends from fastapi.responses import Response -from pydantic import BaseModel +from pydantic import BaseModel, RootModel +from app.platform.errors import AppError, ErrorKind, ValidationError from app.platform.logging.logger import logger from app.control.account.commands import ( + AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery, @@ -68,14 +68,35 @@ class ReplacePoolRequest(BaseModel): tags: list[str] = [] +class AddTokensRequest(BaseModel): + tokens: list[str] + pool: str = "basic" + tags: list[str] = [] + + +class EditTokenRequest(BaseModel): + old_token: str + token: str + pool: str = "basic" + + +class TokenImportItem(BaseModel): + token: str + tags: list[str] = [] + + +class SaveTokensRequest(RootModel[dict[str, list[str | TokenImportItem]]]): + """Legacy bulk-save payload keyed by pool name.""" + + # --------------------------------------------------------------------------- # Serialisation — zero-copy quota extraction # --------------------------------------------------------------------------- def _quota_brief(q: dict) -> dict: - """Extract {auto, fast, expert} with only remaining/total from stored quota dict.""" + """Extract {auto, fast, expert, heavy} with only remaining/total from stored quota dict.""" out = {} - for mode in ("auto", "fast", "expert"): + for mode in ("auto", "fast", "expert", "heavy"): v = q.get(mode) if isinstance(v, dict): out[mode] = { @@ -85,22 +106,15 @@ def _quota_brief(q: dict) -> dict: return out -def _serialize_record(r, pool: str) -> dict: +def _serialize_record(r) -> dict: return { - "token": r.token, - "status": r.status, - "quota": _quota_brief(r.quota) if isinstance(r.quota, dict) else {}, - "consumed": 0, - "created_at": r.created_at, - "last_used_at": r.last_use_at, - "use_count": r.usage_use_count or 0, - "fail_count": r.usage_fail_count or 0, - "last_fail_at": r.last_fail_at, - "last_fail_reason": r.last_fail_reason, - "last_sync_at": r.last_sync_at, - "tags": r.tags or [], - "note": getattr(r, "note", "") or "", - "last_asset_clear_at": r.last_clear_at, + "token": r.token, + "pool": r.pool or "basic", + "status": r.status, + "quota": _quota_brief(r.quota) if isinstance(r.quota, dict) else {}, + "use_count": r.usage_use_count or 0, + "last_used_at": r.last_use_at, + "tags": r.tags or [], } @@ -115,7 +129,7 @@ def _json(data) -> Response: @router.get("/tokens") async def list_tokens(repo: "AccountRepository" = Depends(get_repo)): - """Return all tokens grouped by pool.""" + """Return flat token list.""" all_items: list = [] page_num = 1 while True: @@ -125,17 +139,12 @@ async def list_tokens(repo: "AccountRepository" = Depends(get_repo)): break page_num += 1 - result: dict[str, list] = {} - for r in all_items: - pool = r.pool or "basic" - result.setdefault(pool, []).append(_serialize_record(r, pool)) - - return _json({"tokens": result, "consumed_mode_enabled": False}) + return _json({"tokens": [_serialize_record(r) for r in all_items]}) @router.post("/tokens") async def save_tokens( - data: dict, + req: SaveTokensRequest, repo: "AccountRepository" = Depends(get_repo), refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), ): @@ -143,12 +152,10 @@ async def save_tokens( total_upserted = 0 all_tokens: list[str] = [] - for pool_name, items in data.items(): - if not isinstance(items, list): - continue + for pool_name, items in req.root.items(): upserts = [] for item in items: - td = {"token": item} if isinstance(item, str) else dict(item or {}) + td = {"token": item} if isinstance(item, str) else item.model_dump() token_val = _sanitize(td.get("token", "")) if not token_val: continue @@ -164,23 +171,140 @@ async def save_tokens( return _json({"status": "success", "count": total_upserted}) +@router.post("/tokens/add") +async def add_tokens( + req: AddTokensRequest, + repo: "AccountRepository" = Depends(get_repo), + refresh_svc: "AccountRefreshService" = Depends(get_refresh_svc), +): + requested_pool = (req.pool or "basic").strip().lower() + sync_auto_detect = requested_pool == "auto" + + # Deduplicate and sanitize input + cleaned: list[str] = [] + seen: set[str] = set() + for token in req.tokens: + tok = _sanitize(token) + if tok and tok not in seen: + seen.add(tok) + cleaned.append(tok) + if not cleaned: + raise ValidationError("No valid tokens provided", param="tokens") + + # Only upsert tokens that are not already active — avoids overwriting quota/status. + # Soft-deleted tokens are treated as non-existing so they can be restored. + existing = {r.token for r in await repo.get_accounts(cleaned) if not r.is_deleted()} + new_tokens = [t for t in cleaned if t not in existing] + + if not new_tokens: + return _json({"status": "success", "count": 0, "skipped": len(cleaned)}) + + upserts = [AccountUpsert(token=t, pool=requested_pool, tags=req.tags) for t in new_tokens] + result = await repo.upsert_accounts(upserts) + logger.info("Admin: added {} new tokens to pool={} (skipped {} existing)", + len(new_tokens), requested_pool, len(existing)) + + if sync_auto_detect: + try: + refresh_result = await refresh_svc.refresh_on_import(new_tokens) + logger.info( + "Admin: auto-detect sync completed for {} tokens (refreshed={} failed={})", + len(new_tokens), refresh_result.refreshed, refresh_result.failed, + ) + except Exception as exc: + logger.warning("Admin: auto-detect sync failed for {} tokens: {}", len(new_tokens), exc) + else: + asyncio.create_task(_refresh_imported(refresh_svc, new_tokens)) + + return _json({ + "status": "success", + "count": result.upserted or len(new_tokens), + "skipped": len(existing), + "synced": sync_auto_detect, + }) + + @router.delete("/tokens") async def delete_tokens( - tokens: list[str], + tokens: list[str] = Body(...), repo: "AccountRepository" = Depends(get_repo), ): cleaned = [t for t in (_sanitize(t) for t in tokens) if t] if not cleaned: - return Response( - content=orjson.dumps({"error": "No valid tokens provided"}), - media_type="application/json", - status_code=400, - ) + raise ValidationError("No valid tokens provided", param="tokens") await repo.delete_accounts(cleaned) logger.info("Admin: deleted {} tokens", len(cleaned)) return _json({"deleted": len(cleaned)}) +@router.put("/tokens/edit") +async def edit_token( + req: EditTokenRequest, + repo: "AccountRepository" = Depends(get_repo), +): + old_token = _sanitize(req.old_token) + new_token = _sanitize(req.token) + pool = (req.pool or "basic").strip().lower() + + if not old_token or not new_token: + raise ValidationError("Token is required", param="token") + + records = await repo.get_accounts([old_token]) + if not records: + raise AppError( + "Account not found", + kind=ErrorKind.VALIDATION, + code="account_not_found", + status=404, + ) + record = records[0] + + if old_token != new_token: + existing = await repo.get_accounts([new_token]) + if existing: + raise AppError( + "Target token already exists", + kind=ErrorKind.VALIDATION, + code="token_conflict", + status=409, + ) + + await repo.upsert_accounts([AccountUpsert( + token=new_token, + pool=pool, + tags=record.tags, + ext=record.ext, + )]) + + if old_token == new_token: + logger.info("Admin: updated token {} pool={}", _mask(new_token), pool) + return _json({"status": "success", "token": new_token, "pool": pool}) + + qs = record.quota_set() + await repo.patch_accounts([AccountPatch( + token=new_token, + status=record.status, + tags=record.tags, + quota_auto=qs.auto.to_dict(), + quota_fast=qs.fast.to_dict(), + quota_expert=qs.expert.to_dict(), + usage_use_delta=record.usage_use_count, + usage_fail_delta=record.usage_fail_count, + usage_sync_delta=record.usage_sync_count, + last_use_at=record.last_use_at, + last_fail_at=record.last_fail_at, + last_fail_reason=record.last_fail_reason, + last_sync_at=record.last_sync_at, + last_clear_at=record.last_clear_at, + state_reason=record.state_reason, + ext_merge=record.ext, + )]) + await repo.delete_accounts([old_token]) + + logger.info("Admin: edited token {} -> {} pool={}", _mask(old_token), _mask(new_token), pool) + return _json({"status": "success", "token": new_token, "pool": pool}) + + @router.put("/tokens/pool") async def replace_pool( req: ReplacePoolRequest, diff --git a/app/products/web/routes.py b/app/products/web/router.py similarity index 69% rename from app/products/web/routes.py rename to app/products/web/router.py index 20a3c2b6..02adad29 100644 --- a/app/products/web/routes.py +++ b/app/products/web/router.py @@ -1,19 +1,21 @@ """Web product — unified pages + API for the statics-based frontend.""" -from __future__ import annotations - from pathlib import Path from fastapi import APIRouter, Depends, HTTPException from fastapi.responses import FileResponse, RedirectResponse from app.platform.auth.middleware import is_webui_enabled, verify_webui_key +from app.platform.meta import get_project_version +from app.platform.update_check import get_latest_release_info from .admin import router as admin_api_router +from .webui import router as webui_router router = APIRouter() # Mount admin API sub-router (/admin/api/*) router.include_router(admin_api_router) +router.include_router(webui_router) _DIR = Path(__file__).resolve().parents[2] / "statics" @@ -38,6 +40,14 @@ async def admin_login(): async def admin_account(): return _serve("admin/account.html") +@router.get("/admin/config", include_in_schema=False) +async def admin_config(): + return _serve("admin/config.html") + +@router.get("/admin/cache", include_in_schema=False) +async def admin_cache(): + return _serve("admin/cache.html") + # --- WebUI --- @router.get("/webui", include_in_schema=False) @@ -53,3 +63,13 @@ async def webui_login(): @router.get("/webui/api/verify", dependencies=[Depends(verify_webui_key)]) async def webui_verify(): return {"status": "ok"} + + +@router.get("/meta", include_in_schema=False) +async def app_meta(): + return {"version": get_project_version()} + + +@router.get("/meta/update", include_in_schema=False) +async def app_update_meta(): + return await get_latest_release_info() diff --git a/app/products/web/webui/__init__.py b/app/products/web/webui/__init__.py new file mode 100644 index 00000000..e91e825d --- /dev/null +++ b/app/products/web/webui/__init__.py @@ -0,0 +1,16 @@ +"""WebUI product package.""" + +from fastapi import APIRouter + +from .chat import router as chat_router +from .imagine import router as imagine_router +from .pages import router as pages_router +from .voice import router as voice_router + +router = APIRouter() +router.include_router(chat_router) +router.include_router(imagine_router, prefix="/webui/api") +router.include_router(voice_router) +router.include_router(pages_router) + +__all__ = ["router"] diff --git a/app/products/web/webui/chat.py b/app/products/web/webui/chat.py new file mode 100644 index 00000000..ee79a9f7 --- /dev/null +++ b/app/products/web/webui/chat.py @@ -0,0 +1,47 @@ +"""WebUI chat API routes.""" + +import time + +from fastapi import APIRouter, Depends +from fastapi.responses import JSONResponse + +from app.control.model import registry as model_registry +from app.platform.auth.middleware import verify_webui_key +from app.products.openai.router import chat_completions_endpoint +from app.products.openai.schemas import ChatCompletionRequest + +router = APIRouter(prefix="/webui/api", dependencies=[Depends(verify_webui_key)]) + + +def _capability_name(spec) -> str: + if spec.is_image_edit(): + return "image_edit" + if spec.is_image(): + return "image" + if spec.is_video(): + return "video" + return "chat" + + +@router.get("/models") +async def list_webui_models(): + models = [ + { + "id": spec.model_name, + "object": "model", + "created": int(time.time()), + "owned_by": "xai", + "name": spec.public_name, + "capability": _capability_name(spec), + } + for spec in model_registry.list_enabled() + ] + return JSONResponse({"object": "list", "data": models}) + + +@router.post("/chat/completions") +async def webui_chat_completions(req: ChatCompletionRequest): + return await chat_completions_endpoint(req) + + +__all__ = ["router"] diff --git a/app/products/web/webui/imagine.py b/app/products/web/webui/imagine.py new file mode 100644 index 00000000..7a0b6075 --- /dev/null +++ b/app/products/web/webui/imagine.py @@ -0,0 +1,230 @@ +"""WebUI imagine endpoint backed by Grok Imagine WebSocket only.""" + +import asyncio +import hmac +import uuid +from typing import Optional + +import orjson +from fastapi import APIRouter, WebSocket, WebSocketDisconnect + +from app.platform.auth.middleware import get_webui_key, is_webui_enabled +from app.platform.config.snapshot import get_config +from app.platform.logging.logger import logger +from app.platform.runtime.clock import now_s +from app.products.openai.images import resolve_aspect_ratio + +router = APIRouter() + + +async def _acquire_token(): + from app.dataplane.account import _directory as _acct_dir + if _acct_dir is None: + return None, None + from app.control.model.registry import get as get_model + spec = get_model("grok-imagine-image") + if spec is None: + return None, None + acct = await _acct_dir.reserve( + pool_candidates=spec.pool_candidates(), + mode_id=int(spec.mode_id), + now_s_override=now_s(), + ) + if acct is None: + return None, None + return acct.token, acct + + +def _extract_token(value: str | None) -> str: + raw = str(value or "").strip() + if not raw: + return "" + scheme, _, token = raw.partition(" ") + if scheme.lower() == "bearer" and token: + return token.strip() + return raw + + +def _is_allowed(token: str) -> bool: + webui_key = get_webui_key() + if not webui_key: + return is_webui_enabled() + return bool(token) and hmac.compare_digest(token, webui_key) + + +def _websocket_token(websocket: WebSocket) -> str: + return ( + _extract_token(websocket.headers.get("authorization")) + or str(websocket.query_params.get("access_token") or "").strip() + ) + + +@router.websocket("/imagine/ws") +async def imagine_ws(websocket: WebSocket): + if not _is_allowed(_websocket_token(websocket)): + await websocket.close(code=1008) + return + + await websocket.accept() + stop_event = asyncio.Event() + run_task: Optional[asyncio.Task] = None + + async def _send(payload: dict) -> bool: + try: + await websocket.send_text(orjson.dumps(payload).decode()) + return True + except Exception: + return False + + async def _stop_run(): + nonlocal run_task + stop_event.set() + if run_task and not run_task.done(): + run_task.cancel() + try: + await run_task + except Exception: + pass + run_task = None + stop_event.clear() + + async def _run( + prompt: str, + aspect_ratio: str, + nsfw: Optional[bool], + count: int, + quality: str, + ): + from app.dataplane.account import _directory as _acct_dir + from app.dataplane.reverse.transport.imagine_ws import stream_images + + run_id = uuid.uuid4().hex + enable_pro = quality == "quality" + await _send({ + "type": "status", + "status": "running", + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "run_id": run_id, + "count": count, + "quality": quality, + }) + + acct = None + try: + token, acct = await _acquire_token() + if not token: + await _send({ + "type": "error", + "message": "No available tokens.", + "code": "rate_limit_exceeded", + }) + return + + enable_nsfw = nsfw if nsfw is not None else get_config().get_bool("features.enable_nsfw", True) + async for event in stream_images( + token, + prompt, + aspect_ratio=aspect_ratio, + n=count, + enable_nsfw=enable_nsfw, + enable_pro=enable_pro, + ): + if stop_event.is_set(): + return + if not isinstance(event, dict) or event.get("type") == "_meta": + continue + event.setdefault("run_id", run_id) + await _send(event) + if event.get("type") == "error": + return + + if not stop_event.is_set(): + await _send({ + "type": "status", + "status": "completed", + "run_id": run_id, + "count": count, + }) + except asyncio.CancelledError: + pass + except Exception as exc: + logger.warning("Imagine stream error: {}", exc) + await _send({ + "type": "error", + "message": str(exc), + "code": "internal_error", + }) + finally: + if acct and _acct_dir: + await _acct_dir.release(acct) + if stop_event.is_set(): + await _send({"type": "status", "status": "stopped", "run_id": run_id}) + + try: + while True: + try: + raw = await websocket.receive_text() + except (RuntimeError, WebSocketDisconnect): + break + + try: + payload = orjson.loads(raw) + except Exception: + await _send({ + "type": "error", + "message": "Invalid message format.", + "code": "invalid_payload", + }) + continue + + action = payload.get("type") + if action == "start": + prompt = str(payload.get("prompt") or "").strip() + if not prompt: + await _send({ + "type": "error", + "message": "Prompt cannot be empty.", + "code": "invalid_prompt", + }) + continue + aspect_ratio = resolve_aspect_ratio(str(payload.get("aspect_ratio") or "2:3").strip() or "2:3") + quality = str(payload.get("quality") or "speed").strip().lower() + if quality not in {"speed", "quality"}: + quality = "speed" + nsfw = payload.get("nsfw") + if nsfw is not None: + if isinstance(nsfw, str): + nsfw = nsfw.strip().lower() in {"1", "true", "yes", "on"} + else: + nsfw = bool(nsfw) + try: + count = int(payload.get("count") or 6) + except (TypeError, ValueError): + count = 6 + count = max(1, min(count, 6)) + await _stop_run() + run_task = asyncio.create_task(_run(prompt, aspect_ratio, nsfw, count, quality)) + continue + + if action == "stop": + await _stop_run() + continue + + await _send({ + "type": "error", + "message": "Unknown action.", + "code": "invalid_action", + }) + except WebSocketDisconnect: + pass + except Exception as exc: + logger.warning("WebSocket error: {}", exc) + finally: + await _stop_run() + try: + from starlette.websockets import WebSocketState + if websocket.client_state == WebSocketState.CONNECTED: + await websocket.close(code=1000, reason="Server closing connection") + except Exception: + pass diff --git a/app/products/web/webui/pages.py b/app/products/web/webui/pages.py new file mode 100644 index 00000000..8db8b4b3 --- /dev/null +++ b/app/products/web/webui/pages.py @@ -0,0 +1,43 @@ +"""Static page routes for the statics-based WebUI.""" + +from pathlib import Path + +from fastapi import APIRouter, HTTPException +from fastapi.responses import FileResponse + +from app.platform.auth.middleware import is_webui_enabled + +router = APIRouter(include_in_schema=False) + +STATIC_DIR = Path(__file__).resolve().parents[3] / "statics" / "webui" + + +def _serve(filename: str) -> FileResponse: + path = STATIC_DIR / filename + if not path.exists(): + raise HTTPException(status_code=404, detail="Page not found") + return FileResponse(path) + + +@router.get("/webui/chat") +async def webui_chat_page(): + if not is_webui_enabled(): + raise HTTPException(status_code=404, detail="Not Found") + return _serve("chat.html") + + +@router.get("/webui/chatkit") +async def webui_chatkit_page(): + if not is_webui_enabled(): + raise HTTPException(status_code=404, detail="Not Found") + return _serve("chatkit.html") + + +@router.get("/webui/masonry") +async def webui_masonry_page(): + if not is_webui_enabled(): + raise HTTPException(status_code=404, detail="Not Found") + return _serve("masonry.html") + + +__all__ = ["router"] diff --git a/app/products/webui/voice.py b/app/products/web/webui/voice.py similarity index 66% rename from app/products/webui/voice.py rename to app/products/web/webui/voice.py index 72f8a868..6cec9271 100644 --- a/app/products/webui/voice.py +++ b/app/products/web/webui/voice.py @@ -1,15 +1,14 @@ """Voice token endpoint — LiveKit token acquisition.""" -from __future__ import annotations - -from fastapi import APIRouter +from fastapi import APIRouter, Depends from pydantic import BaseModel from app.platform.errors import AppError, RateLimitError, UpstreamError from app.platform.logging.logger import logger from app.platform.runtime.clock import now_s +from app.platform.auth.middleware import verify_webui_key -router = APIRouter() +router = APIRouter(prefix="/webui/api", dependencies=[Depends(verify_webui_key)]) class VoiceTokenResponse(BaseModel): @@ -30,14 +29,11 @@ async def voice_token( if _acct_dir is None: raise RateLimitError("Account directory not initialised") - # Voice uses super pools (ssoBasic/ssoSuper) → try super first, then basic. - from app.dataplane.shared.enums import PoolId + # Voice uses super/basic pools → try super first, then basic, then heavy. from app.control.model.enums import ModeId ts = now_s() - acct = await _acct_dir.reserve(pool_id=int(PoolId.SUPER), mode_id=int(ModeId.AUTO), now_s_override=ts) - if acct is None: - acct = await _acct_dir.reserve(pool_id=int(PoolId.BASIC), mode_id=int(ModeId.AUTO), now_s_override=ts) + acct = await _acct_dir.reserve(pool_candidates=(1, 0, 2), mode_id=int(ModeId.AUTO), now_s_override=ts) if acct is None: raise RateLimitError("No available tokens for voice mode") @@ -50,7 +46,19 @@ async def voice_token( raise UpstreamError("Upstream returned no voice token") return VoiceTokenResponse( token=lk_token, - url="wss://livekit.grok.com", + url=str(data.get("livekitUrl") or "wss://livekit.grok.com"), + participant_name=str( + data.get("participantName") + or data.get("participant_name") + or data.get("identity") + or "" + ), + room_name=str( + data.get("roomName") + or data.get("room_name") + or data.get("room") + or "" + ), ) except AppError: raise diff --git a/app/products/webui/__init__.py b/app/products/webui/__init__.py deleted file mode 100644 index 77383898..00000000 --- a/app/products/webui/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""WebUI products package.""" diff --git a/app/products/webui/files.py b/app/products/webui/files.py deleted file mode 100644 index b9621cb2..00000000 --- a/app/products/webui/files.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Local cached image/video file serving.""" - -from __future__ import annotations - -from pathlib import Path - -import aiofiles.os -from fastapi import APIRouter, HTTPException -from fastapi.responses import FileResponse - -from app.platform.logging.logger import logger - -router = APIRouter() - -_BASE = Path(__file__).resolve().parents[3] / "data" / "tmp" -_IMAGE_DIR = _BASE / "image" -_VIDEO_DIR = _BASE / "video" - -_CACHE_HEADERS = {"Cache-Control": "public, max-age=31536000, immutable"} - - -@router.get("/image/{filename:path}") -async def get_image(filename: str): - if "/" in filename: - filename = filename.replace("/", "-") - - file_path = _IMAGE_DIR / filename - if await aiofiles.os.path.exists(file_path) and await aiofiles.os.path.isfile(file_path): - suffix = file_path.suffix.lower() - content_type = {".png": "image/png", ".webp": "image/webp"}.get(suffix, "image/jpeg") - return FileResponse(file_path, media_type=content_type, headers=_CACHE_HEADERS) - - logger.warning("Image not found: {}", filename) - raise HTTPException(status_code=404, detail="Image not found") - - -@router.get("/video/{filename:path}") -async def get_video(filename: str): - if "/" in filename: - filename = filename.replace("/", "-") - - file_path = _VIDEO_DIR / filename - if await aiofiles.os.path.exists(file_path) and await aiofiles.os.path.isfile(file_path): - return FileResponse(file_path, media_type="video/mp4", headers=_CACHE_HEADERS) - - logger.warning("Video not found: {}", filename) - raise HTTPException(status_code=404, detail="Video not found") diff --git a/app/products/webui/imagine.py b/app/products/webui/imagine.py deleted file mode 100644 index f32a6514..00000000 --- a/app/products/webui/imagine.py +++ /dev/null @@ -1,389 +0,0 @@ -"""Imagine function — WebSocket, SSE fallback, config, session management.""" - -from __future__ import annotations - -import asyncio -import time -import uuid -from typing import Any, Dict, List, Optional - -import orjson -from fastapi import APIRouter, HTTPException, Query, Request, WebSocket, WebSocketDisconnect -from fastapi.responses import StreamingResponse -from pydantic import BaseModel - -from app.platform.auth.middleware import get_function_api_key, is_function_enabled -from app.platform.config.snapshot import get_config -from app.platform.errors import RateLimitError -from app.platform.logging.logger import logger -from app.platform.runtime.clock import now_s -from app.products.openai.image import resolve_aspect_ratio - -router = APIRouter() - -# --------------------------------------------------------------------------- -# Session store (in-memory) -# --------------------------------------------------------------------------- - -IMAGINE_SESSION_TTL = 600 -_SESSIONS: dict[str, dict] = {} -_SESSIONS_LOCK = asyncio.Lock() - - -async def _clean_sessions(now: float) -> None: - expired = [k for k, v in _SESSIONS.items() if now - float(v.get("created_at") or 0) > IMAGINE_SESSION_TTL] - for k in expired: - _SESSIONS.pop(k, None) - - -async def _new_session(prompt: str, aspect_ratio: str, nsfw: Optional[bool]) -> str: - task_id = uuid.uuid4().hex - now = time.time() - async with _SESSIONS_LOCK: - await _clean_sessions(now) - _SESSIONS[task_id] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "nsfw": nsfw, "created_at": now} - return task_id - - -async def _get_session(task_id: str) -> Optional[dict]: - if not task_id: - return None - now = time.time() - async with _SESSIONS_LOCK: - await _clean_sessions(now) - info = _SESSIONS.get(task_id) - if not info: - return None - if now - float(info.get("created_at") or 0) > IMAGINE_SESSION_TTL: - _SESSIONS.pop(task_id, None) - return None - return dict(info) - - -async def _drop_session(task_id: str) -> None: - if task_id: - async with _SESSIONS_LOCK: - _SESSIONS.pop(task_id, None) - - -async def _drop_sessions(task_ids: List[str]) -> int: - if not task_ids: - return 0 - removed = 0 - async with _SESSIONS_LOCK: - for tid in task_ids: - if tid and tid in _SESSIONS: - _SESSIONS.pop(tid, None) - removed += 1 - return removed - - -# --------------------------------------------------------------------------- -# SSE chunk parser -# --------------------------------------------------------------------------- - -def _parse_sse_chunk(chunk: str) -> Optional[Dict[str, Any]]: - if not chunk: - return None - event = None - data_lines: List[str] = [] - for raw in str(chunk).splitlines(): - line = raw.strip() - if not line: - continue - if line.startswith("event:"): - event = line[6:].strip() - continue - if line.startswith("data:"): - data_lines.append(line[5:].strip()) - if not data_lines: - return None - data_str = "\n".join(data_lines) - if data_str == "[DONE]": - return None - try: - payload = orjson.loads(data_str) - except orjson.JSONDecodeError: - return None - if event and isinstance(payload, dict) and "type" not in payload: - payload["type"] = event - return payload - - -# --------------------------------------------------------------------------- -# Account acquisition helper -# --------------------------------------------------------------------------- - -async def _acquire_token(): - from app.dataplane.account import _directory as _acct_dir - if _acct_dir is None: - return None, None - from app.control.model.registry import get as get_model - spec = get_model("grok-image") - if spec is None: - return None, None - ts = now_s() - acct = await _acct_dir.reserve(pool_id=spec.pool_id(), mode_id=int(spec.mode_id), now_s_override=ts) - if acct is None: - return None, None - return acct.token, acct - - -# --------------------------------------------------------------------------- -# WebSocket endpoint -# --------------------------------------------------------------------------- - -@router.websocket("/imagine/ws") -async def imagine_ws(websocket: WebSocket): - session_id = None - task_id = websocket.query_params.get("task_id") - if task_id: - info = await _get_session(task_id) - if info: - session_id = task_id - - ok = True - if session_id is None: - function_key = get_function_api_key() - function_enabled = is_function_enabled() - if not function_key: - ok = function_enabled - else: - key = websocket.query_params.get("function_key") - ok = key == function_key - - if not ok: - await websocket.close(code=1008) - return - - await websocket.accept() - stop_event = asyncio.Event() - run_task: Optional[asyncio.Task] = None - - async def _send(payload: dict) -> bool: - try: - await websocket.send_text(orjson.dumps(payload).decode()) - return True - except Exception: - return False - - async def _stop_run(): - nonlocal run_task - stop_event.set() - if run_task and not run_task.done(): - run_task.cancel() - try: - await run_task - except Exception: - pass - run_task = None - stop_event.clear() - - async def _run(prompt: str, aspect_ratio: str, nsfw: Optional[bool]): - from app.dataplane.reverse.transport.imagine_ws import stream_images - from app.dataplane.account import _directory as _acct_dir - - run_id = uuid.uuid4().hex - await _send({"type": "status", "status": "running", "prompt": prompt, "aspect_ratio": aspect_ratio, "run_id": run_id}) - - while not stop_event.is_set(): - try: - token, acct = await _acquire_token() - if not token: - await _send({"type": "error", "message": "No available tokens.", "code": "rate_limit_exceeded"}) - await asyncio.sleep(2) - continue - - enable_nsfw = nsfw if nsfw is not None else get_config().get_bool("app.enable_nsfw", True) - async for ev in stream_images(token, prompt, aspect_ratio=aspect_ratio, n=6, enable_nsfw=enable_nsfw): - if isinstance(ev, dict): - ev.setdefault("run_id", run_id) - await _send(ev) - - if acct and _acct_dir: - await _acct_dir.release(acct) - - except asyncio.CancelledError: - break - except Exception as e: - logger.warning("Imagine stream error: {}", e) - await _send({"type": "error", "message": str(e), "code": "internal_error"}) - await asyncio.sleep(1.5) - - await _send({"type": "status", "status": "stopped", "run_id": run_id}) - - try: - while True: - try: - raw = await websocket.receive_text() - except (RuntimeError, WebSocketDisconnect): - break - - try: - payload = orjson.loads(raw) - except Exception: - await _send({"type": "error", "message": "Invalid message format.", "code": "invalid_payload"}) - continue - - action = payload.get("type") - if action == "start": - prompt = str(payload.get("prompt") or "").strip() - if not prompt: - await _send({"type": "error", "message": "Prompt cannot be empty.", "code": "invalid_prompt"}) - continue - aspect_ratio = resolve_aspect_ratio(str(payload.get("aspect_ratio") or "2:3").strip() or "2:3") - nsfw = payload.get("nsfw") - if nsfw is not None: - nsfw = bool(nsfw) - await _stop_run() - run_task = asyncio.create_task(_run(prompt, aspect_ratio, nsfw)) - elif action == "stop": - await _stop_run() - else: - await _send({"type": "error", "message": "Unknown action.", "code": "invalid_action"}) - - except WebSocketDisconnect: - pass - except Exception as e: - logger.warning("WebSocket error: {}", e) - finally: - await _stop_run() - try: - from starlette.websockets import WebSocketState - if websocket.client_state == WebSocketState.CONNECTED: - await websocket.close(code=1000, reason="Server closing connection") - except Exception: - pass - if session_id: - await _drop_session(session_id) - - -# --------------------------------------------------------------------------- -# SSE endpoint -# --------------------------------------------------------------------------- - -@router.get("/imagine/sse") -async def imagine_sse( - request: Request, - task_id: str = Query(""), - prompt: str = Query(""), - aspect_ratio: str = Query("2:3"), -): - session = None - if task_id: - session = await _get_session(task_id) - if not session: - raise HTTPException(status_code=404, detail="Task not found") - else: - function_key = get_function_api_key() - function_enabled = is_function_enabled() - if not function_key: - if not function_enabled: - raise HTTPException(status_code=401, detail="Function access is disabled") - else: - key = request.query_params.get("function_key") - if key != function_key: - raise HTTPException(status_code=401, detail="Invalid authentication token") - - if session: - prompt = str(session.get("prompt") or "").strip() - ratio = str(session.get("aspect_ratio") or "2:3").strip() or "2:3" - nsfw = session.get("nsfw") - else: - prompt = (prompt or "").strip() - if not prompt: - raise HTTPException(status_code=400, detail="Prompt cannot be empty") - ratio = resolve_aspect_ratio(str(aspect_ratio or "2:3").strip() or "2:3") - nsfw = request.query_params.get("nsfw") - if nsfw is not None: - nsfw = str(nsfw).lower() in ("1", "true", "yes", "on") - - async def event_stream(): - from app.dataplane.reverse.transport.imagine_ws import stream_images - from app.dataplane.account import _directory as _acct_dir - - try: - run_id = uuid.uuid4().hex - yield f"data: {orjson.dumps({'type': 'status', 'status': 'running', 'prompt': prompt, 'aspect_ratio': ratio, 'run_id': run_id}).decode()}\n\n" - - while True: - if await request.is_disconnected(): - break - if task_id: - alive = await _get_session(task_id) - if not alive: - break - - try: - token, acct = await _acquire_token() - if not token: - yield f"data: {orjson.dumps({'type': 'error', 'message': 'No available tokens.', 'code': 'rate_limit_exceeded'}).decode()}\n\n" - await asyncio.sleep(2) - continue - - enable_nsfw = nsfw if nsfw is not None else get_config().get_bool("app.enable_nsfw", True) - async for ev in stream_images(token, prompt, aspect_ratio=ratio, n=6, enable_nsfw=enable_nsfw): - if isinstance(ev, dict): - ev.setdefault("run_id", run_id) - yield f"data: {orjson.dumps(ev).decode()}\n\n" - - if acct and _acct_dir: - await _acct_dir.release(acct) - - except asyncio.CancelledError: - break - except Exception as e: - logger.warning("Imagine SSE error: {}", e) - yield f"data: {orjson.dumps({'type': 'error', 'message': str(e), 'code': 'internal_error'}).decode()}\n\n" - await asyncio.sleep(1.5) - - yield f"data: {orjson.dumps({'type': 'status', 'status': 'stopped', 'run_id': run_id}).decode()}\n\n" - finally: - if task_id: - await _drop_session(task_id) - - return StreamingResponse( - event_stream(), - media_type="text/event-stream", - headers={"Cache-Control": "no-cache", "Connection": "keep-alive"}, - ) - - -# --------------------------------------------------------------------------- -# Config / session management -# --------------------------------------------------------------------------- - -@router.get("/imagine/config") -async def imagine_config(): - cfg = get_config() - return { - "final_min_bytes": cfg.get_int("image.final_min_bytes", 0), - "medium_min_bytes": cfg.get_int("image.medium_min_bytes", 0), - "nsfw": cfg.get_bool("image.nsfw"), - } - - -class ImagineStartRequest(BaseModel): - prompt: str - aspect_ratio: Optional[str] = "2:3" - nsfw: Optional[bool] = None - - -@router.post("/imagine/start") -async def imagine_start(data: ImagineStartRequest): - prompt = (data.prompt or "").strip() - if not prompt: - raise HTTPException(status_code=400, detail="Prompt cannot be empty") - ratio = resolve_aspect_ratio(str(data.aspect_ratio or "2:3").strip() or "2:3") - task_id = await _new_session(prompt, ratio, data.nsfw) - return {"task_id": task_id, "aspect_ratio": ratio} - - -class ImagineStopRequest(BaseModel): - task_ids: List[str] - - -@router.post("/imagine/stop") -async def imagine_stop(data: ImagineStopRequest): - removed = await _drop_sessions(data.task_ids or []) - return {"status": "success", "removed": removed} diff --git a/app/products/webui/pages.py b/app/products/webui/pages.py deleted file mode 100644 index f14d6475..00000000 --- a/app/products/webui/pages.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Static HTML page serving for admin and webui.""" - -from __future__ import annotations - -from pathlib import Path - -from fastapi import APIRouter, HTTPException -from fastapi.responses import FileResponse, RedirectResponse - -from app.platform.auth.middleware import is_function_enabled - -router = APIRouter(include_in_schema=False) - -STATIC_DIR = Path(__file__).resolve().parents[2] / "assets" - - -def _serve(relative_path: str) -> FileResponse: - file_path = STATIC_DIR / relative_path - if not file_path.exists(): - raise HTTPException(status_code=404, detail="Page not found") - return FileResponse(file_path) - - -# --------------------------------------------------------------------------- -# Admin pages -# --------------------------------------------------------------------------- - -@router.get("/admin") -async def admin_root(): - return RedirectResponse(url="/admin/login") - - -@router.get("/admin/login") -async def admin_login(): - return _serve("admin/pages/login.html") - - -@router.get("/admin/config") -async def admin_config_page(): - return _serve("admin/pages/config.html") - - -@router.get("/admin/cache") -async def admin_cache_page(): - return _serve("admin/pages/cache.html") - - -@router.get("/admin/token") -async def admin_token_page(): - return _serve("admin/pages/token.html") - - -# --------------------------------------------------------------------------- -# WebUI pages -# --------------------------------------------------------------------------- - -@router.get("/") -async def root(): - if is_function_enabled(): - return RedirectResponse(url="/login") - return RedirectResponse(url="/admin/login") - - -@router.get("/login") -async def webui_login(): - if not is_function_enabled(): - raise HTTPException(status_code=404, detail="Not Found") - return _serve("function/pages/login.html") - - -@router.get("/imagine") -async def webui_imagine(): - if not is_function_enabled(): - raise HTTPException(status_code=404, detail="Not Found") - return _serve("function/pages/imagine.html") - - -@router.get("/voice") -async def webui_voice(): - if not is_function_enabled(): - raise HTTPException(status_code=404, detail="Not Found") - return _serve("function/pages/voice.html") - - -@router.get("/video") -async def webui_video(): - if not is_function_enabled(): - raise HTTPException(status_code=404, detail="Not Found") - return _serve("function/pages/video.html") - - -@router.get("/chat") -async def webui_chat(): - if not is_function_enabled(): - raise HTTPException(status_code=404, detail="Not Found") - return _serve("function/pages/chat.html") diff --git a/app/products/webui/router.py b/app/products/webui/router.py deleted file mode 100644 index ad6989bc..00000000 --- a/app/products/webui/router.py +++ /dev/null @@ -1,19 +0,0 @@ -"""WebUI router — slim aggregator for function + static endpoints.""" - -from __future__ import annotations - -from fastapi import APIRouter, Depends - -from app.platform.auth.middleware import verify_function_key -from .voice import router as voice_router -from .imagine import router as imagine_router -from .pages import router as pages_router -from .files import router as files_router - -router = APIRouter() -router.include_router(voice_router, prefix="/function", dependencies=[Depends(verify_function_key)]) -router.include_router(imagine_router, prefix="/function", dependencies=[Depends(verify_function_key)]) -router.include_router(pages_router) # no prefix — serves at root -router.include_router(files_router) # no prefix — serves at root - -__all__ = ["router"] diff --git a/app/statics/admin/account.html b/app/statics/admin/account.html index 6bff4dd3..9c8e38cf 100644 --- a/app/statics/admin/account.html +++ b/app/statics/admin/account.html @@ -3,7 +3,7 @@ <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <title>Grok2API - 账户管理 + Grok2API - 账户管理 @@ -15,43 +15,45 @@ .page-title{ font-size:22px; font-weight:700; line-height:1.2 } .page-sub { font-size:13px; color:var(--fg-muted); margin-top:5px } .page-actions { display:flex; gap:8px; align-items:center; flex-shrink:0 } - - /* Admin header layout */ - .admin-header { background:#FAF9F5; position:sticky; top:0; z-index:100 } - .admin-header-inner { - max-width:1280px; - width:100%; - height:54px; - margin:0 auto; - padding:0 28px; + .section-head { display:flex; - align-items:center; + align-items:baseline; justify-content:space-between; - flex-wrap:nowrap; - gap:0; + gap:12px; + margin:28px 0 14px; } - .admin-brand-wrap { - display:flex; - align-items:center; - gap:8px; - padding-right:20px; - margin-right:20px; - flex:0 0 auto; - white-space:nowrap; + .section-title { + font-size:13px; + font-weight:600; + color:#222; + letter-spacing:.01em; } - .admin-nav { - display:flex; + .page-action-btn { + height:32px; + padding:0 14px; + border-radius:999px; + display:inline-flex; align-items:center; - gap:0; - flex:1 1 auto; - min-width:0; + justify-content:center; + gap:6px; + font-size:13px; + font-weight:600; + border:1px solid #e6e6e6; + background:#fafafa; + color:#444; } - .admin-header-right { - display:flex; - align-items:center; - gap:8px; - flex:0 0 auto; - white-space:nowrap; + .page-action-btn:hover { + background:#f3f3f3; + border-color:#dcdcdc; + } + .page-action-btn-primary { + background:#111; + border-color:#111; + color:#fff; + } + .page-action-btn-primary:hover { + background:#222; + border-color:#222; } /* Stats */ @@ -105,52 +107,449 @@ } .stat-muted { color:#a1a1aa !important; } - /* Filter tabs — pill style */ - .filter-bar { display:flex; align-items:center; gap:0; background:#efefef; padding:3px; border-radius:24px; align-self:flex-start; margin-bottom:16px } - .ftab { height:30px; padding:0 14px; border-radius:20px; font-size:13px; font-weight:500; color:var(--fg-muted); display:flex; align-items:center; gap:5px; transition:background .15s,color .15s; white-space:nowrap } - .ftab:hover { color:var(--fg) } - .ftab.active { background:#fff; color:var(--fg); box-shadow:0 1px 3px rgba(0,0,0,.1) } - .ftab-n { font-size:12px; font-weight:600 } - .ftab-n.c-green { color:#16a34a } - .ftab-n.c-orange { color:#ea580c } - .ftab-n.c-red { color:#dc2626 } - .ftab-n.c-purple { color:#7c3aed } + /* Filters */ + .filter-bar { + display:flex; + flex-direction:column; + align-items:flex-start; + gap:10px; + margin-bottom:16px; + width:100%; + } + .filter-group { + display:flex; + align-items:center; + gap:8px; + flex-wrap:wrap; + } + .filter-label { + width:52px; + flex:0 0 52px; + font-size:11px; + font-weight:600; + color:#9a9a9a; + letter-spacing:.01em; + text-align:right; + white-space:nowrap; + } + .filter-chip { + height:30px; + min-width:84px; + padding:0 12px; + border-radius:999px; + font-size:12px; + font-weight:500; + color:#8f8f8f; + background:#f5f5f5; + display:flex; + align-items:center; + justify-content:space-between; + gap:6px; + transition:background .15s, color .15s; + white-space:nowrap; + flex:0 0 auto; + } + .filter-chip:hover { color:#555; background:#f1f1f1 } + .filter-chip.active { + background:#111; + color:#fff; + } + .filter-chip-count { + min-width:18px; + height:18px; + padding:0 5px; + border-radius:999px; + background:rgba(255,255,255,.72); + font-size:11px; + font-weight:600; + color:inherit; + display:inline-flex; + align-items:center; + justify-content:center; + font-variant-numeric:tabular-nums; + } + .filter-chip.active .filter-chip-count { + background:rgba(255,255,255,.16); + color:#fff; + } + .filter-chip-count.is-green, + .filter-chip-count.is-orange, + .filter-chip-count.is-red, + .filter-chip-count.is-purple { color:inherit } /* Toolbar row above table */ .table-toolbar { display:flex; align-items:center; gap:8px; margin-bottom:8px; flex-wrap:wrap } .table-toolbar-left { flex:1 } + .table-toolbar-actions { + display:flex; + align-items:center; + gap:8px; + flex-wrap:wrap; + } + .toolbar-action { + height:28px; + padding:0 12px; + border-radius:999px; + background:#fafafa; + font-size:12px; + font-weight:500; + color:#5f5f5f; + } + .toolbar-action:hover { + background:#f3f3f3; + } + .toolbar-action-danger { + color:#b42318; + background:#fff5f4; + border-color:#f3d2cf; + } + .toolbar-action-danger:hover { + background:#feeceb; + border-color:#eab8b3; + } + .toolbar-page-size { + width:94px !important; + height:28px; + border-radius:999px; + font-size:12px; + background:#fafafa; + border-color:transparent; + } /* Table */ - .table-card { background:var(--bg-card); border:1px solid var(--border); border-radius:14px; overflow:hidden } + .table-card { + background:#fff; + border:none; + border-radius:14px; + overflow-x:auto; + overflow-y:hidden; + -webkit-overflow-scrolling:touch; + } + .table-card > table { width:max-content; min-width:100%; border-collapse:collapse } + .table-freeze-last { + --table-sticky-bg:#fff; + --table-sticky-hover-bg:#fdfdfd; + } table { width:100%; border-collapse:collapse } - th { background:var(--bg-card); font-size:12px; font-weight:500; color:var(--fg-muted); padding:10px 16px; text-align:left; border-bottom:1px solid var(--border) } - td { font-size:13px; padding:12px 16px; border-bottom:1px solid var(--border); vertical-align:middle } + th { + background:#fff; + font-size:11px; + font-weight:500; + color:#9b9b9b; + padding:11px 16px; + text-align:left; + border-bottom:none; + letter-spacing:.01em; + } + td { + font-size:13px; + padding:13px 16px; + border-bottom:none; + vertical-align:middle; + color:#3f3f3f; + } tr:last-child td { border-bottom:none } - tr:hover td { background:#fafafa } + tr:hover td { background:#fdfdfd } + .table-card .badge { + display:inline-flex; + align-items:center; + height:20px; + padding:0 8px; + border-radius:999px; + font-size:11px; + font-weight:500; + border:none; + } + .table-card .badge-basic { + color:#6d6d6d; + background:#f7f7f7; + } + .table-card .badge-super { + color:#4c76b2; + background:#f1f6fc; + } + .table-card .badge-heavy { + color:#b07a45; + background:#fbf5ed; + } + .table-card .badge-active { + color:#3e8f69; + background:#f2f8f4; + } + .table-card .badge-cooling { + color:#b47a3d; + background:#fbf5ed; + } + .table-card .badge-expired, + .table-card .badge-invalid, + .table-card .badge-failed { + color:#b66a63; + background:#fbf3f2; + } + .table-center { text-align:center } + .table-center .badge { margin:0 auto } + .token-stack { + display:flex; + align-items:center; + gap:8px; + min-width:0; + } + .row-actions { + display:flex; + align-items:center; + gap:10px; + flex-wrap:wrap; + } + .row-icon-btn { + width:22px; + height:22px; + display:inline-flex; + align-items:center; + justify-content:center; + color:#9a9a9a; + flex:0 0 auto; + } + .row-icon-btn svg { + width:13px; + height:13px; + stroke:currentColor; + stroke-linecap:round; + stroke-linejoin:round; + fill:none; + } + .row-icon-btn:hover { color:#555 } + .row-icon-btn.is-loading { + color:#555; + pointer-events:none; + } + .row-icon-btn.is-loading svg { + animation:spin .85s linear infinite; + } + .row-action { + color:#929292; + font-size:11px; + font-weight:500; + display:inline-flex; + align-items:center; + justify-content:center; + } + .row-action:hover { color:#555 } + .row-action:disabled { + opacity:1; + cursor:default; + } + .row-action-danger { + color:#b7726a; + } + .row-action-danger:hover { color:#92514b } + .row-icon-danger { color:#b7726a } + .row-icon-danger:hover { color:#92514b } + .row-action-static { + color:#8b6bc7; + } + .admin-tooltip { + position:fixed; + left:0; + top:0; + z-index:500; + max-width:220px; + padding:6px 8px; + border-radius:8px; + background:rgba(17,17,17,.94); + color:#fff; + font-size:11px; + line-height:1.35; + white-space:normal; + pointer-events:none; + opacity:0; + transform:translate3d(0,0,0); + transition:opacity .08s ease; + } + .admin-tooltip.show { opacity:1 } + .row-nsfw-btn { + width:22px; + height:22px; + display:inline-flex; + align-items:center; + justify-content:center; + color:#9a9a9a; + flex:0 0 auto; + } + .row-nsfw-btn:hover { color:#555 } + .row-nsfw-btn.is-on { color:#b7726a } + .row-nsfw-btn.is-on:hover { color:#92514b } + .row-nsfw-btn svg { + width:15px; + height:15px; + overflow:visible; + } + .row-nsfw-btn circle, + .row-nsfw-btn path { + stroke:currentColor; + stroke-width:1.7; + stroke-linecap:round; + stroke-linejoin:round; + fill:none; + } + .row-nsfw-btn text { + fill:currentColor; + font-family:var(--font-sans); + font-size:7.2px; + font-weight:700; + text-anchor:middle; + dominant-baseline:central; + } + .table-card .empty-state { + padding:48px 16px; + color:#8a8a8a; + font-size:13px; + } + @keyframes spin { + from { transform:rotate(0deg) } + to { transform:rotate(360deg) } + } /* Quota pills in table cell */ - .quota-cell { display:flex; gap:4px; align-items:center } - .q-pill { font-size:11px; font-weight:600; padding:2px 6px; border-radius:5px } - .q-a { background:#eff6ff; color:#2563eb } - .q-f { background:#f0fdf4; color:#16a34a } - .q-e { background:#faf5ff; color:#7c3aed } - .q-z { background:#f4f4f5; color:#aaa } + .quota-cell { display:flex; gap:8px; align-items:center } + .q-pill { + height:20px; + font-size:11px; + font-weight:500; + padding:0 7px; + border-radius:999px; + display:inline-flex; + align-items:center; + } + .q-a { background:#f1f6fd; color:#5d7fb2 } + .q-f { background:#f2f8f4; color:#4c9168 } + .q-e { background:#f7f3fb; color:#8d6bbd } + .q-h { background:#fff4ed; color:#b0632a } + .q-z { background:#f6f6f6; color:#a0a0a6 } /* Token monospace */ .tok { font-family:ui-monospace,monospace; font-size:12px; color:#333 } /* Pagination */ - .pagi { display:flex; align-items:center; gap:6px; padding:12px 16px; border-top:1px solid var(--border) } - .pagi-info { font-size:13px; color:var(--fg-muted) } + .pagi { display:flex; align-items:center; gap:6px; padding:12px 16px; border-top:none } + .pagi-meta { display:flex; align-items:center; gap:8px } + .pagi-page { + min-width:54px; + height:28px; + padding:0 10px; + border-radius:999px; + background:#f5f5f5; + font-size:12px; + font-weight:600; + color:#222; + display:inline-flex; + align-items:center; + justify-content:center; + font-variant-numeric:tabular-nums; + } + .pagi-info { font-size:12px; color:var(--fg-muted) } .pagi-btn { width:28px; height:28px; border-radius:6px; font-size:13px; display:inline-flex; align-items:center; justify-content:center; color:var(--fg-muted); transition:background .1s } .pagi-btn:hover { background:var(--border) } .pagi-btn.on { background:var(--fg); color:#fff } .pagi-btn:disabled { opacity:.35; pointer-events:none } + /* Dialogs */ + #modal-import .modal, + #modal-import-file .modal { width:min(440px,92vw) } + #modal-export .modal { + width:min(440px,92vw); + padding-top:14px; + } + #modal-export .modal-title { margin-bottom:6px } + #modal-export .dialog-help { + margin-top:0; + margin-bottom:12px; + } + #modal-export .dialog-body { gap:10px } + #modal-export .dialog-actions { margin-top:12px } + .export-option-btn { + width:100%; + min-height:44px; + height:auto; + padding:10px 14px; + display:flex; + align-items:center; + justify-content:center; + text-align:center; + white-space:normal; + line-height:1.4; + } + .modal { box-shadow:none } + .dialog-body { display:grid; gap:12px } + .dialog-help { + font-size:12px; + color:var(--fg-muted); + margin-top:6px; + margin-bottom:2px; + } + .dialog-field { display:flex; align-items:center; gap:10px } + .dialog-label { + width:40px; + font-size:13px; + color:var(--fg-muted); + white-space:nowrap; + flex:0 0 auto; + } + .dialog-textarea { + min-height:140px; + padding:10px 12px; + border-radius:12px; + resize:vertical; + } + .dialog-actions { + display:flex; + justify-content:flex-end; + gap:8px; + margin-top:18px; + } + .dialog-btn { + height:32px; + padding:0 14px; + border-radius:999px; + background:#fafafa; + color:#444; + font-size:13px; + font-weight:600; + } + .dialog-btn:hover { + background:#f3f3f3; + } + .dialog-btn-primary { + background:#111; + color:#fff; + } + .dialog-btn-primary:hover { + background:#222; + } + .dialog-btn-danger { + color:#b42318; + background:#fff5f4; + } + .dialog-btn-danger:hover { + background:#feeceb; + } + /* Import modal */ - #modal-import-file .modal { width:min(420px,92vw) } .import-file-input { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none } - .import-file-row { display:flex; align-items:center; gap:10px } + .import-file-shell { + height:34px; + display:flex; + align-items:center; + padding:0 10px; + border-radius:8px; + background:#f7f7f7; + cursor:pointer; + transition:background .15s; + flex:1; + min-width:0; + } + .import-file-shell:hover { + background:#f2f2f2; + } .import-file-name { font-size:12px; color:#666; @@ -161,8 +560,6 @@ flex:1; } .import-file-name.empty { color:#999 } - .import-field { display:flex; align-items:center; gap:10px } - .import-field-label { font-size:13px; color:var(--fg-muted); white-space:nowrap } @@ -176,26 +573,30 @@
-
账户列表
-
管理 Grok2API 的 xAI 服务账户池。
+
账户列表
+
管理 Grok2API 的 xAI 服务账户池。
- -
+
+
账户概览
+
+
-
账户总数
+
账户总数
@@ -204,7 +605,7 @@
-
账户正常
+
账户正常
@@ -213,7 +614,7 @@
-
账户限流
+
账户限流
@@ -222,7 +623,7 @@
-
账户失效
+
账户失效
@@ -231,7 +632,7 @@
-
Auto 剩余
+
Auto 剩余
@@ -240,7 +641,7 @@
-
Fast 剩余
+
Fast 剩余
@@ -249,7 +650,7 @@
-
Expert 剩余
+
Expert 剩余
@@ -258,23 +659,59 @@
-
总调用次数
- - +
Heavy 剩余
+ +
-
0
+
0
- +
+
账户明细
+
+ +
- - - - - - +
+ 状态 + + + + +
+
+ 类型 +
+
+
+ NSFW + + + +
@@ -283,37 +720,54 @@ - 第 0/0 页 · 共 0 条 +
+ 0 / 0 + 共 0 条 +
- - - - -
- + + + +
-
+
- - - - - - - + + + + + + + + + @@ -325,20 +779,20 @@
Token类型状态额度 A · F · E调用最近使用操作Token类型状态 + 额度 + + A + F + E + H + + 成功失败成功率最近使用操作
+ + + + + + + + + +
文件名大小修改时间操作
+
+
+ + +
+
+ 在线资产指账户在 Grok 平台侧保存的图片与附件。清理仅影响远端文件,不会删除本地缓存。 +
+ +
+
+ + +
+
+ + +
+
+ + + +
+ + + + + + + + + + diff --git a/app/statics/admin/config.html b/app/statics/admin/config.html new file mode 100644 index 00000000..3120b82d --- /dev/null +++ b/app/statics/admin/config.html @@ -0,0 +1,969 @@ + + + + + + Grok2API - 配置管理 + + + + + + + + +
+ + +
+ +
+
+
配置管理
+
统一管理运行时参数与服务行为。保存后即时生效,部分配置需重启服务。
+
+
+ + +
+
+ + +
+ + +
+ +
+ + +
+
存在未保存的更改
+
+ + +
+
+ + + + + + + + diff --git a/app/statics/admin/header.html b/app/statics/admin/header.html index cb8892d5..f42bca0e 100644 --- a/app/statics/admin/header.html +++ b/app/statics/admin/header.html @@ -1,17 +1,59 @@
- - Grok2API - @Chenyme + + + Grok2API + + @Chenyme
- — - +
+ + +
+
diff --git a/app/statics/css/app.css b/app/statics/css/app.css index 281c1477..83733579 100644 --- a/app/statics/css/app.css +++ b/app/statics/css/app.css @@ -2,14 +2,14 @@ :root { --bg:#fafafa; --bg-card:#fff; --fg:#000; --fg-muted:#666; --fg-subtle:#999; --border:#e5e5e5; --radius:6px; --radius-xl:14px; - --success:#059669; --success-bg:#ecfdf5; --error:#dc2626; --error-bg:#fef2f2; + --success:#059669; --success-bg:#ecfdf5; --error:#dc2626; --error-bg:#fef2f2; --info:#525252; --info-bg:#f5f5f5; --shadow-md:0 4px 16px rgba(0,0,0,.08); --shadow-lg:0 20px 50px rgba(0,0,0,.08); --font-sans:'Geist Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif; } *,*::before,*::after{box-sizing:border-box;margin:0;padding:0} body{font-family:var(--font-sans);background:var(--bg);color:var(--fg);line-height:1.5;-webkit-font-smoothing:antialiased;min-height:100vh} a{color:inherit;text-decoration:none} -button,input{font:inherit;border:none;outline:none;background:none;color:inherit} +button,input,textarea{font:inherit;border:none;outline:none;background:none;color:inherit} button{cursor:pointer} /* Login */ @@ -40,7 +40,14 @@ button{cursor:pointer} .toast-icon{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center;border-radius:50%} .toast-success .toast-icon{background:var(--success-bg);color:var(--success)} .toast-error .toast-icon{background:var(--error-bg);color:var(--error)} +.toast-info .toast-icon{background:var(--info-bg);color:var(--info)} .toast-content{flex:1;font-size:12px;font-weight:500} +.toast-progress-label{font-size:12px;font-weight:500} +.toast-progress-track{height:3px;background:rgba(0,0,0,.08);border-radius:999px;margin-top:5px;overflow:hidden} +.toast-progress-fill{height:100%;background:var(--info);border-radius:999px;transition:width .3s} +.toast-success .toast-progress-fill{background:var(--success)} +.toast-error .toast-progress-fill{background:var(--error)} +.toast-progress-count{font-size:11px;color:#aaa;flex-shrink:0;margin-left:8px;font-variant-numeric:tabular-nums} @keyframes toastIn{from{opacity:0;transform:translateY(16px) scale(.96)}to{opacity:1;transform:none}} @keyframes toastOut{from{opacity:1}to{opacity:0;transform:translateY(8px) scale(.96)}} @@ -50,20 +57,698 @@ button{cursor:pointer} /* Admin layout */ .admin-header{background:#FAF9F5;position:sticky;top:0;z-index:100} -.admin-header-inner{max-width:1280px;width:100%;height:54px;margin:0 auto;padding:0 28px;display:flex;align-items:center;justify-content:space-between;flex-wrap:nowrap;gap:0} -.admin-brand-wrap{display:flex;align-items:center;gap:8px;padding-right:20px;margin-right:20px;flex:0 0 auto;white-space:nowrap} +.admin-header-inner{max-width:1280px;width:100%;height:54px;margin:0 auto;padding:0 28px;display:grid;grid-template-columns:minmax(220px,260px) minmax(0,1fr) minmax(240px,272px);align-items:center;gap:16px} +.webui-header-bar{width:100%;background:#FAF9F5} +.webui-header-inner{max-width:none;padding:0 18px} +.admin-brand-wrap{display:flex;align-items:center;gap:8px;min-width:0;white-space:nowrap} +.admin-brand-link{display:inline-flex;align-items:center;gap:8px;min-width:0;color:inherit} .admin-brand{font-size:14px;font-weight:700} -.admin-username{font-size:12px;color:var(--fg-muted)} -.admin-nav{display:flex;align-items:center;gap:0;flex:1 1 auto;min-width:0} +.admin-username{font-size:12px;color:var(--fg-muted);overflow:hidden;text-overflow:ellipsis} +.admin-nav{display:flex;align-items:center;justify-content:center;gap:0;min-width:0} .admin-nav-link{font-size:14px;color:var(--fg-muted);padding:6px 14px;font-weight:500;transition:color .15s;border-radius:0} .admin-nav-link:hover{color:var(--fg)} .admin-nav-link.active{color:var(--fg);font-weight:600} -.admin-header-right{display:flex;align-items:center;gap:8px;flex:0 0 auto;white-space:nowrap} +.admin-header-right{display:flex;align-items:center;justify-content:flex-end;gap:6px;min-width:0;white-space:nowrap} +.admin-header-version{ + display:inline-flex;align-items:center;height:28px;padding:0 10px;border-radius:999px; + position:relative;background:#f1ece2;color:#6a6459;font-size:11px;font-weight:600;letter-spacing:.02em;flex:0 0 auto; + cursor:pointer;user-select:none +} +.admin-header-version.has-update::after{ + content:"";position:absolute;top:2px;right:-3px;width:7px;height:7px;border-radius:999px;background:#2563eb +} +.admin-header-control{ + height:28px;padding:0 11px;border:0;border-radius:999px;background:transparent;color:#444; + font-size:11px;font-weight:500;transition:background .15s,color .15s +} +.admin-header-control:hover{background:#f1ece2;color:#222} +.admin-header-control:focus{box-shadow:none} +.admin-lang-menu{position:relative;flex:0 0 auto} +.admin-lang-trigger{gap:5px;padding:0 6px 0 8px;min-width:48px;border-radius:10px} +.admin-lang-trigger svg{width:12px;height:12px;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;fill:none} +.admin-lang-trigger-code{font-size:11px;font-weight:700;letter-spacing:.08em;line-height:1} +.admin-lang-popover{ + position:absolute;top:calc(100% + 6px);right:0;min-width:138px;padding:4px;background:#faf9f5; + border:1px solid #ece3d6;border-radius:12px;box-shadow:0 12px 28px rgba(22,20,18,.07); + display:grid;gap:2px;opacity:0;pointer-events:none;transform:translateY(-4px); + transition:opacity .16s ease,transform .16s ease;z-index:140 +} +.admin-lang-menu.open .admin-lang-popover{opacity:1;pointer-events:auto;transform:translateY(0)} +.admin-lang-option{ + width:100%;min-height:30px;padding:0 8px;border-radius:9px;display:grid;grid-template-columns:26px minmax(0,1fr); + align-items:center;gap:8px;text-align:left;color:#2a2722 +} +.admin-lang-option:hover,.admin-lang-option.active{background:#f1ece2} +.admin-lang-option-code{font-size:10px;font-weight:700;letter-spacing:.08em;color:#6a6459} +.admin-lang-option-name{font-size:12px;line-height:1.2;white-space:nowrap} +.admin-header-icon-btn{width:28px;min-width:28px;padding:0;justify-content:center;flex:0 0 auto} +.admin-header-icon-btn svg{width:13px;height:13px;stroke:currentColor;stroke-width:1.9;stroke-linecap:round;stroke-linejoin:round;fill:none} .admin-badge{font-size:11px;font-weight:600;padding:3px 9px;border-radius:20px;border:1px solid;letter-spacing:.04em} .admin-badge-green{color:#16a34a;border-color:#16a34a;background:#f0fdf4} .admin-badge-blue{color:#2563eb;border-color:#2563eb;background:#eff6ff} .admin-main{max-width:1280px;margin:0 auto;padding:24px 28px} +/* WebUI layout */ +.webui-page{min-height:100vh;background:#FAF9F5;color:#171717} +.webui-main{width:100%;max-width:none;margin:0;padding:0} +.webui-chat-layout{ + display:grid;grid-template-columns:284px minmax(0,1fr);gap:0; + height:calc(100vh - 54px);min-height:0;overflow:hidden +} +.webui-chatkit-main{width:100%;max-width:none;margin:0;padding:24px 28px 28px} +.webui-chatkit-mobile-toggle{ + display:none;width:36px;min-width:36px;height:36px;padding:0;border-radius:999px; + align-items:center;justify-content:center;background:#f1ece2;color:#302c27 +} +.webui-chatkit-mobile-toggle svg{ + width:18px;height:18px;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;fill:none; + transition:transform .18s ease +} +.webui-chatkit-mobile-toggle.is-open{background:#ebe5d8;color:#1f1c18} +.webui-chatkit-shell{display:grid;grid-template-columns:252px minmax(0,1fr);gap:44px;min-height:calc(100vh - 106px)} +.webui-chatkit-panel{display:grid;gap:16px;align-content:start} +.webui-chatkit-stage{display:grid;gap:28px;align-content:center} +.webui-chatkit-card,.webui-chatkit-stage-card,.webui-chatkit-log-card{ + background:transparent;border:0;border-radius:0;padding:0 +} +.webui-chatkit-panel-head{display:flex;align-items:flex-start;justify-content:flex-start;gap:12px} +.webui-chatkit-panel-title{ + font-size:30px;line-height:1;font-weight:700;letter-spacing:-.05em;color:#191713 +} +.webui-chatkit-settings{display:grid;gap:8px} +.webui-chatkit-settings-title{font-size:13px;font-weight:700;color:#24201b} +.webui-chatkit-settings-shell{ + display:grid;gap:10px;background:#f0ebe2;border-radius:24px;padding:12px +} +.webui-chatkit-kicker{font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#8f887d} +.webui-chatkit-title{margin:10px 0 0;font-size:36px;line-height:1;font-weight:700;letter-spacing:-.045em} +.webui-chatkit-subtitle{max-width:260px;margin:12px 0 0;font-size:14px;line-height:1.75;color:#7a766e} +.webui-chatkit-section-title{font-size:14px;font-weight:700;color:#1e1c18} +.webui-chatkit-form{display:grid;gap:16px;margin-top:16px} +.webui-chatkit-field{display:grid;gap:6px;font-size:11px;color:#777066} +.webui-chatkit-field-range{padding-top:2px} +.webui-chatkit-range-meta{display:flex;justify-content:flex-end;font-size:12px;color:#555047} +.webui-chatkit-field input[type="range"]{width:100%} +.webui-chatkit-field .input{ + height:34px;border:0;border-radius:12px;background:#faf9f5;padding-left:10px;padding-right:10px;box-shadow:none; + font-size:12px +} +.webui-chatkit-meta-grid{display:grid;grid-template-columns:1fr;gap:10px;margin-top:14px} +.webui-chatkit-meta-item{padding:0 0 10px;border-radius:0;background:transparent;border-bottom:1px solid #f0ece4} +.webui-chatkit-meta-item:last-child{padding-bottom:0;border-bottom:0} +.webui-chatkit-meta-label{font-size:11px;color:#8d8679} +.webui-chatkit-meta-value{margin-top:5px;font-size:13px;font-weight:600;color:#24211d;word-break:break-word} +.webui-chatkit-stage-card{ + min-height:calc(100vh - 300px);display:grid;place-items:center;align-content:center;text-align:center;padding:28px 24px 20px; + background:transparent +} +.webui-chatkit-orb-wrap{display:grid;justify-items:center;gap:20px} +.webui-chatkit-orb{ + --chatkit-level:0; + --bubble-a:#2a2621; + --bubble-b:#e5dfd5; + --bubble-c:#c5bcb0; + --bubble-d:#f2ede3; + --cluster-halo:rgba(255,255,255,.62); + --cluster-shadow:rgba(41,35,29,.08); + width:320px;height:220px;position:relative;display:block;isolation:isolate +} +.webui-chatkit-orb::before{ + content:"";position:absolute;inset:22px 38px;border-radius:999px;pointer-events:none; + background:var(--cluster-halo);filter:blur(34px);opacity:.72; + transform:scale(calc(1 + var(--chatkit-level) * .08)); + transition:transform .18s ease,opacity .18s ease +} +.webui-chatkit-bubble{ + position:absolute;border-radius:999px;pointer-events:none; + box-shadow:0 20px 40px var(--cluster-shadow); + transition:box-shadow .2s ease,opacity .2s ease; + will-change:transform +} +.webui-chatkit-bubble-a{ + left:40px;top:52px;width:132px;height:132px;background:var(--bubble-a); + animation:webui-chatkit-bubble-a 7.8s ease-in-out infinite +} +.webui-chatkit-bubble-b{ + left:144px;top:30px;width:96px;height:96px;background:var(--bubble-b); + animation:webui-chatkit-bubble-b 9.2s ease-in-out infinite +} +.webui-chatkit-bubble-c{ + left:176px;top:104px;width:108px;height:108px;background:var(--bubble-c); + animation:webui-chatkit-bubble-c 8.6s ease-in-out infinite +} +.webui-chatkit-bubble-d{ + left:102px;top:136px;width:76px;height:76px;background:var(--bubble-d); + animation:webui-chatkit-bubble-d 6.9s ease-in-out infinite +} +.webui-chatkit-orb.is-idle{ + --bubble-a:#25211d; + --bubble-b:#e7e1d6; + --bubble-c:#cfc6ba; + --bubble-d:#f4efe7; + --cluster-halo:rgba(255,255,255,.56); + animation:webui-chatkit-idle-float 9.8s ease-in-out infinite +} +.webui-chatkit-orb.is-connecting{ + --bubble-a:#5d4725; + --bubble-b:#efe2b9; + --bubble-c:#d9a85f; + --bubble-d:#fbf4df; + --cluster-halo:rgba(246,222,168,.62); + --cluster-shadow:rgba(109,78,26,.14); + animation:webui-chatkit-connecting-pulse 4.2s ease-in-out infinite +} +.webui-chatkit-orb.is-live{ + --bubble-a:#171511; + --bubble-b:#d9d1c4; + --bubble-c:#7fa592; + --bubble-d:#d6a062; + --cluster-halo:rgba(224,244,235,.52); + --cluster-shadow:rgba(28,61,49,.12); + animation:webui-chatkit-live-float 6.8s ease-in-out infinite +} +.webui-chatkit-orb.is-paused{ + --bubble-a:#34312d; + --bubble-b:#d8d7d2; + --bubble-c:#9aa3a9; + --bubble-d:#ecebe7; + --cluster-halo:rgba(227,231,235,.72); + --cluster-shadow:rgba(61,61,61,.1); + animation:webui-chatkit-paused-hold 8.8s ease-in-out infinite +} +.webui-chatkit-orb.is-output-muted{ + --bubble-a:#2f2724; + --bubble-b:#ead7cf; + --bubble-c:#cf8f79; + --bubble-d:#f5e8dd; + --cluster-halo:rgba(245,220,208,.72); + --cluster-shadow:rgba(88,52,40,.12); + animation:webui-chatkit-muted-pulse 5.4s ease-in-out infinite +} +.webui-chatkit-orb.is-connecting::before{opacity:.82} +.webui-chatkit-orb.is-live::before{opacity:.9} +.webui-chatkit-orb.is-paused::before{opacity:.84} +.webui-chatkit-orb.is-output-muted::before{opacity:.88} +.webui-chatkit-orb.is-live.is-speaking{ + filter:saturate(1.04) +} +.webui-chatkit-orb.is-live.is-speaking::before{ + opacity:.98;transform:scale(calc(1.04 + var(--chatkit-level) * .16)) +} +.webui-chatkit-orb.is-live.is-speaking .webui-chatkit-bubble{ + box-shadow:0 24px 52px rgba(41,35,29,.12) +} +.webui-chatkit-orb.is-error{ + --bubble-a:#241614; + --bubble-b:#d6c2b7; + --bubble-c:#b46f63; + --bubble-d:#d59a7b; + --cluster-halo:rgba(220,171,154,.68); + --cluster-shadow:rgba(100,43,31,.14); + animation:webui-chatkit-error-shift 6.2s ease-in-out infinite +} +.webui-chatkit-badge{height:24px;padding:0 10px;border-radius:999px;display:inline-flex;align-items:center;background:#f5f1e8;color:#5f594f;font-size:11px;font-weight:600} +.webui-chatkit-stage-copy{width:min(100%,540px);display:grid;gap:10px;max-width:540px;margin-top:24px;text-align:center} +.webui-chatkit-stage-title{font-size:30px;line-height:1.05;font-weight:700;letter-spacing:-.05em;color:#1c1a17} +.webui-chatkit-stage-text{font-size:14px;line-height:1.75;color:#6f6a62} +.webui-chatkit-controls{display:flex;justify-content:center;gap:8px;flex-wrap:wrap;margin-top:30px} +.webui-chatkit-icon-btn{ + width:40px;min-width:40px;height:40px;padding:0;border-radius:999px;display:grid;place-items:center; + background:#f6f2ea;color:#2a2824 +} +.webui-chatkit-icon-btn svg{ + width:18px;height:18px;stroke:currentColor;stroke-width:1.9;stroke-linecap:round;stroke-linejoin:round;fill:none +} +.webui-chatkit-icon-btn-primary svg{width:20px;height:20px} +.webui-chatkit-icon-btn-primary{background:#171511;color:#fff} +.webui-chatkit-icon-btn:disabled{opacity:.4} +.webui-chatkit-audio{display:none} +.webui-chatkit-log-card{min-height:0;gap:6px} +.webui-chatkit-log-head{display:flex;align-items:center;justify-content:space-between;gap:12px} +.webui-chatkit-clear{width:24px;min-width:24px;height:24px;background:transparent;color:#8a8377} +.webui-chatkit-clear svg{width:15px;height:15px} +.webui-chatkit-log-shell{ + padding:8px 10px;background:rgba(240,235,226,.55);border-radius:18px +} +.webui-chatkit-log{display:grid;gap:2px;max-height:148px;overflow:auto} +.webui-chatkit-log:empty::before{ + content:attr(data-empty);display:block;padding:8px 0;color:#8c8478;font-size:11px;line-height:1.55; + text-align:left +} +.webui-chatkit-log-item{ + padding:5px 0;border-radius:0;background:transparent;color:#6c6559;font-size:10px;line-height:1.4; + font-family:"Geist Mono","SFMono-Regular",ui-monospace,monospace +} +.webui-chatkit-log-item + .webui-chatkit-log-item{border-top:1px dashed rgba(226,217,204,.7)} +.webui-chatkit-log-item.is-warn{color:#8a641a} +.webui-chatkit-log-item.is-error{color:#a13e31} +@keyframes webui-chatkit-idle-float{ + 0%,100%{transform:translate3d(0,0,0)} + 50%{transform:translate3d(0,-6px,0)} +} +@keyframes webui-chatkit-connecting-pulse{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 35%{transform:translate3d(0,-4px,0) scale(1.018)} + 70%{transform:translate3d(0,1px,0) scale(.992)} +} +@keyframes webui-chatkit-live-float{ + 0%,100%{transform:translate3d(0,0,0)} + 50%{transform:translate3d(0,-4px,0)} +} +@keyframes webui-chatkit-paused-hold{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 50%{transform:translate3d(0,-2px,0) scale(.992)} +} +@keyframes webui-chatkit-muted-pulse{ + 0%,100%{transform:translate3d(0,0,0) scale(1)} + 45%{transform:translate3d(0,-3px,0) scale(1.012)} + 70%{transform:translate3d(0,0,0) scale(.996)} +} +@keyframes webui-chatkit-error-shift{ + 0%,100%{transform:translate3d(0,0,0)} + 50%{transform:translate3d(0,-3px,0)} +} +@keyframes webui-chatkit-bubble-a{ + 0%,100%{transform:translate3d(calc(-10px * var(--chatkit-level)),calc(-6px * var(--chatkit-level)),0) scale(calc(1 + var(--chatkit-level) * .04))} + 50%{transform:translate3d(calc(12px - 14px * var(--chatkit-level)),calc(-10px - 10px * var(--chatkit-level)),0) scale(calc(1.04 + var(--chatkit-level) * .06))} +} +@keyframes webui-chatkit-bubble-b{ + 0%,100%{transform:translate3d(calc(8px * var(--chatkit-level)),calc(-8px * var(--chatkit-level)),0) scale(calc(1 + var(--chatkit-level) * .05))} + 50%{transform:translate3d(calc(-10px + 10px * var(--chatkit-level)),calc(12px - 12px * var(--chatkit-level)),0) scale(calc(1.05 + var(--chatkit-level) * .05))} +} +@keyframes webui-chatkit-bubble-c{ + 0%,100%{transform:translate3d(calc(10px * var(--chatkit-level)),calc(8px * var(--chatkit-level)),0) scale(calc(1 + var(--chatkit-level) * .05))} + 50%{transform:translate3d(calc(-12px + 12px * var(--chatkit-level)),calc(-14px - 8px * var(--chatkit-level)),0) scale(calc(1.03 + var(--chatkit-level) * .06))} +} +@keyframes webui-chatkit-bubble-d{ + 0%,100%{transform:translate3d(calc(-8px * var(--chatkit-level)),calc(8px * var(--chatkit-level)),0) scale(calc(1 + var(--chatkit-level) * .06))} + 50%{transform:translate3d(calc(8px - 10px * var(--chatkit-level)),calc(-8px - 12px * var(--chatkit-level)),0) scale(calc(1.06 + var(--chatkit-level) * .08))} +} +.webui-chat-layout.sidebar-collapsed{grid-template-columns:56px minmax(0,1fr)} +.webui-sidebar{ + background:#FAF9F5;border-right:1px solid #ece8de;padding:10px 12px 14px 16px; + display:grid;grid-template-rows:auto minmax(0,1fr) auto;gap:10px; + height:100%;min-height:0;overflow:hidden +} +.webui-chat-layout.sidebar-collapsed .webui-sidebar{padding:8px 8px 16px} +.webui-sidebar-header{display:flex;align-items:flex-start;justify-content:space-between;min-height:36px;padding:0 2px} +.webui-sidebar-headcopy{min-height:30px;display:flex;align-items:flex-start} +.webui-sidebar-headtitle{font-size:30px;font-weight:700;color:#191713;line-height:1;letter-spacing:-.05em} +.webui-sidebar-headmeta{font-size:12px;color:#9a968e;line-height:1.2} +.webui-sidebar-actions{display:inline-flex;align-items:center;gap:6px;flex:0 0 auto} +.webui-sidebar-toggle{width:28px;height:28px;display:grid;place-items:center;color:#202020} +.webui-sidebar-toggle svg{width:22px;height:22px} +.webui-sidebar-new-btn svg{width:18px;height:18px} +.webui-chat-layout.sidebar-collapsed .webui-sidebar-header{justify-content:center} +.webui-chat-layout.sidebar-collapsed .webui-sidebar-headcopy, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-new-btn, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-create, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-sessions, +.webui-chat-layout.sidebar-collapsed .webui-sidebar-settings{display:none} +.webui-sidebar-create{ + height:42px;border-radius:12px;padding:0 14px;background:#ecebe7;color:#181816; + display:flex;align-items:center;justify-content:flex-start;font-size:14px;font-weight:700 +} +.webui-sidebar-create:hover{background:#e7e5e0} +.webui-sidebar-sessions{display:grid;grid-template-rows:auto minmax(0,1fr);gap:6px;min-height:0} +.webui-session-list{display:grid;gap:3px;align-content:start;overflow:auto;padding-right:4px} +.webui-session-list:empty::before{ + content:attr(data-empty);padding:6px 12px;color:#a09d96;font-size:12px +} +.webui-session-item{ + min-height:30px;border-radius:10px;padding:6px 10px;background:transparent;color:#2d2c29; + text-align:left;font-size:13px;line-height:1.3;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:6px +} +.webui-session-item:hover{background:#efeeea} +.webui-session-item.active{background:#ece9e1} +.webui-session-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.webui-session-actions{display:flex;align-items:center;gap:4px;opacity:0;transition:opacity .15s} +.webui-session-item:hover .webui-session-actions, +.webui-session-item.active .webui-session-actions{opacity:1} +.webui-session-action{ + width:24px;height:24px;border-radius:8px;display:grid;place-items:center;color:#75716b +} +.webui-session-action:hover{background:#e8e6e0;color:#1f1f1d} +.webui-session-action svg{width:14px;height:14px} +.webui-sidebar-settings{display:grid;gap:6px;align-content:start} +.webui-sidebar-caption{font-size:12px;font-weight:600;color:#8f887d;padding:2px 12px 0} +.webui-control{display:grid;padding:0 8px} +.webui-control .input{ + height:34px;border-radius:12px;border:0;background:#efe9de;padding-left:12px;padding-right:12px;box-shadow:none;font-size:12px;color:#201d19 +} +.webui-status{ + display:inline-flex;align-items:center;gap:8px;min-height:18px;font-size:12px;font-weight:600;color:#5f5c57;padding:0 12px +} +.webui-status::before{ + content:"";width:7px;height:7px;border-radius:999px;background:#9ca3af;box-shadow:0 0 0 4px rgba(156,163,175,.12) +} +.webui-sidebar .modal .input{margin-top:0} +.webui-workspace{background:#FAF9F5;min-height:0;height:100%;overflow:hidden} +.webui-chat-pane{ + background:#FAF9F5;display:grid;grid-template-rows:minmax(0,1fr) auto;height:100%;min-height:0;overflow:hidden +} +.webui-thread-shell{padding:6px 24px 0;min-height:0;height:100%;overflow:hidden} +.webui-thread{ + height:100%;min-height:0;overflow:auto;padding:0 6px 16px;background:transparent; + scrollbar-width:thin;scrollbar-color:rgba(17,24,39,.18) transparent +} +.webui-thread::-webkit-scrollbar{width:8px} +.webui-thread::-webkit-scrollbar-thumb{background:rgba(17,24,39,.16);border-radius:999px} +.webui-empty{ + min-height:calc(100vh - 300px);display:grid;place-items:center;padding:28px 12px;color:#6f6a62 +} +.webui-empty-card{width:min(100%,540px);text-align:center;display:grid;gap:10px} +.webui-empty-title{font-size:30px;line-height:1.05;font-weight:700;letter-spacing:-.05em;color:#1c1a17} +.webui-empty-text{font-size:14px;line-height:1.75} +.msg{max-width:860px;margin:0 auto 28px;display:grid;gap:8px} +.msg.user{justify-items:end} +.msg-meta{font-size:11px;color:#a3a099} +.msg-actions{display:flex;align-items:center;justify-content:flex-end;gap:4px} +.msg-actions-assistant{width:min(100%,760px);justify-content:flex-start} +.msg-actions[hidden]{display:none !important} +.msg-action-group{display:flex;align-items:center;gap:4px} +.msg-action-btn{ + width:24px;height:24px;padding:0;border-radius:999px;display:grid;place-items:center;color:#7b776f;line-height:0 +} +.msg-action-btn:hover{background:#f2f0ea;color:#22201c} +.msg-action-btn.active{background:#ece8df;color:#171511} +.msg-action-btn svg{width:14px;height:14px;display:block} +.msg-action-btn-regen svg{width:12px;height:12px} +.msg-card-editing{ + width:min(100%,760px);background:#faf9f6;border:1px solid #e8e3d9;border-radius:18px;padding:14px 14px 12px +} +.msg-edit-textarea{ + width:100%;min-height:52px;resize:none;border:0;background:transparent;color:#171717; + font-size:14px;line-height:1.6;overflow:hidden +} +.msg-edit-textarea:focus{outline:none;box-shadow:none} +.msg-edit-footer{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin-top:10px} +.msg-edit-cancel{ + height:32px;padding:0 10px;border-radius:999px;color:#5f5b55;font-size:13px;font-weight:500 +} +.msg-edit-cancel:hover{background:#f2efe8;color:#1f1d19} +.msg-edit-save{ + height:32px;padding:0 14px;border-radius:999px;background:#111;color:#fff;font-size:13px;font-weight:600 +} +.msg-edit-save:hover{background:#000} +.msg-card{ + width:min(100%,760px);padding:0;background:transparent;line-height:1.7;box-shadow:none;color:#20201e +} +.msg-card-user{white-space:pre-wrap;font-size:14px} +.msg-card-assistant{white-space:normal;font-size:14px} +.msg.user .msg-card{ + width:fit-content;max-width:min(100%,720px); + background:#f5f4f1;color:#141414;border-radius:18px;padding:12px 16px +} +.msg-user-parts{display:grid;gap:10px} +.msg-user-text{white-space:pre-wrap} +.msg-user-gallery{ + display:grid;grid-template-columns:repeat(auto-fit,minmax(136px,196px));gap:10px +} +.msg-user-files{ + display:flex;flex-wrap:wrap;gap:8px +} +.msg-user-file{ + max-width:100%;padding:8px 12px;border-radius:999px;background:#ebe9e4;color:#2b2a27; + font-size:12px;line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis +} +.msg-user-gallery img, +.msg-inline-media img{ + display:block;max-width:100%;max-height:240px;height:auto;border-radius:14px;object-fit:cover +} +.msg-inline-media{margin:0 0 12px} +.msg-card-assistant img{ + display:block;max-width:min(100%,400px);max-height:280px;height:auto;border-radius:14px +} +.msg-card-assistant video{ + display:block;width:min(100%,400px);max-height:300px;border-radius:16px;background:#111 +} +.msg-card-assistant > *:first-child{margin-top:0} +.msg-card-assistant > *:last-child{margin-bottom:0} +.msg-card-assistant p, +.msg-card-assistant ul, +.msg-card-assistant ol, +.msg-card-assistant pre, +.msg-card-assistant blockquote, +.msg-card-assistant h1, +.msg-card-assistant h2, +.msg-card-assistant h3, +.msg-card-assistant h4, +.msg-card-assistant h5, +.msg-card-assistant h6{margin:0 0 12px} +.msg-card-assistant h1, +.msg-card-assistant h2, +.msg-card-assistant h3, +.msg-card-assistant h4, +.msg-card-assistant h5, +.msg-card-assistant h6{line-height:1.3;letter-spacing:-.02em} +.msg-card-assistant h1{font-size:24px} +.msg-card-assistant h2{font-size:20px} +.msg-card-assistant h3{font-size:17px} +.msg-card-assistant ul, +.msg-card-assistant ol{padding-left:22px} +.msg-card-assistant li + li{margin-top:4px} +.msg-card-assistant table{ + width:100%;border-collapse:collapse;margin:0 0 12px;font-size:14px;display:block;overflow-x:auto +} +.msg-card-assistant thead th{ + background:#f5f4f1;color:#2b2925;font-size:12px;font-weight:600;text-transform:none;letter-spacing:0;border-bottom:1px solid #e7e1d7 +} +.msg-card-assistant th, +.msg-card-assistant td{ + padding:10px 12px;border:1px solid #ece6dc;text-align:left;vertical-align:top;white-space:nowrap +} +.msg-card-assistant hr{ + border:0;border-top:1px solid #ebe5da;margin:18px 0 +} +.msg-card-assistant a{color:#0f62fe;text-decoration:none} +.msg-card-assistant a:hover{text-decoration:underline} +.msg-card-assistant code{ + font-family:'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace; + font-size:.92em;padding:2px 6px;border-radius:8px;background:#f3f1eb +} +.msg-card-assistant pre{ + overflow:auto;padding:14px 16px;border-radius:16px;background:#171717;color:#f7f7f5 +} +.msg-card-assistant pre code{ + padding:0;background:transparent;color:inherit;font-size:13px;line-height:1.7 +} +.msg-card-assistant blockquote{ + padding-left:14px;border-left:3px solid #ddd7cb;color:#6c675f +} +.msg-reasoning{ + width:min(100%,760px);display:grid;gap:10px;padding:2px 0 4px;background:transparent;color:#8b887f;font-size:12px;line-height:1.5 +} +.msg-reasoning[hidden]{display:none !important} +.msg-reasoning-toggle{ + width:max-content;max-width:100%;min-width:0;height:24px;padding:0 2px;border-radius:8px;display:inline-flex;align-items:center;gap:4px; + color:#8a8479;background:transparent;border:0;box-shadow:none; + font-size:12px;font-weight:500;letter-spacing:0;line-height:1;white-space:nowrap +} +.msg-reasoning-toggle:hover{background:transparent;color:#575249} +.msg-reasoning-toggle svg{width:12px;height:12px;flex:0 0 auto;opacity:.72;transition:transform .18s ease,opacity .18s ease} +.msg-reasoning-toggle[aria-expanded="true"] svg{opacity:1} +.msg-reasoning-label{display:block;overflow:hidden;text-overflow:ellipsis} +.msg-reasoning-body{ + margin-left:10px;padding-left:14px;border-left:1.5px solid #ece6da; + white-space:pre-wrap;font-size:12px;line-height:1.8 +} +.msg-reasoning.is-collapsed .msg-reasoning-toggle svg{transform:rotate(-90deg)} +.msg-reasoning.is-collapsed .msg-reasoning-body{display:none} +.webui-composer{ + position:sticky;bottom:0;z-index:2;padding:0 24px 16px;background:linear-gradient(180deg,rgba(250,249,245,0),#FAF9F5 34%);border-top:0;display:flex;flex-direction:column;align-items:center +} +.webui-upload-meta{ + width:min(100%,940px);padding:0 2px 8px;overflow-x:auto;overflow-y:hidden; + scrollbar-width:none;-ms-overflow-style:none +} +.webui-upload-meta::-webkit-scrollbar{display:none} +.webui-upload-meta-row{ + display:inline-flex;align-items:center;gap:8px;min-width:100%;white-space:nowrap +} +.webui-upload-meta-chip{ + display:inline-flex;align-items:center;gap:6px;max-width:220px;height:30px;padding:0 8px 0 12px;border-radius:999px; + background:#f3f1ec;color:#5d5952;font-size:12px;line-height:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; + flex:0 0 auto +} +.webui-upload-meta-chip-label{ + display:block;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap +} +.webui-upload-meta-chip-remove{ + width:18px;height:18px;padding:0;border-radius:999px;display:grid;place-items:center;flex:0 0 auto;color:#7a766e +} +.webui-upload-meta-chip-remove:hover{background:rgba(0,0,0,.06);color:#2b2a27} +.webui-upload-meta-chip-remove svg{width:12px;height:12px} +.webui-input-shell{ + width:min(100%,940px);display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center; + background:#eee7db;border:0;border-radius:999px;padding:8px 10px 8px 12px; + box-shadow:inset 0 1px 0 rgba(255,255,255,.45);outline:none +} +.webui-upload-btn{ + width:30px;height:30px;border-radius:999px;color:#4b463f;display:grid;place-items:center;flex:0 0 auto +} +.webui-upload-btn:hover{background:rgba(0,0,0,.05);color:#1f1c18} +.webui-upload-btn svg{width:18px;height:18px;stroke-width:1.9} +.webui-sendbar{display:flex;align-items:center;justify-content:flex-end;gap:0} +.webui-textarea{ + height:36px;min-height:36px;max-height:none;padding:8px 0 !important;margin:0;display:block;align-self:center;overflow:hidden;resize:none !important; + border-radius:0 !important;border:0 !important;background:transparent !important;line-height:20px;font-size:14px;color:#20201e +} +.webui-textarea:focus{outline:none !important;box-shadow:none !important} +.webui-textarea::placeholder{line-height:20px;color:#8d877d} +.webui-primary-btn{ + width:36px;height:36px;padding:0;border-radius:999px;background:#111;color:#fff;font-size:0;font-weight:700;display:grid;place-items:center;flex:0 0 auto +} +.webui-primary-btn svg{width:18px;height:18px;display:block} +.webui-primary-btn path{stroke:currentColor;stroke-width:2.2;stroke-linecap:round;stroke-linejoin:round} +.webui-primary-btn:disabled{opacity:.45;cursor:default} +.webui-auth-main{ + min-height:calc(100vh - 92px);display:grid;place-items:center;padding:28px 24px 36px +} +.webui-auth-shell{width:min(980px,100%);display:grid;grid-template-columns:minmax(0,1.1fr) minmax(360px,420px);gap:28px;align-items:center} +.webui-auth-copy{display:grid;gap:14px;padding:12px 4px} +.webui-auth-kicker{ + display:inline-flex;align-items:center;gap:8px;font-size:12px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:#6e6a64 +} +.webui-auth-card{ + padding:22px;display:grid;gap:16px;border-radius:28px; + background:rgba(255,255,255,.76);border:1px solid rgba(255,255,255,.76); + backdrop-filter:blur(18px);box-shadow:0 18px 48px rgba(15,23,42,.1) +} +.webui-auth-head{display:grid;gap:6px} +.webui-auth-title{font-size:28px;line-height:1.05;letter-spacing:-.05em;font-weight:700} +.webui-auth-subtitle{font-size:14px;line-height:1.6;color:#66635f} +.webui-auth-form{display:grid;gap:12px} +.webui-auth-form .input{ + height:46px;border-radius:16px;border-color:rgba(17,24,39,.08); + background:rgba(255,255,255,.88) +} +.webui-auth-submit{height:46px;border-radius:16px;font-size:14px} +.webui-auth-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap} +.webui-link{font-size:13px;color:#5e5b56;transition:color .15s} +.webui-link:hover{color:#111} + +.webui-masonry-main{width:100%;max-width:none;padding:18px 24px 24px} +.webui-masonry-shell{ + width:100%;max-width:none;margin:0;display:grid;grid-template-rows:auto minmax(0,1fr) auto;gap:16px; + min-height:calc(100vh - 96px) +} +.webui-masonry-head{display:flex;align-items:flex-start;justify-content:flex-start;gap:12px} +.webui-masonry-title{font-size:30px;line-height:1;font-weight:700;letter-spacing:-.05em;color:#191713} +.webui-masonry-feed{min-height:0;overflow:auto;padding-right:4px;display:grid;align-content:start;gap:24px} +.webui-masonry-empty{ + min-height:calc(100vh - 300px);display:grid;place-items:center;padding:28px 12px;color:#6f6a62 +} +.webui-masonry-empty[hidden]{display:none !important} +.webui-masonry-empty-card{width:min(100%,540px);text-align:center;display:grid;gap:10px} +.webui-masonry-empty-title{font-size:30px;line-height:1.05;font-weight:700;letter-spacing:-.05em;color:#1c1a17} +.webui-masonry-empty-text{font-size:14px;line-height:1.75} +.webui-masonry-batch{display:grid;gap:14px} +.webui-masonry-batch-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px} +.webui-masonry-batch-prompt{ + font-size:16px;font-weight:600;line-height:1.55;color:#181614;word-break:break-word;max-width:760px +} +.webui-masonry-batch-meta{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap} +.webui-masonry-batch-chip{ + height:24px;padding:0 10px;border-radius:999px;display:inline-flex;align-items:center;background:#f1eee7; + color:#625c52;font-size:11px;font-weight:600;white-space:nowrap +} +.webui-masonry-grid{ + --masonry-columns: 6; + display:grid; + grid-template-columns:repeat(var(--masonry-columns), minmax(0,1fr)); + gap:12px +} +.webui-masonry-tile{ + position:relative;display:block;margin:0;border-radius:14px;overflow:hidden; + background:transparent;box-shadow:none +} +.webui-masonry-tile-body{ + min-height:0;aspect-ratio:var(--tile-aspect, 1 / 1);display:grid;place-items:center;background: + radial-gradient(circle at top,rgba(255,255,255,.48),transparent 56%), + linear-gradient(180deg,#f3efe7 0%,#ece6db 100%) +} +.webui-masonry-tile.is-pending .webui-masonry-tile-body{ + background: + radial-gradient(circle at 50% 14%,rgba(255,255,255,.62),transparent 48%), + linear-gradient(180deg,#f2ede4 0%,#e9e2d6 100%) +} +.webui-masonry-tile.is-ready .webui-masonry-tile-body{min-height:0;background:transparent} +.webui-masonry-tile.is-filtered .webui-masonry-tile-body{background:#ede8df} +.webui-masonry-tile-link{display:block} +.webui-masonry-tile img{display:block;width:100%;height:auto;aspect-ratio:var(--tile-aspect, auto);object-fit:cover} +.webui-masonry-tile-badge{ + position:absolute;top:10px;left:10px;z-index:1;display:inline-flex;align-items:center;justify-content:center; + color:rgba(78,72,64,.72);font-size:10px;font-weight:700;letter-spacing:.02em +} +.webui-masonry-tile-label{ + display:inline-flex;align-items:center;justify-content:center; + color:#6b6459;font-size:12px;font-weight:600 +} +.webui-masonry-tile-progress{ + width:min(74%,124px);display:grid;gap:9px;padding:0;background:transparent;backdrop-filter:none +} +.webui-masonry-tile-progress-value{ + font-size:22px;line-height:1;font-weight:700;color:#4f493f;letter-spacing:-.045em;text-align:center +} +.webui-masonry-tile-progress-track{ + height:3px;border-radius:999px;background:rgba(98,89,78,.12);overflow:hidden +} +.webui-masonry-tile-progress-fill{ + height:100%;border-radius:999px;background:linear-gradient(90deg,#514b42 0%,#82786b 100%);transition:width .25s ease +} +.webui-masonry-composer{ + position:sticky;bottom:0;z-index:2;padding-top:8px;background:linear-gradient(180deg,rgba(250,249,245,0),#faf9f5 30%) +} +.webui-masonry-input-shell{ + width:min(100%,1040px);margin:0 auto;display:grid;gap:12px; + background:#f0ebe2;border-radius:28px;padding:14px 14px 12px; + box-shadow:0 10px 30px rgba(24,22,20,.05), inset 0 1px 0 rgba(255,255,255,.38) +} +.webui-masonry-controls{display:flex;align-items:center;gap:8px;flex-wrap:wrap;min-width:0} +.webui-masonry-toggle{ + height:32px;padding:3px;border-radius:999px;display:inline-flex;align-items:center;gap:1px; + background:#faf9f5 +} +.webui-masonry-toggle-btn{ + min-width:56px;height:26px;padding:0 9px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center; + color:#7d786f;font-size:10px;font-weight:600;transition:background .15s ease,color .15s ease,box-shadow .15s ease +} +.webui-masonry-toggle-btn.is-active{ + background:#111;color:#fff;box-shadow:none +} +.webui-masonry-toggle-btn:disabled{opacity:.45;cursor:default} +.webui-masonry-ratio{ + width:96px;height:32px;padding:0 10px;border-radius:999px;display:grid;grid-template-columns:1fr 2fr;align-items:center;column-gap:6px;background:#faf9f5; +} +.webui-masonry-ratio-icon{ + width:10px;height:18px;border-radius:4px;background:#5f5a52;display:block;justify-self:center +} +.webui-masonry-ratio[data-ratio="1:1"] .webui-masonry-ratio-icon{width:15px;height:15px;border-radius:4px} +.webui-masonry-ratio[data-ratio="3:2"] .webui-masonry-ratio-icon{width:18px;height:12px;border-radius:4px} +.webui-masonry-ratio[data-ratio="16:9"] .webui-masonry-ratio-icon{width:19px;height:11px;border-radius:4px} +.webui-masonry-ratio[data-ratio="2:3"] .webui-masonry-ratio-icon{width:11px;height:18px;border-radius:4px} +.webui-masonry-ratio[data-ratio="9:16"] .webui-masonry-ratio-icon{width:10px;height:19px;border-radius:4px} +.webui-masonry-ratio .input{ + width:100%;min-width:0;height:26px;padding:0 14px 0 0;border:0;border-radius:0;background:transparent;box-shadow:none; + font-size:10px;font-weight:600;color:#111;background-position:right 0 center;background-size:10px 10px;text-align:left +} +.webui-masonry-ratio .input:focus{ + outline:none !important; + box-shadow:none !important; +} +.webui-masonry-toolbar{ + display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0 +} +.webui-masonry-actions{display:flex;align-items:center;justify-content:flex-end;flex:0 0 auto} +.webui-masonry-send{ + width:34px;min-width:34px;height:34px;padding:0;border-radius:999px; + font-size:10px;font-weight:700;display:inline-flex;align-items:center;justify-content:center +} +.webui-masonry-send svg{width:14px;height:14px;display:block;fill:none} +.webui-masonry-send path{stroke:currentColor;stroke-width:2.1;stroke-linecap:round;stroke-linejoin:round} +.webui-masonry-send rect{stroke:currentColor;stroke-width:2.1;stroke-linecap:round;stroke-linejoin:round;fill:none} + /* Stat cards */ .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:20px} .stat-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-xl);padding:16px 18px} @@ -79,8 +764,15 @@ button{cursor:pointer} .tab-count{margin-left:4px;font-size:11px;opacity:.7} /* Table */ -.table-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-xl);overflow:hidden} +.table-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-xl);overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch} .table-wrap{overflow-x:auto} +.table-card>table{width:max-content;min-width:100%;border-collapse:collapse} +.table-freeze-last{--table-sticky-bg:var(--bg-card);--table-sticky-hover-bg:var(--bg)} +.table-freeze-last th:last-child, +.table-freeze-last td:last-child{position:sticky;right:0} +.table-freeze-last th:last-child{z-index:3;background:var(--table-sticky-bg)} +.table-freeze-last td:last-child{z-index:2;background:var(--table-sticky-bg);box-shadow:inset 1px 0 0 rgba(0,0,0,.05)} +.table-freeze-last tr:hover td:last-child{background:var(--table-sticky-hover-bg)} table{width:100%;border-collapse:collapse} th{background:var(--bg);font-size:11px;font-weight:600;color:var(--fg-muted);text-transform:uppercase;letter-spacing:.05em;padding:8px 12px;text-align:left;border-bottom:1px solid var(--border);white-space:nowrap} td{font-size:12px;padding:10px 12px;border-bottom:1px solid var(--border);vertical-align:middle} @@ -108,6 +800,119 @@ tr:hover td{background:var(--bg)} /* Form elements */ select.input{cursor:pointer;padding-right:28px;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 8px center} textarea.input{height:auto;padding:8px 10px;resize:vertical} +textarea.input.webui-textarea{padding:8px 0 !important;resize:none !important} + +@media (max-width: 960px){ + .admin-header-inner{ + height:auto;padding:10px 12px; + grid-template-columns:minmax(0,1fr) auto; + grid-template-areas: + "brand actions" + "nav nav"; + align-items:start;gap:8px;row-gap:8px + } + .admin-brand-wrap{grid-area:brand;gap:6px;min-height:30px;align-self:center} + .admin-brand-link{min-width:0;max-width:100%} + .admin-brand{font-size:13px;line-height:1} + .admin-nav{ + grid-area:nav;justify-content:flex-start;gap:4px;overflow-x:auto;overflow-y:hidden; + padding:0 0 2px;scrollbar-width:none;-ms-overflow-style:none;white-space:nowrap; + align-self:start + } + .admin-nav::-webkit-scrollbar{display:none} + .admin-nav-link{ + flex:0 0 auto;padding:6px 10px;font-size:13px;line-height:1;border-radius:999px;background:transparent + } + .admin-nav-link.active{background:#efe8dc} + .admin-header-right{grid-area:actions;gap:4px;align-self:center} + .admin-header-version{height:30px;padding:0 8px;font-size:10px} + .admin-header-version.has-update::after{top:6px;right:4px} + .admin-header-control{height:30px} + .admin-lang-trigger{min-width:44px;padding:0 5px 0 7px} + .admin-header-icon-btn{width:30px;min-width:30px} + .admin-username{display:none} + .webui-chat-layout,.webui-auth-shell,.webui-chatkit-shell{grid-template-columns:1fr} + .webui-chat-layout{height:calc(100vh - 54px);min-height:0} + .webui-chatkit-main{position:relative;padding:14px 12px 18px} + .webui-chatkit-mobile-toggle{display:inline-flex;position:absolute;top:14px;left:12px;right:auto;z-index:5} + .webui-sidebar{grid-template-rows:auto minmax(0,1fr) auto;padding:8px 12px 14px;height:100%} + .webui-thread-shell{padding:6px 12px 0} + .webui-composer{padding:0 12px 12px} + .webui-input-shell{grid-template-columns:1fr;gap:8px;border-radius:22px;padding:10px 12px} + .webui-upload-btn{display:none} + .webui-sendbar{justify-content:flex-end} + .webui-sidebar-headtitle{font-size:26px} + .webui-masonry-main{padding:14px 12px 18px} + .webui-masonry-shell{gap:14px;min-height:calc(100vh - 84px)} + .webui-masonry-head{display:grid;justify-content:flex-start} + .webui-masonry-title{font-size:26px} + .webui-masonry-batch-head{display:grid} + .webui-masonry-grid{gap:10px} + .webui-masonry-tile{border-radius:12px} + .webui-masonry-input-shell{gap:10px;padding:12px} + .webui-masonry-controls{ + gap:6px;flex:1 1 auto;min-width:0;flex-wrap:nowrap; + overflow-x:auto;overflow-y:hidden;scrollbar-width:none;-ms-overflow-style:none + } + .webui-masonry-controls::-webkit-scrollbar{display:none} + .webui-masonry-toggle{height:30px} + .webui-masonry-toggle-btn{min-width:52px;height:24px;padding:0 7px} + .webui-masonry-ratio{width:90px;height:30px} + .webui-masonry-ratio .input{height:24px} + .webui-masonry-toolbar{ + display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:nowrap + } + .webui-masonry-actions{justify-content:flex-end;flex:0 0 auto} + .webui-masonry-send{width:34px;min-width:34px} + .webui-chatkit-shell{gap:24px;min-height:auto} + .webui-chatkit-panel,.webui-chatkit-stage{gap:18px} + .webui-chatkit-stage{order:1} + .webui-chatkit-stage{min-height:calc(100vh - 148px);align-content:center} + .webui-chatkit-panel{ + position:absolute;top:58px;right:12px;left:auto;width:min(320px,calc(100vw - 24px)); + display:grid;gap:18px;max-height:0;overflow:hidden;opacity:0;pointer-events:none; + padding:0;background:rgba(250,249,245,.96);border:1px solid #e9e2d4;border-radius:20px; + box-shadow:0 16px 44px rgba(22,20,18,.08);backdrop-filter:blur(10px); + transition:opacity .18s ease,transform .18s ease,max-height .22s ease,padding .18s ease; + transform:translateY(-4px);z-index:4 + } + .webui-chatkit-shell.is-mobile-panel-open .webui-chatkit-panel{ + max-height:70vh;opacity:1;pointer-events:auto;padding:16px 16px 14px;overflow:auto;transform:translateY(0) + } + .webui-chatkit-panel-head{padding-right:40px} + .webui-chatkit-panel-title{font-size:26px} + .webui-chatkit-settings-shell{padding:11px} + .webui-chatkit-title{font-size:30px} + .webui-chatkit-field .input{height:32px;border-radius:11px;font-size:12px} + .webui-chatkit-stage-card{min-height:calc(100vh - 300px);padding:12px 0 8px;background:transparent} + .webui-chatkit-orb-wrap{gap:14px} + .webui-chatkit-orb{width:272px;height:188px} + .webui-chatkit-orb::before{inset:20px 32px;filter:blur(28px)} + .webui-chatkit-bubble-a{left:30px;top:44px;width:110px;height:110px} + .webui-chatkit-bubble-b{left:122px;top:22px;width:82px;height:82px} + .webui-chatkit-bubble-c{left:150px;top:90px;width:92px;height:92px} + .webui-chatkit-bubble-d{left:86px;top:116px;width:64px;height:64px} + .webui-chatkit-stage-copy{gap:10px;margin-top:18px} + .webui-chatkit-stage-text{font-size:14px;line-height:1.75} + .webui-chatkit-controls{margin-top:22px} + .webui-chatkit-icon-btn{width:38px;min-width:38px;height:38px} + .webui-chatkit-log-shell{padding:7px 9px} + .webui-chatkit-log{max-height:112px} +} + +@media (max-width: 520px){ + .admin-header-inner{padding:10px 10px 8px} + .admin-brand{font-size:12px} + .admin-nav-link{padding:6px 9px;font-size:12px} + .admin-lang-popover{right:0;min-width:128px} + .admin-header-version{display:none} + .admin-version-modal-row{grid-template-columns:72px minmax(0,1fr);gap:8px} + .webui-empty-title{font-size:24px;line-height:1.05} + .webui-chatkit-stage-title{font-size:24px;line-height:1.05} + .webui-masonry-title{font-size:24px} + .webui-masonry-grid{gap:8px} + .webui-masonry-empty-title{font-size:24px} +} /* Modal */ .modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.3);z-index:300;display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity .2s} @@ -116,6 +921,66 @@ textarea.input{height:auto;padding:8px 10px;resize:vertical} .modal-overlay.open .modal{transform:none} .modal-title{font-size:15px;font-weight:600;margin-bottom:14px} .modal-footer{display:flex;justify-content:flex-end;gap:8px;margin-top:16px} +.admin-version-modal{ + width:min(560px,92vw);max-height:min(80vh,720px); + display:grid;grid-template-rows:auto auto minmax(0,1fr) auto +} +.admin-version-modal-head{ + display:flex;align-items:flex-start;justify-content:space-between;gap:12px +} +.admin-version-modal-head .modal-title{margin-bottom:14px} +.admin-version-modal-badge{ + min-height:28px;padding:0 12px;border-radius:999px;display:inline-flex;align-items:center;flex:0 0 auto; + font-size:12px;font-weight:600;white-space:nowrap +} +.admin-version-modal-badge.is-update{background:#eff6ff;color:#2563eb} +.admin-version-modal-meta{display:grid;gap:8px;margin-bottom:14px} +.admin-version-modal-status{ + min-height:28px;padding:0 12px;border-radius:999px;display:inline-flex;align-items:center;width:max-content; + font-size:12px;font-weight:600 +} +.admin-version-modal-status.is-update{background:#eff6ff;color:#2563eb} +.admin-version-modal-status.is-current{background:#ecfdf5;color:#059669} +.admin-version-modal-status.is-muted{background:#f5f5f5;color:#666} +.admin-version-modal-status.is-hidden{display:none} +.admin-version-modal-row{display:grid;grid-template-columns:84px minmax(0,1fr);gap:10px;align-items:start} +.admin-version-modal-label{font-size:12px;color:#8a8478} +.admin-version-modal-value{font-size:12px;color:#26231f;word-break:break-word} +.admin-version-modal-notes{ + min-height:0;overflow:auto;padding:14px 16px;border-radius:16px;background:#f6f1e7; + color:#2e2a25;font-size:12px;line-height:1.7 +} +.admin-version-modal-notes > :first-child{margin-top:0} +.admin-version-modal-notes > :last-child{margin-bottom:0} +.admin-version-modal-notes h1, +.admin-version-modal-notes h2, +.admin-version-modal-notes h3, +.admin-version-modal-notes h4, +.admin-version-modal-notes h5, +.admin-version-modal-notes h6{margin:0 0 10px;font-size:13px;line-height:1.5;font-weight:700;color:#1f1c18} +.admin-version-modal-notes p{margin:0 0 10px} +.admin-version-modal-notes ul, +.admin-version-modal-notes ol{margin:0 0 10px 18px;padding:0} +.admin-version-modal-notes li + li{margin-top:4px} +.admin-version-modal-notes a{ + text-decoration:underline;text-underline-offset:2px; + overflow-wrap:anywhere;word-break:break-word +} +.admin-version-modal-notes strong{font-weight:700} +.admin-version-modal-notes em{font-style:italic} +.admin-version-modal-notes hr{height:1px;margin:12px 0;border:0;background:rgba(31,28,24,.1)} +.admin-version-modal-notes blockquote{ + margin:0 0 10px;padding-left:12px;border-left:2px solid rgba(31,28,24,.16);color:#6a6459 +} +.admin-version-modal-notes code{ + padding:1px 5px;border-radius:6px;background:rgba(31,28,24,.07); + font-family:'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace;font-size:11px +} +.admin-version-modal-notes pre{ + margin:0 0 10px;padding:10px 12px;border-radius:12px;background:#efe8dc;overflow:auto +} +.admin-version-modal-notes pre code{display:block;padding:0;background:transparent} +.admin-version-modal-link{display:inline-flex;align-items:center} /* Pagination */ .pagination{display:flex;align-items:center;gap:6px;padding:10px 14px;border-top:1px solid var(--border);flex-wrap:wrap} diff --git a/app/statics/i18n/de.json b/app/statics/i18n/de.json new file mode 100644 index 00000000..515d11e1 --- /dev/null +++ b/app/statics/i18n/de.json @@ -0,0 +1,522 @@ +{ + "common": { + "invalidKey": "Ungültiger Schlüssel", + "connectionFailed": "Verbindung fehlgeschlagen" + }, + "login": { + "adminPageTitle": "Grok2API - Admin", + "adminTitle": "Administrationsbereich", + "adminSubtitle": "Geben Sie das Administratorpasswort ein, um fortzufahren", + "adminPlaceholder": "Administratorpasswort", + "continue": "Weiter", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Geben Sie den Zugriffsschlüssel ein", + "webuiPlaceholder": "Zugriffsschlüssel", + "enter": "Öffnen", + "goToAdmin": "Zum Administrationsbereich" + }, + "webui": { + "header": { + "badge": "WebUI", + "login": "Anmelden", + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "login": { + "lead": "Ein leichterer, klarerer Chat-Einstieg im Stil moderner KI-Produkte.", + "sublead": "Geben Sie Ihren Zugriffsschlüssel ein, um den Konversationsbereich zu öffnen, der direkt auf /webui/api/chat/completions basiert.", + "helper": "Mit Sprachumschaltung und nahtloser Zugriffsschlüssel-Prüfung." + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "WebChat", + "eyebrow": "WebUI", + "title": "Chat-Arbeitsbereich", + "subtitle": "Senden Sie Anfragen direkt über /webui/api/chat/completions mit einer ruhigeren und moderneren Chat-Oberfläche.", + "newChat": "Neuer Chat", + "toggleSidebar": "Seitenleiste umschalten", + "upload": "Datei hochladen", + "sessions": "Alle Chats", + "noSessions": "Noch keine Chats", + "untitled": "Neuer Chat", + "rename": "Umbenennen", + "delete": "Löschen", + "edit": "Bearbeiten", + "copy": "Kopieren", + "regenerate": "Neu generieren", + "like": "Gefällt mir", + "dislike": "Gefällt mir nicht", + "reasoning": "Denken", + "save": "Speichern", + "cancel": "Abbrechen", + "confirm": "Bestätigen", + "copySuccess": "Kopiert", + "renamePrompt": "Chat umbenennen", + "deleteConfirm": "Diesen Chat löschen?", + "selectedFiles": "{count} Datei(en): {names}", + "searchChat": "Chats durchsuchen", + "images": "Bilder", + "library": "Bibliothek", + "recent": "Zuletzt", + "recentSample": "Beispielchat: Fragen Sie einfach", + "clear": "Chat leeren", + "modelLabel": "Modell", + "systemLabel": "System", + "statusLabel": "Status", + "systemPlaceholder": "Optional: System-Prompt", + "emptyTitle": "Grok Chat", + "empty": "Beginnen Sie eine neue Unterhaltung, indem Sie eine Nachricht senden.", + "promptPlaceholder": "Geben Sie Ihre Nachricht ein. Enter zum Senden, Shift+Enter für eine neue Zeile.", + "editPlaceholder": "Diese Nachricht bearbeiten", + "stop": "Stoppen", + "send": "Senden", + "statusReady": "Bereit", + "statusConnecting": "Verbinden...", + "statusThinking": "Denkt...", + "statusGenerating": "Generiert...", + "statusDone": "Abgeschlossen", + "statusStopped": "Gestoppt", + "statusFailed": "Fehlgeschlagen", + "statusInitFailed": "Initialisierung fehlgeschlagen", + "userLabel": "Sie", + "assistantLabel": "Grok", + "errors": { + "enterPrompt": "Bitte geben Sie eine Nachricht ein", + "imageUploadsNotSupported": "Die Bilderzeugung akzeptiert hier keine hochgeladenen Referenzen. Verwenden Sie Chat, Bildbearbeitung oder Video mit Referenzbild.", + "imageRequired": "Für die Bildbearbeitung ist mindestens ein Referenzbild erforderlich", + "imageOnly": "Die Bildbearbeitung unterstützt nur Bild-Uploads", + "videoImageOnly": "Die Videogenerierung unterstützt nur Bild-Uploads als Referenz", + "requestFailed": "Anfrage fehlgeschlagen", + "initFailed": "Initialisierung der Chat-Seite fehlgeschlagen" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "eyebrow": "Voice", + "title": "ChatKit", + "subtitle": "Verbinden Sie sich direkt mit Grok LiveKit-Sprachsitzungen und sprechen Sie los, sobald der Mikrofonzugriff erlaubt ist.", + "settings": "Verbindungseinstellungen", + "voiceLabel": "Stimme", + "personalityLabel": "Persönlichkeit", + "speedLabel": "Geschwindigkeit", + "sessionMeta": "Sitzungsinfo", + "roomName": "Raum", + "participantName": "Identität", + "remoteCount": "Remote", + "endpoint": "Endpunkt", + "start": "Start", + "pause": "Pause", + "mute": "Stumm", + "unmute": "Stummschaltung aufheben", + "newSession": "Neue Sitzung", + "logTitle": "Sitzungsprotokoll", + "logEmpty": "Zurzeit im Leerlauf. Sitzungsereignisse erscheinen hier nach der Verbindung.", + "clearLog": "Leeren", + "statusIdle": "Nicht verbunden", + "statusConnecting": "Verbindung wird hergestellt", + "statusLive": "Live", + "statusMuted": "Stumm", + "statusPaused": "Pausiert", + "statusError": "Fehlgeschlagen", + "idleText": "Klicken Sie auf Start, wenn Sie bereit sind, und erlauben Sie den Mikrofonzugriff, um die Sprachsitzung zu starten.", + "connectingText": "Grok-Voice-Sitzung wird angefordert und mit LiveKit verbunden...", + "liveText": "Verbindung hergestellt. Sie können jetzt direkt mit Grok sprechen.", + "mutedText": "Ihr Mikrofon ist stummgeschaltet. Heben Sie die Stummschaltung auf, um das Gespräch fortzusetzen.", + "pausedText": "Die Sitzung ist pausiert. Klicken Sie auf Start, um die aktuelle Sprachsitzung fortzusetzen.", + "errorText": "Die Verbindung konnte nicht hergestellt werden. Prüfen Sie den Mikrofonzugriff und versuchen Sie es erneut.", + "endedText": "Die Sprachsitzung wurde beendet. Sie können jederzeit neu starten.", + "fetchingToken": "Sprach-Token wird angefordert...", + "connected": "Sprachsitzung verbunden", + "disconnected": "Sprachsitzung getrennt", + "panelShow": "Einstellungen & Protokoll", + "panelHide": "Einstellungen & Protokoll ausblenden", + "participantJoined": "Remote-Teilnehmer beigetreten: {identity}", + "participantLeft": "Remote-Teilnehmer getrennt: {identity}", + "trackSubscribed": "Remote-Audio abonniert", + "micEnabled": "Mikrofon aktiviert", + "micMuted": "Mikrofon stumm", + "sessionPaused": "Sprachsitzung pausiert", + "sessionResumed": "Sprachsitzung fortgesetzt", + "outputMuted": "Lautsprecher stumm", + "outputUnmuted": "Lautsprecher aktiviert", + "startingNewSession": "Neue Sprachsitzung wird gestartet...", + "livekitLoadFailed": "LiveKit-SDK konnte nicht geladen werden", + "invalidToken": "Ungültige Antwort für Sprach-Token" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "subtitle": "Eine eigenständige Bild-Waterfall-Seite, die ausschließlich Grok Imagine WebSocket-Generierung verwendet.", + "countLabel": "Fest", + "qualityLabel": "Qualität", + "qualitySpeed": "Tempo", + "qualityQuality": "Qualität", + "modeLabel": "Modus", + "modeRounds": "Runden", + "modeCycles": "Zyklen", + "modeContinuous": "Kontinuierlich", + "modeSingle": "Eine Runde", + "promptPlaceholder": "Beschreiben Sie das gewünschte Bild. Enter zum Generieren, Shift+Enter für eine neue Zeile.", + "generate": "Generieren", + "stop": "Stoppen", + "openImage": "Bild öffnen", + "ratioLabel": "Seitenverhältnis", + "statusReady": "Bereit", + "statusConnecting": "Verbinden...", + "statusGenerating": "Generiert...", + "statusCompleted": "Abgeschlossen", + "statusStopped": "Gestoppt", + "statusFailed": "Fehlgeschlagen", + "emptyTitle": "Mit einem Prompt beginnen", + "emptyText": "Geben Sie einen Prompt ein und die Bilder erscheinen hier der Reihe nach.", + "roundLabel": "Runde {n}", + "batchPending": "Wartet auf Start", + "batchFiltered": "Gefiltert", + "batchError": "Generierung fehlgeschlagen", + "errors": { + "enterPrompt": "Bitte geben Sie einen Prompt ein", + "requestFailed": "Anfrage fehlgeschlagen", + "initFailed": "Initialisierung der Masonry-Seite fehlgeschlagen" + } + } + }, + "header": { + "account": "Kontoverwaltung", + "config": "Konfigurationsverwaltung", + "cache": "Cache-Verwaltung", + "languageLabel": "Sprache", + "switchLanguage": "Sprache wechseln", + "logout": "Abmelden", + "versionDialogTitle": "Version", + "versionCurrent": "Aktuell", + "versionLatest": "Neueste", + "versionPublishedAt": "Veröffentlicht", + "versionUpToDate": "Sie verwenden bereits die neueste Version.", + "versionUpdateAvailable": "Eine neue Version ist verfügbar.", + "versionChecking": "Suche nach Updates...", + "versionUnavailable": "Update-Prüfung fehlgeschlagen.", + "versionNotesEmpty": "Keine Versionshinweise verfügbar.", + "versionOpenRelease": "Release öffnen", + "versionClose": "Schließen" + }, + "account": { + "pageTitle": "Grok2API - Konten", + "nav": "Kontoverwaltung", + "pageHeading": "Kontoverwaltung", + "pageSubtitle": "Verwalten Sie den xAI-Kontopool, den Quotenstatus und den Laufzeitstatus von Grok2API.", + "actionImport": "Konten importieren", + "actionAdd": "Konto hinzufügen", + "sectionOverview": "Übersicht", + "sectionTable": "Kontoliste", + "statTotal": "Konten gesamt", + "statActive": "Aktiv", + "statCooling": "Ratenbegrenzt", + "statInvalid": "Nicht verfügbar", + "statAuto": "Verbleibende Auto-Quote", + "statFast": "Verbleibende Fast-Quote", + "statExpert": "Verbleibende Expert-Quote", + "statHeavy": "Verbleibende Heavy-Quote", + "tabAll": "Alle", + "tabActive": "Aktiv", + "tabCooling": "Ratenbegrenzt", + "tabInvalid": "Nicht verfügbar", + "tabNsfw": "NSFW aktiviert", + "tabNonNsfw": "NSFW deaktiviert", + "filterStatusLabel": "Status", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Typ", + "filterStatusAll": "Alle", + "filterStatusActive": "Aktiv", + "filterStatusCooling": "Ratenbegrenzt", + "filterStatusInvalid": "Nicht verfügbar", + "filterNsfwAll": "Alle", + "filterNsfwEnabled": "Ein", + "filterNsfwDisabled": "Aus", + "filterTypeAll": "Alle", + "export": "Daten exportieren", + "batchNsfw": "NSFW aktivieren", + "batchNsfwDisable": "NSFW deaktivieren", + "batchRefresh": "Auswahl aktualisieren", + "batchDelete": "Auswahl löschen", + "colToken": "Token", + "colType": "Kontotyp", + "colStatus": "Laufzeitstatus", + "colQuota": "Quote", + "colSuccess": "Erfolgreich", + "colFail": "Fehlgeschlagen", + "colRate": "Erfolgsquote", + "colLastUsed": "Zuletzt verwendet", + "colActions": "Aktionen", + "actionCopy": "Kopieren", + "actionRefresh": "Quote aktualisieren", + "actionEdit": "Bearbeiten", + "actionDelete": "Löschen", + "empty": "Keine Konten verfügbar. Verwenden Sie „Konten importieren“ oder „Konto hinzufügen“.", + "pageInfo": "{n} gesamt", + "pageSizeOption": "{n} / Seite", + "backendCount": "{n} Konten", + "backendOffline": "Nicht verfügbar", + "addTitle": "Konto hinzufügen", + "addHint": "Geben Sie ein Token pro Zeile ein. Vorhandene Tokens werden automatisch übersprungen.", + "addPlaceholder": "Tokens einfügen, eines pro Zeile...", + "importTitle": "Konten importieren", + "importHintDefault": "Unterstützt .txt (ein Token pro Zeile) und .json ({pool:[tokens]}).", + "importHintJson": "Die JSON-Datei enthält bereits Informationen zum Kontotyp. Eine zusätzliche Auswahl ist nicht erforderlich.", + "importHintTxt": "Geben Sie ein Token pro Zeile ein. Importierte Tokens werden dem ausgewählten Kontotyp hinzugefügt.", + "labelType": "Typ", + "labelFile": "Datei", + "editTitle": "Konto bearbeiten", + "editTokenPlaceholder": "Aktualisierten Token eingeben", + "exportTitle": "Konten exportieren", + "exportCountPrefix": "", + "exportCountSuffix": " Tokens", + "exportJson": "JSON-Format (vollständig, aber möglicherweise versionsübergreifend nicht kompatibel)", + "exportTxt": "TXT-Format (nur Tokens, mit allen Versionen kompatibel)", + "confirmTitle": "Aktion bestätigen", + "cancel": "Abbrechen", + "confirm": "Bestätigen", + "save": "Änderungen speichern", + "noFile": "Keine Datei ausgewählt", + "copied": "Kopiert", + "copyFailed": "Kopieren fehlgeschlagen", + "loadFailed": "Laden fehlgeschlagen", + "notFound": "Konto nicht gefunden", + "enterToken": "Token eingeben", + "selectFile": "Datei auswählen", + "readFileFailed": "Datei konnte nicht gelesen werden", + "jsonInvalid": "Ungültiges JSON-Format", + "jsonShapeInvalid": "Ungültige JSON-Struktur. Erwartet wurde {pool:[tokens]}.", + "jsonEmpty": "Keine importierbaren Tokens in der JSON-Datei gefunden", + "fileEmpty": "Keine importierbaren Tokens in der Datei gefunden", + "adding": "{n} Konten werden hinzugefügt…", + "addDone": "Konten hinzugefügt", + "addFailed": "Konten konnten nicht hinzugefügt werden", + "importing": "{n} Konten werden importiert…", + "importDone": "Import abgeschlossen", + "importJsonDone": "Import abgeschlossen: {n} Konten verarbeitet", + "importFailed": "Import fehlgeschlagen", + "saving": "Änderungen werden gespeichert…", + "editDone": "Änderungen gespeichert", + "editFailed": "Änderungen konnten nicht gespeichert werden", + "saveResult": "{prefix}: {count} Konten hinzugefügt", + "saveResultSkipped": "{prefix}: {count} hinzugefügt, {skipped} waren bereits vorhanden", + "exportEmpty": "Keine Konten zum Exportieren vorhanden", + "deleteConfirmTitle": "Löschen bestätigen", + "deleteConfirmOne": "{token} löschen?
Diese Aktion kann nicht rückgängig gemacht werden.", + "deleteConfirmMany": "{n} Konten löschen?
Diese Aktion kann nicht rückgängig gemacht werden.", + "deleting": "{n} Konten werden gelöscht…", + "deleteDone": "{n} gelöscht", + "deleteFailed": "Löschen fehlgeschlagen", + "refreshing": "Quoteninformationen für {n} Konten werden aktualisiert…", + "refreshDone": "Aktualisierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "refreshFailed": "Aktualisierung fehlgeschlagen", + "nsfwConfirmTitle": "NSFW aktivieren", + "nsfwConfirmBody": "NSFW für {n} ausgewählte Konten aktivieren?", + "nsfwEnablingOne": "NSFW wird aktiviert…", + "nsfwEnabling": "NSFW wird für {n} Konten aktiviert…", + "nsfwDone": "NSFW-Aktualisierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "nsfwDisablingOne": "NSFW wird deaktiviert…", + "nsfwDisableDone": "NSFW-Deaktivierung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "nsfwEnabledTitle": "Aktiviert", + "operationFailed": "Vorgang fehlgeschlagen", + "unknown": "Unbekannt", + "na": "—", + "pool": { + "autoRecommended": "Automatisch erkennen (empfohlen)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy" + }, + "status": { + "active": "Aktiv", + "cooling": "Ratenbegrenzt", + "expired": "Abgelaufen", + "invalid": "Nicht verfügbar" + } + }, + "config": { + "pageTitle": "Grok2API - Konfigurationsverwaltung", + "pageHeading": "Konfigurationsverwaltung", + "pageSubtitle": "Verwalten Sie Laufzeitparameter und Dienstverhalten zentral. Änderungen werden sofort wirksam, sofern kein Neustart erforderlich ist.", + "resetChanges": "Änderungen zurücksetzen", + "saveChanges": "Änderungen speichern", + "unsavedDefault": "Nicht gespeicherte Änderungen vorhanden", + "unsavedSingle": "1 nicht gespeicherte Änderung vorhanden", + "unsavedMultiple": "{n} nicht gespeicherte Änderungen vorhanden", + "discardChanges": "Änderungen verwerfen", + "randomize": "Wert generieren", + "loadFailed": "Konfiguration konnte nicht geladen werden: {message}", + "saving": "Änderungen werden gespeichert...", + "saveSuccess": "Änderungen gespeichert", + "saveFailed": "Änderungen konnten nicht gespeichert werden: {message}", + "resetSuccess": "Nicht gespeicherte Änderungen verworfen", + "disabledTip": { + "appUrlRequired": "Konfigurieren Sie zuerst die APP-Basis-URL" + }, + "schema": { + "tabs": { + "system": "System", + "features": "Funktionen", + "schedule": "Zeitplanung", + "proxy": "Netzwerk", + "image": "Bildpipeline" + }, + "groups": { + "baseAccess": "Zugriffskontrolle", + "features": "Kernfunktionen", + "mediaFormat": "Medienausgabe", + "refreshSchedule": "Quotenaktualisierung", + "batchConcurrency": "Batch-Konkurrenz", + "egressProxy": "Ausgehender Proxy", + "clearance": "Cloudflare Clearance", + "retry": "Wiederholungsrichtlinie", + "timeouts": "Zeitlimits", + "imageProtocol": "NSFW und Bild-Streaming" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Grok-Nativ)", + "localUrl": "URL (Lokaler Proxy)", + "grokMarkdown": "Markdown (Grok-Nativ)", + "localMarkdown": "Markdown (Lokaler Proxy)", + "base64": "Base64 (Inline)" + }, + "videoFormat": { + "grokUrl": "URL (Grok-Nativ)", + "localUrl": "URL (Lokaler Proxy)", + "grokHtml": "HTML (Grok-Nativ)", + "localHtml": "HTML (Lokaler Proxy)" + }, + "proxyMode": { + "direct": "Direkt", + "singleProxy": "Fester Proxy", + "proxyPool": "Proxy-Pool" + }, + "clearanceMode": { + "none": "Deaktiviert", + "manual": "Manuell", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "APP-Basis-URL" }, + "appKey": { "label": "APP-Zugriffspasswort" }, + "apiKey": { "label": "API-Zugriffsschlüssel" }, + "webuiEnabled": { "label": "WebUI aktivieren" }, + "webuiKey": { "label": "WebUI-Zugriffspasswort" }, + "temporary": { "label": "Temporäre Sitzungen" }, + "memory": { "label": "Konversationsspeicher" }, + "stream": { "label": "Standard-Streaming" }, + "thinking": { "label": "Standard-Ausgabe für Reasoning" }, + "dynamicStatsig": { "label": "Dynamisches Statsig" }, + "enableNsfw": { "label": "NSFW-Erzeugung zulassen" }, + "customInstruction": { "label": "Globale Zusatzanweisung" }, + "imageFormat": { "label": "Bildausgabeformat" }, + "videoFormat": { "label": "Videoausgabeformat" }, + "basicInterval": { "label": "Basic-Aktualisierungsintervall (s)" }, + "superInterval": { "label": "Super-Aktualisierungsintervall (s)" }, + "heavyInterval": { "label": "Heavy-Aktualisierungsintervall (s)" }, + "usageConcurrency": { "label": "Aktualisierungs-Konkurrenz" }, + "onDemandMinInterval": { "label": "Minimales On-Demand-Intervall (s)" }, + "nsfwConcurrency": { "label": "Konkurrenz für NSFW-Aktivierung" }, + "refreshConcurrency": { "label": "Usage-Aktualisierungskonkurrenz" }, + "assetUploadConcurrency": { "label": "Asset-Upload-Konkurrenz" }, + "assetListConcurrency": { "label": "Asset-Listen-Konkurrenz" }, + "assetDeleteConcurrency": { "label": "Asset-Lösch-Konkurrenz" }, + "proxyMode": { "label": "Proxy-Modus" }, + "proxyUrl": { "label": "Primäre Proxy-URL" }, + "resourceProxyUrl": { "label": "Ressourcen-Proxy-URL" }, + "proxyPool": { "label": "Primärer Proxy-Pool" }, + "resourceProxyPool": { "label": "Ressourcen-Proxy-Pool" }, + "skipSslVerify": { "label": "SSL-Prüfung überspringen" }, + "clearanceMode": { "label": "Clearance-Modus" }, + "browserFingerprint": { "label": "Browser-Fingerprint" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cloudflare-Cookies" }, + "flaresolverrUrl": { "label": "FlareSolverr-URL" }, + "challengeTimeout": { "label": "Challenge-Timeout (s)" }, + "refreshInterval": { "label": "Aktualisierungsintervall (s)" }, + "maxRetries": { "label": "Konto-Wiederholungslimit" }, + "retryCodes": { "label": "Retry-Statuscodes" }, + "resetSessionCodes": { "label": "Statuscodes für Sitzungsreset" }, + "chatTimeout": { "label": "Chat-Timeout (s)" }, + "imageTimeout": { "label": "Bild-Timeout (s)" }, + "videoTimeout": { "label": "Video-Timeout (s)" }, + "voiceTimeout": { "label": "Sprach-Timeout (s)" }, + "nsfwTimeout": { "label": "NSFW-Timeout (s)" }, + "assetUploadTimeout": { "label": "Asset-Upload-Timeout (s)" }, + "assetDownloadTimeout": { "label": "Asset-Download-Timeout (s)" }, + "assetListTimeout": { "label": "Asset-Listen-Timeout (s)" }, + "assetDeleteTimeout": { "label": "Asset-Lösch-Timeout (s)" }, + "streamTimeout": { "label": "Streaming-Leerlauf-Timeout (s)" }, + "interRoundWait": { "label": "Wartezeit zwischen Runden (s)" } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Cache-Verwaltung", + "pageHeading": "Cache-Verwaltung", + "pageSubtitle": "Prüfen Sie lokale Cache-Dateien und Online-Assets in einer Oberfläche und bereinigen Sie sie nach Asset-Typ.", + "refresh": "Aktualisieren", + "sectionOverview": "Übersicht", + "statImageCount": "Bild-Cache-Dateien", + "statImageSize": "Bild-Cache-Größe", + "statVideoCount": "Video-Cache-Dateien", + "statVideoSize": "Video-Cache-Größe", + "sectionDetails": "Details", + "tabLocal": "Lokaler Cache", + "tabOnline": "Online-Assets", + "typeImage": "Bilder", + "typeVideo": "Videos", + "typeImageNoun": "Bild", + "typeVideoNoun": "Video", + "clearCurrent": "Aktuellen Cache leeren", + "colFileName": "Dateiname", + "colSize": "Größe", + "colModified": "Zuletzt geändert", + "colActions": "Aktionen", + "colToken": "Token", + "colFileCount": "Dateien", + "onlineAssetLead": "Online-Assets", + "onlineAssetDesc": "sind Bilder und Anhänge, die auf der Grok-Plattform gespeichert sind. Die Bereinigung betrifft nur Remote-Dateien und löscht keinen lokalen Cache.", + "loadAssets": "Asset-Bestand laden", + "clearAll": "Alle löschen", + "cancel": "Abbrechen", + "assetSummary": "{accounts} Konten · {files} Dateien", + "pageIndicator": "Seite {current} / {total}", + "fileCount": "{n} Dateien", + "emptyLocal": "Keine Cache-Dateien gefunden", + "emptyAccounts": "Keine Kontodaten verfügbar", + "actionDelete": "Löschen", + "actionClear": "Bereinigen", + "loadFailed": "Laden fehlgeschlagen: {message}", + "clearLocalConfirm": "Alle lokalen {type}-Cache-Dateien löschen?", + "clearLocalDone": "{count} {type}-Datei(en) entfernt", + "clearFailed": "Bereinigung fehlgeschlagen: {message}", + "deleted": "Gelöscht", + "deleteFailed": "Löschen fehlgeschlagen: {message}", + "loading": "Wird geladen...", + "refreshList": "Liste aktualisieren", + "expand": "Erweitern", + "collapse": "Einklappen", + "clearTokenConfirm": "Alle Online-Assets für {token} löschen?", + "clearTokenDone": "{count} Datei(en) gelöscht", + "clearAllConfirm": "Online-Assets für alle {n} Konten löschen? Diese Aktion kann nicht rückgängig gemacht werden.", + "clearingAssets": "Online-Assets werden bereinigt...", + "clearAllDone": "Bereinigung abgeschlossen: {ok} erfolgreich, {fail} fehlgeschlagen", + "cancelled": "Abgebrochen", + "clearFailedPlain": "Bereinigung fehlgeschlagen", + "connectionInterrupted": "Verbindung unterbrochen", + "startFailed": "Start fehlgeschlagen: {message}", + "cancelInProgress": "Abbruch angefordert. Bitte warten Sie, bis der aktuelle Batch abgeschlossen ist.", + "na": "—" + } +} diff --git a/app/statics/i18n/en.json b/app/statics/i18n/en.json index 6cddf585..92255e44 100644 --- a/app/statics/i18n/en.json +++ b/app/statics/i18n/en.json @@ -16,60 +16,660 @@ "enter": "Enter", "goToAdmin": "Go to Admin Panel" }, + "header": { + "account": "Account Management", + "config": "Configuration Management", + "cache": "Cache Management", + "languageLabel": "Language", + "switchLanguage": "Switch Language", + "logout": "Sign Out", + "versionDialogTitle": "Version", + "versionCurrent": "Current", + "versionLatest": "Latest", + "versionPublishedAt": "Published", + "versionUpToDate": "You are already on the latest version.", + "versionUpdateAvailable": "A new version is available.", + "versionChecking": "Checking for updates...", + "versionUnavailable": "Failed to check for updates.", + "versionNotesEmpty": "No release notes available.", + "versionOpenRelease": "Open Release", + "versionClose": "Close" + }, + "webui": { + "header": { + "badge": "WebUI", + "login": "Sign In", + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "login": { + "lead": "A lighter, cleaner chat surface inspired by modern AI products.", + "sublead": "Enter your access key to open the conversation workspace backed directly by /webui/api/chat/completions.", + "helper": "Includes language switching and seamless access-key verification." + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "WebChat", + "eyebrow": "WebUI", + "title": "Chat Workspace", + "subtitle": "Send requests directly through /webui/api/chat/completions with a calmer, more polished AI chat interface.", + "newChat": "New Chat", + "toggleSidebar": "Toggle sidebar", + "upload": "Upload file", + "sessions": "All Chats", + "noSessions": "No chats yet", + "untitled": "New Chat", + "rename": "Rename", + "delete": "Delete", + "edit": "Edit", + "copy": "Copy", + "regenerate": "Regenerate", + "like": "Like", + "dislike": "Dislike", + "reasoning": "Thinking", + "save": "Save", + "cancel": "Cancel", + "confirm": "Confirm", + "copySuccess": "Copied", + "renamePrompt": "Rename session", + "deleteConfirm": "Delete this session?", + "selectedFiles": "{count} file(s): {names}", + "searchChat": "Search Chats", + "images": "Images", + "library": "Library", + "recent": "Recent", + "recentSample": "Example chat: Ask anything", + "clear": "Clear Chat", + "modelLabel": "Model", + "systemLabel": "System", + "statusLabel": "Status", + "systemPlaceholder": "Optional: System Prompt", + "emptyTitle": "Grok Chat", + "empty": "Start a new conversation by sending a message.", + "promptPlaceholder": "Type your message. Press Enter to send and Shift+Enter for a new line.", + "editPlaceholder": "Edit this message", + "stop": "Stop", + "send": "Send", + "statusReady": "Ready", + "statusConnecting": "Connecting...", + "statusThinking": "Thinking...", + "statusGenerating": "Generating...", + "statusDone": "Completed", + "statusStopped": "Stopped", + "statusFailed": "Failed", + "statusInitFailed": "Initialization failed", + "userLabel": "You", + "assistantLabel": "Grok", + "errors": { + "enterPrompt": "Please enter a message", + "imageUploadsNotSupported": "Image generation does not accept uploaded references here. Use chat, image edit, or video with a reference image.", + "imageRequired": "Image edit requires at least one reference image", + "imageOnly": "Image edit only supports image uploads", + "videoImageOnly": "Video generation only supports image reference uploads", + "requestFailed": "Request failed", + "initFailed": "Chat page initialization failed" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "eyebrow": "Voice", + "title": "ChatKit", + "subtitle": "Connect directly to Grok LiveKit voice sessions and start talking as soon as microphone access is granted.", + "settings": "Connection Settings", + "voiceLabel": "Voice", + "personalityLabel": "Personality", + "speedLabel": "Speed", + "sessionMeta": "Session Info", + "roomName": "Room", + "participantName": "Identity", + "remoteCount": "Remote", + "endpoint": "Endpoint", + "start": "Start", + "pause": "Pause", + "mute": "Mute", + "unmute": "Unmute", + "newSession": "New Session", + "logTitle": "Session Log", + "logEmpty": "Idle for now. Session events will appear here after connection.", + "clearLog": "Clear", + "statusIdle": "Not connected", + "statusConnecting": "Connecting", + "statusLive": "Live", + "statusMuted": "Muted", + "statusPaused": "Paused", + "statusError": "Failed", + "idleText": "Click start when ready and allow microphone access to enter the voice session.", + "connectingText": "Requesting a Grok Voice session and connecting to LiveKit...", + "liveText": "Connection established. You can now speak directly with Grok.", + "mutedText": "Your microphone is muted. Unmute to continue the voice conversation.", + "pausedText": "The session is paused. Click start to continue the current voice session.", + "errorText": "The connection did not complete. Check microphone access and try again.", + "endedText": "The voice session has ended. You can start again at any time.", + "fetchingToken": "Requesting voice token...", + "connected": "Voice session connected", + "disconnected": "Voice session disconnected", + "panelShow": "Settings & Log", + "panelHide": "Hide Settings & Log", + "participantJoined": "Remote participant joined: {identity}", + "participantLeft": "Remote participant left: {identity}", + "trackSubscribed": "Remote audio subscribed", + "micEnabled": "Microphone enabled", + "micMuted": "Microphone muted", + "sessionPaused": "Voice session paused", + "sessionResumed": "Voice session resumed", + "outputMuted": "Speaker muted", + "outputUnmuted": "Speaker unmuted", + "startingNewSession": "Starting a new voice session...", + "livekitLoadFailed": "LiveKit SDK failed to load", + "invalidToken": "Voice token response invalid" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "subtitle": "A dedicated image waterfall page that uses Grok Imagine WebSocket generation only.", + "countLabel": "Fixed", + "qualityLabel": "Quality", + "qualitySpeed": "Speed", + "qualityQuality": "Quality", + "modeLabel": "Mode", + "modeRounds": "Rounds", + "modeCycles": "Cycles", + "modeContinuous": "Continuous", + "modeSingle": "Single round", + "promptPlaceholder": "Describe the image you want. Press Enter to generate and Shift+Enter for a new line.", + "generate": "Generate", + "stop": "Stop", + "openImage": "Open image", + "ratioLabel": "Ratio", + "statusReady": "Ready", + "statusConnecting": "Connecting...", + "statusGenerating": "Generating...", + "statusCompleted": "Completed", + "statusStopped": "Stopped", + "statusFailed": "Failed", + "emptyTitle": "Start with a prompt", + "emptyText": "Enter a prompt and the images will appear here in order.", + "roundLabel": "Round {n}", + "batchPending": "Waiting to start", + "batchFiltered": "Filtered", + "batchError": "Generation failed", + "errors": { + "enterPrompt": "Please enter a prompt", + "requestFailed": "Request failed", + "initFailed": "Masonry page initialization failed" + } + } + }, "account": { "pageTitle": "Grok2API - Accounts", - "nav": "Accounts", - "statTotal": "Total", + "nav": "Account Management", + "pageHeading": "Account Management", + "pageSubtitle": "Manage the xAI account pool, quota posture, and runtime state used by Grok2API.", + "actionImport": "Import Accounts", + "actionAdd": "Add Account", + "sectionOverview": "Overview", + "sectionTable": "Account List", + "statTotal": "Total Accounts", "statActive": "Active", - "statCooling": "Cooling", - "statInvalid": "Invalid", - "statQuota": "Total Quota", - "statCalls": "Total Calls", + "statCooling": "Rate-Limited", + "statInvalid": "Unavailable", + "statAuto": "Auto Quota Remaining", + "statFast": "Fast Quota Remaining", + "statExpert": "Expert Quota Remaining", + "statHeavy": "Heavy Quota Remaining", "tabAll": "All", "tabActive": "Active", - "tabCooling": "Cooling", - "tabInvalid": "Invalid", - "export": "Export", - "import": "Batch Import", + "tabCooling": "Rate-Limited", + "tabInvalid": "Unavailable", + "tabNsfw": "NSFW Enabled", + "tabNonNsfw": "NSFW Disabled", + "filterStatusLabel": "Status", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Type", + "filterStatusAll": "All", + "filterStatusActive": "Active", + "filterStatusCooling": "Rate-Limited", + "filterStatusInvalid": "Unavailable", + "filterNsfwAll": "All", + "filterNsfwEnabled": "On", + "filterNsfwDisabled": "Off", + "filterTypeAll": "All", + "export": "Export Data", "batchNsfw": "Enable NSFW", + "batchNsfwDisable": "Disable NSFW", "batchRefresh": "Refresh Selected", "batchDelete": "Delete Selected", "colToken": "Token", - "colPool": "Pool", - "colStatus": "Status", + "colType": "Account Type", + "colStatus": "Runtime Status", "colQuota": "Quota", - "colCalls": "Calls", + "colSuccess": "Success", + "colFail": "Failed", + "colRate": "Success Rate", "colLastUsed": "Last Used", - "colFails": "Fails", "colActions": "Actions", "actionCopy": "Copy", - "actionRefresh": "Refresh", + "actionRefresh": "Refresh Quota", + "actionEdit": "Edit", "actionDelete": "Delete", - "empty": "No data", - "importTitle": "Batch Import Accounts", - "importHint": "One token per line (new tokens will be appended to the selected pool)", - "importPlaceholder": "Paste tokens, one per line...", - "importPool": "Pool:", + "empty": "No accounts available. Use Import Accounts or Add Account to continue.", + "pageInfo": "{n} total", + "pageSizeOption": "{n} / page", + "backendCount": "{n} accounts", + "backendOffline": "Unavailable", + "addTitle": "Add Account", + "addHint": "Enter one token per line. Existing tokens will be skipped automatically.", + "addPlaceholder": "Paste tokens, one per line...", + "importTitle": "Import Accounts", + "importHintDefault": "Supports .txt (one token per line) and .json ({pool:[tokens]}) formats.", + "importHintJson": "The JSON payload already includes account type metadata. No additional selection is required.", + "importHintTxt": "Enter one token per line. Imported tokens will be appended to the selected account type.", + "labelType": "Type", + "labelFile": "File", + "editTitle": "Edit Account", + "editTokenPlaceholder": "Enter the updated token", + "exportTitle": "Export Accounts", + "exportCountPrefix": "", + "exportCountSuffix": " tokens", + "exportJson": "JSON Format (full fidelity, but may not be compatible across versions)", + "exportTxt": "TXT Format (token-only export, compatible across versions)", + "confirmTitle": "Confirm Action", "cancel": "Cancel", "confirm": "Confirm", + "save": "Save Changes", + "noFile": "No file selected", "copied": "Copied", "copyFailed": "Copy failed", "loadFailed": "Load failed", - "importDone": "Imported {n} tokens", + "notFound": "Account not found", + "enterToken": "Enter a token", + "selectFile": "Select a file", + "readFileFailed": "Failed to read file", + "jsonInvalid": "Invalid JSON format", + "jsonShapeInvalid": "Invalid JSON structure. Expected {pool:[tokens]}.", + "jsonEmpty": "No importable tokens found in the JSON file", + "fileEmpty": "No importable tokens found in the file", + "adding": "Adding {n} accounts…", + "addDone": "Accounts added", + "addFailed": "Failed to add accounts", + "importing": "Importing {n} accounts…", + "importDone": "Import completed", + "importJsonDone": "Import completed: {n} accounts processed", "importFailed": "Import failed", + "saving": "Saving changes…", + "editDone": "Changes saved", + "editFailed": "Failed to save changes", + "saveResult": "{prefix}: {count} accounts added", + "saveResultSkipped": "{prefix}: {count} added, {skipped} already existed", + "exportEmpty": "There are no accounts to export", + "deleteConfirmTitle": "Confirm Delete", + "deleteConfirmOne": "Delete {token}?
This action cannot be undone.", + "deleteConfirmMany": "Delete {n} accounts?
This action cannot be undone.", + "deleting": "Deleting {n} accounts…", "deleteDone": "Deleted {n}", "deleteFailed": "Delete failed", - "refreshing": "Refreshing {n} accounts…", - "refreshDone": "Done: {ok} ok, {fail} failed", + "refreshing": "Refreshing quota data for {n} accounts…", + "refreshDone": "Refresh completed: {ok} succeeded, {fail} failed", "refreshFailed": "Refresh failed", "nsfwConfirmTitle": "Enable NSFW", - "nsfwConfirmBody": "Enable NSFW for {n} selected accounts?", - "nsfwFailed": "Operation failed", - "deleteConfirmTitle": "Confirm Delete", - "statusActive": "Active", - "statusCooling": "Cooling", - "statusExpired": "Expired", - "statusInvalid": "Invalid", - "logout": "Logout" + "nsfwConfirmBody": "Enable NSFW for {n} selected accounts?", + "nsfwEnablingOne": "Enabling NSFW…", + "nsfwEnabling": "Enabling NSFW for {n} accounts…", + "nsfwDone": "NSFW update completed: {ok} succeeded, {fail} failed", + "nsfwDisablingOne": "Disabling NSFW…", + "nsfwDisableDone": "NSFW disable completed: {ok} succeeded, {fail} failed", + "nsfwEnabledTitle": "Enabled", + "operationFailed": "Operation failed", + "unknown": "Unknown", + "na": "—", + "pool": { + "autoRecommended": "Auto Detect (Recommended)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy" + }, + "status": { + "active": "Active", + "cooling": "Rate-Limited", + "expired": "Expired", + "invalid": "Unavailable" + } + }, + "config": { + "pageTitle": "Grok2API - Configuration Management", + "pageHeading": "Configuration Management", + "pageSubtitle": "Manage runtime parameters and service behavior from a single control surface. Changes apply immediately unless a restart is required.", + "resetChanges": "Reset Changes", + "saveChanges": "Save Changes", + "unsavedDefault": "Unsaved changes detected", + "unsavedSingle": "1 unsaved change detected", + "unsavedMultiple": "{n} unsaved changes detected", + "discardChanges": "Discard Changes", + "randomize": "Generate Value", + "loadFailed": "Failed to load configuration: {message}", + "saving": "Saving changes...", + "saveSuccess": "Changes saved", + "saveFailed": "Failed to save changes: {message}", + "resetSuccess": "Unsaved changes discarded", + "disabledTip": { + "appUrlRequired": "Configure the APP Base URL first" + }, + "schema": { + "tabs": { + "system": "System", + "features": "Features", + "schedule": "Scheduling", + "proxy": "Networking", + "image": "Image Pipeline" + }, + "groups": { + "baseAccess": "Access Control", + "features": "Core Features", + "mediaFormat": "Media Output", + "refreshSchedule": "Quota Refresh", + "batchConcurrency": "Batch Concurrency", + "egressProxy": "Egress Proxy", + "clearance": "Cloudflare Clearance", + "retry": "Retry Policy", + "timeouts": "Request Timeouts", + "imageProtocol": "NSFW and Image Streaming" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Grok Native)", + "localUrl": "URL (Local Proxy)", + "grokMarkdown": "Markdown (Grok Native)", + "localMarkdown": "Markdown (Local Proxy)", + "base64": "Base64 (Inline)" + }, + "videoFormat": { + "grokUrl": "URL (Grok Native)", + "localUrl": "URL (Local Proxy)", + "grokHtml": "HTML (Grok Native)", + "localHtml": "HTML (Local Proxy)" + }, + "proxyMode": { + "direct": "Direct", + "singleProxy": "Fixed Proxy", + "proxyPool": "Proxy Pool" + }, + "clearanceMode": { + "none": "Disabled", + "manual": "Manual", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { + "label": "APP Base URL", + "desc": "Root URL exposed by the application, for example https://your-domain.com. Required when local proxy delivery is enabled." + }, + "appKey": { + "label": "APP Access Password", + "desc": "Authentication password for the admin surface. Existing sessions are invalidated immediately after a change." + }, + "apiKey": { + "label": "API Access Key", + "desc": "Authentication key for the OpenAI-compatible API. Separate multiple values with commas. Leave blank to disable authentication." + }, + "webuiEnabled": { + "label": "Enable WebUI", + "desc": "Exposes the WebUI entry point. When disabled, related routes return 404." + }, + "webuiKey": { + "label": "WebUI Access Password", + "desc": "Authentication password required to access the WebUI when enabled." + }, + "temporary": { + "label": "Temporary Sessions", + "desc": "Requests are excluded from Grok conversation history, providing an ephemeral chat mode." + }, + "memory": { + "label": "Conversation Memory", + "desc": "Enables Grok Memory so the model can retain user preferences and context across sessions." + }, + "stream": { + "label": "Default Streaming", + "desc": "Default value applied when the request does not explicitly provide the stream parameter." + }, + "thinking": { + "label": "Default Reasoning Output", + "desc": "Default value applied when the request does not explicitly provide the thinking parameter. When enabled, reasoning steps are returned in reasoning_content." + }, + "dynamicStatsig": { + "label": "Dynamic Statsig", + "desc": "Generates a fresh Statsig device fingerprint for each request to reduce the likelihood of risk-control challenges." + }, + "enableNsfw": { + "label": "Allow NSFW Generation", + "desc": "Permits the image generation endpoint to bypass NSFW content filtering." + }, + "customInstruction": { + "label": "Global Supplemental Instruction", + "desc": "Injects a consistent system message into every request to enforce model behavior or establish a fixed role." + }, + "imageFormat": { + "label": "Image Output Format", + "desc": "grok_url and grok_md return the native Grok CDN address directly. local_* modes download assets to the server first and re-expose them through the local proxy. base64 returns an inline Data URI." + }, + "videoFormat": { + "label": "Video Output Format", + "desc": "local_* modes download video assets to the server and deliver them through the local proxy. Configure the APP Base URL first and account for outbound bandwidth usage." + }, + "basicInterval": { + "label": "Basic Refresh Interval (s)", + "desc": "Scheduled quota refresh interval for the basic pool. Align this with the quota window when possible (default 36000 s / 10 h)." + }, + "superInterval": { + "label": "Super Refresh Interval (s)", + "desc": "Scheduled quota refresh interval for the super pool. Align this with the quota window when possible (default 7200 s / 2 h)." + }, + "heavyInterval": { + "label": "Heavy Refresh Interval (s)", + "desc": "Scheduled quota refresh interval for the heavy pool. Align this with the quota window when possible (default 7200 s / 2 h)." + }, + "usageConcurrency": { + "label": "Refresh Concurrency", + "desc": "Maximum number of parallel usage calls allowed during quota refresh." + }, + "onDemandMinInterval": { + "label": "Minimum On-Demand Refresh Interval (s)", + "desc": "Throttle window for request-triggered refreshes such as 429 handling. Repeated triggers within the interval are coalesced into a single refresh." + }, + "nsfwConcurrency": { + "label": "NSFW Enablement Concurrency", + "desc": "Token-level concurrency for bulk NSFW enablement. Each token requires three network calls." + }, + "refreshConcurrency": { + "label": "Usage Refresh Concurrency", + "desc": "Token-level concurrency used during bulk quota refresh." + }, + "assetUploadConcurrency": { + "label": "Asset Upload Concurrency", + "desc": "Global maximum concurrency for asset uploads triggered by file attachments across all incoming requests." + }, + "assetListConcurrency": { + "label": "Asset Listing Concurrency", + "desc": "Global maximum concurrency for the list_assets endpoint across all requests." + }, + "assetDeleteConcurrency": { + "label": "Asset Deletion Concurrency", + "desc": "Global maximum concurrency for the delete_asset endpoint. Also used as the default token-level concurrency for bulk cleanup in the admin UI." + }, + "proxyMode": { + "label": "Proxy Mode", + "desc": "Controls outbound proxy routing. direct sends traffic without a proxy, single_proxy uses a fixed proxy, and proxy_pool rotates across a pool." + }, + "proxyUrl": { + "label": "Primary Proxy URL", + "desc": "Outbound proxy endpoint for API traffic. Supports http, https, and socks5." + }, + "resourceProxyUrl": { + "label": "Resource Proxy URL", + "desc": "Dedicated proxy endpoint for downloading images, videos, and other media assets. Falls back to the primary proxy when left blank." + }, + "proxyPool": { + "label": "Primary Proxy Pool", + "desc": "Pool of outbound proxies for API traffic, one proxy URL per line." + }, + "resourceProxyPool": { + "label": "Resource Proxy Pool", + "desc": "Dedicated proxy pool for media downloads, one proxy URL per line. Falls back to the primary pool when left blank." + }, + "skipSslVerify": { + "label": "Skip SSL Verification", + "desc": "Bypasses TLS certificate validation for the proxy server. Enable only when using self-signed certificates." + }, + "clearanceMode": { + "label": "Clearance Mode", + "desc": "Controls how Cloudflare Clearance is obtained and refreshed." + }, + "browserFingerprint": { + "label": "Browser Fingerprint", + "desc": "curl_cffi browser fingerprint identifier. It should align with the JA3 profile expected by Cloudflare, for example chrome136." + }, + "userAgent": { + "label": "User-Agent", + "desc": "Request header User-Agent. It must match the browser used when the Cloudflare cookie was validated." + }, + "cfCookies": { + "label": "Cloudflare Cookies", + "desc": "Full cookie string issued by Cloudflare, including fields such as cf_clearance." + }, + "flaresolverrUrl": { + "label": "FlareSolverr URL", + "desc": "HTTP endpoint for the FlareSolverr instance." + }, + "challengeTimeout": { + "label": "Challenge Timeout (s)", + "desc": "Maximum time allowed for FlareSolverr to complete the Cloudflare challenge." + }, + "refreshInterval": { + "label": "Refresh Interval (s)", + "desc": "Scheduling interval for the prewarm task that refreshes the clearance cookie." + }, + "maxRetries": { + "label": "Application Retry Limit", + "desc": "Maximum number of application-layer retries after a request failure. A value of 0 disables retries. Applies to chat.completions and responses." + }, + "retryCodes": { + "label": "Application Retry Status Codes", + "desc": "HTTP status codes that trigger application-layer retries. Separate multiple values with commas, for example 429,503." + }, + "resetSessionCodes": { + "label": "Transport Session Rebuild Status Codes", + "desc": "HTTP status codes that trigger a transport-session rebuild for the proxy layer. Separate multiple values with commas." + }, + "chatTimeout": { + "label": "Chat Request Timeout (s)", + "desc": "HTTP connection timeout for chat and image-edit requests." + }, + "imageTimeout": { + "label": "Image Request Timeout (s)", + "desc": "Overall timeout for image generation WebSocket requests." + }, + "videoTimeout": { + "label": "Video Request Timeout (s)", + "desc": "Unified timeout for video generation requests." + }, + "voiceTimeout": { + "label": "Voice Request Timeout (s)", + "desc": "Unified timeout for voice requests." + }, + "nsfwTimeout": { + "label": "NSFW Processing Timeout (s)", + "desc": "Timeout applied to set_birth_date and enable_nsfw requests." + }, + "assetUploadTimeout": { + "label": "Asset Upload Timeout (s)", + "desc": "Timeout for the asset upload endpoint." + }, + "assetDownloadTimeout": { + "label": "Asset Download Timeout (s)", + "desc": "Timeout for the asset download endpoint." + }, + "assetListTimeout": { + "label": "Asset Listing Timeout (s)", + "desc": "Timeout for the asset listing endpoint." + }, + "assetDeleteTimeout": { + "label": "Asset Deletion Timeout (s)", + "desc": "Timeout for the asset deletion endpoint." + }, + "streamTimeout": { + "label": "Streaming Idle Timeout (s)", + "desc": "Maximum idle time tolerated while receiving streamed image data." + }, + "interRoundWait": { + "label": "Inter-Round Wait (s)", + "desc": "Wait time used after each image round to determine whether the server keeps the connection open. If CLOSE is not received in time, the existing connection is reused for the next round." + } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Cache Management", + "pageHeading": "Cache Management", + "pageSubtitle": "Inspect local cache files and online account assets from one workspace, with cleanup controls by asset type.", + "refresh": "Refresh", + "sectionOverview": "Overview", + "statImageCount": "Image Cache Files", + "statImageSize": "Image Cache Size", + "statVideoCount": "Video Cache Files", + "statVideoSize": "Video Cache Size", + "sectionDetails": "Details", + "tabLocal": "Local Cache", + "tabOnline": "Online Assets", + "typeImage": "Images", + "typeVideo": "Videos", + "typeImageNoun": "image", + "typeVideoNoun": "video", + "clearCurrent": "Clear Current Cache", + "colFileName": "File Name", + "colSize": "Size", + "colModified": "Last Modified", + "colActions": "Actions", + "colToken": "Token", + "colFileCount": "Files", + "onlineAssetLead": "Online Assets", + "onlineAssetDesc": "are images and attachments stored on the Grok platform. Cleanup affects only remote files and does not remove local cache data.", + "loadAssets": "Load Asset Inventory", + "clearAll": "Clear All", + "cancel": "Cancel", + "assetSummary": "{accounts} accounts · {files} files", + "pageIndicator": "Page {current} / {total}", + "fileCount": "{n} files", + "emptyLocal": "No cached files found", + "emptyAccounts": "No account data available", + "actionDelete": "Delete", + "actionClear": "Clear", + "loadFailed": "Load failed: {message}", + "clearLocalConfirm": "Clear all local {type} cache files?", + "clearLocalDone": "Removed {count} {type} file(s)", + "clearFailed": "Clear failed: {message}", + "deleted": "Deleted", + "deleteFailed": "Delete failed: {message}", + "loading": "Loading...", + "refreshList": "Refresh List", + "expand": "Expand", + "collapse": "Collapse", + "clearTokenConfirm": "Clear all online assets for {token}?", + "clearTokenDone": "Deleted {count} file(s)", + "clearAllConfirm": "Clear online assets for all {n} accounts? This action cannot be undone.", + "clearingAssets": "Clearing online assets...", + "clearAllDone": "Cleanup completed: {ok} succeeded, {fail} failed", + "cancelled": "Cancelled", + "clearFailedPlain": "Cleanup failed", + "connectionInterrupted": "Connection interrupted", + "startFailed": "Failed to start: {message}", + "cancelInProgress": "Cancellation requested. Wait for the current batch to finish.", + "na": "—" } } diff --git a/app/statics/i18n/es.json b/app/statics/i18n/es.json new file mode 100644 index 00000000..83bf0172 --- /dev/null +++ b/app/statics/i18n/es.json @@ -0,0 +1,522 @@ +{ + "common": { + "invalidKey": "Clave no válida", + "connectionFailed": "Error de conexión" + }, + "login": { + "adminPageTitle": "Grok2API - Administración", + "adminTitle": "Panel de Administración", + "adminSubtitle": "Introduzca la contraseña de administrador para continuar", + "adminPlaceholder": "Contraseña de administrador", + "continue": "Continuar", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Introduzca la clave de acceso", + "webuiPlaceholder": "Clave de acceso", + "enter": "Entrar", + "goToAdmin": "Ir al Panel de Administración" + }, + "webui": { + "header": { + "badge": "WebUI", + "login": "Iniciar sesión", + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "login": { + "lead": "Una entrada de chat más ligera y limpia, inspirada en productos modernos de IA.", + "sublead": "Introduzca su clave de acceso para abrir el espacio de conversación respaldado directamente por /webui/api/chat/completions.", + "helper": "Incluye cambio de idioma y verificación de clave de acceso sin interrupciones." + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "WebChat", + "eyebrow": "WebUI", + "title": "Espacio de chat", + "subtitle": "Envíe solicitudes directamente mediante /webui/api/chat/completions con una interfaz de chat más serena y moderna.", + "newChat": "Nuevo chat", + "toggleSidebar": "Alternar barra lateral", + "upload": "Subir archivo", + "sessions": "Todos los chats", + "noSessions": "Aún no hay chats", + "untitled": "Nuevo chat", + "rename": "Renombrar", + "delete": "Eliminar", + "edit": "Editar", + "copy": "Copiar", + "regenerate": "Regenerar", + "like": "Me gusta", + "dislike": "No me gusta", + "reasoning": "Pensamiento", + "save": "Guardar", + "cancel": "Cancelar", + "confirm": "Confirmar", + "copySuccess": "Copiado", + "renamePrompt": "Renombrar chat", + "deleteConfirm": "¿Eliminar este chat?", + "selectedFiles": "{count} archivo(s): {names}", + "searchChat": "Buscar chats", + "images": "Imágenes", + "library": "Biblioteca", + "recent": "Recientes", + "recentSample": "Chat de ejemplo: pregunta lo que quieras", + "clear": "Limpiar chat", + "modelLabel": "Modelo", + "systemLabel": "Sistema", + "statusLabel": "Estado", + "systemPlaceholder": "Opcional: prompt del sistema", + "emptyTitle": "Grok Chat", + "empty": "Inicie una nueva conversación enviando un mensaje.", + "promptPlaceholder": "Escriba su mensaje. Enter para enviar y Shift+Enter para una nueva línea.", + "editPlaceholder": "Editar este mensaje", + "stop": "Detener", + "send": "Enviar", + "statusReady": "Listo", + "statusConnecting": "Conectando...", + "statusThinking": "Pensando...", + "statusGenerating": "Generando...", + "statusDone": "Completado", + "statusStopped": "Detenido", + "statusFailed": "Fallido", + "statusInitFailed": "Fallo en la inicialización", + "userLabel": "Tú", + "assistantLabel": "Grok", + "errors": { + "enterPrompt": "Introduzca un mensaje", + "imageUploadsNotSupported": "La generación de imágenes no acepta referencias subidas aquí. Use chat, edición de imagen o vídeo con imagen de referencia.", + "imageRequired": "La edición de imagen requiere al menos una imagen de referencia", + "imageOnly": "La edición de imagen solo admite cargas de imágenes", + "videoImageOnly": "La generación de vídeo solo admite imágenes como referencia", + "requestFailed": "La solicitud falló", + "initFailed": "La inicialización de la página de chat falló" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "eyebrow": "Voice", + "title": "ChatKit", + "subtitle": "Conéctese directamente a las sesiones de voz de Grok LiveKit y empiece a hablar en cuanto se conceda acceso al micrófono.", + "settings": "Configuración de conexión", + "voiceLabel": "Voz", + "personalityLabel": "Personalidad", + "speedLabel": "Velocidad", + "sessionMeta": "Información de sesión", + "roomName": "Sala", + "participantName": "Identidad", + "remoteCount": "Remoto", + "endpoint": "Endpoint", + "start": "Iniciar", + "pause": "Pausar", + "mute": "Silenciar", + "unmute": "Activar sonido", + "newSession": "Nueva sesión", + "logTitle": "Registro de sesión", + "logEmpty": "En espera por ahora. Los eventos de la sesión aparecerán aquí tras la conexión.", + "clearLog": "Limpiar", + "statusIdle": "Sin conexión", + "statusConnecting": "Conectando", + "statusLive": "En vivo", + "statusMuted": "Silenciado", + "statusPaused": "Pausado", + "statusError": "Fallido", + "idleText": "Pulse iniciar cuando esté listo y permita el acceso al micrófono para entrar en la sesión de voz.", + "connectingText": "Solicitando una sesión de voz de Grok y conectando con LiveKit...", + "liveText": "Conexión establecida. Ahora puede hablar directamente con Grok.", + "mutedText": "Su micrófono está silenciado. Active el sonido para continuar la conversación.", + "pausedText": "La sesión está en pausa. Pulse iniciar para continuar la sesión de voz actual.", + "errorText": "No se pudo completar la conexión. Compruebe el acceso al micrófono e inténtelo de nuevo.", + "endedText": "La sesión de voz ha finalizado. Puede iniciar otra en cualquier momento.", + "fetchingToken": "Solicitando token de voz...", + "connected": "Sesión de voz conectada", + "disconnected": "Sesión de voz desconectada", + "panelShow": "Configuración y registro", + "panelHide": "Ocultar configuración y registro", + "participantJoined": "Participante remoto conectado: {identity}", + "participantLeft": "Participante remoto desconectado: {identity}", + "trackSubscribed": "Audio remoto suscrito", + "micEnabled": "Micrófono activado", + "micMuted": "Micrófono silenciado", + "sessionPaused": "Sesión de voz en pausa", + "sessionResumed": "Sesión de voz reanudada", + "outputMuted": "Altavoz silenciado", + "outputUnmuted": "Altavoz activado", + "startingNewSession": "Iniciando una nueva sesión de voz...", + "livekitLoadFailed": "No se pudo cargar el SDK de LiveKit", + "invalidToken": "Respuesta de token de voz no válida" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "subtitle": "Una página independiente de cascada de imágenes que usa únicamente la generación por WebSocket de Grok Imagine.", + "countLabel": "Fijo", + "qualityLabel": "Calidad", + "qualitySpeed": "Velocidad", + "qualityQuality": "Calidad", + "modeLabel": "Modo", + "modeRounds": "Rondas", + "modeCycles": "Ciclos", + "modeContinuous": "Continuo", + "modeSingle": "Una sola ronda", + "promptPlaceholder": "Describa la imagen que desea. Enter para generar y Shift+Enter para nueva línea.", + "generate": "Generar", + "stop": "Detener", + "openImage": "Abrir imagen", + "ratioLabel": "Proporción", + "statusReady": "Listo", + "statusConnecting": "Conectando...", + "statusGenerating": "Generando...", + "statusCompleted": "Completado", + "statusStopped": "Detenido", + "statusFailed": "Fallido", + "emptyTitle": "Empiece con un prompt", + "emptyText": "Introduzca un prompt y las imágenes aparecerán aquí en orden.", + "roundLabel": "Ronda {n}", + "batchPending": "Esperando para iniciar", + "batchFiltered": "Filtrado", + "batchError": "La generación falló", + "errors": { + "enterPrompt": "Introduzca un prompt", + "requestFailed": "La solicitud falló", + "initFailed": "La inicialización de la página Masonry falló" + } + } + }, + "header": { + "account": "Gestión de Cuentas", + "config": "Gestión de Configuración", + "cache": "Gestión de Caché", + "languageLabel": "Idioma", + "switchLanguage": "Cambiar idioma", + "logout": "Cerrar sesión", + "versionDialogTitle": "Versión", + "versionCurrent": "Actual", + "versionLatest": "Última", + "versionPublishedAt": "Publicada", + "versionUpToDate": "Ya está usando la versión más reciente.", + "versionUpdateAvailable": "Hay una nueva versión disponible.", + "versionChecking": "Comprobando actualizaciones...", + "versionUnavailable": "No se pudo comprobar las actualizaciones.", + "versionNotesEmpty": "No hay notas de versión disponibles.", + "versionOpenRelease": "Abrir release", + "versionClose": "Cerrar" + }, + "account": { + "pageTitle": "Grok2API - Cuentas", + "nav": "Gestión de Cuentas", + "pageHeading": "Gestión de Cuentas", + "pageSubtitle": "Administre el pool de cuentas de xAI, la postura de cuota y el estado operativo utilizado por Grok2API.", + "actionImport": "Importar cuentas", + "actionAdd": "Agregar cuenta", + "sectionOverview": "Resumen", + "sectionTable": "Lista de cuentas", + "statTotal": "Cuentas totales", + "statActive": "Activas", + "statCooling": "Limitadas", + "statInvalid": "No disponibles", + "statAuto": "Cuota Auto restante", + "statFast": "Cuota Fast restante", + "statExpert": "Cuota Expert restante", + "statHeavy": "Cuota Heavy restante", + "tabAll": "Todas", + "tabActive": "Activas", + "tabCooling": "Limitadas", + "tabInvalid": "No disponibles", + "tabNsfw": "NSFW activado", + "tabNonNsfw": "NSFW desactivado", + "filterStatusLabel": "Estado", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Tipo", + "filterStatusAll": "Todas", + "filterStatusActive": "Activas", + "filterStatusCooling": "Limitadas", + "filterStatusInvalid": "No disponibles", + "filterNsfwAll": "Todas", + "filterNsfwEnabled": "Activado", + "filterNsfwDisabled": "Desactivado", + "filterTypeAll": "Todos", + "export": "Exportar datos", + "batchNsfw": "Activar NSFW", + "batchNsfwDisable": "Desactivar NSFW", + "batchRefresh": "Actualizar selección", + "batchDelete": "Eliminar selección", + "colToken": "Token", + "colType": "Tipo de cuenta", + "colStatus": "Estado operativo", + "colQuota": "Cuota", + "colSuccess": "Éxito", + "colFail": "Error", + "colRate": "Tasa de éxito", + "colLastUsed": "Último uso", + "colActions": "Acciones", + "actionCopy": "Copiar", + "actionRefresh": "Actualizar cuota", + "actionEdit": "Editar", + "actionDelete": "Eliminar", + "empty": "No hay cuentas disponibles. Use Importar cuentas o Agregar cuenta para continuar.", + "pageInfo": "{n} en total", + "pageSizeOption": "{n} / página", + "backendCount": "{n} cuentas", + "backendOffline": "No disponible", + "addTitle": "Agregar cuenta", + "addHint": "Introduzca un token por línea. Los tokens existentes se omitirán automáticamente.", + "addPlaceholder": "Pegue los tokens, uno por línea...", + "importTitle": "Importar cuentas", + "importHintDefault": "Admite formatos .txt (un token por línea) y .json ({pool:[tokens]}).", + "importHintJson": "El archivo JSON ya incluye la información del tipo de cuenta. No se requiere una selección adicional.", + "importHintTxt": "Introduzca un token por línea. Los tokens importados se agregarán al tipo de cuenta seleccionado.", + "labelType": "Tipo", + "labelFile": "Archivo", + "editTitle": "Editar cuenta", + "editTokenPlaceholder": "Introduzca el token actualizado", + "exportTitle": "Exportar cuentas", + "exportCountPrefix": "", + "exportCountSuffix": " tokens", + "exportJson": "Formato JSON (exportación completa, pero puede no ser compatible entre versiones)", + "exportTxt": "Formato TXT (solo tokens, compatible con todas las versiones)", + "confirmTitle": "Confirmar acción", + "cancel": "Cancelar", + "confirm": "Confirmar", + "save": "Guardar cambios", + "noFile": "No se seleccionó ningún archivo", + "copied": "Copiado", + "copyFailed": "Error al copiar", + "loadFailed": "Error al cargar", + "notFound": "Cuenta no encontrada", + "enterToken": "Introduzca un token", + "selectFile": "Seleccione un archivo", + "readFileFailed": "No se pudo leer el archivo", + "jsonInvalid": "Formato JSON no válido", + "jsonShapeInvalid": "Estructura JSON no válida. Se esperaba {pool:[tokens]}.", + "jsonEmpty": "No se encontraron tokens importables en el archivo JSON", + "fileEmpty": "No se encontraron tokens importables en el archivo", + "adding": "Agregando {n} cuentas…", + "addDone": "Cuentas agregadas", + "addFailed": "No se pudieron agregar las cuentas", + "importing": "Importando {n} cuentas…", + "importDone": "Importación completada", + "importJsonDone": "Importación completada: {n} cuentas procesadas", + "importFailed": "La importación falló", + "saving": "Guardando cambios…", + "editDone": "Cambios guardados", + "editFailed": "No se pudieron guardar los cambios", + "saveResult": "{prefix}: {count} cuentas agregadas", + "saveResultSkipped": "{prefix}: {count} agregadas, {skipped} ya existían", + "exportEmpty": "No hay cuentas para exportar", + "deleteConfirmTitle": "Confirmar eliminación", + "deleteConfirmOne": "¿Eliminar {token}?
Esta acción no se puede deshacer.", + "deleteConfirmMany": "¿Eliminar {n} cuentas?
Esta acción no se puede deshacer.", + "deleting": "Eliminando {n} cuentas…", + "deleteDone": "Se eliminaron {n}", + "deleteFailed": "La eliminación falló", + "refreshing": "Actualizando la información de cuota de {n} cuentas…", + "refreshDone": "Actualización completada: {ok} correctas, {fail} fallidas", + "refreshFailed": "La actualización falló", + "nsfwConfirmTitle": "Activar NSFW", + "nsfwConfirmBody": "¿Activar NSFW para {n} cuentas seleccionadas?", + "nsfwEnablingOne": "Activando NSFW…", + "nsfwEnabling": "Activando NSFW para {n} cuentas…", + "nsfwDone": "Actualización de NSFW completada: {ok} correctas, {fail} fallidas", + "nsfwDisablingOne": "Desactivando NSFW…", + "nsfwDisableDone": "Desactivación de NSFW completada: {ok} correctas, {fail} fallidas", + "nsfwEnabledTitle": "Activado", + "operationFailed": "La operación falló", + "unknown": "Desconocido", + "na": "—", + "pool": { + "autoRecommended": "Detección automática (recomendada)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy" + }, + "status": { + "active": "Activa", + "cooling": "Limitada", + "expired": "Expirada", + "invalid": "No disponible" + } + }, + "config": { + "pageTitle": "Grok2API - Gestión de Configuración", + "pageHeading": "Gestión de Configuración", + "pageSubtitle": "Administre los parámetros de ejecución y el comportamiento del servicio desde una sola superficie de control. Los cambios se aplican de inmediato salvo que se requiera reinicio.", + "resetChanges": "Restablecer cambios", + "saveChanges": "Guardar cambios", + "unsavedDefault": "Hay cambios sin guardar", + "unsavedSingle": "Hay 1 cambio sin guardar", + "unsavedMultiple": "Hay {n} cambios sin guardar", + "discardChanges": "Descartar cambios", + "randomize": "Generar valor", + "loadFailed": "No se pudo cargar la configuración: {message}", + "saving": "Guardando cambios...", + "saveSuccess": "Cambios guardados", + "saveFailed": "No se pudieron guardar los cambios: {message}", + "resetSuccess": "Se descartaron los cambios no guardados", + "disabledTip": { + "appUrlRequired": "Configure primero la URL base de APP" + }, + "schema": { + "tabs": { + "system": "Sistema", + "features": "Funciones", + "schedule": "Programación", + "proxy": "Red", + "image": "Canal de imagen" + }, + "groups": { + "baseAccess": "Control de acceso", + "features": "Funciones principales", + "mediaFormat": "Salida multimedia", + "refreshSchedule": "Actualización de cuota", + "batchConcurrency": "Concurrencia por lotes", + "egressProxy": "Proxy de salida", + "clearance": "Cloudflare Clearance", + "retry": "Política de reintentos", + "timeouts": "Tiempos de espera", + "imageProtocol": "NSFW y transmisión de imágenes" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Nativo de Grok)", + "localUrl": "URL (Proxy local)", + "grokMarkdown": "Markdown (Nativo de Grok)", + "localMarkdown": "Markdown (Proxy local)", + "base64": "Base64 (Integrado)" + }, + "videoFormat": { + "grokUrl": "URL (Nativo de Grok)", + "localUrl": "URL (Proxy local)", + "grokHtml": "HTML (Nativo de Grok)", + "localHtml": "HTML (Proxy local)" + }, + "proxyMode": { + "direct": "Directo", + "singleProxy": "Proxy fijo", + "proxyPool": "Pool de proxies" + }, + "clearanceMode": { + "none": "Desactivado", + "manual": "Manual", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "URL base de APP" }, + "appKey": { "label": "Contraseña de acceso APP" }, + "apiKey": { "label": "Clave de acceso API" }, + "webuiEnabled": { "label": "Activar WebUI" }, + "webuiKey": { "label": "Contraseña de acceso WebUI" }, + "temporary": { "label": "Sesiones temporales" }, + "memory": { "label": "Memoria de conversación" }, + "stream": { "label": "Streaming predeterminado" }, + "thinking": { "label": "Salida de razonamiento predeterminada" }, + "dynamicStatsig": { "label": "Statsig dinámico" }, + "enableNsfw": { "label": "Permitir generación NSFW" }, + "customInstruction": { "label": "Instrucción suplementaria global" }, + "imageFormat": { "label": "Formato de salida de imagen" }, + "videoFormat": { "label": "Formato de salida de video" }, + "basicInterval": { "label": "Intervalo de refresco Basic (s)" }, + "superInterval": { "label": "Intervalo de refresco Super (s)" }, + "heavyInterval": { "label": "Intervalo de refresco Heavy (s)" }, + "usageConcurrency": { "label": "Concurrencia de actualización" }, + "onDemandMinInterval": { "label": "Intervalo mínimo bajo demanda (s)" }, + "nsfwConcurrency": { "label": "Concurrencia de activación NSFW" }, + "refreshConcurrency": { "label": "Concurrencia de refresco de Usage" }, + "assetUploadConcurrency": { "label": "Concurrencia de carga de Asset" }, + "assetListConcurrency": { "label": "Concurrencia de listado de Asset" }, + "assetDeleteConcurrency": { "label": "Concurrencia de eliminación de Asset" }, + "proxyMode": { "label": "Modo de proxy" }, + "proxyUrl": { "label": "URL de proxy principal" }, + "resourceProxyUrl": { "label": "URL de proxy de recursos" }, + "proxyPool": { "label": "Pool de proxy principal" }, + "resourceProxyPool": { "label": "Pool de proxy de recursos" }, + "skipSslVerify": { "label": "Omitir verificación SSL" }, + "clearanceMode": { "label": "Modo de Clearance" }, + "browserFingerprint": { "label": "Huella del navegador" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cookies de Cloudflare" }, + "flaresolverrUrl": { "label": "URL de FlareSolverr" }, + "challengeTimeout": { "label": "Tiempo de espera del desafío (s)" }, + "refreshInterval": { "label": "Intervalo de actualización (s)" }, + "maxRetries": { "label": "Límite de reintentos de cuenta" }, + "retryCodes": { "label": "Códigos de estado para reintento" }, + "resetSessionCodes": { "label": "Códigos para reinicio de sesión" }, + "chatTimeout": { "label": "Tiempo de espera de chat (s)" }, + "imageTimeout": { "label": "Tiempo de espera de imagen (s)" }, + "videoTimeout": { "label": "Tiempo de espera de video (s)" }, + "voiceTimeout": { "label": "Tiempo de espera de voz (s)" }, + "nsfwTimeout": { "label": "Tiempo de espera de NSFW (s)" }, + "assetUploadTimeout": { "label": "Tiempo de espera de carga de Asset (s)" }, + "assetDownloadTimeout": { "label": "Tiempo de espera de descarga de Asset (s)" }, + "assetListTimeout": { "label": "Tiempo de espera de listado de Asset (s)" }, + "assetDeleteTimeout": { "label": "Tiempo de espera de eliminación de Asset (s)" }, + "streamTimeout": { "label": "Tiempo de espera de inactividad en streaming (s)" }, + "interRoundWait": { "label": "Espera entre rondas (s)" } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Gestión de Caché", + "pageHeading": "Gestión de Caché", + "pageSubtitle": "Inspeccione los archivos de caché local y los activos en línea desde un único espacio de trabajo, con controles de limpieza por tipo de activo.", + "refresh": "Actualizar", + "sectionOverview": "Resumen", + "statImageCount": "Archivos de caché de imagen", + "statImageSize": "Tamaño de caché de imagen", + "statVideoCount": "Archivos de caché de video", + "statVideoSize": "Tamaño de caché de video", + "sectionDetails": "Detalles", + "tabLocal": "Caché local", + "tabOnline": "Activos en línea", + "typeImage": "Imágenes", + "typeVideo": "Videos", + "typeImageNoun": "imagen", + "typeVideoNoun": "video", + "clearCurrent": "Vaciar caché actual", + "colFileName": "Nombre del archivo", + "colSize": "Tamaño", + "colModified": "Última modificación", + "colActions": "Acciones", + "colToken": "Token", + "colFileCount": "Archivos", + "onlineAssetLead": "Activos en línea", + "onlineAssetDesc": "son imágenes y adjuntos almacenados en la plataforma Grok. La limpieza afecta solo a los archivos remotos y no elimina la caché local.", + "loadAssets": "Cargar inventario de activos", + "clearAll": "Eliminar todo", + "cancel": "Cancelar", + "assetSummary": "{accounts} cuentas · {files} archivos", + "pageIndicator": "Página {current} / {total}", + "fileCount": "{n} archivos", + "emptyLocal": "No se encontraron archivos en caché", + "emptyAccounts": "No hay datos de cuentas disponibles", + "actionDelete": "Eliminar", + "actionClear": "Limpiar", + "loadFailed": "Error al cargar: {message}", + "clearLocalConfirm": "¿Vaciar todos los archivos de caché local de {type}?", + "clearLocalDone": "Se eliminaron {count} archivo(s) de {type}", + "clearFailed": "La limpieza falló: {message}", + "deleted": "Eliminado", + "deleteFailed": "La eliminación falló: {message}", + "loading": "Cargando...", + "refreshList": "Actualizar lista", + "expand": "Expandir", + "collapse": "Contraer", + "clearTokenConfirm": "¿Eliminar todos los activos en línea de {token}?", + "clearTokenDone": "Se eliminaron {count} archivo(s)", + "clearAllConfirm": "¿Eliminar los activos en línea de las {n} cuentas? Esta acción no se puede deshacer.", + "clearingAssets": "Limpiando activos en línea...", + "clearAllDone": "Limpieza completada: {ok} correctas, {fail} fallidas", + "cancelled": "Cancelado", + "clearFailedPlain": "La limpieza falló", + "connectionInterrupted": "Conexión interrumpida", + "startFailed": "No se pudo iniciar: {message}", + "cancelInProgress": "Se solicitó la cancelación. Espere a que finalice el lote actual.", + "na": "—" + } +} diff --git a/app/statics/i18n/fr.json b/app/statics/i18n/fr.json new file mode 100644 index 00000000..46b08206 --- /dev/null +++ b/app/statics/i18n/fr.json @@ -0,0 +1,522 @@ +{ + "common": { + "invalidKey": "Clé invalide", + "connectionFailed": "Échec de la connexion" + }, + "login": { + "adminPageTitle": "Grok2API - Administration", + "adminTitle": "Panneau d’administration", + "adminSubtitle": "Saisissez le mot de passe administrateur pour continuer", + "adminPlaceholder": "Mot de passe administrateur", + "continue": "Continuer", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "Saisissez la clé d’accès", + "webuiPlaceholder": "Clé d’accès", + "enter": "Entrer", + "goToAdmin": "Accéder au panneau d’administration" + }, + "webui": { + "header": { + "badge": "WebUI", + "login": "Connexion", + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "login": { + "lead": "Une entrée de chat plus légère et plus propre, inspirée des produits IA modernes.", + "sublead": "Saisissez votre clé d’accès pour ouvrir l’espace de conversation reposant directement sur /webui/api/chat/completions.", + "helper": "Inclut le changement de langue et la vérification fluide de la clé d’accès." + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "WebChat", + "eyebrow": "WebUI", + "title": "Espace de chat", + "subtitle": "Envoyez des requêtes directement via /webui/api/chat/completions avec une interface de chat plus calme et plus moderne.", + "newChat": "Nouveau chat", + "toggleSidebar": "Basculer la barre latérale", + "upload": "Téléverser un fichier", + "sessions": "Tous les chats", + "noSessions": "Aucun chat pour le moment", + "untitled": "Nouveau chat", + "rename": "Renommer", + "delete": "Supprimer", + "edit": "Modifier", + "copy": "Copier", + "regenerate": "Régénérer", + "like": "J’aime", + "dislike": "Je n’aime pas", + "reasoning": "Réflexion", + "save": "Enregistrer", + "cancel": "Annuler", + "confirm": "Confirmer", + "copySuccess": "Copié", + "renamePrompt": "Renommer le chat", + "deleteConfirm": "Supprimer ce chat ?", + "selectedFiles": "{count} fichier(s) : {names}", + "searchChat": "Rechercher des chats", + "images": "Images", + "library": "Bibliothèque", + "recent": "Récents", + "recentSample": "Exemple de chat : posez n’importe quelle question", + "clear": "Effacer le chat", + "modelLabel": "Modèle", + "systemLabel": "Système", + "statusLabel": "Statut", + "systemPlaceholder": "Optionnel : prompt système", + "emptyTitle": "Grok Chat", + "empty": "Commencez une nouvelle conversation en envoyant un message.", + "promptPlaceholder": "Saisissez votre message. Entrée pour envoyer, Shift+Entrée pour une nouvelle ligne.", + "editPlaceholder": "Modifier ce message", + "stop": "Arrêter", + "send": "Envoyer", + "statusReady": "Prêt", + "statusConnecting": "Connexion...", + "statusThinking": "Réflexion...", + "statusGenerating": "Génération...", + "statusDone": "Terminé", + "statusStopped": "Arrêté", + "statusFailed": "Échec", + "statusInitFailed": "Échec de l’initialisation", + "userLabel": "Vous", + "assistantLabel": "Grok", + "errors": { + "enterPrompt": "Veuillez saisir un message", + "imageUploadsNotSupported": "La génération d’images n’accepte pas les références téléversées ici. Utilisez le chat, l’édition d’image ou la vidéo avec une image de référence.", + "imageRequired": "L’édition d’image nécessite au moins une image de référence", + "imageOnly": "L’édition d’image ne prend en charge que les téléversements d’images", + "videoImageOnly": "La génération vidéo n’accepte que les images comme référence", + "requestFailed": "Échec de la requête", + "initFailed": "Échec de l’initialisation de la page de chat" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "eyebrow": "Voice", + "title": "ChatKit", + "subtitle": "Connectez-vous directement aux sessions vocales Grok LiveKit et commencez à parler dès que l’accès au micro est accordé.", + "settings": "Paramètres de connexion", + "voiceLabel": "Voix", + "personalityLabel": "Personnalité", + "speedLabel": "Vitesse", + "sessionMeta": "Infos de session", + "roomName": "Salle", + "participantName": "Identité", + "remoteCount": "Distant", + "endpoint": "Point de terminaison", + "start": "Démarrer", + "pause": "Pause", + "mute": "Muet", + "unmute": "Réactiver le son", + "newSession": "Nouvelle session", + "logTitle": "Journal de session", + "logEmpty": "En attente pour le moment. Les événements de session apparaîtront ici après la connexion.", + "clearLog": "Effacer", + "statusIdle": "Non connecté", + "statusConnecting": "Connexion", + "statusLive": "En direct", + "statusMuted": "Muet", + "statusPaused": "En pause", + "statusError": "Échec", + "idleText": "Cliquez sur démarrer quand vous êtes prêt et autorisez l’accès au micro pour rejoindre la session vocale.", + "connectingText": "Demande d’une session vocale Grok et connexion à LiveKit...", + "liveText": "Connexion établie. Vous pouvez maintenant parler directement avec Grok.", + "mutedText": "Votre microphone est coupé. Réactivez-le pour poursuivre la conversation vocale.", + "pausedText": "La session est en pause. Cliquez sur démarrer pour reprendre la session vocale en cours.", + "errorText": "La connexion n’a pas abouti. Vérifiez l’accès au micro puis réessayez.", + "endedText": "La session vocale est terminée. Vous pouvez en démarrer une nouvelle à tout moment.", + "fetchingToken": "Demande du jeton vocal...", + "connected": "Session vocale connectée", + "disconnected": "Session vocale déconnectée", + "panelShow": "Paramètres et journal", + "panelHide": "Masquer paramètres et journal", + "participantJoined": "Participant distant connecté : {identity}", + "participantLeft": "Participant distant déconnecté : {identity}", + "trackSubscribed": "Audio distant abonné", + "micEnabled": "Micro activé", + "micMuted": "Micro coupé", + "sessionPaused": "Session vocale en pause", + "sessionResumed": "Session vocale reprise", + "outputMuted": "Haut-parleur coupé", + "outputUnmuted": "Haut-parleur réactivé", + "startingNewSession": "Démarrage d’une nouvelle session vocale...", + "livekitLoadFailed": "Échec du chargement du SDK LiveKit", + "invalidToken": "Réponse de jeton vocal invalide" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "subtitle": "Une page dédiée au flux d’images qui utilise uniquement la génération Grok Imagine via WebSocket.", + "countLabel": "Fixe", + "qualityLabel": "Qualité", + "qualitySpeed": "Vitesse", + "qualityQuality": "Qualité", + "modeLabel": "Mode", + "modeRounds": "Rounds", + "modeCycles": "Cycles", + "modeContinuous": "Continu", + "modeSingle": "Une seule série", + "promptPlaceholder": "Décrivez l’image souhaitée. Entrée pour générer, Shift+Entrée pour une nouvelle ligne.", + "generate": "Générer", + "stop": "Arrêter", + "openImage": "Ouvrir l’image", + "ratioLabel": "Ratio", + "statusReady": "Prêt", + "statusConnecting": "Connexion...", + "statusGenerating": "Génération...", + "statusCompleted": "Terminé", + "statusStopped": "Arrêté", + "statusFailed": "Échec", + "emptyTitle": "Commencez avec un prompt", + "emptyText": "Saisissez un prompt et les images apparaîtront ici dans l’ordre.", + "roundLabel": "Round {n}", + "batchPending": "En attente de démarrage", + "batchFiltered": "Filtré", + "batchError": "La génération a échoué", + "errors": { + "enterPrompt": "Veuillez saisir un prompt", + "requestFailed": "Échec de la requête", + "initFailed": "Échec de l’initialisation de la page Masonry" + } + } + }, + "header": { + "account": "Gestion des Comptes", + "config": "Gestion de la Configuration", + "cache": "Gestion du Cache", + "languageLabel": "Langue", + "switchLanguage": "Changer de langue", + "logout": "Se déconnecter", + "versionDialogTitle": "Version", + "versionCurrent": "Actuelle", + "versionLatest": "Dernière", + "versionPublishedAt": "Publication", + "versionUpToDate": "Vous utilisez déjà la version la plus récente.", + "versionUpdateAvailable": "Une nouvelle version est disponible.", + "versionChecking": "Vérification des mises à jour...", + "versionUnavailable": "Échec de la vérification des mises à jour.", + "versionNotesEmpty": "Aucune note de version disponible.", + "versionOpenRelease": "Ouvrir la release", + "versionClose": "Fermer" + }, + "account": { + "pageTitle": "Grok2API - Comptes", + "nav": "Gestion des Comptes", + "pageHeading": "Gestion des Comptes", + "pageSubtitle": "Gérez le pool de comptes xAI, la posture de quota et l’état d’exécution utilisés par Grok2API.", + "actionImport": "Importer des comptes", + "actionAdd": "Ajouter un compte", + "sectionOverview": "Vue d’ensemble", + "sectionTable": "Liste des comptes", + "statTotal": "Nombre total de comptes", + "statActive": "Actifs", + "statCooling": "Limités", + "statInvalid": "Indisponibles", + "statAuto": "Quota Auto restant", + "statFast": "Quota Fast restant", + "statExpert": "Quota Expert restant", + "statHeavy": "Quota Heavy restant", + "tabAll": "Tous", + "tabActive": "Actifs", + "tabCooling": "Limités", + "tabInvalid": "Indisponibles", + "tabNsfw": "NSFW activé", + "tabNonNsfw": "NSFW désactivé", + "filterStatusLabel": "Statut", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "Type", + "filterStatusAll": "Tous", + "filterStatusActive": "Actifs", + "filterStatusCooling": "Limités", + "filterStatusInvalid": "Indisponibles", + "filterNsfwAll": "Tous", + "filterNsfwEnabled": "Activé", + "filterNsfwDisabled": "Désactivé", + "filterTypeAll": "Tous", + "export": "Exporter les données", + "batchNsfw": "Activer NSFW", + "batchNsfwDisable": "Désactiver NSFW", + "batchRefresh": "Actualiser la sélection", + "batchDelete": "Supprimer la sélection", + "colToken": "Token", + "colType": "Type de compte", + "colStatus": "Statut d’exécution", + "colQuota": "Quota", + "colSuccess": "Succès", + "colFail": "Échec", + "colRate": "Taux de réussite", + "colLastUsed": "Dernière utilisation", + "colActions": "Actions", + "actionCopy": "Copier", + "actionRefresh": "Actualiser le quota", + "actionEdit": "Modifier", + "actionDelete": "Supprimer", + "empty": "Aucun compte disponible. Utilisez Importer des comptes ou Ajouter un compte pour continuer.", + "pageInfo": "{n} au total", + "pageSizeOption": "{n} / page", + "backendCount": "{n} comptes", + "backendOffline": "Indisponible", + "addTitle": "Ajouter un compte", + "addHint": "Saisissez un token par ligne. Les tokens existants seront ignorés automatiquement.", + "addPlaceholder": "Collez les tokens, un par ligne...", + "importTitle": "Importer des comptes", + "importHintDefault": "Prend en charge les formats .txt (un token par ligne) et .json ({pool:[tokens]}).", + "importHintJson": "Le fichier JSON inclut déjà les informations de type de compte. Aucune sélection supplémentaire n’est requise.", + "importHintTxt": "Saisissez un token par ligne. Les tokens importés seront ajoutés au type de compte sélectionné.", + "labelType": "Type", + "labelFile": "Fichier", + "editTitle": "Modifier le compte", + "editTokenPlaceholder": "Saisissez le token mis à jour", + "exportTitle": "Exporter les comptes", + "exportCountPrefix": "", + "exportCountSuffix": " tokens", + "exportJson": "Format JSON (export complet, mais potentiellement non compatible entre versions)", + "exportTxt": "Format TXT (tokens uniquement, compatible avec toutes les versions)", + "confirmTitle": "Confirmer l’action", + "cancel": "Annuler", + "confirm": "Confirmer", + "save": "Enregistrer les modifications", + "noFile": "Aucun fichier sélectionné", + "copied": "Copié", + "copyFailed": "Échec de la copie", + "loadFailed": "Échec du chargement", + "notFound": "Compte introuvable", + "enterToken": "Saisissez un token", + "selectFile": "Sélectionnez un fichier", + "readFileFailed": "Impossible de lire le fichier", + "jsonInvalid": "Format JSON invalide", + "jsonShapeInvalid": "Structure JSON invalide. Format attendu : {pool:[tokens]}.", + "jsonEmpty": "Aucun token importable trouvé dans le fichier JSON", + "fileEmpty": "Aucun token importable trouvé dans le fichier", + "adding": "Ajout de {n} comptes…", + "addDone": "Comptes ajoutés", + "addFailed": "Échec de l’ajout des comptes", + "importing": "Importation de {n} comptes…", + "importDone": "Importation terminée", + "importJsonDone": "Importation terminée : {n} comptes traités", + "importFailed": "Échec de l’importation", + "saving": "Enregistrement des modifications…", + "editDone": "Modifications enregistrées", + "editFailed": "Impossible d’enregistrer les modifications", + "saveResult": "{prefix} : {count} comptes ajoutés", + "saveResultSkipped": "{prefix} : {count} ajoutés, {skipped} existaient déjà", + "exportEmpty": "Aucun compte à exporter", + "deleteConfirmTitle": "Confirmer la suppression", + "deleteConfirmOne": "Supprimer {token} ?
Cette action est irréversible.", + "deleteConfirmMany": "Supprimer {n} comptes ?
Cette action est irréversible.", + "deleting": "Suppression de {n} comptes…", + "deleteDone": "{n} supprimé(s)", + "deleteFailed": "Échec de la suppression", + "refreshing": "Actualisation des informations de quota pour {n} comptes…", + "refreshDone": "Actualisation terminée : {ok} réussites, {fail} échecs", + "refreshFailed": "Échec de l’actualisation", + "nsfwConfirmTitle": "Activer NSFW", + "nsfwConfirmBody": "Activer NSFW pour {n} comptes sélectionnés ?", + "nsfwEnablingOne": "Activation de NSFW…", + "nsfwEnabling": "Activation de NSFW pour {n} comptes…", + "nsfwDone": "Mise à jour NSFW terminée : {ok} réussites, {fail} échecs", + "nsfwDisablingOne": "Désactivation de NSFW…", + "nsfwDisableDone": "Désactivation de NSFW terminée : {ok} réussites, {fail} échecs", + "nsfwEnabledTitle": "Activé", + "operationFailed": "L’opération a échoué", + "unknown": "Inconnu", + "na": "—", + "pool": { + "autoRecommended": "Détection automatique (recommandée)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy" + }, + "status": { + "active": "Actif", + "cooling": "Limité", + "expired": "Expiré", + "invalid": "Indisponible" + } + }, + "config": { + "pageTitle": "Grok2API - Gestion de la Configuration", + "pageHeading": "Gestion de la Configuration", + "pageSubtitle": "Gérez les paramètres d’exécution et le comportement du service depuis une seule surface de contrôle. Les changements s’appliquent immédiatement sauf redémarrage requis.", + "resetChanges": "Réinitialiser les modifications", + "saveChanges": "Enregistrer les modifications", + "unsavedDefault": "Des modifications non enregistrées ont été détectées", + "unsavedSingle": "1 modification non enregistrée a été détectée", + "unsavedMultiple": "{n} modifications non enregistrées ont été détectées", + "discardChanges": "Ignorer les modifications", + "randomize": "Générer une valeur", + "loadFailed": "Impossible de charger la configuration : {message}", + "saving": "Enregistrement des modifications...", + "saveSuccess": "Modifications enregistrées", + "saveFailed": "Impossible d’enregistrer les modifications : {message}", + "resetSuccess": "Les modifications non enregistrées ont été ignorées", + "disabledTip": { + "appUrlRequired": "Configurez d’abord l’URL de base de l’application" + }, + "schema": { + "tabs": { + "system": "Système", + "features": "Fonctionnalités", + "schedule": "Planification", + "proxy": "Réseau", + "image": "Pipeline d’image" + }, + "groups": { + "baseAccess": "Contrôle d’accès", + "features": "Fonctionnalités principales", + "mediaFormat": "Sortie multimédia", + "refreshSchedule": "Actualisation du quota", + "batchConcurrency": "Concurrence par lot", + "egressProxy": "Proxy sortant", + "clearance": "Cloudflare Clearance", + "retry": "Politique de reprise", + "timeouts": "Délais d’attente", + "imageProtocol": "NSFW et streaming d’images" + }, + "options": { + "imageFormat": { + "grokUrl": "URL (Natif Grok)", + "localUrl": "URL (Proxy local)", + "grokMarkdown": "Markdown (Natif Grok)", + "localMarkdown": "Markdown (Proxy local)", + "base64": "Base64 (Intégré)" + }, + "videoFormat": { + "grokUrl": "URL (Natif Grok)", + "localUrl": "URL (Proxy local)", + "grokHtml": "HTML (Natif Grok)", + "localHtml": "HTML (Proxy local)" + }, + "proxyMode": { + "direct": "Direct", + "singleProxy": "Proxy fixe", + "proxyPool": "Pool de proxys" + }, + "clearanceMode": { + "none": "Désactivé", + "manual": "Manuel", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "URL de base APP" }, + "appKey": { "label": "Mot de passe d’accès APP" }, + "apiKey": { "label": "Clé d’accès API" }, + "webuiEnabled": { "label": "Activer WebUI" }, + "webuiKey": { "label": "Mot de passe d’accès WebUI" }, + "temporary": { "label": "Sessions temporaires" }, + "memory": { "label": "Mémoire conversationnelle" }, + "stream": { "label": "Streaming par défaut" }, + "thinking": { "label": "Sortie de raisonnement par défaut" }, + "dynamicStatsig": { "label": "Statsig dynamique" }, + "enableNsfw": { "label": "Autoriser la génération NSFW" }, + "customInstruction": { "label": "Instruction globale supplémentaire" }, + "imageFormat": { "label": "Format de sortie image" }, + "videoFormat": { "label": "Format de sortie vidéo" }, + "basicInterval": { "label": "Intervalle d’actualisation Basic (s)" }, + "superInterval": { "label": "Intervalle d’actualisation Super (s)" }, + "heavyInterval": { "label": "Intervalle d’actualisation Heavy (s)" }, + "usageConcurrency": { "label": "Concurrence d’actualisation" }, + "onDemandMinInterval": { "label": "Intervalle minimal à la demande (s)" }, + "nsfwConcurrency": { "label": "Concurrence d’activation NSFW" }, + "refreshConcurrency": { "label": "Concurrence d’actualisation Usage" }, + "assetUploadConcurrency": { "label": "Concurrence d’envoi Asset" }, + "assetListConcurrency": { "label": "Concurrence de listage Asset" }, + "assetDeleteConcurrency": { "label": "Concurrence de suppression Asset" }, + "proxyMode": { "label": "Mode proxy" }, + "proxyUrl": { "label": "URL du proxy principal" }, + "resourceProxyUrl": { "label": "URL du proxy de ressources" }, + "proxyPool": { "label": "Pool de proxys principal" }, + "resourceProxyPool": { "label": "Pool de proxys de ressources" }, + "skipSslVerify": { "label": "Ignorer la vérification SSL" }, + "clearanceMode": { "label": "Mode Clearance" }, + "browserFingerprint": { "label": "Empreinte navigateur" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cookies Cloudflare" }, + "flaresolverrUrl": { "label": "URL FlareSolverr" }, + "challengeTimeout": { "label": "Délai du challenge (s)" }, + "refreshInterval": { "label": "Intervalle d’actualisation (s)" }, + "maxRetries": { "label": "Limite de reprise de compte" }, + "retryCodes": { "label": "Codes d’état de reprise" }, + "resetSessionCodes": { "label": "Codes d’état de réinitialisation de session" }, + "chatTimeout": { "label": "Délai d’attente chat (s)" }, + "imageTimeout": { "label": "Délai d’attente image (s)" }, + "videoTimeout": { "label": "Délai d’attente vidéo (s)" }, + "voiceTimeout": { "label": "Délai d’attente voix (s)" }, + "nsfwTimeout": { "label": "Délai d’attente NSFW (s)" }, + "assetUploadTimeout": { "label": "Délai d’envoi Asset (s)" }, + "assetDownloadTimeout": { "label": "Délai de téléchargement Asset (s)" }, + "assetListTimeout": { "label": "Délai de listage Asset (s)" }, + "assetDeleteTimeout": { "label": "Délai de suppression Asset (s)" }, + "streamTimeout": { "label": "Délai d’inactivité du streaming (s)" }, + "interRoundWait": { "label": "Attente inter-cycle (s)" } + } + } + }, + "cache": { + "pageTitle": "Grok2API - Gestion du Cache", + "pageHeading": "Gestion du Cache", + "pageSubtitle": "Inspectez les fichiers de cache locaux et les actifs en ligne depuis un même espace, avec des contrôles de nettoyage par type d’actif.", + "refresh": "Actualiser", + "sectionOverview": "Vue d’ensemble", + "statImageCount": "Fichiers de cache image", + "statImageSize": "Taille du cache image", + "statVideoCount": "Fichiers de cache vidéo", + "statVideoSize": "Taille du cache vidéo", + "sectionDetails": "Détails", + "tabLocal": "Cache local", + "tabOnline": "Actifs en ligne", + "typeImage": "Images", + "typeVideo": "Vidéos", + "typeImageNoun": "image", + "typeVideoNoun": "vidéo", + "clearCurrent": "Vider le cache courant", + "colFileName": "Nom du fichier", + "colSize": "Taille", + "colModified": "Dernière modification", + "colActions": "Actions", + "colToken": "Token", + "colFileCount": "Fichiers", + "onlineAssetLead": "Actifs en ligne", + "onlineAssetDesc": "sont les images et pièces jointes stockées sur la plateforme Grok. Le nettoyage n’affecte que les fichiers distants et ne supprime pas le cache local.", + "loadAssets": "Charger l’inventaire des actifs", + "clearAll": "Tout supprimer", + "cancel": "Annuler", + "assetSummary": "{accounts} comptes · {files} fichiers", + "pageIndicator": "Page {current} / {total}", + "fileCount": "{n} fichiers", + "emptyLocal": "Aucun fichier en cache trouvé", + "emptyAccounts": "Aucune donnée de compte disponible", + "actionDelete": "Supprimer", + "actionClear": "Nettoyer", + "loadFailed": "Échec du chargement : {message}", + "clearLocalConfirm": "Supprimer tous les fichiers de cache local de type {type} ?", + "clearLocalDone": "{count} fichier(s) {type} supprimé(s)", + "clearFailed": "Le nettoyage a échoué : {message}", + "deleted": "Supprimé", + "deleteFailed": "La suppression a échoué : {message}", + "loading": "Chargement...", + "refreshList": "Actualiser la liste", + "expand": "Développer", + "collapse": "Réduire", + "clearTokenConfirm": "Supprimer tous les actifs en ligne pour {token} ?", + "clearTokenDone": "{count} fichier(s) supprimé(s)", + "clearAllConfirm": "Supprimer les actifs en ligne de l’ensemble des {n} comptes ? Cette action est irréversible.", + "clearingAssets": "Nettoyage des actifs en ligne...", + "clearAllDone": "Nettoyage terminé : {ok} réussites, {fail} échecs", + "cancelled": "Annulé", + "clearFailedPlain": "Le nettoyage a échoué", + "connectionInterrupted": "Connexion interrompue", + "startFailed": "Échec du démarrage : {message}", + "cancelInProgress": "Annulation demandée. Veuillez patienter jusqu’à la fin du lot en cours.", + "na": "—" + } +} diff --git a/app/statics/i18n/ja.json b/app/statics/i18n/ja.json new file mode 100644 index 00000000..470c8cce --- /dev/null +++ b/app/statics/i18n/ja.json @@ -0,0 +1,522 @@ +{ + "common": { + "invalidKey": "無効なキーです", + "connectionFailed": "接続に失敗しました" + }, + "login": { + "adminPageTitle": "Grok2API - 管理", + "adminTitle": "管理パネル", + "adminSubtitle": "続行するには管理者パスワードを入力してください", + "adminPlaceholder": "管理者パスワード", + "continue": "続行", + "webuiPageTitle": "Grok2API - WebUI", + "webuiTitle": "WebUI", + "webuiSubtitle": "アクセスキーを入力してください", + "webuiPlaceholder": "アクセスキー", + "enter": "入る", + "goToAdmin": "管理パネルへ" + }, + "webui": { + "header": { + "badge": "WebUI", + "login": "ログイン", + "chat": "Chat", + "masonry": "Masonry", + "chatkit": "ChatKit" + }, + "login": { + "lead": "モダンな AI プロダクトに着想を得た、より軽く洗練されたチャット入口です。", + "sublead": "アクセスキーを入力すると、/webui/api/chat/completions を直接利用する会話ワークスペースを開けます。", + "helper": "言語切り替えとシームレスなアクセスキー検証に対応しています。" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "WebChat", + "eyebrow": "WebUI", + "title": "チャットワークスペース", + "subtitle": "/webui/api/chat/completions を直接使って、より落ち着いた現代的な AI チャット体験を提供します。", + "newChat": "新しいチャット", + "toggleSidebar": "サイドバーを切り替え", + "upload": "ファイルをアップロード", + "sessions": "すべてのチャット", + "noSessions": "まだチャットはありません", + "untitled": "新しいチャット", + "rename": "名前を変更", + "delete": "削除", + "edit": "編集", + "copy": "コピー", + "regenerate": "再生成", + "like": "高評価", + "dislike": "低評価", + "reasoning": "思考", + "save": "保存", + "cancel": "キャンセル", + "confirm": "確認", + "copySuccess": "コピーしました", + "renamePrompt": "チャット名を変更", + "deleteConfirm": "このチャットを削除しますか?", + "selectedFiles": "{count} 件のファイル: {names}", + "searchChat": "チャットを検索", + "images": "画像", + "library": "ライブラリ", + "recent": "最近", + "recentSample": "サンプルチャット: 何でも聞いてください", + "clear": "チャットをクリア", + "modelLabel": "モデル", + "systemLabel": "システム", + "statusLabel": "状態", + "systemPlaceholder": "任意: システムプロンプト", + "emptyTitle": "Grok Chat", + "empty": "メッセージを送信して新しい会話を始めてください。", + "promptPlaceholder": "メッセージを入力してください。Enter で送信、Shift+Enter で改行します。", + "editPlaceholder": "このメッセージを編集", + "stop": "停止", + "send": "送信", + "statusReady": "準備完了", + "statusConnecting": "接続中...", + "statusThinking": "思考中...", + "statusGenerating": "生成中...", + "statusDone": "完了", + "statusStopped": "停止済み", + "statusFailed": "失敗", + "statusInitFailed": "初期化に失敗しました", + "userLabel": "あなた", + "assistantLabel": "Grok", + "errors": { + "enterPrompt": "メッセージを入力してください", + "imageUploadsNotSupported": "ここでは画像生成にアップロードした参照画像は使えません。通常チャット、画像編集、または参照画像付き動画生成を使用してください。", + "imageRequired": "画像編集には少なくとも 1 枚の参照画像が必要です", + "imageOnly": "画像編集では画像ファイルのみアップロードできます", + "videoImageOnly": "動画生成では参照として画像のみアップロードできます", + "requestFailed": "リクエストに失敗しました", + "initFailed": "チャットページの初期化に失敗しました" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "eyebrow": "Voice", + "title": "ChatKit", + "subtitle": "Grok LiveKit の音声セッションへ直接接続し、マイク許可後すぐに会話を始められます。", + "settings": "接続設定", + "voiceLabel": "音声", + "personalityLabel": "性格", + "speedLabel": "速度", + "sessionMeta": "セッション情報", + "roomName": "ルーム", + "participantName": "識別名", + "remoteCount": "リモート", + "endpoint": "エンドポイント", + "start": "開始", + "pause": "一時停止", + "mute": "ミュート", + "unmute": "ミュート解除", + "newSession": "新しいセッション", + "logTitle": "セッションログ", + "logEmpty": "現在は待機中です。接続後、この場所にセッションイベントが表示されます。", + "clearLog": "クリア", + "statusIdle": "未接続", + "statusConnecting": "接続中", + "statusLive": "会話中", + "statusMuted": "ミュート中", + "statusPaused": "一時停止中", + "statusError": "失敗", + "idleText": "準備ができたら開始を押し、マイクへのアクセスを許可して音声セッションに入ってください。", + "connectingText": "Grok Voice セッションを要求し、LiveKit に接続しています...", + "liveText": "接続されました。これで Grok と直接会話できます。", + "mutedText": "マイクはミュートされています。会話を続けるにはミュートを解除してください。", + "pausedText": "セッションは一時停止中です。開始を押すと現在の音声セッションを再開します。", + "errorText": "接続を確立できませんでした。マイク権限を確認して再試行してください。", + "endedText": "音声セッションは終了しました。いつでも再開できます。", + "fetchingToken": "音声トークンを取得しています...", + "connected": "音声セッションに接続しました", + "disconnected": "音声セッションが切断されました", + "panelShow": "設定とログ", + "panelHide": "設定とログを隠す", + "participantJoined": "リモート参加者が参加しました: {identity}", + "participantLeft": "リモート参加者が退出しました: {identity}", + "trackSubscribed": "リモート音声を購読しました", + "micEnabled": "マイクを有効にしました", + "micMuted": "マイクをミュートしました", + "sessionPaused": "音声セッションを一時停止しました", + "sessionResumed": "音声セッションを再開しました", + "outputMuted": "スピーカーをミュートしました", + "outputUnmuted": "スピーカーのミュートを解除しました", + "startingNewSession": "新しい音声セッションを開始しています...", + "livekitLoadFailed": "LiveKit SDK の読み込みに失敗しました", + "invalidToken": "音声トークンの応答が無効です" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "subtitle": "Grok Imagine WebSocket 生成のみを使用する、独立した画像ウォーターフォールページです。", + "countLabel": "固定", + "qualityLabel": "品質", + "qualitySpeed": "速度", + "qualityQuality": "品質", + "modeLabel": "モード", + "modeRounds": "ラウンド", + "modeCycles": "サイクル", + "modeContinuous": "連続", + "modeSingle": "1 ラウンドのみ", + "promptPlaceholder": "生成したい画像を説明してください。Enter で生成、Shift+Enter で改行します。", + "generate": "生成", + "stop": "停止", + "openImage": "画像を開く", + "ratioLabel": "比率", + "statusReady": "準備完了", + "statusConnecting": "接続中...", + "statusGenerating": "生成中...", + "statusCompleted": "完了", + "statusStopped": "停止済み", + "statusFailed": "失敗", + "emptyTitle": "プロンプトから始めましょう", + "emptyText": "プロンプトを入力すると、画像がここに順番に表示されます。", + "roundLabel": "ラウンド {n}", + "batchPending": "開始待ち", + "batchFiltered": "フィルタ済み", + "batchError": "生成に失敗しました", + "errors": { + "enterPrompt": "プロンプトを入力してください", + "requestFailed": "リクエストに失敗しました", + "initFailed": "Masonry ページの初期化に失敗しました" + } + } + }, + "header": { + "account": "アカウント管理", + "config": "構成管理", + "cache": "キャッシュ管理", + "languageLabel": "言語", + "switchLanguage": "言語を切り替え", + "logout": "ログアウト", + "versionDialogTitle": "バージョン", + "versionCurrent": "現在", + "versionLatest": "最新", + "versionPublishedAt": "公開日", + "versionUpToDate": "すでに最新バージョンです。", + "versionUpdateAvailable": "新しいバージョンがあります。", + "versionChecking": "更新を確認しています...", + "versionUnavailable": "更新の確認に失敗しました。", + "versionNotesEmpty": "リリースノートはありません。", + "versionOpenRelease": "リリースを開く", + "versionClose": "閉じる" + }, + "account": { + "pageTitle": "Grok2API - アカウント", + "nav": "アカウント管理", + "pageHeading": "アカウント管理", + "pageSubtitle": "Grok2API で使用する xAI アカウントプール、クォータ状況、実行状態を管理します。", + "actionImport": "アカウントをインポート", + "actionAdd": "アカウントを追加", + "sectionOverview": "概要", + "sectionTable": "アカウント一覧", + "statTotal": "総アカウント数", + "statActive": "有効", + "statCooling": "レート制限中", + "statInvalid": "利用不可", + "statAuto": "Auto 残量", + "statFast": "Fast 残量", + "statExpert": "Expert 残量", + "statHeavy": "Heavy 残量", + "tabAll": "すべて", + "tabActive": "有効", + "tabCooling": "レート制限中", + "tabInvalid": "利用不可", + "tabNsfw": "NSFW 有効", + "tabNonNsfw": "NSFW 無効", + "filterStatusLabel": "状態", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "タイプ", + "filterStatusAll": "すべて", + "filterStatusActive": "有効", + "filterStatusCooling": "レート制限中", + "filterStatusInvalid": "利用不可", + "filterNsfwAll": "すべて", + "filterNsfwEnabled": "オン", + "filterNsfwDisabled": "オフ", + "filterTypeAll": "すべて", + "export": "データをエクスポート", + "batchNsfw": "NSFW を有効化", + "batchNsfwDisable": "NSFW を無効化", + "batchRefresh": "選択項目を更新", + "batchDelete": "選択項目を削除", + "colToken": "トークン", + "colType": "アカウント種別", + "colStatus": "実行状態", + "colQuota": "クォータ", + "colSuccess": "成功", + "colFail": "失敗", + "colRate": "成功率", + "colLastUsed": "最終使用", + "colActions": "操作", + "actionCopy": "コピー", + "actionRefresh": "クォータを更新", + "actionEdit": "編集", + "actionDelete": "削除", + "empty": "アカウントがありません。右上の「アカウントをインポート」または「アカウントを追加」を使用してください。", + "pageInfo": "合計 {n} 件", + "pageSizeOption": "{n} / ページ", + "backendCount": "{n} アカウント", + "backendOffline": "利用不可", + "addTitle": "アカウントを追加", + "addHint": "1 行につき 1 トークンを入力してください。既存トークンは自動的にスキップされます。", + "addPlaceholder": "トークンを貼り付けてください(1 行につき 1 件)...", + "importTitle": "アカウントをインポート", + "importHintDefault": ".txt(1 行につき 1 トークン)および .json({pool:[tokens]})形式に対応しています。", + "importHintJson": "JSON にはアカウント種別情報が含まれているため、追加選択は不要です。", + "importHintTxt": "1 行につき 1 トークンを入力してください。インポートしたトークンは選択したアカウント種別へ追加されます。", + "labelType": "タイプ", + "labelFile": "ファイル", + "editTitle": "アカウントを編集", + "editTokenPlaceholder": "更新後のトークンを入力", + "exportTitle": "アカウントをエクスポート", + "exportCountPrefix": "", + "exportCountSuffix": " トークン", + "exportJson": "JSON 形式(完全なエクスポート。バージョン間互換性は保証されません)", + "exportTxt": "TXT 形式(トークンのみ。すべてのバージョンと互換)", + "confirmTitle": "操作の確認", + "cancel": "キャンセル", + "confirm": "確認", + "save": "変更を保存", + "noFile": "ファイルが選択されていません", + "copied": "コピーしました", + "copyFailed": "コピーに失敗しました", + "loadFailed": "読み込みに失敗しました", + "notFound": "アカウントが見つかりません", + "enterToken": "トークンを入力してください", + "selectFile": "ファイルを選択してください", + "readFileFailed": "ファイルの読み取りに失敗しました", + "jsonInvalid": "JSON 形式が不正です", + "jsonShapeInvalid": "JSON 構造が不正です。{pool:[tokens]} を想定しています。", + "jsonEmpty": "JSON ファイルにインポート可能なトークンがありません", + "fileEmpty": "ファイルにインポート可能なトークンがありません", + "adding": "{n} 件のアカウントを追加しています…", + "addDone": "アカウントを追加しました", + "addFailed": "アカウントの追加に失敗しました", + "importing": "{n} 件のアカウントをインポートしています…", + "importDone": "インポートが完了しました", + "importJsonDone": "インポート完了: {n} 件を処理しました", + "importFailed": "インポートに失敗しました", + "saving": "変更を保存しています…", + "editDone": "変更を保存しました", + "editFailed": "変更の保存に失敗しました", + "saveResult": "{prefix}: {count} 件のアカウントを追加しました", + "saveResultSkipped": "{prefix}: {count} 件を追加、{skipped} 件は既存のためスキップしました", + "exportEmpty": "エクスポート可能なアカウントがありません", + "deleteConfirmTitle": "削除の確認", + "deleteConfirmOne": "{token} を削除しますか?
この操作は元に戻せません。", + "deleteConfirmMany": "{n} 件のアカウントを削除しますか?
この操作は元に戻せません。", + "deleting": "{n} 件のアカウントを削除しています…", + "deleteDone": "{n} 件を削除しました", + "deleteFailed": "削除に失敗しました", + "refreshing": "{n} 件のアカウントのクォータ情報を更新しています…", + "refreshDone": "更新完了: 成功 {ok} 件、失敗 {fail} 件", + "refreshFailed": "更新に失敗しました", + "nsfwConfirmTitle": "NSFW を有効化", + "nsfwConfirmBody": "選択した {n} 件のアカウントで NSFW を有効にしますか?", + "nsfwEnablingOne": "NSFW を有効化しています…", + "nsfwEnabling": "{n} 件のアカウントで NSFW を有効化しています…", + "nsfwDone": "NSFW 更新完了: 成功 {ok} 件、失敗 {fail} 件", + "nsfwDisablingOne": "NSFW を無効化しています…", + "nsfwDisableDone": "NSFW 無効化完了: 成功 {ok} 件、失敗 {fail} 件", + "nsfwEnabledTitle": "有効", + "operationFailed": "操作に失敗しました", + "unknown": "不明", + "na": "—", + "pool": { + "autoRecommended": "自動判定(推奨)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy" + }, + "status": { + "active": "有効", + "cooling": "レート制限中", + "expired": "期限切れ", + "invalid": "利用不可" + } + }, + "config": { + "pageTitle": "Grok2API - 構成管理", + "pageHeading": "構成管理", + "pageSubtitle": "ランタイム設定とサービス挙動を一元管理します。再起動が必要な項目を除き、変更は即時に反映されます。", + "resetChanges": "変更をリセット", + "saveChanges": "変更を保存", + "unsavedDefault": "未保存の変更があります", + "unsavedSingle": "未保存の変更が 1 件あります", + "unsavedMultiple": "未保存の変更が {n} 件あります", + "discardChanges": "変更を破棄", + "randomize": "値を生成", + "loadFailed": "構成の読み込みに失敗しました: {message}", + "saving": "変更を保存しています...", + "saveSuccess": "変更を保存しました", + "saveFailed": "変更の保存に失敗しました: {message}", + "resetSuccess": "未保存の変更を破棄しました", + "disabledTip": { + "appUrlRequired": "先に APP Base URL を設定してください" + }, + "schema": { + "tabs": { + "system": "システム", + "features": "機能", + "schedule": "スケジュール", + "proxy": "ネットワーク", + "image": "画像処理" + }, + "groups": { + "baseAccess": "アクセス制御", + "features": "基本機能", + "mediaFormat": "メディア出力", + "refreshSchedule": "クォータ更新", + "batchConcurrency": "一括処理の並列数", + "egressProxy": "送信プロキシ", + "clearance": "Cloudflare Clearance", + "retry": "再試行ポリシー", + "timeouts": "リクエストタイムアウト", + "imageProtocol": "NSFW と画像ストリーミング" + }, + "options": { + "imageFormat": { + "grokUrl": "URL(Grok ネイティブ)", + "localUrl": "URL(ローカルプロキシ)", + "grokMarkdown": "Markdown(Grok ネイティブ)", + "localMarkdown": "Markdown(ローカルプロキシ)", + "base64": "Base64(埋め込み)" + }, + "videoFormat": { + "grokUrl": "URL(Grok ネイティブ)", + "localUrl": "URL(ローカルプロキシ)", + "grokHtml": "HTML(Grok ネイティブ)", + "localHtml": "HTML(ローカルプロキシ)" + }, + "proxyMode": { + "direct": "直接接続", + "singleProxy": "固定プロキシ", + "proxyPool": "プロキシプール" + }, + "clearanceMode": { + "none": "無効", + "manual": "手動", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { "label": "APP ベース URL" }, + "appKey": { "label": "APP アクセスパスワード" }, + "apiKey": { "label": "API アクセスキー" }, + "webuiEnabled": { "label": "WebUI を有効化" }, + "webuiKey": { "label": "WebUI アクセスパスワード" }, + "temporary": { "label": "一時セッション" }, + "memory": { "label": "会話メモリ" }, + "stream": { "label": "デフォルトのストリーミング" }, + "thinking": { "label": "デフォルトの推論出力" }, + "dynamicStatsig": { "label": "動的 Statsig" }, + "enableNsfw": { "label": "NSFW 生成を許可" }, + "customInstruction": { "label": "グローバル補助指示" }, + "imageFormat": { "label": "画像出力形式" }, + "videoFormat": { "label": "動画出力形式" }, + "basicInterval": { "label": "Basic 更新間隔(秒)" }, + "superInterval": { "label": "Super 更新間隔(秒)" }, + "heavyInterval": { "label": "Heavy 更新間隔(秒)" }, + "usageConcurrency": { "label": "更新並列数" }, + "onDemandMinInterval": { "label": "最小オンデマンド更新間隔(秒)" }, + "nsfwConcurrency": { "label": "NSFW 有効化の並列数" }, + "refreshConcurrency": { "label": "Usage 更新の並列数" }, + "assetUploadConcurrency": { "label": "Asset アップロード並列数" }, + "assetListConcurrency": { "label": "Asset 一覧取得並列数" }, + "assetDeleteConcurrency": { "label": "Asset 削除並列数" }, + "proxyMode": { "label": "プロキシモード" }, + "proxyUrl": { "label": "プライマリプロキシ URL" }, + "resourceProxyUrl": { "label": "リソースプロキシ URL" }, + "proxyPool": { "label": "プライマリプロキシプール" }, + "resourceProxyPool": { "label": "リソースプロキシプール" }, + "skipSslVerify": { "label": "SSL 検証をスキップ" }, + "clearanceMode": { "label": "Clearance モード" }, + "browserFingerprint": { "label": "ブラウザフィンガープリント" }, + "userAgent": { "label": "User-Agent" }, + "cfCookies": { "label": "Cloudflare Cookies" }, + "flaresolverrUrl": { "label": "FlareSolverr URL" }, + "challengeTimeout": { "label": "チャレンジタイムアウト(秒)" }, + "refreshInterval": { "label": "更新間隔(秒)" }, + "maxRetries": { "label": "アカウント再試行上限" }, + "retryCodes": { "label": "再試行対象のステータスコード" }, + "resetSessionCodes": { "label": "セッション再構築対象のステータスコード" }, + "chatTimeout": { "label": "チャットリクエストタイムアウト(秒)" }, + "imageTimeout": { "label": "画像リクエストタイムアウト(秒)" }, + "videoTimeout": { "label": "動画リクエストタイムアウト(秒)" }, + "voiceTimeout": { "label": "音声リクエストタイムアウト(秒)" }, + "nsfwTimeout": { "label": "NSFW 処理タイムアウト(秒)" }, + "assetUploadTimeout": { "label": "Asset アップロードタイムアウト(秒)" }, + "assetDownloadTimeout": { "label": "Asset ダウンロードタイムアウト(秒)" }, + "assetListTimeout": { "label": "Asset 一覧タイムアウト(秒)" }, + "assetDeleteTimeout": { "label": "Asset 削除タイムアウト(秒)" }, + "streamTimeout": { "label": "ストリーミング待機タイムアウト(秒)" }, + "interRoundWait": { "label": "ラウンド間待機時間(秒)" } + } + } + }, + "cache": { + "pageTitle": "Grok2API - キャッシュ管理", + "pageHeading": "キャッシュ管理", + "pageSubtitle": "ローカルキャッシュファイルとオンラインアセットを一元確認し、種類ごとにクリーンアップできます。", + "refresh": "更新", + "sectionOverview": "概要", + "statImageCount": "画像キャッシュ数", + "statImageSize": "画像キャッシュ容量", + "statVideoCount": "動画キャッシュ数", + "statVideoSize": "動画キャッシュ容量", + "sectionDetails": "詳細", + "tabLocal": "ローカルキャッシュ", + "tabOnline": "オンラインアセット", + "typeImage": "画像", + "typeVideo": "動画", + "typeImageNoun": "画像", + "typeVideoNoun": "動画", + "clearCurrent": "現在のキャッシュを消去", + "colFileName": "ファイル名", + "colSize": "サイズ", + "colModified": "更新日時", + "colActions": "操作", + "colToken": "トークン", + "colFileCount": "ファイル数", + "onlineAssetLead": "オンラインアセット", + "onlineAssetDesc": "は Grok プラットフォーム側に保存された画像と添付ファイルです。クリーンアップはリモートファイルのみに影響し、ローカルキャッシュは削除しません。", + "loadAssets": "アセット一覧を読み込む", + "clearAll": "すべて消去", + "cancel": "キャンセル", + "assetSummary": "{accounts} アカウント · {files} ファイル", + "pageIndicator": "{current} / {total} ページ", + "fileCount": "{n} ファイル", + "emptyLocal": "キャッシュファイルはありません", + "emptyAccounts": "アカウントデータがありません", + "actionDelete": "削除", + "actionClear": "消去", + "loadFailed": "読み込みに失敗しました: {message}", + "clearLocalConfirm": "ローカルの{type}キャッシュをすべて消去しますか?", + "clearLocalDone": "{count} 件の{type}ファイルを削除しました", + "clearFailed": "消去に失敗しました: {message}", + "deleted": "削除しました", + "deleteFailed": "削除に失敗しました: {message}", + "loading": "読み込み中...", + "refreshList": "一覧を更新", + "expand": "展開", + "collapse": "折りたたむ", + "clearTokenConfirm": "{token} のオンラインアセットをすべて削除しますか?", + "clearTokenDone": "{count} 件のファイルを削除しました", + "clearAllConfirm": "{n} 件のアカウントのオンラインアセットをすべて削除しますか?この操作は元に戻せません。", + "clearingAssets": "オンラインアセットを削除しています...", + "clearAllDone": "クリーンアップ完了: 成功 {ok} 件、失敗 {fail} 件", + "cancelled": "キャンセルしました", + "clearFailedPlain": "クリーンアップに失敗しました", + "connectionInterrupted": "接続が中断されました", + "startFailed": "開始に失敗しました: {message}", + "cancelInProgress": "キャンセルを要求しました。現在のバッチ完了までお待ちください。", + "na": "—" + } +} diff --git a/app/statics/i18n/zh.json b/app/statics/i18n/zh.json index f247146d..5f385bf5 100644 --- a/app/statics/i18n/zh.json +++ b/app/statics/i18n/zh.json @@ -16,60 +16,660 @@ "enter": "进入", "goToAdmin": "进入管理后台" }, + "header": { + "account": "账户管理", + "config": "配置管理", + "cache": "缓存管理", + "languageLabel": "语言", + "switchLanguage": "切换语言", + "logout": "退出登录", + "versionDialogTitle": "版本信息", + "versionCurrent": "当前版本", + "versionLatest": "最新版本", + "versionPublishedAt": "发布时间", + "versionUpToDate": "当前已经是最新版本。", + "versionUpdateAvailable": "发现新版本可用。", + "versionChecking": "正在检查更新...", + "versionUnavailable": "查询更新失败。", + "versionNotesEmpty": "暂无更新说明。", + "versionOpenRelease": "查看发布页", + "versionClose": "关闭" + }, + "webui": { + "header": { + "badge": "WebUI", + "login": "登录", + "chat": "聊天", + "masonry": "瀑布流", + "chatkit": "ChatKit" + }, + "login": { + "lead": "一个更轻、更像现代 AI 产品的聊天入口。", + "sublead": "输入访问密钥后即可进入对话工作区,直接走 /webui/api/chat/completions。", + "helper": "支持语言切换与无刷新的密钥校验。" + }, + "chat": { + "pageTitle": "Grok2API - WebChat", + "sidebarTitle": "WebChat", + "eyebrow": "WebUI", + "title": "聊天工作台", + "subtitle": "直接通过 /webui/api/chat/completions 发起对话,页面体验更接近现代 AI 对话产品。", + "newChat": "新建聊天", + "toggleSidebar": "折叠侧边栏", + "upload": "上传文件", + "sessions": "所有会话", + "noSessions": "暂无会话", + "untitled": "新建聊天", + "rename": "改名", + "delete": "删除", + "edit": "编辑", + "copy": "复制", + "regenerate": "重新生成", + "like": "点赞", + "dislike": "点踩", + "reasoning": "思考过程", + "save": "保存", + "cancel": "取消", + "confirm": "确认", + "copySuccess": "已复制", + "renamePrompt": "修改会话名称", + "deleteConfirm": "确定删除这个会话吗?", + "selectedFiles": "{count} 个文件:{names}", + "searchChat": "搜索聊天", + "images": "图片", + "library": "库", + "recent": "最近", + "recentSample": "示例聊天:有问题,尽管问", + "clear": "清空对话", + "modelLabel": "模型", + "systemLabel": "系统提示词", + "statusLabel": "状态", + "systemPlaceholder": "可选:System Prompt", + "emptyTitle": "Grok Chat", + "empty": "输入一条消息开始新的会话。", + "promptPlaceholder": "输入你的问题,Enter 发送,Shift+Enter 换行", + "editPlaceholder": "编辑这条消息", + "stop": "停止", + "send": "发送", + "statusReady": "就绪", + "statusConnecting": "正在连接…", + "statusThinking": "思考中…", + "statusGenerating": "生成中…", + "statusDone": "完成", + "statusStopped": "已停止", + "statusFailed": "失败", + "statusInitFailed": "初始化失败", + "userLabel": "你", + "assistantLabel": "Grok", + "errors": { + "enterPrompt": "请输入内容", + "imageUploadsNotSupported": "当前图像生成模式不支持上传参考图。请使用普通聊天、图像编辑或带参考图的视频生成。", + "imageRequired": "图像编辑至少需要上传一张参考图", + "imageOnly": "图像编辑只支持上传图片", + "videoImageOnly": "视频生成只支持上传图片作为参考图", + "requestFailed": "请求失败", + "initFailed": "聊天页面初始化失败" + } + }, + "chatkit": { + "pageTitle": "Grok2API - ChatKit", + "eyebrow": "Voice", + "title": "ChatKit", + "subtitle": "直接连接 Grok LiveKit 语音会话,打开麦克风即可开始对话。", + "settings": "连接设置", + "voiceLabel": "声音", + "personalityLabel": "个性", + "speedLabel": "语速", + "sessionMeta": "会话信息", + "roomName": "房间", + "participantName": "身份", + "remoteCount": "远端", + "endpoint": "端点", + "start": "开始", + "pause": "暂停", + "mute": "静音", + "unmute": "取消静音", + "newSession": "新会话", + "logTitle": "会话日志", + "logEmpty": "待机中,连接后这里会显示会话事件。", + "clearLog": "清空", + "statusIdle": "未连接", + "statusConnecting": "正在连接", + "statusLive": "语音中", + "statusMuted": "已静音", + "statusPaused": "已暂停", + "statusError": "连接失败", + "idleText": "准备好后点击开始,授权麦克风即可进入语音会话。", + "connectingText": "正在向 Grok Voice 申请会话并连接 LiveKit…", + "liveText": "连接已建立,现在可以直接开口和 Grok 对话。", + "mutedText": "你的麦克风已静音,恢复后可继续语音对话。", + "pausedText": "会话已暂停,点击开始即可继续当前语音会话。", + "errorText": "连接没有建立成功,请检查麦克风权限后重试。", + "endedText": "语音会话已结束,可以重新开始。", + "fetchingToken": "正在申请语音 token…", + "connected": "语音会话已连接", + "disconnected": "语音会话已断开", + "panelShow": "设置与日志", + "panelHide": "收起设置与日志", + "participantJoined": "远端参与者已加入:{identity}", + "participantLeft": "远端参与者已离开:{identity}", + "trackSubscribed": "远端音频已订阅", + "micEnabled": "麦克风已开启", + "micMuted": "麦克风已静音", + "sessionPaused": "语音会话已暂停", + "sessionResumed": "语音会话已继续", + "outputMuted": "扬声器已静音", + "outputUnmuted": "扬声器已取消静音", + "startingNewSession": "正在启动新会话…", + "livekitLoadFailed": "LiveKit SDK 加载失败", + "invalidToken": "语音 token 返回无效" + }, + "masonry": { + "pageTitle": "Grok2API - Masonry", + "title": "Masonry", + "subtitle": "独立的图像瀑布流页面,只走 Grok Imagine WebSocket 出图。", + "countLabel": "固定", + "qualityLabel": "质量", + "qualitySpeed": "速度", + "qualityQuality": "质量", + "modeLabel": "模式", + "modeRounds": "轮次", + "modeCycles": "循环", + "modeContinuous": "一直出图", + "modeSingle": "只出一轮", + "promptPlaceholder": "描述你想生成的画面,Enter 生成,Shift+Enter 换行", + "generate": "生成", + "stop": "停止", + "openImage": "打开图片", + "ratioLabel": "比例", + "statusReady": "就绪", + "statusConnecting": "连接中…", + "statusGenerating": "生成中…", + "statusCompleted": "完成", + "statusStopped": "已停止", + "statusFailed": "失败", + "emptyTitle": "从一句提示词开始", + "emptyText": "输入提示词后,图片会按顺序显示在这里。", + "roundLabel": "第 {n} 轮", + "batchPending": "等待开始", + "batchFiltered": "已过滤", + "batchError": "生成失败", + "errors": { + "enterPrompt": "请输入提示词", + "requestFailed": "请求失败", + "initFailed": "瀑布流页面初始化失败" + } + } + }, "account": { "pageTitle": "Grok2API - 账户管理", - "nav": "账户", - "statTotal": "总账户", - "statActive": "活跃", - "statCooling": "冷却中", - "statInvalid": "失效", - "statQuota": "总配额", - "statCalls": "总调用", + "nav": "账户管理", + "pageHeading": "账户管理", + "pageSubtitle": "统一管理 Grok2API 的 xAI 账户池、额度与运行状态。", + "actionImport": "导入账户", + "actionAdd": "新增账户", + "sectionOverview": "概览", + "sectionTable": "账户列表", + "statTotal": "账户总数", + "statActive": "正常账户", + "statCooling": "限流账户", + "statInvalid": "异常账户", + "statAuto": "Auto 剩余额度", + "statFast": "Fast 剩余额度", + "statExpert": "Expert 剩余额度", + "statHeavy": "Heavy 剩余额度", "tabAll": "全部", - "tabActive": "活跃", - "tabCooling": "冷却", - "tabInvalid": "失效", - "export": "导出", - "import": "批量导入", + "tabActive": "正常", + "tabCooling": "限流", + "tabInvalid": "异常", + "tabNsfw": "已启用 NSFW", + "tabNonNsfw": "未启用 NSFW", + "filterStatusLabel": "状态", + "filterNsfwLabel": "NSFW", + "filterTypeLabel": "类型", + "filterStatusAll": "全部", + "filterStatusActive": "正常", + "filterStatusCooling": "限流", + "filterStatusInvalid": "异常", + "filterNsfwAll": "全部", + "filterNsfwEnabled": "开启", + "filterNsfwDisabled": "关闭", + "filterTypeAll": "全部", + "export": "导出数据", "batchNsfw": "开启 NSFW", + "batchNsfwDisable": "关闭 NSFW", "batchRefresh": "刷新选中", "batchDelete": "删除选中", "colToken": "Token", - "colPool": "Pool", - "colStatus": "状态", - "colQuota": "配额", - "colCalls": "调用", + "colType": "账户类型", + "colStatus": "运行状态", + "colQuota": "额度信息", + "colSuccess": "成功", + "colFail": "失败", + "colRate": "成功率", "colLastUsed": "最近使用", - "colFails": "失败次数", "colActions": "操作", "actionCopy": "复制", - "actionRefresh": "刷新", + "actionRefresh": "刷新额度", + "actionEdit": "编辑", "actionDelete": "删除", - "empty": "暂无数据", - "importTitle": "批量导入账户", - "importHint": "每行一个 Token(新 Token 将追加到所选 Pool)", - "importPlaceholder": "粘贴 Token,每行一个...", - "importPool": "Pool:", + "empty": "暂无账户,请使用右上角的“导入账户”或“新增账户”。", + "pageInfo": "共 {n} 条", + "pageSizeOption": "{n} / 页", + "backendCount": "{n} 个账户", + "backendOffline": "未连接", + "addTitle": "新增账户", + "addHint": "每行一个 Token;已存在的 Token 将自动跳过。", + "addPlaceholder": "粘贴 Token,每行一个...", + "importTitle": "导入账户", + "importHintDefault": "支持 .txt(每行一个 Token)与 .json({pool:[tokens]})两种格式。", + "importHintJson": "JSON 文件已包含账户类型信息,无需额外选择。", + "importHintTxt": "每行一个 Token,导入后将追加到所选账户类型。", + "labelType": "类型", + "labelFile": "文件", + "editTitle": "编辑账户", + "editTokenPlaceholder": "请输入新的 Token", + "exportTitle": "导出账户", + "exportCountPrefix": "共 ", + "exportCountSuffix": " 个 Token", + "exportJson": "JSON 格式(完整导出,但跨版本可能不兼容)", + "exportTxt": "TXT 格式(仅导出 Token,兼容所有版本)", + "confirmTitle": "确认操作", "cancel": "取消", "confirm": "确认", + "save": "保存更改", + "noFile": "未选择文件", "copied": "已复制", "copyFailed": "复制失败", "loadFailed": "加载失败", - "importDone": "导入完成,新增 {n} 个 Token", + "notFound": "未找到该账户", + "enterToken": "请输入 Token", + "selectFile": "请选择文件", + "readFileFailed": "读取文件失败", + "jsonInvalid": "JSON 格式错误", + "jsonShapeInvalid": "JSON 结构无效,应为 {pool:[tokens]}。", + "jsonEmpty": "JSON 文件中没有可导入的 Token", + "fileEmpty": "文件中没有可导入的 Token", + "adding": "正在添加 {n} 个账户…", + "addDone": "新增完成", + "addFailed": "新增失败", + "importing": "正在导入 {n} 个账户…", + "importDone": "导入完成", + "importJsonDone": "导入完成,共 {n} 个", "importFailed": "导入失败", + "saving": "正在保存修改…", + "editDone": "保存完成", + "editFailed": "保存失败", + "saveResult": "{prefix},新增 {count} 个账户", + "saveResultSkipped": "{prefix},新增 {count} 个,跳过已存在 {skipped} 个", + "exportEmpty": "当前没有可导出的账户", + "deleteConfirmTitle": "确认删除", + "deleteConfirmOne": "确认删除 {token}?
此操作不可撤销。", + "deleteConfirmMany": "确认删除 {n} 个账户?
此操作不可撤销。", + "deleting": "正在删除 {n} 个账户…", "deleteDone": "已删除 {n} 个", "deleteFailed": "删除失败", - "refreshing": "正在刷新 {n} 个账户…", - "refreshDone": "刷新完成:成功 {ok},失败 {fail}", + "refreshing": "正在刷新 {n} 个账户的额度信息…", + "refreshDone": "刷新完成:成功 {ok} 个,失败 {fail} 个", "refreshFailed": "刷新失败", - "nsfwConfirmTitle": "开启 NSFW", - "nsfwConfirmBody": "为选中的 {n} 个账户开启 NSFW?", - "nsfwFailed": "操作失败", - "deleteConfirmTitle": "确认删除", - "statusActive": "活跃", - "statusCooling": "冷却", - "statusExpired": "过期", - "statusInvalid": "失效", - "logout": "退出" + "nsfwConfirmTitle": "启用 NSFW", + "nsfwConfirmBody": "确认为选中的 {n} 个账户启用 NSFW?", + "nsfwEnablingOne": "正在启用 NSFW…", + "nsfwEnabling": "正在为 {n} 个账户启用 NSFW…", + "nsfwDone": "NSFW 设置完成:成功 {ok} 个,失败 {fail} 个", + "nsfwDisablingOne": "正在关闭 NSFW…", + "nsfwDisableDone": "NSFW 关闭完成:成功 {ok} 个,失败 {fail} 个", + "nsfwEnabledTitle": "已启用", + "operationFailed": "操作失败", + "unknown": "未知", + "na": "—", + "pool": { + "autoRecommended": "自动检测(推荐)", + "basic": "Basic", + "super": "Super", + "heavy": "Heavy" + }, + "mode": { + "auto": "Auto", + "fast": "Fast", + "expert": "Expert", + "heavy": "Heavy" + }, + "status": { + "active": "正常", + "cooling": "限流", + "expired": "过期", + "invalid": "异常" + } + }, + "config": { + "pageTitle": "Grok2API - 配置管理", + "pageHeading": "配置管理", + "pageSubtitle": "统一管理运行时参数与服务行为。保存后即时生效,部分配置需重启服务。", + "resetChanges": "重置更改", + "saveChanges": "保存更改", + "unsavedDefault": "存在未保存的更改", + "unsavedSingle": "存在 1 项未保存的更改", + "unsavedMultiple": "存在 {n} 项未保存的更改", + "discardChanges": "放弃更改", + "randomize": "随机生成", + "loadFailed": "配置加载失败:{message}", + "saving": "正在保存更改…", + "saveSuccess": "更改已保存", + "saveFailed": "保存更改失败:{message}", + "resetSuccess": "未保存的更改已撤销", + "disabledTip": { + "appUrlRequired": "请先填写 APP 访问地址" + }, + "schema": { + "tabs": { + "system": "系统配置", + "features": "应用功能", + "schedule": "任务调度", + "proxy": "网络代理", + "image": "图像能力" + }, + "groups": { + "baseAccess": "基础访问控制", + "features": "基本功能设置", + "mediaFormat": "媒体返回格式", + "refreshSchedule": "配额刷新调度", + "batchConcurrency": "批量操作并发", + "egressProxy": "出站代理设置", + "clearance": "Cloudflare Clearance", + "retry": "重试策略", + "timeouts": "请求超时设置", + "imageProtocol": "NSFW 与图像协议" + }, + "options": { + "imageFormat": { + "grokUrl": "URL(Grok 原生)", + "localUrl": "URL(本地代理)", + "grokMarkdown": "Markdown(Grok 原生)", + "localMarkdown": "Markdown(本地代理)", + "base64": "Base64(内嵌)" + }, + "videoFormat": { + "grokUrl": "URL(Grok 原生)", + "localUrl": "URL(本地代理)", + "grokHtml": "HTML(Grok 原生)", + "localHtml": "HTML(本地代理)" + }, + "proxyMode": { + "direct": "直连", + "singleProxy": "代理(固定)", + "proxyPool": "代理(轮转)" + }, + "clearanceMode": { + "none": "关闭", + "manual": "手动", + "flaresolverr": "FlareSolverr" + } + }, + "fields": { + "appUrl": { + "label": "APP 访问地址", + "desc": "应用对外提供服务的根 URL,格式如 https://your-domain.com。本地代理模式必须配置。" + }, + "appKey": { + "label": "APP 访问密码", + "desc": "管理后台鉴权密码。修改后已有 Session 将立即失效,需重新登录。" + }, + "apiKey": { + "label": "API 调用密钥", + "desc": "OpenAI 兼容 API 的鉴权密钥。多个值请使用英文逗号分隔;留空则禁用鉴权。" + }, + "webuiEnabled": { + "label": "启用 WebUI", + "desc": "开放 WebUI 功能入口。关闭后相关路由将返回 404。" + }, + "webuiKey": { + "label": "WebUI 访问密码", + "desc": "WebUI 的访问鉴权密码。配置后访问时必须提供。" + }, + "temporary": { + "label": "临时会话", + "desc": "启用后请求不会写入 Grok 会话历史,等同于无痕对话。" + }, + "memory": { + "label": "开启会话记忆", + "desc": "启用 Grok Memory,允许模型跨会话记忆用户偏好与上下文。" + }, + "stream": { + "label": "默认流式输出", + "desc": "请求未显式指定 stream 参数时所采用的默认值。" + }, + "thinking": { + "label": "默认思考输出", + "desc": "请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。" + }, + "dynamicStatsig": { + "label": "动态 Statsig", + "desc": "为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。" + }, + "enableNsfw": { + "label": "允许 NSFW 生成", + "desc": "允许图像生成接口绕过 NSFW 内容过滤。" + }, + "customInstruction": { + "label": "全局附加指令", + "desc": "为每次请求注入统一的 system 消息,用于约束模型行为或固定角色设定。" + }, + "imageFormat": { + "label": "图片返回格式", + "desc": "grok_url / grok_md 直接返回 Grok CDN 地址,客户端需具备 CDN 访问能力;local_* 模式会先下载到服务端,再通过本地 URL 代理分发;base64 会以内嵌 Data URI 返回。" + }, + "videoFormat": { + "label": "视频返回格式", + "desc": "local_* 模式会先将视频下载至服务端,再通过本地 URL 代理分发;请确保已配置 APP 访问地址,并评估出站带宽消耗。" + }, + "basicInterval": { + "label": "Basic 刷新周期(秒)", + "desc": "basic 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 36000 s / 10 h)。" + }, + "superInterval": { + "label": "Super 刷新周期(秒)", + "desc": "super 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 7200 s / 2 h)。" + }, + "heavyInterval": { + "label": "Heavy 刷新周期(秒)", + "desc": "heavy 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 7200 s / 2 h)。" + }, + "usageConcurrency": { + "label": "刷新并发数", + "desc": "并发调用 usage 接口刷新额度时允许的最大并行数。" + }, + "onDemandMinInterval": { + "label": "按需刷新最小间隔(秒)", + "desc": "请求链路触发刷新(例如收到 429)时的节流间隔。N 秒内重复触发只执行一次,避免批量打爆配额接口。" + }, + "nsfwConcurrency": { + "label": "开启 NSFW 并发数", + "desc": "批量开启 NSFW 时的 token 级并发数;每个 token 需经历三步网络请求。" + }, + "refreshConcurrency": { + "label": "刷新 Usage 并发数", + "desc": "批量刷新账户额度时的 token 级并发数。" + }, + "assetUploadConcurrency": { + "label": "上传 Asset 并发数", + "desc": "API 接收文件附件后触发的 Asset 上传任务,全局最大并发数,跨所有请求共享。" + }, + "assetListConcurrency": { + "label": "查询 Asset 并发数", + "desc": "list_assets 接口的全局最大并发数,跨所有请求共享。" + }, + "assetDeleteConcurrency": { + "label": "删除 Asset 并发数", + "desc": "delete_asset 接口的全局最大并发数,同时作为管理后台批量清理的 token 级默认并发值。" + }, + "proxyMode": { + "label": "代理模式", + "desc": "控制出站流量代理策略。direct 为直连;single_proxy 使用固定代理;proxy_pool 在代理池中轮转。" + }, + "proxyUrl": { + "label": "基础代理 URL", + "desc": "API 流量的出站代理地址,支持 http、https、socks5 协议。" + }, + "resourceProxyUrl": { + "label": "资源代理 URL", + "desc": "图片、视频等媒体资源下载的专用代理地址;留空时回落至基础代理。" + }, + "proxyPool": { + "label": "基础代理池", + "desc": "API 流量代理池,每行一个代理 URL,请求时轮转使用。" + }, + "resourceProxyPool": { + "label": "资源代理池", + "desc": "媒体资源下载专用代理池,每行一个代理 URL;留空时回落至基础代理池。" + }, + "skipSslVerify": { + "label": "跳过 SSL 校验", + "desc": "跳过代理服务器 TLS 证书校验,仅在使用自签名证书的代理时启用。" + }, + "clearanceMode": { + "label": "Clearance 校准", + "desc": "控制 Cloudflare Clearance 的获取方式。" + }, + "browserFingerprint": { + "label": "浏览器指纹", + "desc": "curl_cffi 浏览器指纹标识,需与 Cloudflare 期望的 JA3 指纹匹配,例如 chrome136。" + }, + "userAgent": { + "label": "User-Agent", + "desc": "请求头中的 User-Agent,需与 Cloudflare 校验 Cookie 时所使用的浏览器保持一致。" + }, + "cfCookies": { + "label": "Cloudflare Cookies", + "desc": "Cloudflare 下发的完整 Cookie 字符串,应包含 cf_clearance 等字段。" + }, + "flaresolverrUrl": { + "label": "FlareSolverr URL", + "desc": "FlareSolverr 实例的 HTTP 服务地址。" + }, + "challengeTimeout": { + "label": "挑战超时(秒)", + "desc": "FlareSolverr 完成 Cloudflare 挑战允许的最长等待时长。" + }, + "refreshInterval": { + "label": "刷新间隔(秒)", + "desc": "Clearance Cookie 预热刷新任务的调度间隔。" + }, + "maxRetries": { + "label": "应用层重试上限", + "desc": "请求失败后的应用层最大重试次数;0 表示不重试。适用于 chat.completions 与 responses 端点。" + }, + "retryCodes": { + "label": "应用层重试触发状态码", + "desc": "收到指定 HTTP 状态码时触发应用层重试,多个值请使用英文逗号分隔,例如 429,503。" + }, + "resetSessionCodes": { + "label": "传输层会话重建状态码", + "desc": "收到指定 HTTP 状态码时自动重建传输层代理会话(Transport Session),多个值请使用英文逗号分隔。" + }, + "chatTimeout": { + "label": "对话请求超时(秒)", + "desc": "对话与图像编辑请求的 HTTP 连接超时时间。" + }, + "imageTimeout": { + "label": "图像请求超时(秒)", + "desc": "图像生成 WebSocket 请求的总超时时间。" + }, + "videoTimeout": { + "label": "视频请求超时(秒)", + "desc": "视频生成请求的统一超时时间。" + }, + "voiceTimeout": { + "label": "语音请求超时(秒)", + "desc": "语音请求的统一超时时间。" + }, + "nsfwTimeout": { + "label": "NSFW 处理超时(秒)", + "desc": "set_birth_date 与 enable_nsfw 接口调用的超时时间。" + }, + "assetUploadTimeout": { + "label": "资产上传超时(秒)", + "desc": "Asset 上传接口的超时时间。" + }, + "assetDownloadTimeout": { + "label": "资产下载超时(秒)", + "desc": "Asset 下载接口的超时时间。" + }, + "assetListTimeout": { + "label": "资产查询超时(秒)", + "desc": "Asset 查询接口的超时时间。" + }, + "assetDeleteTimeout": { + "label": "资产删除超时(秒)", + "desc": "Asset 删除接口的超时时间。" + }, + "streamTimeout": { + "label": "流式空闲超时(秒)", + "desc": "流式接收图像数据时,连续空闲允许的最长等待时长。" + }, + "interRoundWait": { + "label": "轮次间等待(秒)", + "desc": "每轮出图完成后,用于探测服务端是否仍保持连接的等待时长;若超时未收到 CLOSE,则复用现有连接继续下一轮。" + } + } + } + }, + "cache": { + "pageTitle": "Grok2API - 缓存管理", + "pageHeading": "缓存管理", + "pageSubtitle": "统一查看本地缓存文件与账户在线资产,并支持按类型清理。", + "refresh": "刷新", + "sectionOverview": "缓存概览", + "statImageCount": "图片缓存数量", + "statImageSize": "图片缓存大小", + "statVideoCount": "视频缓存数量", + "statVideoSize": "视频缓存大小", + "sectionDetails": "缓存明细", + "tabLocal": "本地缓存", + "tabOnline": "在线资产", + "typeImage": "图片", + "typeVideo": "视频", + "typeImageNoun": "图片", + "typeVideoNoun": "视频", + "clearCurrent": "清空当前缓存", + "colFileName": "文件名", + "colSize": "大小", + "colModified": "修改时间", + "colActions": "操作", + "colToken": "Token", + "colFileCount": "文件数", + "onlineAssetLead": "在线资产", + "onlineAssetDesc": "指账户在 Grok 平台侧保存的图片与附件。清理仅影响远端文件,不会删除本地缓存。", + "loadAssets": "加载资产列表", + "clearAll": "清理全部", + "cancel": "取消", + "assetSummary": "共 {accounts} 个账户 · {files} 个文件", + "pageIndicator": "第 {current} / {total} 页", + "fileCount": "共 {n} 个文件", + "emptyLocal": "暂无缓存文件", + "emptyAccounts": "暂无账户数据", + "actionDelete": "删除", + "actionClear": "清理", + "loadFailed": "加载失败:{message}", + "clearLocalConfirm": "确定要清空所有本地{type}缓存吗?", + "clearLocalDone": "已清除 {count} 个{type}文件", + "clearFailed": "清理失败:{message}", + "deleted": "已删除", + "deleteFailed": "删除失败:{message}", + "loading": "加载中…", + "refreshList": "刷新列表", + "expand": "展开", + "collapse": "收起", + "clearTokenConfirm": "确定要清理 {token} 的全部在线资产吗?", + "clearTokenDone": "已删除 {count} 个文件", + "clearAllConfirm": "确定要清理全部 {n} 个账户的在线资产吗?此操作不可撤销。", + "clearingAssets": "正在清理在线资产…", + "clearAllDone": "清理完成:成功 {ok},失败 {fail}", + "cancelled": "已取消", + "clearFailedPlain": "清理失败", + "connectionInterrupted": "连接中断", + "startFailed": "启动失败:{message}", + "cancelInProgress": "已暂停,请耐心等待本批次完成…", + "na": "—" } } diff --git a/app/statics/js/admin-header.js b/app/statics/js/admin-header.js index a688040d..154d75c5 100644 --- a/app/statics/js/admin-header.js +++ b/app/statics/js/admin-header.js @@ -1,6 +1,495 @@ window.renderAdminHeader = async function renderAdminHeader() { const mount = document.getElementById('admin-header'); if (!mount || mount.children.length) return; + let appVersion = ''; + let updateInfo = null; + let updateStatus = 'idle'; + + const languageCodes = { + zh: 'CN', + en: 'EN', + ja: 'JA', + es: 'ES', + de: 'DE', + fr: 'FR', + }; + + const initLanguageMenu = () => { + const menu = mount.querySelector('#hd-lang-menu'); + const trigger = mount.querySelector('#hd-lang-trigger'); + const code = mount.querySelector('#hd-lang-code'); + const options = Array.from(mount.querySelectorAll('.admin-lang-option')); + if (!menu || !trigger || !code || !options.length) return; + + const close = () => { + menu.classList.remove('open'); + trigger.setAttribute('aria-expanded', 'false'); + }; + + const sync = () => { + const current = window.I18n?.getLang?.() || localStorage.getItem('grok2api_lang') || 'zh'; + code.textContent = languageCodes[current] || current.toUpperCase(); + options.forEach((option) => { + option.classList.toggle('active', option.dataset.lang === current); + }); + }; + + trigger.addEventListener('click', (event) => { + event.stopPropagation(); + const open = !menu.classList.contains('open'); + menu.classList.toggle('open', open); + trigger.setAttribute('aria-expanded', open ? 'true' : 'false'); + }); + + options.forEach((option) => { + option.addEventListener('click', () => { + const lang = option.dataset.lang; + if (!lang) return; + close(); + if (window.I18n?.setLang) { + I18n.setLang(lang); + } else { + localStorage.setItem('grok2api_lang', lang); + location.reload(); + } + }); + }); + + document.addEventListener('click', (event) => { + const target = event.target; + if (!(target instanceof Node) || !menu.contains(target)) close(); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') close(); + }); + + sync(); + return sync; + }; + + const applyHeaderI18n = () => { + if (window.I18n?.apply) I18n.apply(mount); + const trigger = mount.querySelector('#hd-lang-trigger'); + if (trigger) { + const label = window.t ? t('header.languageLabel') : 'Language'; + trigger.title = label; + trigger.setAttribute('aria-label', label); + } + const logout = mount.querySelector('#hd-logout'); + if (logout) { + const label = window.t ? t('header.logout') : 'Logout'; + logout.title = label; + logout.setAttribute('aria-label', label); + } + }; + + const loadVersion = async () => { + try { + const res = await fetch('/meta', { cache: 'no-store' }); + if (!res.ok) throw new Error('meta unavailable'); + const data = await res.json(); + appVersion = String(data?.version || '').trim(); + } catch { + appVersion = ''; + } + }; + + const loadUpdate = async () => { + updateStatus = 'loading'; + try { + const res = await fetch('/meta/update', { cache: 'no-store' }); + if (!res.ok) throw new Error('update unavailable'); + const data = await res.json(); + updateInfo = data && typeof data === 'object' ? data : null; + updateStatus = 'ready'; + } catch { + updateInfo = null; + updateStatus = 'error'; + } + }; + + const text = (key, fallback, params) => { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + }; + + const formatDateTime = (value) => { + if (!value) return '-'; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return String(value); + return date.toLocaleString(); + }; + + const escapeHtml = (value) => String(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + + const sanitizeUrl = (value) => { + try { + const url = new URL(value, window.location.origin); + return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : ''; + } catch { + return ''; + } + }; + + const sanitizeRenderedHtml = (html) => { + const template = document.createElement('template'); + template.innerHTML = html; + const blockedTags = new Set(['script', 'style', 'iframe', 'object', 'embed', 'link', 'meta']); + + const walk = (node) => { + if (node.nodeType !== Node.ELEMENT_NODE) return; + const el = node; + const tag = el.tagName.toLowerCase(); + + if (blockedTags.has(tag)) { + el.remove(); + return; + } + + Array.from(el.attributes).forEach((attr) => { + const name = attr.name.toLowerCase(); + const value = attr.value || ''; + if (name.startsWith('on')) { + el.removeAttribute(attr.name); + return; + } + if ((name === 'href' || name === 'src') && !sanitizeUrl(value)) { + el.removeAttribute(attr.name); + return; + } + if (name === 'target') { + el.setAttribute('target', '_blank'); + } + }); + + Array.from(el.children).forEach((child) => walk(child)); + }; + + Array.from(template.content.children).forEach((child) => walk(child)); + return template.innerHTML; + }; + + const renderInlineMarkdown = (source) => { + let html = escapeHtml(source); + html = html.replace(/`([^`]+)`/g, (_, code) => `${code}`); + html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, href) => { + const safeHref = sanitizeUrl(href.trim()); + const safeLabel = escapeHtml(label.trim() || href.trim()); + return safeHref + ? `${safeLabel}` + : safeLabel; + }); + html = html.replace(/(^|[\s(>])((https?:\/\/|mailto:)[^\s<]+)/g, (_, prefix, rawUrl) => { + const safeHref = sanitizeUrl(rawUrl.trim()); + if (!safeHref) return `${prefix}${rawUrl}`; + return `${prefix}${escapeHtml(rawUrl)}`; + }); + html = html.replace(/\*\*([^*]+)\*\*/g, '$1'); + html = html.replace(/(^|[^\*])\*([^*]+)\*/g, '$1$2'); + return html; + }; + + const renderMarkdown = (source) => { + const lines = String(source || '').replace(/\r\n?/g, '\n').split('\n'); + const html = []; + const paragraph = []; + let listType = ''; + let listItems = []; + let inCodeBlock = false; + let codeLines = []; + let quoteLines = []; + + const flushParagraph = () => { + if (!paragraph.length) return; + html.push(`

${renderInlineMarkdown(paragraph.map((line) => line.trim()).join(' '))}

`); + paragraph.length = 0; + }; + + const flushList = () => { + if (!listItems.length) return; + html.push(`<${listType}>${listItems.map((item) => `
  • ${renderInlineMarkdown(item)}
  • `).join('')}`); + listItems = []; + listType = ''; + }; + + const flushCodeBlock = () => { + if (!inCodeBlock) return; + html.push(`
    ${escapeHtml(codeLines.join('\n'))}
    `); + inCodeBlock = false; + codeLines = []; + }; + + const flushQuote = () => { + if (!quoteLines.length) return; + html.push(`
    ${renderInlineMarkdown(quoteLines.map((line) => line.trim()).join(' '))}
    `); + quoteLines = []; + }; + + for (const line of lines) { + if (line.startsWith('```')) { + flushParagraph(); + flushList(); + flushQuote(); + if (inCodeBlock) { + flushCodeBlock(); + } else { + inCodeBlock = true; + codeLines = []; + } + continue; + } + + if (inCodeBlock) { + codeLines.push(line); + continue; + } + + const trimmed = line.trim(); + const headingMatch = trimmed.match(/^(#{1,6})\s+(.*)$/); + const unorderedMatch = trimmed.match(/^[-*+]\s+(.*)$/); + const orderedMatch = trimmed.match(/^\d+\.\s+(.*)$/); + const quoteMatch = trimmed.match(/^>\s?(.*)$/); + + if (!trimmed) { + flushParagraph(); + flushList(); + flushQuote(); + continue; + } + + if (headingMatch) { + flushParagraph(); + flushList(); + flushQuote(); + const level = headingMatch[1].length; + html.push(`${renderInlineMarkdown(headingMatch[2])}`); + continue; + } + + if (unorderedMatch || orderedMatch) { + flushParagraph(); + flushQuote(); + const nextType = unorderedMatch ? 'ul' : 'ol'; + const itemText = unorderedMatch ? unorderedMatch[1] : orderedMatch[1]; + if (listType && listType !== nextType) flushList(); + listType = nextType; + listItems.push(itemText); + continue; + } + + flushList(); + + if (quoteMatch) { + flushParagraph(); + quoteLines.push(quoteMatch[1]); + continue; + } + + flushQuote(); + + if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { + flushParagraph(); + flushQuote(); + html.push('
    '); + continue; + } + + paragraph.push(line); + } + + flushParagraph(); + flushList(); + flushQuote(); + flushCodeBlock(); + return html.join('') || '

    '; + }; + + const renderReleaseNotes = (source) => { + if (!source.trim()) return `

    ${escapeHtml(text('header.versionNotesEmpty', 'No release notes available.'))}

    `; + if (window.marked && typeof window.marked.parse === 'function') { + return sanitizeRenderedHtml(window.marked.parse(source, { + async: false, + breaks: false, + gfm: true, + })); + } + return renderMarkdown(source); + }; + + const ensureVersionModal = () => { + let overlay = document.getElementById('admin-version-modal'); + if (overlay) return overlay; + + overlay = document.createElement('div'); + overlay.id = 'admin-version-modal'; + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + + `; + document.body.appendChild(overlay); + + const close = () => { + overlay.classList.remove('open'); + overlay.setAttribute('aria-hidden', 'true'); + }; + + overlay.addEventListener('click', (event) => { + if (event.target === overlay) close(); + }); + + overlay.querySelector('#admin-version-modal-close')?.addEventListener('click', close); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && overlay.classList.contains('open')) close(); + }); + + return overlay; + }; + + const openVersionModal = () => { + const overlay = ensureVersionModal(); + const title = overlay.querySelector('#admin-version-modal-title'); + const badge = overlay.querySelector('#admin-version-modal-badge'); + const status = overlay.querySelector('#admin-version-modal-status'); + const currentLabel = overlay.querySelector('#admin-version-modal-current-label'); + const currentValue = overlay.querySelector('#admin-version-modal-current'); + const latestLabel = overlay.querySelector('#admin-version-modal-latest-label'); + const latestValue = overlay.querySelector('#admin-version-modal-latest'); + const publishedLabel = overlay.querySelector('#admin-version-modal-published-label'); + const publishedValue = overlay.querySelector('#admin-version-modal-published'); + const notes = overlay.querySelector('#admin-version-modal-notes'); + const link = overlay.querySelector('#admin-version-modal-link'); + const close = overlay.querySelector('#admin-version-modal-close'); + const latestVersion = String(updateInfo?.latest_version || appVersion || '').trim(); + const currentVersion = String(appVersion || updateInfo?.current_version || '').trim(); + const releaseUrl = String(updateInfo?.release_url || '').trim(); + const releaseNotes = String(updateInfo?.release_notes || '').trim(); + + if (title) title.textContent = text('header.versionDialogTitle', 'Version'); + if (currentLabel) currentLabel.textContent = `${text('header.versionCurrent', 'Current')}:`; + if (currentValue) currentValue.textContent = currentVersion ? `v${currentVersion}` : '-'; + if (latestLabel) latestLabel.textContent = `${text('header.versionLatest', 'Latest')}:`; + if (latestValue) latestValue.textContent = latestVersion ? `v${latestVersion}` : '-'; + if (publishedLabel) publishedLabel.textContent = `${text('header.versionPublishedAt', 'Published')}:`; + if (publishedValue) publishedValue.textContent = formatDateTime(updateInfo?.published_at); + + if (badge) { + badge.hidden = true; + badge.textContent = ''; + badge.className = 'admin-version-modal-badge'; + } + + if (status) { + if (updateStatus === 'loading') { + status.textContent = text('header.versionChecking', 'Checking for updates...'); + status.className = 'admin-version-modal-status is-muted'; + } else if (updateStatus === 'error' || !updateInfo || updateInfo.status === 'error') { + status.textContent = text('header.versionUnavailable', 'Unable to check for updates right now.'); + status.className = 'admin-version-modal-status is-muted'; + } else if (updateInfo.update_available) { + status.textContent = ''; + status.className = 'admin-version-modal-status is-hidden'; + if (badge) { + badge.hidden = false; + badge.textContent = text('header.versionUpdateAvailable', 'A new version is available.'); + badge.className = 'admin-version-modal-badge is-update'; + } + } else { + status.textContent = text('header.versionUpToDate', 'You are already on the latest version.'); + status.className = 'admin-version-modal-status is-current'; + } + } + + if (notes) { + if (updateStatus === 'error' || !updateInfo || updateInfo.status === 'error') { + notes.innerHTML = `

    ${escapeHtml(text('header.versionUnavailable', 'Unable to check for updates right now.'))}

    `; + } else { + notes.innerHTML = renderReleaseNotes(releaseNotes); + } + } + + if (link instanceof HTMLAnchorElement) { + if (releaseUrl) { + link.hidden = false; + link.style.display = 'inline-flex'; + link.href = releaseUrl; + link.textContent = text('header.versionOpenRelease', 'Open Release'); + } else { + link.hidden = true; + link.style.display = 'none'; + link.removeAttribute('href'); + link.textContent = ''; + } + } + + if (close instanceof HTMLButtonElement) { + close.textContent = text('header.versionClose', 'Close'); + } + + overlay.classList.add('open'); + overlay.setAttribute('aria-hidden', 'false'); + }; + + const applyVersion = () => { + const right = mount.querySelector('.admin-header-right'); + if (!right) return; + let node = mount.querySelector('#hd-version'); + if (!appVersion) { + node?.remove(); + return; + } + if (!node) { + node = document.createElement('span'); + node.id = 'hd-version'; + node.className = 'admin-header-version'; + right.insertBefore(node, right.firstChild); + } + const value = `v${appVersion}`; + node.textContent = value; + node.title = value; + node.classList.toggle('has-update', Boolean(updateInfo?.update_available)); + node.setAttribute('role', 'button'); + node.setAttribute('tabindex', '0'); + node.onclick = openVersionModal; + node.onkeydown = (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + openVersionModal(); + } + }; + }; + + await loadVersion(); try { const res = await fetch('/static/admin/header.html', { cache: 'no-store' }); @@ -11,15 +500,58 @@ window.renderAdminHeader = async function renderAdminHeader() {
    - Grok2API + + Grok2API + + @Chenyme
    - — - +
    + + +
    +
    `; @@ -30,16 +562,12 @@ window.renderAdminHeader = async function renderAdminHeader() { link.classList.toggle('active', link.dataset.nav === active); }); - const inner = mount.querySelector('.admin-header-inner'); - if (inner) { - inner.style.maxWidth = '1280px'; - inner.style.width = '100%'; - inner.style.height = '54px'; - inner.style.margin = '0 auto'; - inner.style.padding = '0 28px'; - inner.style.display = 'flex'; - inner.style.alignItems = 'center'; - inner.style.justifyContent = 'space-between'; - inner.style.flexWrap = 'nowrap'; - } + const syncLanguageMenu = initLanguageMenu(); + applyHeaderI18n(); + applyVersion(); + syncLanguageMenu?.(); + + void loadUpdate().then(() => { + applyVersion(); + }); }; diff --git a/app/statics/js/i18n.js b/app/statics/js/i18n.js index daed939c..28257432 100644 --- a/app/statics/js/i18n.js +++ b/app/statics/js/i18n.js @@ -1,17 +1,58 @@ /* Grok2API — i18n */ (function(){ - var KEY='grok2api_lang', LANGS=['zh','en'], lang='zh', data={}, ready=false, queue=[]; + var KEY='grok2api_lang', + LANGS={ + zh:{label:'简体中文', html:'zh-CN'}, + en:{label:'English', html:'en'}, + ja:{label:'日本語', html:'ja'}, + es:{label:'Español', html:'es'}, + de:{label:'Deutsch', html:'de'}, + fr:{label:'Français', html:'fr'} + }, + LANG_CODES=Object.keys(LANGS), + lang='zh', + data={}, + ready=false, + queue=[]; + + function normalize(l){ + if(!l) return ''; + l=String(l).toLowerCase(); + if(LANGS[l]) return l; + l=l.split('-')[0]; + return LANGS[l]?l:''; + } function detect(){ - try{ var s=localStorage.getItem(KEY); if(s&&LANGS.indexOf(s)!==-1) return s; }catch(e){} + try{ var s=normalize(localStorage.getItem(KEY)); if(s) return s; }catch(e){} var p; try{p=new URLSearchParams(location.search).get('lang')}catch(e){} - if(p&&LANGS.indexOf(p)!==-1){try{localStorage.setItem(KEY,p)}catch(e){} return p;} - var b=(navigator.language||'').split('-')[0]; - return LANGS.indexOf(b)!==-1?b:'zh'; + p=normalize(p); + if(p){try{localStorage.setItem(KEY,p)}catch(e){} return p;} + var b=normalize(navigator.language||''); + return b||'zh'; } function get(o,k){ for(var p=k.split('.'),i=0;i/g,'>'); +} + +function showToast(message, type = 'success') { + const tone = type === 'error' ? 'error' : (type === 'info' ? 'info' : 'success'); + const icon = tone === 'success' ? '' - : ''; - el.className = `toast ${ok ? 'toast-success' : 'toast-error'}`; - const safe = String(message).replace(/&/g,'&').replace(//g,'>'); - el.innerHTML = `
    ${icon}
    ${safe}
    `; - c.appendChild(el); + : tone === 'error' + ? '' + : ''; + const el = document.createElement('div'); + el.className = `toast toast-${tone}`; + el.innerHTML = `
    ${icon}
    ${_esc(message)}
    `; + _toastContainer().appendChild(el); setTimeout(() => { el.classList.add('out'); - el.addEventListener('animationend', () => el.remove()); + el.addEventListener('animationend', () => el.remove(), { once: true }); }, 3000); } + +/** + * Show a persistent progress toast that stays open until finish() is called. + * + * @param {string} label Initial label text shown inside the toast. + * @returns {{ update(done, total): void, finish(msg, type?): void, dismiss(): void }} + * + * Usage: + * const p = showProgressToast('正在刷新 Usage…'); + * p.update(10, 50); // update progress bar and counter + * p.finish('完成:50 个', 'success'); // switch to result state, auto-dismiss + */ +function showProgressToast(label) { + const SPIN = ''; + + const el = document.createElement('div'); + el.className = 'toast toast-info'; + el.innerHTML = ` +
    ${SPIN}
    +
    +
    ${_esc(label)}
    +
    +
    + `; + _toastContainer().appendChild(el); + + const iconEl = el.querySelector('.toast-icon'); + const labelEl = el.querySelector('.toast-progress-label'); + const fill = el.querySelector('.toast-progress-fill'); + const countEl = el.querySelector('.toast-progress-count'); + + function _dismiss() { + el.classList.add('out'); + el.addEventListener('animationend', () => el.remove(), { once: true }); + } + + return { + update(done, total) { + const pct = total > 0 ? Math.min(100, Math.round(done / total * 100)) : 0; + fill.style.width = pct + '%'; + countEl.textContent = total > 0 ? `${done} / ${total}` : `${done}`; + }, + finish(msg, type = 'success') { + const tone = type === 'error' ? 'error' : 'success'; + const icon = tone === 'success' + ? '' + : ''; + el.className = `toast toast-${tone}`; + iconEl.innerHTML = icon; + fill.style.width = '100%'; + labelEl.textContent = msg; + countEl.textContent = ''; + setTimeout(_dismiss, 3000); + }, + dismiss: _dismiss, + }; +} diff --git a/app/statics/js/webui-header.js b/app/statics/js/webui-header.js new file mode 100644 index 00000000..1d3e5a9b --- /dev/null +++ b/app/statics/js/webui-header.js @@ -0,0 +1,195 @@ +window.renderWebuiHeader = async function renderWebuiHeader() { + const mount = document.getElementById('webui-header'); + if (!mount || mount.children.length) return; + let appVersion = ''; + + const languageCodes = { + zh: 'CN', + en: 'EN', + ja: 'JA', + es: 'ES', + de: 'DE', + fr: 'FR', + }; + + const initLanguageMenu = () => { + const menu = mount.querySelector('#hd-lang-menu'); + const trigger = mount.querySelector('#hd-lang-trigger'); + const code = mount.querySelector('#hd-lang-code'); + const options = Array.from(mount.querySelectorAll('.admin-lang-option')); + if (!menu || !trigger || !code || !options.length) return; + + const close = () => { + menu.classList.remove('open'); + trigger.setAttribute('aria-expanded', 'false'); + }; + + const sync = () => { + const current = window.I18n?.getLang?.() || localStorage.getItem('grok2api_lang') || 'zh'; + code.textContent = languageCodes[current] || current.toUpperCase(); + options.forEach((option) => { + option.classList.toggle('active', option.dataset.lang === current); + }); + }; + + trigger.addEventListener('click', (event) => { + event.stopPropagation(); + const open = !menu.classList.contains('open'); + menu.classList.toggle('open', open); + trigger.setAttribute('aria-expanded', open ? 'true' : 'false'); + }); + + options.forEach((option) => { + option.addEventListener('click', () => { + const lang = option.dataset.lang; + if (!lang) return; + close(); + if (window.I18n?.setLang) { + I18n.setLang(lang); + } else { + localStorage.setItem('grok2api_lang', lang); + location.reload(); + } + }); + }); + + document.addEventListener('click', (event) => { + const target = event.target; + if (!(target instanceof Node) || !menu.contains(target)) close(); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') close(); + }); + + sync(); + return sync; + }; + + const applyHeaderI18n = () => { + if (window.I18n?.apply) I18n.apply(mount); + const trigger = mount.querySelector('#hd-lang-trigger'); + if (trigger) { + const label = window.t ? t('header.languageLabel') : 'Language'; + trigger.title = label; + trigger.setAttribute('aria-label', label); + } + const logout = mount.querySelector('#hd-logout'); + if (logout) { + const hidden = mount.dataset.hideLogout === 'true'; + logout.hidden = hidden; + if (!hidden) { + const label = window.t ? t('header.logout') : 'Logout'; + logout.title = label; + logout.setAttribute('aria-label', label); + } + } + }; + + const loadVersion = async () => { + try { + const res = await fetch('/meta', { cache: 'no-store' }); + if (!res.ok) throw new Error('meta unavailable'); + const data = await res.json(); + appVersion = String(data?.version || '').trim(); + } catch { + appVersion = ''; + } + }; + + const applyVersion = () => { + const right = mount.querySelector('.admin-header-right'); + if (!right) return; + let node = mount.querySelector('#hd-version'); + if (!appVersion) { + node?.remove(); + return; + } + if (!node) { + node = document.createElement('span'); + node.id = 'hd-version'; + node.className = 'admin-header-version'; + right.insertBefore(node, right.firstChild); + } + const value = `v${appVersion}`; + node.textContent = value; + node.title = value; + }; + + await loadVersion(); + + try { + const res = await fetch('/static/webui/header.html', { cache: 'no-store' }); + if (!res.ok) throw new Error('header unavailable'); + mount.innerHTML = await res.text(); + } catch { + mount.innerHTML = ` +
    +
    + + +
    +
    + + +
    + +
    +
    +
    `; + } + + const active = mount.dataset.active || location.pathname; + mount.querySelectorAll('[data-nav]').forEach((link) => { + link.classList.toggle('active', link.dataset.nav === active); + }); + + const syncLanguageMenu = initLanguageMenu(); + applyHeaderI18n(); + applyVersion(); + syncLanguageMenu?.(); +}; diff --git a/app/statics/js/webui/chat.js b/app/statics/js/webui/chat.js new file mode 100644 index 00000000..a7d4342f --- /dev/null +++ b/app/statics/js/webui/chat.js @@ -0,0 +1,1506 @@ +(() => { + const VERIFY_ENDPOINT = '/webui/api/verify'; + const MODELS_ENDPOINT = '/webui/api/models'; + const CHAT_ENDPOINT = '/webui/api/chat/completions'; + const PREFERRED_MODEL = 'grok-4.20-0309'; + const STORE_KEY = 'grok2api_webui_chat_sessions_v1'; + const SIDEBAR_STORE_KEY = 'grok2api_webui_sidebar_collapsed_v1'; + + const chatLayout = document.getElementById('chatLayout'); + const modelSelect = document.getElementById('modelSelect'); + const systemInput = document.getElementById('systemInput'); + const thread = document.getElementById('thread'); + const emptyState = document.getElementById('emptyState'); + const statusEl = document.getElementById('status'); + const promptInput = document.getElementById('promptInput'); + const sendBtn = document.getElementById('sendBtn'); + const newChatBtn = document.getElementById('newChatBtn'); + const sidebarToggleBtn = document.getElementById('sidebarToggleBtn'); + const sessionList = document.getElementById('sessionList'); + const uploadBtn = document.getElementById('uploadBtn'); + const fileInput = document.getElementById('fileInput'); + const uploadMeta = document.getElementById('uploadMeta'); + const sessionModal = document.getElementById('sessionModal'); + const sessionModalTitle = document.getElementById('sessionModalTitle'); + const sessionModalDesc = document.getElementById('sessionModalDesc'); + const sessionModalInputWrap = document.getElementById('sessionModalInputWrap'); + const sessionModalInput = document.getElementById('sessionModalInput'); + const sessionModalCancel = document.getElementById('sessionModalCancel'); + const sessionModalConfirm = document.getElementById('sessionModalConfirm'); + + let sessions = []; + let currentSessionId = ''; + let messages = []; + let abortController = null; + let sending = false; + let pendingFiles = []; + let modalResolver = null; + let sidebarCollapsed = false; + let availableModels = []; + let activeEdit = null; + const PROMPT_MIN_HEIGHT = 36; + const PROMPT_MAX_HEIGHT = 108; + + function text(key, fallback, params) { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + } + + function toast(message, type = 'info') { + if (typeof showToast === 'function') showToast(message, type); + } + + function currentSystemPrompt() { + return systemInput ? (systemInput.value || '').trim() : ''; + } + + function escapeHtml(value) { + return String(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function hasVisibleReasoning(value) { + return typeof value === 'string' && value.trim().length > 0; + } + + function sanitizeUrl(value) { + try { + const url = new URL(value, window.location.origin); + return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : ''; + } catch { + return ''; + } + } + + function sanitizeRenderedHtml(html) { + const template = document.createElement('template'); + template.innerHTML = html; + + const blockedTags = new Set(['script', 'style', 'iframe', 'object', 'embed', 'link', 'meta']); + + function walk(node) { + if (node.nodeType !== Node.ELEMENT_NODE) return; + const el = node; + const tag = el.tagName.toLowerCase(); + + if (blockedTags.has(tag)) { + el.remove(); + return; + } + + Array.from(el.attributes).forEach((attr) => { + const name = attr.name.toLowerCase(); + const value = attr.value || ''; + if (name.startsWith('on')) { + el.removeAttribute(attr.name); + return; + } + if ((name === 'href' || name === 'src') && !sanitizeUrl(value)) { + el.removeAttribute(attr.name); + return; + } + if (name === 'target') { + el.setAttribute('target', '_blank'); + } + }); + + Array.from(el.children).forEach((child) => walk(child)); + } + + Array.from(template.content.children).forEach((child) => walk(child)); + return template.innerHTML; + } + + function renderInlineMarkdown(source) { + let html = escapeHtml(source); + html = html.replace(/`([^`]+)`/g, (_, code) => `${code}`); + html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, href) => { + const safeHref = sanitizeUrl(href.trim()); + const safeLabel = label.trim() || href.trim(); + return safeHref + ? `${safeLabel}` + : safeLabel; + }); + html = html.replace(/\*\*([^*]+)\*\*/g, '$1'); + html = html.replace(/(^|[^\*])\*([^*]+)\*/g, '$1$2'); + return html; + } + + function renderMarkdown(source) { + const lines = String(source || '').replace(/\r\n?/g, '\n').split('\n'); + const html = []; + const paragraph = []; + let listType = ''; + let listItems = []; + let inCodeBlock = false; + let codeLines = []; + + function flushParagraph() { + if (!paragraph.length) return; + html.push(`

    ${paragraph.map((line) => renderInlineMarkdown(line)).join('
    ')}

    `); + paragraph.length = 0; + } + + function flushList() { + if (!listItems.length) return; + html.push(`<${listType}>${listItems.map((item) => `
  • ${renderInlineMarkdown(item)}
  • `).join('')}`); + listItems = []; + listType = ''; + } + + function flushCodeBlock() { + if (!inCodeBlock) return; + html.push(`
    ${escapeHtml(codeLines.join('\n'))}
    `); + inCodeBlock = false; + codeLines = []; + } + + for (const line of lines) { + if (line.startsWith('```')) { + flushParagraph(); + flushList(); + if (inCodeBlock) { + flushCodeBlock(); + } else { + inCodeBlock = true; + codeLines = []; + } + continue; + } + + if (inCodeBlock) { + codeLines.push(line); + continue; + } + + const trimmed = line.trim(); + const headingMatch = trimmed.match(/^(#{1,6})\s+(.*)$/); + const unorderedMatch = trimmed.match(/^[-*+]\s+(.*)$/); + const orderedMatch = trimmed.match(/^\d+\.\s+(.*)$/); + const quoteMatch = trimmed.match(/^>\s?(.*)$/); + + if (!trimmed) { + flushParagraph(); + flushList(); + continue; + } + + if (headingMatch) { + flushParagraph(); + flushList(); + const level = headingMatch[1].length; + html.push(`${renderInlineMarkdown(headingMatch[2])}`); + continue; + } + + if (unorderedMatch || orderedMatch) { + flushParagraph(); + const nextType = unorderedMatch ? 'ul' : 'ol'; + const itemText = unorderedMatch ? unorderedMatch[1] : orderedMatch[1]; + if (listType && listType !== nextType) flushList(); + listType = nextType; + listItems.push(itemText); + continue; + } + + flushList(); + + if (quoteMatch) { + flushParagraph(); + html.push(`
    ${renderInlineMarkdown(quoteMatch[1])}
    `); + continue; + } + + paragraph.push(line); + } + + flushParagraph(); + flushList(); + flushCodeBlock(); + return html.join('') || '

    '; + } + + function renderRichMarkdown(source) { + if (window.marked && typeof window.marked.parse === 'function') { + const rendered = window.marked.parse(normalizeMediaContent(source), { + async: false, + breaks: true, + gfm: true, + }); + return sanitizeRenderedHtml(rendered); + } + return renderMarkdown(source); + } + + function isImageUrl(value) { + const normalized = String(value || '').trim().toLowerCase(); + return normalized.includes('/v1/files/image') + || /\.(png|jpe?g|gif|webp|bmp|svg)(\?|#|$)/.test(normalized) + || normalized.startsWith('data:image/'); + } + + function isVideoUrl(value) { + const normalized = String(value || '').trim().toLowerCase(); + return normalized.includes('/v1/files/video') + || /\.(mp4|webm|mov|m4v|ogg)(\?|#|$)/.test(normalized); + } + + function normalizeMediaContent(source) { + const input = String(source || '').replace(/\[video\]\(([^)]+)\)/gi, '$1'); + return input.replace(/^(https?:\/\/\S+|\/v1\/files\/(?:image|video)\?id=\S+|data:image\/[^\s]+)$/gm, (match) => { + const url = match.trim(); + if (isImageUrl(url)) return `![image](${url})`; + if (isVideoUrl(url)) return ``; + return match; + }); + } + + function extractTextContent(content) { + if (typeof content === 'string') return content; + if (!Array.isArray(content)) return ''; + return content + .filter((block) => block && block.type === 'text' && typeof block.text === 'string' && block.text.trim()) + .map((block) => block.text.trim()) + .join('\n'); + } + + function extractImageUrls(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (!block || block.type !== 'image_url') return []; + const image = block.image_url; + if (typeof image === 'string' && image.trim()) return [image.trim()]; + if (image && typeof image.url === 'string' && image.url.trim()) return [image.url.trim()]; + return []; + }); + } + + function extractFileItems(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (!block || typeof block !== 'object') return []; + if (block.type === 'input_audio') { + const audio = block.input_audio || {}; + const filename = String(audio.filename || '').trim(); + return [{ kind: 'audio', name: filename || 'audio' }]; + } + if (block.type === 'file') { + const file = block.file || {}; + const filename = String(file.filename || '').trim(); + return [{ kind: 'file', name: filename || 'file' }]; + } + return []; + }); + } + + function dataUrlMime(value) { + const match = String(value || '').match(/^data:([^;,]+)[;,]/i); + return match ? match[1].toLowerCase() : 'application/octet-stream'; + } + + function fallbackNameForMime(mime) { + if (mime.startsWith('image/')) return `image.${mime.split('/')[1] || 'png'}`; + if (mime.startsWith('audio/')) return `audio.${mime.split('/')[1] || 'wav'}`; + return `file.${mime.split('/')[1] || 'bin'}`; + } + + function extractEditablePendingFiles(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (!block || typeof block !== 'object') return []; + if (block.type === 'image_url') { + const image = block.image_url; + const url = typeof image === 'string' ? image : image && typeof image.url === 'string' ? image.url : ''; + if (!url || !url.startsWith('data:')) return []; + const mime = dataUrlMime(url); + return [{ + name: fallbackNameForMime(mime), + type: mime, + size: 0, + dataUrl: url, + }]; + } + if (block.type === 'input_audio') { + const audio = block.input_audio || {}; + const data = String(audio.data || '').trim(); + if (!data) return []; + const mime = dataUrlMime(data); + return [{ + name: String(audio.filename || '').trim() || fallbackNameForMime(mime), + type: mime, + size: 0, + dataUrl: data, + }]; + } + if (block.type === 'file') { + const file = block.file || {}; + const data = String(file.file_data || '').trim(); + if (!data) return []; + const mime = dataUrlMime(data); + return [{ + name: String(file.filename || '').trim() || fallbackNameForMime(mime), + type: mime, + size: 0, + dataUrl: data, + }]; + } + return []; + }); + } + + async function copyToClipboard(value) { + const textValue = String(value || ''); + if (!textValue) return; + if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { + await navigator.clipboard.writeText(textValue); + return; + } + const textarea = document.createElement('textarea'); + textarea.value = textValue; + textarea.setAttribute('readonly', ''); + textarea.style.position = 'fixed'; + textarea.style.opacity = '0'; + document.body.appendChild(textarea); + textarea.select(); + document.execCommand('copy'); + textarea.remove(); + } + + function beginEditMessage(messageIndex, content) { + activeEdit = { + messageIndex, + text: extractTextContent(content) || (typeof content === 'string' ? content : ''), + files: extractEditablePendingFiles(content), + }; + renderThread(); + } + + function summarizeMessageContent(content) { + const textContent = extractTextContent(content).trim(); + const imageCount = extractImageUrls(content).length; + const fileCount = extractFileItems(content).length; + const parts = []; + if (textContent) parts.push(textContent); + if (imageCount) parts.push(`[${imageCount} image${imageCount > 1 ? 's' : ''}]`); + if (fileCount) parts.push(`[${fileCount} file${fileCount > 1 ? 's' : ''}]`); + return parts.join('\n\n'); + } + + function renderMessageContent(card, role, content) { + if (Array.isArray(content)) { + const textContent = extractTextContent(content); + const imageUrls = extractImageUrls(content); + const fileItems = extractFileItems(content); + if (role === 'assistant') { + const parts = []; + if (textContent.trim()) parts.push(renderRichMarkdown(textContent)); + if (imageUrls.length) { + parts.push(imageUrls.map((url) => ( + `
    image
    ` + )).join('')); + } + card.innerHTML = parts.join('') || '

    '; + return; + } + + const body = document.createElement('div'); + body.className = 'msg-user-parts'; + if (textContent.trim()) { + const textNode = document.createElement('div'); + textNode.className = 'msg-user-text'; + textNode.textContent = textContent; + body.appendChild(textNode); + } + if (imageUrls.length) { + const gallery = document.createElement('div'); + gallery.className = 'msg-user-gallery'; + imageUrls.forEach((url) => { + const img = document.createElement('img'); + img.src = url; + img.alt = 'image'; + img.loading = 'lazy'; + gallery.appendChild(img); + }); + body.appendChild(gallery); + } + if (fileItems.length) { + const attachments = document.createElement('div'); + attachments.className = 'msg-user-files'; + fileItems.forEach((item) => { + const chip = document.createElement('div'); + chip.className = 'msg-user-file'; + chip.textContent = item.name; + attachments.appendChild(chip); + }); + body.appendChild(attachments); + } + card.replaceChildren(body); + return; + } + + if (role === 'assistant') { + card.innerHTML = renderRichMarkdown(content); + return; + } + card.textContent = content; + } + + function parseSseEvent(chunk) { + let event = 'message'; + const dataLines = []; + for (const line of chunk.split('\n')) { + if (line.startsWith('event:')) { + event = line.slice(6).trim() || 'message'; + continue; + } + if (line.startsWith('data:')) { + dataLines.push(line.slice(5).trimStart()); + } + } + return { event, data: dataLines.join('\n') }; + } + + function loadStore() { + try { + const raw = localStorage.getItem(STORE_KEY); + if (!raw) return { sessions: [], currentSessionId: '' }; + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) return { sessions: parsed, currentSessionId: parsed[0] && parsed[0].id || '' }; + return { + sessions: Array.isArray(parsed && parsed.sessions) ? parsed.sessions : [], + currentSessionId: parsed && parsed.currentSessionId ? String(parsed.currentSessionId) : '', + }; + } catch { + return { sessions: [], currentSessionId: '' }; + } + } + + function persistStore() { + const serializedSessions = sessions.map((session) => ({ + ...session, + messages: Array.isArray(session.messages) + ? session.messages.map((message) => ({ + ...message, + content: Array.isArray(message.content) + ? summarizeMessageContent(message.content) + : message.content, + })) + : [], + })); + localStorage.setItem(STORE_KEY, JSON.stringify({ sessions: serializedSessions, currentSessionId })); + } + + function applySidebarState() { + if (!chatLayout || !sidebarToggleBtn) return; + chatLayout.classList.toggle('sidebar-collapsed', sidebarCollapsed); + sidebarToggleBtn.setAttribute('aria-expanded', String(!sidebarCollapsed)); + } + + function loadSidebarState() { + try { + sidebarCollapsed = localStorage.getItem(SIDEBAR_STORE_KEY) === 'true'; + } catch { + sidebarCollapsed = false; + } + applySidebarState(); + } + + function toggleSidebar() { + sidebarCollapsed = !sidebarCollapsed; + applySidebarState(); + try { + localStorage.setItem(SIDEBAR_STORE_KEY, String(sidebarCollapsed)); + } catch {} + } + + function createSessionTitle(messagesList) { + const firstUser = messagesList.find((item) => { + if (!item || item.role !== 'user') return false; + return Boolean(extractTextContent(item.content).trim()); + }); + if (!firstUser) return text('webui.chat.untitled', 'New Chat'); + const trimmed = extractTextContent(firstUser.content).trim().replace(/\s+/g, ' '); + return trimmed.length > 24 ? `${trimmed.slice(0, 24)}...` : trimmed; + } + + function createSession() { + return { + id: `chat_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, + title: text('webui.chat.untitled', 'New Chat'), + titleLocked: false, + model: modelSelect.value || PREFERRED_MODEL, + system: '', + messages: [], + updatedAt: Date.now(), + }; + } + + function normalizeSession(item) { + return { + id: item && item.id ? String(item.id) : `chat_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, + title: item && item.title ? String(item.title) : text('webui.chat.untitled', 'New Chat'), + titleLocked: Boolean(item && item.titleLocked), + model: item && item.model ? String(item.model) : PREFERRED_MODEL, + system: item && item.system ? String(item.system) : '', + messages: Array.isArray(item && item.messages) + ? item.messages + .filter((entry) => { + if (!entry || typeof entry.role !== 'string') return false; + return typeof entry.content === 'string' || Array.isArray(entry.content); + }) + .map((entry) => ({ + ...entry, + reasoning_content: entry && entry.role === 'assistant' && hasVisibleReasoning(entry.reasoning_content) + ? entry.reasoning_content + : '', + createdAt: Number(entry && entry.createdAt) || Date.now(), + feedback: entry && typeof entry.feedback === 'string' ? entry.feedback : '', + })) + : [], + updatedAt: Number(item && item.updatedAt) || Date.now(), + }; + } + + function setAssistantFeedback(messageIndex, feedback) { + const session = getCurrentSession(); + const message = session && session.messages && session.messages[messageIndex]; + if (!session || !message || message.role !== 'assistant') return; + message.feedback = message.feedback === feedback ? '' : feedback; + session.updatedAt = Date.now(); + persistStore(); + renderThread(); + } + + function regenerateAssistantAt(messageIndex) { + const session = getCurrentSession(); + if (!session || sending || messageIndex < 0) return; + + let userIndex = -1; + for (let index = messageIndex - 1; index >= 0; index -= 1) { + if (messages[index] && messages[index].role === 'user') { + userIndex = index; + break; + } + } + if (userIndex < 0) return; + + const userContent = messages[userIndex].content; + promptInput.value = extractTextContent(userContent) || (typeof userContent === 'string' ? userContent : ''); + pendingFiles = extractEditablePendingFiles(userContent); + messages = messages.slice(0, userIndex); + session.messages = messages; + session.updatedAt = Date.now(); + activeEdit = null; + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + void sendMessage(); + } + + function getCurrentSession() { + return sessions.find((item) => item.id === currentSessionId) || null; + } + + function moveSessionToTop(session) { + sessions = [session, ...sessions.filter((item) => item.id !== session.id)]; + } + + async function getAuthHeaders() { + const key = await webuiKey.get(); + return key ? { Authorization: `Bearer ${key}` } : {}; + } + + async function ensureAccess() { + const stored = await webuiKey.get(); + if (stored && await verifyKey(VERIFY_ENDPOINT, stored)) return true; + if (stored) webuiKey.clear(); + if (await verifyKey(VERIFY_ENDPOINT, '')) return true; + location.href = '/webui/login'; + return false; + } + + function setStatus(textValue) { + if (statusEl) statusEl.textContent = textValue; + } + + function resizePromptInput() { + if (!promptInput) return; + promptInput.style.height = `${PROMPT_MIN_HEIGHT}px`; + const nextHeight = Math.min(Math.max(promptInput.scrollHeight, PROMPT_MIN_HEIGHT), PROMPT_MAX_HEIGHT); + promptInput.style.height = `${nextHeight}px`; + promptInput.style.overflowY = promptInput.scrollHeight > PROMPT_MAX_HEIGHT ? 'auto' : 'hidden'; + } + + function renderSendButton() { + if (!sendBtn) return; + const label = sending + ? text('webui.chat.stop', 'Stop') + : text('webui.chat.send', 'Send'); + sendBtn.removeAttribute('data-i18n'); + sendBtn.setAttribute('aria-label', label); + sendBtn.setAttribute('title', label); + sendBtn.innerHTML = sending + ? '' + : ''; + } + + function setSending(next) { + sending = next; + promptInput.disabled = next; + modelSelect.disabled = next; + if (systemInput) systemInput.disabled = next; + renderSendButton(); + } + + function scrollThread() { + thread.scrollTop = thread.scrollHeight; + } + + function hideEmpty() { + if (emptyState) emptyState.style.display = 'none'; + } + + function showEmpty() { + if (emptyState) emptyState.style.display = ''; + } + + function renderUploadMeta() { + if (!uploadMeta) return; + if (!pendingFiles.length) { + uploadMeta.hidden = true; + uploadMeta.replaceChildren(); + return; + } + + const row = document.createElement('div'); + row.className = 'webui-upload-meta-row'; + + pendingFiles.forEach((file, index) => { + const chip = document.createElement('div'); + chip.className = 'webui-upload-meta-chip'; + chip.title = file.name || 'file'; + const chars = Array.from(String(file.name || 'file')); + + const label = document.createElement('span'); + label.className = 'webui-upload-meta-chip-label'; + label.textContent = chars.length > 5 ? `${chars.slice(0, 5).join('')}...` : (file.name || 'file'); + chip.appendChild(label); + + const removeBtn = document.createElement('button'); + removeBtn.type = 'button'; + removeBtn.className = 'webui-upload-meta-chip-remove'; + removeBtn.setAttribute('aria-label', `删除 ${file.name || 'file'}`); + removeBtn.setAttribute('title', `删除 ${file.name || 'file'}`); + removeBtn.innerHTML = ''; + removeBtn.addEventListener('click', () => { + pendingFiles = pendingFiles.filter((_, itemIndex) => itemIndex !== index); + if (fileInput && !pendingFiles.length) fileInput.value = ''; + renderUploadMeta(); + }); + chip.appendChild(removeBtn); + + row.appendChild(chip); + }); + + uploadMeta.hidden = false; + uploadMeta.replaceChildren(row); + } + + function currentModelCapability() { + const selected = modelSelect && modelSelect.value + ? availableModels.find((item) => item && item.id === modelSelect.value) + : null; + return selected && selected.capability ? selected.capability : 'chat'; + } + + async function fileToDataUrl(file) { + return await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result || '')); + reader.onerror = () => reject(reader.error || new Error('file read failed')); + reader.readAsDataURL(file); + }); + } + + async function preparePendingFiles(fileList) { + const files = Array.from(fileList || []); + const prepared = []; + + for (const file of files) { + if (!file) continue; + prepared.push({ + name: file.name || 'file', + type: file.type || 'application/octet-stream', + size: Number(file.size) || 0, + dataUrl: await fileToDataUrl(file), + }); + } + + return prepared; + } + + function buildUserMessage(prompt, capability) { + const textBlock = prompt ? [{ type: 'text', text: prompt }] : []; + const imageFiles = pendingFiles.filter((file) => (file.type || '').startsWith('image/')); + const audioFiles = pendingFiles.filter((file) => (file.type || '').startsWith('audio/')); + const otherFiles = pendingFiles.filter((file) => { + const mime = file.type || ''; + return !mime.startsWith('image/') && !mime.startsWith('audio/'); + }); + + const imageBlocks = imageFiles.map((file) => ({ + type: 'image_url', + image_url: { url: file.dataUrl }, + })); + const audioBlocks = audioFiles.map((file) => ({ + type: 'input_audio', + input_audio: { + data: file.dataUrl, + filename: file.name, + }, + })); + const fileBlocks = otherFiles.map((file) => ({ + type: 'file', + file: { + file_data: file.dataUrl, + filename: file.name, + }, + })); + + if (capability === 'image') { + if (pendingFiles.length) { + throw new Error(text( + 'webui.chat.errors.imageUploadsNotSupported', + 'Image generation does not accept uploaded references here. Use chat, image edit, or video with a reference image.', + )); + } + return { role: 'user', content: prompt }; + } + if (capability === 'image_edit') { + if (!imageBlocks.length) { + throw new Error(text('webui.chat.errors.imageRequired', 'Image edit requires at least one reference image')); + } + if (audioBlocks.length || fileBlocks.length) { + throw new Error(text('webui.chat.errors.imageOnly', 'Image edit only supports image uploads')); + } + return { role: 'user', content: [...textBlock, ...imageBlocks] }; + } + if (capability === 'video') { + if (audioBlocks.length || fileBlocks.length) { + throw new Error(text('webui.chat.errors.videoImageOnly', 'Video generation only supports image reference uploads')); + } + return imageBlocks.length + ? { role: 'user', content: [...textBlock, imageBlocks[0]] } + : { role: 'user', content: prompt }; + } + if (imageBlocks.length || audioBlocks.length || fileBlocks.length) { + return { role: 'user', content: [...textBlock, ...imageBlocks, ...audioBlocks, ...fileBlocks] }; + } + return { role: 'user', content: prompt }; + } + + function closeSessionModal(result) { + if (!sessionModal) return; + sessionModal.classList.remove('open'); + sessionModal.setAttribute('aria-hidden', 'true'); + const resolver = modalResolver; + modalResolver = null; + if (resolver) resolver(result); + } + + function openSessionModal({ title, description = '', confirmLabel, cancelLabel, inputValue = '', withInput = false }) { + if (!sessionModal) return Promise.resolve(null); + sessionModalTitle.textContent = title; + sessionModalDesc.textContent = description; + sessionModalInputWrap.hidden = !withInput; + sessionModalInput.value = withInput ? inputValue : ''; + sessionModalCancel.textContent = cancelLabel || text('webui.chat.cancel', 'Cancel'); + sessionModalConfirm.textContent = confirmLabel || text('webui.chat.confirm', 'Confirm'); + sessionModal.classList.add('open'); + sessionModal.setAttribute('aria-hidden', 'false'); + if (withInput) { + setTimeout(() => { + sessionModalInput.focus(); + sessionModalInput.select(); + }, 0); + } + return new Promise((resolve) => { + modalResolver = resolve; + }); + } + + function editMessageAt(messageIndex, content) { + const session = getCurrentSession(); + if (!session || messageIndex < 0) return; + if (sending) stopMessage(); + + promptInput.value = activeEdit ? activeEdit.text : (extractTextContent(content) || (typeof content === 'string' ? content : '')); + pendingFiles = activeEdit ? activeEdit.files.slice() : extractEditablePendingFiles(content); + messages = messages.slice(0, messageIndex); + session.messages = messages; + session.model = modelSelect.value || PREFERRED_MODEL; + session.system = currentSystemPrompt(); + if (!session.titleLocked) session.title = createSessionTitle(session.messages); + session.updatedAt = Date.now(); + activeEdit = null; + moveSessionToTop(session); + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + setStatus(text('webui.chat.statusReady', 'Ready')); + persistStore(); + promptInput.focus(); + } + + function createMessage(role, initialText = '', initialReasoning = '', messageIndex = -1) { + hideEmpty(); + const hasReasoning = role === 'assistant' && hasVisibleReasoning(initialReasoning); + + const wrap = document.createElement('div'); + wrap.className = `msg ${role}`; + + const meta = document.createElement('div'); + meta.className = 'msg-meta'; + meta.textContent = role === 'user' + ? text('webui.chat.userLabel', 'You') + : text('webui.chat.assistantLabel', 'Grok'); + + const reasoning = document.createElement('div'); + reasoning.className = 'msg-reasoning'; + reasoning.hidden = !hasReasoning; + + const reasoningToggle = document.createElement('button'); + reasoningToggle.type = 'button'; + reasoningToggle.className = 'msg-reasoning-toggle'; + reasoningToggle.setAttribute('aria-expanded', 'true'); + reasoningToggle.innerHTML = `${escapeHtml(text('webui.chat.reasoning', 'Reasoning'))}`; + + const reasoningBody = document.createElement('div'); + reasoningBody.className = 'msg-reasoning-body'; + reasoningBody.textContent = hasReasoning ? initialReasoning : ''; + + reasoningToggle.addEventListener('click', () => { + const collapsed = reasoning.classList.toggle('is-collapsed'); + reasoningToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true'); + }); + + reasoning.appendChild(reasoningToggle); + reasoning.appendChild(reasoningBody); + + const card = document.createElement('div'); + card.className = `msg-card msg-card-${role}`; + const isEditing = role === 'user' && activeEdit && activeEdit.messageIndex === messageIndex; + if (isEditing) { + card.classList.add('msg-card-editing'); + + const editor = document.createElement('textarea'); + editor.className = 'msg-edit-textarea'; + editor.value = activeEdit.text; + editor.placeholder = text('webui.chat.editPlaceholder', 'Edit message'); + editor.addEventListener('input', () => { + if (!activeEdit || activeEdit.messageIndex !== messageIndex) return; + activeEdit.text = editor.value; + editor.style.height = 'auto'; + editor.style.height = `${Math.max(editor.scrollHeight, 52)}px`; + }); + editor.style.height = 'auto'; + editor.style.height = `${Math.max(editor.scrollHeight, 52)}px`; + + const footer = document.createElement('div'); + footer.className = 'msg-edit-footer'; + + const cancelBtn = document.createElement('button'); + cancelBtn.type = 'button'; + cancelBtn.className = 'msg-edit-cancel'; + cancelBtn.textContent = text('webui.chat.cancel', 'Cancel'); + cancelBtn.addEventListener('click', () => { + activeEdit = null; + renderThread(); + }); + + const saveBtn = document.createElement('button'); + saveBtn.type = 'button'; + saveBtn.className = 'msg-edit-save'; + saveBtn.textContent = text('webui.chat.save', 'Save'); + saveBtn.addEventListener('click', () => { + editMessageAt(messageIndex, initialText); + }); + + footer.appendChild(cancelBtn); + footer.appendChild(saveBtn); + card.appendChild(editor); + card.appendChild(footer); + + setTimeout(() => { + editor.focus(); + editor.setSelectionRange(editor.value.length, editor.value.length); + }, 0); + } else { + renderMessageContent(card, role, initialText); + } + + wrap.appendChild(meta); + if (role === 'assistant') { + wrap.appendChild(reasoning); + } + wrap.appendChild(card); + + if (role === 'user') { + const actions = document.createElement('div'); + actions.className = 'msg-actions'; + + const editBtn = document.createElement('button'); + editBtn.type = 'button'; + editBtn.className = 'msg-action-btn'; + editBtn.setAttribute('aria-label', text('webui.chat.edit', 'Edit')); + editBtn.setAttribute('title', text('webui.chat.edit', 'Edit')); + editBtn.innerHTML = ''; + editBtn.addEventListener('click', () => { + beginEditMessage(messageIndex, initialText); + }); + + const copyBtn = document.createElement('button'); + copyBtn.type = 'button'; + copyBtn.className = 'msg-action-btn'; + copyBtn.setAttribute('aria-label', text('webui.chat.copy', 'Copy')); + copyBtn.setAttribute('title', text('webui.chat.copy', 'Copy')); + copyBtn.innerHTML = ''; + copyBtn.addEventListener('click', async () => { + try { + await copyToClipboard(extractTextContent(initialText) || (typeof initialText === 'string' ? initialText : '')); + toast(text('webui.chat.copySuccess', 'Copied'), 'info'); + } catch (error) { + toast(error.message || String(error), 'error'); + } + }); + + if (!isEditing) { + actions.appendChild(editBtn); + actions.appendChild(copyBtn); + wrap.appendChild(actions); + } + } + + if (role === 'assistant') { + const actions = document.createElement('div'); + actions.className = 'msg-actions msg-actions-assistant'; + actions.hidden = messageIndex < 0; + const message = messageIndex >= 0 ? messages[messageIndex] : null; + + const right = document.createElement('div'); + right.className = 'msg-action-group'; + + const regenBtn = document.createElement('button'); + regenBtn.type = 'button'; + regenBtn.className = 'msg-action-btn msg-action-btn-regen'; + regenBtn.setAttribute('aria-label', text('webui.chat.regenerate', 'Regenerate')); + regenBtn.setAttribute('title', text('webui.chat.regenerate', 'Regenerate')); + regenBtn.innerHTML = ''; + regenBtn.addEventListener('click', () => { + regenerateAssistantAt(messageIndex); + }); + + const copyBtn = document.createElement('button'); + copyBtn.type = 'button'; + copyBtn.className = 'msg-action-btn'; + copyBtn.setAttribute('aria-label', text('webui.chat.copy', 'Copy')); + copyBtn.setAttribute('title', text('webui.chat.copy', 'Copy')); + copyBtn.innerHTML = ''; + copyBtn.addEventListener('click', async () => { + try { + await copyToClipboard(typeof initialText === 'string' ? initialText : extractTextContent(initialText)); + toast(text('webui.chat.copySuccess', 'Copied'), 'info'); + } catch (error) { + toast(error.message || String(error), 'error'); + } + }); + + const likeBtn = document.createElement('button'); + likeBtn.type = 'button'; + likeBtn.className = `msg-action-btn${message && message.feedback === 'up' ? ' active' : ''}`; + likeBtn.setAttribute('aria-label', text('webui.chat.like', 'Like')); + likeBtn.setAttribute('title', text('webui.chat.like', 'Like')); + likeBtn.innerHTML = ''; + likeBtn.addEventListener('click', () => { + setAssistantFeedback(messageIndex, 'up'); + }); + + const dislikeBtn = document.createElement('button'); + dislikeBtn.type = 'button'; + dislikeBtn.className = `msg-action-btn${message && message.feedback === 'down' ? ' active' : ''}`; + dislikeBtn.setAttribute('aria-label', text('webui.chat.dislike', 'Dislike')); + dislikeBtn.setAttribute('title', text('webui.chat.dislike', 'Dislike')); + dislikeBtn.innerHTML = ''; + dislikeBtn.addEventListener('click', () => { + setAssistantFeedback(messageIndex, 'down'); + }); + + right.appendChild(regenBtn); + right.appendChild(copyBtn); + right.appendChild(likeBtn); + right.appendChild(dislikeBtn); + actions.appendChild(right); + wrap.appendChild(actions); + } + + thread.appendChild(wrap); + + return { reasoning, reasoningBody, card, text: initialText, reasoningText: initialReasoning }; + } + + function updateAssistant(entry, delta) { + entry.text += delta; + renderMessageContent(entry.card, 'assistant', entry.text); + scrollThread(); + } + + function updateReasoning(entry, delta) { + entry.reasoningText += delta; + const hasReasoning = hasVisibleReasoning(entry.reasoningText); + entry.reasoning.hidden = !hasReasoning; + entry.reasoningBody.textContent = hasReasoning ? entry.reasoningText : ''; + scrollThread(); + } + + function renderThread() { + thread.innerHTML = ''; + if (emptyState) thread.appendChild(emptyState); + if (!messages.length) { + showEmpty(); + return; + } + hideEmpty(); + messages.forEach((message, index) => { + createMessage( + message.role, + message.content, + message.role === 'assistant' ? (message.reasoning_content || '') : '', + index, + ); + }); + scrollThread(); + } + + function renderSessionList() { + if (!sessionList) return; + sessionList.innerHTML = ''; + sessionList.dataset.empty = text('webui.chat.noSessions', 'No chats yet'); + + sessions.forEach((session) => { + const item = document.createElement('button'); + item.type = 'button'; + item.className = `webui-session-item${session.id === currentSessionId ? ' active' : ''}`; + + const title = document.createElement('div'); + title.className = 'webui-session-title'; + title.textContent = session.title || text('webui.chat.untitled', 'New Chat'); + const actions = document.createElement('div'); + actions.className = 'webui-session-actions'; + + const renameBtn = document.createElement('button'); + renameBtn.type = 'button'; + renameBtn.className = 'webui-session-action'; + renameBtn.title = text('webui.chat.rename', 'Rename'); + renameBtn.innerHTML = ''; + renameBtn.addEventListener('click', (event) => { + event.stopPropagation(); + renameSession(session.id); + }); + + const deleteBtn = document.createElement('button'); + deleteBtn.type = 'button'; + deleteBtn.className = 'webui-session-action'; + deleteBtn.title = text('webui.chat.delete', 'Delete'); + deleteBtn.innerHTML = ''; + deleteBtn.addEventListener('click', (event) => { + event.stopPropagation(); + deleteSession(session.id); + }); + + actions.appendChild(renameBtn); + actions.appendChild(deleteBtn); + + item.appendChild(title); + item.appendChild(actions); + item.addEventListener('click', () => switchSession(session.id)); + sessionList.appendChild(item); + }); + } + + function syncCurrentSession() { + const session = getCurrentSession(); + if (!session) return; + session.model = modelSelect.value || PREFERRED_MODEL; + session.system = currentSystemPrompt(); + if (!session.titleLocked) session.title = createSessionTitle(session.messages); + session.updatedAt = Date.now(); + moveSessionToTop(session); + persistStore(); + renderSessionList(); + } + + function switchSession(id) { + const session = sessions.find((item) => item.id === id); + if (!session) return; + currentSessionId = session.id; + messages = session.messages; + pendingFiles = []; + activeEdit = null; + if (modelSelect.options.length) { + modelSelect.value = Array.from(modelSelect.options).some((option) => option.value === session.model) + ? session.model + : (modelSelect.value || PREFERRED_MODEL); + } + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + setStatus(text('webui.chat.statusReady', 'Ready')); + persistStore(); + } + + function startNewSession() { + const session = createSession(); + sessions.unshift(session); + currentSessionId = session.id; + messages = session.messages; + pendingFiles = []; + activeEdit = null; + renderUploadMeta(); + renderSessionList(); + renderThread(); + resizePromptInput(); + setStatus(text('webui.chat.statusReady', 'Ready')); + persistStore(); + promptInput.focus(); + } + + function renameSession(id) { + const session = sessions.find((item) => item.id === id); + if (!session) return; + openSessionModal({ + title: text('webui.chat.rename', 'Rename'), + description: text('webui.chat.renamePrompt', 'Rename session'), + confirmLabel: text('webui.chat.confirm', 'Confirm'), + cancelLabel: text('webui.chat.cancel', 'Cancel'), + inputValue: session.title || text('webui.chat.untitled', 'New Chat'), + withInput: true, + }).then((nextTitle) => { + if (typeof nextTitle !== 'string') return; + const trimmed = nextTitle.trim(); + if (!trimmed) return; + session.title = trimmed; + session.titleLocked = true; + session.updatedAt = Date.now(); + moveSessionToTop(session); + persistStore(); + renderSessionList(); + }); + } + + function deleteSession(id) { + const session = sessions.find((item) => item.id === id); + if (!session) return; + openSessionModal({ + title: text('webui.chat.delete', 'Delete'), + description: text('webui.chat.deleteConfirm', 'Delete this session?'), + confirmLabel: text('webui.chat.delete', 'Delete'), + cancelLabel: text('webui.chat.cancel', 'Cancel'), + }).then((confirmed) => { + if (!confirmed) return; + sessions = sessions.filter((item) => item.id !== id); + if (!sessions.length) { + startNewSession(); + return; + } + + const next = sessions[0]; + currentSessionId = next.id; + persistStore(); + switchSession(next.id); + }); + } + + function buildPayload() { + const outgoing = []; + const system = currentSystemPrompt(); + if (system) outgoing.push({ role: 'system', content: system }); + messages.forEach((message) => outgoing.push(message)); + return { + model: modelSelect.value || PREFERRED_MODEL, + messages: outgoing, + stream: true, + temperature: 0.8, + top_p: 0.95, + }; + } + + async function loadModels() { + const headers = await getAuthHeaders(); + const res = await fetch(MODELS_ENDPOINT, { headers, cache: 'no-store' }); + if (!res.ok) throw new Error(`models ${res.status}`); + + const data = await res.json(); + const items = Array.isArray(data && data.data) ? data.data : []; + availableModels = items.filter((item) => item && item.id); + const ids = items.map((item) => item && item.id).filter(Boolean); + + modelSelect.innerHTML = ''; + availableModels.forEach((item) => { + const opt = document.createElement('option'); + opt.value = item.id; + opt.textContent = item.name || item.id; + modelSelect.appendChild(opt); + }); + modelSelect.value = ids.includes(PREFERRED_MODEL) ? PREFERRED_MODEL : (ids[0] || PREFERRED_MODEL); + } + + async function sendMessage() { + if (sending) return; + + const prompt = (promptInput.value || '').trim(); + const capability = currentModelCapability(); + if (!prompt) { + toast(text('webui.chat.errors.enterPrompt', 'Please enter a message'), 'error'); + return; + } + + const session = getCurrentSession(); + if (!session) return; + activeEdit = null; + + let userMessage; + try { + userMessage = buildUserMessage(prompt, capability); + } catch (error) { + toast(error.message || String(error), 'error'); + return; + } + + session.model = modelSelect.value || PREFERRED_MODEL; + session.system = currentSystemPrompt(); + messages.push(userMessage); + if (!session.titleLocked) session.title = createSessionTitle(messages); + session.updatedAt = Date.now(); + moveSessionToTop(session); + persistStore(); + renderSessionList(); + + messages[messages.length - 1].createdAt = Date.now(); + messages[messages.length - 1].feedback = ''; + const userEntry = createMessage('user', userMessage.content, '', messages.length - 1); + void userEntry; + const assistantCreatedAt = Date.now(); + const assistantEntry = createMessage('assistant', '', '', -1); + + promptInput.value = ''; + pendingFiles = []; + if (fileInput) fileInput.value = ''; + renderUploadMeta(); + resizePromptInput(); + abortController = new AbortController(); + setSending(true); + setStatus(text('webui.chat.statusConnecting', 'Connecting...')); + + try { + const headers = { + 'Content-Type': 'application/json', + ...(await getAuthHeaders()), + }; + const res = await fetch(CHAT_ENDPOINT, { + method: 'POST', + headers, + body: JSON.stringify(buildPayload()), + signal: abortController.signal, + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + throw new Error(detail || `HTTP ${res.status}`); + } + + const reader = res.body.getReader(); + const decoder = new TextDecoder('utf-8'); + let buffer = ''; + + function handleStreamChunk(chunk) { + const messageEvent = parseSseEvent(chunk); + const payload = messageEvent.data.trim(); + if (!payload) return false; + if (payload === '[DONE]') { + const finalReasoning = hasVisibleReasoning(assistantEntry.reasoningText) ? assistantEntry.reasoningText : ''; + messages.push({ + role: 'assistant', + content: assistantEntry.text, + reasoning_content: finalReasoning, + createdAt: assistantCreatedAt, + feedback: '', + }); + syncCurrentSession(); + renderThread(); + setStatus(text('webui.chat.statusDone', 'Completed')); + return true; + } + + let json; + try { + json = JSON.parse(payload); + } catch { + return false; + } + + if (messageEvent.event === 'error' || json.error) { + const errorMessage = json.error && json.error.message + ? json.error.message + : text('webui.chat.errors.requestFailed', 'Request failed'); + throw new Error(errorMessage); + } + + const choice = json && json.choices && json.choices[0]; + const delta = choice && choice.delta ? choice.delta : {}; + if (typeof delta.reasoning_content === 'string') { + updateReasoning(assistantEntry, delta.reasoning_content); + if (hasVisibleReasoning(assistantEntry.reasoningText)) { + setStatus(text('webui.chat.statusThinking', 'Thinking...')); + } + } + if (delta.content) { + updateAssistant(assistantEntry, delta.content); + setStatus(text('webui.chat.statusGenerating', 'Generating...')); + } + return false; + } + + while (true) { + const { value, done } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n'); + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() || ''; + + for (const chunk of chunks) { + if (handleStreamChunk(chunk)) return; + } + } + + if (buffer.trim() && handleStreamChunk(buffer)) return; + + const finalReasoning = hasVisibleReasoning(assistantEntry.reasoningText) ? assistantEntry.reasoningText : ''; + messages.push({ + role: 'assistant', + content: assistantEntry.text, + reasoning_content: finalReasoning, + createdAt: assistantCreatedAt, + feedback: '', + }); + syncCurrentSession(); + renderThread(); + setStatus(text('webui.chat.statusDone', 'Completed')); + } catch (error) { + if (error && error.name === 'AbortError') { + setStatus(text('webui.chat.statusStopped', 'Stopped')); + } else { + renderMessageContent( + assistantEntry.card, + 'assistant', + `${text('webui.chat.errors.requestFailed', 'Request failed')}: ${error.message || error}`, + ); + toast(text('webui.chat.errors.requestFailed', 'Request failed'), 'error'); + setStatus(text('webui.chat.statusFailed', 'Failed')); + } + } finally { + abortController = null; + setSending(false); + scrollThread(); + } + } + + function stopMessage() { + if (abortController) abortController.abort(); + } + + function restoreSessions() { + const stored = loadStore(); + sessions = stored.sessions.map(normalizeSession); + currentSessionId = stored.currentSessionId; + + if (!sessions.length) { + startNewSession(); + return; + } + + const existing = sessions.find((item) => item.id === currentSessionId) || sessions[0]; + switchSession(existing.id); + } + + async function boot() { + await renderWebuiHeader?.(); + if (window.I18n?.apply) I18n.apply(document); + renderSendButton(); + window.I18n?.onReady?.(renderSendButton); + if (!await ensureAccess()) return; + loadSidebarState(); + await loadModels(); + restoreSessions(); + resizePromptInput(); + promptInput.focus(); + } + + newChatBtn?.addEventListener('click', startNewSession); + sidebarToggleBtn.addEventListener('click', toggleSidebar); + sendBtn.addEventListener('click', () => { + if (sending) { + stopMessage(); + return; + } + sendMessage(); + }); + modelSelect.addEventListener('change', syncCurrentSession); + systemInput?.addEventListener('change', syncCurrentSession); + uploadBtn.addEventListener('click', () => fileInput.click()); + fileInput.addEventListener('change', async () => { + try { + pendingFiles = await preparePendingFiles(fileInput.files || []); + renderUploadMeta(); + } catch (error) { + pendingFiles = []; + if (fileInput) fileInput.value = ''; + renderUploadMeta(); + toast(error.message || String(error), 'error'); + } + }); + sessionModalCancel.addEventListener('click', () => closeSessionModal(false)); + sessionModalConfirm.addEventListener('click', () => { + const result = sessionModalInputWrap.hidden ? true : sessionModalInput.value; + closeSessionModal(result); + }); + sessionModal.addEventListener('click', (event) => { + if (event.target === sessionModal) closeSessionModal(false); + }); + sessionModalInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + closeSessionModal(sessionModalInput.value); + } + }); + promptInput.addEventListener('input', resizePromptInput); + promptInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + sendMessage(); + } + }); + + boot().catch((error) => { + console.error('webui chat boot failed', error); + toast(text('webui.chat.errors.initFailed', 'Chat page initialization failed'), 'error'); + setStatus(text('webui.chat.statusInitFailed', 'Initialization failed')); + }); +})(); diff --git a/app/statics/js/webui/chatkit.js b/app/statics/js/webui/chatkit.js new file mode 100644 index 00000000..d0fe0b47 --- /dev/null +++ b/app/statics/js/webui/chatkit.js @@ -0,0 +1,514 @@ +(() => { + const VOICE_ENDPOINT = '/webui/api/voice/token'; + const MOBILE_BREAKPOINT = 960; + const voiceSelect = document.getElementById('voiceSelect'); + const personalitySelect = document.getElementById('personalitySelect'); + const speedSelect = document.getElementById('speedSelect'); + const startVoiceBtn = document.getElementById('startVoiceBtn'); + const muteVoiceBtn = document.getElementById('muteVoiceBtn'); + const newSessionBtn = document.getElementById('newSessionBtn'); + const chatkitPanelToggle = document.getElementById('chatkitPanelToggle'); + const chatkitShell = document.querySelector('.webui-chatkit-shell'); + const chatkitPanel = document.querySelector('.webui-chatkit-panel'); + const voiceLog = document.getElementById('voiceLog'); + const clearVoiceLogBtn = document.getElementById('clearVoiceLogBtn'); + const connectionBadge = document.getElementById('connectionBadge'); + const connectionText = document.getElementById('connectionText'); + const voiceOrb = document.getElementById('voiceOrb'); + const roomName = document.getElementById('roomName'); + const participantName = document.getElementById('participantName'); + const remoteCount = document.getElementById('remoteCount'); + const voiceEndpoint = document.getElementById('voiceEndpoint'); + const audioRoot = document.getElementById('audioRoot'); + + let room = null; + let remoteParticipants = 0; + let micEnabled = true; + let outputMuted = false; + let mobilePanelOpen = false; + let orbAudioContext = null; + let orbAnalyser = null; + let orbSource = null; + let orbData = null; + let orbFrame = 0; + let orbLevel = 0; + let orbStreamId = ''; + + const controlIcon = { + start: '', + pause: '', + mute: '', + unmute: '', + newSession: '', + }; + + const text = (key, fallback, params) => { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + }; + + const isMobileLayout = () => window.innerWidth <= MOBILE_BREAKPOINT; + + const syncMobilePanel = () => { + if (!chatkitShell || !chatkitPanelToggle) return; + const mobile = isMobileLayout(); + chatkitShell.classList.toggle('is-mobile-panel-open', mobile && mobilePanelOpen); + chatkitPanelToggle.classList.toggle('is-open', mobile && mobilePanelOpen); + chatkitPanelToggle.hidden = !mobile; + chatkitPanelToggle.setAttribute('aria-expanded', mobile && mobilePanelOpen ? 'true' : 'false'); + const label = mobile && mobilePanelOpen + ? text('webui.chatkit.panelHide', '收起设置') + : text('webui.chatkit.panelShow', '设置'); + chatkitPanelToggle.setAttribute('aria-label', label); + chatkitPanelToggle.setAttribute('title', label); + }; + + const syncVoiceLogEmptyState = () => { + if (!voiceLog) return; + voiceLog.dataset.empty = text( + 'webui.chatkit.logEmpty', + '待机中,连接后这里会显示会话事件。', + ); + }; + + const logLine = (message, level = 'info') => { + if (!voiceLog) return; + const item = document.createElement('div'); + item.className = `webui-chatkit-log-item${level !== 'info' ? ` is-${level}` : ''}`; + item.textContent = `[${new Date().toLocaleTimeString()}] ${message}`; + voiceLog.prepend(item); + syncVoiceLogEmptyState(); + }; + + const setOrbLevel = (level) => { + orbLevel = Math.max(0, Math.min(1, level || 0)); + if (!voiceOrb) return; + voiceOrb.style.setProperty('--chatkit-level', orbLevel.toFixed(3)); + voiceOrb.classList.toggle('is-speaking', voiceOrb.classList.contains('is-live') && orbLevel > 0.08); + }; + + const stopOrbAnalysis = () => { + if (orbFrame) { + cancelAnimationFrame(orbFrame); + orbFrame = 0; + } + if (orbSource) { + try { + orbSource.disconnect(); + } catch {} + } + orbAnalyser = null; + orbSource = null; + orbData = null; + orbStreamId = ''; + setOrbLevel(0); + }; + + const ensureOrbAudioContext = async () => { + const AudioContextCtor = window.AudioContext || window.webkitAudioContext; + if (!AudioContextCtor) return null; + if (!orbAudioContext) orbAudioContext = new AudioContextCtor(); + if (orbAudioContext.state === 'suspended') { + try { + await orbAudioContext.resume(); + } catch {} + } + return orbAudioContext; + }; + + const startOrbAnalysis = async (element) => { + if (!element || !(element.srcObject instanceof MediaStream)) { + stopOrbAnalysis(); + return; + } + + const stream = element.srcObject; + const streamId = stream.id || stream.getAudioTracks?.()[0]?.id || ''; + if (streamId && streamId === orbStreamId && orbAnalyser) return; + + stopOrbAnalysis(); + const context = await ensureOrbAudioContext(); + if (!context) return; + + try { + orbAnalyser = context.createAnalyser(); + orbAnalyser.fftSize = 256; + orbAnalyser.smoothingTimeConstant = 0.82; + orbData = new Uint8Array(orbAnalyser.fftSize); + orbSource = context.createMediaStreamSource(stream); + orbSource.connect(orbAnalyser); + orbStreamId = streamId; + + const render = () => { + if (!orbAnalyser || !orbData) return; + orbAnalyser.getByteTimeDomainData(orbData); + let sum = 0; + for (let index = 0; index < orbData.length; index += 1) { + const normalized = (orbData[index] - 128) / 128; + sum += normalized * normalized; + } + const rms = Math.sqrt(sum / orbData.length); + const targetLevel = Math.max(0, Math.min(1, (rms - 0.015) * 8.2)); + const nextLevel = orbLevel + (targetLevel - orbLevel) * 0.22; + setOrbLevel(nextLevel < 0.012 ? 0 : nextLevel); + orbFrame = requestAnimationFrame(render); + }; + + render(); + } catch { + stopOrbAnalysis(); + } + }; + + const setStatus = (state, label, description) => { + if (connectionBadge) connectionBadge.textContent = label; + if (connectionText) connectionText.textContent = description; + if (voiceOrb) { + voiceOrb.classList.remove('is-idle', 'is-connecting', 'is-live', 'is-paused', 'is-output-muted', 'is-error'); + voiceOrb.classList.add(state); + if (state !== 'is-live') { + voiceOrb.classList.remove('is-speaking'); + setOrbLevel(0); + } + } + }; + + const renderConnectedStatus = () => { + if (!room) { + setStatus( + 'is-idle', + text('webui.chatkit.statusIdle', '未连接'), + text('webui.chatkit.idleText', '准备好后点击开始,授权麦克风即可进入语音会话。'), + ); + return; + } + + if (!micEnabled) { + setStatus( + 'is-paused', + text('webui.chatkit.statusPaused', '已暂停'), + text('webui.chatkit.pausedText', '会话已暂停,点击开始即可继续当前语音会话。'), + ); + return; + } + + if (outputMuted) { + setStatus( + 'is-output-muted', + text('webui.chatkit.statusMuted', '已静音'), + text('webui.chatkit.outputMutedText', '扬声器已静音,你仍然可以继续说话。'), + ); + return; + } + + setStatus( + 'is-live', + text('webui.chatkit.statusLive', '语音中'), + text('webui.chatkit.liveText', '连接已建立,现在可以直接开口和 Grok 对话。'), + ); + }; + + const setButtons = (connected) => { + if (startVoiceBtn) { + startVoiceBtn.disabled = false; + const label = connected && micEnabled + ? text('webui.chatkit.pause', '暂停') + : text('webui.chatkit.start', '开始'); + startVoiceBtn.innerHTML = connected && micEnabled ? controlIcon.pause : controlIcon.start; + startVoiceBtn.setAttribute('aria-label', label); + startVoiceBtn.setAttribute('title', label); + } + if (muteVoiceBtn) { + muteVoiceBtn.disabled = !connected; + const label = outputMuted + ? text('webui.chatkit.unmute', '取消静音') + : text('webui.chatkit.mute', '静音'); + muteVoiceBtn.innerHTML = outputMuted ? controlIcon.unmute : controlIcon.mute; + muteVoiceBtn.setAttribute('aria-label', label); + muteVoiceBtn.setAttribute('title', label); + } + if (newSessionBtn) { + newSessionBtn.disabled = !connected; + const label = text('webui.chatkit.newSession', '新会话'); + newSessionBtn.innerHTML = controlIcon.newSession; + newSessionBtn.setAttribute('aria-label', label); + newSessionBtn.setAttribute('title', label); + } + }; + + const updateRemoteCount = () => { + if (remoteCount) remoteCount.textContent = String(Math.max(0, remoteParticipants)); + }; + + const detachAudio = () => { + stopOrbAnalysis(); + if (!audioRoot) return; + audioRoot.querySelectorAll('audio').forEach((node) => { + try { + node.pause(); + node.srcObject = null; + } catch {} + node.remove(); + }); + }; + + const resetSessionMeta = () => { + if (roomName) roomName.textContent = '-'; + if (participantName) participantName.textContent = '-'; + if (voiceEndpoint) voiceEndpoint.textContent = 'wss://livekit.grok.com'; + remoteParticipants = 0; + updateRemoteCount(); + }; + + const getLiveKit = () => window.LiveKitClient || window.LivekitClient || null; + + const getAuthHeaders = async () => { + const key = await webuiKey.get(); + return key ? { Authorization: `Bearer ${key}` } : {}; + }; + + const addRemoteAudioTrack = (track) => { + if (!audioRoot || !track || track.kind !== 'audio') return; + const element = track.attach(); + element.autoplay = true; + element.playsInline = true; + element.muted = outputMuted; + audioRoot.appendChild(element); + void startOrbAnalysis(element); + }; + + const bindRoomEvents = (lk, currentRoom) => { + currentRoom.on(lk.RoomEvent.ParticipantConnected, (participant) => { + remoteParticipants += 1; + updateRemoteCount(); + logLine(text('webui.chatkit.participantJoined', 'Remote participant joined: {identity}', { + identity: participant.identity || 'remote', + })); + }); + + currentRoom.on(lk.RoomEvent.ParticipantDisconnected, (participant) => { + remoteParticipants = Math.max(0, remoteParticipants - 1); + updateRemoteCount(); + logLine(text('webui.chatkit.participantLeft', 'Remote participant left: {identity}', { + identity: participant.identity || 'remote', + })); + }); + + currentRoom.on(lk.RoomEvent.TrackSubscribed, (track) => { + addRemoteAudioTrack(track); + logLine(text('webui.chatkit.trackSubscribed', 'Remote audio subscribed')); + }); + + currentRoom.on(lk.RoomEvent.TrackUnsubscribed, (track) => { + try { + const elements = track.detach(); + let activeRemoved = false; + elements.forEach((el) => { + if (el instanceof HTMLMediaElement && el.srcObject instanceof MediaStream) { + const streamId = el.srcObject.id || el.srcObject.getAudioTracks?.()[0]?.id || ''; + if (streamId && streamId === orbStreamId) activeRemoved = true; + } + el.remove(); + }); + if (activeRemoved) { + const nextAudio = audioRoot?.querySelector('audio'); + if (nextAudio instanceof HTMLAudioElement) { + void startOrbAnalysis(nextAudio); + } else { + stopOrbAnalysis(); + } + } + } catch {} + }); + + currentRoom.on(lk.RoomEvent.Disconnected, () => { + logLine(text('webui.chatkit.disconnected', 'Voice session disconnected'), 'warn'); + teardownSession(false); + }); + }; + + const teardownSession = async (manual) => { + const currentRoom = room; + room = null; + try { + if (currentRoom) await currentRoom.disconnect(); + } catch {} + detachAudio(); + resetSessionMeta(); + micEnabled = true; + outputMuted = false; + setButtons(false); + renderConnectedStatus(); + if (manual && connectionText) { + connectionText.textContent = text('webui.chatkit.endedText', '语音会话已结束,可以重新开始。'); + } + }; + + const startSession = async () => { + const lk = getLiveKit(); + if (!lk || !lk.Room) { + showToast?.(text('webui.chatkit.livekitLoadFailed', 'LiveKit SDK 加载失败'), 'error'); + return; + } + + if (startVoiceBtn) startVoiceBtn.disabled = true; + void ensureOrbAudioContext(); + setStatus( + 'is-connecting', + text('webui.chatkit.statusConnecting', '正在连接'), + text('webui.chatkit.connectingText', '正在向 Grok Voice 申请会话并连接 LiveKit…'), + ); + logLine(text('webui.chatkit.fetchingToken', 'Requesting voice token...')); + + try { + const params = new URLSearchParams({ + voice: voiceSelect?.value || 'ara', + personality: personalitySelect?.value || 'assistant', + speed: speedSelect?.value || '1.0', + }); + const res = await fetch(`${VOICE_ENDPOINT}?${params.toString()}`, { + headers: await getAuthHeaders(), + cache: 'no-store', + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + throw new Error(detail || `HTTP ${res.status}`); + } + + const payload = await res.json(); + if (!payload || !payload.token || !payload.url) { + throw new Error(text('webui.chatkit.invalidToken', 'Voice token response invalid')); + } + + if (roomName) roomName.textContent = payload.room_name || '-'; + if (participantName) participantName.textContent = payload.participant_name || '-'; + if (voiceEndpoint) voiceEndpoint.textContent = payload.url || 'wss://livekit.grok.com'; + + const currentRoom = new lk.Room({ + adaptiveStream: true, + dynacast: true, + audioCaptureDefaults: { + autoGainControl: true, + echoCancellation: true, + noiseSuppression: true, + }, + }); + room = currentRoom; + bindRoomEvents(lk, currentRoom); + + await currentRoom.connect(payload.url, payload.token); + await currentRoom.localParticipant.setMicrophoneEnabled(true); + + micEnabled = true; + outputMuted = false; + setButtons(true); + renderConnectedStatus(); + logLine(text('webui.chatkit.connected', 'Voice session connected')); + } catch (error) { + const message = error && error.message ? error.message : String(error); + logLine(message, 'error'); + showToast?.(message, 'error'); + setStatus( + 'is-error', + text('webui.chatkit.statusError', '连接失败'), + text('webui.chatkit.errorText', '连接没有建立成功,请检查麦克风权限后重试。'), + ); + await teardownSession(false); + } finally { + if (startVoiceBtn && !room) startVoiceBtn.disabled = false; + } + }; + + const togglePause = async () => { + if (!room) return; + micEnabled = !micEnabled; + await room.localParticipant.setMicrophoneEnabled(micEnabled); + setButtons(true); + renderConnectedStatus(); + logLine( + micEnabled + ? text('webui.chatkit.sessionResumed', 'Voice session resumed') + : text('webui.chatkit.sessionPaused', 'Voice session paused'), + 'warn', + ); + }; + + const toggleOutputMute = () => { + if (!room) return; + outputMuted = !outputMuted; + if (audioRoot) { + audioRoot.querySelectorAll('audio').forEach((node) => { + node.muted = outputMuted; + }); + } + setButtons(true); + renderConnectedStatus(); + logLine( + outputMuted + ? text('webui.chatkit.outputMuted', 'Speaker muted') + : text('webui.chatkit.outputUnmuted', 'Speaker unmuted'), + 'warn', + ); + }; + + const handlePrimaryAction = async () => { + if (!room) { + await startSession(); + return; + } + await togglePause(); + }; + + const startFreshSession = async () => { + if (!room) return; + logLine(text('webui.chatkit.startingNewSession', 'Starting a new voice session...')); + await teardownSession(true); + await startSession(); + }; + + startVoiceBtn?.addEventListener('click', () => { + void handlePrimaryAction(); + }); + muteVoiceBtn?.addEventListener('click', toggleOutputMute); + newSessionBtn?.addEventListener('click', () => { + void startFreshSession(); + }); + clearVoiceLogBtn?.addEventListener('click', () => { + if (voiceLog) voiceLog.innerHTML = ''; + syncVoiceLogEmptyState(); + }); + chatkitPanelToggle?.addEventListener('click', () => { + mobilePanelOpen = !mobilePanelOpen; + syncMobilePanel(); + }); + document.addEventListener('click', (event) => { + if (!isMobileLayout() || !mobilePanelOpen) return; + const target = event.target; + if (!(target instanceof Node)) return; + if (chatkitPanelToggle?.contains(target) || chatkitPanel?.contains(target)) return; + mobilePanelOpen = false; + syncMobilePanel(); + }); + + window.addEventListener('beforeunload', () => { + if (room) void room.disconnect(); + }); + window.addEventListener('resize', () => { + if (!isMobileLayout()) mobilePanelOpen = false; + syncMobilePanel(); + }); + + resetSessionMeta(); + setButtons(false); + setStatus( + 'is-idle', + text('webui.chatkit.statusIdle', '未连接'), + text('webui.chatkit.idleText', '准备好后点击开始,授权麦克风即可进入语音会话。'), + ); + syncVoiceLogEmptyState(); + syncMobilePanel(); + if (typeof renderWebuiHeader === 'function') { + void renderWebuiHeader(); + } +})(); diff --git a/app/statics/js/webui/masonry.js b/app/statics/js/webui/masonry.js new file mode 100644 index 00000000..d9335caf --- /dev/null +++ b/app/statics/js/webui/masonry.js @@ -0,0 +1,668 @@ +(() => { + const VERIFY_ENDPOINT = '/webui/api/verify'; + const IMAGINE_WS_ENDPOINT = '/webui/api/imagine/ws'; + const IMAGE_COUNT = 6; + const PROMPT_MIN_HEIGHT = 52; + const PROMPT_MAX_HEIGHT = 160; + const RECONNECT_DELAY_MS = 250; + + const promptInput = document.getElementById('promptInput'); + const sendBtn = document.getElementById('sendBtn'); + const feed = document.getElementById('masonryFeed'); + const emptyState = document.getElementById('masonryEmpty'); + const statusEl = document.getElementById('masonryStatus'); + const aspectRatioSelect = document.getElementById('aspectRatioSelect'); + const aspectRatioWrap = document.getElementById('aspectRatioWrap'); + const qualityToggle = document.getElementById('qualityToggle'); + const modeToggle = document.getElementById('modeToggle'); + + let activeSocket = null; + let sending = false; + let streamState = null; + + function aspectRatioCss(value) { + const ratio = String(value || '').trim(); + if (!ratio.includes(':')) return '1 / 1'; + const [w, h] = ratio.split(':'); + const width = Number(w) || 1; + const height = Number(h) || 1; + return `${width} / ${height}`; + } + + function computeGridColumns(width) { + const viewport = window.innerWidth || width || 0; + const maxCols = viewport <= 768 ? 3 : 8; + const minTileWidth = viewport <= 768 ? 132 : 188; + const safeWidth = Math.max(width || 0, minTileWidth); + return Math.max(1, Math.min(maxCols, Math.floor(safeWidth / minTileWidth))); + } + + function syncBatchGrid(grid) { + if (!(grid instanceof HTMLElement)) return; + const columns = computeGridColumns(grid.clientWidth); + grid.style.setProperty('--masonry-columns', String(columns)); + } + + function syncAllBatchGrids() { + feed?.querySelectorAll('.webui-masonry-grid').forEach((grid) => { + syncBatchGrid(grid); + }); + } + + function text(key, fallback, params) { + if (typeof window.t !== 'function') return fallback; + const value = t(key, params); + return value === key ? fallback : value; + } + + function toast(message, type = 'info') { + if (typeof showToast === 'function') showToast(message, type); + } + + function buildWebSocketUrl(path, params = {}) { + const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const url = new URL(path, `${protocol}//${window.location.host}`); + Object.entries(params).forEach(([key, value]) => { + if (value === null || value === undefined || value === '') return; + url.searchParams.set(key, String(value)); + }); + return url.toString(); + } + + function resizePromptInput() { + if (!promptInput) return; + promptInput.style.height = `${PROMPT_MIN_HEIGHT}px`; + const nextHeight = Math.min(Math.max(promptInput.scrollHeight, PROMPT_MIN_HEIGHT), PROMPT_MAX_HEIGHT); + promptInput.style.height = `${nextHeight}px`; + promptInput.style.overflowY = promptInput.scrollHeight > PROMPT_MAX_HEIGHT ? 'auto' : 'hidden'; + } + + function setEmptyState() { + if (!feed || !emptyState) return; + const hasBatch = feed.querySelector('.webui-masonry-batch') !== null; + emptyState.hidden = hasBatch; + emptyState.style.display = hasBatch ? 'none' : ''; + } + + function setStatus(message, state = 'idle') { + if (!statusEl) return; + statusEl.textContent = message; + statusEl.dataset.state = state; + } + + function renderSendButton(running) { + if (!sendBtn) return; + const label = running + ? text('webui.masonry.stop', '停止') + : text('webui.masonry.generate', '生成'); + const icon = running + ? '' + : ''; + sendBtn.innerHTML = icon; + sendBtn.setAttribute('aria-label', label); + sendBtn.setAttribute('title', label); + } + + function setSending(next) { + sending = next; + if (promptInput) promptInput.disabled = next; + if (aspectRatioSelect) aspectRatioSelect.disabled = next; + qualityToggle?.querySelectorAll('.webui-masonry-toggle-btn').forEach((button) => { + button.disabled = next; + }); + modeToggle?.querySelectorAll('.webui-masonry-toggle-btn').forEach((button) => { + button.disabled = next; + }); + renderSendButton(next); + } + + function formatRoundLabel(round) { + return text('webui.masonry.roundLabel', '第 {n} 轮', { n: round }); + } + + function formatQualityLabel(quality) { + return quality === 'quality' + ? text('webui.masonry.qualityQuality', 'Quality') + : text('webui.masonry.qualitySpeed', 'Speed'); + } + + function syncAspectRatioIndicator() { + const ratio = aspectRatioSelect?.value || '2:3'; + if (aspectRatioWrap) aspectRatioWrap.dataset.ratio = ratio; + } + + function readToggleValue(group, fallback) { + const active = group?.querySelector('.webui-masonry-toggle-btn.is-active'); + return active?.dataset.value || fallback; + } + + function setToggleValue(group, value) { + group?.querySelectorAll('.webui-masonry-toggle-btn').forEach((button) => { + const active = button.dataset.value === value; + button.classList.toggle('is-active', active); + button.setAttribute('aria-pressed', active ? 'true' : 'false'); + }); + } + + function createSlot(index) { + const tile = document.createElement('article'); + tile.className = 'webui-masonry-tile is-pending'; + + const badge = document.createElement('div'); + badge.className = 'webui-masonry-tile-badge'; + badge.textContent = String(index); + + const body = document.createElement('div'); + body.className = 'webui-masonry-tile-body'; + + const label = document.createElement('div'); + label.className = 'webui-masonry-tile-label'; + label.textContent = '0%'; + + body.appendChild(label); + tile.appendChild(badge); + tile.appendChild(body); + + return { + index, + id: '', + url: '', + progress: 0, + moderated: false, + tile, + body, + label, + }; + } + + function createBatch(prompt, aspectRatio, quality, round) { + const wrap = document.createElement('section'); + wrap.className = 'webui-masonry-batch'; + + const head = document.createElement('header'); + head.className = 'webui-masonry-batch-head'; + + const promptEl = document.createElement('div'); + promptEl.className = 'webui-masonry-batch-prompt'; + promptEl.textContent = prompt; + + const meta = document.createElement('div'); + meta.className = 'webui-masonry-batch-meta'; + + const ratio = document.createElement('span'); + ratio.className = 'webui-masonry-batch-chip'; + ratio.textContent = aspectRatio; + + const qualityChip = document.createElement('span'); + qualityChip.className = 'webui-masonry-batch-chip'; + qualityChip.textContent = formatQualityLabel(quality); + + const roundLabel = document.createElement('span'); + roundLabel.className = 'webui-masonry-batch-chip'; + roundLabel.textContent = formatRoundLabel(round); + + const count = document.createElement('span'); + count.className = 'webui-masonry-batch-chip'; + count.textContent = `0/${IMAGE_COUNT}`; + + const state = document.createElement('span'); + state.className = 'webui-masonry-batch-chip'; + state.textContent = text('webui.masonry.statusGenerating', '生成中…'); + + meta.appendChild(roundLabel); + meta.appendChild(ratio); + meta.appendChild(qualityChip); + meta.appendChild(count); + meta.appendChild(state); + + head.appendChild(promptEl); + head.appendChild(meta); + + const grid = document.createElement('div'); + grid.className = 'webui-masonry-grid'; + grid.style.setProperty('--tile-aspect', aspectRatioCss(aspectRatio)); + + const slots = Array.from({ length: IMAGE_COUNT }, (_, index) => createSlot(index + 1)); + slots.forEach((slot) => grid.appendChild(slot.tile)); + + wrap.appendChild(head); + wrap.appendChild(grid); + feed.prepend(wrap); + setEmptyState(); + syncBatchGrid(grid); + + return { + wrap, + count, + state, + slots, + round, + prompt, + aspectRatio, + quality, + completed: false, + failed: false, + }; + } + + function updateBatchMeta(batch) { + if (batch.failed) { + batch.state.textContent = text('webui.masonry.batchError', '生成失败'); + return; + } + const completed = batch.slots.filter((slot) => slot.url && !slot.moderated).length; + const filtered = batch.slots.filter((slot) => slot.moderated).length; + batch.count.textContent = `${completed}/${IMAGE_COUNT}`; + + if (completed >= IMAGE_COUNT) { + batch.state.textContent = text('webui.masonry.statusCompleted', '完成'); + return; + } + if (filtered >= IMAGE_COUNT) { + batch.state.textContent = text('webui.masonry.batchFiltered', '已过滤'); + return; + } + batch.state.textContent = text('webui.masonry.statusGenerating', '生成中…'); + } + + function markBatchFailed(batch) { + if (!batch || batch.completed || batch.failed) return; + batch.failed = true; + batch.state.textContent = text('webui.masonry.batchError', '生成失败'); + } + + function markBatchStopped(batch) { + if (!batch || batch.completed || batch.failed) return; + batch.state.textContent = text('webui.masonry.statusStopped', '已停止'); + } + + function renderSlot(slot) { + slot.tile.classList.remove('is-pending', 'is-ready', 'is-filtered'); + slot.body.replaceChildren(); + + if (slot.url) { + slot.tile.classList.add('is-ready'); + const link = document.createElement('a'); + link.className = 'webui-masonry-tile-link'; + link.href = slot.url; + link.target = '_blank'; + link.rel = 'noopener'; + link.setAttribute('aria-label', text('webui.masonry.openImage', '打开图片')); + link.title = text('webui.masonry.openImage', '打开图片'); + + const img = document.createElement('img'); + img.src = slot.url; + img.alt = `image ${slot.index}`; + img.loading = 'lazy'; + + link.appendChild(img); + slot.body.appendChild(link); + return; + } + + const label = document.createElement('div'); + if (slot.moderated) { + label.className = 'webui-masonry-tile-label'; + label.textContent = text('webui.masonry.batchFiltered', '已过滤'); + slot.tile.classList.add('is-filtered'); + } else { + const progress = Math.max(0, Math.min(99, slot.progress || 0)); + const shell = document.createElement('div'); + shell.className = 'webui-masonry-tile-progress'; + + const value = document.createElement('div'); + value.className = 'webui-masonry-tile-progress-value'; + value.textContent = `${progress}%`; + + const track = document.createElement('div'); + track.className = 'webui-masonry-tile-progress-track'; + + const fill = document.createElement('div'); + fill.className = 'webui-masonry-tile-progress-fill'; + fill.style.width = `${progress}%`; + + track.appendChild(fill); + shell.appendChild(value); + shell.appendChild(track); + slot.tile.classList.add('is-pending'); + slot.body.appendChild(shell); + return; + } + + slot.body.appendChild(label); + } + + function findSlot(batch, payload) { + const imageId = String(payload.image_id || '').trim(); + const order = Number(payload.order); + let slot = null; + + if (imageId) slot = batch.slots.find((item) => item.id === imageId) || null; + if (!slot && Number.isInteger(order) && order >= 0 && order < batch.slots.length) { + const orderedSlot = batch.slots[order] || null; + if (orderedSlot && !orderedSlot.url && !orderedSlot.moderated) { + slot = orderedSlot; + } + } + if (!slot) { + slot = batch.slots.find((item) => !item.url && !item.moderated) || null; + } + if (!slot) { + slot = batch.slots.find((item) => !item.id && !item.url && !item.moderated) || batch.slots[0]; + } + if (slot && imageId) slot.id = imageId; + return slot; + } + + function syncBatch(batch, payload) { + const slot = findSlot(batch, payload); + if (!slot) return; + + if (payload.type === 'progress') { + slot.progress = Number(payload.progress) || slot.progress || 0; + } else if (payload.type === 'image') { + slot.progress = 100; + slot.url = String(payload.url || '').trim(); + slot.moderated = false; + } else if (payload.type === 'moderated') { + slot.progress = 100; + slot.url = ''; + slot.moderated = true; + } + + renderSlot(slot); + updateBatchMeta(batch); + } + + function createStreamState(prompt, aspectRatio, quality, mode) { + return { + prompt, + aspectRatio, + quality, + mode, + keepRunning: true, + userStopped: false, + failed: false, + batchIndex: 0, + currentRunId: '', + currentBatch: null, + nextBatchQueued: false, + }; + } + + async function ensureAccess() { + const stored = await webuiKey.get(); + if (stored && await verifyKey(VERIFY_ENDPOINT, stored)) return true; + if (stored) webuiKey.clear(); + if (await verifyKey(VERIFY_ENDPOINT, '')) return true; + location.href = '/webui/login'; + return false; + } + + async function connectSocket() { + if (!streamState?.keepRunning) return; + if (activeSocket && (activeSocket.readyState === WebSocket.OPEN || activeSocket.readyState === WebSocket.CONNECTING)) { + return; + } + + const token = await webuiKey.get(); + const wsUrl = buildWebSocketUrl(IMAGINE_WS_ENDPOINT, token ? { access_token: token } : {}); + const socket = new WebSocket(wsUrl); + activeSocket = socket; + + socket.addEventListener('open', () => { + if (activeSocket !== socket || !streamState?.keepRunning) return; + scheduleNextBatch(); + }); + + socket.addEventListener('message', (event) => { + const state = streamState; + if (!state) return; + + let payload; + try { + payload = JSON.parse(String(event.data || '{}')); + } catch { + return; + } + if (!payload || typeof payload !== 'object') return; + + if (payload.run_id && !state.currentRunId) state.currentRunId = String(payload.run_id); + if (state.currentRunId && payload.run_id && String(payload.run_id) !== state.currentRunId) return; + + const batch = state.currentBatch; + if (payload.type === 'status') { + if (payload.status === 'running') { + setStatus(`${text('webui.masonry.statusGenerating', '生成中…')} · ${formatRoundLabel(state.batchIndex)}`, 'running'); + } else if (payload.status === 'completed') { + if (batch) { + batch.completed = true; + batch.state.textContent = text('webui.masonry.statusCompleted', '完成'); + updateBatchMeta(batch); + } + state.currentRunId = ''; + if (state.keepRunning && !state.userStopped && state.mode === 'continuous') { + scheduleNextBatch(); + } else { + state.keepRunning = false; + setStatus(text('webui.masonry.statusCompleted', '完成'), 'completed'); + try { + socket.close(1000, 'completed'); + } catch {} + } + } else if (payload.status === 'stopped') { + state.userStopped = true; + state.keepRunning = false; + markBatchStopped(batch); + setStatus(text('webui.masonry.statusStopped', '已停止'), 'stopped'); + } + return; + } + + if (!batch) return; + + if (payload.type === 'progress' || payload.type === 'image' || payload.type === 'moderated') { + syncBatch(batch, payload); + const ready = batch.slots.filter((slot) => slot.url && !slot.moderated).length; + setStatus(`${text('webui.masonry.statusGenerating', '生成中…')} ${ready}/${IMAGE_COUNT} · ${formatRoundLabel(batch.round)}`, 'running'); + return; + } + + if (payload.type === 'error') { + state.failed = true; + state.keepRunning = false; + markBatchFailed(batch); + setStatus(text('webui.masonry.statusFailed', '失败'), 'failed'); + toast(payload.message || text('webui.masonry.errors.requestFailed', '请求失败'), 'error'); + try { + socket.close(1011, 'error'); + } catch {} + } + }); + + socket.addEventListener('error', () => { + if (streamState?.keepRunning && !streamState.userStopped) { + setStatus(text('webui.masonry.statusConnecting', '连接中…'), 'connecting'); + } + }); + + socket.addEventListener('close', () => { + const state = streamState; + if (activeSocket === socket) activeSocket = null; + if (!state) { + setSending(false); + return; + } + + if (state.userStopped) { + markBatchStopped(state.currentBatch); + setSending(false); + streamState = null; + setStatus(text('webui.masonry.statusStopped', '已停止'), 'stopped'); + promptInput?.focus(); + return; + } + + if (state.failed) { + markBatchFailed(state.currentBatch); + setSending(false); + streamState = null; + setStatus(text('webui.masonry.statusFailed', '失败'), 'failed'); + promptInput?.focus(); + return; + } + + if (state.keepRunning) { + if (state.currentBatch && !state.currentBatch.completed) { + markBatchFailed(state.currentBatch); + } + setStatus(text('webui.masonry.statusConnecting', '连接中…'), 'connecting'); + window.setTimeout(() => { + if (streamState === state && state.keepRunning) { + void connectSocket(); + } + }, RECONNECT_DELAY_MS); + return; + } + + setSending(false); + streamState = null; + promptInput?.focus(); + }); + } + + function scheduleNextBatch() { + const state = streamState; + if (!state?.keepRunning || state.userStopped || state.failed || state.nextBatchQueued) return; + state.nextBatchQueued = true; + + window.setTimeout(() => { + const current = streamState; + if (current !== state) return; + state.nextBatchQueued = false; + if (!state.keepRunning || state.userStopped || state.failed) return; + if (!activeSocket || activeSocket.readyState !== WebSocket.OPEN) { + void connectSocket(); + return; + } + + state.batchIndex += 1; + state.currentRunId = ''; + state.currentBatch = createBatch(state.prompt, state.aspectRatio, state.quality, state.batchIndex); + setStatus(`${text('webui.masonry.statusGenerating', '生成中…')} · ${formatRoundLabel(state.batchIndex)}`, 'running'); + + try { + activeSocket.send(JSON.stringify({ + type: 'start', + prompt: state.prompt, + aspect_ratio: state.aspectRatio, + quality: state.quality, + count: IMAGE_COUNT, + })); + } catch { + void connectSocket(); + } + }, 0); + } + + function stopGeneration({ silent = false } = {}) { + if (streamState) { + streamState.keepRunning = false; + streamState.userStopped = true; + streamState.nextBatchQueued = false; + } + const socket = activeSocket; + if (socket) socket.__userStopped = true; + activeSocket = null; + if (socket) { + try { + socket.send(JSON.stringify({ type: 'stop' })); + } catch {} + try { + socket.close(1000, 'stopped'); + } catch {} + } + setSending(false); + setStatus(text('webui.masonry.statusStopped', '已停止'), 'stopped'); + markBatchStopped(streamState?.currentBatch); + streamState = null; + if (!silent) toast(text('webui.masonry.statusStopped', '已停止'), 'info'); + } + + async function startGeneration() { + if (sending) { + stopGeneration({ silent: true }); + return; + } + + const prompt = String(promptInput?.value || '').trim(); + if (!prompt) { + toast(text('webui.masonry.errors.enterPrompt', '请输入提示词'), 'error'); + return; + } + + const aspectRatio = aspectRatioSelect?.value || '2:3'; + const quality = readToggleValue(qualityToggle, 'speed') === 'quality' ? 'quality' : 'speed'; + const mode = readToggleValue(modeToggle, 'single') === 'continuous' ? 'continuous' : 'single'; + streamState = createStreamState(prompt, aspectRatio, quality, mode); + setSending(true); + setStatus(text('webui.masonry.statusConnecting', '连接中…'), 'connecting'); + promptInput.value = ''; + resizePromptInput(); + await connectSocket(); + } + + async function boot() { + await renderWebuiHeader?.(); + window.I18n?.apply?.(document); + if (!await ensureAccess()) return; + syncAspectRatioIndicator(); + setToggleValue(qualityToggle, 'speed'); + setToggleValue(modeToggle, 'single'); + setSending(false); + setEmptyState(); + setStatus(text('webui.masonry.statusReady', '就绪'), 'idle'); + resizePromptInput(); + promptInput?.focus(); + } + + sendBtn?.addEventListener('click', () => { + void startGeneration(); + }); + + qualityToggle?.addEventListener('click', (event) => { + const button = event.target instanceof Element ? event.target.closest('.webui-masonry-toggle-btn') : null; + if (!(button instanceof HTMLButtonElement) || button.disabled) return; + setToggleValue(qualityToggle, button.dataset.value || 'speed'); + }); + + modeToggle?.addEventListener('click', (event) => { + const button = event.target instanceof Element ? event.target.closest('.webui-masonry-toggle-btn') : null; + if (!(button instanceof HTMLButtonElement) || button.disabled) return; + setToggleValue(modeToggle, button.dataset.value || 'single'); + }); + + promptInput?.addEventListener('input', resizePromptInput); + aspectRatioSelect?.addEventListener('change', syncAspectRatioIndicator); + promptInput?.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + void startGeneration(); + } + }); + + window.addEventListener('beforeunload', () => { + if (!activeSocket) return; + try { + activeSocket.close(1000, 'unload'); + } catch {} + activeSocket = null; + }); + window.addEventListener('resize', syncAllBatchGrids); + + boot().catch((error) => { + console.error('webui masonry boot failed', error); + toast(text('webui.masonry.errors.initFailed', '瀑布流页面初始化失败'), 'error'); + setStatus(text('webui.masonry.statusFailed', '失败'), 'failed'); + }); +})(); diff --git a/app/statics/webui/chat.html b/app/statics/webui/chat.html new file mode 100644 index 00000000..d317faf4 --- /dev/null +++ b/app/statics/webui/chat.html @@ -0,0 +1,93 @@ + + + + + + Grok2API - WebChat + + + + + + +
    +
    + + +
    +
    +
    +
    +
    +
    +
    Web Chat
    +
    输入一条消息开始新的会话。
    +
    +
    +
    +
    + +
    + +
    + + + +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + + + + diff --git a/app/statics/webui/chatkit.html b/app/statics/webui/chatkit.html new file mode 100644 index 00000000..85acf0ba --- /dev/null +++ b/app/statics/webui/chatkit.html @@ -0,0 +1,123 @@ + + + + + + Grok2API - ChatKit + + + + + + + +
    +
    + +
    + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    未连接
    +
    + +
    +
    Grok Voice
    +
    准备好后点击开始,授权麦克风即可进入语音会话。
    +
    + +
    + + + +
    + +
    +
    +
    +
    +
    + + + + + + + + diff --git a/app/statics/webui/header.html b/app/statics/webui/header.html new file mode 100644 index 00000000..1545126f --- /dev/null +++ b/app/statics/webui/header.html @@ -0,0 +1,59 @@ +
    +
    + + +
    +
    + + +
    + +
    +
    +
    diff --git a/app/statics/webui/login.html b/app/statics/webui/login.html index 2221166c..10883ebd 100644 --- a/app/statics/webui/login.html +++ b/app/statics/webui/login.html @@ -24,9 +24,6 @@
    -
    diff --git a/app/statics/webui/masonry.html b/app/statics/webui/masonry.html new file mode 100644 index 00000000..b24df68f --- /dev/null +++ b/app/statics/webui/masonry.html @@ -0,0 +1,79 @@ + + + + + + Grok2API - Masonry + + + + + + +
    + +
    +
    +
    +

    Masonry

    +
    + +
    +
    +
    +
    从一句提示词开始
    +
    每轮固定生成 6 张图,并持续出图直到你停止。
    +
    +
    +
    + +
    +
    + +
    +
    +
    + + +
    +
    + + +
    + +
    +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + diff --git a/config.defaults.toml b/config.defaults.toml index c8c98d53..9b89b637 100644 --- a/config.defaults.toml +++ b/config.defaults.toml @@ -1,217 +1,143 @@ -# ==================== 应用设置 ==================== +# ==================== 访问控制 ==================== [app] -# 应用访问地址(用于生成文件链接) -app_url = "" -# 后台管理密码 +# 管理后台密码 app_key = "grok2api" -# API 调用密钥(可选,支持列表) +# 应用访问地址 +app_url = "" +# API 调用密钥 api_key = "" -# 是否启用 function 功能玩法 +# 启用 WebUI function_enabled = false -# function 调用密钥(可选) +# WebUI 访问密码 function_key = "" -# 生成图片的格式(url 或 base64) -image_format = "url" -# 生成视频的格式(html 或 url) -video_format = "html" -# 是否启用临时对话模式 + + +# ==================== 应用功能 ==================== +[features] +# 是否启用临时对话 temporary = true -# 是否禁用 Grok 记忆功能 -disable_memory = true -# 是否默认启用流式响应 +# 是否启用会话记忆 +memory = false +# 是否启用流式响应 stream = true -# 是否默认启用思维链输出 +# 是否输出思考过程 thinking = true # 是否动态生成 Statsig 指纹 dynamic_statsig = true -# 自定义指令 +# 是否允许生成 NSFW 图片 +enable_nsfw = true +# 全局附加指令 custom_instruction = "" -# 过滤的特殊标签列表 -filter_tags = ["xaiartifact","xai:tool_usage_card","grok:render"] + +# 图片返回格式 +# grok_url — 直接返回 Grok CDN URL +# local_url — 下载后存本地,返回本地代理 URL +# grok_md — Markdown 内嵌 Grok CDN URL +# local_md — Markdown 内嵌本地代理 URL +# base64 — Markdown 内嵌 Base64 Data URI +image_format = "grok_url" + +# 视频返回格式 +# grok_url — 直接返回 Grok CDN URL +# local_url — 下载后存本地,返回本地代理 URL +# grok_html — HTML