|
| 1 | +#include "PromptImprover.h" |
| 2 | + |
| 3 | +#include "ApplicationSettings.h" |
| 4 | +#include "CredentialStore.h" |
| 5 | +#include "LlmHttpClient.h" |
| 6 | + |
| 7 | +#include <QDir> |
| 8 | +#include <QFile> |
| 9 | +#include <QJsonArray> |
| 10 | +#include <QJsonDocument> |
| 11 | +#include <QJsonObject> |
| 12 | +#include <QRegularExpression> |
| 13 | + |
| 14 | +namespace ai { |
| 15 | + |
| 16 | +namespace { |
| 17 | + |
| 18 | +const QString kSystemTemplate = QStringLiteral( |
| 19 | + "You are a prompt improvement assistant for a coding agent chat interface.\n" |
| 20 | + "\n" |
| 21 | + "Your task: rewrite the user's draft prompt to be clearer, more specific, " |
| 22 | + "and more actionable for the target coding agent — while preserving the " |
| 23 | + "user's original intent exactly.\n" |
| 24 | + "\n" |
| 25 | + "Rules:\n" |
| 26 | + "- If the prompt starts with a slash command (e.g. /chore, /feat, /fix, " |
| 27 | + "/refactor), you MUST keep that command at the beginning. Never remove, " |
| 28 | + "rename, or reorder it.\n" |
| 29 | + "- Preserve the user's language (if they write in Vietnamese, respond in " |
| 30 | + "Vietnamese; English stays English).\n" |
| 31 | + "- Do not add information the user did not mention. You may restructure, " |
| 32 | + "clarify ambiguity, add specificity where the intent is obvious, and " |
| 33 | + "improve phrasing.\n" |
| 34 | + "- Do not add greetings, sign-offs, or meta-commentary.\n" |
| 35 | + "- Output ONLY the improved prompt wrapped in " |
| 36 | + "<improved_prompt></improved_prompt> tags. No explanation, no preamble, " |
| 37 | + "no alternatives.\n"); |
| 38 | + |
| 39 | +} // namespace |
| 40 | + |
| 41 | +PromptImprover::PromptImprover(ApplicationSettings *settings, |
| 42 | + CredentialStore *credStore, |
| 43 | + QObject *parent) |
| 44 | + : QObject(parent) |
| 45 | + , m_settings(settings) |
| 46 | + , m_credStore(credStore) |
| 47 | + , m_http(new LlmHttpClient(this)) |
| 48 | +{ |
| 49 | + connect(m_http, &ILlmHttpClient::firstByteReceived, this, &PromptImprover::onFirstByte); |
| 50 | + connect(m_http, &ILlmHttpClient::tokenReceived, this, &PromptImprover::onToken); |
| 51 | + connect(m_http, &ILlmHttpClient::streamEnded, this, &PromptImprover::onStreamEnded); |
| 52 | + connect(m_http, &ILlmHttpClient::errorOccurred, this, &PromptImprover::onStreamError); |
| 53 | +} |
| 54 | + |
| 55 | +PromptImprover::~PromptImprover() { cancel(); } |
| 56 | + |
| 57 | +void PromptImprover::setState(State s) |
| 58 | +{ |
| 59 | + if (m_state == s) return; |
| 60 | + m_state = s; |
| 61 | + emit stateChanged(s); |
| 62 | +} |
| 63 | + |
| 64 | +bool PromptImprover::canImprove(QString *whyNot) const |
| 65 | +{ |
| 66 | + auto fail = [whyNot](const QString &msg) { |
| 67 | + if (whyNot) *whyNot = msg; |
| 68 | + return false; |
| 69 | + }; |
| 70 | + if (!m_settings) return fail(tr("Settings unavailable")); |
| 71 | + if (m_state == State::Streaming) |
| 72 | + return fail(tr("Improvement already in progress")); |
| 73 | + if (m_settings->commitMessageProviderUrl().trimmed().isEmpty()) |
| 74 | + return fail(tr("Configure the AI provider URL in Preferences → AI")); |
| 75 | + if (m_settings->commitMessageModel().trimmed().isEmpty()) |
| 76 | + return fail(tr("Configure the AI model in Preferences → AI")); |
| 77 | + if (m_credStore && !m_credStore->isApiKeyAvailable()) |
| 78 | + return fail(tr("Configure the AI API key in Preferences → AI")); |
| 79 | + return true; |
| 80 | +} |
| 81 | + |
| 82 | +void PromptImprover::trigger(const QString &userDraft, |
| 83 | + const QString &workingDirectory, |
| 84 | + const QList<AcpProtocol::AcpCommandInfo> &commands) |
| 85 | +{ |
| 86 | + QString why; |
| 87 | + if (!canImprove(&why)) { |
| 88 | + emit errorOccurred(why); |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + QString apiKey; |
| 93 | + if (m_credStore) { |
| 94 | + QString err; |
| 95 | + apiKey = m_credStore->retrieveApiKey(&err); |
| 96 | + if (apiKey.isEmpty()) { |
| 97 | + emit errorOccurred(err.isEmpty() ? tr("AI API key not available") : err); |
| 98 | + return; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + const QString rules = loadRules(workingDirectory); |
| 103 | + const QString systemPrompt = buildSystemPrompt(rules, commands); |
| 104 | + |
| 105 | + m_responseBuffer.clear(); |
| 106 | + |
| 107 | + ILlmHttpClient::Request req; |
| 108 | + req.url = QUrl(m_settings->commitMessageProviderUrl()); |
| 109 | + req.model = m_settings->commitMessageModel(); |
| 110 | + req.apiKey = apiKey; |
| 111 | + req.systemPrompt = systemPrompt; |
| 112 | + req.prompt = QStringLiteral("<user_draft>\n%1\n</user_draft>").arg(userDraft); |
| 113 | + req.maxTokens = 4096; |
| 114 | + req.idleTimeoutSec = m_settings->commitMessageStreamIdleTimeoutSec(); |
| 115 | + |
| 116 | + setState(State::Streaming); |
| 117 | + m_http->openStream(req); |
| 118 | +} |
| 119 | + |
| 120 | +void PromptImprover::cancel() |
| 121 | +{ |
| 122 | + if (m_state != State::Streaming) return; |
| 123 | + m_http->cancel(); |
| 124 | + m_responseBuffer.clear(); |
| 125 | + setState(State::Idle); |
| 126 | +} |
| 127 | + |
| 128 | +void PromptImprover::onFirstByte() |
| 129 | +{ |
| 130 | + // Nothing special — streaming state already set in trigger(). |
| 131 | +} |
| 132 | + |
| 133 | +void PromptImprover::onToken(const QString &chunk) |
| 134 | +{ |
| 135 | + if (m_state != State::Streaming) return; |
| 136 | + m_responseBuffer.append(chunk); |
| 137 | +} |
| 138 | + |
| 139 | +void PromptImprover::onStreamEnded() |
| 140 | +{ |
| 141 | + if (m_state != State::Streaming) return; |
| 142 | + |
| 143 | + const QString improved = parseImprovedPrompt(m_responseBuffer); |
| 144 | + m_responseBuffer.clear(); |
| 145 | + |
| 146 | + if (improved.isEmpty()) { |
| 147 | + setState(State::Error); |
| 148 | + emit errorOccurred(tr("Could not parse AI response")); |
| 149 | + setState(State::Idle); |
| 150 | + return; |
| 151 | + } |
| 152 | + |
| 153 | + setState(State::Idle); |
| 154 | + emit finished(improved); |
| 155 | +} |
| 156 | + |
| 157 | +void PromptImprover::onStreamError(int httpStatus, const QString &message) |
| 158 | +{ |
| 159 | + Q_UNUSED(httpStatus); |
| 160 | + m_responseBuffer.clear(); |
| 161 | + setState(State::Error); |
| 162 | + emit errorOccurred(message); |
| 163 | + setState(State::Idle); |
| 164 | +} |
| 165 | + |
| 166 | +QString PromptImprover::buildSystemPrompt( |
| 167 | + const QString &rules, |
| 168 | + const QList<AcpProtocol::AcpCommandInfo> &commands) const |
| 169 | +{ |
| 170 | + QString prompt = kSystemTemplate; |
| 171 | + |
| 172 | + if (!rules.isEmpty()) { |
| 173 | + prompt += QStringLiteral("\n<project_rules>\n%1\n</project_rules>\n").arg(rules); |
| 174 | + } |
| 175 | + |
| 176 | + const QString json = serializeCommands(commands); |
| 177 | + if (!json.isEmpty()) { |
| 178 | + prompt += QStringLiteral("\n<available_commands>\n%1\n</available_commands>\n").arg(json); |
| 179 | + } |
| 180 | + |
| 181 | + return prompt; |
| 182 | +} |
| 183 | + |
| 184 | +QString PromptImprover::loadRules(const QString &workingDirectory) const |
| 185 | +{ |
| 186 | + if (workingDirectory.isEmpty()) return {}; |
| 187 | + |
| 188 | + QDir dir(workingDirectory); |
| 189 | + const QString claudePath = dir.filePath(QStringLiteral("CLAUDE.md")); |
| 190 | + const QString agentsPath = dir.filePath(QStringLiteral("AGENTS.md")); |
| 191 | + |
| 192 | + auto readFile = [](const QString &path) -> QByteArray { |
| 193 | + QFile f(path); |
| 194 | + if (!f.exists() || !f.open(QIODevice::ReadOnly)) return {}; |
| 195 | + return f.readAll(); |
| 196 | + }; |
| 197 | + |
| 198 | + const QByteArray claudeContent = readFile(claudePath); |
| 199 | + const QByteArray agentsContent = readFile(agentsPath); |
| 200 | + |
| 201 | + if (claudeContent.isEmpty() && agentsContent.isEmpty()) |
| 202 | + return {}; |
| 203 | + |
| 204 | + if (claudeContent.isEmpty()) |
| 205 | + return QString::fromUtf8(agentsContent).trimmed(); |
| 206 | + |
| 207 | + if (agentsContent.isEmpty()) |
| 208 | + return QString::fromUtf8(claudeContent).trimmed(); |
| 209 | + |
| 210 | + // De-dup: if identical content, send only one copy. |
| 211 | + if (claudeContent == agentsContent) |
| 212 | + return QString::fromUtf8(claudeContent).trimmed(); |
| 213 | + |
| 214 | + return QString::fromUtf8(claudeContent).trimmed() |
| 215 | + + QStringLiteral("\n\n") |
| 216 | + + QString::fromUtf8(agentsContent).trimmed(); |
| 217 | +} |
| 218 | + |
| 219 | +QString PromptImprover::serializeCommands( |
| 220 | + const QList<AcpProtocol::AcpCommandInfo> &commands) const |
| 221 | +{ |
| 222 | + if (commands.isEmpty()) return {}; |
| 223 | + |
| 224 | + QJsonArray arr; |
| 225 | + for (const auto &cmd : commands) { |
| 226 | + QJsonObject obj; |
| 227 | + obj.insert(QLatin1String("name"), cmd.name); |
| 228 | + if (!cmd.description.isEmpty()) |
| 229 | + obj.insert(QLatin1String("description"), cmd.description); |
| 230 | + if (!cmd.inputHint.isEmpty()) |
| 231 | + obj.insert(QLatin1String("inputHint"), cmd.inputHint); |
| 232 | + arr.append(obj); |
| 233 | + } |
| 234 | + return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact)); |
| 235 | +} |
| 236 | + |
| 237 | +QString PromptImprover::parseImprovedPrompt(const QString &response) const |
| 238 | +{ |
| 239 | + static const QRegularExpression re( |
| 240 | + QStringLiteral("<improved_prompt>([\\s\\S]*?)</improved_prompt>")); |
| 241 | + const auto match = re.match(response); |
| 242 | + if (!match.hasMatch()) return {}; |
| 243 | + const QString content = match.captured(1).trimmed(); |
| 244 | + return content.isEmpty() ? QString() : content; |
| 245 | +} |
| 246 | + |
| 247 | +} // namespace ai |
0 commit comments