Skip to content

Fix/ai system prompt#724

Open
ZENFALLACY wants to merge 9 commits intoaccordproject:mainfrom
ZENFALLACY:fix/ai-system-prompt
Open

Fix/ai system prompt#724
ZENFALLACY wants to merge 9 commits intoaccordproject:mainfrom
ZENFALLACY:fix/ai-system-prompt

Conversation

@ZENFALLACY
Copy link

fix: resolve AI system prompt loss and showFullPrompt crash

Closes

Changes

  • llmProviders.ts: Fixed AnthropicProvider and GoogleProvider incorrectly extracting the system prompt using messages.slice(-2, -1)[0], which silently dropped all AI context after the first message in multi-turn conversations. Now uses messages.findLast(m => m.role === 'system') to reliably find the most recent system message regardless of conversation length.
  • AIChatPanel.tsx: Fixed a runtime crash (TypeError: Cannot read properties of undefined) when showFullPrompt is enabled. The previous code accessed chatState.messages[index-1] which returns undefined at index 0. Now uses slice(0, index).findLast() to safely locate the nearest preceding system message.
  • store.ts: Removed a redundant rebuild() call inside loadFromLink. The decompressed payload already contains a valid agreementHtml, so re-running the full template engine on every shared-link load was unnecessary and could interfere with the shared debounce used by user edits.
  • chatRelay.ts: Fixed a stale state read in stopMessage where updateChatState({ isLoading: false }) could be overwritten by a subsequent spread of a stale chatState snapshot. State is now read once and all changes applied atomically in a single setChatState call.
  • tsconfig.json: Bumped target and lib from ES2020 to ES2023 to enable Array.prototype.findLast.

Flags

  • The tsconfig target bump to ES2023 is a minor compatibility change; all browsers listed in browserslist (last 2 versions, no IE) support ES2023 array methods natively.
  • The loadFromLink change means shared links no longer re-run the template engine on load. If the stored agreementHtml in a link is ever stale, users would need to manually trigger a rebuild — this is an acceptable trade-off given the previous behaviour was always redundant.

Screenshots or Video

N/A — changes are logic fixes with no UI changes.

Related Issues

  • Issue #
  • Pull Request #

Author Checklist

  • Ensure you provide a DCO sign-off for your commits using the --signoff option of git commit.
  • Vital features and changes captured in unit and/or integration tests
  • Commits messages follow AP format
  • Extend the documentation, if necessary
  • Merging to main from fork:branchname

@ZENFALLACY ZENFALLACY requested a review from a team as a code owner February 20, 2026 19:56
@netlify
Copy link

netlify bot commented Feb 20, 2026

Deploy Preview for ap-template-playground ready!

Name Link
🔨 Latest commit c6341cc
🔍 Latest deploy log https://app.netlify.com/projects/ap-template-playground/deploys/699fd7c23c159100082a7cc6
😎 Deploy Preview https://deploy-preview-724--ap-template-playground.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Signed-off-by: ZENFALLACY <udashiv18@gmail.com>
Signed-off-by: ZENFALLACY <udashiv18@gmail.com>
Signed-off-by: ZENFALLACY <udashiv18@gmail.com>
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses several AI assistant chat reliability issues, primarily around preserving system prompts across multi-turn conversations and preventing UI/runtime errors during prompt inspection and message stopping.

Changes:

  • Fixes system-prompt extraction for Anthropic and Google providers to reliably use the most recent system message.
  • Prevents a showFullPrompt runtime crash in the chat panel by safely locating the preceding system message.
  • Avoids stale state overwrites when stopping an in-flight message, and removes an extra rebuild() during shared-link loads.

Reviewed changes

