Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions extensions/levelcode-ai/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,12 @@ async function runAgent(ctx) {
ctx.post({ type: 'agentError', message: 'You’ve hit the model’s context window (the conversation got too long). Start a New chat to reset it, switch to a larger-context model, or pin fewer files — then continue.', kind: 'context' });
reason = 'error';
}
else if (typeof ctx.isSessionExpired === 'function' && ctx.isSessionExpired(e)) {
// The gateway 401 that refreshAuth could not recover: the session is over. A sign-in card,
// not the adapter's raw message — the user needs a button, not a status code.
ctx.post({ type: 'agentError', message: ctx.sessionExpiredMessage || msg, code: 'session_expired' });
reason = 'error';
}
else { ctx.post({ type: 'agentError', message: msg, code }); reason = 'error'; }
} finally {
dbg('agent.done', { reason, steps: step - 1, edits: ctx.editCount || 0, costMicros: runCostMicros, creditsLeftMicros: ctx.credits != null ? ctx.credits : null });
Expand Down
17 changes: 15 additions & 2 deletions extensions/levelcode-ai/aiEdit.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

const vscode = require('vscode');
const path = require('path');
const { SESSION_EXPIRED_MESSAGE } = require('./providers/session');

const SCHEME = 'levelcode-ai';
const CTX_DIFF_ACTIVE = 'levelcode.ai.diffActive';
const SIGN_IN = 'Sign in'; // the button on an edit refused for an ended session, labelled as the chat card's is

/** @type {Map<string,string>} virtual-doc uri -> content */
const contents = new Map();
Expand Down Expand Up @@ -105,7 +107,7 @@ function fullLineRange(editor) {
return new vscode.Range(sel.start.line, 0, endLine, editor.document.lineAt(endLine).text.length);
}

/** @param {{aiConfig:()=>any, prepProviderRequest:(o?:any)=>Promise<any>, streamChat:Function}} deps */
/** @param {{aiConfig:()=>any, prepProviderRequest:(o?:any)=>Promise<any>, streamChat:Function, accountSignIn:()=>Promise<any>}} deps */
async function editSelection(deps) {
const ed = vscode.window.activeTextEditor;
if (!ed || ed.selection.isEmpty) {
Expand Down Expand Up @@ -136,6 +138,10 @@ async function editSelection(deps) {
const onDelta = (d) => { result += d; };
const req = await deps.prepProviderRequest({ prompt: true });
if (!req.ok) {
// An ended LevelCode Cloud session is not a missing key: "No API key set for LevelCode
// Cloud." sent the user looking for one they never needed. Say so, in the sentence chat
// and the agent send for it, and mark it so the catch below can offer the way back.
if (req.reason === 'signedOut') { throw Object.assign(new Error(SESSION_EXPIRED_MESSAGE), { code: 'session_expired' }); }
throw new Error(
req.reason === 'baseURL' ? 'Set a base URL for the custom OpenAI-compatible provider first (levelcode.ai.baseURL).'
: req.reason === 'insecureBaseURL' ? 'Refusing to send your API key over plain http to a non-local host. Use an https (or localhost) base URL.'
Expand All @@ -149,7 +155,14 @@ async function editSelection(deps) {
}
);
} catch (e) {
vscode.window.showErrorMessage('LevelCode AI edit failed: ' + String((e && e.message) || e));
const failed = 'LevelCode AI edit failed: ' + String((e && e.message) || e);
// The one failure with its fix a click away: the same browser sign-in the chat's card starts.
if (e && e.code === 'session_expired') {
const pick = await vscode.window.showErrorMessage(failed, SIGN_IN);
if (pick === SIGN_IN) { await deps.accountSignIn(); }
return;
}
vscode.window.showErrorMessage(failed);
return;
}

Expand Down
312 changes: 283 additions & 29 deletions extensions/levelcode-ai/extension.js

Large diffs are not rendered by default.

37 changes: 34 additions & 3 deletions extensions/levelcode-ai/media/chat.html
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,8 @@
.upgradecard .ucbtn.primary:hover { filter: brightness(1.1); }
.upgradecard .ucbtn.ghost { background: transparent; border: 1px solid var(--border); color: var(--vscode-foreground); }
.upgradecard .ucbtn.ghost:hover { background: var(--vscode-toolbar-hoverBackground, rgba(127,127,127,.14)); }
/* session expired — the upgrade card's shape, because it too ends in one button the user wants to press */
.sessioncard .uchead .ci { color: var(--accent); }
/* our-side outage notice — neutral, NO accent, NO CTA (it is not the user's account/usage) */
.noticecard { border: 1px solid var(--border); border-radius: 12px; margin: 8px 2px; padding: 13px 15px 14px; background: var(--field-bg); }
.noticecard .uchead { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; margin-bottom: 6px; }
Expand Down Expand Up @@ -2733,6 +2735,32 @@
log.appendChild(card); scrollIfStuck();
card.querySelectorAll('[data-act]').forEach((b) => { b.onclick = () => vscode.postMessage({ type: 'accountUpgrade' }); });
}
// The cloud session is over (the refresh token expired — 30 days without use, or a sign-out
// elsewhere). This is the ONE failure the user can fix in a click, so it gets a button, not red
// text: the raw "API 401: Signature has expired" this replaces told them nothing about what to do,
// while the account popover beside it still said they were signed in.
function isSessionExpired(m){ return !!(m && m.code === 'session_expired'); }
let sessionCard = null;
function addSignInCard(m){
clearStatus(); finishAgentBubble(); closeGroup();
if (sessionCard && sessionCard.isConnected){ sessionCard.remove(); } // one card, however many paths find the expiry
const who = m && m.name ? 'Welcome back, ' + esc(m.name) + '.' : '';
const card = document.createElement('div'); card.className = 'upgradecard sessioncard';
card.innerHTML =
'<div class="uchead">' + codicon('shield') + '<span>Your session has expired</span></div>'
+ '<div class="ucbody">' + (who ? who + ' ' : '') + 'Sign in again to keep using LevelCode Cloud — your chat and files here are untouched.</div>'
+ '<div class="ucbtns"><button class="ucbtn primary" data-act="signin">Sign in</button>'
+ '<button class="ucbtn ghost" data-act="byok">Use my own key instead</button></div>';
log.appendChild(card); scrollIfStuck();
card.querySelector('[data-act="signin"]').onclick = () => vscode.postMessage({ type: 'accountSignIn' });
// Choosing your own key answers the expiry — the host stops asking — so the card goes too,
// rather than sitting in the transcript offering a sign-in nobody is waiting on.
card.querySelector('[data-act="byok"]').onclick = () => {
vscode.postMessage({ type: 'byokSettings' });
card.remove(); if (sessionCard === card){ sessionCard = null; }
};
sessionCard = card;
}
// Our-side outage / transient issue → a neutral "service" notice, NOT the red error and NOT the
// upgrade card (the gateway already sanitized the message; this just picks a calmer presentation).
function isServiceIssue(m){
Expand Down Expand Up @@ -4121,7 +4149,8 @@
else if (m.type === 'assistantError'){
pending = ''; flushAll = false; doneSignaled = false;
const cap = capReachedInfo(m.message);
if (cap){ current = null; addUpgradeCard(cap); }
if (isSessionExpired(m)){ current = null; addSignInCard(m); }
else if (cap){ current = null; addUpgradeCard(cap); }
else if (isServiceIssue(m)){ current = null; addServiceCard(m); }
else {
const html = '<span class="err">' + esc(m.message) + '</span>';
Expand All @@ -4130,6 +4159,7 @@
}
setStreaming(false);
}
else if (m.type === 'sessionExpired'){ addSignInCard(m); }
else if (m.type === 'activeFile'){ activeFileLabel = m.label; renderChips(); }
else if (m.type === 'contextFiles'){ ctxFiles = m.files || []; renderChips(); }
else if (m.type === 'autoContext'){ addAutoCtx(m.names); }
Expand Down Expand Up @@ -4167,9 +4197,10 @@
else if (m.type === 'compactStart'){ ctxCompact = 'busy'; renderCtxCard(); }
else if (m.type === 'compactResult'){ onCompactResult(m); }
else if (m.type === 'debug'){ addDebug(m); }
else if (m.type === 'account'){ renderAccount(m); if (m.open) openAccount(); }
else if (m.type === 'account'){
if (m.signedIn && sessionCard && sessionCard.isConnected){ sessionCard.remove(); sessionCard = null; } renderAccount(m); if (m.open) openAccount(); }
else if (m.type === 'fileIndex'){ setFileIndex(m.files || []); }
else if (m.type === 'agentError'){ clearStatus(); finishAgentBubble(); closeGroup(); const cap = capReachedInfo(m.message); if (cap){ addUpgradeCard(cap); } else if (isServiceIssue(m)){ addServiceCard(m); } else { add('assistant', '<span class="err">' + esc(m.message) + '</span>'); } }
else if (m.type === 'agentError'){ clearStatus(); finishAgentBubble(); closeGroup(); const cap = capReachedInfo(m.message); if (isSessionExpired(m)){ addSignInCard(m); } else if (cap){ addUpgradeCard(cap); } else if (isServiceIssue(m)){ addServiceCard(m); } else { add('assistant', '<span class="err">' + esc(m.message) + '</span>'); } }
else if (m.type === 'agentDone'){ clearStatus(); finishAgentBubble(); addAgentDone(m.reason, m.edits, m.credits, m.maxSteps, m.costMicros); setStreaming(false); }
else if (m.type === 'context'){ selLabel = m.label; renderChips(); }
else if (m.type === 'clearContext'){ selLabel = null; renderChips(); }
Expand Down
90 changes: 90 additions & 0 deletions extensions/levelcode-ai/providers/session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*---------------------------------------------------------------------------------------------
* LevelCode — AI · LevelCode Cloud session state (pure)
*
* The editor keeps two credentials for the cloud: a short-lived access token (8 h) and a refresh
* token (30 days, rotated on use). Everything here is the arithmetic and classification around
* them — no VS Code, no IO — so it can be unit-tested (test/session.test.js) and so the host can
* answer "is this session still alive?" WITHOUT a network round-trip, by reading the access
* token's own `exp` claim. A JWT's payload is plain base64url JSON; reading it is not verifying it
* (the server does that), it is only asking the token when it says it dies.
*--------------------------------------------------------------------------------------------*/
// @ts-check
'use strict';

/** Refresh this far ahead of expiry, so a request issued right now cannot land after the deadline. */
const EXPIRY_MARGIN_MS = 5 * 60 * 1000;

/**
* How long the whole refresh exchange may take — connecting, the headers AND the body. The webview's
* `ready` waits on a refresh before it restores the chat, so this is how long a host that accepts the
* connection and then says nothing can hold that up. Running out of it is "this attempt failed",
* never "the session is over".
*/
const REFRESH_TIMEOUT_MS = 10 * 1000;

/** The sentence shown when the session is gone. Mirrors the server's own wording. */
const SESSION_EXPIRED_MESSAGE = 'Your LevelCode Cloud session has expired. Sign in again to continue.';

/**
* The `exp` claim of a JWT as epoch milliseconds, or null when the token is not a JWT, carries no
* `exp`, or is unreadable. Never throws: a malformed token is a reason to re-check with the server,
* not a reason to crash the editor.
* @param {string|null|undefined} token
* @returns {number|null}
*/
function jwtExpiresAt(token) {
try {
const parts = String(token || '').split('.');
if (parts.length !== 3) { return null; }
const b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
const payload = JSON.parse(Buffer.from(b64 + '='.repeat((4 - b64.length % 4) % 4), 'base64').toString('utf8'));
const exp = Number(payload && payload.exp);
return Number.isFinite(exp) && exp > 0 ? exp * 1000 : null;
} catch { return null; }
}

/**
* Whether an access token should be refreshed before use: it expires within the margin, has
* already expired, or cannot be read at all (an unreadable token is treated as expired — the
* server would reject it anyway, and asking first is cheaper than a failed request).
* @param {string|null|undefined} token
* @param {number} [nowMs]
*/
function accessNeedsRefresh(token, nowMs = Date.now()) {
const exp = jwtExpiresAt(token);
return exp === null || exp - nowMs <= EXPIRY_MARGIN_MS;
}

/**
* Classify the outcome of POST /auth/refresh so the caller knows whether the SESSION is over, or
* only this attempt failed.
*
* 'ok' — a new access token was issued
* 'expired' — the server rejected the refresh token itself (401): the session is over, sign in again
* 'retry' — anything else: offline, 5xx, a malformed reply. Keep the tokens; nothing is known yet.
*
* Only an explicit 401 ends the session. Clearing credentials on a network blip would log a user
* out for closing their laptop on the train.
* @param {{status?:number, body?:any}|null|undefined} res
* @returns {'ok'|'expired'|'retry'}
*/
function classifyRefresh(res) {
if (!res) { return 'retry'; }
if (res.status === 401) { return 'expired'; }
if (res.status >= 200 && res.status < 300 && res.body && (res.body.access || res.body.token)) { return 'ok'; }
return 'retry';
}

/**
* True when a provider error means the cloud session is dead — a gateway 401 that a refresh could
* not recover. The adapter formats failures as `<label> API <status>: <detail>`; the server's own
* codes (`token_expired`, `refresh_expired`) are matched too so a structured body is not needed.
* @param {any} e
*/
function isSessionExpiredError(e) {
const status = e && e.status;
const msg = String((e && e.message) || e || '');
return status === 401 || /\bAPI 401\b|token_expired|refresh_expired|signature has expired/i.test(msg);
}

module.exports = { EXPIRY_MARGIN_MS, REFRESH_TIMEOUT_MS, SESSION_EXPIRED_MESSAGE, jwtExpiresAt, accessNeedsRefresh, classifyRefresh, isSessionExpiredError };
37 changes: 25 additions & 12 deletions extensions/levelcode-ai/sketch.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const path = require("path");
const fs = require("fs");
const providers = require("./providers/index");
const catalog = require("./providers/catalog");
const { SESSION_EXPIRED_MESSAGE } = require("./providers/session");
const { AGENT_GROUPS, AGENTS, AGENT_BY_ID } = require("./sketch/agentCatalog");
const graph = require("./sketch/graph");
const pricing = require("./sketch/pricing");
Expand Down Expand Up @@ -458,6 +459,24 @@ async function loadWorkspacePatchContext() {
);
}

/**
* Why prepProviderRequest refused, as this panel says it. An ended LevelCode Cloud session is not a
* missing key, and not a provider that is "not ready": it gets the sentence chat and the agent send
* for it, so the user goes to sign in instead of hunting for a key they never needed. Any other
* reason keeps the caller's wording (`otherwise`).
* @param {{reason?:string, label?:string}} req
* @param {string} otherwise
*/
function notReadyMessage(req, otherwise) {
if (req.reason === "signedOut") {
return SESSION_EXPIRED_MESSAGE;
}
if (req.reason === "key") {
return "No API key set for " + req.label + ".";
}
return otherwise;
}

// ---- the runner -------------------------------------------------------------------------------
/** @param {{sketch:any, deps:any}} o deps = { prepProviderRequest } from extension.js */
async function runSketch(o) {
Expand Down Expand Up @@ -497,10 +516,10 @@ async function runSketch(o) {
clearSlot();
post({
type: "runError",
message:
req.reason === "key"
? "No API key set for " + req.label + "."
: "Provider not ready (" + (req.reason || "unknown") + ").",
message: notReadyMessage(
req,
"Provider not ready (" + (req.reason || "unknown") + ").",
),
});
return;
}
Expand Down Expand Up @@ -745,10 +764,7 @@ async function boardCommand(o) {
if (!req.ok) {
post({
type: "uiError",
message:
req.reason === "key"
? "No API key set for " + req.label + "."
: "Provider not ready.",
message: notReadyMessage(req, "Provider not ready."),
});
return;
}
Expand Down Expand Up @@ -923,10 +939,7 @@ async function generateFlow(o) {
if (!req.ok) {
post({
type: "uiError",
message:
req.reason === "key"
? "No API key set for " + req.label + "."
: "Provider not ready.",
message: notReadyMessage(req, "Provider not ready."),
});
return;
}
Expand Down
Loading
Loading