Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

feat(ai): port ChatGPT OAuth subscription provider from mac PR #53 (#58)

haidang1810e22186c01706
diff --git a/windows/Gridex/AiService.cpp b/windows/Gridex/AiService.cpp
index f4a073e..84d21f3 100644
--- a/windows/Gridex/AiService.cpp
+++ b/windows/Gridex/AiService.cpp
@@ -1,9 +1,14 @@
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
+#include <winhttp.h>
+#pragma comment(lib, "Winhttp.lib")
#include "Models/AiService.h"
+#include "Services/ChatGPTOAuth/ChatGPTOAuthService.h"
#include <nlohmann/json.hpp>
#include <algorithm>
+#include <sstream>
+#include <functional>
// cpp-httplib for HTTP client — suppress deprecated SSL API warnings
#pragma warning(push)
@@ -12,6 +17,81 @@
#include <httplib.h>
#pragma warning(pop)
+namespace {
+ // Native-Win32 HTTPS GET helper. Replaces httplib::SSLClient for
+ // ChatGPT calls — vcpkg httplib 0.40.0 vs OpenSSL 3.x triggers a
+ // SSL_shutdown crash on the worker thread (`s = 0x2`). WinHTTP
+ // sidesteps OpenSSL entirely.
+ struct WinHttpResult { int status = 0; std::string body; };
+
+ WinHttpResult WinHttpsRequest(const std::wstring& host,
+ const std::wstring& method,
+ const std::wstring& path,
+ const std::vector<std::wstring>& headers,
+ const std::string& body,
+ const std::function<bool(const char*, size_t)>* chunkCb = nullptr)
+ {
+ WinHttpResult out;
+ HINTERNET hSession = ::WinHttpOpen(
+ L"Gridex/AiService",
+ WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
+ WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
+ if (!hSession) return out;
+ HINTERNET hConnect = ::WinHttpConnect(
+ hSession, host.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0);
+ if (!hConnect) { ::WinHttpCloseHandle(hSession); return out; }
+ HINTERNET hReq = ::WinHttpOpenRequest(
+ hConnect, method.c_str(), path.c_str(), nullptr,
+ WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
+ WINHTTP_FLAG_SECURE);
+ if (!hReq) { ::WinHttpCloseHandle(hConnect); ::WinHttpCloseHandle(hSession); return out; }
+
+ // Long timeout for streaming responses.
+ ::WinHttpSetTimeouts(hReq, 30000, 30000, 30000, 120000);
+
+ std::wstring hdrBlob;
+ for (auto& h : headers) { hdrBlob += h; hdrBlob += L"\r\n"; }
+
+ BOOL ok = ::WinHttpSendRequest(hReq,
+ hdrBlob.empty() ? WINHTTP_NO_ADDITIONAL_HEADERS : hdrBlob.c_str(),
+ hdrBlob.empty() ? 0 : (DWORD)-1L,
+ body.empty() ? nullptr : (LPVOID)body.data(),
+ (DWORD)body.size(), (DWORD)body.size(), 0);
+ if (ok) ok = ::WinHttpReceiveResponse(hReq, nullptr);
+
+ if (ok)
+ {
+ DWORD statusCode = 0, statusLen = sizeof(statusCode);
+ ::WinHttpQueryHeaders(hReq,
+ WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusLen,
+ WINHTTP_NO_HEADER_INDEX);
+ out.status = (int)statusCode;
+
+ DWORD avail = 0;
+ while (::WinHttpQueryDataAvailable(hReq, &avail) && avail > 0)
+ {
+ std::string chunk(avail, '\0');
+ DWORD read = 0;
+ if (!::WinHttpReadData(hReq, chunk.data(), avail, &read)) break;
+ chunk.resize(read);
+ if (chunkCb)
+ {
+ if (!(*chunkCb)(chunk.data(), chunk.size())) break;
+ }
+ else
+ {
+ out.body.append(chunk);
+ }
+ }
+ }
+ ::WinHttpCloseHandle(hReq);
+ ::WinHttpCloseHandle(hConnect);
+ ::WinHttpCloseHandle(hSession);
+ return out;
+ }
+}
+
namespace DBModels
{
// Trim leading/trailing whitespace from a wide string
@@ -56,6 +136,7 @@ namespace DBModels
case AiProvider::Ollama: return CallOllama(messages, systemPrompt);
case AiProvider::Gemini: return CallGemini(messages, systemPrompt);
case AiProvider::OpenRouter: return CallOpenRouter(messages, systemPrompt);
+ case AiProvider::ChatGPT: return CallChatGPT(messages, systemPrompt);
default: return L"Unsupported AI provider";
}
}
@@ -410,6 +491,144 @@ namespace DBModels
return L"No response content";
}
+ // ── ChatGPT Subscription (Codex Responses API) ─────
+ //
+ // Uses OAuth bearer token from ChatGPT::OAuthService.
+ // POST https://chatgpt.com/backend-api/codex/responses with SSE streaming.
+ // Body shape mirrors Codex CLI's /responses wire format — see
+ // macos/Services/AI/Providers/ChatGPTProvider.swift for the reference impl.
+ std::wstring AiService::CallChatGPT(
+ const std::vector<ChatMessage>& messages,
+ const std::wstring& systemPrompt)
+ {
+ auto bearer = ChatGPT::OAuthService::Instance().BearerToken();
+ if (bearer.empty())
+ return L"Error: Not signed in to ChatGPT. Go to Settings and click Sign in.";
+
+ auto model = trimWs(config_.model);
+ if (model.empty()) model = L"gpt-4o";
+
+ // Build input messages — system role goes to top-level "instructions".
+ // Each content item uses typed parts (input_text / output_text) as
+ // required by the Responses API. Do NOT send temperature or
+ // max_output_tokens — GPT-5 family rejects them (returns HTTP 400).
+ nlohmann::json inputMsgs = nlohmann::json::array();
+ for (auto& m : messages)
+ {
+ if (m.role == L"system") continue; // hoisted to "instructions"
+ std::string partType = (m.role == L"assistant") ? "output_text" : "input_text";
+ nlohmann::json msg;
+ msg["type"] = "message";
+ msg["role"] = toUtf8(m.role);
+ msg["content"] = nlohmann::json::array({
+ nlohmann::json{{"type", partType}, {"text", toUtf8(m.content)}}
+ });
+ inputMsgs.push_back(msg);
+ }
+
+ nlohmann::json body;
+ body["model"] = toUtf8(model);
+ body["instructions"] = toUtf8(systemPrompt);
+ body["input"] = inputMsgs;
+ body["stream"] = true;
+ body["store"] = false;
+
+ std::vector<std::wstring> headers = {
+ L"Authorization: Bearer " + fromUtf8(bearer),
+ L"Content-Type: application/json",
+ L"OpenAI-Beta: responses=v1",
+ };
+ // ChatGPT-Account-ID is required for /responses on accounts
+ // that have multiple workspaces. Mac sends it whenever the
+ // bundle has the claim — mirror that.
+ auto accountId = ChatGPT::OAuthService::Instance().AccountId();
+ if (!accountId.empty())
+ headers.push_back(L"ChatGPT-Account-ID: " + fromUtf8(accountId));
+
+ // Accumulate SSE deltas into full response text.
+ std::string accumulated;
+ bool streamError = false;
+ std::string streamErrorMsg;
+
+ // WinHTTP streaming POST: chunkCb fires per WinHttpReadData read.
+ std::function<bool(const char*, size_t)> chunkCb =
+ [&](const char* data, size_t len) -> bool
+ {
+ // Parse SSE lines from this chunk
+ std::string chunk(data, len);
+ std::istringstream ss(chunk);
+ std::string line;
+ std::string currentEvent;
+
+ while (std::getline(ss, line))
+ {
+ // Strip trailing \r
+ if (!line.empty() && line.back() == '\r')
+ line.pop_back();
+
+ if (line.empty()) { currentEvent.clear(); continue; }
+
+ if (line.rfind("event: ", 0) == 0)
+ {
+ currentEvent = line.substr(7);
+ continue;
+ }
+ if (line.rfind(": ", 0) == 0) continue; // SSE comment
+ if (line.rfind("data: ", 0) != 0) continue;
+
+ std::string payload = line.substr(6);
+ if (payload == "[DONE]") return true;
+
+ if (currentEvent == "response.output_text.delta")
+ {
+ try
+ {
+ auto j = nlohmann::json::parse(payload);
+ if (j.contains("delta") && j["delta"].is_string())
+ accumulated += j["delta"].get<std::string>();
+ }
+ catch (...) {}
+ }
+ else if (currentEvent == "response.error")
+ {
+ streamError = true;
+ streamErrorMsg = payload;
+ return false; // abort stream
+ }
+ else if (currentEvent == "response.completed")
+ {
+ return true;
+ }
+ }
+ return true; // continue receiving
+ };
+
+ auto res = WinHttpsRequest(L"chatgpt.com", L"POST",
+ L"/backend-api/codex/responses", headers, body.dump(), &chunkCb);
+
+ if (res.status == 0)
+ return L"Error: Failed to connect to ChatGPT backend";
+
+ if (res.status == 401 || res.status == 403)
+ {
+ // Token rejected — wipe and tell user to re-authenticate
+ ChatGPT::OAuthService::Instance().SignOut();
+ return L"Error: Session expired. Go to Settings and sign in to ChatGPT again.";
+ }
+
+ if (res.status != 200)
+ return fromUtf8("Error " + std::to_string(res.status) +
+ " from ChatGPT: " + res.body.substr(0, 500));
+
+ if (streamError)
+ return fromUtf8("ChatGPT stream error: " + streamErrorMsg);
+
+ if (accumulated.empty())
+ return L"No response content";
+
+ return fromUtf8(accumulated);
+ }
+
// ── Fetch available models per provider ────────────
//
// Each provider exposes a different listing endpoint and response
@@ -597,6 +816,62 @@ namespace DBModels
break;
}
+ case AiProvider::ChatGPT:
+ {
+ // GET https://chatgpt.com/backend-api/codex/models with bearer token.
+ // Response: {"models": [{"slug": "...", "name": "...", ...}, ...]}
+ auto bearer = ChatGPT::OAuthService::Instance().BearerToken();
+ if (bearer.empty())
+ {
+ r.errorMessage = L"Not signed in to ChatGPT. Sign in via Settings.";
+ return r;
+ }
+ std::vector<std::wstring> hdrs = {
+ L"Authorization: Bearer " + fromUtf8(bearer),
+ };
+ // /backend-api/codex/models rejects the request with
+ // HTTP 400 ({"type":"missing","msg":"Field required"})
+ // when client_version is absent. Mac sends "1.0.0";
+ // mirror that. ChatGPT-Account-ID is required by some
+ // endpoints — pass through when we have it.
+ auto accountId = ChatGPT::OAuthService::Instance().AccountId();
+ if (!accountId.empty())
+ hdrs.push_back(L"ChatGPT-Account-ID: " + fromUtf8(accountId));
+ auto res = WinHttpsRequest(L"chatgpt.com", L"GET",
+ L"/backend-api/codex/models?client_version=1.0.0",
+ hdrs, "");
+ if (res.status == 0)
+ {
+ r.errorMessage = L"ChatGPT models request failed (no response).";
+ return r;
+ }
+ if (res.status == 401 || res.status == 403)
+ {
+ ChatGPT::OAuthService::Instance().SignOut();
+ r.errorMessage = L"Session expired — sign in to ChatGPT again.";
+ return r;
+ }
+ if (res.status != 200)
+ {
+ r.errorMessage = fromUtf8("HTTP " + std::to_string(res.status) + ": " + res.body);
+ return r;
+ }
+ auto json = nlohmann::json::parse(res.body);
+ if (json.contains("models") && json["models"].is_array())
+ {
+ for (auto& m : json["models"])
+ {
+ if (!m.contains("slug")) continue;
+ // Filter to user-listable models only
+ bool supported = m.value("supported_in_api", true);
+ std::string vis = m.value("visibility", "list");
+ if (!supported || vis != "list") continue;
+ r.models.push_back(fromUtf8(m["slug"].get<std::string>()));
+ }
+ }
+ break;
+ }
+
default:
r.errorMessage = L"Unsupported provider.";
return r;
diff --git a/windows/Gridex/ConnectionCard.cpp b/windows/Gridex/ConnectionCard.cpp
index 09f9f0a..abce4fd 100644
--- a/windows/Gridex/ConnectionCard.cpp
+++ b/windows/Gridex/ConnectionCard.cpp
@@ -36,6 +36,28 @@ namespace winrt::Gridex::implementation
ColorTagBar().Background(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(gray));
TagBadge().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);
}
+
+ // Environment tag badge — picks a recognizable colour per
+ // well-known tag so prod is visually distinct from dev/staging
+ // at a glance. Unknown tags fall back to slate gray.
+ if (!config.tag.empty())
+ {
+ winrt::Windows::UI::Color bg;
+ const auto& t = config.tag;
+ if (t == L"Production") bg = winrt::Windows::UI::ColorHelper::FromArgb(255, 220, 38, 38); // red
+ else if (t == L"Staging") bg = winrt::Windows::UI::ColorHelper::FromArgb(255, 234, 88, 12); // orange
+ else if (t == L"Development") bg = winrt::Windows::UI::ColorHelper::FromArgb(255, 22, 163, 74); // green
+ else if (t == L"Testing") bg = winrt::Windows::UI::ColorHelper::FromArgb(255, 124, 58, 237); // purple
+ else if (t == L"Local") bg = winrt::Windows::UI::ColorHelper::FromArgb(255, 75, 85, 99); // slate
+ else bg = winrt::Windows::UI::ColorHelper::FromArgb(255, 100, 100, 100); // gray fallback
+ EnvTagBadge().Background(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(bg));
+ EnvTagBadgeText().Text(winrt::hstring(config.tag));
+ EnvTagBadge().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Visible);
+ }
+ else
+ {
+ EnvTagBadge().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);
+ }
}
void ConnectionCard::ContextConnect_Click(
diff --git a/windows/Gridex/ConnectionCard.xaml b/windows/Gridex/ConnectionCard.xaml
index 7e13e92..ff5d100 100644
--- a/windows/Gridex/ConnectionCard.xaml
+++ b/windows/Gridex/ConnectionCard.xaml
@@ -74,6 +74,16 @@
FontSize="10"
Foreground="White" />
</Border>
+ <!-- Environment tag badge (Production / Staging / ...). Color
+ varies by tag value so prod/dev pop visually different. -->
+ <Border x:Name="EnvTagBadge"
+ CornerRadius="4"
+ Padding="6,1"
+ Visibility="Collapsed">
+ <TextBlock x:Name="EnvTagBadgeText"
+ FontSize="10"
+ Foreground="White" />
+ </Border>
</StackPanel>
<TextBlock x:Name="SubtitleText"
FontSize="12"
diff --git a/windows/Gridex/ConnectionFormDialog.cpp b/windows/Gridex/ConnectionFormDialog.cpp
index 3a90526..d1fb394 100644
--- a/windows/Gridex/ConnectionFormDialog.cpp
+++ b/windows/Gridex/ConnectionFormDialog.cpp
@@ -133,6 +133,20 @@ namespace winrt::Gridex::implementation
config.username = std::wstring(UserInput().Text());
config.database = std::wstring(DatabaseInput().Text());
config.colorTag = selectedColor_;
+ // Persist the environment tag picked in TagCombo. Index 0 is
+ // "None" — store as empty string so the rest of the codebase
+ // can treat absent / "None" identically.
+ {
+ auto tagIdx = TagCombo().SelectedIndex();
+ if (tagIdx > 0)
+ {
+ auto item = TagCombo().Items().GetAt(tagIdx)
+ .try_as<winrt::Microsoft::UI::Xaml::Controls::ComboBoxItem>();
+ if (item)
+ config.tag = std::wstring(winrt::unbox_value<winrt::hstring>(item.Content()));
+ }
+ // tagIdx <= 0 → leave config.tag empty (None).
+ }
auto sslIdx = SslModeInput().SelectedIndex();
config.sslMode = static_cast<DBModels::SSLMode>(sslIdx);
config.sslEnabled = (sslIdx != 1);
@@ -198,6 +212,29 @@ namespace winrt::Gridex::implementation
UriInput().Text(winrt::hstring(config.connectionUri));
MongoOptionsInput().Text(winrt::hstring(config.mongoOptions));
selectedColor_ = config.colorTag;
+ // Restore the environment tag dropdown selection. Match by Content
+ // string against the ComboBoxItem children; fall back to None (0)
+ // when the saved tag isn't in the current option list.
+ {
+ int target = 0;
+ if (!config.tag.empty())
+ {
+ auto items = TagCombo().Items();
+ for (uint32_t i = 0; i < items.Size(); ++i)
+ {
+ auto cbi = items.GetAt(i)
+ .try_as<winrt::Microsoft::UI::Xaml::Controls::ComboBoxItem>();
+ if (!cbi) continue;
+ auto content = winrt::unbox_value<winrt::hstring>(cbi.Content());
+ if (std::wstring(content) == config.tag)
+ {
+ target = static_cast<int>(i);
+ break;
+ }
+ }
+ }
+ TagCombo().SelectedIndex(target);
+ }
if (config.sshConfig.has_value())
{
SshToggle().IsChecked(true);
diff --git a/windows/Gridex/Gridex.items.props b/windows/Gridex/Gridex.items.props
index 289edc6..2250531 100644
--- a/windows/Gridex/Gridex.items.props
+++ b/windows/Gridex/Gridex.items.props
@@ -84,6 +84,11 @@
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ChangeTracker.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\CredentialManager.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\AiService.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\ChatGPTTokenBundle.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\ChatGPTOAuthConstants.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\PKCE.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\JwtDecoder.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\ChatGPTOAuthService.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\AppSettings.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\DumpRestoreService.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ERDiagramService.h" />
@@ -311,6 +316,15 @@
<ClCompile Include="$(MSBuildThisFileDirectory)AiService.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\PKCE.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\JwtDecoder.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\ChatGPTOAuth\ChatGPTOAuthService.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)ExportService.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
diff --git a/windows/Gridex/Models/AiService.h b/windows/Gridex/Models/AiService.h
index 8c7dda7..d873e15 100644
--- a/windows/Gridex/Models/AiService.h
+++ b/windows/Gridex/Models/AiService.h
@@ -16,6 +16,7 @@ namespace DBModels
Ollama = 2,
Gemini = 3,
OpenRouter = 4,
+ ChatGPT = 5, // Subscription-based via OAuth (no API key)
};
struct AiConfig
@@ -88,6 +89,9 @@ namespace DBModels
std::wstring CallOpenRouter(
const std::vector<ChatMessage>& messages,
const std::wstring& systemPrompt);
+ std::wstring CallChatGPT(
+ const std::vector<ChatMessage>& messages,
+ const std::wstring& systemPrompt);
// UTF-8 helpers
static std::string toUtf8(const std::wstring& wstr);
diff --git a/windows/Gridex/Models/ChatGPTTokenBundle.h b/windows/Gridex/Models/ChatGPTTokenBundle.h
new file mode 100644
index 0000000..97e0db6
--- /dev/null
+++ b/windows/Gridex/Models/ChatGPTTokenBundle.h
@@ -0,0 +1,73 @@
+#pragma once
+// ChatGPTTokenBundle.h
+// OAuth token bundle persisted via DPAPI-encrypted file at
+// %APPDATA%\Gridex\chatgpt-tokens.bin for the ChatGPT subscription provider.
+// Stored as JSON (single blob) so refresh writes are atomic.
+
+#include <string>
+#include <chrono>
+#include <nlohmann/json.hpp>
+
+namespace DBModels
+{
+ struct ChatGPTTokenBundle
+ {
+ // JWT — short-lived, used as Authorization: Bearer against chatgpt.com/backend-api/codex.
+ std::string accessToken;
+
+ // JWT — long-lived, used to mint new access tokens. Server may rotate on refresh.
+ std::string refreshToken;
+
+ // JWT — carries claims (email, chatgpt_account_id, chatgpt_plan_type).
+ // Persisted so we can re-derive identity without re-querying the server.
+ std::string idToken;
+
+ // Mirrors chatgpt_account_id from idToken. Sent as ChatGPT-Account-ID header.
+ std::string accountId;
+
+ // Mirrors email claim. UI-only: "Signed in as ...".
+ std::string email;
+
+ // Mirrors chatgpt_plan_type claim (e.g. "plus", "pro"). UI-only.
+ std::string planType;
+
+ // Unix timestamp (seconds) when bundle was minted (sign-in or last refresh).
+ int64_t obtainedAtUnix = 0;
+
+ bool empty() const { return accessToken.empty(); }
+
+ // Serialize to JSON string for DPAPI storage.
+ std::string toJson() const
+ {
+ nlohmann::json j;
+ j["accessToken"] = accessToken;
+ j["refreshToken"] = refreshToken;
+ j["idToken"] = idToken;
+ j["accountId"] = accountId;
+ j["email"] = email;
+ j["planType"] = planType;
+ j["obtainedAt"] = obtainedAtUnix;
+ j["schemaVersion"] = 1;
+ return j.dump();
+ }
+
+ // Deserialize from JSON string. Returns empty bundle on parse error.
+ static ChatGPTTokenBundle fromJson(const std::string& json)
+ {
+ try
+ {
+ auto j = nlohmann::json::parse(json);
+ ChatGPTTokenBundle b;
+ b.accessToken = j.value("accessToken", "");
+ b.refreshToken = j.value("refreshToken", "");
+ b.idToken = j.value("idToken", "");
+ b.accountId = j.value("accountId", "");
+ b.email = j.value("email", "");
+ b.planType = j.value("planType", "");
+ b.obtainedAtUnix = j.value("obtainedAt", int64_t(0));
+ return b;
+ }
+ catch (...) { return {}; }
+ }
+ };
+}
diff --git a/windows/Gridex/Models/ConnectionConfig.h b/windows/Gridex/Models/ConnectionConfig.h
index e90346b..541ed38 100644
--- a/windows/Gridex/Models/ConnectionConfig.h
+++ b/windows/Gridex/Models/ConnectionConfig.h
@@ -47,6 +47,11 @@ namespace DBModels
bool sslEnabled = false;
SSLMode sslMode = SSLMode::Preferred;
std::optional<ColorTag> colorTag;
+ // Free-form environment tag picked from the form's TagCombo
+ // (Production / Staging / Development / Testing / Local).
+ // Empty = "None". Stored as a plain string so we can extend
+ // the dropdown later without a schema migration.
+ std::wstring tag;
std::wstring group;
std::wstring filePath; // SQLite file path
std::wstring connectionUri; // MongoDB URI (mongodb:// or mongodb+srv://)
diff --git a/windows/Gridex/Models/ConnectionStore.h b/windows/Gridex/Models/ConnectionStore.h
index 72942d5..dc733d4 100644
--- a/windows/Gridex/Models/ConnectionStore.h
+++ b/windows/Gridex/Models/ConnectionStore.h
@@ -30,7 +30,7 @@ namespace DBModels
"sort_order, created_at, last_connected_at, connection_uri, "
"mongo_options, "
"ssh_host, ssh_port, ssh_username, ssh_password_enc, "
- "ssh_auth_method, ssh_key_path, mcp_mode "
+ "ssh_auth_method, ssh_key_path, mcp_mode, tag "
"FROM connections ORDER BY sort_order, name";
sqlite3_stmt* stmt = nullptr;
@@ -75,6 +75,9 @@ namespace DBModels
// Column 24: per-connection MCP mode. Defaults to
// Locked (0) for rows created before the migration.
c.mcpMode = static_cast<MCPConnectionMode>(sqlite3_column_int(stmt, 24));
+ // Column 25: free-form environment tag. Empty
+ // string for legacy rows pre-migration.
+ c.tag = ColText16(stmt, 25);
results.push_back(c);
}
sqlite3_finalize(stmt);
@@ -101,10 +104,10 @@ namespace DBModels
"sort_order, created_at, last_connected_at, connection_uri, "
"mongo_options, "
"ssh_host, ssh_port, ssh_username, ssh_password_enc, "
- "ssh_auth_method, ssh_key_path, mcp_mode) "
+ "ssh_auth_method, ssh_key_path, mcp_mode, tag) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0, "
"COALESCE((SELECT created_at FROM connections WHERE id=?), datetime('now')), "
- "datetime('now'), ?, ?, ?,?,?,?,?,?,?)";
+ "datetime('now'), ?, ?, ?,?,?,?,?,?,?,?)";
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) == SQLITE_OK)
@@ -149,6 +152,8 @@ namespace DBModels
// Placeholder 23: per-connection MCP mode. Defaults
// to Locked so new rows never auto-expose data to AI.
sqlite3_bind_int(stmt, 23, static_cast<int>(c.mcpMode));
+ // Placeholder 24: free-form environment tag.
+ BindText(stmt, 24, ToUtf8(c.tag));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
@@ -225,6 +230,12 @@ namespace DBModels
// Default 0 keeps existing connections firewalled from AI until the
// user explicitly opens them up in the MCP Connections tab.
sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN mcp_mode INTEGER DEFAULT 0", nullptr, nullptr, nullptr);
+ // Migration: free-form environment tag (Production / Staging /
+ // Development / Testing / Local / "" for None) picked in the
+ // ConnectionFormDialog's TagCombo. Was rendered in XAML but
+ // never persisted — first run after this migration adds the
+ // column with empty default; existing connections get '' too.
+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN tag TEXT DEFAULT ''", nullptr, nullptr, nullptr);
}
static std::wstring GetDbPath()
diff --git a/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthConstants.h b/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthConstants.h
new file mode 100644
index 0000000..234efcb
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthConstants.h
@@ -0,0 +1,46 @@
+#pragma once
+// ChatGPTOAuthConstants.h
+// Endpoint + parameter constants for the ChatGPT OAuth PKCE flow.
+// All values mirror OpenAI's Codex CLI behaviour. See macos/Services/AI/Auth/ChatGPTOAuthConstants.swift.
+// NOTE: Reusing the public Codex CLI client_id is a deliberate trade-off —
+// OpenAI may revoke it at any time.
+
+#include <string>
+
+namespace ChatGPT
+{
+ // The public OAuth client_id baked into OpenAI's Codex CLI.
+ inline constexpr const char* kClientId = "app_EMoamEEZ73f0CkXaXp7hrann";
+
+ // OAuth issuer base URL — /oauth/authorize and /oauth/token hang off this.
+ inline constexpr const char* kIssuer = "https://auth.openai.com";
+ // Bare host, used when constructing httplib::SSLClient (which takes a
+ // host, NOT a URL — feeding it the full kIssuer makes httplib treat
+ // "https://auth.openai.com" as the literal host name and assert on a
+ // null SSL socket once the handshake is attempted).
+ inline constexpr const char* kIssuerHost = "auth.openai.com";
+
+ // Scope set required by the Codex CLI flow.
+ // `offline_access` gives us a refresh_token.
+ inline constexpr const char* kScopes =
+ "openid profile email offline_access "
+ "api.connectors.read api.connectors.invoke";
+
+ // Codex Responses API backend (distinct from api.openai.com/v1).
+ inline constexpr const char* kBackend = "https://chatgpt.com";
+
+ // Path for the loopback callback.
+ inline constexpr const char* kCallbackPath = "/auth/callback";
+
+ // Loopback port (matches macOS — port 1455 is the Codex CLI default).
+ inline constexpr int kCallbackPort = 1455;
+
+ // Refresh access_token this many seconds before it expires.
+ inline constexpr int kRefreshSkewSeconds = 60;
+
+ // How long to wait for the browser OAuth callback (seconds).
+ inline constexpr int kCallbackTimeoutSeconds = 180;
+
+ // originator query param (informational, not gated by auth server).
+ inline constexpr const char* kOriginator = "gridex_win";
+}
diff --git a/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthService.cpp b/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthService.cpp
new file mode 100644
index 0000000..1ef3a2e
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthService.cpp
@@ -0,0 +1,530 @@
+// ChatGPTOAuthService.cpp
+// Full ChatGPT OAuth lifecycle: sign-in (PKCE + loopback listener),
+// token refresh (coalesced), DPAPI storage, sign-out.
+
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#include <shlobj.h>
+#include <shellapi.h>
+#include <wincrypt.h>
+#include <winhttp.h>
+#pragma comment(lib, "Crypt32.lib")
+#pragma comment(lib, "Shell32.lib")
+#pragma comment(lib, "Winhttp.lib")
+
+#pragma warning(push)
+#pragma warning(disable: 4996)
+#define CPPHTTPLIB_OPENSSL_SUPPORT
+#include <httplib.h>
+#pragma warning(pop)
+
+#include <nlohmann/json.hpp>
+
+#include "ChatGPTOAuthService.h"
+#include "ChatGPTOAuthConstants.h"
+#include "PKCE.h"
+#include "JwtDecoder.h"
+
+namespace {
+ struct HttpResult {
+ int status = 0; // 0 = transport-level failure
+ std::string body;
+ };
+
+ // POST a body to https://<host><path>. WinHTTP-based — replaces an
+ // earlier httplib::SSLClient path that crashed on SSL_shutdown
+ // (vcpkg httplib 0.40.0 vs OpenSSL 3.x ABI / threading mismatch).
+ // Native Windows HTTPS sidesteps the whole question — no extra
+ // dependency, no per-thread OpenSSL state to leak.
+ HttpResult HttpsPost(const std::wstring& host,
+ const std::wstring& path,
+ const std::string& body,
+ const std::wstring& contentType)
+ {
+ HttpResult out;
+ HINTERNET hSession = ::WinHttpOpen(
+ L"Gridex/ChatGPTOAuth",
+ WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
+ WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
+ if (!hSession) return out;
+
+ HINTERNET hConnect = ::WinHttpConnect(
+ hSession, host.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0);
+ if (!hConnect) { ::WinHttpCloseHandle(hSession); return out; }
+
+ HINTERNET hReq = ::WinHttpOpenRequest(
+ hConnect, L"POST", path.c_str(), nullptr,
+ WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
+ WINHTTP_FLAG_SECURE);
+ if (!hReq) {
+ ::WinHttpCloseHandle(hConnect);
+ ::WinHttpCloseHandle(hSession);
+ return out;
+ }
+
+ std::wstring headers = L"Content-Type: " + contentType;
+ BOOL ok = ::WinHttpSendRequest(
+ hReq, headers.c_str(), (DWORD)-1L,
+ (LPVOID)body.data(), (DWORD)body.size(),
+ (DWORD)body.size(), 0);
+ if (ok) ok = ::WinHttpReceiveResponse(hReq, nullptr);
+
+ if (ok)
+ {
+ DWORD statusCode = 0, statusLen = sizeof(statusCode);
+ ::WinHttpQueryHeaders(hReq,
+ WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusLen,
+ WINHTTP_NO_HEADER_INDEX);
+ out.status = static_cast<int>(statusCode);
+
+ DWORD avail = 0;
+ while (::WinHttpQueryDataAvailable(hReq, &avail) && avail > 0)
+ {
+ std::string chunk(avail, '\0');
+ DWORD read = 0;
+ if (!::WinHttpReadData(hReq, chunk.data(), avail, &read)) break;
+ chunk.resize(read);
+ out.body.append(chunk);
+ }
+ }
+
+ ::WinHttpCloseHandle(hReq);
+ ::WinHttpCloseHandle(hConnect);
+ ::WinHttpCloseHandle(hSession);
+ return out;
+ }
+
+ std::wstring Utf8ToWide(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int n = ::MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
+ std::wstring w(n, L'\0');
+ ::MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), w.data(), n);
+ return w;
+ }
+
+ // RFC 3986 percent-encoder for query / form-body values. Anything
+ // outside the unreserved set turns into %XX. Required because the
+ // scope string contains spaces and the redirect_uri contains
+ // reserved chars (:, /) that the OAuth server rejects raw.
+ std::string PercentEncode(const std::string& s)
+ {
+ std::string out;
+ out.reserve(s.size() * 3);
+ auto isUnreserved = [](unsigned char c) {
+ return (c >= 'A' && c <= 'Z') ||
+ (c >= 'a' && c <= 'z') ||
+ (c >= '0' && c <= '9') ||
+ c == '-' || c == '_' || c == '.' || c == '~';
+ };
+ for (unsigned char c : s)
+ {
+ if (isUnreserved(c)) out.push_back(static_cast<char>(c));
+ else
+ {
+ char buf[4];
+ snprintf(buf, sizeof(buf), "%%%02X", c);
+ out.append(buf);
+ }
+ }
+ return out;
+ }
+}
+
+#include <thread>
+#include <chrono>
+#include <stdexcept>
+#include <filesystem>
+#include <fstream>
+
+namespace ChatGPT
+{
+ // ── Singleton ─────────────────────────────────────────────────────────────
+
+ OAuthService& OAuthService::Instance()
+ {
+ static OAuthService instance;
+ return instance;
+ }
+
+ // ── Helpers: UTF-8 ↔ wstring ─────────────────────────────────────────────
+
+ static std::string toUtf8(const std::wstring& w)
+ {
+ if (w.empty()) return {};
+ int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);
+ std::string s(n - 1, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, s.data(), n, nullptr, nullptr);
+ return s;
+ }
+
+ static std::wstring fromUtf8(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
+ std::wstring w(n - 1, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n);
+ return w;
+ }
+
+ // ── DPAPI helpers ─────────────────────────────────────────────────────────
+
+ std::wstring OAuthService::TokenFilePath()
+ {
+ wchar_t* appData = nullptr;
+ SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appData);
+ std::wstring path = appData ? std::wstring(appData) + L"\\Gridex" : L".";
+ CoTaskMemFree(appData);
+ std::filesystem::create_directories(path);
+ return path + L"\\chatgpt-tokens.bin";
+ }
+
+ bool OAuthService::SaveBundle(const DBModels::ChatGPTTokenBundle& bundle)
+ {
+ std::string json = bundle.toJson();
+
+ DATA_BLOB input;
+ input.pbData = reinterpret_cast<BYTE*>(const_cast<char*>(json.data()));
+ input.cbData = static_cast<DWORD>(json.size());
+
+ DATA_BLOB output = {};
+ if (!CryptProtectData(&input, nullptr, nullptr, nullptr, nullptr, 0, &output))
+ return false;
+
+ auto path = TokenFilePath();
+ std::ofstream f(path, std::ios::binary | std::ios::trunc);
+ if (!f) { LocalFree(output.pbData); return false; }
+ f.write(reinterpret_cast<char*>(output.pbData), output.cbData);
+ LocalFree(output.pbData);
+ return true;
+ }
+
+ DBModels::ChatGPTTokenBundle OAuthService::LoadBundle()
+ {
+ auto path = TokenFilePath();
+ std::ifstream f(path, std::ios::binary);
+ if (!f) return {};
+
+ std::vector<BYTE> enc((std::istreambuf_iterator<char>(f)),
+ std::istreambuf_iterator<char>());
+ if (enc.empty()) return {};
+
+ DATA_BLOB input;
+ input.pbData = enc.data();
+ input.cbData = static_cast<DWORD>(enc.size());
+
+ DATA_BLOB output = {};
+ if (!CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr, 0, &output))
+ return {};
+
+ std::string json(reinterpret_cast<char*>(output.pbData), output.cbData);
+ LocalFree(output.pbData);
+ return DBModels::ChatGPTTokenBundle::fromJson(json);
+ }
+
+ void OAuthService::DeleteBundle()
+ {
+ auto path = TokenFilePath();
+ std::error_code ec;
+ std::filesystem::remove(path, ec);
+ }
+
+ // ── JWT claims helper ─────────────────────────────────────────────────────
+
+ void OAuthService::ApplyClaims(DBModels::ChatGPTTokenBundle& bundle)
+ {
+ if (bundle.idToken.empty()) return;
+ try
+ {
+ auto claims = JwtDecodePayload(bundle.idToken);
+ if (claims.contains("email") && claims["email"].is_string())
+ bundle.email = claims["email"].get<std::string>();
+ if (claims.contains("chatgpt_account_id") && claims["chatgpt_account_id"].is_string())
+ bundle.accountId = claims["chatgpt_account_id"].get<std::string>();
+ if (claims.contains("chatgpt_plan_type") && claims["chatgpt_plan_type"].is_string())
+ bundle.planType = claims["chatgpt_plan_type"].get<std::string>();
+ }
+ catch (...) {}
+ }
+
+ // ── Token refresh ─────────────────────────────────────────────────────────
+
+ DBModels::ChatGPTTokenBundle OAuthService::RefreshBundle(
+ const DBModels::ChatGPTTokenBundle& current)
+ {
+ // OAuth token endpoint takes form-urlencoded — switched from
+ // JSON because some upstream OIDC implementations reject JSON.
+ std::string formBody =
+ "client_id=" + PercentEncode(kClientId) +
+ "&grant_type=refresh_token"
+ "&refresh_token=" + PercentEncode(current.refreshToken);
+
+ auto res = HttpsPost(Utf8ToWide(kIssuerHost), L"/oauth/token",
+ formBody, L"application/x-www-form-urlencoded");
+ if (res.status < 200 || res.status >= 300) return {};
+
+ try
+ {
+ auto j = nlohmann::json::parse(res.body);
+ DBModels::ChatGPTTokenBundle updated = current;
+ if (j.contains("access_token") && j["access_token"].is_string())
+ updated.accessToken = j["access_token"].get<std::string>();
+ // Server may rotate refresh_token and id_token
+ if (j.contains("refresh_token") && j["refresh_token"].is_string())
+ {
+ auto rt = j["refresh_token"].get<std::string>();
+ if (!rt.empty()) updated.refreshToken = rt;
+ }
+ if (j.contains("id_token") && j["id_token"].is_string())
+ {
+ auto idt = j["id_token"].get<std::string>();
+ if (!idt.empty()) { updated.idToken = idt; ApplyClaims(updated); }
+ }
+ updated.obtainedAtUnix = std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count();
+ return updated;
+ }
+ catch (...) { return {}; }
+ }
+
+ // ── BearerToken — public, coalesced refresh ────────────────────────────────
+
+ std::string OAuthService::BearerToken()
+ {
+ auto bundle = LoadBundle();
+ if (bundle.empty()) return {};
+
+ // Check expiry with skew window
+ int64_t exp = JwtExpiration(bundle.accessToken);
+ int64_t now = std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count();
+
+ if (exp > 0 && now < exp - kRefreshSkewSeconds)
+ return bundle.accessToken;
+
+ // Coalesce concurrent refresh calls
+ {
+ std::lock_guard<std::mutex> lock(refreshMutex_);
+ if (refreshFuture_.valid())
+ return refreshFuture_.get();
+
+ auto promise = std::make_shared<std::promise<std::string>>();
+ refreshFuture_ = promise->get_future().share();
+
+ std::thread([bundle, promise, this]() mutable {
+ auto updated = RefreshBundle(bundle);
+ if (updated.empty())
+ {
+ // Refresh failed — do not wipe tokens, return old (may be expired)
+ promise->set_value(bundle.accessToken);
+ }
+ else
+ {
+ SaveBundle(updated);
+ promise->set_value(updated.accessToken);
+ }
+ std::lock_guard<std::mutex> lk(refreshMutex_);
+ refreshFuture_ = {};
+ }).detach();
+ }
+
+ return refreshFuture_.get();
+ }
+
+ // ── IsSignedIn / CurrentEmail ─────────────────────────────────────────────
+
+ bool OAuthService::IsSignedIn()
+ {
+ return !LoadBundle().empty();
+ }
+
+ std::wstring OAuthService::CurrentEmail()
+ {
+ auto b = LoadBundle();
+ return fromUtf8(b.email);
+ }
+
+ std::string OAuthService::AccountId()
+ {
+ return LoadBundle().accountId;
+ }
+
+ // ── SignOut ───────────────────────────────────────────────────────────────
+
+ void OAuthService::SignOut()
+ {
+ DeleteBundle();
+ }
+
+ // ── SignIn — loopback listener + PKCE exchange ─────────────────────────────
+
+ void OAuthService::SignIn(SignInCallback callback)
+ {
+ std::thread([callback]() {
+ try
+ {
+ auto verifier = PKCEMakeVerifier();
+ auto challenge = PKCEChallenge(verifier);
+ auto state = PKCEMakeState();
+ // The Codex CLI client_id is registered for the
+ // `localhost` host, not `127.0.0.1`. Using the literal
+ // IP yields OpenAI's generic Authentication Error
+ // ("unknown_error") with no further detail.
+ std::string redirectURI =
+ std::string("http://localhost:") + std::to_string(kCallbackPort) + kCallbackPath;
+
+ // Build the authorize URL — every value is percent-
+ // encoded since the scope contains spaces and the
+ // redirect URI contains reserved chars (:, /).
+ std::string authURL =
+ std::string(kIssuer) + "/oauth/authorize"
+ "?response_type=code"
+ "&client_id=" + PercentEncode(kClientId) +
+ "&redirect_uri=" + PercentEncode(redirectURI) +
+ "&scope=" + PercentEncode(kScopes) +
+ "&code_challenge=" + PercentEncode(challenge) +
+ "&code_challenge_method=S256"
+ "&state=" + PercentEncode(state) +
+ "&id_token_add_organizations=true"
+ "&codex_cli_simplified_flow=true"
+ "&originator=" + PercentEncode(kOriginator);
+
+ // Open the system browser
+ std::wstring wUrl = fromUtf8(authURL);
+ ShellExecuteW(nullptr, L"open", wUrl.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+
+ // Single-shot loopback HTTP listener on 127.0.0.1:1455
+ // Uses cpp-httplib in server mode (already available in the project).
+ std::string receivedCode;
+ std::string receivedState;
+ bool gotCallback = false;
+
+ httplib::Server svr;
+
+ svr.Get(kCallbackPath, [&](const httplib::Request& req,
+ httplib::Response& res)
+ {
+ receivedCode = req.get_param_value("code");
+ receivedState = req.get_param_value("state");
+ gotCallback = true;
+
+ res.set_content(
+ "<!doctype html><html><head><meta charset='utf-8'>"
+ "<title>Gridex sign-in</title>"
+ "<style>body{font:14px sans-serif;text-align:center;padding:80px}</style>"
+ "</head><body><h2>Sign-in complete</h2>"
+ "<p>You can close this tab and return to Gridex.</p>"
+ "<script>setTimeout(()=>window.close(),500)</script>"
+ "</body></html>",
+ "text/html");
+ // Don't call svr.stop() from inside the handler —
+ // the outer wait loop handles teardown via
+ // gotCallback + is_running(). Calling stop() here
+ // (and again outside) trips httplib's
+ // svr_sock_ != INVALID_SOCKET assertion.
+ });
+
+ // Bind to 127.0.0.1 only (not 0.0.0.0) to prevent LAN-side hijack
+ svr.set_address_family(AF_INET);
+
+ // Run the server in a separate thread with timeout
+ bool serverStarted = false;
+ std::mutex startMtx;
+ std::condition_variable startCv;
+
+ std::thread svrThread([&]() {
+ {
+ std::lock_guard<std::mutex> lk(startMtx);
+ serverStarted = true;
+ }
+ startCv.notify_one();
+ svr.listen("127.0.0.1", kCallbackPort);
+ });
+
+ // Wait for server to be ready
+ {
+ std::unique_lock<std::mutex> lk(startMtx);
+ startCv.wait(lk, [&] { return serverStarted; });
+ }
+
+ // Give the server a small moment to bind
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+
+ // Wait for callback (up to kCallbackTimeoutSeconds)
+ auto deadline = std::chrono::steady_clock::now()
+ + std::chrono::seconds(kCallbackTimeoutSeconds);
+ while (!gotCallback && std::chrono::steady_clock::now() < deadline)
+ std::this_thread::sleep_for(std::chrono::milliseconds(200));
+
+ if (svrThread.joinable())
+ {
+ if (svr.is_running()) svr.stop();
+ svrThread.join();
+ }
+
+ if (!gotCallback)
+ throw std::runtime_error("Sign-in timed out — no callback received");
+
+ // CSRF guard
+ if (receivedState != state)
+ throw std::runtime_error("State mismatch — possible CSRF, sign-in aborted");
+
+ if (receivedCode.empty())
+ throw std::runtime_error("No authorization code in callback");
+
+ // Exchange code for tokens via WinHTTP (replaces an
+ // earlier httplib::SSLClient path that crashed on
+ // SSL_shutdown when the SSLClient destructor ran on
+ // the worker thread).
+ std::string formBody =
+ "grant_type=authorization_code"
+ "&code=" + PercentEncode(receivedCode) +
+ "&redirect_uri=" + PercentEncode(redirectURI) +
+ "&client_id=" + PercentEncode(kClientId) +
+ "&code_verifier=" + PercentEncode(verifier);
+
+ auto res2 = HttpsPost(Utf8ToWide(kIssuerHost), L"/oauth/token",
+ formBody, L"application/x-www-form-urlencoded");
+
+ if (res2.status < 200 || res2.status >= 300)
+ {
+ throw std::runtime_error(
+ "Token exchange failed (HTTP " + std::to_string(res2.status)
+ + "): " + (res2.body.empty() ? "(no body)" : res2.body));
+ }
+
+ auto j = nlohmann::json::parse(res2.body);
+ std::string accessToken = j.value("access_token", "");
+ std::string refreshToken = j.value("refresh_token", "");
+ std::string idToken = j.value("id_token", "");
+
+ if (accessToken.empty())
+ throw std::runtime_error("Token exchange returned no access_token");
+ if (refreshToken.empty())
+ throw std::runtime_error("Token exchange returned no refresh_token (offline_access scope missing?)");
+
+ DBModels::ChatGPTTokenBundle bundle;
+ bundle.accessToken = accessToken;
+ bundle.refreshToken = refreshToken;
+ bundle.idToken = idToken;
+ bundle.obtainedAtUnix = std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count();
+ ApplyClaims(bundle);
+
+ SaveBundle(bundle);
+
+ callback(true, fromUtf8(bundle.email));
+ }
+ catch (const std::exception& e)
+ {
+ callback(false, fromUtf8(e.what()));
+ }
+ catch (...)
+ {
+ callback(false, L"Unknown error during sign-in");
+ }
+ }).detach();
+ }
+}
diff --git a/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthService.h b/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthService.h
new file mode 100644
index 0000000..4f8f7ee
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/ChatGPTOAuthService.h
@@ -0,0 +1,74 @@
+#pragma once
+// ChatGPTOAuthService.h
+// Owns the full ChatGPT OAuth lifecycle for the Windows app:
+// - SignIn(callback) — PKCE flow, opens browser, loopback listener, stores tokens
+// - SignOut() — deletes the DPAPI-encrypted token file
+// - BearerToken() — returns current access_token, refreshing if within kRefreshSkewSeconds
+// - CurrentEmail() — UI helper, returns stored email or empty string
+//
+// Token storage: DPAPI-encrypted JSON at %APPDATA%\Gridex\chatgpt-tokens.bin
+// Concurrent refresh coalesced via std::mutex + std::shared_future.
+
+#include <string>
+#include <functional>
+#include <mutex>
+#include <future>
+#include "../../Models/ChatGPTTokenBundle.h"
+
+namespace ChatGPT
+{
+ class OAuthService
+ {
+ public:
+ // Callback type: called on the worker thread after sign-in completes.
+ // success=true: email holds the signed-in address.
+ // success=false: error holds a user-visible message.
+ using SignInCallback = std::function<void(bool success, std::wstring emailOrError)>;
+
+ // Launch the PKCE browser flow asynchronously. Callback fires on a
+ // background thread — marshal to UI thread before touching UI.
+ void SignIn(SignInCallback callback);
+
+ // Wipe the stored token bundle. Safe to call even if not signed in.
+ void SignOut();
+
+ // Returns the current access_token, refreshing it if needed.
+ // Returns empty string if not signed in or refresh failed.
+ std::string BearerToken();
+
+ // Returns the stored email claim, or empty string if signed out.
+ std::wstring CurrentEmail();
+ // ChatGPT-Account-ID claim value (UTF-8). Some /backend-api/codex
+ // endpoints require this as a header; empty when not signed in.
+ std::string AccountId();
+
+ // True if a valid token bundle exists on disk.
+ bool IsSignedIn();
+
+ // Singleton accessor — no DI complexity needed for Windows port.
+ static OAuthService& Instance();
+
+ private:
+ OAuthService() = default;
+
+ // DPAPI-encrypted token file path: %APPDATA%\Gridex\chatgpt-tokens.bin
+ static std::wstring TokenFilePath();
+
+ // Load/save/delete token bundle via DPAPI.
+ static bool SaveBundle(const DBModels::ChatGPTTokenBundle& bundle);
+ static DBModels::ChatGPTTokenBundle LoadBundle();
+ static void DeleteBundle();
+
+ // Perform token refresh via POST /oauth/token with refresh_token grant.
+ // Returns empty bundle on failure.
+ static DBModels::ChatGPTTokenBundle RefreshBundle(
+ const DBModels::ChatGPTTokenBundle& current);
+
+ // Apply claims from id_token into the bundle fields.
+ static void ApplyClaims(DBModels::ChatGPTTokenBundle& bundle);
+
+ // Coalesce concurrent refresh calls.
+ std::mutex refreshMutex_;
+ std::shared_future<std::string> refreshFuture_;
+ };
+}
diff --git a/windows/Gridex/Services/ChatGPTOAuth/JwtDecoder.cpp b/windows/Gridex/Services/ChatGPTOAuth/JwtDecoder.cpp
new file mode 100644
index 0000000..be4475a
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/JwtDecoder.cpp
@@ -0,0 +1,75 @@
+// JwtDecoder.cpp
+// Minimal JWT payload decoder — base64url-decode the middle segment, parse JSON.
+// No signature verification (trusts OpenAI's TLS, matching macOS behaviour).
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <wincrypt.h>
+#pragma comment(lib, "Crypt32.lib")
+
+#include "JwtDecoder.h"
+#include <stdexcept>
+#include <vector>
+
+namespace ChatGPT
+{
+ // base64url -> standard base64 with padding, then decode via CryptStringToBinaryA
+ // (Crypt32.lib is already linked by the project).
+ static std::vector<unsigned char> base64URLDecode(std::string s)
+ {
+ // Reverse URL-safe substitutions
+ for (char& c : s)
+ {
+ if (c == '-') c = '+';
+ else if (c == '_') c = '/';
+ }
+ // Re-pad to multiple of 4
+ while (s.size() % 4 != 0)
+ s += '=';
+
+ DWORD outLen = 0;
+ if (!CryptStringToBinaryA(s.c_str(), static_cast<DWORD>(s.size()),
+ CRYPT_STRING_BASE64, nullptr, &outLen, nullptr, nullptr))
+ throw std::runtime_error("JwtDecoder: base64 size query failed");
+
+ std::vector<unsigned char> out(outLen);
+ if (!CryptStringToBinaryA(s.c_str(), static_cast<DWORD>(s.size()),
+ CRYPT_STRING_BASE64, out.data(), &outLen, nullptr, nullptr))
+ throw std::runtime_error("JwtDecoder: base64 decode failed");
+ out.resize(outLen);
+ return out;
+ }
+
+ nlohmann::json JwtDecodePayload(const std::string& jwt)
+ {
+ // Split "header.payload.signature" on '.'
+ size_t dot1 = jwt.find('.');
+ if (dot1 == std::string::npos)
+ throw std::runtime_error("JwtDecoder: missing first dot");
+ size_t dot2 = jwt.find('.', dot1 + 1);
+ if (dot2 == std::string::npos)
+ throw std::runtime_error("JwtDecoder: missing second dot");
+
+ std::string payload = jwt.substr(dot1 + 1, dot2 - dot1 - 1);
+ auto bytes = base64URLDecode(payload);
+ std::string json(bytes.begin(), bytes.end());
+ return nlohmann::json::parse(json);
+ }
+
+ int64_t JwtExpiration(const std::string& jwt)
+ {
+ try
+ {
+ auto claims = JwtDecodePayload(jwt);
+ if (claims.contains("exp"))
+ {
+ if (claims["exp"].is_number_integer())
+ return claims["exp"].get<int64_t>();
+ if (claims["exp"].is_number_float())
+ return static_cast<int64_t>(claims["exp"].get<double>());
+ }
+ }
+ catch (...) {}
+ return 0; // treat as expired
+ }
+}
diff --git a/windows/Gridex/Services/ChatGPTOAuth/JwtDecoder.h b/windows/Gridex/Services/ChatGPTOAuth/JwtDecoder.h
new file mode 100644
index 0000000..35eded4
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/JwtDecoder.h
@@ -0,0 +1,18 @@
+#pragma once
+// JwtDecoder.h
+// Minimal JWT payload decoder. No signature verification — we trust OpenAI's TLS.
+// Only needed for reading claims: exp, email, chatgpt_account_id, chatgpt_plan_type.
+
+#include <string>
+#include <nlohmann/json.hpp>
+
+namespace ChatGPT
+{
+ // Decode the payload segment of a JWT into a JSON object.
+ // Throws std::runtime_error if the token is malformed.
+ nlohmann::json JwtDecodePayload(const std::string& jwt);
+
+ // Extract the `exp` Unix timestamp from the JWT payload.
+ // Returns 0 if missing or parse error — caller should treat as expired.
+ int64_t JwtExpiration(const std::string& jwt);
+}
diff --git a/windows/Gridex/Services/ChatGPTOAuth/PKCE.cpp b/windows/Gridex/Services/ChatGPTOAuth/PKCE.cpp
new file mode 100644
index 0000000..6c4387b
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/PKCE.cpp
@@ -0,0 +1,81 @@
+// PKCE.cpp
+// RFC 7636 PKCE implementation using OpenSSL EVP_Digest (libcrypto, already
+// linked via vcpkg) and BCryptGenRandom for the CSPRNG.
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <bcrypt.h>
+#pragma comment(lib, "bcrypt.lib")
+
+#include <openssl/evp.h>
+#include <openssl/bio.h>
+#include <openssl/buffer.h>
+
+#include "PKCE.h"
+#include <vector>
+#include <stdexcept>
+
+namespace ChatGPT
+{
+ // base64url-no-pad: standard base64, then + -> -, / -> _, strip =
+ static std::string toBase64URL(const std::vector<unsigned char>& data)
+ {
+ // Use OpenSSL BIO base64 encode
+ BIO* b64 = BIO_new(BIO_f_base64());
+ BIO* mem = BIO_new(BIO_s_mem());
+ b64 = BIO_push(b64, mem);
+ BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
+ BIO_write(b64, data.data(), static_cast<int>(data.size()));
+ BIO_flush(b64);
+
+ BUF_MEM* bptr = nullptr;
+ BIO_get_mem_ptr(b64, &bptr);
+ std::string result(bptr->data, bptr->length);
+ BIO_free_all(b64);
+
+ // Convert to base64url (no padding)
+ for (char& c : result)
+ {
+ if (c == '+') c = '-';
+ else if (c == '/') c = '_';
+ }
+ // Strip trailing '='
+ while (!result.empty() && result.back() == '=')
+ result.pop_back();
+ return result;
+ }
+
+ static std::vector<unsigned char> randomBytes(size_t count)
+ {
+ std::vector<unsigned char> buf(count);
+ NTSTATUS status = BCryptGenRandom(nullptr, buf.data(),
+ static_cast<ULONG>(count), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
+ if (!BCRYPT_SUCCESS(status))
+ throw std::runtime_error("BCryptGenRandom failed");
+ return buf;
+ }
+
+ std::string PKCEMakeVerifier()
+ {
+ return toBase64URL(randomBytes(32));
+ }
+
+ std::string PKCEChallenge(const std::string& verifier)
+ {
+ // SHA-256 via OpenSSL EVP
+ unsigned char hash[EVP_MAX_MD_SIZE];
+ unsigned int hashLen = 0;
+ EVP_MD_CTX* ctx = EVP_MD_CTX_new();
+ EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr);
+ EVP_DigestUpdate(ctx, verifier.data(), verifier.size());
+ EVP_DigestFinal_ex(ctx, hash, &hashLen);
+ EVP_MD_CTX_free(ctx);
+
+ return toBase64URL(std::vector<unsigned char>(hash, hash + hashLen));
+ }
+
+ std::string PKCEMakeState()
+ {
+ return toBase64URL(randomBytes(32));
+ }
+}
diff --git a/windows/Gridex/Services/ChatGPTOAuth/PKCE.h b/windows/Gridex/Services/ChatGPTOAuth/PKCE.h
new file mode 100644
index 0000000..a859e2a
--- /dev/null
+++ b/windows/Gridex/Services/ChatGPTOAuth/PKCE.h
@@ -0,0 +1,18 @@
+#pragma once
+// PKCE.h
+// RFC 7636 PKCE primitives for the ChatGPT OAuth flow. Pure functions, no I/O.
+// Uses OpenSSL EVP_Digest (libcrypto already linked via vcpkg).
+
+#include <string>
+
+namespace ChatGPT
+{
+ // 32 random bytes -> base64url-no-pad (43 chars). Suitable as code_verifier.
+ std::string PKCEMakeVerifier();
+
+ // SHA256(verifier) -> base64url-no-pad. Used as code_challenge with S256.
+ std::string PKCEChallenge(const std::string& verifier);
+
+ // 32 random bytes -> base64url-no-pad. Used as OAuth state param (CSRF guard).
+ std::string PKCEMakeState();
+}
diff --git a/windows/Gridex/SettingsPage.cpp b/windows/Gridex/SettingsPage.cpp
index 78e25da..13be115 100644
--- a/windows/Gridex/SettingsPage.cpp
+++ b/windows/Gridex/SettingsPage.cpp
@@ -5,6 +5,7 @@
#include "SettingsPage.h"
#include "Models/AppSettings.h"
#include "Models/AiService.h"
+#include "Services/ChatGPTOAuth/ChatGPTOAuthService.h"
#include "Models/ShortcutsCatalog.h"
#include "GridexVersion.h"
#include "UpdateService.h"
@@ -48,6 +49,134 @@ namespace winrt::Gridex::implementation
EditorFontSizeBox().Value(static_cast<double>(s.editorFontSize));
RowLimitBox().Value(static_cast<double>(s.rowLimit));
+ // Helper: show/hide provider-specific panels (API key /
+ // OAuth sign-in / Ollama endpoint) based on selection.
+ // Indices: 0 Anthropic, 1 OpenAI, 2 Ollama, 3 Gemini,
+ // 4 OpenRouter, 5 ChatGPT.
+ auto updateProviderUI = [this]()
+ {
+ int idx = AiProviderCombo().SelectedIndex();
+ bool isChatGPT = (idx == 5);
+ bool isOllama = (idx == 2);
+
+ ApiKeyPanel().Visibility(isChatGPT
+ ? mux::Visibility::Collapsed
+ : mux::Visibility::Visible);
+ SignInPanel().Visibility(isChatGPT
+ ? mux::Visibility::Visible
+ : mux::Visibility::Collapsed);
+ // Ollama endpoint is only meaningful for the Ollama
+ // provider — hide it for everyone else so the form
+ // doesn't carry stale state across provider switches.
+ OllamaEndpointPanel().Visibility(isOllama
+ ? mux::Visibility::Visible
+ : mux::Visibility::Collapsed);
+
+ if (isChatGPT)
+ {
+ auto& svc = ChatGPT::OAuthService::Instance();
+ if (svc.IsSignedIn())
+ {
+ auto email = svc.CurrentEmail();
+ std::wstring statusText = email.empty()
+ ? L"Signed in"
+ : L"Signed in as " + email;
+ ChatGPTStatusText().Text(winrt::hstring(statusText));
+ ChatGPTSignInBtn().Visibility(mux::Visibility::Collapsed);
+ ChatGPTSignOutBtn().Visibility(mux::Visibility::Visible);
+ }
+ else
+ {
+ ChatGPTStatusText().Text(L"Not signed in");
+ ChatGPTSignInBtn().Visibility(mux::Visibility::Visible);
+ ChatGPTSignOutBtn().Visibility(mux::Visibility::Collapsed);
+ }
+ }
+ };
+
+ // Apply on load
+ updateProviderUI();
+
+ // Re-apply when user changes the provider ComboBox
+ AiProviderCombo().SelectionChanged(
+ [this, updateProviderUI](winrt::Windows::Foundation::IInspectable const&,
+ muxc::SelectionChangedEventArgs const&)
+ {
+ updateProviderUI();
+ });
+
+ // Sign in button
+ ChatGPTSignInBtn().Click(
+ [this, updateProviderUI](winrt::Windows::Foundation::IInspectable const&,
+ mux::RoutedEventArgs const&)
+ {
+ ChatGPTSignInBtn().IsEnabled(false);
+ ChatGPTStatusText().Text(L"Opening browser…");
+
+ auto dispatcher = this->DispatcherQueue();
+ ChatGPT::OAuthService::Instance().SignIn(
+ [this, dispatcher, updateProviderUI](bool success, std::wstring emailOrError)
+ {
+ dispatcher.TryEnqueue([this, success, emailOrError, updateProviderUI, dispatcher]()
+ {
+ ChatGPTSignInBtn().IsEnabled(true);
+ if (!success)
+ {
+ ChatGPTStatusText().Text(
+ winrt::hstring(L"Sign-in failed: " + emailOrError));
+ return;
+ }
+ updateProviderUI();
+
+ // Stale model from a previous provider
+ // doesn't apply to ChatGPT — wipe the
+ // field and fetch the live model list
+ // from /backend-api/codex/models for
+ // this account.
+ ModelBox().Items().Clear();
+ ModelBox().Text(L"");
+ ModelFetchStatusText().Visibility(mux::Visibility::Visible);
+ ModelFetchStatusText().Text(L"Fetching models…");
+
+ DBModels::AiConfig cfg;
+ cfg.provider = DBModels::AiProvider::ChatGPT;
+ std::thread([cfg, dispatcher, weak = get_weak()]()
+ {
+ auto res = DBModels::AiService::FetchModels(cfg);
+ dispatcher.TryEnqueue([weak, res]()
+ {
+ auto self = weak.get();
+ if (!self) return;
+ if (!res.success)
+ {
+ self->ModelFetchStatusText().Text(
+ winrt::hstring(L"Fetch failed: " + res.errorMessage));
+ return;
+ }
+ for (const auto& m : res.models)
+ self->ModelBox().Items().Append(
+ winrt::box_value(winrt::hstring(m)));
+ if (!res.models.empty())
+ self->ModelBox().Text(winrt::hstring(res.models.front()));
+ self->ModelFetchStatusText().Text(
+ winrt::hstring(L"Loaded "
+ + std::to_wstring(res.models.size())
+ + L" model(s)"));
+ });
+ }).detach();
+ });
+ });
+ });
+
+ // Sign out button
+ ChatGPTSignOutBtn().Click(
+ [this, updateProviderUI](winrt::Windows::Foundation::IInspectable const&,
+ mux::RoutedEventArgs const&)
+ {
+ ChatGPT::OAuthService::Instance().SignOut();
+ updateProviderUI();
+ });
+
// Refresh models: hit the provider's list endpoint on a
// worker thread, populate ModelBox items on success. Keep
// the user's current text selection after repopulating so
diff --git a/windows/Gridex/SettingsPage.xaml b/windows/Gridex/SettingsPage.xaml
index 3928f3b..5ae512f 100644
--- a/windows/Gridex/SettingsPage.xaml
+++ b/windows/Gridex/SettingsPage.xaml
@@ -88,10 +88,11 @@
<ComboBoxItem Content="Ollama (Local)" />
<ComboBoxItem Content="Google Gemini" />
<ComboBoxItem Content="OpenRouter" />
+ <ComboBoxItem Content="OpenAI (Sign in)" />
</ComboBox>
</StackPanel>
- <StackPanel Spacing="4">
+ <StackPanel x:Name="ApiKeyPanel" Spacing="4">
<TextBlock Text="API Key" FontSize="14" />
<PasswordBox x:Name="ApiKeyBox"
PlaceholderText="Enter your API key..."
@@ -99,6 +100,20 @@
HorizontalAlignment="Left" />
</StackPanel>
+ <!-- Shown only when AiProviderCombo index = 5 (ChatGPT / OpenAI Sign in) -->
+ <StackPanel x:Name="SignInPanel" Spacing="8" Visibility="Collapsed">
+ <TextBlock Text="ChatGPT Account" FontSize="14" />
+ <TextBlock x:Name="ChatGPTStatusText"
+ Text="Not signed in"
+ FontSize="13"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ <StackPanel Orientation="Horizontal" Spacing="8">
+ <Button x:Name="ChatGPTSignInBtn" Content="Sign in with OpenAI" />
+ <Button x:Name="ChatGPTSignOutBtn" Content="Sign out"
+ Visibility="Collapsed" />
+ </StackPanel>
+ </StackPanel>
+
<StackPanel Spacing="4">
<TextBlock Text="Model" FontSize="14" />
<StackPanel Orientation="Horizontal" Spacing="6">
diff --git a/windows/README.md b/windows/README.md
index 4235ef6..9eee7ab 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -66,29 +66,29 @@ windows/scripts/
**Git Bash / MSYS2**:
```bash
cd /e/dev/be/vura
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.9"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.10"
```
**PowerShell (5.1 / 7+)**:
```powershell
cd E:\dev\be\vura
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.9"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.10"
```
**CMD**:
```cmd
cd /d E:\dev\be\vura
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.9"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.10"
```
Script sẽ:
1. Cài/update `vpk` global tool (skip nếu đã có)
-2. Build `Gridex.exe` unpackaged, stamp version `0.1.9` vào About section
-3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.9`
+2. Build `Gridex.exe` unpackaged, stamp version `0.1.10` vào About section
+3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.10`
**Output**: `windows/Releases/`
- `Gridex-stable-Setup.exe` — installer user-facing
-- `Gridex-0.1.9-stable-full.nupkg` — package Velopack
+- `Gridex-0.1.10-stable-full.nupkg` — package Velopack
- `releases.stable.json`, `RELEASES-stable` — feed manifests
- `Gridex-stable-Portable.zip` — bản portable
@@ -140,7 +140,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\install-vp
powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1
# Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.9-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.10-test"
```
**PowerShell**:
@@ -149,7 +149,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpa
powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1
# Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.9-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.10-test"
```
**CMD**:
@@ -158,7 +158,7 @@ REM Dev build — About section hiện "0.0.0-dev"
powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1
REM Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.9-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.10-test"
```
Chạy trực tiếp exe để test nhanh mà không cần cài installer:
@@ -177,17 +177,17 @@ Chạy trực tiếp exe để test nhanh mà không cần cài installer:
**Git Bash / MSYS2**:
```bash
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.9-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.10-test"
```
**PowerShell**:
```powershell
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.9-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.10-test"
```
**CMD**:
```cmd
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.9-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.10-test"
```
**Lưu ý**: `-Version` truyền vào `pack-velopack.ps1` **phải khớp** với `-Version` truyền vào `build-unpackaged.ps1`, nếu không thì Velopack sẽ in một số, còn About section của app sẽ in số khác. Dùng `build-and-pack.ps1` ở trên để tránh trường hợp này.
@@ -196,10 +196,10 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velop
- `windows/Gridex/GridexVersion.h` — include unconditional file generated
- `windows/Gridex/GridexVersion.generated.h` — **auto-generated, gitignored**, do `build-unpackaged.ps1` ghi mỗi lần chạy
- - Có `-Version` → `#define GRIDEX_VERSION L"0.1.9"`
+ - Có `-Version` → `#define GRIDEX_VERSION L"0.1.10"`
- Không `-Version` → `#define GRIDEX_VERSION L"0.0.0-dev"`
- `windows/Gridex/SettingsPage.xaml.cpp` — đọc `GRIDEX_VERSION` và set vào `VersionText` text block
-- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.9` → `0.1.9`) và forward sang script
+- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.10` → `0.1.10`) và forward sang script
Build script chỉ rewrite `GridexVersion.generated.h` khi nội dung khác → không force recompile vô ích.
@@ -209,17 +209,17 @@ Mặc định Velopack dùng channel `stable`. Nếu muốn phát hành kênh ri
**Git Bash / MSYS2**:
```bash
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.9-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.10-beta.1" -Channel "beta"
```
**PowerShell**:
```powershell
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.9-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.10-beta.1" -Channel "beta"
```
**CMD**:
```cmd
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.9-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.10-beta.1" -Channel "beta"
```
Output sẽ là `Gridex-beta-Setup.exe` + `releases.beta.json` — auto-updater phân luồng theo channel.
@@ -253,7 +253,7 @@ Chưa cài đủ vcpkg deps. Xem section "Cài vcpkg deps" ở đầu file.
### Gridex.exe crash ngay khi khởi động với `MSVCP140.dll not found`
Máy thiếu VC++ 2015-2022 Redistributable. Script `build-unpackaged.ps1` tự copy CRT DLLs vào output folder → nếu vẫn lỗi thì check VS install path / logs script.
-### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.9`
+### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.10`
Dùng `build-and-pack.ps1` thay vì gọi `pack-velopack.ps1` trực tiếp. Trường hợp chạy `pack-velopack.ps1` với version khác version lúc build `Gridex.exe` → xóa `windows\Gridex\x64\Release\` rồi build lại đúng thứ tự.
### Lỗi `pwsh.exe exited with code 9009` trong vcpkg applocal step
@@ -288,8 +288,8 @@ del /q .\windows\Gridex\GridexVersion.generated.h
CI tự chạy khi push tag matching `v*.*.*`:
```bash
-git tag v0.1.9
-git push origin v0.1.9
+git tag v0.1.10
+git push origin v0.1.10
```
GitHub Actions workflow `windows-release.yml` sẽ tự build + pack + upload assets lên GitHub Release. Xem chi tiết ở `.github/workflows/windows-release.yml`.