← Back to Pull requests

Kitty graphics #20872

Open
mbwilding opened this pull request with 3361 lines diff across 48 files
View on GitHub
mbwilding mbwilding commented on Oct 30, 2026 18:52 UTC
Author

Summary of the Pull Request

This adds support for the kitty graphics protocol to Windows Terminal and conhost. Tools that use the protocol, such as snacks.nvim's image viewer, can display images directly in Windows Terminal, including inline markdown images in Neovim.

<img width="1000" height="660" alt="terminal" src="https://github.com/user-attachments/assets/616b5454-f767-45e3-8250-143db3a69d97" />

<img width="1000" height="540" alt="neovim" src="https://github.com/user-attachments/assets/9890792f-fae6-4016-beb3-310e868b1a96" />

References and Relevant Issues

https://github.com/microsoft/terminal/issues/8389

Detailed Description of the Pull Request / Additional comments

What's supported

  • Transmission: inline (including chunked), from files, from temporary files, and through shared memory.

  • Formats: PNG, decoded with WIC, and raw RGB/RGBA, optionally zlib-compressed.

  • Placement:

  • - cropping, scaling to a cell box with letterboxing, sub-cell offsets, cursor movement control and z-index layering;
    - virtual placements with unicode placeholders, so images move with the text in applications like Neovim.
  • Management: all delete modes, the support query, feature queries, image numbers, and replies that respect the quiet setting.
  • What isn't supported

    Animation, relative placements and the palette-indexed formats (f=8 and f=16) reply with an error.

    New dependency

    zlib is added to vcpkg.json to decompress zlib-compressed transmissions (o=z).

    Change to existing code

    ResizeTraditional previously freed rows without destroying them, so image data leaked on resize. This affected sixel images too, so the fix changes existing behaviour.

    How it works

  • Parser: APC strings are dispatched to a handler. Conhost passes APC replies back through ConPTY.

  • Buffer: images are stored per buffer with least recently used eviction like kitty. Placements are attached to the rows they cover, so they scroll and reflow with the text and aren't erased by text output. Only images entirely inside the scroll margins move with them. Clearing the screen and a terminal reset remove images.

  • Memory limits: the store has a 320 MB quota, rejects images larger than the quota, and holds at most 4096 images.

  • Cursor sync:

  • - The cell footprint and cursor movement use the same virtual cell size as sixel, so ConPTY and the terminal agree on the cursor position.
    - After a placement, conhost marks its cursor position as uncertain, so it rechecks against the real terminal.
    - Conhost only reads the image size rather than decoding it, so images aren't decoded twice.
  • Rendering:

  • - AtlasEngine with Direct3D draws images in three layers by z-index: under cell backgrounds, under text, and above text.
    - AtlasEngine with Direct2D draws two layers. Images under coloured cell backgrounds are drawn under the text but over the background.
    - AtlasEngine downscales images larger than the GPU's maximum bitmap size.
    - GDI draws images under or over the text according to their z-index.
  • Security: file paths must be on local drives. Network and device paths are refused, and temporary files are only deleted from the temp directory.
  • Validation Steps Performed

  • Unit tests: parser, adapter and text buffer tests pass, with new tests for APC parsing, transmission, placement, deletion, chunking, virtual placements, scrolling in margins and reset.

  • Manual: tests were run against every renderer: Direct3D, Direct2D, AtlasEngine in conhost, and GDI. snacks.nvim was also tested with images and inline markdown.
  • PR Checklist


  • Closes https://github.com/microsoft/terminal/issues/8389

  • Tests added/passed

  • Documentation updated

  • Schema updated (if necessary)
  • Written with AI assistance.

    Diff: 3361 lines (+3349 / -12) across 48 files Reviewer: DHowett Review duration: 37457m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.72) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 3361 lines diff across 48 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    39 items
    azure-pipelines[bot] azure-pipelines[bot] commented on Oct 30, 2026 18:52 UTC
    Bot

    <!-- AzurePipelinesStatusComment -->
    <samp>
    Azure Pipelines:<br>
    There may be pipelines that require an authorized user to comment /azp run to run.<br>

    </samp>

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/buffer/out/GraphicsImage.cpp:1
    @@ -0,0 +1,286 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "GraphicsImage.hpp"
    +
    +static std::atomic<uint64_t> s_graphicsRevision{ 0 };
    +
    +// The combining characters used as placeholder row and column numbers, in the
    +// order of their values. These are the characters of combining class 230 in
    +// Unicode 6.0.0 without decomposition mappings, as defined by the protocol.
    +static constexpr char32_t s_placeholderDiacritics[]{
    +    0x0305, 0x030D, 0x030E, 0x0310, 0x0312, 0x033D, 0x033E, 0x033F, 0x0346, 0x034A, 0x034B, 0x034C,
    +    0x0350, 0x0351, 0x0352, 0x0357, 0x035B, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369,
    +    0x036A, 0x036B, 0x036C, 0x036D, 0x036E, 0x036F, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592,
    +    0x0593, 0x0594, 0x0595, 0x0597, 0x0598, 0x0599, 0x059C, 0x059D, 0x059E, 0x059F, 0x05A0, 0x05A1,
    +    0x05A8, 0x05A9, 0x05AB, 0x05AC, 0x05AF, 0x05C4, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615,
    +    0x0616, 0x0617, 0x0657, 0x0658, 0x0659, 0x065A, 0x065B, 0x065D, 0x065E, 0x06D6, 0x06D7, 0x06D8,
    +    0x06D9, 0x06DA, 0x06DB, 0x06DC, 0x06DF, 0x06E0, 0x06E1, 0x06E2, 0x06E4, 0x06E7, 0x06E8, 0x06EB,
    +    0x06EC, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736, 0x073A, 0x073D, 0x073F, 0x0740, 0x0741, 0x0743,
    +    0x0745, 0x0747, 0x0749, 0x074A, 0x07EB, 0x07EC, 0x07ED, 0x07EE, 0x07EF, 0x07F0, 0x07F1, 0x07F3,
    +    0x0816, 0x0817, 0x0818, 0x0819, 0x081B, 0x081C, 0x081D, 0x081E, 0x081F, 0x0820, 0x0821, 0x0822,
    +    0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082A, 0x082B, 0x082C, 0x082D, 0x0951, 0x0953, 0x0954,
    +    0x0F82, 0x0F83, 0x0F86, 0x0F87, 0x135D, 0x135E, 0x135F, 0x17DD, 0x193A, 0x1A17, 0x1A75, 0x1A76,
    +    0x1A77, 0x1A78, 0x1A79, 0x1A7A, 0x1A7B, 0x1A7C, 0x1B6B, 0x1B6D, 0x1B6E, 0x1B6F, 0x1B70, 0x1B71,
    +    0x1B72, 0x1B73, 0x1CD0, 0x1CD1, 0x1CD2, 0x1CDA, 0x1CDB, 0x1CE0, 0x1DC0, 0x1DC1, 0x1DC3, 0x1DC4,
    +    0x1DC5, 0x1DC6, 0x1DC7, 0x1DC8, 0x1DC9, 0x1DCB, 0x1DCC, 0x1DD1, 0x1DD2, 0x1DD3, 0x1DD4, 0x1DD5,
    +    0x1DD6, 0x1DD7, 0x1DD8, 0x1DD9, 0x1DDA, 0x1DDB, 0x1DDC, 0x1DDD, 0x1DDE, 0x1DDF, 0x1DE0, 0x1DE1,
    +    0x1DE2, 0x1DE3, 0x1DE4, 0x1DE5, 0x1DE6, 0x1DFE, 0x20D0, 0x20D1, 0x20D4, 0x20D5, 0x20D6, 0x20D7,
    +    0x20DB, 0x20DC, 0x20E1, 0x20E7, 0x20E9, 0x20F0, 0x2CEF, 0x2CF0, 0x2CF1, 0x2DE0, 0x2DE1, 0x2DE2,
    +    0x2DE3, 0x2DE4, 0x2DE5, 0x2DE6, 0x2DE7, 0x2DE8, 0x2DE9, 0x2DEA, 0x2DEB, 0x2DEC, 0x2DED, 0x2DEE,
    +    0x2DEF, 0x2DF0, 0x2DF1, 0x2DF2, 0x2DF3, 0x2DF4, 0x2DF5, 0x2DF6, 0x2DF7, 0x2DF8, 0x2DF9, 0x2DFA,
    +    0x2DFB, 0x2DFC, 0x2DFD, 0x2DFE, 0x2DFF, 0xA66F, 0xA67C, 0xA67D, 0xA6F0, 0xA6F1, 0xA8E0, 0xA8E1,
    +    0xA8E2, 0xA8E3, 0xA8E4, 0xA8E5, 0xA8E6, 0xA8E7, 0xA8E8, 0xA8E9, 0xA8EA, 0xA8EB, 0xA8EC, 0xA8ED,
    +    0xA8EE, 0xA8EF, 0xA8F0, 0xA8F1, 0xAAB0, 0xAAB2, 0xAAB3, 0xAAB7, 0xAAB8, 0xAABE, 0xAABF, 0xAAC1,
    +    0xFE20, 0xFE21, 0xFE22, 0xFE23, 0xFE24, 0xFE25, 0xFE26, 0x10A0F, 0x10A38, 0x1D185, 0x1D186, 0x1D187,
    +    0x1D188, 0x1D189, 0x1D1AA, 0x1D1AB, 0x1D1AC, 0x1D1AD, 0x1D242, 0x1D243, 0x1D244,
    +};
    +
    +int GraphicsPlaceholder::DiacriticValue(const char32_t ch) noexcept
    +{
    +    const auto it = std::lower_bound(std::begin(s_placeholderDiacritics), std::end(s_placeholderDiacritics), ch);
    +    return it != std::end(s_placeholderDiacritics) && *it == ch ? gsl::narrow_cast<int>(it - std::begin(s_placeholderDiacritics)) : -1;
    +}
    +
    +size_t GraphicsImage::ByteSize() const noexcept
    +{
    +    return pixels.size() * sizeof(uint32_t);
    +}
    +
    +uint64_t GraphicsImage::NextRevision() noexcept
    +{
    +    // Revisions are never 0, so that the renderer can use it as a sentinel.
    +    return s_graphicsRevision.fetch_add(1, std::memory_order_relaxed) + 1;
    +}
    +
    +GraphicsRect GraphicsGeometry::Destination(const til::size cellSize) const noexcept
    +{
    +    const auto scaleX = static_cast<float>(cellSize.width) / std::max(1, virtualCellSize.width);
    +    const auto scaleY = static_cast<float>(cellSize.height) / std::max(1, virtualCellSize.height);
    +    const auto srcWidth = static_cast<float>(std::max(1, source.width()));
    +    const auto srcHeight = static_cast<float>(std::max(1, source.height()));
    +    const auto left = offset.x * scaleX;
    +    const auto top = offset.y * scaleY;
    +
    +    if (columns > 0 && rows > 0)
    +    {
    +        // The image is letterboxed within the requested area to avoid distortion.
    

    check-spelling / Unrecognized Spelling

    [letterboxed](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/renderer/gdi/paint.cpp:1
    @@ -724,6 +755,126 @@
     }
     CATCH_RETURN();
     
    +// Routine Description:
    +// - Draws a strip of a graphics placement. Graphics below the text are drawn
    +//   when the text of the row is painted, the rest is drawn on top right away.
    +// Arguments:
    +// - info - The placement strip to draw.
    +// Return Value:
    +// - S_OK or suitable GDI HRESULT error.
    +[[nodiscard]] HRESULT GdiEngine::PaintGraphics(const GraphicsPaintInfo& info) noexcept
    +try
    +{
    +    if (info.z < 0)
    +    {
    +        if (info.targetRow != _underlayRow)
    +        {
    +            _underlays.clear();
    +            _underlayRow = info.targetRow;
    +        }
    +        _underlays.emplace_back(info);
    +        std::stable_sort(_underlays.begin(), _underlays.end(), [](const auto& a, const auto& b) {
    +            return a.z != b.z ? a.z < b.z : a.order < b.order;
    +        });
    +        return S_OK;
    +    }
    +
    +    LOG_IF_FAILED(_FlushBufferLines());
    +    LOG_IF_FAILED(ResetLineTransform());
    +    return _PaintGraphicsStrip(info, nullptr);
    +}
    +CATCH_RETURN();
    +
    +// Routine Description:
    +// - Draws a strip of a graphics placement, optionally clipped to a rectangle
    +//   in the coordinates of the current line transform.
    +// Arguments:
    +// - info - The placement strip to draw.
    +// - clip - The rectangle to clip to, or nullptr.
    +// Return Value:
    +// - S_OK or suitable GDI HRESULT error.
    +[[nodiscard]] HRESULT GdiEngine::_PaintGraphicsStrip(const GraphicsPaintInfo& info, const RECT* clip) noexcept
    +try
    +{
    +    const auto cellSize = _GetFontSize();
    +    GraphicsStrip strip;
    +    if (!info.image || !ComputeGraphicsStrip(info, cellSize, (_szMemorySurface.width + cellSize.width - 1) / std::max(1, cellSize.width), strip))
    +    {
    +        return S_OK;
    +    }
    +
    +    const auto& image = *info.image;
    +    if (image.pixels.size() < static_cast<size_t>(image.size.width) * image.size.height)
    +    {
    +        return S_OK;
    +    }
    +
    +    auto cached = std::find_if(_graphicsBitmaps.begin(), _graphicsBitmaps.end(), [&](const auto& entry) {
    +        return entry.revision == image.revision;
    +    });
    +    if (cached != _graphicsBitmaps.end())
    +    {
    +        std::rotate(cached, std::next(cached), _graphicsBitmaps.end());
    +    }
    +    else
    +    {
    +        const auto bitmapInfo = BITMAPINFO{
    +            .bmiHeader = {
    +                .biSize = sizeof(BITMAPINFOHEADER),
    +                .biWidth = image.size.width,
    +                .biHeight = -image.size.height,
    +                .biPlanes = 1,
    +                .biBitCount = 32,
    +                .biCompression = BI_RGB,
    +            }
    +        };
    +        wil::unique_hdc hdc{ CreateCompatibleDC(_hdcMemoryContext) };
    +        RETURN_HR_IF_NULL(E_FAIL, hdc.get());
    +        void* bits = nullptr;
    +        wil::unique_hbitmap bitmap{ CreateDIBSection(hdc.get(), &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0) };
    +        RETURN_HR_IF_NULL(E_FAIL, bitmap.get());
    +        memcpy(bits, image.pixels.data(), image.pixels.size() * sizeof(uint32_t));
    +        SelectObject(hdc.get(), bitmap.get());
    +
    +        if (_graphicsBitmaps.size() >= s_graphicsBitmapCacheSize)
    +        {
    +            _graphicsBitmaps.erase(_graphicsBitmaps.begin());
    +        }
    +        _graphicsBitmaps.emplace_back(GraphicsBitmap{ image.revision, std::move(bitmap), std::move(hdc) });
    +    }
    +    const auto graphicsDC = _graphicsBitmaps.back().dc.get();
    +
    +    // The strip is computed in device coordinates, so the line transform is
    +    // reset while drawing it, after converting the clip rectangle as well.
    +    const auto savedDC = SaveDC(_hdcMemoryContext);
    +    const auto restoreDC = wil::scope_exit([&]() noexcept {
    +        RestoreDC(_hdcMemoryContext, savedDC);
    +    });
    +    if (clip)
    +    {
    +        POINT points[2]{ { clip->left, clip->top }, { clip->right, clip->bottom } };
    +        LPtoDP(_hdcMemoryContext, &points[0], 2);
    

    check-spelling / Unrecognized Spelling

    [LPto](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/renderer/gdi/paint.cpp:1
    @@ -724,6 +755,126 @@
     }
     CATCH_RETURN();
     
    +// Routine Description:
    +// - Draws a strip of a graphics placement. Graphics below the text are drawn
    +//   when the text of the row is painted, the rest is drawn on top right away.
    +// Arguments:
    +// - info - The placement strip to draw.
    +// Return Value:
    +// - S_OK or suitable GDI HRESULT error.
    +[[nodiscard]] HRESULT GdiEngine::PaintGraphics(const GraphicsPaintInfo& info) noexcept
    +try
    +{
    +    if (info.z < 0)
    +    {
    +        if (info.targetRow != _underlayRow)
    +        {
    +            _underlays.clear();
    +            _underlayRow = info.targetRow;
    +        }
    +        _underlays.emplace_back(info);
    +        std::stable_sort(_underlays.begin(), _underlays.end(), [](const auto& a, const auto& b) {
    +            return a.z != b.z ? a.z < b.z : a.order < b.order;
    +        });
    +        return S_OK;
    +    }
    +
    +    LOG_IF_FAILED(_FlushBufferLines());
    +    LOG_IF_FAILED(ResetLineTransform());
    +    return _PaintGraphicsStrip(info, nullptr);
    +}
    +CATCH_RETURN();
    +
    +// Routine Description:
    +// - Draws a strip of a graphics placement, optionally clipped to a rectangle
    +//   in the coordinates of the current line transform.
    +// Arguments:
    +// - info - The placement strip to draw.
    +// - clip - The rectangle to clip to, or nullptr.
    +// Return Value:
    +// - S_OK or suitable GDI HRESULT error.
    +[[nodiscard]] HRESULT GdiEngine::_PaintGraphicsStrip(const GraphicsPaintInfo& info, const RECT* clip) noexcept
    +try
    +{
    +    const auto cellSize = _GetFontSize();
    +    GraphicsStrip strip;
    +    if (!info.image || !ComputeGraphicsStrip(info, cellSize, (_szMemorySurface.width + cellSize.width - 1) / std::max(1, cellSize.width), strip))
    +    {
    +        return S_OK;
    +    }
    +
    +    const auto& image = *info.image;
    +    if (image.pixels.size() < static_cast<size_t>(image.size.width) * image.size.height)
    +    {
    +        return S_OK;
    +    }
    +
    +    auto cached = std::find_if(_graphicsBitmaps.begin(), _graphicsBitmaps.end(), [&](const auto& entry) {
    +        return entry.revision == image.revision;
    +    });
    +    if (cached != _graphicsBitmaps.end())
    +    {
    +        std::rotate(cached, std::next(cached), _graphicsBitmaps.end());
    +    }
    +    else
    +    {
    +        const auto bitmapInfo = BITMAPINFO{
    +            .bmiHeader = {
    +                .biSize = sizeof(BITMAPINFOHEADER),
    +                .biWidth = image.size.width,
    +                .biHeight = -image.size.height,
    +                .biPlanes = 1,
    +                .biBitCount = 32,
    +                .biCompression = BI_RGB,
    +            }
    +        };
    +        wil::unique_hdc hdc{ CreateCompatibleDC(_hdcMemoryContext) };
    +        RETURN_HR_IF_NULL(E_FAIL, hdc.get());
    +        void* bits = nullptr;
    +        wil::unique_hbitmap bitmap{ CreateDIBSection(hdc.get(), &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0) };
    +        RETURN_HR_IF_NULL(E_FAIL, bitmap.get());
    +        memcpy(bits, image.pixels.data(), image.pixels.size() * sizeof(uint32_t));
    +        SelectObject(hdc.get(), bitmap.get());
    +
    +        if (_graphicsBitmaps.size() >= s_graphicsBitmapCacheSize)
    +        {
    +            _graphicsBitmaps.erase(_graphicsBitmaps.begin());
    +        }
    +        _graphicsBitmaps.emplace_back(GraphicsBitmap{ image.revision, std::move(bitmap), std::move(hdc) });
    +    }
    +    const auto graphicsDC = _graphicsBitmaps.back().dc.get();
    +
    +    // The strip is computed in device coordinates, so the line transform is
    +    // reset while drawing it, after converting the clip rectangle as well.
    +    const auto savedDC = SaveDC(_hdcMemoryContext);
    +    const auto restoreDC = wil::scope_exit([&]() noexcept {
    +        RestoreDC(_hdcMemoryContext, savedDC);
    +    });
    +    if (clip)
    +    {
    +        POINT points[2]{ { clip->left, clip->top }, { clip->right, clip->bottom } };
    +        LPtoDP(_hdcMemoryContext, &points[0], 2);
    +        ModifyWorldTransform(_hdcMemoryContext, nullptr, MWT_IDENTITY);
    +        IntersectClipRect(_hdcMemoryContext, points[0].x, points[0].y, points[1].x, points[1].y);
    +    }
    +
    +    const auto y = info.targetRow * cellSize.height;
    +    const BLENDFUNCTION blend{ AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
    

    check-spelling / Unrecognized Spelling

    [BLENDFUNCTION](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/ITermDispatch.hpp:1
    @@ -128,6 +128,7 @@
         virtual void DeviceAttributes() = 0; // DA1
         virtual void SecondaryDeviceAttributes() = 0; // DA2
         virtual void TertiaryDeviceAttributes() = 0; // DA3
    +    virtual void RequestTerminalVersion() = 0; // XTVERSION
    

    check-spelling / Unrecognized Spelling

    [XTVERSION](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };

    check-spelling / Unrecognized Spelling

    [mapview](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};

    check-spelling / Unrecognized Spelling

    [mbi](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)

    check-spelling / Unrecognized Spelling

    [mbi](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)

    check-spelling / Unrecognized Spelling

    [mbi](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)

    check-spelling / Unrecognized Spelling

    [mbi](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)
    +        {
    +            return false;
    +        }
    +        const uint64_t mappedSize = mbi.RegionSize;

    check-spelling / Unrecognized Spelling

    [mbi](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)
    +        {
    +            return false;
    +        }
    +        const uint64_t mappedSize = mbi.RegionSize;
    +        if (offset > mappedSize)
    +        {
    +            return false;
    +        }
    +        const auto available = mappedSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +        out.assign(view.get() + offset, view.get() + offset + toRead);
    +        return true;
    +    }
    +
    +    bool isDeletableTempFile(const std::wstring& finalPath)
    +    {
    +        if (lowerCase(finalPath).find(TempFileMarker) == std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        std::wstring tempPath(MAX_PATH + 1, L'\0');
    +        const auto len = GetTempPathW(gsl::narrow_cast<DWORD>(tempPath.size()), tempPath.data());
    +        if (len == 0 || len >= tempPath.size())
    +        {
    +            return false;
    +        }
    +        tempPath.resize(len);
    +        wil::unique_hfile directory{ CreateFileW(tempPath.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr) };
    +        if (!directory)
    +        {
    +            return false;
    +        }
    +        auto tempDirectory = stripFinalPathPrefix(finalPathOf(directory.get()));
    +        if (tempDirectory.empty())
    +        {
    +            return false;
    +        }
    +        if (!tempDirectory.ends_with(L'\\'))
    +        {
    +            tempDirectory.push_back(L'\\');
    +        }
    +        return lowerCase(finalPath).starts_with(lowerCase(tempDirectory));
    +    }
    +
    +    bool inflateData(const std::span<const uint8_t> input, const size_t expectedSize, std::vector<uint8_t>& output)
    +    {
    +        z_stream stream{};
    +        if (inflateInit(&stream) != Z_OK)
    +        {
    +            return false;
    +        }
    +        auto cleanup = wil::scope_exit([&]() noexcept { inflateEnd(&stream); });
    +
    +        output.resize(expectedSize ? expectedSize : std::max<size_t>(input.size() * 4, 4096));
    +        stream.next_in = const_cast<Bytef*>(input.data());

    check-spelling / Unrecognized Spelling

    [Bytef](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)
    +        {
    +            return false;
    +        }
    +        const uint64_t mappedSize = mbi.RegionSize;
    +        if (offset > mappedSize)
    +        {
    +            return false;
    +        }
    +        const auto available = mappedSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +        out.assign(view.get() + offset, view.get() + offset + toRead);
    +        return true;
    +    }
    +
    +    bool isDeletableTempFile(const std::wstring& finalPath)
    +    {
    +        if (lowerCase(finalPath).find(TempFileMarker) == std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        std::wstring tempPath(MAX_PATH + 1, L'\0');
    +        const auto len = GetTempPathW(gsl::narrow_cast<DWORD>(tempPath.size()), tempPath.data());
    +        if (len == 0 || len >= tempPath.size())
    +        {
    +            return false;
    +        }
    +        tempPath.resize(len);
    +        wil::unique_hfile directory{ CreateFileW(tempPath.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr) };
    +        if (!directory)
    +        {
    +            return false;
    +        }
    +        auto tempDirectory = stripFinalPathPrefix(finalPathOf(directory.get()));
    +        if (tempDirectory.empty())
    +        {
    +            return false;
    +        }
    +        if (!tempDirectory.ends_with(L'\\'))
    +        {
    +            tempDirectory.push_back(L'\\');
    +        }
    +        return lowerCase(finalPath).starts_with(lowerCase(tempDirectory));
    +    }
    +
    +    bool inflateData(const std::span<const uint8_t> input, const size_t expectedSize, std::vector<uint8_t>& output)
    +    {
    +        z_stream stream{};
    +        if (inflateInit(&stream) != Z_OK)
    +        {
    +            return false;
    +        }
    +        auto cleanup = wil::scope_exit([&]() noexcept { inflateEnd(&stream); });
    +
    +        output.resize(expectedSize ? expectedSize : std::max<size_t>(input.size() * 4, 4096));
    +        stream.next_in = const_cast<Bytef*>(input.data());
    +        stream.avail_in = gsl::narrow_cast<uInt>(input.size());
    +        size_t produced = 0;
    +        for (;;)
    +        {
    +            stream.next_out = output.data() + produced;
    +            stream.avail_out = gsl::narrow_cast<uInt>(std::min<size_t>(output.size() - produced, UINT_MAX));
    +            const auto before = stream.avail_out;
    +            const auto result = inflate(&stream, Z_NO_FLUSH);
    +            produced += before - stream.avail_out;
    +            if (result == Z_STREAM_END)
    +            {
    +                output.resize(produced);
    +                return true;
    +            }
    +            if (result != Z_OK && result != Z_BUF_ERROR)
    +            {
    +                return false;
    +            }
    +            if (stream.avail_out == 0)
    +            {
    +                if (output.size() >= MaxDataSize)
    +                {
    +                    return false;
    +                }
    +                output.resize(std::min(output.size() * 2, MaxDataSize));
    +            }
    +            else if (stream.avail_in == 0)
    +            {
    +                // The input was truncated.
    +                return false;
    +            }
    +        }
    +    }
    +
    +    bool decodePng(const std::span<const uint8_t> data, til::size& size, std::vector<uint32_t>& pixels)
    +    {
    +        // WIC requires COM. If the thread is already initialized in a different
    +        // apartment, that's fine too, since the factory is free threaded.
    +        const auto hrInit = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    +        auto uninitialize = wil::scope_exit([&]() noexcept {
    +            if (SUCCEEDED(hrInit))
    +            {
    +                CoUninitialize();
    +            }
    +        });
    +
    +        const auto factory = wil::CoCreateInstanceNoThrow<IWICImagingFactory>(CLSID_WICImagingFactory);
    +        if (!factory)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICStream> stream;
    +        if (FAILED(factory->CreateStream(stream.addressof())) ||
    +            FAILED(stream->InitializeFromMemory(const_cast<BYTE*>(data.data()), gsl::narrow_cast<DWORD>(data.size()))))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapDecoder> decoder;
    +        if (FAILED(factory->CreateDecoder(GUID_ContainerFormatPng, nullptr, decoder.addressof())) ||
    +            FAILED(decoder->Initialize(stream.get(), WICDecodeMetadataCacheOnDemand)))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapFrameDecode> frame;
    +        UINT width = 0;
    +        UINT height = 0;
    +        if (FAILED(decoder->GetFrame(0, frame.addressof())) || FAILED(frame->GetSize(&width, &height)))
    +        {
    +            return false;
    +        }
    +        if (width == 0 || height == 0 || width > MaxImageDimension || height > MaxImageDimension)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICFormatConverter> converter;
    +        if (FAILED(factory->CreateFormatConverter(converter.addressof())) ||
    +            FAILED(converter->Initialize(frame.get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom)))

    check-spelling / Unrecognized Spelling

    [PBGRA](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)
    +        {
    +            return false;
    +        }
    +        const uint64_t mappedSize = mbi.RegionSize;
    +        if (offset > mappedSize)
    +        {
    +            return false;
    +        }
    +        const auto available = mappedSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +        out.assign(view.get() + offset, view.get() + offset + toRead);
    +        return true;
    +    }
    +
    +    bool isDeletableTempFile(const std::wstring& finalPath)
    +    {
    +        if (lowerCase(finalPath).find(TempFileMarker) == std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        std::wstring tempPath(MAX_PATH + 1, L'\0');
    +        const auto len = GetTempPathW(gsl::narrow_cast<DWORD>(tempPath.size()), tempPath.data());
    +        if (len == 0 || len >= tempPath.size())
    +        {
    +            return false;
    +        }
    +        tempPath.resize(len);
    +        wil::unique_hfile directory{ CreateFileW(tempPath.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr) };
    +        if (!directory)
    +        {
    +            return false;
    +        }
    +        auto tempDirectory = stripFinalPathPrefix(finalPathOf(directory.get()));
    +        if (tempDirectory.empty())
    +        {
    +            return false;
    +        }
    +        if (!tempDirectory.ends_with(L'\\'))
    +        {
    +            tempDirectory.push_back(L'\\');
    +        }
    +        return lowerCase(finalPath).starts_with(lowerCase(tempDirectory));
    +    }
    +
    +    bool inflateData(const std::span<const uint8_t> input, const size_t expectedSize, std::vector<uint8_t>& output)
    +    {
    +        z_stream stream{};
    +        if (inflateInit(&stream) != Z_OK)
    +        {
    +            return false;
    +        }
    +        auto cleanup = wil::scope_exit([&]() noexcept { inflateEnd(&stream); });
    +
    +        output.resize(expectedSize ? expectedSize : std::max<size_t>(input.size() * 4, 4096));
    +        stream.next_in = const_cast<Bytef*>(input.data());
    +        stream.avail_in = gsl::narrow_cast<uInt>(input.size());
    +        size_t produced = 0;
    +        for (;;)
    +        {
    +            stream.next_out = output.data() + produced;
    +            stream.avail_out = gsl::narrow_cast<uInt>(std::min<size_t>(output.size() - produced, UINT_MAX));
    +            const auto before = stream.avail_out;
    +            const auto result = inflate(&stream, Z_NO_FLUSH);
    +            produced += before - stream.avail_out;
    +            if (result == Z_STREAM_END)
    +            {
    +                output.resize(produced);
    +                return true;
    +            }
    +            if (result != Z_OK && result != Z_BUF_ERROR)
    +            {
    +                return false;
    +            }
    +            if (stream.avail_out == 0)
    +            {
    +                if (output.size() >= MaxDataSize)
    +                {
    +                    return false;
    +                }
    +                output.resize(std::min(output.size() * 2, MaxDataSize));
    +            }
    +            else if (stream.avail_in == 0)
    +            {
    +                // The input was truncated.
    +                return false;
    +            }
    +        }
    +    }
    +
    +    bool decodePng(const std::span<const uint8_t> data, til::size& size, std::vector<uint32_t>& pixels)
    +    {
    +        // WIC requires COM. If the thread is already initialized in a different
    +        // apartment, that's fine too, since the factory is free threaded.
    +        const auto hrInit = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    +        auto uninitialize = wil::scope_exit([&]() noexcept {
    +            if (SUCCEEDED(hrInit))
    +            {
    +                CoUninitialize();
    +            }
    +        });
    +
    +        const auto factory = wil::CoCreateInstanceNoThrow<IWICImagingFactory>(CLSID_WICImagingFactory);
    +        if (!factory)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICStream> stream;
    +        if (FAILED(factory->CreateStream(stream.addressof())) ||
    +            FAILED(stream->InitializeFromMemory(const_cast<BYTE*>(data.data()), gsl::narrow_cast<DWORD>(data.size()))))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapDecoder> decoder;
    +        if (FAILED(factory->CreateDecoder(GUID_ContainerFormatPng, nullptr, decoder.addressof())) ||
    +            FAILED(decoder->Initialize(stream.get(), WICDecodeMetadataCacheOnDemand)))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapFrameDecode> frame;
    +        UINT width = 0;
    +        UINT height = 0;
    +        if (FAILED(decoder->GetFrame(0, frame.addressof())) || FAILED(frame->GetSize(&width, &height)))
    +        {
    +            return false;
    +        }
    +        if (width == 0 || height == 0 || width > MaxImageDimension || height > MaxImageDimension)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICFormatConverter> converter;
    +        if (FAILED(factory->CreateFormatConverter(converter.addressof())) ||
    +            FAILED(converter->Initialize(frame.get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom)))
    +        {
    +            return false;
    +        }
    +        pixels.resize(static_cast<size_t>(width) * height);
    +        if (FAILED(converter->CopyPixels(nullptr, width * 4, gsl::narrow_cast<UINT>(pixels.size() * 4), reinterpret_cast<BYTE*>(pixels.data()))))
    +        {
    +            return false;
    +        }
    +        size = { gsl::narrow_cast<til::CoordType>(width), gsl::narrow_cast<til::CoordType>(height) };
    +        return true;
    +    }
    +
    +    uint32_t premultiply(const uint32_t r, const uint32_t g, const uint32_t b, const uint32_t a) noexcept
    +    {
    +        const auto pr = (r * a + 127) / 255;
    +        const auto pg = (g * a + 127) / 255;
    +        const auto pb = (b * a + 127) / 255;
    +        return (a << 24) | (pr << 16) | (pg << 8) | pb;
    +    }
    +
    +    til::CoordType ceilDiv(const double value, const til::CoordType divisor) noexcept
    +    {
    +        return gsl::narrow_cast<til::CoordType>(std::ceil(value / std::max(1, divisor)));
    +    }
    +}
    +
    +bool KittyGraphics::Control::Has(const char key) const noexcept
    +{
    +    return present.test(static_cast<size_t>(key));
    +}
    +
    +int64_t KittyGraphics::Control::Get(const char key, const int64_t defaultValue) const noexcept
    +{
    +    return Has(key) ? til::at(values, static_cast<size_t>(key)) : defaultValue;
    +}
    +
    +uint32_t KittyGraphics::Control::GetUnsigned(const char key) const noexcept
    +{
    +    return gsl::narrow_cast<uint32_t>(std::clamp<int64_t>(Get(key), 0, UINT32_MAX));
    +}
    +
    +int32_t KittyGraphics::Control::GetSigned(const char key) const noexcept
    +{
    +    return gsl::narrow_cast<int32_t>(std::clamp<int64_t>(Get(key), INT32_MIN, INT32_MAX));
    +}
    +
    +wchar_t KittyGraphics::Control::GetChar(const char key, const wchar_t defaultValue) const noexcept
    +{
    +    return Has(key) && isChar.test(static_cast<size_t>(key)) ? gsl::narrow_cast<wchar_t>(Get(key)) : defaultValue;
    +}
    +
    +KittyGraphics::KittyGraphics(AdaptDispatch& dispatcher) noexcept :
    +    _dispatcher{ dispatcher }
    +{
    +}
    +
    +KittyGraphics::StringHandler KittyGraphics::Command()
    +{
    +    _state = ParseState::Key;
    +    _control = {};
    +    _key = 0;
    +    _value.clear();
    +    _base64Accumulator = 0;
    +    _base64Bits = 0;
    +    _payload.clear();
    +    _payloadTooLarge = false;
    +    return [this](const wchar_t ch) {
    +        try
    +        {
    +            return _parse(ch);
    +        }
    +        catch (...)
    +        {
    +            // An exception (for instance out of memory) aborts the command,
    +            // and the rest of the string is ignored.
    +            LOG_CAUGHT_EXCEPTION();
    +            _abortLoading();
    +            _payload = {};
    +            _state = ParseState::Invalid;
    +            return false;
    +        }
    +    };
    +}
    +
    +void KittyGraphics::Reset() noexcept
    +{
    +    _abortLoading();
    +}
    +
    +bool KittyGraphics::_parse(const wchar_t ch)
    +{
    +    if (ch == AsciiChars::ESC)
    +    {
    +        if (_state == ParseState::Value)
    +        {
    +            _commitValue();
    +        }
    +        if (_state != ParseState::Invalid)
    +        {
    +            _execute();
    +        }
    +        return false;
    +    }
    +
    +    switch (_state)
    +    {
    +    case ParseState::Key:
    +    case ParseState::Value:
    +        if (!_parseControl(ch))
    +        {
    +            _state = ParseState::Invalid;
    +        }
    +        return true;
    +    case ParseState::Payload:
    +        _decodeBase64(ch);
    +        return true;
    +    default:
    +        return true;
    +    }
    +}
    +
    +bool KittyGraphics::_parseControl(const wchar_t ch) noexcept
    +{
    +    if (_state == ParseState::Key)
    +    {
    +        if (ch == L';')
    +        {
    +            _state = ParseState::Payload;
    +            return true;
    +        }
    +        if (ch == L',')
    +        {
    +            return true;
    +        }
    +        if (_key == 0)
    +        {
    +            if (ch < 0x21 || ch >= 0x7f || ch == L'=')
    +            {
    +                return false;
    +            }
    +            _key = static_cast<char>(ch);
    +            return true;
    +        }
    +        if (ch == L'=')
    +        {
    +            _state = ParseState::Value;
    +            _value.clear();
    +            return true;
    +        }
    +        return false;
    +    }
    +
    +    if (ch == L',' || ch == L';')
    +    {
    +        if (!_commitValue())
    +        {
    +            return false;
    +        }
    +        _state = ch == L';' ? ParseState::Payload : ParseState::Key;
    +        return true;
    +    }
    +    if (_value.size() >= 16)
    +    {
    +        return false;
    +    }
    +    _value.push_back(ch);
    +    return true;
    +}
    +
    +bool KittyGraphics::_commitValue() noexcept
    +{
    +    const auto index = static_cast<size_t>(_key);
    +    _key = 0;
    +    _state = ParseState::Key;
    +    if (_value.empty())
    +    {
    +        return false;
    +    }
    +
    +    const auto first = _value.front();
    +    if (first == L'-' || (first >= L'0' && first <= L'9'))
    +    {
    +        int64_t number = 0;
    +        const auto negative = first == L'-';
    +        for (size_t i = negative ? 1 : 0; i < _value.size(); i++)
    +        {
    +            const auto digit = _value[i];
    +            if (digit < L'0' || digit > L'9')
    +            {
    +                return false;
    +            }
    +            number = std::min<int64_t>(number * 10 + (digit - L'0'), UINT32_MAX);
    +        }
    +        til::at(_control.values, index) = negative ? -number : number;
    +        _control.isChar.reset(index);
    +    }
    +    else if (_value.size() == 1)
    +    {
    +        til::at(_control.values, index) = first;
    +        _control.isChar.set(index);
    +    }
    +    else
    +    {
    +        return false;
    +    }
    +    _control.present.set(index);
    +    return true;
    +}
    +
    +void KittyGraphics::_decodeBase64(const wchar_t ch)
    +{
    +    const auto value = base64Value(ch);
    +    if (value < 0 || _payloadTooLarge)
    +    {
    +        return;
    +    }
    +    _base64Accumulator = (_base64Accumulator << 6) | gsl::narrow_cast<uint32_t>(value);
    +    _base64Bits += 6;
    +    if (_base64Bits >= 8)
    +    {
    +        _base64Bits -= 8;
    +        if (_payload.size() >= MaxDataSize)
    +        {
    +            _payloadTooLarge = true;
    +            return;
    +        }
    +        _payload.push_back(gsl::narrow_cast<uint8_t>(_base64Accumulator >> _base64Bits));
    +    }
    +}
    +
    +void KittyGraphics::_abortLoading() noexcept
    +{
    +    _loading = false;
    +    _loadingControl = {};
    +    _loadingData = {};
    +}
    +
    +void KittyGraphics::_execute()
    +{
    +    const auto& control = _control;
    +    auto data = std::move(_payload);
    +    _payload = {};
    +    const auto action = control.GetChar('a', 0);
    +
    +    if (control.GetUnsigned('i') && control.GetUnsigned('I'))
    +    {
    +        const Error error{ L"EINVAL", L"Must not specify both image id and image number" };
    +        _respond(control, control.GetUnsigned('i'), &error);
    +        return;
    +    }
    +
    +    const auto isTransmission = action == 0 || action == L't' || action == L'T' || action == L'q';
    +    const auto isContinuation = _loading && isTransmission && !control.GetUnsigned('i') && !control.GetUnsigned('I');
    +
    +    if (_payloadTooLarge)
    +    {
    +        const Error error{ L"EFBIG", L"Image data is too large" };
    +        const auto& origin = isContinuation ? _loadingControl : control;
    +        _respond(origin, origin.GetUnsigned('i'), &error);
    +        _abortLoading();
    +        return;
    +    }
    +
    +    if (isContinuation)
    +    {
    +        if (_loadingData.size() + data.size() > MaxDataSize)
    +        {
    +            const Error error{ L"EFBIG", L"Image data is too large" };
    +            _respond(_loadingControl, _loadingControl.GetUnsigned('i'), &error);
    +            _abortLoading();
    +            return;
    +        }
    +        _loadingData.insert(_loadingData.end(), data.begin(), data.end());
    +        if (control.Has('q'))
    +        {
    +            til::at(_loadingControl.values, 'q') = control.Get('q');
    +            _loadingControl.present.set('q');
    +        }
    +        if (control.Get('m') == 1)
    +        {
    +            return;
    +        }
    +        auto loadingControl = std::move(_loadingControl);
    +        auto loadingData = std::move(_loadingData);
    +        _abortLoading();
    +        _transmit(loadingControl, std::move(loadingData));
    +        return;
    +    }
    +
    +    // Any other command aborts a chunked transmission that is in progress.
    +    _abortLoading();
    +
    +    switch (action)
    +    {
    +    case 0:
    +    case L't':
    +    case L'T':
    +    case L'q':
    +        if (action == L'q' && control.Has('e'))
    +        {
    +            _featureQuery(control);
    +        }
    +        else if (control.Get('m') == 1)
    +        {
    +            _loading = true;
    +            _loadingControl = control;
    +            _loadingData = std::move(data);
    +        }
    +        else
    +        {
    +            _transmit(control, std::move(data));
    +        }
    +        break;
    +    case L'p':
    +        _put(control);
    +        break;
    +    case L'd':
    +        _delete(control);
    +        break;
    +    default:
    +    {
    +        const Error error{ L"EINVAL", L"Unsupported graphics command action" };
    +        _respond(control, control.GetUnsigned('i'), &error);
    +        break;
    +    }
    +    }
    +}
    +
    +void KittyGraphics::_transmit(const Control& control, std::vector<uint8_t> data)
    +{
    +    const auto action = control.GetChar('a', L't');
    +    const auto isQuery = action == L'q';
    +    const auto requestedId = control.GetUnsigned('i');
    +    const auto number = control.GetUnsigned('I');
    +
    +    if (isQuery && !requestedId)
    +    {
    +        return;
    +    }
    +
    +    Error error{};
    +    auto image = _load(control, std::move(data), error);
    +    if (!image)
    +    {
    +        _respond(control, requestedId, &error);
    +        return;
    +    }
    +    if (isQuery)
    +    {
    +        _respond(control, requestedId, nullptr);
    +        return;
    +    }
    +
    +    auto& store = _store();
    +    image->id = number ? store.NextFreeId() : requestedId;
    +    image->number = number;
    +
    +    auto& buffer = _dispatcher._pages.ActivePage().Buffer();
    +    if (image->id)
    +    {
    +        // Re-transmitting an image deletes the existing image and all its placements.
    +        const auto id = image->id;
    +        _erase(buffer, [=](const GraphicsRowRef& ref) { return ref.placement->image->id == id; }, false);
    +        if (store.FindVirtualPlacement(id, 0))
    +        {
    +            buffer.TriggerRedrawAll();
    +        }
    +    }
    +
    +    // Images without an id are stored as well, so that they count towards the
    +    // quota. Images evicted by the quota are removed from the screen too.
    +    const auto evicted = store.Add(image);
    +    if (!evicted.empty())
    +    {
    +        _erase(buffer, [&](const GraphicsRowRef& ref) {
    +            return std::ranges::any_of(evicted, [&](const auto& e) { return e == ref.placement->image; });
    +        },
    +               false);
    +        buffer.TriggerRedrawAll();
    +    }
    +
    +    if (action == L'T')
    +    {
    +        if (control.GetUnsigned('U') == 1)
    +        {
    +            _placeVirtual(control, image);
    +        }
    +        else if (!_place(control, image, error))
    +        {
    +            _respond(control, image->id, &error);
    +            return;
    +        }
    +    }
    +    _respond(control, image->id, nullptr);
    +}
    +
    +void KittyGraphics::_put(const Control& control)
    +{
    +    const auto image = _findImage(control);
    +    if (!image)
    +    {
    +        const Error error{ L"ENOENT", L"Put command refers to a non-existent image" };

    check-spelling / Forbidden Pattern

    [non-existent](#security-tab) matches a line_forbidden.patterns rule: Should be 'nonexistent' - '\\\b\[Nn\]o\[nt\]\[- \]existent\\\b'

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1353 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION mbi{};
    +        if (!VirtualQuery(view.get(), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT)
    +        {
    +            return false;
    +        }
    +        const uint64_t mappedSize = mbi.RegionSize;
    +        if (offset > mappedSize)
    +        {
    +            return false;
    +        }
    +        const auto available = mappedSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +        out.assign(view.get() + offset, view.get() + offset + toRead);
    +        return true;
    +    }
    +
    +    bool isDeletableTempFile(const std::wstring& finalPath)
    +    {
    +        if (lowerCase(finalPath).find(TempFileMarker) == std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        std::wstring tempPath(MAX_PATH + 1, L'\0');
    +        const auto len = GetTempPathW(gsl::narrow_cast<DWORD>(tempPath.size()), tempPath.data());
    +        if (len == 0 || len >= tempPath.size())
    +        {
    +            return false;
    +        }
    +        tempPath.resize(len);
    +        wil::unique_hfile directory{ CreateFileW(tempPath.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr) };
    +        if (!directory)
    +        {
    +            return false;
    +        }
    +        auto tempDirectory = stripFinalPathPrefix(finalPathOf(directory.get()));
    +        if (tempDirectory.empty())
    +        {
    +            return false;
    +        }
    +        if (!tempDirectory.ends_with(L'\\'))
    +        {
    +            tempDirectory.push_back(L'\\');
    +        }
    +        return lowerCase(finalPath).starts_with(lowerCase(tempDirectory));
    +    }
    +
    +    bool inflateData(const std::span<const uint8_t> input, const size_t expectedSize, std::vector<uint8_t>& output)
    +    {
    +        z_stream stream{};
    +        if (inflateInit(&stream) != Z_OK)
    +        {
    +            return false;
    +        }
    +        auto cleanup = wil::scope_exit([&]() noexcept { inflateEnd(&stream); });
    +
    +        output.resize(expectedSize ? expectedSize : std::max<size_t>(input.size() * 4, 4096));
    +        stream.next_in = const_cast<Bytef*>(input.data());
    +        stream.avail_in = gsl::narrow_cast<uInt>(input.size());
    +        size_t produced = 0;
    +        for (;;)
    +        {
    +            stream.next_out = output.data() + produced;
    +            stream.avail_out = gsl::narrow_cast<uInt>(std::min<size_t>(output.size() - produced, UINT_MAX));
    +            const auto before = stream.avail_out;
    +            const auto result = inflate(&stream, Z_NO_FLUSH);
    +            produced += before - stream.avail_out;
    +            if (result == Z_STREAM_END)
    +            {
    +                output.resize(produced);
    +                return true;
    +            }
    +            if (result != Z_OK && result != Z_BUF_ERROR)
    +            {
    +                return false;
    +            }
    +            if (stream.avail_out == 0)
    +            {
    +                if (output.size() >= MaxDataSize)
    +                {
    +                    return false;
    +                }
    +                output.resize(std::min(output.size() * 2, MaxDataSize));
    +            }
    +            else if (stream.avail_in == 0)
    +            {
    +                // The input was truncated.
    +                return false;
    +            }
    +        }
    +    }
    +
    +    bool decodePng(const std::span<const uint8_t> data, til::size& size, std::vector<uint32_t>& pixels)
    +    {
    +        // WIC requires COM. If the thread is already initialized in a different
    +        // apartment, that's fine too, since the factory is free threaded.
    +        const auto hrInit = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    +        auto uninitialize = wil::scope_exit([&]() noexcept {
    +            if (SUCCEEDED(hrInit))
    +            {
    +                CoUninitialize();
    +            }
    +        });
    +
    +        const auto factory = wil::CoCreateInstanceNoThrow<IWICImagingFactory>(CLSID_WICImagingFactory);
    +        if (!factory)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICStream> stream;
    +        if (FAILED(factory->CreateStream(stream.addressof())) ||
    +            FAILED(stream->InitializeFromMemory(const_cast<BYTE*>(data.data()), gsl::narrow_cast<DWORD>(data.size()))))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapDecoder> decoder;
    +        if (FAILED(factory->CreateDecoder(GUID_ContainerFormatPng, nullptr, decoder.addressof())) ||
    +            FAILED(decoder->Initialize(stream.get(), WICDecodeMetadataCacheOnDemand)))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapFrameDecode> frame;
    +        UINT width = 0;
    +        UINT height = 0;
    +        if (FAILED(decoder->GetFrame(0, frame.addressof())) || FAILED(frame->GetSize(&width, &height)))
    +        {
    +            return false;
    +        }
    +        if (width == 0 || height == 0 || width > MaxImageDimension || height > MaxImageDimension)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICFormatConverter> converter;
    +        if (FAILED(factory->CreateFormatConverter(converter.addressof())) ||
    +            FAILED(converter->Initialize(frame.get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom)))
    +        {
    +            return false;
    +        }
    +        pixels.resize(static_cast<size_t>(width) * height);
    +        if (FAILED(converter->CopyPixels(nullptr, width * 4, gsl::narrow_cast<UINT>(pixels.size() * 4), reinterpret_cast<BYTE*>(pixels.data()))))
    +        {
    +            return false;
    +        }
    +        size = { gsl::narrow_cast<til::CoordType>(width), gsl::narrow_cast<til::CoordType>(height) };
    +        return true;
    +    }
    +
    +    uint32_t premultiply(const uint32_t r, const uint32_t g, const uint32_t b, const uint32_t a) noexcept
    +    {
    +        const auto pr = (r * a + 127) / 255;
    +        const auto pg = (g * a + 127) / 255;
    +        const auto pb = (b * a + 127) / 255;
    +        return (a << 24) | (pr << 16) | (pg << 8) | pb;
    +    }
    +
    +    til::CoordType ceilDiv(const double value, const til::CoordType divisor) noexcept
    +    {
    +        return gsl::narrow_cast<til::CoordType>(std::ceil(value / std::max(1, divisor)));
    +    }
    +}
    +
    +bool KittyGraphics::Control::Has(const char key) const noexcept
    +{
    +    return present.test(static_cast<size_t>(key));
    +}
    +
    +int64_t KittyGraphics::Control::Get(const char key, const int64_t defaultValue) const noexcept
    +{
    +    return Has(key) ? til::at(values, static_cast<size_t>(key)) : defaultValue;
    +}
    +
    +uint32_t KittyGraphics::Control::GetUnsigned(const char key) const noexcept
    +{
    +    return gsl::narrow_cast<uint32_t>(std::clamp<int64_t>(Get(key), 0, UINT32_MAX));
    +}
    +
    +int32_t KittyGraphics::Control::GetSigned(const char key) const noexcept
    +{
    +    return gsl::narrow_cast<int32_t>(std::clamp<int64_t>(Get(key), INT32_MIN, INT32_MAX));
    +}
    +
    +wchar_t KittyGraphics::Control::GetChar(const char key, const wchar_t defaultValue) const noexcept
    +{
    +    return Has(key) && isChar.test(static_cast<size_t>(key)) ? gsl::narrow_cast<wchar_t>(Get(key)) : defaultValue;
    +}
    +
    +KittyGraphics::KittyGraphics(AdaptDispatch& dispatcher) noexcept :
    +    _dispatcher{ dispatcher }
    +{
    +}
    +
    +KittyGraphics::StringHandler KittyGraphics::Command()
    +{
    +    _state = ParseState::Key;
    +    _control = {};
    +    _key = 0;
    +    _value.clear();
    +    _base64Accumulator = 0;
    +    _base64Bits = 0;
    +    _payload.clear();
    +    _payloadTooLarge = false;
    +    return [this](const wchar_t ch) {
    +        try
    +        {
    +            return _parse(ch);
    +        }
    +        catch (...)
    +        {
    +            // An exception (for instance out of memory) aborts the command,
    +            // and the rest of the string is ignored.
    +            LOG_CAUGHT_EXCEPTION();
    +            _abortLoading();
    +            _payload = {};
    +            _state = ParseState::Invalid;
    +            return false;
    +        }
    +    };
    +}
    +
    +void KittyGraphics::Reset() noexcept
    +{
    +    _abortLoading();
    +}
    +
    +bool KittyGraphics::_parse(const wchar_t ch)
    +{
    +    if (ch == AsciiChars::ESC)
    +    {
    +        if (_state == ParseState::Value)
    +        {
    +            _commitValue();
    +        }
    +        if (_state != ParseState::Invalid)
    +        {
    +            _execute();
    +        }
    +        return false;
    +    }
    +
    +    switch (_state)
    +    {
    +    case ParseState::Key:
    +    case ParseState::Value:
    +        if (!_parseControl(ch))
    +        {
    +            _state = ParseState::Invalid;
    +        }
    +        return true;
    +    case ParseState::Payload:
    +        _decodeBase64(ch);
    +        return true;
    +    default:
    +        return true;
    +    }
    +}
    +
    +bool KittyGraphics::_parseControl(const wchar_t ch) noexcept
    +{
    +    if (_state == ParseState::Key)
    +    {
    +        if (ch == L';')
    +        {
    +            _state = ParseState::Payload;
    +            return true;
    +        }
    +        if (ch == L',')
    +        {
    +            return true;
    +        }
    +        if (_key == 0)
    +        {
    +            if (ch < 0x21 || ch >= 0x7f || ch == L'=')
    +            {
    +                return false;
    +            }
    +            _key = static_cast<char>(ch);
    +            return true;
    +        }
    +        if (ch == L'=')
    +        {
    +            _state = ParseState::Value;
    +            _value.clear();
    +            return true;
    +        }
    +        return false;
    +    }
    +
    +    if (ch == L',' || ch == L';')
    +    {
    +        if (!_commitValue())
    +        {
    +            return false;
    +        }
    +        _state = ch == L';' ? ParseState::Payload : ParseState::Key;
    +        return true;
    +    }
    +    if (_value.size() >= 16)
    +    {
    +        return false;
    +    }
    +    _value.push_back(ch);
    +    return true;
    +}
    +
    +bool KittyGraphics::_commitValue() noexcept
    +{
    +    const auto index = static_cast<size_t>(_key);
    +    _key = 0;
    +    _state = ParseState::Key;
    +    if (_value.empty())
    +    {
    +        return false;
    +    }
    +
    +    const auto first = _value.front();
    +    if (first == L'-' || (first >= L'0' && first <= L'9'))
    +    {
    +        int64_t number = 0;
    +        const auto negative = first == L'-';
    +        for (size_t i = negative ? 1 : 0; i < _value.size(); i++)
    +        {
    +            const auto digit = _value[i];
    +            if (digit < L'0' || digit > L'9')
    +            {
    +                return false;
    +            }
    +            number = std::min<int64_t>(number * 10 + (digit - L'0'), UINT32_MAX);
    +        }
    +        til::at(_control.values, index) = negative ? -number : number;
    +        _control.isChar.reset(index);
    +    }
    +    else if (_value.size() == 1)
    +    {
    +        til::at(_control.values, index) = first;
    +        _control.isChar.set(index);
    +    }
    +    else
    +    {
    +        return false;
    +    }
    +    _control.present.set(index);
    +    return true;
    +}
    +
    +void KittyGraphics::_decodeBase64(const wchar_t ch)
    +{
    +    const auto value = base64Value(ch);
    +    if (value < 0 || _payloadTooLarge)
    +    {
    +        return;
    +    }
    +    _base64Accumulator = (_base64Accumulator << 6) | gsl::narrow_cast<uint32_t>(value);
    +    _base64Bits += 6;
    +    if (_base64Bits >= 8)
    +    {
    +        _base64Bits -= 8;
    +        if (_payload.size() >= MaxDataSize)
    +        {
    +            _payloadTooLarge = true;
    +            return;
    +        }
    +        _payload.push_back(gsl::narrow_cast<uint8_t>(_base64Accumulator >> _base64Bits));
    +    }
    +}
    +
    +void KittyGraphics::_abortLoading() noexcept
    +{
    +    _loading = false;
    +    _loadingControl = {};
    +    _loadingData = {};
    +}
    +
    +void KittyGraphics::_execute()
    +{
    +    const auto& control = _control;
    +    auto data = std::move(_payload);
    +    _payload = {};
    +    const auto action = control.GetChar('a', 0);
    +
    +    if (control.GetUnsigned('i') && control.GetUnsigned('I'))
    +    {
    +        const Error error{ L"EINVAL", L"Must not specify both image id and image number" };
    +        _respond(control, control.GetUnsigned('i'), &error);
    +        return;
    +    }
    +
    +    const auto isTransmission = action == 0 || action == L't' || action == L'T' || action == L'q';
    +    const auto isContinuation = _loading && isTransmission && !control.GetUnsigned('i') && !control.GetUnsigned('I');
    +
    +    if (_payloadTooLarge)
    +    {
    +        const Error error{ L"EFBIG", L"Image data is too large" };
    +        const auto& origin = isContinuation ? _loadingControl : control;
    +        _respond(origin, origin.GetUnsigned('i'), &error);
    +        _abortLoading();
    +        return;
    +    }
    +
    +    if (isContinuation)
    +    {
    +        if (_loadingData.size() + data.size() > MaxDataSize)
    +        {
    +            const Error error{ L"EFBIG", L"Image data is too large" };
    +            _respond(_loadingControl, _loadingControl.GetUnsigned('i'), &error);
    +            _abortLoading();
    +            return;
    +        }
    +        _loadingData.insert(_loadingData.end(), data.begin(), data.end());
    +        if (control.Has('q'))
    +        {
    +            til::at(_loadingControl.values, 'q') = control.Get('q');
    +            _loadingControl.present.set('q');
    +        }
    +        if (control.Get('m') == 1)
    +        {
    +            return;
    +        }
    +        auto loadingControl = std::move(_loadingControl);
    +        auto loadingData = std::move(_loadingData);
    +        _abortLoading();
    +        _transmit(loadingControl, std::move(loadingData));
    +        return;
    +    }
    +
    +    // Any other command aborts a chunked transmission that is in progress.
    +    _abortLoading();
    +
    +    switch (action)
    +    {
    +    case 0:
    +    case L't':
    +    case L'T':
    +    case L'q':
    +        if (action == L'q' && control.Has('e'))
    +        {
    +            _featureQuery(control);
    +        }
    +        else if (control.Get('m') == 1)
    +        {
    +            _loading = true;
    +            _loadingControl = control;
    +            _loadingData = std::move(data);
    +        }
    +        else
    +        {
    +            _transmit(control, std::move(data));
    +        }
    +        break;
    +    case L'p':
    +        _put(control);
    +        break;
    +    case L'd':
    +        _delete(control);
    +        break;
    +    default:
    +    {
    +        const Error error{ L"EINVAL", L"Unsupported graphics command action" };
    +        _respond(control, control.GetUnsigned('i'), &error);
    +        break;
    +    }
    +    }
    +}
    +
    +void KittyGraphics::_transmit(const Control& control, std::vector<uint8_t> data)
    +{
    +    const auto action = control.GetChar('a', L't');
    +    const auto isQuery = action == L'q';
    +    const auto requestedId = control.GetUnsigned('i');
    +    const auto number = control.GetUnsigned('I');
    +
    +    if (isQuery && !requestedId)
    +    {
    +        return;
    +    }
    +
    +    Error error{};
    +    auto image = _load(control, std::move(data), error);
    +    if (!image)
    +    {
    +        _respond(control, requestedId, &error);
    +        return;
    +    }
    +    if (isQuery)
    +    {
    +        _respond(control, requestedId, nullptr);
    +        return;
    +    }
    +
    +    auto& store = _store();
    +    image->id = number ? store.NextFreeId() : requestedId;
    +    image->number = number;
    +
    +    auto& buffer = _dispatcher._pages.ActivePage().Buffer();
    +    if (image->id)
    +    {
    +        // Re-transmitting an image deletes the existing image and all its placements.
    +        const auto id = image->id;
    +        _erase(buffer, [=](const GraphicsRowRef& ref) { return ref.placement->image->id == id; }, false);
    +        if (store.FindVirtualPlacement(id, 0))
    +        {
    +            buffer.TriggerRedrawAll();
    +        }
    +    }
    +
    +    // Images without an id are stored as well, so that they count towards the
    +    // quota. Images evicted by the quota are removed from the screen too.
    +    const auto evicted = store.Add(image);
    +    if (!evicted.empty())
    +    {
    +        _erase(buffer, [&](const GraphicsRowRef& ref) {
    +            return std::ranges::any_of(evicted, [&](const auto& e) { return e == ref.placement->image; });
    +        },
    +               false);
    +        buffer.TriggerRedrawAll();
    +    }
    +
    +    if (action == L'T')
    +    {
    +        if (control.GetUnsigned('U') == 1)
    +        {
    +            _placeVirtual(control, image);
    +        }
    +        else if (!_place(control, image, error))
    +        {
    +            _respond(control, image->id, &error);
    +            return;
    +        }
    +    }
    +    _respond(control, image->id, nullptr);
    +}
    +
    +void KittyGraphics::_put(const Control& control)
    +{
    +    const auto image = _findImage(control);
    +    if (!image)
    +    {
    +        const Error error{ L"ENOENT", L"Put command refers to a non-existent image" };
    +        _respond(control, control.GetUnsigned('i'), &error);
    +        return;
    +    }
    +    _store().Touch(image.get());
    +    if (control.GetUnsigned('U') == 1)
    +    {
    +        _placeVirtual(control, image);
    +    }
    +    else
    +    {
    +        Error error{};
    +        if (!_place(control, image, error))
    +        {
    +            _respond(control, image->id, &error);
    +            return;
    +        }
    +    }
    +    _respond(control, image->id, nullptr);
    +}
    +
    +void KittyGraphics::_delete(const Control& control)
    +{
    +    const auto target = control.GetChar('d', L'a');
    +    const auto freeImages = target >= L'A' && target <= L'Z';
    +    auto page = _dispatcher._pages.ActivePage();
    +    auto& buffer = page.Buffer();
    +    auto& store = _store();
    +
    +    // Placements identified by their image, which are deleted wherever they are.
    +    const auto deleteById = [&](const uint32_t id, const uint32_t placementId) {
    +        if (id == 0)
    +        {
    +            return;
    +        }
    +        _erase(buffer, [=](const GraphicsRowRef& ref) {
    +            return ref.placement->image->id == id && (placementId == 0 || ref.placement->placementId == placementId);
    +        },
    +               freeImages);
    +        if (store.FindVirtualPlacement(id, placementId))
    +        {
    +            store.RemoveVirtualPlacements(id, placementId);
    +            buffer.TriggerRedrawAll();
    +        }
    +        if (freeImages && id && !buffer.AnyGraphics([=](const GraphicsRowRef& ref) { return ref.placement->image->id == id; }))
    +        {
    +            store.Remove(id);
    +        }
    +    };
    +
    +    // Placements that intersect a cell of the page, which are deleted entirely.
    +    const auto deleteVisible = [&](const std::function<bool(const GraphicsRowRef&, til::point)>& predicate) {
    +        std::unordered_set<const GraphicsPlacement*> matches;
    +        for (auto y = page.Top(); y < page.Bottom(); y++)
    +        {
    +            for (const auto& ref : buffer.GetRowByOffset(y).GetGraphics())
    +            {
    +                const auto& p = *ref.placement;
    +                for (auto x = std::max(0, p.column); x < std::min(page.Width(), p.column + p.columns); x++)
    +                {
    +                    if (predicate(ref, { x, y - page.Top() }))
    +                    {
    +                        matches.insert(ref.placement.get());
    +                        break;
    +                    }
    +                }
    +            }
    +        }
    +        if (!matches.empty())
    +        {
    +            _erase(buffer, [&](const GraphicsRowRef& ref) { return matches.contains(ref.placement.get()); }, freeImages);
    +        }
    +    };
    +
    +    const auto cellX = gsl::narrow_cast<til::CoordType>(control.Get('x')) - 1;
    +    const auto cellY = gsl::narrow_cast<til::CoordType>(control.Get('y')) - 1;
    +    const auto z = control.GetSigned('z');
    +
    +    switch (target)
    +    {
    +    case L'a':
    +    case L'A':
    +        deleteVisible([](auto&, auto) { return true; });
    +        break;
    +    case L'i':
    +    case L'I':
    +        deleteById(control.GetUnsigned('i'), control.GetUnsigned('p'));
    +        break;
    +    case L'n':
    +    case L'N':
    +        if (const auto image = store.FindByNumber(control.GetUnsigned('I')))
    +        {
    +            deleteById(image->id, control.GetUnsigned('p'));
    +        }
    +        break;
    +    case L'c':
    +    case L'C':
    +    {
    +        const auto cursor = page.Cursor().GetPosition();
    +        deleteVisible([&](auto&, const til::point cell) { return cell == til::point{ cursor.x, cursor.y - page.Top() }; });
    +        break;
    +    }
    +    case L'p':
    +    case L'P':
    +        deleteVisible([&](auto&, const til::point cell) { return cell == til::point{ cellX, cellY }; });
    +        break;
    +    case L'q':
    +    case L'Q':
    +        deleteVisible([&](const GraphicsRowRef& ref, const til::point cell) { return cell == til::point{ cellX, cellY } && ref.placement->z == z; });
    +        break;
    +    case L'x':
    +    case L'X':
    +        deleteVisible([&](auto&, const til::point cell) { return cell.x == cellX; });
    +        break;
    +    case L'y':
    +    case L'Y':
    +        deleteVisible([&](auto&, const til::point cell) { return cell.y == cellY; });
    +        break;
    +    case L'z':
    +    case L'Z':
    +        _erase(buffer, [=](const GraphicsRowRef& ref) { return ref.placement->z == z; }, freeImages);
    +        break;
    +    case L'r':
    +    case L'R':
    +    {
    +        const auto first = control.GetUnsigned('x');
    +        const auto last = control.GetUnsigned('y');
    +        if (first <= last)
    +        {
    +            std::vector<uint32_t> ids;
    +            buffer.AnyGraphics([&](const GraphicsRowRef& ref) {
    +                const auto id = ref.placement->image->id;
    +                if (id >= first && id <= last)
    +                {
    +                    ids.push_back(id);
    +                }
    +                return false;
    +            });
    +            for (const auto id : store.Ids())
    +            {
    +                if (id >= first && id <= last)
    +                {
    +                    ids.push_back(id);
    +                }
    +            }
    +            std::ranges::sort(ids);
    +            ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
    +            for (const auto id : ids)
    +            {
    +                deleteById(id, 0);
    +            }
    +        }
    +        break;
    +    }
    +    default:
    +        break;
    +    }
    +}
    +
    +void KittyGraphics::_featureQuery(const Control& control) const
    +{
    +    const auto action = control.GetChar('e', 0);
    +    std::wstring keys;
    +    const auto echo = [&](const char key) {
    +        keys += L',';
    +        keys += static_cast<wchar_t>(key);
    +        keys += L'=';
    +        if (control.isChar.test(static_cast<size_t>(key)))
    +        {
    +            keys += control.GetChar(key, 0);
    +        }
    +        else
    +        {
    +            keys += std::to_wstring(control.Get(key));
    +        }
    +    };
    +    const auto echoIf = [&](const char key, const bool supported) {
    +        if (control.Has(key) && control.Get(key) != 0 && supported)
    +        {
    +            echo(key);
    +        }
    +    };
    +    const auto echoTransmitKeys = [&]() {
    +        const auto format = control.Get('f', 32);
    +        echoIf('f', !control.isChar.test('f') && (format == 24 || format == 32 || format == 100));
    +        const auto medium = control.GetChar('t', L'd');
    +        echoIf('t', medium == L'f' || medium == L't' || medium == L's');
    +        echoIf('o', control.GetChar('o', 0) == L'z');
    +        for (const auto key : { 's', 'v', 'S', 'O', 'p', 'N' })
    +        {
    +            echoIf(key, !control.isChar.test(static_cast<size_t>(key)));
    +        }
    +    };
    +    const auto echoDisplayKeys = [&]() {
    +        for (const auto key : { 'x', 'y', 'w', 'h', 'X', 'Y', 'c', 'r', 'z', 'p' })
    +        {
    +            if (keys.find(std::wstring{ L',' } + static_cast<wchar_t>(key) + L'=') == std::wstring::npos)
    +            {
    +                echoIf(key, !control.isChar.test(static_cast<size_t>(key)));
    +            }
    +        }
    +        echoIf('C', control.Get('C') == 1);
    +        echoIf('U', control.Get('U') == 1);
    +    };
    +
    +    switch (action)
    +    {
    +    case L't':
    +    case L'q':
    +        keys = L",e=";
    +        keys += action;
    +        echoTransmitKeys();
    +        break;
    +    case L'T':
    +        keys = L",e=T";
    +        echoTransmitKeys();
    +        echoDisplayKeys();
    +        break;
    +    case L'p':
    +        keys = L",e=p";
    +        echoDisplayKeys();
    +        break;
    +    case L'd':
    +    {
    +        keys = L",e=d";
    +        constexpr std::wstring_view supportedTargets = L"aAiInNcCpPqQrRxXyYzZ";
    +        const auto target = control.GetChar('d', 0);
    +        echoIf('d', target && supportedTargets.find(target) != std::wstring_view::npos);
    +        for (const auto key : { 'x', 'y', 'z', 'p' })
    +        {
    +            echoIf(key, !control.isChar.test(static_cast<size_t>(key)));
    +        }
    +        break;
    +    }
    +    default:
    +        break;
    +    }
    +
    +    Control reply;
    +    til::at(reply.values, 'q') = control.Get('q');
    +    reply.present.set('q', control.Has('q'));
    +    _respond(reply, control.GetUnsigned('i'), nullptr, keys);
    +}
    +
    +std::shared_ptr<GraphicsImage> KittyGraphics::_load(const Control& control, std::vector<uint8_t> data, Error& error) const
    +{
    +    std::vector<uint8_t> bytes;
    +    switch (control.GetChar('t', L'd'))
    +    {
    +    case L'd':
    +        bytes = std::move(data);
    +        break;
    +    case L'f':
    +    case L't':
    +    {
    +        const auto path = til::u8u16({ reinterpret_cast<const char*>(data.data()), data.size() });
    +        std::wstring finalPath;
    +        if (!readFile(path, control.Get('O'), control.Get('S'), bytes, finalPath))
    +        {
    +            error = { L"EBADF", L"Failed to read image file" };
    +            return nullptr;
    +        }
    +        // The terminal is responsible for deleting temporary files. When we're
    +        // running as ConPTY, the file is still needed by the attached terminal.
    +        if (control.GetChar('t', L'd') == L't' && !_dispatcher._api.IsConPTY() && isDeletableTempFile(finalPath))
    +        {
    +            DeleteFileW(finalPath.c_str());
    +        }
    +        break;
    +    }
    +    case L's':
    +    {
    +        const auto name = til::u8u16({ reinterpret_cast<const char*>(data.data()), data.size() });
    +        if (!readSharedMemory(name, control.Get('O'), control.Get('S'), bytes))
    +        {
    +            error = { L"EBADF", L"Failed to read shared memory" };
    +            return nullptr;
    +        }
    +        break;
    +    }
    +    default:
    +        error = { L"EINVAL", L"Unknown transmission medium" };
    +        return nullptr;
    +    }
    +
    +    const auto format = control.Get('f', 32);
    +    const auto width = control.Get('s');
    +    const auto height = control.Get('v');
    +    const auto rawFormat = format == 24 || format == 32;
    +    const auto bytesPerPixel = format == 24 ? 3 : 4;
    +    const auto validSize = width > 0 && height > 0 && width <= MaxImageDimension && height <= MaxImageDimension;
    +
    +    if (control.Has('o'))
    +    {
    +        if (control.GetChar('o', 0) != L'z')
    +        {
    +            error = { L"EINVAL", L"Unknown compression" };
    +            return nullptr;
    +        }
    +        const auto expectedSize = rawFormat && validSize ? gsl::narrow_cast<size_t>(width * height * bytesPerPixel) : 0;
    +        std::vector<uint8_t> inflated;
    +        if (!inflateData(bytes, expectedSize, inflated))
    +        {
    +            error = { L"EINVAL", L"Failed to inflate image data" };
    +            return nullptr;
    +        }
    +        bytes = std::move(inflated);
    +    }
    +
    +    auto image = std::make_shared<GraphicsImage>();
    +    if (rawFormat)
    +    {
    +        if (!validSize)
    +        {
    +            error = { L"EINVAL", L"Invalid image dimensions" };
    +            return nullptr;
    +        }
    +        const auto pixelCount = gsl::narrow_cast<size_t>(width * height);
    +        if (bytes.size() < pixelCount * bytesPerPixel)
    +        {
    +            error = { L"ENODATA", L"Insufficient image data" };
    +            return nullptr;
    +        }
    +        image->size = { gsl::narrow_cast<til::CoordType>(width), gsl::narrow_cast<til::CoordType>(height) };
    +        image->pixels.resize(pixelCount);
    +        auto src = bytes.data();
    +        for (auto& pixel : image->pixels)
    +        {
    +            const uint32_t alpha = bytesPerPixel == 4 ? src[3] : 255;
    +            pixel = premultiply(src[0], src[1], src[2], alpha);
    +            src += bytesPerPixel;
    +        }
    +    }
    +    else if (format == 100)
    +    {
    +        if (!decodePng(bytes, image->size, image->pixels))
    +        {
    +            error = { L"EBADPNG", L"Failed to decode PNG data" };

    check-spelling / Unrecognized Spelling

    [EBADPNG](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/adaptDispatch.cpp:1
    @@ -1483,6 +1518,41 @@
         _ReturnDcsResponse(L"!|00000000");
     }
     
    +// Routine Description:
    +// - XTVERSION - Reports the name and version of the terminal.

    check-spelling / Unrecognized Spelling

    [XTVERSION](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/adaptDispatch.cpp:1
    @@ -1483,6 +1518,41 @@
         _ReturnDcsResponse(L"!|00000000");
     }
     
    +// Routine Description:
    +// - XTVERSION - Reports the name and version of the terminal.
    +// Arguments:
    +// - <none>
    +void AdaptDispatch::RequestTerminalVersion()
    +{
    +    static const auto version = []() -> std::wstring {
    +        // The version is read from the resources of the executable.
    +        const auto module = GetModuleHandleW(nullptr);
    +        const auto resource = FindResourceW(module, MAKEINTRESOURCEW(VS_VERSION_INFO), RT_VERSION);
    +        const auto handle = resource ? LoadResource(module, resource) : nullptr;
    +        const auto data = handle ? static_cast<const BYTE*>(LockResource(handle)) : nullptr;
    +        const auto size = resource ? SizeofResource(module, resource) : 0;
    +        // VS_VERSIONINFO starts with 3 WORDs and the "VS_VERSION_INFO" key,

    check-spelling / Unrecognized Spelling

    [VERSIONINFO](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/adaptDispatch.hpp:1
    @@ -79,6 +81,7 @@
             void DeviceAttributes() override; // DA1
             void SecondaryDeviceAttributes() override; // DA2
             void TertiaryDeviceAttributes() override; // DA3
    +        void RequestTerminalVersion() override; // XTVERSION

    check-spelling / Unrecognized Spelling

    [XTVERSION](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/termDispatch.hpp:1
    @@ -114,6 +114,7 @@
         void DeviceAttributes() override {} // DA1
         void SecondaryDeviceAttributes() override {} // DA2
         void TertiaryDeviceAttributes() override {} // DA3
    +    void RequestTerminalVersion() override {} // XTVERSION
    

    check-spelling / Unrecognized Spelling

    [XTVERSION](#security-tab) is not a recognized word

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/adapter/ut_adapter/adapterTest.cpp:1
    @@ -1801,6 +1806,143 @@
             VERIFY_THROWS(_pDispatch->TertiaryDeviceAttributes(), std::exception);
         }
     
    +    TEST_METHOD(RequestTerminalVersionTests)
    +    {
    +        Log::Comment(L"Starting test...");
    +
    +        _testGetSet->PrepData();
    +        _pDispatch->RequestTerminalVersion();
    +
    +        // The version is read from the test executable, so only its format is checked.
    +        const auto& response = _testGetSet->_response;
    +        VERIFY_IS_TRUE(response.starts_with(L"\x1bP>|TestTerminal "));
    +        VERIFY_IS_TRUE(response.ends_with(L"\x1b\\"));
    +    }
    +
    +    TEST_METHOD(KittyGraphicsTests)
    +    {
    +        Log::Comment(L"Starting test...");
    +
    +        _testGetSet->PrepData();
    +        auto& buffer = *_testGetSet->_textBuffer;
    +        auto& cursor = buffer.GetCursor();
    +        const auto graphicsAt = [&](const til::CoordType y) {
    +            return buffer.GetRowByOffset(y).GetGraphics().size();
    +        };
    +
    +        Log::Comment(L"A query with an id is answered.");
    +        _stateMachine->ProcessString(L"\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\");
    +        _testGetSet->ValidateInputEvent(L"\x1b_Gi=31;OK\x1b\\");
    +
    +        Log::Comment(L"Insufficient image data is reported as an error.");
    +        _stateMachine->ProcessString(L"\x1b_Gi=32,s=2,v=2,a=q,f=24;AAAA\x1b\\");
    +        _testGetSet->ValidateInputEvent(L"\x1b_Gi=32;ENODATA:Insufficient image data\x1b\\");
    +
    +        Log::Comment(L"Specifying both an image id and number is an error.");
    +        _stateMachine->ProcessString(L"\x1b_Gi=33,I=1,s=1,v=1,f=24;AAAA\x1b\\");
    +        _testGetSet->ValidateInputEvent(L"\x1b_Gi=33,I=1;EINVAL:Must not specify both image id and image number\x1b\\");
    +
    +        Log::Comment(L"A feature query reports the supported keys.");
    +        _stateMachine->ProcessString(L"\x1b_Ga=q,i=34,e=T,U=1,C=1,P=5\x1b\\");
    +        _testGetSet->ValidateInputEvent(L"\x1b_Gi=34,e=T,C=1,U=1;OK\x1b\\");
    +
    +        Log::Comment(L"An image is displayed over 3x2 cells, and the cursor moves after it.");
    +        cursor.SetPosition({ 5, 25 });
    +        _stateMachine->ProcessString(L"\x1b_Ga=T,i=7,p=3,f=24,s=1,v=1,c=3,r=2;AAAA\x1b\\");
    +        _testGetSet->ValidateInputEvent(L"\x1b_Gi=7,p=3;OK\x1b\\");
    +        VERIFY_ARE_EQUAL(1u, graphicsAt(25));
    +        VERIFY_ARE_EQUAL(1u, graphicsAt(26));
    +        VERIFY_ARE_EQUAL(0u, graphicsAt(27));
    +        VERIFY_ARE_EQUAL(1, buffer.GetRowByOffset(26).GetGraphics()[0].row);
    +        VERIFY_ARE_EQUAL(5, buffer.GetRowByOffset(26).GetGraphics()[0].placement->column);
    +        VERIFY_ARE_EQUAL(til::point(8, 26), cursor.GetPosition());
    +
    +        Log::Comment(L"Text written over the image doesn't erase it.");
    +        cursor.SetPosition({ 5, 25 });
    +        _stateMachine->ProcessString(L"abc");
    +        VERIFY_ARE_EQUAL(1u, graphicsAt(25));
    +
    +        Log::Comment(L"A placement with the same id replaces the old one, and C=1 keeps the cursor.");
    +        cursor.SetPosition({ 0, 30 });
    +        _stateMachine->ProcessString(L"\x1b_Ga=p,i=7,p=3,C=1,q=1\x1b\\");
    +        VERIFY_ARE_EQUAL(til::point(0, 30), cursor.GetPosition());
    +        VERIFY_ARE_EQUAL(0u, graphicsAt(25));
    +        VERIFY_ARE_EQUAL(1u, graphicsAt(30));
    +
    +        Log::Comment(L"Clearing the screen removes the placements.");
    +        _stateMachine->ProcessString(L"\x1b[2J");
    +        VERIFY_IS_FALSE(buffer.AnyGraphics([](auto&) { return true; }));
    +
    +        Log::Comment(L"Deleting by id with d=I frees the image data.");
    +        cursor.SetPosition({ 0, 30 });
    +        _stateMachine->ProcessString(L"\x1b_Ga=p,i=7,C=1,q=1\x1b\\");
    +        VERIFY_IS_TRUE(buffer.AnyGraphics([](auto&) { return true; }));
    +        _stateMachine->ProcessString(L"\x1b_Ga=d,d=I,i=7\x1b\\");
    +        VERIFY_IS_FALSE(buffer.AnyGraphics([](auto&) { return true; }));
    +        _stateMachine->ProcessString(L"\x1b_Ga=p,i=7\x1b\\");
    +        _testGetSet->ValidateInputEvent(L"\x1b_Gi=7;ENOENT:Put command refers to a non-existent image\x1b\\");
    

    check-spelling / Forbidden Pattern

    [non-existent](#security-tab) matches a line_forbidden.patterns rule: Should be 'nonexistent' - '\\\b\[Nn\]o\[nt\]\[- \]existent\\\b'

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 18:55 UTC
    Code Review
    src/terminal/parser/OutputStateMachineEngine.cpp:1
    @@ -533,6 +533,12 @@
                 _dispatch->TertiaryDeviceAttributes();
             }
             break;
    +    case CsiActionCodes::XTVERSION_RequestTerminalVersion:
    

    check-spelling / Unrecognized Spelling

    [XTVERSION](#security-tab) is not a recognized word

    Show more details

    github-actions[bot] github-actions[bot] commented on Oct 30, 2026 18:55 UTC
    Bot

    @check-spelling-bot Report

    🔴 Please review


    See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.

    Unrecognized words (10)

    BLENDFUNCTION
    Bytef
    EBADPNG
    letterboxed
    LPto
    mapview
    mbi
    PBGRA
    VERSIONINFO
    XTVERSION

    <details><summary>These words are not needed and should be removed
    </summary>ADDREF CLAUDE CLIPCHILDREN CLIPSIBLINGS DDESHARE otm PCWCH PSTR yizz
    </details><p></p>

    <details><summary>To accept these unrecognized words as correct and remove the previously acknowledged and now absent words,
    you could run the following commands</summary>

    ... in a clone of the git@github.com:mbwilding/terminal.git repository
    on the kitty-graphics branch ([ℹ️ how do I use this?](
    https://docs.check-spelling.dev/Accepting-Suggestions)):

    `` sh
    curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/cfb6f7e75bbfc89c71eaa30366d0c166f1bd9c8c/apply.pl' |
    perl - 'https://github.com/microsoft/terminal/actions/runs/41110534992/attempts/1' &&
    git commit -m 'Update check-spelling metadata'

    </details>
    
    <details><summary>Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary</summary>
    
    This includes both **expected items** (2031) from .github/actions/spelling/expect/alphabet.txt .github/actions/spelling/expect/expect.txt .github/actions/spelling/expect/web.txt and **unrecognized words** (10)
    
    Dictionary | Entries | Covers | Uniquely
    -|-|-|-
    [cspell:cpp/src/lang-keywords.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/lang-keywords.txt)|44|3|3|
    [cspell:csharp/csharp.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/csharp/csharp.txt)|32|2|2|
    [cspell:cpp/src/compiler-clang-attributes.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/compiler-clang-attributes.txt)|46|2|2|
    [cspell:aws/aws.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/aws/aws.txt)|218|2|2|
    [cspell:python/src/python/python.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/python/src/python/python.txt)|392|2|2|
    
    Consider adding to the `extra_dictionaries` array (in the `.github/actions/spelling/config.json` file):
    
    json
    "cspell:cpp/src/lang-keywords.txt",
    "cspell:csharp/csharp.txt",
    "cspell:cpp/src/compiler-clang-attributes.txt",
    "cspell:aws/aws.txt",
    "cspell:python/src/python/python.txt",

    To stop checking additional dictionaries, put (in the `.github/actions/spelling/config.json` file):
    
    json
    "check_extra_dictionaries": []
    
    </details>
    
    #### Forbidden patterns 🙅 (1)
    
    In order to address this, you could change the content to not match the forbidden patterns (comments before forbidden patterns may help explain why they're forbidden), add patterns for acceptable instances, or adjust the forbidden patterns themselves.
    
    These forbidden patterns matched content:
    
    ##### Should be `nonexistent`
    

    \b[Nn]o[nt][- ]existent\b
    `

    <details><summary>Errors ❌ (1)</summary>

    See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.

    ❌ Errors | Count
    -|-
    ❌ forbidden-pattern | 2

    See ❌ Event descriptions for more information.

    </details>

    <!-- See https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples%3A-advice --> <!-- markdownlint-disable MD033 MD041 -->
    <details>
    <summary>
    :pencil2: Contributor please read this
    </summary>

    By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.

    If the listed items are:

    ... misspelled, then please correct them instead of using the command.
    ... names, please add them to
    .github/actions/spelling/allow/names.txt.
    ... APIs, you can add them to a file in
    .github/actions/spelling/allow/.
    ... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
    ... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in
    .github/actions/spelling/patterns/.

    See the README.md in each directory for more information.

    :microscope: You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. :wink:

    <details><summary>If the flagged items are :exploding_head: false positives</summary>

    If items relate to a ...

    binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can [test](
    https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude [README.md](
    ../tree/HEAD/README.md) (on whichever branch you're using).

  • well-formed pattern.
  • If you can write a [pattern](
    https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples:-patterns
    ) that would match it,
    try adding it to the
    patterns.txt` file.

    Patterns are Perl 5 Regular Expressions - you can [test](
    https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.
    </details>

    </details>

    mbwilding mbwilding commented on Oct 30, 2026 19:06 UTC
    Author

    Matthew Wilding (@mbwilding) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

    >
    > @microsoft-github-policy-service agree [company="{your company}"]
    > 

    > > Options:

    >

    > (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.

    >

    >
    > > @microsoft-github-policy-service agree
    > > 

    >

    >

    >

    >

    >

    >

    >

    >

    >

    >

    >

    >

    > (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.

    >

    >
    > > @microsoft-github-policy-service agree company="Microsoft"
    > > 

    > Contributor License Agreement

    @microsoft-github-policy-service agree

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 30, 2026 19:30 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -0,0 +1,1404 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT license.
    +
    +#include "precomp.h"
    +
    +#include "KittyGraphics.hpp"
    +#include "SixelParser.hpp"
    +#include "adaptDispatch.hpp"
    +#include "../parser/ascii.hpp"
    +
    +#include <unordered_set>
    +#include <wincodec.h>
    +#include <zlib.h>
    +
    +using namespace Microsoft::Console::Types;
    +using namespace Microsoft::Console::VirtualTerminal;
    +
    +namespace
    +{
    +    constexpr size_t MaxDataSize = GraphicsStore::Quota;
    +    constexpr int64_t MaxImageDimension = 10000;
    +    constexpr int64_t MaxCells = 1000;
    +    constexpr std::wstring_view TempFileMarker = L"tty-graphics-protocol";
    +
    +    int base64Value(const wchar_t ch) noexcept
    +    {
    +        if (ch >= L'A' && ch <= L'Z')
    +        {
    +            return ch - L'A';
    +        }
    +        if (ch >= L'a' && ch <= L'z')
    +        {
    +            return ch - L'a' + 26;
    +        }
    +        if (ch >= L'0' && ch <= L'9')
    +        {
    +            return ch - L'0' + 52;
    +        }
    +        if (ch == L'+')
    +        {
    +            return 62;
    +        }
    +        if (ch == L'/')
    +        {
    +            return 63;
    +        }
    +        return -1;
    +    }
    +
    +    std::wstring finalPathOf(const HANDLE handle)
    +    {
    +        std::wstring path(MAX_PATH, L'\0');
    +        for (;;)
    +        {
    +            const auto len = GetFinalPathNameByHandleW(handle, path.data(), gsl::narrow_cast<DWORD>(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
    +            if (len == 0)
    +            {
    +                return {};
    +            }
    +            if (len < path.size())
    +            {
    +                path.resize(len);
    +                return path;
    +            }
    +            path.resize(len);
    +        }
    +    }
    +
    +    // Paths come from potentially untrusted sources, such as programs running on
    +    // a remote machine. Only local drive paths are accepted, because merely
    +    // opening a network path can leak credentials to the remote host.
    +    bool isLocalDrivePath(const std::wstring_view path) noexcept
    +    {
    +        if (path.size() < 3 || !iswalpha(path[0]) || path[1] != L':' || (path[2] != L'\\' && path[2] != L'/'))
    +        {
    +            return false;
    +        }
    +        if (path.find(L'\0') != std::wstring_view::npos)
    +        {
    +            return false;
    +        }
    +        const wchar_t root[]{ path[0], L':', L'\\', L'\0' };
    +        switch (GetDriveTypeW(&root[0]))
    +        {
    +        case DRIVE_FIXED:
    +        case DRIVE_REMOVABLE:
    +        case DRIVE_CDROM:
    +        case DRIVE_RAMDISK:
    +            return true;
    +        default:
    +            return false;
    +        }
    +    }
    +
    +    std::wstring lowerCase(std::wstring text)
    +    {
    +        if (!text.empty())
    +        {
    +            LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, text.data(), gsl::narrow_cast<int>(text.size()), text.data(), gsl::narrow_cast<int>(text.size()), nullptr, nullptr, 0);
    +        }
    +        return text;
    +    }
    +
    +    std::wstring stripFinalPathPrefix(std::wstring path)
    +    {
    +        if (path.starts_with(L"\\\\?\\"))
    +        {
    +            path.erase(0, 4);
    +        }
    +        return path;
    +    }
    +
    +    bool readFile(const std::wstring& requestedPath, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out, std::wstring& finalPath)
    +    {
    +        if (!isLocalDrivePath(requestedPath))
    +        {
    +            return false;
    +        }
    +        std::wstring path(MAX_PATH, L'\0');
    +        auto len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        if (len >= path.size())
    +        {
    +            path.resize(len);
    +            len = GetFullPathNameW(requestedPath.c_str(), gsl::narrow_cast<DWORD>(path.size()), path.data(), nullptr);
    +        }
    +        if (len == 0 || len >= path.size())
    +        {
    +            return false;
    +        }
    +        path.resize(len);
    +        if (!isLocalDrivePath(path))
    +        {
    +            return false;
    +        }
    +
    +        wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) };
    +        if (!file || GetFileType(file.get()) != FILE_TYPE_DISK)
    +        {
    +            return false;
    +        }
    +        BY_HANDLE_FILE_INFORMATION info{};
    +        if (!GetFileInformationByHandle(file.get(), &info) || WI_IsFlagSet(info.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))
    +        {
    +            return false;
    +        }
    +        finalPath = stripFinalPathPrefix(finalPathOf(file.get()));
    +        if (!isLocalDrivePath(finalPath))
    +        {
    +            return false;
    +        }
    +
    +        const auto fileSize = (static_cast<uint64_t>(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
    +        if (offset > fileSize)
    +        {
    +            return false;
    +        }
    +        const auto available = fileSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +
    +        LARGE_INTEGER distance{};
    +        distance.QuadPart = gsl::narrow_cast<LONGLONG>(offset);
    +        if (!SetFilePointerEx(file.get(), distance, nullptr, FILE_BEGIN))
    +        {
    +            return false;
    +        }
    +        out.resize(gsl::narrow_cast<size_t>(toRead));
    +        size_t total = 0;
    +        while (total < out.size())
    +        {
    +            DWORD read = 0;
    +            const auto chunk = gsl::narrow_cast<DWORD>(std::min<size_t>(out.size() - total, 1 << 30));
    +            if (!ReadFile(file.get(), out.data() + total, chunk, &read, nullptr) || read == 0)
    +            {
    +                return false;
    +            }
    +            total += read;
    +        }
    +        return true;
    +    }
    +
    +    bool readSharedMemory(const std::wstring& name, const uint64_t offset, const uint64_t size, std::vector<uint8_t>& out)
    +    {
    +        if (name.empty() || name.find(L'\0') != std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        wil::unique_handle mapping{ OpenFileMappingW(FILE_MAP_READ, FALSE, name.c_str()) };
    +        if (!mapping)
    +        {
    +            return false;
    +        }
    +        wil::unique_mapview_ptr<uint8_t> view{ static_cast<uint8_t*>(MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0)) };
    +        if (!view)
    +        {
    +            return false;
    +        }
    +        // The region only covers pages with the same state, so this also
    +        // ensures that every page we read from is committed.
    +        MEMORY_BASIC_INFORMATION memoryInfo{};
    +        if (!VirtualQuery(view.get(), &memoryInfo, sizeof(memoryInfo)) || memoryInfo.State != MEM_COMMIT)
    +        {
    +            return false;
    +        }
    +        const uint64_t mappedSize = memoryInfo.RegionSize;
    +        if (offset > mappedSize)
    +        {
    +            return false;
    +        }
    +        const auto available = mappedSize - offset;
    +        const auto toRead = size ? size : available;
    +        if (toRead > available || toRead > MaxDataSize)
    +        {
    +            return false;
    +        }
    +        out.assign(view.get() + offset, view.get() + offset + toRead);
    +        return true;
    +    }
    +
    +    bool isDeletableTempFile(const std::wstring& finalPath)
    +    {
    +        if (lowerCase(finalPath).find(TempFileMarker) == std::wstring::npos)
    +        {
    +            return false;
    +        }
    +        std::wstring tempPath(MAX_PATH + 1, L'\0');
    +        const auto len = GetTempPathW(gsl::narrow_cast<DWORD>(tempPath.size()), tempPath.data());
    +        if (len == 0 || len >= tempPath.size())
    +        {
    +            return false;
    +        }
    +        tempPath.resize(len);
    +        wil::unique_hfile directory{ CreateFileW(tempPath.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr) };
    +        if (!directory)
    +        {
    +            return false;
    +        }
    +        auto tempDirectory = stripFinalPathPrefix(finalPathOf(directory.get()));
    +        if (tempDirectory.empty())
    +        {
    +            return false;
    +        }
    +        if (!tempDirectory.ends_with(L'\\'))
    +        {
    +            tempDirectory.push_back(L'\\');
    +        }
    +        return lowerCase(finalPath).starts_with(lowerCase(tempDirectory));
    +    }
    +
    +    bool inflateData(const std::span<const uint8_t> input, const size_t expectedSize, std::vector<uint8_t>& output)
    +    {
    +        z_stream stream{};
    +        if (inflateInit(&stream) != Z_OK)
    +        {
    +            return false;
    +        }
    +        auto cleanup = wil::scope_exit([&]() noexcept { inflateEnd(&stream); });
    +
    +        output.resize(expectedSize ? expectedSize : std::max<size_t>(input.size() * 4, 4096));
    +        stream.next_in = const_cast<Bytef*>(input.data());
    +        stream.avail_in = gsl::narrow_cast<uInt>(input.size());
    +        size_t produced = 0;
    +        for (;;)
    +        {
    +            stream.next_out = output.data() + produced;
    +            stream.avail_out = gsl::narrow_cast<uInt>(std::min<size_t>(output.size() - produced, UINT_MAX));
    +            const auto before = stream.avail_out;
    +            const auto result = inflate(&stream, Z_NO_FLUSH);
    +            produced += before - stream.avail_out;
    +            if (result == Z_STREAM_END)
    +            {
    +                output.resize(produced);
    +                return true;
    +            }
    +            if (result != Z_OK && result != Z_BUF_ERROR)
    +            {
    +                return false;
    +            }
    +            if (stream.avail_out == 0)
    +            {
    +                if (output.size() >= MaxDataSize)
    +                {
    +                    return false;
    +                }
    +                output.resize(std::min(output.size() * 2, MaxDataSize));
    +            }
    +            else if (stream.avail_in == 0)
    +            {
    +                // The input was truncated.
    +                return false;
    +            }
    +        }
    +    }
    +
    +    bool decodePng(const std::span<const uint8_t> data, til::size& size, std::vector<uint32_t>& pixels)
    +    {
    +        // WIC requires COM. If the thread is already initialized in a different
    +        // apartment, that's fine too, since the factory is free threaded.
    +        const auto hrInit = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    +        auto uninitialize = wil::scope_exit([&]() noexcept {
    +            if (SUCCEEDED(hrInit))
    +            {
    +                CoUninitialize();
    +            }
    +        });
    +
    +        const auto factory = wil::CoCreateInstanceNoThrow<IWICImagingFactory>(CLSID_WICImagingFactory);
    +        if (!factory)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICStream> stream;
    +        if (FAILED(factory->CreateStream(stream.addressof())) ||
    +            FAILED(stream->InitializeFromMemory(const_cast<BYTE*>(data.data()), gsl::narrow_cast<DWORD>(data.size()))))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapDecoder> decoder;
    +        if (FAILED(factory->CreateDecoder(GUID_ContainerFormatPng, nullptr, decoder.addressof())) ||
    +            FAILED(decoder->Initialize(stream.get(), WICDecodeMetadataCacheOnDemand)))
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICBitmapFrameDecode> frame;
    +        UINT width = 0;
    +        UINT height = 0;
    +        if (FAILED(decoder->GetFrame(0, frame.addressof())) || FAILED(frame->GetSize(&width, &height)))
    +        {
    +            return false;
    +        }
    +        if (width == 0 || height == 0 || width > MaxImageDimension || height > MaxImageDimension)
    +        {
    +            return false;
    +        }
    +        wil::com_ptr<IWICFormatConverter> converter;
    +        if (FAILED(factory->CreateFormatConverter(converter.addressof())) ||
    +            FAILED(converter->Initialize(frame.get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom)))
    +        {
    +            return false;
    +        }
    +        pixels.resize(static_cast<size_t>(width) * height);
    +        if (FAILED(converter->CopyPixels(nullptr, width * 4, gsl::narrow_cast<UINT>(pixels.size() * 4), reinterpret_cast<BYTE*>(pixels.data()))))
    +        {
    +            return false;
    +        }
    +        size = { gsl::narrow_cast<til::CoordType>(width), gsl::narrow_cast<til::CoordType>(height) };
    +        return true;
    +    }
    +
    +    // Reads the dimensions from the IHDR chunk, which must come first in a PNG.

    check-spelling / Unrecognized Spelling

    [IHDR](#security-tab) is not a recognized word

    Show more details

    github-actions[bot] github-actions[bot] commented on Oct 30, 2026 19:31 UTC
    Bot

    @check-spelling-bot Report

    🔴 Please review


    See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.

    Unrecognized words (1)

    IHDR

    <details><summary>These words are not needed and should be removed
    </summary>ADDREF CLAUDE CLIPCHILDREN CLIPSIBLINGS DDESHARE otm PCWCH PSTR yizz
    </details><p></p>

    <details><summary>To accept these unrecognized words as correct and remove the previously acknowledged and now absent words,
    you could run the following commands</summary>

    ... in a clone of the git@github.com:mbwilding/terminal.git repository
    on the kitty-graphics branch ([ℹ️ how do I use this?](
    https://docs.check-spelling.dev/Accepting-Suggestions)):

    `` sh
    curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/cfb6f7e75bbfc89c71eaa30366d0c166f1bd9c8c/apply.pl' |
    perl - 'https://github.com/microsoft/terminal/actions/runs/41115307580/attempts/1' &&
    git commit -m 'Update check-spelling metadata'

    </details>
    
    <details><summary>Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary</summary>
    
    This includes both **expected items** (2039) from .github/actions/spelling/expect/alphabet.txt .github/actions/spelling/expect/expect.txt .github/actions/spelling/expect/web.txt and **unrecognized words** (1)
    
    Dictionary | Entries | Covers | Uniquely
    -|-|-|-
    [cspell:cpp/src/lang-keywords.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/lang-keywords.txt)|44|3|3|
    [cspell:csharp/csharp.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/csharp/csharp.txt)|32|2|2|
    [cspell:cpp/src/compiler-clang-attributes.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/compiler-clang-attributes.txt)|46|2|2|
    [cspell:aws/aws.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/aws/aws.txt)|218|2|2|
    [cspell:python/src/python/python.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/python/src/python/python.txt)|392|2|2|
    
    Consider adding to the `extra_dictionaries` array (in the `.github/actions/spelling/config.json` file):
    
    json
    "cspell:cpp/src/lang-keywords.txt",
    "cspell:csharp/csharp.txt",
    "cspell:cpp/src/compiler-clang-attributes.txt",
    "cspell:aws/aws.txt",
    "cspell:python/src/python/python.txt",

    To stop checking additional dictionaries, put (in the `.github/actions/spelling/config.json` file):
    
    json
    "check_extra_dictionaries": []
    `

    </details>

    <!-- See https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples%3A-advice --> <!-- markdownlint-disable MD033 MD041 -->
    <details>
    <summary>
    :pencil2: Contributor please read this
    </summary>

    By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.

    If the listed items are:

    ... misspelled, then please correct them instead of using the command.
    ... names, please add them to
    .github/actions/spelling/allow/names.txt.
    ... APIs, you can add them to a file in
    .github/actions/spelling/allow/.
    ... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
    ... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in
    .github/actions/spelling/patterns/.

    See the README.md in each directory for more information.

    :microscope: You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. :wink:

    <details><summary>If the flagged items are :exploding_head: false positives</summary>

    If items relate to a ...

    binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can [test](
    https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude [README.md](
    ../tree/HEAD/README.md) (on whichever branch you're using).

  • well-formed pattern.
  • If you can write a [pattern](
    https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples:-patterns
    ) that would match it,
    try adding it to the
    patterns.txt` file.

    Patterns are Perl 5 Regular Expressions - you can [test](
    https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.
    </details>

    </details>

    DHowett DHowett commented on Oct 30, 2026 19:35 UTC
    Contributor

    XTVERSION

    absolutely not :)

    DHowett DHowett commented on Oct 30, 2026 19:37 UTC
    Contributor

    How it works

    FWIW, I would have hoped to see _something_ explaining the "placement diacritics" and stuff in this section. It seems like a pretty significant part of how it.. works.. 🙂

    DHowett DHowett requested changes on Oct 30, 2026 19:37 UTC
    Changes Requested Reviewer

    (blocking for direction review)

    mbwilding mbwilding commented on Oct 30, 2026 20:01 UTC
    Author

    > How it works

    > FWIW, I would have hoped to see _something_ explaining the "placement diacritics" and stuff in this section. It seems like a pretty significant part of how it.. works.. 🙂

    They're part of the kitty unicode placeholders spec. the app prints U+10EEEE as normal text, the image id goes in the fg colour, the placement id in the underline colour, and the diacritics give the row/column (plus the top byte of the id if it needs it). since it's just text it scrolls and reflows like everything else, so tmux/nvim for example can move images around without knowing anything about the protocol. renderer decodes them per row and draws that part of the image under the text.

    mbwilding mbwilding commented on Oct 30, 2026 20:12 UTC
    Author

    > XTVERSION

    > absolutely not :)

    Certain things rely on this for functionality as it identifies the terminal (admittedly some things use this value to apply work arounds for particular terminal emulators). For example the snacks image plugin for neovim will read this value. What's the aversion to having it as part of WT?

    DHowett DHowett commented on Oct 30, 2026 20:32 UTC
    Contributor

    What's the aversion to having it as part of WT?

    So, mostly on principle. There's a long discussion in both a PR which attempted to introduce it (https://github.com/microsoft/terminal/pull/20268) and the original feature request for it (https://github.com/microsoft/terminal/issues/18382), which I won't go all the way into here.

    The TL;DR:

  • But what about User-Agent?

  • You've already had it.

  • We've had one, yes. But what about second User-Agent?
  • I don't think he knows about second user-agent, Pip.

    mbwilding mbwilding commented on Oct 30, 2026 20:42 UTC
    Author

    No worries, I have removed the logic for XTVERSION.

    undy-aeon undy-aeon commented on Nov 03, 2026 16:19 UTC
    Contributor

    If you want to have some good test/benchmark, you can use my music software that support kitty graphic rendering. rustel.cc (ctrl-o for settings > then choose kitty graphics in rendering mode)

    lhecker lhecker commented on Nov 03, 2026 17:26 UTC
    Reviewer

    I gave this PR a glance and I think this is generally the right direction. It may be worth basing our implementation on this PR out of the 3 we have. Perhaps unsurprisingly it requires significant polishing.

    There's also some things that I have personal feelings on. For instance, I think that deflate compressed raw RGB is a particularly bad aspect of the Kitty protocol, to put it mildly.

    _PNG is literally deflated RGB with a prefilter. Why on god's green earth would you not use it??_

    I have a strong urge to ask you to remove its support, and similar blasphemous features, but I'm not entirely sure about that yet. 🫥

    DHowett DHowett commented on code on Nov 23, 2026 23:43 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -1024,8 +1024,7 @@ std::shared_ptr<GraphicsImage> KittyGraphics::_load(const Control& control, std:
         case L'f':
         case L't':
         {
    -#pragma warning(suppress : 26490) // Don't use reinterpret_cast (type.1).
    -        const auto path = til::u8u16({ reinterpret_cast<const char*>(data.data()), data.size() });
    +        const auto path = til::u8u16(std::string{ data.begin(), data.end() });

    personally I feel that copies are worse than casts.

    DHowett DHowett commented on code on Nov 23, 2026 23:44 UTC
    Code Review
    src/terminal/adapter/KittyGraphics.cpp:1
    @@ -262,14 +264,12 @@ namespace
             auto cleanup = wil::scope_exit([&]() noexcept { inflateEnd(&stream); });
     
             output.resize(expectedSize ? expectedSize : std::max<size_t>(input.size() * 4, 4096));
    -#pragma warning(suppress : 26492) // Don't use const_cast to cast away const or volatile (type.3).
    -        stream.next_in = const_cast<Bytef*>(input.data());
    +        stream.next_in = input.data();
             stream.avail_in = gsl::narrow_cast<uInt>(input.size());
             size_t produced = 0;
             for (;;)
             {
    -#pragma warning(suppress : 26481) // Don't use pointer arithmetic. Use span instead (bounds.1).
    -            stream.next_out = output.data() + produced;
    +            stream.next_out = std::span{ output }.subspan(produced).data();

    this seems like more of an antipattern than having a bounds.1 violation does

    DHowett DHowett commented on Nov 23, 2026 23:45 UTC
    Reviewer

    just some thoughts while commit 2917bdc went by my inbox

    mbwilding mbwilding commented on Nov 24, 2026 06:52 UTC
    Author

    just some thoughts while commit 2917bdc went by my inbox

    No worries, I sorted those out.

    Now, to get this more production ready, what would you like me to sort out in the meantime to move it closer to an approval?

    Reviewers
    Assignees
    mbwilding mbwilding
    Labels
    risk: low confidence: 90.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.6% · Lower = rushed or shallow review
    90.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.7% · Safe to merge
    6.7%