Copilot reviewed 4 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/ai-assistant/llmProviders.ts Uses the most recent system message instead of a fixed slice for provider system instructions.
src/components/AIChatPanel.tsx Fixes showFullPrompt crash by safely finding the preceding system message.
src/store/store.ts Removes rebuild() from loadFromLink and updates store formatting/structure in the diff hunk.
src/ai-assistant/chatRelay.ts Makes stopMessage() apply updates in a single atomic state write to avoid stale overwrites.
tsconfig.json Reformat-only changes; PR description claims an ES target/lib bump that isn’t reflected here.
tsc_out.txt Adds a build/output log file to the repo (should not be versioned).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +349 to 351
`**System message:** ${chatState.messages.slice(0, index).reverse().find(m => m.role === 'system')?.content ?? '(none)'}\n**User message:** ${message.content}`
) : message.content)
: message.content
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When showFullPrompt is enabled, this renders the nearest system message by doing slice(0, index).reverse().find(...) inside the message loop. That allocates and reverses arrays per user message, which can become noticeably expensive for long chats. Consider tracking the last seen system message while iterating (single pass) or precomputing a per-index lookup so rendering stays O(n).

Copilot uses AI. Check for mistakes.
Comment on lines +329 to +345
loadFromLink: async (compressedData: string) => {
try {
const { templateMarkdown, modelCto, data, agreementHtml } = decompress(compressedData);
if (!templateMarkdown || !modelCto || !data) {
throw new Error("Invalid share link data");
}
set(() => ({
templateMarkdown,
editorValue: templateMarkdown,
modelCto,
editorModelCto: modelCto,
data,
editorAgreementData: data,
agreementHtml,
error: undefined,
}));
} catch (error) {
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loadFromLink behavior changed (no longer triggers rebuild() and now relies on agreementHtml from the payload). There are existing tests around share-link generation/compression, but no coverage for loadFromLink (e.g., handling missing/old payload shapes, ensuring preview content is set as expected). Adding a small store-level test here would help prevent regressions for shared-link loads.

Copilot uses AI. Check for mistakes.
Comment on lines +331 to +344
const { templateMarkdown, modelCto, data, agreementHtml } = decompress(compressedData);
if (!templateMarkdown || !modelCto || !data) {
throw new Error("Invalid share link data");
}
set(() => ({
templateMarkdown,
editorValue: templateMarkdown,
modelCto,
editorModelCto: modelCto,
data,
editorAgreementData: data,
agreementHtml,
error: undefined,
}));
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loadFromLink now trusts agreementHtml from the decompressed payload, but decompress() does not enforce/default missing fields and existing compression tests only include {templateMarkdown, modelCto, data} (no agreementHtml). This means older shared links (or any payload without agreementHtml) will set agreementHtml to undefined and skip the rebuild, leaving the preview blank and potentially violating the store's agreementHtml: string contract. Consider defaulting agreementHtml when absent and/or falling back to rebuild() when the field is missing, and update the compression typings/tests accordingly.

Copilot uses AI. Check for mistakes.
…npmrc

Signed-off-by: ZENFALLACY <udashiv18@gmail.com>
Signed-off-by: ZENFALLACY <udashiv18@gmail.com>
…ly.github.com>

I, Matt Roberts <7544022+mttrbrts@users.noreply.github.com>, hereby add my Signed-off-by to this commit: 78ef327
I, Matt Roberts <7544022+mttrbrts@users.noreply.github.com>, hereby add my Signed-off-by to this commit: 85090ea

Signed-off-by: Matt Roberts <7544022+mttrbrts@users.noreply.github.com>
@ZENFALLACY
Copy link
Author

ZENFALLACY commented Feb 26, 2026

@mttrbrts Fixed the failing checks:
The required ones (Build playground (20.x) and E2E Tests) are running now and should pass soon. The earlier failure happened because package-lock.json was accidentally deleted, which broke npm caching that’s been restored and fixed.
The Header rules and Pages changed checks are just Netlify previews, so they’re informational and not blocking.
Also, two commits were missing Signed-off-by lines. I added a DCO remediation commit to fix that without rewriting history.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants