mirror of
https://github.com/anomalyco/opencode.git
synced 2026-07-17 12:56:41 +02:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 75c507f769 | |||
| 80e5fb11c2 | |||
| bc6c4c72ab | |||
| 4db2746e31 | |||
| 71e90073d2 | |||
| ea27114eb9 | |||
| 64d67f2134 | |||
| a99337fbe1 | |||
| b20b569b0e | |||
| c449d3dc74 | |||
| e4eb98b991 | |||
| b32f071502 | |||
| 512e34af83 | |||
| 7051796c38 | |||
| b67f5d741f | |||
| eec0843ce4 | |||
| 55baa16fbc | |||
| c79a9634d3 | |||
| 8dd6448c90 | |||
| 18b9cec50d | |||
| 2932a7a35d | |||
| 922b2e10eb | |||
| a2ee437a0e | |||
| 6618e2bce2 | |||
| cb15b3ad84 | |||
| ee16f08ffa | |||
| 9790a61f96 | |||
| 2339aacbf2 | |||
| 2d348da504 | |||
| cbd2620c46 | |||
| 3bd304796b | |||
| dac81cdb68 | |||
| 2c3bcf3e41 | |||
| d9d43d8519 | |||
| bcc69f0afb | |||
| e53563f402 | |||
| 7e4b02f1bf | |||
| 996928b32a | |||
| c032e821bc | |||
| 6f160bb48f | |||
| ebb672ac39 |
@@ -14,3 +14,4 @@ rekram1-node
|
||||
thdxr
|
||||
simonklee
|
||||
vimtor
|
||||
starptech
|
||||
|
||||
@@ -4,8 +4,8 @@ import { tool } from "@opencode-ai/plugin"
|
||||
const TEAM = {
|
||||
tui: ["kommander", "simonklee"],
|
||||
desktop_web: ["Hona", "Brendonovich"],
|
||||
core: ["jlongster", "rekram1-node", "nexxeln", "kitlangton"],
|
||||
inference: ["fwang", "MrMushrooooom"],
|
||||
core: ["jlongster", "rekram1-node", "nexxeln", "kitlangton", "starptech"],
|
||||
inference: ["fwang", "MrMushrooooom", "starptech"],
|
||||
windows: ["Hona"],
|
||||
} as const
|
||||
|
||||
|
||||
@@ -422,7 +422,13 @@ function createGlobalSync() {
|
||||
|
||||
const updateConfigMutation = useMutation(() => ({
|
||||
mutationFn: (config: Config) => globalSDK.client.global.config.update({ config }),
|
||||
onSuccess: () => bootstrap.refetch(),
|
||||
onSuccess: () => {
|
||||
bootstrap.refetch()
|
||||
// Invalidate all provider queries so newly configured custom providers
|
||||
// appear immediately in the available provider list across all directories.
|
||||
queryClient.invalidateQueries({ queryKey: [null, "providers"] })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[1] === "providers" })
|
||||
},
|
||||
}))
|
||||
|
||||
return {
|
||||
|
||||
@@ -18,6 +18,7 @@ export type Locale =
|
||||
| "ja"
|
||||
| "pl"
|
||||
| "ru"
|
||||
| "uk"
|
||||
| "ar"
|
||||
| "no"
|
||||
| "br"
|
||||
@@ -45,6 +46,7 @@ const LOCALES: readonly Locale[] = [
|
||||
"ja",
|
||||
"pl",
|
||||
"ru",
|
||||
"uk",
|
||||
"bs",
|
||||
"ar",
|
||||
"no",
|
||||
@@ -65,6 +67,7 @@ const INTL: Record<Locale, string> = {
|
||||
ja: "ja",
|
||||
pl: "pl",
|
||||
ru: "ru",
|
||||
uk: "uk",
|
||||
ar: "ar",
|
||||
no: "nb-NO",
|
||||
br: "pt-BR",
|
||||
@@ -85,6 +88,7 @@ const LABEL_KEY: Record<Locale, keyof Dictionary> = {
|
||||
ja: "language.ja",
|
||||
pl: "language.pl",
|
||||
ru: "language.ru",
|
||||
uk: "language.uk",
|
||||
ar: "language.ar",
|
||||
no: "language.no",
|
||||
br: "language.br",
|
||||
@@ -110,6 +114,7 @@ const loaders: Record<Exclude<Locale, "en">, () => Promise<Dictionary>> = {
|
||||
ja: () => merge(import("@/i18n/ja"), import("@opencode-ai/ui/i18n/ja")),
|
||||
pl: () => merge(import("@/i18n/pl"), import("@opencode-ai/ui/i18n/pl")),
|
||||
ru: () => merge(import("@/i18n/ru"), import("@opencode-ai/ui/i18n/ru")),
|
||||
uk: () => merge(import("@/i18n/uk"), import("@opencode-ai/ui/i18n/uk")),
|
||||
ar: () => merge(import("@/i18n/ar"), import("@opencode-ai/ui/i18n/ar")),
|
||||
no: () => merge(import("@/i18n/no"), import("@opencode-ai/ui/i18n/no")),
|
||||
br: () => merge(import("@/i18n/br"), import("@opencode-ai/ui/i18n/br")),
|
||||
@@ -145,6 +150,7 @@ const localeMatchers: Array<{ locale: Locale; match: (language: string) => boole
|
||||
{ locale: "ja", match: (language) => language.startsWith("ja") },
|
||||
{ locale: "pl", match: (language) => language.startsWith("pl") },
|
||||
{ locale: "ru", match: (language) => language.startsWith("ru") },
|
||||
{ locale: "uk", match: (language) => language.startsWith("uk") },
|
||||
{ locale: "ar", match: (language) => language.startsWith("ar") },
|
||||
{
|
||||
locale: "no",
|
||||
|
||||
@@ -416,6 +416,7 @@ export const dict = {
|
||||
"language.no": "Norsk",
|
||||
"language.br": "Português (Brasil)",
|
||||
"language.bs": "Bosanski",
|
||||
"language.uk": "Українська",
|
||||
"language.th": "ไทย",
|
||||
"language.tr": "Türkçe",
|
||||
|
||||
|
||||
@@ -12,12 +12,13 @@ import { dict as ko } from "./ko"
|
||||
import { dict as no } from "./no"
|
||||
import { dict as pl } from "./pl"
|
||||
import { dict as ru } from "./ru"
|
||||
import { dict as uk } from "./uk"
|
||||
import { dict as th } from "./th"
|
||||
import { dict as zh } from "./zh"
|
||||
import { dict as zht } from "./zht"
|
||||
import { dict as tr } from "./tr"
|
||||
|
||||
const locales = [ar, br, bs, da, de, es, fr, ja, ko, no, pl, ru, th, tr, zh, zht]
|
||||
const locales = [ar, br, bs, da, de, es, fr, ja, ko, no, pl, ru, uk, th, tr, zh, zht]
|
||||
const keys = ["command.session.previous.unseen", "command.session.next.unseen"] as const
|
||||
|
||||
describe("i18n parity", () => {
|
||||
|
||||
@@ -0,0 +1,970 @@
|
||||
export const dict = {
|
||||
"command.category.suggested": "Рекомендовані",
|
||||
"command.category.view": "Вигляд",
|
||||
"command.category.project": "Проєкт",
|
||||
"command.category.provider": "Провайдер",
|
||||
"command.category.server": "Сервер",
|
||||
"command.category.session": "Сесія",
|
||||
"command.category.theme": "Тема",
|
||||
"command.category.language": "Мова",
|
||||
"command.category.file": "Файл",
|
||||
"command.category.context": "Контекст",
|
||||
"command.category.terminal": "Термінал",
|
||||
"command.category.model": "Модель",
|
||||
"command.category.mcp": "MCP",
|
||||
"command.category.agent": "Агент",
|
||||
"command.category.permissions": "Дозволи",
|
||||
"command.category.workspace": "Робоча область",
|
||||
"command.category.settings": "Налаштування",
|
||||
|
||||
"theme.scheme.system": "Системна",
|
||||
"theme.scheme.light": "Світла",
|
||||
"theme.scheme.dark": "Темна",
|
||||
|
||||
"command.sidebar.toggle": "Перемкнути бічну панель",
|
||||
"command.project.open": "Відкрити проєкт",
|
||||
"command.project.previous": "Попередній проєкт",
|
||||
"command.project.next": "Наступний проєкт",
|
||||
"command.project.index": "Перемкнути на проєкт {{index}}",
|
||||
"command.provider.connect": "Підключити провайдера",
|
||||
"command.server.switch": "Перемкнути сервер",
|
||||
"command.settings.open": "Відкрити налаштування",
|
||||
"command.session.previous": "Попередня сесія",
|
||||
"command.session.next": "Наступна сесія",
|
||||
"command.session.previous.unseen": "Попередня непрочитана сесія",
|
||||
"command.session.next.unseen": "Наступна непрочитана сесія",
|
||||
"command.session.archive": "Архівувати сесію",
|
||||
|
||||
"command.palette": "Палітра команд",
|
||||
|
||||
"command.theme.cycle": "Перемкнути тему",
|
||||
"command.theme.set": "Використати тему: {{theme}}",
|
||||
"command.theme.scheme.cycle": "Перемкнути кольорову схему",
|
||||
"command.theme.scheme.set": "Використати кольорову схему: {{scheme}}",
|
||||
|
||||
"command.language.cycle": "Перемкнути мову",
|
||||
"command.language.set": "Використати мову: {{language}}",
|
||||
|
||||
"command.session.new": "Нова сесія",
|
||||
"command.file.open": "Відкрити файл",
|
||||
"command.tab.close": "Закрити вкладку",
|
||||
"command.context.addSelection": "Додати виділення до контексту",
|
||||
"command.context.addSelection.description": "Додати вибрані рядки з поточного файлу",
|
||||
"command.input.focus": "Фокус на полі введення",
|
||||
"command.terminal.toggle": "Перемкнути термінал",
|
||||
"command.fileTree.toggle": "Перемкнути дерево файлів",
|
||||
"command.review.toggle": "Перемкнути огляд",
|
||||
"command.terminal.new": "Новий термінал",
|
||||
"command.terminal.new.description": "Створити нову вкладку термінала",
|
||||
"command.steps.toggle": "Перемкнути кроки",
|
||||
"command.steps.toggle.description": "Показати або приховати кроки для поточного повідомлення",
|
||||
"command.message.previous": "Попереднє повідомлення",
|
||||
"command.message.previous.description": "Перейти до попереднього повідомлення користувача",
|
||||
"command.message.next": "Наступне повідомлення",
|
||||
"command.message.next.description": "Перейти до наступного повідомлення користувача",
|
||||
"command.model.choose": "Вибрати модель",
|
||||
"command.model.choose.description": "Вибрати іншу модель",
|
||||
"command.mcp.toggle": "Перемкнути MCP",
|
||||
"command.mcp.toggle.description": "Перемкнути MCP",
|
||||
"command.agent.cycle": "Перемкнути агента",
|
||||
"command.agent.cycle.description": "Перемкнути на наступного агента",
|
||||
"command.agent.cycle.reverse": "Перемкнути агента в зворотному напрямку",
|
||||
"command.agent.cycle.reverse.description": "Перемкнути на попереднього агента",
|
||||
"command.model.variant.cycle": "Перемкнути рівень мислення",
|
||||
"command.model.variant.cycle.description": "Перемкнути на наступний рівень зусилля",
|
||||
"command.prompt.mode.shell": "Команда",
|
||||
"command.prompt.mode.normal": "Запит",
|
||||
"command.permissions.autoaccept.enable": "Автоматично приймати дозволи",
|
||||
"command.permissions.autoaccept.disable": "Зупинити автоматичне прийняття дозволів",
|
||||
"command.workspace.toggle": "Перемкнути робочі області",
|
||||
"command.workspace.toggle.description": "Увімкнути або вимкнути декілька робочих областей на бічній панелі",
|
||||
"command.session.undo": "Скасувати",
|
||||
"command.session.undo.description": "Скасувати останнє повідомлення",
|
||||
"command.session.redo": "Повторити",
|
||||
"command.session.redo.description": "Повторити останнє скасоване повідомлення",
|
||||
"command.session.compact": "Стиснути сесію",
|
||||
"command.session.compact.description": "Підсумувати сесію, щоб зменшити розмір контексту",
|
||||
"command.session.fork": "Відгалузити від повідомлення",
|
||||
"command.session.fork.description": "Створити нову сесію з попереднього повідомлення",
|
||||
"command.session.share": "Поділитися сесією",
|
||||
"command.session.share.description": "Поділитися цією сесією та скопіювати URL у буфер обміну",
|
||||
"command.session.unshare": "Припинити поширення сесії",
|
||||
"command.session.unshare.description": "Припинити поширення цієї сесії",
|
||||
|
||||
"palette.search.placeholder": "Пошук файлів, команд і сесій",
|
||||
"palette.empty": "Результатів не знайдено",
|
||||
"palette.group.commands": "Команди",
|
||||
"palette.group.files": "Файли",
|
||||
|
||||
"dialog.provider.search.placeholder": "Пошук провайдерів",
|
||||
"dialog.provider.empty": "Провайдерів не знайдено",
|
||||
"dialog.provider.group.popular": "Популярні",
|
||||
"dialog.provider.group.other": "Інші",
|
||||
"dialog.provider.tag.recommended": "Рекомендовані",
|
||||
"dialog.provider.opencode.note": "Відібрані моделі, включаючи Claude, GPT, Gemini та інші",
|
||||
"dialog.provider.opencode.tagline": "Надійні оптимізовані моделі",
|
||||
"dialog.provider.opencodeGo.tagline": "Недорога підписка для всіх",
|
||||
"dialog.provider.anthropic.note": "Прямий доступ до моделей Claude, включаючи Pro та Max",
|
||||
"dialog.provider.copilot.note": "Моделі AI для допомоги в кодуванні через GitHub Copilot",
|
||||
"dialog.provider.openai.note": "Моделі GPT для швидких і універсальних завдань AI",
|
||||
"dialog.provider.google.note": "Моделі Gemini для швидких структурованих відповідей",
|
||||
"dialog.provider.openrouter.note": "Доступ до всіх підтримуваних моделей від одного провайдера",
|
||||
"dialog.provider.vercel.note": "Уніфікований доступ до моделей AI з інтелектуальною маршрутизацією",
|
||||
|
||||
"dialog.model.select.title": "Вибрати модель",
|
||||
"dialog.model.search.placeholder": "Пошук моделей",
|
||||
"dialog.model.empty": "Немає результатів моделей",
|
||||
"dialog.model.manage": "Керувати моделями",
|
||||
"dialog.model.manage.description": "Налаштуйте, які моделі відображатимуться у виборі моделей.",
|
||||
"dialog.model.manage.provider.toggle": "Перемкнути всі моделі {{provider}}",
|
||||
|
||||
"dialog.model.unpaid.freeModels.title": "Безкоштовні моделі від OpenCode",
|
||||
"dialog.model.unpaid.addMore.title": "Додати більше моделей від популярних провайдерів",
|
||||
|
||||
"dialog.provider.viewAll": "Показати більше провайдерів",
|
||||
|
||||
"provider.connect.title": "Підключити {{provider}}",
|
||||
"provider.connect.title.anthropicProMax": "Увійти з Claude Pro/Max",
|
||||
"provider.connect.selectMethod": "Виберіть спосіб входу для {{provider}}.",
|
||||
"provider.connect.method.apiKey": "Ключ API",
|
||||
"provider.connect.status.inProgress": "Авторизація виконується...",
|
||||
"provider.connect.status.waiting": "Очікування авторизації...",
|
||||
"provider.connect.status.failed": "Авторизація не вдалася: {{error}}",
|
||||
"provider.connect.apiKey.description":
|
||||
"Введіть ключ API {{provider}}, щоб підключити обліковий запис і використовувати моделі {{provider}} у OpenCode.",
|
||||
"provider.connect.apiKey.label": "Ключ API {{provider}}",
|
||||
"provider.connect.apiKey.placeholder": "Ключ API",
|
||||
"provider.connect.apiKey.required": "Ключ API обов'язковий",
|
||||
"provider.connect.opencodeZen.line1":
|
||||
"OpenCode Zen надає доступ до відібраного набору надійних оптимізованих моделей для агентів кодування.",
|
||||
"provider.connect.opencodeZen.line2":
|
||||
"З одним ключем API ви отримаєте доступ до таких моделей, як Claude, GPT, Gemini, GLM та інших.",
|
||||
"provider.connect.opencodeZen.visit.prefix": "Відвідайте ",
|
||||
"provider.connect.opencodeZen.visit.link": "opencode.ai/zen",
|
||||
"provider.connect.opencodeZen.visit.suffix": ", щоб отримати ключ API.",
|
||||
"provider.connect.oauth.code.visit.prefix": "Відвідайте ",
|
||||
"provider.connect.oauth.code.visit.link": "це посилання",
|
||||
"provider.connect.oauth.code.visit.suffix":
|
||||
", щоб отримати код авторизації, підключити обліковий запис і використовувати моделі {{provider}} у OpenCode.",
|
||||
"provider.connect.oauth.code.label": "Код авторизації {{method}}",
|
||||
"provider.connect.oauth.code.placeholder": "Код авторизації",
|
||||
"provider.connect.oauth.code.required": "Код авторизації обов'язковий",
|
||||
"provider.connect.oauth.code.invalid": "Недійсний код авторизації",
|
||||
"provider.connect.oauth.auto.visit.prefix": "Відвідайте ",
|
||||
"provider.connect.oauth.auto.visit.link": "це посилання",
|
||||
"provider.connect.oauth.auto.visit.suffix":
|
||||
" і введіть код нижче, щоб підключити обліковий запис і використовувати моделі {{provider}} у OpenCode.",
|
||||
"provider.connect.oauth.auto.confirmationCode": "Код підтвердження",
|
||||
"provider.connect.toast.connected.title": "{{provider}} підключено",
|
||||
"provider.connect.toast.connected.description": "Моделі {{provider}} тепер доступні для використання.",
|
||||
|
||||
"provider.custom.title": "Користувацький провайдер",
|
||||
"provider.custom.description.prefix": "Налаштуйте провайдера, сумісного з OpenAI. Перегляньте ",
|
||||
"provider.custom.description.link": "документацію з налаштування провайдера",
|
||||
"provider.custom.description.suffix": ".",
|
||||
"provider.custom.field.providerID.label": "ID провайдера",
|
||||
"provider.custom.field.providerID.placeholder": "myprovider",
|
||||
"provider.custom.field.providerID.description": "Малі літери, цифри, дефіси або підкреслення",
|
||||
"provider.custom.field.name.label": "Відображувана назва",
|
||||
"provider.custom.field.name.placeholder": "Мій AI Провайдер",
|
||||
"provider.custom.field.baseURL.label": "Базовий URL",
|
||||
"provider.custom.field.baseURL.placeholder": "https://api.myprovider.com/v1",
|
||||
"provider.custom.field.apiKey.label": "Ключ API",
|
||||
"provider.custom.field.apiKey.placeholder": "Ключ API",
|
||||
"provider.custom.field.apiKey.description":
|
||||
"Необов'язково. Залиште порожнім, якщо ви керуєте авторизацією через заголовки.",
|
||||
"provider.custom.models.label": "Моделі",
|
||||
"provider.custom.models.id.label": "ID",
|
||||
"provider.custom.models.id.placeholder": "model-id",
|
||||
"provider.custom.models.name.label": "Назва",
|
||||
"provider.custom.models.name.placeholder": "Відображувана назва",
|
||||
"provider.custom.models.remove": "Видалити модель",
|
||||
"provider.custom.models.add": "Додати модель",
|
||||
"provider.custom.headers.label": "Заголовки (необов'язково)",
|
||||
"provider.custom.headers.key.label": "Заголовок",
|
||||
"provider.custom.headers.key.placeholder": "Назва-Заголовка",
|
||||
"provider.custom.headers.value.label": "Значення",
|
||||
"provider.custom.headers.value.placeholder": "значення",
|
||||
"provider.custom.headers.remove": "Видалити заголовок",
|
||||
"provider.custom.headers.add": "Додати заголовок",
|
||||
"provider.custom.error.providerID.required": "ID провайдера обов'язкове",
|
||||
"provider.custom.error.providerID.format": "Використовуйте малі літери, цифри, дефіси або підкреслення",
|
||||
"provider.custom.error.providerID.exists": "ID провайдера вже існує",
|
||||
"provider.custom.error.name.required": "Відображувана назва обов'язкова",
|
||||
"provider.custom.error.baseURL.required": "Базовий URL обов'язковий",
|
||||
"provider.custom.error.baseURL.format": "Має починатися з http:// або https://",
|
||||
"provider.custom.error.required": "Обов'язково",
|
||||
"provider.custom.error.duplicate": "Дублікат",
|
||||
|
||||
"provider.disconnect.toast.disconnected.title": "{{provider}} відключено",
|
||||
"provider.disconnect.toast.disconnected.description": "Моделі {{provider}} більше недоступні.",
|
||||
|
||||
"model.tag.free": "Безкоштовно",
|
||||
"model.tag.latest": "Остання",
|
||||
"model.provider.anthropic": "Anthropic",
|
||||
"model.provider.openai": "OpenAI",
|
||||
"model.provider.google": "Google",
|
||||
"model.provider.xai": "xAI",
|
||||
"model.provider.meta": "Meta",
|
||||
"model.input.text": "текст",
|
||||
"model.input.image": "зображення",
|
||||
"model.input.audio": "аудіо",
|
||||
"model.input.video": "відео",
|
||||
"model.input.pdf": "pdf",
|
||||
"model.tooltip.allows": "Дозволяє: {{inputs}}",
|
||||
"model.tooltip.reasoning.allowed": "Підтримує мислення",
|
||||
"model.tooltip.reasoning.none": "Без мислення",
|
||||
"model.tooltip.context": "Ліміт контексту {{limit}}",
|
||||
|
||||
"common.search.placeholder": "Пошук",
|
||||
"common.goBack": "Назад",
|
||||
"common.goForward": "Вперед",
|
||||
"common.loading": "Завантаження",
|
||||
"common.loading.ellipsis": "...",
|
||||
"common.cancel": "Скасувати",
|
||||
"common.open": "Відкрити",
|
||||
"common.connect": "Підключити",
|
||||
"common.disconnect": "Відключити",
|
||||
"common.continue": "Продовжити",
|
||||
"common.submit": "Надіслати",
|
||||
"common.save": "Зберегти",
|
||||
"common.saving": "Збереження...",
|
||||
"common.default": "За замовчуванням",
|
||||
"common.attachment": "вкладення",
|
||||
|
||||
"prompt.placeholder.shell": "Введіть команду термінала... {{example}}",
|
||||
"prompt.placeholder.normal": 'Запитайте що завгодно... "{{example}}"',
|
||||
"prompt.placeholder.simple": "Запитайте що завгодно...",
|
||||
"prompt.placeholder.summarizeComments": "Підсумувати коментарі…",
|
||||
"prompt.placeholder.summarizeComment": "Підсумувати коментар…",
|
||||
"prompt.mode.shell": "Команда",
|
||||
"prompt.mode.normal": "Запит",
|
||||
"prompt.mode.shell.exit": "esc для виходу",
|
||||
"session.child.promptDisabled": "Сесії підагентів не можна надсилати запити.",
|
||||
"session.child.backToParent": "Назад до основної сесії.",
|
||||
|
||||
"prompt.example.1": "Виправити TODO у коді",
|
||||
"prompt.example.2": "Який технологічний стек цього проєкту?",
|
||||
"prompt.example.3": "Виправити зламані тести",
|
||||
"prompt.example.4": "Пояснити, як працює автентифікація",
|
||||
"prompt.example.5": "Знайти та виправити вразливості безпеки",
|
||||
"prompt.example.6": "Додати модульні тести для сервісу користувача",
|
||||
"prompt.example.7": "Рефакторити цю функцію, щоб зробити її більш читабельною",
|
||||
"prompt.example.8": "Що означає ця помилка?",
|
||||
"prompt.example.9": "Допоможіть мені налагодити цю проблему",
|
||||
"prompt.example.10": "Згенерувати документацію API",
|
||||
"prompt.example.11": "Оптимізувати запити до бази даних",
|
||||
"prompt.example.12": "Додати валідацію введення",
|
||||
"prompt.example.13": "Створити новий компонент для...",
|
||||
"prompt.example.14": "Як розгорнути цей проєкт?",
|
||||
"prompt.example.15": "Перевірити мій код на відповідність найкращим практикам",
|
||||
"prompt.example.16": "Додати обробку помилок до цієї функції",
|
||||
"prompt.example.17": "Пояснити цей регулярний вираз",
|
||||
"prompt.example.18": "Конвертувати це в TypeScript",
|
||||
"prompt.example.19": "Додати логування по всьому коду",
|
||||
"prompt.example.20": "Які залежності застарілі?",
|
||||
"prompt.example.21": "Допоможіть написати скрипт міграції",
|
||||
"prompt.example.22": "Реалізувати кешування для цього ендпоінта",
|
||||
"prompt.example.23": "Додати посторінкову навігацію до цього списку",
|
||||
"prompt.example.24": "Створити команду CLI для...",
|
||||
"prompt.example.25": "Як тут працюють змінні середовища?",
|
||||
|
||||
"prompt.popover.emptyResults": "Немає відповідних результатів",
|
||||
"prompt.popover.emptyCommands": "Немає відповідних команд",
|
||||
"prompt.dropzone.label": "Перетягніть сюди зображення, PDF або текстові файли",
|
||||
"prompt.dropzone.file.label": "Перетягніть, щоб @згадати файл",
|
||||
"prompt.slash.badge.custom": "користувацький",
|
||||
"prompt.slash.badge.skill": "навичка",
|
||||
"prompt.slash.badge.mcp": "mcp",
|
||||
"prompt.context.active": "активний",
|
||||
"prompt.context.includeActiveFile": "Включити активний файл",
|
||||
"prompt.context.removeActiveFile": "Видалити активний файл з контексту",
|
||||
"prompt.context.removeFile": "Видалити файл з контексту",
|
||||
"prompt.action.attachFile": "Додати файли",
|
||||
"prompt.attachment.remove": "Видалити вкладення",
|
||||
"prompt.action.send": "Надіслати",
|
||||
"prompt.action.stop": "Зупинити",
|
||||
|
||||
"prompt.toast.pasteUnsupported.title": "Непідтримуване вкладення",
|
||||
"prompt.toast.pasteUnsupported.description": "Сюди можна прикріплювати лише зображення, PDF або текстові файли.",
|
||||
"prompt.toast.modelAgentRequired.title": "Виберіть агента та модель",
|
||||
"prompt.toast.modelAgentRequired.description": "Виберіть агента та модель перед надсиланням запиту.",
|
||||
"prompt.toast.worktreeCreateFailed.title": "Не вдалося створити робоче дерево",
|
||||
"prompt.toast.sessionCreateFailed.title": "Не вдалося створити сесію",
|
||||
"prompt.toast.shellSendFailed.title": "Не вдалося надіслати команду термінала",
|
||||
"prompt.toast.commandSendFailed.title": "Не вдалося надіслати команду",
|
||||
"prompt.toast.promptSendFailed.title": "Не вдалося надіслати запит",
|
||||
"prompt.toast.promptSendFailed.description": "Не вдалося отримати сесію",
|
||||
|
||||
"dialog.mcp.title": "MCP",
|
||||
"dialog.mcp.description": "{{enabled}} з {{total}} увімкнено",
|
||||
"dialog.mcp.empty": "MCP не налаштовано",
|
||||
|
||||
"dialog.lsp.empty": "LSP автоматично виявлені за типами файлів",
|
||||
"dialog.plugins.empty": "Плагіни налаштовані в opencode.json",
|
||||
|
||||
"mcp.status.connected": "підключено",
|
||||
"mcp.status.failed": "помилка",
|
||||
"mcp.status.needs_auth": "потрібна авторизація",
|
||||
"mcp.status.disabled": "вимкнено",
|
||||
"mcp.auth.clickToAuthenticate": "Натисніть для автентифікації",
|
||||
|
||||
"dialog.fork.empty": "Немає повідомлень для відгалуження",
|
||||
|
||||
"dialog.directory.search.placeholder": "Пошук папок",
|
||||
"dialog.directory.empty": "Папок не знайдено",
|
||||
|
||||
"app.server.unreachable": "Не вдалося досягти {{server}}",
|
||||
"app.server.retrying": "Автоматичне повторення...",
|
||||
"app.server.otherServers": "Інші сервери",
|
||||
|
||||
"dialog.server.title": "Сервери",
|
||||
"dialog.server.description": "Перемкніть сервер OpenCode, до якого підключається ця програма.",
|
||||
"dialog.server.search.placeholder": "Пошук серверів",
|
||||
"dialog.server.empty": "Ще немає серверів",
|
||||
"dialog.server.add.title": "Додати сервер",
|
||||
"dialog.server.add.url": "Адреса сервера",
|
||||
"dialog.server.add.placeholder": "http://localhost:4096",
|
||||
"dialog.server.add.error": "Не вдалося підключитися до сервера",
|
||||
"dialog.server.add.checking": "Перевірка...",
|
||||
"dialog.server.add.button": "Додати сервер",
|
||||
"dialog.server.add.name": "Назва сервера (необов'язково)",
|
||||
"dialog.server.add.namePlaceholder": "Localhost",
|
||||
"dialog.server.add.username": "Ім'я користувача (необов'язково)",
|
||||
"dialog.server.add.usernamePlaceholder": "ім'я користувача",
|
||||
"dialog.server.add.password": "Пароль (необов'язково)",
|
||||
"dialog.server.add.passwordPlaceholder": "пароль",
|
||||
"dialog.server.edit.title": "Редагувати сервер",
|
||||
"dialog.server.default.title": "Сервер за замовчуванням",
|
||||
"dialog.server.default.description":
|
||||
"Підключатися до цього сервера під час запуску програми замість запуску локального сервера. Потребує перезапуску.",
|
||||
"dialog.server.default.none": "Сервер не вибрано",
|
||||
"dialog.server.default.set": "Встановити поточний сервер як сервер за замовчуванням",
|
||||
"dialog.server.default.clear": "Очистити",
|
||||
"dialog.server.action.remove": "Видалити сервер",
|
||||
|
||||
"dialog.server.menu.edit": "Редагувати",
|
||||
"dialog.server.menu.default": "Встановити за замовчуванням",
|
||||
"dialog.server.menu.defaultRemove": "Видалити за замовчуванням",
|
||||
"dialog.server.menu.delete": "Видалити",
|
||||
"dialog.server.current": "Поточний сервер",
|
||||
"dialog.server.status.default": "За замовчуванням",
|
||||
"server.row.noUsername": "без імені користувача",
|
||||
|
||||
"dialog.project.edit.title": "Редагувати проєкт",
|
||||
"dialog.project.edit.name": "Назва",
|
||||
"dialog.project.edit.icon": "Іконка",
|
||||
"dialog.project.edit.icon.alt": "Іконка проєкту",
|
||||
"dialog.project.edit.icon.hint": "Натисніть або перетягніть зображення",
|
||||
"dialog.project.edit.icon.recommended": "Рекомендовано: 128x128px",
|
||||
"dialog.project.edit.color": "Колір",
|
||||
"dialog.project.edit.color.select": "Вибрати колір {{color}}",
|
||||
"dialog.project.edit.worktree.startup": "Скрипт запуску робочої області",
|
||||
"dialog.project.edit.worktree.startup.description": "Виконується після створення нової робочої області (worktree).",
|
||||
"dialog.project.edit.worktree.startup.placeholder": "напр. bun install",
|
||||
|
||||
"dialog.releaseNotes.action.getStarted": "Розпочати",
|
||||
"dialog.releaseNotes.action.next": "Далі",
|
||||
"dialog.releaseNotes.action.hideFuture": "Не показувати це в майбутньому",
|
||||
"dialog.releaseNotes.media.alt": "Попередній перегляд релізу",
|
||||
|
||||
"context.breakdown.title": "Розподіл контексту",
|
||||
"context.breakdown.note":
|
||||
'Приблизний розподіл вхідних токенів. "Інше" включає визначення інструментів і накладні витрати.',
|
||||
"context.breakdown.system": "Система",
|
||||
"context.breakdown.user": "Користувач",
|
||||
"context.breakdown.assistant": "Асистент",
|
||||
"context.breakdown.tool": "Виклики інструментів",
|
||||
"context.breakdown.other": "Інше",
|
||||
|
||||
"context.systemPrompt.title": "Системний запит",
|
||||
"context.rawMessages.title": "Сировинні повідомлення",
|
||||
|
||||
"context.stats.session": "Сесія",
|
||||
"context.stats.messages": "Повідомлення",
|
||||
"context.stats.provider": "Провайдер",
|
||||
"context.stats.model": "Модель",
|
||||
"context.stats.limit": "Ліміт контексту",
|
||||
"context.stats.totalTokens": "Всього токенів",
|
||||
"context.stats.usage": "Використання",
|
||||
"context.stats.inputTokens": "Вхідні токени",
|
||||
"context.stats.outputTokens": "Вихідні токени",
|
||||
"context.stats.reasoningTokens": "Токени мислення",
|
||||
"context.stats.cacheTokens": "Токени кешу (читання/запис)",
|
||||
"context.stats.userMessages": "Повідомлення користувача",
|
||||
"context.stats.assistantMessages": "Повідомлення асистента",
|
||||
"context.stats.totalCost": "Загальна вартість",
|
||||
"context.stats.sessionCreated": "Сесію створено",
|
||||
"context.stats.lastActivity": "Остання активність",
|
||||
|
||||
"context.usage.tokens": "Токени",
|
||||
"context.usage.usage": "Використання",
|
||||
"context.usage.cost": "Вартість",
|
||||
"context.usage.clickToView": "Натисніть, щоб переглянути контекст",
|
||||
"context.usage.view": "Переглянути використання контексту",
|
||||
|
||||
"language.en": "English",
|
||||
"language.zh": "简体中文",
|
||||
"language.zht": "繁體中文",
|
||||
"language.ko": "한국어",
|
||||
"language.de": "Deutsch",
|
||||
"language.es": "Español",
|
||||
"language.fr": "Français",
|
||||
"language.da": "Dansk",
|
||||
"language.ja": "日本語",
|
||||
"language.pl": "Polski",
|
||||
"language.ru": "Русский",
|
||||
"language.ar": "العربية",
|
||||
"language.no": "Norsk",
|
||||
"language.br": "Português (Brasil)",
|
||||
"language.bs": "Bosanski",
|
||||
"language.uk": "Українська",
|
||||
"language.th": "ไทย",
|
||||
"language.tr": "Türkçe",
|
||||
|
||||
"toast.language.title": "Мова",
|
||||
"toast.language.description": "Перемкнено на {{language}}",
|
||||
|
||||
"toast.theme.title": "Тему змінено",
|
||||
"toast.scheme.title": "Кольорова схема",
|
||||
|
||||
"toast.workspace.enabled.title": "Робочі області увімкнено",
|
||||
"toast.workspace.enabled.description": "Кілька робочих дерев тепер відображаються на бічній панелі",
|
||||
"toast.workspace.disabled.title": "Робочі області вимкнено",
|
||||
"toast.workspace.disabled.description": "Тільки головне робоче дерево відображається на бічній панелі",
|
||||
|
||||
"toast.permissions.autoaccept.on.title": "Автоматичне прийняття дозволів",
|
||||
"toast.permissions.autoaccept.on.description": "Запити дозволів будуть автоматично схвалюватися",
|
||||
"toast.permissions.autoaccept.off.title": "Автоматичне прийняття дозволів зупинено",
|
||||
"toast.permissions.autoaccept.off.description": "Запити дозволів вимагатимуть схвалення",
|
||||
|
||||
"toast.model.none.title": "Модель не вибрано",
|
||||
"toast.model.none.description": "Підключіть провайдера, щоб підсумувати цю сесію",
|
||||
|
||||
"toast.file.loadFailed.title": "Не вдалося завантажити файл",
|
||||
"toast.file.listFailed.title": "Не вдалося отримати список файлів",
|
||||
|
||||
"toast.context.noLineSelection.title": "Не вибрано рядків",
|
||||
"toast.context.noLineSelection.description": "Спочатку виберіть діапазон рядків у вкладці файлу.",
|
||||
|
||||
"toast.session.share.copyFailed.title": "Не вдалося скопіювати URL у буфер обміну",
|
||||
"toast.session.share.success.title": "Сесію опубліковано",
|
||||
"toast.session.share.success.description": "Посилання скопійовано в буфер обміну!",
|
||||
"toast.session.share.failed.title": "Не вдалося опублікувати сесію",
|
||||
"toast.session.share.failed.description": "Під час публікації сесії сталася помилка",
|
||||
|
||||
"toast.session.unshare.success.title": "Поширення сесії припинено",
|
||||
"toast.session.unshare.success.description": "Поширення сесії успішно припинено!",
|
||||
"toast.session.unshare.failed.title": "Не вдалося припинити поширення сесії",
|
||||
"toast.session.unshare.failed.description": "Під час припинення поширення сесії сталася помилка",
|
||||
|
||||
"toast.session.listFailed.title": "Не вдалося завантажити сесії для {{project}}",
|
||||
"toast.project.reloadFailed.title": "Не вдалося перезавантажити {{project}}",
|
||||
|
||||
"toast.update.title": "Доступне оновлення",
|
||||
"toast.update.description": "Нова версія OpenCode ({{version}}) тепер доступна для встановлення.",
|
||||
"toast.update.action.installRestart": "Встановити та перезапустити",
|
||||
"toast.update.action.notYet": "Не зараз",
|
||||
|
||||
"error.page.title": "Щось пішло не так",
|
||||
"error.page.description": "Під час завантаження програми сталася помилка.",
|
||||
"error.page.details.label": "Деталі помилки",
|
||||
"error.page.action.restart": "Перезапустити",
|
||||
"error.page.action.report": "Повідомити про помилку",
|
||||
"error.page.action.reported": "Помилку повідомлено",
|
||||
"error.page.action.checking": "Перевірка...",
|
||||
"error.page.action.checkUpdates": "Перевірити оновлення",
|
||||
"error.page.action.updateTo": "Оновити до {{version}}",
|
||||
"error.page.circular": "[Циклічне]",
|
||||
"error.page.report.prefix": "Будь ласка, повідомте про цю помилку команді OpenCode",
|
||||
"error.page.report.discord": "на Discord",
|
||||
"error.page.version": "Версія: {{version}}",
|
||||
|
||||
"error.dev.rootNotFound":
|
||||
"Кореневий елемент не знайдено. Ви забули додати його до index.html? Або, можливо, атрибут id було написано з помилкою?",
|
||||
|
||||
"error.globalSync.connectFailed": "Не вдалося підключитися до сервера. Чи працює сервер за адресою `{{url}}`?",
|
||||
"error.globalSDK.noServerAvailable": "Сервер недоступний",
|
||||
"error.globalSDK.serverNotAvailable": "Сервер недоступний",
|
||||
"error.childStore.persistedCacheCreateFailed": "Не вдалося створити постійний кеш",
|
||||
"error.childStore.persistedProjectMetadataCreateFailed": "Не вдалося створити постійні метадані проєкту",
|
||||
"error.childStore.persistedProjectIconCreateFailed": "Не вдалося створити постійну іконку проєкту",
|
||||
"error.childStore.storeCreateFailed": "Не вдалося створити сховище",
|
||||
"directory.error.invalidUrl": "Недійсний каталог у URL.",
|
||||
|
||||
"error.chain.unknown": "Невідома помилка",
|
||||
"error.server.invalidConfiguration": "Недійсна конфігурація",
|
||||
"error.chain.causedBy": "Причина:",
|
||||
"error.chain.apiError": "Помилка API",
|
||||
"error.chain.status": "Статус: {{status}}",
|
||||
"error.chain.retryable": "Повторювано: {{retryable}}",
|
||||
"error.chain.responseBody": "Тіло відповіді:\n{{body}}",
|
||||
"error.chain.didYouMean": "Можливо, ви мали на увазі: {{suggestions}}",
|
||||
"error.chain.modelNotFound": "Модель не знайдено: {{provider}}/{{model}}",
|
||||
"error.chain.checkConfig": "Перевірте назви провайдерів/моделей у конфігурації (opencode.json)",
|
||||
"error.chain.mcpFailed":
|
||||
'Сервер MCP "{{name}}" не працює. Зверніть увагу, OpenCode ще не підтримує автентифікацію MCP.',
|
||||
"error.chain.providerAuthFailed": "Автентифікація провайдера не вдалася ({{provider}}): {{message}}",
|
||||
"error.chain.providerInitFailed":
|
||||
'Не вдалося ініціалізувати провайдера "{{provider}}". Перевірте облікові дані та конфігурацію.',
|
||||
"error.chain.configJsonInvalid": "Файл конфігурації {{path}} не є дійсним JSON(C)",
|
||||
"error.chain.configJsonInvalidWithMessage": "Файл конфігурації {{path}} не є дійсним JSON(C): {{message}}",
|
||||
"error.chain.configDirectoryTypo":
|
||||
'Каталог "{{dir}}" у {{path}} недійсний. Перейменуйте каталог на "{{suggestion}}" або видаліть його. Це поширена помилка.',
|
||||
"error.chain.configFrontmatterError": "Не вдалося розібрати frontmatter у {{path}}:\n{{message}}",
|
||||
"error.chain.configInvalid": "Файл конфігурації {{path}} недійсний",
|
||||
"error.chain.configInvalidWithMessage": "Файл конфігурації {{path}} недійсний: {{message}}",
|
||||
|
||||
"notification.permission.title": "Потрібен дозвіл",
|
||||
"notification.permission.description": "{{sessionTitle}} у {{projectName}} потребує дозволу",
|
||||
"notification.question.title": "Запитання",
|
||||
"notification.question.description": "{{sessionTitle}} у {{projectName}} має запитання",
|
||||
"notification.action.goToSession": "Перейти до сесії",
|
||||
|
||||
"notification.session.responseReady.title": "Відповідь готова",
|
||||
"notification.session.error.title": "Помилка сесії",
|
||||
"notification.session.error.fallbackDescription": "Сталася помилка",
|
||||
|
||||
"home.recentProjects": "Нещодавні проєкти",
|
||||
"home.empty.title": "Немає нещодавніх проєктів",
|
||||
"home.empty.description": "Почніть, відкривши локальний проєкт",
|
||||
|
||||
"session.tab.session": "Сесія",
|
||||
"session.tab.review": "Огляд",
|
||||
"session.tab.context": "Контекст",
|
||||
"session.panel.reviewAndFiles": "Огляд і файли",
|
||||
"session.review.filesChanged": "Змінено файлів: {{count}}",
|
||||
"session.review.change.one": "Зміна",
|
||||
"session.review.change.other": "Зміни",
|
||||
"session.review.loadingChanges": "Завантаження змін...",
|
||||
"session.review.empty": "У цій сесії ще немає змін",
|
||||
"session.review.noVcs": "Систему контролю версій Git не виявлено, зміни не відображаються",
|
||||
"session.review.noVcs.createGit.title": "Створити Git-репозиторій",
|
||||
"session.review.noVcs.createGit.description": "Відстежуйте, переглядайте та скасовуйте зміни в цьому проєкті",
|
||||
"session.review.noVcs.createGit.actionLoading": "Створення Git-репозиторію...",
|
||||
"session.review.noVcs.createGit.action": "Створити Git-репозиторій",
|
||||
"session.review.noSnapshot": "Відстеження знімків вимкнено в конфігурації, тому зміни сесії недоступні",
|
||||
"session.review.noChanges": "Немає змін",
|
||||
"session.review.noUncommittedChanges": "Ще немає незафіксованих змін",
|
||||
"session.review.noBranchChanges": "Ще немає змін у гілці",
|
||||
|
||||
"session.files.selectToOpen": "Виберіть файл для відкриття",
|
||||
"session.files.all": "Усі файли",
|
||||
"session.files.empty": "Немає файлів",
|
||||
"session.files.binaryContent": "Бінарний файл (вміст не може бути відображено)",
|
||||
|
||||
"session.messages.renderEarlier": "Відобразити раніші повідомлення",
|
||||
"session.messages.loadingEarlier": "Завантаження раніших повідомлень...",
|
||||
"session.messages.loadEarlier": "Завантажити раніші повідомлення",
|
||||
"session.messages.loading": "Завантаження повідомлень...",
|
||||
"session.messages.jumpToLatest": "Перейти до останніх",
|
||||
|
||||
"session.context.addToContext": "Додати {{selection}} до контексту",
|
||||
"session.todo.title": "Завдання",
|
||||
"session.todo.collapse": "Згорнути",
|
||||
"session.todo.expand": "Розгорнути",
|
||||
"session.todo.progress": "Виконано {{done}} з {{total}} завдань",
|
||||
"session.question.progress": "{{current}} з {{total}} запитань",
|
||||
"session.followupDock.summary.one": "{{count}} повідомлення в черзі",
|
||||
"session.followupDock.summary.other": "{{count}} повідомлень у черзі",
|
||||
"session.followupDock.sendNow": "Надіслати зараз",
|
||||
"session.followupDock.edit": "Редагувати",
|
||||
"session.followupDock.collapse": "Згорнути повідомлення в черзі",
|
||||
"session.followupDock.expand": "Розгорнути повідомлення в черзі",
|
||||
"session.revertDock.summary.one": "{{count}} скасоване повідомлення",
|
||||
"session.revertDock.summary.other": "{{count}} скасованих повідомлень",
|
||||
"session.revertDock.collapse": "Згорнути скасовані повідомлення",
|
||||
"session.revertDock.expand": "Розгорнути скасовані повідомлення",
|
||||
"session.revertDock.restore": "Відновити повідомлення",
|
||||
|
||||
"session.new.title": "Створити що завгодно",
|
||||
"session.new.worktree.main": "Основна гілка",
|
||||
"session.new.worktree.mainWithBranch": "Основна гілка ({{branch}})",
|
||||
"session.new.worktree.create": "Створити нове робоче дерево",
|
||||
"session.new.lastModified": "Востаннє змінено",
|
||||
|
||||
"session.header.search.placeholder": "Пошук {{project}}",
|
||||
"session.header.searchFiles": "Пошук файлів",
|
||||
"session.header.openIn": "Відкрити в",
|
||||
"session.header.open.action": "Відкрити {{app}}",
|
||||
"session.header.open.ariaLabel": "Відкрити в {{app}}",
|
||||
"session.header.open.menu": "Параметри відкриття",
|
||||
"session.header.open.copyPath": "Копіювати шлях",
|
||||
"session.header.open.finder": "Finder",
|
||||
"session.header.open.fileExplorer": "Провідник файлів",
|
||||
"session.header.open.fileManager": "Файловий менеджер",
|
||||
"session.header.open.app.vscode": "VS Code",
|
||||
"session.header.open.app.cursor": "Cursor",
|
||||
"session.header.open.app.zed": "Zed",
|
||||
"session.header.open.app.textmate": "TextMate",
|
||||
"session.header.open.app.antigravity": "Antigravity",
|
||||
"session.header.open.app.terminal": "Термінал",
|
||||
"session.header.open.app.iterm2": "iTerm2",
|
||||
"session.header.open.app.ghostty": "Ghostty",
|
||||
"session.header.open.app.warp": "Warp",
|
||||
"session.header.open.app.xcode": "Xcode",
|
||||
"session.header.open.app.androidStudio": "Android Studio",
|
||||
"session.header.open.app.powershell": "PowerShell",
|
||||
"session.header.open.app.sublimeText": "Sublime Text",
|
||||
|
||||
"status.popover.trigger": "Статус",
|
||||
"status.popover.ariaLabel": "Конфігурації серверів",
|
||||
"status.popover.tab.servers": "Сервери",
|
||||
"status.popover.tab.mcp": "MCP",
|
||||
"status.popover.tab.lsp": "LSP",
|
||||
"status.popover.tab.plugins": "Плагіни",
|
||||
"status.popover.action.manageServers": "Керувати серверами",
|
||||
|
||||
"session.share.popover.title": "Опублікувати в інтернеті",
|
||||
"session.share.popover.description.shared":
|
||||
"Ця сесія є публічною в інтернеті. Вона доступна будь-кому за посиланням.",
|
||||
"session.share.popover.description.unshared":
|
||||
"Опублікуйте сесію публічно в інтернеті. Вона буде доступна будь-кому за посиланням.",
|
||||
"session.share.action.share": "Поділитися",
|
||||
"session.share.action.publish": "Опублікувати",
|
||||
"session.share.action.publishing": "Публікація...",
|
||||
"session.share.action.unpublish": "Скасувати публікацію",
|
||||
"session.share.action.unpublishing": "Скасування публікації...",
|
||||
"session.share.action.view": "Переглянути",
|
||||
"session.share.copy.copied": "Скопійовано",
|
||||
"session.share.copy.copyLink": "Копіювати посилання",
|
||||
|
||||
"lsp.tooltip.none": "Немає серверів LSP",
|
||||
"lsp.label.connected": "{{count}} LSP",
|
||||
|
||||
"prompt.loading": "Завантаження запиту...",
|
||||
"terminal.loading": "Завантаження термінала...",
|
||||
"terminal.title": "Термінал",
|
||||
"terminal.title.numbered": "Термінал {{number}}",
|
||||
"terminal.close": "Закрити термінал",
|
||||
"terminal.connectionLost.title": "З'єднання втрачено",
|
||||
"terminal.connectionLost.abnormalClose": "WebSocket закрито аномально: {{code}}",
|
||||
"terminal.connectionLost.description":
|
||||
"З'єднання з терміналом було перервано. Це може статися під час перезапуску сервера.",
|
||||
|
||||
"common.closeTab": "Закрити вкладку",
|
||||
"common.dismiss": "Відхилити",
|
||||
"common.moreCountSuffix": " (ще {{count}})",
|
||||
"common.requestFailed": "Запит не виконано",
|
||||
"common.moreOptions": "Більше опцій",
|
||||
"common.learnMore": "Дізнатися більше",
|
||||
"common.rename": "Перейменувати",
|
||||
"common.reset": "Скинути",
|
||||
"common.archive": "Архівувати",
|
||||
"common.delete": "Видалити",
|
||||
"common.close": "Закрити",
|
||||
"common.edit": "Редагувати",
|
||||
"common.loadMore": "Завантажити більше",
|
||||
"common.key.esc": "ESC",
|
||||
"common.key.ctrl": "Ctrl",
|
||||
"common.key.alt": "Alt",
|
||||
"common.key.shift": "Shift",
|
||||
"common.key.meta": "Meta",
|
||||
"common.key.space": "Пробіл",
|
||||
"common.key.backspace": "Backspace",
|
||||
"common.key.enter": "Enter",
|
||||
"common.key.tab": "Tab",
|
||||
"common.key.delete": "Delete",
|
||||
"common.key.home": "Home",
|
||||
"common.key.end": "End",
|
||||
"common.key.pageUp": "Page Up",
|
||||
"common.key.pageDown": "Page Down",
|
||||
"common.key.insert": "Insert",
|
||||
"common.unknown": "невідомо",
|
||||
|
||||
"common.time.justNow": "Щойно",
|
||||
"common.time.minutesAgo.short": "{{count}} хв тому",
|
||||
"common.time.hoursAgo.short": "{{count}} год тому",
|
||||
"common.time.daysAgo.short": "{{count}} дн тому",
|
||||
|
||||
"sidebar.menu.toggle": "Перемкнути меню",
|
||||
"sidebar.nav.projectsAndSessions": "Проєкти та сесії",
|
||||
"sidebar.settings": "Налаштування",
|
||||
"sidebar.help": "Довідка",
|
||||
"sidebar.workspaces.enable": "Увімкнути робочі області",
|
||||
"sidebar.workspaces.disable": "Вимкнути робочі області",
|
||||
"sidebar.gettingStarted.title": "Початок роботи",
|
||||
"sidebar.gettingStarted.line1": "OpenCode містить безкоштовні моделі, тому ви можете почати негайно.",
|
||||
"sidebar.gettingStarted.line2":
|
||||
"Підключіть будь-якого провайдера, щоб використовувати моделі, включаючи Claude, GPT, Gemini тощо.",
|
||||
"sidebar.project.recentSessions": "Нещодавні сесії",
|
||||
"sidebar.project.viewAllSessions": "Переглянути всі сесії",
|
||||
"sidebar.project.clearNotifications": "Очистити сповіщення",
|
||||
"sidebar.empty.title": "Немає відкритих проєктів",
|
||||
"sidebar.empty.description": "Відкрийте проєкт, щоб почати",
|
||||
|
||||
"debugBar.ariaLabel": "Діагностика продуктивності розробки",
|
||||
"debugBar.na": "н/д",
|
||||
"debugBar.nav.label": "NAV",
|
||||
"debugBar.nav.tip":
|
||||
"Останній завершений перехід маршруту, що торкається сторінки сесії, виміряний від запуску маршрутизатора до першого відображення після стабілізації.",
|
||||
"debugBar.fps.label": "FPS",
|
||||
"debugBar.fps.tip": "Поточна кількість кадрів за секунду за останні 5 секунд.",
|
||||
"debugBar.frame.label": "FRAME",
|
||||
"debugBar.frame.tip": "Найгірший час кадру за останні 5 секунд.",
|
||||
"debugBar.jank.label": "JANK",
|
||||
"debugBar.jank.tip": "Кадри понад 32 мс за останні 5 секунд.",
|
||||
"debugBar.long.label": "LONG",
|
||||
"debugBar.long.tip": "Заблокований час і кількість довгих завдань за останні 5 секунд. Макс. завдання: {{max}}.",
|
||||
"debugBar.delay.label": "DELAY",
|
||||
"debugBar.delay.tip": "Найгірша спостережувана затримка введення за останні 5 секунд.",
|
||||
"debugBar.inp.label": "INP",
|
||||
"debugBar.inp.tip":
|
||||
"Приблизна тривалість взаємодії за останні 5 секунд. Це схоже на INP, а не на офіційний Web Vitals INP.",
|
||||
"debugBar.cls.label": "CLS",
|
||||
"debugBar.cls.tip": "Сукупний зсув макета за весь час роботи програми.",
|
||||
"debugBar.mem.label": "MEM",
|
||||
"debugBar.mem.tipUnavailable": "Використана купа JS проти ліміту купи. Тільки Chromium.",
|
||||
"debugBar.mem.tip": "Використана купа JS проти ліміту купи. {{used}} з {{limit}}.",
|
||||
|
||||
"app.name.desktop": "OpenCode Desktop",
|
||||
|
||||
"settings.section.desktop": "Робочий стіл",
|
||||
"settings.section.server": "Сервер",
|
||||
"settings.tab.general": "Загальні",
|
||||
"settings.tab.shortcuts": "Скорочення",
|
||||
"settings.desktop.section.wsl": "WSL",
|
||||
"settings.desktop.wsl.title": "Інтеграція WSL",
|
||||
"settings.desktop.wsl.description": "Запускати сервер OpenCode всередині WSL на Windows.",
|
||||
|
||||
"settings.general.section.appearance": "Зовнішній вигляд",
|
||||
"settings.general.section.advanced": "Додатково",
|
||||
"settings.general.section.notifications": "Системні сповіщення",
|
||||
"settings.general.section.updates": "Оновлення",
|
||||
"settings.general.section.sounds": "Звукові ефекти",
|
||||
"settings.general.section.feed": "Стрічка",
|
||||
"settings.general.section.display": "Дисплей",
|
||||
|
||||
"settings.general.row.language.title": "Мова",
|
||||
"settings.general.row.language.description": "Змінити мову інтерфейсу OpenCode",
|
||||
"settings.general.row.shell.title": "Командна оболонка термінала",
|
||||
"settings.general.row.shell.description":
|
||||
"Виберіть оболонку для термінала. Сумісні оболонки також використовуються для викликів інструментів агента.",
|
||||
"settings.general.row.shell.autoDefault": "Авто (за замовчуванням)",
|
||||
"settings.general.row.shell.terminalOnly": "тільки термінал",
|
||||
"settings.general.row.appearance.title": "Зовнішній вигляд",
|
||||
"settings.general.row.appearance.description": "Налаштуйте вигляд OpenCode на вашому пристрої",
|
||||
"settings.general.row.colorScheme.title": "Кольорова схема",
|
||||
"settings.general.row.colorScheme.description": "Виберіть, чи OpenCode використовує системну, світлу або темну тему",
|
||||
"settings.general.row.theme.title": "Тема",
|
||||
"settings.general.row.theme.description": "Налаштуйте тему OpenCode.",
|
||||
"settings.general.row.font.title": "Шрифт коду",
|
||||
"settings.general.row.font.description": "Налаштуйте шрифт, який використовується в блоках коду",
|
||||
"settings.general.row.terminalFont.title": "Шрифт термінала",
|
||||
"settings.general.row.terminalFont.description": "Налаштуйте шрифт, який використовується в терміналі",
|
||||
"settings.general.row.uiFont.title": "Шрифт інтерфейсу",
|
||||
"settings.general.row.uiFont.description": "Налаштуйте шрифт, який використовується в інтерфейсі",
|
||||
"settings.general.row.followup.title": "Поведінка продовження",
|
||||
"settings.general.row.followup.description": "Виберіть, чи продовження виконується негайно, чи чекає в черзі",
|
||||
"settings.general.row.followup.option.queue": "Черга",
|
||||
"settings.general.row.followup.option.steer": "Керування",
|
||||
"settings.general.row.showFileTree.title": "Дерево файлів",
|
||||
"settings.general.row.showFileTree.description":
|
||||
"Показувати перемикач і панель дерева файлів у сесіях на робочому столі",
|
||||
"settings.general.row.showNavigation.title": "Елементи навігації",
|
||||
"settings.general.row.showNavigation.description": "Показувати кнопки назад і вперед у заголовку робочого столу",
|
||||
"settings.general.row.showSearch.title": "Палітра команд",
|
||||
"settings.general.row.showSearch.description":
|
||||
"Показувати кнопку пошуку та палітри команд у заголовку робочого столу",
|
||||
"settings.general.row.showTerminal.title": "Термінал",
|
||||
"settings.general.row.showTerminal.description": "Показувати кнопку термінала в заголовку робочого столу",
|
||||
"settings.general.row.showStatus.title": "Статус сервера",
|
||||
"settings.general.row.showStatus.description": "Показувати кнопку статусу сервера в заголовку робочого столу",
|
||||
"settings.general.row.reasoningSummaries.title": "Показувати підсумки мислення",
|
||||
"settings.general.row.reasoningSummaries.description": "Відображати підсумки мислення моделі на часовій шкалі",
|
||||
"settings.general.row.shellToolPartsExpanded.title": "Розгортати частини інструменту оболонки",
|
||||
"settings.general.row.shellToolPartsExpanded.description":
|
||||
"Показувати частини інструменту оболонки розгорнутими за замовчуванням на часовій шкалі",
|
||||
"settings.general.row.editToolPartsExpanded.title": "Розгортати частини інструменту редагування",
|
||||
"settings.general.row.editToolPartsExpanded.description":
|
||||
"Показувати частини інструментів редагування, запису та патчів розгорнутими за замовчуванням на часовій шкалі",
|
||||
"settings.general.row.showSessionProgressBar.title": "Показувати індикатор прогресу сесії",
|
||||
"settings.general.row.showSessionProgressBar.description":
|
||||
"Відображати анімований індикатор прогресу вгорі сесії, коли агент працює",
|
||||
|
||||
"settings.general.row.wayland.title": "Використовувати нативний Wayland",
|
||||
"settings.general.row.wayland.description": "Вимкнути резервний X11 на Wayland. Потребує перезапуску.",
|
||||
"settings.general.row.wayland.tooltip":
|
||||
"На Linux з моніторами з різною частотою оновлення нативний Wayland може бути більш стабільним.",
|
||||
|
||||
"settings.general.row.releaseNotes.title": "Нотатки до релізу",
|
||||
"settings.general.row.releaseNotes.description": 'Показувати спливаючі вікна "Що нового" після оновлень',
|
||||
|
||||
"settings.updates.row.startup.title": "Перевіряти оновлення під час запуску",
|
||||
"settings.updates.row.startup.description": "Автоматично перевіряти наявність оновлень під час запуску OpenCode",
|
||||
"settings.updates.row.check.title": "Перевірити оновлення",
|
||||
"settings.updates.row.check.description": "Вручну перевірити наявність оновлень і встановити, якщо доступні",
|
||||
"settings.updates.action.checkNow": "Перевірити зараз",
|
||||
"settings.updates.action.checking": "Перевірка...",
|
||||
"settings.updates.toast.latest.title": "У вас актуальна версія",
|
||||
"settings.updates.toast.latest.description": "Ви використовуєте останню версію OpenCode.",
|
||||
"sound.option.none": "Немає",
|
||||
"sound.option.alert01": "Alert 01",
|
||||
"sound.option.alert02": "Alert 02",
|
||||
"sound.option.alert03": "Alert 03",
|
||||
"sound.option.alert04": "Alert 04",
|
||||
"sound.option.alert05": "Alert 05",
|
||||
"sound.option.alert06": "Alert 06",
|
||||
"sound.option.alert07": "Alert 07",
|
||||
"sound.option.alert08": "Alert 08",
|
||||
"sound.option.alert09": "Alert 09",
|
||||
"sound.option.alert10": "Alert 10",
|
||||
"sound.option.bipbop01": "Bip-bop 01",
|
||||
"sound.option.bipbop02": "Bip-bop 02",
|
||||
"sound.option.bipbop03": "Bip-bop 03",
|
||||
"sound.option.bipbop04": "Bip-bop 04",
|
||||
"sound.option.bipbop05": "Bip-bop 05",
|
||||
"sound.option.bipbop06": "Bip-bop 06",
|
||||
"sound.option.bipbop07": "Bip-bop 07",
|
||||
"sound.option.bipbop08": "Bip-bop 08",
|
||||
"sound.option.bipbop09": "Bip-bop 09",
|
||||
"sound.option.bipbop10": "Bip-bop 10",
|
||||
"sound.option.staplebops01": "Staplebops 01",
|
||||
"sound.option.staplebops02": "Staplebops 02",
|
||||
"sound.option.staplebops03": "Staplebops 03",
|
||||
"sound.option.staplebops04": "Staplebops 04",
|
||||
"sound.option.staplebops05": "Staplebops 05",
|
||||
"sound.option.staplebops06": "Staplebops 06",
|
||||
"sound.option.staplebops07": "Staplebops 07",
|
||||
"sound.option.nope01": "Nope 01",
|
||||
"sound.option.nope02": "Nope 02",
|
||||
"sound.option.nope03": "Nope 03",
|
||||
"sound.option.nope04": "Nope 04",
|
||||
"sound.option.nope05": "Nope 05",
|
||||
"sound.option.nope06": "Nope 06",
|
||||
"sound.option.nope07": "Nope 07",
|
||||
"sound.option.nope08": "Nope 08",
|
||||
"sound.option.nope09": "Nope 09",
|
||||
"sound.option.nope10": "Nope 10",
|
||||
"sound.option.nope11": "Nope 11",
|
||||
"sound.option.nope12": "Nope 12",
|
||||
"sound.option.yup01": "Yup 01",
|
||||
"sound.option.yup02": "Yup 02",
|
||||
"sound.option.yup03": "Yup 03",
|
||||
"sound.option.yup04": "Yup 04",
|
||||
"sound.option.yup05": "Yup 05",
|
||||
"sound.option.yup06": "Yup 06",
|
||||
|
||||
"settings.general.notifications.agent.title": "Агент",
|
||||
"settings.general.notifications.agent.description":
|
||||
"Показувати системне сповіщення, коли агент завершує роботу або потребує уваги",
|
||||
"settings.general.notifications.permissions.title": "Дозволи",
|
||||
"settings.general.notifications.permissions.description": "Показувати системне сповіщення, коли потрібен дозвіл",
|
||||
"settings.general.notifications.errors.title": "Помилки",
|
||||
"settings.general.notifications.errors.description": "Показувати системне сповіщення, коли виникає помилка",
|
||||
|
||||
"settings.general.sounds.agent.title": "Агент",
|
||||
"settings.general.sounds.agent.description": "Відтворювати звук, коли агент завершує роботу або потребує уваги",
|
||||
"settings.general.sounds.permissions.title": "Дозволи",
|
||||
"settings.general.sounds.permissions.description": "Відтворювати звук, коли потрібен дозвіл",
|
||||
"settings.general.sounds.errors.title": "Помилки",
|
||||
"settings.general.sounds.errors.description": "Відтворювати звук, коли виникає помилка",
|
||||
|
||||
"settings.shortcuts.title": "Скорочення клавіш",
|
||||
"settings.shortcuts.reset.button": "Скинути до стандартних",
|
||||
"settings.shortcuts.reset.toast.title": "Скорочення скинуто",
|
||||
"settings.shortcuts.reset.toast.description": "Скорочення клавіш були скинуті до стандартних.",
|
||||
"settings.shortcuts.conflict.title": "Скорочення вже використовується",
|
||||
"settings.shortcuts.conflict.description": "{{keybind}} вже призначено для {{titles}}.",
|
||||
"settings.shortcuts.unassigned": "Не призначено",
|
||||
"settings.shortcuts.pressKeys": "Натисніть клавіші",
|
||||
"settings.shortcuts.search.placeholder": "Пошук скорочень",
|
||||
"settings.shortcuts.search.empty": "Скорочень не знайдено",
|
||||
|
||||
"settings.shortcuts.group.general": "Загальні",
|
||||
"settings.shortcuts.group.session": "Сесія",
|
||||
"settings.shortcuts.group.navigation": "Навігація",
|
||||
"settings.shortcuts.group.modelAndAgent": "Модель та агент",
|
||||
"settings.shortcuts.group.terminal": "Термінал",
|
||||
"settings.shortcuts.group.prompt": "Запит",
|
||||
|
||||
"settings.providers.title": "Провайдери",
|
||||
"settings.providers.description": "Налаштування провайдерів будуть доступні тут.",
|
||||
"settings.providers.section.connected": "Підключені провайдери",
|
||||
"settings.providers.connected.empty": "Немає підключених провайдерів",
|
||||
"settings.providers.connected.environmentDescription": "Підключено зі змінних середовища",
|
||||
"settings.providers.section.popular": "Популярні провайдери",
|
||||
"settings.providers.custom.description": "Додайте провайдера, сумісного з OpenAI, за базовим URL.",
|
||||
"settings.providers.tag.environment": "Середовище",
|
||||
"settings.providers.tag.config": "Конфігурація",
|
||||
"settings.providers.tag.custom": "Користувацький",
|
||||
"settings.providers.tag.other": "Інше",
|
||||
"settings.models.title": "Моделі",
|
||||
"settings.models.description": "Налаштування моделей будуть доступні тут.",
|
||||
"settings.agents.title": "Агенти",
|
||||
"settings.agents.description": "Налаштування агентів будуть доступні тут.",
|
||||
"settings.commands.title": "Команди",
|
||||
"settings.commands.description": "Налаштування команд будуть доступні тут.",
|
||||
"settings.mcp.title": "MCP",
|
||||
"settings.mcp.description": "Налаштування MCP будуть доступні тут.",
|
||||
|
||||
"settings.permissions.title": "Дозволи",
|
||||
"settings.permissions.description": "Керуйте тим, які інструменти сервер може використовувати за замовчуванням.",
|
||||
"settings.permissions.section.tools": "Інструменти",
|
||||
"settings.permissions.toast.updateFailed.title": "Не вдалося оновити дозволи",
|
||||
|
||||
"settings.permissions.action.allow": "Дозволити",
|
||||
"settings.permissions.action.ask": "Запитувати",
|
||||
"settings.permissions.action.deny": "Заборонити",
|
||||
|
||||
"settings.permissions.tool.read.title": "Читання",
|
||||
"settings.permissions.tool.read.description": "Читання файлу (відповідає шляху файлу)",
|
||||
"settings.permissions.tool.edit.title": "Редагування",
|
||||
"settings.permissions.tool.edit.description": "Зміна файлів, включаючи редагування, запис і патчі",
|
||||
"settings.permissions.tool.glob.title": "Glob",
|
||||
"settings.permissions.tool.glob.description": "Зіставлення файлів за допомогою glob-шаблонів",
|
||||
"settings.permissions.tool.grep.title": "Grep",
|
||||
"settings.permissions.tool.grep.description": "Пошук вмісту файлів за допомогою регулярних виразів",
|
||||
"settings.permissions.tool.list.title": "Список",
|
||||
"settings.permissions.tool.list.description": "Список файлів у каталозі",
|
||||
"settings.permissions.tool.bash.title": "Bash",
|
||||
"settings.permissions.tool.bash.description": "Запуск команд оболонки",
|
||||
"settings.permissions.tool.task.title": "Завдання",
|
||||
"settings.permissions.tool.task.description": "Запуск підагентів",
|
||||
"settings.permissions.tool.skill.title": "Навичка",
|
||||
"settings.permissions.tool.skill.description": "Завантаження навички за назвою",
|
||||
"settings.permissions.tool.lsp.title": "LSP",
|
||||
"settings.permissions.tool.lsp.description": "Виконання запитів мовного сервера",
|
||||
"settings.permissions.tool.todowrite.title": "Todo Write",
|
||||
"settings.permissions.tool.todowrite.description": "Оновлення списку завдань",
|
||||
"settings.permissions.tool.webfetch.title": "Web Fetch",
|
||||
"settings.permissions.tool.webfetch.description": "Отримання вмісту з URL",
|
||||
"settings.permissions.tool.websearch.title": "Web Search",
|
||||
"settings.permissions.tool.websearch.description": "Пошук в інтернеті",
|
||||
"settings.permissions.tool.external_directory.title": "Зовнішній каталог",
|
||||
"settings.permissions.tool.external_directory.description": "Доступ до файлів за межами каталогу проєкту",
|
||||
"settings.permissions.tool.doom_loop.title": "Цикл приреченості",
|
||||
"settings.permissions.tool.doom_loop.description":
|
||||
"Виявлення повторюваних викликів інструментів з однаковими вхідними даними",
|
||||
|
||||
"session.delete.failed.title": "Не вдалося видалити сесію",
|
||||
"session.delete.title": "Видалити сесію",
|
||||
"session.delete.confirm": 'Видалити сесію "{{name}}"?',
|
||||
"session.delete.button": "Видалити сесію",
|
||||
|
||||
"workspace.new": "Нова робоча область",
|
||||
"workspace.type.local": "локальна",
|
||||
"workspace.type.sandbox": "пісочниця",
|
||||
"workspace.create.failed.title": "Не вдалося створити робочу область",
|
||||
"workspace.delete.failed.title": "Не вдалося видалити робочу область",
|
||||
"workspace.resetting.title": "Скидання робочої області",
|
||||
"workspace.resetting.description": "Це може зайняти хвилину.",
|
||||
"workspace.reset.failed.title": "Не вдалося скинути робочу область",
|
||||
"workspace.reset.success.title": "Робочу область скинуто",
|
||||
"workspace.reset.success.description": "Робоча область тепер відповідає гілці за замовчуванням.",
|
||||
"workspace.error.stillPreparing": "Робоча область все ще готується",
|
||||
"workspace.status.checking": "Перевірка незлитих змін...",
|
||||
"workspace.status.error": "Не вдалося перевірити статус git.",
|
||||
"workspace.status.clean": "Незлитих змін не виявлено.",
|
||||
"workspace.status.dirty": "Виявлено незлиті зміни в цій робочій області.",
|
||||
"workspace.delete.title": "Видалити робочу область",
|
||||
"workspace.delete.confirm": 'Видалити робочу область "{{name}}"?',
|
||||
"workspace.delete.button": "Видалити робочу область",
|
||||
"workspace.reset.title": "Скинути робочу область",
|
||||
"workspace.reset.confirm": 'Скинути робочу область "{{name}}"?',
|
||||
"workspace.reset.button": "Скинути робочу область",
|
||||
"workspace.reset.archived.none": "Жодна активна сесія не буде заархівована.",
|
||||
"workspace.reset.archived.one": "1 сесію буде заархівовано.",
|
||||
"workspace.reset.archived.many": "{{count}} сесій буде заархівовано.",
|
||||
"workspace.reset.note": "Це скине робочу область, щоб вона відповідала гілці за замовчуванням.",
|
||||
}
|
||||
@@ -1,19 +1,4 @@
|
||||
import {
|
||||
createEffect,
|
||||
createMemo,
|
||||
createSignal,
|
||||
For,
|
||||
Index,
|
||||
Match,
|
||||
Switch,
|
||||
on,
|
||||
onCleanup,
|
||||
Show,
|
||||
mapArray,
|
||||
untrack,
|
||||
type Accessor,
|
||||
type JSX,
|
||||
} from "solid-js"
|
||||
import { createEffect, createMemo, createSignal, For, Index, on, onCleanup, Show, mapArray, type JSX } from "solid-js"
|
||||
import { createStore, produce } from "solid-js/store"
|
||||
import { Dynamic } from "solid-js/web"
|
||||
import { useNavigate } from "@solidjs/router"
|
||||
@@ -995,26 +980,26 @@ export function MessageTimeline(props: {
|
||||
|
||||
const getMsgPart = (messageID: string, partID: string) => getMsgParts(messageID).find((part) => part.id === partID)
|
||||
|
||||
const renderAssistantPartGroup = (row: Accessor<TimelineRowMap["AssistantPart"]>) => {
|
||||
if (untrack(row).group.type === "context") {
|
||||
const renderAssistantPartGroup = (row: TimelineRowMap["AssistantPart"]) => {
|
||||
if (row.group.type === "context") {
|
||||
const parts = createMemo(() => {
|
||||
const group = row().group
|
||||
const group = row.group
|
||||
if (group.type !== "context") return emptyTools
|
||||
return group.refs
|
||||
.map((ref) => getMsgPart(ref.messageID, ref.partID))
|
||||
.filter((part): part is ToolPart => part?.type === "tool")
|
||||
})
|
||||
|
||||
return <ContextToolGroup parts={parts()} busy={workingTurn(row().userMessageID) && row().lastAssistantPart} />
|
||||
return <ContextToolGroup parts={parts()} busy={workingTurn(row.userMessageID) && row.lastAssistantPart} />
|
||||
}
|
||||
|
||||
const message = createMemo(() => {
|
||||
const group = row().group
|
||||
const group = row.group
|
||||
if (group.type !== "part") return
|
||||
return messageByID().get(group.ref.messageID)
|
||||
})
|
||||
const part = createMemo(() => {
|
||||
const group = row().group
|
||||
const group = row.group
|
||||
if (group.type !== "part") return
|
||||
return getMsgPart(group.ref.messageID, group.ref.partID)
|
||||
})
|
||||
@@ -1027,8 +1012,8 @@ export function MessageTimeline(props: {
|
||||
<MessagePart
|
||||
part={part()}
|
||||
message={message()}
|
||||
showAssistantCopyPartID={assistantCopyPartID(row().userMessageID)}
|
||||
turnDurationMs={turnDurationMs(row().userMessageID)}
|
||||
showAssistantCopyPartID={assistantCopyPartID(row.userMessageID)}
|
||||
turnDurationMs={turnDurationMs(row.userMessageID)}
|
||||
defaultOpen={partDefaultOpen(
|
||||
part(),
|
||||
settings.general.shellToolPartsExpanded(),
|
||||
@@ -1043,25 +1028,25 @@ export function MessageTimeline(props: {
|
||||
)
|
||||
}
|
||||
|
||||
function TimelineRowFrame(input: { row: Accessor<FramedTimelineRow>; children: JSX.Element }) {
|
||||
function TimelineRowFrame(input: { row: FramedTimelineRow; children: JSX.Element }) {
|
||||
const anchor = () => {
|
||||
const row = input.row()
|
||||
const row = input.row
|
||||
return row._tag === "CommentStrip" || (row._tag === "UserMessage" && row.anchor)
|
||||
}
|
||||
const previousUserMessage = () => {
|
||||
const row = input.row()
|
||||
const row = input.row
|
||||
return (row._tag === "CommentStrip" || row._tag === "UserMessage") && row.previousUserMessage
|
||||
}
|
||||
const previousAssistantPart = () => {
|
||||
const row = input.row()
|
||||
const row = input.row
|
||||
return row._tag === "AssistantPart" && row.previousAssistantPart
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
id={anchor() ? props.anchor(input.row().userMessageID) : undefined}
|
||||
data-message-id={input.row().userMessageID}
|
||||
data-timeline-row={input.row()._tag}
|
||||
id={anchor() ? props.anchor(input.row.userMessageID) : undefined}
|
||||
data-message-id={input.row.userMessageID}
|
||||
data-timeline-row={input.row._tag}
|
||||
classList={{
|
||||
"min-w-0 w-full max-w-full": true,
|
||||
"md:max-w-200 2xl:max-w-[1000px]": props.centered,
|
||||
@@ -1077,15 +1062,14 @@ export function MessageTimeline(props: {
|
||||
)
|
||||
}
|
||||
|
||||
const renderTimelineRow = (row: Accessor<TimelineRow.TimelineRow>) => {
|
||||
switch (row()._tag) {
|
||||
const renderTimelineRow = (row: TimelineRow.TimelineRow) => {
|
||||
switch (row._tag) {
|
||||
case "CommentStrip": {
|
||||
const commentStripRow = row as Accessor<TimelineRowByTag<"CommentStrip">>
|
||||
const comments = createMemo(() =>
|
||||
getMsgParts(commentStripRow().userMessageID).flatMap((part) => MessageComment.fromPart(part) ?? []),
|
||||
getMsgParts(row.userMessageID).flatMap((part) => MessageComment.fromPart(part) ?? []),
|
||||
)
|
||||
return (
|
||||
<TimelineRowFrame row={commentStripRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div class="w-full px-4 md:px-5 pb-2">
|
||||
<div class="ml-auto max-w-[82%] overflow-x-auto no-scrollbar">
|
||||
<div class="flex w-max min-w-full justify-end gap-2">
|
||||
@@ -1118,22 +1102,17 @@ export function MessageTimeline(props: {
|
||||
)
|
||||
}
|
||||
case "UserMessage": {
|
||||
const userMessageRow = row as Accessor<TimelineRowByTag<"UserMessage">>
|
||||
const message = createMemo(() => {
|
||||
const m = messageByID().get(userMessageRow().userMessageID)
|
||||
const m = messageByID().get(row.userMessageID)
|
||||
if (m?.role === "user") return m
|
||||
})
|
||||
return (
|
||||
<TimelineRowFrame row={userMessageRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<Show when={message()}>
|
||||
{(message) => (
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<div data-slot="session-turn-message-content" aria-live="off">
|
||||
<Message
|
||||
message={message()}
|
||||
parts={getMsgParts(userMessageRow().userMessageID)}
|
||||
actions={props.actions}
|
||||
/>
|
||||
<Message message={message()} parts={getMsgParts(row.userMessageID)} actions={props.actions} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -1142,14 +1121,13 @@ export function MessageTimeline(props: {
|
||||
)
|
||||
}
|
||||
case "TurnDivider": {
|
||||
const turnDividerRow = row as Accessor<TimelineRowByTag<"TurnDivider">>
|
||||
return (
|
||||
<TimelineRowFrame row={turnDividerRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<div data-slot="session-turn-compaction">
|
||||
<MessageDivider
|
||||
label={language.t(
|
||||
turnDividerRow().label === "compaction" ? "ui.messagePart.compaction" : "ui.message.interrupted",
|
||||
row.label === "compaction" ? "ui.messagePart.compaction" : "ui.message.interrupted",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
@@ -1158,27 +1136,22 @@ export function MessageTimeline(props: {
|
||||
)
|
||||
}
|
||||
case "AssistantPart": {
|
||||
const assistantPartRow = row as Accessor<TimelineRowByTag<"AssistantPart">>
|
||||
return (
|
||||
<TimelineRowFrame row={assistantPartRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<div
|
||||
data-slot="session-turn-assistant-content"
|
||||
aria-hidden={workingTurn(assistantPartRow().userMessageID)}
|
||||
>
|
||||
{renderAssistantPartGroup(assistantPartRow)}
|
||||
<div data-slot="session-turn-assistant-content" aria-hidden={workingTurn(row.userMessageID)}>
|
||||
{renderAssistantPartGroup(row)}
|
||||
</div>
|
||||
</div>
|
||||
</TimelineRowFrame>
|
||||
)
|
||||
}
|
||||
case "Thinking": {
|
||||
const thinkingRow = row as Accessor<TimelineRowByTag<"Thinking">>
|
||||
return (
|
||||
<TimelineRowFrame row={thinkingRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<TimelineThinkingRow
|
||||
reasoningHeading={thinkingRow().reasoningHeading}
|
||||
reasoningHeading={row.reasoningHeading}
|
||||
showReasoningSummaries={settings.general.showReasoningSummaries()}
|
||||
/>
|
||||
</div>
|
||||
@@ -1186,32 +1159,29 @@ export function MessageTimeline(props: {
|
||||
)
|
||||
}
|
||||
case "Retry": {
|
||||
const retryRow = row as Accessor<TimelineRowByTag<"Retry">>
|
||||
return (
|
||||
<TimelineRowFrame row={retryRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<SessionRetry status={sessionStatus()} show={activeMessageID() === retryRow().userMessageID} />
|
||||
<SessionRetry status={sessionStatus()} show={activeMessageID() === row.userMessageID} />
|
||||
</div>
|
||||
</TimelineRowFrame>
|
||||
)
|
||||
}
|
||||
case "DiffSummary": {
|
||||
const diffSummaryRow = row as Accessor<TimelineRowByTag<"DiffSummary">>
|
||||
return (
|
||||
<TimelineRowFrame row={diffSummaryRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<TimelineDiffSummaryRow diffs={diffSummaryRow().diffs} />
|
||||
<TimelineDiffSummaryRow diffs={row.diffs} />
|
||||
</div>
|
||||
</TimelineRowFrame>
|
||||
)
|
||||
}
|
||||
case "Error": {
|
||||
const errorRow = row as Accessor<TimelineRowByTag<"Error">>
|
||||
return (
|
||||
<TimelineRowFrame row={errorRow}>
|
||||
<TimelineRowFrame row={row}>
|
||||
<div data-slot="session-turn-message-container" class="w-full px-4 md:px-5">
|
||||
<Card variant="error" class="error-card">
|
||||
{errorRow().text}
|
||||
{row.text}
|
||||
</Card>
|
||||
</div>
|
||||
</TimelineRowFrame>
|
||||
@@ -1223,7 +1193,11 @@ export function MessageTimeline(props: {
|
||||
}
|
||||
|
||||
function TimelineRowView(props: { rowKey: string }) {
|
||||
return <Show when={timelineRowByKey().get(props.rowKey)}>{(item) => renderTimelineRow(item)}</Show>
|
||||
return (
|
||||
<Show when={timelineRowByKey().get(props.rowKey)} keyed>
|
||||
{(item) => renderTimelineRow(item)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
[data-component="go-credit-confirm"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
min-width: min(34rem, calc(100vw - var(--space-8)));
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-sm);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
[data-slot="usage-preview"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-5);
|
||||
padding: var(--space-4);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--border-radius-sm);
|
||||
background-color: var(--color-bg-surface);
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-item"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-header"] {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-label"] {
|
||||
color: var(--color-text);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-value"] {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
color: var(--color-text-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-after-value"] {
|
||||
color: var(--color-accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-progress"] {
|
||||
position: relative;
|
||||
height: 8px;
|
||||
overflow: hidden;
|
||||
border-radius: var(--border-radius-sm);
|
||||
background-color: var(--color-bg);
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-before"],
|
||||
[data-slot="usage-preview-after"] {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
border-radius: var(--border-radius-sm);
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-before"] {
|
||||
background-color: var(--color-border);
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-after"] {
|
||||
background-color: var(--color-accent);
|
||||
transition: width 0.35s ease;
|
||||
}
|
||||
|
||||
[data-slot="usage-preview-reset"] {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
[data-slot="modal-actions"] {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="invite-link-box"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
|
||||
> div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
border-radius: var(--border-radius-sm);
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
code {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--border-radius-sm);
|
||||
background-color: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-sm);
|
||||
line-height: 1.4;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
padding: var(--space-2-5);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
}
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 130px;
|
||||
white-space: nowrap;
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
min-width: 96px;
|
||||
padding: var(--space-2-5) var(--space-3);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="instructions"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
|
||||
ol {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding-left: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-md);
|
||||
list-style-position: inside;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="go-referral-section"] {
|
||||
[data-component="go-referral-overview"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-8);
|
||||
padding: var(--space-6);
|
||||
border: 1px dashed var(--color-border);
|
||||
border-radius: var(--border-radius-sm);
|
||||
background-color: var(--color-bg-surface);
|
||||
|
||||
@media (max-width: 30rem) {
|
||||
gap: var(--space-8);
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="go-referral-overview"] + [data-slot="section-title"] {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
|
||||
[data-slot="referrals-table"] {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
[data-component="empty-state"] {
|
||||
padding: var(--space-4);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--border-radius-sm);
|
||||
background-color: var(--color-bg-surface);
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
[data-slot="referrals-table-element"] {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: var(--font-size-sm);
|
||||
|
||||
thead {
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
th {
|
||||
padding: var(--space-3) var(--space-4);
|
||||
text-align: left;
|
||||
font-weight: normal;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
|
||||
&:nth-child(1) {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
&:nth-child(3) {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
&:nth-child(4) {
|
||||
width: 140px;
|
||||
}
|
||||
}
|
||||
|
||||
td {
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border-bottom: 1px solid var(--color-border-muted);
|
||||
color: var(--color-text-muted);
|
||||
font-family: var(--font-mono);
|
||||
|
||||
&[data-slot="referral-amount"] {
|
||||
color: var(--color-text);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
&[data-slot="referral-source"] {
|
||||
color: var(--color-text-secondary);
|
||||
font-family: var(--font-sans);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&[data-slot="referral-action"] {
|
||||
text-align: right;
|
||||
font-family: var(--font-sans);
|
||||
white-space: nowrap;
|
||||
|
||||
button {
|
||||
min-width: 96px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tbody tr {
|
||||
&[data-status="applied"] {
|
||||
td:not([data-slot="referral-action"]) {
|
||||
opacity: 0.68;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-status="pending"] {
|
||||
td[data-slot="referral-amount"],
|
||||
td[data-slot="referral-date"] {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
td[data-slot="referral-source"] {
|
||||
color: var(--color-text);
|
||||
}
|
||||
}
|
||||
|
||||
&:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
th,
|
||||
td {
|
||||
padding: var(--space-2) var(--space-3);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { action, json, query, useAction, useSubmission } from "@solidjs/router"
|
||||
import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js"
|
||||
import { getRequestEvent } from "solid-js/web"
|
||||
import { Referral } from "@opencode-ai/console-core/referral.js"
|
||||
import { withActor } from "~/context/auth.withActor"
|
||||
import { Modal } from "~/component/modal"
|
||||
import { IconCheck, IconCopy } from "~/component/icon"
|
||||
import { useI18n } from "~/context/i18n"
|
||||
import { useLanguage } from "~/context/language"
|
||||
import { formatResetTime, liteResetTimeKeys } from "~/lib/format-reset-time"
|
||||
import { queryLiteSubscription } from "~/routes/workspace/[id]/go/lite-section"
|
||||
import "./go-referral.css"
|
||||
|
||||
type GoReferralSummary = Awaited<ReturnType<typeof Referral.summary>>
|
||||
type GoReferralReward = GoReferralSummary["rewards"][number]
|
||||
type GoLiteSubscription = Awaited<ReturnType<typeof queryLiteSubscription>>
|
||||
type GoReferralUsagePreview = NonNullable<Awaited<ReturnType<typeof Referral.usagePreview>>>
|
||||
type GoReferralUsagePreviewItem = GoReferralUsagePreview["rollingUsage"]
|
||||
|
||||
const emptyUsagePreview = {
|
||||
rollingUsage: { beforePercent: 0, afterPercent: 0, resetInSec: 0 },
|
||||
weeklyUsage: { beforePercent: 0, afterPercent: 0, resetInSec: 0 },
|
||||
monthlyUsage: { beforePercent: 0, afterPercent: 0, resetInSec: 0 },
|
||||
} satisfies GoReferralUsagePreview
|
||||
|
||||
export const queryGoReferral = query(async (workspaceID: string) => {
|
||||
"use server"
|
||||
return withActor(() => Referral.summary(), workspaceID)
|
||||
}, "go.referral.get")
|
||||
|
||||
export const queryGoReferralUsagePreview = query(async (workspaceID: string, referralID?: string) => {
|
||||
"use server"
|
||||
if (!referralID) return null
|
||||
return withActor(() => Referral.usagePreview({ referralID }), workspaceID)
|
||||
}, "go.referral.usagePreview")
|
||||
|
||||
export const applyGoReferralReward = action(async (workspaceID: string, referralID: string) => {
|
||||
"use server"
|
||||
return json(await withActor(() => Referral.applyReward({ referralID }), workspaceID), {
|
||||
revalidate: [queryGoReferral.key, queryGoReferralUsagePreview.key, queryLiteSubscription.key],
|
||||
})
|
||||
}, "go.referral.reward.apply")
|
||||
|
||||
function currentUsagePreview(usage: { resetInSec: number; usagePercent: number }) {
|
||||
return {
|
||||
beforePercent: usage.usagePercent,
|
||||
afterPercent: usage.usagePercent,
|
||||
resetInSec: usage.resetInSec,
|
||||
}
|
||||
}
|
||||
|
||||
function formatCurrency(amount: number) {
|
||||
if (amount % 100 === 0) return `$${amount / 100}`
|
||||
return `$${(amount / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
function formatDate(value: string | Date, locale: string) {
|
||||
return new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric" }).format(new Date(value))
|
||||
}
|
||||
|
||||
function rewardDescriptionKey(source: GoReferralReward["source"]) {
|
||||
if (source === "invitee") return "workspace.referral.reward.description.invitee" as const
|
||||
return "workspace.referral.reward.description.inviter" as const
|
||||
}
|
||||
|
||||
function rewardActionKey(reward: GoReferralReward, hasActiveGo: boolean) {
|
||||
if (reward.status === "applied") return "workspace.referral.reward.action.applied" as const
|
||||
if (reward.status === "pending" || !hasActiveGo) return "workspace.referral.reward.action.subscribeUnlock" as const
|
||||
return "workspace.referral.reward.action.view" as const
|
||||
}
|
||||
|
||||
function CopyInviteLink(props: { summary: GoReferralSummary }) {
|
||||
const i18n = useI18n()
|
||||
const [copied, setCopied] = createSignal(false)
|
||||
const event = getRequestEvent()
|
||||
const origin = event
|
||||
? new URL(event.request.url).origin
|
||||
: typeof window === "object"
|
||||
? window.location.origin
|
||||
: undefined
|
||||
const inviteUrl = createMemo(() => {
|
||||
const path = `/go?ref=${props.summary.referralCode}`
|
||||
if (!origin) return path
|
||||
return new URL(path, origin).toString()
|
||||
})
|
||||
|
||||
async function copy() {
|
||||
if (typeof navigator !== "object") return
|
||||
await navigator.clipboard.writeText(inviteUrl())
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 1600)
|
||||
}
|
||||
|
||||
return (
|
||||
<div data-slot="invite-link-box">
|
||||
<div>
|
||||
<code title={inviteUrl()}>{inviteUrl()}</code>
|
||||
<button type="button" onClick={copy}>
|
||||
<Show
|
||||
when={copied()}
|
||||
fallback={
|
||||
<>
|
||||
<IconCopy style={{ width: "16px", height: "16px" }} /> {i18n.t("workspace.referral.copyLink")}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<IconCheck style={{ width: "16px", height: "16px" }} /> {i18n.t("workspace.referral.copied")}
|
||||
</Show>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function GoReferralSection(props: {
|
||||
workspaceID: string
|
||||
summary: GoReferralSummary
|
||||
lite: GoLiteSubscription | undefined
|
||||
}) {
|
||||
const i18n = useI18n()
|
||||
const language = useLanguage()
|
||||
const apply = useAction(applyGoReferralReward)
|
||||
const submission = useSubmission(applyGoReferralReward)
|
||||
const [selected, setSelected] = createSignal<GoReferralReward>()
|
||||
const [preview, setPreview] = createSignal<GoReferralUsagePreview | null>()
|
||||
const displayPreview = createMemo(() => {
|
||||
const loaded = preview()
|
||||
if (loaded) return loaded
|
||||
const current = props.lite
|
||||
if (!current) return emptyUsagePreview
|
||||
return {
|
||||
rollingUsage: currentUsagePreview(current.rollingUsage),
|
||||
weeklyUsage: currentUsagePreview(current.weeklyUsage),
|
||||
monthlyUsage: currentUsagePreview(current.monthlyUsage),
|
||||
} satisfies GoReferralUsagePreview
|
||||
})
|
||||
createEffect(() => {
|
||||
const reward = selected()
|
||||
if (!reward) {
|
||||
setPreview(undefined)
|
||||
return
|
||||
}
|
||||
|
||||
const request = { cancelled: false }
|
||||
setPreview(undefined)
|
||||
queryGoReferralUsagePreview(props.workspaceID, reward.id).then((result) => {
|
||||
if (request.cancelled) return
|
||||
setPreview(result)
|
||||
})
|
||||
onCleanup(() => {
|
||||
request.cancelled = true
|
||||
})
|
||||
})
|
||||
|
||||
async function onApply() {
|
||||
const reward = selected()
|
||||
if (!reward) return
|
||||
await apply(props.workspaceID, reward.id)
|
||||
setSelected(undefined)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Show when={props.lite || props.summary.hasReferral}>
|
||||
<section data-component="go-referral-section">
|
||||
<Show when={props.lite}>
|
||||
<div data-slot="section-title">
|
||||
<h2>{i18n.t("workspace.referral.overview.title")}</h2>
|
||||
<p>{i18n.t("workspace.referral.overview.subtitle")}</p>
|
||||
</div>
|
||||
<div data-component="go-referral-overview">
|
||||
<CopyInviteLink summary={props.summary} />
|
||||
<div data-slot="instructions">
|
||||
<ol>
|
||||
<li>{i18n.t("workspace.referral.instructions.share")}</li>
|
||||
<li>{i18n.t("workspace.referral.instructions.subscribe")}</li>
|
||||
<li>{i18n.t("workspace.referral.instructions.claim")}</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={props.summary.hasReferral}>
|
||||
<div data-slot="section-title">
|
||||
<h2>{i18n.t("workspace.referral.rewards.title")}</h2>
|
||||
<p>{i18n.t("workspace.referral.rewards.description")}</p>
|
||||
</div>
|
||||
<div data-slot="referrals-table">
|
||||
<table data-slot="referrals-table-element">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{i18n.t("workspace.referral.table.reward")}</th>
|
||||
<th>{i18n.t("workspace.referral.table.referral")}</th>
|
||||
<th>{i18n.t("workspace.referral.table.date")}</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<For each={props.summary.rewards}>
|
||||
{(reward) => {
|
||||
const earnedAt = () => formatDate(reward.timeCreated, language.tag(language.locale()))
|
||||
return (
|
||||
<tr data-status={reward.status} data-source={reward.source}>
|
||||
<td data-slot="referral-amount">{formatCurrency(reward.amount)}</td>
|
||||
<td data-slot="referral-source">
|
||||
{i18n.t(rewardDescriptionKey(reward.source), { email: reward.email ?? "" })}
|
||||
</td>
|
||||
<td data-slot="referral-date" title={earnedAt()}>
|
||||
{earnedAt()}
|
||||
</td>
|
||||
<td data-slot="referral-action">
|
||||
<button
|
||||
type="button"
|
||||
disabled={reward.status !== "available" || !props.lite || submission.pending}
|
||||
onClick={() => setSelected(reward)}
|
||||
>
|
||||
{i18n.t(rewardActionKey(reward, !!props.lite))}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Show>
|
||||
</section>
|
||||
</Show>
|
||||
|
||||
<Modal
|
||||
open={!!selected()}
|
||||
onClose={() => setSelected(undefined)}
|
||||
title={i18n.t("workspace.referral.apply.confirmTitle")}
|
||||
>
|
||||
<div data-component="go-credit-confirm">
|
||||
<p>
|
||||
{i18n.t("workspace.referral.apply.confirmBody", {
|
||||
amount: formatCurrency(selected()?.amount ?? 0),
|
||||
})}
|
||||
</p>
|
||||
<GoReferralUsagePreview preview={displayPreview()} />
|
||||
<div data-slot="modal-actions">
|
||||
<button type="button" onClick={() => setSelected(undefined)}>
|
||||
{i18n.t("common.cancel")}
|
||||
</button>
|
||||
<button type="button" data-color="primary" disabled={submission.pending} onClick={onApply}>
|
||||
{submission.pending ? i18n.t("workspace.lite.loading") : i18n.t("workspace.referral.apply.confirmAction")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function GoReferralUsagePreview(props: { preview: GoReferralUsagePreview }) {
|
||||
const i18n = useI18n()
|
||||
|
||||
return (
|
||||
<div data-slot="usage-preview">
|
||||
<GoReferralUsagePreviewRow
|
||||
label={i18n.t("workspace.lite.subscription.rollingUsage")}
|
||||
usage={props.preview.rollingUsage}
|
||||
/>
|
||||
<GoReferralUsagePreviewRow
|
||||
label={i18n.t("workspace.lite.subscription.weeklyUsage")}
|
||||
usage={props.preview.weeklyUsage}
|
||||
/>
|
||||
<GoReferralUsagePreviewRow
|
||||
label={i18n.t("workspace.lite.subscription.monthlyUsage")}
|
||||
usage={props.preview.monthlyUsage}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function GoReferralUsagePreviewRow(props: { label: string; usage: GoReferralUsagePreviewItem }) {
|
||||
const i18n = useI18n()
|
||||
|
||||
return (
|
||||
<div data-slot="usage-preview-item">
|
||||
<div data-slot="usage-preview-header">
|
||||
<span data-slot="usage-preview-label">{props.label}</span>
|
||||
<span data-slot="usage-preview-value">
|
||||
<span>{props.usage.beforePercent}%</span>
|
||||
<span aria-hidden="true">-></span>
|
||||
<span data-slot="usage-preview-after-value">{props.usage.afterPercent}%</span>
|
||||
</span>
|
||||
</div>
|
||||
<div data-slot="usage-preview-progress">
|
||||
<div data-slot="usage-preview-before" style={{ width: `${props.usage.beforePercent}%` }} />
|
||||
<div data-slot="usage-preview-after" style={{ width: `${props.usage.afterPercent}%` }} />
|
||||
</div>
|
||||
<span data-slot="usage-preview-reset">
|
||||
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
|
||||
{formatResetTime(props.usage.resetInSec, i18n, liteResetTimeKeys)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -55,6 +55,61 @@
|
||||
@media (prefers-color-scheme: dark) {
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--border-radius-sm);
|
||||
background-color: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
font-size: var(--font-size-sm);
|
||||
font-family: var(--font-sans);
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background-color: var(--color-surface-hover);
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
|
||||
&:active:not(:disabled) {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
&[data-color="primary"] {
|
||||
background-color: var(--color-primary);
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary-text);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background-color: var(--color-primary-hover);
|
||||
border-color: var(--color-primary-hover);
|
||||
}
|
||||
}
|
||||
|
||||
&[data-color="ghost"] {
|
||||
background-color: transparent;
|
||||
border-color: transparent;
|
||||
color: var(--color-text-muted);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background-color: var(--color-surface-hover);
|
||||
border-color: var(--color-border);
|
||||
color: var(--color-text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="title"] {
|
||||
@@ -64,4 +119,16 @@
|
||||
color: var(--color-text);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
[data-slot="content"][data-variant="black"] {
|
||||
background-color: #000;
|
||||
border-color: rgba(255, 255, 255, 0.17);
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-family: var(--font-mono);
|
||||
|
||||
[data-slot="title"] {
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Dialog as Kobalte } from "@kobalte/core/dialog"
|
||||
import { JSX, Show } from "solid-js"
|
||||
import "./modal.css"
|
||||
|
||||
@@ -5,20 +6,41 @@ interface ModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
title?: string
|
||||
variant?: "black"
|
||||
children: JSX.Element
|
||||
}
|
||||
|
||||
export function Modal(props: ModalProps) {
|
||||
return (
|
||||
<Show when={props.open}>
|
||||
<div data-component="modal" data-slot="overlay" onClick={props.onClose}>
|
||||
<div data-slot="content" onClick={(e) => e.stopPropagation()}>
|
||||
<Show when={props.title}>
|
||||
<h2 data-slot="title">{props.title}</h2>
|
||||
</Show>
|
||||
{props.children}
|
||||
</div>
|
||||
</div>
|
||||
<Kobalte
|
||||
modal
|
||||
open={props.open}
|
||||
preventScroll={false}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) props.onClose()
|
||||
}}
|
||||
>
|
||||
<Kobalte.Portal>
|
||||
<Kobalte.Overlay data-component="modal" data-slot="overlay" onClick={props.onClose}>
|
||||
<Kobalte.Content
|
||||
data-slot="content"
|
||||
data-variant={props.variant}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onOpenAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
const target = e.currentTarget as HTMLElement | null
|
||||
target?.focus({ preventScroll: true })
|
||||
}}
|
||||
>
|
||||
<Show when={props.title}>
|
||||
<Kobalte.Title data-slot="title">{props.title}</Kobalte.Title>
|
||||
</Show>
|
||||
{props.children}
|
||||
</Kobalte.Content>
|
||||
</Kobalte.Overlay>
|
||||
</Kobalte.Portal>
|
||||
</Kobalte>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -660,6 +660,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "طرق دفع أخرى",
|
||||
"workspace.lite.promo.selectMethod": "اختر طريقة الدفع",
|
||||
|
||||
"workspace.referral.copyLink": "نسخ الرابط",
|
||||
"workspace.referral.copied": "تم النسخ",
|
||||
"workspace.referral.overview.title": "ادعُ أصدقاءك",
|
||||
"workspace.referral.overview.subtitle": "احصل على $5 عند اشتراك صديق. وسيحصل هو أيضًا على $5.",
|
||||
"workspace.referral.instructions.share": "شارك رابط الإحالة الخاص بك",
|
||||
"workspace.referral.instructions.subscribe": "ينضم صديقك ويشترك في Go",
|
||||
"workspace.referral.instructions.claim": "تحصلان كلاكما على رصيد استخدام بقيمة $5 لتطبيقه على حدود استخدام Go",
|
||||
"workspace.referral.rewards.title": "مكافآت الإحالة",
|
||||
"workspace.referral.rewards.description": "طبّق أرصدة الإحالة المتاحة على استخدامك لـ Go.",
|
||||
"workspace.referral.rewards.subtitle": "تم تطبيق {{applied}} / {{total}} من المكافآت.",
|
||||
"workspace.referral.rewards.empty": "لا توجد مكافآت إحالة بعد.",
|
||||
"workspace.referral.table.reward": "المكافأة",
|
||||
"workspace.referral.table.referral": "الوصف",
|
||||
"workspace.referral.table.date": "التاريخ",
|
||||
"workspace.referral.reward.description.inviter": "تمت دعوة {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "تمت دعوتك بواسطة {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "اشترك لإلغاء القفل",
|
||||
"workspace.referral.reward.action.view": "عرض المكافأة",
|
||||
"workspace.referral.reward.action.applied": "تم تطبيق المكافأة",
|
||||
"workspace.referral.reward.source.pendingInviter": "بانتظار اشتراكه",
|
||||
"workspace.referral.reward.source.pendingInvitee": "اشترك لإلغاء قفل المكافأة",
|
||||
"workspace.referral.reward.source.available": "المكافأة جاهزة للتطبيق",
|
||||
"workspace.referral.reward.source.applied": "تم تطبيق المكافأة",
|
||||
"workspace.referral.reward.status.applied": "تم تطبيق المكافأة",
|
||||
"workspace.referral.reward.status.pendingInviter": "اشترك لإلغاء القفل",
|
||||
"workspace.referral.reward.status.pendingInvitee": "اشترك لإلغاء القفل",
|
||||
"workspace.referral.apply.noGo": "اشترك لإلغاء القفل",
|
||||
"workspace.referral.apply.preview": "عرض المكافأة",
|
||||
"workspace.referral.apply.action": "تطبيق",
|
||||
"workspace.referral.apply.confirmTitle": "تطبيق المكافأة",
|
||||
"workspace.referral.apply.confirmBody": "طبِّق {{amount}} لتقليل الاستخدام الحالي في مساحة العمل هذه.",
|
||||
"workspace.referral.apply.confirmAction": "تطبيق",
|
||||
|
||||
"download.title": "OpenCode | تنزيل",
|
||||
"download.meta.description": "نزّل OpenCode لـ macOS، Windows، وLinux",
|
||||
"download.hero.title": "تنزيل OpenCode",
|
||||
|
||||
@@ -670,6 +670,40 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Outros métodos de pagamento",
|
||||
"workspace.lite.promo.selectMethod": "Selecionar método de pagamento",
|
||||
|
||||
"workspace.referral.copyLink": "Copiar link",
|
||||
"workspace.referral.copied": "Copiado",
|
||||
"workspace.referral.overview.title": "Convide amigos",
|
||||
"workspace.referral.overview.subtitle": "Ganhe $5 quando um amigo assinar. Ele também ganha $5.",
|
||||
"workspace.referral.instructions.share": "Compartilhe seu link de indicação",
|
||||
"workspace.referral.instructions.subscribe": "Seu amigo entra e assina o Go",
|
||||
"workspace.referral.instructions.claim":
|
||||
"Vocês dois ganham um crédito de uso de $5 para aplicar aos seus limites de uso do Go",
|
||||
"workspace.referral.rewards.title": "Recompensas de indicação",
|
||||
"workspace.referral.rewards.description": "Aplique os créditos de indicação disponíveis no seu uso do Go.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} recompensas aplicadas.",
|
||||
"workspace.referral.rewards.empty": "Ainda não há recompensas de indicação.",
|
||||
"workspace.referral.table.reward": "Recompensa",
|
||||
"workspace.referral.table.referral": "Descrição",
|
||||
"workspace.referral.table.date": "Data",
|
||||
"workspace.referral.reward.description.inviter": "Convidou {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Convidado por {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Assine para desbloquear",
|
||||
"workspace.referral.reward.action.view": "Ver recompensa",
|
||||
"workspace.referral.reward.action.applied": "Recompensa aplicada",
|
||||
"workspace.referral.reward.source.pendingInviter": "Aguardando ele assinar",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Assine para desbloquear a recompensa",
|
||||
"workspace.referral.reward.source.available": "Recompensa pronta para usar",
|
||||
"workspace.referral.reward.source.applied": "Recompensa aplicada",
|
||||
"workspace.referral.reward.status.applied": "Recompensa aplicada",
|
||||
"workspace.referral.reward.status.pendingInviter": "Assine para desbloquear",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Assine para desbloquear",
|
||||
"workspace.referral.apply.noGo": "Assine para desbloquear",
|
||||
"workspace.referral.apply.preview": "Ver recompensa",
|
||||
"workspace.referral.apply.action": "Aplicar",
|
||||
"workspace.referral.apply.confirmTitle": "Aplicar recompensa",
|
||||
"workspace.referral.apply.confirmBody": "Aplique {{amount}} para reduzir o uso atual deste workspace.",
|
||||
"workspace.referral.apply.confirmAction": "Aplicar",
|
||||
|
||||
"download.title": "OpenCode | Baixar",
|
||||
"download.meta.description": "Baixe o OpenCode para macOS, Windows e Linux",
|
||||
"download.hero.title": "Baixar OpenCode",
|
||||
|
||||
@@ -666,6 +666,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Andre betalingsmetoder",
|
||||
"workspace.lite.promo.selectMethod": "Vælg betalingsmetode",
|
||||
|
||||
"workspace.referral.copyLink": "Kopiér link",
|
||||
"workspace.referral.copied": "Kopieret",
|
||||
"workspace.referral.overview.title": "Inviter venner",
|
||||
"workspace.referral.overview.subtitle": "Få $5, når en ven abonnerer. De får også $5.",
|
||||
"workspace.referral.instructions.share": "Del dit henvisningslink",
|
||||
"workspace.referral.instructions.subscribe": "Din ven tilmelder sig og abonnerer på Go",
|
||||
"workspace.referral.instructions.claim": "I får begge $5 i forbrugskredit til at bruge på jeres Go-forbrugsgrænser",
|
||||
"workspace.referral.rewards.title": "Henvisningsbelønninger",
|
||||
"workspace.referral.rewards.description": "Brug tilgængelige henvisningskreditter på dit Go-forbrug.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} belønninger brugt.",
|
||||
"workspace.referral.rewards.empty": "Ingen henvisningsbelønninger endnu.",
|
||||
"workspace.referral.table.reward": "Belønning",
|
||||
"workspace.referral.table.referral": "Beskrivelse",
|
||||
"workspace.referral.table.date": "Dato",
|
||||
"workspace.referral.reward.description.inviter": "Inviterede {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Inviteret af {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Abonner for at låse op",
|
||||
"workspace.referral.reward.action.view": "Vis belønning",
|
||||
"workspace.referral.reward.action.applied": "Belønning brugt",
|
||||
"workspace.referral.reward.source.pendingInviter": "Venter på, at de abonnerer",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Abonner for at låse belønningen op",
|
||||
"workspace.referral.reward.source.available": "Belønning klar til brug",
|
||||
"workspace.referral.reward.source.applied": "Belønning brugt",
|
||||
"workspace.referral.reward.status.applied": "Belønning brugt",
|
||||
"workspace.referral.reward.status.pendingInviter": "Abonner for at låse op",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Abonner for at låse op",
|
||||
"workspace.referral.apply.noGo": "Abonner for at låse op",
|
||||
"workspace.referral.apply.preview": "Vis belønning",
|
||||
"workspace.referral.apply.action": "Brug",
|
||||
"workspace.referral.apply.confirmTitle": "Brug belønning",
|
||||
"workspace.referral.apply.confirmBody": "Brug {{amount}} til at reducere dette workspaces nuværende forbrug.",
|
||||
"workspace.referral.apply.confirmAction": "Brug",
|
||||
|
||||
"download.title": "OpenCode | Download",
|
||||
"download.meta.description": "Download OpenCode til macOS, Windows og Linux",
|
||||
"download.hero.title": "Download OpenCode",
|
||||
|
||||
@@ -669,6 +669,41 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Andere Zahlungsmethoden",
|
||||
"workspace.lite.promo.selectMethod": "Zahlungsmethode auswählen",
|
||||
|
||||
"workspace.referral.copyLink": "Link kopieren",
|
||||
"workspace.referral.copied": "Kopiert",
|
||||
"workspace.referral.overview.title": "Freunde einladen",
|
||||
"workspace.referral.overview.subtitle": "Erhalte $5, wenn ein Freund abonniert. Er bekommt ebenfalls $5.",
|
||||
"workspace.referral.instructions.share": "Teile deinen Empfehlungslink",
|
||||
"workspace.referral.instructions.subscribe": "Dein Freund tritt bei und abonniert Go",
|
||||
"workspace.referral.instructions.claim":
|
||||
"Ihr erhaltet beide ein Nutzungsguthaben von $5, das ihr auf eure Go-Nutzungslimits anrechnen könnt",
|
||||
"workspace.referral.rewards.title": "Empfehlungsbelohnungen",
|
||||
"workspace.referral.rewards.description": "Verfügbare Empfehlungsguthaben auf deine Go-Nutzung anwenden.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} Belohnungen eingelöst.",
|
||||
"workspace.referral.rewards.empty": "Noch keine Empfehlungsbelohnungen.",
|
||||
"workspace.referral.table.reward": "Belohnung",
|
||||
"workspace.referral.table.referral": "Beschreibung",
|
||||
"workspace.referral.table.date": "Datum",
|
||||
"workspace.referral.reward.description.inviter": "{{email}} eingeladen",
|
||||
"workspace.referral.reward.description.invitee": "Eingeladen von {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Abonnieren zum Freischalten",
|
||||
"workspace.referral.reward.action.view": "Belohnung ansehen",
|
||||
"workspace.referral.reward.action.applied": "Belohnung eingelöst",
|
||||
"workspace.referral.reward.source.pendingInviter": "Warten auf das Abo des Freundes",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Abonnieren, um Belohnung freizuschalten",
|
||||
"workspace.referral.reward.source.available": "Belohnung kann eingelöst werden",
|
||||
"workspace.referral.reward.source.applied": "Belohnung eingelöst",
|
||||
"workspace.referral.reward.status.applied": "Belohnung eingelöst",
|
||||
"workspace.referral.reward.status.pendingInviter": "Abonnieren zum Freischalten",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Abonnieren zum Freischalten",
|
||||
"workspace.referral.apply.noGo": "Abonnieren zum Freischalten",
|
||||
"workspace.referral.apply.preview": "Belohnung ansehen",
|
||||
"workspace.referral.apply.action": "Einlösen",
|
||||
"workspace.referral.apply.confirmTitle": "Belohnung einlösen",
|
||||
"workspace.referral.apply.confirmBody":
|
||||
"Löse {{amount}} ein, um die aktuelle Nutzung dieses Workspace zu reduzieren.",
|
||||
"workspace.referral.apply.confirmAction": "Einlösen",
|
||||
|
||||
"download.title": "OpenCode | Download",
|
||||
"download.meta.description": "Lade OpenCode für macOS, Windows und Linux herunter",
|
||||
"download.hero.title": "OpenCode herunterladen",
|
||||
|
||||
@@ -662,6 +662,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Other payment methods",
|
||||
"workspace.lite.promo.selectMethod": "Select payment method",
|
||||
|
||||
"workspace.referral.copyLink": "Copy Link",
|
||||
"workspace.referral.copied": "Copied",
|
||||
"workspace.referral.overview.title": "Invite friends",
|
||||
"workspace.referral.overview.subtitle": "Earn $5 when a friend subscribes. They’ll get $5 too.",
|
||||
"workspace.referral.instructions.share": "Share your referral link",
|
||||
"workspace.referral.instructions.subscribe": "Your friend joins and subscribes to Go",
|
||||
"workspace.referral.instructions.claim": "You both get a $5 usage credit to apply toward your Go usage limits",
|
||||
"workspace.referral.rewards.title": "Referral rewards",
|
||||
"workspace.referral.rewards.description": "Apply available referral credits toward your Go usage.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} rewards applied.",
|
||||
"workspace.referral.rewards.empty": "No referral rewards yet.",
|
||||
"workspace.referral.table.reward": "Reward",
|
||||
"workspace.referral.table.referral": "Description",
|
||||
"workspace.referral.table.date": "Date",
|
||||
"workspace.referral.reward.description.inviter": "Invited {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Invited by {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Subscribe to unlock",
|
||||
"workspace.referral.reward.action.view": "View Reward",
|
||||
"workspace.referral.reward.action.applied": "Reward Applied",
|
||||
"workspace.referral.reward.source.pendingInviter": "Waiting for them to subscribe",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Subscribe to unlock reward",
|
||||
"workspace.referral.reward.source.available": "Reward ready to apply",
|
||||
"workspace.referral.reward.source.applied": "Reward applied",
|
||||
"workspace.referral.reward.status.applied": "Reward Applied",
|
||||
"workspace.referral.reward.status.pendingInviter": "Subscribe to unlock",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Subscribe to unlock",
|
||||
"workspace.referral.apply.noGo": "Subscribe to unlock",
|
||||
"workspace.referral.apply.preview": "View Reward",
|
||||
"workspace.referral.apply.action": "Apply",
|
||||
"workspace.referral.apply.confirmTitle": "Apply reward",
|
||||
"workspace.referral.apply.confirmBody": "Apply {{amount}} to reduce this workspace's current usage.",
|
||||
"workspace.referral.apply.confirmAction": "Apply",
|
||||
|
||||
"download.title": "OpenCode | Download",
|
||||
"download.meta.description": "Download OpenCode for macOS, Windows, and Linux",
|
||||
"download.hero.title": "Download OpenCode",
|
||||
|
||||
@@ -670,6 +670,40 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Otros métodos de pago",
|
||||
"workspace.lite.promo.selectMethod": "Seleccionar método de pago",
|
||||
|
||||
"workspace.referral.copyLink": "Copiar enlace",
|
||||
"workspace.referral.copied": "Copiado",
|
||||
"workspace.referral.overview.title": "Invita amigos",
|
||||
"workspace.referral.overview.subtitle": "Gana $5 cuando un amigo se suscriba. Él también recibirá $5.",
|
||||
"workspace.referral.instructions.share": "Comparte tu enlace de referido",
|
||||
"workspace.referral.instructions.subscribe": "Tu amigo se une y se suscribe a Go",
|
||||
"workspace.referral.instructions.claim":
|
||||
"Ambos reciben un crédito de uso de $5 para aplicar a sus límites de uso de Go",
|
||||
"workspace.referral.rewards.title": "Recompensas por referidos",
|
||||
"workspace.referral.rewards.description": "Aplica los créditos por referidos disponibles a tu uso de Go.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} recompensas aplicadas.",
|
||||
"workspace.referral.rewards.empty": "Aún no hay recompensas por referidos.",
|
||||
"workspace.referral.table.reward": "Recompensa",
|
||||
"workspace.referral.table.referral": "Descripción",
|
||||
"workspace.referral.table.date": "Fecha",
|
||||
"workspace.referral.reward.description.inviter": "Invitaste a {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Invitado por {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Suscríbete para desbloquear",
|
||||
"workspace.referral.reward.action.view": "Ver recompensa",
|
||||
"workspace.referral.reward.action.applied": "Recompensa aplicada",
|
||||
"workspace.referral.reward.source.pendingInviter": "Esperando a que se suscriba",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Suscríbete para desbloquear la recompensa",
|
||||
"workspace.referral.reward.source.available": "Recompensa lista para aplicar",
|
||||
"workspace.referral.reward.source.applied": "Recompensa aplicada",
|
||||
"workspace.referral.reward.status.applied": "Recompensa aplicada",
|
||||
"workspace.referral.reward.status.pendingInviter": "Suscríbete para desbloquear",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Suscríbete para desbloquear",
|
||||
"workspace.referral.apply.noGo": "Suscríbete para desbloquear",
|
||||
"workspace.referral.apply.preview": "Ver recompensa",
|
||||
"workspace.referral.apply.action": "Aplicar",
|
||||
"workspace.referral.apply.confirmTitle": "Aplicar recompensa",
|
||||
"workspace.referral.apply.confirmBody": "Aplica {{amount}} para reducir el uso actual de este workspace.",
|
||||
"workspace.referral.apply.confirmAction": "Aplicar",
|
||||
|
||||
"download.title": "OpenCode | Descargar",
|
||||
"download.meta.description": "Descarga OpenCode para macOS, Windows y Linux",
|
||||
"download.hero.title": "Descargar OpenCode",
|
||||
|
||||
@@ -676,6 +676,41 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Autres méthodes de paiement",
|
||||
"workspace.lite.promo.selectMethod": "Sélectionner la méthode de paiement",
|
||||
|
||||
"workspace.referral.copyLink": "Copier le lien",
|
||||
"workspace.referral.copied": "Copié",
|
||||
"workspace.referral.overview.title": "Inviter des amis",
|
||||
"workspace.referral.overview.subtitle": "Gagnez $5 lorsqu'un ami s'abonne. Il recevra également $5.",
|
||||
"workspace.referral.instructions.share": "Partagez votre lien de parrainage",
|
||||
"workspace.referral.instructions.subscribe": "Votre ami rejoint et s'abonne à Go",
|
||||
"workspace.referral.instructions.claim":
|
||||
"Vous recevez tous les deux un crédit d'utilisation de $5 à appliquer à vos limites d'utilisation Go",
|
||||
"workspace.referral.rewards.title": "Récompenses de parrainage",
|
||||
"workspace.referral.rewards.description":
|
||||
"Utilisez les crédits de parrainage disponibles pour votre utilisation de Go.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} récompenses utilisées.",
|
||||
"workspace.referral.rewards.empty": "Aucune récompense de parrainage pour l'instant.",
|
||||
"workspace.referral.table.reward": "Récompense",
|
||||
"workspace.referral.table.referral": "Description",
|
||||
"workspace.referral.table.date": "Date",
|
||||
"workspace.referral.reward.description.inviter": "Vous avez invité {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Invité par {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Abonnez-vous pour débloquer",
|
||||
"workspace.referral.reward.action.view": "Voir la récompense",
|
||||
"workspace.referral.reward.action.applied": "Récompense utilisée",
|
||||
"workspace.referral.reward.source.pendingInviter": "En attente de son abonnement",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Abonnez-vous pour débloquer la récompense",
|
||||
"workspace.referral.reward.source.available": "Récompense prête à utiliser",
|
||||
"workspace.referral.reward.source.applied": "Récompense utilisée",
|
||||
"workspace.referral.reward.status.applied": "Récompense utilisée",
|
||||
"workspace.referral.reward.status.pendingInviter": "Abonnez-vous pour débloquer",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Abonnez-vous pour débloquer",
|
||||
"workspace.referral.apply.noGo": "Abonnez-vous pour débloquer",
|
||||
"workspace.referral.apply.preview": "Voir la récompense",
|
||||
"workspace.referral.apply.action": "Utiliser",
|
||||
"workspace.referral.apply.confirmTitle": "Utiliser la récompense",
|
||||
"workspace.referral.apply.confirmBody": "Utilisez {{amount}} pour réduire l'utilisation actuelle de ce workspace.",
|
||||
"workspace.referral.apply.confirmAction": "Utiliser",
|
||||
|
||||
"download.title": "OpenCode | Téléchargement",
|
||||
"download.meta.description": "Téléchargez OpenCode pour macOS, Windows et Linux",
|
||||
"download.hero.title": "Télécharger OpenCode",
|
||||
|
||||
@@ -11,6 +11,7 @@ import { dict as da } from "~/i18n/da"
|
||||
import { dict as ja } from "~/i18n/ja"
|
||||
import { dict as pl } from "~/i18n/pl"
|
||||
import { dict as ru } from "~/i18n/ru"
|
||||
import { dict as uk } from "~/i18n/uk"
|
||||
import { dict as ar } from "~/i18n/ar"
|
||||
import { dict as no } from "~/i18n/no"
|
||||
import { dict as br } from "~/i18n/br"
|
||||
@@ -35,6 +36,7 @@ export function i18n(locale: Locale): Dict {
|
||||
if (locale === "ja") return { ...base, ...ja }
|
||||
if (locale === "pl") return { ...base, ...pl }
|
||||
if (locale === "ru") return { ...base, ...ru }
|
||||
if (locale === "uk") return { ...base, ...uk }
|
||||
if (locale === "ar") return { ...base, ...ar }
|
||||
if (locale === "no") return { ...base, ...no }
|
||||
if (locale === "br") return { ...base, ...br }
|
||||
|
||||
@@ -668,6 +668,40 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Altri metodi di pagamento",
|
||||
"workspace.lite.promo.selectMethod": "Seleziona metodo di pagamento",
|
||||
|
||||
"workspace.referral.copyLink": "Copia link",
|
||||
"workspace.referral.copied": "Copiato",
|
||||
"workspace.referral.overview.title": "Invita amici",
|
||||
"workspace.referral.overview.subtitle": "Guadagna $5 quando un amico si abbona. Anche lui riceverà $5.",
|
||||
"workspace.referral.instructions.share": "Condividi il tuo link di referral",
|
||||
"workspace.referral.instructions.subscribe": "Il tuo amico si iscrive e si abbona a Go",
|
||||
"workspace.referral.instructions.claim":
|
||||
"Entrambi ricevete un credito di utilizzo di $5 da applicare ai vostri limiti di utilizzo Go",
|
||||
"workspace.referral.rewards.title": "Premi referral",
|
||||
"workspace.referral.rewards.description": "Applica i crediti referral disponibili al tuo utilizzo di Go.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} premi utilizzati.",
|
||||
"workspace.referral.rewards.empty": "Nessun premio referral ancora.",
|
||||
"workspace.referral.table.reward": "Premio",
|
||||
"workspace.referral.table.referral": "Descrizione",
|
||||
"workspace.referral.table.date": "Data",
|
||||
"workspace.referral.reward.description.inviter": "Hai invitato {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Invitato da {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Abbonati per sbloccare",
|
||||
"workspace.referral.reward.action.view": "Vedi premio",
|
||||
"workspace.referral.reward.action.applied": "Premio utilizzato",
|
||||
"workspace.referral.reward.source.pendingInviter": "In attesa che si abboni",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Abbonati per sbloccare il premio",
|
||||
"workspace.referral.reward.source.available": "Premio pronto da utilizzare",
|
||||
"workspace.referral.reward.source.applied": "Premio utilizzato",
|
||||
"workspace.referral.reward.status.applied": "Premio utilizzato",
|
||||
"workspace.referral.reward.status.pendingInviter": "Abbonati per sbloccare",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Abbonati per sbloccare",
|
||||
"workspace.referral.apply.noGo": "Abbonati per sbloccare",
|
||||
"workspace.referral.apply.preview": "Vedi premio",
|
||||
"workspace.referral.apply.action": "Utilizza",
|
||||
"workspace.referral.apply.confirmTitle": "Utilizza premio",
|
||||
"workspace.referral.apply.confirmBody": "Utilizza {{amount}} per ridurre l'utilizzo attuale di questo workspace.",
|
||||
"workspace.referral.apply.confirmAction": "Utilizza",
|
||||
|
||||
"download.title": "OpenCode | Download",
|
||||
"download.meta.description": "Scarica OpenCode per macOS, Windows e Linux",
|
||||
"download.hero.title": "Scarica OpenCode",
|
||||
|
||||
@@ -668,6 +668,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "その他の支払い方法",
|
||||
"workspace.lite.promo.selectMethod": "支払い方法を選択",
|
||||
|
||||
"workspace.referral.copyLink": "リンクをコピー",
|
||||
"workspace.referral.copied": "コピーしました",
|
||||
"workspace.referral.overview.title": "友達を招待",
|
||||
"workspace.referral.overview.subtitle": "友達がサブスクライブすると $5 を獲得。友達にも $5 が付与されます。",
|
||||
"workspace.referral.instructions.share": "リファラルリンクをシェア",
|
||||
"workspace.referral.instructions.subscribe": "友達が参加して Go にサブスクライブ",
|
||||
"workspace.referral.instructions.claim": "二人とも $5 の利用クレジットを獲得し、Go の利用上限に充当できます",
|
||||
"workspace.referral.rewards.title": "リファラル特典",
|
||||
"workspace.referral.rewards.description": "利用可能なリファラルクレジットを Go の利用に適用します。",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} 件の特典を適用済み。",
|
||||
"workspace.referral.rewards.empty": "リファラル特典はまだありません。",
|
||||
"workspace.referral.table.reward": "特典",
|
||||
"workspace.referral.table.referral": "説明",
|
||||
"workspace.referral.table.date": "日付",
|
||||
"workspace.referral.reward.description.inviter": "{{email}} を招待しました",
|
||||
"workspace.referral.reward.description.invitee": "{{email}} に招待されました",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "サブスクライブしてアンロック",
|
||||
"workspace.referral.reward.action.view": "特典を表示",
|
||||
"workspace.referral.reward.action.applied": "特典を適用済み",
|
||||
"workspace.referral.reward.source.pendingInviter": "友達のサブスクライブ待ち",
|
||||
"workspace.referral.reward.source.pendingInvitee": "サブスクライブして特典をアンロック",
|
||||
"workspace.referral.reward.source.available": "特典は適用可能です",
|
||||
"workspace.referral.reward.source.applied": "特典を適用済み",
|
||||
"workspace.referral.reward.status.applied": "特典を適用済み",
|
||||
"workspace.referral.reward.status.pendingInviter": "サブスクライブしてアンロック",
|
||||
"workspace.referral.reward.status.pendingInvitee": "サブスクライブしてアンロック",
|
||||
"workspace.referral.apply.noGo": "サブスクライブしてアンロック",
|
||||
"workspace.referral.apply.preview": "特典を表示",
|
||||
"workspace.referral.apply.action": "適用",
|
||||
"workspace.referral.apply.confirmTitle": "特典を適用",
|
||||
"workspace.referral.apply.confirmBody": "{{amount}} を適用して、このワークスペースの現在の使用量を減らします。",
|
||||
"workspace.referral.apply.confirmAction": "適用",
|
||||
|
||||
"download.title": "OpenCode | ダウンロード",
|
||||
"download.meta.description": "OpenCode を macOS、Windows、Linux 向けにダウンロード",
|
||||
"download.hero.title": "OpenCode をダウンロード",
|
||||
|
||||
@@ -660,6 +660,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "기타 결제 수단",
|
||||
"workspace.lite.promo.selectMethod": "결제 수단 선택",
|
||||
|
||||
"workspace.referral.copyLink": "링크 복사",
|
||||
"workspace.referral.copied": "복사됨",
|
||||
"workspace.referral.overview.title": "친구 초대",
|
||||
"workspace.referral.overview.subtitle": "친구가 구독하면 $5를 받으세요. 친구도 $5를 받습니다.",
|
||||
"workspace.referral.instructions.share": "추천 링크 공유",
|
||||
"workspace.referral.instructions.subscribe": "친구가 가입하고 Go를 구독",
|
||||
"workspace.referral.instructions.claim": "두 분 모두 $5 사용 크레딧을 받아 Go 사용 한도에 적용할 수 있습니다",
|
||||
"workspace.referral.rewards.title": "추천 보상",
|
||||
"workspace.referral.rewards.description": "사용 가능한 추천 크레딧을 Go 사용량에 적용합니다.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}}개 보상 사용됨.",
|
||||
"workspace.referral.rewards.empty": "아직 추천 보상이 없습니다.",
|
||||
"workspace.referral.table.reward": "보상",
|
||||
"workspace.referral.table.referral": "설명",
|
||||
"workspace.referral.table.date": "날짜",
|
||||
"workspace.referral.reward.description.inviter": "{{email}} 초대됨",
|
||||
"workspace.referral.reward.description.invitee": "{{email}}님이 초대",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "구독하여 잠금 해제",
|
||||
"workspace.referral.reward.action.view": "보상 보기",
|
||||
"workspace.referral.reward.action.applied": "보상 사용됨",
|
||||
"workspace.referral.reward.source.pendingInviter": "친구의 구독을 기다리는 중",
|
||||
"workspace.referral.reward.source.pendingInvitee": "구독하여 보상 잠금 해제",
|
||||
"workspace.referral.reward.source.available": "보상 사용 가능",
|
||||
"workspace.referral.reward.source.applied": "보상 사용됨",
|
||||
"workspace.referral.reward.status.applied": "보상 사용됨",
|
||||
"workspace.referral.reward.status.pendingInviter": "구독하여 잠금 해제",
|
||||
"workspace.referral.reward.status.pendingInvitee": "구독하여 잠금 해제",
|
||||
"workspace.referral.apply.noGo": "구독하여 잠금 해제",
|
||||
"workspace.referral.apply.preview": "보상 보기",
|
||||
"workspace.referral.apply.action": "사용",
|
||||
"workspace.referral.apply.confirmTitle": "보상 사용",
|
||||
"workspace.referral.apply.confirmBody": "{{amount}}를 사용하여 이 워크스페이스의 현재 사용량을 줄입니다.",
|
||||
"workspace.referral.apply.confirmAction": "사용",
|
||||
|
||||
"download.title": "OpenCode | 다운로드",
|
||||
"download.meta.description": "macOS, Windows, Linux용 OpenCode 다운로드",
|
||||
"download.hero.title": "OpenCode 다운로드",
|
||||
|
||||
@@ -667,6 +667,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Andre betalingsmetoder",
|
||||
"workspace.lite.promo.selectMethod": "Velg betalingsmetode",
|
||||
|
||||
"workspace.referral.copyLink": "Kopier lenke",
|
||||
"workspace.referral.copied": "Kopiert",
|
||||
"workspace.referral.overview.title": "Inviter venner",
|
||||
"workspace.referral.overview.subtitle": "Få $5 når en venn abonnerer. De får også $5.",
|
||||
"workspace.referral.instructions.share": "Del henvisningslenken din",
|
||||
"workspace.referral.instructions.subscribe": "Vennen din blir med og abonnerer på Go",
|
||||
"workspace.referral.instructions.claim": "Dere får begge $5 i brukskreditt å bruke på Go-bruksgrensene deres",
|
||||
"workspace.referral.rewards.title": "Henvisningsbelønninger",
|
||||
"workspace.referral.rewards.description": "Bruk tilgjengelige henvisningskreditter på Go-bruken din.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} belønninger brukt.",
|
||||
"workspace.referral.rewards.empty": "Ingen henvisningsbelønninger ennå.",
|
||||
"workspace.referral.table.reward": "Belønning",
|
||||
"workspace.referral.table.referral": "Beskrivelse",
|
||||
"workspace.referral.table.date": "Dato",
|
||||
"workspace.referral.reward.description.inviter": "Inviterte {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Invitert av {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Abonner for å låse opp",
|
||||
"workspace.referral.reward.action.view": "Vis belønning",
|
||||
"workspace.referral.reward.action.applied": "Belønning brukt",
|
||||
"workspace.referral.reward.source.pendingInviter": "Venter på at de abonnerer",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Abonner for å låse opp belønningen",
|
||||
"workspace.referral.reward.source.available": "Belønning klar til bruk",
|
||||
"workspace.referral.reward.source.applied": "Belønning brukt",
|
||||
"workspace.referral.reward.status.applied": "Belønning brukt",
|
||||
"workspace.referral.reward.status.pendingInviter": "Abonner for å låse opp",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Abonner for å låse opp",
|
||||
"workspace.referral.apply.noGo": "Abonner for å låse opp",
|
||||
"workspace.referral.apply.preview": "Vis belønning",
|
||||
"workspace.referral.apply.action": "Bruk",
|
||||
"workspace.referral.apply.confirmTitle": "Bruk belønning",
|
||||
"workspace.referral.apply.confirmBody": "Bruk {{amount}} for å redusere dette workspacets nåværende forbruk.",
|
||||
"workspace.referral.apply.confirmAction": "Bruk",
|
||||
|
||||
"download.title": "OpenCode | Last ned",
|
||||
"download.meta.description": "Last ned OpenCode for macOS, Windows og Linux",
|
||||
"download.hero.title": "Last ned OpenCode",
|
||||
|
||||
@@ -668,6 +668,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Inne metody płatności",
|
||||
"workspace.lite.promo.selectMethod": "Wybierz metodę płatności",
|
||||
|
||||
"workspace.referral.copyLink": "Kopiuj link",
|
||||
"workspace.referral.copied": "Skopiowano",
|
||||
"workspace.referral.overview.title": "Zaproś znajomych",
|
||||
"workspace.referral.overview.subtitle": "Zdobądź $5, gdy znajomy się zasubskrybuje. On też dostanie $5.",
|
||||
"workspace.referral.instructions.share": "Udostępnij swój link polecający",
|
||||
"workspace.referral.instructions.subscribe": "Twój znajomy dołącza i subskrybuje Go",
|
||||
"workspace.referral.instructions.claim": "Oboje otrzymujecie kredyt $5 do wykorzystania na limity użycia Go",
|
||||
"workspace.referral.rewards.title": "Nagrody za polecenia",
|
||||
"workspace.referral.rewards.description": "Wykorzystaj dostępne środki za polecenia na swoje użycie Go.",
|
||||
"workspace.referral.rewards.subtitle": "Wykorzystano {{applied}} / {{total}} nagród.",
|
||||
"workspace.referral.rewards.empty": "Brak nagród za polecenia.",
|
||||
"workspace.referral.table.reward": "Nagroda",
|
||||
"workspace.referral.table.referral": "Opis",
|
||||
"workspace.referral.table.date": "Data",
|
||||
"workspace.referral.reward.description.inviter": "Zaproszono {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Zaproszony przez {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Subskrybuj, aby odblokować",
|
||||
"workspace.referral.reward.action.view": "Zobacz nagrodę",
|
||||
"workspace.referral.reward.action.applied": "Nagroda wykorzystana",
|
||||
"workspace.referral.reward.source.pendingInviter": "Oczekiwanie na jego subskrypcję",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Subskrybuj, aby odblokować nagrodę",
|
||||
"workspace.referral.reward.source.available": "Nagroda gotowa do wykorzystania",
|
||||
"workspace.referral.reward.source.applied": "Nagroda wykorzystana",
|
||||
"workspace.referral.reward.status.applied": "Nagroda wykorzystana",
|
||||
"workspace.referral.reward.status.pendingInviter": "Subskrybuj, aby odblokować",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Subskrybuj, aby odblokować",
|
||||
"workspace.referral.apply.noGo": "Subskrybuj, aby odblokować",
|
||||
"workspace.referral.apply.preview": "Zobacz nagrodę",
|
||||
"workspace.referral.apply.action": "Wykorzystaj",
|
||||
"workspace.referral.apply.confirmTitle": "Wykorzystaj nagrodę",
|
||||
"workspace.referral.apply.confirmBody": "Wykorzystaj {{amount}}, aby zmniejszyć aktualne użycie w tym workspace.",
|
||||
"workspace.referral.apply.confirmAction": "Wykorzystaj",
|
||||
|
||||
"download.title": "OpenCode | Pobierz",
|
||||
"download.meta.description": "Pobierz OpenCode na macOS, Windows i Linux",
|
||||
"download.hero.title": "Pobierz OpenCode",
|
||||
|
||||
@@ -674,6 +674,41 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Другие способы оплаты",
|
||||
"workspace.lite.promo.selectMethod": "Выберите способ оплаты",
|
||||
|
||||
"workspace.referral.copyLink": "Копировать ссылку",
|
||||
"workspace.referral.copied": "Скопировано",
|
||||
"workspace.referral.overview.title": "Пригласите друзей",
|
||||
"workspace.referral.overview.subtitle": "Получите $5, когда друг оформит подписку. Он тоже получит $5.",
|
||||
"workspace.referral.instructions.share": "Поделитесь своей реферальной ссылкой",
|
||||
"workspace.referral.instructions.subscribe": "Ваш друг присоединяется и оформляет подписку на Go",
|
||||
"workspace.referral.instructions.claim":
|
||||
"Вы оба получаете кредит на использование $5, который можно применить к лимитам использования Go",
|
||||
"workspace.referral.rewards.title": "Реферальные награды",
|
||||
"workspace.referral.rewards.description": "Используйте доступные реферальные кредиты для оплаты использования Go.",
|
||||
"workspace.referral.rewards.subtitle": "Использовано {{applied}} / {{total}} наград.",
|
||||
"workspace.referral.rewards.empty": "Реферальных наград пока нет.",
|
||||
"workspace.referral.table.reward": "Награда",
|
||||
"workspace.referral.table.referral": "Описание",
|
||||
"workspace.referral.table.date": "Дата",
|
||||
"workspace.referral.reward.description.inviter": "Приглашён {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "Приглашены пользователем {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Оформите подписку для разблокировки",
|
||||
"workspace.referral.reward.action.view": "Посмотреть награду",
|
||||
"workspace.referral.reward.action.applied": "Награда использована",
|
||||
"workspace.referral.reward.source.pendingInviter": "Ожидание его подписки",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Подпишитесь, чтобы разблокировать награду",
|
||||
"workspace.referral.reward.source.available": "Награда готова к применению",
|
||||
"workspace.referral.reward.source.applied": "Награда использована",
|
||||
"workspace.referral.reward.status.applied": "Награда использована",
|
||||
"workspace.referral.reward.status.pendingInviter": "Оформите подписку для разблокировки",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Оформите подписку для разблокировки",
|
||||
"workspace.referral.apply.noGo": "Оформите подписку для разблокировки",
|
||||
"workspace.referral.apply.preview": "Посмотреть награду",
|
||||
"workspace.referral.apply.action": "Применить",
|
||||
"workspace.referral.apply.confirmTitle": "Применить награду",
|
||||
"workspace.referral.apply.confirmBody":
|
||||
"Используйте {{amount}}, чтобы уменьшить текущее использование этого workspace.",
|
||||
"workspace.referral.apply.confirmAction": "Применить",
|
||||
|
||||
"download.title": "OpenCode | Скачать",
|
||||
"download.meta.description": "Скачать OpenCode для macOS, Windows и Linux",
|
||||
"download.hero.title": "Скачать OpenCode",
|
||||
|
||||
@@ -663,6 +663,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "วิธีการชำระเงินอื่นๆ",
|
||||
"workspace.lite.promo.selectMethod": "เลือกวิธีการชำระเงิน",
|
||||
|
||||
"workspace.referral.copyLink": "คัดลอกลิงก์",
|
||||
"workspace.referral.copied": "คัดลอกแล้ว",
|
||||
"workspace.referral.overview.title": "ชวนเพื่อน",
|
||||
"workspace.referral.overview.subtitle": "รับ $5 เมื่อเพื่อนสมัครสมาชิก เพื่อนก็จะได้รับ $5 เช่นกัน",
|
||||
"workspace.referral.instructions.share": "แชร์ลิงก์แนะนำของคุณ",
|
||||
"workspace.referral.instructions.subscribe": "เพื่อนของคุณเข้าร่วมและสมัครสมาชิก Go",
|
||||
"workspace.referral.instructions.claim": "คุณทั้งคู่จะได้รับเครดิตการใช้งาน $5 เพื่อใช้กับขีดจำกัดการใช้งาน Go",
|
||||
"workspace.referral.rewards.title": "รางวัลการแนะนำ",
|
||||
"workspace.referral.rewards.description": "ใช้เครดิตการแนะนำที่มีอยู่กับการใช้งาน Go ของคุณ",
|
||||
"workspace.referral.rewards.subtitle": "ใช้แล้ว {{applied}} / {{total}} รางวัล",
|
||||
"workspace.referral.rewards.empty": "ยังไม่มีรางวัลการแนะนำ",
|
||||
"workspace.referral.table.reward": "รางวัล",
|
||||
"workspace.referral.table.referral": "คำอธิบาย",
|
||||
"workspace.referral.table.date": "วันที่",
|
||||
"workspace.referral.reward.description.inviter": "เชิญ {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "ได้รับเชิญจาก {{email}}",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "สมัครสมาชิกเพื่อปลดล็อก",
|
||||
"workspace.referral.reward.action.view": "ดูรางวัล",
|
||||
"workspace.referral.reward.action.applied": "ใช้รางวัลแล้ว",
|
||||
"workspace.referral.reward.source.pendingInviter": "รอเพื่อนสมัครสมาชิก",
|
||||
"workspace.referral.reward.source.pendingInvitee": "สมัครสมาชิกเพื่อปลดล็อกรางวัล",
|
||||
"workspace.referral.reward.source.available": "รางวัลพร้อมใช้งาน",
|
||||
"workspace.referral.reward.source.applied": "ใช้รางวัลแล้ว",
|
||||
"workspace.referral.reward.status.applied": "ใช้รางวัลแล้ว",
|
||||
"workspace.referral.reward.status.pendingInviter": "สมัครสมาชิกเพื่อปลดล็อก",
|
||||
"workspace.referral.reward.status.pendingInvitee": "สมัครสมาชิกเพื่อปลดล็อก",
|
||||
"workspace.referral.apply.noGo": "สมัครสมาชิกเพื่อปลดล็อก",
|
||||
"workspace.referral.apply.preview": "ดูรางวัล",
|
||||
"workspace.referral.apply.action": "ใช้",
|
||||
"workspace.referral.apply.confirmTitle": "ใช้รางวัล",
|
||||
"workspace.referral.apply.confirmBody": "ใช้ {{amount}} เพื่อลดการใช้งานปัจจุบันของ workspace นี้",
|
||||
"workspace.referral.apply.confirmAction": "ใช้",
|
||||
|
||||
"download.title": "OpenCode | ดาวน์โหลด",
|
||||
"download.meta.description": "ดาวน์โหลด OpenCode สำหรับ macOS, Windows และ Linux",
|
||||
"download.hero.title": "ดาวน์โหลด OpenCode",
|
||||
|
||||
@@ -670,6 +670,40 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "Diğer ödeme yöntemleri",
|
||||
"workspace.lite.promo.selectMethod": "Ödeme yöntemini seçin",
|
||||
|
||||
"workspace.referral.copyLink": "Bağlantıyı Kopyala",
|
||||
"workspace.referral.copied": "Kopyalandı",
|
||||
"workspace.referral.overview.title": "Arkadaşlarını davet et",
|
||||
"workspace.referral.overview.subtitle": "Bir arkadaşın abone olduğunda $5 kazan. O da $5 alacak.",
|
||||
"workspace.referral.instructions.share": "Referans bağlantını paylaş",
|
||||
"workspace.referral.instructions.subscribe": "Arkadaşın katılır ve Go'ya abone olur",
|
||||
"workspace.referral.instructions.claim":
|
||||
"İkiniz de Go kullanım limitlerinize uygulamak için $5 kullanım kredisi alırsınız",
|
||||
"workspace.referral.rewards.title": "Davet ödülleri",
|
||||
"workspace.referral.rewards.description": "Mevcut davet kredilerini Go kullanımınıza uygulayın.",
|
||||
"workspace.referral.rewards.subtitle": "{{applied}} / {{total}} ödül kullanıldı.",
|
||||
"workspace.referral.rewards.empty": "Henüz davet ödülü yok.",
|
||||
"workspace.referral.table.reward": "Ödül",
|
||||
"workspace.referral.table.referral": "Açıklama",
|
||||
"workspace.referral.table.date": "Tarih",
|
||||
"workspace.referral.reward.description.inviter": "{{email}} davet edildi",
|
||||
"workspace.referral.reward.description.invitee": "{{email}} tarafından davet edildi",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "Kilidi açmak için abone ol",
|
||||
"workspace.referral.reward.action.view": "Ödülü Görüntüle",
|
||||
"workspace.referral.reward.action.applied": "Ödül Kullanıldı",
|
||||
"workspace.referral.reward.source.pendingInviter": "Abone olması bekleniyor",
|
||||
"workspace.referral.reward.source.pendingInvitee": "Ödülün kilidini açmak için abone ol",
|
||||
"workspace.referral.reward.source.available": "Ödül kullanıma hazır",
|
||||
"workspace.referral.reward.source.applied": "Ödül kullanıldı",
|
||||
"workspace.referral.reward.status.applied": "Ödül Kullanıldı",
|
||||
"workspace.referral.reward.status.pendingInviter": "Kilidi açmak için abone ol",
|
||||
"workspace.referral.reward.status.pendingInvitee": "Kilidi açmak için abone ol",
|
||||
"workspace.referral.apply.noGo": "Kilidi açmak için abone ol",
|
||||
"workspace.referral.apply.preview": "Ödülü Görüntüle",
|
||||
"workspace.referral.apply.action": "Kullan",
|
||||
"workspace.referral.apply.confirmTitle": "Ödülü kullan",
|
||||
"workspace.referral.apply.confirmBody": "Bu workspace'in mevcut kullanımını azaltmak için {{amount}} kullan.",
|
||||
"workspace.referral.apply.confirmAction": "Kullan",
|
||||
|
||||
"download.title": "OpenCode | İndir",
|
||||
"download.meta.description": "OpenCode'u macOS, Windows ve Linux için indirin",
|
||||
"download.hero.title": "OpenCode'u İndir",
|
||||
|
||||
@@ -0,0 +1,785 @@
|
||||
import { dict as en } from "./en"
|
||||
|
||||
export const dict = {
|
||||
...en,
|
||||
"nav.github": "GitHub",
|
||||
"nav.docs": "Документація",
|
||||
"nav.changelog": "Журнал змін",
|
||||
"nav.discord": "Discord",
|
||||
"nav.x": "X",
|
||||
"nav.enterprise": "Enterprise",
|
||||
"nav.zen": "Zen",
|
||||
"nav.login": "Увійти",
|
||||
"nav.free": "Завантажити",
|
||||
"nav.home": "Головна",
|
||||
"nav.openMenu": "Відкрити меню",
|
||||
"nav.getStartedFree": "Почати безкоштовно",
|
||||
"nav.logoAlt": "OpenCode",
|
||||
|
||||
"nav.context.copyLogo": "Копіювати логотип як SVG",
|
||||
"nav.context.copyWordmark": "Копіювати знак як SVG",
|
||||
"nav.context.brandAssets": "Бренд-матеріали",
|
||||
|
||||
"footer.github": "GitHub",
|
||||
"footer.docs": "Документація",
|
||||
"footer.changelog": "Журнал змін",
|
||||
"footer.discord": "Discord",
|
||||
"footer.x": "X",
|
||||
|
||||
"legal.brand": "Бренд",
|
||||
"legal.privacy": "Конфіденційність",
|
||||
"legal.terms": "Умови",
|
||||
|
||||
"email.title": "Дізнайтеся першими про нові продукти",
|
||||
"email.subtitle": "Приєднуйтесь до списку очікування для раннього доступу.",
|
||||
"email.placeholder": "Електронна адреса",
|
||||
"email.subscribe": "Підписатися",
|
||||
"email.success": "Майже готово! Перевірте пошту та підтвердьте адресу",
|
||||
|
||||
"notFound.title": "Не знайдено | opencode",
|
||||
"notFound.heading": "404 — Сторінку не знайдено",
|
||||
"notFound.home": "Головна",
|
||||
"notFound.docs": "Документація",
|
||||
"notFound.github": "GitHub",
|
||||
"notFound.discord": "Discord",
|
||||
"notFound.logoLightAlt": "світлий логотип opencode",
|
||||
"notFound.logoDarkAlt": "темний логотип opencode",
|
||||
|
||||
"user.logout": "Вийти",
|
||||
|
||||
"auth.callback.error.codeMissing": "Не знайдено код авторизації.",
|
||||
|
||||
"workspace.select": "Виберіть робочий простір",
|
||||
"workspace.createNew": "+ Створити новий робочий простір",
|
||||
"workspace.modal.title": "Створити новий робочий простір",
|
||||
"workspace.modal.placeholder": "Введіть назву робочого простору",
|
||||
|
||||
"common.cancel": "Скасувати",
|
||||
"common.creating": "Створення...",
|
||||
"common.create": "Створити",
|
||||
"common.contactUs": "Зв'яжіться з нами",
|
||||
|
||||
"common.videoUnsupported": "Ваш браузер не підтримує відео.",
|
||||
"common.figure": "Рис. {{n}}.",
|
||||
"common.faq": "FAQ",
|
||||
"common.learnMore": "Дізнатися більше",
|
||||
|
||||
"error.invalidPlan": "Недійсний план",
|
||||
"error.workspaceRequired": "ID робочого простору обов'язкове",
|
||||
"error.alreadySubscribed": "Цей робочий простір уже має підписку",
|
||||
"error.limitRequired": "Ліміт обов'язковий.",
|
||||
"error.monthlyLimitInvalid": "Встановіть дійсний місячний ліміт.",
|
||||
"error.workspaceNameRequired": "Назва робочого простору обов'язкова.",
|
||||
"error.nameTooLong": "Назва має містити не більше 255 символів.",
|
||||
"error.emailRequired": "Електронна адреса обов'язкова",
|
||||
"error.roleRequired": "Роль обов'язкова",
|
||||
"error.idRequired": "ID обов'язкове",
|
||||
"error.nameRequired": "Назва обов'язкова",
|
||||
"error.providerRequired": "Провайдер обов'язковий",
|
||||
"error.apiKeyRequired": "Ключ API обов'язковий",
|
||||
"error.modelRequired": "Модель обов'язкова",
|
||||
"error.reloadAmountMin": "Сума поповнення має бути щонайменше ${{amount}}",
|
||||
"error.reloadTriggerMin": "Поріг балансу має бути щонайменше ${{amount}}",
|
||||
|
||||
"app.meta.description": "OpenCode — відкритий агент для програмування.",
|
||||
|
||||
"home.title": "OpenCode | Відкритий AI-агент для кодування",
|
||||
|
||||
"temp.title": "opencode | AI-агент для кодування, створений для термінала",
|
||||
"temp.hero.title": "AI-агент для кодування, створений для термінала",
|
||||
"temp.zen": "opencode zen",
|
||||
"temp.getStarted": "Почати",
|
||||
"temp.feature.native.title": "Рідний TUI",
|
||||
"temp.feature.native.body": "Чуйний, рідний інтерфейс термінала з темами",
|
||||
"temp.feature.zen.beforeLink": "A",
|
||||
"temp.feature.zen.link": "добірка моделей",
|
||||
"temp.feature.zen.afterLink": "від opencode",
|
||||
"temp.feature.models.beforeLink": "Підтримує 75+ LLM-провайдерів через",
|
||||
"temp.feature.models.afterLink": ", включаючи локальні моделі",
|
||||
"temp.screenshot.caption": "OpenCode TUI з темою tokyonight",
|
||||
"temp.screenshot.alt": "OpenCode TUI з темою tokyonight",
|
||||
"temp.logoLightAlt": "світлий логотип opencode",
|
||||
"temp.logoDarkAlt": "темний логотип opencode",
|
||||
|
||||
"home.banner.badge": "Нове",
|
||||
"home.banner.text": "Десктопний застосунок доступний у бета-версії",
|
||||
"home.banner.platforms": "на macOS, Windows та Linux",
|
||||
"home.banner.downloadNow": "Завантажити зараз",
|
||||
"home.banner.downloadBetaNow": "Завантажити бета-версію десктопного застосунку",
|
||||
|
||||
"home.hero.title": "Відкритий AI-агент для кодування",
|
||||
"home.hero.subtitle.a": "Безкоштовні моделі включено або підключіть будь-яку модель від будь-якого провайдера,",
|
||||
"home.hero.subtitle.b": "включно з Claude, GPT, Gemini та іншими.",
|
||||
|
||||
"home.install.ariaLabel": "Параметри встановлення",
|
||||
|
||||
"home.what.title": "Що таке OpenCode?",
|
||||
"home.what.body": "OpenCode — це відкритий агент, який допомагає писати код у терміналі, IDE або на десктопі.",
|
||||
"home.what.lsp.title": "LSP увімкнено",
|
||||
"home.what.lsp.body": "Автоматично завантажує потрібні LSP для LLM",
|
||||
"home.what.multiSession.title": "Багатосесійність",
|
||||
"home.what.multiSession.body": "Запускайте кількох агентів паралельно в одному проекті",
|
||||
"home.what.shareLinks.title": "Посилання для обміну",
|
||||
"home.what.shareLinks.body": "Діліться посиланням на будь-яку сесію для обговорення або налагодження",
|
||||
"home.what.copilot.title": "GitHub Copilot",
|
||||
"home.what.copilot.body": "Увійдіть через GitHub, щоб використовувати свій обліковий запис Copilot",
|
||||
"home.what.chatgptPlus.title": "ChatGPT Plus/Pro",
|
||||
"home.what.chatgptPlus.body": "Увійдіть через OpenAI, щоб використовувати ChatGPT Plus або Pro",
|
||||
"home.what.anyModel.title": "Будь-яка модель",
|
||||
"home.what.anyModel.body": "75+ LLM-провайдерів через Models.dev, включаючи локальні моделі",
|
||||
"home.what.anyEditor.title": "Будь-який редактор",
|
||||
"home.what.anyEditor.body": "Доступний як термінальний інтерфейс, десктопний застосунок та розширення IDE",
|
||||
"home.what.readDocs": "Читати документацію",
|
||||
|
||||
"home.growth.title": "Відкритий AI-агент для кодування",
|
||||
"home.growth.body":
|
||||
"З понад <strong>{{stars}}</strong> зірками на GitHub, <strong>{{contributors}}</strong> учасниками та понад <strong>{{commits}}</strong> комітами, OpenCode використовують понад <strong>{{monthlyUsers}}</strong> розробників щомісяця.",
|
||||
"home.growth.githubStars": "Зірки GitHub",
|
||||
"home.growth.contributors": "Учасники",
|
||||
"home.growth.monthlyDevs": "Розробників на місяць",
|
||||
|
||||
"home.privacy.title": "Створено для конфіденційності",
|
||||
"home.privacy.body":
|
||||
"OpenCode не зберігає ваш код або контекстні дані, тому може працювати в середовищах з чутливими даними.",
|
||||
"home.privacy.learnMore": "Дізнатися більше про",
|
||||
"home.privacy.link": "конфіденційність",
|
||||
|
||||
"home.faq.q1": "Що таке OpenCode?",
|
||||
"home.faq.a1":
|
||||
"OpenCode — це відкритий агент, який допомагає писати та запускати код з будь-якою AI-моделлю. Доступний як термінальний інтерфейс, десктопний застосунок або розширення IDE.",
|
||||
"home.faq.q2": "Як почати користуватися OpenCode?",
|
||||
"home.faq.a2.before": "Найпростіший спосіб почати — прочитати",
|
||||
"home.faq.a2.link": "вступ",
|
||||
"home.faq.q3": "Чи потрібні додаткові AI-підписки для використання OpenCode?",
|
||||
"home.faq.a3.p1":
|
||||
"Не обов'язково, OpenCode має набір безкоштовних моделей, які можна використовувати без реєстрації.",
|
||||
"home.faq.a3.p2.beforeZen":
|
||||
"Крім цього, ви можете використовувати будь-які популярні моделі, створивши обліковий запис",
|
||||
"home.faq.a3.p2.afterZen": ".",
|
||||
"home.faq.a3.p3":
|
||||
"Хоча ми рекомендуємо Zen, OpenCode також працює з усіма популярними провайдерами, такими як OpenAI, Anthropic, xAI тощо.",
|
||||
"home.faq.a3.p4.beforeLocal": "Ви навіть можете підключити свої",
|
||||
"home.faq.a3.p4.localLink": "локальні моделі",
|
||||
"home.faq.q4": "Чи можу я використовувати свої наявні AI-підписки з OpenCode?",
|
||||
"home.faq.a4.p1":
|
||||
"Так, OpenCode підтримує підписки всіх основних провайдерів. Ви можете використовувати Claude Pro/Max, ChatGPT Plus/Pro або GitHub Copilot.",
|
||||
"home.faq.q5": "Чи можна використовувати OpenCode лише в терміналі?",
|
||||
"home.faq.a5.beforeDesktop": "Вже ні! OpenCode тепер доступний як застосунок для",
|
||||
"home.faq.a5.desktop": "десктопа",
|
||||
"home.faq.a5.and": "та",
|
||||
"home.faq.a5.web": "вебу",
|
||||
"home.faq.q6": "Скільки коштує OpenCode?",
|
||||
"home.faq.a6":
|
||||
"OpenCode є 100% безкоштовним. Він також має набір безкоштовних моделей. Додаткові витрати можливі, якщо ви підключите іншого провайдера.",
|
||||
"home.faq.q7": "А як щодо даних та конфіденційності?",
|
||||
"home.faq.a7.p1":
|
||||
"Ваші дані зберігаються лише тоді, коли ви використовуєте безкоштовні моделі або створюєте посилання для обміну.",
|
||||
"home.faq.a7.p2.beforeModels": "Дізнайтеся більше про",
|
||||
"home.faq.a7.p2.modelsLink": "наші моделі",
|
||||
"home.faq.a7.p2.and": "та",
|
||||
"home.faq.a7.p2.shareLink": "сторінки обміну",
|
||||
"home.faq.q8": "Чи є OpenCode відкритим?",
|
||||
"home.faq.a8.p1": "Так, OpenCode повністю відкритий. Вихідний код доступний публічно на",
|
||||
"home.faq.a8.p2": "під ліцензією",
|
||||
"home.faq.a8.mitLicense": "MIT License",
|
||||
"home.faq.a8.p3":
|
||||
", тобто кожен може використовувати, змінювати або сприяти його розвитку. Будь-хто зі спільноти може створювати issues, надсилати pull request'и та розширювати функціональність.",
|
||||
|
||||
"home.zenCta.title": "Отримайте доступ до надійних оптимізованих моделей для агентів кодування",
|
||||
"home.zenCta.body":
|
||||
"Zen дає доступ до добірки AI-моделей, які OpenCode протестував спеціально для агентів кодування. Не турбуйтеся про нестабільну якість — використовуйте перевірені моделі.",
|
||||
"home.zenCta.link": "Дізнатися про Zen",
|
||||
|
||||
"zen.title": "OpenCode Zen | Добірка надійних оптимізованих моделей для агентів кодування",
|
||||
"zen.hero.title": "Надійні оптимізовані моделі для агентів кодування",
|
||||
"zen.hero.body":
|
||||
"Zen дає доступ до добірки AI-моделей, які OpenCode протестував спеціально для агентів кодування. Не турбуйтеся про нестабільну якість — використовуйте перевірені моделі.",
|
||||
|
||||
"zen.faq.q1": "Що таке OpenCode Zen?",
|
||||
"zen.faq.a1": "Zen — це добірка AI-моделей, протестованих для агентів кодування, створена командою OpenCode.",
|
||||
"zen.faq.q2": "Чому Zen точніший?",
|
||||
"zen.faq.a2":
|
||||
"Zen надає лише моделі, спеціально протестовані для агентів кодування. Ви ж не використовуєте масло ніж для стейка — не використовуйте погані моделі для кодування.",
|
||||
"zen.faq.q3": "Чи Zen дешевший?",
|
||||
"zen.faq.a3":
|
||||
"Zen не є прибутковим. Zen передає вам вартість від провайдерів моделей. Чим вище використання Zen, тим кращі ціни OpenCode може узгодити та передати вам.",
|
||||
"zen.faq.q4": "Скільки коштує Zen?",
|
||||
"zen.faq.a4.p1.beforePricing": "Zen",
|
||||
"zen.faq.a4.p1.pricingLink": "стягує плату за запит",
|
||||
"zen.faq.a4.p1.afterPricing": "без націнок — ви платите рівно стільки, скільки стягує провайдер моделі.",
|
||||
"zen.faq.a4.p2.beforeAccount": "Загальна вартість залежить від використання. Ви можете встановити місячні ліміти в",
|
||||
"zen.faq.a4.p2.accountLink": "обліковому записі",
|
||||
"zen.faq.a4.p3":
|
||||
"Щоб покрити витрати, OpenCode додає лише невелику комісію за обробку платежу в розмірі $1.23 за кожне поповнення балансу $20.",
|
||||
"zen.faq.q5": "А як щодо даних та конфіденційності?",
|
||||
"zen.faq.a5.beforeExceptions":
|
||||
"Усі моделі Zen розміщені в США. Провайдери дотримуються політики нульового зберігання та не використовують ваші дані для навчання моделей, за",
|
||||
"zen.faq.a5.exceptionsLink": "такими винятками",
|
||||
"zen.faq.q6": "Чи можна встановити ліміти витрат?",
|
||||
"zen.faq.a6": "Так, ви можете встановити місячні ліміти витрат в обліковому записі.",
|
||||
"zen.faq.q7": "Чи можна скасувати?",
|
||||
"zen.faq.a7": "Так, ви можете вимкнути оплату в будь-який час і використовувати залишок.",
|
||||
"zen.faq.q8": "Чи можна використовувати Zen з іншими агентами кодування?",
|
||||
"zen.faq.a8":
|
||||
"Хоча Zen чудово працює з OpenCode, ви можете використовувати Zen з будь-яким агентом. Дотримуйтесь інструкцій з налаштування у вашому агенті.",
|
||||
|
||||
"zen.cta.start": "Почати з Zen",
|
||||
"zen.pricing.title": "Додати $20 балансу Pay as you go",
|
||||
"zen.pricing.fee": "(+$1.23 комісія за обробку карти)",
|
||||
"zen.pricing.body": "Використовуйте з будь-яким агентом. Встановлюйте місячні ліміти. Скасуйте в будь-який час.",
|
||||
"zen.problem.title": "Яку проблему вирішує Zen?",
|
||||
"zen.problem.body":
|
||||
"Доступно багато моделей, але лише деякі добре працюють з агентами кодування. Більшість провайдерів налаштовують їх по-різному з різними результатами.",
|
||||
"zen.problem.subtitle": "Ми вирішуємо це для всіх, а не лише для користувачів OpenCode.",
|
||||
"zen.problem.item1": "Тестування вибраних моделей та консультації з їхніми командами",
|
||||
"zen.problem.item2": "Співпраця з провайдерами для забезпечення правильної доставки",
|
||||
"zen.problem.item3": "Бенчмаркінг усіх комбінацій моделей та провайдерів, які ми рекомендуємо",
|
||||
"zen.how.title": "Як працює Zen",
|
||||
"zen.how.body":
|
||||
"Хоча ми пропонуємо використовувати Zen з OpenCode, ви можете використовувати Zen з будь-яким агентом.",
|
||||
"zen.how.step1.title": "Зареєструйтеся та додайте $20 балансу",
|
||||
"zen.how.step1.beforeLink": "дотримуйтесь",
|
||||
"zen.how.step1.link": "інструкцій з налаштування",
|
||||
"zen.how.step2.title": "Використовуйте Zen із прозорими цінами",
|
||||
"zen.how.step2.link": "платіть за запит",
|
||||
"zen.how.step2.afterLink": "без націнок",
|
||||
"zen.how.step3.title": "Автоматичне поповнення",
|
||||
"zen.how.step3.body": "коли баланс досягає $5, ми автоматично додаємо $20",
|
||||
"zen.privacy.title": "Ваша конфіденційність важлива для нас",
|
||||
"zen.privacy.beforeExceptions":
|
||||
"Усі моделі Zen розміщені в США. Провайдери дотримуються політики нульового зберігання та не використовують ваші дані для навчання моделей, за",
|
||||
"zen.privacy.exceptionsLink": "такими винятками",
|
||||
|
||||
"go.title": "OpenCode Go | Недорогі моделі кодування для всіх",
|
||||
"go.meta.description":
|
||||
"Go починається від $5 за перший місяць, потім $10/місяць, з generous 5-годинними лімітами запитів для GLM-5.1, GLM-5, Kimi K2.5, Kimi K2.6, MiMo-V2.5-Pro, MiMo-V2.5, Qwen3.5 Plus, Qwen3.6 Plus, MiniMax M2.5, MiniMax M2.7, DeepSeek V4 Pro та DeepSeek V4 Flash.",
|
||||
"go.hero.title": "Недорогі моделі кодування для всіх",
|
||||
"go.hero.body":
|
||||
"Go надає агентне програмування програмістам у всьому світі, пропонуючи щедрі ліміти та надійний доступ до найкращих моделей з відкритим кодом.",
|
||||
|
||||
"go.cta.start": "Підписатися на Go",
|
||||
"go.cta.template": "{{text}} {{price}}",
|
||||
"go.cta.text": "Підписатися на Go",
|
||||
"go.cta.price": "$10/місяць",
|
||||
"go.cta.promo": "$5 перший місяць",
|
||||
"go.pricing.body":
|
||||
"Використовуйте з будь-яким агентом. $5 перший місяць, потім $10/місяць. Поповнюйте за потреби. Скасуйте в будь-який час.",
|
||||
"go.graph.free": "Безкоштовно",
|
||||
"go.graph.freePill": "Big Pickle та безкоштовні моделі",
|
||||
"go.graph.go": "Go",
|
||||
"go.graph.label": "Запитів за 5 годин",
|
||||
"go.graph.usageLimits": "Ліміти використання",
|
||||
"go.graph.tick": "{{n}}x",
|
||||
"go.graph.aria": "Запитів за 5 год: {{free}} vs {{go}}",
|
||||
|
||||
"go.testimonials.brand.zen": "Zen",
|
||||
"go.testimonials.brand.go": "Go",
|
||||
"go.testimonials.handle": "@OpenCode",
|
||||
"go.testimonials.dax.name": "Dax Raad",
|
||||
"go.testimonials.dax.title": "ex-CEO, Terminal Products",
|
||||
"go.testimonials.dax.quoteAfter": "змінило моє життя, це справді очевидний вибір.",
|
||||
"go.testimonials.jay.name": "Jay V",
|
||||
"go.testimonials.jay.title": "ex-Founder, SEED, PM, Melt, Pop, Dapt, Cadmus, and ViewPoint",
|
||||
"go.testimonials.jay.quoteBefore": "4 з 5 людей у нашій команді люблять використовувати",
|
||||
"go.testimonials.jay.quoteAfter": ".",
|
||||
"go.testimonials.adam.name": "Adam Elmore",
|
||||
"go.testimonials.adam.title": "ex-Hero, AWS",
|
||||
"go.testimonials.adam.quoteBefore": "Я не можу достатньо рекомендувати",
|
||||
"go.testimonials.adam.quoteAfter": ". Серйозно, це дійсно добре.",
|
||||
"go.testimonials.david.name": "David Hill",
|
||||
"go.testimonials.david.title": "ex-Head of Design, Laravel",
|
||||
"go.testimonials.david.quoteBefore": "Завдяки",
|
||||
"go.testimonials.david.quoteAfter": "я знаю, що всі моделі протестовані та ідеальні для агентів кодування.",
|
||||
"go.testimonials.frank.name": "Frank Wang",
|
||||
"go.testimonials.frank.title": "ex-Intern, Nvidia (4 times)",
|
||||
"go.testimonials.frank.quote": "Хотів би я досі бути в Nvidia.",
|
||||
"go.problem.title": "Яку проблему вирішує Go?",
|
||||
"go.problem.body":
|
||||
"Ми зосереджені на тому, щоб зробити досвід OpenCode доступним для якомога більшої кількості людей. OpenCode Go — це недорога підписка: $5 за перший місяць, потім $10/місяць. Вона надає щедрі ліміти та надійний доступ до найкращих моделей з відкритим кодом.",
|
||||
"go.problem.subtitle": " ",
|
||||
"go.problem.item1": "Недорога підписка",
|
||||
"go.problem.item2": "Щедрі ліміти та надійний доступ",
|
||||
"go.problem.item3": "Створено для якомога більшої кількості програмістів",
|
||||
"go.problem.item4":
|
||||
"Включає GLM-5.1, GLM-5, Kimi K2.5, Kimi K2.6, MiMo-V2.5-Pro, MiMo-V2.5, Qwen3.5 Plus, Qwen3.6 Plus, MiniMax M2.5, MiniMax M2.7, DeepSeek V4 Pro та DeepSeek V4 Flash",
|
||||
"go.how.title": "Як працює Go",
|
||||
"go.how.body":
|
||||
"Go починається від $5 за перший місяць, потім $10/місяць. Використовуйте з OpenCode або будь-яким агентом.",
|
||||
"go.how.step1.title": "Створіть обліковий запис",
|
||||
"go.how.step1.beforeLink": "дотримуйтесь",
|
||||
"go.how.step1.link": "інструкцій з налаштування",
|
||||
"go.how.step2.title": "Підпишіться на Go",
|
||||
"go.how.step2.link": "$5 перший місяць",
|
||||
"go.how.step2.afterLink": "потім $10/місяць із щедрими лімітами",
|
||||
"go.how.step3.title": "Почніть кодувати",
|
||||
"go.how.step3.body": "з надійним доступом до моделей з відкритим кодом",
|
||||
"go.privacy.title": "Ваша конфіденційність важлива для нас",
|
||||
"go.privacy.body":
|
||||
"План розроблений переважно для міжнародних користувачів, з моделями, розміщеними в США, ЄС та Сінгапурі для стабільного глобального доступу.",
|
||||
"go.privacy.contactAfter": "якщо у вас є запитання.",
|
||||
"go.privacy.beforeExceptions":
|
||||
"Моделі Go розміщені в США. Провайдери дотримуються політики нульового зберігання та не використовують ваші дані для навчання моделей, за",
|
||||
"go.privacy.exceptionsLink": "такими винятками",
|
||||
"go.faq.q1": "Що таке OpenCode Go?",
|
||||
"go.faq.a1":
|
||||
"Go — це недорога підписка, яка надає надійний доступ до найкращих моделей з відкритим кодом для агентного кодування.",
|
||||
"go.faq.q2": "Які моделі включає Go?",
|
||||
"go.faq.a2": "Go включає моделі, перелічені нижче, із щедрими лімітами та надійним доступом.",
|
||||
"go.faq.q3": "Чи Go те саме, що Zen?",
|
||||
"go.faq.a3":
|
||||
"Ні. Zen — це плата за використання, тоді як Go починається від $5 за перший місяць, потім $10/місяць, із щедрими лімітами та надійним доступом до моделей з відкритим кодом.",
|
||||
"go.faq.q4": "Скільки коштує Go?",
|
||||
"go.faq.a4.p1.beforePricing": "Go коштує",
|
||||
"go.faq.a4.p1.pricingLink": "$5 за перший місяць",
|
||||
"go.faq.a4.p1.afterPricing": "потім $10/місяць із щедрими лімітами.",
|
||||
"go.faq.a4.p2.beforeAccount": "Ви можете керувати підпискою в",
|
||||
"go.faq.a4.p2.accountLink": "обліковому записі",
|
||||
"go.faq.a4.p3": "Скасуйте в будь-який час.",
|
||||
"go.faq.q5": "А як щодо даних та конфіденційності?",
|
||||
"go.faq.a5.body":
|
||||
"План розроблений переважно для міжнародних користувачів, з моделями в США, ЄС та Сінгапурі. Провайдери дотримуються політики нульового зберігання.",
|
||||
"go.faq.a5.beforeExceptions":
|
||||
"Моделі Go розміщені в США. Провайдери дотримуються політики нульового зберігання та не використовують ваші дані для навчання моделей, за",
|
||||
"go.faq.a5.exceptionsLink": "такими винятками",
|
||||
"go.faq.q6": "Чи можна поповнити баланс?",
|
||||
"go.faq.a6": "Якщо вам потрібно більше використання, ви можете поповнити баланс в обліковому записі.",
|
||||
"go.faq.q7": "Чи можна скасувати?",
|
||||
"go.faq.a7": "Так, ви можете скасувати в будь-який час.",
|
||||
"go.faq.q8": "Чи можна використовувати Go з іншими агентами кодування?",
|
||||
"go.faq.a8": "Так, ви можете використовувати Go з будь-яким агентом.",
|
||||
|
||||
"go.faq.q9": "Яка різниця між безкоштовними моделями та Go?",
|
||||
"go.faq.a9":
|
||||
"Безкоштовні моделі включають Big Pickle та акційні моделі з лімітом 200 запитів/день. Go включає GLM-5.1, GLM-5, Kimi K2.5, Kimi K2.6, MiMo-V2.5-Pro, MiMo-V2.5, Qwen3.5 Plus, Qwen3.6 Plus, MiniMax M2.5, MiniMax M2.7, DeepSeek V4 Pro та DeepSeek V4 Flash із вищими лімітами.",
|
||||
|
||||
"zen.api.error.rateLimitExceeded": "Перевищено ліміт запитів. Спробуйте пізніше.",
|
||||
"zen.api.error.modelNotSupported": "Модель {{model}} не підтримується",
|
||||
"zen.api.error.modelFormatNotSupported": "Модель {{model}} не підтримується для формату {{format}}",
|
||||
"zen.api.error.noProviderAvailable": "Немає доступного провайдера",
|
||||
"zen.api.error.providerNotSupported": "Провайдер {{provider}} не підтримується",
|
||||
"zen.api.error.missingApiKey": "Відсутній ключ API.",
|
||||
"zen.api.error.invalidApiKey": "Недійсний ключ API.",
|
||||
"zen.api.error.subscriptionQuotaExceeded": "Перевищено квоту підписки. Повторіть через {{retryIn}}.",
|
||||
"zen.api.error.goSubscriptionRollingLimitExceeded":
|
||||
"Досягнуто 5-годинного ліміту використання. Скидається через {{retryIn}}. Щоб продовжити, увімкніть використання з доступного балансу: {{consoleGoUrl}}",
|
||||
"zen.api.error.goSubscriptionWeeklyLimitExceeded":
|
||||
"Досягнуто тижневого ліміту використання. Скидається через {{retryIn}}. Щоб продовжити, увімкніть використання з доступного балансу: {{consoleGoUrl}}",
|
||||
"zen.api.error.goSubscriptionMonthlyLimitExceeded":
|
||||
"Досягнуто місячного ліміту використання. Скидається через {{retryIn}}. Щоб продовжити, увімкніть використання з доступного балансу: {{consoleGoUrl}}",
|
||||
"zen.api.error.noPaymentMethod": "Немає способу оплати. Додайте метод оплати: {{billingUrl}}",
|
||||
"zen.api.error.insufficientBalance": "Недостатньо коштів. Керуйте оплатою: {{billingUrl}}",
|
||||
"zen.api.error.workspaceMonthlyLimitReached":
|
||||
"Ваш робочий простір досяг місячного ліміту витрат ${{amount}}. Керуйте лімітами: {{billingUrl}}",
|
||||
"zen.api.error.userMonthlyLimitReached":
|
||||
"Ви досягли місячного ліміту витрат ${{amount}}. Керуйте лімітами: {{membersUrl}}",
|
||||
"zen.api.error.modelDisabled": "Модель вимкнено",
|
||||
"zen.api.error.trialEnded":
|
||||
"Безкоштовна акція для {{model}} закінчилася. Ви можете продовжити використання, підписавшись на OpenCode Go — {{link}}",
|
||||
|
||||
"black.meta.title": "OpenCode Black | Доступ до найкращих моделей кодування",
|
||||
"black.meta.description": "Отримайте доступ до Claude, GPT, Gemini та інших із планами підписки OpenCode Black.",
|
||||
"black.hero.title": "Доступ до найкращих моделей кодування",
|
||||
"black.hero.subtitle": "Включаючи Claude, GPT, Gemini та інші",
|
||||
"black.title": "OpenCode Black | Ціни",
|
||||
"black.paused": "Реєстрація в план Black тимчасово призупинена.",
|
||||
"black.plan.icon20": "План Black 20",
|
||||
"black.plan.icon100": "План Black 100",
|
||||
"black.plan.icon200": "План Black 200",
|
||||
"black.plan.multiplier100": "5x більше використання ніж Black 20",
|
||||
"black.plan.multiplier200": "20x більше використання ніж Black 20",
|
||||
"black.price.perMonth": "на місяць",
|
||||
"black.price.perPersonBilledMonthly": "за особу з щомісячною оплатою",
|
||||
"black.terms.1": "Ваша підписка не розпочнеться негайно",
|
||||
"black.terms.2": "Вас додадуть до списку очікування та активують незабаром",
|
||||
"black.terms.3": "Картку буде списано лише після активації підписки",
|
||||
"black.terms.4": "Діють ліміти використання, інтенсивне автоматичне використання може швидше вичерпати ліміти",
|
||||
"black.terms.5": "Підписки призначені для фізичних осіб, зверніться в Enterprise для команд",
|
||||
"black.terms.6": "Ліміти можуть бути змінені, а плани можуть бути припинені в майбутньому",
|
||||
"black.terms.7": "Скасуйте підписку в будь-який час",
|
||||
"black.action.continue": "Продовжити",
|
||||
"black.finePrint.beforeTerms": "Зазначені ціни не включають податки",
|
||||
"black.finePrint.terms": "Умови надання послуг",
|
||||
"black.workspace.title": "OpenCode Black | Виберіть робочий простір",
|
||||
"black.workspace.selectPlan": "Виберіть робочий простір для цього плану",
|
||||
"black.workspace.name": "Робочий простір {{n}}",
|
||||
"black.subscribe.title": "Підписатися на OpenCode Black",
|
||||
"black.subscribe.paymentMethod": "Спосіб оплати",
|
||||
"black.subscribe.loadingPaymentForm": "Завантаження форми оплати...",
|
||||
"black.subscribe.selectWorkspaceToContinue": "Виберіть робочий простір для продовження",
|
||||
"black.subscribe.failurePrefix": "Ой!",
|
||||
"black.subscribe.error.generic": "Сталася помилка",
|
||||
"black.subscribe.error.invalidPlan": "Недійсний план",
|
||||
"black.subscribe.error.workspaceRequired": "ID робочого простору обов'язкове",
|
||||
"black.subscribe.error.alreadySubscribed": "Цей робочий простір уже має підписку",
|
||||
"black.subscribe.processing": "Обробка...",
|
||||
"black.subscribe.submit": "Підписатися ${{plan}}",
|
||||
"black.subscribe.form.chargeNotice": "Платіж буде списано лише після активації підписки",
|
||||
"black.subscribe.success.title": "Ви в списку очікування OpenCode Black",
|
||||
"black.subscribe.success.subscriptionPlan": "План підписки",
|
||||
"black.subscribe.success.planName": "OpenCode Black {{plan}}",
|
||||
"black.subscribe.success.amount": "Сума",
|
||||
"black.subscribe.success.amountValue": "${{plan}} на місяць",
|
||||
"black.subscribe.success.paymentMethod": "Спосіб оплати",
|
||||
"black.subscribe.success.dateJoined": "Дата приєднання",
|
||||
"black.subscribe.success.chargeNotice": "Вашу картку буде списано після активації підписки",
|
||||
|
||||
"workspace.nav.zen": "Zen",
|
||||
"workspace.nav.go": "Go",
|
||||
"workspace.nav.usage": "Використання",
|
||||
"workspace.nav.apiKeys": "Ключі API",
|
||||
"workspace.nav.members": "Учасники",
|
||||
"workspace.nav.billing": "Оплата",
|
||||
"workspace.nav.settings": "Налаштування",
|
||||
|
||||
"workspace.home.banner.beforeLink": "Надійні оптимізовані моделі для агентів кодування.",
|
||||
"workspace.lite.banner.beforeLink": "Недорогі моделі кодування для всіх.",
|
||||
"workspace.home.billing.loading": "Завантаження...",
|
||||
"workspace.home.billing.enable": "Увімкнути оплату",
|
||||
"workspace.home.billing.currentBalance": "Поточний баланс",
|
||||
|
||||
"workspace.newUser.feature.tested.title": "Протестовані та перевірені моделі",
|
||||
"workspace.newUser.feature.tested.body":
|
||||
"Ми протестували моделі спеціально для агентів кодування, щоб забезпечити найкращу продуктивність.",
|
||||
"workspace.newUser.feature.quality.title": "Найвища якість",
|
||||
"workspace.newUser.feature.quality.body":
|
||||
"Доступ до моделей, налаштованих для оптимальної продуктивності — без зниження якості.",
|
||||
"workspace.newUser.feature.lockin.title": "Без блокування (Lock-in)",
|
||||
"workspace.newUser.feature.lockin.body":
|
||||
"Використовуйте Zen з будь-яким агентом і продовжуйте користуватися іншими провайдерами.",
|
||||
"workspace.newUser.copyApiKey": "Копіювати ключ API",
|
||||
"workspace.newUser.copyKey": "Копіювати ключ",
|
||||
"workspace.newUser.copied": "Скопійовано!",
|
||||
"workspace.newUser.step.enableBilling": "Увімкнути оплату",
|
||||
"workspace.newUser.step.login.before": "Запустіть",
|
||||
"workspace.newUser.step.login.after": "і виберіть opencode",
|
||||
"workspace.newUser.step.pasteKey": "Вставте ключ API",
|
||||
"workspace.newUser.step.models.before": "Запустіть opencode і виконайте",
|
||||
"workspace.newUser.step.models.after": "щоб вибрати модель",
|
||||
|
||||
"workspace.models.title": "Моделі",
|
||||
"workspace.models.subtitle.beforeLink": "Керуйте доступом учасників до моделей.",
|
||||
"workspace.models.table.model": "Модель",
|
||||
"workspace.models.table.enabled": "Увімкнено",
|
||||
|
||||
"workspace.providers.title": "Принесіть власний ключ (BYOK)",
|
||||
"workspace.providers.subtitle": "Налаштуйте власні ключі API від AI-провайдерів.",
|
||||
"workspace.providers.placeholder": "Введіть ключ API {{provider}} ({{prefix}}...)",
|
||||
"workspace.providers.configure": "Налаштувати",
|
||||
"workspace.providers.edit": "Редагувати",
|
||||
"workspace.providers.delete": "Видалити",
|
||||
"workspace.providers.saving": "Збереження...",
|
||||
"workspace.providers.save": "Зберегти",
|
||||
"workspace.providers.table.provider": "Провайдер",
|
||||
"workspace.providers.table.apiKey": "Ключ API",
|
||||
|
||||
"workspace.usage.title": "Історія використання",
|
||||
"workspace.usage.subtitle": "Останнє використання API та витрати.",
|
||||
"workspace.usage.empty": "Зробіть перший API-запит, щоб почати.",
|
||||
"workspace.usage.table.date": "Дата",
|
||||
"workspace.usage.table.model": "Модель",
|
||||
"workspace.usage.table.input": "Вхід",
|
||||
"workspace.usage.table.output": "Вихід",
|
||||
"workspace.usage.table.cost": "Вартість",
|
||||
"workspace.usage.table.session": "Сесія",
|
||||
"workspace.usage.breakdown.input": "Вхід",
|
||||
"workspace.usage.breakdown.cacheRead": "Читання кешу",
|
||||
"workspace.usage.breakdown.cacheWrite": "Запис кешу",
|
||||
"workspace.usage.breakdown.output": "Вихід",
|
||||
"workspace.usage.breakdown.reasoning": "Міркування",
|
||||
"workspace.usage.subscription": "Black (${{amount}})",
|
||||
"workspace.usage.lite": "Go (${{amount}})",
|
||||
"workspace.usage.byok": "BYOK (${{amount}})",
|
||||
|
||||
"workspace.cost.title": "Вартість",
|
||||
"workspace.cost.subtitle": "Витрати в розрізі моделей.",
|
||||
"workspace.cost.allModels": "Усі моделі",
|
||||
"workspace.cost.allKeys": "Усі ключі",
|
||||
"workspace.cost.deletedSuffix": "(видалено)",
|
||||
"workspace.cost.empty": "Немає даних про використання за вибраний період.",
|
||||
"workspace.cost.subscriptionShort": "підп",
|
||||
|
||||
"workspace.keys.title": "Ключі API",
|
||||
"workspace.keys.subtitle": "Керуйте ключами API для доступу до сервісів opencode.",
|
||||
"workspace.keys.create": "Створити ключ API",
|
||||
"workspace.keys.placeholder": "Введіть назву ключа",
|
||||
"workspace.keys.empty": "Створіть ключ API шлюзу opencode",
|
||||
"workspace.keys.table.name": "Назва",
|
||||
"workspace.keys.table.key": "Ключ",
|
||||
"workspace.keys.table.createdBy": "Створено",
|
||||
"workspace.keys.table.lastUsed": "Останнє використання",
|
||||
"workspace.keys.copyApiKey": "Копіювати ключ API",
|
||||
"workspace.keys.delete": "Видалити",
|
||||
|
||||
"workspace.members.title": "Учасники",
|
||||
"workspace.members.subtitle": "Керуйте учасниками робочого простору та їхніми дозволами.",
|
||||
"workspace.members.invite": "Запросити учасника",
|
||||
"workspace.members.inviting": "Запрошення...",
|
||||
"workspace.members.beta.beforeLink": "Робочі простори безкоштовні для команд під час бета-версії.",
|
||||
"workspace.members.form.invitee": "Запрошений",
|
||||
"workspace.members.form.emailPlaceholder": "Введіть email",
|
||||
"workspace.members.form.role": "Роль",
|
||||
"workspace.members.form.monthlyLimit": "Місячний ліміт витрат",
|
||||
"workspace.members.noLimit": "Без ліміту",
|
||||
"workspace.members.noLimitLowercase": "без ліміту",
|
||||
"workspace.members.invited": "запрошено",
|
||||
"workspace.members.edit": "Редагувати",
|
||||
"workspace.members.delete": "Видалити",
|
||||
"workspace.members.saving": "Збереження...",
|
||||
"workspace.members.save": "Зберегти",
|
||||
"workspace.members.table.email": "Email",
|
||||
"workspace.members.table.role": "Роль",
|
||||
"workspace.members.table.monthLimit": "Ліміт на місяць",
|
||||
"workspace.members.role.admin": "Адміністратор",
|
||||
"workspace.members.role.adminDescription": "Може керувати моделями, учасниками та оплатою",
|
||||
"workspace.members.role.member": "Учасник",
|
||||
"workspace.members.role.memberDescription": "Може створювати ключі API лише для себе",
|
||||
|
||||
"workspace.settings.title": "Налаштування",
|
||||
"workspace.settings.subtitle": "Оновіть назву робочого простору та налаштування.",
|
||||
"workspace.settings.workspaceName": "Назва робочого простору",
|
||||
"workspace.settings.defaultName": "Стандартна",
|
||||
"workspace.settings.updating": "Оновлення...",
|
||||
"workspace.settings.save": "Зберегти",
|
||||
"workspace.settings.edit": "Редагувати",
|
||||
|
||||
"workspace.billing.title": "Оплата",
|
||||
"workspace.billing.subtitle.beforeLink": "Керуйте способами оплати.",
|
||||
"workspace.billing.contactUs": "Зв'яжіться з нами",
|
||||
"workspace.billing.subtitle.afterLink": "якщо у вас є запитання.",
|
||||
"workspace.billing.currentBalance": "Поточний баланс",
|
||||
"workspace.billing.add": "Додати $",
|
||||
"workspace.billing.enterAmount": "Введіть суму",
|
||||
"workspace.billing.loading": "Завантаження...",
|
||||
"workspace.billing.addAction": "Додати",
|
||||
"workspace.billing.addBalance": "Поповнити баланс",
|
||||
"workspace.billing.alipay": "Alipay",
|
||||
"workspace.billing.wechat": "WeChat Pay",
|
||||
"workspace.billing.linkedToStripe": "Підключено до Stripe",
|
||||
"workspace.billing.manage": "Керувати",
|
||||
"workspace.billing.enable": "Увімкнути оплату",
|
||||
|
||||
"workspace.monthlyLimit.title": "Місячний ліміт",
|
||||
"workspace.monthlyLimit.subtitle": "Встановіть місячний ліміт використання для облікового запису.",
|
||||
"workspace.monthlyLimit.placeholder": "50",
|
||||
"workspace.monthlyLimit.setting": "Встановлення...",
|
||||
"workspace.monthlyLimit.set": "Встановити",
|
||||
"workspace.monthlyLimit.edit": "Редагувати ліміт",
|
||||
"workspace.monthlyLimit.noLimit": "Ліміт використання не встановлено.",
|
||||
"workspace.monthlyLimit.currentUsage.beforeMonth": "Поточне використання за",
|
||||
"workspace.monthlyLimit.currentUsage.beforeAmount": "становить $",
|
||||
|
||||
"workspace.redeem.title": "Активувати купон",
|
||||
"workspace.redeem.subtitle": "Активуйте код купона для отримання коштів або бонусів.",
|
||||
"workspace.redeem.placeholder": "Введіть код купона",
|
||||
"workspace.redeem.redeem": "Активувати",
|
||||
"workspace.redeem.redeeming": "Активація...",
|
||||
"workspace.redeem.success": "Купон успішно активовано.",
|
||||
|
||||
"workspace.reload.title": "Автоматичне поповнення",
|
||||
"workspace.reload.disabled.before": "Автоматичне поповнення",
|
||||
"workspace.reload.disabled.state": "вимкнено",
|
||||
"workspace.reload.disabled.after": "Увімкніть для автоматичного поповнення при низькому балансі.",
|
||||
"workspace.reload.enabled.before": "Автоматичне поповнення",
|
||||
"workspace.reload.enabled.state": "увімкнено",
|
||||
"workspace.reload.enabled.middle": "Ми поповнимо",
|
||||
"workspace.reload.processingFee": "комісія за обробку",
|
||||
"workspace.reload.enabled.after": "коли баланс досягне",
|
||||
"workspace.reload.edit": "Редагувати",
|
||||
"workspace.reload.enable": "Увімкнути",
|
||||
"workspace.reload.enableAutoReload": "Увімкнути автоматичне поповнення",
|
||||
"workspace.reload.reloadAmount": "Поповнити на $",
|
||||
"workspace.reload.whenBalanceReaches": "Коли баланс досягне $",
|
||||
"workspace.reload.saving": "Збереження...",
|
||||
"workspace.reload.save": "Зберегти",
|
||||
"workspace.reload.failedAt": "Поповнення не вдалося о",
|
||||
"workspace.reload.reason": "Причина:",
|
||||
"workspace.reload.updatePaymentMethod": "Оновіть спосіб оплати та спробуйте ще раз.",
|
||||
"workspace.reload.retrying": "Повтор...",
|
||||
"workspace.reload.retry": "Повторити",
|
||||
"workspace.reload.error.paymentFailed": "Платіж не вдався.",
|
||||
|
||||
"workspace.payments.title": "Історія платежів",
|
||||
"workspace.payments.subtitle": "Останні платіжні транзакції.",
|
||||
"workspace.payments.table.date": "Дата",
|
||||
"workspace.payments.table.paymentId": "ID платежу",
|
||||
"workspace.payments.table.amount": "Сума",
|
||||
"workspace.payments.table.receipt": "Квитанція",
|
||||
"workspace.payments.type.credit": "кредит",
|
||||
"workspace.payments.type.subscription": "підписка",
|
||||
"workspace.payments.view": "Переглянути",
|
||||
|
||||
"workspace.black.loading": "Завантаження...",
|
||||
"workspace.black.time.day": "день",
|
||||
"workspace.black.time.days": "дні",
|
||||
"workspace.black.time.hour": "година",
|
||||
"workspace.black.time.hours": "годин(и)",
|
||||
"workspace.black.time.minute": "хвилина",
|
||||
"workspace.black.time.minutes": "хвилин(и)",
|
||||
"workspace.black.time.fewSeconds": "кілька секунд",
|
||||
"workspace.black.subscription.title": "Підписка",
|
||||
"workspace.black.subscription.message": "Ви підписані на OpenCode Black за ${{plan}} на місяць.",
|
||||
"workspace.black.subscription.manage": "Керувати підпискою",
|
||||
"workspace.black.subscription.rollingUsage": "Використання (5 год)",
|
||||
"workspace.black.subscription.weeklyUsage": "Тижневе використання",
|
||||
"workspace.black.subscription.resetsIn": "Скидається через",
|
||||
"workspace.black.subscription.useBalance": "Використовуйте доступний баланс після досягнення лімітів",
|
||||
"workspace.black.waitlist.title": "Список очікування",
|
||||
"workspace.black.waitlist.joined": "Ви в списку очікування на план OpenCode Black за ${{plan}} на місяць.",
|
||||
"workspace.black.waitlist.ready": "Ми готові зареєструвати вас на план OpenCode Black за ${{plan}} на місяць.",
|
||||
"workspace.black.waitlist.leave": "Залишити список очікування",
|
||||
"workspace.black.waitlist.leaving": "Вихід...",
|
||||
"workspace.black.waitlist.left": "Вишли",
|
||||
"workspace.black.waitlist.enroll": "Зареєструватися",
|
||||
"workspace.black.waitlist.enrolling": "Реєстрація...",
|
||||
"workspace.black.waitlist.enrolled": "Зареєстровано",
|
||||
"workspace.black.waitlist.enrollNote":
|
||||
"Після натискання «Зареєструватися» підписка почнеться негайно, а картку буде списано.",
|
||||
|
||||
"workspace.lite.loading": "Завантаження...",
|
||||
"workspace.lite.time.day": "день",
|
||||
"workspace.lite.time.days": "дні",
|
||||
"workspace.lite.time.hour": "година",
|
||||
"workspace.lite.time.hours": "годин(и)",
|
||||
"workspace.lite.time.minute": "хвилина",
|
||||
"workspace.lite.time.minutes": "хвилин(и)",
|
||||
"workspace.lite.time.fewSeconds": "кілька секунд",
|
||||
"workspace.lite.subscription.message": "Ви підписані на OpenCode Go.",
|
||||
"workspace.lite.subscription.manage": "Керувати підпискою",
|
||||
"workspace.lite.subscription.rollingUsage": "Ковзне використання",
|
||||
"workspace.lite.subscription.weeklyUsage": "Тижневе використання",
|
||||
"workspace.lite.subscription.monthlyUsage": "Місячне використання",
|
||||
"workspace.lite.subscription.resetsIn": "Скидається через",
|
||||
"workspace.lite.subscription.useBalance": "Використовуйте доступний баланс після досягнення лімітів",
|
||||
"workspace.lite.subscription.selectProvider": 'Виберіть "OpenCode Go" як провайдера в конфігурації opencode.',
|
||||
"workspace.lite.black.message":
|
||||
"Ви вже підписані на OpenCode Black або в списку очікування. Спочатку скасуйте підписку, якщо хочете перейти на Go.",
|
||||
"workspace.lite.other.message": "Інший учасник цього робочого простору вже підписаний на OpenCode Go.",
|
||||
"workspace.lite.promo.description": "OpenCode Go починається від {{price}}, потім $10/місяць, із щедрими лімітами.",
|
||||
"workspace.lite.promo.price": "$5 за перший місяць",
|
||||
"workspace.lite.promo.modelsTitle": "Що включено",
|
||||
"workspace.lite.promo.footer": "План призначений для міжнародних користувачів. Ціни можуть змінюватися.",
|
||||
"workspace.lite.promo.subscribe": "Підписатися на Go",
|
||||
"workspace.lite.promo.subscribing": "Перенаправлення...",
|
||||
"workspace.lite.promo.otherMethods": "Інші способи оплати",
|
||||
"workspace.lite.promo.selectMethod": "Виберіть спосіб оплати",
|
||||
|
||||
"download.title": "OpenCode | Завантажити",
|
||||
"download.meta.description": "Завантажте OpenCode для macOS, Windows та Linux",
|
||||
"download.hero.title": "Завантажити OpenCode",
|
||||
"download.hero.subtitle": "Доступно в бета-версії для macOS, Windows та Linux",
|
||||
"download.hero.button": "Завантажити для {{os}}",
|
||||
"download.section.terminal": "Термінал OpenCode",
|
||||
"download.section.desktop": "Десктоп OpenCode (Бета)",
|
||||
"download.section.extensions": "Розширення OpenCode",
|
||||
"download.section.integrations": "Інтеграції OpenCode",
|
||||
"download.action.download": "Завантажити",
|
||||
"download.action.install": "Встановити",
|
||||
|
||||
"download.platform.macosAppleSilicon": "macOS (Apple Silicon)",
|
||||
"download.platform.macosIntel": "macOS (Intel)",
|
||||
"download.platform.windowsX64": "Windows (x64)",
|
||||
"download.platform.linuxDeb": "Linux (.deb)",
|
||||
"download.platform.linuxRpm": "Linux (.rpm)",
|
||||
|
||||
"download.faq.a3.beforeLocal":
|
||||
"Не обов'язково, але ймовірно. Вам знадобиться AI-підписка, якщо ви хочете підключити платного провайдера, хоча ви можете працювати з",
|
||||
"download.faq.a3.localLink": "локальними моделями",
|
||||
"download.faq.a3.afterLocal.beforeZen": "безкоштовно. Хоча ми рекомендуємо",
|
||||
"download.faq.a3.afterZen":
|
||||
", OpenCode працює з усіма популярними провайдерами, такими як OpenAI, Anthropic, xAI тощо.",
|
||||
|
||||
"download.faq.a5.p1": "OpenCode є 100% безкоштовним.",
|
||||
"download.faq.a5.p2.beforeZen":
|
||||
"Будь-які додаткові витрати будуть з вашої підписки у провайдера моделі. Ми рекомендуємо",
|
||||
"download.faq.a5.p2.afterZen": ".",
|
||||
|
||||
"download.faq.a6.p1": "Ваші дані зберігаються лише при створенні посилань для обміну в OpenCode.",
|
||||
"download.faq.a6.p2.beforeShare": "Дізнайтеся більше про",
|
||||
"download.faq.a6.shareLink": "сторінки обміну",
|
||||
|
||||
"enterprise.title": "OpenCode | Enterprise-рішення для вашої організації",
|
||||
"enterprise.meta.description": "Зв'яжіться з OpenCode для Enterprise-рішень",
|
||||
"enterprise.hero.title": "Ваш код належить вам",
|
||||
"enterprise.hero.body1":
|
||||
"OpenCode працює безпечно всередині вашої організації без зберігання даних, ліцензійних обмежень. Почніть пробний період із командою, потім розгорніть через SSO та внутрішній AI-шлюз.",
|
||||
"enterprise.hero.body2": "Дайте знати, чим ми можемо допомогти.",
|
||||
"enterprise.form.name.label": "Повне ім'я",
|
||||
"enterprise.form.name.placeholder": "Джеф Безос",
|
||||
"enterprise.form.role.label": "Посада",
|
||||
"enterprise.form.role.placeholder": "Голова правління",
|
||||
"enterprise.form.company.label": "Компанія",
|
||||
"enterprise.form.company.placeholder": "Acme Inc",
|
||||
"enterprise.form.email.label": "Робоча електронна адреса",
|
||||
"enterprise.form.email.placeholder": "jeff@amazon.com",
|
||||
"enterprise.form.phone.label": "Номер телефону",
|
||||
"enterprise.form.phone.placeholder": "+1 234 567 8900",
|
||||
"enterprise.form.message.label": "Яку проблему ви намагаєтеся вирішити?",
|
||||
"enterprise.form.message.placeholder": "Нам потрібна допомога з...",
|
||||
"enterprise.form.send": "Надіслати",
|
||||
"enterprise.form.sending": "Надсилання...",
|
||||
"enterprise.form.success": "Повідомлення надіслано, ми зв'яжемося найближчим часом.",
|
||||
"enterprise.form.success.submitted": "Форму успішно надіслано.",
|
||||
"enterprise.form.error.allFieldsRequired": "Усі поля обов'язкові.",
|
||||
"enterprise.form.error.invalidEmailFormat": "Недійсний формат email.",
|
||||
"enterprise.form.error.internalServer": "Внутрішня помилка сервера.",
|
||||
"enterprise.faq.title": "FAQ",
|
||||
"enterprise.faq.q1": "Що таке OpenCode Enterprise?",
|
||||
"enterprise.faq.a1":
|
||||
"OpenCode Enterprise для організацій, які хочуть гарантувати, що код і дані ніколи не залишають їхню інфраструктуру.",
|
||||
"enterprise.faq.q2": "Як почати з OpenCode Enterprise?",
|
||||
"enterprise.faq.a2":
|
||||
"Почніть із внутрішнього тестування з командою. OpenCode за замовчуванням не зберігає код. Потім зв'яжіться з нами для обговорення цін.",
|
||||
"enterprise.faq.q3": "Як працює ціноутворення enterprise?",
|
||||
"enterprise.faq.a3":
|
||||
"Ми пропонуємо ціну за робоче місце. Якщо у вас власний LLM-шлюз, ми не стягуємо плату за токени.",
|
||||
"enterprise.faq.q4": "Чи безпечні мої дані з OpenCode Enterprise?",
|
||||
"enterprise.faq.a4":
|
||||
"Так. OpenCode не зберігає ваш код або контекст. Вся обробка відбувається локально або через прямі API-виклики.",
|
||||
|
||||
"brand.title": "OpenCode | Бренд",
|
||||
"brand.meta.description": "Рекомендації щодо бренду OpenCode",
|
||||
"brand.heading": "Рекомендації щодо бренду",
|
||||
"brand.subtitle": "Ресурси та матеріали для роботи з брендом OpenCode.",
|
||||
"brand.downloadAll": "Завантажити всі матеріали",
|
||||
|
||||
"changelog.title": "OpenCode | Журнал змін",
|
||||
"changelog.meta.description": "Нотатки про випуски та журнал змін OpenCode",
|
||||
"changelog.hero.title": "Журнал змін",
|
||||
"changelog.hero.subtitle": "Нові оновлення та покращення OpenCode",
|
||||
"changelog.empty": "Записів у журналі змін не знайдено.",
|
||||
"changelog.viewJson": "Переглянути JSON",
|
||||
|
||||
"bench.list.title": "Бенчмарк",
|
||||
"bench.list.heading": "Бенчмарки",
|
||||
"bench.list.table.agent": "Агент",
|
||||
"bench.list.table.model": "Модель",
|
||||
"bench.list.table.score": "Результат",
|
||||
"bench.submission.error.allFieldsRequired": "Усі поля обов'язкові.",
|
||||
|
||||
"bench.detail.title": "Бенчмарк — {{task}}",
|
||||
"bench.detail.notFound": "Завдання не знайдено",
|
||||
"bench.detail.na": "Н/Д",
|
||||
"bench.detail.labels.agent": "Агент",
|
||||
"bench.detail.labels.model": "Модель",
|
||||
"bench.detail.labels.task": "Завдання",
|
||||
"bench.detail.labels.repo": "Репозиторій",
|
||||
"bench.detail.labels.from": "Від",
|
||||
"bench.detail.labels.to": "До",
|
||||
"bench.detail.labels.prompt": "Prompt",
|
||||
"bench.detail.labels.commit": "Коміт",
|
||||
"bench.detail.labels.averageDuration": "Середня тривалість",
|
||||
"bench.detail.labels.averageScore": "Середній результат",
|
||||
"bench.detail.labels.averageCost": "Середня вартість",
|
||||
"bench.detail.labels.summary": "Підсумок",
|
||||
"bench.detail.labels.runs": "Запуски",
|
||||
"bench.detail.labels.score": "Результат",
|
||||
"bench.detail.labels.base": "База",
|
||||
"bench.detail.labels.penalty": "Штраф",
|
||||
"bench.detail.labels.weight": "вага",
|
||||
"bench.detail.table.run": "Запуск",
|
||||
"bench.detail.table.score": "Результат (База — Штраф)",
|
||||
"bench.detail.table.cost": "Вартість",
|
||||
"bench.detail.table.duration": "Тривалість",
|
||||
"bench.detail.run.title": "Запуск {{n}}",
|
||||
"bench.detail.rawJson": "Сирий JSON",
|
||||
}
|
||||
@@ -643,6 +643,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "其他付款方式",
|
||||
"workspace.lite.promo.selectMethod": "选择付款方式",
|
||||
|
||||
"workspace.referral.copyLink": "复制链接",
|
||||
"workspace.referral.copied": "已复制",
|
||||
"workspace.referral.overview.title": "邀请好友",
|
||||
"workspace.referral.overview.subtitle": "好友订阅后,您可获得 $5,对方也可获得 $5。",
|
||||
"workspace.referral.instructions.share": "分享您的推荐链接。",
|
||||
"workspace.referral.instructions.subscribe": "好友加入并订阅 Go。",
|
||||
"workspace.referral.instructions.claim": "你们都将获得 $5 使用额度,可用于您的 Go 使用限额。",
|
||||
"workspace.referral.rewards.title": "邀请奖励",
|
||||
"workspace.referral.rewards.description": "将可用的邀请积分应用到您的 Go 用量。",
|
||||
"workspace.referral.rewards.subtitle": "已使用 {{applied}} / {{total}} 个奖励。",
|
||||
"workspace.referral.rewards.empty": "暂无邀请奖励。",
|
||||
"workspace.referral.table.reward": "奖励",
|
||||
"workspace.referral.table.referral": "描述",
|
||||
"workspace.referral.table.date": "日期",
|
||||
"workspace.referral.reward.description.inviter": "已邀请 {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "由 {{email}} 邀请",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "订阅以解锁",
|
||||
"workspace.referral.reward.action.view": "查看奖励",
|
||||
"workspace.referral.reward.action.applied": "奖励已使用",
|
||||
"workspace.referral.reward.source.pendingInviter": "等待对方订阅",
|
||||
"workspace.referral.reward.source.pendingInvitee": "订阅即可解锁奖励",
|
||||
"workspace.referral.reward.source.available": "奖励可使用",
|
||||
"workspace.referral.reward.source.applied": "奖励已使用",
|
||||
"workspace.referral.reward.status.applied": "奖励已使用",
|
||||
"workspace.referral.reward.status.pendingInviter": "订阅以解锁",
|
||||
"workspace.referral.reward.status.pendingInvitee": "订阅以解锁",
|
||||
"workspace.referral.apply.noGo": "订阅以解锁",
|
||||
"workspace.referral.apply.preview": "查看奖励",
|
||||
"workspace.referral.apply.action": "使用",
|
||||
"workspace.referral.apply.confirmTitle": "使用奖励",
|
||||
"workspace.referral.apply.confirmBody": "使用 {{amount}} 抵扣当前工作区的用量。",
|
||||
"workspace.referral.apply.confirmAction": "使用",
|
||||
|
||||
"download.title": "OpenCode | 下载",
|
||||
"download.meta.description": "下载适用于 macOS, Windows, 和 Linux 的 OpenCode",
|
||||
"download.hero.title": "下载 OpenCode",
|
||||
|
||||
@@ -643,6 +643,39 @@ export const dict = {
|
||||
"workspace.lite.promo.otherMethods": "其他付款方式",
|
||||
"workspace.lite.promo.selectMethod": "選擇付款方式",
|
||||
|
||||
"workspace.referral.copyLink": "複製連結",
|
||||
"workspace.referral.copied": "已複製",
|
||||
"workspace.referral.overview.title": "邀請朋友",
|
||||
"workspace.referral.overview.subtitle": "朋友訂閱後,您可獲得 $5,對方也可獲得 $5。",
|
||||
"workspace.referral.instructions.share": "分享您的推薦連結。",
|
||||
"workspace.referral.instructions.subscribe": "朋友加入並訂閱 Go。",
|
||||
"workspace.referral.instructions.claim": "你們都將獲得 $5 使用額度,可用於您的 Go 使用限額。",
|
||||
"workspace.referral.rewards.title": "邀請獎勵",
|
||||
"workspace.referral.rewards.description": "將可用的邀請點數套用至您的 Go 使用量。",
|
||||
"workspace.referral.rewards.subtitle": "已使用 {{applied}} / {{total}} 個獎勵。",
|
||||
"workspace.referral.rewards.empty": "暫無邀請獎勵。",
|
||||
"workspace.referral.table.reward": "獎勵",
|
||||
"workspace.referral.table.referral": "描述",
|
||||
"workspace.referral.table.date": "日期",
|
||||
"workspace.referral.reward.description.inviter": "已邀請 {{email}}",
|
||||
"workspace.referral.reward.description.invitee": "由 {{email}} 邀請",
|
||||
"workspace.referral.reward.action.subscribeUnlock": "訂閱以解鎖",
|
||||
"workspace.referral.reward.action.view": "查看獎勵",
|
||||
"workspace.referral.reward.action.applied": "獎勵已使用",
|
||||
"workspace.referral.reward.source.pendingInviter": "等待對方訂閱",
|
||||
"workspace.referral.reward.source.pendingInvitee": "訂閱即可解鎖獎勵",
|
||||
"workspace.referral.reward.source.available": "獎勵可使用",
|
||||
"workspace.referral.reward.source.applied": "獎勵已使用",
|
||||
"workspace.referral.reward.status.applied": "獎勵已使用",
|
||||
"workspace.referral.reward.status.pendingInviter": "訂閱以解鎖",
|
||||
"workspace.referral.reward.status.pendingInvitee": "訂閱以解鎖",
|
||||
"workspace.referral.apply.noGo": "訂閱以解鎖",
|
||||
"workspace.referral.apply.preview": "查看獎勵",
|
||||
"workspace.referral.apply.action": "使用",
|
||||
"workspace.referral.apply.confirmTitle": "使用獎勵",
|
||||
"workspace.referral.apply.confirmBody": "使用 {{amount}} 抵扣目前工作區的用量。",
|
||||
"workspace.referral.apply.confirmAction": "使用",
|
||||
|
||||
"download.title": "OpenCode | 下載",
|
||||
"download.meta.description": "下載適用於 macOS、Windows 與 Linux 的 OpenCode",
|
||||
"download.hero.title": "下載 OpenCode",
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Key } from "~/i18n"
|
||||
import type { useI18n } from "~/context/i18n"
|
||||
|
||||
type ResetTimeKeys = {
|
||||
day: Key
|
||||
days: Key
|
||||
hour: Key
|
||||
hours: Key
|
||||
minute: Key
|
||||
minutes: Key
|
||||
fewSeconds: Key
|
||||
}
|
||||
|
||||
export const liteResetTimeKeys = {
|
||||
day: "workspace.lite.time.day",
|
||||
days: "workspace.lite.time.days",
|
||||
hour: "workspace.lite.time.hour",
|
||||
hours: "workspace.lite.time.hours",
|
||||
minute: "workspace.lite.time.minute",
|
||||
minutes: "workspace.lite.time.minutes",
|
||||
fewSeconds: "workspace.lite.time.fewSeconds",
|
||||
} satisfies ResetTimeKeys
|
||||
|
||||
export const blackResetTimeKeys = {
|
||||
day: "workspace.black.time.day",
|
||||
days: "workspace.black.time.days",
|
||||
hour: "workspace.black.time.hour",
|
||||
hours: "workspace.black.time.hours",
|
||||
minute: "workspace.black.time.minute",
|
||||
minutes: "workspace.black.time.minutes",
|
||||
fewSeconds: "workspace.black.time.fewSeconds",
|
||||
} satisfies ResetTimeKeys
|
||||
|
||||
export function formatResetTime(seconds: number, i18n: ReturnType<typeof useI18n>, keys: ResetTimeKeys) {
|
||||
const days = Math.floor(seconds / 86400)
|
||||
if (days >= 1) {
|
||||
const hours = Math.floor((seconds % 86400) / 3600)
|
||||
return `${days} ${days === 1 ? i18n.t(keys.day) : i18n.t(keys.days)} ${hours} ${hours === 1 ? i18n.t(keys.hour) : i18n.t(keys.hours)}`
|
||||
}
|
||||
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
if (hours >= 1)
|
||||
return `${hours} ${hours === 1 ? i18n.t(keys.hour) : i18n.t(keys.hours)} ${minutes} ${minutes === 1 ? i18n.t(keys.minute) : i18n.t(keys.minutes)}`
|
||||
if (minutes === 0) return i18n.t(keys.fewSeconds)
|
||||
return `${minutes} ${minutes === 1 ? i18n.t(keys.minute) : i18n.t(keys.minutes)}`
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export const LOCALES = [
|
||||
"ja",
|
||||
"pl",
|
||||
"ru",
|
||||
"uk",
|
||||
"ar",
|
||||
"no",
|
||||
"br",
|
||||
@@ -41,6 +42,7 @@ const LABEL = {
|
||||
ja: "日本語",
|
||||
pl: "Polski",
|
||||
ru: "Русский",
|
||||
uk: "Українська",
|
||||
ar: "العربية",
|
||||
no: "Norsk",
|
||||
br: "Português (Brasil)",
|
||||
@@ -61,6 +63,7 @@ const TAG = {
|
||||
ja: "ja",
|
||||
pl: "pl",
|
||||
ru: "ru",
|
||||
uk: "uk",
|
||||
ar: "ar",
|
||||
no: "no",
|
||||
br: "pt-BR",
|
||||
@@ -81,6 +84,7 @@ const DOCS = {
|
||||
ja: "ja",
|
||||
pl: "pl",
|
||||
ru: "ru",
|
||||
uk: "uk",
|
||||
ar: "ar",
|
||||
no: "nb",
|
||||
br: "pt-br",
|
||||
@@ -104,6 +108,7 @@ const DOCS_SEGMENT = new Set([
|
||||
"ru",
|
||||
"th",
|
||||
"tr",
|
||||
"uk",
|
||||
"zh-cn",
|
||||
"zh-tw",
|
||||
])
|
||||
@@ -124,6 +129,7 @@ const DOCS_LOCALE = {
|
||||
ru: "ru",
|
||||
th: "th",
|
||||
tr: "tr",
|
||||
uk: "uk",
|
||||
"zh-cn": "zh",
|
||||
"zh-tw": "zht",
|
||||
} as const satisfies Record<string, Locale>
|
||||
@@ -239,6 +245,7 @@ function match(input: string): Locale | null {
|
||||
if (value.startsWith("ja")) return "ja"
|
||||
if (value.startsWith("pl")) return "pl"
|
||||
if (value.startsWith("ru")) return "ru"
|
||||
if (value.startsWith("uk")) return "uk"
|
||||
if (value.startsWith("ar")) return "ar"
|
||||
if (value.startsWith("tr")) return "tr"
|
||||
if (value.startsWith("th")) return "th"
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Referral } from "@opencode-ai/console-core/referral.js"
|
||||
|
||||
const REFERRAL_COOKIE = "oc_referral"
|
||||
const REFERRAL_MAX_AGE = 60 * 60 * 24 * 30
|
||||
|
||||
export function normalizeReferralCode(code?: string | null) {
|
||||
return Referral.normalizeCode(code)
|
||||
}
|
||||
|
||||
export function referralCookie(code: string) {
|
||||
return `${REFERRAL_COOKIE}=${encodeURIComponent(code)}; Path=/; Max-Age=${REFERRAL_MAX_AGE}; SameSite=Lax; HttpOnly`
|
||||
}
|
||||
|
||||
export function clearReferralCookie() {
|
||||
return `${REFERRAL_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly`
|
||||
}
|
||||
|
||||
export function referralCodeFromCookieHeader(header: string | null) {
|
||||
if (!header) return undefined
|
||||
|
||||
return normalizeReferralCode(
|
||||
header
|
||||
.split(";")
|
||||
.map((x) => x.trim())
|
||||
.find((x) => x.startsWith(`${REFERRAL_COOKIE}=`))
|
||||
?.slice(`${REFERRAL_COOKIE}=`.length),
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
import { createMiddleware } from "@solidjs/start/middleware"
|
||||
import { LOCALE_HEADER, cookie, fromPathname, strip } from "~/lib/language"
|
||||
import { normalizeReferralCode, referralCookie } from "~/lib/referral-invite"
|
||||
|
||||
export default createMiddleware({
|
||||
onRequest(event) {
|
||||
const url = new URL(event.request.url)
|
||||
const locale = fromPathname(url.pathname)
|
||||
if (!locale) return
|
||||
if (locale) {
|
||||
url.pathname = strip(url.pathname)
|
||||
const request = new Request(url, event.request)
|
||||
request.headers.set(LOCALE_HEADER, locale)
|
||||
event.request = request
|
||||
event.response.headers.append("set-cookie", cookie(locale))
|
||||
}
|
||||
|
||||
url.pathname = strip(url.pathname)
|
||||
const request = new Request(url, event.request)
|
||||
request.headers.set(LOCALE_HEADER, locale)
|
||||
event.request = request
|
||||
event.response.headers.append("set-cookie", cookie(locale))
|
||||
const referralCode = normalizeReferralCode(url.searchParams.get("ref"))
|
||||
if (referralCode) event.response.headers.append("set-cookie", referralCookie(referralCode))
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { redirect } from "@solidjs/router"
|
||||
import type { APIEvent } from "@solidjs/start/server"
|
||||
import { Referral } from "@opencode-ai/console-core/referral.js"
|
||||
import { AuthClient } from "~/context/auth"
|
||||
import { useAuthSession } from "~/context/auth"
|
||||
import { i18n } from "~/i18n"
|
||||
import { localeFromRequest, route } from "~/lib/language"
|
||||
import { clearReferralCookie, referralCodeFromCookieHeader } from "~/lib/referral-invite"
|
||||
|
||||
export async function GET(input: APIEvent) {
|
||||
const url = new URL(input.request.url)
|
||||
@@ -17,6 +19,7 @@ export async function GET(input: APIEvent) {
|
||||
if (result.err) throw new Error(result.err.message)
|
||||
const decoded = AuthClient.decode(result.tokens.access, {} as any)
|
||||
if (decoded.err) throw new Error(decoded.err.message)
|
||||
const referralCode = referralCodeFromCookieHeader(input.request.headers.get("cookie"))
|
||||
const session = await useAuthSession()
|
||||
const id = decoded.subject.properties.accountID
|
||||
await session.update((value) => {
|
||||
@@ -32,8 +35,15 @@ export async function GET(input: APIEvent) {
|
||||
current: id,
|
||||
}
|
||||
})
|
||||
if (decoded.subject.properties.newAccount && referralCode) {
|
||||
await Referral.createFromAccount({ accountID: id, referralCode }).catch((error) => {
|
||||
console.error("Referral create failed", error)
|
||||
})
|
||||
}
|
||||
const next = url.pathname === "/auth/callback" ? "/auth" : url.pathname.replace("/auth/callback", "")
|
||||
return redirect(route(locale, next))
|
||||
const response = redirect(route(locale, next))
|
||||
if (referralCode) response.headers.append("set-cookie", clearReferralCookie())
|
||||
return response
|
||||
} catch (e: any) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
|
||||
@@ -700,65 +700,6 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="workspace-picker"] {
|
||||
[data-slot="workspace-list"] {
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
align-self: stretch;
|
||||
outline: none;
|
||||
overflow-y: auto;
|
||||
max-height: 240px;
|
||||
scrollbar-width: none;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-slot="workspace-item"] {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
padding: 8px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
align-self: stretch;
|
||||
cursor: pointer;
|
||||
|
||||
[data-slot="selected-icon"] {
|
||||
visibility: hidden;
|
||||
color: rgba(255, 255, 255, 0.39);
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 16px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 160%;
|
||||
}
|
||||
|
||||
span:last-child {
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-size: 16px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 160%;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-active="true"] {
|
||||
background: #161616;
|
||||
|
||||
[data-slot="selected-icon"] {
|
||||
visibility: visible;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -839,3 +780,64 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="black-workspace-picker-modal"] {
|
||||
font-family: var(--font-mono);
|
||||
|
||||
[data-slot="workspace-list"] {
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
align-self: stretch;
|
||||
outline: none;
|
||||
overflow-y: auto;
|
||||
max-height: 240px;
|
||||
scrollbar-width: none;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="workspace-item"] {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
padding: 8px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
align-self: stretch;
|
||||
cursor: pointer;
|
||||
|
||||
[data-slot="selected-icon"] {
|
||||
visibility: hidden;
|
||||
color: rgba(255, 255, 255, 0.39);
|
||||
font-family: "IBM Plex Mono", monospace;
|
||||
font-size: 16px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 160%;
|
||||
}
|
||||
|
||||
span:last-child {
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-size: 16px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 160%;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-active="true"] {
|
||||
background: #161616;
|
||||
|
||||
[data-slot="selected-icon"] {
|
||||
visibility: visible;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,8 +444,13 @@ export default function BlackSubscribe() {
|
||||
</div>
|
||||
|
||||
{/* Workspace picker modal */}
|
||||
<Modal open={showWorkspacePicker() ?? false} onClose={() => {}} title={i18n.t("black.workspace.selectPlan")}>
|
||||
<div data-slot="workspace-picker">
|
||||
<Modal
|
||||
open={showWorkspacePicker() ?? false}
|
||||
onClose={() => {}}
|
||||
title={i18n.t("black.workspace.selectPlan")}
|
||||
variant="black"
|
||||
>
|
||||
<div data-component="black-workspace-picker-modal" data-slot="workspace-picker">
|
||||
<ul
|
||||
ref={listRef}
|
||||
data-slot="workspace-list"
|
||||
|
||||
@@ -9,7 +9,7 @@ import { Actor } from "@opencode-ai/console-core/actor.js"
|
||||
import { Resource } from "@opencode-ai/console-resource"
|
||||
import { LiteData } from "@opencode-ai/console-core/lite.js"
|
||||
import { BlackData } from "@opencode-ai/console-core/black.js"
|
||||
import { User } from "@opencode-ai/console-core/user.js"
|
||||
import { Referral } from "@opencode-ai/console-core/referral.js"
|
||||
|
||||
export async function POST(input: APIEvent) {
|
||||
const body = await Billing.stripe().webhooks.constructEventAsync(
|
||||
@@ -174,6 +174,13 @@ export async function POST(input: APIEvent) {
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await Referral.completeFromLiteSubscription({
|
||||
workspaceID,
|
||||
userID,
|
||||
}).catch((error) => {
|
||||
console.error("Referral sync failed", error)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,10 @@
|
||||
background-color: var(--color-bg-surface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="workspace-create-modal"] {
|
||||
width: 100%;
|
||||
|
||||
[data-slot="create-form"] {
|
||||
width: 100%;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { query, useParams, action, createAsync, redirect, useSubmission } from "@solidjs/router"
|
||||
import { For, createEffect } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { For, createEffect, createSignal } from "solid-js"
|
||||
import { withActor } from "~/context/auth.withActor"
|
||||
import { Actor } from "@opencode-ai/console-core/actor.js"
|
||||
import { and, Database, eq, isNull } from "@opencode-ai/console-core/drizzle/index.js"
|
||||
@@ -51,9 +50,7 @@ export function WorkspacePicker() {
|
||||
const i18n = useI18n()
|
||||
const workspaces = createAsync(() => getWorkspaces())
|
||||
const submission = useSubmission(createWorkspace)
|
||||
const [store, setStore] = createStore({
|
||||
showForm: false,
|
||||
})
|
||||
const [showForm, setShowForm] = createSignal(false)
|
||||
let inputRef: HTMLInputElement | undefined
|
||||
|
||||
const currentWorkspace = () => {
|
||||
@@ -61,12 +58,8 @@ export function WorkspacePicker() {
|
||||
return ws ? ws.name : i18n.t("workspace.select")
|
||||
}
|
||||
|
||||
const handleWorkspaceNew = () => {
|
||||
setStore("showForm", true)
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (store.showForm && inputRef) {
|
||||
if (showForm() && inputRef) {
|
||||
setTimeout(() => inputRef?.focus(), 0)
|
||||
}
|
||||
})
|
||||
@@ -79,7 +72,7 @@ export function WorkspacePicker() {
|
||||
// Reset signals when workspace ID changes
|
||||
createEffect(() => {
|
||||
params.id
|
||||
setStore("showForm", false)
|
||||
setShowForm(false)
|
||||
})
|
||||
|
||||
return (
|
||||
@@ -92,32 +85,34 @@ export function WorkspacePicker() {
|
||||
</DropdownItem>
|
||||
)}
|
||||
</For>
|
||||
<button data-slot="create-item" type="button" onClick={() => handleWorkspaceNew()}>
|
||||
<button data-slot="create-item" type="button" onClick={() => setShowForm(true)}>
|
||||
{i18n.t("workspace.createNew")}
|
||||
</button>
|
||||
</Dropdown>
|
||||
|
||||
<Modal open={store.showForm} onClose={() => setStore("showForm", false)} title={i18n.t("workspace.modal.title")}>
|
||||
<form data-slot="create-form" action={createWorkspace} method="post">
|
||||
<div data-slot="create-input-group">
|
||||
<input
|
||||
ref={inputRef}
|
||||
data-slot="create-input"
|
||||
type="text"
|
||||
name="workspaceName"
|
||||
placeholder={i18n.t("workspace.modal.placeholder")}
|
||||
required
|
||||
/>
|
||||
<div data-slot="button-group">
|
||||
<button type="button" data-color="ghost" onClick={() => setStore("showForm", false)}>
|
||||
{i18n.t("common.cancel")}
|
||||
</button>
|
||||
<button type="submit" data-color="primary" disabled={submission.pending}>
|
||||
{submission.pending ? i18n.t("common.creating") : i18n.t("common.create")}
|
||||
</button>
|
||||
<Modal open={showForm()} onClose={() => setShowForm(false)} title={i18n.t("workspace.modal.title")}>
|
||||
<div data-component="workspace-create-modal">
|
||||
<form data-slot="create-form" action={createWorkspace} method="post">
|
||||
<div data-slot="create-input-group">
|
||||
<input
|
||||
ref={inputRef}
|
||||
data-slot="create-input"
|
||||
type="text"
|
||||
name="workspaceName"
|
||||
placeholder={i18n.t("workspace.modal.placeholder")}
|
||||
required
|
||||
/>
|
||||
<div data-slot="button-group">
|
||||
<button type="button" data-color="ghost" onClick={() => setShowForm(false)}>
|
||||
{i18n.t("common.cancel")}
|
||||
</button>
|
||||
<button type="submit" data-color="primary" disabled={submission.pending}>
|
||||
{submission.pending ? i18n.t("common.creating") : i18n.t("common.create")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</form>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import styles from "./black-section.module.css"
|
||||
import waitlistStyles from "./black-waitlist-section.module.css"
|
||||
import { useI18n } from "~/context/i18n"
|
||||
import { formError } from "~/lib/form-error"
|
||||
import { blackResetTimeKeys, formatResetTime } from "~/lib/format-reset-time"
|
||||
|
||||
const querySubscription = query(async (workspaceID: string) => {
|
||||
"use server"
|
||||
@@ -52,20 +53,6 @@ const querySubscription = query(async (workspaceID: string) => {
|
||||
}, workspaceID)
|
||||
}, "subscription.get")
|
||||
|
||||
function formatResetTime(seconds: number, i18n: ReturnType<typeof useI18n>) {
|
||||
const days = Math.floor(seconds / 86400)
|
||||
if (days >= 1) {
|
||||
const hours = Math.floor((seconds % 86400) / 3600)
|
||||
return `${days} ${days === 1 ? i18n.t("workspace.black.time.day") : i18n.t("workspace.black.time.days")} ${hours} ${hours === 1 ? i18n.t("workspace.black.time.hour") : i18n.t("workspace.black.time.hours")}`
|
||||
}
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
if (hours >= 1)
|
||||
return `${hours} ${hours === 1 ? i18n.t("workspace.black.time.hour") : i18n.t("workspace.black.time.hours")} ${minutes} ${minutes === 1 ? i18n.t("workspace.black.time.minute") : i18n.t("workspace.black.time.minutes")}`
|
||||
if (minutes === 0) return i18n.t("workspace.black.time.fewSeconds")
|
||||
return `${minutes} ${minutes === 1 ? i18n.t("workspace.black.time.minute") : i18n.t("workspace.black.time.minutes")}`
|
||||
}
|
||||
|
||||
const cancelWaitlist = action(async (workspaceID: string) => {
|
||||
"use server"
|
||||
return json(
|
||||
@@ -209,7 +196,7 @@ export function BlackSection() {
|
||||
</div>
|
||||
<span data-slot="reset-time">
|
||||
{i18n.t("workspace.black.subscription.resetsIn")}{" "}
|
||||
{formatResetTime(sub().rollingUsage.resetInSec, i18n)}
|
||||
{formatResetTime(sub().rollingUsage.resetInSec, i18n, blackResetTimeKeys)}
|
||||
</span>
|
||||
</div>
|
||||
<div data-slot="usage-item">
|
||||
@@ -222,7 +209,7 @@ export function BlackSection() {
|
||||
</div>
|
||||
<span data-slot="reset-time">
|
||||
{i18n.t("workspace.black.subscription.resetsIn")}{" "}
|
||||
{formatResetTime(sub().weeklyUsage.resetInSec, i18n)}
|
||||
{formatResetTime(sub().weeklyUsage.resetInSec, i18n, blackResetTimeKeys)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { createAsync, useParams } from "@solidjs/router"
|
||||
import { Show } from "solid-js"
|
||||
import { IconGo } from "~/component/icon"
|
||||
import { GoReferralSection, queryGoReferral } from "~/component/go-referral"
|
||||
import { useI18n } from "~/context/i18n"
|
||||
import { useLanguage } from "~/context/language"
|
||||
import { LiteSection } from "./lite-section"
|
||||
import { LiteSection, queryLiteSubscription } from "./lite-section"
|
||||
|
||||
export default function () {
|
||||
const params = useParams()
|
||||
const i18n = useI18n()
|
||||
const language = useLanguage()
|
||||
const referral = createAsync(() => queryGoReferral(params.id!))
|
||||
const lite = createAsync(() => queryLiteSubscription(params.id!))
|
||||
|
||||
return (
|
||||
<div data-page="workspace-[id]">
|
||||
@@ -23,7 +29,10 @@ export default function () {
|
||||
</section>
|
||||
|
||||
<div data-slot="sections">
|
||||
<LiteSection />
|
||||
<LiteSection lite={lite()} />
|
||||
<Show when={referral()} fallback={<section>{i18n.t("workspace.lite.loading")}</section>}>
|
||||
{(summary) => <GoReferralSection workspaceID={params.id!} summary={summary()} lite={lite()} />}
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -211,7 +211,9 @@
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.paymentMethodModal {
|
||||
[data-slot="modal-actions"] {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
|
||||
@@ -14,10 +14,11 @@ import styles from "./lite-section.module.css"
|
||||
import { useI18n } from "~/context/i18n"
|
||||
import { useLanguage } from "~/context/language"
|
||||
import { formError } from "~/lib/form-error"
|
||||
import { formatResetTime, liteResetTimeKeys } from "~/lib/format-reset-time"
|
||||
|
||||
import { IconAlipay, IconUpi } from "~/component/icon"
|
||||
|
||||
const queryLiteSubscription = query(async (workspaceID: string) => {
|
||||
export const queryLiteSubscription = query(async (workspaceID: string) => {
|
||||
"use server"
|
||||
return withActor(async () => {
|
||||
const row = await Database.use((tx) =>
|
||||
@@ -67,19 +68,7 @@ const queryLiteSubscription = query(async (workspaceID: string) => {
|
||||
}, workspaceID)
|
||||
}, "lite.subscription.get")
|
||||
|
||||
function formatResetTime(seconds: number, i18n: ReturnType<typeof useI18n>) {
|
||||
const days = Math.floor(seconds / 86400)
|
||||
if (days >= 1) {
|
||||
const hours = Math.floor((seconds % 86400) / 3600)
|
||||
return `${days} ${days === 1 ? i18n.t("workspace.lite.time.day") : i18n.t("workspace.lite.time.days")} ${hours} ${hours === 1 ? i18n.t("workspace.lite.time.hour") : i18n.t("workspace.lite.time.hours")}`
|
||||
}
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
if (hours >= 1)
|
||||
return `${hours} ${hours === 1 ? i18n.t("workspace.lite.time.hour") : i18n.t("workspace.lite.time.hours")} ${minutes} ${minutes === 1 ? i18n.t("workspace.lite.time.minute") : i18n.t("workspace.lite.time.minutes")}`
|
||||
if (minutes === 0) return i18n.t("workspace.lite.time.fewSeconds")
|
||||
return `${minutes} ${minutes === 1 ? i18n.t("workspace.lite.time.minute") : i18n.t("workspace.lite.time.minutes")}`
|
||||
}
|
||||
type LiteSubscription = Awaited<ReturnType<typeof queryLiteSubscription>>
|
||||
|
||||
const createLiteCheckoutUrl = action(
|
||||
async (workspaceID: string, successUrl: string, cancelUrl: string, method?: "alipay" | "upi") => {
|
||||
@@ -140,13 +129,32 @@ const setLiteUseBalance = action(async (form: FormData) => {
|
||||
)
|
||||
}, "setLiteUseBalance")
|
||||
|
||||
export function LiteSection() {
|
||||
function LiteUsageItem(props: { label: string; usage: { usagePercent: number; resetInSec: number } }) {
|
||||
const i18n = useI18n()
|
||||
|
||||
return (
|
||||
<div data-slot="usage-item">
|
||||
<div data-slot="usage-header">
|
||||
<span data-slot="usage-label">{props.label}</span>
|
||||
<span data-slot="usage-value">{props.usage.usagePercent}%</span>
|
||||
</div>
|
||||
<div data-slot="progress">
|
||||
<div data-slot="progress-bar" style={{ width: `${props.usage.usagePercent}%` }} />
|
||||
</div>
|
||||
<span data-slot="reset-time">
|
||||
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
|
||||
{formatResetTime(props.usage.resetInSec, i18n, liteResetTimeKeys)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function LiteSection(props: { lite: LiteSubscription | undefined }) {
|
||||
const params = useParams()
|
||||
const i18n = useI18n()
|
||||
const language = useLanguage()
|
||||
const billingInfo = createAsync(() => queryBillingInfo(params.id!))
|
||||
const isBlack = createMemo(() => billingInfo()?.subscriptionID || billingInfo()?.timeSubscriptionBooked)
|
||||
const lite = createAsync(() => queryLiteSubscription(params.id!))
|
||||
const sessionAction = useAction(createSessionUrl)
|
||||
const sessionSubmission = useSubmission(createSessionUrl)
|
||||
const checkoutAction = useAction(createLiteCheckoutUrl)
|
||||
@@ -186,7 +194,7 @@ export function LiteSection() {
|
||||
<p data-slot="other-message">{i18n.t("workspace.lite.black.message")}</p>
|
||||
</section>
|
||||
</Show>
|
||||
<Show when={!isBlack() && lite() && lite()!.mine && lite()!}>
|
||||
<Show when={!isBlack() && props.lite && props.lite.mine && props.lite}>
|
||||
{(sub) => (
|
||||
<section class={styles.root}>
|
||||
<div data-slot="section-title">
|
||||
@@ -207,44 +215,9 @@ export function LiteSection() {
|
||||
.
|
||||
</div>
|
||||
<div data-slot="usage">
|
||||
<div data-slot="usage-item">
|
||||
<div data-slot="usage-header">
|
||||
<span data-slot="usage-label">{i18n.t("workspace.lite.subscription.rollingUsage")}</span>
|
||||
<span data-slot="usage-value">{sub().rollingUsage.usagePercent}%</span>
|
||||
</div>
|
||||
<div data-slot="progress">
|
||||
<div data-slot="progress-bar" style={{ width: `${sub().rollingUsage.usagePercent}%` }} />
|
||||
</div>
|
||||
<span data-slot="reset-time">
|
||||
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
|
||||
{formatResetTime(sub().rollingUsage.resetInSec, i18n)}
|
||||
</span>
|
||||
</div>
|
||||
<div data-slot="usage-item">
|
||||
<div data-slot="usage-header">
|
||||
<span data-slot="usage-label">{i18n.t("workspace.lite.subscription.weeklyUsage")}</span>
|
||||
<span data-slot="usage-value">{sub().weeklyUsage.usagePercent}%</span>
|
||||
</div>
|
||||
<div data-slot="progress">
|
||||
<div data-slot="progress-bar" style={{ width: `${sub().weeklyUsage.usagePercent}%` }} />
|
||||
</div>
|
||||
<span data-slot="reset-time">
|
||||
{i18n.t("workspace.lite.subscription.resetsIn")} {formatResetTime(sub().weeklyUsage.resetInSec, i18n)}
|
||||
</span>
|
||||
</div>
|
||||
<div data-slot="usage-item">
|
||||
<div data-slot="usage-header">
|
||||
<span data-slot="usage-label">{i18n.t("workspace.lite.subscription.monthlyUsage")}</span>
|
||||
<span data-slot="usage-value">{sub().monthlyUsage.usagePercent}%</span>
|
||||
</div>
|
||||
<div data-slot="progress">
|
||||
<div data-slot="progress-bar" style={{ width: `${sub().monthlyUsage.usagePercent}%` }} />
|
||||
</div>
|
||||
<span data-slot="reset-time">
|
||||
{i18n.t("workspace.lite.subscription.resetsIn")}{" "}
|
||||
{formatResetTime(sub().monthlyUsage.resetInSec, i18n)}
|
||||
</span>
|
||||
</div>
|
||||
<LiteUsageItem label={i18n.t("workspace.lite.subscription.rollingUsage")} usage={sub().rollingUsage} />
|
||||
<LiteUsageItem label={i18n.t("workspace.lite.subscription.weeklyUsage")} usage={sub().weeklyUsage} />
|
||||
<LiteUsageItem label={i18n.t("workspace.lite.subscription.monthlyUsage")} usage={sub().monthlyUsage} />
|
||||
</div>
|
||||
<form action={setLiteUseBalance} method="post" data-slot="setting-row">
|
||||
<p>{i18n.t("workspace.lite.subscription.useBalance")}</p>
|
||||
@@ -263,12 +236,12 @@ export function LiteSection() {
|
||||
</section>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={!isBlack() && lite() && !lite()!.mine}>
|
||||
<Show when={!isBlack() && props.lite && !props.lite.mine}>
|
||||
<section class={styles.root}>
|
||||
<p data-slot="other-message">{i18n.t("workspace.lite.other.message")}</p>
|
||||
</section>
|
||||
</Show>
|
||||
<Show when={!isBlack() && lite() === null}>
|
||||
<Show when={!isBlack() && props.lite === null}>
|
||||
<section class={styles.root}>
|
||||
<p data-slot="promo-description">
|
||||
<For
|
||||
@@ -330,31 +303,33 @@ export function LiteSection() {
|
||||
onClose={() => setStore("showModal", false)}
|
||||
title={i18n.t("workspace.lite.promo.selectMethod")}
|
||||
>
|
||||
<div data-slot="modal-actions">
|
||||
<button
|
||||
type="button"
|
||||
data-slot="method-button"
|
||||
data-color="ghost"
|
||||
disabled={checkoutSubmission.pending || busy()}
|
||||
onClick={() => onClickSubscribe("alipay")}
|
||||
>
|
||||
<Show when={store.loading !== "alipay"}>
|
||||
<IconAlipay style={{ width: "24px", height: "24px" }} />
|
||||
</Show>
|
||||
{store.loading === "alipay" ? i18n.t("workspace.lite.promo.subscribing") : "Alipay"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-slot="method-button"
|
||||
data-color="ghost"
|
||||
disabled={checkoutSubmission.pending || busy()}
|
||||
onClick={() => onClickSubscribe("upi")}
|
||||
>
|
||||
<Show when={store.loading !== "upi"}>
|
||||
<IconUpi style={{ width: "auto", height: "16px" }} />
|
||||
</Show>
|
||||
{store.loading === "upi" ? i18n.t("workspace.lite.promo.subscribing") : "UPI"}
|
||||
</button>
|
||||
<div class={styles.paymentMethodModal}>
|
||||
<div data-slot="modal-actions">
|
||||
<button
|
||||
type="button"
|
||||
data-slot="method-button"
|
||||
data-color="ghost"
|
||||
disabled={checkoutSubmission.pending || busy()}
|
||||
onClick={() => onClickSubscribe("alipay")}
|
||||
>
|
||||
<Show when={store.loading !== "alipay"}>
|
||||
<IconAlipay style={{ width: "24px", height: "24px" }} />
|
||||
</Show>
|
||||
{store.loading === "alipay" ? i18n.t("workspace.lite.promo.subscribing") : "Alipay"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-slot="method-button"
|
||||
data-color="ghost"
|
||||
disabled={checkoutSubmission.pending || busy()}
|
||||
onClick={() => onClickSubscribe("upi")}
|
||||
>
|
||||
<Show when={store.loading !== "upi"}>
|
||||
<IconUpi style={{ width: "auto", height: "16px" }} />
|
||||
</Show>
|
||||
{store.loading === "upi" ? i18n.t("workspace.lite.promo.subscribing") : "UPI"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</section>
|
||||
|
||||
@@ -170,6 +170,10 @@ export async function handler(
|
||||
if (v === "$ip") return [[k, ip]]
|
||||
if (v === "$workspace") return authInfo?.workspaceID ? [[k, authInfo?.workspaceID]] : []
|
||||
if (v === "$session") return sessionId ? [[k, sessionId]] : []
|
||||
if (v === "$user") {
|
||||
const user = sessionId ?? authInfo?.workspaceID ?? ip
|
||||
return user ? [[k, user]] : []
|
||||
}
|
||||
if (v.startsWith("$header.")) {
|
||||
const headerValue = input.request.headers.get(v.slice(8))
|
||||
return headerValue ? [[k, headerValue]] : []
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
CREATE TABLE `referral_code` (
|
||||
`id` varchar(30) NOT NULL,
|
||||
`workspace_id` varchar(30) NOT NULL,
|
||||
`time_created` timestamp(3) NOT NULL DEFAULT (now()),
|
||||
`time_updated` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
`time_deleted` timestamp(3),
|
||||
`code` varchar(10) NOT NULL,
|
||||
CONSTRAINT PRIMARY KEY(`workspace_id`,`id`),
|
||||
CONSTRAINT `referral_code_workspace_id` UNIQUE INDEX(`workspace_id`),
|
||||
CONSTRAINT `referral_code_code` UNIQUE INDEX(`code`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `referral_reward` (
|
||||
`id` varchar(30) NOT NULL,
|
||||
`workspace_id` varchar(30) NOT NULL,
|
||||
`time_created` timestamp(3) NOT NULL DEFAULT (now()),
|
||||
`time_updated` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
`time_deleted` timestamp(3),
|
||||
`referral_id` varchar(30) NOT NULL,
|
||||
`source` enum('inviter','invitee') NOT NULL,
|
||||
`amount` bigint NOT NULL,
|
||||
`applied_by_user_id` varchar(30),
|
||||
`time_applied` timestamp(3),
|
||||
CONSTRAINT PRIMARY KEY(`workspace_id`,`id`),
|
||||
CONSTRAINT `referral_reward_referral_source` UNIQUE INDEX(`referral_id`,`source`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `referral` (
|
||||
`id` varchar(30) NOT NULL,
|
||||
`workspace_id` varchar(30) NOT NULL,
|
||||
`time_created` timestamp(3) NOT NULL DEFAULT (now()),
|
||||
`time_updated` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
`time_deleted` timestamp(3),
|
||||
`inviter_workspace_id` varchar(30) NOT NULL,
|
||||
`invitee_account_id` varchar(30) NOT NULL,
|
||||
`invitee_user_id` varchar(30) NOT NULL,
|
||||
`referral_code_id` varchar(30) NOT NULL,
|
||||
`stripe_customer_id` varchar(255) NOT NULL,
|
||||
`stripe_subscription_id` varchar(255) NOT NULL,
|
||||
CONSTRAINT PRIMARY KEY(`workspace_id`,`id`),
|
||||
CONSTRAINT `referral_invitee_account_id` UNIQUE INDEX(`invitee_account_id`),
|
||||
CONSTRAINT `referral_stripe_subscription_id` UNIQUE INDEX(`stripe_subscription_id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `referral_reward_workspace_time` ON `referral_reward` (`workspace_id`,`time_created`);--> statement-breakpoint
|
||||
CREATE INDEX `referral_inviter_workspace_id` ON `referral` (`inviter_workspace_id`);--> statement-breakpoint
|
||||
CREATE INDEX `referral_code_id` ON `referral` (`referral_code_id`);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
DROP TABLE `referral_code`;--> statement-breakpoint
|
||||
DROP INDEX `referral_reward_referral_source` ON `referral_reward`;--> statement-breakpoint
|
||||
DROP INDEX `referral_stripe_subscription_id` ON `referral`;--> statement-breakpoint
|
||||
DROP INDEX `referral_inviter_workspace_id` ON `referral`;--> statement-breakpoint
|
||||
DROP INDEX `referral_code_id` ON `referral`;--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` DROP PRIMARY KEY;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP PRIMARY KEY;--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` MODIFY COLUMN `workspace_id` varchar(30);--> statement-breakpoint
|
||||
ALTER TABLE `workspace` ADD `referral_code` varchar(16);--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` ADD PRIMARY KEY (`id`);--> statement-breakpoint
|
||||
ALTER TABLE `referral` ADD PRIMARY KEY (`id`);--> statement-breakpoint
|
||||
CREATE INDEX `referral_workspace_id` ON `referral` (`workspace_id`);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `workspace_referral_code` ON `workspace` (`referral_code`);--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` DROP COLUMN `source`;--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` DROP COLUMN `applied_by_user_id`;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP COLUMN `inviter_workspace_id`;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP COLUMN `invitee_user_id`;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP COLUMN `referral_code_id`;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP COLUMN `stripe_customer_id`;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP COLUMN `stripe_subscription_id`;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
DROP INDEX `referral_reward_workspace_time` ON `referral_reward`;--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` DROP PRIMARY KEY;--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` ADD PRIMARY KEY (`workspace_id`,`referral_id`);--> statement-breakpoint
|
||||
ALTER TABLE `referral_reward` DROP COLUMN `id`;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
DROP INDEX `referral_workspace_id` ON `referral`;--> statement-breakpoint
|
||||
ALTER TABLE `referral` DROP PRIMARY KEY;--> statement-breakpoint
|
||||
ALTER TABLE `referral` ADD PRIMARY KEY (`workspace_id`,`id`);
|
||||
+3013
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
UPDATE `workspace` SET `referral_code` = NULL WHERE CHAR_LENGTH(`referral_code`) > 10;--> statement-breakpoint
|
||||
ALTER TABLE `workspace` MODIFY COLUMN `referral_code` varchar(10);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
DROP INDEX `workspace_referral_code` ON `workspace`;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `referral_code` ON `workspace` (`referral_code`);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -155,6 +155,26 @@ export namespace Billing {
|
||||
return amountInMicroCents
|
||||
}
|
||||
|
||||
export const subtractLiteUsage = async (workspaceID: string, amountInMicroCents: number) => {
|
||||
await Database.transaction(async (tx) => {
|
||||
const lite = await tx
|
||||
.select({ id: LiteTable.id })
|
||||
.from(LiteTable)
|
||||
.where(and(eq(LiteTable.workspaceID, workspaceID), isNull(LiteTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (!lite) throw new Error("Subscribe to Go before applying referral rewards")
|
||||
|
||||
await tx
|
||||
.update(LiteTable)
|
||||
.set({
|
||||
monthlyUsage: sql`GREATEST(0, COALESCE(${LiteTable.monthlyUsage}, 0) - ${amountInMicroCents})`,
|
||||
weeklyUsage: sql`GREATEST(0, COALESCE(${LiteTable.weeklyUsage}, 0) - ${amountInMicroCents})`,
|
||||
rollingUsage: sql`GREATEST(0, COALESCE(${LiteTable.rollingUsage}, 0) - ${amountInMicroCents})`,
|
||||
})
|
||||
.where(and(eq(LiteTable.workspaceID, workspaceID), isNull(LiteTable.timeDeleted)))
|
||||
})
|
||||
}
|
||||
|
||||
export const redeemCoupon = async (email: string, type: (typeof CouponType)[number]) => {
|
||||
// validate coupon type
|
||||
await (async () => {
|
||||
|
||||
@@ -12,6 +12,7 @@ export namespace Identifier {
|
||||
model: "mod",
|
||||
payment: "pay",
|
||||
provider: "prv",
|
||||
referral: "ref",
|
||||
subscription: "sub",
|
||||
usage: "usg",
|
||||
user: "usr",
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
import { z } from "zod"
|
||||
import { and, asc, eq, isNull, sql, Database } from "./drizzle"
|
||||
import { Actor } from "./actor"
|
||||
import { Identifier } from "./identifier"
|
||||
import { LiteTable } from "./schema/billing.sql"
|
||||
import { ReferralRewardTable, ReferralTable } from "./schema/referral.sql"
|
||||
import { AuthTable } from "./schema/auth.sql"
|
||||
import { UserTable } from "./schema/user.sql"
|
||||
import { WorkspaceTable } from "./schema/workspace.sql"
|
||||
import { centsToMicroCents, microCentsToCents } from "./util/price"
|
||||
import { fn } from "./util/fn"
|
||||
import { Billing } from "./billing"
|
||||
import { LiteData } from "./lite"
|
||||
import { Subscription } from "./subscription"
|
||||
import { ulid } from "ulid"
|
||||
|
||||
export namespace Referral {
|
||||
export const REWARD_AMOUNT = centsToMicroCents(500)
|
||||
export const CODE_LENGTH = 10
|
||||
|
||||
export function normalizeCode(code?: string | null) {
|
||||
return code
|
||||
?.toUpperCase()
|
||||
.replace(/[^A-Z0-9]/g, "")
|
||||
.slice(0, CODE_LENGTH)
|
||||
}
|
||||
|
||||
function generateCode() {
|
||||
return ulid().slice(-CODE_LENGTH)
|
||||
}
|
||||
|
||||
async function ensureCode(workspaceID = Actor.workspace()) {
|
||||
return Database.transaction(async (tx) => {
|
||||
const existing = await tx
|
||||
.select({ code: WorkspaceTable.referralCode })
|
||||
.from(WorkspaceTable)
|
||||
.where(and(eq(WorkspaceTable.id, workspaceID), isNull(WorkspaceTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (!existing) throw new Error("Workspace not found")
|
||||
if (existing.code) return { code: existing.code }
|
||||
|
||||
for (const _ of Array.from({ length: 5 })) {
|
||||
await tx
|
||||
.update(WorkspaceTable)
|
||||
.set({ referralCode: generateCode() })
|
||||
.where(
|
||||
and(
|
||||
eq(WorkspaceTable.id, workspaceID),
|
||||
isNull(WorkspaceTable.referralCode),
|
||||
isNull(WorkspaceTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
|
||||
const created = await tx
|
||||
.select({ code: WorkspaceTable.referralCode })
|
||||
.from(WorkspaceTable)
|
||||
.where(and(eq(WorkspaceTable.id, workspaceID), isNull(WorkspaceTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (created?.code) return { code: created.code }
|
||||
}
|
||||
|
||||
throw new Error("Failed to generate referral code")
|
||||
})
|
||||
}
|
||||
|
||||
export const summary = fn(z.void(), async () => {
|
||||
const workspaceID = Actor.workspace()
|
||||
const accountID = Actor.account()
|
||||
const code = await ensureCode(workspaceID)
|
||||
const rows = await Database.use(async (tx) => {
|
||||
const [rewards, invites, inviteeReferral, inviteeRewards] = await Promise.all([
|
||||
tx
|
||||
.select({
|
||||
referralID: ReferralRewardTable.referralID,
|
||||
workspaceID: ReferralRewardTable.workspaceID,
|
||||
referralWorkspaceID: ReferralTable.workspaceID,
|
||||
inviteeEmail: AuthTable.subject,
|
||||
amount: ReferralRewardTable.amount,
|
||||
timeCreated: ReferralRewardTable.timeCreated,
|
||||
timeApplied: ReferralRewardTable.timeApplied,
|
||||
})
|
||||
.from(ReferralRewardTable)
|
||||
.innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
|
||||
.innerJoin(
|
||||
AuthTable,
|
||||
and(eq(AuthTable.accountID, ReferralTable.inviteeAccountID), eq(AuthTable.provider, "email")),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralRewardTable.workspaceID, workspaceID),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
isNull(ReferralTable.timeDeleted),
|
||||
),
|
||||
),
|
||||
tx
|
||||
.select({ id: ReferralTable.id, inviteeEmail: AuthTable.subject, timeCreated: ReferralTable.timeCreated })
|
||||
.from(ReferralTable)
|
||||
.innerJoin(
|
||||
AuthTable,
|
||||
and(eq(AuthTable.accountID, ReferralTable.inviteeAccountID), eq(AuthTable.provider, "email")),
|
||||
)
|
||||
.where(and(eq(ReferralTable.workspaceID, workspaceID), isNull(ReferralTable.timeDeleted))),
|
||||
tx
|
||||
.select({ id: ReferralTable.id, inviterEmail: AuthTable.subject, timeCreated: ReferralTable.timeCreated })
|
||||
.from(ReferralTable)
|
||||
.leftJoin(
|
||||
UserTable,
|
||||
and(
|
||||
eq(UserTable.workspaceID, ReferralTable.workspaceID),
|
||||
eq(UserTable.role, "admin"),
|
||||
isNull(UserTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
.leftJoin(AuthTable, and(eq(AuthTable.accountID, UserTable.accountID), eq(AuthTable.provider, "email")))
|
||||
.where(and(eq(ReferralTable.inviteeAccountID, accountID), isNull(ReferralTable.timeDeleted)))
|
||||
.orderBy(asc(UserTable.timeCreated))
|
||||
.then((rows) => rows.find((row) => row.inviterEmail) ?? rows[0]),
|
||||
tx
|
||||
.select({ referralID: ReferralRewardTable.referralID })
|
||||
.from(ReferralRewardTable)
|
||||
.innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralTable.inviteeAccountID, accountID),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
isNull(ReferralTable.timeDeleted),
|
||||
),
|
||||
),
|
||||
])
|
||||
|
||||
return { inviteeReferral, inviteeRewards, invites, rewards }
|
||||
})
|
||||
|
||||
const rewardReferralIDs = new Set(rows.rewards.map((reward) => reward.referralID))
|
||||
const inviteeRewardReferralIDs = new Set(rows.inviteeRewards.map((reward) => reward.referralID))
|
||||
const rewards = rows.rewards.map((reward) => {
|
||||
const source = reward.workspaceID === reward.referralWorkspaceID ? ("inviter" as const) : ("invitee" as const)
|
||||
return {
|
||||
id: reward.referralID,
|
||||
source,
|
||||
status: reward.timeApplied ? ("applied" as const) : ("available" as const),
|
||||
email: source === "invitee" ? (rows.inviteeReferral?.inviterEmail ?? null) : reward.inviteeEmail,
|
||||
amount: microCentsToCents(reward.amount),
|
||||
timeCreated: reward.timeCreated,
|
||||
timeApplied: reward.timeApplied,
|
||||
}
|
||||
})
|
||||
const pending = [
|
||||
...rows.invites
|
||||
.filter((referral) => !rewardReferralIDs.has(referral.id))
|
||||
.map((referral) => ({
|
||||
id: `${referral.id}:inviter`,
|
||||
source: "inviter" as const,
|
||||
status: "pending" as const,
|
||||
email: referral.inviteeEmail,
|
||||
amount: microCentsToCents(REWARD_AMOUNT),
|
||||
timeCreated: referral.timeCreated,
|
||||
timeApplied: null,
|
||||
})),
|
||||
...(rows.inviteeReferral && !inviteeRewardReferralIDs.has(rows.inviteeReferral.id)
|
||||
? [
|
||||
{
|
||||
id: `${rows.inviteeReferral.id}:invitee`,
|
||||
source: "invitee" as const,
|
||||
status: "pending" as const,
|
||||
email: rows.inviteeReferral.inviterEmail,
|
||||
amount: microCentsToCents(REWARD_AMOUNT),
|
||||
timeCreated: rows.inviteeReferral.timeCreated,
|
||||
timeApplied: null,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]
|
||||
const allRewards = [...pending, ...rewards].sort(
|
||||
(a, b) => new Date(b.timeCreated).getTime() - new Date(a.timeCreated).getTime(),
|
||||
)
|
||||
return {
|
||||
referralCode: code.code,
|
||||
hasReferral: allRewards.length > 0,
|
||||
rewardAmount: microCentsToCents(REWARD_AMOUNT),
|
||||
rewards: allRewards,
|
||||
}
|
||||
})
|
||||
|
||||
export const applyReward = fn(z.object({ referralID: z.string() }), async (input) => {
|
||||
const workspaceID = Actor.workspace()
|
||||
|
||||
return Database.transaction(async (tx) => {
|
||||
const reward = await tx
|
||||
.select({ amount: ReferralRewardTable.amount, timeApplied: ReferralRewardTable.timeApplied })
|
||||
.from(ReferralRewardTable)
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralRewardTable.workspaceID, workspaceID),
|
||||
eq(ReferralRewardTable.referralID, input.referralID),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0])
|
||||
if (!reward) throw new Error("Referral reward not found")
|
||||
if (reward.timeApplied) throw new Error("Referral reward already applied")
|
||||
|
||||
const update = await tx
|
||||
.update(ReferralRewardTable)
|
||||
.set({
|
||||
timeApplied: sql`now()`,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralRewardTable.workspaceID, workspaceID),
|
||||
eq(ReferralRewardTable.referralID, input.referralID),
|
||||
isNull(ReferralRewardTable.timeApplied),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
if (update.rowsAffected === 0) throw new Error("Referral reward already applied")
|
||||
|
||||
await Billing.subtractLiteUsage(workspaceID, reward.amount)
|
||||
|
||||
return { amount: microCentsToCents(reward.amount) }
|
||||
})
|
||||
})
|
||||
|
||||
export const usagePreview = fn(z.object({ referralID: z.string() }), async (input) => {
|
||||
const row = await Database.use((tx) =>
|
||||
tx
|
||||
.select({
|
||||
rewardAmount: ReferralRewardTable.amount,
|
||||
rollingUsage: LiteTable.rollingUsage,
|
||||
weeklyUsage: LiteTable.weeklyUsage,
|
||||
monthlyUsage: LiteTable.monthlyUsage,
|
||||
timeRollingUpdated: LiteTable.timeRollingUpdated,
|
||||
timeWeeklyUpdated: LiteTable.timeWeeklyUpdated,
|
||||
timeMonthlyUpdated: LiteTable.timeMonthlyUpdated,
|
||||
timeCreated: LiteTable.timeCreated,
|
||||
})
|
||||
.from(ReferralRewardTable)
|
||||
.innerJoin(LiteTable, eq(LiteTable.workspaceID, ReferralRewardTable.workspaceID))
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralRewardTable.workspaceID, Actor.workspace()),
|
||||
eq(ReferralRewardTable.referralID, input.referralID),
|
||||
isNull(ReferralRewardTable.timeApplied),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
isNull(LiteTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0]),
|
||||
)
|
||||
if (!row) return null
|
||||
|
||||
const limits = LiteData.getLimits()
|
||||
return {
|
||||
rollingUsage: usagePreviewItem(
|
||||
Subscription.analyzeRollingUsage({
|
||||
limit: limits.rollingLimit,
|
||||
window: limits.rollingWindow,
|
||||
usage: row.rollingUsage ?? 0,
|
||||
timeUpdated: row.timeRollingUpdated ?? new Date(),
|
||||
}),
|
||||
Subscription.analyzeRollingUsage({
|
||||
limit: limits.rollingLimit,
|
||||
window: limits.rollingWindow,
|
||||
usage: Math.max(0, (row.rollingUsage ?? 0) - row.rewardAmount),
|
||||
timeUpdated: row.timeRollingUpdated ?? new Date(),
|
||||
}),
|
||||
),
|
||||
weeklyUsage: usagePreviewItem(
|
||||
Subscription.analyzeWeeklyUsage({
|
||||
limit: limits.weeklyLimit,
|
||||
usage: row.weeklyUsage ?? 0,
|
||||
timeUpdated: row.timeWeeklyUpdated ?? new Date(),
|
||||
}),
|
||||
Subscription.analyzeWeeklyUsage({
|
||||
limit: limits.weeklyLimit,
|
||||
usage: Math.max(0, (row.weeklyUsage ?? 0) - row.rewardAmount),
|
||||
timeUpdated: row.timeWeeklyUpdated ?? new Date(),
|
||||
}),
|
||||
),
|
||||
monthlyUsage: usagePreviewItem(
|
||||
Subscription.analyzeMonthlyUsage({
|
||||
limit: limits.monthlyLimit,
|
||||
usage: row.monthlyUsage ?? 0,
|
||||
timeUpdated: row.timeMonthlyUpdated ?? new Date(),
|
||||
timeSubscribed: row.timeCreated,
|
||||
}),
|
||||
Subscription.analyzeMonthlyUsage({
|
||||
limit: limits.monthlyLimit,
|
||||
usage: Math.max(0, (row.monthlyUsage ?? 0) - row.rewardAmount),
|
||||
timeUpdated: row.timeMonthlyUpdated ?? new Date(),
|
||||
timeSubscribed: row.timeCreated,
|
||||
}),
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
export async function createFromAccount(input: { accountID: string; referralCode?: string }) {
|
||||
const referralCode = normalizeCode(input.referralCode)
|
||||
if (!referralCode) return
|
||||
|
||||
return Database.transaction(async (tx) => {
|
||||
const code = await tx
|
||||
.select({ workspaceID: WorkspaceTable.id })
|
||||
.from(WorkspaceTable)
|
||||
.where(and(eq(WorkspaceTable.referralCode, referralCode), isNull(WorkspaceTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (!code) throw new Error("Referral code invalid")
|
||||
|
||||
const existingReferral = await tx
|
||||
.select({ id: ReferralTable.id })
|
||||
.from(ReferralTable)
|
||||
.where(and(eq(ReferralTable.inviteeAccountID, input.accountID), isNull(ReferralTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (existingReferral) throw new Error("Referral already redeemed")
|
||||
|
||||
const selfReferral = await tx
|
||||
.select({ id: UserTable.id })
|
||||
.from(UserTable)
|
||||
.where(
|
||||
and(
|
||||
eq(UserTable.workspaceID, code.workspaceID),
|
||||
eq(UserTable.accountID, input.accountID),
|
||||
isNull(UserTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0])
|
||||
if (selfReferral) throw new Error("Self-referral is not allowed")
|
||||
|
||||
const referralID = Identifier.create("referral")
|
||||
await tx.insert(ReferralTable).ignore().values({
|
||||
workspaceID: code.workspaceID,
|
||||
id: referralID,
|
||||
inviteeAccountID: input.accountID,
|
||||
})
|
||||
|
||||
const referral = await tx
|
||||
.select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID })
|
||||
.from(ReferralTable)
|
||||
.where(and(eq(ReferralTable.inviteeAccountID, input.accountID), isNull(ReferralTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (!referral) throw new Error("Referral not created")
|
||||
if (referral.id !== referralID) throw new Error("Referral already redeemed")
|
||||
})
|
||||
}
|
||||
|
||||
export async function completeFromLiteSubscription(input: { workspaceID: string; userID: string }) {
|
||||
return Database.transaction(async (tx) => {
|
||||
const invitee = await tx
|
||||
.select({ accountID: UserTable.accountID })
|
||||
.from(UserTable)
|
||||
.where(
|
||||
and(
|
||||
eq(UserTable.workspaceID, input.workspaceID),
|
||||
eq(UserTable.id, input.userID),
|
||||
isNull(UserTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0])
|
||||
if (!invitee?.accountID) throw new Error("Referral invitee account missing")
|
||||
|
||||
const referral = await tx
|
||||
.select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID })
|
||||
.from(ReferralTable)
|
||||
.where(and(eq(ReferralTable.inviteeAccountID, invitee.accountID), isNull(ReferralTable.timeDeleted)))
|
||||
.then((rows) => rows[0])
|
||||
if (!referral) throw new Error("Referral not found")
|
||||
|
||||
const result = await tx
|
||||
.insert(ReferralRewardTable)
|
||||
.ignore()
|
||||
.values([
|
||||
{
|
||||
workspaceID: referral.workspaceID,
|
||||
referralID: referral.id,
|
||||
amount: REWARD_AMOUNT,
|
||||
},
|
||||
{
|
||||
workspaceID: input.workspaceID,
|
||||
referralID: referral.id,
|
||||
amount: REWARD_AMOUNT,
|
||||
},
|
||||
])
|
||||
|
||||
if (result.rowsAffected === 0) throw new Error("Referral already completed")
|
||||
})
|
||||
}
|
||||
|
||||
function usagePreviewItem(
|
||||
before: { usagePercent: number; resetInSec: number },
|
||||
after: { usagePercent: number; resetInSec: number },
|
||||
) {
|
||||
return {
|
||||
beforePercent: before.usagePercent,
|
||||
afterPercent: after.usagePercent,
|
||||
resetInSec: after.resetInSec,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { bigint, mysqlTable, primaryKey, uniqueIndex } from "drizzle-orm/mysql-core"
|
||||
import { timestamps, ulid, utc, workspaceColumns } from "../drizzle/types"
|
||||
import { workspaceIndexes } from "./workspace.sql"
|
||||
|
||||
export const ReferralTable = mysqlTable(
|
||||
"referral",
|
||||
{
|
||||
...workspaceColumns,
|
||||
...timestamps,
|
||||
inviteeAccountID: ulid("invitee_account_id").notNull(),
|
||||
},
|
||||
(table) => [...workspaceIndexes(table), uniqueIndex("referral_invitee_account_id").on(table.inviteeAccountID)],
|
||||
)
|
||||
|
||||
export const ReferralRewardTable = mysqlTable(
|
||||
"referral_reward",
|
||||
{
|
||||
workspaceID: ulid("workspace_id").notNull(),
|
||||
referralID: ulid("referral_id").notNull(),
|
||||
...timestamps,
|
||||
amount: bigint("amount", { mode: "number" }).notNull(),
|
||||
timeApplied: utc("time_applied"),
|
||||
},
|
||||
(table) => [primaryKey({ columns: [table.workspaceID, table.referralID] })],
|
||||
)
|
||||
@@ -6,10 +6,11 @@ export const WorkspaceTable = mysqlTable(
|
||||
{
|
||||
id: ulid("id").notNull().primaryKey(),
|
||||
slug: varchar("slug", { length: 255 }),
|
||||
referralCode: varchar("referral_code", { length: 10 }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [uniqueIndex("slug").on(table.slug)],
|
||||
(table) => [uniqueIndex("slug").on(table.slug), uniqueIndex("referral_code").on(table.referralCode)],
|
||||
)
|
||||
|
||||
export function workspaceIndexes(table: any) {
|
||||
|
||||
@@ -26,6 +26,7 @@ export const subjects = createSubjects({
|
||||
account: z.object({
|
||||
accountID: z.string(),
|
||||
email: z.string(),
|
||||
newAccount: z.boolean().optional(),
|
||||
}),
|
||||
user: z.object({
|
||||
userID: z.string(),
|
||||
@@ -142,6 +143,7 @@ export default {
|
||||
}
|
||||
|
||||
// Get account
|
||||
let newAccount = false
|
||||
const accountID = await (async () => {
|
||||
const matches = await Database.use(async (tx) =>
|
||||
tx
|
||||
@@ -166,6 +168,7 @@ export default {
|
||||
if (!accountID) {
|
||||
console.log("creating account for", email)
|
||||
accountID = await Account.create({})
|
||||
newAccount = true
|
||||
}
|
||||
|
||||
await Database.use(async (tx) =>
|
||||
@@ -215,7 +218,7 @@ export default {
|
||||
await Workspace.create({ name: "Default" })
|
||||
}
|
||||
})
|
||||
return ctx.subject("account", accountID, { accountID, email })
|
||||
return ctx.subject("account", accountID, { accountID, email, newAccount })
|
||||
},
|
||||
}).fetch(request, env, ctx)
|
||||
return result
|
||||
|
||||
@@ -11,6 +11,7 @@ import { dict as desktopDa } from "./da"
|
||||
import { dict as desktopJa } from "./ja"
|
||||
import { dict as desktopPl } from "./pl"
|
||||
import { dict as desktopRu } from "./ru"
|
||||
import { dict as desktopUk } from "./uk"
|
||||
import { dict as desktopAr } from "./ar"
|
||||
import { dict as desktopNo } from "./no"
|
||||
import { dict as desktopBr } from "./br"
|
||||
@@ -27,6 +28,7 @@ import { dict as appDa } from "../../../../app/src/i18n/da"
|
||||
import { dict as appJa } from "../../../../app/src/i18n/ja"
|
||||
import { dict as appPl } from "../../../../app/src/i18n/pl"
|
||||
import { dict as appRu } from "../../../../app/src/i18n/ru"
|
||||
import { dict as appUk } from "../../../../app/src/i18n/uk"
|
||||
import { dict as appAr } from "../../../../app/src/i18n/ar"
|
||||
import { dict as appNo } from "../../../../app/src/i18n/no"
|
||||
import { dict as appBr } from "../../../../app/src/i18n/br"
|
||||
@@ -44,6 +46,7 @@ export type Locale =
|
||||
| "ja"
|
||||
| "pl"
|
||||
| "ru"
|
||||
| "uk"
|
||||
| "ar"
|
||||
| "no"
|
||||
| "br"
|
||||
@@ -64,6 +67,7 @@ const LOCALES: readonly Locale[] = [
|
||||
"ja",
|
||||
"pl",
|
||||
"ru",
|
||||
"uk",
|
||||
"bs",
|
||||
"ar",
|
||||
"no",
|
||||
@@ -89,6 +93,7 @@ function detectLocale(): Locale {
|
||||
if (language.toLowerCase().startsWith("ja")) return "ja"
|
||||
if (language.toLowerCase().startsWith("pl")) return "pl"
|
||||
if (language.toLowerCase().startsWith("ru")) return "ru"
|
||||
if (language.toLowerCase().startsWith("uk")) return "uk"
|
||||
if (language.toLowerCase().startsWith("ar")) return "ar"
|
||||
if (
|
||||
language.toLowerCase().startsWith("no") ||
|
||||
@@ -148,6 +153,7 @@ function build(locale: Locale): Dictionary {
|
||||
if (locale === "ja") return { ...base, ...i18n.flatten(appJa), ...i18n.flatten(desktopJa) }
|
||||
if (locale === "pl") return { ...base, ...i18n.flatten(appPl), ...i18n.flatten(desktopPl) }
|
||||
if (locale === "ru") return { ...base, ...i18n.flatten(appRu), ...i18n.flatten(desktopRu) }
|
||||
if (locale === "uk") return { ...base, ...i18n.flatten(appUk), ...i18n.flatten(desktopUk) }
|
||||
if (locale === "ar") return { ...base, ...i18n.flatten(appAr), ...i18n.flatten(desktopAr) }
|
||||
if (locale === "no") return { ...base, ...i18n.flatten(appNo), ...i18n.flatten(desktopNo) }
|
||||
if (locale === "br") return { ...base, ...i18n.flatten(appBr), ...i18n.flatten(desktopBr) }
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
export const dict = {
|
||||
"desktop.menu.checkForUpdates": "Перевірити оновлення...",
|
||||
"desktop.menu.installCli": "Встановити CLI...",
|
||||
"desktop.menu.reloadWebview": "Перезавантажити Webview",
|
||||
"desktop.menu.restart": "Перезапустити",
|
||||
|
||||
"desktop.dialog.chooseFolder": "Виберіть теку",
|
||||
"desktop.dialog.chooseFile": "Виберіть файл",
|
||||
"desktop.dialog.saveFile": "Зберегти файл",
|
||||
|
||||
"desktop.updater.checkFailed.title": "Не вдалося перевірити оновлення",
|
||||
"desktop.updater.checkFailed.message": "Не вдалося перевірити наявність оновлень",
|
||||
"desktop.updater.none.title": "Немає доступних оновлень",
|
||||
"desktop.updater.none.message": "Ви вже використовуєте найновішу версію OpenCode",
|
||||
"desktop.updater.downloadFailed.title": "Помилка оновлення",
|
||||
"desktop.updater.downloadFailed.message": "Не вдалося завантажити оновлення",
|
||||
"desktop.updater.downloaded.title": "Оновлення завантажено",
|
||||
"desktop.updater.downloaded.prompt":
|
||||
"Версію {{version}} OpenCode завантажено. Бажаєте встановити її та перезапустити?",
|
||||
"desktop.updater.installFailed.title": "Помилка оновлення",
|
||||
"desktop.updater.installFailed.message": "Не вдалося встановити оновлення",
|
||||
|
||||
"desktop.cli.installed.title": "CLI встановлено",
|
||||
"desktop.cli.installed.message":
|
||||
"CLI встановлено до {{path}}\n\nПерезапустіть термінал, щоб використовувати команду 'opencode'.",
|
||||
"desktop.cli.failed.title": "Не вдалося встановити",
|
||||
"desktop.cli.failed.message": "Не вдалося встановити CLI: {{error}}",
|
||||
}
|
||||
@@ -230,6 +230,7 @@ Top-level API groups exposed to `tui(api, options, meta)`:
|
||||
- `api.attention.notify(input)`
|
||||
- `api.keys.formatSequence(parts)`, `formatBindings(bindings)`
|
||||
- `api.keymap`
|
||||
- `api.mode.current()`, `api.mode.push(mode)`
|
||||
- `api.route.register(routes)` / `api.route.navigate(name, params?)` / `api.route.current`
|
||||
- `api.ui.Dialog`, `DialogAlert`, `DialogConfirm`, `DialogPrompt`, `DialogSelect`, `Slot`, `Prompt`, `ui.toast`, `ui.dialog`
|
||||
- `api.tuiConfig`
|
||||
@@ -255,6 +256,68 @@ Top-level API groups exposed to `tui(api, options, meta)`:
|
||||
- Disposers returned by `api.keymap` registrations and `acquireResource(...)` are automatically cleaned up when the plugin deactivates. You do not need to add those disposers to `api.lifecycle.onDispose(...)` yourself.
|
||||
- Built-in which-key shortcuts are resolved from flat `keybinds` command ids such as `which_key_toggle`, not plugin options.
|
||||
|
||||
#### Mode-aware layers
|
||||
|
||||
OpenCode registers a `mode` layer field on the host keymap. Plugins can use it to keep bindings active only in the relevant UI state.
|
||||
|
||||
Built-in modes:
|
||||
|
||||
- `base`: normal app, route, and prompt interaction.
|
||||
- `modal`: host dialog stack is open, including dialogs rendered through `api.ui.dialog` and `api.ui.Dialog*` components.
|
||||
- `autocomplete`: host prompt autocomplete is open.
|
||||
- `api.mode.current()` returns the active top mode, or `base` when no pushed mode is active.
|
||||
|
||||
Example: register a command and shortcut that are active only in normal app mode:
|
||||
|
||||
```tsx
|
||||
api.keymap.registerLayer({
|
||||
mode: "base",
|
||||
commands: [
|
||||
{
|
||||
name: "demo.open",
|
||||
title: "Demo",
|
||||
category: "Plugin",
|
||||
namespace: "palette",
|
||||
run() {
|
||||
api.route.navigate("demo")
|
||||
},
|
||||
},
|
||||
],
|
||||
bindings: [{ key: "ctrl+shift+m", cmd: "demo.open", desc: "Open demo" }],
|
||||
})
|
||||
```
|
||||
|
||||
Layers without `mode` are not mode-gated and can remain active while dialogs or autocomplete are open. Use that only for intentionally global commands or low-level keymap extensions.
|
||||
|
||||
Plugins that own a full-screen route or modal-like UI can temporarily push a plugin-specific mode with `api.mode.push(...)`. Use a plugin-scoped mode name. The returned disposer pops that specific stack entry and is idempotent, so popping an older mode while a newer mode is on top leaves the newer mode active.
|
||||
|
||||
```tsx
|
||||
import { onCleanup } from "solid-js"
|
||||
|
||||
api.route.register([
|
||||
{
|
||||
name: "demo",
|
||||
render: () => {
|
||||
const popMode = api.mode.push("acme.demo")
|
||||
onCleanup(popMode)
|
||||
|
||||
return (
|
||||
<box>
|
||||
<text>demo</text>
|
||||
</box>
|
||||
)
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
api.keymap.registerLayer({
|
||||
mode: "acme.demo",
|
||||
bindings: [{ key: "escape", cmd: () => api.route.navigate("home"), desc: "Close demo" }],
|
||||
})
|
||||
```
|
||||
|
||||
Mode pushes are automatically tracked by the plugin runtime. If a plugin is disabled, fails during activation, or the TUI shuts down before the plugin calls the disposer, OpenCode pops the plugin's pushed modes during plugin cleanup. Calling the disposer yourself is still recommended for component lifetimes; cleanup remains idempotent.
|
||||
|
||||
### Keys
|
||||
|
||||
- `api.keys` exposes host-formatted shortcut display helpers for plugin UI.
|
||||
|
||||
@@ -66,8 +66,15 @@ import { createTuiApi } from "@/cli/cmd/tui/plugin/api"
|
||||
import type { RouteMap } from "@/cli/cmd/tui/plugin/api"
|
||||
import { createTuiAttention } from "@/cli/cmd/tui/attention"
|
||||
import { FormatError, FormatUnknownError } from "@/cli/error"
|
||||
import { CommandPaletteProvider, useCommandPalette } from "./context/command-palette"
|
||||
import { OpencodeKeymapProvider, registerOpencodeKeymap, useBindings, useOpencodeKeymap } from "./keymap"
|
||||
import { CommandPaletteDialog } from "./component/command-palette"
|
||||
import {
|
||||
COMMAND_PALETTE_COMMAND,
|
||||
OPENCODE_BASE_MODE,
|
||||
OpencodeKeymapProvider,
|
||||
registerOpencodeKeymap,
|
||||
useBindings,
|
||||
useOpencodeKeymap,
|
||||
} from "./keymap"
|
||||
|
||||
import type { EventSource } from "./context/sdk"
|
||||
import { DialogVariant } from "./component/dialog-variant"
|
||||
@@ -227,17 +234,15 @@ export function tui(input: {
|
||||
<LocalProvider>
|
||||
<PromptStashProvider>
|
||||
<DialogProvider>
|
||||
<CommandPaletteProvider>
|
||||
<FrecencyProvider>
|
||||
<PromptHistoryProvider>
|
||||
<PromptRefProvider>
|
||||
<EditorContextProvider>
|
||||
<App onSnapshot={input.onSnapshot} />
|
||||
</EditorContextProvider>
|
||||
</PromptRefProvider>
|
||||
</PromptHistoryProvider>
|
||||
</FrecencyProvider>
|
||||
</CommandPaletteProvider>
|
||||
<FrecencyProvider>
|
||||
<PromptHistoryProvider>
|
||||
<PromptRefProvider>
|
||||
<EditorContextProvider>
|
||||
<App onSnapshot={input.onSnapshot} />
|
||||
</EditorContextProvider>
|
||||
</PromptRefProvider>
|
||||
</PromptHistoryProvider>
|
||||
</FrecencyProvider>
|
||||
</DialogProvider>
|
||||
</PromptStashProvider>
|
||||
</LocalProvider>
|
||||
@@ -267,7 +272,6 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
|
||||
const dialog = useDialog()
|
||||
const local = useLocal()
|
||||
const kv = useKV()
|
||||
const command = useCommandPalette()
|
||||
const keymap = useOpencodeKeymap()
|
||||
const event = useEvent()
|
||||
const sdk = useSDK()
|
||||
@@ -446,12 +450,12 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
|
||||
const appCommands = createMemo(() =>
|
||||
[
|
||||
{
|
||||
name: "command.palette.show",
|
||||
name: COMMAND_PALETTE_COMMAND,
|
||||
title: "Show command palette",
|
||||
category: "System",
|
||||
hidden: true,
|
||||
run: () => {
|
||||
command.show()
|
||||
dialog.replace(() => <CommandPaletteDialog />)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -801,14 +805,13 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
|
||||
}))
|
||||
|
||||
useBindings(() => ({
|
||||
enabled: command.matcher,
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
bindings: tuiConfig.keybinds.gather("app", appBindingCommands),
|
||||
}))
|
||||
|
||||
useBindings(() => ({
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
enabled: () => {
|
||||
const ok = command.matcher.get()
|
||||
if (!ok) return false
|
||||
const current = promptRef.current
|
||||
if (!current?.focused) return true
|
||||
return current.current.input === ""
|
||||
@@ -817,7 +820,7 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
|
||||
}))
|
||||
|
||||
event.on(TuiEvent.CommandExecute.type, (evt) => {
|
||||
command.run(evt.properties.command)
|
||||
keymap.dispatchCommand(evt.properties.command)
|
||||
})
|
||||
|
||||
event.on(TuiEvent.ToastShow.type, (evt) => {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { createMemo } from "solid-js"
|
||||
import { DialogSelect, type DialogSelectRef } from "@tui/ui/dialog-select"
|
||||
import { type DialogContext } from "@tui/ui/dialog"
|
||||
import {
|
||||
COMMAND_PALETTE_COMMAND,
|
||||
formatKeyBindings,
|
||||
type OpenTuiKeymap,
|
||||
useKeymapSelector,
|
||||
useOpencodeKeymap,
|
||||
} from "../keymap"
|
||||
import { useTuiConfig } from "../context/tui-config"
|
||||
|
||||
type PaletteCommandEntry = ReturnType<OpenTuiKeymap["getCommandEntries"]>[number]
|
||||
|
||||
function isVisiblePaletteCommand(command: PaletteCommandEntry["command"]) {
|
||||
return command.hidden !== true && command.name !== COMMAND_PALETTE_COMMAND
|
||||
}
|
||||
|
||||
function isSuggestedPaletteCommand(entry: PaletteCommandEntry) {
|
||||
const suggested = entry.command.suggested
|
||||
if (typeof suggested === "boolean") return suggested
|
||||
if (typeof suggested === "function") return suggested() === true
|
||||
return false
|
||||
}
|
||||
|
||||
export function CommandPaletteDialog() {
|
||||
const config = useTuiConfig()
|
||||
const keymap = useOpencodeKeymap()
|
||||
const entries = useKeymapSelector((keymap: OpenTuiKeymap) => {
|
||||
const query = {
|
||||
namespace: "palette",
|
||||
}
|
||||
const reachable = keymap.getCommandEntries({
|
||||
...query,
|
||||
visibility: "reachable",
|
||||
filter: isVisiblePaletteCommand,
|
||||
})
|
||||
const registeredBindings = keymap.getCommandBindings({
|
||||
visibility: "registered",
|
||||
commands: reachable.map((entry) => entry.command.name),
|
||||
})
|
||||
|
||||
return reachable.map((entry) => ({
|
||||
...entry,
|
||||
bindings: registeredBindings.get(entry.command.name) ?? entry.bindings,
|
||||
}))
|
||||
})
|
||||
const options = createMemo(() =>
|
||||
entries().map((entry) => ({
|
||||
title: typeof entry.command.title === "string" ? entry.command.title : entry.command.name,
|
||||
description: typeof entry.command.desc === "string" ? entry.command.desc : undefined,
|
||||
category: typeof entry.command.category === "string" ? entry.command.category : undefined,
|
||||
footer: formatKeyBindings(entry.bindings, config),
|
||||
value: entry.command.name,
|
||||
suggested: isSuggestedPaletteCommand(entry),
|
||||
onSelect: (dialog: DialogContext) => {
|
||||
dialog.clear()
|
||||
keymap.dispatchCommand(entry.command.name)
|
||||
},
|
||||
})),
|
||||
)
|
||||
|
||||
let ref: DialogSelectRef<string>
|
||||
const list = () => {
|
||||
if (ref?.filter) return options()
|
||||
return [
|
||||
...options()
|
||||
.filter((option) => option.suggested)
|
||||
.map((option) => ({
|
||||
...option,
|
||||
value: `suggested:${option.value}`,
|
||||
category: "Suggested",
|
||||
})),
|
||||
...options(),
|
||||
]
|
||||
}
|
||||
|
||||
return <DialogSelect ref={(value) => (ref = value)} title="Commands" options={list()} />
|
||||
}
|
||||
@@ -13,12 +13,11 @@ import { getScrollAcceleration } from "../../util/scroll"
|
||||
import { useTuiConfig } from "../../context/tui-config"
|
||||
import { useTheme, selectedForeground } from "@tui/context/theme"
|
||||
import { SplitBorder } from "@tui/component/border"
|
||||
import { useCommandPalette } from "../../context/command-palette"
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
import { Locale } from "@/util/locale"
|
||||
import type { PromptInfo } from "./history"
|
||||
import { useFrecency } from "./frecency"
|
||||
import { useBindings } from "../../keymap"
|
||||
import { useBindings, useCommandSlashes, useOpencodeModeStack } from "../../keymap"
|
||||
import { Reference } from "@/reference/reference"
|
||||
import { ConfigReference } from "@/config/reference"
|
||||
import { displayCharAt, mentionTriggerIndex } from "@/cli/cmd/prompt-display"
|
||||
@@ -87,7 +86,8 @@ export function Autocomplete(props: {
|
||||
const sdk = useSDK()
|
||||
const sync = useSync()
|
||||
const project = useProject()
|
||||
const command = useCommandPalette()
|
||||
const slashes = useCommandSlashes()
|
||||
const modeStack = useOpencodeModeStack()
|
||||
const { theme } = useTheme()
|
||||
const dimensions = useTerminalDimensions()
|
||||
const frecency = useFrecency()
|
||||
@@ -101,6 +101,12 @@ export function Autocomplete(props: {
|
||||
|
||||
const [positionTick, setPositionTick] = createSignal(0)
|
||||
|
||||
createEffect(() => {
|
||||
if (!store.visible) return
|
||||
const popMode = modeStack.push("autocomplete")
|
||||
onCleanup(popMode)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
if (store.visible) {
|
||||
let lastPos = { x: 0, y: 0, width: 0 }
|
||||
@@ -367,7 +373,6 @@ export function Autocomplete(props: {
|
||||
const { filename, part } = createFilePart(item, lineRange)
|
||||
const index = store.visible === "@" ? store.index : props.input().cursorOffset
|
||||
|
||||
command.suspend(false)
|
||||
setStore("visible", false)
|
||||
setStore("index", index)
|
||||
insertPart(filename, part)
|
||||
@@ -539,7 +544,7 @@ export function Autocomplete(props: {
|
||||
)
|
||||
|
||||
const commands = createMemo((): AutocompleteOption[] => {
|
||||
const results: AutocompleteOption[] = [...command.slashes()]
|
||||
const results: AutocompleteOption[] = [...slashes()]
|
||||
|
||||
for (const serverCommand of sync.data.command) {
|
||||
if (serverCommand.source === "skill") continue
|
||||
@@ -730,7 +735,6 @@ export function Autocomplete(props: {
|
||||
}))
|
||||
|
||||
function show(mode: "@" | "/") {
|
||||
command.suspend(true)
|
||||
setStore({
|
||||
visible: mode,
|
||||
index: props.input().cursorOffset,
|
||||
@@ -747,7 +751,6 @@ export function Autocomplete(props: {
|
||||
draft.input = props.input().plainText
|
||||
})
|
||||
}
|
||||
command.suspend(false)
|
||||
setStore("visible", false)
|
||||
}
|
||||
|
||||
|
||||
@@ -59,8 +59,7 @@ import { DialogWorkspaceUnavailable } from "../dialog-workspace-unavailable"
|
||||
import { useArgs } from "@tui/context/args"
|
||||
import { Flag } from "@opencode-ai/core/flag/flag"
|
||||
import { type WorkspaceStatus } from "../workspace-label"
|
||||
import { useCommandPalette } from "../../context/command-palette"
|
||||
import { useBindings, useCommandShortcut, useLeaderActive, useOpencodeKeymap } from "../../keymap"
|
||||
import { OPENCODE_BASE_MODE, useBindings, useCommandShortcut, useLeaderActive, useOpencodeKeymap } from "../../keymap"
|
||||
import { useTuiConfig } from "../../context/tui-config"
|
||||
|
||||
export type PromptProps = {
|
||||
@@ -152,7 +151,6 @@ export function Prompt(props: PromptProps) {
|
||||
const status = createMemo(() => sync.data.session_status?.[props.sessionID ?? ""] ?? { type: "idle" })
|
||||
const history = usePromptHistory()
|
||||
const stash = usePromptStash()
|
||||
const command = useCommandPalette()
|
||||
const keymap = useOpencodeKeymap()
|
||||
const agentShortcut = useCommandShortcut("agent.cycle")
|
||||
const paletteShortcut = useCommandShortcut("command.palette.show")
|
||||
@@ -629,7 +627,7 @@ export function Prompt(props: PromptProps) {
|
||||
}))
|
||||
|
||||
useBindings(() => ({
|
||||
enabled: command.matcher,
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
bindings: tuiConfig.keybinds.gather("prompt.palette", [
|
||||
"prompt.submit",
|
||||
"prompt.editor",
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import { createContext, createMemo, createSignal, useContext, type Accessor, type ParentProps } from "solid-js"
|
||||
import { DialogSelect, type DialogSelectRef } from "@tui/ui/dialog-select"
|
||||
import { useDialog, type DialogContext } from "@tui/ui/dialog"
|
||||
import {
|
||||
formatKeyBindings,
|
||||
reactiveMatcherFromSignal,
|
||||
type OpenTuiKeymap,
|
||||
useKeymapSelector,
|
||||
useOpencodeKeymap,
|
||||
} from "../keymap"
|
||||
import { useTuiConfig } from "./tui-config"
|
||||
|
||||
type SlashEntry = {
|
||||
display: string
|
||||
description?: string
|
||||
aliases?: string[]
|
||||
onSelect: () => void
|
||||
}
|
||||
|
||||
type CommandPaletteContext = {
|
||||
run(command: string): void
|
||||
show(): void
|
||||
slashes: Accessor<readonly SlashEntry[]>
|
||||
suspend(enabled: boolean): void
|
||||
readonly suspended: boolean
|
||||
matcher: ReturnType<typeof reactiveMatcherFromSignal>
|
||||
}
|
||||
|
||||
const COMMAND_PALETTE_DIALOG = "command.palette.show"
|
||||
const ctx = createContext<CommandPaletteContext>()
|
||||
type PaletteCommandEntry = ReturnType<OpenTuiKeymap["getCommandEntries"]>[number]
|
||||
|
||||
function isVisiblePaletteCommand(entry: PaletteCommandEntry) {
|
||||
return entry.command.hidden !== true && entry.command.name !== COMMAND_PALETTE_DIALOG
|
||||
}
|
||||
|
||||
function isSuggestedPaletteCommand(entry: PaletteCommandEntry) {
|
||||
const suggested = entry.command.suggested
|
||||
if (typeof suggested === "boolean") return suggested
|
||||
if (typeof suggested === "function") return suggested() === true
|
||||
return false
|
||||
}
|
||||
|
||||
export function CommandPaletteProvider(props: ParentProps) {
|
||||
const dialog = useDialog()
|
||||
const keymap = useOpencodeKeymap()
|
||||
const [suspendCount, setSuspendCount] = createSignal(0)
|
||||
const entries = useKeymapSelector((keymap: OpenTuiKeymap) =>
|
||||
keymap
|
||||
.getCommandEntries({
|
||||
visibility: "reachable",
|
||||
namespace: "palette",
|
||||
})
|
||||
.filter(isVisiblePaletteCommand),
|
||||
)
|
||||
|
||||
const run = (command: string) => {
|
||||
keymap.dispatchCommand(command)
|
||||
}
|
||||
|
||||
const slashes = createMemo<SlashEntry[]>(() =>
|
||||
entries().flatMap((entry) => {
|
||||
const slashName = entry.command.slashName
|
||||
if (typeof slashName !== "string" || !slashName) return []
|
||||
const slashAliases = entry.command.slashAliases
|
||||
return {
|
||||
display: `/${slashName}`,
|
||||
description:
|
||||
typeof entry.command.desc === "string"
|
||||
? entry.command.desc
|
||||
: typeof entry.command.title === "string"
|
||||
? entry.command.title
|
||||
: undefined,
|
||||
aliases: Array.isArray(slashAliases)
|
||||
? slashAliases.filter((alias): alias is string => typeof alias === "string").map((alias) => `/${alias}`)
|
||||
: undefined,
|
||||
onSelect: () => run(entry.command.name),
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
const value: CommandPaletteContext = {
|
||||
run,
|
||||
show() {
|
||||
dialog.replace(() => <CommandPaletteDialog run={run} />)
|
||||
},
|
||||
slashes,
|
||||
suspend(enabled: boolean) {
|
||||
setSuspendCount((count) => Math.max(0, count + (enabled ? 1 : -1)))
|
||||
},
|
||||
get suspended() {
|
||||
return suspendCount() > 0 || dialog.stack.length > 0
|
||||
},
|
||||
matcher: reactiveMatcherFromSignal(() => suspendCount() === 0 && dialog.stack.length === 0),
|
||||
}
|
||||
|
||||
return <ctx.Provider value={value}>{props.children}</ctx.Provider>
|
||||
}
|
||||
|
||||
export function useCommandPalette() {
|
||||
const value = useContext(ctx)
|
||||
if (!value) throw new Error("CommandPalette context must be used within a CommandPaletteProvider")
|
||||
return value
|
||||
}
|
||||
|
||||
function CommandPaletteDialog(props: { run(command: string): void }) {
|
||||
const config = useTuiConfig()
|
||||
const entries = useKeymapSelector((keymap: OpenTuiKeymap) => {
|
||||
const query = {
|
||||
namespace: "palette",
|
||||
}
|
||||
const reachable = keymap
|
||||
.getCommandEntries({
|
||||
...query,
|
||||
visibility: "reachable",
|
||||
})
|
||||
.filter(isVisiblePaletteCommand)
|
||||
const registeredBindings = keymap.getCommandBindings({
|
||||
visibility: "registered",
|
||||
commands: reachable.map((entry) => entry.command.name),
|
||||
})
|
||||
|
||||
return reachable.map((entry) => ({
|
||||
...entry,
|
||||
bindings: registeredBindings.get(entry.command.name) ?? entry.bindings,
|
||||
}))
|
||||
})
|
||||
const options = createMemo(() =>
|
||||
entries().map((entry) => ({
|
||||
title: typeof entry.command.title === "string" ? entry.command.title : entry.command.name,
|
||||
description: typeof entry.command.desc === "string" ? entry.command.desc : undefined,
|
||||
category: typeof entry.command.category === "string" ? entry.command.category : undefined,
|
||||
footer: formatKeyBindings(entry.bindings, config),
|
||||
value: entry.command.name,
|
||||
suggested: isSuggestedPaletteCommand(entry),
|
||||
onSelect: (dialog: DialogContext) => {
|
||||
dialog.clear()
|
||||
props.run(entry.command.name)
|
||||
},
|
||||
})),
|
||||
)
|
||||
|
||||
let ref: DialogSelectRef<string>
|
||||
const list = () => {
|
||||
if (ref?.filter) return options()
|
||||
return [
|
||||
...options()
|
||||
.filter((option) => option.suggested)
|
||||
.map((option) => ({
|
||||
...option,
|
||||
value: `suggested:${option.value}`,
|
||||
category: "Suggested",
|
||||
})),
|
||||
...options(),
|
||||
]
|
||||
}
|
||||
|
||||
return <DialogSelect ref={(value) => (ref = value)} title="Commands" options={list()} />
|
||||
}
|
||||
|
||||
export function useCommandSlashes(): Accessor<readonly SlashEntry[]> {
|
||||
return useCommandPalette().slashes
|
||||
}
|
||||
@@ -5,30 +5,103 @@ import {
|
||||
formatCommandBindings as formatCommandBindingsExtra,
|
||||
formatKeySequence as formatKeySequenceExtra,
|
||||
} from "@opentui/keymap/extras"
|
||||
import {
|
||||
KeymapProvider,
|
||||
reactiveMatcherFromSignal,
|
||||
useKeymap,
|
||||
useKeymapSelector,
|
||||
useBindings,
|
||||
} from "@opentui/keymap/solid"
|
||||
import type { Accessor } from "solid-js"
|
||||
import { KeymapProvider, useKeymap, useKeymapSelector, useBindings } from "@opentui/keymap/solid"
|
||||
import { createMemo, type Accessor } from "solid-js"
|
||||
import type { TuiConfig } from "./config/tui"
|
||||
import { useTuiConfig } from "./context/tui-config"
|
||||
import { TuiKeybind } from "./config/keybind"
|
||||
|
||||
export const LEADER_TOKEN = "leader"
|
||||
export const OPENCODE_BASE_MODE = "base"
|
||||
export const COMMAND_PALETTE_COMMAND = "command.palette.show"
|
||||
|
||||
const OPENCODE_MODE_KEY = "opencode.mode"
|
||||
|
||||
export const OpencodeKeymapProvider = KeymapProvider
|
||||
export const useOpencodeKeymap = useKeymap
|
||||
|
||||
export { reactiveMatcherFromSignal, useBindings, useKeymapSelector }
|
||||
export { useBindings, useKeymapSelector }
|
||||
|
||||
export type OpenTuiKeymap = ReturnType<typeof useKeymap>
|
||||
type OpencodeModeStack = ReturnType<typeof createOpencodeModeStack>
|
||||
type CommandSlashEntry = {
|
||||
display: string
|
||||
description?: string
|
||||
aliases?: string[]
|
||||
onSelect: () => void
|
||||
}
|
||||
type Command = ReturnType<OpenTuiKeymap["getCommands"]>[number]
|
||||
|
||||
const modeStacks = new WeakMap<OpenTuiKeymap, OpencodeModeStack>()
|
||||
|
||||
function isVisiblePaletteCommand(command: Command) {
|
||||
return command.hidden !== true && command.name !== COMMAND_PALETTE_COMMAND
|
||||
}
|
||||
|
||||
export function createOpencodeModeStack(keymap: OpenTuiKeymap) {
|
||||
keymap.setData(OPENCODE_MODE_KEY, OPENCODE_BASE_MODE)
|
||||
|
||||
const offFields = keymap.registerLayerFields({
|
||||
mode(value, ctx) {
|
||||
ctx.require(OPENCODE_MODE_KEY, value)
|
||||
},
|
||||
})
|
||||
|
||||
const stack: { id: symbol; mode: string }[] = []
|
||||
let disposed = false
|
||||
|
||||
const update = () => {
|
||||
keymap.setData(OPENCODE_MODE_KEY, stack.at(-1)?.mode ?? OPENCODE_BASE_MODE)
|
||||
}
|
||||
|
||||
const stackApi = {
|
||||
current() {
|
||||
return stack.at(-1)?.mode ?? OPENCODE_BASE_MODE
|
||||
},
|
||||
push(mode: string) {
|
||||
if (disposed) return () => {}
|
||||
const id = Symbol(mode)
|
||||
let active = true
|
||||
stack.push({ id, mode })
|
||||
update()
|
||||
|
||||
return () => {
|
||||
if (!active) return
|
||||
active = false
|
||||
const index = stack.findIndex((item) => item.id === id)
|
||||
if (index !== -1) stack.splice(index, 1)
|
||||
update()
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
stack.length = 0
|
||||
offFields()
|
||||
keymap.setData(OPENCODE_MODE_KEY, undefined)
|
||||
modeStacks.delete(keymap)
|
||||
},
|
||||
}
|
||||
|
||||
modeStacks.set(keymap, stackApi)
|
||||
return stackApi
|
||||
}
|
||||
|
||||
export function useOpencodeModeStack() {
|
||||
return getOpencodeModeStack(useOpencodeKeymap())
|
||||
}
|
||||
|
||||
export function getOpencodeModeStack(keymap: OpenTuiKeymap) {
|
||||
const value = modeStacks.get(keymap)
|
||||
if (!value) throw new Error("Opencode mode stack is not registered for this keymap")
|
||||
return value
|
||||
}
|
||||
|
||||
const KEY_ALIASES = {
|
||||
enter: "return",
|
||||
esc: "escape",
|
||||
pgdown: "pagedown",
|
||||
pgup: "pageup",
|
||||
} as const
|
||||
|
||||
function expandKeyAliases(input: string) {
|
||||
@@ -125,6 +198,7 @@ export function registerOpencodeKeymap(
|
||||
renderer: CliRenderer,
|
||||
config: Pick<TuiConfig.Resolved, "keybinds" | "leader_timeout">,
|
||||
) {
|
||||
const modeStack = createOpencodeModeStack(keymap)
|
||||
const offCommaBindings = addons.registerCommaBindings(keymap)
|
||||
const offAliasExpander = registerKeyAliases(keymap)
|
||||
const offBaseLayout = addons.registerBaseLayoutFallback(keymap)
|
||||
@@ -148,6 +222,7 @@ export function registerOpencodeKeymap(
|
||||
offAliasExpander()
|
||||
offBaseLayout()
|
||||
offCommaBindings()
|
||||
modeStack.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,3 +239,35 @@ export function useCommandShortcut(command: string): Accessor<string> {
|
||||
export function useLeaderActive(): Accessor<boolean> {
|
||||
return useKeymapSelector((keymap: OpenTuiKeymap) => keymap.getPendingSequence()[0]?.tokenName === LEADER_TOKEN)
|
||||
}
|
||||
|
||||
export function useCommandSlashes(): Accessor<readonly CommandSlashEntry[]> {
|
||||
const keymap = useOpencodeKeymap()
|
||||
const entries = useKeymapSelector((keymap: OpenTuiKeymap) =>
|
||||
keymap.getCommandEntries({
|
||||
visibility: "reachable",
|
||||
namespace: "palette",
|
||||
filter: isVisiblePaletteCommand,
|
||||
}),
|
||||
)
|
||||
|
||||
return createMemo<CommandSlashEntry[]>(() =>
|
||||
entries().flatMap((entry) => {
|
||||
const slashName = entry.command.slashName
|
||||
if (typeof slashName !== "string" || !slashName) return []
|
||||
const slashAliases = entry.command.slashAliases
|
||||
return {
|
||||
display: `/${slashName}`,
|
||||
description:
|
||||
typeof entry.command.desc === "string"
|
||||
? entry.command.desc
|
||||
: typeof entry.command.title === "string"
|
||||
? entry.command.title
|
||||
: undefined,
|
||||
aliases: Array.isArray(slashAliases)
|
||||
? slashAliases.filter((alias): alias is string => typeof alias === "string").map((alias) => `/${alias}`)
|
||||
: undefined,
|
||||
onSelect: () => keymap.dispatchCommand(entry.command.name),
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -219,6 +219,14 @@ export function createTuiApi(input: Input): TuiPluginApi {
|
||||
},
|
||||
},
|
||||
keymap: input.keymap,
|
||||
mode: {
|
||||
current() {
|
||||
return Keymap.getOpencodeModeStack(input.keymap).current()
|
||||
},
|
||||
push(mode) {
|
||||
return Keymap.getOpencodeModeStack(input.keymap).push(mode)
|
||||
},
|
||||
},
|
||||
route: {
|
||||
register(list) {
|
||||
return routeRegister(input.routes, list, input.bump)
|
||||
|
||||
@@ -192,6 +192,17 @@ function createScopedAttention(
|
||||
}
|
||||
}
|
||||
|
||||
function createScopedMode(mode: TuiPluginApi["mode"], scope: PluginScope): TuiPluginApi["mode"] {
|
||||
return {
|
||||
current() {
|
||||
return mode.current()
|
||||
},
|
||||
push(value) {
|
||||
return scope.track(mode.push(value))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type CleanupResult = { type: "ok" } | { type: "error"; error: unknown } | { type: "timeout" }
|
||||
|
||||
function runCleanup(fn: () => unknown, ms: number): Promise<CleanupResult> {
|
||||
@@ -616,6 +627,7 @@ function pluginApi(runtime: RuntimeState, plugin: PluginEntry, scope: PluginScop
|
||||
command: createCommandShim(keymap, api.ui.dialog, api.tuiConfig.keybinds),
|
||||
keys: api.keys,
|
||||
keymap,
|
||||
mode: createScopedMode(api.mode, scope),
|
||||
route,
|
||||
ui: api.ui,
|
||||
tuiConfig: api.tuiConfig,
|
||||
|
||||
@@ -89,8 +89,7 @@ import { TuiPluginRuntime } from "@/cli/cmd/tui/plugin/runtime"
|
||||
import { DialogRetryAction } from "../../component/dialog-retry-action"
|
||||
import { SessionRetry } from "@/session/retry"
|
||||
import { getRevertDiffFiles } from "../../util/revert-diff"
|
||||
import { useCommandPalette } from "../../context/command-palette"
|
||||
import { useBindings, useCommandShortcut } from "../../keymap"
|
||||
import { OPENCODE_BASE_MODE, useBindings, useCommandShortcut, useOpencodeKeymap } from "../../keymap"
|
||||
import { PathFormatterProvider, usePathFormatter } from "../../context/path-format"
|
||||
|
||||
addDefaultParsers(parsers.parsers)
|
||||
@@ -311,7 +310,7 @@ export function Session() {
|
||||
seeded = true
|
||||
r.set(route.prompt)
|
||||
}
|
||||
const command = useCommandPalette()
|
||||
const keymap = useOpencodeKeymap()
|
||||
const dialog = useDialog()
|
||||
const renderer = useRenderer()
|
||||
|
||||
@@ -1056,7 +1055,7 @@ export function Session() {
|
||||
}))
|
||||
|
||||
useBindings(() => ({
|
||||
enabled: command.matcher,
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
bindings: tuiConfig.keybinds.gather("session", sessionBindingCommands),
|
||||
}))
|
||||
|
||||
@@ -1133,7 +1132,6 @@ export function Session() {
|
||||
<Switch>
|
||||
<Match when={message.id === revert()?.messageID}>
|
||||
{(function () {
|
||||
const command = useCommandPalette()
|
||||
const redoShortcut = useCommandShortcut("session.redo")
|
||||
const [hover, setHover] = createSignal(false)
|
||||
const dialog = useDialog()
|
||||
@@ -1145,7 +1143,7 @@ export function Session() {
|
||||
"Are you sure you want to restore the reverted messages?",
|
||||
)
|
||||
if (confirmed) {
|
||||
command.run("session.redo")
|
||||
keymap.dispatchCommand("session.redo")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,9 @@ import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
|
||||
import { Locale } from "@/util/locale"
|
||||
import { ShellID } from "@/tool/shell/id"
|
||||
import { webSearchProviderLabel } from "@/tool/websearch"
|
||||
import { useDialog } from "../../ui/dialog"
|
||||
import { getScrollAcceleration } from "../../util/scroll"
|
||||
import { useTuiConfig } from "../../context/tui-config"
|
||||
import { useBindings, useCommandShortcut } from "../../keymap"
|
||||
import { OPENCODE_BASE_MODE, useBindings, useCommandShortcut } from "../../keymap"
|
||||
import { usePathFormatter } from "../../context/path-format"
|
||||
|
||||
type PermissionStage = "permission" | "always" | "reject"
|
||||
@@ -448,9 +447,8 @@ function RejectPrompt(props: { onConfirm: (message: string) => void; onCancel: (
|
||||
const tuiConfig = useTuiConfig()
|
||||
const dimensions = useTerminalDimensions()
|
||||
const narrow = createMemo(() => dimensions().width < 80)
|
||||
const dialog = useDialog()
|
||||
useBindings(() => ({
|
||||
enabled: dialog.stack.length === 0,
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
commands: [
|
||||
{
|
||||
name: "app.exit",
|
||||
@@ -542,11 +540,10 @@ function Prompt<const T extends Record<string, string>>(props: {
|
||||
expanded: false,
|
||||
})
|
||||
const narrow = createMemo(() => dimensions().width < 80)
|
||||
const dialog = useDialog()
|
||||
const fullscreenHint = useCommandShortcut("permission.prompt.fullscreen")
|
||||
|
||||
useBindings(() => ({
|
||||
enabled: dialog.stack.length === 0,
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
commands: [
|
||||
{
|
||||
name: "app.exit",
|
||||
|
||||
@@ -6,9 +6,8 @@ import { selectedForeground, tint, useTheme } from "../../context/theme"
|
||||
import type { QuestionAnswer, QuestionRequest } from "@opencode-ai/sdk/v2"
|
||||
import { useSDK } from "../../context/sdk"
|
||||
import { SplitBorder } from "../../component/border"
|
||||
import { useDialog } from "../../ui/dialog"
|
||||
import { useTuiConfig } from "../../context/tui-config"
|
||||
import { useBindings } from "../../keymap"
|
||||
import { OPENCODE_BASE_MODE, useBindings } from "../../keymap"
|
||||
|
||||
export function QuestionPrompt(props: { request: QuestionRequest }) {
|
||||
const sdk = useSDK()
|
||||
@@ -120,9 +119,8 @@ export function QuestionPrompt(props: { request: QuestionRequest }) {
|
||||
pick(opt.label)
|
||||
}
|
||||
|
||||
const dialog = useDialog()
|
||||
|
||||
useBindings(() => ({
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
enabled: store.editing && !confirm(),
|
||||
commands: [
|
||||
{
|
||||
@@ -203,7 +201,8 @@ export function QuestionPrompt(props: { request: QuestionRequest }) {
|
||||
const max = Math.min(total, 9)
|
||||
|
||||
return {
|
||||
enabled: dialog.stack.length === 0 && !store.editing,
|
||||
mode: OPENCODE_BASE_MODE,
|
||||
enabled: !store.editing,
|
||||
commands: [
|
||||
{
|
||||
name: "app.exit",
|
||||
|
||||
@@ -6,8 +6,7 @@ import { SplitBorder } from "@tui/component/border"
|
||||
import type { AssistantMessage } from "@opencode-ai/sdk/v2"
|
||||
import { Locale } from "@/util/locale"
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
import { useCommandPalette } from "../../context/command-palette"
|
||||
import { useCommandShortcut } from "../../keymap"
|
||||
import { useCommandShortcut, useOpencodeKeymap } from "../../keymap"
|
||||
|
||||
export function SubagentFooter() {
|
||||
const route = useRouteData("session")
|
||||
@@ -56,7 +55,7 @@ export function SubagentFooter() {
|
||||
})
|
||||
|
||||
const { theme } = useTheme()
|
||||
const command = useCommandPalette()
|
||||
const keymap = useOpencodeKeymap()
|
||||
const parentShortcut = useCommandShortcut("session.parent")
|
||||
const previousShortcut = useCommandShortcut("session.child.previous")
|
||||
const nextShortcut = useCommandShortcut("session.child.next")
|
||||
@@ -98,7 +97,7 @@ export function SubagentFooter() {
|
||||
<box
|
||||
onMouseOver={() => setHover("parent")}
|
||||
onMouseOut={() => setHover(null)}
|
||||
onMouseUp={() => command.run("session.parent")}
|
||||
onMouseUp={() => keymap.dispatchCommand("session.parent")}
|
||||
backgroundColor={hover() === "parent" ? theme.backgroundElement : theme.backgroundPanel}
|
||||
>
|
||||
<text fg={theme.text}>
|
||||
@@ -108,7 +107,7 @@ export function SubagentFooter() {
|
||||
<box
|
||||
onMouseOver={() => setHover("prev")}
|
||||
onMouseOut={() => setHover(null)}
|
||||
onMouseUp={() => command.run("session.child.previous")}
|
||||
onMouseUp={() => keymap.dispatchCommand("session.child.previous")}
|
||||
backgroundColor={hover() === "prev" ? theme.backgroundElement : theme.backgroundPanel}
|
||||
>
|
||||
<text fg={theme.text}>
|
||||
@@ -118,7 +117,7 @@ export function SubagentFooter() {
|
||||
<box
|
||||
onMouseOver={() => setHover("next")}
|
||||
onMouseOut={() => setHover(null)}
|
||||
onMouseUp={() => command.run("session.child.next")}
|
||||
onMouseUp={() => keymap.dispatchCommand("session.child.next")}
|
||||
backgroundColor={hover() === "next" ? theme.backgroundElement : theme.backgroundPanel}
|
||||
>
|
||||
<text fg={theme.text}>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useRenderer, useTerminalDimensions } from "@opentui/solid"
|
||||
import { batch, createContext, Show, useContext, type JSX, type ParentProps } from "solid-js"
|
||||
import { batch, createContext, createEffect, onCleanup, Show, useContext, type JSX, type ParentProps } from "solid-js"
|
||||
import { useTheme } from "@tui/context/theme"
|
||||
import { MouseButton, Renderable, RGBA } from "@opentui/core"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { useToast } from "./toast"
|
||||
import { Flag } from "@opencode-ai/core/flag/flag"
|
||||
import * as Selection from "@tui/util/selection"
|
||||
import { useBindings } from "../keymap"
|
||||
import { useBindings, useOpencodeModeStack } from "../keymap"
|
||||
|
||||
export function Dialog(
|
||||
props: ParentProps<{
|
||||
@@ -73,6 +73,13 @@ function init() {
|
||||
})
|
||||
|
||||
const renderer = useRenderer()
|
||||
const modeStack = useOpencodeModeStack()
|
||||
|
||||
createEffect(() => {
|
||||
if (store.stack.length === 0) return
|
||||
const popMode = modeStack.push("modal")
|
||||
onCleanup(popMode)
|
||||
})
|
||||
|
||||
let focus: Renderable | null
|
||||
function refocus() {
|
||||
|
||||
@@ -1,5 +1,127 @@
|
||||
import { Schema } from "effect"
|
||||
|
||||
export class InvalidRequestError extends Schema.TaggedErrorClass<InvalidRequestError>()(
|
||||
"InvalidRequestError",
|
||||
{
|
||||
message: Schema.String,
|
||||
kind: Schema.optional(Schema.String),
|
||||
field: Schema.optional(Schema.String),
|
||||
},
|
||||
{ httpApiStatus: 400 },
|
||||
) {}
|
||||
|
||||
export class UnauthorizedError extends Schema.TaggedErrorClass<UnauthorizedError>()(
|
||||
"UnauthorizedError",
|
||||
{ message: Schema.String },
|
||||
{ httpApiStatus: 401 },
|
||||
) {}
|
||||
|
||||
export class ForbiddenError extends Schema.TaggedErrorClass<ForbiddenError>()(
|
||||
"ForbiddenError",
|
||||
{ message: Schema.String },
|
||||
{ httpApiStatus: 403 },
|
||||
) {}
|
||||
|
||||
export class ConflictError extends Schema.TaggedErrorClass<ConflictError>()(
|
||||
"ConflictError",
|
||||
{
|
||||
message: Schema.String,
|
||||
resource: Schema.optional(Schema.String),
|
||||
},
|
||||
{ httpApiStatus: 409 },
|
||||
) {}
|
||||
|
||||
export class UpstreamError extends Schema.TaggedErrorClass<UpstreamError>()(
|
||||
"UpstreamError",
|
||||
{
|
||||
message: Schema.String,
|
||||
service: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.Number),
|
||||
},
|
||||
{ httpApiStatus: 502 },
|
||||
) {}
|
||||
|
||||
export class ServiceUnavailableError extends Schema.TaggedErrorClass<ServiceUnavailableError>()(
|
||||
"ServiceUnavailableError",
|
||||
{
|
||||
message: Schema.String,
|
||||
service: Schema.optional(Schema.String),
|
||||
},
|
||||
{ httpApiStatus: 503 },
|
||||
) {}
|
||||
|
||||
export class TimeoutError extends Schema.TaggedErrorClass<TimeoutError>()(
|
||||
"TimeoutError",
|
||||
{
|
||||
message: Schema.String,
|
||||
operation: Schema.optional(Schema.String),
|
||||
},
|
||||
{ httpApiStatus: 504 },
|
||||
) {}
|
||||
|
||||
export class UnknownError extends Schema.TaggedErrorClass<UnknownError>()(
|
||||
"UnknownError",
|
||||
{
|
||||
message: Schema.String,
|
||||
ref: Schema.optional(Schema.String),
|
||||
},
|
||||
{ httpApiStatus: 500 },
|
||||
) {}
|
||||
|
||||
export class ProviderNotFoundError extends Schema.TaggedErrorClass<ProviderNotFoundError>()(
|
||||
"ProviderNotFoundError",
|
||||
{
|
||||
providerID: Schema.String,
|
||||
message: Schema.String,
|
||||
},
|
||||
{ httpApiStatus: 404 },
|
||||
) {}
|
||||
|
||||
export class ModelNotFoundError extends Schema.TaggedErrorClass<ModelNotFoundError>()(
|
||||
"ModelNotFoundError",
|
||||
{
|
||||
providerID: Schema.String,
|
||||
modelID: Schema.String,
|
||||
suggestions: Schema.Array(Schema.String),
|
||||
message: Schema.String,
|
||||
},
|
||||
{ httpApiStatus: 404 },
|
||||
) {}
|
||||
|
||||
export class SessionNotFoundError extends Schema.TaggedErrorClass<SessionNotFoundError>()(
|
||||
"SessionNotFoundError",
|
||||
{
|
||||
sessionID: Schema.String,
|
||||
message: Schema.String,
|
||||
},
|
||||
{ httpApiStatus: 404 },
|
||||
) {}
|
||||
|
||||
export class MessageNotFoundError extends Schema.TaggedErrorClass<MessageNotFoundError>()(
|
||||
"MessageNotFoundError",
|
||||
{
|
||||
sessionID: Schema.String,
|
||||
messageID: Schema.String,
|
||||
message: Schema.String,
|
||||
},
|
||||
{ httpApiStatus: 404 },
|
||||
) {}
|
||||
|
||||
export class InvalidCursorError extends Schema.TaggedErrorClass<InvalidCursorError>()(
|
||||
"InvalidCursorError",
|
||||
{ message: Schema.String },
|
||||
{ httpApiStatus: 400 },
|
||||
) {}
|
||||
|
||||
export class SessionBusyError extends Schema.TaggedErrorClass<SessionBusyError>()(
|
||||
"SessionBusyError",
|
||||
{
|
||||
sessionID: Schema.String,
|
||||
message: Schema.String,
|
||||
},
|
||||
{ httpApiStatus: 409 },
|
||||
) {}
|
||||
|
||||
export class ApiNotFoundError extends Schema.ErrorClass<ApiNotFoundError>("NotFoundError")(
|
||||
{
|
||||
name: Schema.Literal("NotFoundError"),
|
||||
|
||||
@@ -99,17 +99,13 @@ function matchLegacyOpenApi(input: Record<string, unknown>) {
|
||||
applyLegacySchemaOverrides(spec)
|
||||
normalizeComponentDescriptions(spec)
|
||||
addLegacyErrorSchemas(spec)
|
||||
delete spec.components?.schemas?.Unauthorized
|
||||
delete spec.components?.schemas?.EffectHttpApiErrorBadRequest
|
||||
delete spec.components?.schemas?.EffectHttpApiErrorNotFound
|
||||
delete spec.components?.schemas?.effect_HttpApiError_BadRequest
|
||||
delete spec.components?.schemas?.effect_HttpApiError_NotFound
|
||||
delete spec.components?.securitySchemes
|
||||
|
||||
for (const [path, item] of Object.entries(spec.paths ?? {})) {
|
||||
for (const method of ["get", "post", "put", "delete", "patch"] as const) {
|
||||
const operation = item[method]
|
||||
if (!operation) continue
|
||||
const isV2Api = isV2ApiPath(path)
|
||||
if (operation.requestBody) {
|
||||
// The legacy OpenAPI surface never marked request bodies as required.
|
||||
// Keep that SDK surface stable while the HttpApi spec is tightened.
|
||||
@@ -146,11 +142,14 @@ function matchLegacyOpenApi(input: Record<string, unknown>) {
|
||||
if (content.schema) content.schema = stripOptionalNull(structuredClone(content.schema))
|
||||
}
|
||||
}
|
||||
// Auth is still runtime middleware outside the public OpenAPI metadata, so
|
||||
// the SDK should not expose auth schemes or generated 401 error unions.
|
||||
delete operation.security
|
||||
delete operation.responses?.["401"]
|
||||
normalizeLegacyErrorResponses(operation)
|
||||
if (!isV2Api) {
|
||||
// Auth is still runtime middleware outside the legacy public OpenAPI
|
||||
// metadata, so the legacy SDK should not expose auth schemes or
|
||||
// generated 401 error unions.
|
||||
delete operation.security
|
||||
delete operation.responses?.["401"]
|
||||
normalizeLegacyErrorResponses(operation)
|
||||
}
|
||||
normalizeLegacyOperation(operation, path, method)
|
||||
if ((path === "/event" || path === "/global/event") && method === "get") {
|
||||
// HttpApi has no first-class SSE response schema, and these handlers are
|
||||
@@ -171,9 +170,14 @@ function matchLegacyOpenApi(input: Record<string, unknown>) {
|
||||
for (const param of operation.parameters ?? []) normalizeParameter(param, route)
|
||||
}
|
||||
}
|
||||
deleteUnusedLegacyErrorComponents(spec)
|
||||
return input
|
||||
}
|
||||
|
||||
function isV2ApiPath(path: string) {
|
||||
return path === "/api" || path.startsWith("/api/")
|
||||
}
|
||||
|
||||
function addLegacyErrorSchemas(spec: OpenApiSpec) {
|
||||
if (!spec.components?.schemas) return
|
||||
spec.components.schemas.BadRequestError = {
|
||||
@@ -345,6 +349,26 @@ function normalizeLegacyErrorResponses(operation: OpenApiOperation) {
|
||||
}
|
||||
}
|
||||
|
||||
function deleteUnusedLegacyErrorComponents(spec: OpenApiSpec) {
|
||||
for (const name of [
|
||||
"Unauthorized",
|
||||
"EffectHttpApiErrorBadRequest",
|
||||
"EffectHttpApiErrorNotFound",
|
||||
"effect_HttpApiError_BadRequest",
|
||||
"effect_HttpApiError_NotFound",
|
||||
]) {
|
||||
if (referencesComponent(spec.paths, name)) continue
|
||||
delete spec.components?.schemas?.[name]
|
||||
}
|
||||
}
|
||||
|
||||
function referencesComponent(input: unknown, name: string): boolean {
|
||||
if (Array.isArray(input)) return input.some((item) => referencesComponent(item, name))
|
||||
if (!input || typeof input !== "object") return false
|
||||
if ((input as OpenApiSchema).$ref === `#/components/schemas/${name}`) return true
|
||||
return Object.values(input).some((value) => referencesComponent(value, name))
|
||||
}
|
||||
|
||||
function normalizeLegacyOperation(operation: OpenApiOperation, path: string, method: string) {
|
||||
if (path === "/experimental/console/switch" && method === "post") delete operation.responses?.["400"]
|
||||
if (path === "/pty/{ptyID}" && method === "put") delete operation.responses?.["404"]
|
||||
|
||||
@@ -37,13 +37,16 @@ type StreamInput = {
|
||||
}
|
||||
|
||||
export function status(input: Pick<StreamInput, "model" | "provider" | "auth">): RuntimeStatus {
|
||||
if (input.model.providerID !== "openai" && !input.model.providerID.startsWith("opencode"))
|
||||
return { type: "unsupported", reason: "provider is not openai or opencode" }
|
||||
if (input.model.api.npm !== "@ai-sdk/openai") return { type: "unsupported", reason: "provider package is not OpenAI" }
|
||||
const providerID = input.model.providerID
|
||||
if (providerID !== "openai" && providerID !== "anthropic" && !providerID.startsWith("opencode"))
|
||||
return { type: "unsupported", reason: "provider is not openai, opencode, or anthropic" }
|
||||
const npm = input.model.api.npm
|
||||
if (npm !== "@ai-sdk/openai" && npm !== "@ai-sdk/anthropic")
|
||||
return { type: "unsupported", reason: "provider package is not OpenAI or Anthropic" }
|
||||
if (input.auth?.type === "oauth") return { type: "unsupported", reason: "OAuth auth is not supported" }
|
||||
|
||||
const apiKey = typeof input.provider.options.apiKey === "string" ? input.provider.options.apiKey : input.provider.key
|
||||
if (!apiKey) return { type: "unsupported", reason: "OpenAI API key is not configured" }
|
||||
if (!apiKey) return { type: "unsupported", reason: "API key is not configured" }
|
||||
|
||||
return {
|
||||
type: "supported",
|
||||
|
||||
@@ -145,9 +145,12 @@ export const layer: Layer.Layer<
|
||||
function fromPlugin(id: string, def: ToolDefinition): Tool.Def {
|
||||
// Plugin tools still expose Zod args publicly; keep that compatibility
|
||||
// boxed at the registry boundary and give the LLM the original JSON Schema.
|
||||
const entries = Object.entries(def.args)
|
||||
// Normalize missing args to `{}` once — pre-1.14.49 the code was
|
||||
// `z.object(def.args)` and Zod silently tolerated undefined (#27451, #27630).
|
||||
const args = def.args ?? {}
|
||||
const entries = Object.entries(args)
|
||||
const allZod = entries.every((entry) => isZodType(entry[1]))
|
||||
const zodParams = allZod ? z.object(def.args) : undefined
|
||||
const zodParams = allZod ? z.object(args) : undefined
|
||||
const jsonSchema = zodParams ? zodJsonSchema(zodParams) : legacyJsonSchema(entries)
|
||||
const parameters = zodParams
|
||||
? Schema.declare<unknown>((u): u is unknown => zodParams.safeParse(u).success)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// Subprocess integration tests for `opencode acp`. ACP is a JSON-RPC
|
||||
// protocol spoken over stdin/stdout (not HTTP) — see src/acp/README.md.
|
||||
// This is the only test tier that exercises the full pipe of bun startup →
|
||||
// server boot → ACP agent init → stdio framing → graceful shutdown.
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Duration, Effect } from "effect"
|
||||
import { cliIt } from "../../lib/cli-process"
|
||||
|
||||
describe("opencode acp (subprocess)", () => {
|
||||
// Smoke test: send the `initialize` request from src/acp/README.md and
|
||||
// assert the response advertises the same protocol version and a non-empty
|
||||
// capabilities block. If this fails, every other ACP test will too — start
|
||||
// debugging here.
|
||||
cliIt.live(
|
||||
"responds to initialize with protocolVersion 1 and capabilities",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const acp = yield* opencode.acp()
|
||||
|
||||
yield* acp.send({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: { protocolVersion: 1 },
|
||||
})
|
||||
|
||||
// Tight deadline — the response should arrive within a few seconds
|
||||
// once startup completes. A hang means the agent never finished init,
|
||||
// which is a real regression and not a tuning issue.
|
||||
const response = (yield* acp.receive.pipe(Effect.timeout(Duration.seconds(10)))) as {
|
||||
jsonrpc: string
|
||||
id: number
|
||||
result?: { protocolVersion: number; agentCapabilities: Record<string, unknown> }
|
||||
error?: unknown
|
||||
}
|
||||
|
||||
expect(response.jsonrpc).toBe("2.0")
|
||||
expect(response.id).toBe(1)
|
||||
expect(response.error).toBeUndefined()
|
||||
expect(response.result?.protocolVersion).toBe(1)
|
||||
expect(response.result?.agentCapabilities).toBeDefined()
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// Lock in the scope-close kill path. ACP's clean shutdown is "EOF on stdin"
|
||||
// — if a future refactor breaks the stdin-end branch in the handler, the
|
||||
// process would only exit on SIGTERM fallback (2s in the harness). This
|
||||
// test passing within the inner-scope assertion proves the EOF path works.
|
||||
cliIt.live(
|
||||
"exits cleanly when stdin is closed (scope close)",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const exited = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const acp = yield* opencode.acp()
|
||||
// Capture the Effect — scope-close shuts down stdinQueue, which
|
||||
// propagates as stdin EOF; ACP exits gracefully. The exitCode
|
||||
// Effect itself has no Scope requirement so yielding it after
|
||||
// scope close is safe.
|
||||
return acp.exited
|
||||
}),
|
||||
)
|
||||
|
||||
const code = yield* exited
|
||||
// Signal-killed processes surface as -1; clean EOF gives 0. Either
|
||||
// way we just need a number — proves the process exited.
|
||||
expect(typeof code).toBe("number")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,623 @@
|
||||
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode acp --help 1`] = `
|
||||
"opencode acp
|
||||
|
||||
start ACP (Agent Client Protocol) server
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--port port to listen on [number] [default: 0]
|
||||
--hostname hostname to listen on [string] [default: "127.0.0.1"]
|
||||
--mdns enable mDNS service discovery (defaults hostname to 0.0.0.0)
|
||||
[boolean] [default: false]
|
||||
--mdns-domain custom domain name for mDNS service (default: opencode.local)
|
||||
[string] [default: "opencode.local"]
|
||||
--cors additional domains to allow for CORS [array] [default: []]
|
||||
--cwd working directory [string] [default: "<HOME>"]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp --help 1`] = `
|
||||
"opencode mcp
|
||||
|
||||
manage MCP (Model Context Protocol) servers
|
||||
|
||||
Commands:
|
||||
opencode mcp add add an MCP server
|
||||
opencode mcp list list MCP servers and their status [aliases: ls]
|
||||
opencode mcp auth [name] authenticate with an OAuth-enabled MCP server
|
||||
opencode mcp logout [name] remove OAuth credentials for an MCP server
|
||||
opencode mcp debug <name> debug OAuth connection for an MCP server
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode attach --help 1`] = `
|
||||
"opencode attach <url>
|
||||
|
||||
attach to a running opencode server
|
||||
|
||||
Positionals:
|
||||
url http://localhost:4096 [string] [required]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--dir directory to run in [string]
|
||||
-c, --continue continue the last session [boolean]
|
||||
-s, --session session id to continue [string]
|
||||
--fork fork the session when continuing (use with --continue or --session) [boolean]
|
||||
-p, --password basic auth password (defaults to OPENCODE_SERVER_PASSWORD) [string]
|
||||
-u, --username basic auth username (defaults to OPENCODE_SERVER_USERNAME or 'opencode')[string]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode run --help 1`] = `
|
||||
"opencode run [message..]
|
||||
|
||||
run opencode with a message
|
||||
|
||||
Positionals:
|
||||
message message to send [array] [default: []]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--command the command to run, use message for args [string]
|
||||
-c, --continue continue the last session [boolean]
|
||||
-s, --session session id to continue [string]
|
||||
--fork fork the session before continuing (requires --continue or
|
||||
--session) [boolean]
|
||||
--share share the session [boolean]
|
||||
-m, --model model to use in the format of provider/model [string]
|
||||
--agent agent to use [string]
|
||||
--format format: default (formatted) or json (raw JSON events)
|
||||
[string] [choices: "default", "json"] [default: "default"]
|
||||
-f, --file file(s) to attach to message [array]
|
||||
--title title for the session (uses truncated prompt if no value
|
||||
provided) [string]
|
||||
--attach attach to a running opencode server (e.g.,
|
||||
http://localhost:4096) [string]
|
||||
-p, --password basic auth password (defaults to OPENCODE_SERVER_PASSWORD)
|
||||
[string]
|
||||
-u, --username basic auth username (defaults to OPENCODE_SERVER_USERNAME or
|
||||
'opencode') [string]
|
||||
--dir directory to run in, path on remote server if attaching
|
||||
[string]
|
||||
--port port for the local server (defaults to random port if no value
|
||||
provided) [number]
|
||||
--variant model variant (provider-specific reasoning effort, e.g., high,
|
||||
max, minimal) [string]
|
||||
--thinking show thinking blocks [boolean]
|
||||
--replay replay visible session history on interactive resume
|
||||
[boolean] [default: false]
|
||||
--replay-limit cap visible interactive replay to the newest N messages
|
||||
[number]
|
||||
-i, --interactive run in direct interactive split-footer mode
|
||||
[boolean] [default: false]
|
||||
--dangerously-skip-permissions auto-approve permissions that are not explicitly denied
|
||||
(dangerous!) [boolean] [default: false]
|
||||
--demo enable direct interactive demo slash commands; pass one as the
|
||||
message to run it immediately [boolean] [default: false]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode debug --help 1`] = `
|
||||
"opencode debug
|
||||
|
||||
debugging and troubleshooting tools
|
||||
|
||||
Commands:
|
||||
opencode debug config show resolved configuration
|
||||
opencode debug lsp LSP debugging utilities
|
||||
opencode debug rg ripgrep debugging utilities
|
||||
opencode debug file file system debugging utilities
|
||||
opencode debug scrap list all known projects
|
||||
opencode debug skill list all available skills
|
||||
opencode debug snapshot snapshot debugging utilities
|
||||
opencode debug startup print startup timing
|
||||
opencode debug agent <name> show agent configuration details
|
||||
opencode debug v2 debug v2 catalog and built-in plugins
|
||||
opencode debug info show debug information
|
||||
opencode debug paths show global paths (data, config, cache, state)
|
||||
opencode debug wait wait indefinitely (for debugging)
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode providers --help 1`] = `
|
||||
"opencode providers
|
||||
|
||||
manage AI providers and credentials
|
||||
|
||||
Commands:
|
||||
opencode providers list list providers and credentials [aliases: ls]
|
||||
opencode providers login [url] log in to a provider
|
||||
opencode providers logout log out from a configured provider
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode agent --help 1`] = `
|
||||
"opencode agent
|
||||
|
||||
manage agents
|
||||
|
||||
Commands:
|
||||
opencode agent create create a new agent
|
||||
opencode agent list list all available agents
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode upgrade --help 1`] = `
|
||||
"opencode upgrade [target]
|
||||
|
||||
upgrade opencode to the latest or a specific version
|
||||
|
||||
Positionals:
|
||||
target version to upgrade to, for ex '0.1.48' or 'v0.1.48' [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
-m, --method installation method to use
|
||||
[string] [choices: "curl", "npm", "pnpm", "bun", "brew", "choco", "scoop"]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode uninstall --help 1`] = `
|
||||
"opencode uninstall
|
||||
|
||||
uninstall opencode and remove all related files
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
-c, --keep-config keep configuration files [boolean] [default: false]
|
||||
-d, --keep-data keep session data and snapshots [boolean] [default: false]
|
||||
--dry-run show what would be removed without removing [boolean] [default: false]
|
||||
-f, --force skip confirmation prompts [boolean] [default: false]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode serve --help 1`] = `
|
||||
"opencode serve
|
||||
|
||||
starts a headless opencode server
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--port port to listen on [number] [default: 0]
|
||||
--hostname hostname to listen on [string] [default: "127.0.0.1"]
|
||||
--mdns enable mDNS service discovery (defaults hostname to 0.0.0.0)
|
||||
[boolean] [default: false]
|
||||
--mdns-domain custom domain name for mDNS service (default: opencode.local)
|
||||
[string] [default: "opencode.local"]
|
||||
--cors additional domains to allow for CORS [array] [default: []]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode web --help 1`] = `
|
||||
"opencode web
|
||||
|
||||
start opencode server and open web interface
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--port port to listen on [number] [default: 0]
|
||||
--hostname hostname to listen on [string] [default: "127.0.0.1"]
|
||||
--mdns enable mDNS service discovery (defaults hostname to 0.0.0.0)
|
||||
[boolean] [default: false]
|
||||
--mdns-domain custom domain name for mDNS service (default: opencode.local)
|
||||
[string] [default: "opencode.local"]
|
||||
--cors additional domains to allow for CORS [array] [default: []]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode models --help 1`] = `
|
||||
"opencode models [provider]
|
||||
|
||||
list all available models
|
||||
|
||||
Positionals:
|
||||
provider provider ID to filter models by [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--verbose use more verbose model output (includes metadata like costs) [boolean]
|
||||
--refresh refresh the models cache from models.dev [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode stats --help 1`] = `
|
||||
"opencode stats
|
||||
|
||||
show token usage and cost statistics
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--days show stats for the last N days (default: all time) [number]
|
||||
--tools number of tools to show (default: all) [number]
|
||||
--models show model statistics (default: hidden). Pass a number to show top N, otherwise
|
||||
shows all
|
||||
--project filter by project (default: all projects, empty string: current project)[string]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode export --help 1`] = `
|
||||
"opencode export [sessionID]
|
||||
|
||||
export session data as JSON
|
||||
|
||||
Positionals:
|
||||
sessionID session id to export [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--sanitize redact sensitive transcript and file data [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode import --help 1`] = `
|
||||
"opencode import <file>
|
||||
|
||||
import session data from JSON file or URL
|
||||
|
||||
Positionals:
|
||||
file path to JSON file or share URL [string] [required]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode github --help 1`] = `
|
||||
"opencode github
|
||||
|
||||
manage GitHub agent
|
||||
|
||||
Commands:
|
||||
opencode github install install the GitHub agent
|
||||
opencode github run run the GitHub agent
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode pr --help 1`] = `
|
||||
"opencode pr <number>
|
||||
|
||||
fetch and checkout a GitHub PR branch, then run opencode
|
||||
|
||||
Positionals:
|
||||
number PR number to checkout [number] [required]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode session --help 1`] = `
|
||||
"opencode session
|
||||
|
||||
manage sessions
|
||||
|
||||
Commands:
|
||||
opencode session list list sessions
|
||||
opencode session delete <sessionID> delete a session
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode plugin --help 1`] = `
|
||||
"opencode plugin <module>
|
||||
|
||||
install plugin and update config
|
||||
|
||||
Positionals:
|
||||
module npm module name [string] [required]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
-g, --global install in global config [boolean] [default: false]
|
||||
-f, --force replace existing plugin version [boolean] [default: false]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode db --help 1`] = `
|
||||
"opencode db
|
||||
|
||||
database tools
|
||||
|
||||
Commands:
|
||||
opencode db [query] open an interactive sqlite3 shell or run a query [default]
|
||||
opencode db path print the database path
|
||||
opencode db migrate migrate JSON data to SQLite (merges with existing data)
|
||||
|
||||
Positionals:
|
||||
query SQL query to execute [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--format Output format [string] [choices: "json", "tsv"] [default: "tsv"]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp list --help 1`] = `
|
||||
"opencode mcp list
|
||||
|
||||
list MCP servers and their status
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp add --help 1`] = `
|
||||
"opencode mcp add
|
||||
|
||||
add an MCP server
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp auth --help 1`] = `
|
||||
"opencode mcp auth [name]
|
||||
|
||||
authenticate with an OAuth-enabled MCP server
|
||||
|
||||
Commands:
|
||||
opencode mcp auth list list OAuth-capable MCP servers and their auth status [aliases: ls]
|
||||
|
||||
Positionals:
|
||||
name name of the MCP server [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp logout --help 1`] = `
|
||||
"opencode mcp logout [name]
|
||||
|
||||
remove OAuth credentials for an MCP server
|
||||
|
||||
Positionals:
|
||||
name name of the MCP server [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode providers list --help 1`] = `
|
||||
"opencode providers list
|
||||
|
||||
list providers and credentials
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode providers login --help 1`] = `
|
||||
"opencode providers login [url]
|
||||
|
||||
log in to a provider
|
||||
|
||||
Positionals:
|
||||
url opencode auth provider [string]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
-p, --provider provider id or name to log in to (skips provider selection) [string]
|
||||
-m, --method login method label (skips method selection) [string]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode providers logout --help 1`] = `
|
||||
"opencode providers logout
|
||||
|
||||
log out from a configured provider
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode agent create --help 1`] = `
|
||||
"opencode agent create
|
||||
|
||||
create a new agent
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--path directory path to generate the agent file [string]
|
||||
--description what the agent should do [string]
|
||||
--mode agent mode [string] [choices: "all", "primary", "subagent"]
|
||||
--permissions, --tools comma-separated list of permissions to allow (default: all).
|
||||
Available: "bash, read, edit, glob, grep, webfetch, task, todowrite,
|
||||
websearch, lsp, skill" [string]
|
||||
-m, --model model to use in the format of provider/model [string]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode agent list --help 1`] = `
|
||||
"opencode agent list
|
||||
|
||||
list all available agents
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode session list --help 1`] = `
|
||||
"opencode session list
|
||||
|
||||
list sessions
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
-n, --max-count limit to N most recent sessions [number]
|
||||
--format output format [string] [choices: "table", "json"] [default: "table"]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode session delete --help 1`] = `
|
||||
"opencode session delete <sessionID>
|
||||
|
||||
delete a session
|
||||
|
||||
Positionals:
|
||||
sessionID session ID to delete [string] [required]
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode github install --help 1`] = `
|
||||
"opencode github install
|
||||
|
||||
install the GitHub agent
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode github run --help 1`] = `
|
||||
"opencode github run
|
||||
|
||||
run the GitHub agent
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]
|
||||
--event GitHub mock event to run the agent for [string]
|
||||
--token GitHub personal access token (github_pat_********) [string]"
|
||||
`;
|
||||
|
||||
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode db path --help 1`] = `
|
||||
"opencode db path
|
||||
|
||||
print the database path
|
||||
|
||||
Options:
|
||||
-h, --help show help [boolean]
|
||||
-v, --version show version number [boolean]
|
||||
--print-logs print logs to stderr [boolean]
|
||||
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
|
||||
--pure run without external plugins [boolean]"
|
||||
`;
|
||||
@@ -0,0 +1,132 @@
|
||||
// Help-text snapshots for every CLI command + key subcommand. Catches
|
||||
// accidental flag removals, renames, and reordering in a single sweep —
|
||||
// any change to the user-visible CLI surface shows up here as a diff.
|
||||
//
|
||||
// This is the broad coverage layer that makes the future Effect CLI
|
||||
// migration (yargs → effect-smol/cli) safe to attempt: if a refactor
|
||||
// preserves the surface, the snapshots stay green; if it doesn't, the
|
||||
// diff tells you exactly which command(s) changed.
|
||||
//
|
||||
// Snapshots are taken at COLUMNS=120 so wrapping is stable across
|
||||
// terminal sizes. The default opencode tui command is excluded —
|
||||
// `opencode --help` includes an ASCII banner that pulls in the install
|
||||
// version (changes per release), so we'd snapshot a moving target.
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { cliIt } from "../../lib/cli-process"
|
||||
import { normalizeForSnapshot, PATH_SEP } from "../../lib/snapshot"
|
||||
|
||||
// Composes `normalizeForSnapshot` (CRLF + tmpdir) with two help-specific
|
||||
// rules:
|
||||
//
|
||||
// 1. The harness's `oc-cli-XXX` subdir under TMPDIR collapses to `<HOME>`.
|
||||
// `PATH_SEP` matches `/` and `\\` so the rule works on POSIX + Windows.
|
||||
//
|
||||
// 2. yargs wraps the `[string] [default: "..."]` clause based on the
|
||||
// pre-normalized default's character length, so different random home
|
||||
// path widths produce different leading-whitespace counts (or even
|
||||
// line-wraps onto a fresh line on Windows). `\s+` matches both forms.
|
||||
function normalize(text: string): string {
|
||||
return normalizeForSnapshot(text, {
|
||||
pathReplacements: [
|
||||
// Mixed-case [A-Za-z0-9] because node's mkdtemp suffix is mixed-case
|
||||
// (the harness now uses FileSystem.makeTempDirectoryScoped under the
|
||||
// hood). A `[a-z0-9]+` regex would leave uppercase chars trailing.
|
||||
[new RegExp(`<TMPDIR>${PATH_SEP}oc-cli-[A-Za-z0-9]+`, "g"), "<HOME>"],
|
||||
[/\s+\[string\] \[default: "<HOME>"\]/g, ' [string] [default: "<HOME>"]'],
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
// Top-level commands. Order matches what `opencode --help` prints today;
|
||||
// keep it in that order so the snapshot file reads as a table of contents.
|
||||
// `completion` is intentionally excluded — it's a yargs built-in that emits
|
||||
// top-level help on `--help` and exits 1; not a real opencode command.
|
||||
const TOP_LEVEL = [
|
||||
"acp",
|
||||
"mcp",
|
||||
"attach",
|
||||
"run",
|
||||
"debug",
|
||||
"providers", // aliased to `auth`
|
||||
"agent",
|
||||
"upgrade",
|
||||
"uninstall",
|
||||
"serve",
|
||||
"web",
|
||||
"models",
|
||||
"stats",
|
||||
"export",
|
||||
"import",
|
||||
"github",
|
||||
"pr",
|
||||
"session",
|
||||
"plugin",
|
||||
"db",
|
||||
] as const
|
||||
|
||||
// Subcommands worth pinning. Not exhaustive — the goal is one snapshot per
|
||||
// distinct argv shape, not every leaf. Add new entries when a subcommand
|
||||
// gains user-visible flags that we want to lock in.
|
||||
const SUBCOMMANDS = [
|
||||
["mcp", "list"],
|
||||
["mcp", "add"],
|
||||
["mcp", "auth"],
|
||||
["mcp", "logout"],
|
||||
["providers", "list"],
|
||||
["providers", "login"],
|
||||
["providers", "logout"],
|
||||
["agent", "create"],
|
||||
["agent", "list"],
|
||||
["session", "list"],
|
||||
["session", "delete"],
|
||||
["github", "install"],
|
||||
["github", "run"],
|
||||
["db", "path"],
|
||||
] as const
|
||||
|
||||
// Fixed wrap width so a developer's terminal doesn't affect snapshots.
|
||||
// yargs honors COLUMNS; CI runners typically default to 80 which produces
|
||||
// different wraps from a 200-col local terminal.
|
||||
const SNAPSHOT_ENV = { COLUMNS: "120" }
|
||||
|
||||
describe("opencode CLI help-text snapshots", () => {
|
||||
// Single test, parallel spawns. Each command's help fires under
|
||||
// `concurrency: 8` — wall-clock stays under ~10s even for ~35 commands,
|
||||
// versus ~1 minute if we serialized.
|
||||
cliIt.live(
|
||||
"every documented command emits stable help text",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const argvs: Array<readonly string[]> = [...TOP_LEVEL.map((c) => [c] as const), ...SUBCOMMANDS]
|
||||
|
||||
// Spawn in parallel, then assert in argv order so snapshot output is
|
||||
// deterministic and per-command failures don't abort the rest of
|
||||
// the sweep. `Effect.partition` is the canonical "run all, separate
|
||||
// failures from successes" primitive — no mutable accumulator needed.
|
||||
const [failures, results] = yield* Effect.partition(
|
||||
argvs,
|
||||
(argv) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* opencode.spawn([...argv, "--help"], { env: SNAPSHOT_ENV })
|
||||
if (result.exitCode !== 0) {
|
||||
return yield* Effect.fail(`opencode ${argv.join(" ")}: exit ${result.exitCode}`)
|
||||
}
|
||||
return { argv, result }
|
||||
}),
|
||||
{ concurrency: 8 },
|
||||
)
|
||||
|
||||
for (const { argv, result } of results) {
|
||||
// yargs writes --help to stderr, not stdout. Snapshotting stderr
|
||||
// means our test catches the help body; stdout for these commands
|
||||
// is expected to be empty.
|
||||
expect(normalize(result.stderr)).toMatchSnapshot(`opencode ${argv.join(" ")} --help`)
|
||||
}
|
||||
if (failures.length > 0) {
|
||||
throw new Error(`Help text failed for:\n ${failures.join("\n ")}`)
|
||||
}
|
||||
}),
|
||||
180_000,
|
||||
)
|
||||
})
|
||||
@@ -403,38 +403,82 @@ test("inserts spacers for new visible groups", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("renders replayed user, reasoning, and assistant output after completion", async () => {
|
||||
const out = await setup()
|
||||
// TODO(windows): Re-enable on Windows once the streaming CodeRenderable
|
||||
// flush race is fixed. The reasoning commit is delivered as a `<code>`
|
||||
// renderable with `filetype="markdown"`, `streaming=true`, and
|
||||
// `drawUnstyledText=false`. On Windows the first paragraph of the reasoning
|
||||
// body (here `_Thinking:_ **Plan**`) is dropped from the committed rows —
|
||||
// the failing assertion shows only `Say hello.` survives, while Linux
|
||||
// (where `useThread` is forced off in `@opentui/core/testing`) and macOS
|
||||
// both pass.
|
||||
//
|
||||
// Investigation summary (see PR description for the link to this work):
|
||||
// 1. `reasoning("Thinking: ...", "progress")` enters `entry.body.ts`
|
||||
// `reasoningBody`, which becomes a `code` body with filetype="markdown".
|
||||
// 2. `RunScrollbackStream.writeStreaming` sets `renderable.content = ...`
|
||||
// while `streaming=true`. `CodeRenderable.set content` short-circuits
|
||||
// (does NOT call `textBuffer.setText`) when streaming, drawUnstyledText
|
||||
// is false, and a filetype is set — it relies on the next
|
||||
// `startHighlight()` cycle to populate the buffer.
|
||||
// 3. `ScrollbackSurface.settle()` renders the surface, kicks the
|
||||
// highlight via `renderSelf` → `startHighlight`, waits on
|
||||
// `highlightingDone`, and re-renders. With `MockTreeSitterClient`
|
||||
// returning `{highlights: []}`, the final branch (`else
|
||||
// this.textBuffer.setText(content)`) populates the buffer and
|
||||
// `_shouldRenderTextBuffer = true`.
|
||||
// 4. `flushActive` then commits rows `[0, surface.height - 1)` during
|
||||
// streaming. On Windows the committed rows are blank for the first
|
||||
// paragraph — suggesting the height/text-buffer state is observed
|
||||
// before/after the highlight resolution in a way that drops rows on
|
||||
// that platform.
|
||||
//
|
||||
// The Linux pass path takes `useThread = false` (see
|
||||
// `@opentui/core/testing.js` line ~540) which serializes the FFI render
|
||||
// thread. macOS passes despite `useThread = true`, so the divergence is
|
||||
// likely either Bun's microtask scheduling on Windows or a Zig-side
|
||||
// threading interaction during the second `renderSurface()` pass in
|
||||
// `settleSurface`. A real fix probably belongs in opentui (either force
|
||||
// `useThread=false` for testing on Windows, or eagerly call
|
||||
// `textBuffer.setText` in `CodeRenderable.set content` when streaming
|
||||
// updates a non-empty body).
|
||||
//
|
||||
// Skipping on win32 unblocks unrelated PRs; the assertion is still
|
||||
// exercised on Linux and macOS in CI.
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"renders replayed user, reasoning, and assistant output after completion",
|
||||
async () => {
|
||||
const out = await setup()
|
||||
|
||||
try {
|
||||
const lines: string[] = []
|
||||
const take = () => {
|
||||
const commits = claim(out.renderer)
|
||||
try {
|
||||
lines.push(...commits.flatMap((commit) => renderRows(commit).flatMap((row) => row.split("\n"))))
|
||||
} finally {
|
||||
destroy(commits)
|
||||
try {
|
||||
const lines: string[] = []
|
||||
const take = () => {
|
||||
const commits = claim(out.renderer)
|
||||
try {
|
||||
lines.push(...commits.flatMap((commit) => renderRows(commit).flatMap((row) => row.split("\n"))))
|
||||
} finally {
|
||||
destroy(commits)
|
||||
}
|
||||
}
|
||||
|
||||
await out.scrollback.append(user("Hello you"))
|
||||
take()
|
||||
await out.scrollback.append(reasoning("Thinking: **Plan**\n\nSay hello.", "progress"))
|
||||
await out.scrollback.complete()
|
||||
take()
|
||||
await out.scrollback.append(assistant("Hello.", "progress"))
|
||||
await out.scrollback.complete()
|
||||
take()
|
||||
|
||||
const output = lines.join("\n")
|
||||
expect(output).toContain("› Hello you")
|
||||
expect(output).toContain("Thinking:")
|
||||
expect(output).toContain("Plan")
|
||||
expect(output).toContain("Hello.")
|
||||
} finally {
|
||||
out.scrollback.destroy()
|
||||
}
|
||||
|
||||
await out.scrollback.append(user("Hello you"))
|
||||
take()
|
||||
await out.scrollback.append(reasoning("Thinking: **Plan**\n\nSay hello.", "progress"))
|
||||
await out.scrollback.complete()
|
||||
take()
|
||||
await out.scrollback.append(assistant("Hello.", "progress"))
|
||||
await out.scrollback.complete()
|
||||
take()
|
||||
|
||||
const output = lines.join("\n")
|
||||
expect(output).toContain("› Hello you")
|
||||
expect(output).toContain("Thinking:")
|
||||
expect(output).toContain("Plan")
|
||||
expect(output).toContain("Hello.")
|
||||
} finally {
|
||||
out.scrollback.destroy()
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
test("coalesces same-line tool progress into one snapshot", async () => {
|
||||
const out = await setup()
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Subprocess integration tests for `opencode serve`. Spawns the real CLI in
|
||||
// headless mode and exercises it over HTTP — this is the only test tier that
|
||||
// catches bugs spanning argv → server boot → routing → instance loading.
|
||||
//
|
||||
// `serve` is long-lived: the harness returns a handle (url/port/kill/exited)
|
||||
// and kills the process when the test scope closes. The OS-assigned port is
|
||||
// parsed off the "listening on http://..." line.
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { HttpClient } from "effect/unstable/http"
|
||||
import { cliIt } from "../../lib/cli-process"
|
||||
|
||||
describe("opencode serve (subprocess)", () => {
|
||||
// Smoke test: server starts, binds a port, and /global/health responds.
|
||||
// If this fails, all other serve tests likely will too — debug here first.
|
||||
cliIt.live(
|
||||
"starts, binds a port, and serves /global/health",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* opencode.serve()
|
||||
expect(server.port).toBeGreaterThan(0)
|
||||
expect(server.url).toMatch(/^http:\/\//)
|
||||
|
||||
const client = yield* HttpClient.HttpClient
|
||||
const res = yield* client.get(`${server.url}/global/health`)
|
||||
expect(res.status).toBe(200)
|
||||
// GlobalHealth schema is { success: true, ... } | { success: false, error }.
|
||||
// We don't lock in further shape here — any 200 with parseable JSON is
|
||||
// enough proof the routing + auth-bypass + instance loading is alive.
|
||||
const body = yield* res.json
|
||||
expect(body).toBeDefined()
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// The scope-close finalizer must actually terminate the child. Without this
|
||||
// test a regression in the kill path (e.g. a future refactor that forgets
|
||||
// to wire the finalizer) would leak processes on every test run.
|
||||
cliIt.live(
|
||||
"kills the subprocess on scope close",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
// Inner scope so we can observe `.exited` resolving after it closes.
|
||||
const exited = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* opencode.serve()
|
||||
// Capture the Effect, not its result — scope closes after this
|
||||
// gen returns, at which point the finalizer kills the child.
|
||||
// handle.exitCode itself has no Scope requirement, so yielding
|
||||
// it after scope close is fine.
|
||||
return server.exited
|
||||
}),
|
||||
)
|
||||
// After scope close: finalizer fired, process must have exited.
|
||||
// Signal-killed processes surface as -1 (see ServeHandle.exited).
|
||||
const code = yield* exited
|
||||
expect(typeof code).toBe("number")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
// Tier-A smoke tests for read-only commands. Each test asserts only that the
|
||||
// command exits 0 and produces *some* output in the isolated harness env.
|
||||
//
|
||||
// These are not behavioral tests — they're the cheapest possible signal that
|
||||
// the dependency-layer wiring (config load, DB init, server boot, provider
|
||||
// resolution) doesn't crash for the broad class of "no inputs, no side
|
||||
// effects" commands. A regression in any shared layer (an Effect.fail that
|
||||
// propagates out of a service constructor, a renamed env var, a broken DB
|
||||
// migration) will fail one or more of these tests.
|
||||
//
|
||||
// If a future change should make one of these commands intentionally fail in
|
||||
// an empty env, update the assertion + add a note explaining the new contract.
|
||||
//
|
||||
// Speed: each test pays ~1.5s for bun startup. 7 tests serialize within this
|
||||
// file. See script/prebuild-test-cli.ts for an opt-in pre-built binary that
|
||||
// cuts per-spawn cost when this suite gets bigger.
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { cliIt } from "../../lib/cli-process"
|
||||
|
||||
describe("opencode read-only commands (smoke)", () => {
|
||||
// `mcp list` reads MCP server config and pings each one. With the empty
|
||||
// OPENCODE_CONFIG_CONTENT={} we provide, no servers should be configured
|
||||
// and the command should report that cleanly.
|
||||
cliIt.live(
|
||||
"mcp list: exits 0",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["mcp", "list"])
|
||||
opencode.expectExit(r, 0, "mcp list")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// `providers list` enumerates credentials + env-resolved providers.
|
||||
// (Not config-injected ones — those don't appear here by design.) The
|
||||
// Credentials header always renders; the Environment header only renders
|
||||
// when at least one provider env var is set, which the isolation harness
|
||||
// deliberately doesn't guarantee. Assert the always-present marker so the
|
||||
// test passes on a clean CI runner without env-var leakage.
|
||||
cliIt.live(
|
||||
"providers list: exits 0 and prints the credentials section",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["providers", "list"])
|
||||
opencode.expectExit(r, 0, "providers list")
|
||||
expect(r.stdout).toContain("Credentials")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// `models` lists models from configured providers. Our test/test-model
|
||||
// should appear because it's wired into the test provider config.
|
||||
cliIt.live(
|
||||
"models: exits 0 and lists the test model",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["models"])
|
||||
opencode.expectExit(r, 0, "models")
|
||||
expect(r.stdout).toContain("test/test-model")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// `agent list` walks the agent config. Empty config means no agents
|
||||
// configured; the command should still exit 0 with a "no agents" line or
|
||||
// similar. We don't pin the message — just exit cleanly.
|
||||
cliIt.live(
|
||||
"agent list: exits 0",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["agent", "list"])
|
||||
opencode.expectExit(r, 0, "agent list")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// `session list` reads the session DB. Fresh OPENCODE_TEST_HOME means
|
||||
// empty DB. Exit 0 with no sessions.
|
||||
cliIt.live(
|
||||
"session list: exits 0",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["session", "list"])
|
||||
opencode.expectExit(r, 0, "session list")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// `stats` aggregates token usage from the session DB. Empty DB → all zeros.
|
||||
cliIt.live(
|
||||
"stats: exits 0",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["stats"])
|
||||
opencode.expectExit(r, 0, "stats")
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
|
||||
// `db path` prints the DB file location. Under harness isolation the DB
|
||||
// resolves to SQLite's `:memory:` (no on-disk pollution between tests);
|
||||
// in production it'd be a path under OPENCODE_TEST_HOME / XDG_DATA_HOME.
|
||||
// Accept either form — both prove the resolver ran without crashing.
|
||||
cliIt.live(
|
||||
"db path: exits 0 and prints a path or :memory:",
|
||||
({ opencode }) =>
|
||||
Effect.gen(function* () {
|
||||
const r = yield* opencode.spawn(["db", "path"])
|
||||
opencode.expectExit(r, 0, "db path")
|
||||
expect(r.stdout.trim()).toMatch(/^(:memory:|[/\\].+\.(db|sqlite|sqlite3))$/i)
|
||||
}),
|
||||
60_000,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
|
||||
import { testRender, useRenderer } from "@opentui/solid"
|
||||
import { expect, test } from "bun:test"
|
||||
import { onCleanup } from "solid-js"
|
||||
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
|
||||
import { OpencodeKeymapProvider, registerOpencodeKeymap } from "@/cli/cmd/tui/keymap"
|
||||
|
||||
test("legacy page key aliases compile as page keys", async () => {
|
||||
const sequences: Record<string, string[][]> = {}
|
||||
|
||||
function Harness() {
|
||||
const renderer = useRenderer()
|
||||
const keymap = createDefaultOpenTuiKeymap(renderer)
|
||||
const config = createTuiResolvedConfig({
|
||||
keybinds: {
|
||||
messages_page_up: "pgup",
|
||||
messages_page_down: "pgdown",
|
||||
},
|
||||
})
|
||||
const offKeymap = registerOpencodeKeymap(keymap, renderer, config)
|
||||
const offLayer = keymap.registerLayer({
|
||||
bindings: config.keybinds.gather("session", ["session.page.up", "session.page.down"]),
|
||||
})
|
||||
const bindings = keymap.getCommandBindings({
|
||||
visibility: "registered",
|
||||
commands: ["session.page.up", "session.page.down"],
|
||||
})
|
||||
sequences.up =
|
||||
bindings.get("session.page.up")?.map((binding) => binding.sequence.map((part) => part.stroke.name)) ?? []
|
||||
sequences.down =
|
||||
bindings.get("session.page.down")?.map((binding) => binding.sequence.map((part) => part.stroke.name)) ?? []
|
||||
onCleanup(() => {
|
||||
offLayer()
|
||||
offKeymap()
|
||||
})
|
||||
|
||||
return (
|
||||
<OpencodeKeymapProvider keymap={keymap}>
|
||||
<box />
|
||||
</OpencodeKeymapProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const app = await testRender(() => <Harness />)
|
||||
try {
|
||||
expect(sequences).toEqual({
|
||||
up: [["pageup"]],
|
||||
down: [["pagedown"]],
|
||||
})
|
||||
} finally {
|
||||
app.renderer.destroy()
|
||||
}
|
||||
})
|
||||
@@ -91,6 +91,70 @@ test("toggles plugin runtime state by exported id", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("deactivating plugin pops pushed mode", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "mode-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.mode",
|
||||
tui: async (api) => {
|
||||
api.mode.push("demo.mode")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec }
|
||||
},
|
||||
})
|
||||
|
||||
const stack: { id: symbol; mode: string }[] = []
|
||||
let popCount = 0
|
||||
const api = createTuiPluginApi({
|
||||
mode: {
|
||||
current: () => stack.at(-1)?.mode ?? "base",
|
||||
push(mode) {
|
||||
const id = Symbol(mode)
|
||||
let active = true
|
||||
stack.push({ id, mode })
|
||||
return () => {
|
||||
if (!active) return
|
||||
active = false
|
||||
popCount += 1
|
||||
const index = stack.findIndex((item) => item.id === id)
|
||||
if (index !== -1) stack.splice(index, 1)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
const config = createTuiResolvedConfig({
|
||||
plugin: [tmp.extra.spec],
|
||||
plugin_origins: [{ spec: tmp.extra.spec, scope: "local", source: path.join(tmp.path, "tui.json") }],
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init({ api, config })
|
||||
|
||||
expect(api.mode.current()).toBe("demo.mode")
|
||||
expect(popCount).toBe(0)
|
||||
|
||||
await expect(TuiPluginRuntime.deactivatePlugin("demo.mode")).resolves.toBe(true)
|
||||
|
||||
expect(api.mode.current()).toBe("base")
|
||||
expect(popCount).toBe(1)
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
wait.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("kv plugin_enabled overrides tui config on startup", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -89,6 +89,7 @@ type Opts = {
|
||||
renderer?: HostPluginApi["renderer"]
|
||||
attention?: AttentionOpts
|
||||
event?: HostPluginApi["event"]
|
||||
mode?: HostPluginApi["mode"]
|
||||
count?: Count
|
||||
keymap?: HostPluginApi["keymap"]
|
||||
tuiConfig?: Partial<HostPluginApi["tuiConfig"]>
|
||||
@@ -237,6 +238,10 @@ export function createTuiPluginApi(opts: Opts = {}): HostPluginApi {
|
||||
},
|
||||
},
|
||||
keymap,
|
||||
mode: opts.mode ?? {
|
||||
current: () => "base",
|
||||
push: () => () => {},
|
||||
},
|
||||
route: {
|
||||
register: () => {
|
||||
if (count) count.route_add += 1
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"version": 1,
|
||||
"metadata": {
|
||||
"name": "session/native-anthropic-tool-loop",
|
||||
"recordedAt": "2026-05-19T01:40:12.788Z",
|
||||
"provider": "anthropic",
|
||||
"protocol": "anthropic-messages",
|
||||
"route": "anthropic-messages",
|
||||
"tags": ["opencode", "native", "tool-loop"]
|
||||
},
|
||||
"interactions": [
|
||||
{
|
||||
"transport": "http",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.anthropic.com/v1/messages",
|
||||
"headers": {
|
||||
"content-type": "application/json"
|
||||
},
|
||||
"body": "{\"model\":\"claude-haiku-4-5-20251001\",\"system\":[{\"type\":\"text\",\"text\":\"Answer using tools when appropriate.\\nUse the get_weather tool exactly once to look up Paris, then reply with exactly: Paris is sunny.\",\"cache_control\":{\"type\":\"ephemeral\"}}],\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"What is the weather in Paris?\",\"cache_control\":{\"type\":\"ephemeral\"}}]}],\"tools\":[{\"name\":\"get_weather\",\"description\":\"Get the current weather for a city.\",\"input_schema\":{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"cache_control\":{\"type\":\"ephemeral\"}}],\"stream\":true,\"max_tokens\":32000,\"temperature\":0}"
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "text/event-stream; charset=utf-8"
|
||||
},
|
||||
"body": "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"model\":\"claude-haiku-4-5-20251001\",\"id\":\"msg_01KSRzhxWxF38x5yYVYvktbc\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"stop_reason\":null,\"stop_sequence\":null,\"stop_details\":null,\"usage\":{\"input_tokens\":622,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"cache_creation\":{\"ephemeral_5m_input_tokens\":0,\"ephemeral_1h_input_tokens\":0},\"output_tokens\":54,\"service_tier\":\"standard\",\"inference_geo\":\"not_available\"}} }\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_01A8pEqifk2HVQfq1ZDNP6iY\",\"name\":\"get_weather\",\"input\":{},\"caller\":{\"type\":\"direct\"}} }\n\nevent: ping\ndata: {\"type\": \"ping\"}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"\"} }\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"city\\\": \\\"P\"} }\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"aris\\\"}\"} }\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0 }\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",\"stop_sequence\":null,\"stop_details\":null},\"usage\":{\"input_tokens\":622,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":54} }\n\nevent: message_stop\ndata: {\"type\":\"message_stop\" }\n\n"
|
||||
}
|
||||
},
|
||||
{
|
||||
"transport": "http",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.anthropic.com/v1/messages",
|
||||
"headers": {
|
||||
"content-type": "application/json"
|
||||
},
|
||||
"body": "{\"model\":\"claude-haiku-4-5-20251001\",\"system\":[{\"type\":\"text\",\"text\":\"Answer using tools when appropriate.\\nUse the get_weather tool exactly once to look up Paris, then reply with exactly: Paris is sunny.\",\"cache_control\":{\"type\":\"ephemeral\"}}],\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"What is the weather in Paris?\",\"cache_control\":{\"type\":\"ephemeral\"}}]},{\"role\":\"assistant\",\"content\":[{\"type\":\"tool_use\",\"id\":\"toolu_01A8pEqifk2HVQfq1ZDNP6iY\",\"name\":\"get_weather\",\"input\":{\"city\":{}}}]},{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":\"toolu_01A8pEqifk2HVQfq1ZDNP6iY\",\"content\":\"{\\\"temperature\\\":22,\\\"condition\\\":\\\"sunny\\\"}\"}]}],\"tools\":[{\"name\":\"get_weather\",\"description\":\"Get the current weather for a city.\",\"input_schema\":{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"],\"additionalProperties\":false},\"cache_control\":{\"type\":\"ephemeral\"}}],\"stream\":true,\"max_tokens\":32000,\"temperature\":0}"
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "text/event-stream; charset=utf-8"
|
||||
},
|
||||
"body": "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"model\":\"claude-haiku-4-5-20251001\",\"id\":\"msg_01UyghbuSVecMVozDny14vCD\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"stop_reason\":null,\"stop_sequence\":null,\"stop_details\":null,\"usage\":{\"input_tokens\":697,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"cache_creation\":{\"ephemeral_5m_input_tokens\":0,\"ephemeral_1h_input_tokens\":0},\"output_tokens\":1,\"service_tier\":\"standard\",\"inference_geo\":\"not_available\"}} }\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"} }\n\nevent: ping\ndata: {\"type\": \"ping\"}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Paris\"} }\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\" is sunny.\"} }\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0 }\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null,\"stop_details\":null},\"usage\":{\"input_tokens\":697,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":7} }\n\nevent: message_stop\ndata: {\"type\":\"message_stop\" }\n\n"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
-31
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -18,12 +18,12 @@
|
||||
// without changing the fixture. Long-lived commands like `serve` will need a
|
||||
// different return shape — see the TODO at the bottom of OpencodeCli.
|
||||
import type { TestOptions } from "bun:test"
|
||||
import * as Scope from "effect/Scope"
|
||||
import { Effect } from "effect"
|
||||
import { AppFileSystem } from "@opencode-ai/core/filesystem"
|
||||
import { AppProcess } from "@opencode-ai/core/process"
|
||||
import { Deferred, Duration, Effect, Layer, Queue, Scope, Stream } from "effect"
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http"
|
||||
import { ChildProcess } from "effect/unstable/process"
|
||||
import path from "node:path"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import { Process } from "@/util/process"
|
||||
import { TestLLMServer } from "./llm-server"
|
||||
import { testProviderConfig } from "./test-provider"
|
||||
import { it } from "./effect"
|
||||
@@ -33,6 +33,20 @@ const cliEntry = path.join(opencodeRoot, "src/index.ts")
|
||||
|
||||
export const testModelID = "test/test-model"
|
||||
|
||||
// Long-lived processes (serve, acp) all want the same stderr drain: read every
|
||||
// chunk, push to a tail buffer, swallow stream errors (the child closing the
|
||||
// pipe is normal). `log: true` surfaces a real protocol error to logs so a
|
||||
// regression doesn't silently disappear.
|
||||
function forkStderrDrain(stream: Stream.Stream<Uint8Array, unknown>, into: string[]) {
|
||||
return Effect.forkScoped(
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runForEach((chunk) => Effect.sync(() => into.push(chunk))),
|
||||
Effect.ignore({ log: true }),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function isolatedEnv(home: string, configJson: string): Record<string, string> {
|
||||
return {
|
||||
OPENCODE_TEST_HOME: home,
|
||||
@@ -71,9 +85,68 @@ export type RunOpts = SpawnOpts & {
|
||||
readonly extraArgs?: string[]
|
||||
}
|
||||
|
||||
// `opencode serve` is a long-lived process — it never exits on its own.
|
||||
// `serve(opts)` therefore returns a handle inside the caller's Scope: the
|
||||
// subprocess is killed when the scope closes (test end), and the URL the
|
||||
// server actually bound to (port 0 means OS-assigned) is parsed off stdout.
|
||||
export type ServeOpts = SpawnOpts & {
|
||||
readonly port?: number
|
||||
readonly hostname?: string
|
||||
readonly extraArgs?: string[]
|
||||
// How long to wait for the "listening on http://..." line before failing.
|
||||
// Default 15s — startup is dominated by bun's transpile + plugin init, not
|
||||
// the actual listen() call.
|
||||
readonly readyTimeoutMs?: number
|
||||
}
|
||||
|
||||
export type ServeHandle = {
|
||||
// Full URL the server is bound to, e.g. "http://127.0.0.1:54321". Use this
|
||||
// as the base for HTTP requests in tests — never assume the port.
|
||||
readonly url: string
|
||||
readonly hostname: string
|
||||
readonly port: number
|
||||
// Sends SIGTERM. The scope finalizer also calls this, so tests rarely need
|
||||
// to invoke it directly — useful for tests that assert exit behavior.
|
||||
readonly kill: Effect.Effect<void>
|
||||
// Resolves with the exit code once the process exits. Signal-killed
|
||||
// processes surface as -1 (vs cross-spawn-spawner raising a PlatformError).
|
||||
readonly exited: Effect.Effect<number>
|
||||
}
|
||||
|
||||
// `opencode acp` speaks newline-delimited JSON-RPC over stdin/stdout. It is
|
||||
// long-lived and exits cleanly when stdin is closed. The handle exposes the
|
||||
// duplex stream as send/receive rather than raw pipes so tests don't have to
|
||||
// reimplement framing on every call site.
|
||||
export type AcpOpts = SpawnOpts & {
|
||||
readonly cwd?: string
|
||||
readonly extraArgs?: string[]
|
||||
}
|
||||
|
||||
export type AcpHandle = {
|
||||
// Writes a single JSON-RPC message to the child's stdin as one ndjson line.
|
||||
readonly send: (msg: object) => Effect.Effect<void>
|
||||
// Resolves with the next parsed JSON-RPC line from the child's stdout.
|
||||
// Lines are buffered in a queue so multiple receives in a row won't drop
|
||||
// anything. Pair with `Effect.timeout` if a test wants a deadline.
|
||||
readonly receive: Effect.Effect<unknown>
|
||||
// Closes stdin. ACP exits cleanly on stdin EOF; the scope finalizer also
|
||||
// calls this, so tests only need it when asserting exit behavior.
|
||||
readonly close: Effect.Effect<void>
|
||||
// Resolves with the exit code once the process exits. Signal-killed
|
||||
// processes surface as -1 (see ServeHandle.exited for the same convention).
|
||||
readonly exited: Effect.Effect<number>
|
||||
}
|
||||
|
||||
export type OpencodeCli = {
|
||||
// High-level: run a single prompt against the test model. Short-lived.
|
||||
readonly run: (message: string, opts?: RunOpts) => Effect.Effect<RunResult>
|
||||
// Spawn `opencode serve` and wait until it's listening. Long-lived: the
|
||||
// returned handle is killed when the caller's Scope closes. Fails if the
|
||||
// listening line doesn't appear within `readyTimeoutMs`.
|
||||
readonly serve: (opts?: ServeOpts) => Effect.Effect<ServeHandle, Error, Scope.Scope>
|
||||
// Spawn `opencode acp` and return a duplex JSON-RPC handle. Long-lived:
|
||||
// the subprocess exits on stdin close, which the scope finalizer triggers.
|
||||
readonly acp: (opts?: AcpOpts) => Effect.Effect<AcpHandle, Error, Scope.Scope>
|
||||
// Escape hatch: any CLI invocation with full control over argv. Used to test
|
||||
// commands that don't yet have a typed builder.
|
||||
readonly spawn: (args: string[], opts?: SpawnOpts) => Effect.Effect<RunResult>
|
||||
@@ -85,9 +158,6 @@ export type OpencodeCli = {
|
||||
// event (see src/cli/cmd/run.ts `emit`). Throws on a malformed line so
|
||||
// tests fail loudly rather than silently skipping data.
|
||||
readonly parseJsonEvents: (stdout: string) => Array<Record<string, unknown>>
|
||||
// TODO: long-lived builders for `serve` / `acp` / etc. need a different
|
||||
// return shape — they yield a handle with .url / .kill and live inside the
|
||||
// surrounding Scope. Add when the first long-lived command is tested.
|
||||
}
|
||||
|
||||
export type CliFixture = {
|
||||
@@ -101,37 +171,63 @@ export type CliFixture = {
|
||||
// the caller doesn't need to wire it up — the fixture's lifetime is tied to
|
||||
// the surrounding Scope.
|
||||
export function withCliFixture<A, E>(
|
||||
fn: (input: CliFixture) => Effect.Effect<A, E>,
|
||||
fn: (input: CliFixture) => Effect.Effect<A, E, Scope.Scope | HttpClient.HttpClient>,
|
||||
): Effect.Effect<A, E | unknown, Scope.Scope> {
|
||||
return Effect.gen(function* () {
|
||||
const llm = yield* TestLLMServer
|
||||
const fs = yield* AppFileSystem.Service
|
||||
const appProc = yield* AppProcess.Service
|
||||
|
||||
const home = path.join(os.tmpdir(), "oc-cli-" + Math.random().toString(36).slice(2))
|
||||
yield* Effect.promise(() => fs.mkdir(home, { recursive: true }))
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.promise(() => fs.rm(home, { recursive: true, force: true }).catch(() => undefined)),
|
||||
)
|
||||
// FileSystem.makeTempDirectoryScoped handles both creation and scope-tied
|
||||
// cleanup — replaces the old mkdir + addFinalizer pair.
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "oc-cli-" })
|
||||
|
||||
const configJson = JSON.stringify(testProviderConfig(llm.url))
|
||||
const env = isolatedEnv(home, configJson)
|
||||
|
||||
const spawn = (args: string[], opts?: SpawnOpts): Effect.Effect<RunResult> =>
|
||||
Effect.promise(async () => {
|
||||
const start = Date.now()
|
||||
// Process.run pipes stdout/stderr by default and returns them as Buffers.
|
||||
const result = await Process.run(["bun", "run", "--conditions=browser", cliEntry, ...args], {
|
||||
cwd: home,
|
||||
timeout: opts?.timeoutMs ?? 30_000,
|
||||
env: { ...process.env, ...env, ...opts?.env },
|
||||
nothrow: true,
|
||||
})
|
||||
return {
|
||||
exitCode: result.code,
|
||||
stdout: result.stdout.toString(),
|
||||
stderr: result.stderr.toString(),
|
||||
durationMs: Date.now() - start,
|
||||
}
|
||||
const spawn = Effect.fn("opencode.spawn")(function* (args: string[], opts?: SpawnOpts) {
|
||||
const start = Date.now()
|
||||
const timeoutMs = opts?.timeoutMs ?? 30_000
|
||||
// stdin: "ignore" so the child doesn't see a piped stdin and block
|
||||
// on `Bun.stdin.text()` (see src/cli/cmd/run.ts — non-TTY stdin is
|
||||
// consumed as the prompt). The old Process.run wrapper defaulted to
|
||||
// ignore; ChildProcess.make defaults to pipe, so we set it explicitly.
|
||||
const command = ChildProcess.make("bun", ["run", "--conditions=browser", cliEntry, ...args], {
|
||||
cwd: home,
|
||||
env: { ...env, ...opts?.env },
|
||||
extendEnv: true,
|
||||
stdin: "ignore",
|
||||
})
|
||||
// Pass timeout to appProc.run rather than wrapping with
|
||||
// Effect.timeoutOrElse externally: AppProcess.run is itself scoped, so
|
||||
// its built-in timeout triggers the acquireRelease kill finalizer
|
||||
// inside cross-spawn-spawner *before* surfacing the AppProcessError —
|
||||
// guaranteeing the child is dead by the time the test continues.
|
||||
// External timeoutOrElse interrupts the run fiber but races the
|
||||
// scope close, which can leak the child past the test boundary.
|
||||
//
|
||||
// Catch AppProcessError (timeout OR spawn failure) and synthesize a
|
||||
// non-zero result so the test sees it via the usual `expectExit`
|
||||
// path rather than as an unhandled Effect failure.
|
||||
const result = yield* appProc.run(command, { timeout: Duration.millis(timeoutMs) }).pipe(
|
||||
Effect.catchTag("AppProcessError", (err) =>
|
||||
Effect.succeed({
|
||||
command: err.command,
|
||||
exitCode: err.exitCode ?? -1,
|
||||
stdout: Buffer.alloc(0),
|
||||
stderr: Buffer.from((err.stderr ?? String(err.cause ?? err.message)) + "\n"),
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} satisfies AppProcess.RunResult),
|
||||
),
|
||||
)
|
||||
return {
|
||||
exitCode: result.exitCode,
|
||||
stdout: result.stdout.toString(),
|
||||
stderr: result.stderr.toString(),
|
||||
durationMs: Date.now() - start,
|
||||
}
|
||||
})
|
||||
|
||||
const run = (message: string, opts?: RunOpts): Effect.Effect<RunResult> => {
|
||||
const argv: string[] = ["run"]
|
||||
@@ -145,10 +241,154 @@ export function withCliFixture<A, E>(
|
||||
return spawn(argv, opts)
|
||||
}
|
||||
|
||||
const opencode: OpencodeCli = { run, spawn, expectExit, parseJsonEvents }
|
||||
const serve = Effect.fn("opencode.serve")(function* (opts?: ServeOpts) {
|
||||
const argv = ["serve"]
|
||||
// Default port 0 — let the OS pick a free port, parse the actual one
|
||||
// off stdout. Hard-coded ports flake under parallel tests.
|
||||
argv.push("--port", String(opts?.port ?? 0))
|
||||
if (opts?.hostname) argv.push("--hostname", opts.hostname)
|
||||
if (opts?.extraArgs) argv.push(...opts.extraArgs)
|
||||
|
||||
// ChildProcessSpawner.spawn returns a scoped handle whose acquireRelease
|
||||
// finalizer sends SIGTERM and awaits exit on scope close — same lifecycle
|
||||
// the old Bun.spawn + manual acquireRelease wrapper gave us, no plumbing.
|
||||
const handle = yield* appProc.spawn(
|
||||
ChildProcess.make("bun", ["run", "--conditions=browser", cliEntry, ...argv], {
|
||||
cwd: home,
|
||||
env: { ...env, ...opts?.env },
|
||||
extendEnv: true,
|
||||
stdin: "ignore",
|
||||
}),
|
||||
)
|
||||
|
||||
// Tail buffer so timeout failures can include stderr context. The fork
|
||||
// also keeps the OS pipe buffer from filling and wedging the child.
|
||||
const stderrChunks: string[] = []
|
||||
yield* forkStderrDrain(handle.stderr, stderrChunks)
|
||||
|
||||
// Watch stdout line-by-line for the listening sentinel. Format
|
||||
// (see src/cli/cmd/serve.ts):
|
||||
// "opencode server listening on http://<host>:<port>"
|
||||
const readyRe = /listening on (http:\/\/([^\s:]+):(\d+))/
|
||||
const readyDeferred = yield* Deferred.make<{ url: string; hostname: string; port: number }>()
|
||||
yield* Effect.forkScoped(
|
||||
handle.stdout.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.splitLines,
|
||||
Stream.runForEach((line) => {
|
||||
const m = line.match(readyRe)
|
||||
return m ? Deferred.succeed(readyDeferred, { url: m[1], hostname: m[2], port: Number(m[3]) }) : Effect.void
|
||||
}),
|
||||
Effect.ignore({ log: true }),
|
||||
),
|
||||
)
|
||||
|
||||
const readyTimeoutMs = opts?.readyTimeoutMs ?? 15_000
|
||||
const match = yield* Deferred.await(readyDeferred).pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration: Duration.millis(readyTimeoutMs),
|
||||
orElse: () =>
|
||||
Effect.fail(
|
||||
new Error(
|
||||
`opencode serve did not become ready within ${readyTimeoutMs}ms\n` +
|
||||
`stderr (last 2000):\n${stderrChunks.join("").slice(-2000)}`,
|
||||
),
|
||||
),
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
url: match.url,
|
||||
hostname: match.hostname,
|
||||
port: match.port,
|
||||
kill: handle.kill().pipe(Effect.ignore),
|
||||
// handle.exitCode fails with PlatformError if the process was killed
|
||||
// by signal (the normal scope-close path). Swallow → -1 so the test
|
||||
// can still distinguish exited-vs-not without crashing.
|
||||
exited: handle.exitCode.pipe(
|
||||
Effect.orElseSucceed(() => -1),
|
||||
Effect.map((c) => Number(c)),
|
||||
),
|
||||
} satisfies ServeHandle
|
||||
})
|
||||
|
||||
const acp = Effect.fn("opencode.acp")(function* (opts?: AcpOpts) {
|
||||
const argv = ["acp"]
|
||||
if (opts?.cwd) argv.push("--cwd", opts.cwd)
|
||||
if (opts?.extraArgs) argv.push(...opts.extraArgs)
|
||||
|
||||
// stdin is fed by a Queue<Uint8Array>: send() offers bytes, close()
|
||||
// shuts the queue down. The spawner drains the Queue-backed Stream into
|
||||
// the child's stdin Sink (endOnDone: true by default), so a queue
|
||||
// shutdown propagates as stdin EOF → ACP exits gracefully. Scope-close
|
||||
// is the backstop via the spawner's kill finalizer.
|
||||
const stdinQueue = yield* Queue.unbounded<Uint8Array>()
|
||||
const handle = yield* appProc.spawn(
|
||||
ChildProcess.make("bun", ["run", "--conditions=browser", cliEntry, ...argv], {
|
||||
cwd: opts?.cwd ?? home,
|
||||
env: { ...env, ...opts?.env },
|
||||
extendEnv: true,
|
||||
stdin: Stream.fromQueue(stdinQueue),
|
||||
}),
|
||||
)
|
||||
|
||||
const stderrChunks: string[] = []
|
||||
yield* forkStderrDrain(handle.stderr, stderrChunks)
|
||||
|
||||
// Each ndjson line becomes one queue entry. JSON.parse failures are
|
||||
// surfaced as the raw string so a malformed protocol message doesn't
|
||||
// silently wedge the test in `receive`.
|
||||
const responses = yield* Queue.unbounded<unknown>()
|
||||
yield* Effect.forkScoped(
|
||||
handle.stdout.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.splitLines,
|
||||
Stream.runForEach((line) => {
|
||||
if (line.length === 0) return Effect.void
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(line)
|
||||
} catch {
|
||||
parsed = { _rawLine: line }
|
||||
}
|
||||
return Queue.offer(responses, parsed)
|
||||
}),
|
||||
Effect.ignore({ log: true }),
|
||||
),
|
||||
)
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
return {
|
||||
send: (msg: object) =>
|
||||
Queue.offer(stdinQueue, encoder.encode(JSON.stringify(msg) + "\n")).pipe(Effect.asVoid),
|
||||
receive: Queue.take(responses),
|
||||
// Queue shutdown → Stream.fromQueue completes → spawner ends stdin.
|
||||
// Idempotent: shutting down an already-shut-down queue is a no-op.
|
||||
close: Queue.shutdown(stdinQueue).pipe(Effect.asVoid),
|
||||
// handle.exitCode fails with PlatformError on signal-kill; collapse
|
||||
// to -1 to match the ServeHandle.exited convention.
|
||||
exited: handle.exitCode.pipe(
|
||||
Effect.orElseSucceed(() => -1),
|
||||
Effect.map((c) => Number(c)),
|
||||
),
|
||||
} satisfies AcpHandle
|
||||
})
|
||||
|
||||
const opencode: OpencodeCli = { run, serve, acp, spawn, expectExit, parseJsonEvents }
|
||||
|
||||
return yield* fn({ llm, home, opencode })
|
||||
}).pipe(Effect.provide(TestLLMServer.layer))
|
||||
// FetchHttpClient is provided so test bodies can `yield* HttpClient.HttpClient`
|
||||
// and hit endpoints on `opencode.serve()` without rolling their own fetch.
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
TestLLMServer.layer,
|
||||
FetchHttpClient.layer,
|
||||
AppFileSystem.defaultLayer,
|
||||
AppProcess.defaultLayer,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function parseJsonEvents(stdout: string): Array<Record<string, unknown>> {
|
||||
@@ -180,7 +420,13 @@ function expectExit(result: RunResult, expected: number, label = "opencode") {
|
||||
// Only `.live` is exposed because subprocess tests must run against the real
|
||||
// clock — a TestClock-paused environment can't drive a child process. If you
|
||||
// need `.only` or `.skip`, fall back to `it.live` + `withCliFixture` directly.
|
||||
// Body's R is `Scope.Scope | never` so tests can yield* scope-requiring
|
||||
// resources (e.g. `opencode.serve`) without an extra `Effect.scoped` wrapper —
|
||||
// `withCliFixture`'s outer scope is the natural lifetime.
|
||||
export const cliIt = {
|
||||
live: <A, E>(name: string, body: (input: CliFixture) => Effect.Effect<A, E>, opts?: number | TestOptions) =>
|
||||
it.live(name, () => withCliFixture(body), opts),
|
||||
live: <A, E>(
|
||||
name: string,
|
||||
body: (input: CliFixture) => Effect.Effect<A, E, Scope.Scope | HttpClient.HttpClient>,
|
||||
opts?: number | TestOptions,
|
||||
) => it.live(name, () => withCliFixture(body), opts),
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user