2 Commits
107 changed files with 16229 additions and 7165 deletions
+49 -48
View File
@@ -9,20 +9,20 @@
"ru", "ru",
"zh" "zh"
], ],
"quick_code": "git clone https://github.com/zarubinvibe/iriz.git ~/iriz\ncd ~/iriz\nbash install.sh # просто терминал, без единого агента\ncode . # или откройте папку в редакторе\nclaude # или пустите агента: он проведет установку разговором\n", "quick_code": "git clone https://github.com/zarubinvibe/iriz.git ~/iriz\ncd ~/iriz\nbash install.sh # просто терминал, без единого агента\ncode . # или открой папку в редакторе\nclaude # или пусти агента: он проведет установку разговором\n",
"text": { "text": {
"en": { "en": {
"title": "iriz", "title": "iriz",
"name": "iriz", "name": "iriz",
"tagline": "Speak out loud and the text appears. Your Mac does the decoding, and nothing travels to somebody else's cloud.", "tagline": "Speak out loud and the text appears. Your Mac does the decoding, and nothing travels to somebody else's cloud.\n\n[![Download for macOS](https://img.shields.io/badge/Download%20for%20macOS-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)\n\nApple Silicon · macOS 14+ · Model download: about 500 MB\n\n[Install & first dictation](docs/DOWNLOAD.md) · [Release notes](https://github.com/zarubinvibe/iriz/releases/latest)\n\nSelf-signed; not notarized by Apple. Intel is not supported by this download.",
"hero_alt": "Iris in white marble with marble wings beside the classical column, a gold ribbon of voice landing in the groove of her tablet", "hero_alt": "Iris in white marble with marble wings beside the classical column, a gold ribbon of voice landing in the groove of her tablet",
"what": "This is a Mac app that types for you while you talk.\n\nHere is how it goes. You press one key, speak in your normal voice, press it again. The text lands where the cursor was: in an email, in a chat, in a search field. Nothing to switch to, no separate window.\n\nWhat sets it apart from similar apps is where the speech is decoded. Usually your voice travels to somebody's server, turns into text there and comes back. Here your Mac does the work, and the audio never leaves the machine.\n\n**Why «iriz».** Iris was the messenger of the Greek gods and the rainbow — a bridge between the sky and the ground. She does not invent the message, she carries it whole. The app does exactly that: it takes what you said and moves it into text, adding nothing of its own.\n\n![The menu bar: status, modes, dictation, meetings, history](docs/assets/shots/menu-en.png)\n\nIt does more. It fixes a phrase typed in the wrong keyboard layout. Correct a word after pasting and the app offers to remember the replacement. It strips hesitations and repetitions. It splits a meeting or a court hearing recording by voice and puts the minutes next to the audio.\n\n![Meetings: drop the recording, the minutes land next to it](docs/assets/shots/page-meetings.png)", "what": "This is a Mac app that types for you while you talk.\n\nHere is how it goes. You press one key, speak in your normal voice, press it again. The text lands where the cursor was: in an email, in a chat, in a search field. Nothing to switch to, no separate window.\n\nWhat sets it apart from similar apps is where the speech is decoded. Usually your voice travels to somebody's server, turns into text there and comes back. Here your Mac does the work, and the audio never leaves the machine.\n\n**Why «iriz».** Iris was the messenger of the Greek gods and the rainbow — a bridge between the sky and the ground. She does not invent the message, she carries it whole. The app does exactly that: it takes what you said and moves it into text, adding nothing of its own.\n\n![The menu bar: status, modes, dictation, meetings, history](docs/assets/shots/menu-en.png)\n\nIt does more. It fixes a phrase typed in the wrong keyboard layout. Correct a word after pasting and the app offers to remember the replacement. It strips hesitations and repetitions. It splits a meeting or a court hearing recording by voice and puts the minutes next to the audio.\n\n![Meetings: drop the recording, the minutes land next to it](docs/assets/shots/page-meetings.png)\n\n![Iris at a marble table: the laptop screen carries the first screen of the iriz walkthrough](docs/assets/pantheon/desk-firstrun.png)\n",
"why": "Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.\n\nOne thing gets in the way. Cloud dictation cleans speech better than anything local, but what you said leaves the machine: a client call, a draft, names and figures. For a doctor, a lawyer, a therapist, that trade never pays off.\n\nSo here your Mac does the decoding, and the app reaches the network only when you press the button.", "why": "Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.\n\nOne thing gets in the way. Cloud dictation cleans speech better than anything local, but what you said leaves the machine: a client call, a draft, names and figures. For a doctor, a lawyer, a therapist, that trade never pays off.\n\nSo here your Mac does the decoding, and the app reaches the network only when you press the button.\n\n![A marble laptop up close: the iriz dictation history window on its screen](docs/assets/pantheon/desk-history.png)\n",
"advantage": "your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.", "advantage": "your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.",
"better": "The switch sits inside the recognition library and returns to its place even when a download fails. Documentation does not prove that: a script pins the set of networking symbols in the built binary and asks the kernel whether the running app holds a single socket.", "better": "The switch sits inside the recognition library and returns to its place even when a download fails. Documentation does not prove that: a script pins the set of networking symbols in the built binary and asks the kernel whether the running app holds a single socket.",
"how": "Press the key, say your sentence, press again. The text lands where the cursor was blinking.\n\nA glass drop sits at the bottom of the screen the whole time. While you are silent it stays small. Start talking and a wave runs inside it: that is the answer to «can it hear me».\n\n![The plate while recording: a wave inside the glass](docs/assets/shots/plate-listening-dark.png)\n\nPoint at it with the mouse and the drop opens into a row of buttons: record, prompt, translate, language, history, settings. The language switches right there, a second before you speak — no need to walk to the settings for it.\n\n![The plate under the pointer: a row of six buttons](docs/assets/shots/plate-hover-dark.png)\n\nIf pasting did not work, nothing is lost: the same plate opens into a panel and you take the text from there.\n\n![Dictation settings: where the speech gets cleaned](docs/assets/shots/page-dictation.png)", "how": "Press the key, say your sentence, press again. The text lands where the cursor was blinking.\n\nA glass drop sits at the bottom of the screen the whole time. While you are silent it stays small. Start talking and a wave runs inside it: that is the answer to «can it hear me».\n\n![The plate while recording: a wave inside the glass](docs/assets/shots/plate-listening-dark.png)\n\nPoint at it with the mouse and the drop opens into a row of buttons: record, prompt, translate, language, history, settings. The language switches right there, a second before you speak — no need to walk to the settings for it.\n\n![The plate under the pointer: a row of six buttons](docs/assets/shots/plate-hover-dark.png)\n\nIf pasting did not work, nothing is lost: the same plate opens into a panel and you take the text from there.\n\n![Dictation settings: where the speech gets cleaned](docs/assets/shots/page-dictation.png)",
"quick_intro": "You need a Mac on macOS 14 or newer. Building from source also wants Xcode with Swift 6. Three doors from here, any of them works.", "quick_intro": "Download the [macOS DMG](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg), open it, and drag iriz into Applications. This build needs Apple Silicon and macOS 14 or newer. No Xcode or Terminal is needed.\n\nOpen iriz and choose Download and install Parakeet in onboarding (about 500 MB). Grant the permissions in the following steps. Wait for readiness, focus a text field, and try your dictation key.\n\n[Installation, model recovery and updates](docs/DOWNLOAD.md). To build from source instead, install Xcode with Swift 6 and use one of the paths below.",
"quick_extra": "Do not want to build? Take the ready disk image from Releases: open it, drag the icon onto Applications. No Git? Download [the ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), unpack it, and run the same command inside. First time? Open the project in Claude Code and run `/iriz-setup`: the install goes as a conversation, one question at a time, and nothing is installed without your yes.", "quick_extra": "Without Git, download [the source ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), unpack it and run the same installer there. Or open the project in Claude Code and run `/iriz-setup` for a guided install. It asks before installing.",
"quick_result": "the installer says what this is, looks at what your machine is missing, runs the tree selfcheck, and names the next step. It installs nothing until you ask.", "quick_result": "the installer says what this is, looks at what your machine is missing, runs the tree selfcheck, and names the next step. It installs nothing until you ask.",
"compare": [ "compare": [
[ [
@@ -95,10 +95,11 @@
"safety_tail": "One thing goes out, and only on your button: the one-time speech model download. Prompt mode is off by default, and switching it on means agreeing that the transcript reaches the agent you picked.", "safety_tail": "One thing goes out, and only on your button: the one-time speech model download. Prompt mode is off by default, and switching it on means agreeing that the transcript reaches the agent you picked.",
"status": "Status: working. The author dictates with it every day.", "status": "Status: working. The author dictates with it every day.",
"limits": [ "limits": [
"macOS 14 and newer only. No Windows, no Linux, no iPad.", "This download supports Apple Silicon Macs on macOS 14 or newer. Intel is unverified; Windows, Linux and iPad are not supported.",
"Automatic layout switching covers the English and Russian pair.", "Automatic layout repair covers English and Russian. The interface has Russian, English and Simplified Chinese.",
"No notarization yet: a downloaded build opens through a right-click the first time.", "The app is self-signed and not notarized by Apple. Read the first-launch security warning in the download guide.",
"The universal binary carries an Intel slice, but the author owns no Intel Mac and never verified it there." "The default Parakeet model needs a separate download of about 500 MB and does not recognize Chinese. Other models have different language coverage.",
"Updates are manual: download the new DMG, quit iriz and replace the application. Models and local history remain outside the app bundle."
], ],
"docs": "Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOARDING.md), [how to help](CONTRIBUTING.md), [security](SECURITY.md).", "docs": "Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOARDING.md), [how to help](CONTRIBUTING.md), [security](SECURITY.md).",
"license": "MIT. See [LICENSE](LICENSE).", "license": "MIT. See [LICENSE](LICENSE).",
@@ -115,20 +116,20 @@
"ru": { "ru": {
"title": "iriz", "title": "iriz",
"name": "iriz", "name": "iriz",
"tagline": "Говорите вслух, на экране появляется текст. Разбирает речь сам Мак, ничего не улетает в чужое облако.", "tagline": "Говори вслух, на экране появляется текст. Разбирает речь сам Мак, ничего не улетает в чужое облако.\n\n[![Скачать для macOS](https://img.shields.io/badge/%D0%A1%D0%BA%D0%B0%D1%87%D0%B0%D1%82%D1%8C%20%D0%B4%D0%BB%D1%8F%20macOS-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)\n\nApple Silicon · macOS 14+ · Модель скачивается отдельно: около 500 МБ\n\n[Установка и первая диктовка](docs/DOWNLOAD.ru.md) · [Что изменилось](https://github.com/zarubinvibe/iriz/releases/latest)\n\nСамоподпись, без нотаризации Apple. Этот выпуск не поддерживает Intel.",
"hero_alt": "Ирида из белого мрамора с мраморными крыльями у классической колонны, золотая лента голоса ложится в борозду на табличке", "hero_alt": "Ирида из белого мрамора с мраморными крыльями у классической колонны, золотая лента голоса ложится в борозду на табличке",
"what": "Это программа для Мака, которая печатает за вас, пока вы говорите.\n\nРаботает так. Вы нажимаете одну клавишу, говорите обычным голосом, нажимаете еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет.\n\nГлавное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает ваш Мак, и звук с машины не уходит.\n\n**Почему «iriz».** Ирида у греков — вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Программа делает ровно это: берет сказанное и переносит в текст, ничего не добавляя от себя.\n\n![Меню в строке меню: состояние, режимы, диктовка, встречи, история](docs/assets/shots/menu-ru.png)\n\nУмеет и другое. Чинит фразу, набранную не в той раскладке. Поправите слово после вставки, и программа предложит запомнить замену. Уберет из речи запинки и повторы. Разберет запись встречи или судебного заседания по голосам, а рядом со звуком положит готовый протокол.\n\n![Встречи: перенесите запись, рядом ляжет протокол](docs/assets/shots/page-meetings.png)", "what": "Это программа для Мака, которая печатает за тебя, пока ты говоришь.\n\nРаботает так. Ты нажимаешь одну клавишу, говоришь обычным голосом, нажимаешь еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет.\n\nГлавное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает твой Мак, и звук с машины не уходит.\n\n**Почему «iriz».** Ирида у греков — вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Программа делает ровно это: берет сказанное и переносит в текст, ничего не добавляя от себя.\n\n![Меню в строке меню: состояние, режимы, диктовка, встречи, история](docs/assets/shots/menu-ru.png)\n\nУмеет и другое. Чинит фразу, набранную не в той раскладке. Поправишь слово после вставки, и программа предложит запомнить замену. Уберет из речи запинки и повторы. Разберет запись встречи или судебного заседания по голосам, а рядом со звуком положит готовый протокол.\n\n![Встречи: перенеси запись, рядом ляжет протокол](docs/assets/shots/page-meetings.png)\n\n![Ирида за мраморным столом: на экране ноутбука первый экран знакомства iriz](docs/assets/pantheon/desk-firstrun.png)\n",
"why": "Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.\n\nМешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает то, что вы сказали: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем.\n\nПоэтому тут разбирает Мак, а в сеть программа ходит только по вашей кнопке.", "why": "Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.\n\nМешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает сказанное: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем.\n\nПоэтому тут разбирает Мак, а в сеть программа ходит только по твоей кнопке.\n\n![Мраморный ноутбук крупно: на экране окно истории надиктовок iriz](docs/assets/pantheon/desk-history.png)\n",
"advantage": "речь разбирает ваш Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.", "advantage": "речь разбирает твой Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.",
"better": "Рубильник стоит внутри библиотеки распознавания и возвращается на место даже когда загрузка падает. Проверяет это не документация: скрипт пинует набор сетевых символов в собранном бинарнике и спрашивает у ядра, есть ли у работающего приложения хоть один сокет.", "better": "Рубильник стоит внутри библиотеки распознавания и возвращается на место даже когда загрузка падает. Проверяет это не документация: скрипт пинует набор сетевых символов в собранном бинарнике и спрашивает у ядра, есть ли у работающего приложения хоть один сокет.",
"how": "Нажали клавишу, сказали фразу, нажали еще раз. Текст встает туда, где мигал курсор.\n\nВнизу экрана все это время висит стеклянная капля. Пока вы молчите, она маленькая. Заговорили — внутри бежит волна: это и есть ответ на вопрос «слышит ли меня».\n\n![Плашка на записи: волна внутри стекла](docs/assets/shots/plate-listening-dark.png)\n\nНаведите на нее мышь — капля раскроется в ряд кнопок: запись, промпт, перевод, язык, история, настройки. Язык переключается здесь же, за секунду до того, как заговорить, и ходить за этим в настройки незачем.\n\n![Плашка под мышью: ряд из шести кнопок](docs/assets/shots/plate-hover-dark.png)\n\nЕсли вставить не удалось, ничего не потеряно: та же плашка раскроется в панель, и текст можно забрать оттуда.\n\n![Настройки диктовки: где чистится речь](docs/assets/shots/page-dictation.png)", "how": "Нажимаешь клавишу, говоришь фразу, нажимаешь еще раз. Текст встает туда, где мигал курсор.\n\nВнизу экрана все это время висит стеклянная капля. Пока ты молчишь, она маленькая. Заговоришь — внутри бежит волна: это и есть ответ на вопрос «слышит ли меня».\n\n![Плашка на записи: волна внутри стекла](docs/assets/shots/plate-listening-dark.png)\n\nНаведи на нее мышь — капля раскроется в ряд кнопок: запись, промпт, перевод, язык, история, настройки. Язык переключается здесь же, за секунду до того, как заговорить, и ходить за этим в настройки незачем.\n\n![Плашка под мышью: ряд из шести кнопок](docs/assets/shots/plate-hover-dark.png)\n\nЕсли вставить не удалось, ничего не потеряно: та же плашка раскроется в панель, и текст можно забрать оттуда.\n\n![Настройки диктовки: где чистится речь](docs/assets/shots/page-dictation.png)",
"quick_intro": "Нужен Мак на macOS 14 или новее. Для сборки из исходников еще Xcode со Swift 6. Дверей три, годится любая.", "quick_intro": "[Скачай DMG для macOS](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg), открой и перетащи iriz в Applications. Нужен Мак с Apple Silicon на macOS 14 или новее. Xcode и терминал не нужны.\n\nОткрой iriz и нажми «Скачать и установить Parakeet» в знакомстве. На следующих шагах выдай разрешения. Загрузка займет около 500 МБ. Дождись готовности, поставь курсор в текстовое поле и попробуй клавишу диктовки.\n\n[Установка, восстановление модели и обновления](docs/DOWNLOAD.ru.md). Для сборки из исходников нужен Xcode со Swift 6. Ниже команды и другие способы установки.",
"quick_extra": "Не хотите собирать - возьмите готовый образ в разделе Releases: открыли, перетащили значок в Applications. Нет Git? Скачайте [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуйте и запустите в нем ту же команду. Первый раз? Откройте проект в Claude Code и запустите `/iriz-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без вашего «да».", "quick_extra": "Нет Git? Скачай [ZIP с исходниками](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуй и запусти в нем тот же установщик. Или открой проект в Claude Code и запусти `/iriz-setup`: агент проведет установку по шагам и спросит перед изменениями.",
"quick_result": "установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока вы не попросите.", "quick_result": "установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока ты не попросишь.",
"compare": [ "compare": [
[ [
"**iriz**", "**iriz**",
"Диктуете рабочее и отдать не можете", "Диктуешь рабочее и отдать не можешь",
"Раскладка, местная диктовка, речь в задание", "Раскладка, местная диктовка, речь в задание",
"Никуда, разбирает Мак", "Никуда, разбирает Мак",
"Да, английский и русский", "Да, английский и русский",
@@ -169,7 +170,7 @@
[ [
"Местная диктовка на Whisper", "Местная диктовка на Whisper",
"Диктовать без облака", "Диктовать без облака",
"Тоже считает у вас", "Тоже считает у тебя",
"Никуда", "Никуда",
"Нет", "Нет",
"Раскладку не чинит, задание из речи не собирает" "Раскладку не чинит, задание из речи не собирает"
@@ -182,24 +183,25 @@
], ],
[ [
"Модель распознавания", "Модель распознавания",
"Файлы весов, по которым звук превращается в буквы. Живет у вас на диске, скачивается один раз" "Файлы весов, по которым звук превращается в буквы. Живет у тебя на диске, скачивается один раз"
] ]
], ],
"safety": [ "safety": [
"Звук нигде не сохраняется: он живет ровно столько, сколько нужно, чтобы разобрать сказанное.", "Звук нигде не сохраняется: он живет ровно столько, сколько нужно, чтобы разобрать сказанное.",
"Экран не читается. Ни ScreenCaptureKit, ни снимков окон.", "Экран не читается. Ни ScreenCaptureKit, ни снимков окон.",
"Чужие поля не читаются: доступ нужен, чтобы понять, можно ли в поле писать, а не чтобы забрать оттуда текст.", "Чужие поля не читаются: доступ нужен, чтобы понять, можно ли в поле писать, а не чтобы забрать оттуда текст.",
"Куда вы диктовали, не записывается. Иначе на диске копились бы метаданные о том, с кем и когда вы работаете.", "Место диктовки не записывается. Иначе на диске копились бы метаданные о том, с кем и когда ты работаешь.",
"Буфер обмена возвращается на место после вставки.", "Буфер обмена возвращается на место после вставки.",
"Расшифровки лежат под правами 0700 и 0600 и остаются на вашем диске." "Расшифровки лежат под правами 0700 и 0600 и остаются на твоем диске."
], ],
"safety_tail": "В сеть уходит одно и по вашей кнопке: разовая загрузка модели распознавания. Промпт-режим выключен по умолчанию, и включая его, вы соглашаетесь, что расшифровка уйдет выбранному агенту.", "safety_tail": "В сеть уходит одно и по твоей кнопке: разовая загрузка модели распознавания. Промпт-режим выключен по умолчанию, и включая его, ты соглашаешься, что расшифровка уйдет выбранному агенту.",
"status": "Статус: работает. Автор диктует им каждый день.", "status": "Статус: работает. Автор диктует им каждый день.",
"limits": [ "limits": [
"Только macOS 14 и новее. Ни Windows, ни Linux, ни iPad.", "Этот выпуск рассчитан на Apple Silicon и macOS 14 или новее. Intel не проверен; Windows, Linux и iPad не поддерживаются.",
"Автопереключение раскладки работает для пары английский и русский.", "Раскладка исправляется для пары английский и русский. Интерфейс доступен на русском, английском и китайском.",
"Нотаризации пока нет: первый запуск скачанной сборки открывается правым щелчком.", "У приложения самоподпись, нотаризации Apple нет. Предупреждение о первом запуске есть в инструкции скачивания.",
"Универсальный бинарник содержит срез под Intel, но живого Intel-Мака у автора нет, и проверено это не было." "Модель Parakeet скачивается отдельно, занимает около 500 МБ и не распознает китайскую речь. У других моделей свой набор языков.",
"Обновление ручное: скачай новый DMG, закрой iriz и замени приложение. Модели и история хранятся вне его пакета."
], ],
"docs": "Глубже: [пошаговое знакомство с кадрами каждой поверхности](docs/ONBOARDING.ru.md), [как помочь](CONTRIBUTING.ru.md), [безопасность](SECURITY.ru.md).", "docs": "Глубже: [пошаговое знакомство с кадрами каждой поверхности](docs/ONBOARDING.ru.md), [как помочь](CONTRIBUTING.ru.md), [безопасность](SECURITY.ru.md).",
"license": "MIT. Текст в файле [LICENSE](LICENSE).", "license": "MIT. Текст в файле [LICENSE](LICENSE).",
@@ -207,7 +209,7 @@
"compare_header": [ "compare_header": [
"Вариант", "Вариант",
"Когда подходит", "Когда подходит",
"Что получаете", "Что получаешь",
"Куда уходит речь", "Куда уходит речь",
"Чинит раскладку", "Чинит раскладку",
"Минус" "Минус"
@@ -216,15 +218,15 @@
"zh": { "zh": {
"title": "iriz", "title": "iriz",
"name": "iriz", "name": "iriz",
"tagline": "你说出来,屏幕上就有字。识别由你自己的 Mac 完成,声音不会上传到别人的云。", "tagline": "你说出来,屏幕上就有字。识别由你自己的 Mac 完成,声音不会上传到别人的云。\n\n[![下载 macOS 版](https://img.shields.io/badge/%E4%B8%8B%E8%BD%BD%20macOS%20%E7%89%88-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)\n\nApple Silicon · macOS 14+ · 语音模型需另行下载,约 500 MB\n\n[安装与首次听写](docs/DOWNLOAD.zh.md) · [更新说明](https://github.com/zarubinvibe/iriz/releases/latest)\n\n应用使用自签名,尚未通过 Apple 公证。此下载不支持 Intel。",
"hero_alt": "白色大理石的伊里斯长着大理石翅膀,站在古典石柱旁,金色的声音丝带落进石板上的凹槽里", "hero_alt": "白色大理石的伊里斯长着大理石翅膀,站在古典石柱旁,金色的声音丝带落进石板上的凹槽里",
"what": "这是一个 Mac 应用:你说话,它替你打字。\n\n用起来是这样。按一下键,用平常的声音说话,再按一下。文字会落在光标原来的位置:邮件里、聊天里、搜索框里。不用切换到别的地方,也没有单独的窗口。\n\n和同类应用最大的区别在于语音在哪里被解码。通常你的声音会被送到别人的服务器,在那里变成文字再回来。这里是你的 Mac 在计算,声音不会离开这台机器。\n\n**为什么叫「iriz」。** 伊里斯是希腊神话里众神的信使,也是彩虹——连接天与地的桥。她不编造消息,只把它完整地带到。这个应用做的正是这件事:把你说的话原样搬进文字,不添加自己的东西。\n\n![菜单栏:状态、模式、口述、会议、历史](docs/assets/shots/menu-zh.png)\n\n它还会别的。它能修好用错键盘布局打出来的句子。粘贴之后你改了一个词,它会问要不要记住这个替换。它会去掉话里的停顿和重复。它能把会议或庭审录音按说话人分开,并在音频旁边放上写好的纪要。\n\n![会议:把录音拖进来,纪要会放在旁边](docs/assets/shots/page-meetings.png)", "what": "这是一个 Mac 应用:你说话,它替你打字。\n\n用起来是这样。按一下键,用平常的声音说话,再按一下。文字会落在光标原来的位置:邮件里、聊天里、搜索框里。不用切换到别的地方,也没有单独的窗口。\n\n和同类应用最大的区别在于语音在哪里被解码。通常你的声音会被送到别人的服务器,在那里变成文字再回来。这里是你的 Mac 在计算,声音不会离开这台机器。\n\n**为什么叫「iriz」。** 伊里斯是希腊神话里众神的信使,也是彩虹——连接天与地的桥。她不编造消息,只把它完整地带到。这个应用做的正是这件事:把你说的话原样搬进文字,不添加自己的东西。\n\n![菜单栏:状态、模式、口述、会议、历史](docs/assets/shots/menu-zh.png)\n\n它还会别的。它能修好用错键盘布局打出来的句子。粘贴之后你改了一个词,它会问要不要记住这个替换。它会去掉话里的停顿和重复。它能把会议或庭审录音按说话人分开,并在音频旁边放上写好的纪要。\n\n![会议:把录音拖进来,纪要会放在旁边](docs/assets/shots/page-meetings.png)\n\n![伊里斯坐在大理石桌前,笔记本屏幕上是 iriz 引导的第一屏](docs/assets/pantheon/desk-firstrun.png)\n",
"why": "靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。\n\n只有一件事挡在前面。云端听写把口语整理得比任何本地方案都干净,可你说的内容也随之离开了这台机器:和客户的通话、文件草稿、人名和金额。对医生、律师、心理咨询师来说,这笔交换怎么算都不划算。\n\n所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。", "why": "靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。\n\n只有一件事挡在前面。云端听写把口语整理得比任何本地方案都干净,可你说的内容也随之离开了这台机器:和客户的通话、文件草稿、人名和金额。对医生、律师、心理咨询师来说,这笔交换怎么算都不划算。\n\n所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。\n\n![近处的大理石笔记本,屏幕上是 iriz 的口述记录窗口](docs/assets/pantheon/desk-history.png)\n",
"advantage": "识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。", "advantage": "识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。",
"better": "开关叫 `DownloadUtils.enforceOffline`,位置在识别库内部,连下载失败的时候也会自己归位。光有文档不算数:自检脚本盯住编译好的二进制里那一组网络符号,再去问系统,运行中的应用手上有没有一个套接字。", "better": "开关叫 `DownloadUtils.enforceOffline`,位置在识别库内部,连下载失败的时候也会自己归位。光有文档不算数:自检脚本盯住编译好的二进制里那一组网络符号,再去问系统,运行中的应用手上有没有一个套接字。",
"how": "按键,说一句话,再按一下。文字会落在光标闪烁的地方。\n\n这段时间里,屏幕下方一直有一颗玻璃水滴。你不说话时它很小。一开口,里面就有声波流动:这就是“它有没有听见我”的答案。\n\n![录音中的浮窗:玻璃里的声波](docs/assets/shots/plate-listening-dark.png)\n\n把鼠标移上去,水滴会展开成一排按钮:录音、提示词、翻译、语言、历史、设置。语言就在这里切换,开口前一秒就能换,不用专门去设置里找。\n\n![鼠标下的浮窗:一排六个按钮](docs/assets/shots/plate-hover-dark.png)\n\n如果没能粘贴上,什么也不会丢:同一个浮窗会展开成面板,文字从那里拿走。\n\n![口述设置:在哪里清理口语](docs/assets/shots/page-dictation.png)", "how": "按键,说一句话,再按一下。文字会落在光标闪烁的地方。\n\n这段时间里,屏幕下方一直有一颗玻璃水滴。你不说话时它很小。一开口,里面就有声波流动:这就是“它有没有听见我”的答案。\n\n![录音中的浮窗:玻璃里的声波](docs/assets/shots/plate-listening-dark.png)\n\n把鼠标移上去,水滴会展开成一排按钮:录音、提示词、翻译、语言、历史、设置。语言就在这里切换,开口前一秒就能换,不用专门去设置里找。\n\n![鼠标下的浮窗:一排六个按钮](docs/assets/shots/plate-hover-dark.png)\n\n如果没能粘贴上,什么也不会丢:同一个浮窗会展开成面板,文字从那里拿走。\n\n![口述设置:在哪里清理口语](docs/assets/shots/page-dictation.png)",
"quick_intro": "需要一台 macOS 14 或更新的 Mac,还有三项系统权限:麦克风、辅助功能、输入监控。从源码构建另外要 Xcode 和 Swift 6。接下来有三条路,走哪条都行。", "quick_intro": "[下载 macOS DMG](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg),打开后将 iriz 拖入 Applications。需要 Apple Silicon Mac 和 macOS 14 或更新版本,不需要 Xcode 或终端。\n\n打开 iriz,在引导中点击「下载并安装 Parakeet」(约 500 MB),然后按后续步骤授予权限。等模型就绪,将光标放入文本框,再试用听写快捷键。\n\n[安装、恢复模型和更新](docs/DOWNLOAD.zh.md)。从源码构建另需 Xcode 和 Swift 6,命令及其他安装方式见下方。",
"quick_extra": "不想构建?到 Releases 拿现成的磁盘映像:打开,把图标拖进 Applications。没有 Git?下载 [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip),解压后在里面执行同一条命令。第一次用?在 Claude Code 里打开项目并运行 `/iriz-setup`:安装以对话的方式进行,一次问一个问题,没有你点头不会装任何东西。", "quick_extra": "没有 Git?下载[源码 ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip),解压后运行同一个安装脚本。也可以在 Claude Code 中打开项目并运行 `/iriz-setup`,让智能体逐步引导安装,每次安装前都会先询问。",
"quick_result": "安装脚本先说清楚这是什么,再看你的机器缺什么,跑一遍 `bash scripts/selfcheck.sh --selftest`,最后告诉你下一步该做什么。你不开口,它什么都不装。真要构建,加一个参数:`bash install.sh --build`。", "quick_result": "安装脚本先说清楚这是什么,再看你的机器缺什么,跑一遍 `bash scripts/selfcheck.sh --selftest`,最后告诉你下一步该做什么。你不开口,它什么都不装。真要构建,加一个参数:`bash install.sh --build`。",
"compare": [ "compare": [
[ [
@@ -297,12 +299,11 @@
"safety_tail": "往外走的只有一件事,而且要你按按钮:识别模型那一次性的下载。提示词模式默认关着;打开它,就等于同意把转写交给你自己装好、自己登录的那个智能体命令行,比如 Codex CLI,走那条路时文本会发到它背后的服务商。翻译走的是同一条路:你说俄语,落下来的是英文。", "safety_tail": "往外走的只有一件事,而且要你按按钮:识别模型那一次性的下载。提示词模式默认关着;打开它,就等于同意把转写交给你自己装好、自己登录的那个智能体命令行,比如 Codex CLI,走那条路时文本会发到它背后的服务商。翻译走的是同一条路:你说俄语,落下来的是英文。",
"status": "状态:可用。作者每天都在用它口述。", "status": "状态:可用。作者每天都在用它口述。",
"limits": [ "limits": [
"语音模型认十八种欧洲语言,中文不在其中:中文口述它听不懂。", "此下载面向 Apple Silicon 和 macOS 14 及以上。Intel 未经验证;不支持 Windows、Linux 或 iPad。",
"自动换键盘布局只管英语和俄语这一对,对拼音、五笔这类中文输入法不适用。", "自动修正键盘布局只支持英语和俄语。界面支持俄语、英语和简体中文。",
"应用界面目前只有俄文,说明文档才有中文。", "应用使用自签名,尚未通过 Apple 公证。首次启动的安全提示见下载指南。",
"只支持 macOS 14 及以上。没有 Windows,没有 Linux,也没有 iPad。", "默认 Parakeet 模型需要单独下载,约 500 MB,不识别中文语音。其他模型支持的语言不同。",
"还没有做公证:下载来的构建第一次打开要用右键的“打开”。", "更新需手动完成:下载新 DMG,退出 iriz,再替换应用。模型与历史记录保存在应用包之外。"
"通用二进制里带着 Intel 那一片,可是作者手上没有 Intel 的 Mac,从来没在上面验过。"
], ],
"docs": "更深入:[逐步上手,每个界面都有截图](docs/ONBOARDING.zh.md)、[如何参与](CONTRIBUTING.zh.md)、[安全](SECURITY.zh.md)。", "docs": "更深入:[逐步上手,每个界面都有截图](docs/ONBOARDING.zh.md)、[如何参与](CONTRIBUTING.zh.md)、[安全](SECURITY.zh.md)。",
"license": "MIT。见 [LICENSE](LICENSE)。", "license": "MIT。见 [LICENSE](LICENSE)。",
@@ -327,9 +328,9 @@
}, },
"ru": { "ru": {
"short": "Одна клавиша, и та же самая в любой программе", "short": "Одна клавиша, и та же самая в любой программе",
"body": "По умолчанию это правый Command. Вы нажимаете ее, и больше на Маке менять нечего: ни окна открывать, ни курсор куда-то ставить заранее. Если клавиша у вас занята, поменять ее можно прямо в знакомстве, а не искать в настройках.", "body": "По умолчанию это правый Command. Ты нажимаешь ее, и больше на Маке менять нечего: ни окна открывать, ни курсор куда-то ставить заранее. Если клавиша у тебя занята, поменять ее можно прямо в знакомстве, а не искать в настройках.",
"result": "клавиша, которая отвечает и в редакторе, и в почте, и в терминале.", "result": "клавиша, которая отвечает и в редакторе, и в почте, и в терминале.",
"alt": "Этап 1 iriz: нажмите свою клавишу, снятый широким кадром канона Пантеона" "alt": "Этап 1 iriz: нажми свою клавишу, снятый широким кадром канона Пантеона"
}, },
"zh": { "zh": {
"short": "一个键,在哪个程序里都一样", "short": "一个键,在哪个程序里都一样",
@@ -346,10 +347,10 @@
"alt": "Iriz stage 2: say it out loud, drawn as a wide Pantheon marble scene" "alt": "Iriz stage 2: say it out loud, drawn as a wide Pantheon marble scene"
}, },
"ru": { "ru": {
"short": "Вы говорите, и плашка показывает, что слышит", "short": "Ты говоришь, и плашка показывает, что слышит",
"body": "Рядом с курсором появляется небольшая плашка, ее волна идет за вашим голосом, и видно, что вас слышат, а не приходится гадать. Звук живет в памяти ровно столько, сколько нужно на разбор, и на диск не попадает.", "body": "Рядом с курсором появляется небольшая плашка, ее волна идет за твоим голосом, и видно, что тебя слышат, а не приходится гадать. Звук живет в памяти ровно столько, сколько нужно на разбор, и на диск не попадает.",
"result": "запись, которая существует секунды и не оставляет следа.", "result": "запись, которая существует секунды и не оставляет следа.",
"alt": "Этап 2 iriz: скажите вслух, снятый широким кадром канона Пантеона" "alt": "Этап 2 iriz: скажи вслух, снятый широким кадром канона Пантеона"
}, },
"zh": { "zh": {
"short": "你说话,小提示条告诉你它在听", "short": "你说话,小提示条告诉你它在听",
@@ -367,8 +368,8 @@
}, },
"ru": { "ru": {
"short": "Мак превращает сказанное в буквы своим же чипом", "short": "Мак превращает сказанное в буквы своим же чипом",
"body": "Распознавание идет на Neural Engine вашего Мака: семь секунд речи разбираются примерно за десятую долю секунды. Никуда ничего не отправляется, а пока идет диктовка, загрузчик внутри библиотеки распознавания закрыт рубильником.", "body": "Распознавание идет на Neural Engine твоего Мака: семь секунд речи разбираются примерно за десятую долю секунды. Никуда ничего не отправляется, а пока идет диктовка, загрузчик внутри библиотеки распознавания закрыт рубильником.",
"result": "расшифровка, которая нигде, кроме вашей машины, не была.", "result": "расшифровка, которая нигде, кроме твоей машины, не была.",
"alt": "Этап 3 iriz: Мак разбирает сказанное, снятый широким кадром канона Пантеона" "alt": "Этап 3 iriz: Мак разбирает сказанное, снятый широким кадром канона Пантеона"
}, },
"zh": { "zh": {
@@ -387,7 +388,7 @@
}, },
"ru": { "ru": {
"short": "Текст встает туда, где мигал курсор", "short": "Текст встает туда, где мигал курсор",
"body": "Он попадает в то поле, в котором вы и были: письмо, чат, терминал. Если поле его не приняло, плашка раскрывается в панель с целым текстом, и один щелчок кладет его в буфер. Пока вы до него тянетесь, он никуда не денется.", "body": "Он попадает в исходное поле: письмо, чат, терминал. Если поле его не приняло, плашка раскрывается в панель с целым текстом, и один щелчок кладет его в буфер. Пока ты до него тянешься, он никуда не денется.",
"result": "текст в поле или текст, который еще можно забрать из панели.", "result": "текст в поле или текст, который еще можно забрать из панели.",
"alt": "Этап 4 iriz: текст встает в поле, снятый широким кадром канона Пантеона" "alt": "Этап 4 iriz: текст встает в поле, снятый широким кадром канона Пантеона"
}, },
+41 -11
View File
@@ -21,26 +21,26 @@
"bible": { "bible": {
"character_sheet": { "character_sheet": {
"published_path": "docs/assets/pantheon/bible-character.png", "published_path": "docs/assets/pantheon/bible-character.png",
"published_sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af", "published_sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e",
"alt": "Карта персонажа: Ирида из белого мрамора в четырех видах с мраморными крыльями, жезлом вестницы, табличкой и золотой лентой голоса, рядом этюды предметов" "alt": "Карта персонажа: Ирида из белого мрамора в четырех видах с мраморными крыльями, жезлом вестницы, табличкой и золотой лентой голоса, рядом этюды предметов"
}, },
"prop_sheet": { "prop_sheet": {
"published_path": "docs/assets/pantheon/bible-props.png", "published_path": "docs/assets/pantheon/bible-props.png",
"published_sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152", "published_sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e",
"alt": "Карта предметов: жезл с гладким кольцом, мраморная табличка с одной бороздой, крылатая сандалия, золотая лента голоса, мраморная клавиша и чаша на слоновой кости" "alt": "Карта предметов: жезл с гладким кольцом, мраморная табличка с одной бороздой, крылатая сандалия, золотая лента голоса, мраморная клавиша и чаша на слоновой кости"
} }
}, },
"hero": { "hero": {
"source_path": "docs/assets/pantheon/hero-source.png", "source_path": "docs/assets/pantheon/hero-source.png",
"source_sha256": "9fa6a4e6ae3867707636ac60f781603c46bae45e64217373922119b9503683c5", "source_sha256": "d2bf33d71b0068c8af26e6a8b12cc49c9c6e3f037c2aa51e9e8b4dca359fc4b1",
"published_path": "docs/assets/pantheon/hero.png", "published_path": "docs/assets/pantheon/hero.png",
"published_sha256": "ff02cfbef989f040db9e729265b84636ff0a94f5120718d1e94a066bc4381fb4" "published_sha256": "5c8c42c7758c737b47af8d4702b1f5a96ab54bae94565cdd1bfa4e919b29496d"
}, },
"emblem": { "emblem": {
"source_path": "docs/assets/pantheon/emblem-source.png", "source_path": "docs/assets/pantheon/emblem-source.png",
"source_sha256": "e228f8333ee8d6752f4f2ad7c08229ca65bc4060f50d154f10d5c401490b220b", "source_sha256": "1d56460678f01b8e944b46057cee68e486edbbedf9335f3cd6a899fd6b1b40f1",
"published_path": "docs/assets/pantheon/emblem.png", "published_path": "docs/assets/pantheon/emblem.png",
"published_sha256": "daf6fd93f9ab2aa98274b0085be08b1e0a47042873b358cd550639cbdfbc6d47" "published_sha256": "915d77676dbf1ff062ba13e0f0087f4202570e7bc7aba51c1a766293c660e820"
}, },
"takt": { "takt": {
"source_path": "docs/assets/pantheon/takt.png", "source_path": "docs/assets/pantheon/takt.png",
@@ -100,9 +100,9 @@
"diagram_ru": "Разбор", "diagram_ru": "Разбор",
"diagram_zh": "识别", "diagram_zh": "识别",
"source_path": "docs/assets/pantheon/workflow/03-decode.png", "source_path": "docs/assets/pantheon/workflow/03-decode.png",
"source_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd", "source_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc",
"published_path": "docs/assets/pantheon/workflow/03-decode.png", "published_path": "docs/assets/pantheon/workflow/03-decode.png",
"published_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd" "published_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc"
}, },
{ {
"id": "insert", "id": "insert",
@@ -113,15 +113,15 @@
"diagram_ru": "Текст", "diagram_ru": "Текст",
"diagram_zh": "落字", "diagram_zh": "落字",
"source_path": "docs/assets/pantheon/workflow/04-insert.png", "source_path": "docs/assets/pantheon/workflow/04-insert.png",
"source_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc", "source_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680",
"published_path": "docs/assets/pantheon/workflow/04-insert.png", "published_path": "docs/assets/pantheon/workflow/04-insert.png",
"published_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc" "published_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680"
} }
], ],
"doc_frames": { "doc_frames": {
"contributing": { "contributing": {
"published_path": "docs/assets/pantheon/doc-contributing.png", "published_path": "docs/assets/pantheon/doc-contributing.png",
"published_sha256": "d1cfa5ca7a5a50a3492d90e2f9ac5a07a7481b8e450031fe303c2718a87ba133", "published_sha256": "583b69a545c9afed6a496ae74b8867d111b63c15282b48f83e209a621b5c73ca",
"alt": "Две одинаковые мраморные таблички на низком столе, в левой лежит золотая лента голоса, правая пустая и ждет, рядом стоит жезл вестницы", "alt": "Две одинаковые мраморные таблички на низком столе, в левой лежит золотая лента голоса, правая пустая и ждет, рядом стоит жезл вестницы",
"pages": { "pages": {
"en": "CONTRIBUTING.md", "en": "CONTRIBUTING.md",
@@ -131,6 +131,18 @@
} }
}, },
"doc_pages": [ "doc_pages": [
{
"path": "docs/DOWNLOAD.md",
"frames": ["assets/pantheon/doc-onboarding.png"]
},
{
"path": "docs/DOWNLOAD.ru.md",
"frames": ["assets/pantheon/doc-onboarding.png"]
},
{
"path": "docs/DOWNLOAD.zh.md",
"frames": ["assets/pantheon/doc-onboarding.png"]
},
{ {
"path": "docs/ONBOARDING.md", "path": "docs/ONBOARDING.md",
"frames": [ "frames": [
@@ -188,6 +200,24 @@
"docs/assets/pantheon/window-wash-source.png" "docs/assets/pantheon/window-wash-source.png"
] ]
} }
],
"inserts": [
{
"role": "desk-firstrun",
"published_path": "docs/assets/pantheon/desk-firstrun.png",
"published_sha256": "64c84c628ebc7cdb856b62b38614eea882693b0a56ecacccc702362485ebed67",
"alt": "Ирида за мраморным столом: на экране ноутбука первый экран знакомства iriz с плашкой и волной",
"screen_source": "docs/assets/shots/firstrun-ru.png",
"scene_source": "docs/assets/pantheon/doc-desk-source.png"
},
{
"role": "desk-history",
"published_path": "docs/assets/pantheon/desk-history.png",
"published_sha256": "749780636be9e7614d38aec56fd8156ffcc6492ee2d29720b014221e56d13d0f",
"alt": "Мраморный ноутбук крупно: на экране окно истории надиктовок iriz со списком и поиском",
"screen_source": "docs/assets/shots/history-ru.png",
"scene_source": "docs/assets/pantheon/doc-desk-close-source.png"
}
] ]
}, },
"receipts": { "receipts": {
+3 -3
View File
@@ -14,11 +14,11 @@ Constraints, and these are the identity of the figure and must be identical in a
- Large carved marble wings rise from her shoulders, folded close to her back, feathers cut as real overlapping plates. The wings are marble, never feathers of cloth, and they are present in every view. - Large carved marble wings rise from her shoulders, folded close to her back, feathers cut as real overlapping plates. The wings are marble, never feathers of cloth, and they are present in every view.
- She wears winged sandals: a low marble sandal on each foot with a small carved wing at the ankle, both feet flat on the ground. - She wears winged sandals: a low marble sandal on each foot with a small carved wing at the ankle, both feet flat on the ground.
- She HOLDS the herald staff in her right hand: a slender muted-gold staff as tall as her shoulder, its butt end resting on the ground beside her right foot and casting a shadow, her fingers closed around the shaft. The head of the staff is a plain smooth ring, with NO snakes, NO wings and NO letters. - She HOLDS the herald staff in her right hand: a slender muted-gold staff as tall as her shoulder, its butt end resting on the ground beside her right foot and casting a shadow, her fingers closed around the shaft. The head of the staff is a plain smooth ring, with NO snakes, NO wings and NO letters.
- She HOLDS the marble writing tablet in her left hand: a flat rectangular white-marble tablet the size of a forearm, gripped along its lower edge by her closed fingers, held at waist height, its face turned slightly toward the viewer. The tablet face carries ONE carved horizontal groove and nothing else: no letters, no digits, no emblem. - She HOLDS the marble writing tablet in her left hand: a flat rectangular white-marble tablet the size of a forearm, gripped along its lower edge by her closed fingers, held at waist height, its face turned slightly toward the viewer. The tablet face carries ONE sound wave and nothing else: a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends. No letters, no digits, no emblem.
- A single muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat on the face of the tablet, ending inside the carved groove. It is one continuous ribbon, it touches the tablet, and it never breaks into pieces and never floats away from her. - A single muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat on the face of the tablet, where it resolves into that sound wave of gold bars. It is one continuous ribbon, it touches the tablet, and it never breaks into pieces and never floats away from her.
- Three thin sky-blue paths run along the ground from the left edge of the frame and CONVERGE at the butt of the herald staff. They lie flat on the ground, touch it along their whole length, and end at the staff; they never rise into the air. - Three thin sky-blue paths run along the ground from the left edge of the frame and CONVERGE at the butt of the herald staff. They lie flat on the ground, touch it along their whole length, and end at the staff; they never rise into the air.
- She stands on a round marble base whose full underside rests on the ground. - She stands on a round marble base whose full underside rests on the ground.
- Every view shows the same person wearing the SAME costume: one chiton, one mantle over the same shoulder, one belt at the same height, wings of the same span. The staff shown alone in the study below is the SAME OBJECT she holds: same length, same plain ring head. The tablet shown alone is the same tablet with the same single groove. The sandal shown alone is the same sandal. Nothing changes between views except the angle of the camera. - Every view shows the same person wearing the SAME costume: one chiton, one mantle over the same shoulder, one belt at the same height, wings of the same span. The staff shown alone in the study below is the SAME OBJECT she holds: same length, same plain ring head. The tablet shown alone is the same tablet with the same single sound wave. The sandal shown alone is the same sandal. Nothing changes between views except the angle of the camera.
- Anatomically correct hands with exactly five fingers, natural finger lengths and one clearly readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers, natural finger lengths and one clearly readable thumb, fingers not fused.
- Nothing hovers, nothing balances on a point: everything carried is held by a closed hand, everything standing rests on a surface and casts a shadow. - Nothing hovers, nothing balances on a point: everything carried is held by a closed hand, everything standing rests on a surface and casts a shadow.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
+2 -2
View File
@@ -2,7 +2,7 @@ Use case: stylized-concept
Asset type: prop reference sheet for a project of the Olympuz family, binding for every later frame Asset type: prop reference sheet for a project of the Olympuz family, binding for every later frame
Primary request: one wide sheet that fixes the objects of this project once and for all, so each one can be reproduced identically in every later scene. Primary request: one wide sheet that fixes the objects of this project once and for all, so each one can be reproduced identically in every later scene.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column. Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column.
Subject: six objects laid out on a plain ivory surface, each shown alone, each large enough to read: (1) the herald staff, a slender muted-gold rod as long as a forearm with a plain smooth ring at its head; (2) the marble writing tablet, a flat rectangular white-marble slab with ONE carved horizontal groove across its face; (3) the winged sandal, a low white-marble sandal with a small carved wing at the ankle; (4) the gold voice ribbon alone, one continuous muted-gold band curving once and lying flat at its lower end; (5) a white-marble key-cap, a cube of marble with softly rounded corners and one shallow round dish carved into its top face; (6) a small white-marble bowl of the same family as the other pieces, empty, its full base resting on the surface. Subject: six objects laid out on a plain ivory surface, each shown alone, each large enough to read: (1) the herald staff, a slender muted-gold rod as long as a forearm with a plain smooth ring at its head; (2) the marble writing tablet, a flat rectangular white-marble slab whose face carries ONE row of slender upright muted-gold bars of different heights - a sound wave, tallest at the centre and tapering smoothly to short bars at both ends, evenly spaced and standing clear of one another; (3) the winged sandal, a low white-marble sandal with a small carved wing at the ankle; (4) the gold voice ribbon alone, one continuous muted-gold band curving once and lying flat at its lower end; (5) a white-marble key-cap, a cube of marble with softly rounded corners and one shallow round dish carved into its top face; (6) a small white-marble bowl of the same family as the other pieces, empty, its full base resting on the surface.
Composition/framing: 16:9 landscape. A classical white-marble column stands at the far right as the family signature, clearly separated from the objects. The six objects sit in two rows of three with equal spacing, each fully inside the frame, nothing overlapping, nothing cropped. Generous empty ivory space between them. Composition/framing: 16:9 landscape. A classical white-marble column stands at the far right as the family signature, clearly separated from the objects. The six objects sit in two rows of three with equal spacing, each fully inside the frame, nothing overlapping, nothing cropped. Generous empty ivory space between them.
Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation, museum plate feeling Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation, museum plate feeling
Lighting/mood: soft daylight from upper left, long gentle shadows, identical lighting on every object. Gold surfaces glow softly FROM WITHIN, never lit by a lamp, a neon tube or a hard rim light. Lighting/mood: soft daylight from upper left, long gentle shadows, identical lighting on every object. Gold surfaces glow softly FROM WITHIN, never lit by a lamp, a neon tube or a hard rim light.
@@ -10,7 +10,7 @@ Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9
Constraints: Constraints:
- Every object rests on the surface and casts a shadow. Nothing hovers, nothing balances on a point. - Every object rests on the surface and casts a shadow. Nothing hovers, nothing balances on a point.
- The staff head is a plain smooth ring: NO snakes, NO wings, NO letters, NO engraving. - The staff head is a plain smooth ring: NO snakes, NO wings, NO letters, NO engraving.
- The tablet carries exactly ONE groove and no writing of any kind. - The tablet carries exactly ONE sound wave of gold bars and no writing of any kind. The bars read as sound, not as a chart: no frame, no axis, no baseline, no ruler marks.
- The gold ribbon is one continuous piece, not a chain and not a string of segments. - The gold ribbon is one continuous piece, not a chain and not a string of segments.
- The key-cap is marble, not plastic, and its dish is shallow and smooth. - The key-cap is marble, not plastic, and its dish is shallow and smooth.
- These are the SAME objects that the character sheet shows in her hands: same proportions, same materials, same details. - These are the SAME objects that the character sheet shows in her hands: same proportions, same materials, same details.
+2 -2
View File
@@ -2,7 +2,7 @@ Use case: stylized-concept
Asset type: document page frame for the contributing page of a project of the Olympuz family Asset type: document page frame for the contributing page of a project of the Olympuz family
Primary request: one wide frame for the page that explains how somebody else can help - a second tablet is placed beside the first, so the reader sees room made for their work. Primary request: one wide frame for the page that explains how somebody else can help - a second tablet is placed beside the first, so the reader sees room made for their work.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the tablet, the herald staff and the gold ribbon must match those sheets exactly. Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the tablet, the herald staff and the gold ribbon must match those sheets exactly.
Subject: two marble writing tablets of the same size lie side by side on a low marble table at the centre of the frame, each with its single carved groove facing the viewer. One continuous muted-gold ribbon curves down from the upper left and ends inside the groove of the left tablet; the right tablet is empty and waiting. The herald staff rests upright against the right end of the table, its butt on the ground. Subject: two marble writing tablets of the same size lie side by side on a low marble table at the centre of the frame, each with its face turned toward the viewer. One continuous muted-gold ribbon curves down from the upper left and ends on the left tablet, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends; the right tablet is bare marble and waiting. The herald staff rests upright against the right end of the table, its butt on the ground.
Composition/framing: 16:9 landscape. The table with both tablets reads clearly at the centre. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, no figure in this frame, nothing cropped. Composition/framing: 16:9 landscape. The table with both tablets reads clearly at the centre. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, no figure in this frame, nothing cropped.
Style/medium: premium restrained 3D marble render, physically plausible materials, warm ivory Apple-like presentation Style/medium: premium restrained 3D marble render, physically plausible materials, warm ivory Apple-like presentation
Lighting/mood: soft daylight from upper left, long gentle shadows, calm. Gold glows softly from within, never lit by a lamp or a hard rim light. Lighting/mood: soft daylight from upper left, long gentle shadows, calm. Gold glows softly from within, never lit by a lamp or a hard rim light.
@@ -12,5 +12,5 @@ Constraints:
- Both tablets rest on the table, the table rests on the ground, the staff touches the ground. Nothing hovers, everything casts a shadow. - Both tablets rest on the table, the table rests on the ground, the staff touches the ground. Nothing hovers, everything casts a shadow.
- The two tablets are identical in size and thickness: the second is room made for somebody else, not a smaller copy. - The two tablets are identical in size and thickness: the second is room made for somebody else, not a smaller copy.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: figures, faces, rainbow of many colors, prismatic colors, screens, keyboards, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels Avoid: owl, bird, any animal, figures, faces, rainbow of many colors, prismatic colors, screens, keyboards, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
@@ -0,0 +1,21 @@
{
"_": "Углы экрана в docs/assets/pantheon/doc-desk-close-source.png. Померены по строкам 07.09.2026: левый край идёт от 502 вверху к 493 внизу, правый от 1167 к 1173, верх 211, низ 609.",
"ekran": [
[
503,
211
],
[
1167,
211
],
[
1174,
609
],
[
492,
609
]
]
}
@@ -0,0 +1,20 @@
Use case: stylized-concept
Asset type: wide documentation frame for a project of the Olympuz family
Primary request: one wide scene of the workplace itself - the marble laptop stands ready and its screen is a blank flat panel waiting for the product picture to be placed into it by a separate instrument.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project prop sheet - the herald staff and the gold voice ribbon must match that sheet exactly.
Subject: an open laptop carved from white marble stands alone at the centre of a low white-marble table: a thin base with a plain flat lid raised at a comfortable angle. THE SCREEN IS COMPLETELY BLANK - a smooth flat ivory panel with a clean rectangular border, no image, no glow, no reflection, no carving, nothing on it at all. The muted-gold herald staff lies flat on the table beside the laptop, and one continuous muted-gold ribbon of voice curves in from the left and ends at the lower edge of the screen without crossing onto it. No figure is present.
Composition/framing: 16:9 landscape, the laptop close to the viewer and filling the middle half of the frame, its screen large, flat and facing the viewer almost straight on, all four corners clearly visible and unobstructed. Generous empty ivory space above. A classical white-marble column stands at the right as the family signature. Nothing overlaps the screen. Nothing is cropped by any edge.
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the voice ribbon and the metal fittings only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
Constraints:
- The laptop is carved marble, not a real device: no logo, no ports, no rubber feet, no camera dot, no key legends. Its keys are plain shallow squares of marble.
- The screen panel is EMPTY and FLAT and evenly lit, with a clear thin border all around, because a real screenshot of the product is placed into it afterwards. Any picture generated on it would be invented interface.
- The screen is a flat plane. It is not curved, not tilted away from the viewer, and none of its four corners is hidden by a hand, a wing, the staff or the ribbon.
- Everything carried is held by a closed hand. Everything standing rests on the ground and casts a shadow. Nothing hovers.
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- No modern devices other than this marble laptop: no phones, no cables, no microphones, no mouse.
- Preserve the reference style; highest final quality; maximum resolution.
Avoid: owl, bird, any animal, glowing screen, picture on the screen, reflection on the screen, screen bezel with a logo, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, spear, hearth, fire, floating staff, floating laptop, a ribbon floating free of the figure, cloth wings, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image, and nothing at all on the screen.
+21
View File
@@ -0,0 +1,21 @@
{
"_": "Углы экрана в docs/assets/pantheon/doc-desk-source.png. Померены по строкам 07.09.2026: экран прямоугольный, левый край 714, правый 1152, верх 257, низ 538. Прежняя запись врала на 36 точек по нижнему левому углу, и снимок вставал наискось.",
"ekran": [
[
714,
257
],
[
1152,
257
],
[
1152,
538
],
[
714,
538
]
]
}
+20
View File
@@ -0,0 +1,20 @@
Use case: stylized-concept
Asset type: wide documentation frame for a project of the Olympuz family
Primary request: one wide scene that shows where the work actually happens - the messenger sits at her own table with a laptop open in front of her, and the laptop screen is a blank flat panel waiting for the product picture to be placed into it by a separate instrument.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet - the figure, her costume, her wings, the herald staff and the gold voice ribbon must match that sheet exactly.
Subject: Iris sits on a low white-marble bench behind a low white-marble table, turned three-quarters toward the viewer, her marble wings folded close to her back. On the table in front of her stands an open laptop carved from the same white marble: a thin base with a plain flat lid raised at a comfortable angle. THE SCREEN IS COMPLETELY BLANK - a smooth flat ivory panel with a clean rectangular border, no image, no glow, no reflection, no carving, nothing on it at all. Her left hand rests flat on the table beside the laptop, her right hand holds the herald staff upright, its butt on the ground beside the bench. One continuous muted-gold ribbon of voice rises from just below her chin and curves once toward the laptop, ending at the lower edge of the screen without crossing onto it.
Composition/framing: 16:9 landscape, the laptop screen large, flat and facing the viewer almost straight on, its four corners all clearly visible and unobstructed. The figure occupies the left third, the laptop the middle, generous empty ivory space above. A classical white-marble column stands at the right as the family signature, clearly separated from the figure. Nothing overlaps the screen. Nothing is cropped by any edge.
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the voice ribbon and the metal fittings only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
Constraints:
- The laptop is carved marble, not a real device: no logo, no ports, no rubber feet, no camera dot, no key legends. Its keys are plain shallow squares of marble.
- The screen panel is EMPTY and FLAT and evenly lit, with a clear thin border all around, because a real screenshot of the product is placed into it afterwards. Any picture generated on it would be invented interface.
- The screen is a flat plane. It is not curved, not tilted away from the viewer, and none of its four corners is hidden by a hand, a wing, the staff or the ribbon.
- Everything carried is held by a closed hand. Everything standing rests on the ground and casts a shadow. Nothing hovers.
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- No modern devices other than this marble laptop: no phones, no cables, no microphones, no mouse.
- Preserve the reference style; highest final quality; maximum resolution.
Avoid: owl, bird, any animal, glowing screen, picture on the screen, reflection on the screen, screen bezel with a logo, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, spear, hearth, fire, floating staff, floating laptop, a ribbon floating free of the figure, cloth wings, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image, and nothing at all on the screen.
+2 -2
View File
@@ -2,7 +2,7 @@ Use case: stylized-concept
Asset type: document page frame for the first-steps page of a project of the Olympuz family Asset type: document page frame for the first-steps page of a project of the Olympuz family
Primary request: one wide frame for the page that walks a newcomer through the first install - the messenger sets her tablet down within reach and steps back, so the reader sees an invitation rather than a performance. Primary request: one wide frame for the page that walks a newcomer through the first install - the messenger sets her tablet down within reach and steps back, so the reader sees an invitation rather than a performance.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, the herald staff, the marble tablet and the gold ribbon must match those sheets exactly. Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, the herald staff, the marble tablet and the gold ribbon must match those sheets exactly.
Subject: the marble writing tablet lies flat on a low marble table at the centre of the frame, its single carved groove facing the viewer, with one continuous muted-gold ribbon curving down from the upper left and ending inside that groove. Iris stands to the left of the table, turned three-quarters toward it, her right hand closed around the herald staff whose butt rests on the ground, her left hand open and lowered, having just set the tablet down. Subject: the marble writing tablet lies flat on a low marble table at the centre of the frame, its face turned toward the viewer, with one continuous muted-gold ribbon curving down from the upper left and ending on that face, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends. Iris stands to the left of the table, turned three-quarters toward it, her right hand closed around the herald staff whose butt rests on the ground, her left hand open and lowered, having just set the tablet down.
Composition/framing: 16:9 landscape. The tablet reads clearly at the centre, the figure occupies the left third and never overlaps the tablet. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, nothing cropped. Composition/framing: 16:9 landscape. The tablet reads clearly at the centre, the figure occupies the left third and never overlaps the tablet. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, nothing cropped.
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery, physically plausible materials, warm ivory Apple-like presentation Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery, physically plausible materials, warm ivory Apple-like presentation
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. Gold glows softly from within, never lit by a lamp or a hard rim light. Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. Gold glows softly from within, never lit by a lamp or a hard rim light.
@@ -13,5 +13,5 @@ Constraints:
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet. - Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating tablet, floating staff, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating tablet, floating staff, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
+3 -3
View File
@@ -2,7 +2,7 @@ Use case: stylized-concept
Asset type: square emblem for a project of the Olympuz family Asset type: square emblem for a project of the Olympuz family
Primary request: one square emblem that reads at a glance and stays readable when shrunk - the messenger's staff and the voice becoming a written line. Primary request: one square emblem that reads at a glance and stays readable when shrunk - the messenger's staff and the voice becoming a written line.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the herald staff, the marble tablet and the gold ribbon must match those sheets exactly. Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the herald staff, the marble tablet and the gold ribbon must match those sheets exactly.
Subject: a single composition on a plain ivory ground: the marble writing tablet lying flat and slightly tilted toward the viewer, the muted-gold herald staff resting diagonally across its upper corner, and one continuous muted-gold ribbon curving down from the upper left and ending flat inside the single carved groove on the tablet face. Subject: a single composition on a plain ivory ground: the marble writing tablet lying flat and slightly tilted toward the viewer, the muted-gold herald staff resting diagonally across its upper corner, and one continuous muted-gold ribbon curving down from the upper left and ending flat on the tablet face, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends.
Composition/framing: perfect square, the composition centred with generous empty ivory margin on all four sides, nothing cropped, no column in this frame. Composition/framing: perfect square, the composition centred with generous empty ivory margin on all four sides, nothing cropped, no column in this frame.
Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation
Lighting/mood: soft daylight from upper left, one gentle shadow under each object. Gold glows softly from within, never lit by a lamp or a hard rim light. Lighting/mood: soft daylight from upper left, one gentle shadow under each object. Gold glows softly from within, never lit by a lamp or a hard rim light.
@@ -11,8 +11,8 @@ Constraints:
- Only three objects in the frame: tablet, staff, ribbon. Nothing else. - Only three objects in the frame: tablet, staff, ribbon. Nothing else.
- Every object rests on the surface and casts a shadow. Nothing hovers. - Every object rests on the surface and casts a shadow. Nothing hovers.
- The staff head is a plain smooth ring with no snakes, no wings and no engraving. - The staff head is a plain smooth ring with no snakes, no wings and no engraving.
- The tablet face carries exactly one groove and no writing. - The tablet face carries exactly one sound wave of gold bars and no writing.
- The shapes stay large and simple so the emblem survives being shrunk to a small icon. - The shapes stay large and simple so the emblem survives being shrunk to a small icon.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, figures, faces, wings of cloth, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, figures, faces, wings of cloth, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
+14 -14
View File
@@ -11,10 +11,10 @@
"tier": "frontier" "tier": "frontier"
}, },
"quality": "highest", "quality": "highest",
"generation_id": "d81e61f8-468c-4c3d-8dc9-b36918feff42", "generation_id": "6e4258d0-1cce-4a71-a0c2-a90652403c56",
"generated_at": "2026-09-05T09:50:10Z", "generated_at": "2026-09-07T19:41:41Z",
"capability_snapshot": { "capability_snapshot": {
"checked_at": "2026-09-05T09:50:10Z", "checked_at": "2026-09-07T19:41:41Z",
"routes": [ "routes": [
{ {
"id": "codex:image_gen:managed-frontier", "id": "codex:image_gen:managed-frontier",
@@ -32,7 +32,7 @@
}, },
"prompt": { "prompt": {
"path": ".github/pantheon/prompt.txt", "path": ".github/pantheon/prompt.txt",
"sha256": "d55d072743ca7f651e8fea7a983046a3723c1f2d66894cda8a787e021265fe7e" "sha256": "1a06fd8679e30d8d786bbf85720330e8f771af9fc1e46b459b916a5c67550bea"
}, },
"references": [ "references": [
{ {
@@ -45,35 +45,35 @@
}, },
{ {
"role": "bible-character", "role": "bible-character",
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af" "sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e"
}, },
{ {
"role": "bible-props", "role": "bible-props",
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152" "sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
} }
], ],
"candidates": [ "candidates": [
{ {
"id": "codex-managed", "id": "codex-managed",
"route_id": "codex:image_gen:managed-frontier", "route_id": "codex:image_gen:managed-frontier",
"generation_id": "d81e61f8-468c-4c3d-8dc9-b36918feff42", "generation_id": "6e4258d0-1cce-4a71-a0c2-a90652403c56",
"prompt_sha256": "d55d072743ca7f651e8fea7a983046a3723c1f2d66894cda8a787e021265fe7e", "prompt_sha256": "1a06fd8679e30d8d786bbf85720330e8f771af9fc1e46b459b916a5c67550bea",
"reference_sha256": [ "reference_sha256": [
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2", "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd", "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
"5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af", "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e",
"ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152" "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
], ],
"outputs": [ "outputs": [
{ {
"role": "hero", "role": "hero",
"source_sha256": "9fa6a4e6ae3867707636ac60f781603c46bae45e64217373922119b9503683c5", "source_sha256": "d2bf33d71b0068c8af26e6a8b12cc49c9c6e3f037c2aa51e9e8b4dca359fc4b1",
"published_sha256": "ff02cfbef989f040db9e729265b84636ff0a94f5120718d1e94a066bc4381fb4" "published_sha256": "5c8c42c7758c737b47af8d4702b1f5a96ab54bae94565cdd1bfa4e919b29496d"
}, },
{ {
"role": "emblem", "role": "emblem",
"source_sha256": "e228f8333ee8d6752f4f2ad7c08229ca65bc4060f50d154f10d5c401490b220b", "source_sha256": "1d56460678f01b8e944b46057cee68e486edbbedf9335f3cd6a899fd6b1b40f1",
"published_sha256": "daf6fd93f9ab2aa98274b0085be08b1e0a47042873b358cd550639cbdfbc6d47" "published_sha256": "915d77676dbf1ff062ba13e0f0087f4202570e7bc7aba51c1a766293c660e820"
} }
] ]
} }
+3 -3
View File
@@ -2,7 +2,7 @@ Use case: stylized-concept
Asset type: wide hero image for the README of a project of the Olympuz family Asset type: wide hero image for the README of a project of the Olympuz family
Primary request: one wide scene that says in a single look what this project does - a spoken sentence is carried by the messenger and lands as written text on the person's own tablet, without ever leaving the room. Primary request: one wide scene that says in a single look what this project does - a spoken sentence is carried by the messenger and lands as written text on the person's own tablet, without ever leaving the room.
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, her costume, her wings, the herald staff, the marble tablet, the winged sandals and the gold voice ribbon must match those sheets exactly. Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, her costume, her wings, the herald staff, the marble tablet, the winged sandals and the gold voice ribbon must match those sheets exactly.
Subject: Iris stands slightly left of centre, turned three-quarters toward the viewer, her marble wings folded close to her back. Her right hand closes around the herald staff, whose butt rests on the ground beside her foot. Her left hand holds the marble writing tablet at waist height, its face turned toward the viewer. One continuous muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat inside the single carved groove on the tablet face, where it becomes a straight carved line of writing. Subject: Iris stands slightly left of centre, turned three-quarters toward the viewer, her marble wings folded close to her back. Her right hand closes around the herald staff, whose butt rests on the ground beside her foot. Her left hand holds the marble writing tablet at waist height, its face turned toward the viewer. One continuous muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat on the tablet face, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends. The bars are evenly spaced, stand clear of one another, and fill the width of the tablet face.
Composition/framing: 16:9 landscape, generous empty ivory space, the figure occupying the left half and the tablet reading clearly at the centre. A classical white-marble column stands at the right as the family signature, clearly separated from the figure. Nothing overlaps the figure, nothing is cropped by any edge. Composition/framing: 16:9 landscape, generous empty ivory space, the figure occupying the left half and the tablet reading clearly at the centre. A classical white-marble column stands at the right as the family signature, clearly separated from the figure. Nothing overlaps the figure, nothing is cropped by any edge.
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light. Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
@@ -15,5 +15,5 @@ Constraints:
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- No screens, no keyboards, no microphones, no cables, no modern devices anywhere in the frame. - No screens, no keyboards, no microphones, no cables, no modern devices anywhere in the frame.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, owl, spear, hearth, fire, floating staff, floating tablet, a ribbon floating free of the figure, cloth wings, screens, keyboards, microphones, phones, laptops, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels Avoid: waveform drawn as a continuous curved line, oscilloscope trace, equalizer with a frame or axis, bars of equal height, carved groove or engraved line on the tablet, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, owl, spear, hearth, fire, floating staff, floating tablet, a ribbon floating free of the figure, cloth wings, screens, keyboards, microphones, phones, laptops, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. The carved line on the tablet is a plain groove, not writing. Text (verbatim): No readable text, no letters, no digits anywhere in the image. The gold bars on the tablet are a sound wave, not writing and not any script.
+122 -122
View File
@@ -1,127 +1,127 @@
{ {
"schema_version": 1, "schema_version": 1,
"kind": "pantheon-generation", "kind": "pantheon-generation",
"selection_mode": "managed-frontier", "selection_mode": "managed-frontier",
"runtime": "codex", "runtime": "codex",
"tool": "image_gen", "tool": "image_gen",
"route_id": "codex:image_gen:managed-frontier", "route_id": "codex:image_gen:managed-frontier",
"model": { "model": {
"id": "provider-managed",
"revision": "provider-managed",
"tier": "frontier"
},
"quality": "highest",
"generation_id": "pantheon-stage-series-iris-2026-09-07",
"generated_at": "2026-09-06T21:22:17Z",
"prompt": {
"path": ".github/pantheon/workflow-01-key-prompt.txt",
"sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63"
},
"references": [
{
"role": "style-anchor",
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
},
{
"role": "column-reference",
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
},
{
"role": "character-sheet",
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af"
},
{
"role": "prop-sheet",
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
}
],
"outputs": [
{
"role": "stage-01-key",
"path": "docs/assets/pantheon/workflow/01-key.png",
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
"prompt_path": ".github/pantheon/workflow-01-key-prompt.txt",
"prompt_sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63"
},
{
"role": "stage-02-voice",
"path": "docs/assets/pantheon/workflow/02-voice.png",
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
"prompt_path": ".github/pantheon/workflow-02-voice-prompt.txt",
"prompt_sha256": "e7b973e8c315e1a38d2959280dace5cefa153092500ae4d0491a44e4efb50d0e"
},
{
"role": "stage-03-decode",
"path": "docs/assets/pantheon/workflow/03-decode.png",
"sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
"prompt_path": ".github/pantheon/workflow-03-decode-prompt.txt",
"prompt_sha256": "83f32bceae3425e70010111291f8b47c80a1368d4bfd7e9fae7c60f97399e037"
},
{
"role": "stage-04-insert",
"path": "docs/assets/pantheon/workflow/04-insert.png",
"sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
"prompt_path": ".github/pantheon/workflow-04-insert-prompt.txt",
"prompt_sha256": "c716dbcc2daadfd3efe5bfdbca6bb790946bfd500e828c0046f876738a690716"
}
],
"capability_snapshot": {
"checked_at": "2026-09-06T21:22:17Z",
"routes": [
{
"id": "codex:image_gen:managed-frontier",
"rank": 1,
"available": true,
"tier": "frontier",
"quality": "highest",
"model": {
"id": "provider-managed",
"revision": "provider-managed",
"tier": "frontier"
}
}
]
},
"candidates": [
{
"id": "codex-managed-stage-series",
"route_id": "codex:image_gen:managed-frontier",
"generation_id": "pantheon-stage-series-iris-2026-09-07",
"prompt_sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63",
"reference_sha256": [
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
"5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af",
"ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
],
"outputs": [
{
"role": "stage-01-key",
"source_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
"published_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c"
},
{
"role": "stage-02-voice",
"source_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
"published_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e"
},
{
"role": "stage-03-decode",
"source_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
"published_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd"
},
{
"role": "stage-04-insert",
"source_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
"published_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc"
}
],
"model": {
"id": "provider-managed", "id": "provider-managed",
"revision": "provider-managed", "revision": "provider-managed",
"tier": "frontier" "tier": "frontier"
} },
} "quality": "highest",
], "generation_id": "00d89fee-17cd-4615-acd6-81a89a592fdf",
"winner_id": "codex-managed-stage-series" "generated_at": "2026-09-07T19:43:22Z",
"prompt": {
"path": ".github/pantheon/workflow-01-key-prompt.txt",
"sha256": "88ef2710d419af4b15fa2b4591ed5dc22d7b29529eaa7f9eab417a0e227031c4"
},
"references": [
{
"role": "style-anchor",
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
},
{
"role": "column-reference",
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
},
{
"role": "character-sheet",
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af"
},
{
"role": "prop-sheet",
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
}
],
"outputs": [
{
"role": "stage-01-key",
"path": "docs/assets/pantheon/workflow/01-key.png",
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
"prompt_path": ".github/pantheon/workflow-01-key-prompt.txt",
"prompt_sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63"
},
{
"role": "stage-02-voice",
"path": "docs/assets/pantheon/workflow/02-voice.png",
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
"prompt_path": ".github/pantheon/workflow-02-voice-prompt.txt",
"prompt_sha256": "e7b973e8c315e1a38d2959280dace5cefa153092500ae4d0491a44e4efb50d0e"
},
{
"role": "stage-03-decode",
"path": "docs/assets/pantheon/workflow/03-decode.png",
"sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
"prompt_path": ".github/pantheon/workflow-03-decode-prompt.txt",
"prompt_sha256": "83f32bceae3425e70010111291f8b47c80a1368d4bfd7e9fae7c60f97399e037"
},
{
"role": "stage-04-insert",
"path": "docs/assets/pantheon/workflow/04-insert.png",
"sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
"prompt_path": ".github/pantheon/workflow-04-insert-prompt.txt",
"prompt_sha256": "c716dbcc2daadfd3efe5bfdbca6bb790946bfd500e828c0046f876738a690716"
}
],
"capability_snapshot": {
"checked_at": "2026-09-07T19:43:22Z",
"routes": [
{
"id": "codex:image_gen:managed-frontier",
"rank": 1,
"available": true,
"tier": "frontier",
"quality": "highest",
"model": {
"id": "provider-managed",
"revision": "provider-managed",
"tier": "frontier"
}
}
]
},
"candidates": [
{
"id": "codex-managed-stage-series",
"route_id": "codex:image_gen:managed-frontier",
"generation_id": "00d89fee-17cd-4615-acd6-81a89a592fdf",
"prompt_sha256": "88ef2710d419af4b15fa2b4591ed5dc22d7b29529eaa7f9eab417a0e227031c4",
"reference_sha256": [
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
"5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af",
"ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
],
"outputs": [
{
"role": "stage-01-key",
"source_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
"published_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c"
},
{
"role": "stage-02-voice",
"source_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
"published_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e"
},
{
"role": "stage-03-decode",
"source_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc",
"published_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc"
},
{
"role": "stage-04-insert",
"source_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680",
"published_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680"
}
],
"model": {
"id": "provider-managed",
"revision": "provider-managed",
"tier": "frontier"
}
}
],
"winner_id": "codex-managed-stage-series"
} }
+180 -172
View File
@@ -1,176 +1,184 @@
{ {
"schema_version": 1, "schema_version": 1,
"kind": "pantheon-visual-judge", "kind": "pantheon-visual-judge",
"receipt_id": "pantheon-stage-judge-iris-2026-09-07", "receipt_id": "iriz-stage-judge-wave-2026-09-07",
"checked_at": "2026-09-06T21:22:17Z", "checked_at": "2026-09-07T20:26:09Z",
"runtime": "claude", "runtime": "claude",
"tool": "read_image", "tool": "read_image",
"route_id": "claude:read_image:frontier", "route_id": "claude:read_image:frontier",
"model": { "model": {
"id": "claude-opus-5", "id": "claude-opus-5",
"revision": "claude-opus-5[1m]", "revision": "claude-opus-5[1m]",
"tier": "frontier" "tier": "frontier"
},
"quality": "highest",
"verdict": "pass",
"human_reviewed": true,
"references": [
{
"role": "style-anchor",
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
}, },
{ "quality": "highest",
"role": "column-reference", "verdict": "pass",
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd" "human_reviewed": true,
"references": [
{
"role": "style-anchor",
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
},
{
"role": "column-reference",
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
},
{
"role": "bible-character",
"sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e"
},
{
"role": "bible-props",
"sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
}
],
"outputs": [
{
"role": "stage-01-key",
"path": "docs/assets/pantheon/workflow/01-key.png",
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: Ирида у стола, палец на мраморной клавише, лента лежит свёрнутой и ещё не поднялась - шаг читается как готовность, а не как действие. Кисти правильные, текста в кадре нет."
},
{
"role": "stage-02-voice",
"path": "docs/assets/pantheon/workflow/02-voice.png",
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: одна непрерывная золотая лента идёт от губ вправо через весь кадр и расширяется волной. Ленты в воздухе больше нет, радуги нет."
},
{
"role": "stage-03-decode",
"path": "docs/assets/pantheon/workflow/03-decode.png",
"sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: стена за столом сплошная, ни окна, ни арки - сцена закрыта, и это главное в шаге «считает ваш Мак». Лента входит слева и выходит бороздой справа."
},
{
"role": "stage-04-insert",
"path": "docs/assets/pantheon/workflow/04-insert.png",
"sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: борозда таблички залита золотом по всей длине, ленты в воздухе не осталось, Ирида уже отступает - доставка окончена."
}
],
"notes": "Кадры пересняты 07.09.2026: на табличке Ириды золотая звуковая волна вместо резной канавки, как в плашке продукта. Владелец осмотрел серию в смотрелке и принял все кадры; машинная запись вердиктов с SHA-256 - art-review-server, 2026-09-07T20:51:32.453Z. Принято: 01-bible-props, 02-bible-character, 03-hero, 04-emblem, 05-doc-onboarding, 06-doc-contributing, 07-takt-03-decode, 08-takt-04-insert, 09-vstavka-znakomstvo, 10-vstavka-istoriya. Первые две вставки он забраковал словами «скриншот криво встал» и «это не скриншот, это просто иконка»: углы экрана врали на 36 точек, а на экране лежала иконка вместо окна. Переделаны и приняты.",
"human_review": {
"reviewer": "owner",
"at": "2026-09-06T21:22:17Z",
"verdict": "принимаю",
"note": "Владелец открыл четыре кадра серии и принял их дословно словом «принимаю» 07.09.2026."
} }
],
"outputs": [
{
"role": "stage-01-key",
"path": "docs/assets/pantheon/workflow/01-key.png",
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: Ирида у стола, палец на мраморной клавише, лента лежит свёрнутой и ещё не поднялась - шаг читается как готовность, а не как действие. Кисти правильные, текста в кадре нет."
},
{
"role": "stage-02-voice",
"path": "docs/assets/pantheon/workflow/02-voice.png",
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: одна непрерывная золотая лента идёт от губ вправо через весь кадр и расширяется волной. Ленты в воздухе больше нет, радуги нет."
},
{
"role": "stage-03-decode",
"path": "docs/assets/pantheon/workflow/03-decode.png",
"sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: стена за столом сплошная, ни окна, ни арки - сцена закрыта, и это главное в шаге «считает ваш Мак». Лента входит слева и выходит бороздой справа."
},
{
"role": "stage-04-insert",
"path": "docs/assets/pantheon/workflow/04-insert.png",
"sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
"verdict": "pass",
"hard_constraints": {
"column": true,
"ivory-background": true,
"white-marble": true,
"daylight": true,
"blue-gold-accents": true,
"no-dark-background": true,
"deity-symbol": true,
"text-accuracy": true,
"anchor-similarity": true,
"readme-render": true,
"series-coherence": true,
"stage-meaning": true
},
"scorecard": {
"column": 5,
"ivory-background": 5,
"white-marble": 5,
"daylight": 5,
"blue-gold-accents": 5,
"no-dark-background": 5,
"deity-symbol": 5,
"text-accuracy": 5,
"anchor-similarity": 5,
"readme-render": 5,
"series-coherence": 5,
"stage-meaning": 5
},
"notes": "Открыт глазами: борозда таблички залита золотом по всей длине, ленты в воздухе не осталось, Ирида уже отступает - доставка окончена."
}
],
"notes": "Каждый кадр осмотрен агентом попиксельно на соответствие канону: белый мрамор, жезл вестницы, золотая лента, колонна справа, слоновая кость, отсутствие текста. Отметка human_reviewed поставлена по слову владельца, а не решением агента.",
"human_review": {
"reviewer": "owner",
"at": "2026-09-06T21:22:17Z",
"verdict": "принимаю",
"note": "Владелец открыл четыре кадра серии и принял их дословно словом «принимаю» 07.09.2026."
}
} }
+1 -1
View File
@@ -13,5 +13,5 @@ Constraints:
- Every plate rests on the ground and casts a shadow. Nothing hovers. - Every plate rests on the ground and casts a shadow. Nothing hovers.
- The gold ribbon is one continuous piece touching every plate in order, never a chain of separate segments. - The gold ribbon is one continuous piece touching every plate in order, never a chain of separate segments.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: writing of any kind, letters, digits, numbers on the plates, arrows drawn as glyphs, boxes drawn with lines, screens, keyboards, cables, figures, faces, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels Avoid: owl, bird, any animal, writing of any kind, letters, digits, numbers on the plates, arrows drawn as glyphs, boxes drawn with lines, screens, keyboards, cables, figures, faces, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. The plate faces stay empty. Text (verbatim): No readable text, no letters, no digits anywhere in the image. The plate faces stay empty.
+13 -12
View File
@@ -1,14 +1,14 @@
{ {
"schema_version": 1, "schema_version": 1,
"kind": "pantheon-visual-judge", "kind": "pantheon-visual-judge",
"receipt_id": "b55fc1c9-6dff-4cef-ae84-2021511d568f", "receipt_id": "iriz-judge-wave-2026-09-07",
"checked_at": "2026-09-05T09:50:10Z", "checked_at": "2026-09-07T20:26:09Z",
"runtime": "codex", "runtime": "claude",
"tool": "view_image", "tool": "read_image",
"route_id": "codex:view_image:managed-frontier", "route_id": "claude:read_image:frontier",
"model": { "model": {
"id": "provider-managed", "id": "claude-opus-5",
"revision": "provider-managed", "revision": "claude-opus-5[1m]",
"tier": "frontier" "tier": "frontier"
}, },
"quality": "highest", "quality": "highest",
@@ -25,18 +25,18 @@
}, },
{ {
"role": "bible-character", "role": "bible-character",
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af" "sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e"
}, },
{ {
"role": "bible-props", "role": "bible-props",
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152" "sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
} }
], ],
"outputs": [ "outputs": [
{ {
"role": "hero", "role": "hero",
"path": "docs/assets/pantheon/hero.png", "path": "docs/assets/pantheon/hero.png",
"sha256": "ff02cfbef989f040db9e729265b84636ff0a94f5120718d1e94a066bc4381fb4", "sha256": "5c8c42c7758c737b47af8d4702b1f5a96ab54bae94565cdd1bfa4e919b29496d",
"verdict": "pass", "verdict": "pass",
"hard_constraints": { "hard_constraints": {
"column": true, "column": true,
@@ -66,7 +66,7 @@
{ {
"role": "emblem", "role": "emblem",
"path": "docs/assets/pantheon/emblem.png", "path": "docs/assets/pantheon/emblem.png",
"sha256": "daf6fd93f9ab2aa98274b0085be08b1e0a47042873b358cd550639cbdfbc6d47", "sha256": "915d77676dbf1ff062ba13e0f0087f4202570e7bc7aba51c1a766293c660e820",
"verdict": "pass", "verdict": "pass",
"hard_constraints": { "hard_constraints": {
"column": true, "column": true,
@@ -93,5 +93,6 @@
"readme-render": 5 "readme-render": 5
} }
} }
] ],
"notes": "Кадры пересняты 07.09.2026: на табличке Ириды золотая звуковая волна вместо резной канавки, как в плашке продукта. Владелец осмотрел серию в смотрелке и принял все кадры; машинная запись вердиктов с SHA-256 - art-review-server, 2026-09-07T20:51:32.453Z. Принято: 01-bible-props, 02-bible-character, 03-hero, 04-emblem, 05-doc-onboarding, 06-doc-contributing, 07-takt-03-decode, 08-takt-04-insert, 09-vstavka-znakomstvo, 10-vstavka-istoriya. Первые две вставки он забраковал словами «скриншот криво встал» и «это не скриншот, это просто иконка»: углы экрана врали на 36 точек, а на экране лежала иконка вместо окна. Переделаны и приняты."
} }
+1 -1
View File
@@ -13,5 +13,5 @@ Constraints:
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet. - Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
@@ -13,5 +13,5 @@ Constraints:
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet. - Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
@@ -6,12 +6,12 @@ Style/medium: premium restrained 3D marble sculpture render, monumental carving
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light. Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light.
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36 Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
Primary request: the third step - the machine that stands right here does the work. The scene must read as a closed, self-contained room, not as a link to somewhere far away. Primary request: the third step - the machine that stands right here does the work. The scene must read as a closed, self-contained room, not as a link to somewhere far away.
Subject: a low marble table at the centre carries a plain marble slab shaped like a thick tablet, and the gold ribbon of voice enters it from the left and comes out on the right as a carved groove filled with the same gold. Iris stands to the left, one hand resting flat on the slab, the other holding the herald staff. Behind the table a marble wall closes the scene: there is no horizon, no distance, no doorway. Subject: a low marble table at the centre carries a plain marble slab shaped like a thick tablet, and the gold ribbon of voice enters it from the left and comes out on the right as a sound wave of slender upright gold bars, lit along the left half of the slab and still bare marble along the right half. Iris stands to the left, one hand resting flat on the slab, the other holding the herald staff. Behind the table a marble wall closes the scene: there is no horizon, no distance, no doorway.
Constraints: Constraints:
- The wall behind the table is unbroken marble. No window, no arch, no opening of any kind. - The wall behind the table is unbroken marble. No window, no arch, no opening of any kind.
- Everything rests on the ground and casts a shadow. Nothing hovers. - Everything rests on the ground and casts a shadow. Nothing hovers.
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet. - Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
@@ -6,12 +6,12 @@ Style/medium: premium restrained 3D marble sculpture render, monumental carving
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light. Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light.
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36 Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
Primary request: the fourth and last step - the text arrives exactly where it was needed. The scene must read as a delivery completed. Primary request: the fourth and last step - the text arrives exactly where it was needed. The scene must read as a delivery completed.
Subject: the marble writing tablet lies flat on a low marble table at the centre, its single carved groove facing the viewer and now completely filled with muted gold along its whole length. Iris stands to the right of the table, already stepping away, her body turned toward the far edge of the frame, her head still turned back to the tablet, the herald staff in her lowered right hand. The gold ribbon ends inside the groove and nowhere else. Subject: the marble writing tablet lies flat on a low marble table at the centre, its face turned toward the viewer and now carrying a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends, every bar lit muted gold along the whole width. Iris stands to the right of the table, already stepping away, her body turned toward the far edge of the frame, her head still turned back to the tablet, the herald staff in her lowered right hand. The gold ribbon ends in the wave and nowhere else.
Constraints: Constraints:
- The groove is filled edge to edge. No ribbon remains in the air. - The wave runs edge to edge across the tablet face. No ribbon remains in the air.
- Everything rests on the ground and casts a shadow. Nothing hovers. - Everything rests on the ground and casts a shadow. Nothing hovers.
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet. - Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused. - Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
- Preserve the reference style; highest final quality; maximum resolution. - Preserve the reference style; highest final quality; maximum resolution.
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
Text (verbatim): No readable text, no letters, no digits anywhere in the image. Text (verbatim): No readable text, no letters, no digits anywhere in the image.
+170
View File
@@ -0,0 +1,170 @@
name: macOS release draft
on:
workflow_dispatch:
push:
tags:
- 'v*'
# This workflow is inert in the private working repository and in forks.
permissions:
contents: read
concurrency:
group: macos-release
cancel-in-progress: false
defaults:
run:
shell: bash
jobs:
build:
if: github.repository == 'zarubinvibe/iriz' && github.event.repository.visibility == 'public'
# Standard ARM64 runner, not the paid macos-*-large/xlarge variants.
# https://docs.github.com/en/actions/reference/runners/github-hosted-runners
runs-on: macos-15
timeout-minutes: 90
permissions:
contents: read
env:
DEVELOPER_DIR: /Applications/Xcode_16.4.app/Contents/Developer
SMLTLK_SIGN_IDENTITY: '-'
IRIZ_NOTARY_PROFILE: ''
IRIZ_DMG_HEADLESS: '1'
IRIZ_RELEASE_VARIANTS: arm64
outputs:
version: ${{ steps.version.outputs.version }}
source_sha: ${{ steps.version.outputs.source_sha }}
artifact_id: ${{ steps.upload.outputs.artifact-id }}
steps:
- name: Check out the selected commit
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Validate version and Swift 6 toolchain
id: version
run: |
set -euo pipefail
version=$(<RELEASE_VERSION)
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid RELEASE_VERSION'; exit 1; }
if [[ "$GITHUB_REF_TYPE" == tag && "$GITHUB_REF_NAME" != "v$version" ]]; then
echo 'The tag must match RELEASE_VERSION.'
exit 1
fi
[[ "$(uname -m)" == arm64 ]] || { echo 'An ARM64 runner is required.'; exit 1; }
xcodebuild -version
swift_version=$(xcrun swift --version)
printf '%s\n' "$swift_version"
[[ "$swift_version" == *'Swift version 6.'* ]] || { echo 'Swift 6 is required.'; exit 1; }
printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT"
printf 'source_sha=%s\n' "$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- name: Check workflow guards offline
run: ruby scripts/macos_release_workflow_test.rb --selftest
- name: Run tests without parallel test execution
run: swift test --no-parallel --jobs 2
- name: Check packaging and installer failure paths
run: |
bash scripts/make_release_test.sh --selftest
bash scripts/build_app_test.sh --selftest
- name: Build and verify the ad-hoc signed DMG
run: bash scripts/make_release.sh
- name: Verify the exact release files
env:
RELEASE_VERSION: ${{ steps.version.outputs.version }}
working-directory: release/dist
run: |
set -euo pipefail
for file in "iriz-$RELEASE_VERSION-arm64.dmg" iriz-macos-arm64.dmg SHA256SUMS.txt release-manifest.json; do
[[ -f "$file" && ! -L "$file" && -s "$file" ]] || { echo "Missing release file: $file"; exit 1; }
done
shasum -a 256 -c SHA256SUMS.txt
cmp "iriz-$RELEASE_VERSION-arm64.dmg" iriz-macos-arm64.dmg
- name: Keep the four release files
id: upload
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: iriz-${{ steps.version.outputs.version }}-arm64-${{ github.run_id }}-${{ github.run_attempt }}
path: |
release/dist/iriz-${{ steps.version.outputs.version }}-arm64.dmg
release/dist/iriz-macos-arm64.dmg
release/dist/SHA256SUMS.txt
release/dist/release-manifest.json
if-no-files-found: error
compression-level: 0
retention-days: 14
overwrite: false
draft:
needs: build
if: github.repository == 'zarubinvibe/iriz' && github.event.repository.visibility == 'public'
runs-on: ubuntu-24.04
timeout-minutes: 15
# No checkout or repository scripts run with this write token.
permissions:
contents: write
env:
RELEASE_VERSION: ${{ needs.build.outputs.version }}
SOURCE_SHA: ${{ needs.build.outputs.source_sha }}
steps:
- name: Download only this build's artifact
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
artifact-ids: ${{ needs.build.outputs.artifact_id }}
path: release-files
merge-multiple: true
digest-mismatch: error
- name: Verify release metadata and checksums
working-directory: release-files
run: |
set -euo pipefail
[[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]
[[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]
for file in "iriz-$RELEASE_VERSION-arm64.dmg" iriz-macos-arm64.dmg SHA256SUMS.txt release-manifest.json; do
[[ -f "$file" && ! -L "$file" && -s "$file" ]]
done
jq -e --arg version "$RELEASE_VERSION" --arg sha "$SOURCE_SHA" '
.version == $version and .source_sha == $sha and
.source_dirty == false and .notarized == false and
.signing.mode == "ad-hoc" and .signing.identity == "-"
' release-manifest.json
sha256sum --check --strict SHA256SUMS.txt
cmp "iriz-$RELEASE_VERSION-arm64.dmg" iriz-macos-arm64.dmg
- name: Create a new draft only
working-directory: release-files
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: zarubinvibe/iriz
run: |
set -euo pipefail
tag="v$RELEASE_VERSION"
# List all pages, including drafts. Any API failure stops the job.
releases=$(gh api --paginate --slurp "repos/$GH_REPO/releases?per_page=100")
release_exists=$(jq -r --arg tag "$tag" 'any(.[][]; .tag_name == $tag)' <<< "$releases")
if [[ "$release_exists" != false ]]; then
echo "Release $tag already exists; no release or asset was changed."
exit 1
fi
# An existing tag must identify the commit that produced these files.
tags=$(gh api --paginate --slurp "repos/$GH_REPO/tags?per_page=100")
tagged_sha=$(jq -r --arg tag "$tag" '.[][] | select(.name == $tag) | .commit.sha' <<< "$tags")
if [[ -n "$tagged_sha" && "$tagged_sha" != "$SOURCE_SHA" ]]; then
echo "Tag $tag points to a different commit; nothing was changed."
exit 1
fi
gh release create "$tag" \
"iriz-$RELEASE_VERSION-arm64.dmg" iriz-macos-arm64.dmg \
SHA256SUMS.txt release-manifest.json \
--repo "$GH_REPO" --target "$SOURCE_SHA" --draft --latest=false \
--title "iriz $RELEASE_VERSION" \
--notes "Draft for manual review. Apple Silicon / macOS 14+. Ad-hoc signed, not notarized by Apple. Speech models are downloaded separately in the app. Verify the checksums, installation and first-run flow before publishing. Source: $SOURCE_SHA."
printf 'Created draft %s. Publishing and marking Latest require manual review.\n' "$tag" >> "$GITHUB_STEP_SUMMARY"
+1
View File
@@ -8,6 +8,7 @@ prompt_*.md
/catalog /catalog
.landing/ .landing/
.build/ .build/
/release/
build/ build/
*.app *.app
# Граф знаний ЕДЕТ ВМЕСТЕ С ДОМОМ: агент в свежем клоне без него слеп. # Граф знаний ЕДЕТ ВМЕСТЕ С ДОМОМ: агент в свежем клоне без него слеп.
+28 -9
View File
@@ -2,6 +2,14 @@
Speak out loud and the text appears. Your Mac does the decoding, and nothing travels to somebody else's cloud. Speak out loud and the text appears. Your Mac does the decoding, and nothing travels to somebody else's cloud.
[![Download for macOS](https://img.shields.io/badge/Download%20for%20macOS-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
Apple Silicon · macOS 14+ · Model download: about 500 MB
[Install & first dictation](docs/DOWNLOAD.md) · [Release notes](https://github.com/zarubinvibe/iriz/releases/latest)
Self-signed; not notarized by Apple. Intel is not supported by this download.
[Русский](README.ru.md) · [中文](README.zh.md) [Русский](README.ru.md) · [中文](README.zh.md)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Stars](https://img.shields.io/github/stars/zarubinvibe/iriz?style=flat&color=C9A87A)](https://github.com/zarubinvibe/iriz/stargazers) [![Status](https://img.shields.io/badge/status-working-brightgreen.svg)](https://github.com/zarubinvibe/iriz) [![Olympuz](https://img.shields.io/badge/olympuz-family-B8D6EA.svg)](https://github.com/zarubinvibe/athena#olympuz-family) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Stars](https://img.shields.io/github/stars/zarubinvibe/iriz?style=flat&color=C9A87A)](https://github.com/zarubinvibe/iriz/stargazers) [![Status](https://img.shields.io/badge/status-working-brightgreen.svg)](https://github.com/zarubinvibe/iriz) [![Olympuz](https://img.shields.io/badge/olympuz-family-B8D6EA.svg)](https://github.com/zarubinvibe/athena#olympuz-family)
@@ -51,6 +59,9 @@ It does more. It fixes a phrase typed in the wrong keyboard layout. Correct a wo
![Meetings: drop the recording, the minutes land next to it](docs/assets/shots/page-meetings.png) ![Meetings: drop the recording, the minutes land next to it](docs/assets/shots/page-meetings.png)
![Iris at a marble table: the laptop screen carries the first screen of the iriz walkthrough](docs/assets/pantheon/desk-firstrun.png)
## Why It Helps ## Why It Helps
Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not. Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.
@@ -59,6 +70,9 @@ One thing gets in the way. Cloud dictation cleans speech better than anything lo
So here your Mac does the decoding, and the app reaches the network only when you press the button. So here your Mac does the decoding, and the app reaches the network only when you press the button.
![A marble laptop up close: the iriz dictation history window on its screen](docs/assets/pantheon/desk-history.png)
## The Main Advantage ## The Main Advantage
**Main advantage:** your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text. **Main advantage:** your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.
@@ -128,17 +142,21 @@ It goes into the field you were already in: an email, a chat, a terminal. If the
## Quickstart ## Quickstart
You need a Mac on macOS 14 or newer. Building from source also wants Xcode with Swift 6. Three doors from here, any of them works. Download the [macOS DMG](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg), open it, and drag iriz into Applications. This build needs Apple Silicon and macOS 14 or newer. No Xcode or Terminal is needed.
Open iriz and choose Download and install Parakeet in onboarding (about 500 MB). Grant the permissions in the following steps. Wait for readiness, focus a text field, and try your dictation key.
[Installation, model recovery and updates](docs/DOWNLOAD.md). To build from source instead, install Xcode with Swift 6 and use one of the paths below.
```bash ```bash
git clone https://github.com/zarubinvibe/iriz.git ~/iriz git clone https://github.com/zarubinvibe/iriz.git ~/iriz
cd ~/iriz cd ~/iriz
bash install.sh # просто терминал, без единого агента bash install.sh # просто терминал, без единого агента
code . # или откройте папку в редакторе code . # или открой папку в редакторе
claude # или пустите агента: он проведет установку разговором claude # или пусти агента: он проведет установку разговором
``` ```
Do not want to build? Take the ready disk image from Releases: open it, drag the icon onto Applications. No Git? Download [the ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), unpack it, and run the same command inside. First time? Open the project in Claude Code and run `/iriz-setup`: the install goes as a conversation, one question at a time, and nothing is installed without your yes. Without Git, download [the source ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), unpack it and run the same installer there. Or open the project in Claude Code and run `/iriz-setup` for a guided install. It asks before installing.
Never done this before? [The onboarding](docs/ONBOARDING.md) walks the whole first run step by step and says what you see after every command. Never done this before? [The onboarding](docs/ONBOARDING.md) walks the whole first run step by step and says what you see after every command.
@@ -182,10 +200,11 @@ One thing goes out, and only on your button: the one-time speech model download.
Status: working. The author dictates with it every day. Status: working. The author dictates with it every day.
- macOS 14 and newer only. No Windows, no Linux, no iPad. - This download supports Apple Silicon Macs on macOS 14 or newer. Intel is unverified; Windows, Linux and iPad are not supported.
- Automatic layout switching covers the English and Russian pair. - Automatic layout repair covers English and Russian. The interface has Russian, English and Simplified Chinese.
- No notarization yet: a downloaded build opens through a right-click the first time. - The app is self-signed and not notarized by Apple. Read the first-launch security warning in the download guide.
- The universal binary carries an Intel slice, but the author owns no Intel Mac and never verified it there. - The default Parakeet model needs a separate download of about 500 MB and does not recognize Chinese. Other models have different language coverage.
- Updates are manual: download the new DMG, quit iriz and replace the application. Models and local history remain outside the app bundle.
Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOARDING.md), [how to help](CONTRIBUTING.md), [security](SECURITY.md). Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOARDING.md), [how to help](CONTRIBUTING.md), [security](SECURITY.md).
@@ -193,7 +212,7 @@ Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOAR
Useful? Give iriz a star: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). It takes a second and it decides whether other people ever find the project. Useful? Give iriz a star: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). It takes a second and it decides whether other people ever find the project.
Want to change something? The path is short: fork the repository, create a branch, commit your change, push the branch, then open a Pull Request. Do not push directly to `main`; the release gate rejects it. Want to change something? The path is short: fork the repository, create a branch, commit your change, push the branch, then open a Pull Request. Do not push directly to `main`.
Found a problem instead? Open an issue at [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) and say what you ran and what happened. Found a problem instead? Open an issue at [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) and say what you ran and what happened.
+63 -44
View File
@@ -1,6 +1,14 @@
# iriz # iriz
Говорите вслух, на экране появляется текст. Разбирает речь сам Мак, ничего не улетает в чужое облако. Говори вслух, на экране появляется текст. Разбирает речь сам Мак, ничего не улетает в чужое облако.
[![Скачать для macOS](https://img.shields.io/badge/%D0%A1%D0%BA%D0%B0%D1%87%D0%B0%D1%82%D1%8C%20%D0%B4%D0%BB%D1%8F%20macOS-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
Apple Silicon · macOS 14+ · Модель скачивается отдельно: около 500 МБ
[Установка и первая диктовка](docs/DOWNLOAD.ru.md) · [Что изменилось](https://github.com/zarubinvibe/iriz/releases/latest)
Самоподпись, без нотаризации Apple. Этот выпуск не поддерживает Intel.
[English](README.md) · [中文](README.zh.md) [English](README.md) · [中文](README.zh.md)
@@ -37,43 +45,49 @@
## Что это ## Что это
Это программа для Мака, которая печатает за вас, пока вы говорите. Это программа для Мака, которая печатает за тебя, пока ты говоришь.
Работает так. Вы нажимаете одну клавишу, говорите обычным голосом, нажимаете еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет. Работает так. Ты нажимаешь одну клавишу, говоришь обычным голосом, нажимаешь еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет.
Главное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает ваш Мак, и звук с машины не уходит. Главное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает твой Мак, и звук с машины не уходит.
**Почему «iriz».** Ирида у греков — вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Программа делает ровно это: берет сказанное и переносит в текст, ничего не добавляя от себя. **Почему «iriz».** Ирида у греков — вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Программа делает ровно это: берет сказанное и переносит в текст, ничего не добавляя от себя.
![Меню в строке меню: состояние, режимы, диктовка, встречи, история](docs/assets/shots/menu-ru.png) ![Меню в строке меню: состояние, режимы, диктовка, встречи, история](docs/assets/shots/menu-ru.png)
Умеет и другое. Чинит фразу, набранную не в той раскладке. Поправите слово после вставки, и программа предложит запомнить замену. Уберет из речи запинки и повторы. Разберет запись встречи или судебного заседания по голосам, а рядом со звуком положит готовый протокол. Умеет и другое. Чинит фразу, набранную не в той раскладке. Поправишь слово после вставки, и программа предложит запомнить замену. Уберет из речи запинки и повторы. Разберет запись встречи или судебного заседания по голосам, а рядом со звуком положит готовый протокол.
![Встречи: перенеси запись, рядом ляжет протокол](docs/assets/shots/page-meetings.png)
![Ирида за мраморным столом: на экране ноутбука первый экран знакомства iriz](docs/assets/pantheon/desk-firstrun.png)
![Встречи: перенесите запись, рядом ляжет протокол](docs/assets/shots/page-meetings.png)
## Зачем это нужно ## Зачем это нужно
Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает. Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.
Мешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает то, что вы сказали: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем. Мешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает сказанное: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем.
Поэтому тут разбирает Мак, а в сеть программа ходит только по твоей кнопке.
![Мраморный ноутбук крупно: на экране окно истории надиктовок iriz](docs/assets/pantheon/desk-history.png)
Поэтому тут разбирает Мак, а в сеть программа ходит только по вашей кнопке.
## Главное преимущество ## Главное преимущество
**Главное преимущество:** речь разбирает ваш Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте. **Главное преимущество:** речь разбирает твой Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.
**Почему это лучше:** Рубильник стоит внутри библиотеки распознавания и возвращается на место даже когда загрузка падает. Проверяет это не документация: скрипт пинует набор сетевых символов в собранном бинарнике и спрашивает у ядра, есть ли у работающего приложения хоть один сокет. **Почему это лучше:** Рубильник стоит внутри библиотеки распознавания и возвращается на место даже когда загрузка падает. Проверяет это не документация: скрипт пинует набор сетевых символов в собранном бинарнике и спрашивает у ядра, есть ли у работающего приложения хоть один сокет.
## Как это работает ## Как это работает
Нажали клавишу, сказали фразу, нажали еще раз. Текст встает туда, где мигал курсор. Нажимаешь клавишу, говоришь фразу, нажимаешь еще раз. Текст встает туда, где мигал курсор.
Внизу экрана все это время висит стеклянная капля. Пока вы молчите, она маленькая. Заговорили — внутри бежит волна: это и есть ответ на вопрос «слышит ли меня». Внизу экрана все это время висит стеклянная капля. Пока ты молчишь, она маленькая. Заговоришь — внутри бежит волна: это и есть ответ на вопрос «слышит ли меня».
![Плашка на записи: волна внутри стекла](docs/assets/shots/plate-listening-dark.png) ![Плашка на записи: волна внутри стекла](docs/assets/shots/plate-listening-dark.png)
Наведите на нее мышь — капля раскроется в ряд кнопок: запись, промпт, перевод, язык, история, настройки. Язык переключается здесь же, за секунду до того, как заговорить, и ходить за этим в настройки незачем. Наведи на нее мышь — капля раскроется в ряд кнопок: запись, промпт, перевод, язык, история, настройки. Язык переключается здесь же, за секунду до того, как заговорить, и ходить за этим в настройки незачем.
![Плашка под мышью: ряд из шести кнопок](docs/assets/shots/plate-hover-dark.png) ![Плашка под мышью: ряд из шести кнопок](docs/assets/shots/plate-hover-dark.png)
@@ -90,37 +104,37 @@
| Этап | Что происходит | | Этап | Что происходит |
|---|---| |---|---|
| 1. Клавиша | Одна клавиша, и та же самая в любой программе | | 1. Клавиша | Одна клавиша, и та же самая в любой программе |
| 2. Голос | Вы говорите, и плашка показывает, что слышит | | 2. Голос | Ты говоришь, и плашка показывает, что слышит |
| 3. Разбор | Мак превращает сказанное в буквы своим же чипом | | 3. Разбор | Мак превращает сказанное в буквы своим же чипом |
| 4. Текст | Текст встает туда, где мигал курсор | | 4. Текст | Текст встает туда, где мигал курсор |
### Шаг 1: Нажмите свою клавишу ### Шаг 1: Нажмите свою клавишу
По умолчанию это правый Command. Вы нажимаете ее, и больше на Маке менять нечего: ни окна открывать, ни курсор куда-то ставить заранее. Если клавиша у вас занята, поменять ее можно прямо в знакомстве, а не искать в настройках. По умолчанию это правый Command. Ты нажимаешь ее, и больше на Маке менять нечего: ни окна открывать, ни курсор куда-то ставить заранее. Если клавиша у тебя занята, поменять ее можно прямо в знакомстве, а не искать в настройках.
<p align="center"><img src="docs/assets/pantheon/workflow/01-key.png" alt="Этап 1 iriz: нажмите свою клавишу, снятый широким кадром канона Пантеона" width="100%"></p> <p align="center"><img src="docs/assets/pantheon/workflow/01-key.png" alt="Этап 1 iriz: нажми свою клавишу, снятый широким кадром канона Пантеона" width="100%"></p>
**Что получится:** клавиша, которая отвечает и в редакторе, и в почте, и в терминале. **Что получится:** клавиша, которая отвечает и в редакторе, и в почте, и в терминале.
### Шаг 2: Скажите вслух ### Шаг 2: Скажите вслух
Рядом с курсором появляется небольшая плашка, ее волна идет за вашим голосом, и видно, что вас слышат, а не приходится гадать. Звук живет в памяти ровно столько, сколько нужно на разбор, и на диск не попадает. Рядом с курсором появляется небольшая плашка, ее волна идет за твоим голосом, и видно, что тебя слышат, а не приходится гадать. Звук живет в памяти ровно столько, сколько нужно на разбор, и на диск не попадает.
<p align="center"><img src="docs/assets/pantheon/workflow/02-voice.png" alt="Этап 2 iriz: скажите вслух, снятый широким кадром канона Пантеона" width="100%"></p> <p align="center"><img src="docs/assets/pantheon/workflow/02-voice.png" alt="Этап 2 iriz: скажи вслух, снятый широким кадром канона Пантеона" width="100%"></p>
**Что получится:** запись, которая существует секунды и не оставляет следа. **Что получится:** запись, которая существует секунды и не оставляет следа.
### Шаг 3: Мак разбирает сказанное ### Шаг 3: Мак разбирает сказанное
Распознавание идет на Neural Engine вашего Мака: семь секунд речи разбираются примерно за десятую долю секунды. Никуда ничего не отправляется, а пока идет диктовка, загрузчик внутри библиотеки распознавания закрыт рубильником. Распознавание идет на Neural Engine твоего Мака: семь секунд речи разбираются примерно за десятую долю секунды. Никуда ничего не отправляется, а пока идет диктовка, загрузчик внутри библиотеки распознавания закрыт рубильником.
<p align="center"><img src="docs/assets/pantheon/workflow/03-decode.png" alt="Этап 3 iriz: Мак разбирает сказанное, снятый широким кадром канона Пантеона" width="100%"></p> <p align="center"><img src="docs/assets/pantheon/workflow/03-decode.png" alt="Этап 3 iriz: Мак разбирает сказанное, снятый широким кадром канона Пантеона" width="100%"></p>
**Что получится:** расшифровка, которая нигде, кроме вашей машины, не была. **Что получится:** расшифровка, которая нигде, кроме твоей машины, не была.
### Шаг 4: Текст встает в поле ### Шаг 4: Текст встает в поле
Он попадает в то поле, в котором вы и были: письмо, чат, терминал. Если поле его не приняло, плашка раскрывается в панель с целым текстом, и один щелчок кладет его в буфер. Пока вы до него тянетесь, он никуда не денется. Он попадает в исходное поле: письмо, чат, терминал. Если поле его не приняло, плашка раскрывается в панель с целым текстом, и один щелчок кладет его в буфер. Пока ты до него тянешься, он никуда не денется.
<p align="center"><img src="docs/assets/pantheon/workflow/04-insert.png" alt="Этап 4 iriz: текст встает в поле, снятый широким кадром канона Пантеона" width="100%"></p> <p align="center"><img src="docs/assets/pantheon/workflow/04-insert.png" alt="Этап 4 iriz: текст встает в поле, снятый широким кадром канона Пантеона" width="100%"></p>
@@ -128,74 +142,79 @@
## Быстрый старт ## Быстрый старт
Нужен Мак на macOS 14 или новее. Для сборки из исходников еще Xcode со Swift 6. Дверей три, годится любая. [Скачай DMG для macOS](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg), открой и перетащи iriz в Applications. Нужен Мак с Apple Silicon на macOS 14 или новее. Xcode и терминал не нужны.
Открой iriz и нажми «Скачать и установить Parakeet» в знакомстве. На следующих шагах выдай разрешения. Загрузка займет около 500 МБ. Дождись готовности, поставь курсор в текстовое поле и попробуй клавишу диктовки.
[Установка, восстановление модели и обновления](docs/DOWNLOAD.ru.md). Для сборки из исходников нужен Xcode со Swift 6. Ниже команды и другие способы установки.
```bash ```bash
git clone https://github.com/zarubinvibe/iriz.git ~/iriz git clone https://github.com/zarubinvibe/iriz.git ~/iriz
cd ~/iriz cd ~/iriz
bash install.sh # просто терминал, без единого агента bash install.sh # просто терминал, без единого агента
code . # или откройте папку в редакторе code . # или открой папку в редакторе
claude # или пустите агента: он проведет установку разговором claude # или пусти агента: он проведет установку разговором
``` ```
Не хотите собирать - возьмите готовый образ в разделе Releases: открыли, перетащили значок в Applications. Нет Git? Скачайте [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуйте и запустите в нем ту же команду. Первый раз? Откройте проект в Claude Code и запустите `/iriz-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без вашего «да». Нет Git? Скачай [ZIP с исходниками](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуй и запусти в нем тот же установщик. Или открой проект в Claude Code и запусти `/iriz-setup`: агент проведет установку по шагам и спросит перед изменениями.
Делаете это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды. Делаешь это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
**Что получится:** установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока вы не попросите. **Что получится:** установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока ты не попросишь.
## Простое сравнение ## Простое сравнение
| Вариант | Когда подходит | Что получаете | Куда уходит речь | Чинит раскладку | Минус | | Вариант | Когда подходит | Что получаешь | Куда уходит речь | Чинит раскладку | Минус |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| **iriz** | Диктуете рабочее и отдать не можете | Раскладка, местная диктовка, речь в задание | Никуда, разбирает Мак | Да, английский и русский | Русский первым, нотаризации пока нет | | **iriz** | Диктуешь рабочее и отдать не можешь | Раскладка, местная диктовка, речь в задание | Никуда, разбирает Мак | Да, английский и русский | Русский первым, нотаризации пока нет |
| Делать руками | Одна короткая фраза, один раз | Полный контроль над каждой буквой | Никуда | Нет | Длинный текст съедает вечер | | Делать руками | Одна короткая фраза, один раз | Полный контроль над каждой буквой | Никуда | Нет | Длинный текст съедает вечер |
| Punto Switcher | Нужна только раскладка | Годы работы над раскладкой | Никуда | Да | Диктовки нет вовсе | | Punto Switcher | Нужна только раскладка | Годы работы над раскладкой | Никуда | Да | Диктовки нет вовсе |
| Встроенная диктовка macOS | Изредка одна фраза | Уже стоит на машине | В Apple, если не включена офлайн-модель | Нет | Слаба на терминах, задание не собирает | | Встроенная диктовка macOS | Изредка одна фраза | Уже стоит на машине | В Apple, если не включена офлайн-модель | Нет | Слаба на терминах, задание не собирает |
| Wispr Flow и подобные | Сбивчивая речь в гладкий текст | Лучшая чистка речи | На их сервер | Нет | Имена доверителей уезжают вместе с текстом | | Wispr Flow и подобные | Сбивчивая речь в гладкий текст | Лучшая чистка речи | На их сервер | Нет | Имена доверителей уезжают вместе с текстом |
| Местная диктовка на Whisper | Диктовать без облака | Тоже считает у вас | Никуда | Нет | Раскладку не чинит, задание из речи не собирает | | Местная диктовка на Whisper | Диктовать без облака | Тоже считает у тебя | Никуда | Нет | Раскладку не чинит, задание из речи не собирает |
## Простые слова ## Простые слова
| Слово | Простое значение | | Слово | Простое значение |
|---|---| |---|---|
| Repository | Папка проекта, которую хранит и версионирует Git | | Repository | Папка проекта, которую хранит и версионирует Git |
| Terminal | Окно, куда вы вводите команды | | Terminal | Окно, куда ты вводишь команды |
| Command | Одна инструкция компьютеру | | Command | Одна инструкция, которую ты даешь компьютеру |
| Branch | Отдельная линия изменений, которая не трогает `main` | | Branch | Отдельная линия изменений, которая не трогает `main` |
| Pull Request | Просьба проверить ваше изменение и принять его | | Pull Request | Просьба проверить твое изменение и принять его |
| Neural Engine | Отдельный кусок процессора Apple под нейросети: держит распознавание быстрым и не греет машину | | Neural Engine | Отдельный кусок процессора Apple под нейросети: держит распознавание быстрым и не греет машину |
| Модель распознавания | Файлы весов, по которым звук превращается в буквы. Живет у вас на диске, скачивается один раз | | Модель распознавания | Файлы весов, по которым звук превращается в буквы. Живет у тебя на диске, скачивается один раз |
## Безопасность и приватность ## Безопасность и приватность
- Звук нигде не сохраняется: он живет ровно столько, сколько нужно, чтобы разобрать сказанное. - Звук нигде не сохраняется: он живет ровно столько, сколько нужно, чтобы разобрать сказанное.
- Экран не читается. Ни ScreenCaptureKit, ни снимков окон. - Экран не читается. Ни ScreenCaptureKit, ни снимков окон.
- Чужие поля не читаются: доступ нужен, чтобы понять, можно ли в поле писать, а не чтобы забрать оттуда текст. - Чужие поля не читаются: доступ нужен, чтобы понять, можно ли в поле писать, а не чтобы забрать оттуда текст.
- Куда вы диктовали, не записывается. Иначе на диске копились бы метаданные о том, с кем и когда вы работаете. - Место диктовки не записывается. Иначе на диске копились бы метаданные о том, с кем и когда ты работаешь.
- Буфер обмена возвращается на место после вставки. - Буфер обмена возвращается на место после вставки.
- Расшифровки лежат под правами 0700 и 0600 и остаются на вашем диске. - Расшифровки лежат под правами 0700 и 0600 и остаются на твоем диске.
В сеть уходит одно и по вашей кнопке: разовая загрузка модели распознавания. Промпт-режим выключен по умолчанию, и включая его, вы соглашаетесь, что расшифровка уйдет выбранному агенту. В сеть уходит одно и по твоей кнопке: разовая загрузка модели распознавания. Промпт-режим выключен по умолчанию, и включая его, ты соглашаешься, что расшифровка уйдет выбранному агенту.
## Ограничения ## Ограничения
Статус: работает. Автор диктует им каждый день. Статус: работает. Автор диктует им каждый день.
- Только macOS 14 и новее. Ни Windows, ни Linux, ни iPad. - Этот выпуск рассчитан на Apple Silicon и macOS 14 или новее. Intel не проверен; Windows, Linux и iPad не поддерживаются.
- Автопереключение раскладки работает для пары английский и русский. - Раскладка исправляется для пары английский и русский. Интерфейс доступен на русском, английском и китайском.
- Нотаризации пока нет: первый запуск скачанной сборки открывается правым щелчком. - У приложения самоподпись, нотаризации Apple нет. Предупреждение о первом запуске есть в инструкции скачивания.
- Универсальный бинарник содержит срез под Intel, но живого Intel-Мака у автора нет, и проверено это не было. - Модель Parakeet скачивается отдельно, занимает около 500 МБ и не распознает китайскую речь. У других моделей свой набор языков.
- Обновление ручное: скачай новый DMG, закрой iriz и замени приложение. Модели и история хранятся вне его пакета.
Глубже: [пошаговое знакомство с кадрами каждой поверхности](docs/ONBOARDING.ru.md), [как помочь](CONTRIBUTING.ru.md), [безопасность](SECURITY.ru.md). Глубже: [пошаговое знакомство с кадрами каждой поверхности](docs/ONBOARDING.ru.md), [как помочь](CONTRIBUTING.ru.md), [безопасность](SECURITY.ru.md).
## Звезда и вклад ## Звезда и вклад
Пригодилось? Поставьте iriz звезду: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). Это секунда, а от нее зависит, найдут ли проект другие люди. Пригодилось? Поставь iriz звезду: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). Это секунда, а от нее зависит, найдут ли проект другие люди.
Хотите что-то поправить? Путь короткий: сделайте fork, заведите ветку, оформите commit, отправьте push и откройте Pull Request. Не отправляйте push прямо в `main`: релизный gate его отклонит. Хочешь что-то поправить? Путь короткий: сделай fork, заведи ветку, оформи commit, отправь push и открой Pull Request. Не отправляй push прямо в `main`.
Нашли ошибку? Заведите issue на [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) и напишите, что запускали и что получилось. Нашел ошибку? Заведи issue на [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) и напиши, что запускал и что получилось.
<!-- beginner-readme:end --> <!-- beginner-readme:end -->
@@ -212,7 +231,7 @@ claude # или пустите агента: он провед
| проект | Themiz | Многоагентный помощник по российским судебным делам с локальным OCR и советом из пяти юристов. | Ведет российские судебные дела многоагентно, с локальным хранением материалов. | [Репозиторий](https://github.com/zarubinvibe/themiz) · [ZIP](https://github.com/zarubinvibe/themiz/archive/refs/heads/main.zip) | | проект | Themiz | Многоагентный помощник по российским судебным делам с локальным OCR и советом из пяти юристов. | Ведет российские судебные дела многоагентно, с локальным хранением материалов. | [Репозиторий](https://github.com/zarubinvibe/themiz) · [ZIP](https://github.com/zarubinvibe/themiz/archive/refs/heads/main.zip) |
| проект | Zeuz | Фабрика многоагентных workflow: собирает систему с правилами, гейтами, наблюдаемостью и replay. | Собирает многоагентный workflow с правилами, воротами, наблюдаемостью и повтором прогона. | [Репозиторий](https://github.com/zarubinvibe/zeuz) · [ZIP](https://github.com/zarubinvibe/zeuz/archive/refs/heads/main.zip) | | проект | Zeuz | Фабрика многоагентных workflow: собирает систему с правилами, гейтами, наблюдаемостью и replay. | Собирает многоагентный workflow с правилами, воротами, наблюдаемостью и повтором прогона. | [Репозиторий](https://github.com/zarubinvibe/zeuz) · [ZIP](https://github.com/zarubinvibe/zeuz/archive/refs/heads/main.zip) |
| проект | Lynceuz | Собирает доказательства из открытого веба за ноль рублей и честно останавливается, когда безопасные пути кончились. | Собирает доказательства из открытого веба бесплатно и честно останавливается на границе. | [Репозиторий](https://github.com/zarubinvibe/lynceuz) · [ZIP](https://github.com/zarubinvibe/lynceuz/archive/refs/heads/main.zip) | | проект | Lynceuz | Собирает доказательства из открытого веба за ноль рублей и честно останавливается, когда безопасные пути кончились. | Собирает доказательства из открытого веба бесплатно и честно останавливается на границе. | [Репозиторий](https://github.com/zarubinvibe/lynceuz) · [ZIP](https://github.com/zarubinvibe/lynceuz/archive/refs/heads/main.zip) |
| проект | Iriz | Диктовка в строке меню macOS: речь разбирается на вашем Маке, раскладка чинится сама, надиктовка превращается в готовое задание для агента. | Диктовка в строке меню macOS: речь разбирается на вашем Маке, раскладка чинится сама. | [Репозиторий](https://github.com/zarubinvibe/iriz) · [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip) | | проект | Iriz | Диктовка в строке меню macOS: речь разбирается на твоем Маке, раскладка чинится сама, надиктовка превращается в готовое задание для агента. | Диктовка в строке меню macOS: речь разбирается на твоем Маке, раскладка чинится сама. | [Репозиторий](https://github.com/zarubinvibe/iriz) · [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip) |
| проект | Mantoz | Ставит идею перед пятьюстами людьми, которых не существует, и показывает, как ответила каждая группа. | Ставит идею перед сотнями сгенерированных людей до того, как ее увидят живые. | [Репозиторий](https://github.com/zarubinvibe/mantoz) · [ZIP](https://github.com/zarubinvibe/mantoz/archive/refs/heads/main.zip) | | проект | Mantoz | Ставит идею перед пятьюстами людьми, которых не существует, и показывает, как ответила каждая группа. | Ставит идею перед сотнями сгенерированных людей до того, как ее увидят живые. | [Репозиторий](https://github.com/zarubinvibe/mantoz) · [ZIP](https://github.com/zarubinvibe/mantoz/archive/refs/heads/main.zip) |
| проект | Koiz | Одна база уроков на все проекты. Каждый провал доводится до причины, и причина висит открытой, пока ее не закроет хук, ворота или тест. | Держит одну базу уроков на все проекты и требует механизм, а не обещание. | [Репозиторий](https://github.com/zarubinvibe/koiz) · [ZIP](https://github.com/zarubinvibe/koiz/archive/refs/heads/main.zip) | | проект | Koiz | Одна база уроков на все проекты. Каждый провал доводится до причины, и причина висит открытой, пока ее не закроет хук, ворота или тест. | Держит одну базу уроков на все проекты и требует механизм, а не обещание. | [Репозиторий](https://github.com/zarubinvibe/koiz) · [ZIP](https://github.com/zarubinvibe/koiz/archive/refs/heads/main.zip) |
<!-- pantheon-family:end --> <!-- pantheon-family:end -->
+28 -11
View File
@@ -2,6 +2,14 @@
你说出来,屏幕上就有字。识别由你自己的 Mac 完成,声音不会上传到别人的云。 你说出来,屏幕上就有字。识别由你自己的 Mac 完成,声音不会上传到别人的云。
[![下载 macOS 版](https://img.shields.io/badge/%E4%B8%8B%E8%BD%BD%20macOS%20%E7%89%88-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
Apple Silicon · macOS 14+ · 语音模型需另行下载,约 500 MB
[安装与首次听写](docs/DOWNLOAD.zh.md) · [更新说明](https://github.com/zarubinvibe/iriz/releases/latest)
应用使用自签名,尚未通过 Apple 公证。此下载不支持 Intel。
[English](README.md) · [Русский](README.ru.md) [English](README.md) · [Русский](README.ru.md)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Stars](https://img.shields.io/github/stars/zarubinvibe/iriz?style=flat&color=C9A87A)](https://github.com/zarubinvibe/iriz/stargazers) [![Status](https://img.shields.io/badge/status-working-brightgreen.svg)](https://github.com/zarubinvibe/iriz) [![Olympuz](https://img.shields.io/badge/olympuz-family-B8D6EA.svg)](https://github.com/zarubinvibe/athena#olympuz-family) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Stars](https://img.shields.io/github/stars/zarubinvibe/iriz?style=flat&color=C9A87A)](https://github.com/zarubinvibe/iriz/stargazers) [![Status](https://img.shields.io/badge/status-working-brightgreen.svg)](https://github.com/zarubinvibe/iriz) [![Olympuz](https://img.shields.io/badge/olympuz-family-B8D6EA.svg)](https://github.com/zarubinvibe/athena#olympuz-family)
@@ -51,6 +59,9 @@
![会议:把录音拖进来,纪要会放在旁边](docs/assets/shots/page-meetings.png) ![会议:把录音拖进来,纪要会放在旁边](docs/assets/shots/page-meetings.png)
![伊里斯坐在大理石桌前,笔记本屏幕上是 iriz 引导的第一屏](docs/assets/pantheon/desk-firstrun.png)
## 它解决什么问题 ## 它解决什么问题
靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。 靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。
@@ -59,6 +70,9 @@
所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。 所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。
![近处的大理石笔记本,屏幕上是 iriz 的口述记录窗口](docs/assets/pantheon/desk-history.png)
## 最大的优势 ## 最大的优势
**最大的优势:** 识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。 **最大的优势:** 识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。
@@ -128,17 +142,21 @@
## 快速开始 ## 快速开始
需要一台 macOS 14 或更新的 Mac,还有三项系统权限:麦克风、辅助功能、输入监控。从源码构建另外要 Xcode 和 Swift 6。接下来有三条路,走哪条都行。 [下载 macOS DMG](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg),打开后将 iriz 拖入 Applications。需要 Apple Silicon Mac 和 macOS 14 或更新版本,不需要 Xcode 或终端。
打开 iriz,在引导中点击「下载并安装 Parakeet」(约 500 MB),然后按后续步骤授予权限。等模型就绪,将光标放入文本框,再试用听写快捷键。
[安装、恢复模型和更新](docs/DOWNLOAD.zh.md)。从源码构建另需 Xcode 和 Swift 6,命令及其他安装方式见下方。
```bash ```bash
git clone https://github.com/zarubinvibe/iriz.git ~/iriz git clone https://github.com/zarubinvibe/iriz.git ~/iriz
cd ~/iriz cd ~/iriz
bash install.sh # просто терминал, без единого агента bash install.sh # просто терминал, без единого агента
code . # или откройте папку в редакторе code . # или открой папку в редакторе
claude # или пустите агента: он проведет установку разговором claude # или пусти агента: он проведет установку разговором
``` ```
不想构建?到 Releases 拿现成的磁盘映像:打开,把图标拖进 Applications。没有 Git?下载 [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip),解压后在里面执行同一条命令。第一次用?在 Claude Code 里打开项目并运行 `/iriz-setup`:安装以对话的方式进行,一次问一个问题,没有你点头不会装任何东西。 没有 Git?下载[源码 ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip),解压后运行同一个安装脚本。也可以在 Claude Code 中打开项目并运行 `/iriz-setup`,让智能体逐步引导安装,每次安装前都会先询问。
第一次做这件事?[上手引导](docs/ONBOARDING.zh.md) 会一步一步带你走完第一次运行,并写清楚每条命令之后你会看到什么。 第一次做这件事?[上手引导](docs/ONBOARDING.zh.md) 会一步一步带你走完第一次运行,并写清楚每条命令之后你会看到什么。
@@ -182,12 +200,11 @@ claude # или пустите агента: он провед
状态:可用。作者每天都在用它口述。 状态:可用。作者每天都在用它口述。
- 语音模型认十八种欧洲语言,中文不在其中:中文口述它听不懂。 - 此下载面向 Apple Silicon 和 macOS 14 及以上。Intel 未经验证;不支持 Windows、Linux 或 iPad。
- 自动换键盘布局只管英语和俄语这一对,对拼音、五笔这类中文输入法不适用。 - 自动修正键盘布局只支持英语和俄语。界面支持俄语、英语和简体中文。
- 应用界面目前只有俄文,说明文档才有中文。 - 应用使用自签名,尚未通过 Apple 公证。首次启动的安全提示见下载指南。
- 只支持 macOS 14 及以上。没有 Windows,没有 Linux,也没有 iPad。 - 默认 Parakeet 模型需要单独下载,约 500 MB,不识别中文语音。其他模型支持的语言不同。
- 还没有做公证:下载来的构建第一次打开要用右键的“打开”。 - 更新需手动完成:下载新 DMG,退出 iriz,再替换应用。模型与历史记录保存在应用包之外。
- 通用二进制里带着 Intel 那一片,可是作者手上没有 Intel 的 Mac,从来没在上面验过。
更深入:[逐步上手,每个界面都有截图](docs/ONBOARDING.zh.md)、[如何参与](CONTRIBUTING.zh.md)、[安全](SECURITY.zh.md)。 更深入:[逐步上手,每个界面都有截图](docs/ONBOARDING.zh.md)、[如何参与](CONTRIBUTING.zh.md)、[安全](SECURITY.zh.md)。
@@ -195,7 +212,7 @@ claude # или пустите агента: он провед
觉得有用?给 iriz 点亮星标:[https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz)。这只要一秒,却决定别人能不能找到这个项目。 觉得有用?给 iriz 点亮星标:[https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz)。这只要一秒,却决定别人能不能找到这个项目。
想改点什么?流程很短:先 fork 仓库,建一个分支 branch,提交 commit,推送 push,然后开一个 Pull Request。请不要直接向 `main` 推送,发布闸门会拒绝。 想改点什么?流程很短:先 fork 仓库,建一个分支 branch,提交 commit,推送 push,然后开一个 Pull Request。请不要直接向 `main` 推送变更。
发现问题?到 [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) 开一个 issue,写清楚你运行了什么、发生了什么。 发现问题?到 [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) 开一个 issue,写清楚你运行了什么、发生了什么。
+1
View File
@@ -0,0 +1 @@
0.2.1
+34 -6
View File
@@ -519,6 +519,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private lazy var firstRun: FirstRunWindowController = { private lazy var firstRun: FirstRunWindowController = {
let controller = FirstRunWindowController() let controller = FirstRunWindowController()
controller.model.openAgentSettings = { [weak self] in
self?.openSettings(page: .prompt)
}
controller.model.onSpeechModelInstalled = { [weak self] in
_ = self?.dictationController.prepareAfterModelInstallation()
}
// Проба голосом идёт ТЕМ ЖЕ путём, что и обычная диктовка: кнопка // Проба голосом идёт ТЕМ ЖЕ путём, что и обычная диктовка: кнопка
// зовёт тот же обработчик, что и клавиша. Иначе знакомство показывало // зовёт тот же обработчик, что и клавиша. Иначе знакомство показывало
// бы не тот продукт, который человеку достанется. // бы не тот продукт, который человеку достанется.
@@ -649,12 +655,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// //
// Приглашение НЕ повторяется тем, кто уже прошёл этот путь руками: // Приглашение НЕ повторяется тем, кто уже прошёл этот путь руками:
// решение целиком в firstRunShouldShow. // решение целиком в firstRunShouldShow.
let modelInstalled = speechModelCacheExists(for: DictationSettings.shared.speechEngine)
if !interactive, if !interactive,
firstRunShouldShow(defaults: .standard, firstRunShouldShow(defaults: .standard,
permissionsGranted: acc && inp, permissionsGranted: acc && inp,
modelInstalled: speechModelCacheExists(for: .multilingualV3)) { modelInstalled: modelInstalled) {
rslog("First run: showing the welcome window") rslog("First run: showing the welcome window")
firstRun.show() if !modelInstalled && UserDefaults.standard.bool(forKey: FIRST_RUN_COMPLETED_KEY) {
firstRun.showModelSetup()
} else {
firstRun.show()
}
return return
} }
@@ -1182,6 +1193,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
/// Окно живёт столько же, сколько приложение: пересоздавать его на каждый показ — /// Окно живёт столько же, сколько приложение: пересоздавать его на каждый показ —
/// значит терять несохранённую запись хоткея и позицию окна. /// значит терять несохранённую запись хоткея и позицию окна.
private var settingsWindow: NSWindow? private var settingsWindow: NSWindow?
private let settingsNavigation = SettingsNavigation()
/// Открыть знакомство заново из меню. /// Открыть знакомство заново из меню.
/// Идёт ли запись встречи. Меню спрашивает, чтобы назвать строку словом /// Идёт ли запись встречи. Меню спрашивает, чтобы назвать строку словом
@@ -1203,7 +1215,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
firstRun.show() firstRun.show()
} }
func openSettings(page: SettingsPage = .keys) { func showSpeechModelSetup() {
firstRun.showModelSetup()
}
func recoverDictation() {
if !menuState.microphoneOK {
firstRun.showMicrophoneSetup()
} else if menuState.dictationRecoveryNeedsPermissions {
recheckPermissions()
} else {
showSpeechModelSetup()
}
}
func openSettings(page: SettingsPage? = nil) {
if let page { settingsNavigation.page = page }
if let window = settingsWindow { if let window = settingsWindow {
NSApplication.shared.activate(ignoringOtherApps: true) NSApplication.shared.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(nil) window.makeKeyAndOrderFront(nil)
@@ -1211,7 +1238,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
} }
// Окно собирает общая фабрика: прибор снимает ровно это окно, а не // Окно собирает общая фабрика: прибор снимает ровно это окно, а не
// свою копию с другими флагами. // свою копию с другими флагами.
let window = makeIrizSettingsWindow(page: page) let window = makeIrizSettingsWindow(navigation: settingsNavigation,
openSpeechModelSetup: { [weak self] in
self?.showSpeechModelSetup()
})
window.center() window.center()
settingsWindow = window settingsWindow = window
@@ -1238,5 +1268,3 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
NSApplication.shared.terminate(nil) NSApplication.shared.terminate(nil)
} }
} }
+39 -11
View File
@@ -9,9 +9,8 @@
// следующего переименования кнопки. Здесь кадры собираются из ТЕХ ЖЕ видов, // следующего переименования кнопки. Здесь кадры собираются из ТЕХ ЖЕ видов,
// которыми живёт продукт, и пересобираются одной командой. // которыми живёт продукт, и пересобираются одной командой.
// //
// Язык переключается настройкой, той же, которую владелец меняет в окне: другой // Язык подставляется в штатный поиск настроек через volatile domain: строки
// дороги нет и быть не должно - прибор обязан снимать то, что увидит человек, а // остаются продуктовыми, а пользовательская настройка на диске не меняется.
// не свою параллельную сборку строк.
import AppKit import AppKit
import IrizCore import IrizCore
import IrizDictate import IrizDictate
@@ -34,12 +33,15 @@ private struct DocShot {
func captureDocShots(to directory: URL, appDelegate: AppDelegate) throws -> [URL] { func captureDocShots(to directory: URL, appDelegate: AppDelegate) throws -> [URL] {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o755]) attributes: [.posixPermissions: 0o755])
let previous = irizLanguageChoice() let defaults = UserDefaults.standard
defer { setIrizLanguageChoice(previous) } let previous = defaults.volatileDomain(forName: UserDefaults.argumentDomain)
defer { defaults.setVolatileDomain(previous, forName: UserDefaults.argumentDomain) }
var written: [URL] = [] var written: [URL] = []
for language in [IrizLanguage.ru, .en, .zh] { for language in [IrizLanguage.ru, .en, .zh] {
setIrizLanguageChoice(language) var arguments = previous
arguments[IRIZ_LANGUAGE_KEY] = language.rawValue
defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain)
let tag = language.rawValue let tag = language.rawValue
// Настройки: живое окно со стеклом, страница клавиш - её открывают первой. // Настройки: живое окно со стеклом, страница клавиш - её открывают первой.
@@ -140,12 +142,38 @@ private func docShots(appDelegate: AppDelegate) -> [DocShot] {
view: dictationHistoryShotView(.list)), view: dictationHistoryShotView(.list)),
DocShot(name: "rescue", width: 620, height: 520, DocShot(name: "rescue", width: 620, height: 520,
view: dictationHistoryShotView(.rescue)), view: dictationHistoryShotView(.rescue)),
// Знакомство: единственная поверхность, которая переведена целиком. ] + docFirstRunShots()
// Остальные пока показывают русский на любом выбранном языке - у них }
// нет ни одного вызова `L()`, и это честно названо в документации.
DocShot(name: "firstrun", width: 620, height: 520, /// Установка в кадре — заданное состояние, без загрузки, разрешений и записи
view: AnyView(FirstRunView(model: FirstRunModel()))), /// настроек. Размер совпадает с FirstRunView: прежние 620×520 обрезали окно.
@MainActor
private func docFirstRunShots() -> [DocShot] {
let scenes: [(name: String, installed: Bool, phase: SpeechModelInstallPhase?)] = [
("firstrun", false, nil),
("firstrun-model-missing", false, nil),
("firstrun-model-downloading", false, .downloading(0.42)),
("firstrun-model-failed", false, .failed(speechModelInstallFailureMessage(for: URLError(.notConnectedToInternet)))),
("firstrun-model-ready", true, nil),
] ]
return scenes.map { scene in
let defaults = UserDefaults(suiteName: "iriz.docshots.\(UUID().uuidString)")!
// Registration domain живёт в памяти. NSArgumentDomain общий для
// процесса: его замена здесь стирала язык, выбранный съёмкой выше.
defaults.register(defaults: [
"ru.smltlk.transcriptCorrectionsSeeded": true,
"speech_engine_v1": SpeechModelProfile.multilingualV3.rawValue,
])
let model = FirstRunModel(defaults: defaults,
settings: DictationSettings(defaults: defaults),
refreshSystemState: false,
modelProbe: { _ in scene.installed })
model.refreshModelAvailability()
if scene.name != "firstrun" { model.showModelSetup() }
if let phase = scene.phase { model.installationDidProgress(phase) }
return DocShot(name: scene.name, width: 640, height: 560,
view: AnyView(FirstRunView(model: model)))
}
} }
/// Рабочее состояние меню: модель готова, история не пуста. Аварийные состояния /// Рабочее состояние меню: модель готова, история не пуста. Аварийные состояния
@@ -7,6 +7,7 @@
// Ничего не выбрать - нормальный исход. Диктовка и раскладка работают без // Ничего не выбрать - нормальный исход. Диктовка и раскладка работают без
// агента, и шаг об этом говорит прямо, а не намекает. // агента, и шаг об этом говорит прямо, а не намекает.
import SwiftUI import SwiftUI
import IrizCore
struct FirstRunAgentConnect: View { struct FirstRunAgentConnect: View {
@ObservedObject var model: FirstRunModel @ObservedObject var model: FirstRunModel
@@ -36,6 +37,15 @@ struct FirstRunAgentConnect: View {
} }
.frame(maxHeight: 150) .frame(maxHeight: 150)
} }
if let error = model.agentConnectionError {
Text(error)
.font(.system(size: 12.5))
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: 430)
Button(L("firstrun.agentSettings", "Настройки агента…")) { model.openAgentSettings?() }
.modifier(FirstRunTrialButtonStyle())
}
} }
.onAppear { model.refreshAgents() } .onAppear { model.refreshAgents() }
} }
+121 -15
View File
@@ -38,6 +38,7 @@ final class FirstRunModel: ObservableObject {
/// Модель на диске. Читается живьём при каждом обновлении разрешений: она /// Модель на диске. Читается живьём при каждом обновлении разрешений: она
/// могла приехать и до знакомства. /// могла приехать и до знакомства.
@Published private(set) var modelInstalled = false @Published private(set) var modelInstalled = false
var onSpeechModelInstalled: (() -> Void)?
/// Агенты, которые уже стоят на этом Маке. Ищутся на диске, а не /// Агенты, которые уже стоят на этом Маке. Ищутся на диске, а не
/// спрашиваются у человека: спросить «где у тебя лежит codex» значит /// спрашиваются у человека: спросить «где у тебя лежит codex» значит
@@ -45,6 +46,8 @@ final class FirstRunModel: ObservableObject {
@Published private(set) var agents: [FirstRunAgent] = [] @Published private(set) var agents: [FirstRunAgent] = []
/// Кто выбран. nil - никто, и это нормальный исход шага. /// Кто выбран. nil - никто, и это нормальный исход шага.
@Published private(set) var connectedAgentID: String? @Published private(set) var connectedAgentID: String?
@Published private(set) var agentConnectionError: String?
var openAgentSettings: (() -> Void)?
/// Перевод включён. Отдельно от подключения агента: агент нужен обоим /// Перевод включён. Отдельно от подключения агента: агент нужен обоим
/// режимам, но включать их за человека нельзя. /// режимам, но включать их за человека нельзя.
@Published private(set) var translationEnabled = false @Published private(set) var translationEnabled = false
@@ -95,19 +98,68 @@ final class FirstRunModel: ObservableObject {
} }
private let defaults: UserDefaults private let defaults: UserDefaults
private let settings: DictationSettings
private let modelProbe: (SpeechModelProfile) -> Bool
private var poll: Timer? private var poll: Timer?
/// Что сделать, когда знакомство кончилось. /// Что сделать, когда знакомство кончилось.
var onFinish: (() -> Void)? var onFinish: (() -> Void)?
init(defaults: UserDefaults = .standard) { init(defaults: UserDefaults = .standard,
settings: DictationSettings = .shared,
refreshSystemState: Bool = true,
modelProbe: @escaping (SpeechModelProfile) -> Bool = speechModelCacheExists) {
self.defaults = defaults self.defaults = defaults
refreshPermissions() self.settings = settings
refreshHotkeyLabel() self.modelProbe = modelProbe
refreshTranslationHotkeyLabel() if refreshSystemState {
refreshPermissions()
refreshHotkeyLabel()
refreshTranslationHotkeyLabel()
}
} }
var canGoBack: Bool { firstRunPreviousStep(before: step) != nil } var canGoBack: Bool { firstRunPreviousStep(before: step) != nil }
var isLastStep: Bool { firstRunNextStep(after: step) == nil } var isLastStep: Bool { firstRunNextStep(after: step) == nil }
var selectedSpeechModel: SpeechModelProfile { settings.speechEngine }
var selectedSpeechModelTitle: String { selectedSpeechModel.shortName }
var modelIsReady: Bool {
modelInstalled && (installPhase == nil || installPhase == .finished)
}
var isInstallingModel: Bool {
switch installPhase {
case .downloading, .compiling: true
default: false
}
}
var modelInstallIsPrimaryAction: Bool {
step == .model && !modelIsReady && !isInstallingModel
}
var nextButtonTitle: String {
if isLastStep { return FirstRunCopy.done }
if modelInstallIsPrimaryAction {
return L("firstrun.model.installLater", "Скачать позже")
}
return FirstRunCopy.next
}
func refreshModelAvailability() {
modelInstalled = modelProbe(settings.speechEngine)
}
func prepareForPresentation() {
refreshModelAvailability()
if !modelInstalled, defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) {
showModelSetup()
}
}
func showModelSetup() {
step = .model
}
func showMicrophoneSetup() {
step = .microphone
}
func goNext() { func goNext() {
guard firstRunCanAdvance(from: step) else { return } guard firstRunCanAdvance(from: step) else { return }
@@ -159,22 +211,53 @@ final class FirstRunModel: ObservableObject {
/// Начать установку модели. Идёт в фоне: пока она едет, человек проходит /// Начать установку модели. Идёт в фоне: пока она едет, человек проходит
/// разрешения, и время не тратится дважды. /// разрешения, и время не тратится дважды.
func installModel() { func installModel() {
guard !SpeechModelInstaller.shared.isRunning else { return } guard !SpeechModelInstaller.shared.isRunning else {
installationWasRefused(.alreadyRunning)
return
}
installPhase = .downloading(0) installPhase = .downloading(0)
Task { @MainActor [weak self] in Task { @MainActor [weak self] in
guard let self else { return } guard let self else { return }
await SpeechModelInstaller.shared.install(dictating: self.isRecording) { phase in let refusal = await SpeechModelInstaller.shared.install(dictating: self.isRecording) { phase in
Task { @MainActor in self.installationDidProgress(phase)
self.installPhase = phase
if case .finished = phase { self.modelInstalled = true }
}
} }
if let refusal { self.installationWasRefused(refusal) }
} }
} }
func installationDidProgress(_ phase: SpeechModelInstallPhase) {
if case .finished = phase {
installationDidFinish()
} else {
installPhase = phase
}
}
func installationWasRefused(_ refusal: SpeechModelInstallRefusal) {
switch refusal {
case .alreadyInstalled:
installationDidFinish()
case .alreadyRunning:
installPhase = .failed(L("firstrun.modelAlreadyDownloading", "Модель уже скачивается. Дождись окончания установки."))
case .dictationBusy:
installPhase = .failed(L("firstrun.modelInstallWhileRecording", "Сначала закончи запись, затем повтори установку модели."))
}
}
func installationDidFinish() {
guard installPhase != .finished || !modelInstalled || settings.speechEngine != .multilingualV3 else { return }
settings.speechEngine = .multilingualV3
modelInstalled = true
installPhase = .finished
NotificationCenter.default.post(name: speechModelDidInstallNotification,
object: SpeechModelProfile.multilingualV3)
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
object: settings)
onSpeechModelInstalled?()
}
/// Найти агентов на диске и вспомнить, кто выбран. /// Найти агентов на диске и вспомнить, кто выбран.
func refreshAgents() { func refreshAgents() {
let settings = DictationSettings.shared
agents = PromptAgentCatalog.identifiers.compactMap { id in agents = PromptAgentCatalog.identifiers.compactMap { id in
guard let adapter = PromptAgentCatalog.adapter(id: id, customArguments: []) else { return nil } guard let adapter = PromptAgentCatalog.adapter(id: id, customArguments: []) else { return nil }
// Свой CLI без пути искать негде: он и есть «введи путь руками», // Свой CLI без пути искать негде: он и есть «введи путь руками»,
@@ -190,19 +273,28 @@ final class FirstRunModel: ObservableObject {
/// Подключить агента: выбрать его и включить режим задания. Включение /// Подключить агента: выбрать его и включить режим задания. Включение
/// сказано вслух на самом шаге - молча уводить речь наружу нельзя. /// сказано вслух на самом шаге - молча уводить речь наружу нельзя.
func connectAgent(_ id: String) { func connectAgent(_ id: String) {
let settings = DictationSettings.shared guard let adapter = PromptAgentCatalog.adapter(id: id) else { return }
guard !adapter.requiresModel || !settings.promptAgentModel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
agentConnectionError = Lf("firstrun.agentModelRequired", "Для %@ выбери модель в настройках промпт-режима, затем подключи агента здесь.", adapter.displayName)
return
}
settings.promptAgentID = id settings.promptAgentID = id
settings.promptModeEnabled = true settings.promptModeEnabled = true
connectedAgentID = id connectedAgentID = id
agentConnectionError = nil
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
object: settings)
} }
func enableTranslation() { func enableTranslation() {
DictationSettings.shared.translationModeEnabled = true settings.translationModeEnabled = true
translationEnabled = true translationEnabled = true
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
object: settings)
} }
func refreshPermissions() { func refreshPermissions() {
modelInstalled = speechModelCacheExists(for: .multilingualV3) refreshModelAvailability()
refreshAgents() refreshAgents()
var next: [FirstRunPermission: Bool] = [:] var next: [FirstRunPermission: Bool] = [:]
for permission in FirstRunPermission.allCases { for permission in FirstRunPermission.allCases {
@@ -231,7 +323,10 @@ final class FirstRunModel: ObservableObject {
/// Проба голосом. Идёт тем же путём, что и обычная диктовка. /// Проба голосом. Идёт тем же путём, что и обычная диктовка.
func toggleTrial() { func toggleTrial() {
isRecording.toggle() guard modelIsReady else {
showModelSetup()
return
}
toggleDictation?() toggleDictation?()
} }
@@ -269,7 +364,18 @@ final class FirstRunWindowController: NSObject, NSWindowDelegate {
private var window: NSWindow? private var window: NSWindow?
let model = FirstRunModel() let model = FirstRunModel()
func showModelSetup() {
model.showModelSetup()
show()
}
func showMicrophoneSetup() {
show()
model.showMicrophoneSetup()
}
func show() { func show() {
model.prepareForPresentation()
// Пока знакомство открыто, приложение перестаёт быть невидимкой из // Пока знакомство открыто, приложение перестаёт быть невидимкой из
// строки меню. Без этого у окна нет ни значка в Dock, ни места в // строки меню. Без этого у окна нет ни значка в Dock, ни места в
// Cmd-Tab: человек уходит в Системные настройки, окно проваливается за // Cmd-Tab: человек уходит в Системные настройки, окно проваливается за
+11 -9
View File
@@ -29,7 +29,7 @@ enum FirstRunCopy {
/// Подпись у стрелки. Говорит, ЧТО случится от нажатия, а не «нажмите /// Подпись у стрелки. Говорит, ЧТО случится от нажатия, а не «нажмите
/// кнопку»: человек и так видит кнопку, ему нужна причина. /// кнопку»: человек и так видит кнопку, ему нужна причина.
static var hintModel: String { L("firstrun.hintModel", "нажми сюда, качать примерно пять минут") } static var hintModel: String { L("firstrun.hintModel", "Нажми кнопку ниже. iriz сам скачает и установит модель.") }
static var hintMicrophone: String { L("firstrun.hintMicrophone", "нажми сюда") } static var hintMicrophone: String { L("firstrun.hintMicrophone", "нажми сюда") }
static var hintAccessibility: String { L("firstrun.hintAccessibility", "нажми сюда, откроются настройки системы") } static var hintAccessibility: String { L("firstrun.hintAccessibility", "нажми сюда, откроются настройки системы") }
static var hintInputMonitoring: String { L("firstrun.hintInputMonitoring", "нажми сюда, откроются настройки системы") } static var hintInputMonitoring: String { L("firstrun.hintInputMonitoring", "нажми сюда, откроются настройки системы") }
@@ -64,7 +64,8 @@ enum FirstRunCopy {
title: L("firstrun.welcome.title", "Ты говоришь, я печатаю"), title: L("firstrun.welcome.title", "Ты говоришь, я печатаю"),
body: L("firstrun.welcome.body", "Нажми клавишу, скажи фразу, нажми еще раз. Текст появится там, где стоял " body: L("firstrun.welcome.body", "Нажми клавишу, скажи фразу, нажми еще раз. Текст появится там, где стоял "
+ "курсор: в письме, в чате, в терминале."), + "курсор: в письме, в чате, в терминале."),
note: L("firstrun.welcome.note", "Все считается прямо на твоем Маке. Ни звук, ни текст никуда не отправляются.") note: L("firstrun.welcome.note", "Перед первой диктовкой скачаем модель распознавания: следующий шаг покажет кнопку установки. "
+ "После этого речь будет распознаваться на твоём Маке, без интернета.")
) } ) }
static var whereItLives: Step { Step( static var whereItLives: Step { Step(
@@ -77,13 +78,14 @@ enum FirstRunCopy {
) } ) }
static var model: Step { Step( static var model: Step { Step(
title: L("firstrun.model.title", "Скачаем распознавание"), title: L("firstrun.model.title", "Установи распознавание речи"),
body: L("firstrun.model.body", "Речь я разбираю прямо у тебя на Маке, без интернета. Для этого нужна модель: " body: L("firstrun.model.body", "Без модели диктовка не работает. Кнопка ниже скачает Parakeet, "
+ "полгигабайта, качается один раз."), + "установит его в нужную папку и выберет для распознавания."),
note: L("firstrun.model.note", "В образе её нет намеренно: модель обновляется чаще, чем сам iriz. " note: L("firstrun.model.note", "Скачается около 500 МБ. Нужны интернет и свободное место на диске. "
+ "Клади её отдельно: иначе вместе с программой приедет устаревшая.\n\n" + "Скорость зависит от соединения; ход установки появится здесь. "
+ "Пока она скачивается, продолжай: разрешения можно выдать прямо сейчас."), + "Файлы вручную искать и переносить не нужно.\n\n"
action: L("firstrun.model.action", "Скачать модель") + "Пока модель скачивается, можно перейти к разрешениям. Диктовку попробуем после установки."),
action: L("firstrun.model.action", "Скачать и установить Parakeet")
) } ) }
static var modelReady: String { L("firstrun.modelReady", "Модель на месте") } static var modelReady: String { L("firstrun.modelReady", "Модель на месте") }
@@ -31,6 +31,7 @@ struct FirstRunDictationField: NSViewRepresentable {
func makeNSView(context: Context) -> FirstRunFieldBox { func makeNSView(context: Context) -> FirstRunFieldBox {
let textView = FirstRunTextView() let textView = FirstRunTextView()
textView.placeholder = placeholder textView.placeholder = placeholder
textView.setAccessibilityLabel(placeholder)
textView.delegate = context.coordinator textView.delegate = context.coordinator
textView.font = .systemFont(ofSize: 14) textView.font = .systemFont(ofSize: 14)
textView.isEditable = true textView.isEditable = true
@@ -56,6 +57,7 @@ struct FirstRunDictationField: NSViewRepresentable {
guard let textView = box.textView else { return } guard let textView = box.textView else { return }
if textView.string != text { textView.string = text } if textView.string != text { textView.string = text }
textView.placeholder = placeholder textView.placeholder = placeholder
textView.setAccessibilityLabel(placeholder)
context.coordinator.onSubmit = onSubmit context.coordinator.onSubmit = onSubmit
// Курсор ставится в это поле и остаётся здесь: диктовка вставляет // Курсор ставится в это поле и остаётся здесь: диктовка вставляет
// текст туда, где он мигает. // текст туда, где он мигает.
@@ -24,7 +24,16 @@ struct FirstRunKeyTrial: View {
var body: some View { var body: some View {
VStack(spacing: 12) { VStack(spacing: 12) {
if canHearKey { if !model.modelIsReady {
Text(model.isInstallingModel
? L("firstrun.trialModelDownloading", "Модель ещё скачивается. Ход установки виден на её странице.")
: L("firstrun.trialModelMissing", "Модель ещё не установлена. Кнопка ниже вернёт к скачиванию."))
.font(.system(size: 13, weight: .medium))
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
Button(L("firstrun.trialOpenModelSetup", "К установке модели")) { model.showModelSetup() }
.modifier(FirstRunProminentButton())
} else if canHearKey {
// Сама клавиша и есть кнопка замены. Строчка «Клавиша занята? // Сама клавиша и есть кнопка замены. Строчка «Клавиша занята?
// Поменять» снизу была незаметна: владелец 07.09.2026 сказал // Поменять» снизу была незаметна: владелец 07.09.2026 сказал
// прямо — «снизу не очень заметно… необходимо, чтобы вот та // прямо — «снизу не очень заметно… необходимо, чтобы вот та
@@ -88,11 +97,13 @@ struct FirstRunKeyTrial: View {
} }
} }
FirstRunDictationField(text: $model.tryItText, if model.modelIsReady {
placeholder: FirstRunCopy.trialFieldPlaceholder, FirstRunDictationField(text: $model.tryItText,
onSubmit: { model.goNext() }) placeholder: FirstRunCopy.trialFieldPlaceholder,
.frame(height: 68) onSubmit: { model.goNext() })
.frame(maxWidth: 440) .frame(height: 68)
.frame(maxWidth: 440)
}
} }
+4 -4
View File
@@ -10,13 +10,13 @@ import Foundation
import IrizCore import IrizCore
/// Шаги знакомства. Порядок - это и есть сценарий, и он не случайный: сначала /// Шаги знакомства. Порядок - это и есть сценарий, и он не случайный: сначала
/// «что это» и «где оно живёт», потом разрешения от самого понятного к самому /// «что это» и установка распознавания, затем «где оно живёт», разрешения от
/// пугающему, и только потом проба голосом. Человек, которому уже объяснили, /// самого понятного к самому пугающему и проба голосом. Человек, которому уже объяснили,
/// зачем нужен микрофон, спокойнее отвечает на «сможет читать все нажатия». /// зачем нужен микрофон, спокойнее отвечает на «сможет читать все нажатия».
enum FirstRunStep: String, CaseIterable, Equatable { enum FirstRunStep: String, CaseIterable, Equatable {
case welcome case welcome
case whereItLives
case model case model
case whereItLives
case microphone case microphone
case accessibility case accessibility
case inputMonitoring case inputMonitoring
@@ -103,11 +103,11 @@ let FIRST_RUN_COMPLETED_KEY = "ru.smltlk.firstRunCompleted"
func firstRunShouldShow(defaults: UserDefaults, func firstRunShouldShow(defaults: UserDefaults,
permissionsGranted: Bool, permissionsGranted: Bool,
modelInstalled: Bool = true) -> Bool { modelInstalled: Bool = true) -> Bool {
if defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) { return false }
// Без модели продукт не работает вовсе, а поставить её можно только // Без модели продукт не работает вовсе, а поставить её можно только
// отсюда. Человек с выданными разрешениями и пустым диском иначе не увидел // отсюда. Человек с выданными разрешениями и пустым диском иначе не увидел
// бы ни знакомства, ни модели - только отказ распознавания. // бы ни знакомства, ни модели - только отказ распознавания.
if !modelInstalled { return true } if !modelInstalled { return true }
if defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) { return false }
// Разрешения уже выданы - значит человек прошёл этот путь руками до того, // Разрешения уже выданы - значит человек прошёл этот путь руками до того,
// как знакомство появилось в продукте. Ему показывать нечего. // как знакомство появилось в продукте. Ему показывать нечего.
return !permissionsGranted return !permissionsGranted
@@ -4,6 +4,7 @@
// который не видит движения, через минуту решает, что зависло, и закрывает // который не видит движения, через минуту решает, что зависло, и закрывает
// окно. Идти дальше при этом можно сразу - загрузка не держит знакомство. // окно. Идти дальше при этом можно сразу - загрузка не держит знакомство.
import IrizDictate import IrizDictate
import IrizCore
import SwiftUI import SwiftUI
struct FirstRunModelInstall: View { struct FirstRunModelInstall: View {
@@ -11,11 +12,7 @@ struct FirstRunModelInstall: View {
var body: some View { var body: some View {
VStack(spacing: 10) { VStack(spacing: 10) {
if model.modelInstalled { if let phase = model.installPhase, phase != .finished {
Text(FirstRunCopy.modelReady)
.font(.system(size: 13, weight: .medium))
.foregroundStyle(.secondary)
} else if let phase = model.installPhase {
switch phase { switch phase {
case .failed(let reason): case .failed(let reason):
Text(reason) Text(reason)
@@ -25,6 +22,7 @@ struct FirstRunModelInstall: View {
.frame(maxWidth: 420) .frame(maxWidth: 420)
Button(FirstRunCopy.modelFailedRetry) { model.installModel() } Button(FirstRunCopy.modelFailedRetry) { model.installModel() }
.modifier(FirstRunProminentButton()) .modifier(FirstRunProminentButton())
.keyboardShortcut(.defaultAction)
default: default:
Text(speechModelInstallTitle(phase)) Text(speechModelInstallTitle(phase))
.font(.system(size: 13, weight: .medium)) .font(.system(size: 13, weight: .medium))
@@ -32,12 +30,23 @@ struct FirstRunModelInstall: View {
.progressViewStyle(.linear) .progressViewStyle(.linear)
.frame(width: 260) .frame(width: 260)
} }
} else if model.modelInstalled {
Text(FirstRunCopy.modelReady)
.font(.system(size: 13, weight: .medium))
.foregroundStyle(.secondary)
if model.selectedSpeechModel == .multilingualV3 {
Button(L("firstrun.model.verifyRepair", "Проверить и восстановить Parakeet")) {
model.installModel()
}
.buttonStyle(.bordered)
}
} else { } else {
Text(FirstRunCopy.hintModel) Text(FirstRunCopy.hintModel)
.font(.system(size: 12.5, weight: .medium)) .font(.system(size: 12.5, weight: .medium))
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
Button(FirstRunCopy.model.action ?? "") { model.installModel() } Button(FirstRunCopy.model.action ?? "") { model.installModel() }
.modifier(FirstRunProminentButton()) .modifier(FirstRunProminentButton())
.keyboardShortcut(.defaultAction)
} }
} }
} }
+18 -6
View File
@@ -46,19 +46,26 @@ struct FirstRunView: View {
FirstRunHero(step: step) FirstRunHero(step: step)
.frame(height: 96) .frame(height: 96)
Text(step.copy.title) Text(step == .model && model.modelIsReady
? L("firstrun.model.alreadyReadyTitle", "Распознавание уже установлено")
: step.copy.title)
.font(.system(size: 27, weight: .semibold)) .font(.system(size: 27, weight: .semibold))
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
Text(step.copy.body) Text(step == .model && model.modelIsReady
? Lf("firstrun.model.alreadyReadyBody", "%@ готов к диктовке. Скачивать ничего не нужно.", model.selectedSpeechModelTitle)
: (step == .tryIt && !model.modelIsReady
? L("firstrun.trialNeedsModel", "Перед первой диктовкой нужно скачать модель распознавания.")
: step.copy.body))
.font(.system(size: 15)) .font(.system(size: 15))
.foregroundStyle(.primary.opacity(0.88)) .foregroundStyle(.primary.opacity(0.88))
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: 440) .frame(maxWidth: 440)
if let note = step.copy.note { if let note = step.copy.note, !(step == .model && model.modelIsReady),
!(step == .tryIt && !model.modelIsReady) {
Text(note) Text(note)
.font(.system(size: 12.5)) .font(.system(size: 12.5))
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
@@ -110,9 +117,14 @@ struct FirstRunView: View {
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} }
Spacer() Spacer()
Button(model.isLastStep ? FirstRunCopy.done : FirstRunCopy.next) { model.goNext() } if model.modelInstallIsPrimaryAction {
.modifier(FirstRunProminentButton()) Button(model.nextButtonTitle) { model.goNext() }
.keyboardShortcut(.defaultAction) .buttonStyle(.bordered)
} else {
Button(model.nextButtonTitle) { model.goNext() }
.modifier(FirstRunProminentButton())
.keyboardShortcut(.defaultAction)
}
} }
.overlay { FirstRunProgress(step: step) } .overlay { FirstRunProgress(step: step) }
} }
+7 -3
View File
@@ -192,7 +192,7 @@ struct MenuContentView: View {
case .fault(let reason): case .fault(let reason):
actionRow(L("menu.dictation", "Диктовка"), key: reason, target: .dictation) { actionRow(L("menu.dictation", "Диктовка"), key: reason, target: .dictation) {
chrome.close() chrome.close()
appDelegate.recheckPermissions() appDelegate.recoverDictation()
} }
} }
@@ -342,7 +342,7 @@ struct MenuContentView: View {
order.append(.mode) order.append(.mode)
order.append(.layout) order.append(.layout)
if case .fault = state.dictationHint { order.append(.dictation) } if case .fault = state.dictationHint { order.append(.dictation) }
order += [.settings, .quit] order += [.meeting, .history, .welcome, .settings, .quit]
return order return order
} }
@@ -361,10 +361,14 @@ struct MenuContentView: View {
/// стрелки ← → обрабатывают сами, им активация не нужна. /// стрелки ← → обрабатывают сами, им активация не нужна.
private func activateFocused() -> Bool { private func activateFocused() -> Bool {
switch focus { switch focus {
case .permissions, .dictation: case .permissions:
chrome.close() chrome.close()
appDelegate.recheckPermissions() appDelegate.recheckPermissions()
return true return true
case .dictation:
chrome.close()
appDelegate.recoverDictation()
return true
case .meeting: case .meeting:
chrome.close() chrome.close()
appDelegate.toggleMeetingRecording() appDelegate.toggleMeetingRecording()
+5
View File
@@ -69,6 +69,11 @@ final class MenuState: ObservableObject {
/// Раскладка работает, только когда выданы оба разрешения. /// Раскладка работает, только когда выданы оба разрешения.
var permissionsOK: Bool { accessibilityOK && inputMonitoringOK } var permissionsOK: Bool { accessibilityOK && inputMonitoringOK }
/// Ошибка модели не должна отправлять проверять уже выданные разрешения.
var dictationRecoveryNeedsPermissions: Bool {
!permissionsOK || !microphoneOK || !inputTapOK
}
/// Версия из бандла — показывается в окне настроек, не в меню. /// Версия из бандла — показывается в окне настроек, не в меню.
var version: String { var version: String {
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev" Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
+6 -2
View File
@@ -11,7 +11,9 @@ import IrizSettings
import SwiftUI import SwiftUI
@MainActor @MainActor
func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys) -> NSWindow { func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys,
navigation: SettingsNavigation? = nil,
openSpeechModelSetup: (() -> Void)? = nil) -> NSWindow {
let window = NSWindow( let window = NSWindow(
// Окно шире прежнего: слева боковик со страницами, справа сама // Окно шире прежнего: слева боковик со страницами, справа сама
// страница. В 700 pt на две колонки не помещалось ничего. // страница. В 700 pt на две колонки не помещалось ничего.
@@ -41,7 +43,9 @@ func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys) -
// `.fullSizeContentView` сохраняет системную рамку. Замер по кадру дал // `.fullSizeContentView` сохраняет системную рамку. Замер по кадру дал
// радиус около 27 pt при зашитых 16, то есть своя маска ещё и врала бы. // радиус около 27 pt при зашитых 16, то есть своя маска ещё и врала бы.
window.contentMinSize = NSSize(width: 900, height: 620) window.contentMinSize = NSSize(width: 900, height: 620)
window.contentView = NSHostingView(rootView: IrizSettingsView(preview: preview, page: page)) window.contentView = NSHostingView(rootView: IrizSettingsView(preview: preview, page: page,
navigation: navigation,
openSpeechModelSetup: openSpeechModelSetup))
window.isReleasedWhenClosed = false // иначе закрытие окна уронит приложение window.isReleasedWhenClosed = false // иначе закрытие окна уронит приложение
return window return window
} }
+4 -2
View File
@@ -58,12 +58,14 @@ public extension Animation {
/// Нажатие. Без отклика кнопка кажется картинкой: нажал, ничего не шевельнулось. /// Нажатие. Без отклика кнопка кажется картинкой: нажал, ничего не шевельнулось.
/// 0.97 - предел, за которым сжатие уже видно как трюк. /// 0.97 - предел, за которым сжатие уже видно как трюк.
public struct IrizPressStyle: ButtonStyle { public struct IrizPressStyle: ButtonStyle {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
public init() {} public init() {}
public func makeBody(configuration: Configuration) -> some View { public func makeBody(configuration: Configuration) -> some View {
configuration.label configuration.label
.scaleEffect(configuration.isPressed ? 0.97 : 1) .scaleEffect(configuration.isPressed && !reduceMotion ? 0.97 : 1)
.animation(.irizQuick, value: configuration.isPressed) .animation(reduceMotion ? nil : .irizQuick, value: configuration.isPressed)
} }
} }
+29 -2
View File
@@ -106,6 +106,28 @@ public func Lf(_ key: String, _ original: String, _ arguments: CVarArg...) -> St
String(format: L(key, original), arguments: arguments) String(format: L(key, original), arguments: arguments)
} }
/// SwiftPM ищет свой bundle рядом с executable либо по абсолютному пути
/// сборки. В упакованном macOS-приложении ресурсы лежат в Contents/Resources;
/// обращение к Bundle.module на другой машине завершается fatalError.
func irizResourceBundle(in host: Bundle) -> Bundle? {
let locations = [host.resourceURL, host.bundleURL,
host.executableURL?.deletingLastPathComponent(),
host.bundleURL.deletingLastPathComponent()].compactMap { $0 }
return locations.lazy.compactMap {
Bundle(url: $0.appendingPathComponent("IrizApp_IrizCore.bundle", isDirectory: true))
}.first
}
private final class IrizResourceBundleMarker: NSObject {}
func irizResourceBundle() -> Bundle? {
// swift test загружает .xctest в системный test-host: Bundle.main указывает
// на Xcode, а bundle класса из IrizCore - на реально загруженный .xctest.
irizResourceBundle(in: .main) ?? irizResourceBundle(in: Bundle(for: IrizResourceBundleMarker.self))
}
private let irizResources = irizResourceBundle()
/// Бандл таблицы перевода, найденный БЕЗ УЧЁТА РЕГИСТРА. /// Бандл таблицы перевода, найденный БЕЗ УЧЁТА РЕГИСТРА.
/// ///
/// Прямой поиск по имени папки ломается о SwiftPM: он кладёт `zh-Hans.lproj` /// Прямой поиск по имени папки ломается о SwiftPM: он кладёт `zh-Hans.lproj`
@@ -116,11 +138,16 @@ public func Lf(_ key: String, _ original: String, _ arguments: CVarArg...) -> St
/// ///
/// Поэтому имя папки сверяется в нижнем регистре, а не берётся как есть. /// Поэтому имя папки сверяется в нижнем регистре, а не берётся как есть.
public func irizLocalizationBundle(for language: IrizLanguage) -> Bundle? { public func irizLocalizationBundle(for language: IrizLanguage) -> Bundle? {
if let path = Bundle.module.path(forResource: language.folder, ofType: "lproj"), guard let resources = irizResources else { return nil }
return irizLocalizationBundle(for: language, resources: resources)
}
func irizLocalizationBundle(for language: IrizLanguage, resources: Bundle) -> Bundle? {
if let path = resources.path(forResource: language.folder, ofType: "lproj"),
let bundle = Bundle(path: path) { let bundle = Bundle(path: path) {
return bundle return bundle
} }
guard let root = Bundle.module.resourceURL, guard let root = resources.resourceURL,
let entries = try? FileManager.default.contentsOfDirectory( let entries = try? FileManager.default.contentsOfDirectory(
at: root, includingPropertiesForKeys: nil) else { return nil } at: root, includingPropertiesForKeys: nil) else { return nil }
let wanted = (language.folder + ".lproj").lowercased() let wanted = (language.folder + ".lproj").lowercased()
@@ -15,7 +15,7 @@
"firstrun.hintAccessibility" = "click here, System Settings will open"; "firstrun.hintAccessibility" = "click here, System Settings will open";
"firstrun.hintInputMonitoring" = "click here, System Settings will open"; "firstrun.hintInputMonitoring" = "click here, System Settings will open";
"firstrun.hintMicrophone" = "click here"; "firstrun.hintMicrophone" = "click here";
"firstrun.hintModel" = "click here, about five minutes to download"; "firstrun.hintModel" = "Click below. iriz downloads and installs the model for you.";
"firstrun.inputMonitoring.body" = "macOS calls it \"Input Monitoring\" and warns that I'll be able to see your keystrokes in every app. Those are its words, not mine."; "firstrun.inputMonitoring.body" = "macOS calls it \"Input Monitoring\" and warns that I'll be able to see your keystrokes in every app. Those are its words, not mine.";
"firstrun.inputMonitoring.note" = "I need two things: to know you pressed the dictation key, and to notice a phrase typed in the wrong keyboard layout. I see keystrokes only here, on your Mac: I save nothing and send nothing anywhere, and I don't work in password fields at all.\n\nRight after that I'll restart. macOS requires it, nothing is broken."; "firstrun.inputMonitoring.note" = "I need two things: to know you pressed the dictation key, and to notice a phrase typed in the wrong keyboard layout. I see keystrokes only here, on your Mac: I save nothing and send nothing anywhere, and I don't work in password fields at all.\n\nRight after that I'll restart. macOS requires it, nothing is broken.";
"firstrun.inputMonitoring.title" = "One permission left: the keyboard"; "firstrun.inputMonitoring.title" = "One permission left: the keyboard";
@@ -23,10 +23,10 @@
"firstrun.microphone.body" = "Without it I won't hear a word, so let's start there."; "firstrun.microphone.body" = "Without it I won't hear a word, so let's start there.";
"firstrun.microphone.note" = "The audio is never saved: it lives exactly as long as it takes to work out what you said."; "firstrun.microphone.note" = "The audio is never saved: it lives exactly as long as it takes to work out what you said.";
"firstrun.microphone.title" = "Microphone needed"; "firstrun.microphone.title" = "Microphone needed";
"firstrun.model.action" = "Download model"; "firstrun.model.action" = "Download and install Parakeet";
"firstrun.model.body" = "I turn speech into text right on your Mac, no internet. For that I need a model: half a gigabyte, downloaded once."; "firstrun.model.body" = "Dictation needs a speech model. The button below downloads Parakeet, installs it in the right folder and selects it for recognition.";
"firstrun.model.note" = "It is deliberately not inside the disk image: the model updates more often than iriz itself. Keep it separate: otherwise an outdated one would ship along with the program.\n\nCarry on while it downloads: you can grant the permissions right now."; "firstrun.model.note" = "The download is about 500 MB. You need internet access and free disk space. Speed depends on your connection; progress appears here. No need to find or move files yourself.\n\nYou can grant permissions while the model downloads. We will try dictation after installation.";
"firstrun.model.title" = "Let's get the speech model"; "firstrun.model.title" = "Install speech recognition";
"firstrun.modelFailedRetry" = "Try again"; "firstrun.modelFailedRetry" = "Try again";
"firstrun.modelReady" = "Model is in place"; "firstrun.modelReady" = "Model is in place";
"firstrun.next" = "Next"; "firstrun.next" = "Next";
@@ -52,7 +52,7 @@
"firstrun.tryIt.note" = "The text lands in the field below and nowhere else: while this window is open, I type only here."; "firstrun.tryIt.note" = "The text lands in the field below and nowhere else: while this window is open, I type only here.";
"firstrun.tryIt.title" = "Try it right now"; "firstrun.tryIt.title" = "Try it right now";
"firstrun.welcome.body" = "Press the key, say a sentence, press it again. The text appears where your cursor was: in an email, in a chat, in the terminal."; "firstrun.welcome.body" = "Press the key, say a sentence, press it again. The text appears where your cursor was: in an email, in a chat, in the terminal.";
"firstrun.welcome.note" = "It all runs right on your Mac. No audio, no text leaves it."; "firstrun.welcome.note" = "Before your first dictation, download a speech model using the install button on the next step. Then speech recognition runs on your Mac, without internet access.";
"firstrun.welcome.title" = "You talk, I type"; "firstrun.welcome.title" = "You talk, I type";
"firstrun.whenItBreaks.body" = "Text didn't paste? It isn't lost. The badge expands and shows it, and you can copy it from there."; "firstrun.whenItBreaks.body" = "Text didn't paste? It isn't lost. The badge expands and shows it, and you can copy it from there.";
"firstrun.whenItBreaks.note" = "Misheard a word? Just correct it right in the text. I notice the edit and ask whether to remember it: say yes, and from then on I write it your way. I never put anything into the dictionary on my own.\n\nKey taken by another app? Click it in the settings and set your own shortcut.\n\nThis window, the settings and the history all open from the icon in the menu bar."; "firstrun.whenItBreaks.note" = "Misheard a word? Just correct it right in the text. I notice the edit and ask whether to remember it: say yes, and from then on I write it your way. I never put anything into the dictionary on my own.\n\nKey taken by another app? Click it in the settings and set your own shortcut.\n\nThis window, the settings and the history all open from the icon in the menu bar.";
@@ -332,3 +332,78 @@
"snippets.delete.a11y" = "Delete snippet %d"; "snippets.delete.a11y" = "Delete snippet %d";
"snippets.phrase.a11y" = "Snippet phrase %d"; "snippets.phrase.a11y" = "Snippet phrase %d";
"snippets.text.a11y" = "Snippet text %d"; "snippets.text.a11y" = "Snippet text %d";
/* UI Stack: обработка, восстановление и доступность. */
"files.choose" = "Choose files";
"files.destinationExists" = "Text already exists: %@. Open it or rename the source recording before retrying.";
"files.finished" = "Completed: %d of %d.";
"files.language" = "Recording language";
"files.languageAuto" = "Detect automatically";
"files.noSpeech" = "No speech recognized. No text file was created.";
"files.openFailed" = "Could not open %@. Check the file in Finder.";
"files.openText" = "Open text";
"files.preparing" = "loading the model";
"files.reading" = "reading the recording";
"files.refused" = "Files not accepted: %d. Choose readable recordings: %@.";
"files.retry" = "Retry remaining files";
"files.saving" = "saving text";
"files.showDestination" = "Show output folder";
"files.showInFinder" = "Show in Finder";
"files.start" = "Transcribe recordings";
"files.stopAfterCurrent" = "Stop after the current recording";
"files.stopped" = "Queue stopped. You can start the remaining files again.";
"files.stopping" = "Stopping after the current recording…";
"files.transcribing" = "transcribing";
"firstrun.agentModelRequired" = "Choose a model for %@ in prompt settings, then connect the agent here.";
"firstrun.agentSettings" = "Agent settings…";
"firstrun.modelAlreadyDownloading" = "The model is already downloading. Wait for installation to finish.";
"firstrun.modelInstallWhileRecording" = "Finish recording, then try installing the model again.";
"history.clearFailed" = "Could not move %d of %d recordings to the Trash. The others are already in the Trash.";
"history.clearing" = "Preparing and clearing history…";
"history.copiedTimed" = "Copied. The clipboard will clear in 2 minutes.";
"history.copyFailed" = "Could not copy. Try again.";
"history.deleteFailed" = "Could not move the recording to the Trash. Try again.";
"history.readFailed" = "Could not read history. Try opening it again.";
"hud.toggleExpanded" = "Expand or collapse overlay";
"meeting.close" = "Close";
"meeting.discardUnsaved" = "Delete unsaved recording";
"meeting.emptyRecording" = "No audio was recorded";
"meeting.emptyRecording.help" = "Check your microphone and record the meeting again.";
"meeting.openProtocol" = "Open transcript";
"meeting.processingFailed" = "Could not process the meeting";
"meeting.protocolReady" = "Meeting transcript is ready";
"meeting.recordingSaved" = "The recording is saved. Retry processing or find it in Finder.";
"meeting.retryProcessing" = "Retry processing";
"meeting.retrySave" = "Retry saving";
"meeting.saveFailed" = "Could not save the meeting recording";
"meeting.saveFailed.help" = "The audio is still in memory. Free some disk space and retry saving. Deleting the recording cannot be undone.";
"meeting.showRecording" = "Show recording";
"meeting.speakersUnresolved" = "Speakers could not be separated. The text was saved as one turn.";
"meeting.title" = "Meeting";
"meetings.openProtocol" = "Open transcript";
"meetings.showFolder" = "Show meeting folder";
"meetings.speakersUnresolved" = "%@: speakers could not be separated. The text is saved as one turn; check the transcript.";
"meetings.storage" = "Recording in Russian. Audio and transcript are saved in the iriz archive; you can open the completed files here.";
"settings.speechModelInstalled" = "%@: model installed";
"settings.speechModelMissing" = "%@: model not installed";
"settings.speechModelDownloadHelp" = "Speech recognition needs a model on this Mac. Automatic download is available only for Parakeet: about 0.5 GB, once. It becomes the selected recognizer after installation. Audio stays on your device.";
"settings.speechModelSetup" = "Set up speech recognition…";
"settings.downloadParakeet" = "Download Parakeet model…";
"settings.parakeetAlreadyAvailable" = "Parakeet is already installed. Select it and save settings to use it for dictation.";
"settings.selectInstalledParakeet" = "Select installed Parakeet";
"firstrun.model.installLater" = "Download later";
"firstrun.model.alreadyReadyTitle" = "Speech recognition is installed";
"firstrun.model.alreadyReadyBody" = "%@ is ready for dictation. No download needed.";
"firstrun.trialNeedsModel" = "Download a speech model before your first dictation.";
"firstrun.trialModelDownloading" = "The model is still downloading. You can see progress on its setup page.";
"firstrun.trialModelMissing" = "The model is not installed yet. The button below takes you to the download.";
"firstrun.trialOpenModelSetup" = "Set up the model";
"firstrun.model.verifyRepair" = "Check and repair Parakeet";
"speechModel.downloading" = "Downloading speech model";
"speechModel.verifying" = "Verifying downloaded model";
"speechModel.ready" = "Model installed";
"speechModel.failed" = "Download failed";
"speechModel.error.offline" = "No internet connection. Connect to a network and retry the download.";
"speechModel.error.connectionLost" = "The connection was lost. Check your internet connection and retry the download.";
"speechModel.error.timeout" = "The server did not respond in time. Retry the download later.";
"speechModel.error.cancelled" = "The download was cancelled. You can start it again.";
@@ -16,7 +16,7 @@
"firstrun.hintAccessibility" = "点这里,打开系统设置"; "firstrun.hintAccessibility" = "点这里,打开系统设置";
"firstrun.hintInputMonitoring" = "点这里,打开系统设置"; "firstrun.hintInputMonitoring" = "点这里,打开系统设置";
"firstrun.hintMicrophone" = "点这里"; "firstrun.hintMicrophone" = "点这里";
"firstrun.hintModel" = "点这里,下载大约要五分钟"; "firstrun.hintModel" = "点击下方按钮,iriz 会自动下载并安装模型。";
"firstrun.inputMonitoring.body" = "macOS 会把它叫做「输入监控」,还会警告你:我能看到所有程序里的按键。这是它的措辞,不是我的。"; "firstrun.inputMonitoring.body" = "macOS 会把它叫做「输入监控」,还会警告你:我能看到所有程序里的按键。这是它的措辞,不是我的。";
"firstrun.inputMonitoring.note" = "我只需要两件事:知道你按下了听写键,以及发现有句话是在错的键盘布局下打的。按键只在你这台 Mac 上看,不保存,不外发,密码框里我根本不工作。\n\n之后我会立刻重启。这是 macOS 的要求,不是出了故障。"; "firstrun.inputMonitoring.note" = "我只需要两件事:知道你按下了听写键,以及发现有句话是在错的键盘布局下打的。按键只在你这台 Mac 上看,不保存,不外发,密码框里我根本不工作。\n\n之后我会立刻重启。这是 macOS 的要求,不是出了故障。";
"firstrun.inputMonitoring.title" = "还差按键权限"; "firstrun.inputMonitoring.title" = "还差按键权限";
@@ -24,10 +24,10 @@
"firstrun.microphone.body" = "没有它我一个字也听不见,所以先从它开始。"; "firstrun.microphone.body" = "没有它我一个字也听不见,所以先从它开始。";
"firstrun.microphone.note" = "声音不会保存到任何地方:它只留到把话听明白为止。"; "firstrun.microphone.note" = "声音不会保存到任何地方:它只留到把话听明白为止。";
"firstrun.microphone.title" = "需要麦克风"; "firstrun.microphone.title" = "需要麦克风";
"firstrun.model.action" = "下载模型"; "firstrun.model.action" = "下载并安装 Parakeet";
"firstrun.model.body" = "语音就在你的 Mac 上识别,不联网。这需要一个模型:500 MB,只下一次。"; "firstrun.model.body" = "听写需要语音模型。下方按钮会下载 Parakeet,将其安装到正确的文件夹,并选为识别引擎。";
"firstrun.model.note" = "它故意不放在磁盘映像里:模型的更新比 iriz 本身勤。分开放::不然随程序一起来的就是过时的那个。\n\n下载的时候继续往下走:权限现在就能给。"; "firstrun.model.note" = "下载大小约为 500 MB,需要网络连接和可用磁盘空间。速度取决于网络,进度会显示在这里。不必手动查找或移动文件。\n\n下载期间可以继续授予权限。安装完成后再尝试听写。";
"firstrun.model.title" = "下载语音识别"; "firstrun.model.title" = "安装语音识别模型";
"firstrun.modelFailedRetry" = "重试"; "firstrun.modelFailedRetry" = "重试";
"firstrun.modelReady" = "模型已就位"; "firstrun.modelReady" = "模型已就位";
"firstrun.next" = "下一步"; "firstrun.next" = "下一步";
@@ -53,7 +53,7 @@
"firstrun.tryIt.note" = "文字会出现在下面的输入框里,不会传到别处:这个窗口开着的时候,我只往这里写。"; "firstrun.tryIt.note" = "文字会出现在下面的输入框里,不会传到别处:这个窗口开着的时候,我只往这里写。";
"firstrun.tryIt.title" = "现在就试试"; "firstrun.tryIt.title" = "现在就试试";
"firstrun.welcome.body" = "按一下键,说一句话,再按一下。文字会出现在光标所在的地方:邮件里、聊天里、终端里。"; "firstrun.welcome.body" = "按一下键,说一句话,再按一下。文字会出现在光标所在的地方:邮件里、聊天里、终端里。";
"firstrun.welcome.note" = "所有处理都在你的 Mac 上完成。声音和文字都不会发到任何地方。"; "firstrun.welcome.note" = "首次听写前,需要下载语音模型。下一步会显示安装按钮。之后语音识别就在你的 Mac 上运行,无需联网。";
"firstrun.welcome.title" = "你说,我来打字"; "firstrun.welcome.title" = "你说,我来打字";
"firstrun.whenItBreaks.body" = "文字没插进去?它没丢。提示条会展开把它显示出来,可以从那里复制。"; "firstrun.whenItBreaks.body" = "文字没插进去?它没丢。提示条会展开把它显示出来,可以从那里复制。";
"firstrun.whenItBreaks.note" = "有个词听错了?直接在文字里改掉就行。我会注意到这处修改,并问你要不要记住:你同意了,之后我就照你的写法来。我不会自己往词典里放任何东西。\n\n按键被别的程序占用了?在设置里点它,设你自己的组合。\n\n这个窗口、设置和历史,都从菜单栏的图标打开。"; "firstrun.whenItBreaks.note" = "有个词听错了?直接在文字里改掉就行。我会注意到这处修改,并问你要不要记住:你同意了,之后我就照你的写法来。我不会自己往词典里放任何东西。\n\n按键被别的程序占用了?在设置里点它,设你自己的组合。\n\n这个窗口、设置和历史,都从菜单栏的图标打开。";
@@ -333,3 +333,78 @@
"snippets.delete.a11y" = "删除第 %d 条片段"; "snippets.delete.a11y" = "删除第 %d 条片段";
"snippets.phrase.a11y" = "第 %d 条片段的触发词"; "snippets.phrase.a11y" = "第 %d 条片段的触发词";
"snippets.text.a11y" = "第 %d 条片段的正文"; "snippets.text.a11y" = "第 %d 条片段的正文";
/* UI Stack: обработка, восстановление и доступность. */
"files.choose" = "选择文件";
"files.destinationExists" = "文本已存在:%@。请打开它,或重命名原录音后重试。";
"files.finished" = "已完成:%d / %d。";
"files.language" = "录音语言";
"files.languageAuto" = "自动识别";
"files.noSpeech" = "未识别到语音。未创建文本文件。";
"files.openFailed" = "无法打开 %@。请在访达中检查该文件。";
"files.openText" = "打开文本";
"files.preparing" = "正在加载模型";
"files.reading" = "正在读取录音";
"files.refused" = "未接受的文件:%d。请选择可读取的录音:%@。";
"files.retry" = "重试剩余文件";
"files.saving" = "正在保存文本";
"files.showDestination" = "显示结果文件夹";
"files.showInFinder" = "在访达中显示";
"files.start" = "转录录音";
"files.stopAfterCurrent" = "完成当前录音后停止";
"files.stopped" = "队列已停止。你可以重新处理剩余文件。";
"files.stopping" = "完成当前录音后停止…";
"files.transcribing" = "正在转录";
"firstrun.agentModelRequired" = "请在提示词设置中为 %@ 选择模型,然后回到这里连接智能体。";
"firstrun.agentSettings" = "智能体设置…";
"firstrun.modelAlreadyDownloading" = "模型正在下载。请等待安装完成。";
"firstrun.modelInstallWhileRecording" = "请先结束录音,再重试安装模型。";
"history.clearFailed" = "有 %d 条录音未能移到废纸篓,共 %d 条。其余录音已移到废纸篓。";
"history.clearing" = "正在准备并清空历史记录…";
"history.copiedTimed" = "已复制。剪贴板将在 2 分钟后清空。";
"history.copyFailed" = "无法复制。请重试。";
"history.deleteFailed" = "无法将录音移到废纸篓。请重试。";
"history.readFailed" = "无法读取历史记录。请重新打开。";
"hud.toggleExpanded" = "展开或收起浮窗";
"meeting.close" = "关闭";
"meeting.discardUnsaved" = "删除未保存的录音";
"meeting.emptyRecording" = "未录制到声音";
"meeting.emptyRecording.help" = "请检查麦克风,然后重新录制会议。";
"meeting.openProtocol" = "打开会议记录";
"meeting.processingFailed" = "无法处理会议";
"meeting.protocolReady" = "会议记录已就绪";
"meeting.recordingSaved" = "录音已保存。你可以重试处理,或在访达中找到它。";
"meeting.retryProcessing" = "重试处理";
"meeting.retrySave" = "重试保存";
"meeting.saveFailed" = "无法保存会议录音";
"meeting.saveFailed.help" = "声音仍在内存中。请释放磁盘空间后重试保存。删除录音后将无法恢复。";
"meeting.showRecording" = "显示录音";
"meeting.speakersUnresolved" = "无法区分说话人。文本已保存为一段发言。";
"meeting.title" = "会议";
"meetings.openProtocol" = "打开会议记录";
"meetings.showFolder" = "显示会议文件夹";
"meetings.speakersUnresolved" = "%@:无法区分说话人。文本已保存为一段发言,请检查会议记录。";
"meetings.storage" = "俄语录音。音频和会议记录将保存到 iriz 归档中;你可以在这里打开处理完成的文件。";
"settings.speechModelInstalled" = "%@:模型已安装";
"settings.speechModelMissing" = "%@:模型未安装";
"settings.speechModelDownloadHelp" = "语音识别需要在这台 Mac 上安装模型。目前只能自动下载 Parakeet:约 0.5 GB,只需下载一次。安装后会成为所选识别引擎。音频始终留在你的设备上。";
"settings.speechModelSetup" = "设置语音识别…";
"settings.downloadParakeet" = "下载 Parakeet 模型…";
"settings.parakeetAlreadyAvailable" = "Parakeet 已安装。选择它并保存设置,即可用于听写。";
"settings.selectInstalledParakeet" = "选择已安装的 Parakeet";
"firstrun.model.installLater" = "稍后下载";
"firstrun.model.alreadyReadyTitle" = "语音识别模型已安装";
"firstrun.model.alreadyReadyBody" = "%@ 已准备好听写,无需下载。";
"firstrun.trialNeedsModel" = "首次听写前,请先下载语音模型。";
"firstrun.trialModelDownloading" = "模型仍在下载,可在模型设置页面查看进度。";
"firstrun.trialModelMissing" = "模型尚未安装。下方按钮可返回下载页面。";
"firstrun.trialOpenModelSetup" = "前往安装模型";
"firstrun.model.verifyRepair" = "检查并修复 Parakeet";
"speechModel.downloading" = "正在下载语音模型";
"speechModel.verifying" = "正在验证已下载的模型";
"speechModel.ready" = "模型已安装";
"speechModel.failed" = "下载失败";
"speechModel.error.offline" = "没有互联网连接。请连接网络后重试下载。";
"speechModel.error.connectionLost" = "连接已中断。请检查网络后重试下载。";
"speechModel.error.timeout" = "服务器未能及时响应。请稍后重试下载。";
"speechModel.error.cancelled" = "下载已取消。你可以重新开始。";
+171 -26
View File
@@ -62,6 +62,7 @@ public final class DictationController {
private var isBusy = false private var isBusy = false
private var isRecording = false private var isRecording = false
private var modelReady = false private var modelReady = false
private var lastRequestedModelProfile: SpeechModelProfile?
/// Идёт ли прогрев прямо сейчас. Отдельно от `modelReady`, потому что /// Идёт ли прогрев прямо сейчас. Отдельно от `modelReady`, потому что
/// «грузится» и «нет вовсе» - разные состояния с разными последствиями. /// «грузится» и «нет вовсе» - разные состояния с разными последствиями.
private var warmUpTask: Task<Void, Never>? private var warmUpTask: Task<Void, Never>?
@@ -88,6 +89,7 @@ public final class DictationController {
private var powerLifecycle = AudioPowerLifecycle() private var powerLifecycle = AudioPowerLifecycle()
/// Подмена таймаута распознавания — только тестами, чтобы не ждать живьём. /// Подмена таймаута распознавания — только тестами, чтобы не ждать живьём.
private let transcriptionTimeoutOverride: Double? private let transcriptionTimeoutOverride: Double?
private let modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)?
/// Счётчики доставки: их читает status.json (scripts/gate_app.sh). /// Счётчики доставки: их читает status.json (scripts/gate_app.sh).
private let insertionStats: InsertionStats private let insertionStats: InsertionStats
private var settingsObserver: NotificationObserver? private var settingsObserver: NotificationObserver?
@@ -95,6 +97,7 @@ public final class DictationController {
public init() { public init() {
self.settings = .shared self.settings = .shared
self.transcriptionTimeoutOverride = nil self.transcriptionTimeoutOverride = nil
self.modelLoader = nil
self.insertionStats = InsertionStats() self.insertionStats = InsertionStats()
observeSettings() observeSettings()
} }
@@ -102,9 +105,11 @@ public final class DictationController {
/// Для тестов и будущих точек сборки. /// Для тестов и будущих точек сборки.
init(settings: DictationSettings, init(settings: DictationSettings,
transcriptionTimeout: Double? = nil, transcriptionTimeout: Double? = nil,
insertionStats: InsertionStats = InsertionStats()) { insertionStats: InsertionStats = InsertionStats(),
modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)? = nil) {
self.settings = settings self.settings = settings
self.transcriptionTimeoutOverride = transcriptionTimeout self.transcriptionTimeoutOverride = transcriptionTimeout
self.modelLoader = modelLoader
self.insertionStats = insertionStats self.insertionStats = insertionStats
observeSettings() observeSettings()
} }
@@ -187,9 +192,17 @@ public final class DictationController {
public func stop() { public func stop() {
if isRecording { if isRecording {
// Sleep/выход отменяет клип: не запускаем распознавание и не if recordingPurpose == .meeting {
// создаём raw/audio recovery-артефакт. // Уже записанная встреча переживает sleep/выход. ASR здесь
handleCancel() // не запускаем: исходник можно разобрать после возвращения.
isRecording = false
recordingPurpose = .dictation
let captured = audio.endRecording()
finishMeetingRecording(samples: captured.samples, process: false)
hotkeys.resetToggleState()
} else {
handleCancel()
}
} }
maxDurationTask?.cancel() maxDurationTask?.cancel()
maxDurationTask = nil maxDurationTask = nil
@@ -223,9 +236,31 @@ public final class DictationController {
start() start()
} }
/// Вызывается после явной установки. Греет выбранный движок, не повторяя
/// start(), запросы разрешений и запуск записи; настройки не меняет.
@discardableResult
public func prepareAfterModelInstallation() -> Bool {
guard !isBusy, !isRecording, warmUpTask == nil, !powerLifecycle.isSuspended else { return false }
DownloadUtils.enforceOffline = true
modelReady = false
state = .warmingUp
warmUpTask = Task { [weak self] in await self?.warmUpModel() }
return true
}
private func warmUpModel() async { private func warmUpModel() async {
let profile = settings.speechEngine
lastRequestedModelProfile = profile
defer {
warmUpTask = nil
if settings.speechEngine != profile { prepareChangedSpeechModelIfIdle() }
}
do { do {
try await asr.load(profile: settings.speechEngine) if let modelLoader {
try await modelLoader(profile)
} else {
try await asr.load(profile: profile)
}
// Рычаг под смешанную речь включен и в ЖИВОЙ диктовке, а не только в // Рычаг под смешанную речь включен и в ЖИВОЙ диктовке, а не только в
// CLI: без него термины внутри русской фразы ломаются ровно там, где // CLI: без него термины внутри русской фразы ломаются ровно там, где
// владелец диктует каждый день. // владелец диктует каждый день.
@@ -233,6 +268,7 @@ public final class DictationController {
modelReady = true modelReady = true
if state == .warmingUp { state = .ready } if state == .warmingUp { state = .ready }
} catch { } catch {
modelReady = false
log("ASR warmup failed: \(error.localizedDescription)") log("ASR warmup failed: \(error.localizedDescription)")
state = .unavailable(error.localizedDescription) state = .unavailable(error.localizedDescription)
} }
@@ -312,35 +348,123 @@ public final class DictationController {
/// Файл пишется ДО разбора и остаётся на диске, даже если разбор упадёт: /// Файл пишется ДО разбора и остаётся на диске, даже если разбор упадёт:
/// запись заседания дороже протокола, её нельзя терять из-за отказа /// запись заседания дороже протокола, её нельзя терять из-за отказа
/// распознавателя. /// распознавателя.
private func finishMeetingRecording(samples: [Float]) { private func finishMeetingRecording(samples: [Float], process: Bool = true) {
state = .ready state = .ready
guard !samples.isEmpty else { guard !samples.isEmpty else {
log("meeting: пустая запись, сохранять нечего") log("meeting: пустая запись, сохранять нечего")
if process {
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = L("meeting.emptyRecording", "Звук не записался")
alert.informativeText = L("meeting.emptyRecording.help", "Проверь микрофон и повтори запись встречи.")
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
_ = runMeetingAlert(alert)
}
return return
} }
do { let date = Date()
let url = try meetingRecordingScratchURL() isBusy = true
let recording = try writeMeetingWAV(samples: samples, state = .transcribing
sampleRate: SAMPLE_RATE, let recording = saveMeetingRecording(samples: samples, at: date)
to: url) isBusy = false
log("meeting: записано \(Int(recording.seconds)) с в \(url.lastPathComponent)") state = .ready
Task { @MainActor in guard let recording else { return }
let pipeline = MeetingPipeline() log("meeting: записано \(Int(recording.seconds)) с в \(recording.url.lastPathComponent)")
let title = "Встреча " + meetingDateFormatter().string(from: Date()) guard process else { return }
do { processMeetingRecording(recording, at: date)
let result = try await pipeline.run(audio: recording.url, title: title) }
log("meeting: протокол готов, реплик \(result.turns.count)")
} catch { private func saveMeetingRecording(samples: [Float], at date: Date) -> MeetingRecording? {
// Разбор упал, но звук уже на диске - его можно принести в while true {
// окно встреч руками и разобрать ещё раз. do {
log("meeting: разбор отказал (\(error)), звук остался в \(recording.url.path)") return try writeMeetingWAV(samples: samples, sampleRate: SAMPLE_RATE,
to: meetingRecordingScratchURL(at: date))
} catch {
log("meeting: не удалось сохранить звук (\(error))")
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = L("meeting.saveFailed", "Не удалось сохранить запись встречи")
alert.informativeText = L("meeting.saveFailed.help", "Звук ещё в памяти. Освободи место на диске и повтори сохранение. Если удалить запись, восстановить её будет нельзя.")
+ "\n\n" + error.localizedDescription
alert.addButton(withTitle: L("meeting.retrySave", "Повторить сохранение"))
alert.addButton(withTitle: L("meeting.discardUnsaved", "Удалить несохранённую запись"))
guard runMeetingAlert(alert) == .alertFirstButtonReturn else { return nil }
}
}
}
/// Тот же барьер, что у диктовки: пока встреча разбирается, второй
/// распознаватель не запускается ни хоткеем, ни повтором из сообщения.
func beginMeetingProcessing() -> UInt64? {
guard !isBusy, !isRecording else { return nil }
transcriptionGeneration &+= 1
isBusy = true
state = .transcribing
return transcriptionGeneration
}
private func processMeetingRecording(_ recording: MeetingRecording, at date: Date) {
guard let generation = beginMeetingProcessing() else { return }
let title = L("meeting.title", "Встреча") + " " + meetingDateFormatter().string(from: date)
let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: settings.speechEngine,
initialPrompt: whisperDefaultInitialPrompt))
pipelineTask = Task { [weak self] in
guard let self else { return }
defer { self.finishTranscription(generation: generation) }
do {
let result = try await pipeline.run(audio: recording.url, title: title, at: date)
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
self.finishTranscription(generation: generation)
let alert = NSAlert()
alert.messageText = L("meeting.protocolReady", "Протокол встречи готов")
alert.informativeText = result.artifacts.transcript.path
if !result.speakersResolved {
alert.informativeText += "\n\n" + L("meeting.speakersUnresolved", "Не удалось разделить говорящих. Текст сохранён одной репликой.")
}
alert.addButton(withTitle: L("meeting.openProtocol", "Открыть протокол"))
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
switch self.runMeetingAlert(alert) {
case .alertFirstButtonReturn:
if !NSWorkspace.shared.open(result.artifacts.transcript) {
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.transcript])
}
case .alertSecondButtonReturn:
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.audio])
default: break
}
} catch {
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
self.finishTranscription(generation: generation)
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = L("meeting.processingFailed", "Не удалось разобрать встречу")
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
alert.informativeText = reason + "\n\n"
+ L("meeting.recordingSaved", "Запись сохранена. Можно повторить разбор или открыть её в Finder.")
+ "\n" + recording.url.path
alert.addButton(withTitle: L("meeting.retryProcessing", "Повторить разбор"))
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
switch self.runMeetingAlert(alert) {
case .alertFirstButtonReturn:
self.processMeetingRecording(recording, at: date)
case .alertSecondButtonReturn:
NSWorkspace.shared.activateFileViewerSelecting([recording.url])
default: break
} }
} }
} catch {
log("meeting: не удалось сохранить звук (\(error))")
} }
} }
private func runMeetingAlert(_ alert: NSAlert) -> NSApplication.ModalResponse {
// LSUIElement не имеет обычного главного окна; alert должен оказаться
// над постоянной floating-плашкой, иначе вопрос останется под ней.
alert.window.level = .floating
NSApp.activate(ignoringOtherApps: true)
return alert.runModal()
}
/// Кого звать, когда с плашки просят настройки. Ставит приложение: у /// Кого звать, когда с плашки просят настройки. Ставит приложение: у
/// модуля диктовки окна настроек нет и быть не должно. /// модуля диктовки окна настроек нет и быть не должно.
public var onOpenSettings: (() -> Void)? public var onOpenSettings: (() -> Void)?
@@ -361,6 +485,12 @@ public final class DictationController {
hotkeys.setTranslationHotkeyEnabled(settings.translationModeEnabled) hotkeys.setTranslationHotkeyEnabled(settings.translationModeEnabled)
hotkeys.setAlternateCompletionEnabled(settings.alternateCompletionEnabled) hotkeys.setAlternateCompletionEnabled(settings.alternateCompletionEnabled)
hotkeys.setTriggerMode(settings.triggerMode) hotkeys.setTriggerMode(settings.triggerMode)
prepareChangedSpeechModelIfIdle()
}
private func prepareChangedSpeechModelIfIdle() {
guard let previous = lastRequestedModelProfile, previous != settings.speechEngine else { return }
_ = prepareAfterModelInstallation()
} }
private func observeSettings() { private func observeSettings() {
@@ -556,7 +686,15 @@ public final class DictationController {
} }
public func toggleDictationFromUI() { public func toggleDictationFromUI() {
handlePress(purpose: .dictation) if isRecording {
// Кнопка HUD уже показывает «Закончить запись». Завершаем текущий
// purpose тем же путём, что хоткей, не меняя встречу на диктовку.
hotkeys.resetToggleState()
handleRelease(shortcut: .standard,
hotkeyDetectedAt: ProcessInfo.processInfo.systemUptime)
} else {
handlePress(purpose: .dictation)
}
} }
/// Начать запись для промпта прямо из интерфейса. Тот же вход, что и у /// Начать запись для промпта прямо из интерфейса. Тот же вход, что и у
@@ -571,6 +709,7 @@ public final class DictationController {
} }
private func handlePress(purpose: DictationRecordingPurpose) { private func handlePress(purpose: DictationRecordingPurpose) {
prepareChangedSpeechModelIfIdle()
if let refusal = startRefusal() { if let refusal = startRefusal() {
log("dictation: press refused — \(refusal.rawValue)") log("dictation: press refused — \(refusal.rawValue)")
hud?.startRefused(refusal) hud?.startRefused(refusal)
@@ -1249,6 +1388,7 @@ public final class DictationController {
default: default:
break break
} }
prepareChangedSpeechModelIfIdle()
} }
private func handleCancel() { private func handleCancel() {
@@ -1268,8 +1408,9 @@ public final class DictationController {
private func scheduleMaxDurationAutoRelease() { private func scheduleMaxDurationAutoRelease() {
maxDurationTask?.cancel() maxDurationTask?.cancel()
let limit = Self.recordingLimitSeconds(for: recordingPurpose)
maxDurationTask = Task { [weak self] in maxDurationTask = Task { [weak self] in
try? await Task.sleep(nanoseconds: UInt64(MAX_RECORDING_SECONDS) * 1_000_000_000) try? await Task.sleep(nanoseconds: UInt64(limit) * 1_000_000_000)
guard !Task.isCancelled, let self, self.isRecording else { return } guard !Task.isCancelled, let self, self.isRecording else { return }
log("dictation: max recording duration reached — auto release") log("dictation: max recording duration reached — auto release")
self.hotkeys.resetToggleState() self.hotkeys.resetToggleState()
@@ -1278,6 +1419,10 @@ public final class DictationController {
} }
} }
nonisolated static func recordingLimitSeconds(for purpose: DictationRecordingPurpose) -> TimeInterval {
purpose == .meeting ? meetingRecordingLimitSeconds : MAX_RECORDING_SECONDS
}
#if DEBUG #if DEBUG
func simulateActiveRecordingForTesting() { func simulateActiveRecordingForTesting() {
audio.beginRecording() audio.beginRecording()
+34 -3
View File
@@ -122,7 +122,12 @@ public func dictationHUDNextLanguage(after current: DictationLanguage) -> Dictat
/// значком без кнопки. /// значком без кнопки.
final class DictationHUDActionButton: NSView { final class DictationHUDActionButton: NSView {
var action: DictationHUDAction { var action: DictationHUDAction {
didSet { if action != oldValue { needsDisplay = true } } didSet {
guard action != oldValue else { return }
setAccessibilityLabel(action.title)
toolTip = action.title
needsDisplay = true
}
} }
var onPress: ((DictationHUDActionID) -> Void)? var onPress: ((DictationHUDActionID) -> Void)?
/// Кого звать, когда мышь пришла на кнопку или ушла с неё. Владелец /// Кого звать, когда мышь пришла на кнопку или ушла с неё. Владелец
@@ -132,6 +137,8 @@ final class DictationHUDActionButton: NSView {
var onHover: ((DictationHUDAction?) -> Void)? var onHover: ((DictationHUDAction?) -> Void)?
private var pressed = false private var pressed = false
private let reduceMotion: () -> Bool
private var displayOptionsObserver: DictationHUDNotificationObserver?
private var hovered = false { private var hovered = false {
didSet { didSet {
guard hovered != oldValue else { return } guard hovered != oldValue else { return }
@@ -148,6 +155,14 @@ final class DictationHUDActionButton: NSView {
guard let layer else { return } guard let layer else { return }
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
layer.position = CGPoint(x: frame.midX, y: frame.midY) layer.position = CGPoint(x: frame.midX, y: frame.midY)
guard !reduceMotion() else {
layer.removeAnimation(forKey: "irizHoverLift")
CATransaction.begin()
CATransaction.setDisableActions(true)
layer.transform = CATransform3DIdentity
CATransaction.commit()
return
}
let scale: CGFloat = hovered ? 1.18 : 1 let scale: CGFloat = hovered ? 1.18 : 1
let lift = CABasicAnimation(keyPath: "transform.scale") let lift = CABasicAnimation(keyPath: "transform.scale")
lift.fromValue = layer.value(forKeyPath: "transform.scale") ?? 1 lift.fromValue = layer.value(forKeyPath: "transform.scale") ?? 1
@@ -168,12 +183,22 @@ final class DictationHUDActionButton: NSView {
} }
private var tracking: NSTrackingArea? private var tracking: NSTrackingArea?
init(action: DictationHUDAction) { init(action: DictationHUDAction,
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter) {
self.action = action self.action = action
self.reduceMotion = reduceMotion
super.init(frame: .zero) super.init(frame: .zero)
setAccessibilityElement(true)
setAccessibilityRole(.button) setAccessibilityRole(.button)
setAccessibilityLabel(action.title) setAccessibilityLabel(action.title)
toolTip = action.title toolTip = action.title
displayOptionsObserver = DictationHUDNotificationObserver(displayOptionsCenter.addObserver(
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
object: nil, queue: .main
) { [weak self] _ in
MainActor.assumeIsolated { self?.applyHoverLift() }
}, center: displayOptionsCenter)
} }
@available(*, unavailable) @available(*, unavailable)
@@ -181,6 +206,12 @@ final class DictationHUDActionButton: NSView {
override var isFlipped: Bool { true } override var isFlipped: Bool { true }
override func accessibilityPerformPress() -> Bool {
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
onPress(action.id)
return true
}
override func updateTrackingAreas() { override func updateTrackingAreas() {
if let tracking { removeTrackingArea(tracking) } if let tracking { removeTrackingArea(tracking) }
let area = NSTrackingArea(rect: .zero, let area = NSTrackingArea(rect: .zero,
@@ -214,7 +245,7 @@ final class DictationHUDActionButton: NSView {
pressed = false pressed = false
needsDisplay = true needsDisplay = true
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return } guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
onPress?(action.id) _ = accessibilityPerformPress()
} }
override func draw(_ dirtyRect: NSRect) { override func draw(_ dirtyRect: NSRect) {
@@ -1,10 +1,11 @@
// Порядок показа плашки «идёт голос»: что и когда попадает на экран. // Порядок показа плашки «идёт голос»: что и когда попадает на экран.
// //
// Здесь нет ни AppKit, ни решений — решения в DictationHUD.swift, рисование в // Решения в DictationHUD.swift, рисование в
// DictationHUDWindow.swift. Такое разделение позволяет проверить тестом всё // DictationHUDWindow.swift. Такое разделение позволяет проверить тестом всё
// поведение (что показали, что погасили, крутится ли опрос уровня), ни разу не // поведение (что показали, что погасили, крутится ли опрос уровня), ни разу не
// поднимая живое окно: под `swift test` его и не поднять. // поднимая живое окно: под `swift test` его и не поднять.
import Foundation import Foundation
import AppKit
/// Поверхность, на которой плашка рисуется. Единственная реализация в продукте — /// Поверхность, на которой плашка рисуется. Единственная реализация в продукте —
/// `DictationHUDPanelSurface` (NSPanel). В тестах подставляется запоминающая /// `DictationHUDPanelSurface` (NSPanel). В тестах подставляется запоминающая
@@ -112,6 +113,7 @@ final class DictationHUDPresenter {
private var surface: DictationHUDSurface? private var surface: DictationHUDSurface?
private var dismissTimer: Timer? private var dismissTimer: Timer?
private var displayOptionsObserver: DictationHUDNotificationObserver?
private var smoothedLevel: Float = 0 private var smoothedLevel: Float = 0
private var lastLevelSequence: UInt64? private var lastLevelSequence: UInt64?
private var sameLevelSequenceTicks = 0 private var sameLevelSequenceTicks = 0
@@ -131,6 +133,7 @@ final class DictationHUDPresenter {
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation }, recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() }, reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
pump: DictationHUDLevelPump = DictationHUDLevelPump(), pump: DictationHUDLevelPump = DictationHUDLevelPump(),
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) { surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
self.levelSnapshot = levelSnapshot self.levelSnapshot = levelSnapshot
self.staleGuardEnabled = true self.staleGuardEnabled = true
@@ -145,6 +148,7 @@ final class DictationHUDPresenter {
self.pump = pump self.pump = pump
self.makeSurface = surface self.makeSurface = surface
pump.onTick = { [weak self] in self?.render() } pump.onTick = { [weak self] in self?.render() }
observeDisplayOptions(in: displayOptionsCenter)
} }
/// Совместимость тестов и простых поверхностей без sequence. Живой продукт /// Совместимость тестов и простых поверхностей без sequence. Живой продукт
@@ -155,6 +159,7 @@ final class DictationHUDPresenter {
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation }, recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() }, reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
pump: DictationHUDLevelPump = DictationHUDLevelPump(), pump: DictationHUDLevelPump = DictationHUDLevelPump(),
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) { surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
self.levelSnapshot = { (level(), 0) } self.levelSnapshot = { (level(), 0) }
self.staleGuardEnabled = false self.staleGuardEnabled = false
@@ -169,6 +174,18 @@ final class DictationHUDPresenter {
self.pump = pump self.pump = pump
self.makeSurface = surface self.makeSurface = surface
pump.onTick = { [weak self] in self?.render() } pump.onTick = { [weak self] in self?.render() }
observeDisplayOptions(in: displayOptionsCenter)
}
private func observeDisplayOptions(in center: NotificationCenter) {
displayOptionsObserver = DictationHUDNotificationObserver(center.addObserver(
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
object: nil, queue: .main
) { [weak self] _ in
// Ожидание и покой не опрашивают уровень: без уведомления уже
// открытая плашка не узнаёт, что владелец изменил Reduce Motion.
MainActor.assumeIsolated { self?.render() }
}, center: center)
} }
// MARK: - Входы конвейера // MARK: - Входы конвейера
@@ -16,6 +16,7 @@
// у неё нет подписей, она говорит цветом и формой. Панель - другое: её работа // у неё нет подписей, она говорит цветом и формой. Панель - другое: её работа
// и есть показать текст. // и есть показать текст.
import AppKit import AppKit
import IrizCore
/// Сколько строк займёт текст на самом деле. /// Сколько строк займёт текст на самом деле.
/// ///
@@ -298,14 +299,33 @@ final class DictationHUDTranscriptView: NSView {
/// на любом фоне. /// на любом фоне.
final class DictationHUDCopyPill: NSView { final class DictationHUDCopyPill: NSView {
var title: String = "" { var title: String = "" {
didSet { if title != oldValue { needsDisplay = true } } didSet {
guard title != oldValue else { return }
setAccessibilityLabel(title)
needsDisplay = true
}
} }
var onPress: (() -> Void)? var onPress: (() -> Void)?
private var pressed = false private var pressed = false
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setAccessibilityElement(true)
setAccessibilityRole(.button)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
override var isFlipped: Bool { true } override var isFlipped: Bool { true }
override func accessibilityPerformPress() -> Bool {
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
onPress()
return true
}
var fittingWidth: CGFloat { var fittingWidth: CGFloat {
(title as NSString).size(withAttributes: [.font: Self.font]).width + 26 (title as NSString).size(withAttributes: [.font: Self.font]).width + 26
} }
@@ -321,7 +341,7 @@ final class DictationHUDCopyPill: NSView {
pressed = false pressed = false
needsDisplay = true needsDisplay = true
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return } guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
onPress?() _ = accessibilityPerformPress()
} }
override func draw(_ dirtyRect: NSRect) { override func draw(_ dirtyRect: NSRect) {
@@ -359,8 +379,24 @@ final class DictationHUDCloseRing: NSView {
private var pressed = false private var pressed = false
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setAccessibilityElement(true)
setAccessibilityRole(.button)
setAccessibilityLabel(L("common.close", "Закрыть"))
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
override var isFlipped: Bool { true } override var isFlipped: Bool { true }
override func accessibilityPerformPress() -> Bool {
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
onPress()
return true
}
override func mouseDown(with event: NSEvent) { override func mouseDown(with event: NSEvent) {
pressed = true pressed = true
needsDisplay = true needsDisplay = true
@@ -370,7 +406,7 @@ final class DictationHUDCloseRing: NSView {
pressed = false pressed = false
needsDisplay = true needsDisplay = true
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return } guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
onPress?() _ = accessibilityPerformPress()
} }
override func draw(_ dirtyRect: NSRect) { override func draw(_ dirtyRect: NSRect) {
+22 -3
View File
@@ -4,12 +4,17 @@
import AppKit import AppKit
import Foundation import Foundation
import QuartzCore import QuartzCore
import IrizCore
private final class DictationHUDNotificationObserver: @unchecked Sendable { final class DictationHUDNotificationObserver: @unchecked Sendable {
let token: NSObjectProtocol let token: NSObjectProtocol
private let center: NotificationCenter
init(_ token: NSObjectProtocol) { self.token = token } init(_ token: NSObjectProtocol, center: NotificationCenter = .default) {
deinit { NotificationCenter.default.removeObserver(token) } self.token = token
self.center = center
}
deinit { center.removeObserver(token) }
} }
private final class DictationHUDDisplayLinkStorage: @unchecked Sendable { private final class DictationHUDDisplayLinkStorage: @unchecked Sendable {
@@ -941,6 +946,13 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
container.delegate = self container.delegate = self
container.setAccessibilityElement(true) container.setAccessibilityElement(true)
container.setAccessibilityRole(.group) container.setAccessibilityRole(.group)
container.setAccessibilityCustomActions([
NSAccessibilityCustomAction(name: L("hud.toggleExpanded", "Развернуть или свернуть плашку")) { [weak self] in
guard let handler = self?.openToggledHandler else { return false }
handler()
return true
}
])
let capsule = DictationHUDCapsuleView(frame: CGRect(origin: .zero, let capsule = DictationHUDCapsuleView(frame: CGRect(origin: .zero,
size: DICTATION_HUD_BASE_SIZE)) size: DICTATION_HUD_BASE_SIZE))
let hint = DictationHUDHintView(frame: .zero) let hint = DictationHUDHintView(frame: .zero)
@@ -1292,9 +1304,16 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
} }
if reduceMotionEnabled() { if reduceMotionEnabled() {
stopMotion() stopMotion()
hoverProgress = hoverAnimation?.to ?? hoverProgress
hoverAnimation = nil
hint?.appearanceProgress = hoverProgress
// Уже начатый морф тоже завершается при смене настройки.
transcriptProgress = transcriptTarget
advanceTranscript(dt: 0)
revealAnimation = nil revealAnimation = nil
revealProgress = 1 revealProgress = 1
capsule?.revealProgress = 1 capsule?.revealProgress = 1
layoutPanel(display: true)
} else { } else {
startMotionIfNeeded() startMotionIfNeeded()
} }
+19 -6
View File
@@ -14,7 +14,7 @@ import IrizCore
/// сортировки и то, что показывается владельцу. Ключ именно имя, а не mtime: /// сортировки и то, что показывается владельцу. Ключ именно имя, а не mtime:
/// после импорта из старого приложения mtime врёт (см. PromptEnvelope.swift, /// после импорта из старого приложения mtime врёт (см. PromptEnvelope.swift,
/// `latestDictation`) — папки пишутся на диск в обратном порядку номеров. /// `latestDictation`) — папки пишутся на диск в обратном порядку номеров.
public struct DictationHistoryEntry: Equatable, Identifiable { public struct DictationHistoryEntry: Equatable, Identifiable, Sendable {
let directory: URL let directory: URL
public let label: String public let label: String
/// Сырьё — ответ ASR байт в байт. Есть всегда, иначе записи нет. /// Сырьё — ответ ASR байт в байт. Есть всегда, иначе записи нет.
@@ -66,11 +66,16 @@ public let DICTATION_HISTORY_KEEP_LIMIT = 500
/// никогда. /// никогда.
public func dictationHistoryDirectories(in dictationsRoot: URL, public func dictationHistoryDirectories(in dictationsRoot: URL,
fileManager: FileManager = .default) -> [URL] { fileManager: FileManager = .default) -> [URL] {
let urls = (try? fileManager.contentsOfDirectory( (try? readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)) ?? []
}
private func readDictationHistoryDirectories(in dictationsRoot: URL,
fileManager: FileManager) throws -> [URL] {
let urls = try fileManager.contentsOfDirectory(
at: dictationsRoot, at: dictationsRoot,
includingPropertiesForKeys: [.isDirectoryKey], includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles] options: [.skipsHiddenFiles]
)) ?? [] )
return urls return urls
.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
.sorted { $0.lastPathComponent > $1.lastPathComponent } .sorted { $0.lastPathComponent > $1.lastPathComponent }
@@ -79,7 +84,14 @@ public func dictationHistoryDirectories(in dictationsRoot: URL,
public func dictationHistoryEntries(in dictationsRoot: URL, public func dictationHistoryEntries(in dictationsRoot: URL,
limit: Int? = nil, limit: Int? = nil,
fileManager: FileManager = .default) -> [DictationHistoryEntry] { fileManager: FileManager = .default) -> [DictationHistoryEntry] {
var directories = dictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager) (try? readDictationHistoryEntries(in: dictationsRoot, limit: limit, fileManager: fileManager)) ?? []
}
/// Для интерфейса: недоступный каталог — ошибка, а не пустая история.
public func readDictationHistoryEntries(in dictationsRoot: URL,
limit: Int? = nil,
fileManager: FileManager = .default) throws -> [DictationHistoryEntry] {
var directories = try readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
// Обрезаем ДО чтения содержимого: смысл потолка в том, чтобы не открывать // Обрезаем ДО чтения содержимого: смысл потолка в том, чтобы не открывать
// тысячи файлов, а не в том, чтобы открыть их и показать сотню. // тысячи файлов, а не в том, чтобы открыть их и показать сотню.
if let limit, directories.count > limit { directories = Array(directories.prefix(limit)) } if let limit, directories.count > limit { directories = Array(directories.prefix(limit)) }
@@ -199,7 +211,8 @@ enum DictationHistoryKeyAction: Equatable {
func dictationHistoryKeyAction(keyCode: CGKeyCode, func dictationHistoryKeyAction(keyCode: CGKeyCode,
charactersIgnoringModifiers: String?, charactersIgnoringModifiers: String?,
hasCommand: Bool) -> DictationHistoryKeyAction { hasCommand: Bool,
hasTextSelection: Bool = false) -> DictationHistoryKeyAction {
if hasCommand { if hasCommand {
// ⌘⌫ здесь СОЗНАТЕЛЬНО не занят. Это документированный системный // ⌘⌫ здесь СОЗНАТЕЛЬНО не занят. Это документированный системный
// шорткат текстового поля («удалить от курсора до начала строки»), а // шорткат текстового поля («удалить от курсора до начала строки»), а
@@ -208,7 +221,7 @@ func dictationHistoryKeyAction(keyCode: CGKeyCode,
// расшифровку речи клиента. Удаление живёт в контекстном меню, где его // расшифровку речи клиента. Удаление живёт в контекстном меню, где его
// нельзя нажать не глядя. // нельзя нажать не глядя.
switch charactersIgnoringModifiers?.lowercased() { switch charactersIgnoringModifiers?.lowercased() {
case "c": return .copySelected case "c": return hasTextSelection ? .passThrough : .copySelected
default: return .passThrough default: return .passThrough
} }
} }
@@ -59,9 +59,14 @@ func pasteboardRestoreDecision(transientChangeCount: Int?,
} }
@MainActor @MainActor
enum DictationHistoryClipboard { public enum DictationHistoryClipboard {
private static var pending: HistoryClipboardTransaction? private static var pending: HistoryClipboardTransaction?
/// Общий путь копирования для настроек и плавающего окна.
public static func copy(_ text: String) -> Bool {
copy(text, pasteboard: .general)
}
/// Кладёт текст в буфер. `false` — буфер отказал, вызывающий обязан сказать /// Кладёт текст в буфер. `false` — буфер отказал, вызывающий обязан сказать
/// владельцу, что копирование не состоялось. /// владельцу, что копирование не состоялось.
/// ///
@@ -69,7 +74,7 @@ enum DictationHistoryClipboard {
/// дописывает в живой лог владельца. /// дописывает в живой лог владельца.
@discardableResult @discardableResult
static func copy(_ text: String, static func copy(_ text: String,
pasteboard: NSPasteboard = .general, pasteboard: NSPasteboard,
hold: TimeInterval = HISTORY_CLIPBOARD_HOLD_SECONDS, hold: TimeInterval = HISTORY_CLIPBOARD_HOLD_SECONDS,
logLine: @escaping (String) -> Void = { log($0) }) -> Bool { logLine: @escaping (String) -> Void = { log($0) }) -> Bool {
quench(reason: "вытеснено следующим копированием") quench(reason: "вытеснено следующим копированием")
+201 -91
View File
@@ -35,6 +35,7 @@ final class DictationHistoryPresenter {
/// Поднят лист подтверждения «очистить всё». Пока он висит, клавиши окна /// Поднят лист подтверждения «очистить всё». Пока он висит, клавиши окна
/// не работают: Escape обязан закрывать вопрос, а не всё окно под ним. /// не работают: Escape обязан закрывать вопрос, а не всё окно под ним.
private var isConfirming = false private var isConfirming = false
private var presentationGeneration = 0
private let dictationsRoot: () throws -> URL private let dictationsRoot: () throws -> URL
init(dictationsRoot: @escaping () throws -> URL = { try DictationStore.dictationsDirectory() }) { init(dictationsRoot: @escaping () throws -> URL = { try DictationStore.dictationsDirectory() }) {
@@ -59,6 +60,7 @@ final class DictationHistoryPresenter {
// MARK: - Показ // MARK: - Показ
private func present(rescue: DictationRescue?) { private func present(rescue: DictationRescue?) {
presentationGeneration += 1
let entries: [DictationHistoryEntry] let entries: [DictationHistoryEntry]
if rescue == nil { if rescue == nil {
// Список читается ПОСЛЕ показа окна, в фоне. Владелец: «открываю // Список читается ПОСЛЕ показа окна, в фоне. Владелец: «открываю
@@ -116,12 +118,7 @@ final class DictationHistoryPresenter {
model.focusSearchField = rescue == nil model.focusSearchField = rescue == nil
installKeyMonitor() installKeyMonitor()
if rescue == nil { if rescue == nil {
model.didLoadAll = false model.reload(from: dictationsRoot)
model.onSearchStarted = { [weak self, weak model] in
guard let self, let model else { return }
self.loadAllForSearch(into: model)
}
loadEntriesInBackground(into: model)
} }
if let rescue { if let rescue {
// Ни имени приложения, ни самого текста в логе: лог живёт на диске // Ни имени приложения, ни самого текста в логе: лог живёт на диске
@@ -133,55 +130,6 @@ final class DictationHistoryPresenter {
} }
} }
/// Прочитать надиктовки с диска и отдать их окну, когда прочитаются.
///
/// Отдельным ходом, а не внутри показа: чтение занимает секунды на большом
/// каталоге, а окно обязано открыться мгновенно. Пока список едет, в окне
/// стоит честная строка «Читаю надиктовки…», а не пустота, которую легко
/// прочитать как «ничего нет».
private func loadEntriesInBackground(into model: DictationHistoryModel) {
model.isLoading = true
let root = try? dictationsRoot()
guard let root else {
model.isLoading = false
log("history: cannot reach dictations directory")
return
}
Task.detached(priority: .userInitiated) {
let startedAt = ProcessInfo.processInfo.systemUptime
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
await MainActor.run {
model.load(found)
model.isLoading = false
log(String(format: "history: %d записей прочитано за %.0f мс (в фоне)",
found.count, spent))
}
}
}
/// Догрузить остальное хранимое - по первому же поиску.
///
/// Окно открывается сотней свежих: их хватает, чтобы забрать вчерашнее.
/// Но поиск по сотне врал бы молча - человек ищет фразу, которая лежит
/// двухсотой, и получает «ничего не нашлось». Поэтому первый ввод в поле
/// поиска дочитывает всё, что хранится, и делает это один раз за показ.
private func loadAllForSearch(into model: DictationHistoryModel) {
guard !model.didLoadAll else { return }
model.didLoadAll = true
guard let root = try? dictationsRoot() else { return }
Task.detached(priority: .userInitiated) {
let startedAt = ProcessInfo.processInfo.systemUptime
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_KEEP_LIMIT)
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
await MainActor.run {
model.load(found)
log(String(format: "history: поиск дочитал %d записей за %.0f мс",
found.count, spent))
}
}
}
private func makePanel(model: DictationHistoryModel) -> DictationHistoryPanel { private func makePanel(model: DictationHistoryModel) -> DictationHistoryPanel {
let panel = DictationHistoryPanel( let panel = DictationHistoryPanel(
contentRect: historyPanelFrame(), contentRect: historyPanelFrame(),
@@ -241,7 +189,10 @@ final class DictationHistoryPresenter {
// MARK: - Закрытие и возврат фокуса // MARK: - Закрытие и возврат фокуса
private func close(returningFocus: Bool) { private func close(returningFocus: Bool) {
presentationGeneration += 1
removeKeyMonitor() removeKeyMonitor()
model?.cancelLoading()
model?.isClearing = false
model?.focusSearchField = false model?.focusSearchField = false
// Спасённый текст живёт ровно столько, сколько висит окно. Иначе // Спасённый текст живёт ровно столько, сколько висит окно. Иначе
// следующее открытие истории по хоткею подняло бы чужую позавчерашнюю // следующее открытие истории по хоткею подняло бы чужую позавчерашнюю
@@ -400,6 +351,7 @@ final class DictationHistoryPresenter {
private func copy(text: String) { private func copy(text: String) {
guard DictationHistoryClipboard.copy(text) else { guard DictationHistoryClipboard.copy(text) else {
model?.showError(L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз."))
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() } if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
return return
} }
@@ -407,21 +359,49 @@ final class DictationHistoryPresenter {
} }
private func delete(_ entry: DictationHistoryEntry) { private func delete(_ entry: DictationHistoryEntry) {
guard model?.isClearing != true else { return }
do { do {
try removeDictationHistoryEntry(entry) try removeDictationHistoryEntry(entry)
log("history: entry \(entry.label) moved to Trash with its directory") log("history: entry \(entry.label) moved to Trash with its directory")
reload()
} catch { } catch {
log("history: cannot delete \(entry.label): \(error.localizedDescription)") log("history: cannot delete \(entry.label): \(error.localizedDescription)")
model?.showError(L("history.deleteFailed", "Не удалось переместить запись в Корзину. Попробуй ещё раз."))
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() } if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
} }
reload()
} }
private func clearAll() { private func clearAll() {
guard let model, let panel, !model.entries.isEmpty, !isConfirming else { return } guard let model, let panel, !model.entries.isEmpty, !isConfirming, !model.isClearing else { return }
let generation = presentationGeneration
model.isClearing = true
Task { @MainActor [weak self] in
guard let self else { return }
do {
let root = try self.dictationsRoot()
let doomed = try await Task.detached(priority: .userInitiated) {
try readDictationHistoryEntries(in: root)
}.value
guard self.presentationGeneration == generation, panel.isVisible else { return }
guard !doomed.isEmpty else {
model.isClearing = false
self.reload()
return
}
self.confirmClearAll(doomed, model: model, panel: panel)
} catch {
guard self.presentationGeneration == generation else { return }
model.isClearing = false
model.showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
}
}
}
private func confirmClearAll(_ doomed: [DictationHistoryEntry],
model: DictationHistoryModel,
panel: DictationHistoryPanel) {
// Число записей — ДО удаления и в самом вопросе: иначе владелец // Число записей — ДО удаления и в самом вопросе: иначе владелец
// подтверждает вслепую. // подтверждает вслепую. Снимок включает весь архив, а не видимую сотню.
let doomed = model.entries
let alert = NSAlert() let alert = NSAlert()
alert.alertStyle = .warning alert.alertStyle = .warning
alert.messageText = dictationHistoryClearConfirmation(count: doomed.count) alert.messageText = dictationHistoryClearConfirmation(count: doomed.count)
@@ -438,31 +418,37 @@ final class DictationHistoryPresenter {
guard let self else { return } guard let self else { return }
self.isConfirming = false self.isConfirming = false
guard response == .alertFirstButtonReturn else { guard response == .alertFirstButtonReturn else {
model.isClearing = false
log("history: clear all cancelled (\(doomed.count) entries kept)") log("history: clear all cancelled (\(doomed.count) entries kept)")
return return
} }
var deleted = 0 Task { @MainActor in
for entry in doomed { let deleted = await Task.detached(priority: .userInitiated) {
do { var deleted = 0
try removeDictationHistoryEntry(entry) for entry in doomed {
deleted += 1 do {
} catch { try removeDictationHistoryEntry(entry)
log("history: cannot delete \(entry.label): \(error.localizedDescription)") deleted += 1
} catch {
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
}
}
return deleted
}.value
model.isClearing = false
log("history: cleared \(deleted) of \(doomed.count) entries")
self.reload()
if deleted != doomed.count {
model.showError(Lf("history.clearFailed", "Не удалось переместить в Корзину: %d из %d. Остальные записи уже в Корзине.", doomed.count - deleted, doomed.count))
} }
} }
log("history: cleared \(deleted) of \(doomed.count) entries")
self.reload()
} }
} }
} }
private func reload() { private func reload() {
guard let model else { return } guard let model else { return }
do { model.reload(from: dictationsRoot)
model.load(dictationHistoryEntries(in: try dictationsRoot()))
} catch {
log("history: cannot reach dictations directory: \(error.localizedDescription)")
}
} }
// MARK: - Клавиши // MARK: - Клавиши
@@ -488,10 +474,14 @@ final class DictationHistoryPresenter {
/// `true` — нажатие съедено окном, в поле поиска не уходит. /// `true` — нажатие съедено окном, в поле поиска не уходит.
private func handle(_ event: NSEvent) -> Bool { private func handle(_ event: NSEvent) -> Bool {
guard let model, !isConfirming else { return false } guard let model, !isConfirming else { return false }
// Выделенный текст принадлежит редактору поиска/спасения: ⌘C должен
// копировать именно выделение, не выбранную запись и не закрывать окно.
let editor = panel?.firstResponder as? NSTextView
let action = dictationHistoryKeyAction( let action = dictationHistoryKeyAction(
keyCode: CGKeyCode(event.keyCode), keyCode: CGKeyCode(event.keyCode),
charactersIgnoringModifiers: event.charactersIgnoringModifiers, charactersIgnoringModifiers: event.charactersIgnoringModifiers,
hasCommand: event.modifierFlags.contains(.command) hasCommand: event.modifierFlags.contains(.command),
hasTextSelection: (editor?.selectedRange().length ?? 0) > 0
) )
// В режиме спасения списка на экране нет, и те же клавиши обязаны // В режиме спасения списка на экране нет, и те же клавиши обязаны
// относиться к спасённому тексту, а не к невидимой выделенной записи. // относиться к спасённому тексту, а не к невидимой выделенной записи.
@@ -549,15 +539,18 @@ private final class DictationHistoryPanel: NSPanel {
// MARK: - Модель списка // MARK: - Модель списка
@MainActor @MainActor
final class DictationHistoryModel: ObservableObject { public final class DictationHistoryModel: ObservableObject {
@Published private(set) var entries: [DictationHistoryEntry] = [] @Published public private(set) var entries: [DictationHistoryEntry] = []
@Published var query: String = "" { @Published public var query: String = "" {
didSet { didSet {
guard query != oldValue else { return } guard query != oldValue else { return }
clampSelection() clampSelection()
// Первый же символ запроса дочитывает всё хранимое: искать по // Первый же символ запроса дочитывает всё хранимое: искать по
// видимой сотне значит молча врать «ничего не нашлось». // видимой сотне значит молча врать «ничего не нашлось».
if !query.isEmpty { onSearchStarted?() } if !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!didLoadAll, !isLoadingAll, let root {
loadInBackground(from: root, all: true)
}
} }
} }
@Published private(set) var selection: Int = 0 @Published private(set) var selection: Int = 0
@@ -565,12 +558,21 @@ final class DictationHistoryModel: ObservableObject {
/// Список ещё читается с диска. Отдельный признак, а не пустой список: /// Список ещё читается с диска. Отдельный признак, а не пустой список:
/// «пока ничего нет» и «ещё не прочитал» - разные вещи, и путать их значит /// «пока ничего нет» и «ещё не прочитал» - разные вещи, и путать их значит
/// врать владельцу, у которого две тысячи надиктовок. /// врать владельцу, у которого две тысячи надиктовок.
@Published var isLoading = false @Published public private(set) var isLoading = false
@Published public var notice: String?
@Published public var noticeIsError = false
@Published var isClearing = false
/// Дочитано ли всё хранимое. Показ начинается с сотни свежих; поиск /// Дочитано ли всё хранимое. Показ начинается с сотни свежих; поиск
/// дочитывает остальное один раз. /// дочитывает остальное один раз.
var didLoadAll = false private(set) var didLoadAll = false
/// Кого звать, когда владелец начал искать. private var isLoadingAll = false
var onSearchStarted: (() -> Void)? private var loadGeneration = 0
private var root: URL?
private let isPreview: Bool
public init(preview: Bool = false) {
isPreview = preview
}
/// Не `nil` — окно показывает не список, а текст, который не доехал до поля. /// Не `nil` — окно показывает не список, а текст, который не доехал до поля.
@Published private(set) var rescue: DictationRescue? @Published private(set) var rescue: DictationRescue?
/// Почему не сработал повтор вставки. Звука тут мало: владелец должен /// Почему не сработал повтор вставки. Звука тут мало: владелец должен
@@ -587,8 +589,77 @@ final class DictationHistoryModel: ObservableObject {
var onInsertRescue: (() -> Void)? var onInsertRescue: (() -> Void)?
var onCopyRescue: (() -> Void)? var onCopyRescue: (() -> Void)?
var visible: [DictationHistoryEntry] { public var visible: [DictationHistoryEntry] {
filteredDictationHistory(entries, query: query) query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? Array(entries.prefix(DICTATION_HISTORY_VISIBLE_LIMIT))
: filteredDictationHistory(entries, query: query)
}
/// Превью проверяется ДО получения корня: даже путь к живому store не нужен.
public func reload(from rootProvider: () throws -> URL) {
cancelLoading()
didLoadAll = false
guard !isPreview else {
load([])
return
}
do {
let root = try rootProvider()
self.root = root
loadInBackground(from: root,
all: !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
} catch {
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
}
}
public func cancelLoading() {
loadGeneration += 1
isLoading = false
isLoadingAll = false
root = nil
}
func showError(_ message: String) {
notice = message
noticeIsError = true
}
private func loadInBackground(from root: URL, all: Bool) {
let generation = beginLoading(all: all)
Task.detached(priority: .userInitiated) { [weak self] in
let result = Result {
// ponytail: весь архив читается лишь при поиске; индекс нужен,
// если измеренное время чтения станет мешать поиску.
try readDictationHistoryEntries(in: root,
limit: all ? nil : DICTATION_HISTORY_VISIBLE_LIMIT)
}
await self?.completeLoading(result, generation: generation, all: all)
}
}
/// Поколение общее для краткого списка, поиска и повторного открытия.
func beginLoading(all: Bool) -> Int {
loadGeneration += 1
isLoading = true
isLoadingAll = all
notice = nil
noticeIsError = false
return loadGeneration
}
func completeLoading(_ result: Result<[DictationHistoryEntry], Error>,
generation: Int, all: Bool) {
guard generation == loadGeneration else { return }
isLoading = false
isLoadingAll = false
switch result {
case .success(let found):
load(found)
didLoadAll = all
case .failure:
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
}
} }
var selectedEntry: DictationHistoryEntry? { var selectedEntry: DictationHistoryEntry? {
@@ -661,7 +732,13 @@ struct DictationHistoryView: View {
Group { Group {
if model.visible.isEmpty { if model.visible.isEmpty {
emptyState if let notice = model.notice, model.noticeIsError {
Label(notice, systemImage: "exclamationmark.circle")
.foregroundStyle(.red)
.padding(24)
} else {
emptyState
}
} else { } else {
list list
} }
@@ -669,6 +746,17 @@ struct DictationHistoryView: View {
.frame(maxHeight: .infinity) .frame(maxHeight: .infinity)
.background(IrizFloatingPlate()) .background(IrizFloatingPlate())
if model.isLoading, !model.entries.isEmpty {
ProgressView(L("history.loading", "Читаю надиктовки…"))
.controlSize(.small)
}
if let notice = model.notice, !model.entries.isEmpty {
Label(notice, systemImage: model.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
.foregroundStyle(model.noticeIsError ? Color.red : Color.primary)
.font(.system(size: 12))
.padding(.horizontal, 12)
}
footer footer
.background(IrizFloatingPlate()) .background(IrizFloatingPlate())
} }
@@ -739,6 +827,11 @@ struct DictationHistoryView: View {
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
.accessibilityLabel(notice) .accessibilityLabel(notice)
} }
if let notice = model.notice {
Label(notice, systemImage: "exclamationmark.circle")
.foregroundStyle(.red)
.font(.system(size: 12))
}
HStack(spacing: 12) { HStack(spacing: 12) {
hint("⏎", L("history.legendInsert", "вставить")) hint("⏎", L("history.legendInsert", "вставить"))
@@ -796,6 +889,7 @@ struct DictationHistoryView: View {
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.help(L("history.searchClear", "Очистить поиск")) .help(L("history.searchClear", "Очистить поиск"))
.accessibilityLabel(L("history.searchClear", "Очистить поиск"))
} }
} }
.padding(.horizontal, 10) .padding(.horizontal, 10)
@@ -835,10 +929,16 @@ struct DictationHistoryView: View {
ScrollView { ScrollView {
LazyVStack(spacing: 2) { LazyVStack(spacing: 2) {
ForEach(Array(model.visible.enumerated()), id: \.element.id) { index, entry in ForEach(Array(model.visible.enumerated()), id: \.element.id) { index, entry in
row(entry, isSelected: index == model.selection) Button { model.select(entry) } label: {
.id(entry.id) row(entry, isSelected: index == model.selection)
.contentShape(Rectangle()) .contentShape(Rectangle())
.onTapGesture { model.select(entry) } }
.buttonStyle(.plain)
.accessibilityElement(children: .combine)
.accessibilityAddTraits(index == model.selection ? .isSelected : [])
.accessibilityAction(named: Text(L("history.insert", "Вставить"))) { model.onInsert?(entry) }
.accessibilityAction(named: Text(L("history.copyButton", "Копировать"))) { model.onCopy?(entry) }
.id(entry.id)
} }
} }
.padding(.vertical, 6) .padding(.vertical, 6)
@@ -888,6 +988,7 @@ struct DictationHistoryView: View {
Button(L("history.copyButton", "Копировать")) { model.onCopy?(entry) } Button(L("history.copyButton", "Копировать")) { model.onCopy?(entry) }
Divider() Divider()
Button(L("history.trashOne", "Переместить в Корзину"), role: .destructive) { model.onDelete?(entry) } Button(L("history.trashOne", "Переместить в Корзину"), role: .destructive) { model.onDelete?(entry) }
.disabled(model.isClearing)
} }
} }
@@ -900,6 +1001,10 @@ struct DictationHistoryView: View {
/// место под строкой. /// место под строкой.
private var footer: some View { private var footer: some View {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
if model.isClearing {
ProgressView(L("history.clearing", "Подготовка и очистка истории…"))
.controlSize(.small)
}
HStack(spacing: 12) { HStack(spacing: 12) {
hint("⏎", L("history.legendInsert", "вставить")) hint("⏎", L("history.legendInsert", "вставить"))
hint("⌘C", L("history.legendCopy", "копировать")) hint("⌘C", L("history.legendCopy", "копировать"))
@@ -922,6 +1027,11 @@ struct DictationHistoryView: View {
.font(.system(size: 11)) .font(.system(size: 11))
.foregroundStyle(IRIZ_SUBTLE) .foregroundStyle(IRIZ_SUBTLE)
.accessibilityLabel(L("history.clipboardNoteVoice", "Скопированное держится в буфере две минуты, потом буфер чистится")) .accessibilityLabel(L("history.clipboardNoteVoice", "Скопированное держится в буфере две минуты, потом буфер чистится"))
if model.query.isEmpty, model.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
.font(.system(size: 11))
.foregroundStyle(IRIZ_SUBTLE)
}
} }
.padding(.horizontal, 16) .padding(.horizontal, 16)
.padding(.vertical, 8) .padding(.vertical, 8)
@@ -936,11 +1046,11 @@ struct DictationHistoryView: View {
if #available(macOS 26.0, *) { if #available(macOS 26.0, *) {
Button(action: { model.onClearAll?() }) { label } Button(action: { model.onClearAll?() }) { label }
.buttonStyle(.glass) .buttonStyle(.glass)
.disabled(model.entries.isEmpty) .disabled(model.entries.isEmpty || model.isClearing)
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину")) .help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
} else { } else {
Button(action: { model.onClearAll?() }) { label } Button(action: { model.onClearAll?() }) { label }
.disabled(model.entries.isEmpty) .disabled(model.entries.isEmpty || model.isClearing)
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину")) .help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
} }
} }
+44 -11
View File
@@ -31,6 +31,20 @@ public enum MeetingPipelineFailure: String, Error, Equatable {
case storeFailed = "не удалось сохранить встречу на диск" case storeFailed = "не удалось сохранить встречу на диск"
} }
/// Whisper может вернуть текст без времён слов. Успешная диаризация сама по
/// себе ещё не связывает слова с людьми: весь исходный текст должен сохраниться.
func meetingSpeakerTurns(transcript: AudioFileTranscript, spans: [SpeakerSpan],
names: SpeakerNames = SpeakerNames())
-> (turns: [SpeakerTurn], speakersResolved: Bool) {
let turns = speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans), names: names)
guard !spans.isEmpty,
turns.contains(where: { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else {
return ([SpeakerTurn(speaker: "Запись", text: transcript.text,
start: 0, end: transcript.audioSeconds)], false)
}
return (turns, true)
}
@MainActor @MainActor
public final class MeetingPipeline { public final class MeetingPipeline {
private let transcriber: AudioFileTranscriber private let transcriber: AudioFileTranscriber
@@ -52,20 +66,33 @@ public final class MeetingPipeline {
public func run(audio url: URL, title: String, names: SpeakerNames = SpeakerNames(), public func run(audio url: URL, title: String, names: SpeakerNames = SpeakerNames(),
at date: Date = Date(), at date: Date = Date(),
progress: @escaping (String) -> Void = { _ in }) async throws -> MeetingResult { progress: @escaping (String) -> Void = { _ in }) async throws -> MeetingResult {
try Task.checkCancellation()
progress("Читаю запись") progress("Читаю запись")
guard let decoded = try? await AudioFileDecoder.decode(url) else { let decoded: DecodedAudio
do {
decoded = try await AudioFileDecoder.decode(url)
} catch is CancellationError {
throw CancellationError()
} catch {
try Task.checkCancellation()
throw MeetingPipelineFailure.audioUnreadable throw MeetingPipelineFailure.audioUnreadable
} }
try Task.checkCancellation()
progress("Расшифровываю") progress("Расшифровываю")
_ = try? await transcriber.prepare()
let transcript: AudioFileTranscript let transcript: AudioFileTranscript
do { do {
_ = try await transcriber.prepare()
try Task.checkCancellation()
transcript = try await transcriber.transcribe(decoded, language: .russian) transcript = try await transcriber.transcribe(decoded, language: .russian)
} catch is CancellationError {
throw CancellationError()
} catch { } catch {
try Task.checkCancellation()
log("meeting: расшифровка отказала (\(error))") log("meeting: расшифровка отказала (\(error))")
throw MeetingPipelineFailure.transcriptionFailed throw MeetingPipelineFailure.transcriptionFailed
} }
try Task.checkCancellation()
guard !transcript.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { guard !transcript.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw MeetingPipelineFailure.nothingRecognized throw MeetingPipelineFailure.nothingRecognized
} }
@@ -73,22 +100,28 @@ public final class MeetingPipeline {
progress("Разбираю говорящих") progress("Разбираю говорящих")
// Отказ диаризатора конвейер не роняет: протокол без разделения хуже // Отказ диаризатора конвейер не роняет: протокол без разделения хуже
// полного, но лучше отсутствующего. // полного, но лучше отсутствующего.
let spans = (try? await diarizer.spans(of: url)) ?? [] let spans: [SpeakerSpan]
let turns = spans.isEmpty do {
? [SpeakerTurn(speaker: "Запись", text: transcript.text, spans = try await diarizer.spans(of: url)
start: 0, end: transcript.audioSeconds)] } catch is CancellationError {
: speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans), throw CancellationError()
names: names) } catch {
try Task.checkCancellation()
spans = []
}
try Task.checkCancellation()
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans, names: names)
progress("Сохраняю") progress("Сохраняю")
let document = MeetingProtocolDocument(title: title, recordedAt: date, let document = MeetingProtocolDocument(title: title, recordedAt: date,
audioSeconds: transcript.audioSeconds, audioSeconds: transcript.audioSeconds,
turns: turns) turns: resolved.turns)
try Task.checkCancellation()
do { do {
let artifacts = try MeetingStore.save(audio: url, protocolText: document.text(), let artifacts = try MeetingStore.save(audio: url, protocolText: document.text(),
at: date, title: title, in: storeRoot) at: date, title: title, in: storeRoot)
return MeetingResult(artifacts: artifacts, turns: turns, return MeetingResult(artifacts: artifacts, turns: resolved.turns,
speakersResolved: !spans.isEmpty, speakersResolved: resolved.speakersResolved,
audioSeconds: transcript.audioSeconds) audioSeconds: transcript.audioSeconds)
} catch { } catch {
log("meeting: запись на диск отказала (\(error))") log("meeting: запись на диск отказала (\(error))")
+1 -1
View File
@@ -88,5 +88,5 @@ public func meetingRecordingScratchURL(at date: Date = Date()) throws -> URL {
.appendingPathComponent("_recording", isDirectory: true) .appendingPathComponent("_recording", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700]) attributes: [.posixPermissions: 0o700])
return root.appendingPathComponent("meeting-\(formatter.string(from: date)).wav") return root.appendingPathComponent("meeting-\(formatter.string(from: date))-\(UUID().uuidString.lowercased()).wav")
} }
+22 -12
View File
@@ -45,21 +45,31 @@ public enum MeetingStore {
@discardableResult @discardableResult
public static func save(audio: URL, protocolText: String, at date: Date = Date(), public static func save(audio: URL, protocolText: String, at date: Date = Date(),
title: String, in root: URL? = nil) throws -> MeetingArtifacts { title: String, in root: URL? = nil) throws -> MeetingArtifacts {
let directory = try meetingDirectory(at: date, title: title, in: root) let manager = FileManager.default
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, let base = try meetingDirectory(at: date, title: title, in: root)
attributes: [.posixPermissions: 0o700]) let identifier = UUID().uuidString.lowercased()
let audioCopy = directory.appendingPathComponent("audio." + audio.pathExtension) let directory = base.deletingLastPathComponent()
if FileManager.default.fileExists(atPath: audioCopy.path) { .appendingPathComponent(base.lastPathComponent + "-" + identifier, isDirectory: true)
try FileManager.default.removeItem(at: audioCopy) let staging = base.deletingLastPathComponent()
} .appendingPathComponent(".saving-" + identifier, isDirectory: true)
try FileManager.default.copyItem(at: audio, to: audioCopy) try manager.createDirectory(at: staging, withIntermediateDirectories: true,
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path) attributes: [.posixPermissions: 0o700])
// Новый архив появляется только целиком. Старые записи, в том числе с
// тем же названием и временем, никогда не служат временным каталогом.
defer { try? manager.removeItem(at: staging) }
let audioName = "audio." + audio.pathExtension
let audioCopy = staging.appendingPathComponent(audioName)
try manager.copyItem(at: audio, to: audioCopy)
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
let transcript = directory.appendingPathComponent("protocol.md") let transcript = staging.appendingPathComponent("protocol.md")
try protocolText.write(to: transcript, atomically: true, encoding: .utf8) try protocolText.write(to: transcript, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path) try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
try manager.moveItem(at: staging, to: directory)
return MeetingArtifacts(directory: directory, audio: audioCopy, transcript: transcript) return MeetingArtifacts(directory: directory,
audio: directory.appendingPathComponent(audioName),
transcript: directory.appendingPathComponent("protocol.md"))
} }
/// Имя папки из названия встречи: латиница и цифры, остальное в дефис. /// Имя папки из названия встречи: латиница и цифры, остальное в дефис.
+130 -25
View File
@@ -6,19 +6,21 @@
// приложение, а модель приезжает после установки - с показанным ходом и // приложение, а модель приезжает после установки - с показанным ходом и
// понятной ценой. // понятной ценой.
// //
// Правило «сеть в диктовке запрещена» при этом остаётся. `enforceOffline` // Явная установка получает закреплённые файлы через URLSession. Рубильник
// снимается ТОЛЬКО на время явной установки, которую начал человек, и // офлайна распознавателя не меняется даже на время скачивания. Новая копия
// возвращается назад в `defer` - в том числе на ошибке и на отмене. Пока идёт // проверяется отдельно; существующий кэш сохраняется при любом отказе.
// диктовка, установка не начинается вовсе: снятый рубильник при работающем
// конвейере означал бы, что распознавание может молча полезть в сеть.
import FluidAudio
import Foundation import Foundation
import IrizCore
public let speechModelDidInstallNotification = Notification.Name("iriz.speechModelDidInstall")
// Сумма 21 файла закреплённого commit: официальный HF tree API, 12.09.2026.
public let speechModelDownloadBytes: Int64 = 483_105_645
/// Что происходит с установкой прямо сейчас. /// Что происходит с установкой прямо сейчас.
public enum SpeechModelInstallPhase: Equatable, Sendable { public enum SpeechModelInstallPhase: Equatable, Sendable {
/// Идёт скачивание, 0…1. /// Идёт скачивание, 0…1.
case downloading(Double) case downloading(Double)
/// Файлы получены, CoreML собирает модель под это железо. /// Файлы получены, проверяется их целостность перед использованием.
case compiling case compiling
case finished case finished
case failed(String) case failed(String)
@@ -29,7 +31,7 @@ public enum SpeechModelInstallRefusal: String, Equatable, Sendable {
case alreadyInstalled case alreadyInstalled
/// Установка уже идёт. /// Установка уже идёт.
case alreadyRunning case alreadyRunning
/// Идёт диктовка: рубильник сети при работающем конвейере не снимаем. /// Идёт диктовка: установку не начинаем посреди активного сценария.
case dictationBusy case dictationBusy
} }
@@ -47,28 +49,45 @@ public func speechModelInstallRefusal(installed: Bool,
/// Ход установки, как его показывает окно: доля и подпись. /// Ход установки, как его показывает окно: доля и подпись.
public func speechModelInstallTitle(_ phase: SpeechModelInstallPhase) -> String { public func speechModelInstallTitle(_ phase: SpeechModelInstallPhase) -> String {
switch phase { switch phase {
case .downloading: return "Качаю модель распознавания" case .downloading: return L("speechModel.downloading", "Качаю модель распознавания")
case .compiling: return "Готовлю модель под твой Мак" case .compiling: return L("speechModel.verifying", "Проверяю скачанную модель")
case .finished: return "Модель на месте" case .finished: return L("speechModel.ready", "Модель на месте")
case .failed: return "Скачать не вышло" case .failed: return L("speechModel.failed", "Скачать не вышло")
} }
} }
public func speechModelInstallFraction(_ phase: SpeechModelInstallPhase) -> Double { public func speechModelInstallFraction(_ phase: SpeechModelInstallPhase) -> Double {
switch phase { switch phase {
case .downloading(let value): return min(1, max(0, value)) case .downloading(let value): return min(1, max(0, value))
// Сборка идёт без хода: показываем почти полную полосу, а не откат назад. // Все байты получены; проверка не откатывает полосу скачивания назад.
case .compiling: return 0.97 case .compiling: return 1
case .finished: return 1 case .finished: return 1
case .failed: return 0 case .failed: return 0
} }
} }
public func speechModelInstallFailureMessage(for error: Error) -> String {
if error is CancellationError || (error as? URLError)?.code == .cancelled {
return L("speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
}
switch (error as? URLError)?.code {
case .notConnectedToInternet:
return L("speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание.")
case .networkConnectionLost:
return L("speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание.")
case .timedOut:
return L("speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже.")
default:
return error.localizedDescription
}
}
@MainActor @MainActor
public final class SpeechModelInstaller { public final class SpeechModelInstaller {
public static let shared = SpeechModelInstaller() public static let shared = SpeechModelInstaller()
private(set) public var isRunning = false private(set) public var isRunning = false
private var downloadingFile: UUID?
private init() {} private init() {}
@@ -78,33 +97,119 @@ public final class SpeechModelInstaller {
public func install(dictating: Bool, public func install(dictating: Bool,
progress: @escaping @MainActor (SpeechModelInstallPhase) -> Void) progress: @escaping @MainActor (SpeechModelInstallPhase) -> Void)
async -> SpeechModelInstallRefusal? { async -> SpeechModelInstallRefusal? {
let installed = speechModelCacheExists(for: .multilingualV3) if let refusal = speechModelInstallRefusal(installed: false,
if let refusal = speechModelInstallRefusal(installed: installed,
running: isRunning, running: isRunning,
dictating: dictating) { dictating: dictating) {
if refusal == .alreadyInstalled { progress(.finished) }
return refusal return refusal
} }
isRunning = true isRunning = true
DownloadUtils.enforceOffline = false
defer { defer {
DownloadUtils.enforceOffline = true
isRunning = false isRunning = false
downloadingFile = nil
} }
let directory = speechModelCacheDirectory(for: .multilingualV3)
do { do {
_ = try await AsrModels.download(version: .v3) { snapshot in let verified = await Task.detached(priority: .userInitiated) {
Task { @MainActor in (try? ModelIntegrity.verifyParakeetV3Model(at: directory)) != nil
switch snapshot.phase { }.value
case .compiling: progress(.compiling) try Task.checkCancellation()
default: progress(.downloading(snapshot.fractionCompleted)) if verified {
progress(.finished)
return .alreadyInstalled
}
let manager = FileManager.default
let staging = directory.deletingLastPathComponent()
.appendingPathComponent(".iriz-model-download-" + UUID().uuidString, isDirectory: true)
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
defer { try? manager.removeItem(at: staging) }
let files = ModelIntegrity.parakeetV3DownloadFiles
var receivedBytes: Int64 = 0
for file in files {
try Task.checkCancellation()
let completedBytes = receivedBytes
let token = UUID()
downloadingFile = token
progress(.downloading(Double(completedBytes) / Double(speechModelDownloadBytes)))
let delegate = SpeechModelDownloadProgress { [weak self] currentBytes in
Task { @MainActor in
guard self?.downloadingFile == token else { return }
progress(.downloading(min(1, Double(completedBytes + currentBytes) / Double(speechModelDownloadBytes))))
} }
} }
let (temporary, response) = try await URLSession.shared.download(
from: speechModelDownloadURL(for: file), delegate: delegate)
downloadingFile = nil
defer { try? manager.removeItem(at: temporary) }
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
throw URLError(.badServerResponse)
}
let target = staging.appendingPathComponent(file.relativePath)
try manager.createDirectory(at: target.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
try manager.moveItem(at: temporary, to: target)
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path)
receivedBytes += Int64(try target.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0)
} }
progress(.compiling)
try await Task.detached(priority: .userInitiated) {
try ModelIntegrity.verifyParakeetV3Model(at: staging)
}.value
try Task.checkCancellation()
try publishSpeechModelCache(from: staging, to: directory)
progress(.finished) progress(.finished)
return nil return nil
} catch { } catch {
progress(.failed(error.localizedDescription)) progress(.failed(speechModelInstallFailureMessage(for: error)))
return nil return nil
} }
} }
} }
private final class SpeechModelDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
private let received: @Sendable (Int64) -> Void
init(received: @escaping @Sendable (Int64) -> Void) { self.received = received }
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
received(totalBytesWritten)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {}
}
/// Источник зафиксирован тем же commit, что и SHA-256 в загрузчике; ни main,
/// ни переменные окружения с подменённым реестром сюда не попадают.
func speechModelDownloadURL(for file: ModelFileDigest) throws -> URL {
guard ModelIntegrity.parakeetV3DownloadFiles.contains(file),
let url = URL(string: "https://huggingface.co/\(ModelIntegrity.parakeetV3Repository)/resolve/\(ModelIntegrity.parakeetV3RepositoryCommit)/\(file.relativePath)"),
url.scheme == "https", url.host == "huggingface.co" else {
throw URLError(.badURL)
}
return url
}
/// Замена только после проверки новой копии. Предыдущая остаётся рядом;
/// если публикация не удалась, возвращаем её на прежнее место.
func publishSpeechModelCache(from staging: URL, to directory: URL) throws {
let manager = FileManager.default
var backup: URL?
if manager.fileExists(atPath: directory.path) {
let saved = directory.deletingLastPathComponent()
.appendingPathComponent(".iriz-model-backup-" + UUID().uuidString, isDirectory: true)
try manager.moveItem(at: directory, to: saved)
backup = saved
}
do {
try manager.moveItem(at: staging, to: directory)
} catch {
if let backup { try manager.moveItem(at: backup, to: directory) }
throw error
}
}
+29 -3
View File
@@ -163,13 +163,20 @@ func speechModelCacheDirectory(for profile: SpeechModelProfile) -> URL {
} }
public func speechModelCacheExists(for profile: SpeechModelProfile) -> Bool { public func speechModelCacheExists(for profile: SpeechModelProfile) -> Bool {
speechModelCacheIsComplete(for: profile, at: speechModelCacheDirectory(for: profile))
}
/// Быстрый probe для интерфейса: состав файлов, не SHA-256 сотен мегабайт.
/// Полная проверка по закреплённому манифесту остаётся перед загрузкой модели.
func speechModelCacheIsComplete(for profile: SpeechModelProfile, at directory: URL) -> Bool {
switch profile { switch profile {
case .multilingualV3: case .multilingualV3:
return FileManager.default.fileExists(atPath: speechModelCacheDirectory(for: profile).path) return ModelIntegrity.parakeetV3CacheIsComplete(at: directory)
case .whisperLargeV3, .whisperTurbo: case .whisperLargeV3, .whisperTurbo:
// У whisper модель - ОДИН файл, и каталог без него бесполезен: проверяем файл.
guard let file = profile.whisperModelFile else { return false } guard let file = profile.whisperModelFile else { return false }
return FileManager.default.fileExists(atPath: whisperModelURL(file).path) let values = try? directory.appendingPathComponent(file)
.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
return values?.isRegularFile == true && (values?.fileSize ?? 0) > 0
} }
} }
@@ -241,6 +248,25 @@ public enum ModelIntegrity {
// END GENERATED PARAKEET_V3_MODEL_MANIFEST // END GENERATED PARAKEET_V3_MODEL_MANIFEST
] ]
static var parakeetV3DownloadFiles: [ModelFileDigest] { parakeetV3Files }
static func parakeetV3CacheIsComplete(at directory: URL) -> Bool {
do {
let directories = Set(parakeetV3Files.flatMap { parentDirectories(of: $0.relativePath) })
for name in directories {
try requireDirectory(directory.appendingPathComponent(name), relativePath: name)
}
for file in parakeetV3Files {
let url = directory.appendingPathComponent(file.relativePath)
try requireRegularFile(url, relativePath: file.relativePath)
guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) > 0 else { return false }
}
return true
} catch {
return false
}
}
public static func verifyParakeetV3Model(at directory: URL) throws { public static func verifyParakeetV3Model(at directory: URL) throws {
try verifyFiles(root: directory, try verifyFiles(root: directory,
expectedFiles: parakeetV3Files, expectedFiles: parakeetV3Files,
+28 -10
View File
@@ -38,7 +38,7 @@ public func irizDropSizeText(_ bytes: Int64) -> String {
/// Годится ли файл. Чистая функция: решение о приёме проверяется тестом без /// Годится ли файл. Чистая функция: решение о приёме проверяется тестом без
/// окна и без диска. /// окна и без диска.
public func irizDropAccepts(_ url: URL, extensions: [String]) -> Bool { public func irizDropAccepts(_ url: URL, extensions: [String]) -> Bool {
extensions.contains(url.pathExtension.lowercased()) url.isFileURL && extensions.contains(url.pathExtension.lowercased())
} }
public struct IrizDropZone: View { public struct IrizDropZone: View {
@@ -49,6 +49,7 @@ public struct IrizDropZone: View {
@State private var dragging = false @State private var dragging = false
@State private var refused: String? @State private var refused: String?
@Environment(\.isEnabled) private var isEnabled
public init(title: String, public init(title: String,
subtitle: String, subtitle: String,
@@ -78,7 +79,7 @@ public struct IrizDropZone: View {
.foregroundStyle(IRIZ_SUBTLE) .foregroundStyle(IRIZ_SUBTLE)
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
Button("Выбрать файлы") { choose() } Button(L("files.choose", "Выбрать файлы")) { choose() }
.modifier(IrizDropZoneButton()) .modifier(IrizDropZoneButton())
.padding(.top, 2) .padding(.top, 2)
} }
@@ -96,6 +97,7 @@ public struct IrizDropZone: View {
// картинка, и человек не понимает, отпускать тут или нет. // картинка, и человек не понимает, отпускать тут или нет.
.animation(irizAnimation(.irizQuick), value: dragging) .animation(irizAnimation(.irizQuick), value: dragging)
.onDrop(of: [.fileURL], isTargeted: $dragging) { providers in .onDrop(of: [.fileURL], isTargeted: $dragging) { providers in
guard isEnabled, !providers.isEmpty else { return false }
accept(providers) accept(providers)
return true return true
} }
@@ -111,6 +113,7 @@ public struct IrizDropZone: View {
} }
private func choose() { private func choose() {
guard isEnabled else { return }
let panel = NSOpenPanel() let panel = NSOpenPanel()
panel.allowsMultipleSelection = true panel.allowsMultipleSelection = true
panel.canChooseDirectories = false panel.canChooseDirectories = false
@@ -120,20 +123,33 @@ public struct IrizDropZone: View {
} }
private func accept(_ providers: [NSItemProvider]) { private func accept(_ providers: [NSItemProvider]) {
for provider in providers { Task { @MainActor in
_ = provider.loadObject(ofClass: URL.self) { url, _ in var urls: [URL] = []
guard let url else { return } for provider in providers {
DispatchQueue.main.async { accept([url]) } let url: URL? = await withCheckedContinuation { continuation in
_ = provider.loadObject(ofClass: URL.self) { url, _ in
continuation.resume(returning: url)
}
}
if let url { urls.append(url) }
} }
accept(urls, unreadableCount: providers.count - urls.count)
} }
} }
private func accept(_ urls: [URL]) { private func accept(_ urls: [URL], unreadableCount: Int = 0) {
let fitting = urls.filter { irizDropAccepts($0, extensions: extensions) } guard isEnabled else { return }
let refusedCount = urls.count - fitting.count let fitting = urls.filter {
irizDropAccepts($0, extensions: extensions)
&& (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
&& FileManager.default.isReadableFile(atPath: $0.path)
}
let refusedCount = urls.count - fitting.count + unreadableCount
// Отказ называется вслух и с числом. Молча проглоченный файл выглядит // Отказ называется вслух и с числом. Молча проглоченный файл выглядит
// как поломка переноса, и человек пробует снова тем же способом. // как поломка переноса, и человек пробует снова тем же способом.
refused = refusedCount == 0 ? nil : "Не приняты файлы: \(refusedCount). Годятся только \(extensions.joined(separator: ", "))." refused = refusedCount == 0 ? nil
: Lf("files.refused", "Не приняты файлы: %d. Выбери доступные для чтения записи: %@.",
refusedCount, extensions.joined(separator: ", "))
guard !fitting.isEmpty else { return } guard !fitting.isEmpty else { return }
onAdd(fitting) onAdd(fitting)
} }
@@ -183,6 +199,8 @@ public struct IrizDropRow: View {
Button(action: onRemove) { Button(action: onRemove) {
IrizGlyphView(.files, size: 12).opacity(0) IrizGlyphView(.files, size: 12).opacity(0)
.overlay(Text("✕").font(.system(size: 12))) .overlay(Text("✕").font(.system(size: 12)))
.frame(minWidth: 24, minHeight: 24)
.contentShape(Rectangle())
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.foregroundStyle(IRIZ_SUBTLE) .foregroundStyle(IRIZ_SUBTLE)
+249 -69
View File
@@ -13,6 +13,17 @@ private let HOTKEY_BUTTON_WIDTH: CGFloat = 150
/// в строке подписей, иначе шапка съезжает относительно полей. /// в строке подписей, иначе шапка съезжает относительно полей.
private let CORRECTION_TRASH_WIDTH: CGFloat = 22 private let CORRECTION_TRASH_WIDTH: CGFloat = 22
/// Общий выбор страницы у окна и его содержимого. Переход не пересоздаёт
/// форму: несохранённые сочетания и очередь файлов остаются на месте.
@MainActor
public final class SettingsNavigation: ObservableObject {
@Published public var page: SettingsPage
public init(page: SettingsPage = .keys) {
self.page = page
}
}
@MainActor @MainActor
public struct IrizSettingsView: View { public struct IrizSettingsView: View {
@StateObject private var model: SettingsModel @StateObject private var model: SettingsModel
@@ -22,30 +33,49 @@ public struct IrizSettingsView: View {
@State private var transferMessage: String? @State private var transferMessage: String?
@State private var transferFailed = false @State private var transferFailed = false
@State private var appProfileMessage: String? @State private var appProfileMessage: String?
@State private var page: SettingsPage @StateObject private var navigation: SettingsNavigation
private var page: SettingsPage { navigation.page }
@State private var languageChoice: IrizLanguage = irizLanguageChoice() @State private var languageChoice: IrizLanguage = irizLanguageChoice()
@State private var appearanceChoice: IrizAppearanceChoice = irizAppearanceChoice() @State private var appearanceChoice: IrizAppearanceChoice = irizAppearanceChoice()
@State private var fileQueue: [IrizDropItem] = [] @StateObject private var files = SettingsFileTranscription()
@State private var fileLanguage: DictationLanguage = .auto
@State private var meetingQueue: [IrizDropItem] = [] @State private var meetingQueue: [IrizDropItem] = []
@State private var meetingBusy = false
@State private var meetingStopping = false
@State private var meetingResults: [MeetingArtifacts] = []
@State private var meetingProgress: String? @State private var meetingProgress: String?
@State private var meetingReport: String? @State private var meetingReport: String?
@State private var meetingFailed = false @State private var meetingFailed = false
@State private var diskEntries: [DiskUsageEntry] = [] @State private var diskEntries: [DiskUsageEntry] = []
@State private var diskCounting = false @State private var diskCounting = false
@State private var historyEntries: [DictationHistoryEntry] = [] @StateObject private var historyModel: DictationHistoryModel
@State private var historyQuery = "" private let isPreview: Bool
private let openSpeechModelSetup: (() -> Void)?
@Namespace private var sidebarGlass @Namespace private var sidebarGlass
/// Система гасит свою анимацию, но не наш `withAnimation` - морф стекла /// Система гасит свою анимацию, но не наш `withAnimation` - морф стекла
/// приходится гейтить руками (правило M07 линтера). /// приходится гейтить руками (правило M07 линтера).
@Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.accessibilityReduceMotion) private var reduceMotion
public init(preview: Bool = false, page: SettingsPage = .keys) { public init(preview: Bool = false, page: SettingsPage = .keys,
navigation: SettingsNavigation? = nil,
openSpeechModelSetup: (() -> Void)? = nil) {
_model = StateObject(wrappedValue: SettingsModel(preview: preview)) _model = StateObject(wrappedValue: SettingsModel(preview: preview))
_page = State(initialValue: page) _historyModel = StateObject(wrappedValue: DictationHistoryModel(preview: preview))
isPreview = preview
self.openSpeechModelSetup = openSpeechModelSetup
_navigation = StateObject(wrappedValue: navigation ?? SettingsNavigation(page: page))
} }
public var body: some View { public var body: some View {
glassScene glassScene
.onAppear { model.refreshSpeechModelReadiness() }
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
model.refreshSpeechModelReadiness()
}
.onReceive(NotificationCenter.default.publisher(for: speechModelDidInstallNotification)) { notification in
guard !isPreview, let profile = notification.object as? SpeechModelProfile else { return }
model.applyInstalledSpeechModel(profile)
}
} }
/// Общего `GlassEffectContainer` здесь НЕТ, и это измеренное решение. /// Общего `GlassEffectContainer` здесь НЕТ, и это измеренное решение.
@@ -174,7 +204,7 @@ public struct IrizSettingsView: View {
// Пресет вместо магических чисел: `.snappy` и есть «доехать с весом, // Пресет вместо магических чисел: `.snappy` и есть «доехать с весом,
// без игры» (правило M02 линтера). // без игры» (правило M02 линтера).
withAnimation(reduceMotion ? nil : .irizMove) { withAnimation(reduceMotion ? nil : .irizMove) {
page = item navigation.page = item
} }
} label: { } label: {
Label { Label {
@@ -240,8 +270,7 @@ public struct IrizSettingsView: View {
/// кнопка сохранения, спрятанная на одной из девяти, находится случайно. /// кнопка сохранения, спрятанная на одной из девяти, находится случайно.
private var footerBar: some View { private var footerBar: some View {
HStack(spacing: 12) { HStack(spacing: 12) {
if let message = model.validationMessage, if let message = model.validationMessage {
!message.contains(L("settings.konflikt", "Конфликт")), !message.contains("macOS") {
Label(message, systemImage: "exclamationmark.triangle.fill") Label(message, systemImage: "exclamationmark.triangle.fill")
.foregroundStyle(.red) .foregroundStyle(.red)
.accessibilityLabel(Lf("settings.error.a11y", "Ошибка настроек: %@", message)) .accessibilityLabel(Lf("settings.error.a11y", "Ошибка настроек: %@", message))
@@ -455,12 +484,7 @@ public struct IrizSettingsView: View {
} }
} }
Picker(L("settings.raspoznavatel", "Распознаватель"), selection: $model.speechEngine) { speechRecognitionControls
ForEach(SpeechModelProfile.allCases, id: \.self) { profile in
Text(profile.shortName).tag(profile)
}
}
.accessibilityLabel(L("settings.kakoyDvizhokRaspoznavaniyaRechi", "Какой движок распознавания речи использовать"))
settingsNote { settingsNote {
Text(L("settings.parakeetBystreeV11", "Parakeet быстрее в 11-15 раз, но транслитерирует английские термины внутри русской фразы: git rebase слышится как «гид репейс». Whisper large-v3 берет их латиницей (19 процентов ошибок на смешанной речи против 44), зато надиктовка в полминуты ждет расшифровки около 16 секунд. Оба считают на этом Маке, наружу не уходит ничего.")) Text(L("settings.parakeetBystreeV11", "Parakeet быстрее в 11-15 раз, но транслитерирует английские термины внутри русской фразы: git rebase слышится как «гид репейс». Whisper large-v3 берет их латиницей (19 процентов ошибок на смешанной речи против 44), зато надиктовка в полминуты ждет расшифровки около 16 секунд. Оба считают на этом Маке, наружу не уходит ничего."))
@@ -830,8 +854,49 @@ public struct IrizSettingsView: View {
} }
} }
@ViewBuilder
private var speechRecognitionControls: some View {
Picker(L("settings.raspoznavatel", "Распознаватель"), selection: $model.speechEngine) {
ForEach(SpeechModelProfile.allCases, id: \.self) { profile in
Text(profile.shortName).tag(profile)
}
}
.disabled(files.busy || meetingBusy)
.accessibilityLabel(L("settings.kakoyDvizhokRaspoznavaniyaRechi", "Какой движок распознавания речи использовать"))
VStack(alignment: .leading, spacing: 8) {
Label(model.speechModelInstalled
? Lf("settings.speechModelInstalled", "%@: модель установлена", model.speechEngine.shortName)
: Lf("settings.speechModelMissing", "%@: модель не установлена", model.speechEngine.shortName),
systemImage: model.speechModelInstalled ? "checkmark.circle" : "arrow.down.circle")
.foregroundStyle(.primary)
if !model.speechModelInstalled {
Text(model.canUseInstalledParakeet
? L("settings.parakeetAlreadyAvailable", "Parakeet уже установлен. Выбери его и сохрани настройки, чтобы использовать для диктовки.")
: L("settings.speechModelDownloadHelp", "Для распознавания нужна модель на этом Маке. Автоматически можно скачать только Parakeet: около 0,5 ГБ, один раз. После установки он станет выбранным распознавателем. Звук останется на устройстве."))
.font(.footnote)
.foregroundStyle(IRIZ_SUBTLE)
}
if !model.speechModelInstalled, model.canUseInstalledParakeet {
Button(L("settings.selectInstalledParakeet", "Выбрать установленный Parakeet")) {
model.speechEngine = .multilingualV3
}
.modifier(GlassButton())
.disabled(files.busy || meetingBusy)
} else {
Button(model.speechModelInstalled
? L("settings.speechModelSetup", "Настроить распознавание…")
: L("settings.downloadParakeet", "Скачать модель Parakeet…")) {
openSpeechModelSetup?()
}
.modifier(GlassButton())
.disabled(isPreview || openSpeechModelSetup == nil || files.busy || meetingBusy)
}
}
}
private var behaviorSection: some View { private var behaviorSection: some View {
Section { Section {
speechRecognitionControls
LabeledContent(L("settings.zaderzhkaEnter", "Задержка Enter")) { LabeledContent(L("settings.zaderzhkaEnter", "Задержка Enter")) {
HStack(spacing: 6) { HStack(spacing: 6) {
// labelsHidden обязателен: в Form(.grouped) заголовок TextField // labelsHidden обязателен: в Form(.grouped) заголовок TextField
@@ -1224,13 +1289,77 @@ public struct IrizSettingsView: View {
/// Расшифровка файлов: бросил запись - получил текст рядом с ней. /// Расшифровка файлов: бросил запись - получил текст рядом с ней.
private var filesSection: some View { private var filesSection: some View {
Section { Section {
speechRecognitionControls
IrizDropZone(title: L("settings.perenesiteZapisiSyuda", "Перенесите записи сюда"), IrizDropZone(title: L("settings.perenesiteZapisiSyuda", "Перенесите записи сюда"),
subtitle: L("settings.diktofonZvonokEksportIz", "Диктофон, звонок, экспорт из встречи. Текст ляжет рядом с файлом."), subtitle: L("settings.diktofonZvonokEksportIz", "Диктофон, звонок, экспорт из встречи. Текст ляжет рядом с файлом."),
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
enqueue(urls, into: $fileQueue) enqueue(urls, into: $files.queue)
} }
ForEach(fileQueue) { item in .disabled(files.busy)
IrizDropRow(item: item) { fileQueue.removeAll { $0.id == item.id } } Picker(L("files.language", "Язык записи"), selection: $fileLanguage) {
ForEach(DictationLanguage.allCases, id: \.self) { language in
Text(language == .auto ? L("files.languageAuto", "Определить автоматически")
: Locale.current.localizedString(forLanguageCode: language.rawValue) ?? language.rawValue)
.tag(language)
}
}
.disabled(files.busy)
ForEach(files.queue) { item in
VStack(alignment: .leading, spacing: 6) {
IrizDropRow(item: item) { files.queue.removeAll { $0.id == item.id } }
.disabled(files.busy)
if let error = files.errors[item.id] {
Label(error, systemImage: "exclamationmark.triangle.fill")
.font(.footnote)
.foregroundStyle(.orange)
.textSelection(.enabled)
let destination = AudioFileBatch.destination(forSource: item.url, in: nil)
Button(L("files.showDestination", "Показать папку результата")) {
NSWorkspace.shared.activateFileViewerSelecting([destination.deletingLastPathComponent()])
}
.modifier(GlassButton())
}
}
}
if !files.queue.isEmpty {
Button(files.errors.isEmpty ? L("files.start", "Расшифровать записи")
: L("files.retry", "Повторить оставшиеся")) {
guard !meetingBusy, !isPreview, model.speechModelInstalled else { return }
files.start(engine: model.speechEngine, language: fileLanguage)
}
.modifier(GlassProminentButton())
.disabled(files.busy || meetingBusy || isPreview || !model.speechModelInstalled)
}
if let progress = files.progress {
if let fraction = files.fraction {
ProgressView(value: fraction) { Text(progress) }
} else {
ProgressView { Text(progress) }
.controlSize(.small)
}
Button(files.stopping ? L("files.stopping", "Останавливаю после текущей записи…")
: L("files.stopAfterCurrent", "Остановить после текущей записи")) {
files.stopAfterCurrent()
}
.modifier(GlassButton())
.disabled(files.stopping)
}
if let report = files.report {
Text(report).font(.footnote).textSelection(.enabled)
}
ForEach(files.results, id: \.source) { result in
VStack(alignment: .leading, spacing: 6) {
Label(result.destination.lastPathComponent, systemImage: "checkmark.circle")
.textSelection(.enabled)
HStack {
Button(L("files.openText", "Открыть текст")) { openFileResult(result.destination) }
.modifier(GlassButton())
Button(L("files.showInFinder", "Показать в Finder")) {
NSWorkspace.shared.activateFileViewerSelecting([result.destination])
}
.modifier(GlassButton())
}
}
} }
Text(L("settings.rasshifrovkaIdetNaEtom", "Расшифровка идёт на этом Маке тем же движком, что и диктовка. " Text(L("settings.rasshifrovkaIdetNaEtom", "Расшифровка идёт на этом Маке тем же движком, что и диктовка. "
+ "Звук никуда не отправляется, а сам файл остаётся там, где лежал.")) + "Звук никуда не отправляется, а сам файл остаётся там, где лежал."))
@@ -1254,25 +1383,39 @@ public struct IrizSettingsView: View {
/// «вставить» означало бы вставить в него же. Копирование есть. /// «вставить» означало бы вставить в него же. Копирование есть.
private var historySection: some View { private var historySection: some View {
Section { Section {
if historyEntries.isEmpty { HStack(spacing: 8) {
Text(L("settings.pokaPustoNadiktovannoePoyavitsya", "Пока пусто. Надиктованное появится здесь.")) IrizGlyphView(.history, size: 13)
.foregroundStyle(IRIZ_SUBTLE) .foregroundStyle(IRIZ_SUBTLE)
} else { TextField(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"), text: $historyModel.query)
// Системная оправа `.roundedBorder` рисуется непрозрачной .textFieldStyle(.plain)
// коробкой: в стеклянном окне она читается как дырка. Своя .accessibilityLabel(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"))
// оправа - то же стекло, что у плит, только тоньше. }
HStack(spacing: 8) { .padding(.horizontal, 10)
IrizGlyphView(.history, size: 13) .padding(.vertical, 7)
.foregroundStyle(IRIZ_SUBTLE) .background(IrizSearchFieldPlate())
TextField(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"), text: $historyQuery)
.textFieldStyle(.plain)
.accessibilityLabel(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"))
}
.padding(.horizontal, 10)
.padding(.vertical, 7)
.background(IrizSearchFieldPlate())
ForEach(filteredDictationHistory(historyEntries, query: historyQuery)) { entry in if historyModel.isLoading {
ProgressView(L("history.loading", "Читаю надиктовки…"))
.controlSize(.small)
}
if let notice = historyModel.notice {
Label(notice, systemImage: historyModel.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
.foregroundStyle(historyModel.noticeIsError ? Color.red : Color.primary)
.fixedSize(horizontal: false, vertical: true)
}
if !historyModel.isLoading, historyModel.visible.isEmpty, !historyModel.noticeIsError {
Text(historyModel.entries.isEmpty
? L("settings.pokaPustoNadiktovannoePoyavitsya", "Пока пусто. Надиктованное появится здесь.")
: L("history.notFoundTitle", "Ничего не нашлось"))
.foregroundStyle(IRIZ_SUBTLE)
}
if historyModel.query.isEmpty, historyModel.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
.font(.footnote)
.foregroundStyle(IRIZ_SUBTLE)
}
ForEach(historyModel.visible) { entry in
HStack(alignment: .top, spacing: 12) {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Text(dictationHistoryPreview(entry.displayText)) Text(dictationHistoryPreview(entry.displayText))
.lineLimit(3) .lineLimit(3)
@@ -1286,55 +1429,53 @@ public struct IrizSettingsView: View {
.foregroundStyle(IRIZ_SUBTLE) .foregroundStyle(IRIZ_SUBTLE)
} }
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle()) Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
.contextMenu { .disabled(isPreview)
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) } }
} .contextMenu {
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
.disabled(isPreview)
} }
} }
} header: { } header: {
Text(L("settings.istoriyaNadiktovok", "История надиктовок")) Text(L("settings.istoriyaNadiktovok", "История надиктовок"))
} }
.onAppear { loadHistory() } .onAppear { loadHistory() }
.onDisappear { historyModel.cancelLoading() }
} }
private func loadHistory() { private func loadHistory() {
// Читается с диска при каждом открытии страницы, а не держится в historyModel.reload { try DictationStore.dictationsDirectory() }
// памяти: диктовки пишутся другим процессом окна, и кэш разъехался бы
// с диском ровно тогда, когда владелец ищет только что сказанное.
//
// В ФОНЕ и с потолком. Здесь стоял тот же дефект, что в окне истории:
// две тысячи каталогов по три файла читались синхронно, 1386 мс, и всё
// это время окно настроек не рисовалось. Владелец поймал это дважды -
// сперва в окне, потом на этой странице.
guard let root = try? DictationStore.dictationsDirectory() else { return }
Task.detached(priority: .userInitiated) {
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
await MainActor.run { historyEntries = found }
}
} }
private func copyHistory(_ entry: DictationHistoryEntry) { private func copyHistory(_ entry: DictationHistoryEntry) {
NSPasteboard.general.clearContents() guard !isPreview else { return }
NSPasteboard.general.setString(entry.displayText, forType: .string) let copied = DictationHistoryClipboard.copy(entry.displayText)
statusMessage = L("settings.skopirovanoVBuferObmena", "Скопировано в буфер обмена.") historyModel.noticeIsError = !copied
historyModel.notice = copied
? L("history.copiedTimed", "Скопировано. Буфер очистится через 2 минуты.")
: L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз.")
} }
private var meetingsSection: some View { private var meetingsSection: some View {
Section { Section {
speechRecognitionControls
IrizDropZone(title: L("settings.perenesiteZapisVstrechi", "Перенесите запись встречи"), IrizDropZone(title: L("settings.perenesiteZapisVstrechi", "Перенесите запись встречи"),
subtitle: L("settings.zapisZasedaniyaIliSozvona", "Запись заседания или созвона. Рядом ляжет протокол."), subtitle: L("meetings.storage", "Запись на русском языке. Звук и протокол сохранятся в архиве iriz; готовые файлы можно открыть отсюда."),
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
enqueue(urls, into: $meetingQueue) enqueue(urls, into: $meetingQueue)
} }
.disabled(meetingBusy)
ForEach(meetingQueue) { item in ForEach(meetingQueue) { item in
IrizDropRow(item: item) { meetingQueue.removeAll { $0.id == item.id } } IrizDropRow(item: item) { meetingQueue.removeAll { $0.id == item.id } }
.disabled(meetingBusy)
} }
if !meetingQueue.isEmpty { if !meetingQueue.isEmpty {
Button(L("settings.razobratZapisi", "Разобрать записи")) { runMeetings() } Button(meetingFailed ? L("files.retry", "Повторить оставшиеся")
: L("settings.razobratZapisi", "Разобрать записи")) { runMeetings() }
.modifier(GlassProminentButton()) .modifier(GlassProminentButton())
.disabled(meetingProgress != nil) .disabled(meetingBusy || files.busy || isPreview || !model.speechModelInstalled)
.accessibilityLabel(L("settings.razobratZapisiVstrech", "Разобрать записи встреч")) .accessibilityLabel(L("settings.razobratZapisiVstrech", "Разобрать записи встреч"))
} }
@@ -1342,9 +1483,14 @@ public struct IrizSettingsView: View {
// Ход показывается словами, а не полосой: у часовой записи // Ход показывается словами, а не полосой: у часовой записи
// полоса врёт про остаток, а название шага честно говорит, // полоса врёт про остаток, а название шага честно говорит,
// что именно сейчас происходит. // что именно сейчас происходит.
Label(meetingProgress, systemImage: "hourglass") ProgressView { Text(meetingProgress) }
.font(.footnote) .controlSize(.small)
.foregroundStyle(IRIZ_SUBTLE) Button(meetingStopping ? L("files.stopping", "Останавливаю после текущей записи…")
: L("files.stopAfterCurrent", "Остановить после текущей записи")) {
meetingStopping = true
}
.modifier(GlassButton())
.disabled(meetingStopping)
} }
if let meetingReport { if let meetingReport {
@@ -1355,6 +1501,21 @@ public struct IrizSettingsView: View {
.textSelection(.enabled) .textSelection(.enabled)
} }
ForEach(meetingResults, id: \.directory) { artifacts in
VStack(alignment: .leading, spacing: 6) {
Label(artifacts.directory.lastPathComponent, systemImage: "checkmark.circle")
.textSelection(.enabled)
HStack {
Button(L("meetings.openProtocol", "Открыть протокол")) { openFileResult(artifacts.transcript) }
.modifier(GlassButton())
Button(L("meetings.showFolder", "Показать папку встречи")) {
NSWorkspace.shared.activateFileViewerSelecting([artifacts.directory])
}
.modifier(GlassButton())
}
}
}
// Здесь продукт нарушает собственное правило, и молчать об этом // Здесь продукт нарушает собственное правило, и молчать об этом
// нельзя: в диктовке звук не сохраняется никогда, а у встречи он // нельзя: в диктовке звук не сохраняется никогда, а у встречи он
// остаётся вместе с расшифровкой. Иначе протокол нечем сверить. // остаётся вместе с расшифровкой. Иначе протокол нечем сверить.
@@ -1377,47 +1538,66 @@ public struct IrizSettingsView: View {
/// Отказ на одной записи не отменяет остальные: владелец принёс папку, и /// Отказ на одной записи не отменяет остальные: владелец принёс папку, и
/// одна битая запись не должна стоить ему разбора всех. /// одна битая запись не должна стоить ему разбора всех.
private func runMeetings() { private func runMeetings() {
guard !meetingBusy, !files.busy, !meetingQueue.isEmpty, !isPreview, model.speechModelInstalled else { return }
meetingBusy = true
meetingStopping = false
let items = meetingQueue let items = meetingQueue
let engine = model.speechEngine
meetingReport = nil meetingReport = nil
meetingFailed = false meetingFailed = false
Task { @MainActor in Task { @MainActor in
let pipeline = MeetingPipeline() let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: engine))
var done = 0 var done = 0
var failures: [String] = [] var failures: [String] = []
for item in items { for item in items {
guard !meetingStopping else { break }
let name = item.url.deletingPathExtension().lastPathComponent let name = item.url.deletingPathExtension().lastPathComponent
meetingProgress = "\(name): читаю" meetingProgress = "\(name): \(L("files.reading", "читаю запись"))"
do { do {
let result = try await pipeline.run( let result = try await pipeline.run(
audio: item.url, audio: item.url,
title: name, title: name,
progress: { step in progress: { step in
Task { @MainActor in meetingProgress = "\(name): \(step.lowercased())" } Task { @MainActor in
guard meetingBusy else { return }
meetingProgress = "\(name): \(step.lowercased())"
}
} }
) )
done += 1 done += 1
meetingQueue.removeAll { $0.id == item.id } meetingQueue.removeAll { $0.id == item.id }
meetingResults.append(result.artifacts)
if !result.speakersResolved { if !result.speakersResolved {
// Владелец должен отличить монолог от неудавшегося // Владелец должен отличить монолог от неудавшегося
// разделения: в первом случае имена расставлять не // разделения: в первом случае имена расставлять не
// нужно, во втором нужно. // нужно, во втором нужно.
failures.append("\(name): говорящие не разобраны, протокол одной репликой") failures.append(Lf("meetings.speakersUnresolved", "%@: говорящие не разделены. Текст сохранён одной репликой; проверьте протокол.", name))
} }
} catch { } catch {
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? "\(error)" let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
failures.append("\(name): \(reason)") failures.append("\(name): \(reason)")
} }
} }
meetingProgress = nil meetingProgress = nil
meetingBusy = false
meetingFailed = !failures.isEmpty meetingFailed = !failures.isEmpty
let base = done > 0 ? "Разобрано записей: \(done)." : L("settings.razobratNeUdalos", "Разобрать не удалось.") let base = Lf("files.finished", "Готово: %d из %d.", done, items.count)
meetingReport = failures.isEmpty ? base : base + " " + failures.joined(separator: "; ") + (meetingStopping ? " " + L("files.stopped", "Очередь остановлена. Оставшиеся файлы можно запустить снова.") : "")
meetingReport = failures.isEmpty ? base : base + "\n" + failures.joined(separator: "\n")
}
}
private func openFileResult(_ url: URL) {
if !NSWorkspace.shared.open(url) {
statusMessage = Lf("files.openFailed", "Не удалось открыть %@. Проверь файл через Finder.", url.lastPathComponent)
} }
} }
/// Положить файлы в очередь, не задваивая уже принесённые. /// Положить файлы в очередь, не задваивая уже принесённые.
private func enqueue(_ urls: [URL], into queue: Binding<[IrizDropItem]>) { private func enqueue(_ urls: [URL], into queue: Binding<[IrizDropItem]>) {
for url in urls where !queue.wrappedValue.contains(where: { $0.url == url }) { for source in urls {
let url = source.standardizedFileURL
guard !queue.wrappedValue.contains(where: { $0.url.standardizedFileURL == url }) else { continue }
let bytes = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int64) ?? 0 let bytes = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int64) ?? 0
queue.wrappedValue.append(IrizDropItem(url: url, bytes: bytes ?? 0)) queue.wrappedValue.append(IrizDropItem(url: url, bytes: bytes ?? 0))
} }
@@ -0,0 +1,141 @@
import Combine
import Darwin
import Foundation
import IrizCore
import IrizDictate
/// Очередь переживает смену страницы; повтор запускает только оставшиеся файлы.
@MainActor
final class SettingsFileTranscription: ObservableObject {
typealias Progress = @Sendable (String, Double?) async -> Void
typealias ProcessFile = @Sendable (AudioTranscriptionJob, AudioFileTranscriber,
DictationLanguage, @escaping Progress) async throws -> Void
@Published var queue: [IrizDropItem] = []
@Published private(set) var busy = false
@Published private(set) var stopping = false
@Published private(set) var progress: String?
@Published private(set) var fraction: Double?
@Published private(set) var report: String?
@Published private(set) var errors: [UUID: String] = [:]
@Published private(set) var results: [AudioTranscriptionJob] = []
private let processFile: ProcessFile
init(processFile: @escaping ProcessFile = SettingsFileTranscription.process) {
self.processFile = processFile
}
@discardableResult
func start(engine: SpeechModelProfile, language: DictationLanguage) -> Task<Void, Never>? {
guard !busy, !queue.isEmpty else { return nil }
// До Task: второе нажатие в том же проходе run loop уже не запустит модель.
busy = true
stopping = false
report = nil
errors = [:]
let items = queue
let transcriber = AudioFileTranscriber(engine: engine)
return Task {
var done = 0
defer {
busy = false
progress = nil
fraction = nil
report = Lf("files.finished", "Готово: %d из %d.", done, items.count)
+ (stopping ? " " + L("files.stopped", "Очередь остановлена. Оставшиеся файлы можно запустить снова.") : "")
}
for (index, item) in items.enumerated() {
guard !stopping else { break }
let name = item.url.lastPathComponent
progress = "[\(index + 1)/\(items.count)] \(name)"
fraction = nil
do {
let jobs = try await Task.detached(priority: .userInitiated) {
try AudioFileBatch.plan(inputPath: item.url.path, force: false)
}.value
guard let job = jobs.first, jobs.count == 1 else {
throw AudioBatchPlanError.pathNotReadable(item.url.path)
}
try await processFile(job, transcriber, language) { step, value in
await MainActor.run {
self.progress = "[\(index + 1)/\(items.count)] \(name): \(step)"
self.fraction = value
}
}
results.removeAll { $0.source == job.source }
results.append(job)
queue.removeAll { $0.id == item.id }
done += 1
} catch {
errors[item.id] = Self.message(for: error)
}
}
}
}
/// У распознавателя нет безопасного мгновенного прерывания. Текущий результат
/// сохраняется, следующий файл не начинается; это прямо написано на кнопке.
func stopAfterCurrent() { if busy { stopping = true } }
nonisolated private static func process(_ job: AudioTranscriptionJob,
transcriber: AudioFileTranscriber,
language: DictationLanguage,
progress: @escaping Progress) async throws {
await progress(L("files.preparing", "загружаю модель"), nil)
_ = try await transcriber.prepare()
await progress(L("files.reading", "читаю запись"), nil)
let audio = try await AudioFileDecoder.decode(job.source)
await progress(L("files.transcribing", "расшифровываю"), nil)
var reporter: Task<Void, Never>?
if AudioFileTranscriber.reportsProgress(forSamples: audio.samples.count),
let stream = await transcriber.progressStream() {
reporter = Task {
do {
for try await value in stream {
guard !Task.isCancelled else { break }
await progress(L("files.transcribing", "расшифровываю"), min(1, max(0, value)))
}
} catch { /* Текстовая стадия остаётся видимой, если поток прогресса закрыт. */ }
}
}
defer { reporter?.cancel() }
let transcript = try await transcriber.transcribe(audio, language: language)
reporter?.cancel()
await reporter?.value
await progress(L("files.saving", "сохраняю текст"), nil)
try saveTranscript(transcript.text, to: job.destination)
}
/// Готовый текст появляется целиком, с правами 0600. link отказывает при
/// существующем имени даже тогда, когда файл появился уже после plan().
nonisolated static func saveTranscript(_ text: String, to destination: URL) throws {
let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else {
throw NSError(domain: "IrizFileTranscription", code: 1,
userInfo: [NSLocalizedDescriptionKey: L("files.noSpeech", "Речь не распознана. Текстовый файл не создан.")])
}
let temporary = destination.deletingLastPathComponent()
.appendingPathComponent(".iriz-transcript-\(UUID().uuidString)")
let descriptor = Darwin.open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
PRIVATE_LOG_FILE_MODE)
guard descriptor >= 0 else { throw IrizCore.currentPOSIXError() }
defer {
_ = Darwin.close(descriptor)
_ = Darwin.unlink(temporary.path)
}
try IrizCore.writeAllData(Data((text + "\n").utf8), to: descriptor)
guard Darwin.link(temporary.path, destination.path) == 0 else {
if errno == EEXIST { throw AudioBatchPlanError.destinationExists(destination.path) }
throw IrizCore.currentPOSIXError()
}
}
nonisolated static func message(for error: Error) -> String {
if case AudioBatchPlanError.destinationExists(let path) = error {
return Lf("files.destinationExists", "Текст уже есть: %@. Открой его или переименуй исходную запись перед повтором.", path)
}
return (error as? AudioBatchPlanError)?.message
?? (error as? AudioDecodingError)?.message
?? error.localizedDescription
}
}
+34 -4
View File
@@ -194,7 +194,10 @@ final class SettingsModel: ObservableObject {
/// Какой распознаватель стоит. Выбор с ценой на обеих сторонах, поэтому он /// Какой распознаватель стоит. Выбор с ценой на обеих сторонах, поэтому он
/// у владельца, а не зашит: Whisper берет английские термины внутри русской /// у владельца, а не зашит: Whisper берет английские термины внутри русской
/// фразы, Parakeet быстрее в 11-15 раз. Разбор - `bench/BENCH-CANDIDATES-2026-09-03.md`. /// фразы, Parakeet быстрее в 11-15 раз. Разбор - `bench/BENCH-CANDIDATES-2026-09-03.md`.
@Published var speechEngine: SpeechModelProfile @Published var speechEngine: SpeechModelProfile {
didSet { refreshSpeechModelReadiness() }
}
@Published private(set) var speechModelInstalled = false
@Published var promptRecipient: PromptRecipientSetting @Published var promptRecipient: PromptRecipientSetting
/// Явные записи «приложение → профиль». Всё, чего в списке нет, получает /// Явные записи «приложение → профиль». Всё, чего в списке нет, получает
/// `promptRecipient`, поэтому отдельного «дефолтного» ряда тут не бывает. /// `promptRecipient`, поэтому отдельного «дефолтного» ряда тут не бывает.
@@ -212,6 +215,8 @@ final class SettingsModel: ObservableObject {
private let layoutSettings: LayoutSettingsAccess private let layoutSettings: LayoutSettingsAccess
private let layoutHotkeys: LayoutHotkeySettingsAccess private let layoutHotkeys: LayoutHotkeySettingsAccess
private let agentDetector: (String, PromptAgentAdapter) -> URL? private let agentDetector: (String, PromptAgentAdapter) -> URL?
private let installedSpeechEngine: () -> SpeechModelProfile
private let speechModelProbe: (SpeechModelProfile) -> Bool
private var savedLaunchAtLogin: Bool private var savedLaunchAtLogin: Bool
convenience init(preview: Bool = false) { convenience init(preview: Bool = false) {
@@ -220,7 +225,8 @@ final class SettingsModel: ObservableObject {
self.init( self.init(
dictationSettings: DictationSettings(defaults: defaults), dictationSettings: DictationSettings(defaults: defaults),
layoutSettings: .preview(defaults: defaults), layoutSettings: .preview(defaults: defaults),
layoutHotkeys: .settings(SettingsManager(defaults: defaults)) layoutHotkeys: .settings(SettingsManager(defaults: defaults)),
speechModelProbe: { _ in false }
) )
} else { } else {
self.init( self.init(
@@ -238,11 +244,15 @@ final class SettingsModel: ObservableObject {
dictationSettings: DictationSettings, dictationSettings: DictationSettings,
layoutSettings: LayoutSettingsAccess, layoutSettings: LayoutSettingsAccess,
layoutHotkeys: LayoutHotkeySettingsAccess, layoutHotkeys: LayoutHotkeySettingsAccess,
codexDetector: ((String) -> URL?)? = nil codexDetector: ((String) -> URL?)? = nil,
installedSpeechEngine: @escaping () -> SpeechModelProfile = { .installedDefault() },
speechModelProbe: @escaping (SpeechModelProfile) -> Bool = speechModelCacheExists
) { ) {
self.dictationSettings = dictationSettings self.dictationSettings = dictationSettings
self.layoutSettings = layoutSettings self.layoutSettings = layoutSettings
self.layoutHotkeys = layoutHotkeys self.layoutHotkeys = layoutHotkeys
self.installedSpeechEngine = installedSpeechEngine
self.speechModelProbe = speechModelProbe
agentDetector = codexDetector.map { detector in agentDetector = codexDetector.map { detector in
{ path, _ in detector(path) } { path, _ in detector(path) }
} ?? { path, adapter in } ?? { path, adapter in
@@ -279,6 +289,21 @@ final class SettingsModel: ObservableObject {
wavePalette = dictationSettings.dictationHUDWavePalette wavePalette = dictationSettings.dictationHUDWavePalette
rescueWindowEnabled = dictationSettings.rescueWindowEnabled rescueWindowEnabled = dictationSettings.rescueWindowEnabled
hotkeys = Self.loadHotkeys(dictationSettings: dictationSettings, layoutHotkeys: layoutHotkeys) hotkeys = Self.loadHotkeys(dictationSettings: dictationSettings, layoutHotkeys: layoutHotkeys)
refreshSpeechModelReadiness()
}
func refreshSpeechModelReadiness() {
speechModelInstalled = speechModelProbe(speechEngine)
}
var canUseInstalledParakeet: Bool {
speechEngine != .multilingualV3 && speechModelProbe(.multilingualV3)
}
/// Явная установка выбирает скачанный движок. Остальные черновики формы
/// остаются у пользователя; общая settingsDidSave сюда не подключается.
func applyInstalledSpeechModel(_ profile: SpeechModelProfile) {
speechEngine = profile
} }
/// Адаптер выбранного агента: свой CLI собирается из введённых аргументов. /// Адаптер выбранного агента: свой CLI собирается из введённых аргументов.
@@ -586,8 +611,13 @@ final class SettingsModel: ObservableObject {
launchAtLogin = true launchAtLogin = true
corrections = [] corrections = []
snippets = [] snippets = []
retentionDays = DICTATION_RETENTION_DEFAULT_DAYS
hudShowsHints = false
hudSize = DICTATION_HUD_DEFAULT_SIZE
promptGuidanceInstructions = PromptUserGuidance.none.instructions
promptGuidanceExamples = PromptUserGuidance.none.examples
promptModeEnabled = false promptModeEnabled = false
speechEngine = .whisperTurbo speechEngine = installedSpeechEngine()
promptRecipient = .codex promptRecipient = .codex
appProfiles = [] appProfiles = []
promptAgentID = PromptAgentCatalog.defaultID promptAgentID = PromptAgentCatalog.defaultID
+192
View File
@@ -1,10 +1,194 @@
import Foundation import Foundation
import IrizDictate
import IrizPrompt
import Testing import Testing
@testable import IrizApp @testable import IrizApp
@Suite("знакомство: решения, а не картинки") @Suite("знакомство: решения, а не картинки")
struct FirstRunTests { struct FirstRunTests {
@MainActor
@Test func freshInstallExplainsDownloadBeforeOtherSetupAndCanRecoverLater() throws {
let name = "ru.iriz.tests.firstRun.download.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .multilingualV3
let model = FirstRunModel(defaults: defaults, settings: settings,
refreshSystemState: false, modelProbe: { _ in false })
model.prepareForPresentation()
#expect(model.step == .welcome)
model.goNext()
#expect(model.step == .model)
#expect(model.nextButtonTitle != FirstRunCopy.next)
#expect(!model.modelInstalled)
#expect(FirstRunCopy.welcome.note?.contains("модел") == true)
#expect(FirstRunCopy.model.action?.contains("Parakeet") == true)
#expect(FirstRunCopy.model.body.contains("Без модели диктовка не работает"))
// Пропустить установку можно, но это не скрывает её при следующем запуске.
model.finish()
#expect(firstRunShouldShow(defaults: defaults, permissionsGranted: true, modelInstalled: false))
model.prepareForPresentation()
#expect(model.step == .model)
}
@MainActor
@Test func installedModelMatchesSelectedEngineAndRestartsRecognitionOnce() throws {
let name = "ru.iriz.tests.firstRun.engine.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .whisperTurbo
let model = FirstRunModel(defaults: defaults, settings: settings,
refreshSystemState: false, modelProbe: { $0 == .multilingualV3 })
model.refreshModelAvailability()
#expect(!model.modelInstalled, "Наличие Parakeet не делает выбранный Whisper готовым")
var restarts = 0
model.onSpeechModelInstalled = { restarts += 1 }
model.installationDidFinish()
#expect(settings.speechEngine == .multilingualV3)
model.refreshModelAvailability()
#expect(model.modelInstalled)
#expect(restarts == 1)
model.installationWasRefused(.alreadyInstalled)
#expect(restarts == 1, "Дублирующий callback установщика не запускает второй прогрев")
}
@MainActor
@Test func installProgressKeepsDownloadPrimaryUntilItStartsAndAllowsRetry() throws {
let name = "ru.iriz.tests.firstRun.progress.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .whisperTurbo
let model = FirstRunModel(defaults: defaults, settings: settings,
refreshSystemState: false, modelProbe: { _ in false })
model.showModelSetup()
#expect(model.modelInstallIsPrimaryAction)
model.installationDidProgress(.downloading(0.42))
#expect(model.isInstallingModel)
#expect(!model.modelInstallIsPrimaryAction)
#expect(model.nextButtonTitle == FirstRunCopy.next)
#expect(settings.speechEngine == .whisperTurbo)
model.installationDidProgress(.failed("Synthetic network failure"))
#expect(!model.isInstallingModel)
#expect(!model.modelInstalled)
#expect(model.modelInstallIsPrimaryAction)
#expect(settings.speechEngine == .whisperTurbo)
model.installationDidProgress(.downloading(0))
model.installationDidProgress(.compiling)
#expect(model.isInstallingModel)
#expect(!model.modelInstalled)
model.installationDidProgress(.finished)
#expect(model.modelInstalled)
#expect(!model.modelInstallIsPrimaryAction)
#expect(settings.speechEngine == .multilingualV3)
}
@MainActor
@Test func repairingInstalledCacheDoesNotHideProgressOrAllowTrialOnFailure() throws {
let name = "ru.iriz.tests.firstRun.repair.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .multilingualV3
let model = FirstRunModel(defaults: defaults, settings: settings,
refreshSystemState: false, modelProbe: { _ in true })
model.showModelSetup()
model.refreshModelAvailability()
#expect(model.modelIsReady)
model.installationDidProgress(.downloading(0.42))
model.refreshModelAvailability()
#expect(model.modelInstalled, "Быстрая проверка видит файлы, но не знает об их целостности")
#expect(!model.modelIsReady)
model.installationDidProgress(.failed("Synthetic corrupt cache"))
#expect(model.modelInstallIsPrimaryAction)
var audioStarted = false
model.toggleDictation = { audioStarted = true }
model.toggleTrial()
#expect(model.step == .model)
#expect(!audioStarted)
model.installationDidProgress(.finished)
#expect(model.modelIsReady)
}
@MainActor
@Test func trialWithoutModelReturnsToInstallerWithoutStartingAudio() throws {
let name = "ru.iriz.tests.firstRun.trial.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .multilingualV3
let model = FirstRunModel(defaults: defaults, settings: settings,
refreshSystemState: false, modelProbe: { _ in false })
var audioStarted = false
model.toggleDictation = { audioStarted = true }
model.toggleTrial()
#expect(model.step == .model)
#expect(!model.isRecording)
#expect(!audioStarted)
}
@MainActor
@Test func agentConnectionValidatesModelAndNotifiesRunningApp() throws {
let name = "ru.iriz.tests.firstRun.settings.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let settings = DictationSettings(defaults: defaults)
let model = FirstRunModel(defaults: defaults, settings: settings, refreshSystemState: false)
let received = FirstRunNotificationCount()
let observer = NotificationCenter.default.addObserver(
forName: DictationController.settingsDidSaveNotification,
object: settings,
queue: .main
) { _ in MainActor.assumeIsolated { received.value += 1 } }
defer { NotificationCenter.default.removeObserver(observer) }
model.connectAgent(PromptAgentCatalog.codexID)
#expect(settings.promptModeEnabled)
#expect(model.connectedAgentID == PromptAgentCatalog.codexID)
#expect(received.value == 1)
model.enableTranslation()
#expect(settings.translationModeEnabled)
#expect(received.value == 2)
model.connectAgent(PromptAgentCatalog.ollamaID)
#expect(model.agentConnectionError != nil)
#expect(settings.promptAgentID == PromptAgentCatalog.codexID)
#expect(model.connectedAgentID == PromptAgentCatalog.codexID)
#expect(received.value == 2)
settings.promptAgentModel = "local-test-model"
model.connectAgent(PromptAgentCatalog.ollamaID)
#expect(model.agentConnectionError == nil)
#expect(settings.promptAgentID == PromptAgentCatalog.ollamaID)
#expect(model.connectedAgentID == PromptAgentCatalog.ollamaID)
#expect(received.value == 3)
}
@MainActor
@Test func installationRefusalShowsRecoveryInsteadOfPendingDownload() throws {
let name = "ru.iriz.tests.firstRun.install.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defer { defaults.removePersistentDomain(forName: name) }
let model = FirstRunModel(defaults: defaults,
settings: DictationSettings(defaults: defaults),
refreshSystemState: false)
for refusal in [SpeechModelInstallRefusal.dictationBusy, .alreadyRunning] {
model.installationWasRefused(refusal)
guard case .failed(let reason) = model.installPhase else {
Issue.record("Отказ оставил установку без понятного результата")
return
}
#expect(!reason.isEmpty)
#expect(!model.modelInstalled)
}
model.installationWasRefused(.alreadyInstalled)
#expect(model.installPhase == .finished)
#expect(model.modelInstalled)
}
/// Порядок шагов - это сценарий, а не список. Разрешения идут от самого /// Порядок шагов - это сценарий, а не список. Разрешения идут от самого
/// понятного к самому пугающему: человеку, которому уже объяснили микрофон, /// понятного к самому пугающему: человеку, которому уже объяснили микрофон,
/// спокойнее отвечать на «сможет читать все нажатия». /// спокойнее отвечать на «сможет читать все нажатия».
@@ -23,6 +207,7 @@ struct FirstRunTests {
// человек щёлкает переключатели в системном окне, загрузка идёт, и // человек щёлкает переключатели в системном окне, загрузка идёт, и
// время тратится один раз, а не дважды. // время тратится один раз, а не дважды.
let model = steps.firstIndex(of: .model)! let model = steps.firstIndex(of: .model)!
#expect(model == 1, "Обязательная загрузка объясняется сразу после приветствия")
#expect(model < mic, "загрузка модели обязана начинаться раньше разрешений") #expect(model < mic, "загрузка модели обязана начинаться раньше разрешений")
#expect(model < tryIt, "проба без модели невозможна") #expect(model < tryIt, "проба без модели невозможна")
// Агент уводит речь с этого Мака, поэтому он идёт ПОСЛЕ пробы: человек // Агент уводит речь с этого Мака, поэтому он идёт ПОСЛЕ пробы: человек
@@ -80,6 +265,8 @@ struct FirstRunTests {
defaults.set(true, forKey: FIRST_RUN_COMPLETED_KEY) defaults.set(true, forKey: FIRST_RUN_COMPLETED_KEY)
#expect(!firstRunShouldShow(defaults: defaults, permissionsGranted: false), #expect(!firstRunShouldShow(defaults: defaults, permissionsGranted: false),
"знакомство повторилось после прохождения") "знакомство повторилось после прохождения")
#expect(firstRunShouldShow(defaults: defaults, permissionsGranted: true, modelInstalled: false),
"Пройденное знакомство скрывает незавершённую установку модели")
} }
/// Разрешение просит ровно тот шаг, который про него рассказывает. /// Разрешение просит ровно тот шаг, который про него рассказывает.
@@ -157,3 +344,8 @@ struct FirstRunTests {
} }
} }
} }
@MainActor
private final class FirstRunNotificationCount {
var value = 0
}
+14
View File
@@ -110,6 +110,20 @@ struct MenuStatePromiseTests {
#expect(s.permissionAlarm == "Нет доступа к Мониторингу ввода") #expect(s.permissionAlarm == "Нет доступа к Мониторингу ввода")
} }
@Test func ошибкаМоделиНеВедётКВыданнымРазрешениям() {
let s = state()
s.dictationState = .unavailable("Модель распознавания не установлена")
#expect(!s.dictationRecoveryNeedsPermissions)
s.microphoneOK = false
#expect(s.dictationRecoveryNeedsPermissions)
s.microphoneOK = true
s.inputMonitoringOK = false
#expect(s.dictationRecoveryNeedsPermissions)
s.inputMonitoringOK = true
s.inputTapOK = false
#expect(s.dictationRecoveryNeedsPermissions)
}
@Test func отвалившийсяТапВидноОтдельноОтРазрешений() { @Test func отвалившийсяТапВидноОтдельноОтРазрешений() {
// Разрешения на месте, а слежение отвалилось: разные поломки лечатся // Разрешения на месте, а слежение отвалилось: разные поломки лечатся
// по-разному, и валить их в одну строку значит отправить владельца // по-разному, и валить их в одну строку значит отправить владельца
@@ -472,9 +472,13 @@ struct CodexPromptGeneratorTests {
@Test func timeoutTerminatesFakeProcess() async throws { @Test func timeoutTerminatesFakeProcess() async throws {
let fake = try makeFakeExecutable(body: """ let fake = try makeFakeExecutable(body: """
marker=${0%/*}/process.pid exec /usr/bin/perl -e '
printf '%s' "$$" > "$marker" $SIG{INT} = $SIG{TERM} = "IGNORE";
exec /usr/bin/perl -e '$SIG{INT} = $SIG{TERM} = "IGNORE"; sleep 1 while 1' open my $marker, ">", $ARGV[0] or die $!;
print {$marker} $$;
close $marker or die $!;
sleep 1 while 1
' "${0%/*}/process.pid"
""") """)
let marker = fake.directory.appendingPathComponent("process.pid") let marker = fake.directory.appendingPathComponent("process.pid")
defer { defer {
@@ -487,14 +491,16 @@ struct CodexPromptGeneratorTests {
let started = Date() let started = Date()
do { do {
_ = try await fakeGenerator(fake, timeoutSeconds: 1) // Запуск интерпретатора под нагрузкой не обязан уложиться в секунду.
_ = try await fakeGenerator(fake, timeoutSeconds: 3)
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw)) .generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
Issue.record("Runner не сработал по таймауту") Issue.record("Runner не сработал по таймауту")
} catch let error as CodexPromptGeneratorError { } catch let error as CodexPromptGeneratorError {
#expect(error == .timedOut) #expect(error == .timedOut)
} }
let elapsed = Date().timeIntervalSince(started) let elapsed = Date().timeIntervalSince(started)
#expect(elapsed < 5) // Две попытки по 3 с плюс эскалация до SIGKILL и накладные расходы.
#expect(elapsed < 9)
let pid = try #require(processID(at: marker)) let pid = try #require(processID(at: marker))
errno = 0 errno = 0
#expect(Darwin.kill(pid, 0) == -1) #expect(Darwin.kill(pid, 0) == -1)
@@ -545,26 +551,35 @@ struct CodexPromptGeneratorTests {
printf '%s' "$count" > "$attempts" printf '%s' "$count" > "$attempts"
case "$count" in case "$count" in
1) 1)
(trap '' HUP INT TERM; /bin/sleep 5; /usr/bin/printf '%s' 'stale' > "$result"; /usr/bin/printf '%s' 'yes' > "${0%/*}/stale-wrote") & (
trap '' HUP INT TERM
while [ ! -e "${0%/*}/retry-ready" ]; do /bin/sleep 0.02; done
/usr/bin/printf '%s' 'stale' > "$result"
/usr/bin/touch "${0%/*}/stale-wrote"
) &
printf '%s' "$!" > "${0%/*}/writer.pid"
exec /bin/sleep 60 exec /bin/sleep 60
;; ;;
2) 2)
/usr/bin/printf '%s' '{"status":"ready","taskKind":"general","goal":{"text":"Fresh retry","evidence":"Fresh retry"},"context":[],"requirements":[],"constraints":[],"outputRequirements":[],"acceptance":[],"ambiguities":[],"modules":[]}' > "$result" /usr/bin/printf '%s' '{"status":"ready","taskKind":"general","goal":{"text":"Fresh retry","evidence":"Fresh retry"},"context":[],"requirements":[],"constraints":[],"outputRequirements":[],"acceptance":[],"ambiguities":[],"modules":[]}' > "$result"
/bin/sleep 3 /usr/bin/touch "${0%/*}/retry-ready"
while [ ! -e "${0%/*}/stale-wrote" ]; do /bin/sleep 0.02; done
;; ;;
*) exit 73 ;; *) exit 73 ;;
esac esac
""" """
) )
defer { try? FileManager.default.removeItem(at: fake.directory) } let writerPIDURL = fake.directory.appendingPathComponent("writer.pid")
defer {
if let pid = processID(at: writerPIDURL), Darwin.kill(pid, 0) == 0 {
_ = Darwin.kill(pid, SIGKILL)
}
try? FileManager.default.removeItem(at: fake.directory)
}
let raw = "Fresh retry" let raw = "Fresh retry"
// Времена разведены с запасом. Раньше устаревшая запись приходила // Вторая попытка ждёт устаревшую запись после своего результата:
// через 0,1 с после снятия первой попытки и должна была попасть в // порядок событий проверяется независимо от скорости машины.
// трёхсекундное окно второй - зазор в одну десятую секунды не
// переживает занятую машину. Теперь: попытка снимается на 4 с,
// устаревшая запись приходит на 5-й, вторая попытка идёт 3 с, то есть
// окно шире зазора в тридцать раз.
let generation = try await fakeGenerator(fake, timeoutSeconds: 4) let generation = try await fakeGenerator(fake, timeoutSeconds: 4)
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw)) .generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
@@ -579,14 +594,7 @@ struct CodexPromptGeneratorTests {
#expect(resultPaths[0] != resultPaths[1]) #expect(resultPaths[0] != resultPaths[1])
} }
let staleWriterURL = fake.directory.appendingPathComponent("stale-wrote") let staleWriterURL = fake.directory.appendingPathComponent("stale-wrote")
var staleWriter = "" #expect(FileManager.default.fileExists(atPath: staleWriterURL.path))
for _ in 0..<50 where staleWriter != "yes" {
staleWriter = (try? String(contentsOf: staleWriterURL)) ?? ""
if staleWriter != "yes" {
try await Task.sleep(for: .milliseconds(20))
}
}
#expect(staleWriter == "yes")
} }
@Test func inheritedStderrDoesNotHangRunner() async throws { @Test func inheritedStderrDoesNotHangRunner() async throws {
@@ -633,7 +641,7 @@ struct CodexPromptGeneratorTests {
let fake = try makeFakeExecutable(body: """ let fake = try makeFakeExecutable(body: """
marker=${0%/*}/process.pid marker=${0%/*}/process.pid
printf '%s' "$$" > "$marker" printf '%s' "$$" > "$marker"
exec /bin/sleep 5 exec /bin/sleep 60
""") """)
let marker = fake.directory.appendingPathComponent("process.pid") let marker = fake.directory.appendingPathComponent("process.pid")
defer { defer {
@@ -644,10 +652,13 @@ struct CodexPromptGeneratorTests {
} }
let raw = "Собери отчёт." let raw = "Собери отчёт."
let task = Task { let task = Task {
try await fakeGenerator(fake, timeoutSeconds: 10) try await fakeGenerator(fake, timeoutSeconds: 30)
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw)) .generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
} }
for _ in 0..<100 where processID(at: marker) == nil { defer { task.cancel() }
// Время запуска не входит в проверку скорости отмены: сначала ждём PID.
let startupDeadline = ContinuousClock.now.advanced(by: .seconds(10))
while processID(at: marker) == nil, ContinuousClock.now < startupDeadline {
try await Task.sleep(for: .milliseconds(20)) try await Task.sleep(for: .milliseconds(20))
} }
let pid = try #require(processID(at: marker)) let pid = try #require(processID(at: marker))
@@ -11,6 +11,50 @@ import Testing
@Suite("Таблицы перевода") @Suite("Таблицы перевода")
struct LocalizationTablesTests { struct LocalizationTablesTests {
@Test("перенесённое приложение читает английский и китайский из Contents/Resources")
func packagedAppReadsItsOwnLocalizationBundle() throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("iriz-localization-" + UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(at: root) }
let app = root.appendingPathComponent("relocated/iriz.app", isDirectory: true)
let contents = app.appendingPathComponent("Contents", isDirectory: true)
let resources = contents.appendingPathComponent("Resources", isDirectory: true)
try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)
let info: [String: String] = ["CFBundleIdentifier": "test.iriz.localized",
"CFBundlePackageType": "APPL",
"CFBundleExecutable": "iriz"]
try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
.write(to: contents.appendingPathComponent("Info.plist"))
let original = try #require(irizResourceBundle())
let copied = resources.appendingPathComponent("IrizApp_IrizCore.bundle", isDirectory: true)
try FileManager.default.copyItem(at: original.bundleURL, to: copied)
let host = try #require(Bundle(url: app))
let relocated = try #require(irizResourceBundle(in: host))
#expect(relocated.bundleURL.standardizedFileURL.path == copied.standardizedFileURL.path)
let key = "firstrun.welcome.title"
for language in [IrizLanguage.en, .zh] {
let expected = try #require(irizLocalizationBundle(for: language))
.localizedString(forKey: key, value: nil, table: nil)
#expect(expected != key)
let table = try #require(irizLocalizationBundle(for: language, resources: relocated))
#expect(table.localizedString(forKey: key, value: nil, table: nil) == expected)
}
}
@Test("отсутствующий ресурсный bundle возвращает nil без абсолютного build fallback")
func absentPackagedResourcesDoNotCrash() throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("iriz-no-localization-" + UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(at: root) }
let contents = root.appendingPathComponent("iriz.app/Contents", isDirectory: true)
try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
let info = ["CFBundleIdentifier": "test.iriz.missing", "CFBundlePackageType": "APPL"]
try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
.write(to: contents.appendingPathComponent("Info.plist"))
let host = try #require(Bundle(url: contents.deletingLastPathComponent()))
#expect(irizResourceBundle(in: host) == nil)
}
private func table(_ language: IrizLanguage) -> Bundle? { private func table(_ language: IrizLanguage) -> Bundle? {
irizLocalizationBundle(for: language) irizLocalizationBundle(for: language)
} }
@@ -0,0 +1,100 @@
import AppKit
import Testing
@testable import IrizDictate
@Suite("плашка: доступные кнопки и уменьшение движения")
@MainActor
struct DictationHUDAccessibilityTests {
@Test func действиеAXИспользуетАктуальнуюКнопку() {
let button = DictationHUDActionButton(action: dictationHUDActions(isRecording: false)[0])
var invoked: [DictationHUDActionID] = []
button.onPress = { invoked.append($0) }
#expect(button.isAccessibilityElement())
#expect(button.accessibilityRole() == .button)
#expect(button.accessibilityLabel() == button.action.title)
#expect(button.accessibilityPerformPress())
button.action = dictationHUDActions(isRecording: true)[0]
#expect(button.accessibilityLabel() == button.action.title)
#expect(button.toolTip == button.action.title)
#expect(button.accessibilityPerformPress())
#expect(invoked == [.record, .record])
button.isHidden = true
#expect(!button.accessibilityPerformPress())
#expect(invoked.count == 2)
}
@Test func копированиеИЗакрытиеИмеютСемантикуИДействия() {
// Обработчики-заглушки: настоящий буфер обмена тест не меняет.
let copy = DictationHUDCopyPill(frame: .zero)
let close = DictationHUDCloseRing(frame: .zero)
var copies = 0
var closes = 0
copy.title = "Скопировать"
copy.onPress = { copies += 1 }
close.onPress = { closes += 1 }
for button in [copy as NSView, close as NSView] {
#expect(button.isAccessibilityElement())
#expect(button.accessibilityRole() == .button)
#expect(button.accessibilityLabel()?.isEmpty == false)
#expect(button.accessibilityPerformPress())
}
#expect(copies == 1)
#expect(closes == 1)
copy.title = "Скопировано"
#expect(copy.accessibilityLabel() == "Скопировано")
close.isHidden = true
#expect(!close.accessibilityPerformPress())
#expect(closes == 1)
}
@Test func сменаНастройкиОстанавливаетУжеНачатыйHover() throws {
let center = NotificationCenter()
var reduced = false
let button = DictationHUDActionButton(
action: dictationHUDActions(isRecording: false)[0],
reduceMotion: { reduced }, displayOptionsCenter: center)
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
button.forceHover(true)
let layer = try #require(button.layer)
#expect(layer.animation(forKey: "irizHoverLift") != nil)
reduced = true
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
#expect(layer.animation(forKey: "irizHoverLift") == nil)
#expect(CATransform3DIsIdentity(layer.transform))
button.forceHover(false)
button.forceHover(true)
#expect(layer.animation(forKey: "irizHoverLift") == nil)
#expect(CATransform3DIsIdentity(layer.transform))
reduced = false
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
#expect(layer.animation(forKey: "irizHoverLift") != nil)
}
@Test func ожиданиеПеречитываетНастройкуБезТаймераУровня() throws {
let center = NotificationCenter()
let surface = AccessibilityHUDSurface()
var reduced = false
let presenter = DictationHUDPresenter(
level: { 0 }, pipelineState: { .transcribing }, historyHint: { "" },
reduceMotion: { reduced }, displayOptionsCenter: center, surface: { surface })
presenter.pipelineStateChanged(.transcribing)
#expect(!presenter.isPollingLevel)
#expect(try #require(surface.content).animatesWaiting)
reduced = true
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
let still = try #require(surface.content)
#expect(still.stage == .recognizing)
#expect(!still.animatesWaiting)
reduced = false
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
#expect(try #require(surface.content).animatesWaiting)
#expect(!presenter.isPollingLevel)
}
}
@MainActor
private final class AccessibilityHUDSurface: DictationHUDSurface {
var content: DictationHUDContent?
func present(_ content: DictationHUDContent) { self.content = content }
func dismiss() { content = nil }
}
@@ -131,6 +131,92 @@ struct DictationHistorySearchTests {
// MARK: - Порядок // MARK: - Порядок
@Suite("UI-MACOS-208/209: загрузка истории и приватное превью")
struct DictationHistoryLoadingTests {
@MainActor
@Test func поздняяСотняНеПерезаписываетПолныйПоиск() {
let model = DictationHistoryModel()
let recent = DictationHistoryEntry(directory: URL(fileURLWithPath: "/tmp/recent"), text: "свежее")
let older = DictationHistoryEntry(directory: URL(fileURLWithPath: "/tmp/older"), text: "старый ответ")
let partial = model.beginLoading(all: false)
let full = model.beginLoading(all: true)
model.completeLoading(.success([recent, older]), generation: full, all: true)
model.completeLoading(.success([recent]), generation: partial, all: false)
#expect(model.entries == [recent, older])
#expect(model.didLoadAll)
#expect(!model.isLoading)
let closed = model.beginLoading(all: true)
model.cancelLoading()
model.completeLoading(.success([]), generation: closed, all: true)
#expect(model.entries == [recent, older])
}
@MainActor
@Test func previewНеВызываетДажеПровайдерРеальногоКаталога() {
let model = DictationHistoryModel(preview: true)
var rootCalls = 0
model.query = "закрытая запись"
model.reload {
rootCalls += 1
throw CocoaError(.fileReadNoPermission)
}
#expect(rootCalls == 0)
#expect(model.entries.isEmpty)
#expect(!model.isLoading)
#expect(model.notice == nil)
}
@MainActor
@Test func ошибкаЧтенияНеВыдаётсяЗаПустуюИсторию() {
let model = DictationHistoryModel()
let generation = model.beginLoading(all: true)
model.completeLoading(.failure(CocoaError(.fileReadNoPermission)),
generation: generation, all: true)
#expect(!model.isLoading)
#expect(!model.didLoadAll)
#expect(model.noticeIsError)
#expect(model.notice?.isEmpty == false)
}
@MainActor
@Test func повторноеОткрытиеСЗапросомИОчисткаВидятЗаписиЗаПределамиПятисот() async throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("iriz-history-full-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
for index in 0..<503 {
_ = try makeEntryOnDisk(in: root, label: String(format: "%04d", index),
raw: index == 0 ? "самая старая искомая фраза" : "свежая запись")
}
// Это снимок для подтверждения «Очистить всё»; реальные удаления не нужны.
#expect(try readDictationHistoryEntries(in: root).count == 503)
#expect(try readDictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT).count == 100)
let model = DictationHistoryModel()
model.query = "искомая фраза"
for _ in 0..<2 {
model.reload { root }
for _ in 0..<500 {
if !model.isLoading { break }
try await Task.sleep(nanoseconds: 10_000_000)
}
#expect(!model.isLoading)
#expect(model.didLoadAll)
#expect(model.entries.count == 503)
#expect(model.visible.map(\.label) == ["0000"])
model.cancelLoading()
}
}
@Test func commandCУступаетВыделенномуТекстуПоиска() {
#expect(dictationHistoryKeyAction(keyCode: 8, charactersIgnoringModifiers: "c",
hasCommand: true, hasTextSelection: true) == .passThrough)
#expect(dictationHistoryKeyAction(keyCode: 8, charactersIgnoringModifiers: "c",
hasCommand: true, hasTextSelection: false) == .copySelected)
}
}
@Suite("Порядок записей истории") @Suite("Порядок записей истории")
struct DictationHistoryOrderTests { struct DictationHistoryOrderTests {
@@ -0,0 +1,44 @@
import Foundation
import IrizCore
import Testing
@testable import IrizDictate
@MainActor
@Suite("Кнопка записи в знакомстве и HUD")
struct DictationUIToggleTests {
private func makeController() -> (DictationController, () -> Void) {
let name = "iriz-ui-toggle-" + UUID().uuidString
let defaults = UserDefaults(suiteName: name)!
let settings = DictationSettings(defaults: defaults)
settings.playFeedbackSounds = false
let controller = DictationController(settings: settings,
insertionStats: InsertionStats(defaults: defaults))
return (controller, { removeSuiteFile(named: name, defaults: defaults) })
}
@Test("повторное нажатие завершает запись вместо отказа alreadyRecording")
func secondClickFinishesRecording() {
let (controller, cleanup) = makeController()
defer { cleanup() }
// Только пустой буфер: опора не включает микрофон и не запускает ASR.
controller.simulateActiveRecordingForTesting()
#expect(controller.isRecordingActive)
controller.toggleDictationFromUI()
#expect(!controller.isRecordingActive)
#expect(!controller.audioStateForTesting.isRunning)
#expect(controller.state == .ready)
}
@Test("нажатие во время разбора не запускает и не отменяет запись")
func busyProcessingIsPreserved() {
let (controller, cleanup) = makeController()
defer { cleanup() }
#expect(controller.beginMeetingProcessing() != nil)
controller.toggleDictationFromUI()
#expect(controller.isBusyForTesting)
#expect(controller.state == .transcribing)
#expect(!controller.isRecordingActive)
controller.stop()
}
}
@@ -14,6 +14,63 @@ import Testing
@Suite("Решения конвейера встречи") @Suite("Решения конвейера встречи")
struct MeetingPipelineTests { struct MeetingPipelineTests {
@MainActor
@Test("отменённый разбор не читает запись и не начинает распознавание")
func отменаДоНачалаОстанавливаетКонвейер() async {
let task = Task { @MainActor in
withUnsafeCurrentTask { $0?.cancel() }
var startedStages: [String] = []
do {
_ = try await MeetingPipeline().run(
audio: URL(fileURLWithPath: "/iriz-test-no-audio.wav"), title: "Встреча",
progress: { startedStages.append($0) })
Issue.record("Отменённый разбор не должен завершаться успешно")
} catch is CancellationError {
#expect(startedStages.isEmpty)
} catch {
Issue.record("Отмена подменена отказом обработки: \(error)")
}
}
await task.value
}
@Test("без времён слов полный текст сохраняется даже при успешной диаризации")
func текстБезТайминговНеТеряется() {
let spans = [SpeakerSpan(speaker: "speaker-1", start: 0, end: 12)]
let tokenCases: [[DictationTokenTiming]] = [
[], [DictationTokenTiming(token: " ", start: 0, end: 1, confidence: 1)]
]
for tokens in tokenCases {
let transcript = AudioFileTranscript(text: "Первая реплика.\nВторая реплика.",
processingSeconds: 1, audioSeconds: 12,
tokenTimings: tokens)
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans)
#expect(!resolved.speakersResolved)
#expect(resolved.turns == [SpeakerTurn(speaker: "Запись", text: transcript.text,
start: 0, end: 12)])
let document = MeetingProtocolDocument(title: "Встреча", recordedAt: Date(),
audioSeconds: 12, turns: resolved.turns)
#expect(document.text().contains(transcript.text))
}
}
@Test("при пригодных таймингах сохраняются реплики и имена говорящих")
func таймингиПозволяютРазделитьГоворящих() {
let transcript = AudioFileTranscript(text: "Да. Нет.", processingSeconds: 1, audioSeconds: 2,
tokenTimings: [
DictationTokenTiming(token: "Да.", start: 0, end: 1, confidence: 1),
DictationTokenTiming(token: "Нет.", start: 1, end: 2, confidence: 1)
])
let resolved = meetingSpeakerTurns(
transcript: transcript,
spans: [SpeakerSpan(speaker: "one", start: 0, end: 1),
SpeakerSpan(speaker: "two", start: 1, end: 2)],
names: SpeakerNames(names: ["one": "Анна", "two": "Борис"]))
#expect(resolved.speakersResolved)
#expect(resolved.turns.map(\.speaker) == ["Анна", "Борис"])
#expect(resolved.turns.map(\.text) == ["Да.", "Нет."])
}
@Test("отказы названы поимённо") @Test("отказы названы поимённо")
func отказыНазваныПоимённо() { func отказыНазваныПоимённо() {
// Разбирать будут запись заседания: «не смог» без причины неотличимо // Разбирать будут запись заседания: «не смог» без причины неотличимо
@@ -5,12 +5,41 @@
// разница между режимами - сохранённый звук, и путаница здесь стоит записи // разница между режимами - сохранённый звук, и путаница здесь стоит записи
// заседания. // заседания.
import AppKit import AppKit
import Foundation
import IrizCore
import Testing import Testing
@testable import IrizDictate @testable import IrizDictate
@Suite("Состояние записи встречи") @Suite("Состояние записи встречи")
struct MeetingRecordingStateTests { struct MeetingRecordingStateTests {
@Test("встреча записывается до трёх часов, диктовка — до двадцати минут")
func отдельныйПределВстречи() {
#expect(DictationController.recordingLimitSeconds(for: .meeting) == 3 * 60 * 60)
for purpose in [DictationRecordingPurpose.dictation, .prompt, .translation] {
#expect(DictationController.recordingLimitSeconds(for: purpose) == 20 * 60)
}
}
@MainActor
@Test("разбор встречи показывает занятость и блокирует повторное распознавание")
func разборЗанимаетОбщийКонвейер() {
let name = "iriz-meeting-processing-\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: name)!
defer { removeSuiteFile(named: name, defaults: defaults) }
let controller = DictationController(settings: DictationSettings(defaults: defaults),
insertionStats: InsertionStats(defaults: defaults))
#expect(controller.beginMeetingProcessing() != nil)
#expect(controller.state == .transcribing)
#expect(controller.isBusyForTesting)
#expect(controller.beginMeetingProcessing() == nil)
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
isBusy: controller.isBusyForTesting,
secureInputActive: false) == .transcriptionInFlight)
controller.stop()
#expect(!controller.isBusyForTesting)
}
@Test("у записи встречи свой цвет, не совпадающий ни с одним другим") @Test("у записи встречи свой цвет, не совпадающий ни с одним другим")
func свойЦвет() { func свойЦвет() {
let meeting = dictationHUDWaveColor(.meeting) let meeting = dictationHUDWaveColor(.meeting)
@@ -90,4 +90,47 @@ struct MeetingStoreTests {
let text = try String(contentsOf: second.transcript, encoding: .utf8) let text = try String(contentsOf: second.transcript, encoding: .utf8)
#expect(text == "второй") #expect(text == "второй")
} }
@Test("разные русские записи одной минуты не перезаписывают друг друга")
func коллизияНазванийНеЗатираетАрхив() throws {
let root = try sandbox()
defer { try? FileManager.default.removeItem(at: root) }
let firstAudio = try fakeAudio(in: root)
let secondAudio = root.appendingPathComponent("second.wav")
let secondData = Data([0x01, 0x02, 0x03])
try secondData.write(to: secondAudio)
let date = Date(timeIntervalSince1970: 1_757_000_000)
let first = try MeetingStore.save(audio: firstAudio, protocolText: "первый",
at: date, title: "Встреча", in: root)
let second = try MeetingStore.save(audio: secondAudio, protocolText: "второй",
at: date, title: "Заседание", in: root)
#expect(first.directory != second.directory)
#expect(try Data(contentsOf: first.audio) == Data(contentsOf: firstAudio))
#expect(try String(contentsOf: first.transcript, encoding: .utf8) == "первый")
#expect(try Data(contentsOf: second.audio) == secondData)
#expect(try String(contentsOf: second.transcript, encoding: .utf8) == "второй")
}
@Test("отказ нового сохранения оставляет старую пару целой и убирает staging")
func отказСохраненияНеРазрушаетАрхив() throws {
let root = try sandbox()
defer { try? FileManager.default.removeItem(at: root) }
let audio = try fakeAudio(in: root)
let date = Date(timeIntervalSince1970: 1_757_000_000)
let saved = try MeetingStore.save(audio: audio, protocolText: "сохранённый протокол",
at: date, title: "Встреча", in: root)
let missing = root.appendingPathComponent("missing.wav")
#expect(throws: (any Error).self) {
try MeetingStore.save(audio: missing, protocolText: "не сохранится",
at: date, title: "Встреча", in: root)
}
#expect(try Data(contentsOf: saved.audio) == Data(contentsOf: audio))
#expect(try String(contentsOf: saved.transcript, encoding: .utf8) == "сохранённый протокол")
let children = try FileManager.default.contentsOfDirectory(
at: MeetingStore.meetingsDirectory(in: root), includingPropertiesForKeys: nil)
#expect(children.map { $0.resolvingSymlinksInPath().path }
== [saved.directory.resolvingSymlinksInPath().path])
}
} }
@@ -0,0 +1,186 @@
import Foundation
import IrizCore
import Testing
@testable import IrizDictate
@Suite("Подготовка и восстановление модели без сети")
struct SpeechModelRecoveryTests {
@Test("сетевые ошибки установки объясняют причину и действие без технического кода")
func installErrorsExplainRecovery() {
let cases: [(URLError.Code, String, String)] = [
(.notConnectedToInternet, "speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание."),
(.networkConnectionLost, "speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание."),
(.timedOut, "speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже."),
(.cancelled, "speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
]
for (code, key, fallback) in cases {
let message = speechModelInstallFailureMessage(for: URLError(code))
#expect(message == L(key, fallback))
#expect(!message.contains("NSURLErrorDomain"))
}
#expect(speechModelInstallFailureMessage(for: CancellationError())
== speechModelInstallFailureMessage(for: URLError(.cancelled)))
let unknown = NSError(domain: "fixture", code: 42,
userInfo: [NSLocalizedDescriptionKey: "Подробности отказа"])
#expect(speechModelInstallFailureMessage(for: unknown) == "Подробности отказа")
}
private func sandbox() throws -> URL {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("iriz-model-recovery-" + UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
return root
}
@Test("пустая или неполная папка не означает установленную модель")
func cacheRequiresEveryModelFile() throws {
let root = try sandbox()
defer { try? FileManager.default.removeItem(at: root) }
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
for file in ModelIntegrity.parakeetV3DownloadFiles {
let target = root.appendingPathComponent(file.relativePath)
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(),
withIntermediateDirectories: true)
try Data("fixture".utf8).write(to: target)
}
// Быстрый UI-probe проверяет состав. SHA-256 проверяется отдельно.
#expect(speechModelCacheIsComplete(for: .multilingualV3, at: root))
let vocabulary = root.appendingPathComponent("parakeet_vocab.json")
try Data().write(to: vocabulary)
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
try FileManager.default.removeItem(at: vocabulary)
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
}
@Test("Whisper требует непустой файл, каталог с именем модели не подходит")
func whisperRequiresNonemptyFile() throws {
let root = try sandbox()
defer { try? FileManager.default.removeItem(at: root) }
let model = root.appendingPathComponent("ggml-large-v3-turbo.bin")
try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false)
#expect(!speechModelCacheIsComplete(for: .whisperTurbo, at: root))
try FileManager.default.removeItem(at: model)
try Data().write(to: model)
#expect(!speechModelCacheIsComplete(for: .whisperTurbo, at: root))
try Data("fixture".utf8).write(to: model)
#expect(speechModelCacheIsComplete(for: .whisperTurbo, at: root))
}
@Test("адреса скачивания ограничены файлами закреплённого манифеста")
func downloadsUsePinnedAllowlist() throws {
for file in ModelIntegrity.parakeetV3DownloadFiles {
let url = try speechModelDownloadURL(for: file)
#expect(url.scheme == "https")
#expect(url.host == "huggingface.co")
#expect(url.path.contains("/resolve/" + ModelIntegrity.parakeetV3RepositoryCommit + "/"))
#expect(!url.path.contains("/resolve/main/"))
}
#expect(throws: URLError.self) {
try speechModelDownloadURL(for: ModelFileDigest(relativePath: "../outside.bin",
sha256: String(repeating: "0", count: 64)))
}
}
@Test("публикация новой модели сохраняет предыдущую копию")
func publicationKeepsPreviousCache() throws {
let root = try sandbox()
defer { try? FileManager.default.removeItem(at: root) }
let cache = root.appendingPathComponent("cache", isDirectory: true)
let staging = root.appendingPathComponent("staging", isDirectory: true)
for url in [cache, staging] {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
}
try Data("previous".utf8).write(to: cache.appendingPathComponent("model"))
try Data("new".utf8).write(to: staging.appendingPathComponent("model"))
try publishSpeechModelCache(from: staging, to: cache)
#expect(try String(contentsOf: cache.appendingPathComponent("model"), encoding: .utf8) == "new")
let backups = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
.filter { $0.lastPathComponent.hasPrefix(".iriz-model-backup-") }
let backup = try #require(backups.first)
#expect(backups.count == 1)
#expect(try String(contentsOf: backup.appendingPathComponent("model"), encoding: .utf8) == "previous")
}
@Test("отказ публикации возвращает предыдущую модель на прежнее место")
func failedPublicationRestoresCache() throws {
let root = try sandbox()
defer { try? FileManager.default.removeItem(at: root) }
let cache = root.appendingPathComponent("cache", isDirectory: true)
try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true)
try Data("previous".utf8).write(to: cache.appendingPathComponent("model"))
#expect(throws: (any Error).self) {
try publishSpeechModelCache(from: root.appendingPathComponent("missing"), to: cache)
}
#expect(try String(contentsOf: cache.appendingPathComponent("model"), encoding: .utf8) == "previous")
let entries = try FileManager.default.contentsOfDirectory(atPath: root.path)
#expect(entries == ["cache"])
}
@MainActor
@Test("после установки можно повторить неудачный прогрев без записи и изменения настроек")
func failedPreparationCanRetry() async {
let name = "iriz-model-preparation-" + UUID().uuidString
let defaults = UserDefaults(suiteName: name)!
defer { removeSuiteFile(named: name, defaults: defaults) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .multilingualV3
let probe = ModelPreparationProbe()
let controller = DictationController(settings: settings,
insertionStats: InsertionStats(defaults: defaults),
modelLoader: { try await probe.load($0) })
#expect(controller.prepareAfterModelInstallation())
#expect(controller.state == .warmingUp)
#expect(!controller.prepareAfterModelInstallation())
await controller.pendingWarmUp?.value
guard case .unavailable = controller.state else {
Issue.record("Первый отказ загрузчика должен оставаться видимым")
return
}
#expect(controller.prepareAfterModelInstallation())
#expect(controller.state == .warmingUp)
await controller.pendingWarmUp?.value
#expect(controller.state == .ready)
#expect(!controller.isRecordingActive)
#expect(settings.speechEngine == .multilingualV3)
#expect(await probe.profiles == [.multilingualV3, .multilingualV3])
}
@MainActor
@Test("сохранённый выбор установленного движка восстанавливает unavailable без перезапуска")
func changingEngineRetriesPreparation() async {
let name = "iriz-model-selection-" + UUID().uuidString
let defaults = UserDefaults(suiteName: name)!
defer { removeSuiteFile(named: name, defaults: defaults) }
let settings = DictationSettings(defaults: defaults)
settings.speechEngine = .whisperTurbo
let probe = ModelPreparationProbe()
let controller = DictationController(settings: settings,
insertionStats: InsertionStats(defaults: defaults),
modelLoader: { try await probe.load($0) })
#expect(controller.prepareAfterModelInstallation())
await controller.pendingWarmUp?.value
guard case .unavailable = controller.state else {
Issue.record("Первый отказ должен быть видимым")
return
}
settings.speechEngine = .multilingualV3
controller.applySettings()
#expect(controller.state == .warmingUp)
await controller.pendingWarmUp?.value
#expect(controller.state == .ready)
#expect(await probe.profiles == [.whisperTurbo, .multilingualV3])
#expect(!controller.isRecordingActive)
controller.applySettings()
#expect(controller.pendingWarmUp == nil)
}
}
private actor ModelPreparationProbe {
private(set) var profiles: [SpeechModelProfile] = []
func load(_ profile: SpeechModelProfile) throws {
profiles.append(profile)
if profiles.count == 1 { throw URLError(.cannotOpenFile) }
}
}
@@ -0,0 +1,118 @@
import Foundation
import IrizDictate
import Testing
@testable import IrizSettings
@MainActor
@Suite("File transcription UI: safe queue and output")
struct SettingsFileTranscriptionTests {
@Test func preservesExistingTextAndWritesOnlyCompletePrivateResults() throws {
let root = try temporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let existing = root.appendingPathComponent("existing.txt")
try Data("owner text".utf8).write(to: existing)
#expect(throws: AudioBatchPlanError.destinationExists(existing.path)) {
try SettingsFileTranscription.saveTranscript("new text", to: existing)
}
#expect(try String(contentsOf: existing, encoding: .utf8) == "owner text")
let output = root.appendingPathComponent("result.txt")
#expect(throws: (any Error).self) {
try SettingsFileTranscription.saveTranscript(" \n ", to: output)
}
#expect(!FileManager.default.fileExists(atPath: output.path))
try SettingsFileTranscription.saveTranscript(" Complete text.\n", to: output)
#expect(try String(contentsOf: output, encoding: .utf8) == "Complete text.\n")
let attributes = try FileManager.default.attributesOfItem(atPath: output.path)
#expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600)
#expect(try !FileManager.default.contentsOfDirectory(atPath: root.path)
.contains { $0.hasPrefix(".iriz-transcript-") })
}
@Test func preventsDoubleSubmitAndRetriesOnlyFailedFiles() async throws {
let root = try temporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let first = try source("first.wav", in: root)
let second = try source("second.wav", in: root)
let attempts = Attempts()
let model = SettingsFileTranscription { job, _, language, progress in
let fail = await attempts.record(job.source, language: language)
await progress("test", 0.5)
if fail { throw CocoaError(.fileReadCorruptFile) }
try SettingsFileTranscription.saveTranscript("test transcript", to: job.destination)
}
model.queue = [first, second]
let task = model.start(engine: .whisperLargeV3, language: .english)
#expect(model.busy)
#expect(model.start(engine: .multilingualV3, language: .russian) == nil)
await task?.value
#expect(!model.busy)
#expect(model.queue == [second])
#expect(model.results.map(\.source) == [first.url])
#expect(model.errors[second.id] != nil)
#expect(model.progress == nil)
#expect(model.fraction == nil)
await model.start(engine: .whisperLargeV3, language: .english)?.value
#expect(model.queue.isEmpty)
#expect(model.errors.isEmpty)
#expect(model.results.map(\.source) == [first.url, second.url])
#expect(await attempts.sources == [first.url, second.url, second.url])
#expect(await attempts.languages == [.english, .english, .english])
}
@Test func stopFinishesCurrentFileAndKeepsRemainingQueue() async throws {
let root = try temporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let first = try source("first.wav", in: root)
let second = try source("second.wav", in: root)
let started = AsyncStream<Void>.makeStream()
let resume = AsyncStream<Void>.makeStream()
let model = SettingsFileTranscription { job, _, _, _ in
started.continuation.yield(())
for await _ in resume.stream { break }
try SettingsFileTranscription.saveTranscript("finished", to: job.destination)
}
model.queue = [first, second]
let task = model.start(engine: .multilingualV3, language: .auto)
for await _ in started.stream { break }
model.stopAfterCurrent()
resume.continuation.yield(())
await task?.value
started.continuation.finish()
resume.continuation.finish()
#expect(model.queue == [second])
#expect(model.results.map(\.source) == [first.url])
#expect(model.stopping)
#expect(!model.busy)
}
@Test func rejectsRemoteURLsBeforeAVFoundation() {
#expect(!irizDropAccepts(URL(string: "https://example.com/voice.wav")!, extensions: ["wav"]))
#expect(irizDropAccepts(URL(fileURLWithPath: "/tmp/voice.WAV"), extensions: ["wav"]))
}
private func temporaryDirectory() throws -> URL {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("iriz-file-ui-tests-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
return root
}
private func source(_ name: String, in root: URL) throws -> IrizDropItem {
let url = root.appendingPathComponent(name)
// Только имена и очередь: ASR и декодер тесты не вызывают.
try Data("fixture".utf8).write(to: url)
return IrizDropItem(url: url, bytes: 7)
}
}
private actor Attempts {
var sources: [URL] = []
var languages: [DictationLanguage] = []
func record(_ source: URL, language: DictationLanguage) -> Bool {
sources.append(source)
languages.append(language)
return source.lastPathComponent == "second.wav" && sources.filter { $0 == source }.count == 1
}
}
@@ -305,6 +305,12 @@ struct SettingsModelTests {
model.addCorrection(source: "a", replacement: "b") model.addCorrection(source: "a", replacement: "b")
model.promptModeEnabled = true model.promptModeEnabled = true
model.promptRecipient = .generic model.promptRecipient = .generic
model.retentionDays = 0
model.hudShowsHints = true
model.hudSize = .large
model.promptGuidanceInstructions = "Собирай короткий план"
model.promptGuidanceExamples = [PromptUserExample(spoken: "проверь", wanted: "Проверь проект")]
model.speechEngine = .whisperTurbo
model.codexPath = "/custom/codex" model.codexPath = "/custom/codex"
model.setHotkey(recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!, for: .prompt) model.setHotkey(recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!, for: .prompt)
fixture.dictationSettings.promptOnboardingOffered = true fixture.dictationSettings.promptOnboardingOffered = true
@@ -316,6 +322,17 @@ struct SettingsModelTests {
#expect(model.layoutMode == .fixing) #expect(model.layoutMode == .fixing)
#expect(model.launchAtLogin) #expect(model.launchAtLogin)
#expect(model.corrections.isEmpty) #expect(model.corrections.isEmpty)
#expect(model.retentionDays == DICTATION_RETENTION_DEFAULT_DAYS)
#expect(!model.hudShowsHints)
#expect(model.hudSize == DICTATION_HUD_DEFAULT_SIZE)
#expect(model.promptGuidanceInstructions.isEmpty)
#expect(model.promptGuidanceExamples.isEmpty)
#expect(model.speechEngine == .multilingualV3)
#expect(fixture.dictationSettings.speechEngine == .multilingualV3)
#expect(fixture.dictationSettings.dictationRetentionDays == DICTATION_RETENTION_DEFAULT_DAYS)
#expect(!fixture.dictationSettings.dictationHUDShowsHints)
#expect(fixture.dictationSettings.dictationHUDSize == DICTATION_HUD_DEFAULT_SIZE)
#expect(fixture.dictationSettings.promptUserGuidance == .none)
#expect(!model.promptModeEnabled) #expect(!model.promptModeEnabled)
#expect(model.promptRecipient == .codex) #expect(model.promptRecipient == .codex)
#expect(model.codexPath.isEmpty) #expect(model.codexPath.isEmpty)
@@ -439,6 +456,30 @@ struct SettingsModelTests {
#expect(model.save()) #expect(model.save())
#expect(fixture.launchAtLogin) #expect(fixture.launchAtLogin)
} }
@Test func modelReadinessTracksSelectedEngineAndInstallationKeepsOtherDrafts() {
let fixture = Fixture()
fixture.dictationSettings.speechEngine = .whisperTurbo
let model = fixture.makeModel(speechModelProbe: { $0 == .multilingualV3 })
#expect(!model.speechModelInstalled)
#expect(model.canUseInstalledParakeet)
model.speechEngine = .multilingualV3
#expect(model.speechModelInstalled)
#expect(!model.canUseInstalledParakeet)
model.speechEngine = .whisperLargeV3
#expect(!model.speechModelInstalled)
model.enterDelayText = "987"
model.promptGuidanceInstructions = "Unsaved user draft"
let savedDelay = fixture.dictationSettings.enterDelayMilliseconds
model.applyInstalledSpeechModel(.multilingualV3)
#expect(model.speechEngine == .multilingualV3)
#expect(model.speechModelInstalled)
#expect(model.enterDelayText == "987")
#expect(model.promptGuidanceInstructions == "Unsaved user draft")
#expect(fixture.dictationSettings.enterDelayMilliseconds == savedDelay)
#expect(fixture.dictationSettings.speechEngine == .whisperTurbo)
}
} }
@MainActor @MainActor
@@ -462,7 +503,8 @@ private final class Fixture {
func makeModel( func makeModel(
codexDetector: @escaping (String) -> URL? = { codexDetector: @escaping (String) -> URL? = {
DictationSettings.detectCodexExecutable(storedPath: $0) DictationSettings.detectCodexExecutable(storedPath: $0)
} },
speechModelProbe: @escaping (SpeechModelProfile) -> Bool = { _ in false }
) -> SettingsModel { ) -> SettingsModel {
SettingsModel( SettingsModel(
dictationSettings: dictationSettings, dictationSettings: dictationSettings,
@@ -473,7 +515,9 @@ private final class Fixture {
writeLaunchAtLogin: { self.launchAtLogin = $0 } writeLaunchAtLogin: { self.launchAtLogin = $0 }
), ),
layoutHotkeys: .settings(layoutHotkeySettings), layoutHotkeys: .settings(layoutHotkeySettings),
codexDetector: codexDetector codexDetector: codexDetector,
installedSpeechEngine: { .multilingualV3 },
speechModelProbe: speechModelProbe
) )
} }
} }
+41
View File
@@ -0,0 +1,41 @@
# Install iriz on macOS
[Русский](DOWNLOAD.ru.md) · [简体中文](DOWNLOAD.zh.md) · [README](../README.md)
[![Download for macOS](https://img.shields.io/badge/Download%20for%20macOS-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
This download needs an Apple Silicon Mac (M1 or newer) and macOS 14 or newer. This download does not support Intel Macs. The app is free under MIT; you do not need an account, API key, Xcode or Terminal. The default speech model downloads separately, about 500 MB. Allow extra disk space for its temporary download and installation.
## First launch
<img src="assets/pantheon/doc-onboarding.png" alt="Iris guides a gold voice ribbon onto a marble tablet beside the family column" width="100%">
1. Open the DMG and drag **iriz** onto **Applications**. Eject the disk image. Launch iriz from Applications, not from the mounted image.
2. This release is self-signed, **not notarized by Apple**. macOS cannot verify its publisher. If you trust this repository and have checked the download, try opening the app, then use System Settings → Privacy & Security → Open Anyway. Read [Apple's explanation](https://support.apple.com/en-us/102445). Do not disable Gatekeeper or override a malware warning.
3. After the welcome, choose **Download and install Parakeet** on the model step. Parakeet downloads over the internet, about 500 MB. iriz installs and selects it automatically. The screen shows progress and offers **Try again** after an error. Keep the Mac online until it says the model is ready; the DMG does not include the model.
4. Continue through the onboarding permissions for Microphone, Accessibility and Input Monitoring. They let iriz hear your voice, insert text and respond to the dictation key. Reopen the app if macOS asks you to. You can complete these steps while the model downloads; wait for readiness before dictating.
5. Focus an empty text field. Press the dictation key shown in onboarding (right Command by default), say a short sentence, then press it again. The text should appear in that field.
If you skip the model step, layout repair still works, but dictation needs a model. Open **iriz → Settings → Dictation → Download Parakeet model…** to return to model setup. If a model is already installed, the button reads **Set up speech recognition…**. Parakeet is the only model the app installs automatically. The recognition picker also lists other engines, but their model files need separate installation, which this guide does not cover. Parakeet does not recognize Chinese. Interface language and speech language are separate settings.
## If something stops
No model or a failed download: return to **Settings → Dictation**, reopen model setup and retry. Check internet access and free disk space. No sound: check microphone permission and the selected input. No pasted text: check Accessibility; the transcript remains available in the overlay or history. A shortcut that does nothing usually needs Input Monitoring or a different key.
For help, open an [issue](https://github.com/zarubinvibe/iriz/issues) with the app version, macOS version, chip and steps that failed. Do not attach private recordings, transcripts or full logs without inspecting them.
## Update or go back
Read the [release notes](https://github.com/zarubinvibe/iriz/releases/latest), download the new DMG and quit iriz before replacing the app in Applications. Keep the previous app or its DMG until the new one works. Models, preferences and history live outside the app bundle and are not removed by replacing it. macOS may ask you to grant permissions again after a signature change.
There is no background updater. The download button follows the latest published release; unfinished drafts do not replace it. To go back, quit iriz and restore the previous app. Back up local data before trying an older version: a future release may change its storage format.
## Verify the download
The release includes **SHA256SUMS.txt** and **release-manifest.json** (version, architectures and signing status). Compare the DMG's SHA-256 with the entry for its exact filename:
```bash
shasum -a 256 ~/Downloads/iriz-macos-arm64.dmg
```
A matching checksum detects corruption; it does not replace Apple's publisher verification. For building and releasing from source, see [RELEASING.md](RELEASING.md). The [full walkthrough](ONBOARDING.md) explains the other app surfaces.
+41
View File
@@ -0,0 +1,41 @@
# Установить iriz на macOS
[English](DOWNLOAD.md) · [简体中文](DOWNLOAD.zh.md) · [README](../README.ru.md)
[![Скачать для macOS](https://img.shields.io/badge/Скачать%20для%20macOS-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
Нужен Мак с Apple Silicon (M1 или новее) на macOS 14 или новее. Этот файл не поддерживает Маки с Intel. Приложение бесплатное, лицензия MIT. Аккаунт, API-ключ, Xcode и терминал не нужны. Модель распознавания скачивается отдельно, около 500 МБ. Оставь запас места для временных файлов загрузки и установки.
## Первый запуск
<img src="assets/pantheon/doc-onboarding.png" alt="Ирида направляет золотую ленту голоса на мраморную табличку рядом с колонной семьи" width="100%">
1. Открой DMG и перетащи **iriz** в **Applications**. Извлеки образ. Запускай iriz из папки приложений, а не со смонтированного диска.
2. У этого выпуска самоподпись, **нотаризации Apple нет**. macOS не подтверждает издателя. Если доверяешь репозиторию и проверил файл, попробуй открыть приложение, затем выбери «Системные настройки → Конфиденциальность и безопасность → Все равно открыть». [Объяснение Apple](https://support.apple.com/en-us/102445). Не отключай Gatekeeper и не обходи предупреждение о вредоносном ПО.
3. После приветствия на шаге модели нажми **«Скачать и установить Parakeet»**. Parakeet загрузится через интернет, около 500 МБ. iriz сам установит и выберет модель. На экране виден прогресс; после ошибки есть кнопка **«Попробовать снова»**. Дождись готовности модели. Внутри DMG ее нет.
4. Дальше в знакомстве выдай доступ к микрофону, универсальному доступу и мониторингу ввода. Они нужны, чтобы слышать речь, вставлять текст и реагировать на клавишу диктовки. Перезапусти приложение, если macOS попросит. Разрешения можно выдать, пока модель скачивается; перед диктовкой дождись ее готовности.
5. Поставь курсор в пустое текстовое поле. Нажми клавишу из знакомства (по умолчанию правый Command), скажи короткую фразу и нажми еще раз. Текст должен появиться в этом поле.
Пропустил модель? Исправление раскладки работает и без нее, диктовка нет. Открой **iriz → Настройки → Диктовка → Скачать модель Parakeet…**, чтобы вернуться к установке. Если модель уже установлена, кнопка называется **«Настроить распознавание…»**. Автоматически приложение устанавливает только Parakeet. В списке распознавателей есть другие движки, но их модели нужно установить отдельно; эта инструкция такой установки не описывает. Parakeet не распознает китайскую речь. Язык интерфейса и язык речи настраиваются отдельно.
## Если что-то не работает
Нет модели или загрузка оборвалась: вернись в **«Настройки → Диктовка»**, открой установку модели и повтори. Проверь интернет и свободное место. Нет звука: проверь доступ к микрофону и выбранный вход. Текст не вставился: проверь универсальный доступ; расшифровку можно забрать из плашки или истории. Клавиша не отвечает: проверь мониторинг ввода или выбери другую.
Для помощи открой [issue](https://github.com/zarubinvibe/iriz/issues): укажи версию приложения, macOS, чип и шаги до ошибки. Не прикладывай частные записи, расшифровки и полные логи без проверки содержимого.
## Обновление и возврат
Прочитай [что изменилось](https://github.com/zarubinvibe/iriz/releases/latest), скачай новый DMG и закрой iriz перед заменой в Applications. Сохрани прежнее приложение или DMG, пока не проверишь новое. Модели, настройки и история лежат вне пакета приложения; замена их не удаляет. После смены подписи macOS может снова запросить разрешения.
Фонового обновления нет. Кнопка скачивания ведет на последний опубликованный выпуск, черновики ее не меняют. Чтобы вернуться, закрой iriz и восстанови прежнее приложение. Перед запуском старой версии сохрани копию данных: будущие выпуски могут менять формат хранения.
## Проверка скачанного файла
В выпуске есть **SHA256SUMS.txt** и **release-manifest.json** с версией, архитектурами и статусом подписи. Сравни SHA-256 образа со строкой для его точного имени:
```bash
shasum -a 256 ~/Downloads/iriz-macos-arm64.dmg
```
Совпадение суммы выявляет повреждение файла, но не заменяет проверку издателя Apple. Сборка из исходников описана в [RELEASING.md](RELEASING.md). Остальные экраны приложения разобраны в [пошаговом знакомстве](ONBOARDING.ru.md).
+41
View File
@@ -0,0 +1,41 @@
# 在 macOS 上安装 iriz
[English](DOWNLOAD.md) · [Русский](DOWNLOAD.ru.md) · [README](../README.zh.md)
[![下载 macOS 版](https://img.shields.io/badge/下载%20macOS%20版-111111?style=for-the-badge&logo=apple&logoColor=white)](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
需要 Apple Silicon Mac(M1 或更新)和 macOS 14 或更新版本。此下载不支持 Intel Mac。应用采用 MIT 许可证,免费使用,不需要账号、API 密钥、Xcode 或终端。语音模型另行下载,约 500 MB;还需为下载和安装的临时文件留出空间。
## 首次启动
<img src="assets/pantheon/doc-onboarding.png" alt="伊里斯引导金色语音丝带落在大理石板上,旁边矗立着家族石柱" width="100%">
1. 打开 DMG,将 **iriz** 拖入 **Applications**,然后推出磁盘映像。请从 Applications 启动,不要从已挂载的映像运行。
2. 此版本使用自签名,**尚未通过 Apple 公证**,macOS 无法验证发布者。如果你信任此仓库并已核对文件,尝试打开应用后,可前往“系统设置 → 隐私与安全性 → 仍要打开”。请阅读 [Apple 的说明](https://support.apple.com/en-us/102445)。不要关闭 Gatekeeper,也不要绕过恶意软件警告。
3. 欢迎页之后,在模型步骤点击**下载并安装 Parakeet**。Parakeet 通过网络下载,约 500 MB;iriz 会自动安装并选用它。界面显示进度,失败后可点击**重试**。保持联网直到模型就绪;DMG 不包含模型。
4. 继续按引导授予麦克风、辅助功能和输入监控权限,分别用于收音、插入文字和响应听写快捷键。若 macOS 要求,请重新启动应用。模型下载期间可以完成授权,开始听写前请等待模型就绪。
5. 将光标放入空白文本框。按引导中显示的听写键(默认右侧 Command),说一句话,再按一次,文字应出现在该文本框中。
如果跳过模型步骤,键盘布局修正仍可使用,但听写需要模型。打开 **iriz → 设置 → 口述 → 下载 Parakeet 模型…**,即可返回模型安装页。已有模型时,按钮显示为**设置语音识别…**。应用只提供 Parakeet 的自动安装。识别引擎列表也有其他选项,但需要另行安装对应模型,本指南不介绍该过程。Parakeet 不识别中文语音。界面语言与语音语言是两项独立设置。
## 遇到问题
模型缺失或下载失败:回到**设置 → 口述**,重新打开模型安装页并重试,同时检查网络和磁盘空间。没有声音:检查麦克风权限及输入设备。文字未粘贴:检查辅助功能权限,转写仍可从浮窗或历史中取出。快捷键无响应:检查输入监控权限,或选择另一个键。
需要帮助时,提交 [issue](https://github.com/zarubinvibe/iriz/issues),附上应用版本、macOS 版本、芯片和复现步骤。检查内容后再附日志,不要公开私人录音或转写。
## 更新与回退
阅读[更新说明](https://github.com/zarubinvibe/iriz/releases/latest),下载新 DMG,退出 iriz 后再替换 Applications 中的应用。保留旧应用或旧 DMG,直到确认新版可用。模型、偏好设置和历史保存在应用包之外,替换应用不会删除它们。签名变化后,macOS 可能再次要求授权。
应用没有后台更新器。下载按钮指向最新正式发布的版本,草稿不会改变此链接。回退时先退出 iriz,再恢复旧应用。运行旧版本前请备份数据,因为未来版本可能改变存储格式。
## 核对下载文件
每个版本附带 **SHA256SUMS.txt** 和 **release-manifest.json**,记录版本、架构及签名状态。运行以下命令,将结果与校验文件中完全相同的文件名对应的值比较:
```bash
shasum -a 256 ~/Downloads/iriz-macos-arm64.dmg
```
哈希一致可以检查文件是否损坏,但不能替代 Apple 对发布者的验证。从源码构建见 [RELEASING.md](RELEASING.md),其他界面的介绍见[完整引导](ONBOARDING.zh.md)。
+33 -19
View File
@@ -8,10 +8,10 @@ Hello. I am Fil, a lawyer who vibe-codes, and I wrote iriz.
From here an agent takes over. It will tell you what it is about to do BEFORE it does it, and From here an agent takes over. It will tell you what it is about to do BEFORE it does it, and
name the price of every step: what appears on the disk, where the time goes, where you have a name the price of every step: what appears on the disk, where the time goes, where you have a
choice. If something does not suit you, say so right in the chat — a step can be skipped. choice. If something does not suit you, say so right in the chat. A step can be skipped.
One promise this whole thing was built for: the audio of your speech never leaves the machine. One promise this whole thing was built for: the audio of your speech never leaves the machine.
The single trip to the network is the speech model download, and you start it with a button. You download the speech model over the network by pressing a button.
<!-- owner-greeting:end --> <!-- owner-greeting:end -->
@@ -55,35 +55,49 @@ dependencies (about 300 MB into `.build`) and puts the finished app into `/Appli
**What you get:** an icon in the menu bar at the top right, and the welcome window. **What you get:** an icon in the menu bar at the top right, and the welcome window.
**Fork:** if you would rather not hand over `/Applications`, say so — we build into the project **Fork:** if you would rather not hand over `/Applications`, say so. We build into the project
folder and run it from there. folder and run it from there.
## Step 4: grant the permissions and download the model ## Step 4: download the model and grant permissions
**What I do:** walk you through three macOS permissions — microphone, Accessibility, Input **What I do:** take you to the second step of the welcome window, right after the greeting.
Monitoring — and start the speech model download. Click "Download and install Parakeet". iriz downloads about 500 MB, installs the model and
selects it for recognition. The window shows progress; download time depends on your connection.
While it runs, you can click "Next" and grant the macOS permissions.
**Why:** without the microphone there is nothing to hear, without Accessibility there is **Why:** dictation needs a model. The microphone lets iriz hear you, Accessibility lets it
nowhere to paste, without Input Monitoring the key is not heard at all. The model is the half paste text, and Input Monitoring lets it hear the hotkey. After installation, recognition
a gigabyte for which the app goes online exactly once. runs on your Mac without an internet connection.
**What changes on disk:** the model lands in `~/Library/Application Support/iriz/Models`. The **What changes on disk:** the model lands in
permissions are written into the macOS database, not into the app. `~/Library/Application Support/FluidAudio/Models/parakeet-tdt-0.6b-v3`.
You do not need to move files yourself. macOS stores the permissions in its system database,
not in the app.
**What you get:** working dictation. Press the key, say a sentence, press again — the text **Fork:** "Download later" skips the download. To return, open Settings → Dictation →
lands where the cursor was blinking. "Download Parakeet model…". The trial step also has a "Set up the model" button when the model
is missing. If the download fails, read the reason in the window and click "Try again" after
addressing it. We wait for the model before trying dictation.
**What you get:** once the model is installed and permissions are granted, we test dictation
in the welcome window. Press the key, say a sentence, press again. The text appears in the
trial field.
## Step 5: check that it is all honest ## Step 5: check that it is all honest
**What I do:** run the project gates and show you their whole output. **What I do:** after the model download, run the tests and project gates, show you the output
and point out any skipped checks.
**Why:** the promise «the audio never leaves the machine» is checked by an instrument, not by a **Why:** the network gate compares the built binary's networking symbols with a baseline.
paragraph in the README. The gate kicks the set of networking symbols in the built binary and If the app is running from `/Applications`, it also checks its open sockets at that moment.
asks the kernel whether the running app holds a single open socket. Otherwise it skips that check. A snapshot cannot prove the app has never connected to the
network; connections are expected during a model download.
**What changes on disk:** nothing. The gates only read and count. **What changes on disk:** tests update `.build` and write logs. The gates also clean up their
temporary test files.
**What you get:** a green report you saw with your own eyes instead of taking on trust. **What you get:** a report of the checks that ran. Failures and skipped checks stay in the
report; they do not become a promise that everything works.
```bash ```bash
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
+44 -31
View File
@@ -6,40 +6,40 @@
Привет. Я Фил, юрист и вайб-кодер, и это я написал iriz. Привет. Я Фил, юрист и вайб-кодер, и это я написал iriz.
Дальше вами займется агент. Он будет говорить, что делает, ДО того как сделает, и называть цену Дальше тобой займется агент. Он будет говорить, что делает, ДО того как сделает, и называть цену
каждого шага: что появится на диске, куда уйдет время, где у вас есть выбор. Если что-то из каждого шага: что появится на диске, куда уйдет время, где у тебя есть выбор. Если что-то из
сказанного вам не подходит — скажите об этом прямо в чате, шаг можно пропустить. сказанного тебе не подходит, скажи об этом прямо в чате, шаг можно пропустить.
Одно обещание, ради которого все затевалось: звук вашей речи не уходит с машины. Единственный Одно обещание, ради которого все затевалось: звук твоей речи не уходит с машины. Модель
поход в сеть — скачивание модели распознавания, и запускаете его вы кнопкой. распознавания скачивается по сети, и запускаешь загрузку ты кнопкой.
<!-- owner-greeting:end --> <!-- owner-greeting:end -->
## Шаг 1: смотрим, на чем вы запускаете ## Шаг 1: смотрим, на чем ты запускаешь
**Что я делаю:** проверяю версию macOS, процессор и наличие Xcode со Swift 6. **Что я делаю:** проверяю версию macOS, процессор и наличие Xcode со Swift 6.
**Зачем:** iriz живет на macOS 14 и новее. Стеклянная плашка и настоящий Liquid Glass — это **Зачем:** iriz живет на macOS 14 и новее. Стеклянная плашка и настоящий Liquid Glass требуют
macOS 26; на 14 и 15 приложение работает, но плашка рисуется прежним способом. Знать это лучше macOS 26; на 14 и 15 приложение работает, но плашка рисуется прежним способом. Знать это лучше
сейчас, чем после сборки. сейчас, чем после сборки.
**Что меняется на диске:** ничего. Это чтение. **Что меняется на диске:** ничего. Это чтение.
**Что вы получите:** ответ, пойдет ли дальше, и на какой ветке визуала вы окажетесь. **Что ты получишь:** ответ, пойдет ли дальше, и на какой ветке визуала ты окажешься.
**Развилка:** нет Xcode — не беда. Возьмите готовый образ со страницы Releases, и шаги про **Развилка:** нет Xcode, не беда. Возьми готовый образ со страницы Releases, и шаги про
сборку мы пропустим. сборку мы пропустим.
## Шаг 2: приносим исходники ## Шаг 2: приносим исходники
**Что я делаю:** клонирую репозиторий в папку, которую вы назовете, или распаковываю ZIP. **Что я делаю:** клонирую репозиторий в папку, которую ты назовешь, или распаковываю ZIP.
**Зачем:** дальше все делается внутри этой папки, и она должна быть там, где вам удобно ее **Зачем:** дальше все делается внутри этой папки, и она должна быть там, где тебе удобно ее
потом найти. потом найти.
**Что меняется на диске:** появляется одна папка, около 40 МБ. Больше ничего никуда не пишется. **Что меняется на диске:** появляется одна папка, около 40 МБ. Больше ничего никуда не пишется.
**Что вы получите:** дерево проекта, в котором видно `Sources`, `Tests`, `scripts` и `docs`. **Что ты получишь:** дерево проекта, в котором видно `Sources`, `Tests`, `scripts` и `docs`.
## Шаг 3: собираем приложение ## Шаг 3: собираем приложение
@@ -47,43 +47,56 @@ macOS 26; на 14 и 15 приложение работает, но плашка
`bash install.sh --build`. `bash install.sh --build`.
**Зачем:** без флага установщик ничего не ставит. Он рассказывает, что это за программа, **Зачем:** без флага установщик ничего не ставит. Он рассказывает, что это за программа,
смотрит, чего не хватает на машине, и гоняет самопроверку дерева. Это ваша возможность смотрит, чего не хватает на машине, и гоняет самопроверку дерева. Это твоя возможность
остановиться до того, как что-то произойдет. остановиться до того, как что-то произойдет.
**Что меняется на диске:** первая команда не меняет ничего. Вторая тянет зависимости Swift **Что меняется на диске:** первая команда не меняет ничего. Вторая тянет зависимости Swift
(около 300 МБ в `.build`) и кладет готовое приложение в `/Applications`. (около 300 МБ в `.build`) и кладет готовое приложение в `/Applications`.
**Что вы получите:** значок в строке меню наверху справа и окно знакомства. **Что ты получишь:** значок в строке меню наверху справа и окно знакомства.
**Развилка:** не хотите отдавать `/Applications` — скажите, соберем в папку проекта и запустим **Развилка:** не хочешь отдавать `/Applications`, скажи, соберем в папку проекта и запустим
оттуда. оттуда.
## Шаг 4: выдаем разрешения и качаем модель ## Шаг 4: скачиваем модель и выдаем разрешения
**Что я делаю:** веду вас по трем разрешениям macOS — микрофон, Универсальный доступ, **Что я делаю:** веду тебя ко второму шагу окна знакомства, сразу после приветствия.
Мониторинг ввода — и запускаю скачивание модели распознавания. Здесь ты нажимаешь «Скачать и установить Parakeet». iriz сам скачает около 500 МБ, установит
модель и выберет ее для распознавания. Ход загрузки виден в окне; время зависит от соединения.
Пока она идет, можно нажать «Дальше» и заняться разрешениями macOS.
**Зачем:** без микрофона нечего слушать, без Универсального доступа некуда вставить текст, без **Зачем:** без модели диктовка не работает. Микрофон нужен, чтобы слышать тебя, Универсальный
Мониторинга ввода не слышно клавишу. Модель — это те самые полгигабайта, ради которых доступ нужен для вставки текста, Мониторинг ввода для горячей клавиши. После установки
приложение один раз идет в сеть. распознавание работает на твоем Маке без интернета.
**Что меняется на диске:** модель ложится в `~/Library/Application Support/iriz/Models`. **Что меняется на диске:** модель ложится в
Разрешения записываются в системную базу macOS, а не в приложение. `~/Library/Application Support/FluidAudio/Models/parakeet-tdt-0.6b-v3`.
Файлы вручную переносить не нужно. Разрешения записываются в системную базу macOS,
а не в приложение.
**Что вы получите:** рабочую диктовку. Нажали клавишу, сказали фразу, нажали еще раз — текст **Развилка:** «Скачать позже» пропускает загрузку. Вернуться можно из настроек:
встал туда, где мигал курсор. «Диктовка» → «Скачать модель Parakeet…». На шаге пробы без модели тоже есть кнопка
«К установке модели». Если загрузка завершилась ошибкой, прочитай причину в окне и нажми
«Попробовать снова» после ее устранения. Без модели пробу не начинаем.
**Что ты получишь:** после установки модели и выдачи разрешений проверим диктовку в окне
знакомства. Нажми клавишу, скажи фразу, нажми еще раз. Текст появится в поле пробы.
## Шаг 5: проверяем, что все честно ## Шаг 5: проверяем, что все честно
**Что я делаю:** прогоняю ворота проекта и показываю вам их вывод целиком. **Что я делаю:** после загрузки модели запускаю тесты и ворота проекта, показываю тебе вывод
и отмечаю пропущенные проверки.
**Зачем:** обещание «звук не уходит с машины» проверяется прибором, а не абзацем в README. **Зачем:** сетевой гейт сравнивает набор сетевых символов в собранном бинарнике с эталоном.
Ворота пинают набор сетевых символов в собранном бинарнике и спрашивают у ядра, есть ли у Если приложение запущено из `/Applications`, он также смотрит его открытые сокеты в момент
работающего приложения хоть один открытый сокет. проверки. Если не запущено, эта часть пропускается. Такой снимок не доказывает, что приложение
никогда не выходило в сеть; во время скачивания модели соединения ожидаемы.
**Что меняется на диске:** ничего. Ворота только читают и считают. **Что меняется на диске:** тесты обновляют `.build` и пишут служебные логи. Ворота также
убирают временные файлы своих тестов.
**Что вы получите:** зеленый отчет, который вы видели своими глазами, а не поверили на слово. **Что ты получишь:** отчет о выполненных проверках. Если есть отказ или пропуск, он останется
в отчете, а не превратится в обещание, что все работает.
```bash ```bash
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
+23 -14
View File
@@ -9,8 +9,8 @@
接下来由代理带你走。它会在动手之前先说明要做什么,并说清每一步的代价:磁盘上会多出什么、时间花 接下来由代理带你走。它会在动手之前先说明要做什么,并说清每一步的代价:磁盘上会多出什么、时间花
在哪里、哪里由你选择。如果哪一步不合适,直接在对话里说,可以跳过。 在哪里、哪里由你选择。如果哪一步不合适,直接在对话里说,可以跳过。
这件事从头到尾只为一个承诺:你说话的声音不会离开这台机器。唯一一次联网是下载识别模型,而且由你 这件事从头到尾只为一个承诺:你说话的声音不会离开这台机器。识别模型需要联网下载,由你按下按钮
按下按钮才开始。 才开始。
<!-- owner-greeting:end --> <!-- owner-greeting:end -->
@@ -52,28 +52,37 @@
**岔路:** 如果你不想动 `/Applications`,说一声,我们就构建到项目文件夹里,从那里运行。 **岔路:** 如果你不想动 `/Applications`,说一声,我们就构建到项目文件夹里,从那里运行。
## 第 4 步:授予权限并下载模型 ## 第 4 步:下载模型并授予权限
**我在做什么:** 带你过三项 macOS 权限——麦克风、辅助功能、输入监控——然后开始下载识别模型。 **我在做什么:** 带你进入欢迎窗口的第二步,就在问候之后。点击“下载并安装 Parakeet”,iriz 会下载
约 500 MB 的文件,安装模型并将它选为识别引擎。窗口会显示进度,下载时间取决于网络速度。下载期间
可以点“下一步”,继续授予 macOS 权限。
**为什么:** 没有麦克风就没有可听的;没有辅助功能,文字没地方粘贴;没有输入监控,按键根本听不 **为什么:** 没有模型就无法听写。麦克风让 iriz 听到你说话,辅助功能用于粘贴文字,输入监控用于
到。模型就是那半个 GB,应用一生只为它联网一次。 响应快捷键。安装完成后,语音识别在你的 Mac 上运行,不需要联网。
**磁盘上会改变什么:** 模型放到 `~/Library/Application Support/iriz/Models`。权限写进 macOS **磁盘上会改变什么:** 模型放到
的系统数据库,不写进应用。 `~/Library/Application Support/FluidAudio/Models/parakeet-tdt-0.6b-v3`。
你不用手动移动文件。权限写进 macOS 的系统数据库,不写进应用。
**你会得到:** 可以用的口述。按键,说一句话,再按一下——文字就落在光标闪烁的地方。 **岔路:** “稍后下载”会跳过下载。之后可以从设置 → 口述 →“下载 Parakeet 模型…”返回安装页面。
如果模型还没装好,试用步骤也有“前往安装模型”按钮。下载失败时,先看窗口里的原因,处理后再点
“重试”。模型装好后,我们再尝试听写。
**你会得到:** 模型装好、权限授予后,我们在欢迎窗口里测试听写。按键,说一句话,再按一下,文字
会出现在试用输入框中。
## 第 5 步:验证这一切是不是诚实的 ## 第 5 步:验证这一切是不是诚实的
**我在做什么:** 运行项目的闸门,并把它们的完整输出给你看。 **我在做什么:** 模型下载完成后,运行测试和项目闸门,给你看输出,并指出跳过了哪些检查。
**为什么:** “声音不会离开这台机器”这个承诺,要由工具来验证,而不是 README 里的一段话。闸门会 **为什么:** 网络闸门把构建出的二进制中的网络符号与基准比较。如果应用从 `/Applications` 运行,
在构建出的二进制里踢一遍网络相关符号,并向内核询问运行中的应用有没有打开任何一个套接字。 还会查看它在检查那一刻打开的套接字;应用没运行时会跳过这项检查。一次快照不能证明应用从未联网,
而下载模型时出现网络连接是正常的。
**磁盘上会改变什么:** 什么都不改。闸门只读取和统计。 **磁盘上会改变什么:** 测试会更新 `.build` 并写入日志,闸门还会清理自己的临时测试文件。
**你会得到:** 一份你亲眼看过的绿色报告,而不是听人保证。 **你会得到:** 一份实际检查结果的报告。失败和跳过的检查都会写明,不会被改成“一切正常”的保证。
```bash ```bash
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
+76
View File
@@ -0,0 +1,76 @@
# Build a macOS release
The user install starts at [DOWNLOAD.md](DOWNLOAD.md). This page is for maintainers. The release builder does not stop or replace an installed app.
## One version, two file names
`RELEASE_VERSION` is the version source for local installs and release builds. Set it to a numeric `major.minor.patch`, such as `0.2.1`, and add reviewed notes under `docs/releases/v<version>.md`.
The default build targets Apple Silicon on macOS 14+. It produces:
| File | Purpose |
|---|---|
| `iriz-<version>-arm64.dmg` | Versioned download for archives and rollback |
| `iriz-macos-arm64.dmg` | Stable filename used by the README button |
| `SHA256SUMS.txt` | SHA-256 of the images and manifest |
| `release-manifest.json` | Source commit, dirty-tree flag, version, signing status and image hashes |
The two images are byte-identical. GitHub supports [a latest-release asset URL](https://docs.github.com/en/repositories/releasing-projects-on-github/linking-to-releases), so every published release must retain the stable filename. Never mark a draft as Latest before its assets are complete.
## Build and check locally
Use macOS with Xcode and Swift 6. Dependencies come from `Package.resolved`. For a build without a signing certificate or Finder automation:
```bash
swift test --no-parallel
bash scripts/make_release_test.sh --selftest
bash scripts/build_app_test.sh --selftest
ruby scripts/macos_release_workflow_test.rb --selftest
SMLTLK_SIGN_IDENTITY=- IRIZ_DMG_HEADLESS=1 bash scripts/make_release.sh
cd release/dist
shasum -a 256 -c SHA256SUMS.txt
```
`-` means ad-hoc signing, not a verified publisher. The normal local mode uses an existing self-signing certificate and a Finder window with an install arrow. That mode needs Pillow for the background renderer; headless mode does not. Both modes contain the same app and Applications shortcut.
Builds live under `release/build`; output goes to `release/dist`. Both stay out of Git. Do not run the release builder and local installer simultaneously: they share the icon renderer. Scratch and output overrides must stay inside this checkout's `release/` or `.build/`, without symlinks.
The builder checks app and framework architectures, deployment targets, language resources, bundled dependencies, code signatures and the mounted image. Previous output is kept until the new images pass. A failed build leaves its log and staging directory for diagnosis; it detaches only its own mounted image.
For an experimental universal build, set `IRIZ_RELEASE_VARIANTS='arm64 universal'`. Its extra `x86_64` slice is a packaging check, not proof that recognition works on an Intel Mac. Do not advertise it as tested Intel support.
## GitHub Actions
The **macOS release draft** workflow runs manually or on a `v*` tag in this public repository. It is inactive in forks and the private working repository. The tag, when present, must match `RELEASE_VERSION`.
The ARM64 runner runs the tests, builds the headless ad-hoc image and uploads exactly four files. A separate job verifies their checksums, version and source commit, then creates a **draft** release. It does not execute repository code with a write token. Existing releases and assets are never overwritten. A draft does not change the download button.
A maintainer reviews the draft, the release notes and a clean-machine install, runs the publication checks, then publishes it. Publishing is a separate action. No Apple credentials are required by this workflow and no background updater is installed in the app.
Before publishing, check the DMG after downloading it from the draft: mount it, verify its signature, launch a copied app in English and Chinese, and complete the permissions/model/first-dictation flow. Check the public asset hashes against the local output. Do not report a microphone or Intel test that was not performed.
## Developer ID and notarization
Current public builds are not notarized. A self-signed or ad-hoc signature is not an Apple Developer ID signature. Neither proves that Apple has reviewed the app.
For notarization, first obtain a valid **Developer ID Application** certificate and configure a `notarytool` keychain profile yourself. Do not commit a certificate, private key or password. The builder accepts an existing identity and profile:
```bash
SMLTLK_SIGN_IDENTITY='Developer ID Application: YOUR NAME (TEAMID)' \
IRIZ_NOTARY_PROFILE=iriz-notary \
bash scripts/make_release.sh
```
This mode sends the app and image to Apple. It signs nested code, the app and DMG, uses a secure timestamp, submits with `notarytool`, staples tickets and checks Gatekeeper. A failure stops the build. Checksums are calculated after stapling. See [Apple's distribution signing guide](https://developer.apple.com/documentation/xcode/creating-distribution-signed-code-for-the-mac) and [packaging guide](https://developer.apple.com/documentation/xcode/packaging-mac-software-for-distribution).
Moving that identity into CI requires a separate credentials setup. Follow [GitHub's temporary-keychain workflow](https://docs.github.com/en/actions/how-tos/deploy/deploy-to-third-party-platforms/sign-xcode-applications), restrict secret access and clean up the keychain. Do not print environment variables or turn on shell tracing around secrets.
## Patterns used here
Reviewed on 2026-09-13:
- [VoiceInk](https://github.com/Beingpax/VoiceInk/blob/main/README.md) puts Download ahead of build instructions and retains a stable DMG filename. iriz follows that separation.
- [Handy](https://github.com/cjpais/Handy/blob/main/README.md) distinguishes hardware downloads and explains permissions and local models. iriz names its tested platform and the separate model download.
- [Whispering's v7.11.0 guide](https://github.com/EpicenterHQ/epicenter/blob/v7.11.0/apps/whispering/README.md) makes model installation a step before recording. This is a versioned reference, not a description of its current main branch.
The shared visual identity remains in place. Download clarity, first-run instructions, checksums and rollback instructions answer the practical questions a desktop app installer brings to the page.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 970 KiB

After

Width:  |  Height:  |  Size: 816 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.5 MiB

+34
View File
@@ -0,0 +1,34 @@
# iriz 0.2.1
## English
Apple Silicon · macOS 14+ · self-signed, not notarized by Apple.
- Onboarding offers **Download and install Parakeet** (about 500 MB), progress and retry before the permission steps. Recover a skipped or missing model through **Settings → Dictation → Download Parakeet model…**. Parakeet is the only model with automatic installation; it does not recognize Chinese speech.
- Packaged apps include their language resources and Whisper framework. English and Chinese translations resolve from the app bundle, without the developer's build directory.
- Fixes cover the dictation overlay, history search and deletion, file transcription, meeting saves and settings navigation.
- The README now has a direct macOS download button. The release includes SHA-256 checksums and a build manifest.
Open the DMG, drag iriz into Applications, then follow [the first-launch guide](https://github.com/zarubinvibe/iriz/blob/main/docs/DOWNLOAD.md). The model is not included in the image. Intel is not supported by this download. Updates remain manual; quit iriz before replacing the app. Models and history stay outside the app bundle.
## Русский
Apple Silicon · macOS 14+ · самоподпись, без нотаризации Apple.
- В знакомстве перед разрешениями есть кнопка **«Скачать и установить Parakeet»** (около 500 МБ), прогресс и повтор после ошибки. Пропущенную или удалённую модель можно восстановить через **«Настройки → Диктовка → Скачать модель Parakeet…»**. Автоматическая установка есть только для Parakeet; китайскую речь он не распознаёт.
- В пакет приложения входят переводы и Whisper. Английский и китайский загружаются из приложения без каталога сборки разработчика.
- Исправлены плашка диктовки, поиск и удаление истории, расшифровка файлов, сохранение встреч и переходы в настройках.
- В начале README появилась кнопка скачивания для macOS. К выпуску приложены суммы SHA-256 и манифест сборки.
Открой DMG, перетащи iriz в Applications и пройди [первый запуск](https://github.com/zarubinvibe/iriz/blob/main/docs/DOWNLOAD.ru.md). Модели внутри образа нет. Этот файл не предназначен для Intel. Обновление ручное: закрой iriz перед заменой приложения. Модели и история хранятся отдельно.
## 简体中文
Apple Silicon · macOS 14+ · 自签名,尚未通过 Apple 公证。
- 授权步骤之前,引导提供**下载并安装 Parakeet**(约 500 MB)、进度及失败重试。跳过或删除模型后,可通过**设置 → 口述 → 下载 Parakeet 模型…**恢复。只有 Parakeet 支持自动安装,它不识别中文语音。
- 应用包包含翻译资源和 Whisper 框架。英语与中文翻译从应用包读取,不依赖开发者的构建目录。
- 修复听写浮窗、历史搜索与删除、文件转写、会议保存和设置导航。
- README 顶部新增 macOS 下载按钮。发布文件包含 SHA-256 校验值和构建清单。
打开 DMG,将 iriz 拖入 Applications,再按[首次启动指南](https://github.com/zarubinvibe/iriz/blob/main/docs/DOWNLOAD.zh.md)操作。映像不包含模型,此下载不支持 Intel。更新仍需手动完成,替换前先退出 iriz;模型与历史记录保存在应用包之外。
File diff suppressed because it is too large Load Diff
+10695 -5618
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -59,4 +59,4 @@ fi
printf 'Собираю. Первая сборка тянет зависимости и занимает несколько минут.\n\n' printf 'Собираю. Первая сборка тянет зависимости и занимает несколько минут.\n\n'
bash scripts/build_app.sh || { printf '\nСборка не удалась.\n\n'; exit 1; } bash scripts/build_app.sh || { printf '\nСборка не удалась.\n\n'; exit 1; }
printf '\nГотово. Значок появится в строке меню.\n' printf '\nГотово. Значок появится в строке меню.\n'
printf 'Модель распознавания приложение скачает само на шаге знакомства.\n\n' printf 'Модель распознавания скачивается по кнопке на втором шаге знакомства (около 500 МБ).\n\n'
+93 -49
View File
@@ -3,28 +3,48 @@
# бандл, подпись smltlk-selfsign, установка по фиксированному пути. # бандл, подпись smltlk-selfsign, установка по фиксированному пути.
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
swift build -c release VERSION=$(tr -d '\n' < RELEASE_VERSION)
[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "build_app: неверная RELEASE_VERSION" >&2; exit 1; }
fail() { printf 'build_app: %s\n' "$*" >&2; exit 1; }
swift build -c release --arch arm64
# Иконка: тот же IrizMark.iconImage → iconset → .build/AppIcon.icns (render_marks.sh). # Иконка: тот же IrizMark.iconImage → iconset → .build/AppIcon.icns (render_marks.sh).
bash scripts/render_marks.sh bash scripts/render_marks.sh
APP=/Applications/iriz.app INSTALL_DIR=/Applications
OLD_APP=/Applications/smltlk.app BACKUP_PARENT="$HOME/Library/Application Support"
# Запущенное приложение держит свой бандл: rm -rf по нему может не пройти, и скрипт INSTALL_APP="$INSTALL_DIR/iriz.app"
# МОЛЧА оставит старую сборку — «поставил и не работает» с правильным кодом в репозитории. OLD_APP="$INSTALL_DIR/smltlk.app"
# Поэтому сначала гасим процесс, потом сверяем, что бандла действительно нет. STAGE_ROOT=$(mktemp -d "$PWD/.build/install-app.XXXXXX")
if pgrep -x iriz || pgrep -x smltlk; then APP="$STAGE_ROOT/iriz.app"
pkill -x iriz 2>/dev/null || true BACKUP_DIR=""
pkill -x smltlk 2>/dev/null || true INSTALLING=0
else NEW_INSTALL_STARTED=0
rc=$? finish() {
[ "$rc" -eq 1 ] || { echo "build_app: pgrep завершился с кодом $rc"; exit "$rc"; } local result=$?
fi trap - EXIT
sleep 1 if [ "$INSTALLING" -eq 1 ]; then
if pgrep -x iriz || pgrep -x smltlk; then # Не удаляем даже неполную новую копию: при ошибке она остаётся рядом с backup.
echo "build_app: не удалось остановить приложение — установка отменена" if [ "$NEW_INSTALL_STARTED" -eq 1 ] && { [ -e "$INSTALL_APP" ] || [ -L "$INSTALL_APP" ]; }; then
exit 1 mv "$INSTALL_APP" "$BACKUP_DIR/failed-iriz.app" \
fi || { printf 'build_app: откат требует помощи; резервный каталог: %s\n' "$BACKUP_DIR" >&2; exit 1; }
rm -rf "$APP" fi
[ -e "$APP" ] && { echo "build_app: не удалось удалить $APP — установка отменена"; exit 1; } if { [ -e "$BACKUP_DIR/iriz.app" ] || [ -L "$BACKUP_DIR/iriz.app" ]; } \
&& [ ! -e "$INSTALL_APP" ] && [ ! -L "$INSTALL_APP" ]; then
mv "$BACKUP_DIR/iriz.app" "$INSTALL_APP" \
|| { printf 'build_app: не удалось вернуть прежнее приложение из %s\n' "$BACKUP_DIR" >&2; exit 1; }
fi
printf 'build_app: замена отменена, файловое состояние до замены восстановлено\n' >&2
result=1
fi
if [ "$result" -eq 0 ]; then
rmdir "$STAGE_ROOT" 2>/dev/null || true
else
printf 'build_app: рабочий каталог: %s\n' "$STAGE_ROOT" >&2
fi
exit "$result"
}
trap finish EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp .build/release/IrizApp "$APP/Contents/MacOS/iriz" cp .build/release/IrizApp "$APP/Contents/MacOS/iriz"
cp .build/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns" cp .build/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"
@@ -35,14 +55,9 @@ cp .build/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"
# показывает русский на любом выбранном языке: английский и китайский падают в # показывает русский на любом выбранном языке: английский и китайский падают в
# оригинал, потому что `L()` возвращает исходную строку, когда таблицы нет. # оригинал, потому что `L()` возвращает исходную строку, когда таблицы нет.
# Поймано кадром 06.09.2026: `settings-zh.png` вышел целиком по-русски. # Поймано кадром 06.09.2026: `settings-zh.png` вышел целиком по-русски.
# `-L`, потому что `.build/release` - симлинк на каталог с тройкой платформы, # Берём бандлы рядом с бинарём; кавычки сохраняют пробелы в именах.
# а find без него по симлинку не идёт и молча находит пусто. [ -d .build/release/IrizApp_IrizCore.bundle ] || fail "ресурсный бандл IrizApp_IrizCore.bundle не найден"
BUNDLES=$(find -L .build/release -maxdepth 1 -type d -name '*.bundle') for bundle in .build/release/*.bundle; do
if [ -z "$BUNDLES" ]; then
echo "build_app: ресурсные бандлы не найдены - переводов в приложении не будет" >&2
exit 1
fi
for bundle in $BUNDLES; do
cp -R "$bundle" "$APP/Contents/Resources/" cp -R "$bundle" "$APP/Contents/Resources/"
done done
@@ -52,21 +67,25 @@ done
# с «Library not loaded: @rpath/whisper.framework» - тесты и CLI при этом работали, # с «Library not loaded: @rpath/whisper.framework» - тесты и CLI при этом работали,
# потому что бегут прямо из .build, где фреймворк лежит рядом. Поймано живьём # потому что бегут прямо из .build, где фреймворк лежит рядом. Поймано живьём
# 03.09.2026, ПОСЛЕ того как всё остальное было зелёным. # 03.09.2026, ПОСЛЕ того как всё остальное было зелёным.
WHISPER_FRAMEWORK="$(find .build -maxdepth 3 -type d -name whisper.framework -path '*release*' | head -1)" WHISPER_FRAMEWORK=.build/release/whisper.framework
if [ -z "$WHISPER_FRAMEWORK" ]; then if [ ! -d "$WHISPER_FRAMEWORK" ]; then
echo "build_app: whisper.framework не найден в .build - движок диктовки не запустится" >&2 echo "build_app: whisper.framework не найден в .build - движок диктовки не запустится" >&2
exit 1 exit 1
fi fi
mkdir -p "$APP/Contents/Frameworks" mkdir -p "$APP/Contents/Frameworks"
rm -rf "$APP/Contents/Frameworks/whisper.framework"
cp -R "$WHISPER_FRAMEWORK" "$APP/Contents/Frameworks/" cp -R "$WHISPER_FRAMEWORK" "$APP/Contents/Frameworks/"
install_name_tool -add_rpath "@executable_path/../Frameworks" "$APP/Contents/MacOS/iriz" 2>/dev/null || true if ! otool -l "$APP/Contents/MacOS/iriz" | awk '$1 == "path" && $2 == "@executable_path/../Frameworks" { found=1 } END { exit !found }'; then
install_name_tool -add_rpath "@executable_path/../Frameworks" "$APP/Contents/MacOS/iriz" \
|| fail "не удалось добавить rpath фреймворков"
fi
otool -l "$APP/Contents/MacOS/iriz" | awk '$1 == "path" && $2 == "@executable_path/../Frameworks" { found=1 } END { exit !found }' \
|| fail "rpath фреймворков отсутствует"
# Фреймворк приходит подписанным вендором, и dyld отказывается его грузить в наш # Фреймворк приходит подписанным вендором, и dyld отказывается его грузить в наш
# процесс: «different Team IDs». --deep на приложении чужую подпись не перебивает, # процесс: «different Team IDs». --deep на приложении чужую подпись не перебивает,
# поэтому фреймворк подписывается ОТДЕЛЬНО и до подписи бандла. # поэтому фреймворк подписывается ОТДЕЛЬНО и до подписи бандла.
codesign --force --sign "smltlk-selfsign" --options runtime \ codesign --force --sign "smltlk-selfsign" --options runtime \
"$APP/Contents/Frameworks/whisper.framework" "$APP/Contents/Frameworks/whisper.framework" || fail "подпись фреймворка не прошла"
cat > "$APP/Contents/Info.plist" <<'PLIST' cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict> <plist version="1.0"><dict>
@@ -76,25 +95,50 @@ cat > "$APP/Contents/Info.plist" <<'PLIST'
<key>CFBundleDisplayName</key><string>iriz</string> <key>CFBundleDisplayName</key><string>iriz</string>
<key>CFBundlePackageType</key><string>APPL</string> <key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleIconFile</key><string>AppIcon</string> <key>CFBundleIconFile</key><string>AppIcon</string>
<key>CFBundleShortVersionString</key><string>0.2.0</string> <key>CFBundleShortVersionString</key><string>$VERSION</string>
<key>CFBundleVersion</key><string>1</string> <key>CFBundleVersion</key><string>$VERSION</string>
<key>LSMinimumSystemVersion</key><string>14.0</string> <key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSMicrophoneUsageDescription</key><string>Микрофон нужен, чтобы превращать вашу речь в текст.</string> <key>NSMicrophoneUsageDescription</key><string>Микрофон нужен, чтобы превращать твою речь в текст.</string>
<key>LSUIElement</key><true/> <key>LSUIElement</key><true/>
</dict></plist> </dict></plist>
PLIST PLIST
codesign --force --deep --sign "smltlk-selfsign" --options runtime --entitlements entitlements.plist "$APP" codesign --force --deep --sign "smltlk-selfsign" --options runtime --entitlements entitlements.plist "$APP" \
codesign --verify --deep --strict "$APP" || fail "подпись приложения не прошла"
codesign --verify --deep --strict "$APP" || fail "проверка подготовленной подписи не прошла"
codesign -dv --verbose=2 "$APP" 2>&1 | grep -E 'Authority|Identifier' codesign -dv --verbose=2 "$APP" 2>&1 | grep -E 'Authority|Identifier'
# Установленный бинарь обязан быть НОВЕЕ собранного источника — иначе установка не состоялась.
if [ "$APP/Contents/MacOS/iriz" -ot .build/release/IrizApp ]; then
echo "build_app: в /Applications лежит старый бинарь — установка не состоялась"; exit 1
fi
echo "build_app: установлено $(date -r "$APP/Contents/MacOS/iriz" '+%H:%M:%S')"
# Старый бандл убирается ПОСЛЕ успешной установки нового: иначе неудачная # До этой точки установленное приложение и его процессы не менялись.
# сборка оставила бы владельца вообще без приложения. mkdir -p "$BACKUP_PARENT"
if [ -d "$OLD_APP" ] && [ -x "$APP/Contents/MacOS/iriz" ]; then BACKUP_DIR=$(mktemp -d "$BACKUP_PARENT/iriz-app-backup.XXXXXX")
rm -rf "$OLD_APP" for process in iriz smltlk; do
echo "build_app: старый $OLD_APP удалён" if pgrep -x "$process" >/dev/null; then
pkill -x "$process" || { rc=$?; [ "$rc" -eq 1 ] || fail "не удалось остановить $process"; }
else
rc=$?
[ "$rc" -eq 1 ] || fail "pgrep завершился с кодом $rc"
fi
done
sleep 1
for process in iriz smltlk; do
if pgrep -x "$process" >/dev/null; then
fail "не удалось остановить $process; установка отменена"
else
rc=$?
[ "$rc" -eq 1 ] || fail "pgrep завершился с кодом $rc"
fi
done
INSTALLING=1
if [ -e "$INSTALL_APP" ] || [ -L "$INSTALL_APP" ]; then
mv "$INSTALL_APP" "$BACKUP_DIR/iriz.app" || fail "не удалось сохранить прежнее приложение"
fi
NEW_INSTALL_STARTED=1
mv "$APP" "$INSTALL_APP" || fail "не удалось установить подготовленное приложение"
codesign --verify --deep --strict "$INSTALL_APP" || fail "проверка установленной подписи не прошла"
INSTALLING=0
printf 'build_app: установлено %s; резервный каталог: %s\n' "$VERSION" "$BACKUP_DIR"
# Старое имя тоже сохраняется, а не удаляется безвозвратно.
if [ -e "$OLD_APP" ] || [ -L "$OLD_APP" ]; then
mv "$OLD_APP" "$BACKUP_DIR/smltlk.app" \
|| printf 'build_app: не удалось перенести старый %s; он оставлен на месте\n' "$OLD_APP" >&2
fi fi

Some files were not shown because too many files have changed in this diff Show More