diff --git a/src/Main.qml b/src/Main.qml index f8b1ebf..9bafaf4 100644 --- a/src/Main.qml +++ b/src/Main.qml @@ -35,7 +35,7 @@ ApplicationWindow { if (backend.outcome === "material") return qsTr("Draw · insufficient material") if (backend.outcome === "fifty-moves") return qsTr("Draw · fifty-move rule") if (backend.outcome === "repetition") return qsTr("Draw · threefold repetition") - if (backend.thinking) return qsTr("Considering the next move…") + if (backend.thinking) return backend.agent ? qsTr("%1 is thinking…").arg(backend.agentName) : qsTr("Considering the next move…") if (backend.checked) return backend.whiteTurn ? qsTr("White is in check") : qsTr("Black is in check") return backend.whiteTurn ? qsTr("White to move") : qsTr("Black to move") } @@ -224,10 +224,10 @@ ApplicationWindow { spacing: 18 RowLayout { Layout.fillWidth: true - Text { text: backend.computer ? qsTr("VS COMPUTER") : qsTr("TWO PLAYERS"); font.pixelSize: 10; font.letterSpacing: Qt.application.layoutDirection === Qt.RightToLeft ? 0 : 2; color: window.muted; Layout.fillWidth: true } + Text { text: backend.agent ? qsTr("VS AGENT") : backend.computer ? qsTr("VS COMPUTER") : qsTr("TWO PLAYERS"); font.pixelSize: 10; font.letterSpacing: Qt.application.layoutDirection === Qt.RightToLeft ? 0 : 2; color: window.muted; Layout.fillWidth: true } Text { text: "●"; color: window.setColors[backend.pieceSet]; font.pixelSize: 9 } } - Text { text: backend.computer ? window.difficultyNames[backend.difficulty] : qsTr("One board. Two minds."); color: theme.foreground; font.family: "serif"; font.pixelSize: 23; Layout.fillWidth: true; wrapMode: Text.WordWrap } + Text { text: backend.agent ? backend.agentName : backend.computer ? window.difficultyNames[backend.difficulty] : qsTr("One board. Two minds."); color: theme.foreground; font.family: "serif"; font.pixelSize: 23; Layout.fillWidth: true; wrapMode: Text.WordWrap } Repeater { model: [false,true] Rectangle { @@ -243,7 +243,7 @@ ApplicationWindow { Text { text: modelData ? "♙" : "♟"; font.pixelSize: 29; color: theme.foreground } ColumnLayout { spacing: 3 - Text { text: backend.computer ? (backend.humanWhite === modelData ? qsTr("You") : qsTr("Computer")) : (modelData ? qsTr("Player 1") : qsTr("Player 2")); color: theme.foreground; font.pixelSize: 14 } + Text { text: backend.computer ? (backend.humanWhite === modelData ? qsTr("You") : backend.agent ? backend.agentName : qsTr("Computer")) : (modelData ? qsTr("Player 1") : qsTr("Player 2")); color: theme.foreground; font.pixelSize: 14 } Text { text: modelData ? qsTr("White") : qsTr("Black"); color: window.muted; font.pixelSize: 11 } } Item { Layout.fillWidth: true } @@ -295,7 +295,9 @@ ApplicationWindow { id: errorRow anchors { left: parent.left; right: parent.right; verticalCenter: parent.verticalCenter; margins: 14 } Text { text: backend.error; color: theme.foreground; wrapMode: Text.WordWrap; Layout.fillWidth: true } - FlatButton { text: qsTr("Dismiss"); onClicked: backend.dismissError() } + // A stalled agent keeps its message up until the player asks again, undoes, or starts over. + FlatButton { objectName: "askAgain"; text: qsTr("Ask again"); visible: backend.agentStalled; onClicked: backend.askAgentAgain() } + FlatButton { text: qsTr("Dismiss"); visible: !backend.agentStalled; onClicked: backend.dismissError() } } } } @@ -317,20 +319,23 @@ ApplicationWindow { } Material.roundedScale: theme.radius onOpened: { - mode.currentIndex = backend.computer ? 0 : 1 + backend.refreshAgent() + mode.currentIndex = backend.agent && backend.agentAvailable ? 2 : backend.computer ? 0 : 1 level.currentIndex = backend.difficulty side.currentIndex = backend.humanWhite ? 0 : 1 mode.forceActiveFocus() } - onAccepted: { backend.newGame(mode.currentIndex === 0,level.currentIndex,side.currentIndex === 0); board.resetCamera() } + onAccepted: { backend.newGame(mode.currentIndex !== 1,level.currentIndex,side.currentIndex === 0,mode.currentIndex === 2); board.resetCamera() } contentItem: ColumnLayout { LayoutMirroring.enabled: Qt.application.layoutDirection === Qt.RightToLeft LayoutMirroring.childrenInherit: true spacing: 16 Label { text: backend.canUndo ? qsTr("Starting a new match replaces the saved game.") : qsTr("Choose your opponent and settle in."); wrapMode: Text.WordWrap; Layout.fillWidth: true } - ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: mode; objectName: "mode"; Layout.fillWidth: true; model: [qsTr("Play against the computer"),qsTr("Two players · same device")]; Material.roundedScale: theme.radius } + ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: mode; objectName: "mode"; Layout.fillWidth: true; // The default Omarchy agent joins the list when it can answer on its own; it comes last so the others keep their places. + model: backend.agentAvailable ? [qsTr("Play against the computer"),qsTr("Two players · same device"),qsTr("Play against %1").arg(backend.agentName)] + : [qsTr("Play against the computer"),qsTr("Two players · same device")]; Material.roundedScale: theme.radius } ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: level; Layout.fillWidth: true; model: window.difficultyNames; visible: mode.currentIndex === 0; Material.roundedScale: theme.radius } - ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: side; Layout.fillWidth: true; model: [qsTr("Play as White"),qsTr("Play as Black")]; visible: mode.currentIndex === 0; Material.roundedScale: theme.radius } + ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: side; Layout.fillWidth: true; model: [qsTr("Play as White"),qsTr("Play as Black")]; visible: mode.currentIndex !== 1; Material.roundedScale: theme.radius } } } Dialog { diff --git a/src/agentplayer.cpp b/src/agentplayer.cpp new file mode 100644 index 0000000..f2796f5 --- /dev/null +++ b/src/agentplayer.cpp @@ -0,0 +1,147 @@ +#include "agentplayer.h" + +#include +#include +#include + +namespace { +QString coordinates(Chess::Move move) { + auto text = Chess::squareName(move.from) + Chess::squareName(move.to); + if (move.promotion) text += char(std::tolower(" PNBRQK"[move.promotion])); + return QString::fromStdString(text); +} +} + +AgentPlayer::AgentPlayer(const QString &defaultsFile, QObject *parent) : QObject(parent), m_defaultsFile(defaultsFile) { + m_timeout.setSingleShot(true); + // Agents think for a while, and some start slowly; past this the turn is handed back to the player to decide. + m_timeout.setInterval(180000); + connect(&m_timeout,&QTimer::timeout,this,[this] { fail(tr("%1 took too long to answer.").arg(name())); }); +} +AgentPlayer::~AgentPlayer() { + m_timeout.stop(); + if (m_process) { m_process->disconnect(this); m_process->kill(); } +} + +QString AgentPlayer::omarchyDefaultsFile() { + return QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + "/omarchy/defaults/agent"; +} +QString AgentPlayer::id() const { + QFile file(m_defaultsFile); + if (m_defaultsFile.isEmpty() || !file.open(QIODevice::ReadOnly)) return {}; + return QString::fromUtf8(file.readLine(256)).trimmed(); +} +QString AgentPlayer::displayName(const QString &id) { + static const QHash names{ + {"claude","Claude Code"},{"codex","Codex"},{"opencode","OpenCode"},{"kilo","Kilo"},{"pi","Pi"},{"omp","Oh My Pi"}, + {"grok","Grok"},{"crush","Crush"},{"copilot","GitHub Copilot"},{"cursor-agent","Cursor CLI"},{"agy","Antigravity"}, + {"qwen","Qwen Code"},{"kimi","Kimi"},{"amp","Amp"},{"ori","Ori"},{"hermes","Hermes"},{"openclaw","OpenClaw"}, + {"muse","Muse Code"},{"dsh","DeepSeek Harness"},{"mcode","MiniMax Code"},{"kiro-cli","Kiro CLI"},{"freebuff","Freebuff"}, + {"devin","Devin CLI"},{"commandcode","Command Code"}}; + return names.value(id,id); +} +QStringList AgentPlayer::command(const QString &id, const QString &prompt) { + // Each harness spells "answer once and exit" its own way. One that isn't here has no such mode we know of. + if (id == "claude" || id == "pi" || id == "omp" || id == "grok" || id == "copilot" || id == "cursor-agent" || id == "agy" || id == "qwen") + return {id,"-p",prompt}; + // Codex refuses to run outside a git repository unless told the folder is fine. + if (id == "codex") return {id,"exec","--skip-git-repo-check",prompt}; + if (id == "opencode" || id == "kilo" || id == "crush") return {id,"run",prompt}; + if (id == "kimi") return {id,"--prompt",prompt}; + if (id == "amp") return {id,"--execute",prompt}; + if (id == "ori") return {id,"code","--prompt",prompt}; + return {}; +} +bool AgentPlayer::available() const { + if (!m_override.isEmpty()) return !id().isEmpty(); + const auto argv = command(id(),{}); + return !argv.isEmpty() && !QStandardPaths::findExecutable(argv.first()).isEmpty(); +} +QString AgentPlayer::prompt(const Chess::Position &position, const QStringList &history, const QString &rejected) { + QStringList played; + for (int i = 0; i < history.size(); ++i) played << (i % 2 ? history[i] : QString::number(i / 2 + 1) + ". " + history[i]); + QStringList legal; + for (auto move : position.legal()) legal << coordinates(move); + QString text = QString("You are playing chess as %1 and it is your move.\n\n").arg(position.white ? "White" : "Black"); + text += "Position (FEN): " + QString::fromStdString(position.fen()) + "\n"; + text += "Moves so far: " + (played.isEmpty() ? QString("none") : played.join(' ')) + "\n"; + text += "Your legal moves: " + legal.join(' ') + "\n\n"; + if (!rejected.isEmpty()) text += "Your last answer, \"" + rejected.left(80) + "\", named no move from that list.\n"; + text += "Pick the strongest move from the list and reply with that move alone, written exactly as it is in the list, such as " + legal.value(0) + + ". Use no tools, read no files, and give no explanation."; + return text; +} +bool AgentPlayer::parse(const QString &answer, const Chess::Position &position, Chess::Move *move) { + const auto legal = position.legal(); + int best = -1; + // The last move named wins: an agent that thinks aloud ends on its choice. + static const QRegularExpression coordinate("(? best) { best = match.capturedStart(); *move = candidate; } + } + if (best >= 0) return true; + for (auto candidate : legal) { + QString san = QString::fromStdString(position.san(candidate)); + san.remove('+').remove('#'); + const QRegularExpression written("(? best) { best = match.capturedStart(); *move = candidate; } + } + } + return best >= 0; +} +void AgentPlayer::ask(const Chess::Position &position, const QStringList &history) { + cancel(); + m_position = position; m_history = history; m_retried = false; + start({}); +} +void AgentPlayer::start(const QString &rejected) { + m_asked = name(); + const QString text = prompt(m_position,m_history,rejected); + QStringList argv = m_override.isEmpty() ? command(id(),text) : m_override + QStringList{text}; + if (argv.isEmpty()) { fail(tr("%1 can't answer on its own yet. Choose another default agent, or play the computer.").arg(m_asked)); return; } + m_process = std::make_unique(); + m_process->setWorkingDirectory(m_workspace.path()); + // Nothing to read on its input, so an agent that waits for one sees the end of it at once. + m_process->setStandardInputFile(QProcess::nullDevice()); + connect(m_process.get(),&QProcess::finished,this,&AgentPlayer::finish); + connect(m_process.get(),&QProcess::errorOccurred,this,[this](QProcess::ProcessError error) { + if (error == QProcess::FailedToStart) fail(tr("%1 is not installed.").arg(m_asked)); + }); + m_timeout.start(); + m_process->start(argv.first(),argv.mid(1)); +} +void AgentPlayer::finish(int exitCode, QProcess::ExitStatus status) { + if (!m_process) return; + m_timeout.stop(); + const QString answer = QString::fromUtf8(m_process->readAllStandardOutput()); + const QString complaint = QString::fromUtf8(m_process->readAllStandardError()).trimmed(); + m_process.release()->deleteLater(); + Chess::Move move; + if (status == QProcess::NormalExit && exitCode == 0 && parse(answer,m_position,&move)) { emit answered(move); return; } + if (status != QProcess::NormalExit || exitCode != 0) { + // The agent's own last words say why: not signed in, out of credit, offline. + const QString why = complaint.isEmpty() ? answer.trimmed() : complaint; + fail(why.isEmpty() ? tr("%1 stopped without answering.").arg(m_asked) : tr("%1 stopped without answering: %2").arg(m_asked,why.section('\n',-1).left(200))); + return; + } + if (!m_retried) { m_retried = true; start(answer.trimmed()); return; } + fail(tr("%1 did not answer with a legal move.").arg(m_asked)); +} +void AgentPlayer::fail(const QString &reason) { + cancel(); + emit failed(reason); +} +void AgentPlayer::cancel() { + m_timeout.stop(); + if (!m_process) return; + auto process = m_process.release(); + process->disconnect(this); + // Asked to stop, then stopped: the process is given its own time to end rather than blocking the window on it. + connect(process,&QProcess::finished,process,&QObject::deleteLater); + if (process->state() == QProcess::NotRunning) { process->deleteLater(); return; } + process->terminate(); + QTimer::singleShot(2000,process,&QProcess::kill); +} diff --git a/src/agentplayer.h b/src/agentplayer.h new file mode 100644 index 0000000..34befd6 --- /dev/null +++ b/src/agentplayer.h @@ -0,0 +1,55 @@ +#pragma once + +#include "chess.h" +#include +#include +#include +#include +#include +#include + +// Plays a side by asking the user's default Omarchy agent for each move. Omarchy only opens agents in a +// terminal, so the agent's own one-shot mode is run here: one prompt in, one answer out. +class AgentPlayer : public QObject { + Q_OBJECT +public: + // Tests pass their own defaults file; an empty path means no agent is chosen. + explicit AgentPlayer(const QString &defaultsFile, QObject *parent = nullptr); + ~AgentPlayer() override; + // Where `omarchy default agent` records the choice. + static QString omarchyDefaultsFile(); + // The chosen agent's id as Omarchy writes it ("claude", "codex"), read fresh so a new choice is seen. + QString id() const; + QString name() const { return displayName(id()); } + // Whether the chosen agent can answer on its own and is installed. + bool available() const; + static QString displayName(const QString &id); + // The agent's one-shot command for a prompt, or nothing when it has no such mode we know of. + static QStringList command(const QString &id, const QString &prompt); + static QString prompt(const Chess::Position &position, const QStringList &history, const QString &rejected = {}); + // The last legal move the answer names, in coordinates (e7e5) or as written in the game (Nf6). + static bool parse(const QString &answer, const Chess::Position &position, Chess::Move *move); + void setDefaultsFile(const QString &path) { m_defaultsFile = path; } + // Tests stand a script in for the agent: the prompt is added as its last argument. + void setCommandOverride(const QStringList &command) { m_override = command; } + void setTimeout(int milliseconds) { m_timeout.setInterval(milliseconds); } + void ask(const Chess::Position &position, const QStringList &history); + void cancel(); +signals: + void answered(Chess::Move move); + void failed(const QString &reason); +private: + void start(const QString &rejected); + void finish(int exitCode, QProcess::ExitStatus status); + void fail(const QString &reason); + QString m_defaultsFile; + QStringList m_override; + std::unique_ptr m_process; + // The agent works in an empty folder of its own, never among the user's files. + QTemporaryDir m_workspace; + QTimer m_timeout; + Chess::Position m_position; + QStringList m_history; + QString m_asked; + bool m_retried = false; +}; diff --git a/src/backend.cpp b/src/backend.cpp index addb6be..5c09ddd 100644 --- a/src/backend.cpp +++ b/src/backend.cpp @@ -21,7 +21,17 @@ QString adjudicate(const Chess::Position &p, const std::vector &leg } } -Backend::Backend(const QString &savePath, QObject *parent) : QObject(parent), m_savePath(savePath) { +// A game kept only in memory is a test's or a headless command's, and never reaches for the user's own agent. +Backend::Backend(const QString &savePath, QObject *parent) + : QObject(parent), m_savePath(savePath), m_agentPlayer(savePath == ":memory:" ? QString() : AgentPlayer::omarchyDefaultsFile()) { + connect(&m_agentPlayer,&AgentPlayer::answered,this,[this](Chess::Move move) { + m_thinking = false; + if (std::find(m_legal.begin(),m_legal.end(),move) != m_legal.end()) apply(move); + else { m_agentStalled = true; m_error = tr("%1 did not answer with a legal move.").arg(agentName()); emit changed(); } + }); + connect(&m_agentPlayer,&AgentPlayer::failed,this,[this](const QString &reason) { + m_thinking = false; m_agentStalled = true; m_error = reason; emit changed(); + }); if (m_savePath.isEmpty()) m_savePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/game.json"; m_repetitions[position().key()] = 1; if (m_savePath != ":memory:") { @@ -96,11 +106,19 @@ void Backend::apply(Chess::Move move) { void Backend::cancelComputer() { ++m_generation; if (m_cancel) m_cancel->store(true); + m_agentPlayer.cancel(); + if (m_agentStalled) { m_agentStalled = false; m_error.clear(); } m_thinking = false; } void Backend::scheduleComputer() { if (!m_computer || whiteTurn() == m_humanWhite || finished() || m_thinking) return; m_thinking = true; + if (m_agent) { + // The agent answers in its own time, in a process of its own; its move or its failure comes back as a signal. + m_agentPlayer.ask(position(),m_notation); + emit changed(); + return; + } auto cancel = m_cancel = std::make_shared(false); const auto generation = m_generation; const auto p = position(); @@ -119,11 +137,11 @@ void Backend::scheduleComputer() { watcher->setFuture(QtConcurrent::run([p,difficulty,cancel,history] { return Chess::bestMove(p,difficulty,cancel,history); })); emit changed(); } -void Backend::newGame(bool computer, int difficulty, bool humanWhite) { +void Backend::newGame(bool computer, int difficulty, bool humanWhite, bool agent) { cancelComputer(); if (!ownsSave()) return; m_saveBlocked = false; m_error.clear(); - m_computer = computer; m_difficulty = std::clamp(difficulty,0,2); m_humanWhite = humanWhite; + m_computer = computer || agent; m_agent = agent; m_difficulty = std::clamp(difficulty,0,2); m_humanWhite = humanWhite; m_positions = {Chess::Position::initial()}; m_moves.clear(); m_notation.clear(); m_pending = {}; m_selected = -1; m_repetitions.clear(); m_repetitions[position().key()] = 1; refresh(); save(); scheduleComputer(); @@ -138,6 +156,12 @@ void Backend::undo() { m_selected = -1; m_pending = {}; refresh(); save(); scheduleComputer(); } +void Backend::askAgentAgain() { + if (!m_agentStalled) return; + cancelComputer(); + scheduleComputer(); + emit changed(); +} void Backend::dismissError() { m_error.clear(); emit changed(); } void Backend::setPieceSet(int value) { if (value < 0 || value > 3 || value == m_pieceSet) return; @@ -159,7 +183,7 @@ void Backend::save() { if (m_savePath == ":memory:" || m_saveBlocked || !ownsSave()) return; QJsonArray moves; for (auto m : m_moves) moves.append(QJsonArray{m.from,m.to,m.promotion}); - QJsonObject data{{"version",1},{"moves",moves},{"computer",m_computer},{"humanWhite",m_humanWhite}, + QJsonObject data{{"version",1},{"moves",moves},{"computer",m_computer},{"agent",m_agent},{"humanWhite",m_humanWhite}, {"difficulty",m_difficulty},{"pieceSet",m_pieceSet},{"reducedMotion",m_reducedMotion},{"autoRotate",m_autoRotate},{"sidebar",m_sidebar}}; QDir().mkpath(QFileInfo(m_savePath).absolutePath()); QSaveFile file(m_savePath); @@ -199,7 +223,7 @@ void Backend::restore() { m_positions.push_back(position().after(move)); m_moves.push_back(move); ++m_repetitions[position().key()]; } - m_computer = data["computer"].toBool(true); m_humanWhite = data["humanWhite"].toBool(true); + m_agent = data["agent"].toBool(); m_computer = data["computer"].toBool(true) || m_agent; m_humanWhite = data["humanWhite"].toBool(true); m_difficulty = std::clamp(data["difficulty"].toInt(1),0,2); m_pieceSet = std::clamp(data["pieceSet"].toInt(),0,3); m_reducedMotion = data["reducedMotion"].toBool(); m_autoRotate = data["autoRotate"].toBool(); m_sidebar = data["sidebar"].toBool(true); } diff --git a/src/backend.h b/src/backend.h index 4ff0743..26f1c22 100644 --- a/src/backend.h +++ b/src/backend.h @@ -1,6 +1,7 @@ #pragma once #include "chess.h" +#include "agentplayer.h" #include #include #include @@ -26,6 +27,10 @@ class Backend : public QObject { Q_PROPERTY(bool computer READ computer NOTIFY changed) Q_PROPERTY(bool humanWhite READ humanWhite NOTIFY changed) Q_PROPERTY(int difficulty READ difficulty NOTIFY changed) + Q_PROPERTY(bool agent READ agent NOTIFY changed) + Q_PROPERTY(QString agentName READ agentName NOTIFY changed) + Q_PROPERTY(bool agentAvailable READ agentAvailable NOTIFY changed) + Q_PROPERTY(bool agentStalled READ agentStalled NOTIFY changed) Q_PROPERTY(int pieceSet READ pieceSet WRITE setPieceSet NOTIFY preferencesChanged) Q_PROPERTY(bool reducedMotion READ reducedMotion WRITE setReducedMotion NOTIFY preferencesChanged) Q_PROPERTY(bool autoRotate READ autoRotate WRITE setAutoRotate NOTIFY preferencesChanged) @@ -52,6 +57,14 @@ class Backend : public QObject { bool computer() const { return m_computer; } bool humanWhite() const { return m_humanWhite; } int difficulty() const { return m_difficulty; } + // The opponent is the user's default Omarchy agent rather than the built-in player. + bool agent() const { return m_agent; } + // The agent in the game while one is being played, and the one a new game would be against otherwise. + QString agentName() const { return m_agentPlayer.name(); } + bool agentAvailable() const { return m_agentPlayer.available(); } + // The agent failed to move; the game waits for the player to ask again, undo, or start over. + bool agentStalled() const { return m_agentStalled; } + AgentPlayer &agentPlayer() { return m_agentPlayer; } int pieceSet() const { return m_pieceSet; } bool reducedMotion() const { return m_reducedMotion; } bool autoRotate() const { return m_autoRotate; } @@ -65,7 +78,10 @@ class Backend : public QObject { Q_INVOKABLE bool move(int from, int to, int promotion = Chess::Empty); Q_INVOKABLE void promote(int kind); Q_INVOKABLE void cancelSelection(); - Q_INVOKABLE void newGame(bool computer, int difficulty, bool humanWhite = true); + Q_INVOKABLE void newGame(bool computer, int difficulty, bool humanWhite = true, bool agent = false); + Q_INVOKABLE void askAgentAgain(); + // The default agent is read when asked for, so the dialog asks for a fresh look as it opens. + Q_INVOKABLE void refreshAgent() { emit changed(); } Q_INVOKABLE void undo(); Q_INVOKABLE void dismissError(); void setPieceSet(int value); @@ -93,7 +109,8 @@ class Backend : public QObject { int m_selected = -1; Chess::Move m_pending; QString m_outcome, m_error, m_savePath; - bool m_computer = true, m_humanWhite = true, m_thinking = false; + bool m_computer = true, m_humanWhite = true, m_thinking = false, m_agent = false, m_agentStalled = false; + AgentPlayer m_agentPlayer; int m_difficulty = 1, m_pieceSet = 0; bool m_reducedMotion = false, m_autoRotate = false, m_sidebar = true, m_saveBlocked = false, m_saveFailed = false; unsigned m_generation = 0; diff --git a/src/i18n/ar.json b/src/i18n/ar.json index 6ce757b..5b31892 100644 --- a/src/i18n/ar.json +++ b/src/i18n/ar.json @@ -69,5 +69,15 @@ "Click a piece, then a highlighted square.\n\nArrow keys · Navigate the board\nSpace / Enter · Select or move\nEscape · Cancel selection\nCtrl+Z · Undo\nN · New game\nF · Flip board\nR · Reset camera\n1–4 · Piece set\nB · Show or hide the sidebar\nTab · Show or hide the interface\nS · Settings\n? · Keyboard shortcuts\nQ · Quit (your game is saved)\n\nRight-drag to orbit. Scroll to zoom.": "انقر على قطعة ثم على مربع مميز.\n\nمفاتيح الأسهم · التنقل على الرقعة\nSpace / Enter · اختيار أو تحريك\nEscape · إلغاء الاختيار\nCtrl+Z · تراجع\nN · لعبة جديدة\nF · قلب الرقعة\nR · إعادة ضبط الكاميرا\n1–4 · مجموعة القطع\nB · إظهار الشريط الجانبي أو إخفاؤه\nTab · إظهار الواجهة أو إخفاؤها\nS · الإعدادات\n? · الاختصارات\nQ · خروج (تحفظ اللعبة)\n\nاسحب بالزر الأيمن للتدوير ومرر للتكبير.", "Piece set": "مجموعة القطع", "Hide sidebar": "إخفاء الشريط الجانبي", - "Show sidebar": "إظهار الشريط الجانبي" + "Show sidebar": "إظهار الشريط الجانبي", + "%1 is thinking…": "%1 يفكّر…", + "VS AGENT": "ضد الوكيل", + "Play against %1": "العب ضد %1", + "Ask again": "اسأل مجددًا", + "%1 took too long to answer.": "استغرق %1 وقتًا طويلًا للرد.", + "%1 can't answer on its own yet. Choose another default agent, or play the computer.": "لا يستطيع %1 الرد بمفرده بعد. اختر وكيلًا افتراضيًا آخر أو العب ضد الحاسوب.", + "%1 is not installed.": "%1 غير مثبّت.", + "%1 stopped without answering.": "توقّف %1 دون أن يرد.", + "%1 stopped without answering: %2": "توقّف %1 دون أن يرد: %2", + "%1 did not answer with a legal move.": "لم يرد %1 بنقلة قانونية." } diff --git a/src/i18n/da.json b/src/i18n/da.json index 15c4997..5abf8b1 100644 --- a/src/i18n/da.json +++ b/src/i18n/da.json @@ -69,5 +69,15 @@ "Click a piece, then a highlighted square.\n\nArrow keys · Navigate the board\nSpace / Enter · Select or move\nEscape · Cancel selection\nCtrl+Z · Undo\nN · New game\nF · Flip board\nR · Reset camera\n1–4 · Piece set\nB · Show or hide the sidebar\nTab · Show or hide the interface\nS · Settings\n? · Keyboard shortcuts\nQ · Quit (your game is saved)\n\nRight-drag to orbit. Scroll to zoom.": "Klik på en brik og derefter på et markeret felt.\n\nPiletaster · Naviger på brættet\nSpace / Enter · Vælg eller flyt\nEscape · Annuller valg\nCtrl+Z · Fortryd\nN · Nyt spil\nF · Vend brættet\nR · Nulstil kamera\n1–4 · Briksæt\nB · Vis eller skjul sidepanelet\nTab · Vis eller skjul brugerfladen\nS · Indstillinger\n? · Tastaturgenveje\nQ · Afslut (spillet gemmes)\n\nTræk med højre museknap for at rotere. Rul for at zoome.", "Piece set": "Briksæt", "Hide sidebar": "Skjul sidepanel", - "Show sidebar": "Vis sidepanel" + "Show sidebar": "Vis sidepanel", + "%1 is thinking…": "%1 tænker…", + "VS AGENT": "MOD AGENT", + "Play against %1": "Spil mod %1", + "Ask again": "Spørg igen", + "%1 took too long to answer.": "%1 var for længe om at svare.", + "%1 can't answer on its own yet. Choose another default agent, or play the computer.": "%1 kan endnu ikke svare på egen hånd. Vælg en anden standardagent, eller spil mod computeren.", + "%1 is not installed.": "%1 er ikke installeret.", + "%1 stopped without answering.": "%1 stoppede uden at svare.", + "%1 stopped without answering: %2": "%1 stoppede uden at svare: %2", + "%1 did not answer with a legal move.": "%1 svarede ikke med et lovligt træk." } diff --git a/src/i18n/en.json b/src/i18n/en.json index fbb4e7c..5de7cf9 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -69,5 +69,15 @@ "↶ Undo move": "↶ Undo move", "Piece set": "Piece set", "Hide sidebar": "Hide sidebar", - "Show sidebar": "Show sidebar" + "Show sidebar": "Show sidebar", + "%1 is thinking…": "%1 is thinking…", + "VS AGENT": "VS AGENT", + "Play against %1": "Play against %1", + "Ask again": "Ask again", + "%1 took too long to answer.": "%1 took too long to answer.", + "%1 can't answer on its own yet. Choose another default agent, or play the computer.": "%1 can't answer on its own yet. Choose another default agent, or play the computer.", + "%1 is not installed.": "%1 is not installed.", + "%1 stopped without answering.": "%1 stopped without answering.", + "%1 stopped without answering: %2": "%1 stopped without answering: %2", + "%1 did not answer with a legal move.": "%1 did not answer with a legal move." } diff --git a/tests/checkmate_tests.cpp b/tests/checkmate_tests.cpp index 7adb04d..c301934 100644 --- a/tests/checkmate_tests.cpp +++ b/tests/checkmate_tests.cpp @@ -602,6 +602,115 @@ private slots: QVERIFY(next.legal().empty()); } + void agentCommandsAndAnswers() { + // Each harness has its own way to answer once and exit; one without is not offered. + QCOMPARE(AgentPlayer::command("claude","go"),(QStringList{"claude","-p","go"})); + QCOMPARE(AgentPlayer::command("codex","go"),(QStringList{"codex","exec","--skip-git-repo-check","go"})); + QCOMPARE(AgentPlayer::command("opencode","go"),(QStringList{"opencode","run","go"})); + QVERIFY(AgentPlayer::command("freebuff","go").isEmpty()); + QCOMPARE(AgentPlayer::displayName("claude"),QString("Claude Code")); + QCOMPARE(AgentPlayer::displayName("something-new"),QString("something-new")); + + auto p=Chess::Position::initial().after({12,28}); + const QString asked=AgentPlayer::prompt(p,{"e4"}); + QVERIFY(asked.contains("as Black")); + QVERIFY(asked.contains(QString::fromStdString(p.fen()))); + QVERIFY(asked.contains("1. e4")); + QVERIFY(asked.contains("e7e5")); + Chess::Move move; + QVERIFY(AgentPlayer::parse("e7e5",p,&move)); + QCOMPARE(move,(Chess::Move{52,36})); + // An agent that thinks aloud ends on its choice, and may write it as the game does. + QVERIFY(AgentPlayer::parse("I considered e7e5 but **g8f6** develops a piece.",p,&move)); + QCOMPARE(move,(Chess::Move{62,45})); + QVERIFY(AgentPlayer::parse("My move: Nf6.",p,&move)); + QCOMPARE(move,(Chess::Move{62,45})); + // White's own move, a square alone, or prose name nothing Black can play. + QVERIFY(!AgentPlayer::parse("e2e4",p,&move)); + QVERIFY(!AgentPlayer::parse("I resign.",p,&move)); + const auto promotion=Chess::Position::fromFen("8/P6k/8/8/8/8/8/K7 w - - 0 1"); + QVERIFY(AgentPlayer::parse("a7a8q",promotion,&move)); + QCOMPARE(move.promotion,int(Chess::Queen)); + } + + void agentPlaysTheOtherSide() { + QTemporaryDir dir; + const QString defaults=dir.filePath("agent"); + auto script=[&](const QString &name,const QString &body) { + const QString path=dir.filePath(name); + write(path,("#!/bin/sh\n"+body+"\n").toUtf8()); + QFile::setPermissions(path,QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner); + return path; + }; + Backend game(":memory:"); + // A game in memory never looks at the user's own agent, and with none chosen there is nobody to play. + QVERIFY(!game.agentAvailable()); + game.agentPlayer().setDefaultsFile(defaults); + QVERIFY(!game.agentAvailable()); + write(defaults,"claude\n"); + // The prompt arrives as the last argument, in a folder that holds nothing of the user's. + game.agentPlayer().setCommandOverride({script("good","case \"$1\" in *'FEN'*e7e5*) ;; *) exit 3;; esac\n[ -z \"$(ls -A)\" ] || exit 4\necho 'I will play e7e5.'")}); + QVERIFY(game.agentAvailable()); + QCOMPARE(game.agentName(),QString("Claude Code")); + game.newGame(true,0,true,true); + QVERIFY(game.agent() && game.computer()); + QVERIFY(game.move(12,28)); + QTRY_VERIFY_WITH_TIMEOUT(game.thinking(),2000); + QTRY_COMPARE_WITH_TIMEOUT(game.moves(),(QStringList{"e4","e5"}),5000); + QVERIFY(!game.thinking() && !game.agentStalled() && game.whiteTurn()); + // Undo takes back both moves, as against the computer. + game.undo(); + QVERIFY(game.moves().isEmpty()); + + // Nonsense is asked about once more, then the game waits on the player with the reason shown. + const QString count=dir.filePath("count"); + game.agentPlayer().setCommandOverride({script("bad","echo x >> '"+count+"'\necho 'Checkmate in one, surely.'")}); + QVERIFY(game.move(12,28)); + QTRY_VERIFY_WITH_TIMEOUT(game.agentStalled(),5000); + QVERIFY(game.error().contains("Claude Code")); + QVERIFY(!game.thinking()); + QCOMPARE(lines(count),2); + QCOMPARE(game.moves().size(),1); + // Asking again with an agent that answers carries on. + game.agentPlayer().setCommandOverride({script("good2","echo g8f6")}); + game.askAgentAgain(); + QTRY_COMPARE_WITH_TIMEOUT(game.moves().size(),2,5000); + QVERIFY(!game.agentStalled()); + QVERIFY(game.error().isEmpty()); + + // A failing agent's own last words are the reason. + game.agentPlayer().setCommandOverride({script("broke","echo 'Not signed in' >&2\nexit 1")}); + QVERIFY(game.move(11,27)); + QTRY_VERIFY_WITH_TIMEOUT(game.agentStalled(),5000); + QVERIFY(game.error().contains("Not signed in")); + // A slow one is given up on, and a new game stops one mid-thought without a late move arriving. + game.agentPlayer().setCommandOverride({script("slow","sleep 5\necho e7e5")}); + game.agentPlayer().setTimeout(300); + game.newGame(true,0,true,true); + QVERIFY(!game.agentStalled() && game.error().isEmpty()); + QVERIFY(game.move(12,28)); + QTRY_VERIFY_WITH_TIMEOUT(game.agentStalled(),5000); + game.agentPlayer().setTimeout(60000); + game.askAgentAgain(); + QVERIFY(game.thinking()); + game.newGame(false,0); + QVERIFY(!game.thinking() && !game.agent()); + QTest::qWait(300); + QVERIFY(game.moves().isEmpty()); + + // The opponent is saved with the game. + const QString save=dir.filePath("game.json"); + { + Backend saved(save); + saved.agentPlayer().setDefaultsFile(defaults); + saved.agentPlayer().setCommandOverride({script("good3","echo e7e5")}); + saved.newGame(true,0,true,true); + } + Backend restored(save); + restored.agentPlayer().setDefaultsFile(QString()); + QVERIFY(restored.agent() && restored.computer()); + } + void sculptedSurfacesFaceTheirNormals() { SculptGeometry geometry; for(int design=0;design<4;++design) for(int kind=1;kind<=6;++kind) for(int part=0;part<6;++part) { @@ -822,6 +931,23 @@ private slots: QTRY_VERIFY(dialog->property("opened").toBool()); QTest::keyClick(window,Qt::Key_Escape); QTRY_VERIFY(!dialog->property("visible").toBool()); + { + // With a default agent that can answer on its own, the dialog offers it by name after the other two. + auto *mode=window->findChild("mode"); + QVERIFY(mode); + QCOMPARE(mode->property("count").toInt(),2); + QVERIFY(write(dir.filePath("agent"),"codex\n")); + backend.agentPlayer().setDefaultsFile(dir.filePath("agent")); + backend.agentPlayer().setCommandOverride({"/bin/true"}); + QTest::keyClick(window,Qt::Key_N); + QTRY_VERIFY(dialog->property("opened").toBool()); + QCOMPARE(mode->property("count").toInt(),3); + QVERIFY(mode->property("model").toStringList().last().contains("Codex")); + QTest::keyClick(window,Qt::Key_Escape); + QTRY_VERIFY(!dialog->property("visible").toBool()); + backend.agentPlayer().setDefaultsFile(QString()); + backend.agentPlayer().setCommandOverride({}); + } auto *board=window->findChild("board"); QVERIFY(board); {